dxil: smaller code, as dxc's optimizer makes it
Unreal's 11,488 compiles came out 1.7 times dxc's DXIL; now 1.09. - cfg.zig: blocks that only branch to a block with no other predecessor take it in; blocks holding only a branch are bypassed; if/else arms with up to two cheap instructions become selects (dxc's simplifycfg); a branch or switch going one way everywhere goes there. - cse.zig: repeated computations over the dominator tree (arithmetic, readnone dx.ops, cbuffer loads, handles), as EarlyCSE and GVN. - promote: floating-point constants folded (arithmetic, FAbs, Saturate, rounding, Sqrt, min/max), `zext i1 != 0`, `and` by known-zero bits, and compares of selects and phis of constants (`(c ? 2 : 1) == 3`). - [unroll] loops: their back edge is marked for the unroller, which unrolls them up to dxc's 1024 iterations whatever their size. - -Od promotes locals and removes dead code, as dxc's does: 14 times dxc's size before, 0.89 now. Every compile validates with Unreal's validator 1.8. Compile time over the corpus: 584 s summed, 539 before.
This commit is contained in:
parent
e4cf1caaf2
commit
ddefd450f7
|
|
@ -19,7 +19,7 @@ a file or, through the library interfaces, from memory.
|
||||||
| `-P` | Preprocess instead of compiling. |
|
| `-P` | Preprocess instead of compiling. |
|
||||||
| `-spirv` | Emit SPIR-V instead of DXIL. |
|
| `-spirv` | Emit SPIR-V instead of DXIL. |
|
||||||
| `-Zpr` / `-Zpc` | Select row- or column-major matrix packing. |
|
| `-Zpr` / `-Zpc` | Select row- or column-major matrix packing. |
|
||||||
| `-O0` … `-O3`, `-Od` | Select the optimization level. |
|
| `-O0` … `-O3`, `-Od` | Select the optimization level. `-Od`, as in dxc, still promotes locals to SSA values and removes dead code, but does nothing else. |
|
||||||
| `--job=<file>` | Compile a JSON batch of shaders in one process. |
|
| `--job=<file>` | Compile a JSON batch of shaders in one process. |
|
||||||
|
|
||||||
DXIL is the default backend. Add `-spirv` for SPIR-V, with the `-fvk-*` and
|
DXIL is the default backend. Add `-spirv` for SPIR-V, with the `-fvk-*` and
|
||||||
|
|
|
||||||
|
|
@ -563,7 +563,7 @@ fn run(ctx: *Ctx, arena: std.mem.Allocator) !void {
|
||||||
m.entries.items[0].root_signature = try rootSignatureMacroText(ctx, arena, opts, input, macro) orelse return error.CompileFailed;
|
m.entries.items[0].root_signature = try rootSignatureMacroText(ctx, arena, opts, input, macro) orelse return error.CompileFailed;
|
||||||
};
|
};
|
||||||
const zd = stats.begin(.dxil);
|
const zd = stats.begin(.dxil);
|
||||||
const dxil_out = zdxc.dxil.emit.emitWithReflection(arena, m, profile.?, &diags, !opts.no_opt and opts.opt_level != .od) catch |err| switch (err) {
|
const dxil_out = zdxc.dxil.emit.emitWithReflectionAt(arena, m, profile.?, &diags, if (opts.no_opt) .none else if (opts.opt_level == .od) .debug else .full) catch |err| switch (err) {
|
||||||
error.Unsupported => {
|
error.Unsupported => {
|
||||||
try diags.render(&sm, ctx.stderr, .{ .format = opts.diag_format, .color = false });
|
try diags.render(&sm, ctx.stderr, .{ .format = opts.diag_format, .color = false });
|
||||||
return error.CompileFailed;
|
return error.CompileFailed;
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,497 @@
|
||||||
|
//! Control-flow cleanup, as dxc's simplifycfg does it: a block that only
|
||||||
|
//! branches to a block with no other predecessor takes that block in, and
|
||||||
|
//! a block holding nothing but an unconditional branch is bypassed (its
|
||||||
|
//! predecessors branch straight to its successor). Lowering gives every
|
||||||
|
//! statement, scope and inlined call its own blocks, and the optimizer
|
||||||
|
//! empties many more; without this they stay as chains of branches.
|
||||||
|
//!
|
||||||
|
//! Run on a function in SSA form, after promotion (which drops the blocks
|
||||||
|
//! no path reaches).
|
||||||
|
|
||||||
|
const std = @import("std");
|
||||||
|
const Allocator = std.mem.Allocator;
|
||||||
|
const module = @import("module.zig");
|
||||||
|
const promote = @import("promote.zig");
|
||||||
|
const stats = @import("../stats.zig");
|
||||||
|
|
||||||
|
const Value = module.Value;
|
||||||
|
const Inst = module.Inst;
|
||||||
|
|
||||||
|
const none = std.math.maxInt(u32);
|
||||||
|
|
||||||
|
const Edge = @typeInfo(@FieldType(@FieldType(@FieldType(Inst, "op"), "phi"), "incoming")).pointer.child;
|
||||||
|
const Case = @typeInfo(@FieldType(@FieldType(@FieldType(Inst, "op"), "switch"), "cases")).pointer.child;
|
||||||
|
|
||||||
|
fn isTerminator(inst: Inst) bool {
|
||||||
|
return switch (inst.op) {
|
||||||
|
.ret, .br, .@"switch", .@"unreachable" => true,
|
||||||
|
else => false,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Most cost of the instructions one arm of an if may hoist above its
|
||||||
|
/// branch to become a select (LLVM's phi-node-folding-threshold, as in
|
||||||
|
/// dxc).
|
||||||
|
const max_arm_cost = 2;
|
||||||
|
|
||||||
|
const State = struct {
|
||||||
|
a: Allocator,
|
||||||
|
m: *const module.Module,
|
||||||
|
insts: []Inst,
|
||||||
|
/// Each block's instructions (old indices), its terminator last.
|
||||||
|
body: []std.ArrayList(u32),
|
||||||
|
/// Predecessor edges (a block twice if it branches here twice).
|
||||||
|
preds: []std.ArrayList(u32),
|
||||||
|
/// The block that now holds a merged block's terminator: phis naming
|
||||||
|
/// the merged block mean it.
|
||||||
|
owner: []u32,
|
||||||
|
alive: []bool,
|
||||||
|
/// Phis replaced by their one input.
|
||||||
|
repl: []?Value,
|
||||||
|
|
||||||
|
fn find(s: *State, b: u32) u32 {
|
||||||
|
var x = b;
|
||||||
|
while (s.owner[x] != x) x = s.owner[x];
|
||||||
|
var y = b;
|
||||||
|
while (s.owner[y] != x) {
|
||||||
|
const next = s.owner[y];
|
||||||
|
s.owner[y] = x;
|
||||||
|
y = next;
|
||||||
|
}
|
||||||
|
return x;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn term(s: *State, b: u32) *Inst {
|
||||||
|
const items = s.body[b].items;
|
||||||
|
return &s.insts[items[items.len - 1]];
|
||||||
|
}
|
||||||
|
|
||||||
|
fn hasPhis(s: *State, b: u32) bool {
|
||||||
|
return s.insts[s.body[b].items[0]].op == .phi;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn removePred(s: *State, b: u32, p: u32) void {
|
||||||
|
const l = &s.preds[b];
|
||||||
|
for (l.items, 0..) |x, k| if (x == p) {
|
||||||
|
_ = l.swapRemove(k);
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
fn renamePred(s: *State, x: u32, from: u32, to: u32) void {
|
||||||
|
for (s.preds[x].items) |*p| {
|
||||||
|
if (p.* == from) p.* = to;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn countPred(s: *State, b: u32, p: u32) u32 {
|
||||||
|
var c: u32 = 0;
|
||||||
|
for (s.preds[b].items) |x| c += @intFromBool(x == p);
|
||||||
|
return c;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `b` (unconditional branch to `c`, `c`'s only predecessor) takes in
|
||||||
|
/// `c`.
|
||||||
|
fn merge(s: *State, b: u32, c: u32) Allocator.Error!void {
|
||||||
|
const cb = s.body[c].items;
|
||||||
|
var k: usize = 0;
|
||||||
|
while (k < cb.len and s.insts[cb[k]].op == .phi) : (k += 1) {
|
||||||
|
s.repl[cb[k]] = s.insts[cb[k]].op.phi.incoming[0].val;
|
||||||
|
}
|
||||||
|
const bb = &s.body[b];
|
||||||
|
_ = bb.pop();
|
||||||
|
try bb.appendSlice(s.a, cb[k..]);
|
||||||
|
s.alive[c] = false;
|
||||||
|
s.owner[c] = b;
|
||||||
|
// (`c`'s successors now have `b` for a predecessor.)
|
||||||
|
switch (s.term(b).op) {
|
||||||
|
.br => |br| {
|
||||||
|
s.renamePred(br.then, c, b);
|
||||||
|
if (br.@"else") |e| s.renamePred(e, c, b);
|
||||||
|
},
|
||||||
|
.@"switch" => |sw| {
|
||||||
|
s.renamePred(sw.default, c, b);
|
||||||
|
for (sw.cases) |x| s.renamePred(x.block, c, b);
|
||||||
|
},
|
||||||
|
else => {},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Retargets `p`'s edges to `b` at `c`.
|
||||||
|
fn retarget(s: *State, p: u32, b: u32, c: u32) Allocator.Error!void {
|
||||||
|
const t = s.term(p);
|
||||||
|
switch (t.op) {
|
||||||
|
.br => |*br| {
|
||||||
|
if (br.then == b) br.then = c;
|
||||||
|
if (br.@"else") |*e| if (e.* == b) {
|
||||||
|
e.* = c;
|
||||||
|
};
|
||||||
|
},
|
||||||
|
.@"switch" => |*sw| {
|
||||||
|
if (sw.default == b) sw.default = c;
|
||||||
|
const cs = try s.a.dupe(Case, sw.cases);
|
||||||
|
for (cs) |*x| if (x.block == b) {
|
||||||
|
x.block = c;
|
||||||
|
};
|
||||||
|
sw.cases = cs;
|
||||||
|
},
|
||||||
|
else => unreachable,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// True if `b` is cheap instructions safe to run on either path (see
|
||||||
|
/// cost) and `br m`, and only `p` branches to it.
|
||||||
|
fn armFrom(s: *State, b: u32, p: u32, m: u32) bool {
|
||||||
|
if (s.preds[b].items.len != 1 or s.preds[b].items[0] != p) return false;
|
||||||
|
const t = s.term(b).op;
|
||||||
|
if (t != .br or t.br.@"else" != null or t.br.then != m) return false;
|
||||||
|
const items = s.body[b].items;
|
||||||
|
var total: u32 = 0;
|
||||||
|
for (items[0 .. items.len - 1]) |i| {
|
||||||
|
total += s.cost(s.insts[i]) orelse return false;
|
||||||
|
if (total > max_arm_cost) return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What hoisting `inst` above a branch costs, or null if it cannot
|
||||||
|
/// be: it has an effect, may trap (integer division), or reads memory.
|
||||||
|
fn cost(s: *State, inst: Inst) ?u32 {
|
||||||
|
return switch (inst.op) {
|
||||||
|
.binop => |b| switch (b.op) {
|
||||||
|
.udiv, .sdiv, .urem, .srem => if (s.m.types.items[inst.ty] == .int) null else 1,
|
||||||
|
else => 1,
|
||||||
|
},
|
||||||
|
.cast => |c| if (c.op == .bitcast) 0 else 1,
|
||||||
|
.cmp, .select, .extractvalue, .extractelement, .insertelement => 1,
|
||||||
|
else => null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The instructions of `b` before its terminator, moved to the end of
|
||||||
|
/// `p` (before its terminator).
|
||||||
|
fn hoist(s: *State, b: u32, p: u32) Allocator.Error!void {
|
||||||
|
const from = s.body[b].items;
|
||||||
|
if (from.len < 2) return;
|
||||||
|
const to = &s.body[p];
|
||||||
|
const t = to.pop().?;
|
||||||
|
try to.appendSlice(s.a, from[0 .. from.len - 1]);
|
||||||
|
try to.append(s.a, t);
|
||||||
|
from[0] = from[from.len - 1];
|
||||||
|
s.body[b].shrinkRetainingCapacity(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A branch to one block every way goes there unconditionally; the
|
||||||
|
/// phis there keep one input from it.
|
||||||
|
fn collapse(s: *State, b: u32) Allocator.Error!bool {
|
||||||
|
const t = s.term(b);
|
||||||
|
const target: u32 = switch (t.op) {
|
||||||
|
.br => |br| if (br.@"else") |e| (if (e == br.then) e else return false) else return false,
|
||||||
|
.@"switch" => |sw| blk: {
|
||||||
|
for (sw.cases) |c| if (c.block != sw.default) return false;
|
||||||
|
break :blk sw.default;
|
||||||
|
},
|
||||||
|
else => return false,
|
||||||
|
};
|
||||||
|
t.op = .{ .br = .{ .then = target } };
|
||||||
|
while (s.countPred(target, b) > 1) s.removePred(target, b);
|
||||||
|
const cb = s.body[target].items;
|
||||||
|
var k: usize = 0;
|
||||||
|
while (k < cb.len and s.insts[cb[k]].op == .phi) : (k += 1) {
|
||||||
|
const phi = &s.insts[cb[k]].op.phi;
|
||||||
|
var out: std.ArrayList(Edge) = .empty;
|
||||||
|
var seen = false;
|
||||||
|
for (phi.incoming) |in| {
|
||||||
|
if (s.find(in.block) == b) {
|
||||||
|
if (seen) continue;
|
||||||
|
seen = true;
|
||||||
|
}
|
||||||
|
try out.append(s.a, in);
|
||||||
|
}
|
||||||
|
phi.incoming = out.items;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `m`'s two predecessors: a conditional branch and a block it
|
||||||
|
/// branches to (a triangle), or two blocks one conditional
|
||||||
|
/// branch picks between (a diamond). `m`'s phis become selects on the
|
||||||
|
/// branch's condition, and the branch goes straight to `m` (dxc's
|
||||||
|
/// simplifycfg folds two-entry phis so). True if done.
|
||||||
|
fn ifConvert(s: *State, m: u32) Allocator.Error!bool {
|
||||||
|
const ps = s.preds[m].items;
|
||||||
|
if (ps.len != 2 or ps[0] == ps[1]) return false;
|
||||||
|
// The branching block, and the block each of its arms reaches `m`
|
||||||
|
// from.
|
||||||
|
var p: u32 = none;
|
||||||
|
var via: [2]u32 = undefined;
|
||||||
|
for (0..2) |k| {
|
||||||
|
const q = ps[k];
|
||||||
|
const other = ps[1 - k];
|
||||||
|
const t = s.term(q).op;
|
||||||
|
if (q == m or t != .br) continue;
|
||||||
|
const e = t.br.@"else" orelse continue;
|
||||||
|
if (t.br.then == m and e == other and s.armFrom(other, q, m)) {
|
||||||
|
p = q;
|
||||||
|
via = .{ q, other };
|
||||||
|
} else if (e == m and t.br.then == other and s.armFrom(other, q, m)) {
|
||||||
|
p = q;
|
||||||
|
via = .{ other, q };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (p == none) {
|
||||||
|
// A diamond: both predecessors empty, from one branch.
|
||||||
|
if (s.preds[ps[0]].items.len != 1) return false;
|
||||||
|
const q = s.preds[ps[0]].items[0];
|
||||||
|
if (q == m or !s.armFrom(ps[0], q, m) or !s.armFrom(ps[1], q, m)) return false;
|
||||||
|
const t = s.term(q).op;
|
||||||
|
if (t != .br) return false;
|
||||||
|
const e = t.br.@"else" orelse return false;
|
||||||
|
if (t.br.then == ps[0] and e == ps[1]) {
|
||||||
|
via = .{ ps[0], ps[1] };
|
||||||
|
} else if (t.br.then == ps[1] and e == ps[0]) {
|
||||||
|
via = .{ ps[1], ps[0] };
|
||||||
|
} else return false;
|
||||||
|
p = q;
|
||||||
|
}
|
||||||
|
const cond = s.term(p).op.br.cond.?;
|
||||||
|
const mb = s.body[m].items;
|
||||||
|
var k: usize = 0;
|
||||||
|
while (k < mb.len and s.insts[mb[k]].op == .phi) : (k += 1) {
|
||||||
|
const inst = &s.insts[mb[k]];
|
||||||
|
var vals: [2]?Value = .{ null, null };
|
||||||
|
for (inst.op.phi.incoming) |in| {
|
||||||
|
const from = s.find(in.block);
|
||||||
|
if (from == via[0]) vals[0] = in.val else if (from == via[1]) vals[1] = in.val;
|
||||||
|
}
|
||||||
|
if (vals[0] == null or vals[1] == null) return false;
|
||||||
|
}
|
||||||
|
k = 0;
|
||||||
|
while (k < mb.len and s.insts[mb[k]].op == .phi) : (k += 1) {
|
||||||
|
const inst = &s.insts[mb[k]];
|
||||||
|
var vals: [2]Value = undefined;
|
||||||
|
for (inst.op.phi.incoming) |in| {
|
||||||
|
const from = s.find(in.block);
|
||||||
|
if (from == via[0]) vals[0] = in.val else if (from == via[1]) vals[1] = in.val;
|
||||||
|
}
|
||||||
|
if (std.meta.eql(vals[0], vals[1])) {
|
||||||
|
s.repl[mb[k]] = vals[0];
|
||||||
|
} else inst.op = .{ .select = .{ .cond = cond, .t = vals[0], .f = vals[1] } };
|
||||||
|
}
|
||||||
|
// `p` goes to `m`, running what the arms did first; their blocks
|
||||||
|
// go.
|
||||||
|
for (via) |v| if (v != p) try s.hoist(v, p);
|
||||||
|
s.term(p).op = .{ .br = .{ .then = m } };
|
||||||
|
for (via) |v| if (v != p) {
|
||||||
|
s.alive[v] = false;
|
||||||
|
s.preds[v].clearRetainingCapacity();
|
||||||
|
};
|
||||||
|
s.preds[m].clearRetainingCapacity();
|
||||||
|
try s.preds[m].append(s.a, p);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Bypasses `b` (only `br c`): its predecessors branch to `c`.
|
||||||
|
fn bypass(s: *State, b: u32, c: u32) Allocator.Error!void {
|
||||||
|
const ps = try s.a.dupe(u32, s.preds[b].items);
|
||||||
|
const phis = s.hasPhis(c);
|
||||||
|
// `c`'s phis: the input from `b` comes from each of `b`'s
|
||||||
|
// predecessors instead.
|
||||||
|
const cb = s.body[c].items;
|
||||||
|
var k: usize = 0;
|
||||||
|
while (k < cb.len and s.insts[cb[k]].op == .phi) : (k += 1) {
|
||||||
|
const phi = &s.insts[cb[k]].op.phi;
|
||||||
|
var out: std.ArrayList(Edge) = .empty;
|
||||||
|
try out.ensureTotalCapacity(s.a, phi.incoming.len + ps.len);
|
||||||
|
for (phi.incoming) |in| {
|
||||||
|
if (s.find(in.block) == b) {
|
||||||
|
for (ps) |p| out.appendAssumeCapacity(.{ .val = in.val, .block = p });
|
||||||
|
} else out.appendAssumeCapacity(in);
|
||||||
|
}
|
||||||
|
phi.incoming = out.items;
|
||||||
|
}
|
||||||
|
// (Each distinct predecessor once: retarget moves all its edges.)
|
||||||
|
for (ps, 0..) |p, i| {
|
||||||
|
if (std.mem.indexOfScalar(u32, ps[0..i], p) != null) continue;
|
||||||
|
try s.retarget(p, b, c);
|
||||||
|
}
|
||||||
|
s.removePred(c, b);
|
||||||
|
try s.preds[c].appendSlice(s.a, ps);
|
||||||
|
s.preds[b].clearRetainingCapacity();
|
||||||
|
s.alive[b] = false;
|
||||||
|
// A conditional branch now going to `c` both ways goes there
|
||||||
|
// unconditionally (when `c` has no phis to give two inputs).
|
||||||
|
if (!phis) for (ps) |p| {
|
||||||
|
const t = s.term(p);
|
||||||
|
if (t.op == .br) if (t.op.br.@"else") |e| if (e == t.op.br.then) {
|
||||||
|
t.op.br = .{ .then = e };
|
||||||
|
s.removePred(c, p);
|
||||||
|
};
|
||||||
|
};
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Simplifies `func`'s control flow; true if anything changed.
|
||||||
|
pub fn run(a: Allocator, m: *module.Module, func: u32) Allocator.Error!bool {
|
||||||
|
const zone = stats.begin(.cfg);
|
||||||
|
defer zone.end();
|
||||||
|
const f = &m.functions.items[func];
|
||||||
|
const nb = f.num_blocks;
|
||||||
|
const n: u32 = @intCast(f.insts.items.len);
|
||||||
|
if (nb < 2) return false;
|
||||||
|
|
||||||
|
var s: State = .{
|
||||||
|
.a = a,
|
||||||
|
.m = m,
|
||||||
|
.insts = try a.dupe(Inst, f.insts.items),
|
||||||
|
.body = try a.alloc(std.ArrayList(u32), nb),
|
||||||
|
.preds = try a.alloc(std.ArrayList(u32), nb),
|
||||||
|
.owner = try a.alloc(u32, nb),
|
||||||
|
.alive = try a.alloc(bool, nb),
|
||||||
|
.repl = try a.alloc(?Value, n),
|
||||||
|
};
|
||||||
|
@memset(s.repl, null);
|
||||||
|
@memset(s.alive, true);
|
||||||
|
for (s.owner, 0..) |*o, b| o.* = @intCast(b);
|
||||||
|
{
|
||||||
|
var b: u32 = 0;
|
||||||
|
var start: u32 = 0;
|
||||||
|
for (s.insts, 0..) |inst, i| {
|
||||||
|
if (!isTerminator(inst)) continue;
|
||||||
|
if (b >= nb) return false; // not the block layout expected
|
||||||
|
s.body[b] = .empty;
|
||||||
|
try s.body[b].ensureTotalCapacity(a, i + 1 - start);
|
||||||
|
for (start..i + 1) |k| s.body[b].appendAssumeCapacity(@intCast(k));
|
||||||
|
start = @intCast(i + 1);
|
||||||
|
b += 1;
|
||||||
|
}
|
||||||
|
if (b != nb or start != n) return false;
|
||||||
|
}
|
||||||
|
for (s.preds) |*p| p.* = .empty;
|
||||||
|
for (0..nb) |b| {
|
||||||
|
const t = s.term(@intCast(b)).*;
|
||||||
|
switch (t.op) {
|
||||||
|
.br => |br| {
|
||||||
|
try s.preds[br.then].append(a, @intCast(b));
|
||||||
|
if (br.@"else") |e| try s.preds[e].append(a, @intCast(b));
|
||||||
|
},
|
||||||
|
.@"switch" => |sw| {
|
||||||
|
try s.preds[sw.default].append(a, @intCast(b));
|
||||||
|
for (sw.cases) |c| try s.preds[c.block].append(a, @intCast(b));
|
||||||
|
},
|
||||||
|
else => {},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var changed = false;
|
||||||
|
var again = true;
|
||||||
|
while (again) {
|
||||||
|
again = false;
|
||||||
|
for (0..nb) |bi| {
|
||||||
|
const b: u32 = @intCast(bi);
|
||||||
|
if (!s.alive[b]) continue;
|
||||||
|
// Take in the chain of blocks only `b` leads to.
|
||||||
|
while (true) {
|
||||||
|
const t = s.term(b).*;
|
||||||
|
if (t.op != .br or t.op.br.@"else" != null) break;
|
||||||
|
const c = t.op.br.then;
|
||||||
|
if (c == b or c == 0 or s.preds[c].items.len != 1) break;
|
||||||
|
try s.merge(b, c);
|
||||||
|
changed = true;
|
||||||
|
again = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (1..nb) |bi| {
|
||||||
|
const b: u32 = @intCast(bi);
|
||||||
|
if (!s.alive[b] or s.body[b].items.len != 1) continue;
|
||||||
|
const t = s.term(b).*;
|
||||||
|
if (t.op != .br or t.op.br.@"else" != null) continue;
|
||||||
|
const c = t.op.br.then;
|
||||||
|
const ps = s.preds[b].items;
|
||||||
|
if (c == b or ps.len == 0) continue;
|
||||||
|
if (std.mem.indexOfScalar(u32, ps, b) != null) continue;
|
||||||
|
// With phis in `c`, a predecessor already branching there could
|
||||||
|
// need two values on one edge: left alone.
|
||||||
|
if (s.hasPhis(c)) {
|
||||||
|
const clash = for (ps) |p| {
|
||||||
|
if (s.countPred(c, p) != 0) break true;
|
||||||
|
} else false;
|
||||||
|
if (clash) continue;
|
||||||
|
}
|
||||||
|
try s.bypass(b, c);
|
||||||
|
changed = true;
|
||||||
|
again = true;
|
||||||
|
}
|
||||||
|
for (0..nb) |bi| {
|
||||||
|
const b: u32 = @intCast(bi);
|
||||||
|
if (!s.alive[b] or !try s.collapse(b)) continue;
|
||||||
|
changed = true;
|
||||||
|
again = true;
|
||||||
|
}
|
||||||
|
for (1..nb) |bi| {
|
||||||
|
const b: u32 = @intCast(bi);
|
||||||
|
if (!s.alive[b] or !try s.ifConvert(b)) continue;
|
||||||
|
changed = true;
|
||||||
|
again = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!changed) return false;
|
||||||
|
|
||||||
|
// Lay the blocks out again, in their old order, and renumber.
|
||||||
|
const new_block = try a.alloc(u32, nb);
|
||||||
|
var kept: u32 = 0;
|
||||||
|
for (0..nb) |b| {
|
||||||
|
new_block[b] = if (s.alive[b]) kept else none;
|
||||||
|
if (s.alive[b]) kept += 1;
|
||||||
|
}
|
||||||
|
const index = try a.alloc(u32, n);
|
||||||
|
@memset(index, none);
|
||||||
|
var count: u32 = 0;
|
||||||
|
for (0..nb) |b| if (s.alive[b]) for (s.body[b].items) |i| {
|
||||||
|
if (s.repl[i] != null) continue;
|
||||||
|
index[i] = count;
|
||||||
|
count += 1;
|
||||||
|
};
|
||||||
|
const Map = struct {
|
||||||
|
repl: []const ?Value,
|
||||||
|
index: []const u32,
|
||||||
|
pub fn visit(ctx: *@This(), v: Value, _: promote.Role) Value {
|
||||||
|
var x = v;
|
||||||
|
while (x == .inst) {
|
||||||
|
const r = ctx.repl[x.inst] orelse break;
|
||||||
|
x = r;
|
||||||
|
}
|
||||||
|
return if (x == .inst) .{ .inst = ctx.index[x.inst] } else x;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
var map: Map = .{ .repl = s.repl, .index = index };
|
||||||
|
const ma = m.allocator();
|
||||||
|
var out: std.ArrayList(Inst) = .empty;
|
||||||
|
try out.ensureTotalCapacityPrecise(ma, count);
|
||||||
|
for (0..nb) |b| if (s.alive[b]) for (s.body[b].items) |i| {
|
||||||
|
if (s.repl[i] != null) continue;
|
||||||
|
var inst = s.insts[i];
|
||||||
|
try promote.operands(true, ma, &inst, &map);
|
||||||
|
switch (inst.op) {
|
||||||
|
.phi => |*p| {
|
||||||
|
const es: []Edge = @constCast(p.incoming);
|
||||||
|
for (es) |*e| e.block = new_block[s.find(e.block)];
|
||||||
|
},
|
||||||
|
.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(Case, 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);
|
||||||
|
};
|
||||||
|
f.insts = out;
|
||||||
|
f.num_blocks = kept;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,325 @@
|
||||||
|
//! Common subexpression elimination over the dominator tree, as dxc's
|
||||||
|
//! EarlyCSE and GVN do it: an instruction that computes what one in a
|
||||||
|
//! dominating position already computed (same operation, same operands)
|
||||||
|
//! is replaced by it. Only instructions without effects and whose result
|
||||||
|
//! depends on nothing but their operands: arithmetic, comparisons, casts,
|
||||||
|
//! selects, address computations, readnone dx.op calls, and the readonly
|
||||||
|
//! ones that read what cannot change during the shader (constant buffer
|
||||||
|
//! loads, handle creation).
|
||||||
|
//!
|
||||||
|
//! Inlining every call and lowering each use of a cbuffer field to its own
|
||||||
|
//! load leaves many such repeats.
|
||||||
|
|
||||||
|
const std = @import("std");
|
||||||
|
const Allocator = std.mem.Allocator;
|
||||||
|
const module = @import("module.zig");
|
||||||
|
const promote = @import("promote.zig");
|
||||||
|
const stats = @import("../stats.zig");
|
||||||
|
|
||||||
|
const Value = module.Value;
|
||||||
|
const Inst = module.Inst;
|
||||||
|
|
||||||
|
const none = std.math.maxInt(u32);
|
||||||
|
|
||||||
|
fn isTerminator(inst: Inst) bool {
|
||||||
|
return switch (inst.op) {
|
||||||
|
.ret, .br, .@"switch", .@"unreachable" => true,
|
||||||
|
else => false,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// dx.op readonly operations that read only what a dispatch cannot change:
|
||||||
|
/// CreateHandle, CBufferLoad, CBufferLoadLegacy, CreateHandleForLib,
|
||||||
|
/// CreateHandleFromBinding, CreateHandleFromHeap.
|
||||||
|
fn stableReadonly(opcode: i64) bool {
|
||||||
|
return switch (opcode) {
|
||||||
|
57, 58, 59, 160, 217, 218 => true,
|
||||||
|
else => false,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
fn eligible(m: *const module.Module, inst: Inst) bool {
|
||||||
|
return switch (inst.op) {
|
||||||
|
.binop, .cast, .cmp, .select, .extractvalue, .gep, .extractelement, .insertelement => true,
|
||||||
|
.call => |c| {
|
||||||
|
const callee = m.functions.items[c.callee];
|
||||||
|
if (callee.num_blocks != 0 or !std.mem.startsWith(u8, callee.name, "dx.op.")) return false;
|
||||||
|
switch (callee.attrs) {
|
||||||
|
.nounwind_readnone => return true,
|
||||||
|
.nounwind_readonly => {
|
||||||
|
if (c.args.len == 0 or c.args[0] != .constant) return false;
|
||||||
|
return switch (m.constants.items[c.args[0].constant].kind) {
|
||||||
|
.int => |k| stableReadonly(k),
|
||||||
|
else => false,
|
||||||
|
};
|
||||||
|
},
|
||||||
|
else => return false,
|
||||||
|
}
|
||||||
|
},
|
||||||
|
else => false,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An instruction's identity as bytes: its operation, type, the fields
|
||||||
|
/// that are not operands, and its operands (resolved through replaced
|
||||||
|
/// instructions).
|
||||||
|
const Key = struct {
|
||||||
|
buf: std.ArrayList(u8) = .empty,
|
||||||
|
a: Allocator,
|
||||||
|
repl: []const ?Value,
|
||||||
|
failed: bool = false,
|
||||||
|
|
||||||
|
fn resolve(k: *const Key, v: Value) Value {
|
||||||
|
var x = v;
|
||||||
|
while (x == .inst) {
|
||||||
|
const r = k.repl[x.inst] orelse break;
|
||||||
|
x = r;
|
||||||
|
}
|
||||||
|
return x;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn word(k: *Key, w: u64) void {
|
||||||
|
k.buf.appendSlice(k.a, std.mem.asBytes(&w)) catch {
|
||||||
|
k.failed = true;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn visit(k: *Key, v: Value, _: promote.Role) Value {
|
||||||
|
const x = k.resolve(v);
|
||||||
|
const tag: u64 = @backingInt(std.meta.activeTag(x));
|
||||||
|
const id: u64 = switch (x) {
|
||||||
|
inline else => |i| i,
|
||||||
|
};
|
||||||
|
k.word(tag << 32 | id);
|
||||||
|
return v;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn build(k: *Key, inst: Inst) Allocator.Error![]const u8 {
|
||||||
|
k.buf.clearRetainingCapacity();
|
||||||
|
k.word(@backingInt(std.meta.activeTag(inst.op)));
|
||||||
|
k.word(inst.ty);
|
||||||
|
switch (inst.op) {
|
||||||
|
.binop => |b| k.word(@as(u64, @backingInt(b.op)) << 32 | b.flags),
|
||||||
|
.cast => |c| k.word(@backingInt(c.op)),
|
||||||
|
.cmp => |c| k.word(c.pred),
|
||||||
|
.extractvalue => |x| k.word(x.index),
|
||||||
|
.gep => |g| k.word(g.elem),
|
||||||
|
.call => |c| k.word(c.callee),
|
||||||
|
else => {},
|
||||||
|
}
|
||||||
|
var copy = inst;
|
||||||
|
try promote.operands(false, k.a, ©, k);
|
||||||
|
if (k.failed) return error.OutOfMemory;
|
||||||
|
return k.buf.items;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Replaces `func`'s repeated computations; true if any.
|
||||||
|
pub fn run(a: Allocator, m: *module.Module, func: u32) Allocator.Error!bool {
|
||||||
|
const zone = stats.begin(.cse);
|
||||||
|
defer zone.end();
|
||||||
|
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);
|
||||||
|
{
|
||||||
|
var b: u32 = 0;
|
||||||
|
block_start[0] = 0;
|
||||||
|
for (insts, 0..) |inst, i| if (isTerminator(inst)) {
|
||||||
|
if (b >= nb) return false;
|
||||||
|
b += 1;
|
||||||
|
block_start[b] = @intCast(i + 1);
|
||||||
|
};
|
||||||
|
if (b != nb or block_start[nb] != n) return false;
|
||||||
|
}
|
||||||
|
// Successors, predecessors.
|
||||||
|
const succ_off = try a.alloc(u32, nb + 1);
|
||||||
|
var succs: std.ArrayList(u32) = .empty;
|
||||||
|
for (0..nb) |b| {
|
||||||
|
succ_off[b] = @intCast(succs.items.len);
|
||||||
|
switch (insts[block_start[b + 1] - 1].op) {
|
||||||
|
.br => |br| {
|
||||||
|
try succs.append(a, br.then);
|
||||||
|
if (br.@"else") |e| try succs.append(a, e);
|
||||||
|
},
|
||||||
|
.@"switch" => |sw| {
|
||||||
|
try succs.append(a, sw.default);
|
||||||
|
for (sw.cases) |c| try succs.append(a, c.block);
|
||||||
|
},
|
||||||
|
else => {},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
succ_off[nb] = @intCast(succs.items.len);
|
||||||
|
const pred_off = try a.alloc(u32, nb + 1);
|
||||||
|
@memset(pred_off, 0);
|
||||||
|
for (succs.items) |s| pred_off[s + 1] += 1;
|
||||||
|
for (1..nb + 1) |b| pred_off[b] += pred_off[b - 1];
|
||||||
|
const preds = try a.alloc(u32, succs.items.len);
|
||||||
|
{
|
||||||
|
const fill = try a.dupe(u32, pred_off[0..nb]);
|
||||||
|
for (0..nb) |b| for (succs.items[succ_off[b]..succ_off[b + 1]]) |s| {
|
||||||
|
preds[fill[s]] = @intCast(b);
|
||||||
|
fill[s] += 1;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
// Reverse postorder, then immediate dominators (Cooper, Harvey and
|
||||||
|
// Kennedy).
|
||||||
|
const rpo_index = try a.alloc(u32, nb);
|
||||||
|
@memset(rpo_index, none);
|
||||||
|
const rpo = try a.alloc(u32, nb);
|
||||||
|
var nr: u32 = 0;
|
||||||
|
{
|
||||||
|
const post = try a.alloc(u32, nb);
|
||||||
|
var np: u32 = 0;
|
||||||
|
const seen = try a.alloc(bool, nb);
|
||||||
|
@memset(seen, false);
|
||||||
|
const Frame = struct { b: u32, next: u32 };
|
||||||
|
var stack: std.ArrayList(Frame) = .empty;
|
||||||
|
try stack.append(a, .{ .b = 0, .next = succ_off[0] });
|
||||||
|
seen[0] = true;
|
||||||
|
while (stack.items.len > 0) {
|
||||||
|
const top = &stack.items[stack.items.len - 1];
|
||||||
|
if (top.next < succ_off[top.b + 1]) {
|
||||||
|
const s = succs.items[top.next];
|
||||||
|
top.next += 1;
|
||||||
|
if (!seen[s]) {
|
||||||
|
seen[s] = true;
|
||||||
|
try stack.append(a, .{ .b = s, .next = succ_off[s] });
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
post[np] = top.b;
|
||||||
|
np += 1;
|
||||||
|
_ = stack.pop();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (0..np) |k| {
|
||||||
|
rpo[k] = post[np - 1 - k];
|
||||||
|
rpo_index[rpo[k]] = @intCast(k);
|
||||||
|
}
|
||||||
|
nr = np;
|
||||||
|
}
|
||||||
|
const idom = try a.alloc(u32, nb);
|
||||||
|
@memset(idom, none);
|
||||||
|
idom[0] = 0;
|
||||||
|
{
|
||||||
|
var changed = true;
|
||||||
|
while (changed) {
|
||||||
|
changed = false;
|
||||||
|
for (rpo[1..nr]) |b| {
|
||||||
|
var new: u32 = none;
|
||||||
|
for (preds[pred_off[b]..pred_off[b + 1]]) |p| {
|
||||||
|
if (idom[p] == none) continue;
|
||||||
|
if (new == none) {
|
||||||
|
new = p;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
var x = p;
|
||||||
|
var y = new;
|
||||||
|
while (x != y) {
|
||||||
|
while (rpo_index[x] > rpo_index[y]) x = idom[x];
|
||||||
|
while (rpo_index[y] > rpo_index[x]) y = idom[y];
|
||||||
|
}
|
||||||
|
new = x;
|
||||||
|
}
|
||||||
|
if (new != idom[b]) {
|
||||||
|
idom[b] = new;
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Dominator tree children, in reverse postorder.
|
||||||
|
const child_off = try a.alloc(u32, nb + 1);
|
||||||
|
@memset(child_off, 0);
|
||||||
|
for (rpo[1..nr]) |b| child_off[idom[b] + 1] += 1;
|
||||||
|
for (1..nb + 1) |b| child_off[b] += child_off[b - 1];
|
||||||
|
const children = try a.alloc(u32, if (nr > 0) nr - 1 else 0);
|
||||||
|
{
|
||||||
|
const fill = try a.dupe(u32, child_off[0..nb]);
|
||||||
|
for (rpo[1..nr]) |b| {
|
||||||
|
children[fill[idom[b]]] = b;
|
||||||
|
fill[idom[b]] += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const repl = try a.alloc(?Value, n);
|
||||||
|
@memset(repl, null);
|
||||||
|
// The keys of the instructions available (in the dominating blocks),
|
||||||
|
// to the instruction.
|
||||||
|
var table: std.StringHashMapUnmanaged(u32) = .empty;
|
||||||
|
var added: std.ArrayList([]const u8) = .empty;
|
||||||
|
var key: Key = .{ .a = a, .repl = repl };
|
||||||
|
var found = false;
|
||||||
|
|
||||||
|
const Frame = struct { b: u32, next: u32, mark: usize };
|
||||||
|
var stack: std.ArrayList(Frame) = .empty;
|
||||||
|
try stack.append(a, .{ .b = 0, .next = child_off[0], .mark = 0 });
|
||||||
|
var entered = true;
|
||||||
|
while (stack.items.len > 0) {
|
||||||
|
const top = &stack.items[stack.items.len - 1];
|
||||||
|
if (entered) {
|
||||||
|
entered = false;
|
||||||
|
top.mark = added.items.len;
|
||||||
|
for (block_start[top.b]..block_start[top.b + 1]) |i| {
|
||||||
|
const inst = insts[i];
|
||||||
|
if (!eligible(m, inst)) continue;
|
||||||
|
// (The key is built in one buffer, and kept only if new.)
|
||||||
|
const gop = try table.getOrPut(a, try key.build(inst));
|
||||||
|
if (gop.found_existing) {
|
||||||
|
repl[i] = .{ .inst = gop.value_ptr.* };
|
||||||
|
found = true;
|
||||||
|
} else {
|
||||||
|
gop.key_ptr.* = try a.dupe(u8, key.buf.items);
|
||||||
|
gop.value_ptr.* = @intCast(i);
|
||||||
|
try added.append(a, gop.key_ptr.*);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (top.next < child_off[top.b + 1]) {
|
||||||
|
const c = children[top.next];
|
||||||
|
top.next += 1;
|
||||||
|
try stack.append(a, .{ .b = c, .next = child_off[c], .mark = 0 });
|
||||||
|
entered = true;
|
||||||
|
} else {
|
||||||
|
for (added.items[top.mark..]) |k| _ = table.remove(k);
|
||||||
|
added.shrinkRetainingCapacity(top.mark);
|
||||||
|
_ = stack.pop();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!found) return false;
|
||||||
|
|
||||||
|
// Renumber without the replaced instructions.
|
||||||
|
const index = try a.alloc(u32, n);
|
||||||
|
var count: u32 = 0;
|
||||||
|
for (0..n) |i| {
|
||||||
|
index[i] = count;
|
||||||
|
if (repl[i] == null) count += 1;
|
||||||
|
}
|
||||||
|
const Map = struct {
|
||||||
|
repl: []const ?Value,
|
||||||
|
index: []const u32,
|
||||||
|
pub fn visit(ctx: *@This(), v: Value, _: promote.Role) Value {
|
||||||
|
var x = v;
|
||||||
|
while (x == .inst) {
|
||||||
|
const r = ctx.repl[x.inst] orelse break;
|
||||||
|
x = r;
|
||||||
|
}
|
||||||
|
return if (x == .inst) .{ .inst = ctx.index[x.inst] } else x;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
var map: Map = .{ .repl = repl, .index = index };
|
||||||
|
const ma = m.allocator();
|
||||||
|
var out: std.ArrayList(Inst) = .empty;
|
||||||
|
try out.ensureTotalCapacityPrecise(ma, count);
|
||||||
|
for (insts, 0..) |inst, i| {
|
||||||
|
if (repl[i] != null) continue;
|
||||||
|
var copy = inst;
|
||||||
|
try promote.operands(true, ma, ©, &map);
|
||||||
|
out.appendAssumeCapacity(copy);
|
||||||
|
}
|
||||||
|
f.insts = out;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
@ -28,6 +28,8 @@ const promote = @import("promote.zig");
|
||||||
const unroll = @import("unroll.zig");
|
const unroll = @import("unroll.zig");
|
||||||
const stats = @import("../stats.zig");
|
const stats = @import("../stats.zig");
|
||||||
const sccp = @import("sccp.zig");
|
const sccp = @import("sccp.zig");
|
||||||
|
const cfg = @import("cfg.zig");
|
||||||
|
const cse = @import("cse.zig");
|
||||||
const opt = @import("../ir/opt.zig");
|
const opt = @import("../ir/opt.zig");
|
||||||
|
|
||||||
const TypeId = types.TypeId;
|
const TypeId = types.TypeId;
|
||||||
|
|
@ -53,9 +55,18 @@ pub fn emit(gpa: Allocator, m: *const ir.Module, profile: shader.Profile, diags:
|
||||||
pub const Output = struct { object: []u8, reflection: []u8 };
|
pub const Output = struct { object: []u8, reflection: []u8 };
|
||||||
|
|
||||||
pub fn emitWithReflection(gpa: Allocator, m: *const ir.Module, profile: shader.Profile, diags: *diag.Diagnostics, optimize: bool) Error!Output {
|
pub fn emitWithReflection(gpa: Allocator, m: *const ir.Module, profile: shader.Profile, diags: *diag.Diagnostics, optimize: bool) Error!Output {
|
||||||
|
return emitWithReflectionAt(gpa, m, profile, diags, if (optimize) .full else .none);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How much `emitWithReflectionAt` optimizes: nothing (-zdxc-no-opt), as
|
||||||
|
/// dxc's -Od does (locals promoted to SSA values and what that leaves
|
||||||
|
/// dead removed, nothing else), or fully.
|
||||||
|
pub const Optimize = enum { none, debug, full };
|
||||||
|
|
||||||
|
pub fn emitWithReflectionAt(gpa: Allocator, m: *const ir.Module, profile: shader.Profile, diags: *diag.Diagnostics, level: Optimize) Error!Output {
|
||||||
var arena_state: BumpArena = .init(gpa);
|
var arena_state: BumpArena = .init(gpa);
|
||||||
defer arena_state.deinit();
|
defer arena_state.deinit();
|
||||||
var e: Emitter = .{ .arena = arena_state.allocator(), .dm = .init(gpa), .m = m, .t = m.types, .profile = profile, .diags = diags, .optimize = optimize };
|
var e: Emitter = .{ .arena = arena_state.allocator(), .dm = .init(gpa), .m = m, .t = m.types, .profile = profile, .diags = diags, .optimize = level == .full, .promote_only = level == .debug };
|
||||||
defer e.dm.deinit();
|
defer e.dm.deinit();
|
||||||
// Native 16-bit types are laid out at their own size.
|
// Native 16-bit types are laid out at their own size.
|
||||||
if (m.native_16bit) e.dm.datalayout = "e-m:e-p:32:32-i1:32-i8:8-i16:16-i32:32-i64:64-f16:16-f32:32-f64:64-n8:16:32:64";
|
if (m.native_16bit) e.dm.datalayout = "e-m:e-p:32:32-i1:32-i8:8-i16:16-i32:32-i64:64-f16:16-f32:32-f64:64-n8:16:32:64";
|
||||||
|
|
@ -337,6 +348,8 @@ const Emitter = struct {
|
||||||
dyn_ranges: std.AutoHashMapUnmanaged(u32, [2]u32) = .empty,
|
dyn_ranges: std.AutoHashMapUnmanaged(u32, [2]u32) = .empty,
|
||||||
/// See `emit`.
|
/// See `emit`.
|
||||||
optimize: bool = true,
|
optimize: bool = true,
|
||||||
|
/// -Od: only promotion runs on the finished functions.
|
||||||
|
promote_only: bool = false,
|
||||||
/// Arrays of inlined callees that have returned, by type, for later
|
/// Arrays of inlined callees that have returned, by type, for later
|
||||||
/// callees' locals of that type (per function).
|
/// callees' locals of that type (per function).
|
||||||
array_pool: std.AutoHashMapUnmanaged(TypeId, std.ArrayList(Ptr)) = .empty,
|
array_pool: std.AutoHashMapUnmanaged(TypeId, std.ArrayList(Ptr)) = .empty,
|
||||||
|
|
@ -1553,6 +1566,17 @@ const Emitter = struct {
|
||||||
try promote.run(e.arena, &e.dm, func, &.empty);
|
try promote.run(e.arena, &e.dm, func, &.empty);
|
||||||
if (e.dm.functions.items[func].insts.items.len == before) break;
|
if (e.dm.functions.items[func].insts.items.len == before) break;
|
||||||
}
|
}
|
||||||
|
// Repeated computations, then blocks that only branch on:
|
||||||
|
// merged, bypassed, and if-converted.
|
||||||
|
// (What that leaves dead, or folds, and the blocks that leaves
|
||||||
|
// empty: again, until nothing changes.)
|
||||||
|
_ = try cse.run(e.arena, &e.dm, func);
|
||||||
|
var passes: u32 = 0;
|
||||||
|
while (passes < 3 and try cfg.run(e.arena, &e.dm, func)) : (passes += 1) {
|
||||||
|
try promote.run(e.arena, &e.dm, func, &.empty);
|
||||||
|
}
|
||||||
|
} else if (e.promote_only) {
|
||||||
|
try promote.run(e.arena, &e.dm, func, &ranges);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -2147,7 +2171,16 @@ const Emitter = struct {
|
||||||
_ = try e.add(void_ty, .{ .br = .{ .then = cont } });
|
_ = try e.add(void_ty, .{ .br = .{ .then = cont } });
|
||||||
} else _ = try e.add(void_ty, .{ .ret = null });
|
} else _ = try e.add(void_ty, .{ .ret = null });
|
||||||
},
|
},
|
||||||
.br => |t| _ = try e.add(void_ty, .{ .br = .{ .then = try e.blockFor(frame, t.index()) } }),
|
.br => |t| {
|
||||||
|
const br = try e.add(void_ty, .{ .br = .{ .then = try e.blockFor(frame, t.index()) } });
|
||||||
|
// An `[unroll]` loop's back edge: marked for the unroller.
|
||||||
|
switch (f.blocks.items[t.index()].merge) {
|
||||||
|
.loop => |l| if (l.unroll == .unroll and l.@"continue".index() == bi) {
|
||||||
|
e.insts.at(br.inst).md = .unroll;
|
||||||
|
},
|
||||||
|
else => {},
|
||||||
|
}
|
||||||
|
},
|
||||||
.cond_br => |c| {
|
.cond_br => |c| {
|
||||||
const cond = (try e.scalars(frame, c.cond))[0];
|
const cond = (try e.scalars(frame, c.cond))[0];
|
||||||
if (frame.taken.len > 0) if (e.constIntOf(cond)) |k| {
|
if (frame.taken.len > 0) if (e.constIntOf(cond)) |k| {
|
||||||
|
|
|
||||||
|
|
@ -164,7 +164,17 @@ pub const Inst = struct {
|
||||||
|
|
||||||
/// An instruction's metadata attachment: an index into Module.inst_mds,
|
/// An instruction's metadata attachment: an index into Module.inst_mds,
|
||||||
/// kept out of line (few instructions have one).
|
/// kept out of line (few instructions have one).
|
||||||
pub const InstMd = enum(u32) { none = 0, _ };
|
/// `unroll` is no attachment: it marks the back edge of an `[unroll]` loop
|
||||||
|
/// for the unroller, and is not written.
|
||||||
|
pub const InstMd = enum(u32) {
|
||||||
|
none = 0,
|
||||||
|
unroll = std.math.maxInt(u32),
|
||||||
|
_,
|
||||||
|
|
||||||
|
pub fn written(md: InstMd) bool {
|
||||||
|
return md != .none and md != .unroll;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
pub const Function = struct {
|
pub const Function = struct {
|
||||||
name: []const u8,
|
name: []const u8,
|
||||||
|
|
@ -977,10 +987,10 @@ const Encoder = struct {
|
||||||
}
|
}
|
||||||
// METADATA_ATTACHMENT: [instruction index, (kind, node)...]
|
// METADATA_ATTACHMENT: [instruction index, (kind, node)...]
|
||||||
var any_md = false;
|
var any_md = false;
|
||||||
for (f.insts.items) |inst| any_md = any_md or inst.md != .none;
|
for (f.insts.items) |inst| any_md = any_md or inst.md.written();
|
||||||
if (any_md) {
|
if (any_md) {
|
||||||
try w.enterBlock(block_metadata_attachment, 3);
|
try w.enterBlock(block_metadata_attachment, 3);
|
||||||
for (f.insts.items, 0..) |inst, k| if (inst.md != .none) {
|
for (f.insts.items, 0..) |inst, k| if (inst.md.written()) {
|
||||||
const md = e.m.inst_mds.items[@backingInt(inst.md) - 1];
|
const md = e.m.inst_mds.items[@backingInt(inst.md) - 1];
|
||||||
try e.ops.appendSlice(e.gpa(), &.{ k, md.kind, md.node });
|
try e.ops.appendSlice(e.gpa(), &.{ k, md.kind, md.node });
|
||||||
try e.rec(11);
|
try e.rec(11);
|
||||||
|
|
|
||||||
|
|
@ -23,14 +23,14 @@ const TypeId = module.TypeId;
|
||||||
|
|
||||||
const none = std.math.maxInt(u32);
|
const none = std.math.maxInt(u32);
|
||||||
|
|
||||||
const Role = enum { load_ptr, store_ptr, gep_base, other };
|
pub const Role = enum { load_ptr, store_ptr, gep_base, other };
|
||||||
|
|
||||||
const Edge = @typeInfo(@FieldType(@FieldType(@FieldType(Inst, "op"), "phi"), "incoming")).pointer.child;
|
const Edge = @typeInfo(@FieldType(@FieldType(@FieldType(Inst, "op"), "phi"), "incoming")).pointer.child;
|
||||||
|
|
||||||
/// Visits each operand of `inst` (with the way it is used) through
|
/// Visits each operand of `inst` (with the way it is used) through
|
||||||
/// `ctx.visit(value, role) Value`. With `write`, the results replace the
|
/// `ctx.visit(value, role) Value`. With `write`, the results replace the
|
||||||
/// operands, in newly allocated slices where the operands are slices.
|
/// operands, in newly allocated slices where the operands are slices.
|
||||||
fn operands(comptime write: bool, a: Allocator, inst: *Inst, ctx: anytype) Allocator.Error!void {
|
pub fn operands(comptime write: bool, a: Allocator, inst: *Inst, ctx: anytype) Allocator.Error!void {
|
||||||
const S = struct {
|
const S = struct {
|
||||||
fn one(c: anytype, v: *Value, role: Role) void {
|
fn one(c: anytype, v: *Value, role: Role) void {
|
||||||
const r = c.visit(v.*, role);
|
const r = c.visit(v.*, role);
|
||||||
|
|
@ -1088,6 +1088,7 @@ fn simplify(m: *module.Module, f: *const module.Function, repl: []const ?Value,
|
||||||
return null;
|
return null;
|
||||||
},
|
},
|
||||||
.binop => |b| {
|
.binop => |b| {
|
||||||
|
if (try foldFloat(m, repl, inst)) |v| return v;
|
||||||
const w = S.intWidth(m, inst.ty) orelse return null;
|
const w = S.intWidth(m, inst.ty) orelse return null;
|
||||||
const l = resolve(repl, b.lhs);
|
const l = resolve(repl, b.lhs);
|
||||||
const r = resolve(repl, b.rhs);
|
const r = resolve(repl, b.rhs);
|
||||||
|
|
@ -1127,6 +1128,10 @@ fn simplify(m: *module.Module, f: *const module.Function, repl: []const ?Value,
|
||||||
.@"and" => if (S.bits(x, w) == S.bits(-1, w)) return r,
|
.@"and" => if (S.bits(x, w) == S.bits(-1, w)) return r,
|
||||||
else => {},
|
else => {},
|
||||||
};
|
};
|
||||||
|
if (b.op == .@"and" and w <= 64) {
|
||||||
|
if (rc) |y| return andKnown(m, f, repl, n, l, S.bits(y, w), w, inst.ty);
|
||||||
|
if (lc) |x| return andKnown(m, f, repl, n, r, S.bits(x, w), w, inst.ty);
|
||||||
|
}
|
||||||
return null;
|
return null;
|
||||||
},
|
},
|
||||||
.cmp => |c| {
|
.cmp => |c| {
|
||||||
|
|
@ -1159,25 +1164,50 @@ fn simplify(m: *module.Module, f: *const module.Function, repl: []const ?Value,
|
||||||
return try m.constant(.{ .ty = inst.ty, .kind = .{ .int = @intFromBool(t) } });
|
return try m.constant(.{ .ty = inst.ty, .kind = .{ .int = @intFromBool(t) } });
|
||||||
}
|
}
|
||||||
if (c.pred < 32 or c.pred > 41) return null; // integer predicates
|
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;
|
// A bool widened and compared again: `zext i1 x != 0` and
|
||||||
const x = S.bits(constInt(m, l) orelse return null, w);
|
// `zext i1 x == 1` are x.
|
||||||
const y = S.bits(constInt(m, r) orelse return null, w);
|
if (c.pred == 32 or c.pred == 33) if (l == .inst and l.inst < n) {
|
||||||
const sx = S.stored(x, w);
|
const z = f.insts.items[l.inst].op;
|
||||||
const sy = S.stored(y, w);
|
if (z == .cast and z.cast.op == .zext) {
|
||||||
const t = switch (c.pred) {
|
const x = resolve(repl, z.cast.val);
|
||||||
32 => x == y,
|
if (S.intWidth(m, S.ty(m, f, n, phi_var, var_ty, x)) == 1) {
|
||||||
33 => x != y,
|
if (constInt(m, r)) |k| {
|
||||||
34 => x > y,
|
if ((c.pred == 33 and k == 0) or (c.pred == 32 and k == 1)) return x;
|
||||||
35 => x >= y,
|
}
|
||||||
36 => x < y,
|
}
|
||||||
37 => x <= y,
|
}
|
||||||
38 => sx > sy,
|
|
||||||
39 => sx >= sy,
|
|
||||||
40 => sx < sy,
|
|
||||||
else => sx <= sy,
|
|
||||||
};
|
};
|
||||||
return try m.constant(.{ .ty = inst.ty, .kind = .{ .int = @intFromBool(t) } });
|
const w = S.intWidth(m, S.ty(m, f, n, phi_var, var_ty, l)) orelse return null;
|
||||||
|
// Each side's possible values: a constant, or selects and phis
|
||||||
|
// of constants (`(c ? 2 : 1) == 3` is false, as dxc's
|
||||||
|
// instcombine finds); the same answer for every pair folds.
|
||||||
|
var lv: Cands = .{};
|
||||||
|
var rv: Cands = .{};
|
||||||
|
if (!lv.add(m, f, repl, n, l, 2) or !rv.add(m, f, repl, n, r, 2)) return null;
|
||||||
|
var result: ?bool = null;
|
||||||
|
for (lv.vals[0..lv.len]) |lk| for (rv.vals[0..rv.len]) |rk| {
|
||||||
|
const x = S.bits(lk, w);
|
||||||
|
const y = S.bits(rk, w);
|
||||||
|
const sx = S.stored(x, w);
|
||||||
|
const sy = S.stored(y, w);
|
||||||
|
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,
|
||||||
|
};
|
||||||
|
if (result) |prev| if (prev != t) return null;
|
||||||
|
result = t;
|
||||||
|
};
|
||||||
|
return try m.constant(.{ .ty = inst.ty, .kind = .{ .int = @intFromBool(result orelse return null) } });
|
||||||
},
|
},
|
||||||
|
.call => return foldDxOp(m, repl, inst),
|
||||||
.select => |sl| {
|
.select => |sl| {
|
||||||
const t = resolve(repl, sl.t);
|
const t = resolve(repl, sl.t);
|
||||||
const fv = resolve(repl, sl.f);
|
const fv = resolve(repl, sl.f);
|
||||||
|
|
@ -1250,6 +1280,240 @@ fn edgePhi(m: *module.Module, insts: []const Inst, block_start: []const u32, rep
|
||||||
return try m.constant(.{ .ty = inst.ty, .kind = .{ .int = same orelse return null } });
|
return try m.constant(.{ .ty = inst.ty, .kind = .{ .int = same orelse return null } });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The integer constants a value can be: itself if constant, or each arm
|
||||||
|
/// of a select or input of a phi that is (`depth` levels deep).
|
||||||
|
const Cands = struct {
|
||||||
|
vals: [8]i64 = undefined,
|
||||||
|
len: usize = 0,
|
||||||
|
|
||||||
|
fn add(c: *Cands, m: *const module.Module, f: *const module.Function, repl: []const ?Value, n: u32, v: Value, depth: u32) bool {
|
||||||
|
const x = resolve(repl, v);
|
||||||
|
if (constInt(m, x)) |k| {
|
||||||
|
for (c.vals[0..c.len]) |e| if (e == k) return true;
|
||||||
|
if (c.len == c.vals.len) return false;
|
||||||
|
c.vals[c.len] = k;
|
||||||
|
c.len += 1;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (x != .inst or x.inst >= n or depth == 0) return false;
|
||||||
|
switch (f.insts.items[x.inst].op) {
|
||||||
|
.select => |sl| return c.add(m, f, repl, n, sl.t, depth - 1) and c.add(m, f, repl, n, sl.f, depth - 1),
|
||||||
|
.phi => |p| {
|
||||||
|
for (p.incoming) |in| {
|
||||||
|
const y = resolve(repl, in.val);
|
||||||
|
if (y == .inst and y.inst == x.inst) continue;
|
||||||
|
if (!c.add(m, f, repl, n, y, depth - 1)) return false;
|
||||||
|
}
|
||||||
|
return c.len > 0;
|
||||||
|
},
|
||||||
|
else => return false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
/// The bits of the `w`-bit integer `v` known to be zero, from what
|
||||||
|
/// computes it (`depth` levels deep): constants, masks, shifts by
|
||||||
|
/// constants, widening, and the bitwise operations and selects of such.
|
||||||
|
fn knownZero(m: *const module.Module, f: *const module.Function, repl: []const ?Value, n: u32, v: Value, w: u32, depth: u32) u64 {
|
||||||
|
const mask: u64 = if (w >= 64) ~@as(u64, 0) else (@as(u64, 1) << @intCast(w)) - 1;
|
||||||
|
const x = resolve(repl, v);
|
||||||
|
if (constInt(m, x)) |k| return ~@as(u64, @bitCast(k)) & mask;
|
||||||
|
if (x != .inst or x.inst >= n or depth == 0) return 0;
|
||||||
|
const inst = f.insts.items[x.inst];
|
||||||
|
const d = depth - 1;
|
||||||
|
return mask & switch (inst.op) {
|
||||||
|
.binop => |b| switch (b.op) {
|
||||||
|
.@"and" => knownZero(m, f, repl, n, b.lhs, w, d) | knownZero(m, f, repl, n, b.rhs, w, d),
|
||||||
|
.@"or", .xor => knownZero(m, f, repl, n, b.lhs, w, d) & knownZero(m, f, repl, n, b.rhs, w, d),
|
||||||
|
.shl => blk: {
|
||||||
|
const k = constInt(m, resolve(repl, b.rhs)) orelse break :blk 0;
|
||||||
|
if (k < 0 or k >= w) break :blk 0;
|
||||||
|
const sh: u6 = @intCast(k);
|
||||||
|
break :blk (knownZero(m, f, repl, n, b.lhs, w, d) << sh) | ((@as(u64, 1) << sh) - 1);
|
||||||
|
},
|
||||||
|
.lshr => blk: {
|
||||||
|
const k = constInt(m, resolve(repl, b.rhs)) orelse break :blk 0;
|
||||||
|
if (k < 0 or k >= w) break :blk 0;
|
||||||
|
const sh: u6 = @intCast(k);
|
||||||
|
break :blk (knownZero(m, f, repl, n, b.lhs, w, d) >> sh) | ~(mask >> sh);
|
||||||
|
},
|
||||||
|
else => 0,
|
||||||
|
},
|
||||||
|
.cast => |c| switch (c.op) {
|
||||||
|
.zext => blk: {
|
||||||
|
// (A phi promotion made has no instruction to read its
|
||||||
|
// type from yet.)
|
||||||
|
const src = resolve(repl, c.val);
|
||||||
|
if (src == .inst and src.inst >= n) break :blk 0;
|
||||||
|
const from = switch (m.types.items[typeOf(m, f, src)]) {
|
||||||
|
.int => |iw| iw,
|
||||||
|
else => break :blk 0,
|
||||||
|
};
|
||||||
|
const from_mask: u64 = if (from >= 64) ~@as(u64, 0) else (@as(u64, 1) << @intCast(from)) - 1;
|
||||||
|
break :blk knownZero(m, f, repl, n, c.val, from, d) | ~from_mask;
|
||||||
|
},
|
||||||
|
else => 0,
|
||||||
|
},
|
||||||
|
.select => |sl| knownZero(m, f, repl, n, sl.t, w, d) & knownZero(m, f, repl, n, sl.f, w, d),
|
||||||
|
else => 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `x & c` (`w` bits) when known bits decide it, as dxc's instcombine
|
||||||
|
/// does: 0 if every bit `c` keeps is known zero in `x`; `x` if every bit
|
||||||
|
/// it clears already is; and through `a | b` where `b` only has bits `c`
|
||||||
|
/// clears and `a` only bits it keeps, `a`. (Flags packed into one integer
|
||||||
|
/// with other fields, then tested.)
|
||||||
|
fn andKnown(m: *module.Module, f: *const module.Function, repl: []const ?Value, n: u32, x: Value, c: u64, w: u32, ty: TypeId) Allocator.Error!?Value {
|
||||||
|
const mask: u64 = if (w >= 64) ~@as(u64, 0) else (@as(u64, 1) << @intCast(w)) - 1;
|
||||||
|
const kz = knownZero(m, f, repl, n, x, w, 6);
|
||||||
|
if (c & ~kz & mask == 0) return try m.constant(.{ .ty = ty, .kind = .{ .int = 0 } });
|
||||||
|
if (~c & ~kz & mask == 0) return resolve(repl, x);
|
||||||
|
const xr = resolve(repl, x);
|
||||||
|
if (xr == .inst and xr.inst < n) {
|
||||||
|
const inst = f.insts.items[xr.inst];
|
||||||
|
if (inst.op == .binop and inst.op.binop.op == .@"or") {
|
||||||
|
const o = inst.op.binop;
|
||||||
|
const sides = [2][2]Value{ .{ o.lhs, o.rhs }, .{ o.rhs, o.lhs } };
|
||||||
|
for (sides) |ab| {
|
||||||
|
const kb = knownZero(m, f, repl, n, ab[1], w, 6);
|
||||||
|
const ka = knownZero(m, f, repl, n, ab[0], w, 6);
|
||||||
|
if (c & ~kb & mask == 0 and ~c & ~ka & mask == 0) return resolve(repl, ab[0]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A half, float or double constant of type `ty` with value `x` (rounded
|
||||||
|
/// to the type).
|
||||||
|
fn floatConst(m: *module.Module, ty: TypeId, x: f64) Allocator.Error!?Value {
|
||||||
|
const b: u64 = switch (m.types.items[ty]) {
|
||||||
|
.half => @as(u16, @bitCast(@as(f16, @floatCast(x)))),
|
||||||
|
.float => @as(u32, @bitCast(@as(f32, @floatCast(x)))),
|
||||||
|
.double => @bitCast(x),
|
||||||
|
else => return null,
|
||||||
|
};
|
||||||
|
return try m.constant(.{ .ty = ty, .kind = .{ .float_bits = b } });
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `x op y` in `T`'s precision.
|
||||||
|
fn floatOp(comptime T: type, op: module.BinOp, x: f64, y: f64) ?f64 {
|
||||||
|
const a: T = @floatCast(x);
|
||||||
|
const c: T = @floatCast(y);
|
||||||
|
return @floatCast(switch (op) {
|
||||||
|
.add => a + c,
|
||||||
|
.sub => a - c,
|
||||||
|
.mul => a * c,
|
||||||
|
.sdiv => a / c,
|
||||||
|
.srem => if (c == 0 or std.math.isInf(a) or std.math.isNan(a) or std.math.isNan(c)) std.math.nan(T) else @rem(a, c),
|
||||||
|
else => return null,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Floating-point arithmetic on two constants, and the identities exact
|
||||||
|
/// in IEEE arithmetic (`x * 1`, `x / 1`, `x - 0`, `x + -0`), as dxc's
|
||||||
|
/// constant folding and instcombine fold them.
|
||||||
|
fn foldFloat(m: *module.Module, repl: []const ?Value, inst: Inst) Allocator.Error!?Value {
|
||||||
|
const b = inst.op.binop;
|
||||||
|
const is_float = switch (m.types.items[inst.ty]) {
|
||||||
|
.half, .float, .double => true,
|
||||||
|
else => false,
|
||||||
|
};
|
||||||
|
if (!is_float) return null;
|
||||||
|
const l = resolve(repl, b.lhs);
|
||||||
|
const r = resolve(repl, b.rhs);
|
||||||
|
const lc = constFloat(m, l);
|
||||||
|
const rc = constFloat(m, r);
|
||||||
|
if (lc != null and rc != null) {
|
||||||
|
const x = switch (m.types.items[inst.ty]) {
|
||||||
|
.half => floatOp(f16, b.op, lc.?, rc.?),
|
||||||
|
.float => floatOp(f32, b.op, lc.?, rc.?),
|
||||||
|
else => floatOp(f64, b.op, lc.?, rc.?),
|
||||||
|
} orelse return null;
|
||||||
|
return floatConst(m, inst.ty, x);
|
||||||
|
}
|
||||||
|
if (rc) |y| {
|
||||||
|
const neg_zero = y == 0 and std.math.signbit(y);
|
||||||
|
switch (b.op) {
|
||||||
|
.mul, .sdiv => if (y == 1) return l,
|
||||||
|
.sub => if (y == 0 and !neg_zero) return l,
|
||||||
|
.add => if (neg_zero) return l,
|
||||||
|
else => {},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (lc) |x| switch (b.op) {
|
||||||
|
.mul => if (x == 1) return r,
|
||||||
|
.add => if (x == 0 and std.math.signbit(x)) return r,
|
||||||
|
else => {},
|
||||||
|
};
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A dx.op call on constants, folded as dxc folds them (the operations
|
||||||
|
/// whose result does not depend on the GPU's precision, and the min / max
|
||||||
|
/// family).
|
||||||
|
fn foldDxOp(m: *module.Module, repl: []const ?Value, inst: Inst) Allocator.Error!?Value {
|
||||||
|
const c = inst.op.call;
|
||||||
|
if (!std.mem.startsWith(u8, m.functions.items[c.callee].name, "dx.op.")) return null;
|
||||||
|
if (c.args.len < 2) return null;
|
||||||
|
const opc = constInt(m, c.args[0]) orelse return null;
|
||||||
|
switch (opc) {
|
||||||
|
// FAbs, Saturate, Round_ne, Round_ni, Round_pi, Round_z, Sqrt
|
||||||
|
6, 7, 24, 26, 27, 28, 29 => {
|
||||||
|
if (c.args.len != 2) return null;
|
||||||
|
const x = constFloat(m, resolve(repl, c.args[1])) orelse return null;
|
||||||
|
if (std.math.isNan(x)) return null;
|
||||||
|
const y: f64 = switch (opc) {
|
||||||
|
6 => @abs(x),
|
||||||
|
7 => @min(@max(x, 0), 1),
|
||||||
|
24 => if (x < 0) return null else switch (m.types.items[inst.ty]) {
|
||||||
|
.half => @floatCast(@sqrt(@as(f16, @floatCast(x)))),
|
||||||
|
.float => @floatCast(@sqrt(@as(f32, @floatCast(x)))),
|
||||||
|
else => @sqrt(x),
|
||||||
|
},
|
||||||
|
// (Halves to even.)
|
||||||
|
26 => if (@abs(x - @trunc(x)) == 0.5) 2 * @round(x / 2) else @round(x),
|
||||||
|
27 => @floor(x),
|
||||||
|
28 => @ceil(x),
|
||||||
|
else => @trunc(x),
|
||||||
|
};
|
||||||
|
return floatConst(m, inst.ty, y);
|
||||||
|
},
|
||||||
|
// FMax, FMin
|
||||||
|
35, 36 => {
|
||||||
|
if (c.args.len != 3) return null;
|
||||||
|
const x = constFloat(m, resolve(repl, c.args[1])) orelse return null;
|
||||||
|
const y = constFloat(m, resolve(repl, c.args[2])) orelse return null;
|
||||||
|
if (std.math.isNan(x) or std.math.isNan(y)) return null;
|
||||||
|
return floatConst(m, inst.ty, if (opc == 35) @max(x, y) else @min(x, y));
|
||||||
|
},
|
||||||
|
// IMax, IMin, UMax, UMin
|
||||||
|
37, 38, 39, 40 => {
|
||||||
|
if (c.args.len != 3) return null;
|
||||||
|
const w: u32 = switch (m.types.items[inst.ty]) {
|
||||||
|
.int => |iw| iw,
|
||||||
|
else => return null,
|
||||||
|
};
|
||||||
|
const x = constInt(m, resolve(repl, c.args[1])) orelse return null;
|
||||||
|
const y = constInt(m, resolve(repl, c.args[2])) orelse return null;
|
||||||
|
// (Constants hold their value sign-extended: unsigned order is
|
||||||
|
// that of the w-bit patterns.)
|
||||||
|
const mask: u64 = if (w >= 64) ~@as(u64, 0) else (@as(u64, 1) << @intCast(w)) - 1;
|
||||||
|
const ux = @as(u64, @bitCast(x)) & mask;
|
||||||
|
const uy = @as(u64, @bitCast(y)) & mask;
|
||||||
|
const pick_x = switch (opc) {
|
||||||
|
37 => x >= y,
|
||||||
|
38 => x <= y,
|
||||||
|
39 => ux >= uy,
|
||||||
|
else => ux <= uy,
|
||||||
|
};
|
||||||
|
return if (pick_x) resolve(repl, c.args[1]) else resolve(repl, c.args[2]);
|
||||||
|
},
|
||||||
|
else => return null,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// A half, float or double constant's value.
|
/// A half, float or double constant's value.
|
||||||
fn constFloat(m: *const module.Module, v: Value) ?f64 {
|
fn constFloat(m: *const module.Module, v: Value) ?f64 {
|
||||||
if (v != .constant) return null;
|
if (v != .constant) return null;
|
||||||
|
|
|
||||||
|
|
@ -31,6 +31,9 @@ const none = std.math.maxInt(u32);
|
||||||
const max_trips = 256;
|
const max_trips = 256;
|
||||||
const max_loop_growth = 300;
|
const max_loop_growth = 300;
|
||||||
const max_growth = 65536;
|
const max_growth = 65536;
|
||||||
|
/// For `[unroll]` loops: dxc's limit on their iterations (its
|
||||||
|
/// DxilLoopUnroll), and no limit on their size but the function's.
|
||||||
|
const max_marked_trips = 1024;
|
||||||
|
|
||||||
/// Unrolls the qualifying loops of `func`, innermost first; true if any.
|
/// Unrolls the qualifying loops of `func`, innermost first; true if any.
|
||||||
pub fn run(a: Allocator, m: *module.Module, func: u32) Allocator.Error!bool {
|
pub fn run(a: Allocator, m: *module.Module, func: u32) Allocator.Error!bool {
|
||||||
|
|
@ -495,6 +498,10 @@ fn unrollOne(a: Allocator, m: *module.Module, func: u32, budget: *usize, tried:
|
||||||
// Innermost: no other loop's header inside.
|
// Innermost: no other loop's header inside.
|
||||||
for (loops.items) |other| if (other.h != h and lp.body.has(other.h)) continue :candidates;
|
for (loops.items) |other| if (other.h != h and lp.body.has(other.h)) continue :candidates;
|
||||||
try tried.put(a, h, {});
|
try tried.put(a, h, {});
|
||||||
|
// `[unroll]` (its back edge marked by the emitter).
|
||||||
|
const marked_loop = for (lp.latches) |l| {
|
||||||
|
if (insts[cfg.block_start[l + 1] - 1].md == .unroll) break true;
|
||||||
|
} else false;
|
||||||
|
|
||||||
// One way out: a conditional branch from one block, to one block.
|
// One way out: a conditional branch from one block, to one block.
|
||||||
var exiting: u32 = none;
|
var exiting: u32 = none;
|
||||||
|
|
@ -547,7 +554,7 @@ fn unrollOne(a: Allocator, m: *module.Module, func: u32, budget: *usize, tried:
|
||||||
while (true) {
|
while (true) {
|
||||||
const c = eval(m, f, &state, xcond, 0) orelse continue :candidates;
|
const c = eval(m, f, &state, xcond, 0) orelse continue :candidates;
|
||||||
if ((c & 1) != stay_on) break;
|
if ((c & 1) != stay_on) break;
|
||||||
if (states.items.len >= max_trips) continue :candidates;
|
if (states.items.len >= @as(usize, if (marked_loop) max_marked_trips else max_trips)) continue :candidates;
|
||||||
try states.append(a, try state.clone(a));
|
try states.append(a, try state.clone(a));
|
||||||
// Next values: what every latch passes back (the same).
|
// Next values: what every latch passes back (the same).
|
||||||
var next: std.AutoHashMapUnmanaged(u32, i64) = .empty;
|
var next: std.AutoHashMapUnmanaged(u32, i64) = .empty;
|
||||||
|
|
@ -570,7 +577,7 @@ fn unrollOne(a: Allocator, m: *module.Module, func: u32, budget: *usize, tried:
|
||||||
}
|
}
|
||||||
const trips = states.items.len;
|
const trips = states.items.len;
|
||||||
const growth = (trips + 1) * size;
|
const growth = (trips + 1) * size;
|
||||||
if (growth > max_loop_growth or growth > budget.*) continue;
|
if ((!marked_loop and growth > max_loop_growth) or growth > budget.*) continue;
|
||||||
budget.* -= growth;
|
budget.* -= growth;
|
||||||
try states.append(a, state); // the last pass, up to the exit
|
try states.append(a, state); // the last pass, up to the exit
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -23,6 +23,9 @@ pub const Stage = enum {
|
||||||
promote,
|
promote,
|
||||||
sccp,
|
sccp,
|
||||||
unroll,
|
unroll,
|
||||||
|
cse,
|
||||||
|
/// Block merging, bypassing and if-conversion (dxil/cfg.zig).
|
||||||
|
cfg,
|
||||||
bitcode,
|
bitcode,
|
||||||
container,
|
container,
|
||||||
spirv,
|
spirv,
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue