Compare commits

...

2 Commits

Author SHA1 Message Date
peterino2 72f1760844 Unroll small loops only, and SCCP in reverse postorder
The Unreal work unrolled far more than dxc does: the IR unrolled any
small constant-count loop, and the DXIL unroller any loop of up to 256
trips. On Glide's GlimmerProbeTrace and GlimmerSHUpdate compiles took
10-17x longer and DXIL grew to 470 KB (dxc: 155 KB), so Glide's
replayed compiles took 2.7x as long as with main.

- the IR's automatic unrolling is gone again (it did little for Unreal)
- DXIL unrolls a loop only when unrolled it stays within 300
  instructions, as dxc unrolls only small loops without [unroll]
- SCCP visits blocks in reverse postorder, so it settles in a few passes

Glide, against main (bb942b0): 24 threads 1.36 s vs 1.25 s, serial sum
13.2 s vs 11.8 s, DXIL 58.1 MB vs 61.4 MB. Unreal's corpus still
compiles, validates, and reflects no UAV dxc leaves out.
2026-11-03 00:12:50 -08:00
peterino2 a80a77c0b8 Compile Unreal Engine 5.8's shaders as a DXC drop-in
Every shader the editor compiles (11,488 recorded Compile calls) now
compiles, passes DXC 1.8's validator, and reflects bindings the engine
accepts; the editor runs with the D3D debug layer clean.

Front end and semantics:
- -HV 2016..2018 and 2021, with HLSL 2018's component-wise &&, || and ?:
- overload ranking with DXC's conversion costs (worst, then sum), where
  intrinsics compete with user functions and templates; ref parameters
  of intrinsics (Interlocked* destinations) match exactly
- template class methods checked on use; elaborated struct declarations;
  struct fields before globals in methods
- layout of structs over 256 fields

DXIL backend:
- loops with a constant trip count unrolled after promotion (unroll.zig)
- sparse conditional constant propagation (sccp.zig)
- loops with no effects deleted; constant switches folded; float compares
  of constants folded; phis read on the edge their branch's condition
  decides; empty branches folded through chains of empty blocks
- unreachable blocks, unused groupshared, and resources no code uses any
  more dropped; shader flags, PSV and handle properties from what is left
- 64-bit typed resources and atomics
2026-11-02 23:34:14 -08:00
14 changed files with 2498 additions and 227 deletions

View File

@ -168,6 +168,8 @@ const Options = struct {
preprocess: bool = false, preprocess: bool = false,
pp_output: ?[]const u8 = null, pp_output: ?[]const u8 = null,
enable_16bit: bool = false, enable_16bit: bool = false,
/// -HV: 2021, or 2016-2018 (component-wise `&&`, `||` and `?:`).
hlsl_version: u16 = 2021,
row_major: bool = false, row_major: bool = false,
col_major: bool = false, col_major: bool = false,
/// -force-rootsig-ver, -Qstrip_rootsignature, -rootsig-define, -Frs. /// -force-rootsig-ver, -Qstrip_rootsignature, -rootsig-define, -Frs.
@ -249,8 +251,12 @@ fn parseArgs(ctx: *Ctx, arena: std.mem.Allocator, args: []const []const u8) !?Op
try opts.defines.append(arena, .{ .name = v[0..eq], .value = v[eq + 1 ..] }); try opts.defines.append(arena, .{ .name = v[0..eq], .value = v[eq + 1 ..] });
} else try opts.defines.append(arena, .{ .name = v }), } else try opts.defines.append(arena, .{ .name = v }),
.I => try opts.include_dirs.append(arena, v), .I => try opts.include_dirs.append(arena, v),
.hlsl_version => if (!std.mem.eql(u8, v, "2021")) { .hlsl_version => {
return ctx.fail("HLSL version {s} is not supported; zdxc implements HLSL 2021 only", .{v}); const n = std.fmt.parseInt(u16, v, 10) catch 0;
if (n != 2021 and (n < 2016 or n > 2018)) {
return ctx.fail("HLSL version {s} is not supported; zdxc implements HLSL 2016-2018 and 2021", .{v});
}
opts.hlsl_version = n;
}, },
.P => opts.preprocess = true, .P => opts.preprocess = true,
.spirv => opts.spirv = true, .spirv => opts.spirv = true,
@ -435,6 +441,7 @@ fn run(ctx: *Ctx, arena: std.mem.Allocator) !void {
.spirv = opts.spirv, .spirv = opts.spirv,
.spirv_minor = if (zdxc.spirv.emit.TargetEnv.parse(opts.target_env)) |t| t.minor else 0, .spirv_minor = if (zdxc.spirv.emit.TargetEnv.parse(opts.target_env)) |t| t.minor else 0,
.enable_16bit = opts.enable_16bit, .enable_16bit = opts.enable_16bit,
.hlsl_version = opts.hlsl_version,
}); });
var out: Io.Writer.Allocating = .init(arena); var out: Io.Writer.Allocating = .init(arena);
var module: ?zdxc.ir.ir.Module = null; var module: ?zdxc.ir.ir.Module = null;
@ -452,6 +459,7 @@ fn run(ctx: *Ctx, arena: std.mem.Allocator) !void {
.entry = if (opts.sema or is_lib) null else opts.entry, .entry = if (opts.sema or is_lib) null else opts.entry,
.spirv = opts.spirv, .spirv = opts.spirv,
.enable_16bit = opts.enable_16bit, .enable_16bit = opts.enable_16bit,
.hlsl_version = opts.hlsl_version,
.sm_minor = if (profile) |p| p.minor else 10, .sm_minor = if (profile) |p| p.minor else 10,
.library = is_lib, .library = is_lib,
.root = opts.entry, .root = opts.entry,

File diff suppressed because it is too large Load Diff

View File

@ -237,7 +237,7 @@ pub fn featureInfo(fl: u64) u64 {
.{ bit.typed_uav_load, 0x800 }, .{ bit.resource_heap, 0x2000000 }, .{ bit.sampler_heap, 0x4000000 }, .{ bit.typed_uav_load, 0x800 }, .{ bit.resource_heap, 0x2000000 }, .{ bit.sampler_heap, 0x4000000 },
.{ bit.barycentrics, 0x20000 }, .{ bit.extended_command_info, 0x100000000 }, .{ bit.tiled_resources, 0x100 }, .{ bit.barycentrics, 0x20000 }, .{ bit.extended_command_info, 0x100000000 }, .{ bit.tiled_resources, 0x100 },
.{ 1 << 29, 0x1000000 }, .{ 1 << 18, 0x1000 }, .{ 1 << 41, 0x200000000 }, .{ bit.raytracing_1_1, 0x100000 }, .{ bit.sampler_feedback, 0x200000 }, .{ 1 << 29, 0x1000000 }, .{ 1 << 18, 0x1000 }, .{ 1 << 41, 0x200000000 }, .{ bit.raytracing_1_1, 0x100000 }, .{ bit.sampler_feedback, 0x200000 },
.{ bit.advanced_texture_ops, 0x20000000 }, .{ bit.uses_derivatives, 0x100 << 32 }, .{ bit.requires_group, 0x200 << 32 }, .{ bit.advanced_texture_ops, 0x20000000 }, .{ 1 << 27, 0x400000 }, .{ bit.uses_derivatives, 0x100 << 32 }, .{ bit.requires_group, 0x200 << 32 },
}; };
var out: u64 = 0; var out: u64 = 0;
for (map) |e| if (fl & e[0] != 0) { for (map) |e| if (fl & e[0] != 0) {

View File

@ -309,7 +309,9 @@ pub fn run(a: Allocator, m: *module.Module, func: u32, dyn: *const std.AutoHashM
return v; return v;
} }
}; };
for (insts, 0..) |inst, i| switch (inst.op) { // (Code no path reaches, such as loops unrolling left behind, does
// not count.)
for (insts, 0..) |inst, i| if (rpo_index[block_of[i]] != none) switch (inst.op) {
.gep => |g| if (g.ptr == .inst and var_base[g.ptr.inst] != none and insts[g.ptr.inst].op == .alloca) { .gep => |g| if (g.ptr == .inst and var_base[g.ptr.inst] != none and insts[g.ptr.inst].op == .alloca) {
const al = g.ptr.inst; const al = g.ptr.inst;
if (direct[al]) { if (direct[al]) {
@ -329,10 +331,11 @@ pub fn run(a: Allocator, m: *module.Module, func: u32, dyn: *const std.AutoHashM
}; };
{ {
var scan: Scan = .{ .insts = insts, .var_base = var_base, .direct = direct, .gep_alloca = gep_alloca }; var scan: Scan = .{ .insts = insts, .var_base = var_base, .direct = direct, .gep_alloca = gep_alloca };
for (insts) |*inst| try operands(false, a, inst, &scan); for (insts, 0..) |*inst, i| if (rpo_index[block_of[i]] != none) try operands(false, a, inst, &scan);
} }
// Loads and stores must move whole elements of the element type. // Loads and stores must move whole elements of the element type.
for (insts) |inst| { for (insts, 0..) |inst, i| {
if (rpo_index[block_of[i]] == none) continue;
const ptr, const ty = switch (inst.op) { const ptr, const ty = switch (inst.op) {
.load => |x| .{ x.ptr, inst.ty }, .load => |x| .{ x.ptr, inst.ty },
.store => |x| .{ x.ptr, typeOf(m, f, x.val) }, .store => |x| .{ x.ptr, typeOf(m, f, x.val) },
@ -350,7 +353,6 @@ pub fn run(a: Allocator, m: *module.Module, func: u32, dyn: *const std.AutoHashM
var_base[i] = nv; var_base[i] = nv;
nv += if (direct[i]) 1 else @intCast(m.types.items[inst.op.alloca.elem].array.len); nv += if (direct[i]) 1 else @intCast(m.types.items[inst.op.alloca.elem].array.len);
} }
if (nv == 0) return;
const var_ty = try a.alloc(TypeId, nv); const var_ty = try a.alloc(TypeId, nv);
for (insts, 0..) |inst, i| { for (insts, 0..) |inst, i| {
if (inst.op != .alloca or var_base[i] == none) continue; if (inst.op != .alloca or var_base[i] == none) continue;
@ -591,9 +593,18 @@ pub fn run(a: Allocator, m: *module.Module, func: u32, dyn: *const std.AutoHashM
// selects on a constant. // selects on a constant.
for (insts, 0..) |inst, i| { for (insts, 0..) |inst, i| {
if (repl[i] != null) continue; if (repl[i] != null) continue;
if (inst.op == .phi) if (try edgePhi(m, insts, block_start, repl, n, block_of[i], inst)) |v| {
repl[i] = v;
continue;
};
repl[i] = try simplify(m, f, repl, n, phi_var.items, var_ty, inst); repl[i] = try simplify(m, f, repl, n, phi_var.items, var_ty, inst);
} }
// Branches on what is now a constant go one way (as dxc's simplifycfg
// makes them): blocks no longer reachable keep only an `unreachable`,
// and phis lose the edges that are gone.
var reach = try foldConstantBranches(a, m, insts, block_start, repl, bphis, bphi_off, incoming);
// The instructions that go: promoted allocas, their getelementptrs, // The instructions that go: promoted allocas, their getelementptrs,
// loads and stores. // loads and stores.
const removed = try a.alloc(bool, n); const removed = try a.alloc(bool, n);
@ -608,50 +619,66 @@ pub fn run(a: Allocator, m: *module.Module, func: u32, dyn: *const std.AutoHashM
// transitively; new phis likewise. (The loads promotion leaves dead, // transitively; new phis likewise. (The loads promotion leaves dead,
// such as copies of arguments never read, go too.) // such as copies of arguments never read, go too.)
const live = try a.alloc(bool, n + np); const live = try a.alloc(bool, n + np);
@memset(live, false); while (true) {
{ @memset(live, false);
var work: std.ArrayList(u32) = .empty; {
const Mark = struct { var work: std.ArrayList(u32) = .empty;
repl: []const ?Value, const Mark = struct {
live: []bool, repl: []const ?Value,
removed: []const bool, live: []bool,
work: *std.ArrayList(u32), removed: []const bool,
a: Allocator, work: *std.ArrayList(u32),
failed: bool = false, a: Allocator,
failed: bool = false,
fn visit(s: *@This(), v: Value, _: Role) Value { fn visit(s: *@This(), v: Value, _: Role) Value {
const x = resolve(s.repl, v); const x = resolve(s.repl, v);
if (x == .inst and !s.live[x.inst] and !(x.inst < s.removed.len and s.removed[x.inst])) { if (x == .inst and !s.live[x.inst] and !(x.inst < s.removed.len and s.removed[x.inst])) {
s.live[x.inst] = true; s.live[x.inst] = true;
s.work.append(s.a, x.inst) catch { s.work.append(s.a, x.inst) catch {
s.failed = true; s.failed = true;
}; };
}
return v;
}
};
var mark: Mark = .{ .repl = repl, .live = live, .removed = removed, .work = &work, .a = a };
for (insts, 0..) |inst, i| if (!removed[i] and hasEffects(m, inst) and (reach[block_of[i]] or i == block_start[block_of[i] + 1] - 1)) {
live[i] = true;
try work.append(a, @intCast(i));
};
while (work.pop()) |x| {
if (x < n) {
var inst = insts[x];
try operands(false, a, &inst, &mark);
} else for (incoming[x - n]) |in| {
_ = mark.visit(in.val, .other);
} }
return v;
}
};
var mark: Mark = .{ .repl = repl, .live = live, .removed = removed, .work = &work, .a = a };
for (insts, 0..) |inst, i| if (!removed[i] and hasEffects(m, inst)) {
live[i] = true;
try work.append(a, @intCast(i));
};
while (work.pop()) |x| {
if (x < n) {
var inst = insts[x];
try operands(false, a, &inst, &mark);
} else for (incoming[x - n]) |in| {
_ = mark.visit(in.val, .other);
} }
if (mark.failed) return error.OutOfMemory;
} }
if (mark.failed) return error.OutOfMemory; // A branch whose arms do nothing (live) and meet again, with the
// same values for the merge's phis, goes nowhere: its condition
// becomes `true` (dxc's simplifycfg removes the branch) and liveness
// runs again without what only the condition read.
if (!try foldEmptyBranches(a, m, insts, block_start, reach, live, repl, n, bphis, bphi_off, incoming)) break;
reach = try foldConstantBranches(a, m, insts, block_start, repl, bphis, bphi_off, incoming);
} }
// New indices: in each block the existing phis, then the new ones, // New indices: in each block the existing phis, then the new ones,
// then the rest. // then the rest.
// (Blocks no path reaches go: the validator rejects `unreachable`.)
const new_block = try a.alloc(u32, nb);
var kept: u32 = 0;
for (new_block, reach) |*nbk, r| {
nbk.* = if (r) kept else none;
if (r) kept += 1;
}
const index = try a.alloc(u32, n + np); const index = try a.alloc(u32, n + np);
@memset(index, none); @memset(index, none);
var count: u32 = 0; var count: u32 = 0;
for (0..nb) |b| { for (0..nb) |b| {
if (!reach[b]) continue;
var i = block_start[b]; var i = block_start[b];
while (i < block_start[b + 1] and insts[i].op == .phi) : (i += 1) if (live[i]) { while (i < block_start[b + 1] and insts[i].op == .phi) : (i += 1) if (live[i]) {
index[i] = count; index[i] = count;
@ -679,25 +706,234 @@ pub fn run(a: Allocator, m: *module.Module, func: u32, dyn: *const std.AutoHashM
var out: std.ArrayList(Inst) = .empty; var out: std.ArrayList(Inst) = .empty;
try out.ensureTotalCapacityPrecise(ma, count); try out.ensureTotalCapacityPrecise(ma, count);
for (0..nb) |b| { for (0..nb) |b| {
if (!reach[b]) continue;
var i = block_start[b]; var i = block_start[b];
while (i < block_start[b + 1] and insts[i].op == .phi) : (i += 1) if (live[i]) { while (i < block_start[b + 1] and insts[i].op == .phi) : (i += 1) if (live[i]) {
var inst = insts[i]; var inst = insts[i];
try operands(true, ma, &inst, &map); try operands(true, ma, &inst, &map);
const edges = try ma.alloc(Edge, inst.op.phi.incoming.len);
for (inst.op.phi.incoming, edges) |in, *e| e.* = .{ .val = in.val, .block = new_block[in.block] };
inst.op.phi.incoming = edges;
out.appendAssumeCapacity(inst); out.appendAssumeCapacity(inst);
}; };
for (bphis[bphi_off[b]..bphi_off[b + 1]]) |j| if (live[n + j]) { for (bphis[bphi_off[b]..bphi_off[b + 1]]) |j| if (live[n + j]) {
const edges = try ma.alloc(Edge, incoming[j].len); const edges = try ma.alloc(Edge, incoming[j].len);
for (incoming[j], edges) |in, *e| e.* = .{ .val = map.visit(in.val, .other), .block = in.block }; for (incoming[j], edges) |in, *e| e.* = .{ .val = map.visit(in.val, .other), .block = new_block[in.block] };
out.appendAssumeCapacity(.{ .ty = var_ty[phi_var.items[j]], .op = .{ .phi = .{ .incoming = edges } } }); out.appendAssumeCapacity(.{ .ty = var_ty[phi_var.items[j]], .op = .{ .phi = .{ .incoming = edges } } });
}; };
while (i < block_start[b + 1]) : (i += 1) if (live[i]) { while (i < block_start[b + 1]) : (i += 1) if (live[i]) {
var inst = insts[i]; var inst = insts[i];
try operands(true, ma, &inst, &map); try operands(true, ma, &inst, &map);
if (inst.op == .gep) try clampIndex(m, &inst.op.gep); if (inst.op == .gep) try clampIndex(m, &inst.op.gep);
switch (inst.op) {
.br => |*br| {
br.then = new_block[br.then];
if (br.@"else") |*e| e.* = new_block[e.*];
},
.@"switch" => |*sw| {
sw.default = new_block[sw.default];
const cs = try ma.alloc(@typeInfo(@TypeOf(sw.cases)).pointer.child, sw.cases.len);
for (sw.cases, cs) |c, *o| o.* = .{ .val = c.val, .block = new_block[c.block] };
sw.cases = cs;
},
else => {},
}
out.appendAssumeCapacity(inst); out.appendAssumeCapacity(inst);
}; };
} }
f.insts = out; f.insts = out;
f.num_blocks = kept;
}
/// See run. Returns the blocks still reachable.
fn foldConstantBranches(a: Allocator, m: *module.Module, insts: []Inst, block_start: []const u32, repl: []const ?Value, bphis: []const u32, bphi_off: []const u32, incoming: [][]Edge) Allocator.Error![]bool {
const nb = block_start.len - 1;
for (0..nb) |b| {
const term = &insts[block_start[b + 1] - 1];
if (term.op != .br) continue;
const br = term.op.br;
const cond = br.cond orelse continue;
const els = br.@"else" orelse continue;
const c = constInt(m, resolve(repl, cond)) orelse continue;
term.op = .{ .br = .{ .then = if (c != 0) br.then else els } };
}
// Switches on a constant too.
for (0..nb) |b| {
const term = &insts[block_start[b + 1] - 1];
if (term.op != .@"switch") continue;
const sw = term.op.@"switch";
const c = constInt(m, resolve(repl, sw.cond)) orelse continue;
var target = sw.default;
for (sw.cases) |cs| if (constInt(m, cs.val) == c) {
target = cs.block;
};
term.op = .{ .br = .{ .then = target } };
}
const reach = try a.alloc(bool, nb);
@memset(reach, false);
var stack: std.ArrayList(u32) = .empty;
try stack.append(a, 0);
while (stack.pop()) |b| {
if (reach[b]) continue;
reach[b] = true;
switch (insts[block_start[b + 1] - 1].op) {
.br => |br| {
try stack.append(a, br.then);
if (br.@"else") |e| try stack.append(a, e);
},
.@"switch" => |sw| {
try stack.append(a, sw.default);
for (sw.cases) |cs| try stack.append(a, cs.block);
},
else => {},
}
}
const Edges = struct {
insts: []const Inst,
block_start: []const u32,
reach: []const bool,
/// How many edges go from `p` to `t` (a phi has an entry per edge).
fn count(s: @This(), p: u32, t: u32) u32 {
if (!s.reach[p]) return 0;
return switch (s.insts[s.block_start[p + 1] - 1].op) {
.br => |br| @as(u32, @intFromBool(br.then == t)) + @intFromBool(br.@"else" == t),
.@"switch" => |sw| blk: {
var k: u32 = @intFromBool(sw.default == t);
for (sw.cases) |cs| k += @intFromBool(cs.block == t);
break :blk k;
},
else => 0,
};
}
/// Whether entry `x` of `ins` (from `ins[x].block`) is one of the
/// edges there still are.
fn keeps(s: @This(), ins: []const Edge, x: usize, t: u32) bool {
var before: u32 = 0;
for (ins[0..x]) |in| before += @intFromBool(in.block == ins[x].block);
return before < s.count(ins[x].block, t);
}
};
const edges: Edges = .{ .insts = insts, .block_start = block_start, .reach = reach };
for (0..nb) |b| {
const t: u32 = @intCast(b);
const last = block_start[b + 1] - 1;
if (!reach[b]) {
insts[last].op = .@"unreachable";
continue;
}
var i = block_start[b];
while (i < last and insts[i].op == .phi) : (i += 1) {
const old = insts[i].op.phi.incoming;
var keep: usize = 0;
for (0..old.len) |x| keep += @intFromBool(edges.keeps(old, x, t));
if (keep == old.len) continue;
const new = try m.allocator().alloc(Edge, keep);
var k: usize = 0;
for (old, 0..) |in, x| if (edges.keeps(old, x, t)) {
new[k] = in;
k += 1;
};
insts[i].op.phi.incoming = new;
}
for (bphis[bphi_off[b]..bphi_off[b + 1]]) |j| {
// (Kept entries move down; each is checked against those
// before it in the original order.)
const orig = try a.dupe(Edge, incoming[j]);
var k: usize = 0;
for (orig, 0..) |in, x| if (edges.keeps(orig, x, t)) {
incoming[j][k] = in;
k += 1;
};
incoming[j] = incoming[j][0..k];
}
}
return reach;
}
/// See run: rewrites such branches' conditions; true if any changed.
fn foldEmptyBranches(a: Allocator, m: *module.Module, insts: []Inst, block_start: []const u32, reach: []const bool, live: []const bool, repl: []const ?Value, n: u32, bphis: []const u32, bphi_off: []const u32, incoming: []const []Edge) Allocator.Error!bool {
const nb = block_start.len - 1;
var changed = false;
const from_of = try a.alloc(u32, nb);
@memset(from_of, none);
var marked: std.ArrayList(u32) = .empty;
for (0..nb) |b| {
if (!reach[b]) continue;
const term = &insts[block_start[b + 1] - 1];
if (term.op != .br) continue;
const br = term.op.br;
const cond = br.cond orelse continue;
if (cond != .inst) continue;
const f_ = br.@"else" orelse continue;
// Each side: the block it lands in, and the predecessor that
// edge reaches it from.
const Side = struct { land: u32, from: u32 };
// Each side's way on: the blocks it lands in, through empty blocks
// (only an unconditional branch live, and no live phis; other
// branches may enter them too, the way on is the same). The first
// side's marks each block it lands in with the edge it came by;
// the second stops where it lands in a marked one.
var sides: [2]Side = undefined;
var met = false;
marked.clearRetainingCapacity();
for ([2]u32{ br.then, f_ }, 0..) |t0, k| {
var side: Side = .{ .land = t0, .from = @intCast(b) };
var steps: usize = 0;
while (steps <= nb) : (steps += 1) {
if (k == 0) {
if (from_of[side.land] != none) break; // a cycle
from_of[side.land] = side.from;
try marked.append(a, side.land);
} else if (from_of[side.land] != none) {
sides = .{ .{ .land = side.land, .from = from_of[side.land] }, side };
met = true;
break;
}
const t = side.land;
const last = block_start[t + 1] - 1;
if (insts[last].op != .br) break;
// (A branch on a constant goes one way.)
const tb = insts[last].op.br;
const next = if (tb.cond) |c| blk: {
const kc = constInt(m, resolve(repl, c)) orelse break;
break :blk if (kc != 0) tb.then else tb.@"else" orelse tb.then;
} else tb.then;
var empty = true;
for (block_start[t]..last) |i| if (live[i]) {
empty = false;
};
for (bphis[bphi_off[t]..bphi_off[t + 1]]) |j| if (live[n + j]) {
empty = false;
};
if (!empty) break;
side = .{ .land = next, .from = t };
}
}
for (marked.items) |x| from_of[x] = none;
if (!met or sides[0].from == sides[1].from) continue;
const mb = sides[0].land;
// The merge's phis take the same value from both sides.
var same = true;
var i = block_start[mb];
while (i < block_start[mb + 1] and insts[i].op == .phi) : (i += 1) if (live[i]) {
var vals: [2]?Value = .{ null, null };
for (insts[i].op.phi.incoming) |in| for (sides, 0..) |sd, k| if (in.block == sd.from) {
vals[k] = resolve(repl, in.val);
};
if (vals[0] == null or vals[1] == null or !std.meta.eql(vals[0].?, vals[1].?)) same = false;
};
for (bphis[bphi_off[mb]..bphi_off[mb + 1]]) |j| if (live[n + j]) {
var vals: [2]?Value = .{ null, null };
for (incoming[j]) |in| for (sides, 0..) |sd, k| if (in.block == sd.from) {
vals[k] = resolve(repl, in.val);
};
if (vals[0] == null or vals[1] == null or !std.meta.eql(vals[0].?, vals[1].?)) same = false;
};
if (!same) continue;
term.op.br.cond = try m.constInt(1, 1);
changed = true;
}
return changed;
} }
/// An index into an array that folding made a constant out of range (on /// An index into an array that folding made a constant out of range (on
@ -743,7 +979,30 @@ fn simplify(m: *module.Module, f: *const module.Function, repl: []const ?Value,
} }
}; };
switch (inst.op) { switch (inst.op) {
// A phi taking one value on every edge is that value.
.phi => |p| {
if (p.incoming.len == 0) return null;
const first = resolve(repl, p.incoming[0].val);
if (first == .inst and first.inst < n and std.meta.eql(f.insts.items[first.inst].op, inst.op)) return null;
for (p.incoming[1..]) |in| if (!std.meta.eql(resolve(repl, in.val), first)) return null;
return first;
},
.cast => |c| { .cast => |c| {
// Integer widening and narrowing of a constant.
if (c.op == .zext or c.op == .sext or c.op == .trunc) {
const v = resolve(repl, c.val);
const k = constInt(m, v) orelse return null;
const from = S.intWidth(m, typeOf(m, f, v)) orelse return null;
const to = S.intWidth(m, inst.ty) orelse return null;
const p = S.bits(k, from);
const out: u64 = switch (c.op) {
.zext => p,
// (i1 is stored as 0 / 1: true sign-extends to all ones.)
.sext => if (from == 1) (if (p & 1 != 0) ~@as(u64, 0) else 0) else @bitCast(S.stored(p, from)),
else => p,
};
return try m.constant(.{ .ty = inst.ty, .kind = .{ .int = S.stored(S.bits(@bitCast(out), to), to) } });
}
if (c.op != .bitcast) return null; if (c.op != .bitcast) return null;
const x = resolve(repl, c.val); const x = resolve(repl, c.val);
if (x == .inst and x.inst < n) { if (x == .inst and x.inst < n) {
@ -817,9 +1076,35 @@ fn simplify(m: *module.Module, f: *const module.Function, repl: []const ?Value,
return null; return null;
}, },
.cmp => |c| { .cmp => |c| {
if (c.pred < 32 or c.pred > 41) return null; // integer predicates only
const l = resolve(repl, c.lhs); const l = resolve(repl, c.lhs);
const r = resolve(repl, c.rhs); const r = resolve(repl, c.rhs);
if (c.pred <= 15) {
// Floating-point predicates on two constants (ordered:
// false with a NaN; unordered: true).
const x = constFloat(m, l) orelse return null;
const y = constFloat(m, r) orelse return null;
const uno = std.math.isNan(x) or std.math.isNan(y);
const t = switch (c.pred) {
0 => false,
1 => !uno and x == y,
2 => !uno and x > y,
3 => !uno and x >= y,
4 => !uno and x < y,
5 => !uno and x <= y,
6 => !uno and x != y,
7 => !uno,
8 => uno,
9 => uno or x == y,
10 => uno or x > y,
11 => uno or x >= y,
12 => uno or x < y,
13 => uno or x <= y,
14 => uno or x != y,
else => true,
};
return try m.constant(.{ .ty = inst.ty, .kind = .{ .int = @intFromBool(t) } });
}
if (c.pred < 32 or c.pred > 41) return null; // integer predicates
const w = S.intWidth(m, S.ty(m, f, n, phi_var, var_ty, l)) orelse return null; const w = S.intWidth(m, S.ty(m, f, n, phi_var, var_ty, l)) orelse return null;
const x = S.bits(constInt(m, l) orelse return null, w); const x = S.bits(constInt(m, l) orelse return null, w);
const y = S.bits(constInt(m, r) orelse return null, w); const y = S.bits(constInt(m, r) orelse return null, w);
@ -862,6 +1147,71 @@ fn hasEffects(m: *const module.Module, inst: Inst) bool {
}; };
} }
/// Wave and quad operations: declared without readnone (so nothing moves
/// them across control flow), but with no effect besides their result.
/// (Only loop deletion drops them, as dxc's does; dxc's dead code removal
/// keeps them, and with them what they read.)
pub fn isWaveOp(name: []const u8) bool {
return std.mem.startsWith(u8, name, "dx.op.wave") or std.mem.startsWith(u8, name, "dx.op.quad");
}
/// A phi that is one constant once each input is read on its edge: an input
/// that is the condition of the branch the edge leaves by (or its zext or
/// sext) is known there. (`a && b` with `b` false merges `zext a`, on the
/// edge where `a` is false, with `false`; dxc's optimizer folds it.)
fn edgePhi(m: *module.Module, insts: []const Inst, block_start: []const u32, repl: []const ?Value, n: u32, block: u32, inst: Inst) Allocator.Error!?Value {
var same: ?i64 = null;
var known = false;
for (inst.op.phi.incoming) |in| {
const x = resolve(repl, in.val);
var k = constInt(m, x);
if (k == null) {
const term = insts[block_start[in.block + 1] - 1].op;
const br = switch (term) {
.br => |b| b,
else => return null,
};
const cond = resolve(repl, br.cond orelse return null);
const other = br.@"else" orelse return null;
if (br.then == other) return null;
const truth: i64 = if (block == br.then) 1 else if (block == other) 0 else return null;
if (std.meta.eql(x, cond)) {
k = truth;
} else if (x == .inst and x.inst < n and insts[x.inst].op == .cast) {
const c = insts[x.inst].op.cast;
if (!std.meta.eql(resolve(repl, c.val), cond)) return null;
k = switch (c.op) {
.zext => truth,
.sext => -truth,
else => return null,
};
} else return null;
known = true;
}
if (same) |s| {
if (s != k.?) return null;
} else same = k;
}
if (!known) return null;
return try m.constant(.{ .ty = inst.ty, .kind = .{ .int = same orelse return null } });
}
/// A half, float or double constant's value.
fn constFloat(m: *const module.Module, v: Value) ?f64 {
if (v != .constant) return null;
const c = m.constants.items[v.constant];
const b = switch (c.kind) {
.float_bits => |b| b,
else => return null,
};
return switch (m.types.items[c.ty]) {
.half => @floatCast(@as(f16, @bitCast(@as(u16, @truncate(b))))),
.float => @floatCast(@as(f32, @bitCast(@as(u32, @truncate(b))))),
.double => @bitCast(b),
else => null,
};
}
/// `v` with replaced loads and phis followed to their final value. /// `v` with replaced loads and phis followed to their final value.
fn resolve(repl: []const ?Value, v: Value) Value { fn resolve(repl: []const ?Value, v: Value) Value {
var x = v; var x = v;
@ -904,6 +1254,52 @@ fn typeOf(m: *const module.Module, f: *const module.Function, v: Value) TypeId {
/// rejects unused external functions), renumbering the other functions. /// rejects unused external functions), renumbering the other functions.
/// Run last: indices the emitter holds go stale. Returns the new index of /// Run last: indices the emitter holds go stale. Returns the new index of
/// each old function (`none` for dropped ones), or null if none went. /// each old function (`none` for dropped ones), or null if none went.
/// Drops groupshared variables nothing refers to any more (dead code
/// removal can take their last use, and the validator rejects unused
/// internal declarations), renumbering the other globals.
pub fn pruneGlobals(a: Allocator, m: *module.Module) Allocator.Error!void {
const globals = m.globals.items;
const used = try a.alloc(bool, globals.len);
for (globals, used) |g, *u| u.* = g.addr_space != 3;
const Use = struct {
used: []bool,
fn visit(s: *@This(), v: Value, _: Role) Value {
if (v == .global) s.used[v.global] = true;
return v;
}
};
var use: Use = .{ .used = used };
for (m.functions.items) |f| for (f.insts.items) |*inst| try operands(false, a, inst, &use);
for (m.metadata.items) |md| if (md == .value and md.value.val == .global) {
used[md.value.val.global] = true;
};
if (std.mem.indexOfScalar(bool, used, false) == null) return;
const index = try a.alloc(u32, globals.len);
var count: u32 = 0;
for (used, index) |u, *x| {
x.* = if (u) count else none;
if (u) count += 1;
}
const Map = struct {
index: []const u32,
fn visit(s: *@This(), v: Value, _: Role) Value {
return if (v == .global) .{ .global = s.index[v.global] } else v;
}
};
var map: Map = .{ .index = index };
const ma = m.allocator();
for (m.functions.items) |*f| for (f.insts.items) |*inst| try operands(true, ma, inst, &map);
for (m.metadata.items) |*md| if (md.* == .value and md.value.val == .global) {
md.value.val = .{ .global = index[md.value.val.global] };
};
var k: usize = 0;
for (globals, used) |g, u| if (u) {
globals[k] = g;
k += 1;
};
m.globals.shrinkRetainingCapacity(k);
}
pub fn pruneDeclarations(a: Allocator, m: *module.Module) Allocator.Error!?[]const u32 { pub fn pruneDeclarations(a: Allocator, m: *module.Module) Allocator.Error!?[]const u32 {
const funcs = m.functions.items; const funcs = m.functions.items;
const used = try a.alloc(bool, funcs.len); const used = try a.alloc(bool, funcs.len);

372
src/dxil/sccp.zig Normal file
View File

@ -0,0 +1,372 @@
//! Sparse conditional constant propagation (Wegman and Zadeck) on a DXIL
//! function in SSA form, over integer values: optimistic, so values carried
//! round a loop that only ever hold one constant are found, and code only
//! reachable through branches that never go that way is left out. (A flag
//! that starts false and is passed back unchanged through a loop, or a loop
//! whose first test already fails, as dxc's optimizer finds them.)
//!
//! The results go into the function as constants: the uses of values found
//! constant, and the conditions of branches found to go one way; promotion
//! then drops what that leaves dead or unreachable.
const std = @import("std");
const Allocator = std.mem.Allocator;
const module = @import("module.zig");
const unroll = @import("unroll.zig");
const Value = module.Value;
const Inst = module.Inst;
const none = std.math.maxInt(u32);
/// Not yet known (optimistically anything), one constant, or varying.
const Lat = union(enum) {
top,
k: i64,
bot,
fn meet(x: Lat, y: Lat) Lat {
return switch (x) {
.top => y,
.bot => .bot,
.k => |a| switch (y) {
.top => x,
.bot => .bot,
.k => |b| if (a == b) x else .bot,
},
};
}
fn eql(x: Lat, y: Lat) bool {
return std.meta.eql(x, y);
}
};
fn intWidth(m: *const module.Module, ty: module.TypeId) ?u32 {
return switch (m.types.items[ty]) {
.int => |w| w,
else => null,
};
}
fn bitsOf(v: i64, w: u32) u64 {
const u: u64 = @bitCast(v);
return if (w >= 64) u else u & ((@as(u64, 1) << @intCast(w)) - 1);
}
/// A `w`-bit pattern as constants hold it: 0 / 1 for i1, sign-extended
/// above.
fn stored(p: u64, w: u32) i64 {
if (w == 1) return @intCast(p & 1);
if (w >= 64) return @bitCast(p);
const sh: u6 = @intCast(64 - w);
return @as(i64, @bitCast(p << sh)) >> sh;
}
fn typeOf(m: *const module.Module, f: *const module.Function, v: Value) ?module.TypeId {
return switch (v) {
.inst => |i| f.insts.items[i].ty,
.constant => |c| m.constants.items[c].ty,
.arg => |k| m.types.items[f.ty].function.params[k],
else => null,
};
}
fn isTerminator(inst: Inst) bool {
return switch (inst.op) {
.ret, .br, .@"switch", .@"unreachable" => true,
else => false,
};
}
/// A terminator's successor blocks.
const Succs = struct {
br: [2]u32 = undefined,
sw: ?@FieldType(@FieldType(Inst, "op"), "switch") = null,
len: usize = 0,
fn get(s: Succs, k: usize) u32 {
if (s.sw) |sw| return if (k == 0) sw.default else sw.cases[k - 1].block;
return s.br[k];
}
};
fn successors(term: Inst) Succs {
return switch (term.op) {
.br => |br| if (br.@"else") |e| .{ .br = .{ br.then, e }, .len = 2 } else .{ .br = .{ br.then, 0 }, .len = 1 },
.@"switch" => |sw| .{ .sw = sw, .len = 1 + sw.cases.len },
else => .{},
};
}
/// Runs the propagation on `func`; true if it changed anything.
pub fn run(a: Allocator, m: *module.Module, func: u32) Allocator.Error!bool {
const f = &m.functions.items[func];
const insts = f.insts.items;
const n: u32 = @intCast(insts.len);
const nb = f.num_blocks;
if (n == 0 or nb == 0) return false;
const block_start = try a.alloc(u32, nb + 1);
const block_of = try a.alloc(u32, n);
{
var b: u32 = 0;
block_start[0] = 0;
for (insts, 0..) |inst, i| {
if (b >= nb) return false;
block_of[i] = b;
if (isTerminator(inst)) {
b += 1;
block_start[b] = @intCast(i + 1);
}
}
if (b != nb) return false;
}
const lat = try a.alloc(Lat, n);
@memset(lat, .top);
const exec = try a.alloc(bool, nb);
@memset(exec, false);
exec[0] = true;
var edges: std.AutoHashMapUnmanaged(u64, void) = .empty;
const S = struct {
fn key(from: u32, to: u32) u64 {
return @as(u64, from) << 32 | to;
}
};
const Eval = struct {
m: *const module.Module,
f: *const module.Function,
lat: []const Lat,
fn of(s: @This(), v: Value) Lat {
return switch (v) {
.inst => |i| s.lat[i],
.constant => |c| switch (s.m.constants.items[c].kind) {
.int => |x| .{ .k = x },
else => .bot,
},
else => .bot,
};
}
fn inst(s: @This(), i: u32) Lat {
const in = s.f.insts.items[i];
const w = intWidth(s.m, in.ty) orelse return .bot;
switch (in.op) {
.binop => |b| {
const l = s.of(b.lhs);
const r = s.of(b.rhs);
if (l == .bot or r == .bot) {
// (Varying, but a zero still decides these.)
const z = if (l == .k and l.k == 0) true else if (r == .k and r.k == 0) true else false;
if (z and (b.op == .@"and" or b.op == .mul)) return .{ .k = 0 };
return .bot;
}
if (l == .top or r == .top) return .top;
const x = bitsOf(l.k, w);
const y = bitsOf(r.k, w);
const sx = stored(x, w);
const sy = stored(y, w);
const p: u64 = switch (b.op) {
.add => x +% y,
.sub => x -% y,
.mul => x *% y,
.@"and" => x & y,
.@"or" => x | y,
.xor => x ^ y,
.shl => if (y < w) x << @intCast(y) else return .bot,
.lshr => if (y < w) x >> @intCast(y) else return .bot,
.ashr => if (y < w) @bitCast(sx >> @intCast(y)) else return .bot,
.udiv => if (y != 0) x / y else return .bot,
.urem => if (y != 0) x % y else return .bot,
.sdiv => if (sy != 0 and !(sy == -1 and sx == std.math.minInt(i64))) @bitCast(@divTrunc(sx, sy)) else return .bot,
.srem => if (sy != 0 and sy != -1) @bitCast(@rem(sx, sy)) else return .bot,
};
return .{ .k = stored(bitsOf(@bitCast(p), w), w) };
},
.cast => |c| {
if (c.op != .zext and c.op != .sext and c.op != .trunc) return .bot;
const from = intWidth(s.m, typeOf(s.m, s.f, c.val) orelse return .bot) orelse return .bot;
const v = s.of(c.val);
if (v != .k) return v;
const x = bitsOf(v.k, from);
const out: u64 = switch (c.op) {
.sext => if (from == 1) (if (x & 1 != 0) ~@as(u64, 0) else 0) else @bitCast(stored(x, from)),
else => x,
};
return .{ .k = stored(bitsOf(@bitCast(out), w), w) };
},
.cmp => |c| {
if (c.pred < 32 or c.pred > 41) return .bot;
const cw = intWidth(s.m, typeOf(s.m, s.f, c.lhs) orelse return .bot) orelse return .bot;
const l = s.of(c.lhs);
const r = s.of(c.rhs);
if (l == .bot or r == .bot) return .bot;
if (l == .top or r == .top) return .top;
const x = bitsOf(l.k, cw);
const y = bitsOf(r.k, cw);
const sx = stored(x, cw);
const sy = stored(y, cw);
const t = switch (c.pred) {
32 => x == y,
33 => x != y,
34 => x > y,
35 => x >= y,
36 => x < y,
37 => x <= y,
38 => sx > sy,
39 => sx >= sy,
40 => sx < sy,
else => sx <= sy,
};
return .{ .k = @intFromBool(t) };
},
.select => |sel| {
const c = s.of(sel.cond);
return switch (c) {
.top => .top,
.k => |x| s.of(if (x & 1 != 0) sel.t else sel.f),
.bot => s.of(sel.t).meet(s.of(sel.f)),
};
},
else => return .bot,
}
}
};
const ev: Eval = .{ .m = m, .f = f, .lat = lat };
// Blocks in reverse postorder: definitions before uses except round
// loops, so the fixed point takes a few passes (the lattice is three
// levels deep).
var rpo: std.ArrayList(u32) = .empty;
{
var post: std.ArrayList(u32) = .empty;
const seen = try a.alloc(bool, nb);
@memset(seen, false);
const Fr = struct { b: u32, next: u32 };
var stack: std.ArrayList(Fr) = .empty;
try stack.append(a, .{ .b = 0, .next = 0 });
seen[0] = true;
while (stack.items.len > 0) {
const top = &stack.items[stack.items.len - 1];
const succs = successors(insts[block_start[top.b + 1] - 1]);
if (top.next < succs.len) {
const t = succs.get(top.next);
top.next += 1;
if (!seen[t]) {
seen[t] = true;
try stack.append(a, .{ .b = t, .next = 0 });
}
} else {
try post.append(a, top.b);
_ = stack.pop();
}
}
var k = post.items.len;
while (k > 0) {
k -= 1;
try rpo.append(a, post.items[k]);
}
}
var changed = true;
var rounds: u32 = 0;
while (changed) : (rounds += 1) {
if (rounds > 1000) return false;
changed = false;
for (rpo.items) |b| {
if (!exec[b]) continue;
for (block_start[b]..block_start[b + 1]) |ii| {
const i: u32 = @intCast(ii);
const inst = insts[i];
var new: Lat = undefined;
switch (inst.op) {
.phi => |p| {
if (intWidth(m, inst.ty) == null) {
new = .bot;
} else {
new = .top;
for (p.incoming) |in| {
if (!edges.contains(S.key(in.block, b))) continue;
new = new.meet(ev.of(in.val));
}
}
},
.br => |br| {
const targets: [2]?u32 = if (br.cond) |c| switch (ev.of(c)) {
.top => .{ null, null },
.k => |x| .{ if (x & 1 != 0) br.then else br.@"else", null },
.bot => .{ br.then, br.@"else" },
} else .{ br.then, null };
for (targets) |t| if (t) |tb| {
const gop = try edges.getOrPut(a, S.key(b, tb));
if (!gop.found_existing) {
exec[tb] = true;
changed = true;
}
};
continue;
},
.@"switch" => |sw| {
const c = ev.of(sw.cond);
if (c == .top) continue;
var taken: ?u32 = null;
if (c == .k) {
taken = sw.default;
for (sw.cases) |cs| if (ev.of(cs.val) == .k and ev.of(cs.val).k == c.k) {
taken = cs.block;
};
}
var list: std.ArrayList(u32) = .empty;
if (taken) |t| try list.append(a, t) else {
try list.append(a, sw.default);
for (sw.cases) |cs| try list.append(a, cs.block);
}
for (list.items) |tb| {
const gop = try edges.getOrPut(a, S.key(b, tb));
if (!gop.found_existing) {
exec[tb] = true;
changed = true;
}
}
continue;
},
else => new = ev.inst(i),
}
const merged = lat[i].meet(new);
if (!merged.eql(lat[i])) {
lat[i] = merged;
changed = true;
}
}
}
}
// Constants into the function: the uses of integer values found
// constant, and branch conditions.
const repl = try a.alloc(?Value, n);
@memset(repl, null);
var any = false;
for (insts, 0..) |inst, i| {
if (!exec[block_of[i]]) continue;
if (lat[i] != .k) continue;
if (intWidth(m, inst.ty) == null) continue;
repl[i] = try m.constant(.{ .ty = inst.ty, .kind = .{ .int = lat[i].k } });
}
const Mapper = struct {
repl: []const ?Value,
any: *bool,
pub fn visit(c: *@This(), v: Value, _: anytype) Value {
if (v == .inst and v.inst < c.repl.len) if (c.repl[v.inst]) |r| {
c.any.* = true;
return r;
};
return v;
}
};
var mapper: Mapper = .{ .repl = repl, .any = &any };
const ma = m.allocator();
for (insts) |*inst| try unroll.operandsMap(ma, inst, &mapper);
return any;
}

752
src/dxil/unroll.zig Normal file
View File

@ -0,0 +1,752 @@
//! Full unrolling of loops with a constant trip count, on a DXIL function
//! after promotion to SSA values (as dxc's loop unrolling runs after SROA):
//! by then a loop's bound often comes from struct fields and arguments
//! only inlining made constant. Unrolled, indices into local arrays become
//! constants (so promotion can take the arrays out of memory) and code
//! guarded by the counter folds away, as it does for dxc.
//!
//! A loop qualifies when it is innermost, has one block leaving it (a
//! conditional branch out of the loop, to one block), and that branch's
//! condition is decided by header phis that start constant and step by
//! values computed from themselves. Its blocks are copied once per
//! iteration, and once more up to the exit, after the function's last
//! block; the original blocks are left unreachable for promotion to drop.
const std = @import("std");
const Allocator = std.mem.Allocator;
const module = @import("module.zig");
const promote = @import("promote.zig");
const Value = module.Value;
const Inst = module.Inst;
const Edge = @typeInfo(@FieldType(@FieldType(@FieldType(Inst, "op"), "phi"), "incoming")).pointer.child;
const none = std.math.maxInt(u32);
/// Most iterations unrolled, most instructions one loop may grow to
/// unrolled (small loops only, as dxc's full unrolling of loops without
/// [unroll]: larger ones cost compile time and code size for little), and
/// most one function may grow by.
const max_trips = 256;
const max_loop_growth = 300;
const max_growth = 65536;
/// Unrolls the qualifying loops of `func`, innermost first; true if any.
pub fn run(a: Allocator, m: *module.Module, func: u32) Allocator.Error!bool {
var budget: usize = max_growth;
var tried: std.AutoHashMapUnmanaged(u32, void) = .empty;
var any = false;
while (try unrollOne(a, m, func, &budget, &tried)) any = true;
return any;
}
const Cfg = struct {
nb: u32,
block_start: []u32,
succs: [][]u32,
preds: [][]u32,
idom: []u32,
fn dominates(c: *const Cfg, d: u32, b: u32) bool {
var x = b;
while (true) {
if (x == d) return true;
const p = c.idom[x];
if (p == none or p == x) return false;
x = p;
}
}
};
fn isTerminator(inst: Inst) bool {
return switch (inst.op) {
.ret, .br, .@"switch", .@"unreachable" => true,
else => false,
};
}
fn buildCfg(a: Allocator, f: *const module.Function) Allocator.Error!?Cfg {
const nb = f.num_blocks;
const insts = f.insts.items;
const block_start = try a.alloc(u32, nb + 1);
var b: u32 = 0;
block_start[0] = 0;
for (insts, 0..) |inst, i| {
if (b >= nb) return null;
if (isTerminator(inst)) {
b += 1;
block_start[b] = @intCast(i + 1);
}
}
if (b != nb) return null;
const succs = try a.alloc([]u32, nb);
var pred_lists = try a.alloc(std.ArrayList(u32), nb);
for (pred_lists) |*p| p.* = .empty;
for (0..nb) |bi| {
var s: std.ArrayList(u32) = .empty;
switch (insts[block_start[bi + 1] - 1].op) {
.br => |br| {
try s.append(a, br.then);
if (br.@"else") |e| if (e != br.then) try s.append(a, e);
},
.@"switch" => |sw| {
try s.append(a, sw.default);
for (sw.cases) |c| if (std.mem.indexOfScalar(u32, s.items, c.block) == null) try s.append(a, c.block);
},
else => {},
}
succs[bi] = s.items;
for (s.items) |t| try pred_lists[t].append(a, @intCast(bi));
}
const preds = try a.alloc([]u32, nb);
for (preds, pred_lists) |*p, l| p.* = l.items;
// Reverse postorder, then Cooper, Harvey and Kennedy's dominators.
const order = try a.alloc(u32, nb);
@memset(order, none);
var rpo: std.ArrayList(u32) = .empty;
{
var post: std.ArrayList(u32) = .empty;
const seen = try a.alloc(bool, nb);
@memset(seen, false);
const Fr = struct { b: u32, next: u32 };
var stack: std.ArrayList(Fr) = .empty;
try stack.append(a, .{ .b = 0, .next = 0 });
seen[0] = true;
while (stack.items.len > 0) {
const top = &stack.items[stack.items.len - 1];
if (top.next < succs[top.b].len) {
const s = succs[top.b][top.next];
top.next += 1;
if (!seen[s]) {
seen[s] = true;
try stack.append(a, .{ .b = s, .next = 0 });
}
} else {
try post.append(a, top.b);
_ = stack.pop();
}
}
var k = post.items.len;
while (k > 0) {
k -= 1;
order[post.items[k]] = @intCast(rpo.items.len);
try rpo.append(a, post.items[k]);
}
}
const idom = try a.alloc(u32, nb);
@memset(idom, none);
idom[0] = 0;
var changed = true;
while (changed) {
changed = false;
for (rpo.items[1..]) |bb| {
var new: u32 = none;
for (preds[bb]) |p| {
if (idom[p] == none) continue;
if (new == none) {
new = p;
continue;
}
var x = p;
var y = new;
while (x != y) {
while (order[x] > order[y]) x = idom[x];
while (order[y] > order[x]) y = idom[y];
}
new = x;
}
if (new != none and idom[bb] != new) {
idom[bb] = new;
changed = true;
}
}
}
return .{ .nb = nb, .block_start = block_start, .succs = succs, .preds = preds, .idom = idom };
}
fn constInt(m: *const module.Module, v: Value) ?i64 {
if (v != .constant) return null;
return switch (m.constants.items[v.constant].kind) {
.int => |x| x,
else => null,
};
}
fn intWidth(m: *const module.Module, ty: module.TypeId) ?u32 {
return switch (m.types.items[ty]) {
.int => |w| w,
else => null,
};
}
fn bitsOf(v: i64, w: u32) u64 {
const u: u64 = @bitCast(v);
return if (w >= 64) u else u & ((@as(u64, 1) << @intCast(w)) - 1);
}
/// A `w`-bit pattern as constants hold it: 0 / 1 for i1, sign-extended
/// above.
fn stored(p: u64, w: u32) i64 {
if (w == 1) return @intCast(p & 1);
if (w >= 64) return @bitCast(p);
const sh: u6 = @intCast(64 - w);
return @as(i64, @bitCast(p << sh)) >> sh;
}
/// Integer value of `v` given the header phis' values in `state` (index:
/// instruction), or null.
fn eval(m: *const module.Module, f: *const module.Function, state: *const std.AutoHashMapUnmanaged(u32, i64), v: Value, depth: u32) ?i64 {
if (depth > 64) return null;
if (constInt(m, v)) |c| return c;
if (v != .inst) return null;
if (state.get(v.inst)) |s| return s;
const inst = f.insts.items[v.inst];
const w = intWidth(m, inst.ty) orelse return null;
switch (inst.op) {
.binop => |b| {
const x = bitsOf(eval(m, f, state, b.lhs, depth + 1) orelse return null, w);
const y = bitsOf(eval(m, f, state, b.rhs, depth + 1) orelse return null, w);
const sx = stored(x, w);
const sy = stored(y, w);
const p: u64 = switch (b.op) {
.add => x +% y,
.sub => x -% y,
.mul => x *% y,
.@"and" => x & y,
.@"or" => x | y,
.xor => x ^ y,
.shl => if (y < w) x << @intCast(y) else return null,
.lshr => if (y < w) x >> @intCast(y) else return null,
.ashr => if (y < w) @bitCast(sx >> @intCast(y)) else return null,
.udiv => if (y != 0) x / y else return null,
.urem => if (y != 0) x % y else return null,
.sdiv => if (sy != 0 and !(sy == -1 and sx == std.math.minInt(i64))) @bitCast(@divTrunc(sx, sy)) else return null,
.srem => if (sy != 0 and sy != -1) @bitCast(@rem(sx, sy)) else return null,
};
return stored(bitsOf(@bitCast(p), w), w);
},
.cast => |c| {
const from = intWidth(m, typeOf(m, f, c.val) orelse return null) orelse return null;
const x = bitsOf(eval(m, f, state, c.val, depth + 1) orelse return null, from);
const out: u64 = switch (c.op) {
.zext, .trunc => x,
.sext => if (from == 1) (if (x & 1 != 0) ~@as(u64, 0) else 0) else @bitCast(stored(x, from)),
else => return null,
};
return stored(bitsOf(@bitCast(out), w), w);
},
.cmp => |c| {
if (c.pred < 32 or c.pred > 41) return null;
const cw = intWidth(m, typeOf(m, f, c.lhs) orelse return null) orelse return null;
const x = bitsOf(eval(m, f, state, c.lhs, depth + 1) orelse return null, cw);
const y = bitsOf(eval(m, f, state, c.rhs, depth + 1) orelse return null, cw);
const sx = stored(x, cw);
const sy = stored(y, cw);
const t = switch (c.pred) {
32 => x == y,
33 => x != y,
34 => x > y,
35 => x >= y,
36 => x < y,
37 => x <= y,
38 => sx > sy,
39 => sx >= sy,
40 => sx < sy,
else => sx <= sy,
};
return @intFromBool(t);
},
.select => |s| {
const c = eval(m, f, state, s.cond, depth + 1) orelse return null;
return eval(m, f, state, if (c & 1 != 0) s.t else s.f, depth + 1);
},
else => return null,
}
}
fn typeOf(m: *const module.Module, f: *const module.Function, v: Value) ?module.TypeId {
return switch (v) {
.inst => |i| f.insts.items[i].ty,
.constant => |c| m.constants.items[c].ty,
.arg => |k| m.types.items[f.ty].function.params[k],
else => null,
};
}
fn unrollOne(a: Allocator, m: *module.Module, func: u32, budget: *usize, tried: *std.AutoHashMapUnmanaged(u32, void)) Allocator.Error!bool {
const f = &m.functions.items[func];
const cfg = (try buildCfg(a, f)) orelse return false;
const nb = cfg.nb;
const insts = f.insts.items;
// Loops: headers with back edges (from blocks they dominate), and
// their blocks.
const Loop = struct { h: u32, body: []bool, latches: []u32 };
var loops: std.ArrayList(Loop) = .empty;
for (0..nb) |hb| {
const h: u32 = @intCast(hb);
if (cfg.idom[h] == none) continue;
var latches: std.ArrayList(u32) = .empty;
for (cfg.preds[h]) |p| if (cfg.idom[p] != none and cfg.dominates(h, p)) try latches.append(a, p);
if (latches.items.len == 0) continue;
const body = try a.alloc(bool, nb);
@memset(body, false);
body[h] = true;
var stack: std.ArrayList(u32) = .empty;
try stack.appendSlice(a, latches.items);
while (stack.pop()) |x| {
if (body[x]) continue;
body[x] = true;
for (cfg.preds[x]) |p| if (cfg.idom[p] != none) try stack.append(a, p);
}
try loops.append(a, .{ .h = h, .body = body, .latches = latches.items });
}
// Loops that do nothing (as dxc's loop deletion removes them): no
// instruction with an effect, one block they leave to, and nothing
// after them reading their values. Their preheader goes straight to
// that block; their blocks are left unreachable for promotion to drop.
// (Nested ones too: an outer loop whose inner loops do nothing.)
const loop_inst = try a.alloc(bool, insts.len);
dead: for (loops.items) |lp| {
var exit: u32 = none;
for (0..nb) |bb| {
if (!lp.body[bb]) continue;
for (cfg.block_start[bb]..cfg.block_start[bb + 1]) |i| switch (insts[i].op) {
.br, .@"switch" => {},
.ret, .@"unreachable", .store, .atomicrmw, .cmpxchg => continue :dead,
.call => |c| switch (m.functions.items[c.callee].attrs) {
.nounwind_readnone, .nounwind_readonly => {},
else => if (!promote.isWaveOp(m.functions.items[c.callee].name)) continue :dead,
},
else => {},
};
for (cfg.succs[bb]) |s| if (!lp.body[s]) {
if (exit != none and exit != s) continue :dead;
exit = s;
};
}
if (exit == none) continue;
var pre: u32 = none;
for (cfg.preds[lp.h]) |p| if (!lp.body[p]) {
if (pre != none) continue :dead;
pre = p;
};
if (pre == none) continue;
const pterm = &insts[cfg.block_start[pre + 1] - 1];
if (pterm.op != .br) continue;
if (pterm.op.br.then == exit or pterm.op.br.@"else" == exit) continue;
for (0..nb) |bb| for (cfg.block_start[bb]..cfg.block_start[bb + 1]) |i| {
loop_inst[i] = lp.body[bb];
};
// The exit's phis: one value from the loop, from before it.
const phi_end = blk: {
var i = cfg.block_start[exit];
while (insts[i].op == .phi) i += 1;
break :blk i;
};
const from_loop = try a.alloc(?Value, phi_end - cfg.block_start[exit]);
for (cfg.block_start[exit]..phi_end, from_loop) |i, *fl| {
fl.* = null;
for (insts[i].op.phi.incoming) |in| if (lp.body[in.block]) {
if (in.val == .inst and loop_inst[in.val.inst]) continue :dead;
if (fl.* != null and !std.meta.eql(fl.*.?, in.val)) continue :dead;
fl.* = in.val;
};
}
// Nothing else outside reads the loop's values.
const Check = struct {
loop_inst: []const bool,
used: bool = false,
pub fn visit(c: *@This(), v: Value, _: anytype) Value {
if (v == .inst and v.inst < c.loop_inst.len and c.loop_inst[v.inst]) c.used = true;
return v;
}
};
var check: Check = .{ .loop_inst = loop_inst };
for (0..nb) |bb| {
if (lp.body[bb]) continue;
for (cfg.block_start[bb]..cfg.block_start[bb + 1]) |i| {
if (bb == exit and i < phi_end) continue;
var copy = insts[i];
try operandsMap(a, &copy, &check);
}
}
if (check.used) continue;
const ma = m.allocator();
for (cfg.block_start[exit]..phi_end, from_loop) |i, fl| {
var edges: std.ArrayList(Edge) = .empty;
for (insts[i].op.phi.incoming) |in| if (!lp.body[in.block]) try edges.append(ma, in);
if (fl) |v| try edges.append(ma, .{ .val = v, .block = pre });
insts[i].op.phi.incoming = edges.items;
}
if (pterm.op.br.then == lp.h) pterm.op.br.then = exit;
if (pterm.op.br.@"else") |*e| if (e.* == lp.h) {
e.* = exit;
};
for (0..nb) |bb| if (lp.body[bb]) {
insts[cfg.block_start[bb + 1] - 1].op = .@"unreachable";
};
return true;
}
candidates: for (loops.items) |lp| {
const h = lp.h;
if (tried.contains(h)) continue;
// Innermost: no other loop's header inside.
for (loops.items) |other| if (other.h != h and lp.body[other.h]) continue :candidates;
try tried.put(a, h, {});
// One way out: a conditional branch from one block, to one block.
var exiting: u32 = none;
var exit: u32 = none;
var size: usize = 0;
var body_blocks: std.ArrayList(u32) = .empty;
for (0..nb) |bb| {
if (!lp.body[bb]) continue;
try body_blocks.append(a, @intCast(bb));
size += cfg.block_start[bb + 1] - cfg.block_start[bb];
const term = insts[cfg.block_start[bb + 1] - 1].op;
if (term == .@"switch") {
for (cfg.succs[bb]) |s| if (!lp.body[s]) continue :candidates;
}
for (cfg.succs[bb]) |s| if (!lp.body[s]) {
if (exiting != none) continue :candidates;
exiting = @intCast(bb);
exit = s;
};
}
if (exiting == none) continue;
const xterm = insts[cfg.block_start[exiting + 1] - 1].op;
if (xterm != .br or xterm.br.@"else" == null) continue;
const stay = if (xterm.br.then == exit) xterm.br.@"else".? else xterm.br.then;
if (!lp.body[stay] or stay == exit) continue;
for (lp.latches) |l| if (!cfg.dominates(exiting, l)) continue :candidates;
// One way in.
var pre: u32 = none;
for (cfg.preds[h]) |p| if (!lp.body[p]) {
if (pre != none) continue :candidates;
pre = p;
};
if (pre == none) continue;
// The header's phis: the integer ones whose values can be followed.
var phis: std.ArrayList(u32) = .empty;
{
var i = cfg.block_start[h];
while (insts[i].op == .phi) : (i += 1) try phis.append(a, i);
}
var state: std.AutoHashMapUnmanaged(u32, i64) = .empty;
for (phis.items) |pi| {
if (intWidth(m, insts[pi].ty) == null) continue;
for (insts[pi].op.phi.incoming) |in| if (in.block == pre) {
if (constInt(m, in.val)) |c| try state.put(a, pi, c);
};
}
const xcond = xterm.br.cond.?;
const stay_on: i64 = if (xterm.br.then == stay) 1 else 0;
var states: std.ArrayList(std.AutoHashMapUnmanaged(u32, i64)) = .empty;
while (true) {
const c = eval(m, f, &state, xcond, 0) orelse continue :candidates;
if ((c & 1) != stay_on) break;
if (states.items.len >= max_trips) continue :candidates;
try states.append(a, try state.clone(a));
// Next values: what every latch passes back (the same).
var next: std.AutoHashMapUnmanaged(u32, i64) = .empty;
for (phis.items) |pi| {
if (!state.contains(pi)) continue;
var val: ?i64 = null;
var ok = true;
for (insts[pi].op.phi.incoming) |in| {
if (in.block == pre) continue;
const v = eval(m, f, &state, in.val, 0) orelse {
ok = false;
break;
};
if (val != null and val.? != v) ok = false;
val = v;
}
if (ok) if (val) |v| try next.put(a, pi, v);
}
state = next;
}
const trips = states.items.len;
const growth = (trips + 1) * size;
if (growth > max_loop_growth or growth > budget.*) continue;
budget.* -= growth;
try states.append(a, state); // the last pass, up to the exit
// Copies: block `body_blocks[j]` of copy `k` is block
// `nb + k * nbody + j`.
const nbody: u32 = @intCast(body_blocks.items.len);
const index_in = try a.alloc(u32, nb);
@memset(index_in, none);
for (body_blocks.items, 0..) |bb, j| index_in[bb] = @intCast(j);
const n0: u32 = @intCast(insts.len);
const copies: u32 = @intCast(trips + 1);
// Value maps per copy (original instruction -> value).
const maps = try a.alloc(std.AutoHashMapUnmanaged(u32, Value), copies);
for (maps) |*mp| mp.* = .empty;
const S = struct {
fn block(nb_: u32, nbody_: u32, idx: []const u32, k: u32, b: u32) u32 {
return nb_ + k * nbody_ + idx[b];
}
};
var out: std.ArrayList(Inst) = .empty;
const ma = m.allocator();
// New instruction indices come after the existing ones.
var next_index: u32 = n0;
// First pass: give every copied instruction its index (phis of
// later copies refer back, latch values refer forward to the next
// copy's header).
const new_index = try a.alloc([]u32, copies);
for (0..copies) |k| {
new_index[k] = try a.alloc(u32, n0);
@memset(new_index[k], none);
for (body_blocks.items) |bb| {
var i = cfg.block_start[bb];
while (i < cfg.block_start[bb + 1]) : (i += 1) {
new_index[k][i] = next_index;
next_index += 1;
}
}
}
// Header phis: a constant where followed, else the value from the
// copy before (or from the preheader).
for (0..copies) |k| {
for (phis.items) |pi| {
if (states.items[k].get(pi)) |c| {
try maps[k].put(a, pi, try m.constant(.{ .ty = insts[pi].ty, .kind = .{ .int = c } }));
continue;
}
if (k == 0) {
for (insts[pi].op.phi.incoming) |in| if (in.block == pre) try maps[0].put(a, pi, in.val);
}
}
}
const Mapper = struct {
maps: []std.AutoHashMapUnmanaged(u32, Value),
new_index: [][]u32,
k: u32,
fn val(c: @This(), v: Value) Value {
if (v != .inst) return v;
if (c.maps[c.k].get(v.inst)) |x| return x;
if (v.inst < c.new_index[c.k].len and c.new_index[c.k][v.inst] != none) return .{ .inst = c.new_index[c.k][v.inst] };
return v;
}
fn visit(c: *@This(), v: Value, _: anytype) Value {
return c.val(v);
}
};
for (0..copies) |kk| {
const k: u32 = @intCast(kk);
for (body_blocks.items) |bb| {
var i = cfg.block_start[bb];
while (i < cfg.block_start[bb + 1]) : (i += 1) {
var inst = insts[i];
var mapper: Mapper = .{ .maps = maps, .new_index = new_index, .k = k };
if (bb == h and inst.op == .phi) {
if (maps[k].get(i)) |v| {
// Folded away: a phi of that value on every
// edge keeps the numbering (promotion drops it).
var edges: std.ArrayList(Edge) = .empty;
if (k == 0) {
try edges.append(ma, .{ .val = v, .block = pre });
} else for (lp.latches) |l| try edges.append(ma, .{ .val = v, .block = S.block(nb, nbody, index_in, k - 1, l) });
try out.append(ma, .{ .ty = inst.ty, .op = .{ .phi = .{ .incoming = edges.items } } });
continue;
}
// From the latches of the copy before.
var edges: std.ArrayList(Edge) = .empty;
for (inst.op.phi.incoming) |in| {
if (in.block == pre or k == 0) continue;
const prev: Mapper = .{ .maps = maps, .new_index = new_index, .k = k - 1 };
try edges.append(ma, .{ .val = prev.val(in.val), .block = S.block(nb, nbody, index_in, k - 1, in.block) });
}
if (k == 0) {
// (Not followed and no preheader value mapped:
// the preheader's incoming.)
for (inst.op.phi.incoming) |in| if (in.block == pre) try edges.append(ma, .{ .val = in.val, .block = pre });
}
try out.append(ma, .{ .ty = inst.ty, .op = .{ .phi = .{ .incoming = edges.items } } });
continue;
}
if (inst.op == .phi) {
const edges = try ma.alloc(Edge, inst.op.phi.incoming.len);
for (inst.op.phi.incoming, edges) |in, *e| e.* = .{ .val = mapper.val(in.val), .block = if (index_in[in.block] != none) S.block(nb, nbody, index_in, k, in.block) else in.block };
inst.op = .{ .phi = .{ .incoming = edges } };
try out.append(ma, inst);
continue;
}
try operandsMap(ma, &inst, &mapper);
// Branches: within the copy; back to the header: the
// next copy; out of the exiting block: per copy.
switch (inst.op) {
.br => |*br| {
if (bb == exiting) {
const target = if (k + 1 < copies) stay else exit;
const tb = if (target == exit) exit else S.block(nb, nbody, index_in, k, target);
br.* = .{ .then = tb };
} else {
br.then = mapBlock(br.then, h, k, copies, nb, nbody, index_in);
if (br.@"else") |*e| e.* = mapBlock(e.*, h, k, copies, nb, nbody, index_in);
}
},
.@"switch" => |*sw| {
sw.default = mapBlock(sw.default, h, k, copies, nb, nbody, index_in);
const cs = try ma.alloc(@typeInfo(@TypeOf(sw.cases)).pointer.child, sw.cases.len);
for (sw.cases, cs) |c, *o| o.* = .{ .val = c.val, .block = mapBlock(c.block, h, k, copies, nb, nbody, index_in) };
sw.cases = cs;
},
else => {},
}
// Integer values the counter decides: constants.
if (inst.op == .binop or inst.op == .cast or inst.op == .cmp or inst.op == .select) {
if (eval(m, f, &states.items[k], .{ .inst = i }, 0)) |c| {
if (intWidth(m, inst.ty) != null) try maps[k].put(a, i, try m.constant(.{ .ty = inst.ty, .kind = .{ .int = c } }));
}
}
try out.append(ma, inst);
}
}
}
// The preheader enters the first copy; the exit's phis and the
// code after the loop see the last copy's values.
const last: Mapper = .{ .maps = maps, .new_index = new_index, .k = copies - 1 };
const in_body = try a.alloc(bool, n0);
for (0..nb) |bb| for (cfg.block_start[bb]..cfg.block_start[bb + 1]) |i| {
in_body[i] = lp.body[bb];
};
const Outside = struct {
last: Mapper,
in_body: []const bool,
fn visit(c: *@This(), v: Value, _: anytype) Value {
if (v == .inst and v.inst < c.in_body.len and c.in_body[v.inst]) return c.last.val(v);
return v;
}
};
var outside: Outside = .{ .last = last, .in_body = in_body };
for (0..nb) |bb| {
if (lp.body[bb]) {
// The originals: unreachable now.
insts[cfg.block_start[bb + 1] - 1].op = .@"unreachable";
continue;
}
for (cfg.block_start[bb]..cfg.block_start[bb + 1]) |i| {
var inst = &insts[i];
if (inst.op == .phi) {
const edges = try ma.alloc(Edge, inst.op.phi.incoming.len);
for (inst.op.phi.incoming, edges) |in, *e| e.* = .{
.val = outside.visit(in.val, {}),
.block = if (in.block == exiting and bb == exit) S.block(nb, nbody, index_in, copies - 1, exiting) else in.block,
};
inst.op = .{ .phi = .{ .incoming = edges } };
continue;
}
try operandsMap(ma, inst, &outside);
if (bb == pre) switch (inst.op) {
.br => |*br| {
if (br.then == h) br.then = S.block(nb, nbody, index_in, 0, h);
if (br.@"else") |*e| if (e.* == h) {
e.* = S.block(nb, nbody, index_in, 0, h);
};
},
.@"switch" => |*sw| {
if (sw.default == h) sw.default = S.block(nb, nbody, index_in, 0, h);
const cs = try ma.alloc(@typeInfo(@TypeOf(sw.cases)).pointer.child, sw.cases.len);
for (sw.cases, cs) |c, *o| o.* = .{ .val = c.val, .block = if (c.block == h) S.block(nb, nbody, index_in, 0, h) else c.block };
sw.cases = cs;
},
else => {},
};
}
}
try f.insts.appendSlice(ma, out.items);
f.num_blocks = nb + copies * nbody;
return true;
}
return false;
}
/// A branch target in copy `k`: the copy's own block, or (the header) the
/// next copy's.
fn mapBlock(t: u32, h: u32, k: u32, copies: u32, nb: u32, nbody: u32, idx: []const u32) u32 {
if (idx[t] == none) return t;
if (t == h) return nb + @min(k + 1, copies - 1) * nbody + idx[t];
return nb + k * nbody + idx[t];
}
/// Rewrites `inst`'s value operands through `ctx.visit` (block operands
/// are the caller's).
pub fn operandsMap(a: Allocator, inst: *Inst, ctx: anytype) Allocator.Error!void {
const S = struct {
fn one(c: anytype, v: *Value) void {
v.* = c.visit(v.*, {});
}
fn many(al: Allocator, c: anytype, vs: *[]const Value) Allocator.Error!void {
const o = try al.alloc(Value, vs.len);
for (vs.*, o) |v, *x| x.* = c.visit(v, {});
vs.* = o;
}
};
switch (inst.op) {
.ret => |*v| if (v.*) |*x| S.one(ctx, x),
.br => |*b| if (b.cond) |*c| S.one(ctx, c),
.@"switch" => |*sw| S.one(ctx, &sw.cond),
.call => |*c| try S.many(a, ctx, &c.args),
.binop => |*b| {
S.one(ctx, &b.lhs);
S.one(ctx, &b.rhs);
},
.cast => |*c| S.one(ctx, &c.val),
.cmp => |*c| {
S.one(ctx, &c.lhs);
S.one(ctx, &c.rhs);
},
.select => |*s| {
S.one(ctx, &s.cond);
S.one(ctx, &s.t);
S.one(ctx, &s.f);
},
.extractvalue => |*x| S.one(ctx, &x.agg),
.phi => |*p| {
const out = try a.alloc(Edge, p.incoming.len);
for (p.incoming, out) |in, *o| o.* = .{ .val = ctx.visit(in.val, {}), .block = in.block };
p.incoming = out;
},
.alloca => |*x| S.one(ctx, &x.size),
.load => |*x| S.one(ctx, &x.ptr),
.store => |*x| {
S.one(ctx, &x.ptr);
S.one(ctx, &x.val);
},
.gep => |*x| {
S.one(ctx, &x.ptr);
try S.many(a, ctx, &x.indices);
},
.atomicrmw => |*x| {
S.one(ctx, &x.ptr);
S.one(ctx, &x.val);
},
.cmpxchg => |*x| {
S.one(ctx, &x.ptr);
S.one(ctx, &x.cmp);
S.one(ctx, &x.new);
},
.@"unreachable" => {},
.extractelement => |*x| {
S.one(ctx, &x.vec);
S.one(ctx, &x.index);
},
.insertelement => |*x| {
S.one(ctx, &x.vec);
S.one(ctx, &x.val);
S.one(ctx, &x.index);
},
}
}

View File

@ -51,6 +51,8 @@ pub const TypeRef = struct {
/// `#pragma pack_matrix` in effect where the type was written (true: /// `#pragma pack_matrix` in effect where the type was written (true:
/// row_major): the orientation of a matrix declared without one. /// row_major): the orientation of a matrix declared without one.
pack_matrix: ?bool = null, pack_matrix: ?bool = null,
/// `struct S`: declares S (at namespace scope) if it is not yet a type.
elaborated: bool = false,
}; };
/// Storage classes, type qualifiers and parameter / interpolation /// Storage classes, type qualifiers and parameter / interpolation

View File

@ -20,7 +20,8 @@ const Loc = source.Loc;
pub const Error = Allocator.Error || error{Syntax}; pub const Error = Allocator.Error || error{Syntax};
const NameKind = enum { type, template_type, template_func, value }; /// (`function`: a plain function, which may overload function templates.)
const NameKind = enum { type, template_type, template_func, value, function };
pub const Parser = struct { pub const Parser = struct {
arena: Allocator, arena: Allocator,
@ -316,6 +317,14 @@ pub const Parser = struct {
try p.scopes.items[p.scopes.items.len - 1].append(p.arena, name); try p.scopes.items[p.scopes.items.len - 1].append(p.arena, name);
} }
/// Declares `name` in the outermost scope (under any inner entries).
fn declareGlobalName(p: *Parser, name: []const u8, kind: NameKind) Allocator.Error!void {
const gop = try p.names.getOrPut(p.arena, name);
if (!gop.found_existing) gop.value_ptr.* = .empty;
try gop.value_ptr.insert(p.arena, 0, kind);
try p.scopes.items[0].append(p.arena, name);
}
fn lookupName(p: *const Parser, name: []const u8) ?NameKind { fn lookupName(p: *const Parser, name: []const u8) ?NameKind {
const list = p.names.get(name) orelse return null; const list = p.names.get(name) orelse return null;
if (list.items.len == 0) return null; if (list.items.len == 0) return null;
@ -336,6 +345,10 @@ pub const Parser = struct {
if (p.lookupName(name)) |k| { if (p.lookupName(name)) |k| {
if (k == .template_type or k == .template_func) return true; if (k == .template_type or k == .template_func) return true;
if (k == .value) return false; if (k == .value) return false;
if (k == .function) {
for (p.names.get(name).?.items) |o| if (o == .template_func) return true;
return false;
}
} }
// Builtin templates keep working when a same-named user type exists // Builtin templates keep working when a same-named user type exists
// in some namespace (the name table is not namespace-aware). // in some namespace (the name table is not namespace-aware).
@ -347,6 +360,7 @@ pub const Parser = struct {
fn scanType(p: *const Parser, start: usize) ?usize { fn scanType(p: *const Parser, start: usize) ?usize {
var i = start; var i = start;
while (isTypeAttrWord(p.toks[i])) i += 1; while (isTypeAttrWord(p.toks[i])) i += 1;
if ((p.toks[i].isIdent("struct") or p.toks[i].isIdent("class")) and p.toks[i + 1].kind == .identifier) i += 1;
if (p.toks[i].isIdent("typename")) return p.scanDependentType(i + 1); if (p.toks[i].isIdent("typename")) return p.scanDependentType(i + 1);
if (p.toks[i].isIdent("unsigned") or p.toks[i].isIdent("signed")) { if (p.toks[i].isIdent("unsigned") or p.toks[i].isIdent("signed")) {
i += 1; i += 1;
@ -555,6 +569,12 @@ pub const Parser = struct {
} }
fn parseTypeInner(p: *Parser) Error!*ast.TypeRef { 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;
if (elaborated) {
_ = p.advance();
if (!p.isTypeName(p.tok().text)) try p.declareGlobalName(p.tok().text, .type);
}
const start = p.tok(); const start = p.tok();
if (p.eatIdent("typename")) { if (p.eatIdent("typename")) {
// Dependent name: `typename X<T>::type`. // Dependent name: `typename X<T>::type`.
@ -586,7 +606,7 @@ pub const Parser = struct {
} }
var args: []const ast.TemplateArg = &.{}; var args: []const ast.TemplateArg = &.{};
if (p.at(.less) and (p.forced_template or p.isTemplateName(name.last()))) args = try p.parseTemplateArgs(); if (p.at(.less) and (p.forced_template or p.isTemplateName(name.last()))) args = try p.parseTemplateArgs();
return p.mk(ast.TypeRef, .{ .loc = start.loc, .name = name, .args = args }); return p.mk(ast.TypeRef, .{ .loc = start.loc, .name = name, .args = args, .elaborated = elaborated });
} }
/// A qualified name whose final part may carry template arguments. /// A qualified name whose final part may carry template arguments.
@ -1269,7 +1289,7 @@ pub const Parser = struct {
if (template_params.len > 0) { if (template_params.len > 0) {
try p.declareNameOuter(name.last(), .template_func, true); try p.declareNameOuter(name.last(), .template_func, true);
} else if (ctx != .member) { } else if (ctx != .member) {
try p.declareName(name.last(), .value); try p.declareName(name.last(), .function);
} }
_ = try p.expect(.l_paren, "'('"); _ = try p.expect(.l_paren, "'('");
try p.pushScope(); try p.pushScope();

View File

@ -30,6 +30,7 @@ pub const Options = struct {
/// SPIR-V 1.x of the target environment. /// SPIR-V 1.x of the target environment.
spirv_minor: u32 = 0, spirv_minor: u32 = 0,
enable_16bit: bool = false, enable_16bit: bool = false,
hlsl_version: u16 = 2021,
}; };
const Builtin = enum { const Builtin = enum {
@ -229,7 +230,10 @@ pub const Preprocessor = struct {
\\#define __DXC_VERSION_MINOR 10 \\#define __DXC_VERSION_MINOR 10
\\#define __DXC_VERSION_RELEASE 0 \\#define __DXC_VERSION_RELEASE 0
\\#define __DXC_VERSION_COMMITS 0 \\#define __DXC_VERSION_COMMITS 0
\\#define __HLSL_VERSION 2021 \\
);
try w.print("#define __HLSL_VERSION {d}\n", .{o.hlsl_version});
try w.writeAll(
\\#define __SHADER_STAGE_VERTEX 1 \\#define __SHADER_STAGE_VERTEX 1
\\#define __SHADER_STAGE_PIXEL 0 \\#define __SHADER_STAGE_PIXEL 0
\\#define __SHADER_STAGE_GEOMETRY 2 \\#define __SHADER_STAGE_GEOMETRY 2

View File

@ -169,9 +169,7 @@ fn structAlign(t: *const TypeTable, info: *const types.StructInfo, rules: Rules)
} }
fn structSize(t: *const TypeTable, info: *const types.StructInfo, rules: Rules) Error!u32 { fn structSize(t: *const TypeTable, info: *const types.StructInfo, rules: Rules) Error!u32 {
var buf: [256]u32 = undefined; const off = try layoutFields(t, info, rules, null);
if (info.fields.items.len > buf.len) return error.Unsupported;
const off = try layoutFields(t, info, rules, buf[0..info.fields.items.len]);
return switch (rules) { return switch (rules) {
.dx_legacy => off, .dx_legacy => off,
// (Packed structs still round up to their widest component: a // (Packed structs still round up to their widest component: a
@ -180,9 +178,9 @@ fn structSize(t: *const TypeTable, info: *const types.StructInfo, rules: Rules)
}; };
} }
/// Stores the offsets of `info`'s fields in `out`; returns where the last /// Stores the offsets of `info`'s fields in `out` (if given); returns where
/// one ends. /// the last one ends.
fn layoutFields(t: *const TypeTable, info: *const types.StructInfo, rules: Rules, out: []u32) Error!u32 { fn layoutFields(t: *const TypeTable, info: *const types.StructInfo, rules: Rules, out: ?[]u32) Error!u32 {
var off: u32 = 0; var off: u32 = 0;
var first: usize = 0; var first: usize = 0;
if (info.bases.items.len > 0 and rules != .dx_legacy and rules != .dx_packed) { if (info.bases.items.len > 0 and rules != .dx_legacy and rules != .dx_packed) {
@ -190,7 +188,7 @@ fn layoutFields(t: *const TypeTable, info: *const types.StructInfo, rules: Rules
// its alignment); DXIL lays its fields out in place. // its alignment); DXIL lays its fields out in place.
const base = info.bases.items[0]; const base = info.bases.items[0];
first = base.fields.items.len; first = base.fields.items.len;
_ = try layoutFields(t, base, rules, out[0..first]); _ = try layoutFields(t, base, rules, if (out) |o| o[0..first] else null);
off = try structSize(t, base, rules); off = try structSize(t, base, rules);
} }
// Explicit offsets (packoffset / register(cN)): the other members // Explicit offsets (packoffset / register(cN)): the other members
@ -201,20 +199,20 @@ fn layoutFields(t: *const TypeTable, info: *const types.StructInfo, rules: Rules
}; };
if (packed_end) |pe| off = @max(off, pe); if (packed_end) |pe| off = @max(off, pe);
var end: u32 = off; var end: u32 = off;
for (info.fields.items[first..], out[first..]) |f, *o| { for (info.fields.items[first..], first..) |f, i| {
// (Resources in structs take no space in buffers.) // (Resources in structs take no space in buffers.)
if (isOpaque(t, f.type)) { const at = if (isOpaque(t, f.type))
o.* = off; off
continue; else if (f.pack_offset) |po|
} po
if (f.pack_offset) |po| { else at: {
o.* = po; // [[vk::offset]] (SPIR-V only): later members continue from it.
continue; const o = if (f.vk_offset) |vo| vo else try place(t, off, f.type, f.row_major, rules);
} off = o + try sizeOf(t, f.type, f.row_major, rules);
// [[vk::offset]] (SPIR-V only): later members continue from it. end = @max(end, off);
o.* = if (f.vk_offset) |vo| vo else try place(t, off, f.type, f.row_major, rules); break :at o;
off = o.* + try sizeOf(t, f.type, f.row_major, rules); };
end = @max(end, off); if (out) |o| o[i] = at;
} }
return @max(end, packed_end orelse 0); return @max(end, packed_end orelse 0);
} }

View File

@ -1026,6 +1026,15 @@ const Lowerer = struct {
}, },
.conditional => |x| { .conditional => |x| {
const ty = try l.concrete(e.ty); const ty = try l.concrete(e.ty);
// HLSL 2018: both operands, then a (per-component) select.
if (l.s.opts.hlsl_version < 2021 and t.isNumeric(ty)) {
const cs = t.shape(x.cond.ty);
const cond_ty = if (cs != null and cs.?.kind != .scalar) try t.withComponent(ty, .bool) else try t.scalar(.bool);
const cond = try l.converted(x.cond, cond_ty);
const a = try l.converted(x.then, ty);
const b = try l.converted(x.@"else", ty);
return l.b.add(.{ .op = .{ .select = .{ .cond = cond, .t = a, .f = b } }, .ty = ty });
}
const tmp = try l.b.add(.{ .op = .local_var, .ty = ty, .ptr = .function }); const tmp = try l.b.add(.{ .op = .local_var, .ty = ty, .ptr = .function });
const cond = try l.condition(x.cond); const cond = try l.condition(x.cond);
const then_b = try l.b.newBlock(); const then_b = try l.b.newBlock();
@ -1072,6 +1081,9 @@ const Lowerer = struct {
return l.b.load(p); return l.b.load(p);
}, },
.sizeof_type, .sizeof_expr, .is_same => { .sizeof_type, .sizeof_expr, .is_same => {
// (Sema keeps the size; a template instance's type names
// no longer resolve here.)
if (e.kind == .sizeof_type and e.info != 0) return l.b.constInt(try l.concrete(e.ty), e.info - 1);
if (l.s.evalInt(e)) |v| return l.b.constInt(try l.concrete(e.ty), v); if (l.s.evalInt(e)) |v| return l.b.constInt(try l.concrete(e.ty), v);
return l.fail(e, "this expression"); return l.fail(e, "this expression");
}, },
@ -1103,7 +1115,13 @@ const Lowerer = struct {
_ = try l.rvalue(lhs); _ = try l.rvalue(lhs);
return l.rvalue(rhs); return l.rvalue(rhs);
}, },
.log_and, .log_or => { .log_and, .log_or => if (l.s.opts.hlsl_version < 2021) {
// HLSL 2018: both operands, component-wise.
const ty = try l.concrete(e.ty);
const a = try l.converted(lhs, ty);
const b = try l.converted(rhs, ty);
return l.b.add(.{ .op = .{ .binary = .{ .op = if (op == .log_and) .log_and else .log_or, .lhs = a, .rhs = b } }, .ty = ty });
} else {
// Short-circuit (HLSL 2021: scalar operands). // Short-circuit (HLSL 2021: scalar operands).
const bool_ty = try t.scalar(.bool); const bool_ty = try t.scalar(.bool);
const tmp = try l.b.add(.{ .op = .local_var, .ty = bool_ty, .ptr = .function }); const tmp = try l.b.add(.{ .op = .local_var, .ty = bool_ty, .ptr = .function });
@ -1756,6 +1774,12 @@ const Lowerer = struct {
return l.variableLvalue(e, r.variable); return l.variableLvalue(e, r.variable);
}, },
.member => |m| { .member => |m| {
// One component of a vector (atomics' `ref`, `B[i].x`).
if (l.s.resolution(e) == null and t.get(m.base.ty) == .vector) if (try swizzleComponents(l.arena, m.name)) |comps| if (comps.len == 1) {
const base = try l.lvalue(m.base);
const idx = try l.b.constInt(try t.scalar(.uint), comps[0]);
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 });
};
const r = l.s.resolution(e) orelse return l.fail(e, "this member"); const r = l.s.resolution(e) orelse return l.fail(e, "this member");
// A static member through an object. // A static member through an object.
if (r == .variable) return l.variableLvalue(e, r.variable); if (r == .variable) return l.variableLvalue(e, r.variable);

View File

@ -8,7 +8,8 @@
//! coerced into the group's class (`float_like`, `numeric`, `any_int`...), //! coerced into the group's class (`float_like`, `numeric`, `any_int`...),
//! and the layout is taken from the declared dimensions (binding symbolic //! and the layout is taken from the declared dimensions (binding symbolic
//! sizes like `c` and `r2` across arguments) or, for `<>`, from the //! sizes like `c` and `r2` across arguments) or, for `<>`, from the
//! arguments. Candidates are ranked by total conversion cost. //! arguments. Candidates are ranked by their worst conversion, then their
//! total conversion cost.
const std = @import("std"); const std = @import("std");
const Allocator = std.mem.Allocator; const Allocator = std.mem.Allocator;
@ -91,6 +92,17 @@ pub const Db = struct {
return list.items; return list.items;
} }
/// The conversion cost of the best overload of global intrinsic `name`
/// for `args`, or null if none fits (no diagnostics).
pub fn bestCost(db: *const Db, sema: anytype, name: []const u8, args: []const ArgInfo) !?u32 {
var best: ?u32 = null;
for (try db.candidates(sema.arena, "Intrinsics", name)) |ci| {
const m = try matchOne(sema, &table.intrinsics[ci], null, args, null) orelse continue;
if (best == null or m.cost < best.?) best = m.cost;
}
return best;
}
/// Resolve a call; reports a diagnostic and returns the error type when /// Resolve a call; reports a diagnostic and returns the error type when
/// no overload matches. `sema` is the calling Sema (for conversions and /// no overload matches. `sema` is the calling Sema (for conversions and
/// diagnostics); `object` is the method's object type, if any. /// diagnostics); `object` is the method's object type, if any.
@ -211,11 +223,13 @@ fn matchOne(sema: anytype, it: *const table.Intrinsic, object: ?TypeId, args: []
var bindings: Bindings = .{}; var bindings: Bindings = .{};
for (args[0..it.params.len], 1..) |a, i| { for (args[0..it.params.len], 1..) |a, i| {
if (!specs[i].any_layout) continue; // (Also arguments whose layout links to a `<>` one.)
if (!specs[i].any_layout and !specs[layout_group[i]].any_layout) continue;
const sh = t.shape(a.ty) orelse continue; const sh = t.shape(a.ty) orelse continue;
if (bindings.any_shape == null or sh.count() > bindings.any_shape.?.count()) bindings.any_shape = sh; if (bindings.any_shape == null or sh.count() > bindings.any_shape.?.count()) bindings.any_shape = sh;
} }
var cost: u32 = 0; var sum: u32 = 0;
var worst: u32 = 0;
const out_params = try sema.arena.alloc(bool, args.len); const out_params = try sema.arena.alloc(bool, args.len);
@memset(out_params, false); @memset(out_params, false);
const param_types = try sema.arena.alloc(TypeId, args.len); const param_types = try sema.arena.alloc(TypeId, args.len);
@ -230,13 +244,17 @@ fn matchOne(sema: anytype, it: *const table.Intrinsic, object: ?TypeId, args: []
param_types[ai] = if (pt == TypeTable.error_type) a.ty else pt; param_types[ai] = if (pt == TypeTable.error_type) a.ty else pt;
if (pt == TypeTable.error_type) continue; // unconstrained object / unknown class if (pt == TypeTable.error_type) continue; // unconstrained object / unknown class
const c = sema.conversionCost(a.ty, pt) orelse return null; const c = sema.conversionCost(a.ty, pt) orelse return null;
cost += c; // A `ref` argument (InterlockedAdd's destination) is the storage
// itself: its type must match.
if (s.qual == .ref and c != 0) return null;
sum += c;
worst = @max(worst, c);
} }
// Return type. // Return type.
const ret = try paramType(sema, specs, 0, comp_group, layout_group, group_comp, &bindings, args, obj_elem, explicit) orelse return null; const ret = try paramType(sema, specs, 0, comp_group, layout_group, group_comp, &bindings, args, obj_elem, explicit) orelse return null;
for (args[@min(args.len, it.params.len)..], @min(args.len, it.params.len)..) |a, ai| param_types[ai] = a.ty; // varargs for (args[@min(args.len, it.params.len)..], @min(args.len, it.params.len)..) |a, ai| param_types[ai] = a.ty; // varargs
return .{ .ret = ret, .cost = cost, .out_params = out_params, .params = param_types }; return .{ .ret = ret, .cost = Scalar.overloadCost(worst, sum), .out_params = out_params, .params = param_types };
} }
/// The concrete type of spec `i`, or null if the arguments cannot fit. /// The concrete type of spec `i`, or null if the arguments cannot fit.

View File

@ -25,6 +25,9 @@ pub const Options = struct {
entry: ?[]const u8 = null, entry: ?[]const u8 = null,
spirv: bool = false, spirv: bool = false,
enable_16bit: bool = false, enable_16bit: bool = false,
/// HLSL 2016-2018 (below 2021): `&&`, `||` and `?:` work component-wise
/// on vectors and evaluate both operands.
hlsl_version: u16 = 2021,
/// Target shader model 6.x (long vectors need 6.9). /// Target shader model 6.x (long vectors need 6.9).
sm_minor: u8 = 10, sm_minor: u8 = 10,
/// Library target (`lib_6_x`): exported functions are the roots of /// Library target (`lib_6_x`): exported functions are the roots of
@ -113,13 +116,20 @@ pub const Function = struct {
param_vars: []?*Variable = &.{}, param_vars: []?*Variable = &.{},
/// A function template instance's arguments. /// A function template instance's arguments.
template_args: []const Bound = &.{}, template_args: []const Bound = &.{},
/// A method of a class template instance: its body, checked when the
/// method is first called (as C++ instantiates members).
pending: ?*const PendingBody = null,
}; };
pub const PendingBody = struct { f: *const ast.FuncDecl, scope: *Scope, strct: ?*types.StructInfo };
/// A bound template argument. /// A bound template argument.
pub const Bound = types.TemplateArg; pub const Bound = types.TemplateArg;
pub const FuncSet = struct { pub const FuncSet = struct {
funcs: std.ArrayList(*Function) = .empty, funcs: std.ArrayList(*Function) = .empty,
/// Function templates of the same name, overloading with `funcs`.
templates: ?*TemplateSet = null,
}; };
pub const Symbol = union(enum) { pub const Symbol = union(enum) {
@ -309,8 +319,15 @@ pub const Sema = struct {
const set = blk: { const set = blk: {
if (s.scope.syms.get(name)) |sym| switch (sym) { if (s.scope.syms.get(name)) |sym| switch (sym) {
.template => |t| break :blk t, .template => |t| break :blk t,
// Plain functions take precedence over templates. // Function templates overload the plain functions.
.functions => return, .functions => |fs| {
if (d.kind != .func) return;
if (fs.templates == null) {
fs.templates = try s.arena.create(TemplateSet);
fs.templates.?.* = .{};
}
break :blk fs.templates.?;
},
else => {}, else => {},
}; };
const set = try s.arena.create(TemplateSet); const set = try s.arena.create(TemplateSet);
@ -740,18 +757,74 @@ pub const Sema = struct {
/// A call to a function template: deduce, instantiate (once per /// A call to a function template: deduce, instantiate (once per
/// argument list), then resolve as an ordinary call. /// argument list), then resolve as an ordinary call.
fn callTemplate(s: *Sema, e: *ast.Expr, tset: *TemplateSet, explicit: []const ast.TemplateArg, args: []const intrinsics.ArgInfo, callee: *ast.Expr, owner: ?*types.StructInfo) Allocator.Error!TypeId { fn callTemplate(s: *Sema, e: *ast.Expr, tset: *TemplateSet, explicit: []const ast.TemplateArg, args: []const intrinsics.ArgInfo, callee: *ast.Expr, owner: ?*types.StructInfo) Allocator.Error!TypeId {
// Every overload that deduces contributes its instance. const all = try s.templateInstances(tset, explicit, args, callee, owner, tset.decls.items.len > 1);
const all = try s.arena.create(FuncSet);
all.* = .{};
for (tset.decls.items) |d| {
if (d.kind != .func) continue;
const inst = try s.instantiateCall(d, explicit, args, callee, tset.decls.items.len > 1, owner);
if (inst) |set| try all.funcs.appendSlice(s.arena, set.funcs.items);
}
if (all.funcs.items.len == 0) { if (all.funcs.items.len == 0) {
s.err(callee.loc, "this call to a function template is not supported yet", .{}); s.err(callee.loc, "this call to a function template is not supported yet", .{});
return TypeTable.error_type; return TypeTable.error_type;
} }
return s.resolveInstances(e, all, args, callee);
}
/// The instances of `tset`'s function templates that deduce for `args`.
fn templateInstances(s: *Sema, tset: *TemplateSet, explicit: []const ast.TemplateArg, args: []const intrinsics.ArgInfo, callee: *ast.Expr, owner: ?*types.StructInfo, quiet: bool) Allocator.Error!*FuncSet {
const all = try s.arena.create(FuncSet);
all.* = .{};
for (tset.decls.items) |d| {
if (d.kind != .func) continue;
// (Not with too many or too few arguments.)
const ps = d.kind.func.params;
var required: usize = 0;
for (ps) |p| {
if (p.init == null) required += 1;
}
if (args.len > ps.len or args.len < required) continue;
const inst = try s.instantiateCall(d, explicit, args, callee, quiet, owner);
if (inst) |set| try all.funcs.appendSlice(s.arena, set.funcs.items);
}
return all;
}
/// A call to plain functions and function templates of one name: the
/// templates' instances win only by a lower cost (as in C++, a tie goes
/// to the plain function).
fn callOverloads(s: *Sema, e: *ast.Expr, set: *FuncSet, tset: *TemplateSet, args: []const intrinsics.ArgInfo, callee: *ast.Expr) Allocator.Error!Typed {
const insts = try s.templateInstances(tset, &.{}, args, callee, null, true);
const both = try s.arena.create(FuncSet);
both.* = .{};
try both.funcs.appendSlice(s.arena, set.funcs.items);
try both.funcs.appendSlice(s.arena, insts.funcs.items);
if (try s.intrinsicFitsBetter(callee, both, args)) return s.intrinsicCall(e, callee, callee.kind.name.parts[0], args, &.{});
var plain: ?u32 = null;
for (set.funcs.items) |f| {
const cost = s.callCost(f, args) orelse continue;
if (plain == null or cost < plain.?) plain = cost;
}
var templ: ?u32 = null;
for (insts.funcs.items) |f| {
const cost = s.callCost(f, args) orelse continue;
if (templ == null or cost < templ.?) templ = cost;
}
if (templ != null and (plain == null or templ.? < plain.?)) return rvalue(try s.resolveInstances(e, insts, args, callee));
return rvalue(s.resolveUserCall(e, set, args, callee));
}
/// Whether a call by an intrinsic's name to user functions `set` (or
/// template instances) goes to the intrinsic: when it fits better, or
/// when none of them fits (a tie goes to the user function).
fn intrinsicFitsBetter(s: *Sema, callee: *ast.Expr, set: *FuncSet, args: []const intrinsics.ArgInfo) Allocator.Error!bool {
if (callee.kind != .name or callee.kind.name.parts.len != 1) return false;
const name = callee.kind.name.parts[0];
if (!s.intrinsic_db.has(name, s.opts.spirv)) return false;
var user: ?u32 = null;
for (set.funcs.items) |f| {
const cost = s.callCost(f, args) orelse continue;
if (user == null or cost < user.?) user = cost;
}
const ic = try s.intrinsic_db.bestCost(s, name, args) orelse return user == null;
return user == null or ic < user.?;
}
fn resolveInstances(s: *Sema, e: *ast.Expr, all: *FuncSet, args: []const intrinsics.ArgInfo, callee: *ast.Expr) Allocator.Error!TypeId {
// A template declared, then defined: its definition's instance. // A template declared, then defined: its definition's instance.
var kept: usize = 0; var kept: usize = 0;
for (all.funcs.items) |a| { for (all.funcs.items) |a| {
@ -1279,6 +1352,14 @@ pub const Sema = struct {
// `S<T>::type` where the instance has no such member (the // `S<T>::type` where the instance has no such member (the
// parser cannot tell); other unknown names were reported there. // parser cannot tell); other unknown names were reported there.
if (t.name.parts.len > 1 and t.name.args.len > 0) s.err(t.loc, "no type named '{s}' in this template instance", .{n}); if (t.name.parts.len > 1 and t.name.args.len > 0) s.err(t.loc, "no type named '{s}' in this template instance", .{n});
// `struct S` before any declaration of S: forward-declares it.
if (t.elaborated and t.name.parts.len == 1 and s.global.syms.get(n) == null) {
const info = try s.arena.create(types.StructInfo);
info.* = .{ .name = n, .scopes = &.{} };
const ty = try s.types.intern(.{ .@"struct" = info });
try s.global.syms.put(s.arena, n, .{ .type = ty });
return ty;
}
return TypeTable.error_type; return TypeTable.error_type;
} }
@ -2300,10 +2381,16 @@ pub const Sema = struct {
// Unsized arrays take their size from the initializer. // Unsized arrays take their size from the initializer.
if (v.init) |init_e| if (!is_auto) { if (v.init) |init_e| if (!is_auto) {
if (s.types.get(ty) == .array and s.types.get(ty).array.len == 0 and init_e.kind == .init_list) { if (s.types.get(ty) == .array and s.types.get(ty).array.len == 0 and init_e.kind == .init_list) {
// (Its items typed first: their sizes count.)
_ = try s.checkInitializer(TypeTable.error_type, init_e);
const elem = s.types.get(ty).array.elem; const elem = s.types.get(ty).array.elem;
const elem_count = s.types.componentCount(elem) orelse 1; const elem_count = s.types.componentCount(elem) orelse 1;
const flat = s.flatCount(init_e); const flat = s.flatCount(init_e);
ty = try s.types.array(elem, @intCast(@max(1, (flat + elem_count - 1) / @max(1, elem_count)))); ty = try s.types.array(elem, @intCast(@max(1, (flat + elem_count - 1) / @max(1, elem_count))));
variable.type = ty;
init_e.ty = ty;
if (!s.checkInitCount(ty, init_e)) variable.type = TypeTable.error_type;
return;
} }
variable.type = ty; variable.type = ty;
// Uses of a declaration with a bad initializer are not // Uses of a declaration with a bad initializer are not
@ -2395,15 +2482,17 @@ pub const Sema = struct {
// Add to the overload set, matching an earlier prototype if any. // Add to the overload set, matching an earlier prototype if any.
const set = blk: { const set = blk: {
var templates: ?*TemplateSet = null;
if (s.scope.syms.get(name)) |sym| { if (s.scope.syms.get(name)) |sym| {
if (sym == .functions) break :blk sym.functions; if (sym == .functions) break :blk sym.functions;
if (sym != .template) { if (sym != .template) {
s.err(d.loc, "redefinition of '{s}' as a different kind of symbol", .{name}); s.err(d.loc, "redefinition of '{s}' as a different kind of symbol", .{name});
return; return;
} }
if (sym.template.decls.items.len > 0 and sym.template.decls.items[0].kind == .func) templates = sym.template;
} }
const set = try s.arena.create(FuncSet); const set = try s.arena.create(FuncSet);
set.* = .{}; set.* = .{ .templates = templates };
try s.declare(name, .{ .functions = set }, d.loc); try s.declare(name, .{ .functions = set }, d.loc);
break :blk set; break :blk set;
}; };
@ -2525,6 +2614,26 @@ pub const Sema = struct {
} }
fn funcBody(s: *Sema, func: *Function, f: *const ast.FuncDecl) Allocator.Error!void { fn funcBody(s: *Sema, func: *Function, f: *const ast.FuncDecl) Allocator.Error!void {
if (f.body != null and func.owner != null and s.instance_depth > 0 and s.current_fn == null) {
const p = try s.arena.create(PendingBody);
p.* = .{ .f = f, .scope = s.scope, .strct = s.current_struct };
func.pending = p;
return;
}
return s.checkBody(func, f);
}
/// Checks a pending method body (see Function.pending).
fn ensureBody(s: *Sema, func: *Function) Allocator.Error!void {
const p = func.pending orelse return;
func.pending = null;
const ctx = s.enterInstance(p.scope);
defer s.leaveInstance(ctx);
s.current_struct = p.strct;
try s.checkBody(func, p.f);
}
fn checkBody(s: *Sema, func: *Function, f: *const ast.FuncDecl) Allocator.Error!void {
const params = func.params; const params = func.params;
const body = f.body orelse return; const body = f.body orelse return;
const saved_fn = s.current_fn; const saved_fn = s.current_fn;
@ -2799,7 +2908,36 @@ pub const Sema = struct {
} }
} }
/// Whether `name` is declared in the current function (its parameters
/// and blocks).
fn inFunctionScope(s: *Sema, name: []const u8) bool {
var sc: ?*Scope = s.scope;
while (sc) |c| : (sc = c.parent) {
if (c.kind != .block and c.kind != .function) return false;
if (c.syms.contains(name)) return true;
if (c.kind == .function) return false;
}
return false;
}
/// A field (or bitfield) of the method's struct named `name`.
fn thisField(s: *Sema, e: *ast.Expr, info: *types.StructInfo, name: []const u8) Allocator.Error!?Typed {
for (info.fields.items, 0..) |f, k| if (std.mem.eql(u8, f.name, name)) {
s.record(e, .{ .this_field = @intCast(k) });
return .{ .ty = f.type, .lvalue = true };
};
if (findBitfield(info, name)) |bf| {
s.record(e, .{ .this_bitfield = bf });
return .{ .ty = bf.type, .lvalue = true };
}
return null;
}
fn nameExpr(s: *Sema, e: *ast.Expr, n: ast.Name) Allocator.Error!Typed { fn nameExpr(s: *Sema, e: *ast.Expr, n: ast.Name) Allocator.Error!Typed {
// Inside methods, fields come before names outside the function.
if (n.parts.len == 1 and s.current_struct != null and !s.inFunctionScope(n.parts[0])) {
if (try s.thisField(e, s.current_struct.?, n.parts[0])) |t| return t;
}
if (s.lookupName(n)) |sym| switch (sym) { if (s.lookupName(n)) |sym| switch (sym) {
.variable => |v| { .variable => |v| {
s.record(e, .{ .variable = v }); s.record(e, .{ .variable = v });
@ -2827,16 +2965,7 @@ pub const Sema = struct {
} }
// Struct fields and methods used unqualified inside methods. // Struct fields and methods used unqualified inside methods.
if (s.current_struct) |info| { if (s.current_struct) |info| {
if (n.parts.len == 1) { if (n.parts.len == 1) if (try s.thisField(e, info, n.parts[0])) |t| return t;
for (info.fields.items, 0..) |f, k| if (std.mem.eql(u8, f.name, n.parts[0])) {
s.record(e, .{ .this_field = @intCast(k) });
return .{ .ty = f.type, .lvalue = true };
};
if (findBitfield(info, n.parts[0])) |bf| {
s.record(e, .{ .this_bitfield = bf });
return .{ .ty = bf.type, .lvalue = true };
}
}
} }
if (n.parts.len > 1) { if (n.parts.len > 1) {
for (n.parts[0 .. n.parts.len - 1], 0..) |part, i| { for (n.parts[0 .. n.parts.len - 1], 0..) |part, i| {
@ -3027,6 +3156,10 @@ pub const Sema = struct {
const ls = s.types.shape(lt) orelse return s.invalidOperands(loc, lt, rt); const ls = s.types.shape(lt) orelse return s.invalidOperands(loc, lt, rt);
const rs = s.types.shape(rt) orelse return s.invalidOperands(loc, lt, rt); const rs = s.types.shape(rt) orelse return s.invalidOperands(loc, lt, rt);
if (logical) { if (logical) {
if (s.opts.hlsl_version < 2021 and (ls.kind != .scalar or rs.kind != .scalar)) {
const sh = TypeTable.combineDimensions(ls, rs) orelse return s.invalidOperands(loc, lt, rt);
return try s.types.withShape(.bool, sh);
}
if (ls.kind != .scalar or rs.kind != .scalar) { if (ls.kind != .scalar or rs.kind != .scalar) {
s.err(loc, "operands for short-circuiting logical binary operator must be scalar, for non-scalar types use '{s}'", .{if (op == .log_and) "and" else "or"}); s.err(loc, "operands for short-circuiting logical binary operator must be scalar, for non-scalar types use '{s}'", .{if (op == .log_and) "and" else "or"});
return null; return null;
@ -3160,6 +3293,7 @@ pub const Sema = struct {
const c = try s.expr(cond); const c = try s.expr(cond);
const t = try s.expr(then); const t = try s.expr(then);
const f = try s.expr(else_e); const f = try s.expr(else_e);
if (s.opts.hlsl_version < 2021) return s.legacyConditional(e, c, t, f);
if (c.ty != TypeTable.error_type) { if (c.ty != TypeTable.error_type) {
if (s.types.shape(c.ty)) |sh| { if (s.types.shape(c.ty)) |sh| {
if (sh.kind != .scalar) { if (sh.kind != .scalar) {
@ -3177,6 +3311,29 @@ pub const Sema = struct {
return err_typed; return err_typed;
} }
/// HLSL 2018's `?:`: a vector condition selects per component, and the
/// result takes the shape of all three operands.
fn legacyConditional(s: *Sema, e: *ast.Expr, c: Typed, t: Typed, f: Typed) Allocator.Error!Typed {
if (c.ty == TypeTable.error_type or t.ty == TypeTable.error_type or f.ty == TypeTable.error_type) return err_typed;
const r = if (t.ty == f.ty) t.ty else if (s.types.isNumeric(t.ty) and s.types.isNumeric(f.ty))
s.arithmetic(e, t.ty, f.ty) orelse return err_typed
else {
s.err(e.loc, "incompatible operand types ('{s}' and '{s}')", .{ s.typeName(t.ty), s.typeName(f.ty) });
return err_typed;
};
const cs = s.types.shape(c.ty) orelse return rvalue(r);
if (cs.kind == .scalar) return rvalue(r);
const rs = s.types.shape(r) orelse {
s.err(e.loc, "incompatible operand types ('{s}' and '{s}')", .{ s.typeName(c.ty), s.typeName(r) });
return err_typed;
};
const sh = TypeTable.combineDimensions(cs, rs) orelse {
s.err(e.loc, "incompatible operand types ('{s}' and '{s}')", .{ s.typeName(c.ty), s.typeName(r) });
return err_typed;
};
return rvalue(try s.types.withShape(s.types.component(r).?, sh));
}
/// `sizeof(ty)` plus one, or zero when it has no size: HLSL sizes are /// `sizeof(ty)` plus one, or zero when it has no size: HLSL sizes are
/// tightly packed at scalar alignment. A struct that had errors has /// tightly packed at scalar alignment. A struct that had errors has
/// size 1, as in clang. /// size 1, as in clang.
@ -3520,7 +3677,13 @@ pub const Sema = struct {
}; };
for (arg_types) |a| if (a.ty == TypeTable.error_type) return err_typed; for (arg_types) |a| if (a.ty == TypeTable.error_type) return err_typed;
switch (target) { switch (target) {
.functions => |set| return rvalue(s.resolveUserCall(e, set, arg_types, callee)), .functions => |set| if (set.templates) |tset| {
if (template_args.len > 0) return rvalue(try s.callTemplate(e, tset, template_args, arg_types, callee, null));
return s.callOverloads(e, set, tset, arg_types, callee);
} else {
if (try s.intrinsicFitsBetter(callee, set, arg_types)) return s.intrinsicCall(e, callee, callee.kind.name.parts[0], arg_types, template_args);
return rvalue(s.resolveUserCall(e, set, arg_types, callee));
},
.template => |set| { .template => |set| {
// A member template called unqualified from a method. // A member template called unqualified from a method.
var owner: ?*types.StructInfo = null; var owner: ?*types.StructInfo = null;
@ -3530,15 +3693,13 @@ pub const Sema = struct {
owner = info; owner = info;
}; };
}; };
if (template_args.len == 0 and owner == null) {
const insts = try s.templateInstances(set, &.{}, arg_types, callee, null, true);
if (try s.intrinsicFitsBetter(callee, insts, arg_types)) return s.intrinsicCall(e, callee, callee.kind.name.parts[0], arg_types, template_args);
}
return rvalue(try s.callTemplate(e, set, template_args, arg_types, callee, owner)); return rvalue(try s.callTemplate(e, set, template_args, arg_types, callee, owner));
}, },
.intrinsic => |name| { .intrinsic => |name| return s.intrinsicCall(e, callee, name, arg_types, template_args),
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 } });
return rvalue(r.ret);
},
.method => |m| { .method => |m| {
switch (s.types.get(m.object)) { switch (s.types.get(m.object)) {
.@"struct" => |info| { .@"struct" => |info| {
@ -3592,33 +3753,44 @@ pub const Sema = struct {
return null; return null;
} }
fn intrinsicCall(s: *Sema, e: *ast.Expr, callee: *ast.Expr, name: []const u8, arg_types: []const intrinsics.ArgInfo, template_args: []const ast.TemplateArg) Allocator.Error!Typed {
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 } });
return rvalue(r.ret);
}
/// The cost of calling `f` with `args`, or null if it cannot take them.
fn callCost(s: *Sema, f: *const Function, args: []const intrinsics.ArgInfo) ?u32 {
if (args.len > f.params.len) return null;
var required: usize = 0;
for (f.params) |p| {
if (!p.has_default) required += 1;
}
if (args.len < required) return null;
var sum: u32 = 0;
var worst: u32 = 0;
for (args, 0..) |a, i| {
const p = f.params[i];
var c = s.conversionCost(a.ty, p.type) orelse return null;
// groupshared parameters bind only groupshared arguments
// (and are preferred for them).
if (p.groupshared and !a.groupshared) return null;
if (a.groupshared and !p.groupshared) c += 4;
sum += c;
worst = @max(worst, c);
}
return types.Scalar.overloadCost(worst, sum);
}
/// Overload resolution among user functions by conversion cost. /// Overload resolution among user functions by conversion cost.
fn resolveUserCall(s: *Sema, e: *ast.Expr, set: *FuncSet, args: []const intrinsics.ArgInfo, callee: *ast.Expr) TypeId { fn resolveUserCall(s: *Sema, e: *ast.Expr, set: *FuncSet, args: []const intrinsics.ArgInfo, callee: *ast.Expr) TypeId {
var best: ?*Function = null; var best: ?*Function = null;
var best_cost: u32 = std.math.maxInt(u32); var best_cost: u32 = std.math.maxInt(u32);
var ambiguous = false; var ambiguous = false;
for (set.funcs.items) |f| { for (set.funcs.items) |f| {
if (args.len > f.params.len) continue; const cost = s.callCost(f, args) orelse continue;
var required: usize = 0;
for (f.params) |p| {
if (!p.has_default) required += 1;
}
if (args.len < required) continue;
var cost: u32 = 0;
var ok = true;
for (args, 0..) |a, i| {
const p = f.params[i];
const c = s.conversionCost(a.ty, p.type);
// groupshared parameters bind only groupshared arguments
// (and are preferred for them).
if (c == null or (p.groupshared and !a.groupshared)) {
ok = false;
break;
}
cost += c.?;
if (a.groupshared and !p.groupshared) cost += 1;
}
if (!ok) continue;
if (cost < best_cost) { if (cost < best_cost) {
best = f; best = f;
best_cost = cost; best_cost = cost;
@ -3641,6 +3813,7 @@ pub const Sema = struct {
} }
if (s.current_fn) |caller| caller.callees.append(s.arena, f) catch {}; if (s.current_fn) |caller| caller.callees.append(s.arena, f) catch {};
s.record(e, .{ .function = f }); s.record(e, .{ .function = f });
s.ensureBody(f) catch {};
return f.ret; return f.ret;
} }
@ -3658,24 +3831,24 @@ pub const Sema = struct {
if (tt == .@"enum" and (tt.@"enum".scoped or ft == .@"enum")) return null; // needs a cast if (tt == .@"enum" and (tt.@"enum".scoped or ft == .@"enum")) return null; // needs a cast
const fs = s.types.shape(from).?; const fs = s.types.shape(from).?;
const ts = s.types.shape(to).?; const ts = s.types.shape(to).?;
var cost: u32 = if (fc.? == tc.?) 0 else if (fc.?.isLiteral()) 1 else if (fc.?.isFloat() == tc.?.isFloat() and tc.?.rank() > fc.?.rank()) 2 else 3; var cost: u32 = fc.?.conversionCost(tc.?);
cost += switch (TypeTable.convertDimensions(ts, fs) orelse return null) { cost += switch (TypeTable.convertDimensions(ts, fs) orelse return null) {
.identity => 0, .identity => 0,
.scalar => 1, // float1 -> float .scalar => 4, // float1 -> float
.splat => if (ts.count() == 1) 1 else 4, .splat => if (ts.count() == 1) 4 else 16,
.conversion => 6, // vector <-> matrix of the same size .conversion => 24, // vector <-> matrix of the same size
.truncation => if (ts.count() == 1) 10 else 8, .truncation => if (ts.count() == 1) 40 else 32,
}; };
return cost; return cost;
} }
// A descriptor heap element converts to any resource or sampler. // A descriptor heap element converts to any resource or sampler.
if (ft == .dynamic_resource and (tt == .resource or tt == .sampler)) return 0; if (ft == .dynamic_resource and (tt == .resource or tt == .sampler)) return 0;
// Derived structs convert to their bases. // Derived structs convert to their bases.
if (ft == .@"struct" and tt == .@"struct" and derivesFrom(ft.@"struct", tt.@"struct")) return 2; if (ft == .@"struct" and tt == .@"struct" and derivesFrom(ft.@"struct", tt.@"struct")) return 8;
// int -> unscoped enum (dxc accepts it). // int -> unscoped enum (dxc accepts it).
if (tt == .@"enum" and !tt.@"enum".scoped and s.types.isNumeric(from) and ft != .@"enum") return 3; if (tt == .@"enum" and !tt.@"enum".scoped and s.types.isNumeric(from) and ft != .@"enum") return 12;
// ConstantBuffer<S> / TextureBuffer<S> are usable as an S value. // ConstantBuffer<S> / TextureBuffer<S> are usable as an S value.
if (ft == .resource and (ft.resource.kind == .constant_buffer or ft.resource.kind == .texture_buffer) and ft.resource.elem == to) return 1; if (ft == .resource and (ft.resource.kind == .constant_buffer or ft.resource.kind == .texture_buffer) and ft.resource.elem == to) return 4;
return switch (ft) { return switch (ft) {
.array => |fa| switch (tt) { .array => |fa| switch (tt) {
.array => |ta| if ((ta.len == fa.len or ta.len == 0) and s.conversionCost(fa.elem, ta.elem) == 0) 0 else null, .array => |ta| if ((ta.len == fa.len or ta.len == 0) and s.conversionCost(fa.elem, ta.elem) == 0) 0 else null,
@ -3730,18 +3903,7 @@ pub const Sema = struct {
if (item.kind != .init_list) _ = try s.expr(item) else _ = try s.checkInitializer(TypeTable.error_type, item); if (item.kind != .init_list) _ = try s.expr(item) else _ = try s.checkInitializer(TypeTable.error_type, item);
} }
e.ty = target; e.ty = target;
if (target == TypeTable.error_type) return true; return s.checkInitCount(target, e);
const want = if (s.types.get(target) == .string) 1 else s.types.componentCount(target) orelse return true;
const have = s.flatCount(e);
if (have != want and have != 0) {
if (have < want) {
s.err(e.loc, "too few elements in vector initialization (expected {d} element{s}, have {d})", .{ want, if (want == 1) "" else "s", have });
} else {
s.err(e.loc, "too many elements in vector initialization (expected {d} element{s}, have {d})", .{ want, if (want == 1) "" else "s", have });
}
return false;
}
return true;
} }
const t = try s.expr(e); const t = try s.expr(e);
if (t.callee != null and t.ty == TypeTable.error_type) { if (t.callee != null and t.ty == TypeTable.error_type) {
@ -3757,6 +3919,23 @@ pub const Sema = struct {
return false; return false;
} }
/// An initializer list (its items typed) has as many components as
/// `target`.
fn checkInitCount(s: *Sema, target: TypeId, e: *ast.Expr) bool {
if (target == TypeTable.error_type) return true;
const want = if (s.types.get(target) == .string) 1 else s.types.componentCount(target) orelse return true;
const have = s.flatCount(e);
if (have != want and have != 0) {
if (have < want) {
s.err(e.loc, "too few elements in vector initialization (expected {d} element{s}, have {d})", .{ want, if (want == 1) "" else "s", have });
} else {
s.err(e.loc, "too many elements in vector initialization (expected {d} element{s}, have {d})", .{ want, if (want == 1) "" else "s", have });
}
return false;
}
return true;
}
/// dxc's err_hlsl_cannot_convert: "implicitly" only when an explicit /// dxc's err_hlsl_cannot_convert: "implicitly" only when an explicit
/// cast would work. /// cast would work.
fn convertError(s: *Sema, loc: Loc, from: TypeId, to: TypeId) void { fn convertError(s: *Sema, loc: Loc, from: TypeId, to: TypeId) void {

View File

@ -97,6 +97,45 @@ pub const Scalar = enum(u8) {
}; };
} }
/// The cost of converting a component from `a` to `b` in overload
/// resolution (lower is better), ordered as dxc ranks them: a literal to
/// its own kind, widening within a kind, then a change of sign, then
/// integer to bool, then narrowing or a change of kind, and integer to
/// float last.
pub fn conversionCost(a: Scalar, b: Scalar) u32 {
if (a == b) return 0;
const l = a.props();
const r = b.props();
if (a.isLiteral()) {
// (An integer literal takes bool before float.)
if (r.p.floating == l.p.floating and b != .bool) return if (r.p.min_precision) 5 else 4;
return if (b == .bool and !l.p.floating) 6 else 7;
}
if (l.p.floating and r.p.floating) {
if (r.bits < l.bits) return 12;
// `half` (32-bit, partial precision) ranks after float.
return if (r.p.partial_precision) 9 else 8;
}
if (a.isInt() and b.isInt()) {
const same_sign = l.p.unsigned == r.p.unsigned;
if (r.bits < l.bits) return if (same_sign and !l.p.unsigned) 10 else 12;
if (same_sign) return 8;
// A change of sign: to signed best at the same width, to
// unsigned best wider.
return if ((r.bits == l.bits) == l.p.unsigned) 9 else 10;
}
// (From 64 bits, bool ranks with the narrowing to 32.)
if (a.isInt() and b == .bool) return if (l.bits <= 32) 11 else if (l.p.unsigned) 12 else 10;
if (a.isInt() and r.p.floating) return 13;
return 12;
}
/// An overload candidate's cost from its arguments' conversion costs:
/// dxc ranks candidates by their worst conversion, then by all of them.
pub fn overloadCost(worst: u32, sum: u32) u32 {
return worst << 16 | @min(sum, 0xffff);
}
/// The component type of a binary operation on `a` and `b`: a port of /// The component type of a binary operation on `a` and `b`: a port of
/// dxc's CombineBasicTypes. /// dxc's CombineBasicTypes.
pub fn combine(a: Scalar, b: Scalar) Scalar { pub fn combine(a: Scalar, b: Scalar) Scalar {