diff --git a/src/compile.zig b/src/compile.zig index 52baea1..b393efe 100644 --- a/src/compile.zig +++ b/src/compile.zig @@ -528,6 +528,7 @@ fn run(ctx: *Ctx, arena: std.mem.Allocator) !void { const zv = stats.begin(.spirv); defer if (opts.spirv) zv.end(); if (opts.spirv) { + try zdxc.ir.inline_calls.runResourceReturns(m); zdxc.ir.split_resources.run(arena, m, &diags) catch |err| switch (err) { error.Unsupported => { try diags.render(&sm, ctx.stderr, .{ .format = opts.diag_format, .color = false }); diff --git a/src/front/parser.zig b/src/front/parser.zig index c74f9f0..e772cd0 100644 --- a/src/front/parser.zig +++ b/src/front/parser.zig @@ -41,6 +41,8 @@ pub const Parser = struct { /// Name of the struct most recently parsed by parseStructDeclInto /// (synthesized for anonymous structs), for `typedef struct ...`. last_struct_name: []const u8 = "", + /// The last parseType read `const` after the type (`float const x`). + type_const: bool = false, /// The qualifier words read by the last parseQualifiers call. last_quals: []const ast.QualWord = &.{}, /// Qualifier words for the next parseDeclaratorsInto call. @@ -410,6 +412,8 @@ pub const Parser = struct { fn skipTypeAttrs(p: *const Parser, start: usize) usize { var i = start; + // `T const`: a type qualifier written after the type. + while (p.toks[i].isIdent("const")) i += 1; if (!(p.toks[i].kind == .l_square and p.toks[i + 1].kind == .l_square)) return i; var depth: u32 = 0; while (true) : (i += 1) { @@ -565,10 +569,19 @@ pub const Parser = struct { t.pack_matrix = p.packMatrixAt(type_pos); if (norm != .none) t.norm = norm; if (words.items.len > 0) t.attr_words = words.items; + p.type_const = false; + while (p.eatIdent("const")) p.type_const = true; if (p.at(.l_square) and p.peek(1).kind == .l_square) t.attrs = try p.parseAttributes(); return t; } + /// parseType for a declaration: `const` after the type joins `quals`. + fn parseDeclType(p: *Parser, quals: *ast.Qualifiers) Error!*ast.TypeRef { + const t = try p.parseType(); + if (p.type_const) quals.@"const" = true; + return t; + } + fn parseTypeInner(p: *Parser) Error!*ast.TypeRef { // An elaborated type: `struct S` names S (declaring it if needed). const elaborated = (p.atIdent("struct") or p.atIdent("class")) and p.peek(1).kind == .identifier and p.peek(2).kind != .l_brace and p.peek(2).kind != .colon; @@ -835,9 +848,9 @@ pub const Parser = struct { return out.append(p.arena, d); } - const quals = p.parseQualifiers(); + var quals = p.parseQualifiers(); const words = p.last_quals; - const ty = try p.parseType(); + const ty = try p.parseDeclType(&quals); p.decl_quals = words; const first = out.items.len; try p.parseDeclaratorsInto(out, attrs, quals, template_params, ty, ctx); @@ -1299,9 +1312,9 @@ pub const Parser = struct { if (p.atIdent("void") and p.peek(1).kind == .r_paren) _ = p.advance(); while (!p.at(.r_paren)) { const pattrs = try p.parseAttributes(); - const pquals = p.parseQualifiers(); + var pquals = p.parseQualifiers(); const pwords = p.last_quals; - const pty = try p.parseType(); + const pty = try p.parseDeclType(&pquals); var pname: []const u8 = ""; var pname_loc = p.tok().loc; if (p.at(.identifier) and !isReserved(p.tok().text)) { @@ -1507,8 +1520,8 @@ pub const Parser = struct { /// `expr`, or `T name = init` (C++ condition declaration). fn parseCondition(p: *Parser) Error!struct { decl: ?*ast.Decl, cond: *ast.Expr } { if (!p.startsLocalDecl()) return .{ .decl = null, .cond = try p.parseExpr() }; - const quals = p.parseQualifiers(); - const ty = try p.parseType(); + var quals = p.parseQualifiers(); + const ty = try p.parseDeclType(&quals); const name = try p.expectIdent("variable name"); _ = try p.expect(.equal, "'='"); const init_expr = try p.parseAssign(); diff --git a/src/ir/inline.zig b/src/ir/inline.zig index 6d69561..a432bf8 100644 --- a/src/ir/inline.zig +++ b/src/ir/inline.zig @@ -20,6 +20,7 @@ const Allocator = std.mem.Allocator; const ir = @import("ir.zig"); const types = @import("../sema/types.zig"); const opt = @import("opt.zig"); +const split_resources = @import("split_resources.zig"); const Ref = ir.Ref; const BlockId = ir.BlockId; @@ -73,6 +74,41 @@ pub fn run(m: *ir.Module) Error!void { try markDead(m); } +/// Inlines only the calls of functions that return a resource or a struct +/// holding one, in every kind of module (ray-tracing libraries included), +/// before resources are split out of structs: what such a function +/// returns can be an element of a resource array picked by an index it +/// computes (`bindless[NonUniformResourceIndex(i)]`), which no function +/// signature can pass back. dxc's legalization inlines everything. +pub fn runResourceReturns(m: *ir.Module) Error!void { + const a = m.arena; + const n = m.functions.items.len; + const shapes = try a.alloc(?Shape, n); + var any = false; + for (m.functions.items, shapes) |f, *sh| { + sh.* = .keep; + if (!isResource(m.types, f.ret) and !split_resources.holdsResources(m.types, f.ret)) continue; + const shape = try shapeOf(a, m, f); + sh.* = shape; + if (shape != .keep) any = true; + } + if (!any) return; + const done = try a.alloc(bool, n); + @memset(done, false); + var work: std.ArrayList(u32) = .empty; + for (m.entries.items) |e| { + try work.append(a, e.wrapper); + if (e.patch_wrapper) |pw| try work.append(a, pw); + } + try work.appendSlice(a, m.exports.items); + while (work.pop()) |fi| { + if (done[fi]) continue; + done[fi] = true; + try inlineCalls(m, m.functions.items[fi], shapes, &work); + } + try markDead(m); +} + /// How a function returns, for inlining it. const Shape = union(enum) { /// Not inlinable. diff --git a/src/ir/ir.zig b/src/ir/ir.zig index 60aa17d..063679d 100644 --- a/src/ir/ir.zig +++ b/src/ir/ir.zig @@ -533,8 +533,9 @@ pub const SpirvExt = struct { pub const SpirvInst = struct { opcode: u32, set: ?[]const u8 = null, - /// Values, pointers (`[[vk::ext_reference]]`) or literal words. - operands: []const union(enum) { value: Ref, literal: u32, type: TypeId }, + /// Values, pointers (`[[vk::ext_reference]]`), literal words, types, + /// or the id of an OpString (printf's format). + operands: []const union(enum) { value: Ref, literal: u32, type: TypeId, string: []const u8 }, capabilities: []const u32 = &.{}, extensions: []const []const u8 = &.{}, }; diff --git a/src/ir/lower.zig b/src/ir/lower.zig index a9c82fd..2b53209 100644 --- a/src/ir/lower.zig +++ b/src/ir/lower.zig @@ -1565,6 +1565,16 @@ const Lowerer = struct { }; return result; } + // printf: NonSemantic.DebugPrintf's DebugPrintf (opcode 1) + // with the format as an OpString (SPIR-V only). + if (std.mem.eql(u8, name, "printf") and l.s.opts.spirv and args.len >= 1 and args[0].kind == .string_lit) { + const p = try l.arena.create(ir.SpirvInst); + const ops = try l.arena.alloc(@typeInfo(@TypeOf(p.operands)).pointer.child, args.len); + ops[0] = .{ .string = try stringContents(l.arena, args[0].kind.string_lit) }; + for (ops[1..], args[1..]) |*o, a| o.* = .{ .value = try l.converted(a, try l.concrete(a.ty)) }; + p.* = .{ .opcode = 1, .set = "NonSemantic.DebugPrintf", .operands = ops, .extensions = try l.arena.dupe([]const u8, &.{"SPV_KHR_non_semantic_info"}) }; + return l.b.add(.{ .op = .{ .spirv_inst = p }, .ty = TypeTable.void_type }); + } if (std.mem.eql(u8, name, "DispatchMesh") and args.len == 4) { // The payload goes by reference (a groupshared // variable). diff --git a/src/ir/opt.zig b/src/ir/opt.zig index d135021..e561dda 100644 --- a/src/ir/opt.zig +++ b/src/ir/opt.zig @@ -207,7 +207,7 @@ pub fn mapOp(a: Allocator, op: Op, ctx: anytype) Allocator.Error!Op { const ops = try a.dupe(@typeInfo(@TypeOf(x.operands)).pointer.child, x.operands); for (ops) |*o| switch (o.*) { .value => |*v| v.* = ctx.map(v.*), - .literal, .type => {}, + .literal, .type, .string => {}, }; const n = try a.create(ir.SpirvInst); n.* = x.*; @@ -278,7 +278,7 @@ pub fn eachOperand(op: Op, ctx: anytype) void { .heap_resource => |h| ctx.use(h.index), .spirv_inst => |x| for (x.operands) |o| switch (o) { .value => |v| ctx.use(v), - .literal, .type => {}, + .literal, .type, .string => {}, }, .patch_output => |x| ctx.use(x.value), .phi => |ps| for (ps) |pp| ctx.use(pp.value), diff --git a/src/ir/split_resources.zig b/src/ir/split_resources.zig index d5f4aa1..3179c23 100644 --- a/src/ir/split_resources.zig +++ b/src/ir/split_resources.zig @@ -189,6 +189,8 @@ const Pass = struct { if (info.done) return; info.done = true; const f = p.m.functions.items[fi]; + // (Inlined everywhere: not emitted.) + if (f.dead) return; // Callees first: their returns may be resources. for (f.insts.items) |inst| if (inst.op == .call) try p.function(inst.op.call.func); @@ -209,7 +211,10 @@ const Pass = struct { const n_old = f.insts.items.len; const ret_holds = holdsResources(p.t, f.ret) or isOpaque(p.t, f.ret); - for (f.blocks.items, 0..) |*blk, bi| { + // Definitions before uses: inlining leaves a call's continuation + // ahead of the callee's blocks. + for (try reversePostorder(p.a, f)) |bi| { + const blk = &f.blocks.items[bi]; var out: std.ArrayList(Ref) = .empty; for (blk.insts.items) |r| { const old = f.insts.items[r.index()]; @@ -421,7 +426,6 @@ const Pass = struct { .@"switch" => |sw| blk.term = .{ .@"switch" = .{ .value = mp.map(sw.value), .default = sw.default, .cases = sw.cases } }, else => {}, } - _ = bi; } _ = n_old; // What each out / inout resource holds when the function returns: @@ -480,6 +484,42 @@ const Pass = struct { } }; +/// `f`'s blocks in reverse postorder from the entry (each block after its +/// dominators), then any unreachable ones in list order. +fn reversePostorder(a: Allocator, f: *const ir.Function) Allocator.Error![]const u32 { + const n = f.blocks.items.len; + const seen = try a.alloc(bool, n); + @memset(seen, false); + var post: std.ArrayList(u32) = try .initCapacity(a, n); + // (block, whether its successors were pushed) + var stack: std.ArrayList(struct { b: u32, expanded: bool }) = .empty; + if (n > 0) try stack.append(a, .{ .b = 0, .expanded = false }); + while (stack.pop()) |it| { + if (it.expanded) { + post.appendAssumeCapacity(it.b); + continue; + } + if (seen[it.b]) continue; + seen[it.b] = true; + try stack.append(a, .{ .b = it.b, .expanded = true }); + const succs: []const ir.BlockId = switch (f.blocks.items[it.b].term) { + .br => |t| &.{t}, + .cond_br => |c| &.{ c.@"else", c.then }, + .@"switch" => |sw| blk: { + const out = try a.alloc(ir.BlockId, sw.cases.len + 1); + for (sw.cases, 0..) |c, i| out[sw.cases.len - 1 - i] = c.block; + out[sw.cases.len] = sw.default; + break :blk out; + }, + else => &.{}, + }; + for (succs) |sb| if (sb != .none and !seen[sb.index()]) try stack.append(a, .{ .b = @intCast(sb.index()), .expanded = false }); + } + std.mem.reverse(u32, post.items); + for (0..n) |bi| if (!seen[bi]) post.appendAssumeCapacity(@intCast(bi)); + return post.items; +} + /// Splits every function's resource-holding aggregates (SPIR-V only). pub fn run(a: Allocator, m: *ir.Module, diags: *diag.Diagnostics) Error!void { var any = false; diff --git a/src/sema/intrinsics.zig b/src/sema/intrinsics.zig index 415c6e5..1008460 100644 --- a/src/sema/intrinsics.zig +++ b/src/sema/intrinsics.zig @@ -197,6 +197,16 @@ const Bindings = struct { return null; } + /// Bind `name` to `v` unless it is bound to a smaller value. + fn lower(b: *Bindings, name: []const u8, v: u16) void { + if (std.fmt.parseInt(u16, name, 10)) |_| return else |_| {} + for (b.names[0..b.n], b.values[0..b.n]) |k, *old| if (std.mem.eql(u8, k, name)) { + old.* = @min(old.*, v); + return; + }; + _ = b.bind(name, v); + } + /// Bind or check; false on conflict. fn bind(b: *Bindings, name: []const u8, v: u16) bool { if (b.get(name)) |old| return old == v; @@ -260,6 +270,22 @@ fn matchOne(sema: anytype, it: *const table.Intrinsic, object: ?TypeId, args: [] const sh = t.shape(a.ty) orelse continue; if (bindings.any_shape == null or sh.count() > bindings.any_shape.?.count()) bindings.any_shape = sh; } + // A dimension shared by several arguments (`dot(numeric, + // numeric)`, mul's `numeric` and `numeric`) is the + // smallest one: dxc truncates the larger arguments (with a warning). + // Scalars splat and do not bind it. + for (args[0..it.params.len], 1..) |a, i| { + const ls = if (specs[i].dims.len > 0) specs[i] else specs[layout_group[i]]; + const sh = t.shape(a.ty) orelse continue; + switch (ls.dims.len) { + 1 => if (sh.kind == .vector) bindings.lower(ls.dims[0], sh.cols), + 2 => if (sh.kind == .matrix) { + bindings.lower(ls.dims[0], sh.rows); + bindings.lower(ls.dims[1], sh.cols); + }, + else => {}, + } + } var sum: u32 = 0; var worst: u32 = 0; const out_params = try sema.arena.alloc(bool, args.len); diff --git a/src/sema/sema.zig b/src/sema/sema.zig index 9fa2d52..c9844c4 100644 --- a/src/sema/sema.zig +++ b/src/sema/sema.zig @@ -99,6 +99,10 @@ pub const Param = struct { type: TypeId, dir: enum { in, out, inout }, has_default: bool, + /// A template instance's default argument that does not convert to + /// the parameter's type: an error only where a call uses it (C++ + /// instantiates default arguments on use). + bad_default: bool = false, /// `groupshared` parameter (SM 6.8 groupshared arguments). groupshared: bool = false, }; @@ -2521,7 +2525,16 @@ pub const Sema = struct { .has_default = p.init != null, .groupshared = p.quals.groupshared, }; - if (p.init) |init_e| _ = try s.checkInitializer(pt, init_e); + if (p.init) |init_e| { + if (s.instance_depth > 0) { + const m = s.diags.mark(); + _ = try s.checkInitializer(pt, init_e); + if (s.diags.error_count != m.errors) { + s.diags.rollback(m); + out.bad_default = true; + } + } else _ = try s.checkInitializer(pt, init_e); + } } const func = try s.arena.create(Function); func.* = .{ .name = name, .decl = f, .loc = d.loc, .ret = ret, .params = params, .defined = f.body != null, .owner = owner }; @@ -3843,7 +3856,17 @@ pub const Sema = struct { var explicit: ?TypeId = null; if (template_args.len > 0) explicit = try s.typeArg(template_args[0]); const r = try s.intrinsic_db.resolve(s, e.loc, if (s.opts.spirv and isVkQualified(callee)) "VkIntrinsics" else "Intrinsics", name, null, arg_types, explicit); - if (r.ok) s.record(e, .{ .intrinsic = .{ .index = r.index, .params = r.params } }); + if (r.ok) { + s.record(e, .{ .intrinsic = .{ .index = r.index, .params = r.params } }); + // `dot(float4, float3)`: the longer argument is truncated. + for (arg_types, r.params[0..@min(arg_types.len, r.params.len)], 0..) |a, pt, i| { + const as = s.types.shape(a.ty) orelse continue; + const ps = s.types.shape(pt) orelse continue; + if (as.kind == .scalar or ps.kind == .scalar or (ps.rows >= as.rows and ps.cols >= as.cols)) continue; + const loc = if (e.kind == .call and i < e.kind.call.args.len) startLoc(e.kind.call.args[i]) else a.loc; + s.warn(loc, "conversion", "implicit truncation of vector type", .{}); + } + } return rvalue(r.ret); } @@ -3897,6 +3920,10 @@ pub const Sema = struct { s.err(a.loc, "cannot bind non-lvalue argument to {s} parameter", .{if (f.params[i].dir == .out) "out" else "inout"}); } } + for (f.params[@min(args.len, f.params.len)..]) |p| if (p.bad_default) { + s.err(callee.loc, "cannot initialize a parameter of type '{s}' with its default argument", .{s.typeName(p.type)}); + return TypeTable.error_type; + }; if (s.current_fn) |caller| caller.callees.append(s.arena, f) catch {}; s.record(e, .{ .function = f }); s.ensureBody(f) catch {}; @@ -4138,6 +4165,9 @@ pub fn parseIntLiteral(text: []const u8) ?i64 { if (digits.len > 2 and digits[0] == '0' and (digits[1] == 'x' or digits[1] == 'X')) { base = 16; body = digits[2..]; + } else if (isBinaryLiteral(digits)) { + base = 2; + body = digits[2..]; } else if (digits.len > 1 and digits[0] == '0') { base = 8; body = digits[1..]; @@ -4157,6 +4187,11 @@ pub fn parseFloatLiteral(text: []const u8) ?f64 { /// dxc's `.#INF`): where the suffix starts and whether it is floating. fn scanLiteral(text: []const u8) struct { end: usize, float: bool, inf: bool = false } { var i: usize = 0; + if (isBinaryLiteral(text)) { + i = 2; + while (i < text.len and (text[i] == '0' or text[i] == '1')) i += 1; + return .{ .end = i, .float = false }; + } const hex = text.len > 1 and text[0] == '0' and (text[1] == 'x' or text[1] == 'X'); if (hex) i = 2; const isDigit = struct { @@ -4185,6 +4220,24 @@ fn scanLiteral(text: []const u8) struct { end: usize, float: bool, inf: bool = f return .{ .end = i, .float = float }; } +/// `0b101`: a binary integer literal (clang accepts them in HLSL). +/// Where an expression's text starts (clang's getBeginLoc): `i` in `i.T`. +fn startLoc(e: *const ast.Expr) Loc { + return switch (e.kind) { + .member => |m| startLoc(m.base), + .index => |x| startLoc(x.base), + .binary => |b| startLoc(b.lhs), + .assign => |b| startLoc(b.lhs), + .conditional => |c| startLoc(c.cond), + .call => |c| startLoc(c.callee), + else => e.loc, + }; +} + +fn isBinaryLiteral(text: []const u8) bool { + return text.len > 2 and text[0] == '0' and (text[1] == 'b' or text[1] == 'B') and (text[2] == '0' or text[2] == '1'); +} + /// `f16` / `f32` / `f64` (any case) at the end of a float literal. fn fixedFloatSuffix(text: []const u8) ?[]const u8 { if (text.len < 4) return null; diff --git a/src/spirv/builder.zig b/src/spirv/builder.zig index 3f02d15..7ef7880 100644 --- a/src/spirv/builder.zig +++ b/src/spirv/builder.zig @@ -10,6 +10,7 @@ pub const Id = u32; pub const Op = enum(u16) { undef = 1, source = 3, + string = 7, name = 5, member_name = 6, extension = 10, @@ -259,6 +260,8 @@ pub const Section = enum { memory_model, entry_points, execution_modes, + /// OpString (before OpSource and the names). + debug_strings, debug_names, annotations, types_globals, diff --git a/src/spirv/emit.zig b/src/spirv/emit.zig index c64105c..41e117b 100644 --- a/src/spirv/emit.zig +++ b/src/spirv/emit.zig @@ -202,6 +202,7 @@ const Emitter = struct { used_bindings: std.AutoHashMapUnmanaged(struct { u32, u32 }, void) = .empty, spec_ids: std.AutoHashMapUnmanaged(u32, Id) = .empty, ext_imports: std.StringHashMapUnmanaged(Id) = .empty, + string_ids: std.StringHashMapUnmanaged(Id) = .empty, /// Flattened resource arrays: a variable per element. flat_vars: std.AutoHashMapUnmanaged(u32, []const Id) = .empty, flat_iface: std.ArrayList(Id) = .empty, @@ -837,12 +838,22 @@ const Emitter = struct { .value => |r| e.val(r), .literal => |w| w, .type => |t| try e.typeId(t), + .string => |str| try e.stringId(str), }); const op: Op = if (x.set != null) .ext_inst else @enumFromInt(@as(u16, @intCast(x.opcode))); try e.b.emit(.functions, op, words.items); return id; } + /// An OpString of `str` (made once). + fn stringId(e: *Emitter, str: []const u8) Error!Id { + if (e.string_ids.get(str)) |id| return id; + const id = e.b.newId(); + try e.b.emitWithString(.debug_strings, .string, &.{id}, str, &.{}); + try e.string_ids.put(e.arena, str, id); + return id; + } + /// An OpExtInstImport of `name` (made once). fn extInstImport(e: *Emitter, name: []const u8) Error!Id { if (std.mem.eql(u8, name, "GLSL.std.450")) {