Compare commits
26 Commits
e6a089eb34
...
35dedc171e
| Author | SHA1 | Date |
|---|---|---|
|
|
35dedc171e | |
|
|
9bb4feb32b | |
|
|
531b5c6227 | |
|
|
e4d5bb5ddc | |
|
|
9b2fc76c56 | |
|
|
5c99b1c4db | |
|
|
4a12f2b89a | |
|
|
0634987f5e | |
|
|
69b33c2af2 | |
|
|
2c8f5c5f53 | |
|
|
5c31ce84b8 | |
|
|
bc8aee17eb | |
|
|
6d38019763 | |
|
|
3833ea57d0 | |
|
|
9f8c46792b | |
|
|
e8982e3378 | |
|
|
b659b5a4af | |
|
|
0a2607946f | |
|
|
ab2641a57d | |
|
|
e05a217cc1 | |
|
|
5019d2b838 | |
|
|
dfb629ace0 | |
|
|
ec64ffa4b0 | |
|
|
1594c37464 | |
|
|
c423c0c1a0 | |
|
|
d3538e1db3 |
|
|
@ -0,0 +1,193 @@
|
||||||
|
//! An arena for one thread: what std.heap.ArenaAllocator does, without the
|
||||||
|
//! atomic operations that make that one safe to share between threads (an
|
||||||
|
//! atomic add on every allocation). A compile runs on one thread and
|
||||||
|
//! allocates millions of times.
|
||||||
|
//!
|
||||||
|
//! Memory comes from the child allocator in chunks, each larger than the
|
||||||
|
//! last; freeing or resizing an allocation works in place only for the
|
||||||
|
//! most recent one. reset can keep the chunks for the next use.
|
||||||
|
const BumpArena = @This();
|
||||||
|
|
||||||
|
const std = @import("std");
|
||||||
|
const Allocator = std.mem.Allocator;
|
||||||
|
const Alignment = std.mem.Alignment;
|
||||||
|
|
||||||
|
child: Allocator,
|
||||||
|
/// Chunks in use, newest first; allocations bump `end` in the newest.
|
||||||
|
used: ?*Chunk = null,
|
||||||
|
/// Chunks a reset kept, for reuse.
|
||||||
|
spare: ?*Chunk = null,
|
||||||
|
end: usize = 0,
|
||||||
|
|
||||||
|
const Chunk = struct {
|
||||||
|
next: ?*Chunk,
|
||||||
|
/// Bytes after the header.
|
||||||
|
len: usize,
|
||||||
|
|
||||||
|
fn data(c: *Chunk) [*]u8 {
|
||||||
|
return @as([*]u8, @ptrCast(c)) + @sizeOf(Chunk);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const chunk_align: Alignment = .@"16";
|
||||||
|
const min_chunk = 64 << 10;
|
||||||
|
|
||||||
|
pub fn init(child: Allocator) BumpArena {
|
||||||
|
return .{ .child = child };
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn deinit(b: *BumpArena) void {
|
||||||
|
freeList(b.child, b.used);
|
||||||
|
freeList(b.child, b.spare);
|
||||||
|
b.* = undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn freeList(child: Allocator, first: ?*Chunk) void {
|
||||||
|
var c = first;
|
||||||
|
while (c) |chunk| {
|
||||||
|
c = chunk.next;
|
||||||
|
const bytes: [*]u8 = @ptrCast(chunk);
|
||||||
|
child.rawFree(bytes[0 .. @sizeOf(Chunk) + chunk.len], chunk_align, @returnAddress());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn allocator(b: *BumpArena) Allocator {
|
||||||
|
return .{ .ptr = b, .vtable = &vtable };
|
||||||
|
}
|
||||||
|
|
||||||
|
const vtable: Allocator.VTable = .{ .alloc = alloc, .resize = resize, .remap = remap, .free = free };
|
||||||
|
|
||||||
|
/// Total bytes of the chunks held (in use and spare).
|
||||||
|
pub fn queryCapacity(b: *const BumpArena) usize {
|
||||||
|
var n: usize = 0;
|
||||||
|
inline for (.{ b.used, b.spare }) |first| {
|
||||||
|
var c = first;
|
||||||
|
while (c) |chunk| : (c = chunk.next) n += chunk.len;
|
||||||
|
}
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub const ResetMode = std.heap.ArenaAllocator.ResetMode;
|
||||||
|
|
||||||
|
/// Frees every allocation. `.retain_capacity` keeps the chunks for reuse;
|
||||||
|
/// `.retain_with_limit` keeps them up to that many bytes (largest first
|
||||||
|
/// kept); `.free_all` gives them back.
|
||||||
|
pub fn reset(b: *BumpArena, mode: ResetMode) bool {
|
||||||
|
const limit: usize = switch (mode) {
|
||||||
|
.free_all => 0,
|
||||||
|
.retain_capacity => std.math.maxInt(usize),
|
||||||
|
.retain_with_limit => |l| l,
|
||||||
|
};
|
||||||
|
// All chunks, then keep the largest that fit under the limit.
|
||||||
|
var all = b.used;
|
||||||
|
if (all) |first| {
|
||||||
|
var last = first;
|
||||||
|
while (last.next) |nx| last = nx;
|
||||||
|
last.next = b.spare;
|
||||||
|
} else all = b.spare;
|
||||||
|
b.used = null;
|
||||||
|
b.spare = null;
|
||||||
|
b.end = 0;
|
||||||
|
var kept: usize = 0;
|
||||||
|
var c = all;
|
||||||
|
while (c) |chunk| {
|
||||||
|
c = chunk.next;
|
||||||
|
if (kept + chunk.len <= limit) {
|
||||||
|
kept += chunk.len;
|
||||||
|
chunk.next = null;
|
||||||
|
b.addSpare(chunk);
|
||||||
|
} else {
|
||||||
|
const bytes: [*]u8 = @ptrCast(chunk);
|
||||||
|
b.child.rawFree(bytes[0 .. @sizeOf(Chunk) + chunk.len], chunk_align, @returnAddress());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Adds a chunk to the spare list, largest first.
|
||||||
|
fn addSpare(b: *BumpArena, chunk: *Chunk) void {
|
||||||
|
var link = &b.spare;
|
||||||
|
while (link.*) |s| : (link = &s.next) if (s.len < chunk.len) break;
|
||||||
|
chunk.next = link.*;
|
||||||
|
link.* = chunk;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn alloc(ctx: *anyopaque, n: usize, alignment: Alignment, ra: usize) ?[*]u8 {
|
||||||
|
const b: *BumpArena = @ptrCast(@alignCast(ctx));
|
||||||
|
if (b.used) |c| {
|
||||||
|
const base = c.data();
|
||||||
|
const start = alignment.forward(@intFromPtr(base) + b.end) - @intFromPtr(base);
|
||||||
|
if (start + n <= c.len) {
|
||||||
|
b.end = start + n;
|
||||||
|
return base + start;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return b.allocSlow(n, alignment, ra);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn allocSlow(b: *BumpArena, n: usize, alignment: Alignment, ra: usize) ?[*]u8 {
|
||||||
|
const need = n + alignment.toByteUnits();
|
||||||
|
// A spare chunk big enough (the largest is first), else a new one half
|
||||||
|
// again as large as the current.
|
||||||
|
const chunk: *Chunk = if (b.spare != null and b.spare.?.len >= need) blk: {
|
||||||
|
const s = b.spare.?;
|
||||||
|
b.spare = s.next;
|
||||||
|
break :blk s;
|
||||||
|
} else blk: {
|
||||||
|
const grow = if (b.used) |c| c.len + c.len / 2 else 0;
|
||||||
|
const len = @max(need, grow, min_chunk);
|
||||||
|
const bytes = b.child.rawAlloc(@sizeOf(Chunk) + len, chunk_align, ra) orelse return null;
|
||||||
|
const c: *Chunk = @ptrCast(@alignCast(bytes));
|
||||||
|
c.len = len;
|
||||||
|
break :blk c;
|
||||||
|
};
|
||||||
|
chunk.next = b.used;
|
||||||
|
b.used = chunk;
|
||||||
|
const base = chunk.data();
|
||||||
|
const start = alignment.forward(@intFromPtr(base)) - @intFromPtr(base);
|
||||||
|
b.end = start + n;
|
||||||
|
return base + start;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether `buf` is the newest allocation (the only one that can change
|
||||||
|
/// in place).
|
||||||
|
fn isLast(b: *const BumpArena, buf: []u8) bool {
|
||||||
|
const c = b.used orelse return false;
|
||||||
|
return buf.ptr + buf.len == c.data() + b.end;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn resize(ctx: *anyopaque, buf: []u8, _: Alignment, new_len: usize, _: usize) bool {
|
||||||
|
const b: *BumpArena = @ptrCast(@alignCast(ctx));
|
||||||
|
if (!b.isLast(buf)) return new_len <= buf.len;
|
||||||
|
const c = b.used.?;
|
||||||
|
const start = @intFromPtr(buf.ptr) - @intFromPtr(c.data());
|
||||||
|
if (start + new_len > c.len) return false;
|
||||||
|
b.end = start + new_len;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn remap(ctx: *anyopaque, buf: []u8, alignment: Alignment, new_len: usize, ra: usize) ?[*]u8 {
|
||||||
|
return if (resize(ctx, buf, alignment, new_len, ra)) buf.ptr else null;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn free(ctx: *anyopaque, buf: []u8, _: Alignment, _: usize) void {
|
||||||
|
const b: *BumpArena = @ptrCast(@alignCast(ctx));
|
||||||
|
if (b.isLast(buf)) b.end -= buf.len;
|
||||||
|
}
|
||||||
|
|
||||||
|
test "allocations, growth in place, reset" {
|
||||||
|
var b: BumpArena = .init(std.testing.allocator);
|
||||||
|
defer b.deinit();
|
||||||
|
const a = b.allocator();
|
||||||
|
var list: std.ArrayList(u32) = .empty;
|
||||||
|
for (0..100_000) |k| try list.append(a, @intCast(k));
|
||||||
|
for (list.items, 0..) |x, k| try std.testing.expectEqual(k, x);
|
||||||
|
const big = try a.alignedAlloc(u8, .@"64", 1 << 20);
|
||||||
|
try std.testing.expect(std.mem.isAligned(@intFromPtr(big.ptr), 64));
|
||||||
|
const cap = b.queryCapacity();
|
||||||
|
_ = b.reset(.retain_capacity);
|
||||||
|
try std.testing.expectEqual(cap, b.queryCapacity());
|
||||||
|
_ = try a.alloc(u8, 100);
|
||||||
|
_ = b.reset(.{ .retain_with_limit = 0 });
|
||||||
|
try std.testing.expectEqual(0, b.queryCapacity());
|
||||||
|
}
|
||||||
|
|
@ -2,6 +2,7 @@
|
||||||
//! owns an arena; nothing is global.
|
//! owns an arena; nothing is global.
|
||||||
|
|
||||||
const std = @import("std");
|
const std = @import("std");
|
||||||
|
const BumpArena = @import("zdxc").BumpArena;
|
||||||
const zdxc = @import("zdxc");
|
const zdxc = @import("zdxc");
|
||||||
const compile = zdxc.compile;
|
const compile = zdxc.compile;
|
||||||
const FileSystem = zdxc.front.source.FileSystem;
|
const FileSystem = zdxc.front.source.FileSystem;
|
||||||
|
|
@ -22,7 +23,7 @@ const CompileInfo = extern struct {
|
||||||
const Output = enum(c_int) { object, diagnostics, preprocessed, root_signature, text, _ };
|
const Output = enum(c_int) { object, diagnostics, preprocessed, root_signature, text, _ };
|
||||||
|
|
||||||
const Result = struct {
|
const Result = struct {
|
||||||
arena: std.heap.ArenaAllocator,
|
arena: BumpArena,
|
||||||
status: compile.Status,
|
status: compile.Status,
|
||||||
/// Indexed by `Output`; each NUL-terminated.
|
/// Indexed by `Output`; each NUL-terminated.
|
||||||
outputs: [5]?[:0]const u8,
|
outputs: [5]?[:0]const u8,
|
||||||
|
|
@ -32,7 +33,7 @@ const Result = struct {
|
||||||
export fn zdxc_compile(info: ?*const CompileInfo) ?*Result {
|
export fn zdxc_compile(info: ?*const CompileInfo) ?*Result {
|
||||||
const i = info orelse return null;
|
const i = info orelse return null;
|
||||||
if (i.size < @sizeOf(CompileInfo)) return null;
|
if (i.size < @sizeOf(CompileInfo)) return null;
|
||||||
var arena: std.heap.ArenaAllocator = .init(std.heap.smp_allocator);
|
var arena: BumpArena = .init(std.heap.smp_allocator);
|
||||||
const r = compileInto(&arena, i) catch {
|
const r = compileInto(&arena, i) catch {
|
||||||
arena.deinit();
|
arena.deinit();
|
||||||
return null;
|
return null;
|
||||||
|
|
@ -41,7 +42,7 @@ export fn zdxc_compile(info: ?*const CompileInfo) ?*Result {
|
||||||
return r;
|
return r;
|
||||||
}
|
}
|
||||||
|
|
||||||
fn compileInto(arena: *std.heap.ArenaAllocator, i: *const CompileInfo) !*Result {
|
fn compileInto(arena: *BumpArena, i: *const CompileInfo) !*Result {
|
||||||
const a = arena.allocator();
|
const a = arena.allocator();
|
||||||
const args = try a.alloc([]const u8, i.arg_count);
|
const args = try a.alloc([]const u8, i.arg_count);
|
||||||
for (args, 0..) |*d, k| d.* = std.mem.span(i.args.?[k] orelse return error.InvalidArgument);
|
for (args, 0..) |*d, k| d.* = std.mem.span(i.args.?[k] orelse return error.InvalidArgument);
|
||||||
|
|
|
||||||
|
|
@ -3,6 +3,7 @@
|
||||||
//! include chains and macro expansion backtraces.
|
//! include chains and macro expansion backtraces.
|
||||||
|
|
||||||
const std = @import("std");
|
const std = @import("std");
|
||||||
|
const BumpArena = @import("BumpArena.zig");
|
||||||
const Allocator = std.mem.Allocator;
|
const Allocator = std.mem.Allocator;
|
||||||
const source = @import("front/source.zig");
|
const source = @import("front/source.zig");
|
||||||
const Loc = source.Loc;
|
const Loc = source.Loc;
|
||||||
|
|
@ -56,7 +57,7 @@ pub const Report = struct {
|
||||||
};
|
};
|
||||||
|
|
||||||
pub const Diagnostics = struct {
|
pub const Diagnostics = struct {
|
||||||
arena: std.heap.ArenaAllocator,
|
arena: BumpArena,
|
||||||
list: std.ArrayList(*Diagnostic) = .empty,
|
list: std.ArrayList(*Diagnostic) = .empty,
|
||||||
error_count: u32 = 0,
|
error_count: u32 = 0,
|
||||||
warning_count: u32 = 0,
|
warning_count: u32 = 0,
|
||||||
|
|
|
||||||
|
|
@ -14,6 +14,7 @@
|
||||||
//! does (test/dropin in the development repo compares the two).
|
//! does (test/dropin in the development repo compares the two).
|
||||||
|
|
||||||
const std = @import("std");
|
const std = @import("std");
|
||||||
|
const BumpArena = @import("zdxc").BumpArena;
|
||||||
const builtin = @import("builtin");
|
const builtin = @import("builtin");
|
||||||
const zdxc = @import("zdxc");
|
const zdxc = @import("zdxc");
|
||||||
const compile = zdxc.compile;
|
const compile = zdxc.compile;
|
||||||
|
|
@ -839,7 +840,7 @@ const Compiler = struct {
|
||||||
/// gives its blocks back to the OS (smp_allocator maps 64 KiB and up
|
/// gives its blocks back to the OS (smp_allocator maps 64 KiB and up
|
||||||
/// directly), and faulting fresh pages in again costs more than the compile
|
/// directly), and faulting fresh pages in again costs more than the compile
|
||||||
/// on many threads. What a thread keeps is capped at `retain_limit`.
|
/// on many threads. What a thread keeps is capped at `retain_limit`.
|
||||||
threadlocal var thread_arena: ?std.heap.ArenaAllocator = null;
|
threadlocal var thread_arena: ?BumpArena = null;
|
||||||
const retain_limit = 64 << 20;
|
const retain_limit = 64 << 20;
|
||||||
|
|
||||||
fn run(source: *const Buffer, wargs: []const ?[*:0]const WCHAR, include: ?*anyopaque) error{ OutOfMemory, InvalidArgument }!*Result {
|
fn run(source: *const Buffer, wargs: []const ?[*:0]const WCHAR, include: ?*anyopaque) error{ OutOfMemory, InvalidArgument }!*Result {
|
||||||
|
|
|
||||||
|
|
@ -6,6 +6,7 @@
|
||||||
//! signed DXIL container.
|
//! signed DXIL container.
|
||||||
|
|
||||||
const std = @import("std");
|
const std = @import("std");
|
||||||
|
const BumpArena = @import("../BumpArena.zig");
|
||||||
const Allocator = std.mem.Allocator;
|
const Allocator = std.mem.Allocator;
|
||||||
const ir = @import("../ir/ir.zig");
|
const ir = @import("../ir/ir.zig");
|
||||||
const types = @import("../sema/types.zig");
|
const types = @import("../sema/types.zig");
|
||||||
|
|
@ -52,7 +53,7 @@ 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 {
|
||||||
var arena_state = std.heap.ArenaAllocator.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 = optimize };
|
||||||
defer e.dm.deinit();
|
defer e.dm.deinit();
|
||||||
|
|
@ -76,6 +77,10 @@ const Lowered = union(enum) {
|
||||||
/// per resource, each an alias of what is stored into it.
|
/// per resource, each an alias of what is stored into it.
|
||||||
agg_ptr: struct { data: ?*const Lowered, slots: []const u32, ty: TypeId },
|
agg_ptr: struct { data: ?*const Lowered, slots: []const u32, ty: TypeId },
|
||||||
ptr: Ptr,
|
ptr: Ptr,
|
||||||
|
/// A by-value parameter's copy that is never written and only indexed
|
||||||
|
/// by constants (Emitter.regsLocals): the argument's components, from
|
||||||
|
/// `offset` on, with no memory behind them.
|
||||||
|
regs: struct { vals: []const Value, offset: u32 = 0 },
|
||||||
/// A resource handle (index into Emitter.resources).
|
/// A resource handle (index into Emitter.resources).
|
||||||
handle: u32,
|
handle: u32,
|
||||||
/// A local holding a resource (index into Emitter.res_locals): an
|
/// A local holding a resource (index into Emitter.res_locals): an
|
||||||
|
|
@ -168,6 +173,8 @@ const Resource = struct {
|
||||||
|
|
||||||
const Frame = struct {
|
const Frame = struct {
|
||||||
f: *const ir.Function,
|
f: *const ir.Function,
|
||||||
|
/// For inlined calls: Emitter.regsLocals of `f`.
|
||||||
|
regs: []const bool = &.{},
|
||||||
vals: []Lowered,
|
vals: []Lowered,
|
||||||
params: []const Lowered,
|
params: []const Lowered,
|
||||||
blocks: []?u32,
|
blocks: []?u32,
|
||||||
|
|
@ -196,7 +203,56 @@ const Frame = struct {
|
||||||
arrays: std.ArrayList(struct { ty: TypeId, ptr: Ptr }) = .empty,
|
arrays: std.ArrayList(struct { ty: TypeId, ptr: Ptr }) = .empty,
|
||||||
};
|
};
|
||||||
|
|
||||||
const PInst = struct { inst: module.Inst, id: u32 };
|
/// Hash maps keyed by a Value (or a Value and an offset). A Value has
|
||||||
|
/// padding, so the automatic context hashes it field by field; this one
|
||||||
|
/// mixes its tag and index into one word.
|
||||||
|
fn ValueMap(comptime V: type) type {
|
||||||
|
return std.HashMapUnmanaged(Value, V, ValueContext, std.hash_map.default_max_load_percentage);
|
||||||
|
}
|
||||||
|
|
||||||
|
const ValueContext = struct {
|
||||||
|
fn word(v: Value) u64 {
|
||||||
|
return @as(u64, @backingInt(v)) << 32 | switch (v) {
|
||||||
|
inline else => |x| x,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
fn mix(x: u64) u64 {
|
||||||
|
var z = x;
|
||||||
|
z = (z ^ (z >> 30)) *% 0xbf58476d1ce4e5b9;
|
||||||
|
z = (z ^ (z >> 27)) *% 0x94d049bb133111eb;
|
||||||
|
return z ^ (z >> 31);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn hash(_: ValueContext, k: anytype) u64 {
|
||||||
|
return switch (@TypeOf(k)) {
|
||||||
|
Value => mix(word(k)),
|
||||||
|
else => mix(word(k[0]) ^ @as(u64, k[1]) << 40),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn eql(_: ValueContext, a: anytype, b: @TypeOf(a)) bool {
|
||||||
|
return std.meta.eql(a, b);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
/// The current function's instructions, by id, in chunks that never move
|
||||||
|
/// (blocks and the prologue list ids).
|
||||||
|
const InstStore = struct {
|
||||||
|
const shift = 10;
|
||||||
|
const chunk_len = 1 << shift;
|
||||||
|
chunks: std.ArrayList(*[chunk_len]module.Inst) = .empty,
|
||||||
|
|
||||||
|
/// Stores instruction `id`, the next one.
|
||||||
|
fn put(s: *InstStore, a: Allocator, id: u32, inst: module.Inst) Allocator.Error!void {
|
||||||
|
if (id >> shift >= s.chunks.items.len) try s.chunks.append(a, try a.create([chunk_len]module.Inst));
|
||||||
|
s.chunks.items[id >> shift][id & (chunk_len - 1)] = inst;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn at(s: *const InstStore, id: u32) *module.Inst {
|
||||||
|
return &s.chunks.items[id >> shift][id & (chunk_len - 1)];
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const Emitter = struct {
|
const Emitter = struct {
|
||||||
arena: Allocator,
|
arena: Allocator,
|
||||||
|
|
@ -215,8 +271,9 @@ const Emitter = struct {
|
||||||
payload_global: ?u32 = null,
|
payload_global: ?u32 = null,
|
||||||
payload_local: ?struct { func: *const ir.Function, inst: u32 } = null,
|
payload_local: ?struct { func: *const ir.Function, inst: u32 } = null,
|
||||||
/// Instructions per block, in creation order, with provisional ids.
|
/// Instructions per block, in creation order, with provisional ids.
|
||||||
blocks: std.ArrayList(std.ArrayList(PInst)) = .empty,
|
insts: InstStore = .{},
|
||||||
prologue: std.ArrayList(PInst) = .empty,
|
blocks: std.ArrayList(std.ArrayList(u32)) = .empty,
|
||||||
|
prologue: std.ArrayList(u32) = .empty,
|
||||||
next_id: u32 = 0,
|
next_id: u32 = 0,
|
||||||
/// Each instruction's type, by id.
|
/// Each instruction's type, by id.
|
||||||
inst_types: std.ArrayList(DType) = .empty,
|
inst_types: std.ArrayList(DType) = .empty,
|
||||||
|
|
@ -228,12 +285,12 @@ const Emitter = struct {
|
||||||
private_typed: std.AutoHashMapUnmanaged(u32, @FieldType(Lowered, "typed")) = .empty,
|
private_typed: std.AutoHashMapUnmanaged(u32, @FieldType(Lowered, "typed")) = .empty,
|
||||||
/// Locals holding a copy of a texel read through an index (see the
|
/// Locals holding a copy of a texel read through an index (see the
|
||||||
/// `access` op): writes through them would not reach the texture.
|
/// `access` op): writes through them would not reach the texture.
|
||||||
texel_copies: std.AutoHashMapUnmanaged(Value, void) = .empty,
|
texel_copies: ValueMap(void) = .empty,
|
||||||
/// Static globals holding resources (as locals: Emitter.aggLocal).
|
/// Static globals holding resources (as locals: Emitter.aggLocal).
|
||||||
private_aggs: std.AutoHashMapUnmanaged(u32, Lowered) = .empty,
|
private_aggs: std.AutoHashMapUnmanaged(u32, Lowered) = .empty,
|
||||||
res_locals: std.ArrayList(?Lowered) = .empty,
|
res_locals: std.ArrayList(?Lowered) = .empty,
|
||||||
/// Indices marked with NonUniformResourceIndex.
|
/// Indices marked with NonUniformResourceIndex.
|
||||||
nonuniform: std.AutoHashMapUnmanaged(Value, void) = .empty,
|
nonuniform: ValueMap(void) = .empty,
|
||||||
uses_double: bool = false,
|
uses_double: bool = false,
|
||||||
uses_int64: bool = false,
|
uses_int64: bool = false,
|
||||||
/// 16-bit min-precision values cross the signature.
|
/// 16-bit min-precision values cross the signature.
|
||||||
|
|
@ -266,8 +323,8 @@ const Emitter = struct {
|
||||||
last_resret: Value = undefined,
|
last_resret: Value = undefined,
|
||||||
/// Status values, forwarded through locals within a block: the
|
/// Status values, forwarded through locals within a block: the
|
||||||
/// validator wants CheckAccessFullyMapped's operand to be one.
|
/// validator wants CheckAccessFullyMapped's operand to be one.
|
||||||
status_vals: std.AutoHashMapUnmanaged(Value, void) = .empty,
|
status_vals: ValueMap(void) = .empty,
|
||||||
forwarded: std.AutoHashMapUnmanaged(struct { Value, u32 }, struct { v: Value, block: u32 }) = .empty,
|
forwarded: std.HashMapUnmanaged(struct { Value, u32 }, struct { v: Value, block: u32 }, ValueContext, std.hash_map.default_max_load_percentage) = .empty,
|
||||||
/// Dynamically indexed getelementptrs into locals (by id) and the
|
/// Dynamically indexed getelementptrs into locals (by id) and the
|
||||||
/// components they can reach, for promote.run.
|
/// components they can reach, for promote.run.
|
||||||
dyn_ranges: std.AutoHashMapUnmanaged(u32, [2]u32) = .empty,
|
dyn_ranges: std.AutoHashMapUnmanaged(u32, [2]u32) = .empty,
|
||||||
|
|
@ -280,6 +337,7 @@ const Emitter = struct {
|
||||||
writes: u32 = 0,
|
writes: u32 = 0,
|
||||||
/// paramCopies per IR function.
|
/// paramCopies per IR function.
|
||||||
param_copies: std.AutoHashMapUnmanaged(u32, []const u32) = .empty,
|
param_copies: std.AutoHashMapUnmanaged(u32, []const u32) = .empty,
|
||||||
|
regs_locals: std.AutoHashMapUnmanaged(u32, []const bool) = .empty,
|
||||||
uses_barycentrics: bool = false,
|
uses_barycentrics: bool = false,
|
||||||
uses_sampler_heap: bool = false,
|
uses_sampler_heap: bool = false,
|
||||||
/// The shader's reflection (reflect.zig), made with the object; owned
|
/// The shader's reflection (reflect.zig), made with the object; owned
|
||||||
|
|
@ -316,6 +374,16 @@ const Emitter = struct {
|
||||||
/// Each HLSL struct's module type (struct types are named, and two
|
/// Each HLSL struct's module type (struct types are named, and two
|
||||||
/// structs may share a name: `A<int>::In`, `A<float>::In`).
|
/// structs may share a name: `A<int>::In`, `A<float>::In`).
|
||||||
struct_types: std.AutoHashMapUnmanaged(TypeId, DType) = .empty,
|
struct_types: std.AutoHashMapUnmanaged(TypeId, DType) = .empty,
|
||||||
|
/// Per type: see structComps, mixedSizes and mixedStorage.
|
||||||
|
struct_comps: std.AutoHashMapUnmanaged(TypeId, []const TypeId) = .empty,
|
||||||
|
comp_offsets: std.AutoHashMapUnmanaged(struct { TypeId, bool, layout.Rules }, []const u32) = .empty,
|
||||||
|
field_offsets: std.AutoHashMapUnmanaged(struct { *const types.StructInfo, layout.Rules }, []const u32) = .empty,
|
||||||
|
/// elementPtr's last pointer type, and its shared index slices (by the
|
||||||
|
/// index constant).
|
||||||
|
elem_ptr_ty: struct { elem: DType = std.math.maxInt(DType), space: u32 = 0, ty: DType = 0 } = .{},
|
||||||
|
zero_indexed: std.ArrayList([]const Value) = .empty,
|
||||||
|
mixed_sizes: std.AutoHashMapUnmanaged(TypeId, bool) = .empty,
|
||||||
|
mixed_storage: std.AutoHashMapUnmanaged(TypeId, bool) = .empty,
|
||||||
/// Prologue instructions dropped again if unused (resource handles).
|
/// Prologue instructions dropped again if unused (resource handles).
|
||||||
lib_removable: std.AutoHashMapUnmanaged(u32, void) = .empty,
|
lib_removable: std.AutoHashMapUnmanaged(u32, void) = .empty,
|
||||||
|
|
||||||
|
|
@ -343,7 +411,8 @@ const Emitter = struct {
|
||||||
},
|
},
|
||||||
else => {},
|
else => {},
|
||||||
}
|
}
|
||||||
try e.blocks.items[e.cur].append(e.arena, .{ .inst = .{ .ty = ty, .op = op }, .id = id });
|
try e.insts.put(e.arena, id, .{ .ty = ty, .op = op });
|
||||||
|
try e.blocks.items[e.cur].append(e.arena, id);
|
||||||
return .{ .inst = id };
|
return .{ .inst = id };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -351,7 +420,8 @@ const Emitter = struct {
|
||||||
const id = e.next_id;
|
const id = e.next_id;
|
||||||
e.next_id += 1;
|
e.next_id += 1;
|
||||||
try e.inst_types.append(e.arena, ty);
|
try e.inst_types.append(e.arena, ty);
|
||||||
try e.prologue.append(e.arena, .{ .inst = .{ .ty = ty, .op = op }, .id = id });
|
try e.insts.put(e.arena, id, .{ .ty = ty, .op = op });
|
||||||
|
try e.prologue.append(e.arena, id);
|
||||||
return .{ .inst = id };
|
return .{ .inst = id };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -417,15 +487,58 @@ const Emitter = struct {
|
||||||
.vector => |v| v.len,
|
.vector => |v| v.len,
|
||||||
.matrix => |m| @as(u32, m.rows) * m.cols,
|
.matrix => |m| @as(u32, m.rows) * m.cols,
|
||||||
.array => |a| a.len * try e.flatCount(a.elem),
|
.array => |a| a.len * try e.flatCount(a.elem),
|
||||||
.@"struct" => |s| blk: {
|
.@"struct" => @intCast((try e.structComps(ty)).len),
|
||||||
var n: u32 = 0;
|
|
||||||
for (s.fields.items) |f| n += try e.flatCount(f.type);
|
|
||||||
break :blk n;
|
|
||||||
},
|
|
||||||
else => e.unsupported("values of type '{s}' are not supported yet", .{try e.t.format(e.arena, ty)}),
|
else => e.unsupported("values of type '{s}' are not supported yet", .{try e.t.format(e.arena, ty)}),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Byte offsets of `st`'s fields under `rules`, worked out once per
|
||||||
|
/// struct.
|
||||||
|
fn fieldOffsets(e: *Emitter, st: *const types.StructInfo, rules: layout.Rules) layout.Error![]const u32 {
|
||||||
|
const gop = try e.field_offsets.getOrPut(e.arena, .{ st, rules });
|
||||||
|
if (gop.found_existing) return gop.value_ptr.*;
|
||||||
|
gop.value_ptr.* = layout.fieldOffsets(e.arena, e.t, st, rules) catch |err| {
|
||||||
|
_ = e.field_offsets.remove(.{ st, rules });
|
||||||
|
return err;
|
||||||
|
};
|
||||||
|
return gop.value_ptr.*;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// layout.componentOffset, from a table of `ty`'s components worked out
|
||||||
|
/// once per type.
|
||||||
|
fn componentOffset(e: *Emitter, ty: TypeId, row_major: bool, k: u32, rules: layout.Rules) layout.Error!u32 {
|
||||||
|
const gop = try e.comp_offsets.getOrPut(e.arena, .{ ty, row_major, rules });
|
||||||
|
if (!gop.found_existing) {
|
||||||
|
gop.value_ptr.* = &.{};
|
||||||
|
const n = layout.flatCount(e.t, ty) catch 0;
|
||||||
|
// (Small types: worked out each time, as cheaply.)
|
||||||
|
if (n > 4) {
|
||||||
|
const table = try e.arena.alloc(u32, n);
|
||||||
|
const ok = for (table, 0..) |*o, c| {
|
||||||
|
o.* = layout.componentOffset(e.arena, e.t, ty, row_major, @intCast(c), rules) catch break false;
|
||||||
|
} else true;
|
||||||
|
if (ok) gop.value_ptr.* = table;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const table = gop.value_ptr.*;
|
||||||
|
if (k < table.len) return table[k];
|
||||||
|
return layout.componentOffset(e.arena, e.t, ty, row_major, k, rules);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The scalar type of each flattened component of struct `ty`, worked
|
||||||
|
/// out once per type.
|
||||||
|
fn structComps(e: *Emitter, ty: TypeId) Error![]const TypeId {
|
||||||
|
if (e.struct_comps.get(ty)) |c| return c;
|
||||||
|
var out: std.ArrayList(TypeId) = .empty;
|
||||||
|
for (e.t.get(ty).@"struct".fields.items) |f| {
|
||||||
|
const n = try e.flatCount(f.type);
|
||||||
|
try out.ensureUnusedCapacity(e.arena, n);
|
||||||
|
for (0..n) |k| out.appendAssumeCapacity(try e.componentType(f.type, @intCast(k)));
|
||||||
|
}
|
||||||
|
try e.struct_comps.put(e.arena, ty, out.items);
|
||||||
|
return out.items;
|
||||||
|
}
|
||||||
|
|
||||||
/// Undefined values for the flattened components of `ty`.
|
/// Undefined values for the flattened components of `ty`.
|
||||||
fn undefValues(e: *Emitter, ty: TypeId) Error![]const Value {
|
fn undefValues(e: *Emitter, ty: TypeId) Error![]const Value {
|
||||||
var out: std.ArrayList(Value) = .empty;
|
var out: std.ArrayList(Value) = .empty;
|
||||||
|
|
@ -524,6 +637,7 @@ const Emitter = struct {
|
||||||
e.call_memo = .empty;
|
e.call_memo = .empty;
|
||||||
e.texel_copies = .empty;
|
e.texel_copies = .empty;
|
||||||
e.next_id = 0;
|
e.next_id = 0;
|
||||||
|
e.insts = .{};
|
||||||
e.inst_types = .empty;
|
e.inst_types = .empty;
|
||||||
e.private_globals = .empty;
|
e.private_globals = .empty;
|
||||||
e.private_typed = .empty;
|
e.private_typed = .empty;
|
||||||
|
|
@ -713,6 +827,7 @@ const Emitter = struct {
|
||||||
e.call_memo = .empty;
|
e.call_memo = .empty;
|
||||||
e.texel_copies = .empty;
|
e.texel_copies = .empty;
|
||||||
e.next_id = 0;
|
e.next_id = 0;
|
||||||
|
e.insts = .{};
|
||||||
e.inst_types = .empty;
|
e.inst_types = .empty;
|
||||||
e.private_globals = .empty;
|
e.private_globals = .empty;
|
||||||
e.private_typed = .empty;
|
e.private_typed = .empty;
|
||||||
|
|
@ -748,6 +863,7 @@ const Emitter = struct {
|
||||||
e.call_memo = .empty;
|
e.call_memo = .empty;
|
||||||
e.texel_copies = .empty;
|
e.texel_copies = .empty;
|
||||||
e.next_id = 0;
|
e.next_id = 0;
|
||||||
|
e.insts = .{};
|
||||||
e.inst_types = .empty;
|
e.inst_types = .empty;
|
||||||
e.private_globals = .empty;
|
e.private_globals = .empty;
|
||||||
e.private_typed = .empty;
|
e.private_typed = .empty;
|
||||||
|
|
@ -918,6 +1034,7 @@ const Emitter = struct {
|
||||||
e.call_memo = .empty;
|
e.call_memo = .empty;
|
||||||
e.texel_copies = .empty;
|
e.texel_copies = .empty;
|
||||||
e.next_id = 0;
|
e.next_id = 0;
|
||||||
|
e.insts = .{};
|
||||||
e.inst_types = .empty;
|
e.inst_types = .empty;
|
||||||
e.private_globals = .empty;
|
e.private_globals = .empty;
|
||||||
e.private_typed = .empty;
|
e.private_typed = .empty;
|
||||||
|
|
@ -1360,12 +1477,12 @@ const Emitter = struct {
|
||||||
if (e.lib_removable.count() > 0) try e.pruneProlog();
|
if (e.lib_removable.count() > 0) try e.pruneProlog();
|
||||||
const map = try e.arena.alloc(u32, e.next_id);
|
const map = try e.arena.alloc(u32, e.next_id);
|
||||||
var n: u32 = 0;
|
var n: u32 = 0;
|
||||||
for (e.prologue.items) |pi| {
|
for (e.prologue.items) |id| {
|
||||||
map[pi.id] = n;
|
map[id] = n;
|
||||||
n += 1;
|
n += 1;
|
||||||
}
|
}
|
||||||
for (e.blocks.items) |blk| for (blk.items) |pi| {
|
for (e.blocks.items) |blk| for (blk.items) |id| {
|
||||||
map[pi.id] = n;
|
map[id] = n;
|
||||||
n += 1;
|
n += 1;
|
||||||
};
|
};
|
||||||
const f = &e.dm.functions.items[func];
|
const f = &e.dm.functions.items[func];
|
||||||
|
|
@ -1375,6 +1492,11 @@ const Emitter = struct {
|
||||||
return if (x == .inst) .{ .inst = mp[x.inst] } else x;
|
return if (x == .inst) .{ .inst = mp[x.inst] } else x;
|
||||||
}
|
}
|
||||||
fn vs(a: Allocator, mp: []const u32, xs: []const Value) Allocator.Error![]const Value {
|
fn vs(a: Allocator, mp: []const u32, xs: []const Value) Allocator.Error![]const Value {
|
||||||
|
// (Nothing to renumber, as in most getelementptr indices:
|
||||||
|
// the slice is kept; no pass writes operand slices.)
|
||||||
|
for (xs) |x| {
|
||||||
|
if (x == .inst) break;
|
||||||
|
} else return xs;
|
||||||
const out = try a.alloc(Value, xs.len);
|
const out = try a.alloc(Value, xs.len);
|
||||||
for (xs, out) |x, *o| o.* = v(mp, x);
|
for (xs, out) |x, *o| o.* = v(mp, x);
|
||||||
return out;
|
return out;
|
||||||
|
|
@ -1382,9 +1504,17 @@ const Emitter = struct {
|
||||||
};
|
};
|
||||||
stats.add(.dxil_lowered, n);
|
stats.add(.dxil_lowered, n);
|
||||||
try f.insts.ensureUnusedCapacity(e.dm.allocator(), n);
|
try f.insts.ensureUnusedCapacity(e.dm.allocator(), n);
|
||||||
const all = [_][]const PInst{e.prologue.items};
|
// (Copied into place, then renumbered there.)
|
||||||
for (all) |items| for (items) |pi| try f.insts.append(e.dm.allocator(), try remapInst(e.arena, map, pi.inst, remap));
|
for (e.prologue.items) |id| {
|
||||||
for (e.blocks.items) |blk| for (blk.items) |pi| try f.insts.append(e.dm.allocator(), try remapInst(e.arena, map, pi.inst, remap));
|
const dst = f.insts.addOneAssumeCapacity();
|
||||||
|
dst.* = e.insts.at(id).*;
|
||||||
|
try remapInst(e.arena, map, dst, remap);
|
||||||
|
}
|
||||||
|
for (e.blocks.items) |blk| for (blk.items) |id| {
|
||||||
|
const dst = f.insts.addOneAssumeCapacity();
|
||||||
|
dst.* = e.insts.at(id).*;
|
||||||
|
try remapInst(e.arena, map, dst, remap);
|
||||||
|
};
|
||||||
var ranges: std.AutoHashMapUnmanaged(u32, [2]u32) = .empty;
|
var ranges: std.AutoHashMapUnmanaged(u32, [2]u32) = .empty;
|
||||||
var it = e.dyn_ranges.iterator();
|
var it = e.dyn_ranges.iterator();
|
||||||
while (it.next()) |kv| try ranges.put(e.arena, map[kv.key_ptr.*], kv.value_ptr.*);
|
while (it.next()) |kv| try ranges.put(e.arena, map[kv.key_ptr.*], kv.value_ptr.*);
|
||||||
|
|
@ -1423,13 +1553,12 @@ const Emitter = struct {
|
||||||
while (changed) {
|
while (changed) {
|
||||||
changed = false;
|
changed = false;
|
||||||
@memset(used, false);
|
@memset(used, false);
|
||||||
const all = [_][]const PInst{e.prologue.items};
|
for (e.prologue.items) |id| markUses(e.arena, e.insts.at(id).*, used);
|
||||||
for (all) |items| for (items) |pi| markUses(e.arena, pi.inst, used);
|
for (e.blocks.items) |blk| for (blk.items) |id| markUses(e.arena, e.insts.at(id).*, used);
|
||||||
for (e.blocks.items) |blk| for (blk.items) |pi| markUses(e.arena, pi.inst, used);
|
|
||||||
var k: usize = 0;
|
var k: usize = 0;
|
||||||
while (k < e.prologue.items.len) {
|
while (k < e.prologue.items.len) {
|
||||||
const pi = e.prologue.items[k];
|
const id = e.prologue.items[k];
|
||||||
if (e.lib_removable.contains(pi.id) and !used[pi.id]) {
|
if (e.lib_removable.contains(id) and !used[id]) {
|
||||||
_ = e.prologue.orderedRemove(k);
|
_ = e.prologue.orderedRemove(k);
|
||||||
changed = true;
|
changed = true;
|
||||||
} else k += 1;
|
} else k += 1;
|
||||||
|
|
@ -1451,11 +1580,11 @@ const Emitter = struct {
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
M.u = used;
|
M.u = used;
|
||||||
_ = remapInst(a, &.{}, inst, M) catch {};
|
var copy = inst;
|
||||||
|
remapInst(a, &.{}, ©, M) catch {};
|
||||||
}
|
}
|
||||||
|
|
||||||
fn remapInst(a: Allocator, map: []const u32, inst: module.Inst, comptime R: type) Allocator.Error!module.Inst {
|
fn remapInst(a: Allocator, map: []const u32, out: *module.Inst, comptime R: type) Allocator.Error!void {
|
||||||
var out = inst;
|
|
||||||
switch (out.op) {
|
switch (out.op) {
|
||||||
.ret => |*v| if (v.*) |x| {
|
.ret => |*v| if (v.*) |x| {
|
||||||
v.* = R.v(map, x);
|
v.* = R.v(map, x);
|
||||||
|
|
@ -1515,7 +1644,6 @@ const Emitter = struct {
|
||||||
x.index = R.v(map, x.index);
|
x.index = R.v(map, x.index);
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
return out;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ------------------------------------------------------------------
|
// ------------------------------------------------------------------
|
||||||
|
|
@ -1553,7 +1681,7 @@ const Emitter = struct {
|
||||||
try e.prologue.appendSlice(e.arena, items[from .. items.len - 1]);
|
try e.prologue.appendSlice(e.arena, items[from .. items.len - 1]);
|
||||||
items[from] = br;
|
items[from] = br;
|
||||||
e.blocks.items[b].items.len = from + 1;
|
e.blocks.items[b].items.len = from + 1;
|
||||||
b = br.inst.op.br.then;
|
b = e.insts.at(br).op.br.then;
|
||||||
from = 0;
|
from = 0;
|
||||||
}
|
}
|
||||||
e.forwarded.clearRetainingCapacity();
|
e.forwarded.clearRetainingCapacity();
|
||||||
|
|
@ -1571,11 +1699,11 @@ const Emitter = struct {
|
||||||
while (b != e.cur) {
|
while (b != e.cur) {
|
||||||
const items = e.blocks.items[b].items;
|
const items = e.blocks.items[b].items;
|
||||||
if (items.len <= from) return false;
|
if (items.len <= from) return false;
|
||||||
for (items[from .. items.len - 1]) |pi| switch (pi.inst.op) {
|
for (items[from .. items.len - 1]) |id| switch (e.insts.at(id).op) {
|
||||||
.br, .@"switch", .ret, .phi => return false,
|
.br, .@"switch", .ret, .phi => return false,
|
||||||
else => {},
|
else => {},
|
||||||
};
|
};
|
||||||
const last = items[items.len - 1].inst.op;
|
const last = e.insts.at(items[items.len - 1]).op;
|
||||||
if (last != .br or last.br.cond != null or last.br.then < first_new) return false;
|
if (last != .br or last.br.cond != null or last.br.then < first_new) return false;
|
||||||
b = last.br.then;
|
b = last.br.then;
|
||||||
from = 0;
|
from = 0;
|
||||||
|
|
@ -1665,6 +1793,7 @@ const Emitter = struct {
|
||||||
@memset(frame.vals, .none);
|
@memset(frame.vals, .none);
|
||||||
@memset(frame.blocks, null);
|
@memset(frame.blocks, null);
|
||||||
if (e.optimize and args.len > 0) frame.copies = try e.paramCopies(fi);
|
if (e.optimize and args.len > 0) frame.copies = try e.paramCopies(fi);
|
||||||
|
if (e.optimize) frame.regs = try e.regsLocals(fi);
|
||||||
const is_entry = e.cur == 0 and e.blocks.items[0].items.len == 0 and (fi == e.entry.wrapper or fi == e.entry.patch_wrapper);
|
const is_entry = e.cur == 0 and e.blocks.items[0].items.len == 0 and (fi == e.entry.wrapper or fi == e.entry.patch_wrapper);
|
||||||
if (!is_entry) frame.cont = try e.newBlock();
|
if (!is_entry) frame.cont = try e.newBlock();
|
||||||
// The callee's entry continues the current block.
|
// The callee's entry continues the current block.
|
||||||
|
|
@ -1746,6 +1875,112 @@ const Emitter = struct {
|
||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// For each instruction of IR function `fi`: whether it is a local
|
||||||
|
/// that can be the values stored into it (see Lowered.regs), indexed
|
||||||
|
/// only by constants and either a copy of a parameter (paramCopies) or
|
||||||
|
/// stored once, whole, in the entry block before any other use of it
|
||||||
|
/// (and otherwise only read).
|
||||||
|
fn regsLocals(e: *Emitter, fi: u32) Error![]const bool {
|
||||||
|
const gop = try e.regs_locals.getOrPut(e.arena, fi);
|
||||||
|
if (gop.found_existing) return gop.value_ptr.*;
|
||||||
|
const none = std.math.maxInt(u32);
|
||||||
|
const f = e.m.functions.items[fi];
|
||||||
|
const copies = try e.paramCopies(fi);
|
||||||
|
const n = copies.len;
|
||||||
|
const out = try e.arena.alloc(bool, n);
|
||||||
|
for (out, copies) |*o, c| o.* = c != none;
|
||||||
|
|
||||||
|
// Locals stored once from a value. The local each pointer is into:
|
||||||
|
const root = try e.arena.alloc(u32, n);
|
||||||
|
@memset(root, none);
|
||||||
|
var changed = true;
|
||||||
|
while (changed) {
|
||||||
|
changed = false;
|
||||||
|
for (f.insts.items, 0..) |inst, k| {
|
||||||
|
const want: u32 = switch (inst.op) {
|
||||||
|
.local_var => @intCast(k),
|
||||||
|
.access => |x| root[x.base.index()],
|
||||||
|
else => none,
|
||||||
|
};
|
||||||
|
if (want != root[k]) {
|
||||||
|
root[k] = want;
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const stores = try e.arena.alloc(u32, n);
|
||||||
|
@memset(stores, 0);
|
||||||
|
const bad = try e.arena.alloc(bool, n);
|
||||||
|
@memset(bad, false);
|
||||||
|
const Use = struct {
|
||||||
|
root: []const u32,
|
||||||
|
bad: []bool,
|
||||||
|
pub fn map(u: @This(), x: Ref) Ref {
|
||||||
|
if (x != .none and u.root[x.index()] != none) u.bad[u.root[x.index()]] = true;
|
||||||
|
return x;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const use: Use = .{ .root = root, .bad = bad };
|
||||||
|
for (f.insts.items) |inst| switch (inst.op) {
|
||||||
|
.local_var, .load => {},
|
||||||
|
.access => |x| for (x.indices) |ix| {
|
||||||
|
_ = use.map(ix);
|
||||||
|
},
|
||||||
|
.store => |x| {
|
||||||
|
_ = use.map(x.value);
|
||||||
|
const l = root[x.ptr.index()];
|
||||||
|
if (l == none) continue;
|
||||||
|
if (x.ptr.index() != l) bad[l] = true;
|
||||||
|
stores[l] += 1;
|
||||||
|
},
|
||||||
|
else => _ = try opt.mapOp(e.arena, inst.op, use),
|
||||||
|
};
|
||||||
|
// The store: in the entry block (not branched back to), before any
|
||||||
|
// load or access of the local there.
|
||||||
|
var reentered = false;
|
||||||
|
for (f.blocks.items) |blk| switch (blk.term) {
|
||||||
|
.br => |t| reentered = reentered or t.index() == 0,
|
||||||
|
.cond_br => |c| reentered = reentered or c.then.index() == 0 or c.@"else".index() == 0,
|
||||||
|
.@"switch" => |sw| {
|
||||||
|
reentered = reentered or sw.default.index() == 0;
|
||||||
|
for (sw.cases) |cs| reentered = reentered or cs.block.index() == 0;
|
||||||
|
},
|
||||||
|
else => {},
|
||||||
|
};
|
||||||
|
if (!reentered and f.blocks.items.len > 0) {
|
||||||
|
const used = try e.arena.alloc(bool, n);
|
||||||
|
@memset(used, false);
|
||||||
|
for (f.blocks.items[0].insts.items) |r| {
|
||||||
|
const inst = f.inst(r);
|
||||||
|
switch (inst.op) {
|
||||||
|
.load => |p| if (root[p.index()] != none) {
|
||||||
|
used[root[p.index()]] = true;
|
||||||
|
},
|
||||||
|
.access => if (root[r.index()] != none) {
|
||||||
|
used[root[r.index()]] = true;
|
||||||
|
},
|
||||||
|
.store => |x| {
|
||||||
|
const l = root[x.ptr.index()];
|
||||||
|
if (l == none or used[l] or bad[l] or stores[l] != 1 or copies[l] != none) continue;
|
||||||
|
if (f.inst(x.value).op == .param) continue;
|
||||||
|
const ty = f.inst(@fromBackingInt(@intCast(l))).ty;
|
||||||
|
if (isResourceType(e.t, ty) or e.holdsResources(ty) or e.containsLinAlg(ty) or isRayQuery(e.t, ty)) continue;
|
||||||
|
out[l] = true;
|
||||||
|
},
|
||||||
|
else => {},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Only constant indices.
|
||||||
|
for (f.insts.items, 0..) |inst, k| if (inst.op == .access and root[k] != none) {
|
||||||
|
for (inst.op.access.indices) |ix| if (f.inst(ix).op != .constant or f.inst(ix).op.constant != .int) {
|
||||||
|
out[root[k]] = false;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
gop.value_ptr.* = out;
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
/// For each instruction of IR function `fi`: the parameter a
|
/// For each instruction of IR function `fi`: the parameter a
|
||||||
/// `local_var` only ever holds a copy of (stored once, from that
|
/// `local_var` only ever holds a copy of (stored once, from that
|
||||||
/// by-value parameter, and otherwise only read), else maxInt.
|
/// by-value parameter, and otherwise only read), else maxInt.
|
||||||
|
|
@ -2088,6 +2323,15 @@ const Emitter = struct {
|
||||||
const k = frame.param_copies[r.index()];
|
const k = frame.param_copies[r.index()];
|
||||||
if (k != std.math.maxInt(u32)) if (frame.param_srcs[k]) |alias| return alias;
|
if (k != std.math.maxInt(u32)) if (frame.param_srcs[k]) |alias| return alias;
|
||||||
}
|
}
|
||||||
|
// A copy of a parameter passed as values, or a local stored
|
||||||
|
// once from a value before any use, never written again:
|
||||||
|
// those values (no alloca, no stores, no loads). Its store
|
||||||
|
// sets them.
|
||||||
|
if (frame.regs.len > 0 and frame.regs[r.index()]) {
|
||||||
|
const k = if (frame.copies.len > 0) frame.copies[r.index()] else std.math.maxInt(u32);
|
||||||
|
if (k == std.math.maxInt(u32)) return .{ .regs = .{ .vals = &.{} } };
|
||||||
|
if (frame.params[k] == .scalars) return .{ .regs = .{ .vals = frame.params[k].scalars } };
|
||||||
|
}
|
||||||
if (e.payload_local) |pl| if (pl.func == f and pl.inst == r.index()) {
|
if (e.payload_local) |pl| if (pl.func == f and pl.inst == r.index()) {
|
||||||
const dty = try e.memoryType(i.ty);
|
const dty = try e.memoryType(i.ty);
|
||||||
const base = try e.addPrologue(try e.dm.ptrType(dty), .{ .alloca = .{ .elem = dty, .size = try e.i32Const(1) } });
|
const base = try e.addPrologue(try e.dm.ptrType(dty), .{ .alloca = .{ .elem = dty, .size = try e.i32Const(1) } });
|
||||||
|
|
@ -2128,6 +2372,11 @@ const Emitter = struct {
|
||||||
return frame.params[frame.copies[p.index()]];
|
return frame.params[frame.copies[p.index()]];
|
||||||
} else switch (frame.vals[p.index()]) {
|
} else switch (frame.vals[p.index()]) {
|
||||||
.handle => |h| return .{ .handle = h },
|
.handle => |h| return .{ .handle = h },
|
||||||
|
.regs => |rg| {
|
||||||
|
const n = try e.flatCount(i.ty);
|
||||||
|
if (rg.offset + n > rg.vals.len) return .{ .scalars = try e.undefValues(i.ty) };
|
||||||
|
return .{ .scalars = rg.vals[rg.offset..][0..n] };
|
||||||
|
},
|
||||||
.agg_ptr => |ap| {
|
.agg_ptr => |ap| {
|
||||||
const vals: []const Value = if (ap.data) |d| switch (d.*) {
|
const vals: []const Value = if (ap.data) |d| switch (d.*) {
|
||||||
.ptr => |ptr| (try e.loadPtr(ptr, ap.ty)).scalars,
|
.ptr => |ptr| (try e.loadPtr(ptr, ap.ty)).scalars,
|
||||||
|
|
@ -2195,6 +2444,11 @@ const Emitter = struct {
|
||||||
else => |v| return e.unsupported("internal: load from a non-pointer ({s} from %{d} '{s}' in '{s}')", .{ @tagName(v), p.index(), @tagName(frame.f.inst(p).op), frame.f.name }),
|
else => |v| return e.unsupported("internal: load from a non-pointer ({s} from %{d} '{s}' in '{s}')", .{ @tagName(v), p.index(), @tagName(frame.f.inst(p).op), frame.f.name }),
|
||||||
},
|
},
|
||||||
.store => |s| {
|
.store => |s| {
|
||||||
|
// (The values a local kept as values holds.)
|
||||||
|
if (frame.vals[s.ptr.index()] == .regs) {
|
||||||
|
frame.vals[s.ptr.index()] = .{ .regs = .{ .vals = try e.scalars(frame, s.value) } };
|
||||||
|
return .none;
|
||||||
|
}
|
||||||
if (frame.param_copies.len > 0) if (f.inst(s.value).op == .param) {
|
if (frame.param_copies.len > 0) if (f.inst(s.value).op == .param) {
|
||||||
const k = f.inst(s.value).op.param;
|
const k = f.inst(s.value).op.param;
|
||||||
if (frame.param_copies[s.ptr.index()] == k and frame.param_srcs[k] != null) return .none;
|
if (frame.param_copies[s.ptr.index()] == k and frame.param_srcs[k] != null) return .none;
|
||||||
|
|
@ -2279,6 +2533,31 @@ const Emitter = struct {
|
||||||
return .{ .typed = tp };
|
return .{ .typed = tp };
|
||||||
}
|
}
|
||||||
if (frame.vals[a.base.index()] == .agg_ptr) return e.aggAccess(frame, frame.vals[a.base.index()].agg_ptr, a.indices);
|
if (frame.vals[a.base.index()] == .agg_ptr) return e.aggAccess(frame, frame.vals[a.base.index()].agg_ptr, a.indices);
|
||||||
|
if (frame.vals[a.base.index()] == .regs) {
|
||||||
|
var rg = frame.vals[a.base.index()].regs;
|
||||||
|
var cur = f.inst(a.base).ty;
|
||||||
|
for (a.indices) |x| {
|
||||||
|
const k: u32 = @intCast(@max(f.inst(x).op.constant.int, 0));
|
||||||
|
switch (e.t.get(cur)) {
|
||||||
|
.@"struct" => |st| {
|
||||||
|
if (k >= st.fields.items.len) return e.unsupported("struct member index out of range", .{});
|
||||||
|
for (st.fields.items[0..k]) |fld| rg.offset += try e.flatCount(fld.type);
|
||||||
|
cur = st.fields.items[k].type;
|
||||||
|
},
|
||||||
|
else => {
|
||||||
|
const elem: TypeId = switch (e.t.get(cur)) {
|
||||||
|
.array => |arr| arr.elem,
|
||||||
|
.vector => |v| try e.t.scalar(v.elem),
|
||||||
|
.matrix => |mt| try e.t.vector(mt.elem, mt.cols),
|
||||||
|
else => return e.unsupported("indexing this type is not supported yet", .{}),
|
||||||
|
};
|
||||||
|
rg.offset += k * try e.flatCount(elem);
|
||||||
|
cur = elem;
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return .{ .regs = rg };
|
||||||
|
}
|
||||||
// An element of a local array of resources: of the array
|
// An element of a local array of resources: of the array
|
||||||
// it aliases.
|
// it aliases.
|
||||||
if (frame.vals[a.base.index()] == .res_local) {
|
if (frame.vals[a.base.index()] == .res_local) {
|
||||||
|
|
@ -2752,6 +3031,18 @@ const Emitter = struct {
|
||||||
/// memory rather than a flat array).
|
/// memory rather than a flat array).
|
||||||
fn mixedSizes(e: *Emitter, ty: TypeId) Error!bool {
|
fn mixedSizes(e: *Emitter, ty: TypeId) Error!bool {
|
||||||
if (e.t.get(ty) != .@"struct" and e.t.get(ty) != .array) return false;
|
if (e.t.get(ty) != .@"struct" and e.t.get(ty) != .array) return false;
|
||||||
|
if (e.mixed_sizes.get(ty)) |v| return v;
|
||||||
|
const v = try e.checkMixedSizes(ty);
|
||||||
|
try e.mixed_sizes.put(e.arena, ty, v);
|
||||||
|
return v;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn checkMixedSizes(e: *Emitter, ty: TypeId) Error!bool {
|
||||||
|
// (An array's components repeat its element's.)
|
||||||
|
if (e.t.get(ty) == .array) {
|
||||||
|
const arr = e.t.get(ty).array;
|
||||||
|
return arr.len > 0 and try e.mixedSizes(arr.elem);
|
||||||
|
}
|
||||||
const n = try e.flatCount(ty);
|
const n = try e.flatCount(ty);
|
||||||
var size: ?u32 = null;
|
var size: ?u32 = null;
|
||||||
for (0..n) |k| {
|
for (0..n) |k| {
|
||||||
|
|
@ -2765,6 +3056,17 @@ const Emitter = struct {
|
||||||
/// Whether `ty`'s components differ in type (all 32-bit), so storage is
|
/// Whether `ty`'s components differ in type (all 32-bit), so storage is
|
||||||
/// i32 with bitcasts.
|
/// i32 with bitcasts.
|
||||||
fn mixedStorage(e: *Emitter, ty: TypeId) Error!bool {
|
fn mixedStorage(e: *Emitter, ty: TypeId) Error!bool {
|
||||||
|
if (e.mixed_storage.get(ty)) |v| return v;
|
||||||
|
const v = try e.checkMixedStorage(ty);
|
||||||
|
try e.mixed_storage.put(e.arena, ty, v);
|
||||||
|
return v;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn checkMixedStorage(e: *Emitter, ty: TypeId) Error!bool {
|
||||||
|
if (e.t.get(ty) == .array) {
|
||||||
|
const arr = e.t.get(ty).array;
|
||||||
|
return arr.len > 0 and try e.mixedStorage(arr.elem);
|
||||||
|
}
|
||||||
const n = try e.flatCount(ty);
|
const n = try e.flatCount(ty);
|
||||||
var first: ?Scalar = null;
|
var first: ?Scalar = null;
|
||||||
var mixed = false;
|
var mixed = false;
|
||||||
|
|
@ -2784,7 +3086,7 @@ const Emitter = struct {
|
||||||
const n = try e.flatCount(ty);
|
const n = try e.flatCount(ty);
|
||||||
const out = try e.arena.alloc(Value, n);
|
const out = try e.arena.alloc(Value, n);
|
||||||
for (out, 0..) |*o, c| {
|
for (out, 0..) |*o, c| {
|
||||||
if (ptr.offset_dyn == null) if (e.forwarded.get(.{ ptr.base, ptr.offset_const + @as(u32, @intCast(c)) })) |fw| if (fw.block == e.cur) {
|
if (ptr.offset_dyn == null and e.forwarded.count() > 0) if (e.forwarded.get(.{ ptr.base, ptr.offset_const + @as(u32, @intCast(c)) })) |fw| if (fw.block == e.cur) {
|
||||||
o.* = fw.v;
|
o.* = fw.v;
|
||||||
continue;
|
continue;
|
||||||
};
|
};
|
||||||
|
|
@ -2807,10 +3109,14 @@ const Emitter = struct {
|
||||||
for (vals, 0..) |v, c| {
|
for (vals, 0..) |v, c| {
|
||||||
if (ptr.offset_dyn == null) {
|
if (ptr.offset_dyn == null) {
|
||||||
const key = .{ ptr.base, ptr.offset_const + @as(u32, @intCast(c)) };
|
const key = .{ ptr.base, ptr.offset_const + @as(u32, @intCast(c)) };
|
||||||
// (Constants too, in locals: ops such as linear algebra
|
// (Every value stored to a local: later loads of it in the
|
||||||
// layouts need immediates passed through parameters.)
|
// block need no instructions, and constants stay constants,
|
||||||
const forward = e.status_vals.contains(v) or (v == .constant and ptr.addr_space == 0);
|
// as ops such as linear algebra layouts need immediates
|
||||||
if (forward) try e.forwarded.put(e.arena, key, .{ .v = v, .block = e.cur }) else _ = e.forwarded.remove(key);
|
// passed through parameters.)
|
||||||
|
const forward = ptr.addr_space == 0 or (e.status_vals.count() > 0 and e.status_vals.contains(v));
|
||||||
|
if (forward) {
|
||||||
|
try e.forwarded.put(e.arena, key, .{ .v = v, .block = e.cur });
|
||||||
|
} else if (e.forwarded.count() > 0) _ = e.forwarded.remove(key);
|
||||||
} else e.forwarded.clearRetainingCapacity();
|
} else e.forwarded.clearRetainingCapacity();
|
||||||
const p = try e.elementPtr(ptr, @intCast(c));
|
const p = try e.elementPtr(ptr, @intCast(c));
|
||||||
const ct = e.compOf(try e.componentType(ty, @intCast(c)));
|
const ct = e.compOf(try e.componentType(ty, @intCast(c)));
|
||||||
|
|
@ -2836,12 +3142,27 @@ const Emitter = struct {
|
||||||
fn elementPtr(e: *Emitter, ptr: Ptr, c: u32) Error!Value {
|
fn elementPtr(e: *Emitter, ptr: Ptr, c: u32) Error!Value {
|
||||||
var idx = try e.i32Const(ptr.offset_const + c);
|
var idx = try e.i32Const(ptr.offset_const + c);
|
||||||
if (ptr.offset_dyn) |d| idx = try e.add(try e.dm.intType(32), .{ .binop = .{ .op = .add, .lhs = d, .rhs = idx } });
|
if (ptr.offset_dyn) |d| idx = try e.add(try e.dm.intType(32), .{ .binop = .{ .op = .add, .lhs = d, .rhs = idx } });
|
||||||
const pt = try e.dm.getType(.{ .pointer = .{ .elem = ptr.scalar_ty, .addr_space = ptr.addr_space } });
|
if (e.elem_ptr_ty.elem != ptr.scalar_ty or e.elem_ptr_ty.space != ptr.addr_space) e.elem_ptr_ty = .{
|
||||||
const gep = try e.add(pt, .{ .gep = .{ .elem = ptr.array_ty, .ptr = ptr.base, .indices = try e.arena.dupe(Value, &.{ try e.i32Const(0), idx }) } });
|
.elem = ptr.scalar_ty,
|
||||||
|
.space = ptr.addr_space,
|
||||||
|
.ty = try e.dm.getType(.{ .pointer = .{ .elem = ptr.scalar_ty, .addr_space = ptr.addr_space } }),
|
||||||
|
};
|
||||||
|
const zero = try e.i32Const(0);
|
||||||
|
const gep = try e.add(e.elem_ptr_ty.ty, .{ .gep = .{ .elem = ptr.array_ty, .ptr = ptr.base, .indices = try e.zeroIndexed(zero, idx) } });
|
||||||
if (ptr.offset_dyn != null) if (ptr.dyn_range) |r| try e.dyn_ranges.put(e.arena, gep.inst, r);
|
if (ptr.offset_dyn != null) if (ptr.dyn_range) |r| try e.dyn_ranges.put(e.arena, gep.inst, r);
|
||||||
return gep;
|
return gep;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The indices `{ 0, idx }`, shared between getelementptrs with the
|
||||||
|
/// same constant `idx` (no pass writes operand slices).
|
||||||
|
fn zeroIndexed(e: *Emitter, zero: Value, idx: Value) Error![]const Value {
|
||||||
|
if (idx != .constant) return e.arena.dupe(Value, &.{ zero, idx });
|
||||||
|
const k = idx.constant;
|
||||||
|
if (k >= e.zero_indexed.items.len) try e.zero_indexed.appendNTimes(e.arena, &.{}, k + 1 - e.zero_indexed.items.len);
|
||||||
|
if (e.zero_indexed.items[k].len == 0) e.zero_indexed.items[k] = try e.arena.dupe(Value, &.{ zero, idx });
|
||||||
|
return e.zero_indexed.items[k];
|
||||||
|
}
|
||||||
|
|
||||||
fn convertScalar(e: *Emitter, v: Value, from: Scalar, to: Scalar) Error!Value {
|
fn convertScalar(e: *Emitter, v: Value, from: Scalar, to: Scalar) Error!Value {
|
||||||
if (from == to) return v;
|
if (from == to) return v;
|
||||||
const tt = try e.scalarTy(to);
|
const tt = try e.scalarTy(to);
|
||||||
|
|
@ -3682,7 +4003,7 @@ const Emitter = struct {
|
||||||
switch (e.t.get(cur)) {
|
switch (e.t.get(cur)) {
|
||||||
.@"struct" => |st| {
|
.@"struct" => |st| {
|
||||||
const k: u32 = @intCast(xi.op.constant.int);
|
const k: u32 = @intCast(xi.op.constant.int);
|
||||||
const offs = layout.fieldOffsets(e.arena, e.t, st, .dx_legacy) catch return e.unsupported("constant buffer member types", .{});
|
const offs = e.fieldOffsets(st, .dx_legacy) catch return e.unsupported("constant buffer member types", .{});
|
||||||
c.offset += offs[k];
|
c.offset += offs[k];
|
||||||
c.row_major = st.fields.items[k].row_major;
|
c.row_major = st.fields.items[k].row_major;
|
||||||
cur = st.fields.items[k].type;
|
cur = st.fields.items[k].type;
|
||||||
|
|
@ -3734,7 +4055,7 @@ const Emitter = struct {
|
||||||
const mem_c: Scalar = if (c == .bool) .uint else c;
|
const mem_c: Scalar = if (c == .bool) .uint else c;
|
||||||
// A register holds 16 bytes: 4 32-bit, 2 64-bit or 8 16-bit values.
|
// A register holds 16 bytes: 4 32-bit, 2 64-bit or 8 16-bit values.
|
||||||
const sz = mem_c.size();
|
const sz = mem_c.size();
|
||||||
const off = offset + (layout.componentOffset(e.arena, e.t, ty, row_major, @intCast(k), .dx_legacy) catch return e.unsupported("constant buffer member types", .{}));
|
const off = offset + (e.componentOffset(ty, row_major, @intCast(k), .dx_legacy) catch return e.unsupported("constant buffer member types", .{}));
|
||||||
const reg = off / 16;
|
const reg = off / 16;
|
||||||
const st = try e.scalarTy(mem_c);
|
const st = try e.scalarTy(mem_c);
|
||||||
if (res.kind == 15) {
|
if (res.kind == 15) {
|
||||||
|
|
@ -3799,14 +4120,10 @@ const Emitter = struct {
|
||||||
.scalar, .@"enum", .linalg => return ty,
|
.scalar, .@"enum", .linalg => return ty,
|
||||||
.vector, .matrix => return e.t.scalar(e.t.component(ty).?),
|
.vector, .matrix => return e.t.scalar(e.t.component(ty).?),
|
||||||
.array => |a| return e.componentType(a.elem, k % try e.flatCount(a.elem)),
|
.array => |a| return e.componentType(a.elem, k % try e.flatCount(a.elem)),
|
||||||
.@"struct" => |s| {
|
.@"struct" => {
|
||||||
var kk = k;
|
const comps = try e.structComps(ty);
|
||||||
for (s.fields.items) |f| {
|
if (k >= comps.len) return e.unsupported("struct component", .{});
|
||||||
const n = try e.flatCount(f.type);
|
return comps[k];
|
||||||
if (kk < n) return e.componentType(f.type, kk);
|
|
||||||
kk -= n;
|
|
||||||
}
|
|
||||||
return e.unsupported("struct component", .{});
|
|
||||||
},
|
},
|
||||||
else => return e.unsupported("component type", .{}),
|
else => return e.unsupported("component type", .{}),
|
||||||
}
|
}
|
||||||
|
|
@ -3920,7 +4237,8 @@ const Emitter = struct {
|
||||||
const ptr = try e.add(try e.dm.ptrType(class_ty), .{ .gep = .{ .elem = arr_ty, .ptr = .{ .global = lg }, .indices = try e.arena.dupe(Value, &.{ try e.i32Const(0), index }) } });
|
const ptr = try e.add(try e.dm.ptrType(class_ty), .{ .gep = .{ .elem = arr_ty, .ptr = .{ .global = lg }, .indices = try e.arena.dupe(Value, &.{ try e.i32Const(0), index }) } });
|
||||||
if (nonuniform) {
|
if (nonuniform) {
|
||||||
const blk = e.blocks.items[e.cur].items;
|
const blk = e.blocks.items[e.cur].items;
|
||||||
blk[blk.len - 1].inst.md = .{ .kind = try e.dm.mdKind("dx.nonuniform"), .node = try e.dm.mdNode(&.{try e.dm.mdI32(1)}) };
|
const kind = try e.dm.mdKind("dx.nonuniform");
|
||||||
|
e.insts.at(blk[blk.len - 1]).md = try e.dm.instMd(kind, try e.dm.mdNode(&.{try e.dm.mdI32(1)}));
|
||||||
}
|
}
|
||||||
const loaded = try e.add(class_ty, .{ .load = .{ .ptr = ptr, .@"align" = 4 } });
|
const loaded = try e.add(class_ty, .{ .load = .{ .ptr = ptr, .@"align" = 4 } });
|
||||||
const struct_name = e.dm.types.items[class_ty].@"struct".name;
|
const struct_name = e.dm.types.items[class_ty].@"struct".name;
|
||||||
|
|
@ -4419,7 +4737,7 @@ const Emitter = struct {
|
||||||
switch (e.t.get(cur)) {
|
switch (e.t.get(cur)) {
|
||||||
.@"struct" => |st| {
|
.@"struct" => |st| {
|
||||||
const k: u32 = @intCast(xi.op.constant.int);
|
const k: u32 = @intCast(xi.op.constant.int);
|
||||||
const offs = layout.fieldOffsets(e.arena, e.t, st, .dx_packed) catch return e.unsupported("buffer member types", .{});
|
const offs = e.fieldOffsets(st, .dx_packed) catch return e.unsupported("buffer member types", .{});
|
||||||
b.offset += offs[k];
|
b.offset += offs[k];
|
||||||
b.row_major = st.fields.items[k].row_major;
|
b.row_major = st.fields.items[k].row_major;
|
||||||
cur = st.fields.items[k].type;
|
cur = st.fields.items[k].type;
|
||||||
|
|
@ -4463,15 +4781,15 @@ const Emitter = struct {
|
||||||
const res = e.resources.items[b.res];
|
const res = e.resources.items[b.res];
|
||||||
for (vals, 0..) |v, j| {
|
for (vals, 0..) |v, j| {
|
||||||
const c: u32 = mat.col orelse @intCast(j);
|
const c: u32 = mat.col orelse @intCast(j);
|
||||||
const off0 = layout.componentOffset(e.arena, e.t, mat.ty, b.row_major, c, .dx_packed) catch return e.unsupported("buffer element types", .{});
|
const off0 = e.componentOffset(mat.ty, b.row_major, c, .dx_packed) catch return e.unsupported("buffer element types", .{});
|
||||||
const const_row: ?i64 = if (m.rows == 1) 0 else e.constIntOf(mat.row);
|
const const_row: ?i64 = if (m.rows == 1) 0 else e.constIntOf(mat.row);
|
||||||
if (const_row) |row| {
|
if (const_row) |row| {
|
||||||
const off = layout.componentOffset(e.arena, e.t, mat.ty, b.row_major, @as(u32, @intCast(row)) * m.cols + c, .dx_packed) catch return e.unsupported("buffer element types", .{});
|
const off = e.componentOffset(mat.ty, b.row_major, @as(u32, @intCast(row)) * m.cols + c, .dx_packed) catch return e.unsupported("buffer element types", .{});
|
||||||
try e.structuredStore(res, b.index, b.offset + off, b.dyn, b.row_major, ec, &.{v});
|
try e.structuredStore(res, b.index, b.offset + off, b.dyn, b.row_major, ec, &.{v});
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
// A dynamic row: rows are a constant byte step apart.
|
// A dynamic row: rows are a constant byte step apart.
|
||||||
const step = (layout.componentOffset(e.arena, e.t, mat.ty, b.row_major, m.cols + c, .dx_packed) catch return e.unsupported("buffer element types", .{})) - off0;
|
const step = (e.componentOffset(mat.ty, b.row_major, m.cols + c, .dx_packed) catch return e.unsupported("buffer element types", .{})) - off0;
|
||||||
var dyn = try e.add(i32t, .{ .binop = .{ .op = .mul, .lhs = mat.row, .rhs = try e.i32Const(step) } });
|
var dyn = try e.add(i32t, .{ .binop = .{ .op = .mul, .lhs = mat.row, .rhs = try e.i32Const(step) } });
|
||||||
if (b.dyn) |d| dyn = try e.add(i32t, .{ .binop = .{ .op = .add, .lhs = d, .rhs = dyn } });
|
if (b.dyn) |d| dyn = try e.add(i32t, .{ .binop = .{ .op = .add, .lhs = d, .rhs = dyn } });
|
||||||
try e.structuredStore(res, b.index, b.offset + off0, dyn, b.row_major, ec, &.{v});
|
try e.structuredStore(res, b.index, b.offset + off0, dyn, b.row_major, ec, &.{v});
|
||||||
|
|
@ -4489,12 +4807,12 @@ const Emitter = struct {
|
||||||
while (k < n) {
|
while (k < n) {
|
||||||
const c0 = e.compOf(try e.componentType(ty, k));
|
const c0 = e.compOf(try e.componentType(ty, k));
|
||||||
const mem: Scalar = if (c0 == .bool) .uint else c0;
|
const mem: Scalar = if (c0 == .bool) .uint else c0;
|
||||||
const off0 = layout.componentOffset(e.arena, e.t, ty, row_major, k, .dx_packed) catch return e.unsupported("buffer element types", .{});
|
const off0 = e.componentOffset(ty, row_major, k, .dx_packed) catch return e.unsupported("buffer element types", .{});
|
||||||
var count: u32 = 1;
|
var count: u32 = 1;
|
||||||
while (k + count < n and count < 4) : (count += 1) {
|
while (k + count < n and count < 4) : (count += 1) {
|
||||||
const cn = e.compOf(try e.componentType(ty, k + count));
|
const cn = e.compOf(try e.componentType(ty, k + count));
|
||||||
const mn: Scalar = if (cn == .bool) .uint else cn;
|
const mn: Scalar = if (cn == .bool) .uint else cn;
|
||||||
const on = layout.componentOffset(e.arena, e.t, ty, row_major, k + count, .dx_packed) catch break;
|
const on = e.componentOffset(ty, row_major, k + count, .dx_packed) catch break;
|
||||||
if (mn != mem or on != off0 + count * mem.size()) break;
|
if (mn != mem or on != off0 + count * mem.size()) break;
|
||||||
}
|
}
|
||||||
const st = try e.scalarTy(mem);
|
const st = try e.scalarTy(mem);
|
||||||
|
|
@ -4548,12 +4866,12 @@ const Emitter = struct {
|
||||||
while (k < n) {
|
while (k < n) {
|
||||||
const c0 = e.compOf(try e.componentType(ty, k));
|
const c0 = e.compOf(try e.componentType(ty, k));
|
||||||
const mem: Scalar = if (c0 == .bool) .uint else c0;
|
const mem: Scalar = if (c0 == .bool) .uint else c0;
|
||||||
const off0 = layout.componentOffset(e.arena, e.t, ty, row_major, k, .dx_packed) catch return e.unsupported("buffer element types", .{});
|
const off0 = e.componentOffset(ty, row_major, k, .dx_packed) catch return e.unsupported("buffer element types", .{});
|
||||||
var count: u32 = 1;
|
var count: u32 = 1;
|
||||||
while (k + count < n and count < 4) : (count += 1) {
|
while (k + count < n and count < 4) : (count += 1) {
|
||||||
const cn = e.compOf(try e.componentType(ty, k + count));
|
const cn = e.compOf(try e.componentType(ty, k + count));
|
||||||
const mn: Scalar = if (cn == .bool) .uint else cn;
|
const mn: Scalar = if (cn == .bool) .uint else cn;
|
||||||
const on = layout.componentOffset(e.arena, e.t, ty, row_major, k + count, .dx_packed) catch break;
|
const on = e.componentOffset(ty, row_major, k + count, .dx_packed) catch break;
|
||||||
if (mn != mem or on != off0 + count * mem.size()) break;
|
if (mn != mem or on != off0 + count * mem.size()) break;
|
||||||
}
|
}
|
||||||
const st = try e.scalarTy(mem);
|
const st = try e.scalarTy(mem);
|
||||||
|
|
@ -4666,7 +4984,7 @@ const Emitter = struct {
|
||||||
/// (templated Load / Store: natural alignment; dxc's DXIL lays
|
/// (templated Load / Store: natural alignment; dxc's DXIL lays
|
||||||
/// matrices out by row here, its SPIR-V by column).
|
/// matrices out by row here, its SPIR-V by column).
|
||||||
fn rawOffset(e: *Emitter, ty: TypeId, k: u32) Error!u32 {
|
fn rawOffset(e: *Emitter, ty: TypeId, k: u32) Error!u32 {
|
||||||
return layout.componentOffset(e.arena, e.t, ty, true, k, .dx_packed) catch e.unsupported("byte-address buffer accesses of type '{s}' are not supported yet", .{try e.t.format(e.arena, ty)});
|
return e.componentOffset(ty, true, k, .dx_packed) catch e.unsupported("byte-address buffer accesses of type '{s}' are not supported yet", .{try e.t.format(e.arena, ty)});
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A templated byte-address Load: one raw load per component.
|
/// A templated byte-address Load: one raw load per component.
|
||||||
|
|
@ -5926,7 +6244,7 @@ const Emitter = struct {
|
||||||
if (resources) |r| try dm.addNamedMetadata("dx.resources", &.{r});
|
if (resources) |r| try dm.addNamedMetadata("dx.resources", &.{r});
|
||||||
if (funcs.len > 0) try dm.addNamedMetadata("dx.typeAnnotations", &.{type_annotations});
|
if (funcs.len > 0) try dm.addNamedMetadata("dx.typeAnnotations", &.{type_annotations});
|
||||||
try dm.addNamedMetadata("dx.entryPoints", entries.items);
|
try dm.addNamedMetadata("dx.entryPoints", entries.items);
|
||||||
return dm.writeBitcode(dm.arena.child_allocator);
|
return dm.writeBitcode(dm.arena.child);
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---- Reflection (reflect.zig) -----------------------------------------
|
// ---- Reflection (reflect.zig) -----------------------------------------
|
||||||
|
|
@ -6207,7 +6525,7 @@ const Emitter = struct {
|
||||||
d.rows = 1;
|
d.rows = 1;
|
||||||
d.cols = layout.flatCount(e.t, t) catch 0;
|
d.cols = layout.flatCount(e.t, t) catch 0;
|
||||||
d.name = s.name;
|
d.name = s.name;
|
||||||
const offs = layout.fieldOffsets(e.arena, e.t, s, .dx_legacy) catch return e.unsupported("reflection of '{s}'", .{s.name});
|
const offs = e.fieldOffsets(s, .dx_legacy) catch return e.unsupported("reflection of '{s}'", .{s.name});
|
||||||
var members: std.ArrayList(reflect.Member) = .empty;
|
var members: std.ArrayList(reflect.Member) = .empty;
|
||||||
for (s.fields.items, offs) |fld, off| {
|
for (s.fields.items, offs) |fld, off| {
|
||||||
if (fld.bits or layout.isOpaque(e.t, fld.type)) continue;
|
if (fld.bits or layout.isOpaque(e.t, fld.type)) continue;
|
||||||
|
|
@ -6370,7 +6688,7 @@ const Emitter = struct {
|
||||||
if (g.space == .cbuffer and e.t.get(g.ty) == .@"struct") {
|
if (g.space == .cbuffer and e.t.get(g.ty) == .@"struct") {
|
||||||
// A cbuffer block: its members are the variables.
|
// A cbuffer block: its members are the variables.
|
||||||
const s = e.t.get(g.ty).@"struct";
|
const s = e.t.get(g.ty).@"struct";
|
||||||
const offs = layout.fieldOffsets(e.arena, e.t, s, .dx_legacy) catch return e.unsupported("reflection of constant buffer '{s}'", .{g.name});
|
const offs = e.fieldOffsets(s, .dx_legacy) catch return e.unsupported("reflection of constant buffer '{s}'", .{g.name});
|
||||||
for (s.fields.items, offs) |fld, off| {
|
for (s.fields.items, offs) |fld, off| {
|
||||||
if (fld.bits) continue;
|
if (fld.bits) continue;
|
||||||
const fsize = layout.sizeOf(e.t, fld.type, fld.row_major, .dx_legacy) catch 0;
|
const fsize = layout.sizeOf(e.t, fld.type, fld.row_major, .dx_legacy) catch 0;
|
||||||
|
|
@ -6627,7 +6945,7 @@ const Emitter = struct {
|
||||||
try dm.addNamedMetadata("dx.entryPoints", &.{entry_md});
|
try dm.addNamedMetadata("dx.entryPoints", &.{entry_md});
|
||||||
try promote.pruneGlobals(e.arena, dm);
|
try promote.pruneGlobals(e.arena, dm);
|
||||||
_ = try promote.pruneDeclarations(e.arena, dm);
|
_ = try promote.pruneDeclarations(e.arena, dm);
|
||||||
return dm.writeBitcode(dm.arena.child_allocator);
|
return dm.writeBitcode(dm.arena.child);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// `!{id, name, comp, kind, !{indices}, interp, rows, cols, row, col,
|
/// `!{id, name, comp, kind, !{indices}, interp, rows, cols, row, col,
|
||||||
|
|
|
||||||
|
|
@ -3,6 +3,7 @@
|
||||||
//! unabbreviated records only.
|
//! unabbreviated records only.
|
||||||
|
|
||||||
const std = @import("std");
|
const std = @import("std");
|
||||||
|
const BumpArena = @import("../BumpArena.zig");
|
||||||
const Allocator = std.mem.Allocator;
|
const Allocator = std.mem.Allocator;
|
||||||
const bitstream = @import("bitstream.zig");
|
const bitstream = @import("bitstream.zig");
|
||||||
|
|
||||||
|
|
@ -39,6 +40,38 @@ pub const Type = union(enum) {
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/// splitmix64's finalizer: a cheap hash of a word, for the type and
|
||||||
|
/// constant pools (a hash map uses both its high and low bits).
|
||||||
|
fn mix(x: u64) u64 {
|
||||||
|
var z = x;
|
||||||
|
z = (z ^ (z >> 30)) *% 0xbf58476d1ce4e5b9;
|
||||||
|
z = (z ^ (z >> 27)) *% 0x94d049bb133111eb;
|
||||||
|
return z ^ (z >> 31);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Hashes what Type.eql compares.
|
||||||
|
const TypeContext = struct {
|
||||||
|
pub fn hash(_: TypeContext, t: Type) u64 {
|
||||||
|
const tag: u64 = @backingInt(t);
|
||||||
|
return switch (t) {
|
||||||
|
.void, .label, .metadata, .half, .float, .double => mix(tag),
|
||||||
|
.int => |w| mix(tag << 56 | w),
|
||||||
|
.pointer => |p| mix(tag << 56 | @as(u64, p.addr_space) << 32 | p.elem),
|
||||||
|
.function => |f| mix(tag << 56 | f.ret) ^ std.hash.Wyhash.hash(0, std.mem.sliceAsBytes(f.params)),
|
||||||
|
.@"struct" => |st| mix(tag) ^ std.hash.Wyhash.hash(0, st.name),
|
||||||
|
.array => |x| mix(mix(tag << 56 | x.elem) ^ x.len),
|
||||||
|
.vector => |x| mix(tag << 56 | @as(u64, x.len) << 32 | x.elem),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn eql(_: TypeContext, a: Type, b: Type) bool {
|
||||||
|
return a.eql(b);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const no_type = std.math.maxInt(TypeId);
|
||||||
|
const no_const = std.math.maxInt(ConstId);
|
||||||
|
|
||||||
pub const Constant = struct {
|
pub const Constant = struct {
|
||||||
ty: TypeId,
|
ty: TypeId,
|
||||||
kind: union(enum) {
|
kind: union(enum) {
|
||||||
|
|
@ -52,6 +85,24 @@ pub const Constant = struct {
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/// Constants are equal when their type and kind are (aggregates: the same
|
||||||
|
/// element slice, as std.meta.eql compares slices).
|
||||||
|
const ConstantContext = struct {
|
||||||
|
pub fn hash(_: ConstantContext, c: Constant) u64 {
|
||||||
|
const head = mix(@as(u64, @backingInt(c.kind)) << 32 | c.ty);
|
||||||
|
return switch (c.kind) {
|
||||||
|
.int => |v| mix(head ^ @as(u64, @bitCast(v))),
|
||||||
|
.float_bits => |v| mix(head ^ v),
|
||||||
|
.undef, .null => head,
|
||||||
|
.aggregate => |a| mix(head ^ @intFromPtr(a.ptr) ^ a.len << 48),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn eql(_: ConstantContext, a: Constant, b: Constant) bool {
|
||||||
|
return a.ty == b.ty and std.meta.eql(a.kind, b.kind);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
pub const Linkage = enum(u32) { external = 0, internal = 3 };
|
pub const Linkage = enum(u32) { external = 0, internal = 3 };
|
||||||
|
|
||||||
/// Attribute group for function declarations (e.g. dx.op functions).
|
/// Attribute group for function declarations (e.g. dx.op functions).
|
||||||
|
|
@ -106,11 +157,15 @@ pub const Inst = struct {
|
||||||
extractelement: struct { vec: Value, index: Value },
|
extractelement: struct { vec: Value, index: Value },
|
||||||
insertelement: struct { vec: Value, val: Value, index: Value },
|
insertelement: struct { vec: Value, val: Value, index: Value },
|
||||||
},
|
},
|
||||||
/// An attached metadata node (`kind` from Module.mdKind), as
|
/// An attached metadata node, as `!dx.nonuniform` on a resource
|
||||||
/// `!dx.nonuniform` on a resource array's getelementptr.
|
/// array's getelementptr (see Module.instMd).
|
||||||
md: ?struct { kind: u32, node: MdId } = null,
|
md: InstMd = .none,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/// An instruction's metadata attachment: an index into Module.inst_mds,
|
||||||
|
/// kept out of line (few instructions have one).
|
||||||
|
pub const InstMd = enum(u32) { none = 0, _ };
|
||||||
|
|
||||||
pub const Function = struct {
|
pub const Function = struct {
|
||||||
name: []const u8,
|
name: []const u8,
|
||||||
ty: TypeId,
|
ty: TypeId,
|
||||||
|
|
@ -130,15 +185,24 @@ pub const Metadata = union(enum) {
|
||||||
};
|
};
|
||||||
|
|
||||||
pub const Module = struct {
|
pub const Module = struct {
|
||||||
arena: std.heap.ArenaAllocator,
|
arena: BumpArena,
|
||||||
triple: []const u8 = "dxil-ms-dx",
|
triple: []const u8 = "dxil-ms-dx",
|
||||||
datalayout: []const u8 = "e-m:e-p:32:32-i1:32-i8:32-i16:32-i32:32-i64:64-f16:32-f32:32-f64:64-n8:16:32:64",
|
datalayout: []const u8 = "e-m:e-p:32:32-i1:32-i8:32-i16:32-i32:32-i64:64-f16:32-f32:32-f64:64-n8:16:32:64",
|
||||||
types: std.ArrayList(Type) = .empty,
|
types: std.ArrayList(Type) = .empty,
|
||||||
|
/// Index of `types`, for getType to find existing ones.
|
||||||
|
type_ids: std.HashMapUnmanaged(Type, TypeId, TypeContext, std.hash_map.default_max_load_percentage) = .empty,
|
||||||
constants: std.ArrayList(Constant) = .empty,
|
constants: std.ArrayList(Constant) = .empty,
|
||||||
|
/// Index of `constants`, for constant() to find existing ones.
|
||||||
|
constant_ids: std.HashMapUnmanaged(Constant, ConstId, ConstantContext, std.hash_map.default_max_load_percentage) = .empty,
|
||||||
functions: std.ArrayList(Function) = .empty,
|
functions: std.ArrayList(Function) = .empty,
|
||||||
|
/// intType's and constInt's results for common arguments.
|
||||||
|
int_types: [65]TypeId = @splat(no_type),
|
||||||
|
small_i32: [1024]ConstId = @splat(no_const),
|
||||||
globals: std.ArrayList(GlobalVar) = .empty,
|
globals: std.ArrayList(GlobalVar) = .empty,
|
||||||
metadata: std.ArrayList(Metadata) = .empty,
|
metadata: std.ArrayList(Metadata) = .empty,
|
||||||
named_metadata: std.ArrayList(struct { name: []const u8, nodes: []const MdId }) = .empty,
|
named_metadata: std.ArrayList(struct { name: []const u8, nodes: []const MdId }) = .empty,
|
||||||
|
/// Instruction metadata attachments (InstMd), from 1.
|
||||||
|
inst_mds: std.ArrayList(struct { kind: u32, node: MdId }) = .empty,
|
||||||
/// Instruction metadata kinds, by id.
|
/// Instruction metadata kinds, by id.
|
||||||
md_kinds: std.ArrayList([]const u8) = .empty,
|
md_kinds: std.ArrayList([]const u8) = .empty,
|
||||||
|
|
||||||
|
|
@ -155,9 +219,7 @@ pub const Module = struct {
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn getType(m: *Module, t: Type) !TypeId {
|
pub fn getType(m: *Module, t: Type) !TypeId {
|
||||||
for (m.types.items, 0..) |existing, i| {
|
if (m.type_ids.get(t)) |id| return id;
|
||||||
if (existing.eql(t)) return @intCast(i);
|
|
||||||
}
|
|
||||||
const a = m.allocator();
|
const a = m.allocator();
|
||||||
var owned = t;
|
var owned = t;
|
||||||
switch (owned) {
|
switch (owned) {
|
||||||
|
|
@ -168,11 +230,18 @@ pub const Module = struct {
|
||||||
},
|
},
|
||||||
else => {},
|
else => {},
|
||||||
}
|
}
|
||||||
|
const id: TypeId = @intCast(m.types.items.len);
|
||||||
|
try m.type_ids.ensureUnusedCapacity(a, 1);
|
||||||
try m.types.append(a, owned);
|
try m.types.append(a, owned);
|
||||||
return @intCast(m.types.items.len - 1);
|
m.type_ids.putAssumeCapacity(owned, id);
|
||||||
|
return id;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn intType(m: *Module, bits: u32) !TypeId {
|
pub fn intType(m: *Module, bits: u32) !TypeId {
|
||||||
|
if (bits < m.int_types.len) {
|
||||||
|
if (m.int_types[bits] == no_type) m.int_types[bits] = try m.getType(.{ .int = bits });
|
||||||
|
return m.int_types[bits];
|
||||||
|
}
|
||||||
return m.getType(.{ .int = bits });
|
return m.getType(.{ .int = bits });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -200,17 +269,134 @@ pub const Module = struct {
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn constant(m: *Module, c: Constant) !Value {
|
pub fn constant(m: *Module, c: Constant) !Value {
|
||||||
for (m.constants.items, 0..) |existing, i| {
|
const gop = try m.constant_ids.getOrPut(m.allocator(), c);
|
||||||
if (existing.ty == c.ty and std.meta.eql(existing.kind, c.kind)) return .{ .constant = @intCast(i) };
|
if (!gop.found_existing) {
|
||||||
|
gop.value_ptr.* = @intCast(m.constants.items.len);
|
||||||
|
m.constants.append(m.allocator(), c) catch |err| {
|
||||||
|
m.constant_ids.removeByPtr(gop.key_ptr);
|
||||||
|
return err;
|
||||||
|
};
|
||||||
}
|
}
|
||||||
try m.constants.append(m.allocator(), c);
|
return .{ .constant = gop.value_ptr.* };
|
||||||
return .{ .constant = @intCast(m.constants.items.len - 1) };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn constInt(m: *Module, bits: u32, v: i64) !Value {
|
pub fn constInt(m: *Module, bits: u32, v: i64) !Value {
|
||||||
|
if (bits == 32 and v >= 0 and v < m.small_i32.len) {
|
||||||
|
const k: usize = @intCast(v);
|
||||||
|
if (m.small_i32[k] == no_const) m.small_i32[k] = (try m.constant(.{ .ty = try m.intType(32), .kind = .{ .int = v } })).constant;
|
||||||
|
return .{ .constant = m.small_i32[k] };
|
||||||
|
}
|
||||||
return m.constant(.{ .ty = try m.intType(bits), .kind = .{ .int = v } });
|
return m.constant(.{ .ty = try m.intType(bits), .kind = .{ .int = v } });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// An attachment of node `node` as metadata kind `kind` (from mdKind).
|
||||||
|
pub fn instMd(m: *Module, kind: u32, node: MdId) !InstMd {
|
||||||
|
try m.inst_mds.append(m.allocator(), .{ .kind = kind, .node = node });
|
||||||
|
return @fromBackingInt(@intCast(m.inst_mds.items.len));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Drops the constants nothing uses, and numbers the rest in order of
|
||||||
|
/// first use (functions' instructions, then metadata), grouped by type,
|
||||||
|
/// with aggregates last, after their elements. The output then depends
|
||||||
|
/// only on the code that is left, not on code made and removed again or
|
||||||
|
/// on the order constants were first asked for.
|
||||||
|
fn pruneConstants(m: *Module) !void {
|
||||||
|
const a = m.allocator();
|
||||||
|
const n = m.constants.items.len;
|
||||||
|
if (n == 0) return;
|
||||||
|
const Walk = struct {
|
||||||
|
m: *Module,
|
||||||
|
a: Allocator,
|
||||||
|
seen: []bool,
|
||||||
|
order: std.ArrayList(ConstId) = .empty,
|
||||||
|
failed: bool = false,
|
||||||
|
|
||||||
|
fn map(w: *@This(), v: Value) Value {
|
||||||
|
if (v == .constant) w.visit(v.constant) catch {
|
||||||
|
w.failed = true;
|
||||||
|
};
|
||||||
|
return v;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn visit(w: *@This(), c: ConstId) Allocator.Error!void {
|
||||||
|
if (w.seen[c]) return;
|
||||||
|
w.seen[c] = true;
|
||||||
|
switch (w.m.constants.items[c].kind) {
|
||||||
|
.aggregate => |els| for (els) |el| try w.visit(el),
|
||||||
|
else => {},
|
||||||
|
}
|
||||||
|
try w.order.append(w.a, c);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
var walk: Walk = .{ .m = m, .a = a, .seen = try a.alloc(bool, n) };
|
||||||
|
@memset(walk.seen, false);
|
||||||
|
for (m.functions.items) |f| for (f.insts.items) |inst| {
|
||||||
|
var copy = inst;
|
||||||
|
// (Reading only: no slice is copied, nothing changes.)
|
||||||
|
try mapOperands(a, ©, &walk);
|
||||||
|
};
|
||||||
|
for (m.metadata.items) |md| if (md == .value) {
|
||||||
|
_ = walk.map(md.value.val);
|
||||||
|
};
|
||||||
|
if (walk.failed) return error.OutOfMemory;
|
||||||
|
|
||||||
|
// Types in order of first use; scalars by type (stable), then
|
||||||
|
// aggregates in walk order (each after its elements).
|
||||||
|
var rank: std.AutoHashMapUnmanaged(TypeId, u32) = .empty;
|
||||||
|
const Key = struct { rank: u32, id: ConstId };
|
||||||
|
var scalars: std.ArrayList(Key) = .empty;
|
||||||
|
var aggregates: std.ArrayList(ConstId) = .empty;
|
||||||
|
for (walk.order.items) |c| {
|
||||||
|
const k = m.constants.items[c];
|
||||||
|
if (k.kind == .aggregate) {
|
||||||
|
try aggregates.append(a, c);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const gop = try rank.getOrPut(a, k.ty);
|
||||||
|
if (!gop.found_existing) gop.value_ptr.* = rank.count() - 1;
|
||||||
|
try scalars.append(a, .{ .rank = gop.value_ptr.*, .id = c });
|
||||||
|
}
|
||||||
|
std.sort.block(Key, scalars.items, {}, struct {
|
||||||
|
fn lt(_: void, x: Key, y: Key) bool {
|
||||||
|
return x.rank < y.rank;
|
||||||
|
}
|
||||||
|
}.lt);
|
||||||
|
|
||||||
|
const new_id = try a.alloc(ConstId, n);
|
||||||
|
@memset(new_id, no_const);
|
||||||
|
var kept: std.ArrayList(Constant) = .empty;
|
||||||
|
try kept.ensureTotalCapacityPrecise(a, walk.order.items.len);
|
||||||
|
for (scalars.items) |k| {
|
||||||
|
new_id[k.id] = @intCast(kept.items.len);
|
||||||
|
kept.appendAssumeCapacity(m.constants.items[k.id]);
|
||||||
|
}
|
||||||
|
for (aggregates.items) |c| {
|
||||||
|
var k = m.constants.items[c];
|
||||||
|
const els = try a.alloc(ConstId, k.kind.aggregate.len);
|
||||||
|
for (k.kind.aggregate, els) |el, *o| o.* = new_id[el];
|
||||||
|
k.kind = .{ .aggregate = els };
|
||||||
|
new_id[c] = @intCast(kept.items.len);
|
||||||
|
kept.appendAssumeCapacity(k);
|
||||||
|
}
|
||||||
|
|
||||||
|
const Remap = struct {
|
||||||
|
new_id: []const ConstId,
|
||||||
|
fn map(r: @This(), v: Value) Value {
|
||||||
|
return if (v == .constant) .{ .constant = r.new_id[v.constant] } else v;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const remap: Remap = .{ .new_id = new_id };
|
||||||
|
for (m.functions.items) |*f| for (f.insts.items) |*inst| try mapOperands(a, inst, remap);
|
||||||
|
for (m.metadata.items) |*md| if (md.* == .value) {
|
||||||
|
md.value.val = remap.map(md.value.val);
|
||||||
|
};
|
||||||
|
m.constants = kept;
|
||||||
|
// (Constants made from here on start a new index.)
|
||||||
|
m.constant_ids = .empty;
|
||||||
|
for (m.constants.items, 0..) |c, i| try m.constant_ids.put(a, c, @intCast(i));
|
||||||
|
m.small_i32 = @splat(no_const);
|
||||||
|
}
|
||||||
|
|
||||||
pub fn addFunction(m: *Module, f: Function) !u32 {
|
pub fn addFunction(m: *Module, f: Function) !u32 {
|
||||||
var owned = f;
|
var owned = f;
|
||||||
owned.name = try m.allocator().dupe(u8, f.name);
|
owned.name = try m.allocator().dupe(u8, f.name);
|
||||||
|
|
@ -269,12 +455,94 @@ pub const Module = struct {
|
||||||
|
|
||||||
/// Encode the module as raw LLVM bitcode (starting with 'BC' 0xC0DE).
|
/// Encode the module as raw LLVM bitcode (starting with 'BC' 0xC0DE).
|
||||||
pub fn writeBitcode(m: *Module, gpa: Allocator) ![]u8 {
|
pub fn writeBitcode(m: *Module, gpa: Allocator) ![]u8 {
|
||||||
|
try m.pruneConstants();
|
||||||
var enc: Encoder = .{ .m = m, .w = .init(gpa) };
|
var enc: Encoder = .{ .m = m, .w = .init(gpa) };
|
||||||
defer enc.w.deinit();
|
defer enc.w.deinit();
|
||||||
return enc.write();
|
return enc.write();
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/// Calls `ctx.map(v) Value` on each value operand of `inst` and stores the
|
||||||
|
/// results; operand slices whose values change are copied (slices may be
|
||||||
|
/// shared between instructions).
|
||||||
|
fn mapOperands(a: Allocator, inst: *Inst, ctx: anytype) !void {
|
||||||
|
const S = struct {
|
||||||
|
fn many(al: Allocator, c: anytype, xs: []const Value) ![]const Value {
|
||||||
|
for (xs, 0..) |x, k| {
|
||||||
|
if (std.meta.eql(c.map(x), x)) continue;
|
||||||
|
const out = try al.dupe(Value, xs);
|
||||||
|
for (out[k..]) |*o| o.* = c.map(o.*);
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
return xs;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
switch (inst.op) {
|
||||||
|
.ret => |*v| if (v.*) |x| {
|
||||||
|
v.* = ctx.map(x);
|
||||||
|
},
|
||||||
|
.br => |*b| if (b.cond) |c| {
|
||||||
|
b.cond = ctx.map(c);
|
||||||
|
},
|
||||||
|
.@"switch" => |*sw| {
|
||||||
|
sw.cond = ctx.map(sw.cond);
|
||||||
|
const cases = try a.dupe(@typeInfo(@TypeOf(sw.cases)).pointer.child, sw.cases);
|
||||||
|
for (cases) |*c| c.val = ctx.map(c.val);
|
||||||
|
sw.cases = cases;
|
||||||
|
},
|
||||||
|
.call => |*c| c.args = try S.many(a, ctx, c.args),
|
||||||
|
.binop => |*b| {
|
||||||
|
b.lhs = ctx.map(b.lhs);
|
||||||
|
b.rhs = ctx.map(b.rhs);
|
||||||
|
},
|
||||||
|
.cast => |*c| c.val = ctx.map(c.val),
|
||||||
|
.cmp => |*c| {
|
||||||
|
c.lhs = ctx.map(c.lhs);
|
||||||
|
c.rhs = ctx.map(c.rhs);
|
||||||
|
},
|
||||||
|
.select => |*x| {
|
||||||
|
x.cond = ctx.map(x.cond);
|
||||||
|
x.t = ctx.map(x.t);
|
||||||
|
x.f = ctx.map(x.f);
|
||||||
|
},
|
||||||
|
.extractvalue => |*x| x.agg = ctx.map(x.agg),
|
||||||
|
.phi => |*p| {
|
||||||
|
const ins = try a.dupe(@typeInfo(@TypeOf(p.incoming)).pointer.child, p.incoming);
|
||||||
|
for (ins) |*in| in.val = ctx.map(in.val);
|
||||||
|
p.incoming = ins;
|
||||||
|
},
|
||||||
|
.alloca => |*x| x.size = ctx.map(x.size),
|
||||||
|
.load => |*x| x.ptr = ctx.map(x.ptr),
|
||||||
|
.store => |*x| {
|
||||||
|
x.ptr = ctx.map(x.ptr);
|
||||||
|
x.val = ctx.map(x.val);
|
||||||
|
},
|
||||||
|
.gep => |*x| {
|
||||||
|
x.ptr = ctx.map(x.ptr);
|
||||||
|
x.indices = try S.many(a, ctx, x.indices);
|
||||||
|
},
|
||||||
|
.atomicrmw => |*x| {
|
||||||
|
x.ptr = ctx.map(x.ptr);
|
||||||
|
x.val = ctx.map(x.val);
|
||||||
|
},
|
||||||
|
.cmpxchg => |*x| {
|
||||||
|
x.ptr = ctx.map(x.ptr);
|
||||||
|
x.cmp = ctx.map(x.cmp);
|
||||||
|
x.new = ctx.map(x.new);
|
||||||
|
},
|
||||||
|
.@"unreachable" => {},
|
||||||
|
.extractelement => |*x| {
|
||||||
|
x.vec = ctx.map(x.vec);
|
||||||
|
x.index = ctx.map(x.index);
|
||||||
|
},
|
||||||
|
.insertelement => |*x| {
|
||||||
|
x.vec = ctx.map(x.vec);
|
||||||
|
x.val = ctx.map(x.val);
|
||||||
|
x.index = ctx.map(x.index);
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const block_module = 8;
|
const block_module = 8;
|
||||||
const block_paramattr = 9;
|
const block_paramattr = 9;
|
||||||
const block_paramattr_group = 10;
|
const block_paramattr_group = 10;
|
||||||
|
|
@ -702,10 +970,11 @@ 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 != null;
|
for (f.insts.items) |inst| any_md = any_md or inst.md != .none;
|
||||||
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) |md| {
|
for (f.insts.items, 0..) |inst, k| if (inst.md != .none) {
|
||||||
|
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);
|
||||||
};
|
};
|
||||||
|
|
|
||||||
|
|
@ -137,15 +137,25 @@ pub fn run(a: Allocator, m: *module.Module, func: u32, dyn: *const std.AutoHashM
|
||||||
// per edge, so a switch's repeated target counts once per case).
|
// per edge, so a switch's repeated target counts once per case).
|
||||||
const block_start = try a.alloc(u32, nb + 1);
|
const block_start = try a.alloc(u32, nb + 1);
|
||||||
const block_of = try a.alloc(u32, n);
|
const block_of = try a.alloc(u32, n);
|
||||||
|
// The allocas, getelementptrs, and loads and stores, in order: the
|
||||||
|
// passes over just those walk these, not every instruction.
|
||||||
|
var allocas: std.ArrayList(u32) = .empty;
|
||||||
|
var geps: std.ArrayList(u32) = .empty;
|
||||||
|
var mems: std.ArrayList(u32) = .empty;
|
||||||
{
|
{
|
||||||
var b: u32 = 0;
|
var b: u32 = 0;
|
||||||
block_start[0] = 0;
|
block_start[0] = 0;
|
||||||
for (insts, 0..) |inst, i| {
|
for (insts, 0..) |inst, i| {
|
||||||
if (b >= nb) return; // not the block layout this pass expects
|
if (b >= nb) return; // not the block layout this pass expects
|
||||||
block_of[i] = b;
|
block_of[i] = b;
|
||||||
if (isTerminator(inst)) {
|
switch (inst.op) {
|
||||||
b += 1;
|
.alloca => try allocas.append(a, @intCast(i)),
|
||||||
block_start[b] = @intCast(i + 1);
|
.gep => try geps.append(a, @intCast(i)),
|
||||||
|
.load, .store => try mems.append(a, @intCast(i)),
|
||||||
|
else => if (isTerminator(inst)) {
|
||||||
|
b += 1;
|
||||||
|
block_start[b] = @intCast(i + 1);
|
||||||
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (b != nb) return;
|
if (b != nb) return;
|
||||||
|
|
@ -271,8 +281,9 @@ pub fn run(a: Allocator, m: *module.Module, func: u32, dyn: *const std.AutoHashM
|
||||||
@memset(var_base, none);
|
@memset(var_base, none);
|
||||||
const elem_ty = try a.alloc(TypeId, n);
|
const elem_ty = try a.alloc(TypeId, n);
|
||||||
const direct = try a.alloc(bool, n);
|
const direct = try a.alloc(bool, n);
|
||||||
for (insts, 0..) |inst, i| switch (inst.op) {
|
for (allocas.items) |i| {
|
||||||
.alloca => |x| switch (m.types.items[x.elem]) {
|
const x = insts[i].op.alloca;
|
||||||
|
switch (m.types.items[x.elem]) {
|
||||||
.array => |arr| if (isScalar(m, arr.elem) and arr.len > 0) {
|
.array => |arr| if (isScalar(m, arr.elem) and arr.len > 0) {
|
||||||
var_base[i] = 0;
|
var_base[i] = 0;
|
||||||
elem_ty[i] = arr.elem;
|
elem_ty[i] = arr.elem;
|
||||||
|
|
@ -283,9 +294,8 @@ pub fn run(a: Allocator, m: *module.Module, func: u32, dyn: *const std.AutoHashM
|
||||||
elem_ty[i] = x.elem;
|
elem_ty[i] = x.elem;
|
||||||
direct[i] = true;
|
direct[i] = true;
|
||||||
},
|
},
|
||||||
},
|
}
|
||||||
else => {},
|
}
|
||||||
};
|
|
||||||
// getelementptrs of candidates: the alloca and the element they
|
// getelementptrs of candidates: the alloca and the element they
|
||||||
// address (`none` for a dynamic index, which pins its range).
|
// address (`none` for a dynamic index, which pins its range).
|
||||||
const gep_alloca = try a.alloc(u32, n);
|
const gep_alloca = try a.alloc(u32, n);
|
||||||
|
|
@ -315,8 +325,9 @@ pub fn run(a: Allocator, m: *module.Module, func: u32, dyn: *const std.AutoHashM
|
||||||
};
|
};
|
||||||
// (Code no path reaches, such as loops unrolling left behind, does
|
// (Code no path reaches, such as loops unrolling left behind, does
|
||||||
// not count.)
|
// not count.)
|
||||||
for (insts, 0..) |inst, i| if (rpo_index[block_of[i]] != none) switch (inst.op) {
|
for (geps.items) |i| if (rpo_index[block_of[i]] != none) {
|
||||||
.gep => |g| if (g.ptr == .inst and var_base[g.ptr.inst] != none and insts[g.ptr.inst].op == .alloca) {
|
const g = insts[i].op.gep;
|
||||||
|
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]) {
|
||||||
var_base[al] = none;
|
var_base[al] = none;
|
||||||
|
|
@ -326,20 +337,20 @@ pub fn run(a: Allocator, m: *module.Module, func: u32, dyn: *const std.AutoHashM
|
||||||
if (k) |kk| {
|
if (k) |kk| {
|
||||||
gep_alloca[i] = al;
|
gep_alloca[i] = al;
|
||||||
gep_k[i] = kk;
|
gep_k[i] = kk;
|
||||||
} else if (dyn.contains(@intCast(i)) and g.indices.len == 2 and constInt(m, g.indices[0]) == 0) {
|
} else if (dyn.contains(i) and g.indices.len == 2 and constInt(m, g.indices[0]) == 0) {
|
||||||
gep_alloca[i] = al;
|
gep_alloca[i] = al;
|
||||||
gep_k[i] = none;
|
gep_k[i] = none;
|
||||||
} else var_base[al] = none;
|
} else var_base[al] = none;
|
||||||
},
|
}
|
||||||
else => {},
|
|
||||||
};
|
};
|
||||||
{
|
{
|
||||||
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, 0..) |*inst, i| if (rpo_index[block_of[i]] != none) 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, 0..) |inst, i| {
|
for (mems.items) |i| {
|
||||||
if (rpo_index[block_of[i]] == none) continue;
|
if (rpo_index[block_of[i]] == none) continue;
|
||||||
|
const inst = insts[i];
|
||||||
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) },
|
||||||
|
|
@ -352,14 +363,16 @@ pub fn run(a: Allocator, m: *module.Module, func: u32, dyn: *const std.AutoHashM
|
||||||
|
|
||||||
// Variables.
|
// Variables.
|
||||||
var nv: u32 = 0;
|
var nv: u32 = 0;
|
||||||
for (insts, 0..) |inst, i| {
|
for (allocas.items) |i| {
|
||||||
if (inst.op != .alloca or var_base[i] == none) continue;
|
const inst = insts[i];
|
||||||
|
if (var_base[i] == none) continue;
|
||||||
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);
|
||||||
}
|
}
|
||||||
const var_ty = try a.alloc(TypeId, nv);
|
const var_ty = try a.alloc(TypeId, nv);
|
||||||
for (insts, 0..) |inst, i| {
|
for (allocas.items) |i| {
|
||||||
if (inst.op != .alloca or var_base[i] == none) continue;
|
const inst = insts[i];
|
||||||
|
if (var_base[i] == none) continue;
|
||||||
const len: u32 = if (direct[i]) 1 else @intCast(m.types.items[inst.op.alloca.elem].array.len);
|
const len: u32 = if (direct[i]) 1 else @intCast(m.types.items[inst.op.alloca.elem].array.len);
|
||||||
@memset(var_ty[var_base[i]..][0..len], elem_ty[i]);
|
@memset(var_ty[var_base[i]..][0..len], elem_ty[i]);
|
||||||
}
|
}
|
||||||
|
|
@ -369,12 +382,12 @@ pub fn run(a: Allocator, m: *module.Module, func: u32, dyn: *const std.AutoHashM
|
||||||
@memset(pinned, false);
|
@memset(pinned, false);
|
||||||
const keep = try a.alloc(bool, n);
|
const keep = try a.alloc(bool, n);
|
||||||
@memset(keep, false);
|
@memset(keep, false);
|
||||||
for (insts, 0..) |inst, i| {
|
for (geps.items) |i| {
|
||||||
if (inst.op != .gep or gep_alloca[i] == none or gep_k[i] != none) continue;
|
if (gep_alloca[i] == none or gep_k[i] != none) continue;
|
||||||
const al = gep_alloca[i];
|
const al = gep_alloca[i];
|
||||||
if (var_base[al] == none) continue;
|
if (var_base[al] == none) continue;
|
||||||
const len: u32 = @intCast(m.types.items[insts[al].op.alloca.elem].array.len);
|
const len: u32 = @intCast(m.types.items[insts[al].op.alloca.elem].array.len);
|
||||||
const r = dyn.get(@intCast(i)).?;
|
const r = dyn.get(i).?;
|
||||||
const lo = @min(r[0], len);
|
const lo = @min(r[0], len);
|
||||||
const hi = @min(r[1], len);
|
const hi = @min(r[1], len);
|
||||||
@memset(pinned[var_base[al] + lo .. var_base[al] + hi], true);
|
@memset(pinned[var_base[al] + lo .. var_base[al] + hi], true);
|
||||||
|
|
@ -383,11 +396,11 @@ pub fn run(a: Allocator, m: *module.Module, func: u32, dyn: *const std.AutoHashM
|
||||||
// The variable an instruction loads or stores, or `none`.
|
// The variable an instruction loads or stores, or `none`.
|
||||||
const access = try a.alloc(u32, n);
|
const access = try a.alloc(u32, n);
|
||||||
@memset(access, none);
|
@memset(access, none);
|
||||||
for (insts, 0..) |inst, i| {
|
for (mems.items) |i| {
|
||||||
const ptr = switch (inst.op) {
|
const ptr = switch (insts[i].op) {
|
||||||
.load => |x| x.ptr,
|
.load => |x| x.ptr,
|
||||||
.store => |x| x.ptr,
|
.store => |x| x.ptr,
|
||||||
else => continue,
|
else => unreachable,
|
||||||
};
|
};
|
||||||
if (ptr != .inst) continue;
|
if (ptr != .inst) continue;
|
||||||
const p = ptr.inst;
|
const p = ptr.inst;
|
||||||
|
|
@ -404,19 +417,19 @@ pub fn run(a: Allocator, m: *module.Module, func: u32, dyn: *const std.AutoHashM
|
||||||
@memset(first_block, none);
|
@memset(first_block, none);
|
||||||
const global = try a.alloc(bool, nv);
|
const global = try a.alloc(bool, nv);
|
||||||
@memset(global, false);
|
@memset(global, false);
|
||||||
for (insts, 0..) |inst, i| {
|
for (mems.items) |i| {
|
||||||
const v = access[i];
|
const v = access[i];
|
||||||
if (v == none) continue;
|
if (v == none) continue;
|
||||||
if (first_block[v] == none) {
|
if (first_block[v] == none) {
|
||||||
first_block[v] = block_of[i];
|
first_block[v] = block_of[i];
|
||||||
if (inst.op == .load) global[v] = true;
|
if (insts[i].op == .load) global[v] = true;
|
||||||
} else if (first_block[v] != block_of[i]) global[v] = true;
|
} else if (first_block[v] != block_of[i]) global[v] = true;
|
||||||
}
|
}
|
||||||
const Def = struct { v: u32, b: u32 };
|
const Def = struct { v: u32, b: u32 };
|
||||||
var defs: std.ArrayList(Def) = .empty;
|
var defs: std.ArrayList(Def) = .empty;
|
||||||
for (insts, 0..) |inst, i| {
|
for (mems.items) |i| {
|
||||||
const v = access[i];
|
const v = access[i];
|
||||||
if (v == none or inst.op != .store or !global[v] or rpo_index[block_of[i]] == none) continue;
|
if (v == none or insts[i].op != .store or !global[v] or rpo_index[block_of[i]] == none) continue;
|
||||||
try defs.append(a, .{ .v = v, .b = block_of[i] });
|
try defs.append(a, .{ .v = v, .b = block_of[i] });
|
||||||
}
|
}
|
||||||
std.sort.pdq(Def, defs.items, {}, struct {
|
std.sort.pdq(Def, defs.items, {}, struct {
|
||||||
|
|
@ -556,8 +569,8 @@ pub fn run(a: Allocator, m: *module.Module, func: u32, dyn: *const std.AutoHashM
|
||||||
filled[j] += 1;
|
filled[j] += 1;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for (insts, 0..) |inst, i| {
|
for (mems.items) |i| {
|
||||||
if (access[i] != none and inst.op == .load and repl[i] == null)
|
if (access[i] != none and insts[i].op == .load and repl[i] == null)
|
||||||
repl[i] = try Zero.get(a, m, &zeros, var_ty[access[i]]);
|
repl[i] = try Zero.get(a, m, &zeros, var_ty[access[i]]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -612,17 +625,18 @@ pub fn run(a: Allocator, m: *module.Module, func: u32, dyn: *const std.AutoHashM
|
||||||
// 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);
|
||||||
for (insts, 0..) |inst, i| removed[i] = switch (inst.op) {
|
@memset(removed, false);
|
||||||
.alloca => var_base[i] != none and !keep[i],
|
for (allocas.items) |i| removed[i] = var_base[i] != none and !keep[i];
|
||||||
.gep => gep_alloca[i] != none and var_base[gep_alloca[i]] != none and gep_k[i] != none and !pinned[var_base[gep_alloca[i]] + gep_k[i]],
|
for (geps.items) |i| removed[i] = gep_alloca[i] != none and var_base[gep_alloca[i]] != none and gep_k[i] != none and !pinned[var_base[gep_alloca[i]] + gep_k[i]];
|
||||||
.load, .store => access[i] != none,
|
for (mems.items) |i| removed[i] = access[i] != none;
|
||||||
else => false,
|
|
||||||
};
|
|
||||||
|
|
||||||
// What stays: instructions with effects, and what they read,
|
// What stays: instructions with effects, and what they read,
|
||||||
// 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);
|
||||||
|
// (What has effects, worked out once for every round.)
|
||||||
|
var effects: std.ArrayList(u32) = .empty;
|
||||||
|
for (insts, 0..) |inst, i| if (!removed[i] and hasEffects(m, inst)) try effects.append(a, @intCast(i));
|
||||||
while (true) {
|
while (true) {
|
||||||
@memset(live, false);
|
@memset(live, false);
|
||||||
{
|
{
|
||||||
|
|
@ -647,9 +661,9 @@ pub fn run(a: Allocator, m: *module.Module, func: u32, dyn: *const std.AutoHashM
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
var mark: Mark = .{ .repl = repl, .live = live, .removed = removed, .work = &work, .a = a };
|
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)) {
|
for (effects.items) |i| if (reach[block_of[i]] or i == block_start[block_of[i] + 1] - 1) {
|
||||||
live[i] = true;
|
live[i] = true;
|
||||||
try work.append(a, @intCast(i));
|
try work.append(a, i);
|
||||||
};
|
};
|
||||||
while (work.pop()) |x| {
|
while (work.pop()) |x| {
|
||||||
if (x < n) {
|
if (x < n) {
|
||||||
|
|
@ -809,15 +823,44 @@ fn foldConstantBranches(a: Allocator, m: *module.Module, insts: []Inst, block_st
|
||||||
else => 0,
|
else => 0,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
/// Whether entry `x` of `ins` (from `ins[x].block`) is one of the
|
/// Whether each entry of `ins` (from `ins[x].block`) is one of the
|
||||||
/// edges there still are.
|
/// edges to `t` there still are: the k-th entry from a block is,
|
||||||
fn keeps(s: @This(), ins: []const Edge, x: usize, t: u32) bool {
|
/// if the block has more than k edges to `t`. `seen` and `edges_to`
|
||||||
var before: u32 = 0;
|
/// are per-block scratch (0 and `none`), left as they were.
|
||||||
for (ins[0..x]) |in| before += @intFromBool(in.block == ins[x].block);
|
fn keeps(s: @This(), ins: []const Edge, t: u32, seen: []u32, edges_to: []u32, out: []bool) void {
|
||||||
return before < s.count(ins[x].block, t);
|
for (ins, out) |in, *o| {
|
||||||
|
if (edges_to[in.block] == none) edges_to[in.block] = s.count(in.block, t);
|
||||||
|
o.* = seen[in.block] < edges_to[in.block];
|
||||||
|
seen[in.block] += 1;
|
||||||
|
}
|
||||||
|
for (ins) |in| {
|
||||||
|
seen[in.block] = 0;
|
||||||
|
edges_to[in.block] = none;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
const edges: Edges = .{ .insts = insts, .block_start = block_start, .reach = reach };
|
const edges: Edges = .{ .insts = insts, .block_start = block_start, .reach = reach };
|
||||||
|
const seen = try a.alloc(u32, nb);
|
||||||
|
@memset(seen, 0);
|
||||||
|
const edges_to = try a.alloc(u32, nb);
|
||||||
|
@memset(edges_to, none);
|
||||||
|
var kept: std.ArrayList(bool) = .empty;
|
||||||
|
// Edges into each block from reachable ones. A phi has an entry per
|
||||||
|
// edge, and folding only takes edges away: one with that many entries
|
||||||
|
// lost none.
|
||||||
|
const into = try a.alloc(u32, nb);
|
||||||
|
@memset(into, 0);
|
||||||
|
for (0..nb) |p| if (reach[p]) switch (insts[block_start[p + 1] - 1].op) {
|
||||||
|
.br => |br| {
|
||||||
|
into[br.then] += 1;
|
||||||
|
if (br.@"else") |e| into[e] += 1;
|
||||||
|
},
|
||||||
|
.@"switch" => |sw| {
|
||||||
|
into[sw.default] += 1;
|
||||||
|
for (sw.cases) |cs| into[cs.block] += 1;
|
||||||
|
},
|
||||||
|
else => {},
|
||||||
|
};
|
||||||
for (0..nb) |b| {
|
for (0..nb) |b| {
|
||||||
const t: u32 = @intCast(b);
|
const t: u32 = @intCast(b);
|
||||||
const last = block_start[b + 1] - 1;
|
const last = block_start[b + 1] - 1;
|
||||||
|
|
@ -828,12 +871,15 @@ fn foldConstantBranches(a: Allocator, m: *module.Module, insts: []Inst, block_st
|
||||||
var i = block_start[b];
|
var i = block_start[b];
|
||||||
while (i < last and insts[i].op == .phi) : (i += 1) {
|
while (i < last and insts[i].op == .phi) : (i += 1) {
|
||||||
const old = insts[i].op.phi.incoming;
|
const old = insts[i].op.phi.incoming;
|
||||||
var keep: usize = 0;
|
if (old.len == into[b]) continue;
|
||||||
for (0..old.len) |x| keep += @intFromBool(edges.keeps(old, x, t));
|
kept.clearRetainingCapacity();
|
||||||
|
try kept.resize(a, old.len);
|
||||||
|
edges.keeps(old, t, seen, edges_to, kept.items);
|
||||||
|
const keep = std.mem.count(bool, kept.items, &.{true});
|
||||||
if (keep == old.len) continue;
|
if (keep == old.len) continue;
|
||||||
const new = try m.allocator().alloc(Edge, keep);
|
const new = try m.allocator().alloc(Edge, keep);
|
||||||
var k: usize = 0;
|
var k: usize = 0;
|
||||||
for (old, 0..) |in, x| if (edges.keeps(old, x, t)) {
|
for (old, kept.items) |in, kp| if (kp) {
|
||||||
new[k] = in;
|
new[k] = in;
|
||||||
k += 1;
|
k += 1;
|
||||||
};
|
};
|
||||||
|
|
@ -842,9 +888,13 @@ fn foldConstantBranches(a: Allocator, m: *module.Module, insts: []Inst, block_st
|
||||||
for (bphis[bphi_off[b]..bphi_off[b + 1]]) |j| {
|
for (bphis[bphi_off[b]..bphi_off[b + 1]]) |j| {
|
||||||
// (Kept entries move down; each is checked against those
|
// (Kept entries move down; each is checked against those
|
||||||
// before it in the original order.)
|
// before it in the original order.)
|
||||||
const orig = try a.dupe(Edge, incoming[j]);
|
const ins = incoming[j];
|
||||||
|
if (ins.len == into[b]) continue;
|
||||||
|
kept.clearRetainingCapacity();
|
||||||
|
try kept.resize(a, ins.len);
|
||||||
|
edges.keeps(ins, t, seen, edges_to, kept.items);
|
||||||
var k: usize = 0;
|
var k: usize = 0;
|
||||||
for (orig, 0..) |in, x| if (edges.keeps(orig, x, t)) {
|
for (ins, kept.items) |in, kp| if (kp) {
|
||||||
incoming[j][k] = in;
|
incoming[j][k] = in;
|
||||||
k += 1;
|
k += 1;
|
||||||
};
|
};
|
||||||
|
|
|
||||||
|
|
@ -8,6 +8,7 @@
|
||||||
//! ZRFL part holding the rest as JSON.
|
//! ZRFL part holding the rest as JSON.
|
||||||
|
|
||||||
const std = @import("std");
|
const std = @import("std");
|
||||||
|
const BumpArena = @import("../BumpArena.zig");
|
||||||
const Allocator = std.mem.Allocator;
|
const Allocator = std.mem.Allocator;
|
||||||
const container = @import("container.zig");
|
const container = @import("container.zig");
|
||||||
|
|
||||||
|
|
@ -194,7 +195,7 @@ test "encode and decode" {
|
||||||
};
|
};
|
||||||
const blob = try encode(a, r, &.{});
|
const blob = try encode(a, r, &.{});
|
||||||
defer a.free(blob);
|
defer a.free(blob);
|
||||||
var arena: std.heap.ArenaAllocator = .init(a);
|
var arena: BumpArena = .init(a);
|
||||||
defer arena.deinit();
|
defer arena.deinit();
|
||||||
const view = try container.parse(arena.allocator(), blob);
|
const view = try container.parse(arena.allocator(), blob);
|
||||||
const back = try decode(arena.allocator(), view.find(part) orelse return error.TestUnexpectedResult);
|
const back = try decode(arena.allocator(), view.find(part) orelse return error.TestUnexpectedResult);
|
||||||
|
|
|
||||||
|
|
@ -18,6 +18,7 @@
|
||||||
//! Self-contained: depends on std only.
|
//! Self-contained: depends on std only.
|
||||||
|
|
||||||
const std = @import("std");
|
const std = @import("std");
|
||||||
|
const BumpArena = @import("../BumpArena.zig");
|
||||||
const Allocator = std.mem.Allocator;
|
const Allocator = std.mem.Allocator;
|
||||||
|
|
||||||
pub const Version = enum(u32) {
|
pub const Version = enum(u32) {
|
||||||
|
|
@ -66,7 +67,7 @@ pub fn compile(gpa: Allocator, text: []const u8, version: Version, diag: *Diagno
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn compileWithOptions(gpa: Allocator, text: []const u8, opts: Options, diag: *Diagnostic) Allocator.Error!?[]u8 {
|
pub fn compileWithOptions(gpa: Allocator, text: []const u8, opts: Options, diag: *Diagnostic) Allocator.Error!?[]u8 {
|
||||||
var arena_state = std.heap.ArenaAllocator.init(gpa);
|
var arena_state = BumpArena.init(gpa);
|
||||||
defer arena_state.deinit();
|
defer arena_state.deinit();
|
||||||
const arena = arena_state.allocator();
|
const arena = arena_state.allocator();
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -49,16 +49,77 @@ const Cfg = struct {
|
||||||
succs: [][]u32,
|
succs: [][]u32,
|
||||||
preds: [][]u32,
|
preds: [][]u32,
|
||||||
idom: []u32,
|
idom: []u32,
|
||||||
|
/// Each reachable block's interval in a depth-first walk of the
|
||||||
|
/// dominator tree (`none` for unreachable blocks): `d` dominates `b`
|
||||||
|
/// when `b`'s interval is inside `d`'s.
|
||||||
|
dom_pre: []u32,
|
||||||
|
dom_post: []u32,
|
||||||
|
|
||||||
fn dominates(c: *const Cfg, d: u32, b: u32) bool {
|
fn dominates(c: *const Cfg, d: u32, b: u32) bool {
|
||||||
var x = b;
|
if (d == b) return true;
|
||||||
while (true) {
|
if (c.dom_pre[d] == none or c.dom_pre[b] == none) return false;
|
||||||
if (x == d) return true;
|
return c.dom_pre[d] <= c.dom_pre[b] and c.dom_post[b] <= c.dom_post[d];
|
||||||
const p = c.idom[x];
|
}
|
||||||
if (p == none or p == x) return false;
|
};
|
||||||
x = p;
|
|
||||||
|
/// Numbers the dominator tree's blocks in and out of a depth-first walk.
|
||||||
|
fn domIntervals(a: Allocator, idom: []const u32) Allocator.Error!struct { []u32, []u32 } {
|
||||||
|
const nb = idom.len;
|
||||||
|
// Children lists, packed: block b's are kids[first[b]..first[b + 1]].
|
||||||
|
const first = try a.alloc(u32, nb + 1);
|
||||||
|
@memset(first, 0);
|
||||||
|
for (idom, 0..) |p, b| if (p != none and p != b) {
|
||||||
|
first[p + 1] += 1;
|
||||||
|
};
|
||||||
|
for (1..nb + 1) |k| first[k] += first[k - 1];
|
||||||
|
const fill = try a.dupe(u32, first[0..nb]);
|
||||||
|
const kids = try a.alloc(u32, first[nb]);
|
||||||
|
for (idom, 0..) |p, b| if (p != none and p != b) {
|
||||||
|
kids[fill[p]] = @intCast(b);
|
||||||
|
fill[p] += 1;
|
||||||
|
};
|
||||||
|
const pre = try a.alloc(u32, nb);
|
||||||
|
const post = try a.alloc(u32, nb);
|
||||||
|
@memset(pre, none);
|
||||||
|
@memset(post, none);
|
||||||
|
if (nb == 0) return .{ pre, post };
|
||||||
|
var clock: u32 = 0;
|
||||||
|
// `next` reuses fill: the next child to visit.
|
||||||
|
@memcpy(fill, first[0..nb]);
|
||||||
|
var stack: std.ArrayList(u32) = .empty;
|
||||||
|
try stack.append(a, 0);
|
||||||
|
pre[0] = clock;
|
||||||
|
clock += 1;
|
||||||
|
while (stack.items.len > 0) {
|
||||||
|
const b = stack.items[stack.items.len - 1];
|
||||||
|
if (fill[b] < first[b + 1]) {
|
||||||
|
const k = kids[fill[b]];
|
||||||
|
fill[b] += 1;
|
||||||
|
pre[k] = clock;
|
||||||
|
clock += 1;
|
||||||
|
try stack.append(a, k);
|
||||||
|
} else {
|
||||||
|
post[b] = clock;
|
||||||
|
clock += 1;
|
||||||
|
_ = stack.pop();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
return .{ pre, post };
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A loop's blocks: a bit per block of the function, and the list in
|
||||||
|
/// block order.
|
||||||
|
const Body = struct {
|
||||||
|
bits: []u64,
|
||||||
|
blocks: []const u32,
|
||||||
|
|
||||||
|
fn has(b: Body, x: u32) bool {
|
||||||
|
return b.bits[x >> 6] >> @intCast(x & 63) & 1 != 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn add(b: *Body, x: u32) void {
|
||||||
|
b.bits[x >> 6] |= @as(u64, 1) << @intCast(x & 63);
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
fn isTerminator(inst: Inst) bool {
|
fn isTerminator(inst: Inst) bool {
|
||||||
|
|
@ -82,27 +143,43 @@ fn buildCfg(a: Allocator, f: *const module.Function) Allocator.Error!?Cfg {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (b != nb) return null;
|
if (b != nb) return null;
|
||||||
const succs = try a.alloc([]u32, nb);
|
// Successors (each once) and predecessors, packed: each block's are a
|
||||||
var pred_lists = try a.alloc(std.ArrayList(u32), nb);
|
// slice of one array.
|
||||||
for (pred_lists) |*p| p.* = .empty;
|
var succ_flat: std.ArrayList(u32) = .empty;
|
||||||
|
try succ_flat.ensureTotalCapacity(a, 2 * nb);
|
||||||
|
const succ_off = try a.alloc(u32, nb + 1);
|
||||||
for (0..nb) |bi| {
|
for (0..nb) |bi| {
|
||||||
var s: std.ArrayList(u32) = .empty;
|
const start = succ_flat.items.len;
|
||||||
|
succ_off[bi] = @intCast(start);
|
||||||
switch (insts[block_start[bi + 1] - 1].op) {
|
switch (insts[block_start[bi + 1] - 1].op) {
|
||||||
.br => |br| {
|
.br => |br| {
|
||||||
try s.append(a, br.then);
|
try succ_flat.append(a, br.then);
|
||||||
if (br.@"else") |e| if (e != br.then) try s.append(a, e);
|
if (br.@"else") |e| if (e != br.then) try succ_flat.append(a, e);
|
||||||
},
|
},
|
||||||
.@"switch" => |sw| {
|
.@"switch" => |sw| {
|
||||||
try s.append(a, sw.default);
|
try succ_flat.append(a, sw.default);
|
||||||
for (sw.cases) |c| if (std.mem.indexOfScalar(u32, s.items, c.block) == null) try s.append(a, c.block);
|
for (sw.cases) |c| if (std.mem.indexOfScalar(u32, succ_flat.items[start..], c.block) == null) try succ_flat.append(a, c.block);
|
||||||
},
|
},
|
||||||
else => {},
|
else => {},
|
||||||
}
|
}
|
||||||
succs[bi] = s.items;
|
}
|
||||||
for (s.items) |t| try pred_lists[t].append(a, @intCast(bi));
|
succ_off[nb] = @intCast(succ_flat.items.len);
|
||||||
|
const succs = try a.alloc([]u32, nb);
|
||||||
|
for (succs, 0..) |*sl, bi| sl.* = succ_flat.items[succ_off[bi]..succ_off[bi + 1]];
|
||||||
|
const pred_off = try a.alloc(u32, nb + 1);
|
||||||
|
@memset(pred_off, 0);
|
||||||
|
for (succ_flat.items) |t| pred_off[t + 1] += 1;
|
||||||
|
for (1..nb + 1) |k| pred_off[k] += pred_off[k - 1];
|
||||||
|
const pred_flat = try a.alloc(u32, succ_flat.items.len);
|
||||||
|
{
|
||||||
|
const fill = try a.dupe(u32, pred_off[0..nb]);
|
||||||
|
for (0..nb) |bi| for (succs[bi]) |t| {
|
||||||
|
pred_flat[fill[t]] = @intCast(bi);
|
||||||
|
fill[t] += 1;
|
||||||
|
};
|
||||||
}
|
}
|
||||||
const preds = try a.alloc([]u32, nb);
|
const preds = try a.alloc([]u32, nb);
|
||||||
for (preds, pred_lists) |*p, l| p.* = l.items;
|
for (preds, 0..) |*pl, bi| pl.* = pred_flat[pred_off[bi]..pred_off[bi + 1]];
|
||||||
|
|
||||||
// Reverse postorder, then Cooper, Harvey and Kennedy's dominators.
|
// Reverse postorder, then Cooper, Harvey and Kennedy's dominators.
|
||||||
const order = try a.alloc(u32, nb);
|
const order = try a.alloc(u32, nb);
|
||||||
|
|
@ -165,7 +242,8 @@ fn buildCfg(a: Allocator, f: *const module.Function) Allocator.Error!?Cfg {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return .{ .nb = nb, .block_start = block_start, .succs = succs, .preds = preds, .idom = idom };
|
const pre, const post = try domIntervals(a, idom);
|
||||||
|
return .{ .nb = nb, .block_start = block_start, .succs = succs, .preds = preds, .idom = idom, .dom_pre = pre, .dom_post = post };
|
||||||
}
|
}
|
||||||
|
|
||||||
fn constInt(m: *const module.Module, v: Value) ?i64 {
|
fn constInt(m: *const module.Module, v: Value) ?i64 {
|
||||||
|
|
@ -285,7 +363,7 @@ fn unrollOne(a: Allocator, m: *module.Module, func: u32, budget: *usize, tried:
|
||||||
|
|
||||||
// Loops: headers with back edges (from blocks they dominate), and
|
// Loops: headers with back edges (from blocks they dominate), and
|
||||||
// their blocks.
|
// their blocks.
|
||||||
const Loop = struct { h: u32, body: []bool, latches: []u32 };
|
const Loop = struct { h: u32, body: Body, latches: []u32 };
|
||||||
var loops: std.ArrayList(Loop) = .empty;
|
var loops: std.ArrayList(Loop) = .empty;
|
||||||
for (0..nb) |hb| {
|
for (0..nb) |hb| {
|
||||||
const h: u32 = @intCast(hb);
|
const h: u32 = @intCast(hb);
|
||||||
|
|
@ -293,16 +371,30 @@ fn unrollOne(a: Allocator, m: *module.Module, func: u32, budget: *usize, tried:
|
||||||
var latches: std.ArrayList(u32) = .empty;
|
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);
|
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;
|
if (latches.items.len == 0) continue;
|
||||||
const body = try a.alloc(bool, nb);
|
const bits = try a.alloc(u64, (nb + 63) / 64);
|
||||||
@memset(body, false);
|
@memset(bits, 0);
|
||||||
body[h] = true;
|
var body: Body = .{ .bits = bits, .blocks = &.{} };
|
||||||
|
body.add(h);
|
||||||
|
var count: usize = 1;
|
||||||
var stack: std.ArrayList(u32) = .empty;
|
var stack: std.ArrayList(u32) = .empty;
|
||||||
try stack.appendSlice(a, latches.items);
|
try stack.appendSlice(a, latches.items);
|
||||||
while (stack.pop()) |x| {
|
while (stack.pop()) |x| {
|
||||||
if (body[x]) continue;
|
if (body.has(x)) continue;
|
||||||
body[x] = true;
|
body.add(x);
|
||||||
|
count += 1;
|
||||||
for (cfg.preds[x]) |p| if (cfg.idom[p] != none) try stack.append(a, p);
|
for (cfg.preds[x]) |p| if (cfg.idom[p] != none) try stack.append(a, p);
|
||||||
}
|
}
|
||||||
|
// The blocks in order, from the bits.
|
||||||
|
const blocks = try a.alloc(u32, count);
|
||||||
|
var k: usize = 0;
|
||||||
|
for (bits, 0..) |word, wi| {
|
||||||
|
var w = word;
|
||||||
|
while (w != 0) : (w &= w - 1) {
|
||||||
|
blocks[k] = @intCast(wi * 64 + @ctz(w));
|
||||||
|
k += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
body.blocks = blocks;
|
||||||
try loops.append(a, .{ .h = h, .body = body, .latches = latches.items });
|
try loops.append(a, .{ .h = h, .body = body, .latches = latches.items });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -312,10 +404,14 @@ fn unrollOne(a: Allocator, m: *module.Module, func: u32, budget: *usize, tried:
|
||||||
// that block; their blocks are left unreachable for promotion to drop.
|
// that block; their blocks are left unreachable for promotion to drop.
|
||||||
// (Nested ones too: an outer loop whose inner loops do nothing.)
|
// (Nested ones too: an outer loop whose inner loops do nothing.)
|
||||||
const loop_inst = try a.alloc(bool, insts.len);
|
const loop_inst = try a.alloc(bool, insts.len);
|
||||||
|
@memset(loop_inst, false);
|
||||||
|
// (The loop whose instructions loop_inst marks, cleared for the next.)
|
||||||
|
var marked: ?Body = null;
|
||||||
dead: for (loops.items) |lp| {
|
dead: for (loops.items) |lp| {
|
||||||
|
if (marked) |mk| for (mk.blocks) |bb| @memset(loop_inst[cfg.block_start[bb]..cfg.block_start[bb + 1]], false);
|
||||||
|
marked = null;
|
||||||
var exit: u32 = none;
|
var exit: u32 = none;
|
||||||
for (0..nb) |bb| {
|
for (lp.body.blocks) |bb| {
|
||||||
if (!lp.body[bb]) continue;
|
|
||||||
for (cfg.block_start[bb]..cfg.block_start[bb + 1]) |i| switch (insts[i].op) {
|
for (cfg.block_start[bb]..cfg.block_start[bb + 1]) |i| switch (insts[i].op) {
|
||||||
.br, .@"switch" => {},
|
.br, .@"switch" => {},
|
||||||
.ret, .@"unreachable", .store, .atomicrmw, .cmpxchg => continue :dead,
|
.ret, .@"unreachable", .store, .atomicrmw, .cmpxchg => continue :dead,
|
||||||
|
|
@ -325,14 +421,14 @@ fn unrollOne(a: Allocator, m: *module.Module, func: u32, budget: *usize, tried:
|
||||||
},
|
},
|
||||||
else => {},
|
else => {},
|
||||||
};
|
};
|
||||||
for (cfg.succs[bb]) |s| if (!lp.body[s]) {
|
for (cfg.succs[bb]) |s| if (!lp.body.has(s)) {
|
||||||
if (exit != none and exit != s) continue :dead;
|
if (exit != none and exit != s) continue :dead;
|
||||||
exit = s;
|
exit = s;
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
if (exit == none) continue;
|
if (exit == none) continue;
|
||||||
var pre: u32 = none;
|
var pre: u32 = none;
|
||||||
for (cfg.preds[lp.h]) |p| if (!lp.body[p]) {
|
for (cfg.preds[lp.h]) |p| if (!lp.body.has(p)) {
|
||||||
if (pre != none) continue :dead;
|
if (pre != none) continue :dead;
|
||||||
pre = p;
|
pre = p;
|
||||||
};
|
};
|
||||||
|
|
@ -341,9 +437,8 @@ fn unrollOne(a: Allocator, m: *module.Module, func: u32, budget: *usize, tried:
|
||||||
if (pterm.op != .br) continue;
|
if (pterm.op != .br) continue;
|
||||||
if (pterm.op.br.then == exit or pterm.op.br.@"else" == exit) 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| {
|
for (lp.body.blocks) |bb| @memset(loop_inst[cfg.block_start[bb]..cfg.block_start[bb + 1]], true);
|
||||||
loop_inst[i] = lp.body[bb];
|
marked = lp.body;
|
||||||
};
|
|
||||||
// The exit's phis: one value from the loop, from before it.
|
// The exit's phis: one value from the loop, from before it.
|
||||||
const phi_end = blk: {
|
const phi_end = blk: {
|
||||||
var i = cfg.block_start[exit];
|
var i = cfg.block_start[exit];
|
||||||
|
|
@ -353,7 +448,7 @@ fn unrollOne(a: Allocator, m: *module.Module, func: u32, budget: *usize, tried:
|
||||||
const from_loop = try a.alloc(?Value, phi_end - cfg.block_start[exit]);
|
const from_loop = try a.alloc(?Value, phi_end - cfg.block_start[exit]);
|
||||||
for (cfg.block_start[exit]..phi_end, from_loop) |i, *fl| {
|
for (cfg.block_start[exit]..phi_end, from_loop) |i, *fl| {
|
||||||
fl.* = null;
|
fl.* = null;
|
||||||
for (insts[i].op.phi.incoming) |in| if (lp.body[in.block]) {
|
for (insts[i].op.phi.incoming) |in| if (lp.body.has(in.block)) {
|
||||||
if (in.val == .inst and loop_inst[in.val.inst]) continue :dead;
|
if (in.val == .inst and loop_inst[in.val.inst]) continue :dead;
|
||||||
if (fl.* != null and !std.meta.eql(fl.*.?, in.val)) continue :dead;
|
if (fl.* != null and !std.meta.eql(fl.*.?, in.val)) continue :dead;
|
||||||
fl.* = in.val;
|
fl.* = in.val;
|
||||||
|
|
@ -370,7 +465,7 @@ fn unrollOne(a: Allocator, m: *module.Module, func: u32, budget: *usize, tried:
|
||||||
};
|
};
|
||||||
var check: Check = .{ .loop_inst = loop_inst };
|
var check: Check = .{ .loop_inst = loop_inst };
|
||||||
for (0..nb) |bb| {
|
for (0..nb) |bb| {
|
||||||
if (lp.body[bb]) continue;
|
if (lp.body.has(@intCast(bb))) continue;
|
||||||
for (cfg.block_start[bb]..cfg.block_start[bb + 1]) |i| {
|
for (cfg.block_start[bb]..cfg.block_start[bb + 1]) |i| {
|
||||||
if (bb == exit and i < phi_end) continue;
|
if (bb == exit and i < phi_end) continue;
|
||||||
var copy = insts[i];
|
var copy = insts[i];
|
||||||
|
|
@ -382,7 +477,7 @@ fn unrollOne(a: Allocator, m: *module.Module, func: u32, budget: *usize, tried:
|
||||||
const ma = m.allocator();
|
const ma = m.allocator();
|
||||||
for (cfg.block_start[exit]..phi_end, from_loop) |i, fl| {
|
for (cfg.block_start[exit]..phi_end, from_loop) |i, fl| {
|
||||||
var edges: std.ArrayList(Edge) = .empty;
|
var edges: std.ArrayList(Edge) = .empty;
|
||||||
for (insts[i].op.phi.incoming) |in| if (!lp.body[in.block]) try edges.append(ma, in);
|
for (insts[i].op.phi.incoming) |in| if (!lp.body.has(in.block)) try edges.append(ma, in);
|
||||||
if (fl) |v| try edges.append(ma, .{ .val = v, .block = pre });
|
if (fl) |v| try edges.append(ma, .{ .val = v, .block = pre });
|
||||||
insts[i].op.phi.incoming = edges.items;
|
insts[i].op.phi.incoming = edges.items;
|
||||||
}
|
}
|
||||||
|
|
@ -390,9 +485,7 @@ fn unrollOne(a: Allocator, m: *module.Module, func: u32, budget: *usize, tried:
|
||||||
if (pterm.op.br.@"else") |*e| if (e.* == lp.h) {
|
if (pterm.op.br.@"else") |*e| if (e.* == lp.h) {
|
||||||
e.* = exit;
|
e.* = exit;
|
||||||
};
|
};
|
||||||
for (0..nb) |bb| if (lp.body[bb]) {
|
for (lp.body.blocks) |bb| insts[cfg.block_start[bb + 1] - 1].op = .@"unreachable";
|
||||||
insts[cfg.block_start[bb + 1] - 1].op = .@"unreachable";
|
|
||||||
};
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -400,7 +493,7 @@ fn unrollOne(a: Allocator, m: *module.Module, func: u32, budget: *usize, tried:
|
||||||
const h = lp.h;
|
const h = lp.h;
|
||||||
if (tried.contains(h)) continue;
|
if (tried.contains(h)) continue;
|
||||||
// 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[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, {});
|
||||||
|
|
||||||
// One way out: a conditional branch from one block, to one block.
|
// One way out: a conditional branch from one block, to one block.
|
||||||
|
|
@ -408,17 +501,16 @@ fn unrollOne(a: Allocator, m: *module.Module, func: u32, budget: *usize, tried:
|
||||||
var exit: u32 = none;
|
var exit: u32 = none;
|
||||||
var size: usize = 0;
|
var size: usize = 0;
|
||||||
var body_blocks: std.ArrayList(u32) = .empty;
|
var body_blocks: std.ArrayList(u32) = .empty;
|
||||||
for (0..nb) |bb| {
|
for (lp.body.blocks) |bb| {
|
||||||
if (!lp.body[bb]) continue;
|
try body_blocks.append(a, bb);
|
||||||
try body_blocks.append(a, @intCast(bb));
|
|
||||||
size += cfg.block_start[bb + 1] - cfg.block_start[bb];
|
size += cfg.block_start[bb + 1] - cfg.block_start[bb];
|
||||||
const term = insts[cfg.block_start[bb + 1] - 1].op;
|
const term = insts[cfg.block_start[bb + 1] - 1].op;
|
||||||
if (term == .@"switch") {
|
if (term == .@"switch") {
|
||||||
for (cfg.succs[bb]) |s| if (!lp.body[s]) continue :candidates;
|
for (cfg.succs[bb]) |s| if (!lp.body.has(s)) continue :candidates;
|
||||||
}
|
}
|
||||||
for (cfg.succs[bb]) |s| if (!lp.body[s]) {
|
for (cfg.succs[bb]) |s| if (!lp.body.has(s)) {
|
||||||
if (exiting != none) continue :candidates;
|
if (exiting != none) continue :candidates;
|
||||||
exiting = @intCast(bb);
|
exiting = bb;
|
||||||
exit = s;
|
exit = s;
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
@ -426,11 +518,11 @@ fn unrollOne(a: Allocator, m: *module.Module, func: u32, budget: *usize, tried:
|
||||||
const xterm = insts[cfg.block_start[exiting + 1] - 1].op;
|
const xterm = insts[cfg.block_start[exiting + 1] - 1].op;
|
||||||
if (xterm != .br or xterm.br.@"else" == null) continue;
|
if (xterm != .br or xterm.br.@"else" == null) continue;
|
||||||
const stay = if (xterm.br.then == exit) xterm.br.@"else".? else xterm.br.then;
|
const stay = if (xterm.br.then == exit) xterm.br.@"else".? else xterm.br.then;
|
||||||
if (!lp.body[stay] or stay == exit) continue;
|
if (!lp.body.has(stay) or stay == exit) continue;
|
||||||
for (lp.latches) |l| if (!cfg.dominates(exiting, l)) continue :candidates;
|
for (lp.latches) |l| if (!cfg.dominates(exiting, l)) continue :candidates;
|
||||||
// One way in.
|
// One way in.
|
||||||
var pre: u32 = none;
|
var pre: u32 = none;
|
||||||
for (cfg.preds[h]) |p| if (!lp.body[p]) {
|
for (cfg.preds[h]) |p| if (!lp.body.has(p)) {
|
||||||
if (pre != none) continue :candidates;
|
if (pre != none) continue :candidates;
|
||||||
pre = p;
|
pre = p;
|
||||||
};
|
};
|
||||||
|
|
@ -623,7 +715,7 @@ fn unrollOne(a: Allocator, m: *module.Module, func: u32, budget: *usize, tried:
|
||||||
const last: Mapper = .{ .maps = maps, .new_index = new_index, .k = copies - 1 };
|
const last: Mapper = .{ .maps = maps, .new_index = new_index, .k = copies - 1 };
|
||||||
const in_body = try a.alloc(bool, n0);
|
const in_body = try a.alloc(bool, n0);
|
||||||
for (0..nb) |bb| for (cfg.block_start[bb]..cfg.block_start[bb + 1]) |i| {
|
for (0..nb) |bb| for (cfg.block_start[bb]..cfg.block_start[bb + 1]) |i| {
|
||||||
in_body[i] = lp.body[bb];
|
in_body[i] = lp.body.has(@intCast(bb));
|
||||||
};
|
};
|
||||||
const Outside = struct {
|
const Outside = struct {
|
||||||
last: Mapper,
|
last: Mapper,
|
||||||
|
|
@ -635,7 +727,7 @@ fn unrollOne(a: Allocator, m: *module.Module, func: u32, budget: *usize, tried:
|
||||||
};
|
};
|
||||||
var outside: Outside = .{ .last = last, .in_body = in_body };
|
var outside: Outside = .{ .last = last, .in_body = in_body };
|
||||||
for (0..nb) |bb| {
|
for (0..nb) |bb| {
|
||||||
if (lp.body[bb]) {
|
if (lp.body.has(@intCast(bb))) {
|
||||||
// The originals: unreachable now.
|
// The originals: unreachable now.
|
||||||
insts[cfg.block_start[bb + 1] - 1].op = .@"unreachable";
|
insts[cfg.block_start[bb + 1] - 1].op = .@"unreachable";
|
||||||
continue;
|
continue;
|
||||||
|
|
|
||||||
|
|
@ -7,6 +7,7 @@
|
||||||
//! builtin types are recognized by name.
|
//! builtin types are recognized by name.
|
||||||
|
|
||||||
const std = @import("std");
|
const std = @import("std");
|
||||||
|
const BumpArena = @import("../BumpArena.zig");
|
||||||
const Allocator = std.mem.Allocator;
|
const Allocator = std.mem.Allocator;
|
||||||
const ast = @import("ast.zig");
|
const ast = @import("ast.zig");
|
||||||
const lexer = @import("lexer.zig");
|
const lexer = @import("lexer.zig");
|
||||||
|
|
@ -523,7 +524,7 @@ pub const Parser = struct {
|
||||||
defer p.last_quals = words.items;
|
defer p.last_quals = words.items;
|
||||||
while (p.at(.identifier)) {
|
while (p.at(.identifier)) {
|
||||||
const word = p.tok().text;
|
const word = p.tok().text;
|
||||||
if (inList(&reserved_declspecs, word)) {
|
if (isReservedDeclspec(word)) {
|
||||||
// dxc reports these and parses on as if they were absent.
|
// dxc reports these and parses on as if they were absent.
|
||||||
_ = p.reportAt(p.pos, .@"error", "'{s}' is a reserved keyword in HLSL", .{word});
|
_ = p.reportAt(p.pos, .@"error", "'{s}' is a reserved keyword in HLSL", .{word});
|
||||||
_ = p.advance();
|
_ = p.advance();
|
||||||
|
|
@ -1565,7 +1566,7 @@ pub const Parser = struct {
|
||||||
if (std.mem.eql(u8, w, "struct") or std.mem.eql(u8, w, "class") or std.mem.eql(u8, w, "typedef") or
|
if (std.mem.eql(u8, w, "struct") or std.mem.eql(u8, w, "class") or std.mem.eql(u8, w, "typedef") or
|
||||||
std.mem.eql(u8, w, "using") or std.mem.eql(u8, w, "enum") or std.mem.eql(u8, w, "_Static_assert"))
|
std.mem.eql(u8, w, "using") or std.mem.eql(u8, w, "enum") or std.mem.eql(u8, w, "_Static_assert"))
|
||||||
return true;
|
return true;
|
||||||
if (inList(&reserved_declspecs, w)) return true;
|
if (isReservedDeclspec(w)) return true;
|
||||||
if (isEffectObjectWord(t) and p.peek(1).kind == .identifier) return true;
|
if (isEffectObjectWord(t) and p.peek(1).kind == .identifier) return true;
|
||||||
if (qualifierField(w) != null) {
|
if (qualifierField(w) != null) {
|
||||||
if (!isContextualQualifier(w)) return true;
|
if (!isContextualQualifier(w)) return true;
|
||||||
|
|
@ -1939,14 +1940,22 @@ fn isTechniqueWord(t: Token) bool {
|
||||||
}
|
}
|
||||||
|
|
||||||
/// dxc's g_DeprecatedEffectObjectNames.
|
/// dxc's g_DeprecatedEffectObjectNames.
|
||||||
|
const effect_object_words = [_][]const u8{
|
||||||
|
"texture", "Texture", "pixelshader", "PixelShader", "vertexshader",
|
||||||
|
"VertexShader", "pixelfragment", "vertexfragment", "ComputeShader", "DomainShader",
|
||||||
|
"GeometryShader", "HullShader", "BlendState", "DepthStencilState", "DepthStencilView",
|
||||||
|
"RasterizerState", "RenderTargetView",
|
||||||
|
};
|
||||||
|
|
||||||
fn isEffectObjectWord(t: Token) bool {
|
fn isEffectObjectWord(t: Token) bool {
|
||||||
const names = [_][]const u8{
|
if (t.kind != .identifier) return false;
|
||||||
"texture", "Texture", "pixelshader", "PixelShader", "vertexshader",
|
const info = word_map.get(t.text) orelse return false;
|
||||||
"VertexShader", "pixelfragment", "vertexfragment", "ComputeShader", "DomainShader",
|
return info.effect_object;
|
||||||
"GeometryShader", "HullShader", "BlendState", "DepthStencilState", "DepthStencilView",
|
}
|
||||||
"RasterizerState", "RenderTargetView",
|
|
||||||
};
|
fn isReservedDeclspec(w: []const u8) bool {
|
||||||
return t.kind == .identifier and inList(&names, t.text);
|
const info = word_map.get(w) orelse return false;
|
||||||
|
return info.declspec;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Type attributes that may precede a type: `unorm float`,
|
/// Type attributes that may precede a type: `unorm float`,
|
||||||
|
|
@ -2077,6 +2086,8 @@ const WordInfo = struct {
|
||||||
numeric_scalar: bool = false,
|
numeric_scalar: bool = false,
|
||||||
object: bool = false,
|
object: bool = false,
|
||||||
template: bool = false,
|
template: bool = false,
|
||||||
|
declspec: bool = false,
|
||||||
|
effect_object: bool = false,
|
||||||
};
|
};
|
||||||
|
|
||||||
fn inList(list: []const []const u8, w: []const u8) bool {
|
fn inList(list: []const []const u8, w: []const u8) bool {
|
||||||
|
|
@ -2088,7 +2099,7 @@ fn inList(list: []const []const u8, w: []const u8) bool {
|
||||||
/// replaces linear scans of the lists above (a third of parse time).
|
/// replaces linear scans of the lists above (a third of parse time).
|
||||||
const word_map = blk: {
|
const word_map = blk: {
|
||||||
@setEvalBranchQuota(1_000_000);
|
@setEvalBranchQuota(1_000_000);
|
||||||
var words: []const []const u8 = &(reserved_words ++ contextual_words ++ scalar_types ++ object_types ++ enum_typedefs ++ template_types ++ template_funcs);
|
var words: []const []const u8 = &(reserved_words ++ contextual_words ++ scalar_types ++ object_types ++ enum_typedefs ++ template_types ++ template_funcs ++ reserved_declspecs ++ effect_object_words);
|
||||||
for (qualifier_words) |q| words = words ++ &[_][]const u8{q[0]};
|
for (qualifier_words) |q| words = words ++ &[_][]const u8{q[0]};
|
||||||
var kvs: [words.len]struct { []const u8, WordInfo } = undefined;
|
var kvs: [words.len]struct { []const u8, WordInfo } = undefined;
|
||||||
var n: usize = 0;
|
var n: usize = 0;
|
||||||
|
|
@ -2101,6 +2112,8 @@ const word_map = blk: {
|
||||||
.numeric_scalar = inList(&scalar_types, w) and !std.mem.endsWith(u8, w, "_packed"),
|
.numeric_scalar = inList(&scalar_types, w) and !std.mem.endsWith(u8, w, "_packed"),
|
||||||
.object = inList(&object_types, w) or inList(&enum_typedefs, w),
|
.object = inList(&object_types, w) or inList(&enum_typedefs, w),
|
||||||
.template = inList(&template_types, w) or inList(&template_funcs, w),
|
.template = inList(&template_types, w) or inList(&template_funcs, w),
|
||||||
|
.declspec = inList(&reserved_declspecs, w),
|
||||||
|
.effect_object = inList(&effect_object_words, w),
|
||||||
};
|
};
|
||||||
for (qualifier_words) |q| {
|
for (qualifier_words) |q| {
|
||||||
if (std.mem.eql(u8, q[0], w)) info.qualifier = q[1];
|
if (std.mem.eql(u8, q[0], w)) info.qualifier = q[1];
|
||||||
|
|
@ -2109,9 +2122,66 @@ const word_map = blk: {
|
||||||
n += 1;
|
n += 1;
|
||||||
}
|
}
|
||||||
const final = kvs[0..n].*;
|
const final = kvs[0..n].*;
|
||||||
break :blk std.StaticStringMap(WordInfo).initComptime(final);
|
break :blk WordMap(WordInfo, final.len).init(final);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/// A string map built at compile time: an open-addressing table on a cheap
|
||||||
|
/// hash, comparing a stored hash before any bytes. Most identifiers a
|
||||||
|
/// lookup sees are not in it, and miss after a probe or two (what
|
||||||
|
/// std.StaticStringMap does is compare every key of the same length).
|
||||||
|
fn WordMap(comptime V: type, comptime n: usize) type {
|
||||||
|
return struct {
|
||||||
|
const Self = @This();
|
||||||
|
/// Twice the keys or more, a power of two.
|
||||||
|
const size = std.math.ceilPowerOfTwoAssert(usize, n * 4);
|
||||||
|
const empty = std.math.maxInt(u16);
|
||||||
|
|
||||||
|
keys: [n][]const u8,
|
||||||
|
values: [n]V,
|
||||||
|
hashes: [n]u32,
|
||||||
|
slots: [size]u16,
|
||||||
|
|
||||||
|
fn hash(w: []const u8) u32 {
|
||||||
|
var h: u32 = 2166136261;
|
||||||
|
for (w) |c| h = (h ^ c) *% 16777619;
|
||||||
|
return h;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn init(comptime kvs: anytype) Self {
|
||||||
|
var m: Self = undefined;
|
||||||
|
m.slots = @splat(empty);
|
||||||
|
for (kvs, 0..) |kv, k| {
|
||||||
|
m.keys[k] = kv[0];
|
||||||
|
m.values[k] = kv[1];
|
||||||
|
m.hashes[k] = hash(kv[0]);
|
||||||
|
var i = m.hashes[k] & (size - 1);
|
||||||
|
while (m.slots[i] != empty) i = (i + 1) & (size - 1);
|
||||||
|
m.slots[i] = k;
|
||||||
|
}
|
||||||
|
return m;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get(m: *const Self, w: []const u8) ?V {
|
||||||
|
const h = hash(w);
|
||||||
|
var i = h & (size - 1);
|
||||||
|
while (true) : (i = (i + 1) & (size - 1)) {
|
||||||
|
const k = m.slots[i];
|
||||||
|
if (k == empty) return null;
|
||||||
|
if (m.hashes[k] == h and std.mem.eql(u8, m.keys[k], w)) return m.values[k];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
test WordMap {
|
||||||
|
const M = WordMap(u8, 3);
|
||||||
|
const m = comptime M.init(.{ .{ "float", 1 }, .{ "in", 2 }, .{ "inout", 3 } });
|
||||||
|
try std.testing.expectEqual(1, m.get("float").?);
|
||||||
|
try std.testing.expectEqual(3, m.get("inout").?);
|
||||||
|
try std.testing.expectEqual(null, m.get("floa"));
|
||||||
|
try std.testing.expectEqual(null, m.get(""));
|
||||||
|
}
|
||||||
|
|
||||||
fn isNumericScalar(w: []const u8) bool {
|
fn isNumericScalar(w: []const u8) bool {
|
||||||
const info = word_map.get(w) orelse return false;
|
const info = word_map.get(w) orelse return false;
|
||||||
return info.numeric_scalar;
|
return info.numeric_scalar;
|
||||||
|
|
@ -2154,7 +2224,7 @@ const TestParse = struct {
|
||||||
mfs: source.MemoryFs = .{},
|
mfs: source.MemoryFs = .{},
|
||||||
sm: source.SourceManager = undefined,
|
sm: source.SourceManager = undefined,
|
||||||
diags: Diagnostics = undefined,
|
diags: Diagnostics = undefined,
|
||||||
arena: std.heap.ArenaAllocator = undefined,
|
arena: BumpArena = undefined,
|
||||||
out: std.Io.Writer.Allocating = undefined,
|
out: std.Io.Writer.Allocating = undefined,
|
||||||
|
|
||||||
fn run(t: *TestParse, text: []const u8) ![]const u8 {
|
fn run(t: *TestParse, text: []const u8) ![]const u8 {
|
||||||
|
|
|
||||||
|
|
@ -4,6 +4,7 @@
|
||||||
//! disabled macro.
|
//! disabled macro.
|
||||||
|
|
||||||
const std = @import("std");
|
const std = @import("std");
|
||||||
|
const BumpArena = @import("../BumpArena.zig");
|
||||||
const Allocator = std.mem.Allocator;
|
const Allocator = std.mem.Allocator;
|
||||||
const source = @import("source.zig");
|
const source = @import("source.zig");
|
||||||
const lexer = @import("lexer.zig");
|
const lexer = @import("lexer.zig");
|
||||||
|
|
@ -1446,7 +1447,7 @@ const TestPP = struct {
|
||||||
mfs: source.MemoryFs = .{},
|
mfs: source.MemoryFs = .{},
|
||||||
sm: source.SourceManager = undefined,
|
sm: source.SourceManager = undefined,
|
||||||
diags: Diagnostics = undefined,
|
diags: Diagnostics = undefined,
|
||||||
arena: std.heap.ArenaAllocator = undefined,
|
arena: BumpArena = undefined,
|
||||||
pp: Preprocessor = undefined,
|
pp: Preprocessor = undefined,
|
||||||
|
|
||||||
fn init(t: *TestPP, files: []const [2][]const u8, main: []const u8, opts: Options) !void {
|
fn init(t: *TestPP, files: []const [2][]const u8, main: []const u8, opts: Options) !void {
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,7 @@
|
||||||
//! Source files and locations.
|
//! Source files and locations.
|
||||||
|
|
||||||
const std = @import("std");
|
const std = @import("std");
|
||||||
|
const BumpArena = @import("../BumpArena.zig");
|
||||||
const Allocator = std.mem.Allocator;
|
const Allocator = std.mem.Allocator;
|
||||||
const scan = @import("scan.zig");
|
const scan = @import("scan.zig");
|
||||||
|
|
||||||
|
|
@ -134,7 +135,7 @@ pub const LineOverride = struct {
|
||||||
pub const PresumedLoc = struct { file: []const u8, line: u32 };
|
pub const PresumedLoc = struct { file: []const u8, line: u32 };
|
||||||
|
|
||||||
pub const SourceManager = struct {
|
pub const SourceManager = struct {
|
||||||
arena: std.heap.ArenaAllocator,
|
arena: BumpArena,
|
||||||
files: std.ArrayList(File) = .empty,
|
files: std.ArrayList(File) = .empty,
|
||||||
fs: FileSystem,
|
fs: FileSystem,
|
||||||
/// path -> contents, or null if the path could not be read.
|
/// path -> contents, or null if the path could not be read.
|
||||||
|
|
@ -317,30 +318,46 @@ fn decodeUtf16(a: Allocator, raw: []const u8) !?[]const u8 {
|
||||||
}
|
}
|
||||||
|
|
||||||
fn spliceLines(a: Allocator, raw: []const u8) ![]const u8 {
|
fn spliceLines(a: Allocator, raw: []const u8) ![]const u8 {
|
||||||
if (std.mem.indexOfScalar(u8, raw, '\\') == null) return raw;
|
var i = std.mem.indexOfScalar(u8, raw, '\\') orelse return raw;
|
||||||
var out: std.ArrayList(u8) = .empty;
|
var out: std.ArrayList(u8) = .empty;
|
||||||
try out.ensureTotalCapacity(a, raw.len);
|
try out.ensureTotalCapacity(a, raw.len);
|
||||||
var i: usize = 0;
|
out.appendSliceAssumeCapacity(raw[0..i]);
|
||||||
|
// At a backslash: a splice, or the backslash kept; then the run to the
|
||||||
|
// next backslash, copied whole.
|
||||||
while (i < raw.len) {
|
while (i < raw.len) {
|
||||||
if (raw[i] == '\\') {
|
var j = i + 1;
|
||||||
var j = i + 1;
|
// Clang tolerates whitespace between the backslash and newline.
|
||||||
// Clang tolerates whitespace between the backslash and newline.
|
while (j < raw.len and (raw[j] == ' ' or raw[j] == '\t')) j += 1;
|
||||||
while (j < raw.len and (raw[j] == ' ' or raw[j] == '\t')) j += 1;
|
if (j < raw.len and raw[j] == '\n') {
|
||||||
if (j < raw.len and raw[j] == '\n') {
|
i = j + 1;
|
||||||
i = j + 1;
|
} else if (j + 1 < raw.len and raw[j] == '\r' and raw[j + 1] == '\n') {
|
||||||
continue;
|
i = j + 2;
|
||||||
}
|
} else {
|
||||||
if (j + 1 < raw.len and raw[j] == '\r' and raw[j + 1] == '\n') {
|
out.appendAssumeCapacity('\\');
|
||||||
i = j + 2;
|
i += 1;
|
||||||
continue;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
out.appendAssumeCapacity(raw[i]);
|
const next = std.mem.indexOfScalarPos(u8, raw, i, '\\') orelse raw.len;
|
||||||
i += 1;
|
out.appendSliceAssumeCapacity(raw[i..next]);
|
||||||
|
i = next;
|
||||||
}
|
}
|
||||||
return out.items;
|
return out.items;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
test spliceLines {
|
||||||
|
const cases = [_][2][]const u8{
|
||||||
|
.{ "a\\\nb", "ab" },
|
||||||
|
.{ "a\\ \t\r\nb\\", "ab\\" },
|
||||||
|
.{ "\\x\\\\\ny", "\\x\\y" },
|
||||||
|
.{ "no splice", "no splice" },
|
||||||
|
.{ "#define A 1 \\\n + 2\n", "#define A 1 + 2\n" },
|
||||||
|
};
|
||||||
|
for (cases) |c| {
|
||||||
|
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
|
||||||
|
defer arena.deinit();
|
||||||
|
try std.testing.expectEqualStrings(c[1], try spliceLines(arena.allocator(), c[0]));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
test "line and column lookup" {
|
test "line and column lookup" {
|
||||||
var mfs: MemoryFs = .{};
|
var mfs: MemoryFs = .{};
|
||||||
var sm = SourceManager.init(std.testing.allocator, mfs.fileSystem());
|
var sm = SourceManager.init(std.testing.allocator, mfs.fileSystem());
|
||||||
|
|
|
||||||
|
|
@ -28,6 +28,7 @@
|
||||||
//! and fails its job.
|
//! and fails its job.
|
||||||
|
|
||||||
const std = @import("std");
|
const std = @import("std");
|
||||||
|
const BumpArena = @import("zdxc").BumpArena;
|
||||||
const Io = std.Io;
|
const Io = std.Io;
|
||||||
const Allocator = std.mem.Allocator;
|
const Allocator = std.mem.Allocator;
|
||||||
const FileSystem = @import("zdxc").front.source.FileSystem;
|
const FileSystem = @import("zdxc").front.source.FileSystem;
|
||||||
|
|
@ -238,7 +239,7 @@ const Batch = struct {
|
||||||
/// jobs ahead of the compiles.
|
/// jobs ahead of the compiles.
|
||||||
fn read(b: *Batch) void {
|
fn read(b: *Batch) void {
|
||||||
const gpa = std.heap.smp_allocator;
|
const gpa = std.heap.smp_allocator;
|
||||||
var arena: std.heap.ArenaAllocator = .init(gpa);
|
var arena: BumpArena = .init(gpa);
|
||||||
defer arena.deinit();
|
defer arena.deinit();
|
||||||
for (b.jobs, b.sources, 0..) |args, *s, i| {
|
for (b.jobs, b.sources, 0..) |args, *s, i| {
|
||||||
while (true) {
|
while (true) {
|
||||||
|
|
@ -303,7 +304,7 @@ const Batch = struct {
|
||||||
|
|
||||||
fn work(b: *Batch) void {
|
fn work(b: *Batch) void {
|
||||||
const gpa = std.heap.smp_allocator;
|
const gpa = std.heap.smp_allocator;
|
||||||
var arena: std.heap.ArenaAllocator = .init(gpa);
|
var arena: BumpArena = .init(gpa);
|
||||||
defer arena.deinit();
|
defer arena.deinit();
|
||||||
while (true) {
|
while (true) {
|
||||||
const i = b.next.fetchAdd(1, .monotonic);
|
const i = b.next.fetchAdd(1, .monotonic);
|
||||||
|
|
|
||||||
|
|
@ -4,6 +4,7 @@ pub const diag = @import("diag.zig");
|
||||||
pub const options = @import("options.zig");
|
pub const options = @import("options.zig");
|
||||||
pub const compile = @import("compile.zig");
|
pub const compile = @import("compile.zig");
|
||||||
pub const stats = @import("stats.zig");
|
pub const stats = @import("stats.zig");
|
||||||
|
pub const BumpArena = @import("BumpArena.zig");
|
||||||
pub const Diagnostics = diag.Diagnostics;
|
pub const Diagnostics = diag.Diagnostics;
|
||||||
|
|
||||||
pub const front = struct {
|
pub const front = struct {
|
||||||
|
|
|
||||||
|
|
@ -112,6 +112,37 @@ pub const Db = struct {
|
||||||
pub const Resolved = struct { ret: TypeId, index: u16 = 0, params: []const TypeId = &.{}, ok: bool = false };
|
pub const Resolved = struct { ret: TypeId, index: u16 = 0, params: []const TypeId = &.{}, ok: bool = false };
|
||||||
|
|
||||||
pub fn resolve(db: *const Db, sema: anytype, loc: source.Loc, ns: []const u8, name: []const u8, object: ?TypeId, args: []const ArgInfo, explicit: ?TypeId) !Resolved {
|
pub fn resolve(db: *const Db, sema: anytype, loc: source.Loc, ns: []const u8, name: []const u8, object: ?TypeId, args: []const ArgInfo, explicit: ?TypeId) !Resolved {
|
||||||
|
// The same call (name, object, explicit type, argument types and
|
||||||
|
// lvalues) resolves the same way: matched once per compile.
|
||||||
|
var key_buf: [256]u8 = undefined;
|
||||||
|
var key: std.ArrayList(u8) = .initBuffer(&key_buf);
|
||||||
|
const keyed = memoKey(&key, ns, name, object, args, explicit);
|
||||||
|
if (keyed) if (sema.intrinsic_memo.get(key.items)) |r| return r;
|
||||||
|
const reported = sema.diags.list.items.len;
|
||||||
|
const r = try db.resolveUncached(sema, loc, ns, name, object, args, explicit);
|
||||||
|
// (Not one that reported something: a repeat reports it again.)
|
||||||
|
if (keyed and r.ok and sema.diags.list.items.len == reported) try sema.intrinsic_memo.put(sema.arena, try sema.arena.dupe(u8, key.items), r);
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The memo key of a call; false if it does not fit.
|
||||||
|
fn memoKey(key: *std.ArrayList(u8), ns: []const u8, name: []const u8, object: ?TypeId, args: []const ArgInfo, explicit: ?TypeId) bool {
|
||||||
|
const fixed = ns.len + name.len + 2 + 2 * @sizeOf(TypeId) + args.len * (@sizeOf(TypeId) + 1);
|
||||||
|
if (fixed > key.capacity) return false;
|
||||||
|
key.appendSliceAssumeCapacity(ns);
|
||||||
|
key.appendAssumeCapacity(0);
|
||||||
|
key.appendSliceAssumeCapacity(name);
|
||||||
|
key.appendAssumeCapacity(0);
|
||||||
|
key.appendSliceAssumeCapacity(std.mem.asBytes(&@as(TypeId, object orelse std.math.maxInt(TypeId))));
|
||||||
|
key.appendSliceAssumeCapacity(std.mem.asBytes(&@as(TypeId, explicit orelse std.math.maxInt(TypeId))));
|
||||||
|
for (args) |a| {
|
||||||
|
key.appendSliceAssumeCapacity(std.mem.asBytes(&a.ty));
|
||||||
|
key.appendAssumeCapacity(@intFromBool(a.lvalue));
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn resolveUncached(db: *const Db, sema: anytype, loc: source.Loc, ns: []const u8, name: []const u8, object: ?TypeId, args: []const ArgInfo, explicit: ?TypeId) !Resolved {
|
||||||
const cands = try db.candidates(sema.arena, ns, name);
|
const cands = try db.candidates(sema.arena, ns, name);
|
||||||
if (cands.len == 0) {
|
if (cands.len == 0) {
|
||||||
if (object) |o| {
|
if (object) |o| {
|
||||||
|
|
|
||||||
|
|
@ -219,6 +219,8 @@ pub const Sema = struct {
|
||||||
loop_depth: u32 = 0,
|
loop_depth: u32 = 0,
|
||||||
switch_depth: u32 = 0,
|
switch_depth: u32 = 0,
|
||||||
intrinsic_db: *const intrinsics.Db,
|
intrinsic_db: *const intrinsics.Db,
|
||||||
|
/// Intrinsic calls resolved so far (see Db.resolve).
|
||||||
|
intrinsic_memo: std.StringHashMapUnmanaged(intrinsics.Db.Resolved) = .empty,
|
||||||
enum_scopes: std.AutoHashMapUnmanaged(*types.EnumInfo, *Scope) = .empty,
|
enum_scopes: std.AutoHashMapUnmanaged(*types.EnumInfo, *Scope) = .empty,
|
||||||
/// Where each template was declared (its names resolve from there).
|
/// Where each template was declared (its names resolve from there).
|
||||||
template_scopes: std.AutoHashMapUnmanaged(*const ast.Decl, *Scope) = .empty,
|
template_scopes: std.AutoHashMapUnmanaged(*const ast.Decl, *Scope) = .empty,
|
||||||
|
|
@ -938,13 +940,26 @@ pub const Sema = struct {
|
||||||
}
|
}
|
||||||
|
|
||||||
fn lookup(s: *Sema, name: []const u8) ?Symbol {
|
fn lookup(s: *Sema, name: []const u8) ?Symbol {
|
||||||
|
// (The name hashed once, for every scope out to the global one.)
|
||||||
|
const key: Prehashed = .{ .h = std.hash_map.hashString(name) };
|
||||||
var sc: ?*Scope = s.scope;
|
var sc: ?*Scope = s.scope;
|
||||||
while (sc) |c| : (sc = c.parent) {
|
while (sc) |c| : (sc = c.parent) {
|
||||||
if (c.syms.get(name)) |sym| return sym;
|
if (c.syms.getAdapted(name, key)) |sym| return sym;
|
||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A string hash map key context with the hash already worked out.
|
||||||
|
const Prehashed = struct {
|
||||||
|
h: u64,
|
||||||
|
pub fn hash(k: Prehashed, _: []const u8) u64 {
|
||||||
|
return k.h;
|
||||||
|
}
|
||||||
|
pub fn eql(_: Prehashed, a: []const u8, b: []const u8) bool {
|
||||||
|
return std.mem.eql(u8, a, b);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
/// Resolve a possibly qualified name.
|
/// Resolve a possibly qualified name.
|
||||||
fn lookupName(s: *Sema, n: ast.Name) ?Symbol {
|
fn lookupName(s: *Sema, n: ast.Name) ?Symbol {
|
||||||
return s.lookupNameInst(n) catch null;
|
return s.lookupNameInst(n) catch null;
|
||||||
|
|
|
||||||
|
|
@ -357,10 +357,10 @@ pub const ResourceKind = enum(u8) {
|
||||||
|
|
||||||
/// vk::SampledTexture* by name.
|
/// vk::SampledTexture* by name.
|
||||||
pub const vk_names = [_]struct { []const u8, ResourceKind }{
|
pub const vk_names = [_]struct { []const u8, ResourceKind }{
|
||||||
.{ "SampledTexture1D", .sampled_texture1d }, .{ "SampledTexture1DArray", .sampled_texture1d_array },
|
.{ "SampledTexture1D", .sampled_texture1d }, .{ "SampledTexture1DArray", .sampled_texture1d_array },
|
||||||
.{ "SampledTexture2D", .sampled_texture2d }, .{ "SampledTexture2DArray", .sampled_texture2d_array },
|
.{ "SampledTexture2D", .sampled_texture2d }, .{ "SampledTexture2DArray", .sampled_texture2d_array },
|
||||||
.{ "SampledTexture2DMS", .sampled_texture2dms }, .{ "SampledTexture2DMSArray", .sampled_texture2dms_array },
|
.{ "SampledTexture2DMS", .sampled_texture2dms }, .{ "SampledTexture2DMSArray", .sampled_texture2dms_array },
|
||||||
.{ "SampledTexture3D", .sampled_texture3d }, .{ "SampledTextureCUBE", .sampled_texture_cube },
|
.{ "SampledTexture3D", .sampled_texture3d }, .{ "SampledTextureCUBE", .sampled_texture_cube },
|
||||||
.{ "SampledTextureCUBEArray", .sampled_texture_cube_array },
|
.{ "SampledTextureCUBEArray", .sampled_texture_cube_array },
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
@ -535,7 +535,9 @@ pub const LinAlgMatrix = struct { comp: u32, m: u32, n: u32, use: u32, scope: u3
|
||||||
pub const TypeTable = struct {
|
pub const TypeTable = struct {
|
||||||
gpa: Allocator,
|
gpa: Allocator,
|
||||||
types: std.ArrayList(Type) = .empty,
|
types: std.ArrayList(Type) = .empty,
|
||||||
map: std.AutoHashMapUnmanaged(Key, TypeId) = .empty,
|
map: std.HashMapUnmanaged(Key, TypeId, KeyContext, std.hash_map.default_max_load_percentage) = .empty,
|
||||||
|
/// scalar's results.
|
||||||
|
scalars: [@typeInfo(Scalar).@"enum".field_names.len]TypeId = @splat(std.math.maxInt(TypeId)),
|
||||||
|
|
||||||
pub const error_type: TypeId = 0;
|
pub const error_type: TypeId = 0;
|
||||||
pub const void_type: TypeId = 1;
|
pub const void_type: TypeId = 1;
|
||||||
|
|
@ -543,6 +545,23 @@ pub const TypeTable = struct {
|
||||||
/// Hashable identity of structural types.
|
/// Hashable identity of structural types.
|
||||||
const Key = struct { tag: u8, a: u64, b: u64 };
|
const Key = struct { tag: u8, a: u64, b: u64 };
|
||||||
|
|
||||||
|
/// Hashes a Key's words (it has padding, which the automatic context
|
||||||
|
/// hashes around field by field).
|
||||||
|
const KeyContext = struct {
|
||||||
|
fn mix(x: u64) u64 {
|
||||||
|
var z = x;
|
||||||
|
z = (z ^ (z >> 30)) *% 0xbf58476d1ce4e5b9;
|
||||||
|
z = (z ^ (z >> 27)) *% 0x94d049bb133111eb;
|
||||||
|
return z ^ (z >> 31);
|
||||||
|
}
|
||||||
|
pub fn hash(_: KeyContext, k: Key) u64 {
|
||||||
|
return mix(k.a ^ mix(k.b ^ @as(u64, k.tag) << 56));
|
||||||
|
}
|
||||||
|
pub fn eql(_: KeyContext, x: Key, y: Key) bool {
|
||||||
|
return x.tag == y.tag and x.a == y.a and x.b == y.b;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
pub fn init(gpa: Allocator) !TypeTable {
|
pub fn init(gpa: Allocator) !TypeTable {
|
||||||
var t: TypeTable = .{ .gpa = gpa };
|
var t: TypeTable = .{ .gpa = gpa };
|
||||||
try t.types.append(gpa, .@"error");
|
try t.types.append(gpa, .@"error");
|
||||||
|
|
@ -591,7 +610,9 @@ pub const TypeTable = struct {
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn scalar(t: *TypeTable, s: Scalar) !TypeId {
|
pub fn scalar(t: *TypeTable, s: Scalar) !TypeId {
|
||||||
return t.intern(.{ .scalar = s });
|
const k = @backingInt(s);
|
||||||
|
if (t.scalars[k] == std.math.maxInt(TypeId)) t.scalars[k] = try t.intern(.{ .scalar = s });
|
||||||
|
return t.scalars[k];
|
||||||
}
|
}
|
||||||
|
|
||||||
/// `len == 1` vectors are kept distinct from scalars (float1 != float).
|
/// `len == 1` vectors are kept distinct from scalars (float1 != float).
|
||||||
|
|
|
||||||
|
|
@ -4,6 +4,7 @@
|
||||||
//! (binding = register number, descriptor set = register space).
|
//! (binding = register number, descriptor set = register space).
|
||||||
|
|
||||||
const std = @import("std");
|
const std = @import("std");
|
||||||
|
const BumpArena = @import("../BumpArena.zig");
|
||||||
const Allocator = std.mem.Allocator;
|
const Allocator = std.mem.Allocator;
|
||||||
const ir = @import("../ir/ir.zig");
|
const ir = @import("../ir/ir.zig");
|
||||||
const types = @import("../sema/types.zig");
|
const types = @import("../sema/types.zig");
|
||||||
|
|
@ -142,7 +143,7 @@ pub const TargetEnv = struct {
|
||||||
};
|
};
|
||||||
|
|
||||||
pub fn emit(gpa: Allocator, m: *const ir.Module, diags: *diag.Diagnostics, env: TargetEnv) Error![]u8 {
|
pub fn emit(gpa: Allocator, m: *const ir.Module, diags: *diag.Diagnostics, env: TargetEnv) Error![]u8 {
|
||||||
var arena_state = std.heap.ArenaAllocator.init(gpa);
|
var arena_state = BumpArena.init(gpa);
|
||||||
defer arena_state.deinit();
|
defer arena_state.deinit();
|
||||||
var e: Emitter = .{ .arena = arena_state.allocator(), .b = .init(gpa), .m = m, .t = m.types, .diags = diags, .spv_minor = env.minor, .universal = env.universal, .vk = m.vk };
|
var e: Emitter = .{ .arena = arena_state.allocator(), .b = .init(gpa), .m = m, .t = m.types, .diags = diags, .spv_minor = env.minor, .universal = env.universal, .vk = m.vk };
|
||||||
defer e.b.deinit();
|
defer e.b.deinit();
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue