diff --git a/src/dxil/emit.zig b/src/dxil/emit.zig index 481b87a..1033c36 100644 --- a/src/dxil/emit.zig +++ b/src/dxil/emit.zig @@ -95,8 +95,11 @@ const Resource = struct { /// Registers in the range (arrays of resources); maxInt for unsized. count: u32 = 1, /// An array element's handle made at its use: a copy of the array's - /// entry, skipped by metadata. + /// entry, skipped by metadata. (Descriptor heap resources are views + /// with no global.) view: bool = false, + /// The resource type (without array dimensions); 0 for cbuffer blocks. + rty: TypeId = 0, const Class = enum(u8) { srv = 0, uav = 1, cbuffer = 2, sampler = 3 }; }; @@ -150,6 +153,8 @@ const Emitter = struct { /// A typed UAV load of more than one component. uses_typed_uav_load: bool = false, uses_inner_coverage: bool = false, + uses_resource_heap: bool = false, + uses_sampler_heap: bool = false, sig_in: []signature.Element = &.{}, sig_out: []signature.Element = &.{}, @@ -336,6 +341,31 @@ const Emitter = struct { return e.assemble(gpa, entry, bitcode); } + /// 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 { + if (e.t.get(ty) == .sampler) return .{ .global = 0, .class = .sampler, .kind = 14, .elem = ty, .comparison = e.t.get(ty).sampler.comparison, .rty = ty }; + const r = e.t.get(ty).resource; + const kind: u32 = switch (r.kind) { + .structured_buffer, .rw_structured_buffer, .append_structured_buffer, .consume_structured_buffer => 12, + .byte_address_buffer, .rw_byte_address_buffer => 11, + .buffer, .rw_buffer => 10, + .texture1d, .rw_texture1d => 1, + .texture2d, .rw_texture2d => 2, + .texture2dms, .rw_texture2dms => 3, + .texture3d, .rw_texture3d => 4, + .texture_cube => 5, + .texture1d_array, .rw_texture1d_array => 6, + .texture2d_array, .rw_texture2d_array => 7, + .texture2dms_array, .rw_texture2dms_array => 8, + .texture_cube_array => 9, + .constant_buffer => 13, + else => return e.unsupported("resource type '{s}' is not supported yet", .{r.name}), + }; + const class: Resource.Class = if (kind == 13) .cbuffer else if (r.kind.isWritable() or r.kind == .consume_structured_buffer) .uav else .srv; + 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 }; + } + fn collectResources(e: *Emitter) Error!void { var counts = [_]u32{ 0, 0, 0, 0 }; // Constant buffers: `$Globals` first, then the others in order. @@ -362,30 +392,22 @@ const Emitter = struct { try e.resource_of_global.put(e.arena, @intCast(gi), @intCast(e.resources.items.len - 1)); continue; } - const r = switch (e.t.get(gty)) { - .resource => |r| r, - else => return e.unsupported("global '{s}' is not supported yet", .{g.name}), + if (e.t.get(gty) != .resource) return e.unsupported("global '{s}' is not supported yet", .{g.name}); + var res = try e.resourceFor(gty); + const class = res.class; + const want: u8 = switch (class) { + .uav => 'u', + .srv => 't', + .cbuffer => 'b', + .sampler => 's', }; - const kind: u32 = switch (r.kind) { - .structured_buffer, .rw_structured_buffer, .append_structured_buffer, .consume_structured_buffer => 12, - .byte_address_buffer, .rw_byte_address_buffer => 11, - .buffer, .rw_buffer => 10, - .texture1d, .rw_texture1d => 1, - .texture2d, .rw_texture2d => 2, - .texture2dms, .rw_texture2dms => 3, - .texture3d, .rw_texture3d => 4, - .texture_cube => 5, - .texture1d_array, .rw_texture1d_array => 6, - .texture2d_array, .rw_texture2d_array => 7, - .texture2dms_array, .rw_texture2dms_array => 8, - .texture_cube_array => 9, - else => return e.unsupported("resource type '{s}' is not supported yet", .{r.name}), - }; - const class: Resource.Class = if (r.kind.isWritable() or r.kind == .consume_structured_buffer) .uav else .srv; - if (g.binding.explicit and g.binding.class != @as(u8, if (class == .uav) 'u' else 't')) { + if (g.binding.explicit and g.binding.class != want) { return e.unsupported("binding '{s}' to the wrong register class", .{g.name}); } - try e.resources.append(e.arena, .{ .global = @intCast(gi), .class = class, .id = counts[@backingInt(class)], .kind = kind, .elem = r.elem, .count = count, .has_counter = r.kind == .append_structured_buffer or r.kind == .consume_structured_buffer }); + res.global = @intCast(gi); + res.id = counts[@backingInt(class)]; + res.count = count; + try e.resources.append(e.arena, res); counts[@backingInt(class)] += 1; try e.resource_of_global.put(e.arena, @intCast(gi), @intCast(e.resources.items.len - 1)); } @@ -475,11 +497,7 @@ const Emitter = struct { const cls = try e.dm.constant(.{ .ty = i8t, .kind = .{ .int = @backingInt(res.class) } }); const bind = try e.dm.constant(.{ .ty = bind_ty, .kind = .{ .aggregate = try e.arena.dupe(module.ConstId, &.{ lb_c.constant, ub_c.constant, space.constant, cls.constant }) } }); const raw = try emitCall(e, prologue, create, &.{ try e.i32Const(217), bind, index, nu }); - const p = try e.resourceProperties(res); - const p0 = try e.dm.constant(.{ .ty = i32t, .kind = .{ .int = p[0] } }); - const p1 = try e.dm.constant(.{ .ty = i32t, .kind = .{ .int = p[1] } }); - const props = try e.dm.constant(.{ .ty = props_ty, .kind = .{ .aggregate = try e.arena.dupe(module.ConstId, &.{ p0.constant, p1.constant }) } }); - return emitCall(e, prologue, annotate, &.{ try e.i32Const(216), raw, props }); + return emitCall(e, prologue, annotate, &.{ try e.i32Const(216), raw, try e.propertiesConst(res) }); } const create = try e.dxOp("dx.op.createHandle", e.handle_ty, &.{ i32t, i8t, i32t, i32t, i1t }, .nounwind_readonly); return emitCall(e, prologue, create, &.{ @@ -491,6 +509,24 @@ const Emitter = struct { }); } + /// The ResourceProperties constant annotating `res`'s handles. + fn propertiesConst(e: *Emitter, res: Resource) Error!Value { + const i32t = try e.dm.intType(32); + const props_ty = try e.dm.getType(.{ .@"struct" = .{ .name = "dx.types.ResourceProperties", .elems = &.{ i32t, i32t } } }); + const p = try e.resourceProperties(res); + const p0 = try e.dm.constant(.{ .ty = i32t, .kind = .{ .int = p[0] } }); + const p1 = try e.dm.constant(.{ .ty = i32t, .kind = .{ .int = p[1] } }); + return e.dm.constant(.{ .ty = props_ty, .kind = .{ .aggregate = try e.arena.dupe(module.ConstId, &.{ p0.constant, p1.constant }) } }); + } + + /// annotateHandle at the current point. + fn annotateHandle(e: *Emitter, res: Resource, raw: Value) Error!Value { + const i32t = try e.dm.intType(32); + const props_ty = try e.dm.getType(.{ .@"struct" = .{ .name = "dx.types.ResourceProperties", .elems = &.{ i32t, i32t } } }); + const fn_i = try e.dxOp("dx.op.annotateHandle", e.handle_ty, &.{ i32t, e.handle_ty, props_ty }, .nounwind_readnone); + return e.callOp(fn_i, e.handle_ty, &.{ try e.i32Const(216), raw, try e.propertiesConst(res) }); + } + fn self_sm66(e: *Emitter) bool { return e.profile.minor >= 6; } @@ -767,6 +803,22 @@ const Emitter = struct { switch (i.op) { .constant => |c| return e.list(&.{try e.constant(i.ty, c)}), .param => |p| return frame.params[p], + .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", .{}); + var res = try e.resourceFor(i.ty); + res.global = std.math.maxInt(u32); + res.view = true; + const idx = (try e.scalars(frame, h.index))[0]; + const i32t = try e.dm.intType(32); + const i1t = try e.dm.intType(1); + const create = try e.dxOp("dx.op.createHandleFromHeap", e.handle_ty, &.{ i32t, i32t, i1t, i1t }, .nounwind_readnone); + const raw = try e.callOp(create, e.handle_ty, &.{ try e.i32Const(218), idx, try e.dm.constant(.{ .ty = i1t, .kind = .{ .int = @intFromBool(h.sampler) } }), try e.dm.constant(.{ .ty = i1t, .kind = .{ .int = @intFromBool(e.nonuniform.contains(idx)) } }) }); + res.handle = try e.annotateHandle(res, raw); + if (h.sampler) e.uses_sampler_heap = true else e.uses_resource_heap = true; + try e.resources.append(e.arena, res); + return .{ .handle = @intCast(e.resources.items.len - 1) }; + }, .mesh_output => |k| return .{ .mesh = .{ .kind = k, .ty = i.ty } }, .mesh_payload => { const dty = try e.memoryType(i.ty); @@ -807,7 +859,7 @@ const Emitter = struct { return .{ .ptr = gop.value_ptr.* }; } const ri = e.resource_of_global.get(g) orelse return e.unsupported("global '{s}' is not supported yet", .{e.m.globals.items[g].name}); - if (e.resources.items[ri].class == .cbuffer) return .{ .cbuf = .{ .res = ri } }; + if (e.resources.items[ri].class == .cbuffer and e.m.globals.items[g].space == .cbuffer) return .{ .cbuf = .{ .res = ri } }; if (e.resources.items[ri].count != 1) return .{ .res_array = .{ .res = ri, .ty = e.m.globals.items[g].ty } }; return .{ .handle = ri }; }, @@ -895,6 +947,7 @@ const Emitter = struct { if (frame.vals[a.base.index()] == .handle) { const ri = frame.vals[a.base.index()].handle; const rk = e.resources.items[ri].kind; + if (rk == 13) return e.cbufferAccess(frame, .{ .res = ri }, e.resources.items[ri].elem, a.indices); if (rk >= 1 and rk <= 10) return .{ .texel = .{ .res = ri, .coords = try e.scalars(frame, a.indices[0]) } }; if (rk != 12) return e.unsupported("member access into this resource is not supported yet", .{}); const start: @FieldType(Lowered, "buf") = .{ .res = ri, .index = (try e.scalars(frame, a.indices[0]))[0] }; @@ -1891,8 +1944,7 @@ const Emitter = struct { // Constant buffers fn cbufferSize(e: *Emitter, res: Resource) Error!i64 { - const g = e.m.globals.items[res.global]; - return layout.sizeOf(e.t, g.ty, false, .dx_legacy) catch e.unsupported("constant buffer '{s}' contains types that are not supported yet", .{g.name}); + return layout.sizeOf(e.t, res.elem, false, .dx_legacy) catch e.unsupported("constant buffer '{s}' contains types that are not supported yet", .{try e.t.format(e.arena, res.elem)}); } /// Byte offset of a member / element inside a constant buffer. @@ -2049,6 +2101,7 @@ const Emitter = struct { } fn resourceKind(e: *Emitter, res: Resource) types.ResourceKind { + if (res.rty != 0) return e.t.get(res.rty).resource.kind; var ty = e.m.globals.items[res.global].ty; while (e.t.get(ty) == .array) ty = e.t.get(ty).array.elem; return e.t.get(ty).resource.kind; @@ -2158,7 +2211,7 @@ const Emitter = struct { } } if (res.kind == 12 and (eq(u8, name, "IncrementCounter") or eq(u8, name, "DecrementCounter") or eq(u8, name, "Append") or eq(u8, name, "Consume"))) { - for (e.resources.items) |*r2| if (r2.global == res.global) { + if (res.global != std.math.maxInt(u32)) for (e.resources.items) |*r2| if (r2.global == res.global) { r2.has_counter = true; }; const i8t = try e.dm.intType(8); @@ -3129,6 +3182,8 @@ const Emitter = struct { flags |= 1 << 24; }; if (e.uses_view_id) flags |= 1 << 21; + if (e.uses_resource_heap) flags |= 1 << 30; + if (e.uses_sampler_heap) flags |= 1 << 31; if (e.uses_wave) flags |= 1 << 19; if (e.uses_inner_coverage) flags |= 1 << 10; return flags; @@ -3140,6 +3195,7 @@ const Emitter = struct { .{ 1 << 2, 0x1 }, .{ 1 << 16, 0x4 }, .{ 1 << 15, 0x8 }, .{ 1 << 5, 0x10 }, .{ 1 << 11, 0x200 }, .{ 1 << 10, 0x400 }, .{ 1 << 9, 0x2000 }, .{ 1 << 20, 0x8000 }, .{ 1 << 21, 0x10000 }, .{ 1 << 24, 0x80000 }, .{ 1 << 19, 0x4000 }, .{ 1 << 13, 0x800 }, + .{ 1 << 30, 0x2000000 }, .{ 1 << 31, 0x4000000 }, }; var f: u64 = 0; for (map) |m| if (flags & m[0] != 0) { @@ -3184,10 +3240,11 @@ const Emitter = struct { }.f; if (r.class == .cbuffer) { const f32t = try dm.getType(.float); - const cb_ty = try dm.getType(.{ .@"struct" = .{ .name = g.name, .elems = &.{f32t} } }); + 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, 1), try mdI32(dm, try e.cbufferSize(r)), null })); + 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 })); continue; } if (r.class == .sampler) { diff --git a/src/ir/ir.zig b/src/ir/ir.zig index 60e29ed..9c6dc64 100644 --- a/src/ir/ir.zig +++ b/src/ir/ir.zig @@ -119,6 +119,9 @@ pub const Op = union(enum) { /// from the amplification shader. mesh_output: MeshOutput, mesh_payload, + /// `ResourceDescriptorHeap[index]` / `SamplerDescriptorHeap[index]` + /// as a resource of the instruction's type. + heap_resource: struct { index: Ref, sampler: bool }, patch_output: struct { element: u32, value: Ref }, output_vertex: struct { element: u32, vertex: u32 }, /// Geometry shaders: emit the vertex written to the outputs of a stream, @@ -442,6 +445,7 @@ fn dumpInst(m: *const Module, f: *const Function, r: Ref, w: *std.Io.Writer) !vo .patch_input => |k| try w.print("patch input {d}", .{k}), .mesh_output => |k| try w.print("mesh output {s}", .{@tagName(k)}), .mesh_payload => try w.print("mesh payload", .{}), + .heap_resource => |h| try w.print("{s}[%{d}]", .{ if (h.sampler) "SamplerDescriptorHeap" else "ResourceDescriptorHeap", h.index.index() }), .patch_output => |x| try w.print("patch output {d} = %{d}", .{ x.element, x.value.index() }), .output_vertex => |x| try w.print("output {d} vertex {d}", .{ x.element, x.vertex }), .cut => |k| try w.print("cut stream {d}", .{k}), diff --git a/src/ir/lower.zig b/src/ir/lower.zig index 73c0ec1..07dd9f7 100644 --- a/src/ir/lower.zig +++ b/src/ir/lower.zig @@ -447,6 +447,23 @@ const Lowerer = struct { const t = l.types(); const inst = l.b.f.inst(v); if (inst.ty == target) return v; + // A descriptor heap element takes the type it is used as. + if (t.get(inst.ty) == .dynamic_resource and inst.op == .heap_resource) { + return l.b.add(.{ .op = .{ .heap_resource = inst.op.heap_resource }, .ty = target }); + } + // ConstantBuffer read as an S: member by member. + if (t.get(inst.ty) == .resource and t.get(target) == .@"struct") { + const rs = t.get(inst.ty).resource; + if ((rs.kind == .constant_buffer or rs.kind == .texture_buffer) and rs.elem == target) { + const fields = t.get(target).@"struct".fields.items; + const parts = try l.arena.alloc(Ref, fields.len); + for (parts, fields, 0..) |*p, fld, k| { + const idx = try l.b.constInt(try t.scalar(.uint), @intCast(k)); + p.* = try l.b.load(try l.b.add(.{ .op = .{ .access = .{ .base = v, .indices = try l.arena.dupe(Ref, &.{idx}) } }, .ty = fld.type, .ptr = .cbuffer })); + } + return l.b.add(.{ .op = .{ .construct = parts }, .ty = target }); + } + } // Derived structs convert to a base: its fields are a prefix. if (t.get(inst.ty) == .@"struct" and t.get(target) == .@"struct") { const tf = t.get(target).@"struct".fields.items; @@ -700,6 +717,10 @@ const Lowerer = struct { .member => |m| return l.member(e, m.base, m.name), .index => |x| { const bt = t.get(x.base.ty); + if (bt == .descriptor_heap) { + const idx = try l.converted(x.index, try t.scalar(.uint)); + return l.b.add(.{ .op = .{ .heap_resource = .{ .index = idx, .sampler = bt.descriptor_heap.sampler } }, .ty = e.ty }); + } if (bt == .resource) { const res = try l.rvalue(x.base); const idx = try l.indexValue(x.index, bt.resource.kind.indexDims()); @@ -835,6 +856,7 @@ const Lowerer = struct { const t = l.types(); const from = l.b.f.inst(v).ty; if (from == target) return v; + if (t.get(from) == .dynamic_resource) return l.convert(v, target); const aggregate = switch (t.get(target)) { .@"struct", .array => true, else => switch (t.get(from)) { @@ -919,6 +941,19 @@ const Lowerer = struct { const v = try l.rvalue(base); return l.b.add(.{ .op = .{ .extract = .{ .agg = v, .index = r.field } }, .ty = e.ty }); }, + // ConstantBuffer / TextureBuffer: members of S. + .resource => |rs| { + if (rs.kind != .constant_buffer and rs.kind != .texture_buffer) return l.fail(e, "this member access"); + const r = l.s.resolution(e) orelse return l.fail(e, "this member"); + if (r == .bitfield) { + const bf = r.bitfield; + const idx = try l.b.constInt(try t.scalar(.uint), bf.storage); + const sty = t.get(rs.elem).@"struct".fields.items[bf.storage].type; + const ptr = try l.b.add(.{ .op = .{ .access = .{ .base = try l.rvalue(base), .indices = try l.arena.dupe(Ref, &.{idx}) } }, .ty = sty, .ptr = .cbuffer }); + return l.bitRead(try l.b.load(ptr), bf); + } + return l.b.load(try l.lvalue(e)); + }, else => return l.fail(e, "this member access"), } } @@ -965,8 +1000,14 @@ const Lowerer = struct { // struct (a base prefix of derived objects), written // back afterwards to writable storage. const tmp = try l.b.add(.{ .op = .local_var, .ty = owner_ty, .ptr = .function }); - const whole = if (direct) |p| try l.b.load(p) else try l.rvalue(base); - try l.b.store(tmp, try l.basePrefix(whole, base.ty, owner_ty)); + var whole = if (direct) |p| try l.b.load(p) else try l.rvalue(base); + var whole_ty = base.ty; + if (l.s.types.get(base.ty) == .resource) { + // A method of ConstantBuffer's S: on a copy of S. + whole_ty = l.s.types.get(base.ty).resource.elem; + whole = try l.convert(whole, whole_ty); + } + try l.b.store(tmp, try l.basePrefix(whole, whole_ty, owner_ty)); object = tmp; if (direct) |p| switch (l.b.f.inst(p).ptr) { .function, .private, .groupshared => write_back = p, @@ -1156,8 +1197,13 @@ const Lowerer = struct { .member => |m| { const r = l.s.resolution(e) orelse return l.fail(e, "this member"); if (r != .field) return l.fail(e, "this member"); - const base = try l.lvalue(m.base); const idx = try l.b.constInt(try t.scalar(.uint), r.field); + if (t.get(m.base.ty) == .resource) { + // A member of a ConstantBuffer: inside the buffer. + const res = try l.rvalue(m.base); + return l.b.add(.{ .op = .{ .access = .{ .base = res, .indices = try l.arena.dupe(Ref, &.{idx}) } }, .ty = e.ty, .ptr = .cbuffer }); + } + const base = try l.lvalue(m.base); return l.b.add(.{ .op = .{ .access = .{ .base = base, .indices = try l.arena.dupe(Ref, &.{idx}) } }, .ty = e.ty, .ptr = l.b.f.inst(base).ptr }); }, .index => |x| { diff --git a/src/ir/opt.zig b/src/ir/opt.zig index 9b9e867..d7203ab 100644 --- a/src/ir/opt.zig +++ b/src/ir/opt.zig @@ -202,6 +202,7 @@ fn mapOp(a: Allocator, op: Op, ctx: anytype) Allocator.Error!Op { .res_store => |x| .{ .res_store = .{ .res = ctx.map(x.res), .index = ctx.map(x.index), .value = ctx.map(x.value) } }, .method => |x| .{ .method = .{ .name = x.name, .res = ctx.map(x.res), .args = try mapRefs(a, x.args, ctx) } }, .output => |x| .{ .output = .{ .element = x.element, .value = ctx.map(x.value) } }, + .heap_resource => |h| .{ .heap_resource = .{ .index = ctx.map(h.index), .sampler = h.sampler } }, .patch_output => |x| .{ .patch_output = .{ .element = x.element, .value = ctx.map(x.value) } }, .phi => |ps| blk: { const out = try a.alloc(@typeInfo(@TypeOf(ps)).pointer.child, ps.len); diff --git a/src/sema/sema.zig b/src/sema/sema.zig index 9134da2..eb02695 100644 --- a/src/sema/sema.zig +++ b/src/sema/sema.zig @@ -2789,8 +2789,18 @@ pub const Sema = struct { if (r.kind == .constant_buffer or r.kind == .texture_buffer) { if (s.types.get(r.elem) == .@"struct") { const info = s.types.get(r.elem).@"struct"; - for (info.fields.items) |f| { - if (std.mem.eql(u8, f.name, name)) return .{ .ty = f.type, .lvalue = true, .read_only = true }; + var fi = info.fields.items.len; + while (fi > 0) { + fi -= 1; + const f = info.fields.items[fi]; + if (std.mem.eql(u8, f.name, name)) { + s.record(e, .{ .field = @intCast(fi) }); + return .{ .ty = f.type, .lvalue = true, .read_only = true }; + } + } + if (findBitfield(info, name)) |bf| { + s.record(e, .{ .bitfield = bf }); + return .{ .ty = bf.type, .lvalue = true, .read_only = true }; } if (info.sema) |p| { const ss: *StructSema = @ptrCast(@alignCast(p)); diff --git a/src/spirv/emit.zig b/src/spirv/emit.zig index 3ef0f3a..a1734f1 100644 --- a/src/spirv/emit.zig +++ b/src/spirv/emit.zig @@ -23,6 +23,9 @@ const Ref = ir.Ref; pub const Error = Allocator.Error || error{Unsupported}; /// SPIR-V storage classes. +/// Marks a binding that is a recipe (see Emitter.resourceBinding). +const recipe_tag: u32 = 0x8000_0000; + const StorageClass = enum(u32) { uniform_constant = 0, input = 1, uniform = 2, output = 3, workgroup = 4, private = 6, function = 7, image = 11, storage_buffer = 12, task_payload_workgroup = 5402 }; const Capability = enum(u32) { @@ -58,6 +61,7 @@ const Capability = enum(u32) { group_non_uniform_shuffle = 65, group_non_uniform_quad = 68, shader_non_uniform = 5301, + uniform_buffer_array_non_uniform_indexing = 5306, runtime_descriptor_array = 5302, uniform_texel_buffer_array_non_uniform_indexing = 5311, storage_texel_buffer_array_non_uniform_indexing = 5312, @@ -118,6 +122,12 @@ const Emitter = struct { global_vars: []Id = &.{}, /// Buffer block structs by resource type. buffer_blocks: std.AutoHashMapUnmanaged(TypeId, Id) = .empty, + /// ConstantBuffer blocks by S. + cb_blocks: std.AutoHashMapUnmanaged(TypeId, Id) = .empty, + /// Descriptor heaps: a runtime array variable per (heap, element type), + /// on the heap's binding. + heap_vars: std.AutoHashMapUnmanaged(struct { bool, Id }, Id) = .empty, + heap_bindings: [2]u32 = .{ 0, 0 }, /// Image types by (sampled type, dim, arrayed, ms, sampled, format). image_types: std.AutoHashMapUnmanaged([6]u32, Id) = .empty, sampled_image_types: std.AutoHashMapUnmanaged(Id, Id) = .empty, @@ -133,6 +143,10 @@ const Emitter = struct { /// through them). nonuniform_ids: std.AutoHashMapUnmanaged(Id, void) = .empty, variants: std.ArrayList(struct { fi: u32, bindings: []const Id, id: Id }) = .empty, + /// The bindings of the function being emitted (a specialization). + cur_bindings: []const Id = &.{}, + /// Resource array elements bound to specialized parameters. + recipes: std.ArrayList(struct { var_id: Id, ptr_ty: Id, indices: []const Id }) = .empty, /// Entry inputs / outputs: interface variable and its value type. inputs: []Interface = &.{}, outputs: []Interface = &.{}, @@ -324,7 +338,17 @@ const Emitter = struct { const stride = layout.arrayStride(e.t, a.elem, row_major, rules) catch return e.unsupported("buffer member type", .{}); try e.b.emit(.annotations, .decorate, &.{ id, 6, stride }); // ArrayStride }, - .@"struct" => |st| { + .@"struct" => |st| try e.layoutStruct(id, st, rules, st.name), + else => return e.unsupported("buffer members of type '{s}' are not supported yet", .{try e.t.format(e.arena, ty)}), + } + try e.layout_types.put(e.arena, key, id); + return id; + } + + /// Emits struct `id` with `st`'s fields laid out by `rules`. + fn layoutStruct(e: *Emitter, id: Id, st: *const types.StructInfo, rules: layout.Rules, name: []const u8) Error!void { + { + { var ops: std.ArrayList(u32) = .empty; try ops.append(e.arena, id); for (st.fields.items) |fld| try ops.append(e.arena, try e.layoutTypeId(fld.type, rules, fld.row_major)); @@ -343,11 +367,20 @@ const Emitter = struct { } try e.b.emitWithString(.debug_names, .member_name, &.{ id, mk }, fld.name, &.{}); } - try e.b.emitWithString(.debug_names, .name, &.{id}, st.name, &.{}); - }, - else => return e.unsupported("buffer members of type '{s}' are not supported yet", .{try e.t.format(e.arena, ty)}), + try e.b.emitWithString(.debug_names, .name, &.{id}, name, &.{}); + } } - try e.layout_types.put(e.arena, key, id); + } + + /// The Block struct of ConstantBuffer: S's members laid out as a + /// constant buffer (a type of its own, so S itself can be nested). + fn constantBufferBlock(e: *Emitter, s: TypeId) Error!Id { + if (e.cb_blocks.get(s)) |id| return id; + const st = e.t.get(s).@"struct"; + const id = e.b.newId(); + try e.layoutStruct(id, st, .vk_relaxed, try std.fmt.allocPrint(e.arena, "type.ConstantBuffer.{s}", .{st.name})); + try e.b.emit(.annotations, .decorate, &.{ id, 2 }); // Block + try e.cb_blocks.put(e.arena, s, id); return id; } @@ -671,6 +704,22 @@ const Emitter = struct { } } + // Descriptor heaps: the next free bindings of set 0 (resources, + // then samplers), as dxc. + for ([_]bool{ false, true }) |sampler| { + const used_heap = for (m.functions.items) |f| { + const hit = for (f.insts.items) |inst| switch (inst.op) { + .heap_resource => |h| if (h.sampler == sampler) break true, + else => {}, + } else false; + if (hit) break true; + } else false; + if (!used_heap) continue; + while (used.contains(.{ 0, next_free })) next_free += 1; + try used.put(e.arena, .{ 0, next_free }, {}); + e.heap_bindings[@intFromBool(sampler)] = next_free; + } + // Hidden counters (as dxc): a `{ int }` buffer per structured buffer // that uses one, on the next free binding of its set. e.counter_vars = try e.arena.alloc(Id, m.globals.items.len); @@ -929,6 +978,55 @@ const Emitter = struct { /// `bindings` (resource variables; 0 for other parameters). Vulkan /// cannot pass buffer pointers to functions, so each distinct set of /// resource arguments gets its own copy (dxc gets there by inlining). + /// What a resource argument binds a specialized callee's parameter + /// to: a module variable, or (an element of a resource array) a + /// recipe the callee re-creates: `recipe_tag | index` into `recipes`. + fn resourceBinding(e: *Emitter, a: Ref) Error!Id { + const f = e.f; + var x = a; + while (true) switch (f.inst(x).op) { + .load => |p| x = p, + // A resource local: what was stored into it. + .local_var => x = for (f.insts.items) |inst| { + if (inst.op == .store and inst.op.store.ptr == x) break inst.op.store.value; + } else return e.val(x), + else => break, + }; + switch (f.inst(x).op) { + .global => return e.val(x), + .heap_resource => |h| { + // A heap element at a constant index. + if (f.inst(h.index).op != .constant) return e.unsupported("passing a resource from a descriptor heap at a dynamic index to a function is not supported yet", .{}); + const p = try e.resourcePointee(f.inst(x).ty); + const hv = e.heap_vars.get(.{ h.sampler, p.ty }) orelse return e.unsupported("internal: heap variable missing", .{}); + return e.addRecipe(hv, try e.pointerType(p.sc, p.ty), try e.arena.dupe(Id, &.{e.val(h.index)})); + }, + // A specialized parameter passes on what it is bound to. + .param => |pi| return if (pi < e.cur_bindings.len and e.cur_bindings[pi] != 0) e.cur_bindings[pi] else e.val(x), + .access => |acc| { + var base = acc.base; + while (f.inst(base).op == .load) base = f.inst(base).op.load; + if (f.inst(base).op != .global) return e.unsupported("passing this resource to a function is not supported yet", .{}); + const idx = try e.arena.alloc(Id, acc.indices.len); + for (idx, acc.indices) |*d, r| { + if (f.inst(r).op != .constant) return e.unsupported("passing a dynamically selected resource to a function is not supported yet", .{}); + d.* = e.val(r); + } + const p = try e.resourcePointee(f.inst(x).ty); + return e.addRecipe(e.val(base), try e.pointerType(p.sc, p.ty), idx); + }, + else => return e.val(x), + } + } + + fn addRecipe(e: *Emitter, var_id: Id, ptr_ty: Id, idx: []const Id) Error!Id { + for (e.recipes.items, 0..) |rc, k| { + if (rc.var_id == var_id and rc.ptr_ty == ptr_ty and std.mem.eql(Id, rc.indices, idx)) return recipe_tag | @as(Id, @intCast(k)); + } + try e.recipes.append(e.arena, .{ .var_id = var_id, .ptr_ty = ptr_ty, .indices = idx }); + return recipe_tag | @as(Id, @intCast(e.recipes.items.len - 1)); + } + fn variantFor(e: *Emitter, fi: u32, bindings: []const Id) Error!Id { for (e.variants.items) |v| if (v.fi == fi and std.mem.eql(Id, v.bindings, bindings)) return v.id; const id = e.b.newId(); @@ -939,6 +1037,7 @@ const Emitter = struct { fn emitFunction(e: *Emitter, f: *const ir.Function, fn_id: Id, bindings: []const Id) Error!void { e.f = f; + e.cur_bindings = bindings; e.texel_places = .empty; e.mesh_places = .empty; e.vals = try e.arena.alloc(Id, f.insts.items.len); @@ -959,7 +1058,8 @@ const Emitter = struct { var next: usize = 0; for (f.params, param_ids, 0..) |p, *id, k| { if (bindings.len > 0 and bindings[k] != 0) { - id.* = bindings[k]; + // Recipes are re-created at the start of the body. + id.* = if (bindings[k] & recipe_tag != 0) e.b.newId() else bindings[k]; continue; } if (e.mesh_params.contains(.{ f, @intCast(k) })) { @@ -997,6 +1097,13 @@ const Emitter = struct { e.vals[i] = e.b.newId(); try e.b.emit(.functions, .variable, &.{ ptr, e.vals[i], @backingInt(StorageClass.function) }); }; + for (bindings, 0..) |bd, k| if (bd & recipe_tag != 0) { + const rc = e.recipes.items[bd & ~recipe_tag]; + var ops: std.ArrayList(u32) = .empty; + try ops.appendSlice(e.arena, &.{ rc.ptr_ty, param_ids[k], rc.var_id }); + try ops.appendSlice(e.arena, rc.indices); + try e.b.emit(.functions, .access_chain, ops.items); + }; } const blk = f.blocks.items[bi]; for (blk.insts.items) |r| try e.emitInst(r); @@ -1229,6 +1336,7 @@ const Emitter = struct { // Buffers reached through locals or parameters are still // Uniform std430 storage. const into_buffer = e.t.get(f.inst(a.base).ty) == .resource; + const into_cb = into_buffer and e.t.get(f.inst(a.base).ty).resource.kind == .constant_buffer; const base_pl = e.ptr_layouts[a.base.index()]; if (i.ptr == .mesh) { // Mesh outputs: a place, written component by component. @@ -1262,19 +1370,21 @@ const Emitter = struct { try e.mesh_places.put(e.arena, ri, mp); return; } - const sc: StorageClass = if (into_buffer or (base_pl != null and base_pl.?.rules == .std430)) e.bufferSc() else if (base_pl != null) .uniform else switch (i.ptr) { + const sc: StorageClass = if (into_cb) .uniform else if (into_buffer or (base_pl != null and base_pl.?.rules == .std430)) e.bufferSc() else if (base_pl != null) .uniform else switch (i.ptr) { .function => .function, .private => .private, .groupshared => if (e.payload_global != null and e.rootGlobal(a.base) == e.payload_global) .task_payload_workgroup else .workgroup, .cbuffer, .resource => .uniform, else => return e.unsupported("access into this storage is not supported yet", .{}), }; - var pl = if (into_buffer) PtrLayout{ .rules = .std430, .row_major = false } else e.ptr_layouts[a.base.index()]; + var pl = if (into_cb) PtrLayout{ .rules = .vk_relaxed, .row_major = false } else if (into_buffer) PtrLayout{ .rules = .std430, .row_major = false } else e.ptr_layouts[a.base.index()]; var ops: std.ArrayList(u32) = .empty; try ops.appendSlice(e.arena, &.{ 0, 0, e.val(a.base) }); var cur = f.inst(a.base).ty; var indices = a.indices; - if (e.t.get(cur) == .resource) { + if (into_cb) { + cur = e.t.get(cur).resource.elem; + } else if (e.t.get(cur) == .resource) { // buffer[i]...: member 0 (the runtime array), element i. const rk = e.t.get(cur).resource; if (try e.bufferElemType(cur) == null) return e.unsupported("indexing this resource is not supported yet", .{}); @@ -1489,7 +1599,7 @@ const Emitter = struct { const callee = e.m.functions.items[c.func]; if (e.hasResourceParams(callee)) { const bindings = try e.arena.alloc(Id, c.args.len); - for (callee.params, c.args, bindings) |p, a, *bd| bd.* = if (isResourceType(e.t, p.ty)) e.val(a) else 0; + for (callee.params, c.args, bindings) |p, a, *bd| bd.* = if (isResourceType(e.t, p.ty)) try e.resourceBinding(a) else 0; try ops.append(e.arena, try e.variantFor(c.func, bindings)); for (callee.params, c.args) |p, a| if (!isResourceType(e.t, p.ty)) try ops.append(e.arena, e.val(a)); e.vals[ri] = try e.op1(.function_call, i.ty, ops.items); @@ -1547,6 +1657,28 @@ const Emitter = struct { }, .patch_input => |k| e.vals[ri] = try e.loadInterface(e.patches[k], .input, i.ty), .mesh_output => try e.mesh_places.put(e.arena, ri, .{ .kind = i.op.mesh_output, .ty = i.ty }), + .heap_resource => |h| { + if (e.t.get(i.ty) != .resource and e.t.get(i.ty) != .sampler) return; + const p = try e.resourcePointee(i.ty); + const key = .{ h.sampler, p.ty }; + const hv = e.heap_vars.get(key) orelse blk: { + try e.cap(.runtime_descriptor_array); + try e.extension("SPV_EXT_descriptor_indexing"); + const arr = e.b.newId(); + try e.b.emit(.types_globals, .type_runtime_array, &.{ arr, p.ty }); + const v = e.b.newId(); + try e.b.emit(.types_globals, .variable, &.{ try e.pointerType(p.sc, arr), v, @backingInt(p.sc) }); + try e.b.emit(.annotations, .decorate, &.{ v, 34, 0 }); // DescriptorSet + try e.b.emit(.annotations, .decorate, &.{ v, 33, e.heap_bindings[@intFromBool(h.sampler)] }); // Binding + try e.b.emitWithString(.debug_names, .name, &.{v}, if (h.sampler) "SamplerDescriptorHeap" else "ResourceDescriptorHeap", &.{}); + if (e.spv_minor >= 4) try e.interface_ids.append(e.arena, v); + try e.heap_vars.put(e.arena, key, v); + break :blk v; + }; + const id = try e.opRaw(.access_chain, try e.pointerType(p.sc, p.ty), &.{ hv, e.val(h.index) }); + e.vals[ri] = id; + if (e.nonuniform_ids.contains(e.val(h.index))) try e.markNonUniform(id, i.ty); + }, .mesh_payload => { if (e.payload_var == 0) { e.payload_var = e.b.newId(); @@ -1825,6 +1957,7 @@ const Emitter = struct { .sampler => return .{ .sc = .uniform_constant, .ty = try e.samplerType() }, .resource => |r| switch (r.kind) { .structured_buffer, .rw_structured_buffer, .append_structured_buffer, .consume_structured_buffer, .byte_address_buffer, .rw_byte_address_buffer => return .{ .sc = e.bufferSc(), .ty = try e.bufferBlockType(ty) }, + .constant_buffer => if (e.t.get(r.elem) == .@"struct") return .{ .sc = .uniform, .ty = try e.constantBufferBlock(r.elem) }, else => if (texture.shape(r.kind)) |sh| return .{ .sc = .uniform_constant, .ty = try e.imageType(sh, r.elem) }, }, .array => |arr| { @@ -1880,6 +2013,7 @@ const Emitter = struct { .resource => |r| switch (r.kind) { .structured_buffer, .rw_structured_buffer, .append_structured_buffer, .consume_structured_buffer, .byte_address_buffer, .rw_byte_address_buffer => .storage_buffer_array_non_uniform_indexing, .buffer => .uniform_texel_buffer_array_non_uniform_indexing, + .constant_buffer => .uniform_buffer_array_non_uniform_indexing, .rw_buffer => .storage_texel_buffer_array_non_uniform_indexing, else => if (r.kind.isWritable()) .storage_image_array_non_uniform_indexing else .sampled_image_array_non_uniform_indexing, },