Compare commits

..

No commits in common. "2526fa65f74014738a5922173667781742f8f350" and "06222920e5d0995454d079495c3d139e406ce3da" have entirely different histories.

8 changed files with 32 additions and 313 deletions

View File

@ -453,9 +453,6 @@ fn run(ctx: *Ctx, arena: std.mem.Allocator) !void {
.root = opts.entry,
.row_major = opts.row_major,
});
// About one resolution per expression: reserve rather
// than grow, which leaves every old buffer in the arena.
try sema.resolutions.ensureTotalCapacity(arena, parser.toks.len);
try sema.checkUnit(tu);
if (!opts.sema and !diags.hasErrors() and profile != null) {
const stage: zdxc.ir.ir.Stage = switch (profile.?.kind) {

View File

@ -665,7 +665,7 @@ fn makeResult(c: compile.Result) !*Result {
try addOutput(r, .remarks, try Blob.utf8(""), null);
std.mem.sortUnstable(Output, r.outputs.items, {}, struct {
fn lt(_: void, x: Output, y: Output) bool {
return @backingInt(x.kind) < @backingInt(y.kind);
return @intFromEnum(x.kind) < @intFromEnum(y.kind);
}
}.lt);
return r;
@ -826,17 +826,9 @@ const Compiler = struct {
}
};
/// Each thread's compile arena, kept between calls. Freeing it per call
/// 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
/// on many threads. What a thread keeps is capped at `retain_limit`.
threadlocal var thread_arena: ?std.heap.ArenaAllocator = null;
const retain_limit = 64 << 20;
fn run(source: *const Buffer, wargs: []const ?[*:0]const WCHAR, include: ?*anyopaque) error{ OutOfMemory, InvalidArgument }!*Result {
if (thread_arena == null) thread_arena = .init(gpa);
const arena = &thread_arena.?;
defer _ = arena.reset(.{ .retain_with_limit = retain_limit });
var arena: std.heap.ArenaAllocator = .init(gpa);
defer arena.deinit();
const a = arena.allocator();
const args = try a.alloc([]const u8, wargs.len);
for (args, wargs) |*d, w| d.* = try fromWide(a, w orelse return error.InvalidArgument);

View File

@ -192,8 +192,6 @@ const Emitter = struct {
blocks: std.ArrayList(std.ArrayList(PInst)) = .empty,
prologue: std.ArrayList(PInst) = .empty,
next_id: u32 = 0,
/// Each instruction's type, by id.
inst_types: std.ArrayList(DType) = .empty,
cur: u32 = 0,
resources: std.ArrayList(Resource) = .empty,
@ -295,7 +293,6 @@ const Emitter = struct {
fn add(e: *Emitter, ty: DType, op: @FieldType(module.Inst, "op")) Error!Value {
const id = e.next_id;
e.next_id += 1;
try e.inst_types.append(e.arena, ty);
switch (op) {
.store, .atomicrmw, .cmpxchg => e.writes += 1,
.call => |c| if (!std.mem.startsWith(u8, e.dm.functions.items[c.callee].name, "dx.op.")) {
@ -310,7 +307,6 @@ const Emitter = struct {
fn addPrologue(e: *Emitter, ty: DType, op: @FieldType(module.Inst, "op")) Error!Value {
const id = e.next_id;
e.next_id += 1;
try e.inst_types.append(e.arena, ty);
try e.prologue.append(e.arena, .{ .inst = .{ .ty = ty, .op = op }, .id = id });
return .{ .inst = id };
}
@ -461,7 +457,6 @@ const Emitter = struct {
e.blocks = .empty;
e.prologue = .empty;
e.next_id = 0;
e.inst_types = .empty;
e.private_globals = .empty;
e.private_typed = .empty;
e.nonuniform = .empty;
@ -619,7 +614,6 @@ const Emitter = struct {
e.blocks = .empty;
e.prologue = .empty;
e.next_id = 0;
e.inst_types = .empty;
e.private_globals = .empty;
e.private_typed = .empty;
e.nonuniform = .empty;
@ -651,7 +645,6 @@ const Emitter = struct {
e.blocks = .empty;
e.prologue = .empty;
e.next_id = 0;
e.inst_types = .empty;
e.private_globals = .empty;
e.private_typed = .empty;
e.nonuniform = .empty;
@ -817,7 +810,6 @@ const Emitter = struct {
e.blocks = .empty;
e.prologue = .empty;
e.next_id = 0;
e.inst_types = .empty;
e.private_globals = .empty;
e.private_typed = .empty;
e.nonuniform = .empty;
@ -1267,7 +1259,6 @@ const Emitter = struct {
return out;
}
};
try f.insts.ensureUnusedCapacity(e.dm.allocator(), n);
const all = [_][]const PInst{e.prologue.items};
for (all) |items| for (items) |pi| try f.insts.append(e.dm.allocator(), try remapInst(e.arena, map, pi.inst, remap));
for (e.blocks.items) |blk| for (blk.items) |pi| try f.insts.append(e.dm.allocator(), try remapInst(e.arena, map, pi.inst, remap));
@ -1600,7 +1591,11 @@ const Emitter = struct {
fn valueType(e: *Emitter, v: Value) Error!DType {
return switch (v) {
.constant => |c| e.dm.constants.items[c].ty,
.inst => |id| e.inst_types.items[id],
.inst => |id| blk: {
for (e.prologue.items) |pi| if (pi.id == id) break :blk pi.inst.ty;
for (e.blocks.items) |b| for (b.items) |pi| if (pi.id == id) break :blk pi.inst.ty;
unreachable;
},
else => e.unsupported("value kind", .{}),
};
}

View File

@ -58,11 +58,6 @@ pub const Parser = struct {
/// Collect every token from `pp` and set up a parser over them.
pub fn fromPreprocessor(arena: Allocator, diags: *Diagnostics, pp: *Preprocessor) !Parser {
var toks: std.ArrayList(Token) = .empty;
// Growing a large list in an arena leaves every old buffer behind:
// reserve about one token per 5 bytes of the files loaded so far.
var loaded: usize = 0;
for (pp.sm.files.items) |f| loaded += f.text.len;
try toks.ensureTotalCapacity(arena, loaded / 5 + 64);
var packs: std.ArrayList(PackPragma) = .empty;
while (true) {
// Preprocessor diagnostics are ordered by the token being produced.
@ -605,22 +600,17 @@ pub const Parser = struct {
fn parseName(p: *Parser) Error!ast.Name {
const loc = p.tok().loc;
// Names are parsed very often and nearly all have one part: collect
// them on the stack and copy them to the arena once.
var parts_buf: [32][]const u8 = undefined;
var args_buf: [32][]const ast.TemplateArg = undefined;
var parts: std.ArrayList([]const u8) = .initBuffer(&parts_buf);
var args: std.ArrayList([]const ast.TemplateArg) = .initBuffer(&args_buf);
var parts: std.ArrayList([]const u8) = .empty;
var args: std.ArrayList([]const ast.TemplateArg) = .empty;
var any_args = false;
p.forced_template = false;
if (p.eat(.colon_colon)) {
parts.appendAssumeCapacity("");
args.appendAssumeCapacity(&.{});
try parts.append(p.arena, "");
try args.append(p.arena, &.{});
}
while (true) {
const id = try p.expectIdent("identifier");
if (parts.items.len == parts_buf.len) return p.fail("name has too many parts", .{});
parts.appendAssumeCapacity(id.text);
try parts.append(p.arena, id.text);
var part_args: []const ast.TemplateArg = &.{};
// `S<T>::member`: arguments followed by `::` belong to this part.
if (p.at(.less) and p.isTemplateName(id.text)) {
@ -631,7 +621,7 @@ pub const Parser = struct {
}
}
}
args.appendAssumeCapacity(part_args);
try args.append(p.arena, part_args);
if (!(p.at(.colon_colon) and p.peek(1).kind == .identifier and !p.peek(1).isIdent("operator"))) break;
_ = p.advance();
// `X<T>::template Y<U>`: the disambiguator.
@ -640,11 +630,7 @@ pub const Parser = struct {
p.forced_template = true;
}
}
return .{
.loc = loc,
.parts = try p.arena.dupe([]const u8, parts.items),
.args = if (any_args) try p.arena.dupe([]const ast.TemplateArg, args.items) else &.{},
};
return .{ .loc = loc, .parts = parts.items, .args = if (any_args) args.items else &.{} };
}
fn parseTemplateArgs(p: *Parser) Error![]const ast.TemplateArg {

View File

@ -20,44 +20,14 @@
//! directory, as on the command line. Each job's output and diagnostics
//! are printed in job order; the exit code is 0 when every job succeeds,
//! else 1 if any job failed on its command line or I/O, else 5.
//!
//! Two more threads read the jobs' input files ahead of the compiles and
//! write their outputs after them, so the compile threads do not wait on
//! opening files (which Windows, with its on-access scanner, serializes).
//! An output that cannot be written is reported after every job's output,
//! and fails its job.
const std = @import("std");
const Io = std.Io;
const Allocator = std.mem.Allocator;
const FileSystem = @import("zdxc").front.source.FileSystem;
/// Compiles one job: `args` is a full command line (argv[0] first). It
/// writes to `stdout` / `stderr` and returns the exit code.
pub const CompileFn = *const fn (io: Io, arena: Allocator, args: []const [:0]const u8, ctx: Context, stdout: *Io.Writer, stderr: *Io.Writer) u8;
/// What a run gives a compile besides its command line.
pub const Context = struct {
/// The input file's text, already read.
source: ?[]const u8 = null,
/// Reads the other files (null: from disk).
fs: ?FileSystem = null,
/// Where to add the files to write (allocated in the compile's arena),
/// instead of writing them.
outputs: ?*Outputs = null,
};
/// A file a job writes.
pub const Output = struct { path: []const u8, bytes: []const u8 };
pub const Outputs = std.ArrayList(Output);
/// The input file a job's command line names, if any.
pub const InputFn = *const fn (arena: Allocator, args: []const [:0]const u8) ?[]const u8;
/// How many jobs the reading thread may get ahead of the compiles.
const read_ahead = 256;
/// The compiles wake the reading thread every this many jobs.
const wake_every = 32;
pub const CompileFn = *const fn (io: Io, arena: Allocator, args: []const [:0]const u8, stdout: *Io.Writer, stderr: *Io.Writer) u8;
const JobFile = struct {
threads: ?u32 = null,
@ -73,7 +43,7 @@ pub fn find(argv: []const [:0]const u8) ?usize {
/// Runs the job file `argv[at]` names; the other arguments apply to every
/// job. Returns the process exit code.
pub fn run(io: Io, arena: Allocator, argv: []const [:0]const u8, at: usize, compile: CompileFn, input: InputFn, stdout: *Io.Writer, stderr: *Io.Writer) !u8 {
pub fn run(io: Io, arena: Allocator, argv: []const [:0]const u8, at: usize, compile: CompileFn, stdout: *Io.Writer, stderr: *Io.Writer) !u8 {
const path = argv[at]["--job=".len..];
const text = Io.Dir.cwd().readFileAlloc(io, path, arena, .limited(1 << 30)) catch |e| {
try stderr.print("zdxc: error: cannot read job file '{s}': {s}\n", .{ path, @errorName(e) });
@ -100,23 +70,8 @@ pub fn run(io: Io, arena: Allocator, argv: []const [:0]const u8, at: usize, comp
j.* = full;
}
var b: Batch = .{
.io = io,
.jobs = jobs,
.results = try arena.alloc(Result, jobs.len),
.sources = try arena.alloc(Source, jobs.len),
.files = .{ .io = io },
.compile = compile,
.input = input,
.stdout = stdout,
.stderr = stderr,
};
var b: Batch = .{ .io = io, .jobs = jobs, .results = try arena.alloc(Result, jobs.len), .compile = compile, .stdout = stdout, .stderr = stderr };
@memset(b.results, .{});
@memset(b.sources, .{});
const reader: ?std.Thread = std.Thread.spawn(.{}, Batch.read, .{&b}) catch null;
b.reading = reader != null;
const writer: ?std.Thread = std.Thread.spawn(.{}, Batch.write, .{&b}) catch null;
b.writing = writer != null;
const cpus: u32 = @intCast(std.Thread.getCpuCount() catch 1);
const nthreads = @max(1, @min(file.threads orelse cpus, jobs.len));
// The calling thread is one of the workers.
@ -128,9 +83,6 @@ pub fn run(io: Io, arena: Allocator, argv: []const [:0]const u8, at: usize, comp
}
b.work();
for (threads[0..spawned]) |t| t.join();
if (reader) |t| t.join();
if (writer) |t| t.join();
try stderr.writeAll(b.write_errors.items);
var failed: usize = 0;
var code: u8 = 0;
@ -147,160 +99,20 @@ const Result = struct {
code: u8 = 0,
out: []u8 = &.{},
err: []u8 = &.{},
/// Files for the writing thread; owned by smp_allocator.
writes: []Output = &.{},
};
/// Files the jobs read (headers, mostly), shared by the whole run: each is
/// opened once, rather than once per job and include directory searched.
/// Files that do not exist are remembered too. The text lives until the
/// process exits.
const FileCache = struct {
io: Io,
mutex: Io.Mutex = .init,
files: std.StringHashMapUnmanaged(?[]const u8) = .empty,
fn fileSystem(c: *FileCache) FileSystem {
return .{ .ctx = c, .readFn = read };
}
fn read(ctx: *anyopaque, _: Allocator, path: []const u8) ?[]const u8 {
const c: *FileCache = @ptrCast(@alignCast(ctx));
const gpa = std.heap.smp_allocator;
{
c.mutex.lockUncancelable(c.io);
defer c.mutex.unlock(c.io);
if (c.files.get(path)) |cached| return cached;
}
// Read outside the lock: other jobs keep using the cache meanwhile.
const text: ?[]const u8 = Io.Dir.cwd().readFileAlloc(c.io, path, gpa, .limited(256 << 20)) catch null;
c.mutex.lockUncancelable(c.io);
defer c.mutex.unlock(c.io);
const key = gpa.dupe(u8, path) catch return text;
const gop = c.files.getOrPut(gpa, key) catch {
gpa.free(key);
return text;
};
if (gop.found_existing) {
gpa.free(key);
if (text) |t| gpa.free(t);
return gop.value_ptr.*;
}
gop.value_ptr.* = text;
return text;
}
};
/// A job's input file, as read by the reading thread.
const Source = struct {
state: std.atomic.Value(State) = .init(.pending),
/// Valid once `state` is `.read`; owned by smp_allocator.
text: []u8 = &.{},
const State = enum(u32) {
pending,
read,
/// No input named, or it could not be read: the compile reads (and
/// reports) it itself.
none,
};
};
const Batch = struct {
io: Io,
jobs: []const []const [:0]const u8,
results: []Result,
sources: []Source,
files: FileCache,
compile: CompileFn,
input: InputFn,
stdout: *Io.Writer,
stderr: *Io.Writer,
/// Whether the reading thread is running (else every source is read by
/// its compile).
reading: bool = false,
/// Whether the writing thread is running (else every compile writes its
/// own outputs).
writing: bool = false,
/// Messages for the outputs the writing thread could not write.
write_errors: std.ArrayList(u8) = .empty,
/// `printed`, for the writing thread to wait on: it writes a job's
/// outputs once the job is printed.
printed_count: std.atomic.Value(u32) = .init(0),
next: std.atomic.Value(usize) = .init(0),
/// Jobs taken by the compiles, for the reading thread to wait on.
started: std.atomic.Value(u32) = .init(0),
/// Guards `results` and the writers; jobs are printed in order.
mutex: Io.Mutex = .init,
printed: usize = 0,
/// Reads every job's input file in job order, at most `read_ahead`
/// jobs ahead of the compiles.
fn read(b: *Batch) void {
const gpa = std.heap.smp_allocator;
var arena: std.heap.ArenaAllocator = .init(gpa);
defer arena.deinit();
for (b.jobs, b.sources, 0..) |args, *s, i| {
while (true) {
const started = b.started.load(.acquire);
if (i < @as(usize, started) + read_ahead) break;
b.io.futexWaitUncancelable(u32, &b.started.raw, started);
}
_ = arena.reset(.retain_capacity);
const text: ?[]u8 = if (b.input(arena.allocator(), args)) |path|
Io.Dir.cwd().readFileAlloc(b.io, path, gpa, .limited(256 << 20)) catch null
else
null;
if (text) |t| s.text = t;
s.state.store(if (text != null) .read else .none, .release);
b.io.futexWake(Source.State, &s.state.raw, std.math.maxInt(u32));
}
}
/// Writes every job's outputs, in job order, as the jobs are printed.
fn write(b: *Batch) void {
const gpa = std.heap.smp_allocator;
for (b.results, 0..) |*r, i| {
while (true) {
const printed = b.printed_count.load(.acquire);
if (i < printed) break;
b.io.futexWaitUncancelable(u32, &b.printed_count.raw, printed);
}
for (r.writes) |o| {
Io.Dir.cwd().writeFile(b.io, .{ .sub_path = o.path, .data = o.bytes }) catch |e| {
b.write_errors.print(gpa, "zdxc: error: cannot write '{s}': {s}\n", .{ o.path, @errorName(e) }) catch {};
r.code = 1;
};
gpa.free(o.path);
gpa.free(o.bytes);
}
gpa.free(r.writes);
r.writes = &.{};
}
}
/// The outputs of a job, copied out of its arena (null if out of
/// memory: then the job fails).
fn keep(outputs: []const Output) ?[]Output {
const gpa = std.heap.smp_allocator;
const kept = gpa.alloc(Output, outputs.len) catch return null;
for (kept, outputs, 0..) |*k, o, n| {
const path = gpa.dupe(u8, o.path) catch null;
const bytes = if (path != null) gpa.dupe(u8, o.bytes) catch null else null;
if (bytes == null) {
if (path) |p| gpa.free(p);
for (kept[0..n]) |d| {
gpa.free(d.path);
gpa.free(d.bytes);
}
gpa.free(kept);
return null;
}
k.* = .{ .path = path.?, .bytes = bytes.? };
}
return kept;
}
fn work(b: *Batch) void {
const gpa = std.heap.smp_allocator;
var arena: std.heap.ArenaAllocator = .init(gpa);
@ -308,43 +120,17 @@ const Batch = struct {
while (true) {
const i = b.next.fetchAdd(1, .monotonic);
if (i >= b.jobs.len) return;
if (b.started.fetchAdd(1, .release) % wake_every == wake_every - 1) b.io.futexWake(u32, &b.started.raw, 1);
_ = arena.reset(.retain_capacity);
const a = arena.allocator();
var out: Io.Writer.Allocating = .init(a);
var err: Io.Writer.Allocating = .init(a);
const s = &b.sources[i];
var source: ?[]const u8 = null;
if (b.reading) {
while (true) switch (s.state.load(.acquire)) {
.pending => b.io.futexWaitUncancelable(Source.State, &s.state.raw, .pending),
.read => {
source = s.text;
break;
},
.none => break,
};
}
var outputs: Outputs = .empty;
var code = b.compile(b.io, a, b.jobs[i], .{
.source = source,
.fs = b.files.fileSystem(),
.outputs = if (b.writing) &outputs else null,
}, &out.writer, &err.writer);
gpa.free(s.text);
s.text = &.{};
const code = b.compile(b.io, a, b.jobs[i], &out.writer, &err.writer);
// The arena is reused for the next job: keep the output.
const writes: []Output = keep(outputs.items) orelse writes: {
err.writer.writeAll("zdxc: error: OutOfMemory\n") catch {};
code = 1;
break :writes &.{};
};
b.finish(i, .{
.done = true,
.code = code,
.out = gpa.dupe(u8, out.written()) catch &.{},
.err = gpa.dupe(u8, err.written()) catch &.{},
.writes = writes,
});
}
}
@ -366,7 +152,5 @@ const Batch = struct {
}
b.stdout.flush() catch {};
b.stderr.flush() catch {};
b.printed_count.store(@intCast(b.printed), .release);
b.io.futexWake(u32, &b.printed_count.raw, 1);
}
};

View File

@ -18,9 +18,9 @@ pub fn main(init: std.process.Init) !u8 {
const args = try init.minimal.args.toSlice(arena);
const code = if (job.find(args)) |at|
try job.run(io, arena, args, at, runCommandLine, inputFile, &stdout_writer.interface, &stderr_writer.interface)
try job.run(io, arena, args, at, runCommandLine, &stdout_writer.interface, &stderr_writer.interface)
else
runCommandLine(io, arena, args, .{}, &stdout_writer.interface, &stderr_writer.interface);
runCommandLine(io, arena, args, &stdout_writer.interface, &stderr_writer.interface);
try stdout_writer.interface.flush();
return code;
}
@ -28,30 +28,19 @@ pub fn main(init: std.process.Init) !u8 {
/// Runs one command line (argv[0] first) and returns its exit code, which
/// follows dxc: 1 for command-line and I/O errors, 5 when the compilation
/// reports errors.
fn runCommandLine(io: Io, arena: std.mem.Allocator, argv: []const [:0]const u8, ctx: job.Context, stdout: *Io.Writer, stderr: *Io.Writer) u8 {
return runOrFail(io, arena, argv, ctx, stdout, stderr) catch |err| {
fn runCommandLine(io: Io, arena: std.mem.Allocator, argv: []const [:0]const u8, stdout: *Io.Writer, stderr: *Io.Writer) u8 {
return runOrFail(io, arena, argv, stdout, stderr) catch |err| {
stderr.print("zdxc: error: {s}\n", .{@errorName(err)}) catch {};
stderr.flush() catch {};
return 1;
};
}
/// The input file a command line (argv[0] first) compiles, if it names one.
fn inputFile(arena: std.mem.Allocator, argv: []const [:0]const u8) ?[]const u8 {
const args = arena.alloc([]const u8, argv.len -| 1) catch return null;
for (args, argv[1..]) |*a, v| a.* = v;
var failure: zdxc.options.Failure = .{};
const parsed = zdxc.options.parse(arena, args, &failure) catch return null;
return if (parsed.inputs.len > 0) parsed.inputs[parsed.inputs.len - 1] else null;
}
fn runOrFail(io: Io, arena: std.mem.Allocator, argv: []const [:0]const u8, ctx: job.Context, stdout: *Io.Writer, stderr: *Io.Writer) !u8 {
fn runOrFail(io: Io, arena: std.mem.Allocator, argv: []const [:0]const u8, stdout: *Io.Writer, stderr: *Io.Writer) !u8 {
const args = try arena.alloc([]const u8, argv.len -| 1);
for (args, argv[1..]) |*a, v| a.* = v;
const r = try zdxc.compile.compile(arena, .{
.args = args,
.source = ctx.source,
.fs = ctx.fs,
.io = io,
.color = Io.File.stderr().supportsAnsiEscapeCodes(io) catch false,
.require_output = true,
@ -59,19 +48,17 @@ fn runOrFail(io: Io, arena: std.mem.Allocator, argv: []const [:0]const u8, ctx:
try stdout.writeAll(r.text);
try stderr.writeAll(r.diagnostics);
try stderr.flush();
if (r.status != .ok) return @backingInt(r.status);
if (r.object) |bytes| try write(io, arena, ctx.outputs, stderr, r.object_name.?, bytes) orelse return 1;
if (r.root_signature) |bytes| try write(io, arena, ctx.outputs, stderr, r.root_signature_name.?, bytes) orelse return 1;
if (r.status != .ok) return @intFromEnum(r.status);
if (r.object) |bytes| try write(io, stderr, r.object_name.?, bytes) orelse return 1;
if (r.root_signature) |bytes| try write(io, stderr, r.root_signature_name.?, bytes) orelse return 1;
if (r.preprocessed) |text| {
if (r.preprocessed_name) |path| try write(io, arena, ctx.outputs, stderr, path, text) orelse return 1 else try stdout.writeAll(text);
if (r.preprocessed_name) |path| try write(io, stderr, path, text) orelse return 1 else try stdout.writeAll(text);
}
return 0;
}
/// Writes an output file (or adds it to `outputs`); null (after an error
/// message) if it cannot.
fn write(io: Io, arena: std.mem.Allocator, outputs: ?*job.Outputs, stderr: *Io.Writer, path: []const u8, bytes: []const u8) !?void {
if (outputs) |o| return try o.append(arena, .{ .path = path, .bytes = bytes });
/// Writes an output file; null (after an error message) if it cannot.
fn write(io: Io, stderr: *Io.Writer, path: []const u8, bytes: []const u8) !?void {
Io.Dir.cwd().writeFile(io, .{ .sub_path = path, .data = bytes }) catch |err| {
try stderr.print("zdxc: error: cannot write '{s}': {s}\n", .{ path, @errorName(err) });
try stderr.flush();

View File

@ -48,28 +48,6 @@ pub const Db = struct {
return db;
}
var shared_db: Db = .{};
/// 0: not built, 1: being built, 2: built.
var shared_state: std.atomic.Value(u8) = .init(0);
/// The Db, built once per process and then shared read-only: it
/// depends only on the generated table, and building it costs thousands
/// of allocations per compile.
pub fn shared() Allocator.Error!*const Db {
while (true) switch (shared_state.load(.acquire)) {
2 => return &shared_db,
0 => if (shared_state.cmpxchgStrong(0, 1, .acquire, .monotonic) == null) {
shared_db = init(std.heap.smp_allocator) catch |e| {
shared_state.store(0, .release);
return e;
};
shared_state.store(2, .release);
return &shared_db;
},
else => std.atomic.spinLoopHint(),
};
}
/// `ns` (e.g. `Texture2DMethods`) declares a method `name`.
pub fn hasMethod(db: *const Db, ns: []const u8, name: []const u8) bool {
var buf: [256]u8 = undefined;

View File

@ -208,7 +208,7 @@ pub const Sema = struct {
current_block: ?*const ast.Decl = null,
loop_depth: u32 = 0,
switch_depth: u32 = 0,
intrinsic_db: *const intrinsics.Db,
intrinsic_db: intrinsics.Db,
enum_scopes: std.AutoHashMapUnmanaged(*types.EnumInfo, *Scope) = .empty,
/// Where each template was declared (its names resolve from there).
template_scopes: std.AutoHashMapUnmanaged(*const ast.Decl, *Scope) = .empty,
@ -232,7 +232,7 @@ pub const Sema = struct {
.opts = opts,
.global = global,
.scope = global,
.intrinsic_db = try intrinsics.Db.shared(),
.intrinsic_db = try intrinsics.Db.init(arena),
};
try s.declareBuiltins();
return s;