Phase 5: atomics through every layer (RFC 0015)
AIR: linear atomic<T> (AtomicScalar), atomic.new/take/load/store/RMW/ cmpxchg (two results)/fence with explicit orderings; feature atomics published. Verifier: ordering tables (E4201), ordinary access (E4202), effects [atomic] / [atomic, atomic.weak], linearity, take while lent (E4101, also for mutex.take). Interpreter: timestamped message machine (src/interp/weak.zig); views travel through spawn/join, channels, mutexes, close and cancel; seq_cst reads the latest message and programs without weak reads make no extra draw (existing records unchanged). aji explore: exhaustive exploration that branches only before visible operations. Litmus: 20/20 tests give exactly the oracle's sets; differential test (1500 random programs) found no unsound outcome. .aji layer 10, Quick Reference atomics, source coverage 67/67, audit report atomic_operations. AIR bundle +5.9 %, QUICK.md +0.5k.
This commit is contained in:
1 parent
ce9ef03bc0
commit
4242132b2a
70 files changed
+2630
-80
No files matched your search
@@ -25,6 +25,8 @@ pub const ArithMode = module.ArithMode;
|
||||
pub const BitOp = module.BitOp;
|
||||
pub const CmpOp = module.CmpOp;
|
||||
pub const CastMode = module.CastMode;
|
||||
pub const Ordering = module.Ordering;
|
||||
pub const RmwOp = module.RmwOp;
|
||||
pub const forEachUse = module.forEachUse;
|
||||
pub const successors = module.successors;
|
||||
pub const allocTargets = module.allocTargets;
|
||||
|
||||
@@ -24,7 +24,7 @@ pub const Feature = struct {
|
||||
pub const registry = [_]Feature{
|
||||
.{ .name = "arc", .depends = &.{ "capabilities", "effects", "heap", "islands", "ownership", "resources" }, .status = .published, .phase = 4 },
|
||||
.{ .name = "arrays", .depends = &.{"ownership"}, .status = .published, .phase = 1 },
|
||||
.{ .name = "atomics", .depends = &.{ "effects", "ownership" }, .status = .reserved, .phase = 5 },
|
||||
.{ .name = "atomics", .depends = &.{ "effects", "ownership" }, .status = .published, .phase = 5 },
|
||||
.{ .name = "borrow_joins", .depends = &.{"ownership"}, .status = .reserved, .phase = null },
|
||||
.{ .name = "cancellation", .depends = &.{ "effects", "ownership", "tasks" }, .status = .published, .phase = 3 },
|
||||
.{ .name = "capabilities", .depends = &.{ "effects", "ownership" }, .status = .published, .phase = 2 },
|
||||
@@ -49,7 +49,7 @@ pub const registry = [_]Feature{
|
||||
};
|
||||
|
||||
/// Features implemented by this toolchain, sorted.
|
||||
pub const supported = [_][]const u8{ "arc", "arrays", "cancellation", "capabilities", "channels", "effects", "heap", "islands", "ownership", "regions", "resources", "sync", "tasks", "unsafe" };
|
||||
pub const supported = [_][]const u8{ "arc", "arrays", "atomics", "cancellation", "capabilities", "channels", "effects", "heap", "islands", "ownership", "regions", "resources", "sync", "tasks", "unsafe" };
|
||||
|
||||
pub const Reason = enum {
|
||||
unknown_feature,
|
||||
|
||||
+67
-5
@@ -99,6 +99,8 @@ pub const Type = union(enum) {
|
||||
frozen: *const Type,
|
||||
arc: *const Type,
|
||||
iref: *const Type,
|
||||
// Feature `atomics` (spec 04 §23, §42): a linear atomic cell.
|
||||
atomic: *const Type,
|
||||
|
||||
pub const Array = struct { elem: Type, len: u64 };
|
||||
|
||||
@@ -107,7 +109,7 @@ pub const Type = union(enum) {
|
||||
return switch (a) {
|
||||
.int => |x| b.int == x,
|
||||
.named => |x| b.named == x,
|
||||
.local, .ref, .mut, .slice, .slice_mut, .own, .own_array, .task, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .iref => |x| x.eql(b.inner().?),
|
||||
.local, .ref, .mut, .slice, .slice_mut, .own, .own_array, .task, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .iref, .atomic => |x| x.eql(b.inner().?),
|
||||
.region, .scope, .shield => true,
|
||||
.array => |x| x.len == b.array.len and x.elem.eql(b.array.elem),
|
||||
.cap => |k| b.cap == k,
|
||||
@@ -120,7 +122,7 @@ pub const Type = union(enum) {
|
||||
/// Element or pointee type of storage, borrow and slice types.
|
||||
pub fn inner(t: Type) ?Type {
|
||||
return switch (t) {
|
||||
.local, .ref, .mut, .slice, .slice_mut, .own, .own_array, .task, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .iref => |x| x.*,
|
||||
.local, .ref, .mut, .slice, .slice_mut, .own, .own_array, .task, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .iref, .atomic => |x| x.*,
|
||||
.array => |a| a.elem,
|
||||
else => null,
|
||||
};
|
||||
@@ -137,7 +139,7 @@ pub const Type = union(enum) {
|
||||
/// Linear values: consumed exactly once (spec 06 §6.2–§6.3).
|
||||
pub fn isLinear(t: Type) bool {
|
||||
return switch (t) {
|
||||
.resource, .own, .own_array, .region, .scope, .task, .shield, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc => true,
|
||||
.resource, .own, .own_array, .region, .scope, .task, .shield, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .atomic => true,
|
||||
else => false,
|
||||
};
|
||||
}
|
||||
@@ -171,7 +173,7 @@ pub const Type = union(enum) {
|
||||
/// Linear resources are neither values nor borrows: they are moved.
|
||||
pub fn isValue(t: Type) bool {
|
||||
return switch (t) {
|
||||
.void, .never, .local, .ref, .mut, .slice, .slice_mut, .resource, .own, .own_array, .region, .scope, .task, .shield, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc => false,
|
||||
.void, .never, .local, .ref, .mut, .slice, .slice_mut, .resource, .own, .own_array, .region, .scope, .task, .shield, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .atomic => false,
|
||||
else => true,
|
||||
};
|
||||
}
|
||||
@@ -239,6 +241,41 @@ pub const BitOp = enum { @"and", @"or", xor, shl, shr };
|
||||
pub const CmpOp = enum { eq, ne, lt, le, gt, ge };
|
||||
pub const CastMode = enum { checked, wrap, widen };
|
||||
|
||||
/// Memory orderings (spec 04 §24). There is no default and no `consume`.
|
||||
pub const Ordering = enum {
|
||||
relaxed,
|
||||
acquire,
|
||||
release,
|
||||
acq_rel,
|
||||
seq_cst,
|
||||
|
||||
pub fn hasAcquire(o: Ordering) bool {
|
||||
return o == .acquire or o == .acq_rel or o == .seq_cst;
|
||||
}
|
||||
|
||||
pub fn hasRelease(o: Ordering) bool {
|
||||
return o == .release or o == .acq_rel or o == .seq_cst;
|
||||
}
|
||||
};
|
||||
|
||||
/// Atomic read-modify-write operations (spec 04 §24.2).
|
||||
pub const RmwOp = enum {
|
||||
xchg,
|
||||
add_wrap,
|
||||
sub_wrap,
|
||||
@"and",
|
||||
@"or",
|
||||
xor,
|
||||
|
||||
pub fn text(op: RmwOp) []const u8 {
|
||||
return switch (op) {
|
||||
.add_wrap => "add.wrap",
|
||||
.sub_wrap => "sub.wrap",
|
||||
inline else => |o| @tagName(o),
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
pub const Op = union(enum) {
|
||||
// Feature `ownership` (spec 07a).
|
||||
local_alloc: Type,
|
||||
@@ -341,6 +378,15 @@ pub const Op = union(enum) {
|
||||
arc_root: ValueId,
|
||||
arc_borrow: struct { owner: ValueId, iref: ValueId },
|
||||
iref_eq: struct { a: ValueId, b: ValueId },
|
||||
// Feature `atomics` (spec 04 §42).
|
||||
atomic_new: ValueId,
|
||||
atomic_take: ValueId,
|
||||
atomic_load: struct { cell: ValueId, ord: Ordering },
|
||||
atomic_store: struct { cell: ValueId, value: ValueId, ord: Ordering },
|
||||
atomic_rmw: struct { op: RmwOp, cell: ValueId, value: ValueId, ord: Ordering },
|
||||
/// Two results: `Inst.result` (old value) and `Inst.result2` (exchanged).
|
||||
atomic_cmpxchg: struct { cell: ValueId, expected: ValueId, desired: ValueId, success: Ordering, failure: Ordering },
|
||||
atomic_fence: Ordering,
|
||||
ret: ?ValueId,
|
||||
trap,
|
||||
|
||||
@@ -375,7 +421,7 @@ pub const Op = union(enum) {
|
||||
|
||||
pub const Inst = struct {
|
||||
result: ?ValueId,
|
||||
/// Second result of `slice.split`.
|
||||
/// Second result of `slice.split` and `atomic.cmpxchg`.
|
||||
result2: ?ValueId = null,
|
||||
op: Op,
|
||||
span: Span,
|
||||
@@ -525,6 +571,22 @@ pub fn forEachUse(op: Op, ctx: anytype, comptime f: fn (@TypeOf(ctx), ValueId) v
|
||||
f(ctx, x.a);
|
||||
f(ctx, x.b);
|
||||
},
|
||||
.atomic_new, .atomic_take => |v| f(ctx, v),
|
||||
.atomic_load => |x| f(ctx, x.cell),
|
||||
.atomic_store => |x| {
|
||||
f(ctx, x.cell);
|
||||
f(ctx, x.value);
|
||||
},
|
||||
.atomic_rmw => |x| {
|
||||
f(ctx, x.cell);
|
||||
f(ctx, x.value);
|
||||
},
|
||||
.atomic_cmpxchg => |x| {
|
||||
f(ctx, x.cell);
|
||||
f(ctx, x.expected);
|
||||
f(ctx, x.desired);
|
||||
},
|
||||
.atomic_fence => {},
|
||||
.task_join_cancel => |x| f(ctx, x.task),
|
||||
.channel_make => |x| {
|
||||
f(ctx, x.cap);
|
||||
|
||||
+80
-3
@@ -560,7 +560,7 @@ const Parser = struct {
|
||||
boxed.* = inner;
|
||||
return if (eql(t.text, "own")) .{ .own = boxed } else .{ .own_array = boxed };
|
||||
}
|
||||
const Wrapper = enum { task, sender, receiver, mutex, guard, island, frozen, arc, iref };
|
||||
const Wrapper = enum { task, sender, receiver, mutex, guard, island, frozen, arc, iref, atomic };
|
||||
if (std.meta.stringToEnum(Wrapper, t.text)) |which| {
|
||||
try p.requireFeature(switch (which) {
|
||||
.task => "tasks",
|
||||
@@ -568,6 +568,7 @@ const Parser = struct {
|
||||
.mutex, .guard => "sync",
|
||||
.island, .frozen, .iref => "islands",
|
||||
.arc => "arc",
|
||||
.atomic => "atomics",
|
||||
}, t.span, t.text);
|
||||
_ = try p.expect(.lt, "`<`");
|
||||
// Element rules (spec 04 §38.1) are checked by the type stage.
|
||||
@@ -585,6 +586,7 @@ const Parser = struct {
|
||||
.frozen => .{ .frozen = boxed },
|
||||
.arc => .{ .arc = boxed },
|
||||
.iref => .{ .iref = boxed },
|
||||
.atomic => .{ .atomic = boxed },
|
||||
};
|
||||
}
|
||||
if (eql(t.text, "cap")) {
|
||||
@@ -1015,6 +1017,10 @@ const Parser = struct {
|
||||
}
|
||||
if (try p.parseAllocOp(op_tok)) |aop| break :op aop;
|
||||
if (try p.parseGraphOp(op_tok)) |gop| break :op gop;
|
||||
if (std.mem.startsWith(u8, op_tok.text, "atomic.")) {
|
||||
if (try p.parseAtomicOp(op_tok)) |aop| break :op aop;
|
||||
return p.unknownOpcode(op_tok);
|
||||
}
|
||||
if (try p.parseTaskOp(op_tok)) |top| break :op top;
|
||||
if (try p.parseCoordinationOp(op_tok)) |cop| break :op cop;
|
||||
if (eql(op_tok.text, "intrinsic")) {
|
||||
@@ -1046,6 +1052,7 @@ const Parser = struct {
|
||||
.own_take, .task_scope_begin, .task_spawn, .task_cancelled => true,
|
||||
.task_shield_begin, .channel_dup, .mutex_make, .mutex_take, .mutex_borrow => true,
|
||||
.island_root, .island_borrow, .island_freeze, .frozen_root, .frozen_borrow, .arc_from_frozen, .arc_clone, .arc_root, .arc_borrow, .iref_eq => true,
|
||||
.atomic_new, .atomic_take, .atomic_load, .atomic_rmw, .atomic_cmpxchg => true,
|
||||
.@"const", .copy, .arith, .bit, .cmp, .cast, .struct_make, .struct_get, .enum_make => true,
|
||||
.local_alloc, .local_load, .borrow_ref, .borrow_mut, .borrow_field, .load => true,
|
||||
.array_splat, .borrow_index, .slice_make, .slice_len, .slice_sub, .slice_split => true,
|
||||
@@ -1057,8 +1064,9 @@ const Parser = struct {
|
||||
} else if (produces_value) {
|
||||
return p.fail(op_tok, "result binding `%name =`");
|
||||
}
|
||||
if ((op == .slice_split) != (result2_tok != null)) {
|
||||
return p.fail(result_tok orelse op_tok, if (op == .slice_split) "two results `%left, %right =`" else "a single result");
|
||||
const two_results = op == .slice_split or op == .atomic_cmpxchg;
|
||||
if (two_results != (result2_tok != null)) {
|
||||
return p.fail(result_tok orelse op_tok, if (op == .slice_split) "two results `%left, %right =`" else if (op == .atomic_cmpxchg) "two results `%old, %exchanged =`" else "a single result");
|
||||
}
|
||||
const def: air.ValueInfo.Def = .{ .inst = .{ .block = block, .index = index } };
|
||||
const result = if (result_tok) |rt| try p.defineValue(rt, def) else null;
|
||||
@@ -1254,6 +1262,75 @@ const Parser = struct {
|
||||
}
|
||||
}
|
||||
|
||||
/// Instructions of the feature `atomics` (spec 04 §42). The orderings are
|
||||
/// part of the opcode; which are valid for an operation is the type
|
||||
/// stage's (`E4201`). Returns null for an opcode that is not one of them.
|
||||
fn parseAtomicOp(p: *Parser, op_tok: Token) Error!?air.Op {
|
||||
var buf: [5][]const u8 = undefined;
|
||||
var n: usize = 0;
|
||||
var it = std.mem.splitScalar(u8, op_tok.text, '.');
|
||||
while (it.next()) |part| {
|
||||
if (n == buf.len) return null;
|
||||
buf[n] = part;
|
||||
n += 1;
|
||||
}
|
||||
const parts = buf[0..n];
|
||||
const ord = struct {
|
||||
fn of(t: []const u8) ?air.Ordering {
|
||||
return std.meta.stringToEnum(air.Ordering, t);
|
||||
}
|
||||
}.of;
|
||||
const Name = enum { new, take, load, store, xchg, add, sub, @"and", @"or", xor, cmpxchg, fence };
|
||||
const name = std.meta.stringToEnum(Name, parts[1]) orelse return null;
|
||||
try p.requireFeature("atomics", op_tok.span, op_tok.text);
|
||||
switch (name) {
|
||||
.new, .take => {
|
||||
if (n != 2) return null;
|
||||
const v = try p.useValue();
|
||||
return if (name == .new) .{ .atomic_new = v } else .{ .atomic_take = v };
|
||||
},
|
||||
.load => {
|
||||
if (n != 3) return null;
|
||||
const o = ord(parts[2]) orelse return null;
|
||||
return .{ .atomic_load = .{ .cell = try p.useValue(), .ord = o } };
|
||||
},
|
||||
.store => {
|
||||
if (n != 3) return null;
|
||||
const o = ord(parts[2]) orelse return null;
|
||||
const c, const v = try p.twoOperands();
|
||||
return .{ .atomic_store = .{ .cell = c, .value = v, .ord = o } };
|
||||
},
|
||||
.xchg, .@"and", .@"or", .xor, .add, .sub => {
|
||||
const wraps = name == .add or name == .sub;
|
||||
if (n != (if (wraps) @as(usize, 4) else 3)) return null;
|
||||
if (wraps and !std.mem.eql(u8, parts[2], "wrap")) return null;
|
||||
const o = ord(parts[n - 1]) orelse return null;
|
||||
const op: air.RmwOp = switch (name) {
|
||||
.xchg => .xchg,
|
||||
.add => .add_wrap,
|
||||
.sub => .sub_wrap,
|
||||
.@"and" => .@"and",
|
||||
.@"or" => .@"or",
|
||||
else => .xor,
|
||||
};
|
||||
const c, const v = try p.twoOperands();
|
||||
return .{ .atomic_rmw = .{ .op = op, .cell = c, .value = v, .ord = o } };
|
||||
},
|
||||
.cmpxchg => {
|
||||
if (n != 4) return null;
|
||||
const sc = ord(parts[2]) orelse return null;
|
||||
const fl = ord(parts[3]) orelse return null;
|
||||
const c, const e = try p.twoOperands();
|
||||
_ = try p.expect(.comma, "`,`");
|
||||
return .{ .atomic_cmpxchg = .{ .cell = c, .expected = e, .desired = try p.useValue(), .success = sc, .failure = fl } };
|
||||
},
|
||||
.fence => {
|
||||
if (n != 3) return null;
|
||||
return .{ .atomic_fence = ord(parts[2]) orelse return null };
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Instructions of the features `heap` and `regions` (spec 03 §19–§20).
|
||||
fn parseAllocOp(p: *Parser, op_tok: Token) Error!?air.Op {
|
||||
const Name = enum { @"own.new", @"own.array", @"own.take", @"own.free", @"region.create", @"region.new", @"region.array", @"region.reset", @"region.destroy" };
|
||||
|
||||
+28
-1
@@ -122,7 +122,7 @@ pub fn printType(m: air.Module, t: air.Type, w: *Writer) Writer.Error!void {
|
||||
},
|
||||
.region => try w.writeAll("region"),
|
||||
.scope => try w.writeAll("scope"),
|
||||
.task, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .iref => |inner| {
|
||||
.task, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .iref, .atomic => |inner| {
|
||||
try w.print("{s}<", .{@tagName(t)});
|
||||
try printType(m, inner.*, w);
|
||||
try w.writeByte('>');
|
||||
@@ -422,6 +422,33 @@ fn printOp(m: air.Module, f: air.Function, op: air.Op, w: *Writer) Writer.Error!
|
||||
.frozen_borrow => |x| try two(f, w, "frozen.borrow", x.owner, x.iref),
|
||||
.arc_borrow => |x| try two(f, w, "arc.borrow", x.owner, x.iref),
|
||||
.iref_eq => |x| try two(f, w, "iref.eq", x.a, x.b),
|
||||
.atomic_new => |v| try one(f, w, "atomic.new", v),
|
||||
.atomic_take => |v| try one(f, w, "atomic.take", v),
|
||||
.atomic_load => |x| {
|
||||
try w.print("atomic.load.{s} ", .{@tagName(x.ord)});
|
||||
try value(f, x.cell, w);
|
||||
},
|
||||
.atomic_store => |x| {
|
||||
try w.print("atomic.store.{s} ", .{@tagName(x.ord)});
|
||||
try value(f, x.cell, w);
|
||||
try w.writeAll(", ");
|
||||
try value(f, x.value, w);
|
||||
},
|
||||
.atomic_rmw => |x| {
|
||||
try w.print("atomic.{s}.{s} ", .{ x.op.text(), @tagName(x.ord) });
|
||||
try value(f, x.cell, w);
|
||||
try w.writeAll(", ");
|
||||
try value(f, x.value, w);
|
||||
},
|
||||
.atomic_cmpxchg => |x| {
|
||||
try w.print("atomic.cmpxchg.{s}.{s} ", .{ @tagName(x.success), @tagName(x.failure) });
|
||||
try value(f, x.cell, w);
|
||||
try w.writeAll(", ");
|
||||
try value(f, x.expected, w);
|
||||
try w.writeAll(", ");
|
||||
try value(f, x.desired, w);
|
||||
},
|
||||
.atomic_fence => |o| try w.print("atomic.fence.{s}", .{@tagName(o)}),
|
||||
.cap_narrow => |x| {
|
||||
try w.print("cap.narrow.{s} ", .{x.form});
|
||||
try value(f, x.cap, w);
|
||||
|
||||
+139
-15
@@ -73,13 +73,15 @@ pub const Ty = union(enum) {
|
||||
frozen: *const Ty,
|
||||
arc: *const Ty,
|
||||
iref: *const Ty,
|
||||
/// `atomic<T>` (spec 04 §23; layer 10): a linear cell.
|
||||
atomic: *const Ty,
|
||||
|
||||
pub const Arr = struct { elem: Ty, len: u64 };
|
||||
|
||||
/// Linear: consumed exactly once, by `move` (spec 15 §5).
|
||||
fn isLinear(t: Ty) bool {
|
||||
return switch (t) {
|
||||
.own, .own_array, .region, .resource, .task, .sender, .receiver, .scope, .mutex, .guard, .shield, .island, .frozen, .arc => true,
|
||||
.own, .own_array, .region, .resource, .task, .sender, .receiver, .scope, .mutex, .guard, .shield, .island, .frozen, .arc, .atomic => true,
|
||||
else => false,
|
||||
};
|
||||
}
|
||||
@@ -90,7 +92,7 @@ pub const Ty = union(enum) {
|
||||
.int => |x| std.mem.eql(u8, x, b.int),
|
||||
.named => |i| i == b.named,
|
||||
.array => |x| x.len == b.array.len and x.elem.eql(b.array.elem),
|
||||
.ref, .mut, .slice, .slice_mut, .own, .own_array, .task, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .iref => |x| x.eql(inner(b).?),
|
||||
.ref, .mut, .slice, .slice_mut, .own, .own_array, .task, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .iref, .atomic => |x| x.eql(inner(b).?),
|
||||
.cap => |k| std.mem.eql(u8, k, b.cap),
|
||||
.builtin => |e| e == b.builtin,
|
||||
.resource => |r| r == b.resource,
|
||||
@@ -100,7 +102,7 @@ pub const Ty = union(enum) {
|
||||
|
||||
fn inner(t: Ty) ?Ty {
|
||||
return switch (t) {
|
||||
.ref, .mut, .slice, .slice_mut, .own, .own_array, .task, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .iref => |x| x.*,
|
||||
.ref, .mut, .slice, .slice_mut, .own, .own_array, .task, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .iref, .atomic => |x| x.*,
|
||||
.array => |a| a.elem,
|
||||
else => null,
|
||||
};
|
||||
@@ -117,6 +119,11 @@ pub const Ty = union(enum) {
|
||||
|
||||
const int_types = [_][]const u8{ "u8", "u16", "u32", "u64", "u128", "usize", "i8", "i16", "i32", "i64", "i128", "isize" };
|
||||
|
||||
/// AtomicScalar (spec 04 §23): `bool` and integers of at most 64 bits.
|
||||
fn atomicScalar(t: Ty) bool {
|
||||
return t == .bool or (t == .int and intBits(t.int) <= 64);
|
||||
}
|
||||
|
||||
fn isIntName(n: []const u8) bool {
|
||||
for (int_types) |t| if (std.mem.eql(u8, t, n)) return true;
|
||||
return false;
|
||||
@@ -327,7 +334,7 @@ const Lowerer = struct {
|
||||
.never => "never",
|
||||
.named => |i| l.typeNames[i],
|
||||
.array => |a| std.fmt.allocPrint(l.arena, "array<{s}, {d}>", .{ l.tyText(a.elem), a.len }) catch "array",
|
||||
.ref, .mut, .slice, .slice_mut, .own, .own_array, .task, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .iref => |x| std.fmt.allocPrint(l.arena, "{s}<{s}>", .{ @tagName(t), l.tyText(x.*) }) catch "borrow",
|
||||
.ref, .mut, .slice, .slice_mut, .own, .own_array, .task, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .iref, .atomic => |x| std.fmt.allocPrint(l.arena, "{s}<{s}>", .{ @tagName(t), l.tyText(x.*) }) catch "borrow",
|
||||
.scope => "scope",
|
||||
.shield => "shield",
|
||||
.region => "region",
|
||||
@@ -449,6 +456,9 @@ const Lowerer = struct {
|
||||
.{ "cancellation", &.{ "task.shield", "task.check_cancel", "task.join.cancel" } },
|
||||
.{ "islands", &.{ "island.", "island<", "frozen.", "frozen<", "iref.", "iref<" } },
|
||||
.{ "arc", &.{ "arc.", "arc<" } },
|
||||
// Instructions only: the effect names `atomic` and `atomic.weak`
|
||||
// in a function header are not uses of the feature.
|
||||
.{ "atomics", &.{ "= atomic.", "atomic.store.", "atomic.fence.", "atomic<" } },
|
||||
};
|
||||
for (rules) |r| {
|
||||
const used = for (texts.items) |t| {
|
||||
@@ -519,7 +529,7 @@ const Lowerer = struct {
|
||||
},
|
||||
.array => |a| return l.arrayOf(try l.memberType(a.elem.*), a.len),
|
||||
.wrapped => |w| {
|
||||
const Wr = enum { ref, mut, slice, slice_mut, own, own_array, task, sender, receiver, mutex, island, frozen, arc, iref };
|
||||
const Wr = enum { ref, mut, slice, slice_mut, own, own_array, task, sender, receiver, mutex, island, frozen, arc, iref, atomic };
|
||||
const which = std.meta.stringToEnum(Wr, w.wrapper) orelse return l.notYet(t.span, "this type (later layers)");
|
||||
const in = try l.typeOf(w.inner.*);
|
||||
return switch (which) {
|
||||
@@ -537,6 +547,7 @@ const Lowerer = struct {
|
||||
.frozen => l.wrap(.frozen, in),
|
||||
.arc => l.wrap(.arc, in),
|
||||
.iref => l.wrap(.iref, in),
|
||||
.atomic => if (atomicScalar(in)) l.wrap(.atomic, in) else l.fail("E7005", t.span, "atomic<T> needs bool or an integer of at most 64 bits", &.{.{ .name = "found", .value = l.tyText(in) }}),
|
||||
};
|
||||
},
|
||||
.cap => |k| {
|
||||
@@ -856,7 +867,10 @@ const Lowerer = struct {
|
||||
fn stmt(l: *Lowerer, s: ast.Stmt) Error!void {
|
||||
switch (s.kind) {
|
||||
.let => |x| {
|
||||
if (x.names.len == 2) return l.splitLet(s, x.names, x.e);
|
||||
if (x.names.len == 2) {
|
||||
if (pathOf(x.e.kind.call.callee.*)) |p| if (std.mem.eql(u8, p, "atomic.compare_exchange")) return l.compareExchangeLet(s, x.names, x.e);
|
||||
return l.splitLet(s, x.names, x.e);
|
||||
}
|
||||
if (x.e.kind == .borrow) return l.fail("E7006", x.e.span, "bind a borrow with `ref name = place;` or `mut name = place;`", &.{});
|
||||
if (x.e.kind == .bytes) {
|
||||
const st = try l.materializeBytes(x.e.kind.bytes, x.e.span);
|
||||
@@ -1239,6 +1253,8 @@ const Lowerer = struct {
|
||||
const r = try l.expr(x.*, null);
|
||||
const in = r.ty.inner() orelse return l.fail("E7005", e.span, "`*` reads through a borrow", &.{.{ .name = "found", .value = l.tyText(r.ty) }});
|
||||
if (r.ty == .slice or r.ty == .slice_mut or in == .array) return l.fail("E7006", e.span, "read slice and array elements with `s[i]`, not `*`", &.{});
|
||||
// The verifier's code (spec 15 §1 rule 2, spec 04 §28).
|
||||
if (in == .atomic) return l.fail("E4202", e.span, "an atomic cell is read only by atomic operations: use `atomic.load(r, ordering)`", &.{});
|
||||
return l.def("v", in, try l.fmt("load %{s}", .{r.name}), e.span);
|
||||
},
|
||||
.index => |x| {
|
||||
@@ -1421,6 +1437,7 @@ const Lowerer = struct {
|
||||
return .{ .name = "", .ty = .void };
|
||||
}
|
||||
if (try l.concurrencyCall(e, p, args)) |v| return v;
|
||||
if (std.mem.startsWith(u8, p, "atomic.")) return l.atomicCall(e, p, args);
|
||||
if (authority.intrinsicIndex(p)) |ix| {
|
||||
const x = authority.intrinsics[ix];
|
||||
var temps: std.ArrayList([]const u8) = .empty;
|
||||
@@ -1725,6 +1742,14 @@ const Lowerer = struct {
|
||||
const eq = std.mem.eql;
|
||||
if ((eq(u8, p, "own.take") or eq(u8, p, "task.join")) and args.len == 1) return if (l.peekType(args[0])) |t| t.inner() else null;
|
||||
if (eq(u8, p, "task.cancelled")) return .bool;
|
||||
if (std.mem.startsWith(u8, p, "atomic.") and args.len >= 1) {
|
||||
if (eq(u8, p, "atomic.new")) return if (l.peekType(args[0])) |t| (l.wrap(.atomic, t) catch null) else null;
|
||||
if (eq(u8, p, "atomic.take")) return if (l.peekType(args[0])) |t| t.inner() else null;
|
||||
if (eq(u8, p, "atomic.store") or eq(u8, p, "atomic.fence") or eq(u8, p, "atomic.compare_exchange")) return null;
|
||||
// A `ref a` argument, or a `ref<atomic<T>>` binding: the cell's T.
|
||||
const cell: ?Ty = if (args[0].kind == .borrow) l.peekType(args[0].kind.borrow.place.*) else if (l.peekType(args[0])) |t| t.inner() else null;
|
||||
return if (cell) |c| (if (c == .atomic) c.inner() else null) else null;
|
||||
}
|
||||
if ((eq(u8, p, "island.root") or eq(u8, p, "frozen.root") or eq(u8, p, "arc.root")) and args.len == 1)
|
||||
return if (l.peekType(args[0])) |t| (if (t.inner()) |o| (if (o.inner()) |root| l.wrap(.iref, root) catch null else null) else null) else null;
|
||||
if (eq(u8, p, "island.freeze") and args.len == 1) return if (l.peekType(args[0])) |t| (if (t == .island) l.wrap(.frozen, t.inner().?) catch null else null) else null;
|
||||
@@ -1900,6 +1925,8 @@ const Lowerer = struct {
|
||||
.region => if (mutable) try l.wrap(.mut, .region) else try l.wrap(.ref, .region),
|
||||
.resource, .mutex, .sender, .receiver, .task, .island => if (mutable) try l.wrap(.mut, b.ty) else try l.wrap(.ref, b.ty),
|
||||
.frozen, .arc => if (mutable) return l.fail("E7005", place.span, "frozen graphs and arcs are immutable: borrow them with `ref`", &.{.{ .name = "name", .value = n }}) else try l.wrap(.ref, b.ty),
|
||||
// Atomic operations go through a shared borrow (spec 04 §23).
|
||||
.atomic => if (mutable) return l.fail("E7005", place.span, "an atomic cell is borrowed with `ref`: every atomic operation goes through a shared borrow", &.{.{ .name = "name", .value = n }}) else try l.wrap(.ref, b.ty),
|
||||
else => null,
|
||||
};
|
||||
const t = bt orelse return l.fail("E7006", place.span, "this value is not addressable here; borrow a variable, a field or an element", &.{.{ .name = "name", .value = n }});
|
||||
@@ -2164,6 +2191,101 @@ const Lowerer = struct {
|
||||
|
||||
// ------------------------------------------------------------ tasks and channels (layer 7)
|
||||
|
||||
// ------------------------------------------------------------ atomics (spec 15 §12, spec 04 §42)
|
||||
|
||||
/// An ordering, written as a bare word (spec 15 §12).
|
||||
fn ordering(l: *Lowerer, a: ast.Expr) Error![]const u8 {
|
||||
const words = [_][]const u8{ "relaxed", "acquire", "release", "acq_rel", "seq_cst" };
|
||||
if (a.kind == .name) for (words) |w| if (std.mem.eql(u8, a.kind.name, w)) return w;
|
||||
return l.fail("E7006", a.span, "an ordering is one of the words relaxed, acquire, release, acq_rel, seq_cst, written in place", &.{});
|
||||
}
|
||||
|
||||
/// The cell operand of an atomic operation: a `ref<atomic<T>>` binding or
|
||||
/// parameter, or `ref a` of an atomic, borrowed for the operation.
|
||||
fn cellOperand(l: *Lowerer, a: ast.Expr, temps: *std.ArrayList([]const u8)) Error!Value {
|
||||
if (a.kind == .borrow) {
|
||||
const br = a.kind.borrow;
|
||||
if (br.mutable) return l.fail("E7005", a.span, "atomic operations take `ref` of the cell, never `mut`", &.{});
|
||||
const b = try l.bindingOf(br.place.*, "an atomic cell");
|
||||
if (b.ty != .atomic) return l.fail("E7005", a.span, "an atomic operation takes `ref` of an `atomic<T>`", &.{.{ .name = "found", .value = l.tyText(b.ty) }});
|
||||
const r = try l.def(br.place.kind.name, try l.wrap(.ref, b.ty), try l.fmt("borrow.ref %{s}", .{b.value}), a.span);
|
||||
try temps.append(l.arena, r.name);
|
||||
return r;
|
||||
}
|
||||
const b = try l.bindingOf(a, "an atomic cell");
|
||||
if (b.ty == .atomic) return l.fail("E7005", a.span, "pass the cell as `ref a` (or a `ref` binding of it): atomic operations go through a shared borrow", &.{.{ .name = "suggestion", .value = try l.fmt("ref {s}", .{a.kind.name}) }});
|
||||
if (b.ty == .ref and b.ty.inner().? == .atomic) return .{ .name = b.value, .ty = b.ty };
|
||||
return l.fail("E7005", a.span, "an atomic operation takes a `ref<atomic<T>>`", &.{.{ .name = "found", .value = l.tyText(b.ty) }});
|
||||
}
|
||||
|
||||
fn atomicCall(l: *Lowerer, e: ast.Expr, p: []const u8, args: []const ast.Expr) Error!Value {
|
||||
const eq = std.mem.eql;
|
||||
if (eq(u8, p, "atomic.new")) {
|
||||
if (args.len != 1) return l.fail("E7005", e.span, "`atomic.new` takes the initial value", &.{});
|
||||
const v = try l.expr(args[0], null);
|
||||
if (!atomicScalar(v.ty)) return l.fail("E7005", args[0].span, "atomic<T> needs bool or an integer of at most 64 bits", &.{.{ .name = "found", .value = l.tyText(v.ty) }});
|
||||
return l.def("atomic", try l.wrap(.atomic, v.ty), try l.fmt("atomic.new %{s}", .{v.name}), e.span);
|
||||
}
|
||||
if (eq(u8, p, "atomic.take")) {
|
||||
if (args.len != 1) return l.fail("E7005", e.span, "`atomic.take` takes one cell", &.{});
|
||||
const c = try l.consuming(args[0], null);
|
||||
if (c.ty != .atomic) return l.fail("E7005", args[0].span, "`atomic.take` takes an `atomic<T>`", &.{.{ .name = "found", .value = l.tyText(c.ty) }});
|
||||
return l.def("v", c.ty.inner().?, try l.fmt("atomic.take %{s}", .{c.name}), e.span);
|
||||
}
|
||||
if (eq(u8, p, "atomic.fence")) {
|
||||
if (args.len != 1) return l.fail("E7005", e.span, "`atomic.fence` takes one ordering", &.{});
|
||||
try l.emit(try l.fmt("atomic.fence.{s}", .{try l.ordering(args[0])}), e.span);
|
||||
return .{ .name = "", .ty = .void };
|
||||
}
|
||||
if (eq(u8, p, "atomic.compare_exchange"))
|
||||
return l.fail("E7006", e.span, "`atomic.compare_exchange` has two results: `let (old, exchanged) = atomic.compare_exchange(c, expected, desired, success, failure);`", &.{});
|
||||
var temps: std.ArrayList([]const u8) = .empty;
|
||||
const want: usize = if (eq(u8, p, "atomic.load")) 2 else 3;
|
||||
if (args.len != want) return l.fail("E7005", e.span, "wrong number of operands", &.{ .{ .name = "operation", .value = p }, .{ .name = "expected", .value = try l.fmt("{d}", .{want}) } });
|
||||
const c = try l.cellOperand(args[0], &temps);
|
||||
const t = c.ty.inner().?.inner().?;
|
||||
const ord = try l.ordering(args[want - 1]);
|
||||
if (eq(u8, p, "atomic.load")) {
|
||||
const v = try l.def("v", t, try l.fmt("atomic.load.{s} %{s}", .{ ord, c.name }), e.span);
|
||||
try l.endNow(temps.items, e.span);
|
||||
return v;
|
||||
}
|
||||
const operand = try l.expr(args[1], t);
|
||||
try l.checkTy(args[1].span, operand.ty, t);
|
||||
if (eq(u8, p, "atomic.store")) {
|
||||
try l.emit(try l.fmt("atomic.store.{s} %{s}, %{s}", .{ ord, c.name, operand.name }), e.span);
|
||||
try l.endNow(temps.items, e.span);
|
||||
return .{ .name = "", .ty = .void };
|
||||
}
|
||||
const op: []const u8 = if (eq(u8, p, "atomic.swap")) "xchg" else p["atomic.".len..];
|
||||
if ((eq(u8, op, "add.wrap") or eq(u8, op, "sub.wrap")) and t != .int) return l.fail("E7005", args[1].span, "`atomic.add.wrap` and `atomic.sub.wrap` need an integer cell", &.{.{ .name = "found", .value = l.tyText(t) }});
|
||||
const v = try l.def("old", t, try l.fmt("atomic.{s}.{s} %{s}, %{s}", .{ op, ord, c.name, operand.name }), e.span);
|
||||
try l.endNow(temps.items, e.span);
|
||||
return v;
|
||||
}
|
||||
|
||||
/// `let (old, exchanged) = atomic.compare_exchange(c, expected, desired,
|
||||
/// success, failure);` (spec 15 §12): the second multi-result binding.
|
||||
fn compareExchangeLet(l: *Lowerer, s: ast.Stmt, names: []const []const u8, e: ast.Expr) Error!void {
|
||||
const args = e.kind.call.args;
|
||||
if (args.len != 5) return l.fail("E7005", e.span, "`atomic.compare_exchange` takes a cell, the expected and the desired value, and two orderings", &.{});
|
||||
var temps: std.ArrayList([]const u8) = .empty;
|
||||
const c = try l.cellOperand(args[0], &temps);
|
||||
const t = c.ty.inner().?.inner().?;
|
||||
const expected = try l.expr(args[1], t);
|
||||
try l.checkTy(args[1].span, expected.ty, t);
|
||||
const desired = try l.expr(args[2], t);
|
||||
try l.checkTy(args[2].span, desired.ty, t);
|
||||
const succ = try l.ordering(args[3]);
|
||||
const failure = try l.ordering(args[4]);
|
||||
const old = try l.freshName(names[0]);
|
||||
const ok = try l.freshName(names[1]);
|
||||
try l.emit(try l.fmt("%{s}, %{s} = atomic.cmpxchg.{s}.{s} %{s}, %{s}, %{s}", .{ old, ok, succ, failure, c.name, expected.name, desired.name }), s.span);
|
||||
try l.endNow(temps.items, s.span);
|
||||
try l.bindings.append(l.arena, .{ .name = names[0], .mutable = false, .value = old, .ty = t, .kind = .ssa });
|
||||
try l.bindings.append(l.arena, .{ .name = names[1], .mutable = false, .value = ok, .ty = .bool, .kind = .ssa });
|
||||
}
|
||||
|
||||
fn bindingOf(l: *Lowerer, a: ast.Expr, what: []const u8) Error!*Binding {
|
||||
if (a.kind != .name) return l.fail("E7005", a.span, try l.fmt("{s} is expected here, by name", .{what}), &.{});
|
||||
return l.lookup(a.kind.name) orelse l.unknown(a.span, a.kind.name);
|
||||
@@ -2926,15 +3048,17 @@ fn elemOf(t: Ty) ?Ty {
|
||||
/// `cap.narrow.budget`; null for anything else.
|
||||
fn pathOf(e: ast.Expr) ?[]const u8 {
|
||||
const known = [_][]const u8{
|
||||
"slice.copy", "own.new", "own.array", "own.take", "own.free",
|
||||
"region.create", "region.new", "region.array", "region.reset", "region.destroy",
|
||||
"cap.narrow.budget", "cap.narrow.prefix", "task.spawn", "task.join", "task.cancel",
|
||||
"task.cancelled", "channel.make", "channel.dup", "channel.send", "channel.recv",
|
||||
"channel.close_sender", "channel.close_receiver", "mutex.make", "mutex.take", "task.check_cancel",
|
||||
"task.join_cancel", "island.create", "island.alloc", "island.root", "island.at",
|
||||
"island.freeze", "island.destroy", "frozen.root", "frozen.at", "frozen.release",
|
||||
"arc.from_frozen", "arc.new", "arc.clone", "arc.release", "arc.root",
|
||||
"arc.at",
|
||||
"slice.copy", "own.new", "own.array", "own.take", "own.free",
|
||||
"region.create", "region.new", "region.array", "region.reset", "region.destroy",
|
||||
"cap.narrow.budget", "cap.narrow.prefix", "task.spawn", "task.join", "task.cancel",
|
||||
"task.cancelled", "channel.make", "channel.dup", "channel.send", "channel.recv",
|
||||
"channel.close_sender", "channel.close_receiver", "mutex.make", "mutex.take", "task.check_cancel",
|
||||
"task.join_cancel", "island.create", "island.alloc", "island.root", "island.at",
|
||||
"island.freeze", "island.destroy", "frozen.root", "frozen.at", "frozen.release",
|
||||
"arc.from_frozen", "arc.new", "arc.clone", "arc.release", "arc.root",
|
||||
"arc.at", "atomic.new", "atomic.take", "atomic.load", "atomic.store",
|
||||
"atomic.swap", "atomic.add.wrap", "atomic.sub.wrap", "atomic.and", "atomic.or",
|
||||
"atomic.xor", "atomic.compare_exchange", "atomic.fence",
|
||||
};
|
||||
var buf: [64]u8 = undefined;
|
||||
const text = dotted(e, &buf) orelse return null;
|
||||
|
||||
@@ -17,6 +17,8 @@ pub const MemoryStats = machine.MemoryStats;
|
||||
|
||||
/// For `tests/extended/memory.zig`: the loop shapes of the memory invariant
|
||||
/// test and the function that measures one.
|
||||
pub const Explore = machine.Explore;
|
||||
|
||||
pub const memory_test = struct {
|
||||
pub const loop_shapes = machine.loop_shapes;
|
||||
pub const memoryOf = machine.memoryOf;
|
||||
@@ -25,4 +27,5 @@ pub const memory_test = struct {
|
||||
|
||||
test {
|
||||
_ = machine;
|
||||
_ = @import("interp/weak.zig");
|
||||
}
|
||||
+312
-34
@@ -27,6 +27,7 @@ const diag = @import("../diag.zig");
|
||||
const world_mod = @import("world.zig");
|
||||
const host_mod = @import("host.zig");
|
||||
const budget = @import("../verifier/budget.zig");
|
||||
const weak = @import("weak.zig");
|
||||
|
||||
pub const WorldOptions = world_mod.Options;
|
||||
|
||||
@@ -72,10 +73,17 @@ pub const Value = union(enum) {
|
||||
graph: *Graph,
|
||||
/// `iref<T>`: graph identity and slot; opaque to programs.
|
||||
iref: struct { id: u64, slot: u32 },
|
||||
/// `atomic<T>`: index into the machine's atomic cells (spec 04 §42).
|
||||
atomic: u32,
|
||||
|
||||
/// The guarded value is a separate cell, so a place borrowed through a
|
||||
/// guard points at an ordinary cell.
|
||||
pub const MutexCell = struct { locked: bool, cell: *Cell };
|
||||
pub const MutexCell = struct {
|
||||
locked: bool,
|
||||
cell: *Cell,
|
||||
/// The view of the last unlock (spec 04 §20.3: unlock → next lock).
|
||||
view: weak.View = .{},
|
||||
};
|
||||
|
||||
/// A graph: object cells addressed by slot, an identity never reused in
|
||||
/// the execution, the authority it charges and the bytes it holds.
|
||||
@@ -197,6 +205,9 @@ pub const Options = struct {
|
||||
quantum: u64 = 1000,
|
||||
task_limit: u64 = 1024,
|
||||
schedule_seed: ?u64 = null,
|
||||
/// Exhaustive exploration: choices come from `Explore` instead of the
|
||||
/// schedule generator (spec 04 §20.5).
|
||||
explore: ?*Explore = null,
|
||||
};
|
||||
|
||||
/// Observable output of a run in the deterministic profile.
|
||||
@@ -262,6 +273,8 @@ pub fn run(arena: std.mem.Allocator, module: air.Module, entry: []const u8, opti
|
||||
|
||||
m.exec_heap.every_step = options.collect_every_step;
|
||||
m.arc_events = options.arc_events;
|
||||
m.explore = options.explore;
|
||||
m.mem.weak_reads = hasWeakReads(module);
|
||||
if (options.collect_threshold) |t| {
|
||||
m.exec_heap.floor = t;
|
||||
m.exec_heap.threshold = t;
|
||||
@@ -282,6 +295,31 @@ pub fn run(arena: std.mem.Allocator, module: air.Module, entry: []const u8, opti
|
||||
return result;
|
||||
}
|
||||
|
||||
/// Operations whose order between tasks can change an outcome: atomic
|
||||
/// memory operations and the synchronization of channels, mutexes and
|
||||
/// cancellation. `task.spawn` and `task.join` commute with them.
|
||||
fn isVisibleOp(op: air.Op) bool {
|
||||
return switch (op) {
|
||||
.atomic_load, .atomic_store, .atomic_rmw, .atomic_cmpxchg, .atomic_fence => true,
|
||||
.channel_send, .channel_recv, .channel_close_sender, .channel_close_receiver, .select => true,
|
||||
.mutex_lock, .mutex_unlock => true,
|
||||
.task_cancel, .task_cancelled, .task_check_cancel, .task_join_cancel => true,
|
||||
else => false,
|
||||
};
|
||||
}
|
||||
|
||||
/// Whether a read may read an older message: a non-`seq_cst` load or
|
||||
/// compare-exchange failure (spec 04 §42). Without one, cells keep only their
|
||||
/// latest message.
|
||||
fn hasWeakReads(module: air.Module) bool {
|
||||
for (module.functions) |f| for (f.blocks) |b| for (b.insts) |inst| switch (inst.op) {
|
||||
.atomic_load => |x| if (x.ord != .seq_cst) return true,
|
||||
.atomic_cmpxchg => |x| if (x.failure != .seq_cst) return true,
|
||||
else => {},
|
||||
};
|
||||
return false;
|
||||
}
|
||||
|
||||
/// Copies values into another heap, preserving sharing: a cell, a mutex or
|
||||
/// a payload reached twice is copied once.
|
||||
const Copier = struct {
|
||||
@@ -303,7 +341,7 @@ const Copier = struct {
|
||||
.mutex => |mc| .{ .mutex = try c.mutex(mc) },
|
||||
.guard => |mc| .{ .guard = try c.mutex(mc) },
|
||||
.graph => |g| .{ .graph = try c.graph(g) },
|
||||
.int, .boolean, .void, .cap, .resource, .region, .scope, .task, .builtin, .shield, .sender, .receiver, .iref => v,
|
||||
.int, .boolean, .void, .cap, .resource, .region, .scope, .task, .builtin, .shield, .sender, .receiver, .iref, .atomic => v,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -332,7 +370,7 @@ const Copier = struct {
|
||||
if (c.mutexes.get(old)) |n| return n;
|
||||
const n = try c.to.create(Value.MutexCell);
|
||||
try c.mutexes.put(c.tmp, old, n);
|
||||
n.* = .{ .locked = old.locked, .cell = try c.cell(old.cell) };
|
||||
n.* = .{ .locked = old.locked, .cell = try c.cell(old.cell), .view = try old.view.copy(c.to) };
|
||||
return n;
|
||||
}
|
||||
|
||||
@@ -403,13 +441,18 @@ pub const Wait = union(enum) {
|
||||
|
||||
/// A rendezvous offer: a task waiting to send or receive on a capacity-0
|
||||
/// channel, in arm `arm` of its instruction (0 outside `select`).
|
||||
const Offer = struct { task: u32, arm: u32, value: Value = .void };
|
||||
const Offer = struct { task: u32, arm: u32, value: Value = .void, view: weak.View = .{} };
|
||||
|
||||
/// A channel (spec 04 §38.3).
|
||||
const Channel = struct {
|
||||
capacity: u64,
|
||||
buf: std.ArrayList(Value) = .empty,
|
||||
/// The sender's view of each buffered value (spec 04 §20.3: send → the
|
||||
/// receive that obtains the value). Parallel to `buf`.
|
||||
views: std.ArrayList(weak.View) = .empty,
|
||||
head: usize = 0,
|
||||
/// Joined views of the senders' closes (close → the `closed` outcome).
|
||||
close_view: weak.View = .{},
|
||||
senders: u64 = 1,
|
||||
receiver: enum { open, closing, closed } = .open,
|
||||
authority: u32,
|
||||
@@ -445,7 +488,21 @@ const Task = struct {
|
||||
/// Shield depth (spec 04 §37.3).
|
||||
shield: u32 = 0,
|
||||
/// Set by a peer that completed a rendezvous against this waiting task.
|
||||
delivered: ?struct { arm: u32, value: Value } = null,
|
||||
delivered: ?struct { arm: u32, value: Value, view: weak.View = .{} } = null,
|
||||
/// Weak-memory views (spec 04 §42).
|
||||
views: weak.TaskViews = .{},
|
||||
/// Joined views of the cancellers (cancel → the `cancelled` outcome).
|
||||
cancel_view: weak.View = .{},
|
||||
/// Exploration: the scheduler already chose this task to perform the
|
||||
/// atomic operation it is at.
|
||||
chosen: bool = false,
|
||||
};
|
||||
|
||||
/// Exhaustive exploration (spec 04 §20.5): replays a prefix of choices,
|
||||
/// then takes choice 0, and records the number of options at every choice.
|
||||
pub const Explore = struct {
|
||||
prefix: []const u32 = &.{},
|
||||
widths: std.ArrayList(u32) = .empty,
|
||||
};
|
||||
|
||||
/// Execution heap: collected between instructions (see the file comment).
|
||||
@@ -490,6 +547,9 @@ const Machine = struct {
|
||||
drew: bool = false,
|
||||
/// Instructions executed so far.
|
||||
steps: u64 = 0,
|
||||
/// Atomic cells and the `seq_cst` view (spec 04 §42).
|
||||
mem: weak.Memory = .{},
|
||||
explore: ?*Explore = null,
|
||||
|
||||
// ------------------------------------------------------------ tasks and the scheduler (spec 04 §36)
|
||||
|
||||
@@ -511,6 +571,16 @@ const Machine = struct {
|
||||
const b = f.blocks[frame.block];
|
||||
const inst = b.insts[frame.inst];
|
||||
const here: Location = .{ .function = f.name, .block = b.name, .inst = frame.inst };
|
||||
// Exploration branches only before visible operations: what a
|
||||
// task does between two of them is local to it and commutes with
|
||||
// every other task (spec 04 §20.5). The task parks there; the
|
||||
// scheduler chooses once every runnable task is parked.
|
||||
if (m.explore != null and isVisibleOp(inst.op) and !t.chosen) {
|
||||
t.chosen = true;
|
||||
if (try m.schedule()) |o| return o;
|
||||
continue;
|
||||
}
|
||||
t.chosen = false;
|
||||
// Fuel is consumed when an instruction begins (spec 11 §7.1); a
|
||||
// blocked instruction paid when it first began (spec 04 §36.3).
|
||||
if (!t.fuel_paid) {
|
||||
@@ -588,20 +658,40 @@ const Machine = struct {
|
||||
for (m.tasks.items) |*t| {
|
||||
for (t.frames.items) |*fr| fr.vals = try c.items(fr.vals);
|
||||
t.result = try c.value(t.result);
|
||||
if (t.delivered) |*d| d.value = try c.value(d.value);
|
||||
if (t.delivered) |*d| {
|
||||
d.value = try c.value(d.value);
|
||||
d.view = try d.view.copy(c.to);
|
||||
}
|
||||
t.views = try t.views.copy(c.to);
|
||||
t.cancel_view = try t.cancel_view.copy(c.to);
|
||||
}
|
||||
for (m.channels.items) |*ch| {
|
||||
var buf: std.ArrayList(Value) = .empty;
|
||||
try buf.ensureTotalCapacity(c.to, ch.buf.items.len - ch.head);
|
||||
for (ch.buf.items[ch.head..]) |v| buf.appendAssumeCapacity(try c.value(v));
|
||||
var views: std.ArrayList(weak.View) = .empty;
|
||||
try views.ensureTotalCapacity(c.to, ch.views.items.len - ch.head);
|
||||
for (ch.views.items[ch.head..]) |v| views.appendAssumeCapacity(try v.copy(c.to));
|
||||
ch.buf = buf;
|
||||
ch.views = views;
|
||||
ch.head = 0;
|
||||
ch.close_view = try ch.close_view.copy(c.to);
|
||||
var offers: std.ArrayList(Offer) = .empty;
|
||||
try offers.ensureTotalCapacity(c.to, ch.send_offers.items.len);
|
||||
for (ch.send_offers.items) |o| offers.appendAssumeCapacity(.{ .task = o.task, .arm = o.arm, .value = try c.value(o.value) });
|
||||
for (ch.send_offers.items) |o| offers.appendAssumeCapacity(.{ .task = o.task, .arm = o.arm, .value = try c.value(o.value), .view = try o.view.copy(c.to) });
|
||||
ch.send_offers = offers;
|
||||
if (ch.recv_offer) |*o| o.value = try c.value(o.value);
|
||||
if (ch.recv_offer) |*o| {
|
||||
o.value = try c.value(o.value);
|
||||
o.view = try o.view.copy(c.to);
|
||||
}
|
||||
}
|
||||
// Atomic messages no live task can read any more are dropped.
|
||||
const floor = try tmp.allocator().alloc(u64, m.mem.cells.items.len);
|
||||
@memset(floor, std.math.maxInt(u64));
|
||||
for (m.tasks.items) |t| if (t.state != .done) for (floor, 0..) |*fl, i| {
|
||||
fl.* = @min(fl.*, t.views.cur.get(@intCast(i)));
|
||||
};
|
||||
try m.mem.compact(c.to, floor);
|
||||
var owners: std.AutoHashMapUnmanaged(*Value.Cell, OwnInfo) = .empty;
|
||||
try owners.ensureTotalCapacity(c.to, m.owners.count());
|
||||
var it = m.owners.iterator();
|
||||
@@ -660,12 +750,35 @@ const Machine = struct {
|
||||
m.current = runnable.items[0]; // no choice to make: no draw
|
||||
return null;
|
||||
}
|
||||
const x = m.sched.next();
|
||||
m.choices += 1;
|
||||
m.current = runnable.items[x % runnable.items.len];
|
||||
// Exploration: tasks with local work run first, without a choice.
|
||||
if (m.explore != null) for (runnable.items) |id| if (!m.tasks.items[id].chosen) {
|
||||
m.current = id;
|
||||
return null;
|
||||
};
|
||||
m.current = runnable.items[try m.choose(runnable.items.len)];
|
||||
return null;
|
||||
}
|
||||
|
||||
/// Exhaustive exploration does not branch after `task.spawn` and a
|
||||
/// completed `task.join`: they commute with every operation of every
|
||||
/// other task, so branching there would only repeat outcomes. Ordinary
|
||||
/// runs keep them as scheduling points (spec 04 §36.1).
|
||||
fn yieldUnlessExploring(m: *Machine) Step {
|
||||
return if (m.explore != null) .next else .yield;
|
||||
}
|
||||
|
||||
/// One choice among `n > 1` options (spec 04 §36.2): a draw from the
|
||||
/// schedule generator, or the next choice of an exhaustive exploration.
|
||||
fn choose(m: *Machine, n: usize) !usize {
|
||||
m.choices += 1;
|
||||
if (m.explore) |e| {
|
||||
const i = e.widths.items.len;
|
||||
try e.widths.append(m.arena, @intCast(n));
|
||||
return if (i < e.prefix.len) e.prefix[i] else 0;
|
||||
}
|
||||
return m.sched.next() % n;
|
||||
}
|
||||
|
||||
const Step = union(enum) {
|
||||
next,
|
||||
jump: u32,
|
||||
@@ -769,25 +882,33 @@ const Machine = struct {
|
||||
m.live_tasks += 1;
|
||||
m.spawned = true;
|
||||
const id: u32 = @intCast(m.tasks.items.len);
|
||||
try m.tasks.append(m.arena, .{});
|
||||
// spawn → the child's first event (spec 04 §20.3).
|
||||
const parent = m.tasks.items[m.current].views.cur;
|
||||
try m.tasks.append(m.arena, .{ .views = .{ .cur = parent, .acq = parent } });
|
||||
try m.pushFrame(id, x.callee, try m.gather(vals, x.args));
|
||||
vals[inst.result.?] = .{ .task = id };
|
||||
return .yield;
|
||||
return m.yieldUnlessExploring();
|
||||
},
|
||||
.task_join => |v| {
|
||||
const id = vals[v].task;
|
||||
const t = m.tasks.items[id];
|
||||
if (t.state != .done) return .{ .wait = .{ .join = id } };
|
||||
m.live_tasks -= 1;
|
||||
// The child's last event → join (spec 04 §20.3).
|
||||
try m.tasks.items[m.current].views.acquire(t.views.cur, m.heap());
|
||||
if (inst.result) |r| vals[r] = t.result;
|
||||
return .yield;
|
||||
return m.yieldUnlessExploring();
|
||||
},
|
||||
.task_cancel => |v| {
|
||||
m.tasks.items[vals[v].task].cancel = true;
|
||||
const target = &m.tasks.items[vals[v].task];
|
||||
target.cancel = true;
|
||||
target.cancel_view = try target.cancel_view.join(m.tasks.items[m.current].views.cur, m.heap());
|
||||
return .yield;
|
||||
},
|
||||
.task_cancelled => {
|
||||
vals[inst.result.?] = .{ .boolean = m.tasks.items[m.current].cancel };
|
||||
const cancelled = m.tasks.items[m.current].cancel;
|
||||
if (cancelled) try m.observeCancel();
|
||||
vals[inst.result.?] = .{ .boolean = cancelled };
|
||||
return .yield;
|
||||
},
|
||||
.task_check_cancel, .task_join_cancel, .task_shield_begin, .task_shield_end => return m.execCancellation(f, vals, inst),
|
||||
@@ -795,6 +916,7 @@ const Machine = struct {
|
||||
.mutex_make, .mutex_take, .mutex_lock, .mutex_borrow, .mutex_unlock => return m.execMutex(f, vals, inst),
|
||||
.own_new, .own_array, .own_take, .own_free, .region_create, .region_new, .region_array, .region_reset, .region_destroy => return m.execAlloc(f, vals, {}, inst),
|
||||
.island_create, .island_alloc, .island_root, .island_borrow, .island_freeze, .island_destroy, .frozen_root, .frozen_borrow, .frozen_release, .arc_from_frozen, .arc_new, .arc_clone, .arc_release, .arc_root, .arc_borrow, .iref_eq => return m.execGraph(f, vals, inst),
|
||||
.atomic_new, .atomic_take, .atomic_load, .atomic_store, .atomic_rmw, .atomic_cmpxchg, .atomic_fence => return m.execAtomic(vals, inst),
|
||||
.intrinsic => |x| return m.intrinsic(f, vals, inst, x),
|
||||
.ret => |v| return .{ .ret = if (v) |x| vals[x] else .void },
|
||||
.trap => return .{ .trap = .explicit },
|
||||
@@ -869,33 +991,52 @@ const Machine = struct {
|
||||
}
|
||||
|
||||
/// Completes the peer of a rendezvous: it resumes on arm `arm`.
|
||||
fn deliver(m: *Machine, o: Offer, value: Value) void {
|
||||
fn deliver(m: *Machine, o: Offer, value: Value, view: weak.View) void {
|
||||
m.removeOffers(o.task);
|
||||
const t = &m.tasks.items[o.task];
|
||||
t.delivered = .{ .arm = o.arm, .value = value };
|
||||
t.delivered = .{ .arm = o.arm, .value = value, .view = view };
|
||||
if (t.state == .waiting) t.state = .runnable;
|
||||
}
|
||||
|
||||
/// Performs an `ok`-ready send.
|
||||
/// The sender's view travels with the value (spec 04 §20.3).
|
||||
fn doSend(m: *Machine, id: u32, v: Value) !void {
|
||||
const c = &m.channels.items[id];
|
||||
if (c.capacity > 0) return c.buf.append(m.heap(), try m.deepCopy(v));
|
||||
const view = m.tasks.items[m.current].views.cur;
|
||||
if (c.capacity > 0) {
|
||||
try c.views.append(m.heap(), view);
|
||||
return c.buf.append(m.heap(), try m.deepCopy(v));
|
||||
}
|
||||
const o = c.recv_offer.?;
|
||||
m.deliver(o, try m.deepCopy(v));
|
||||
m.deliver(o, try m.deepCopy(v), view);
|
||||
}
|
||||
|
||||
/// Performs an `ok`-ready receive.
|
||||
fn doRecv(m: *Machine, id: u32) Value {
|
||||
fn doRecv(m: *Machine, id: u32) !Value {
|
||||
const c = &m.channels.items[id];
|
||||
const views = &m.tasks.items[m.current].views;
|
||||
if (c.buffered() > 0) {
|
||||
c.head += 1;
|
||||
try views.acquire(c.views.items[c.head - 1], m.heap());
|
||||
return c.buf.items[c.head - 1];
|
||||
}
|
||||
const o = c.send_offers.orderedRemove(0);
|
||||
m.deliver(o, .void);
|
||||
m.deliver(o, .void, .{});
|
||||
try views.acquire(o.view, m.heap());
|
||||
return o.value;
|
||||
}
|
||||
|
||||
/// The `cancelled` outcome synchronizes with the cancels (spec 04 §20.3).
|
||||
fn observeCancel(m: *Machine) !void {
|
||||
const t = &m.tasks.items[m.current];
|
||||
try t.views.acquire(t.cancel_view, m.heap());
|
||||
}
|
||||
|
||||
/// The `closed` outcome of a receive synchronizes with the closes.
|
||||
fn observeClose(m: *Machine, id: u32) !void {
|
||||
try m.tasks.items[m.current].views.acquire(m.channels.items[id].close_view, m.heap());
|
||||
}
|
||||
|
||||
/// Returns the channel's bytes once it is `CLOSED` with no sender.
|
||||
fn maybeRelease(m: *Machine, id: u32) void {
|
||||
const c = &m.channels.items[id];
|
||||
@@ -911,15 +1052,21 @@ const Machine = struct {
|
||||
fn execCancellation(m: *Machine, f: air.Function, vals: []Value, inst: air.Inst) !Step {
|
||||
const t = &m.tasks.items[m.current];
|
||||
switch (inst.op) {
|
||||
.task_check_cancel => |x| return .{ .jump_yield = if (cancelObservable(t)) x.cancelled else x.ok },
|
||||
.task_check_cancel => |x| {
|
||||
if (!cancelObservable(t)) return .{ .jump_yield = x.ok };
|
||||
try m.observeCancel();
|
||||
return .{ .jump_yield = x.cancelled };
|
||||
},
|
||||
.task_join_cancel => |x| {
|
||||
const child = vals[x.task].task;
|
||||
if (m.tasks.items[child].state == .done) {
|
||||
m.live_tasks -= 1;
|
||||
try t.views.acquire(m.tasks.items[child].views.cur, m.heap());
|
||||
setParams(f, vals, x.ok, &.{m.tasks.items[child].result});
|
||||
return .{ .jump_yield = x.ok };
|
||||
}
|
||||
if (cancelObservable(t)) {
|
||||
try m.observeCancel();
|
||||
setParams(f, vals, x.cancelled, &.{vals[x.task]});
|
||||
return .{ .jump_yield = x.cancelled };
|
||||
}
|
||||
@@ -958,7 +1105,9 @@ const Machine = struct {
|
||||
},
|
||||
.channel_close_sender => |v| {
|
||||
const id = vals[v].sender;
|
||||
m.channels.items[id].senders -= 1;
|
||||
const ch = &m.channels.items[id];
|
||||
ch.close_view = try ch.close_view.join(m.tasks.items[self].views.cur, m.heap());
|
||||
ch.senders -= 1;
|
||||
m.maybeRelease(id);
|
||||
return .yield;
|
||||
},
|
||||
@@ -994,11 +1143,12 @@ const Machine = struct {
|
||||
},
|
||||
.none => {
|
||||
if (cancelObservable(t)) {
|
||||
try m.observeCancel();
|
||||
setParams(f, vals, x.cancelled, &.{v});
|
||||
return .{ .jump_yield = x.cancelled };
|
||||
}
|
||||
const c = &m.channels.items[id];
|
||||
if (c.capacity == 0) try c.send_offers.append(m.heap(), .{ .task = self, .arm = 0, .value = v });
|
||||
if (c.capacity == 0) try c.send_offers.append(m.heap(), .{ .task = self, .arm = 0, .value = v, .view = t.views.cur });
|
||||
return .{ .wait = .op };
|
||||
},
|
||||
}
|
||||
@@ -1007,6 +1157,7 @@ const Machine = struct {
|
||||
const t = &m.tasks.items[self];
|
||||
if (t.delivered) |d| {
|
||||
t.delivered = null;
|
||||
try t.views.acquire(d.view, m.heap());
|
||||
setParams(f, vals, x.ok, &.{d.value});
|
||||
return .{ .jump_yield = x.ok };
|
||||
}
|
||||
@@ -1014,12 +1165,18 @@ const Machine = struct {
|
||||
const id = endpointOf(vals[x.receiver]);
|
||||
switch (m.recvState(id)) {
|
||||
.ok => {
|
||||
setParams(f, vals, x.ok, &.{m.doRecv(id)});
|
||||
setParams(f, vals, x.ok, &.{try m.doRecv(id)});
|
||||
return .{ .jump_yield = x.ok };
|
||||
},
|
||||
.closed => return .{ .jump_yield = x.closed },
|
||||
.closed => {
|
||||
try m.observeClose(id);
|
||||
return .{ .jump_yield = x.closed };
|
||||
},
|
||||
.none => {
|
||||
if (cancelObservable(t)) return .{ .jump_yield = x.cancelled };
|
||||
if (cancelObservable(t)) {
|
||||
try m.observeCancel();
|
||||
return .{ .jump_yield = x.cancelled };
|
||||
}
|
||||
const c = &m.channels.items[id];
|
||||
if (c.capacity == 0) c.recv_offer = .{ .task = self, .arm = 0 };
|
||||
return .{ .wait = .op };
|
||||
@@ -1041,6 +1198,7 @@ const Machine = struct {
|
||||
for (vs, v_vals) |v, *o| o.* = vals[v];
|
||||
if (t.delivered) |d| {
|
||||
t.delivered = null;
|
||||
try t.views.acquire(d.view, m.heap());
|
||||
return m.selectOk(f, vals, x, d.arm, d.value, vs, v_vals);
|
||||
}
|
||||
m.removeOffers(self);
|
||||
@@ -1052,6 +1210,7 @@ const Machine = struct {
|
||||
}
|
||||
if (ready_arms.items.len == 0) {
|
||||
if (cancelObservable(t)) {
|
||||
try m.observeCancel();
|
||||
setParams(f, vals, x.cancelled, v_vals);
|
||||
return .{ .jump_yield = x.cancelled };
|
||||
}
|
||||
@@ -1059,21 +1218,21 @@ const Machine = struct {
|
||||
const c = &m.channels.items[endpointOf(vals[arm.endpoint])];
|
||||
if (c.capacity != 0) continue;
|
||||
if (arm.value) |v| {
|
||||
try c.send_offers.append(m.heap(), .{ .task = self, .arm = @intCast(i), .value = vals[v] });
|
||||
try c.send_offers.append(m.heap(), .{ .task = self, .arm = @intCast(i), .value = vals[v], .view = t.views.cur });
|
||||
} else c.recv_offer = .{ .task = self, .arm = @intCast(i) };
|
||||
}
|
||||
return .{ .wait = .op };
|
||||
}
|
||||
var pick: usize = 0;
|
||||
if (ready_arms.items.len > 1) {
|
||||
pick = m.sched.next() % ready_arms.items.len;
|
||||
m.choices += 1;
|
||||
pick = try m.choose(ready_arms.items.len);
|
||||
m.drew = true;
|
||||
}
|
||||
const arm_i, const st = ready_arms.items[pick];
|
||||
const arm = x.arms[arm_i];
|
||||
const ch = endpointOf(vals[arm.endpoint]);
|
||||
if (st == .closed) {
|
||||
if (arm.value == null) try m.observeClose(ch);
|
||||
setParams(f, vals, arm.closed, v_vals);
|
||||
return .{ .jump_yield = arm.closed };
|
||||
}
|
||||
@@ -1081,7 +1240,7 @@ const Machine = struct {
|
||||
try m.doSend(ch, vals[v]);
|
||||
return m.selectOk(f, vals, x, arm_i, .void, vs, v_vals);
|
||||
}
|
||||
return m.selectOk(f, vals, x, arm_i, m.doRecv(ch), vs, v_vals);
|
||||
return m.selectOk(f, vals, x, arm_i, try m.doRecv(ch), vs, v_vals);
|
||||
}
|
||||
|
||||
/// Continues at the `ok` target of arm `i`: the received value (for a
|
||||
@@ -1109,21 +1268,140 @@ const Machine = struct {
|
||||
const mc = mutexOf(vals[x.mutex]);
|
||||
if (!mc.locked) {
|
||||
mc.locked = true;
|
||||
// unlock → the next lock (spec 04 §20.3).
|
||||
try m.tasks.items[m.current].views.acquire(mc.view, m.heap());
|
||||
setParams(f, vals, x.ok, &.{.{ .guard = mc }});
|
||||
return .{ .jump_yield = x.ok };
|
||||
}
|
||||
if (cancelObservable(&m.tasks.items[m.current])) return .{ .jump_yield = x.cancelled };
|
||||
if (cancelObservable(&m.tasks.items[m.current])) {
|
||||
try m.observeCancel();
|
||||
return .{ .jump_yield = x.cancelled };
|
||||
}
|
||||
return .{ .wait = .op };
|
||||
},
|
||||
.mutex_borrow => |g| return bind(vals, inst.result, .{ .place = .{ .cell = vals[g].guard.cell, .path = &.{} } }),
|
||||
.mutex_unlock => |g| {
|
||||
vals[g].guard.locked = false;
|
||||
vals[g].guard.view = m.tasks.items[m.current].views.cur;
|
||||
return .yield;
|
||||
},
|
||||
else => unreachable,
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ atomics (spec 04 §20–§30, §42)
|
||||
|
||||
fn cellOf(v: Value) u32 {
|
||||
return switch (v) {
|
||||
.atomic => |id| id,
|
||||
.place => |p| cellOf(placePtr(p).*),
|
||||
else => unreachable,
|
||||
};
|
||||
}
|
||||
|
||||
fn scalarBits(v: Value) u128 {
|
||||
return switch (v) {
|
||||
.int => |x| x.bits,
|
||||
.boolean => |b| @intFromBool(b),
|
||||
else => unreachable,
|
||||
};
|
||||
}
|
||||
|
||||
fn scalarValue(ty: air.Type, bits: u128) Value {
|
||||
return switch (ty) {
|
||||
.int => |it| .{ .int = .{ .ty = it, .bits = bits } },
|
||||
.bool => .{ .boolean = bits != 0 },
|
||||
else => unreachable,
|
||||
};
|
||||
}
|
||||
|
||||
/// A weak-memory choice among `n` readable messages (spec 04 §42).
|
||||
fn weakChoice(m: *Machine, n: u64) !u64 {
|
||||
if (n == 1) return 0;
|
||||
m.drew = true;
|
||||
return try m.choose(@intCast(n));
|
||||
}
|
||||
|
||||
fn execAtomic(m: *Machine, vals: []Value, inst: air.Inst) !Step {
|
||||
const gpa = m.heap();
|
||||
const views = &m.tasks.items[m.current].views;
|
||||
switch (inst.op) {
|
||||
.atomic_new => |v| {
|
||||
const ty: air.Type = switch (vals[v]) {
|
||||
.int => |x| .{ .int = x.ty },
|
||||
else => .bool,
|
||||
};
|
||||
return bind(vals, inst.result, .{ .atomic = try m.mem.create(gpa, m.arena, ty, scalarBits(vals[v])) });
|
||||
},
|
||||
.atomic_take => |v| {
|
||||
const c = &m.mem.cells.items[vals[v].atomic];
|
||||
const value = scalarValue(c.ty, c.at(c.latest()).bits);
|
||||
c.taken = true;
|
||||
return bind(vals, inst.result, value);
|
||||
},
|
||||
.atomic_load => |x| {
|
||||
const id = cellOf(vals[x.cell]);
|
||||
const first, const last = m.mem.readRange(views, id, x.ord);
|
||||
const ts = first + try m.weakChoice(last - first + 1);
|
||||
const bits = try m.mem.read(gpa, views, id, ts, x.ord);
|
||||
vals[inst.result.?] = scalarValue(m.mem.cells.items[id].ty, bits);
|
||||
return m.yieldUnlessExploring();
|
||||
},
|
||||
.atomic_store => |x| {
|
||||
try m.mem.write(gpa, views, cellOf(vals[x.cell]), scalarBits(vals[x.value]), x.ord, .{});
|
||||
return m.yieldUnlessExploring();
|
||||
},
|
||||
.atomic_rmw => |x| {
|
||||
const id = cellOf(vals[x.cell]);
|
||||
const ty = m.mem.cells.items[id].ty;
|
||||
const old, const carried = try m.mem.rmwRead(gpa, views, id, x.ord);
|
||||
const operand = scalarBits(vals[x.value]);
|
||||
const new: u128 = switch (x.op) {
|
||||
.xchg => operand,
|
||||
.add_wrap => arith(.add, .wrap, ty.int, old, operand) catch unreachable,
|
||||
.sub_wrap => arith(.sub, .wrap, ty.int, old, operand) catch unreachable,
|
||||
.@"and" => old & operand,
|
||||
.@"or" => old | operand,
|
||||
.xor => old ^ operand,
|
||||
};
|
||||
try m.mem.write(gpa, views, id, new, x.ord, carried);
|
||||
vals[inst.result.?] = scalarValue(ty, old);
|
||||
return m.yieldUnlessExploring();
|
||||
},
|
||||
.atomic_cmpxchg => |x| {
|
||||
const id = cellOf(vals[x.cell]);
|
||||
const c = &m.mem.cells.items[id];
|
||||
const expected = scalarBits(vals[x.expected]);
|
||||
// Readable messages: the latest (a success when it equals
|
||||
// the expected value), and older ones that differ from it
|
||||
// (failures; a strong CAS cannot fail on an equal value).
|
||||
const first, const last = m.mem.readRange(views, id, x.failure);
|
||||
var options: std.ArrayList(u64) = .empty;
|
||||
var ts = first;
|
||||
while (ts < last) : (ts += 1) if (c.at(ts).bits != expected) try options.append(gpa, ts);
|
||||
try options.append(gpa, c.latest());
|
||||
const pick = options.items[@intCast(try m.weakChoice(options.items.len))];
|
||||
const ty = c.ty;
|
||||
if (pick == c.latest() and c.at(pick).bits == expected) {
|
||||
const old, const carried = try m.mem.rmwRead(gpa, views, id, x.success);
|
||||
try m.mem.write(gpa, views, id, scalarBits(vals[x.desired]), x.success, carried);
|
||||
vals[inst.result.?] = scalarValue(ty, old);
|
||||
vals[inst.result2.?] = .{ .boolean = true };
|
||||
} else {
|
||||
const bits = try m.mem.read(gpa, views, id, pick, x.failure);
|
||||
vals[inst.result.?] = scalarValue(ty, bits);
|
||||
vals[inst.result2.?] = .{ .boolean = false };
|
||||
}
|
||||
return m.yieldUnlessExploring();
|
||||
},
|
||||
.atomic_fence => |o| {
|
||||
try m.mem.fence(gpa, views, o);
|
||||
return m.yieldUnlessExploring();
|
||||
},
|
||||
else => unreachable,
|
||||
}
|
||||
}
|
||||
|
||||
fn mutexOf(v: Value) *Value.MutexCell {
|
||||
return switch (v) {
|
||||
.mutex => |mc| mc,
|
||||
@@ -1857,7 +2135,7 @@ pub fn writeValue(module: air.Module, v: Value, s: *std.json.Stringify) std.Io.W
|
||||
},
|
||||
// Storage and borrows cannot be returned from `@main` (spec 08 §11.3).
|
||||
.local, .place, .slice => try s.write(null),
|
||||
.resource, .own, .region, .scope, .task, .shield, .sender, .receiver, .mutex, .guard, .graph, .iref => try s.write(null),
|
||||
.resource, .own, .region, .scope, .task, .shield, .sender, .receiver, .mutex, .guard, .graph, .iref, .atomic => try s.write(null),
|
||||
// A capability is opaque: only its kind is shown, never its identity.
|
||||
.cap => {
|
||||
try s.beginObject();
|
||||
|
||||
@@ -0,0 +1,294 @@
|
||||
//! The weak-memory machine of the deterministic interpreter (spec 04 §20,
|
||||
//! §42; RFC 0015 D10). Not normative: the normative model is the axioms of
|
||||
//! spec 04 §20. This machine must be sound for every program
|
||||
//! (`observed ⊆ allowed`) and exact on the litmus corpus
|
||||
//! (`observed_exhaustive = allowed`), which `tools/litmus` checks against the
|
||||
//! independent oracle.
|
||||
//!
|
||||
//! Design: a timestamped message machine without promises.
|
||||
//!
|
||||
//! - Every atomic cell keeps its writes in modification order. A message has
|
||||
//! the value written and the view a reader acquires from it.
|
||||
//! - Every task keeps three views (cell → timestamp): `cur` (it may not read
|
||||
//! below), `acq` (what an acquire fence would add) and `rel` (the view of
|
||||
//! its last release fence, carried by its relaxed writes).
|
||||
//! - A non-`seq_cst` read may read any message at or above `cur`; which one is
|
||||
//! a choice of the schedule stream. A `seq_cst` read and every RMW read the
|
||||
//! latest message.
|
||||
//! - Writes append, so modification order is execution order and no read
|
||||
//! reads a write that does not exist yet: `sb ∪ rf` stays acyclic
|
||||
//! (NO-THIN-AIR).
|
||||
//! - `seq_cst` accesses and fences synchronize through one global view `sc`.
|
||||
//!
|
||||
//! Without non-`seq_cst` accesses every read takes the latest message, so the
|
||||
//! machine is the interleaving machine and makes no extra choice.
|
||||
|
||||
const std = @import("std");
|
||||
const air = @import("../air.zig");
|
||||
|
||||
/// For each atomic cell observed, the oldest timestamp that may still be read.
|
||||
/// Immutable: operations return new views and share unchanged ones.
|
||||
pub const View = struct {
|
||||
/// Sorted by cell.
|
||||
entries: []const Entry = &.{},
|
||||
|
||||
pub const Entry = struct { cell: u32, ts: u64 };
|
||||
|
||||
pub fn get(v: View, cell: u32) u64 {
|
||||
for (v.entries) |e| {
|
||||
if (e.cell == cell) return e.ts;
|
||||
if (e.cell > cell) break;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
fn below(a: View, b: View) bool {
|
||||
for (a.entries) |e| if (b.get(e.cell) < e.ts) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// The pointwise maximum.
|
||||
pub fn join(a: View, b: View, gpa: std.mem.Allocator) !View {
|
||||
if (below(b, a)) return a;
|
||||
if (below(a, b)) return b;
|
||||
var out: std.ArrayList(Entry) = .empty;
|
||||
var i: usize = 0;
|
||||
var j: usize = 0;
|
||||
while (i < a.entries.len or j < b.entries.len) {
|
||||
if (j == b.entries.len or (i < a.entries.len and a.entries[i].cell < b.entries[j].cell)) {
|
||||
try out.append(gpa, a.entries[i]);
|
||||
i += 1;
|
||||
} else if (i == a.entries.len or b.entries[j].cell < a.entries[i].cell) {
|
||||
try out.append(gpa, b.entries[j]);
|
||||
j += 1;
|
||||
} else {
|
||||
try out.append(gpa, .{ .cell = a.entries[i].cell, .ts = @max(a.entries[i].ts, b.entries[j].ts) });
|
||||
i += 1;
|
||||
j += 1;
|
||||
}
|
||||
}
|
||||
return .{ .entries = out.items };
|
||||
}
|
||||
|
||||
pub fn with(v: View, cell: u32, ts: u64, gpa: std.mem.Allocator) !View {
|
||||
if (v.get(cell) >= ts) return v;
|
||||
// The single entry must outlive this call: `join` may return it.
|
||||
const one = try gpa.alloc(Entry, 1);
|
||||
one[0] = .{ .cell = cell, .ts = ts };
|
||||
return v.join(.{ .entries = one }, gpa);
|
||||
}
|
||||
|
||||
pub fn copy(v: View, gpa: std.mem.Allocator) !View {
|
||||
if (v.entries.len == 0) return v;
|
||||
return .{ .entries = try gpa.dupe(Entry, v.entries) };
|
||||
}
|
||||
};
|
||||
|
||||
/// The views of one task.
|
||||
pub const TaskViews = struct {
|
||||
cur: View = .{},
|
||||
acq: View = .{},
|
||||
rel: View = .{},
|
||||
|
||||
/// Synchronizes with `v` (an `sw` edge into this task).
|
||||
pub fn acquire(t: *TaskViews, v: View, gpa: std.mem.Allocator) !void {
|
||||
t.cur = try t.cur.join(v, gpa);
|
||||
t.acq = try t.acq.join(v, gpa);
|
||||
}
|
||||
|
||||
pub fn copy(t: TaskViews, gpa: std.mem.Allocator) !TaskViews {
|
||||
return .{ .cur = try t.cur.copy(gpa), .acq = try t.acq.copy(gpa), .rel = try t.rel.copy(gpa) };
|
||||
}
|
||||
};
|
||||
|
||||
/// One write: the value (an AtomicScalar bit pattern) and the view a reader
|
||||
/// acquires from it.
|
||||
pub const Msg = struct { bits: u128, view: View };
|
||||
|
||||
/// An atomic cell: its writes in modification order. `msgs[i]` has timestamp
|
||||
/// `base + i`; older messages no task can read any more are dropped.
|
||||
pub const Cell = struct {
|
||||
ty: air.Type,
|
||||
msgs: std.ArrayList(Msg) = .empty,
|
||||
base: u64 = 0,
|
||||
taken: bool = false,
|
||||
|
||||
pub fn latest(c: *const Cell) u64 {
|
||||
return c.base + c.msgs.items.len - 1;
|
||||
}
|
||||
|
||||
pub fn at(c: *const Cell, ts: u64) Msg {
|
||||
return c.msgs.items[@intCast(ts - c.base)];
|
||||
}
|
||||
|
||||
/// The oldest timestamp a read by a task with view `cur` may read.
|
||||
pub fn oldest(c: *const Cell, id: u32, cur: View) u64 {
|
||||
return @max(c.base, cur.get(id));
|
||||
}
|
||||
};
|
||||
|
||||
/// The global state of the machine.
|
||||
pub const Memory = struct {
|
||||
cells: std.ArrayList(Cell) = .empty,
|
||||
/// The view of the `seq_cst` order.
|
||||
sc: View = .{},
|
||||
/// The program may read older messages (it has a non-`seq_cst` load or
|
||||
/// compare-exchange). Otherwise only the latest message is kept.
|
||||
weak_reads: bool = false,
|
||||
|
||||
pub fn create(mem: *Memory, gpa: std.mem.Allocator, arena: std.mem.Allocator, ty: air.Type, bits: u128) !u32 {
|
||||
try mem.cells.append(arena, .{ .ty = ty });
|
||||
const id: u32 = @intCast(mem.cells.items.len - 1);
|
||||
// The distinguished initialization write (spec 04 §20.1): first in
|
||||
// `mo`, starts no `sw`.
|
||||
try mem.cells.items[id].msgs.append(gpa, .{ .bits = bits, .view = .{} });
|
||||
return id;
|
||||
}
|
||||
|
||||
/// Before a `seq_cst` access or fence: synchronize with the SC view.
|
||||
fn scBefore(mem: *Memory, t: *TaskViews, gpa: std.mem.Allocator) !void {
|
||||
try t.acquire(mem.sc, gpa);
|
||||
}
|
||||
|
||||
fn scAfter(mem: *Memory, t: *TaskViews, gpa: std.mem.Allocator) !void {
|
||||
mem.sc = try mem.sc.join(t.cur, gpa);
|
||||
}
|
||||
|
||||
/// The timestamps a read with ordering `ord` may read: `[first, last]`.
|
||||
pub fn readRange(mem: *Memory, t: *const TaskViews, id: u32, ord: air.Ordering) struct { u64, u64 } {
|
||||
const c = &mem.cells.items[id];
|
||||
const last = c.latest();
|
||||
if (ord == .seq_cst) return .{ last, last };
|
||||
return .{ c.oldest(id, t.cur), last };
|
||||
}
|
||||
|
||||
/// Reads message `ts` (one of `readRange`) with ordering `ord`.
|
||||
pub fn read(mem: *Memory, gpa: std.mem.Allocator, t: *TaskViews, id: u32, ts: u64, ord: air.Ordering) !u128 {
|
||||
if (ord == .seq_cst) try mem.scBefore(t, gpa);
|
||||
const msg = mem.cells.items[id].at(ts);
|
||||
const seen = try msg.view.with(id, ts, gpa);
|
||||
if (ord.hasAcquire()) {
|
||||
t.cur = try t.cur.join(seen, gpa);
|
||||
} else {
|
||||
t.cur = try t.cur.with(id, ts, gpa);
|
||||
}
|
||||
t.acq = try t.acq.join(seen, gpa);
|
||||
if (ord == .seq_cst) try mem.scAfter(t, gpa);
|
||||
return msg.bits;
|
||||
}
|
||||
|
||||
/// Appends a write with ordering `ord`. `carried` is the view of the
|
||||
/// message an RMW read, which continues its release sequence.
|
||||
pub fn write(mem: *Memory, gpa: std.mem.Allocator, t: *TaskViews, id: u32, bits: u128, ord: air.Ordering, carried: View) !void {
|
||||
if (ord == .seq_cst) try mem.scBefore(t, gpa);
|
||||
const c = &mem.cells.items[id];
|
||||
const ts = c.latest() + 1;
|
||||
t.cur = try t.cur.with(id, ts, gpa);
|
||||
t.acq = try t.acq.with(id, ts, gpa);
|
||||
var view = if (ord.hasRelease()) t.cur else try t.rel.with(id, ts, gpa);
|
||||
view = try view.join(carried, gpa);
|
||||
if (mem.weak_reads) {
|
||||
try c.msgs.append(gpa, .{ .bits = bits, .view = view });
|
||||
} else {
|
||||
// No read can read an older message: keep only the latest.
|
||||
c.msgs.clearRetainingCapacity();
|
||||
c.msgs.appendAssumeCapacity(.{ .bits = bits, .view = view });
|
||||
c.base = ts;
|
||||
}
|
||||
if (ord == .seq_cst) try mem.scAfter(t, gpa);
|
||||
}
|
||||
|
||||
/// A read-modify-write: reads the latest message (atomicity), then writes
|
||||
/// `bits` computed from it. Returns the value read.
|
||||
pub fn rmwRead(mem: *Memory, gpa: std.mem.Allocator, t: *TaskViews, id: u32, ord: air.Ordering) !struct { u128, View } {
|
||||
const c = &mem.cells.items[id];
|
||||
const ts = c.latest();
|
||||
const msg = c.at(ts);
|
||||
// The read part: acquire as the ordering says; its write part
|
||||
// follows with `write`.
|
||||
if (ord == .seq_cst) try mem.scBefore(t, gpa);
|
||||
const seen = try msg.view.with(id, ts, gpa);
|
||||
if (ord.hasAcquire()) t.cur = try t.cur.join(seen, gpa) else t.cur = try t.cur.with(id, ts, gpa);
|
||||
t.acq = try t.acq.join(seen, gpa);
|
||||
return .{ msg.bits, msg.view };
|
||||
}
|
||||
|
||||
pub fn fence(mem: *Memory, gpa: std.mem.Allocator, t: *TaskViews, ord: air.Ordering) !void {
|
||||
if (ord.hasAcquire()) t.cur = try t.cur.join(t.acq, gpa);
|
||||
if (ord == .seq_cst) {
|
||||
try mem.scBefore(t, gpa);
|
||||
try mem.scAfter(t, gpa);
|
||||
}
|
||||
if (ord.hasRelease()) t.rel = t.cur;
|
||||
}
|
||||
|
||||
/// Drops messages below `floor[id]`, the oldest timestamp any live task
|
||||
/// may still read, and copies the rest into `gpa` (the collector).
|
||||
pub fn compact(mem: *Memory, gpa: std.mem.Allocator, floor: []const u64) !void {
|
||||
mem.sc = try mem.sc.copy(gpa);
|
||||
for (mem.cells.items, 0..) |*c, i| {
|
||||
var next: std.ArrayList(Msg) = .empty;
|
||||
if (c.taken) {
|
||||
c.msgs = next;
|
||||
continue;
|
||||
}
|
||||
const keep_from = @min(@max(c.base, floor[i]), c.latest());
|
||||
try next.ensureTotalCapacity(gpa, @intCast(c.latest() + 1 - keep_from));
|
||||
var ts = keep_from;
|
||||
while (ts <= c.latest()) : (ts += 1) {
|
||||
const m = c.at(ts);
|
||||
next.appendAssumeCapacity(.{ .bits = m.bits, .view = try m.view.copy(gpa) });
|
||||
}
|
||||
c.msgs = next;
|
||||
c.base = keep_from;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
test "views join pointwise and share when one contains the other" {
|
||||
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
|
||||
defer arena.deinit();
|
||||
const a = arena.allocator();
|
||||
const v1: View = .{ .entries = &.{ .{ .cell = 0, .ts = 2 }, .{ .cell = 2, .ts = 1 } } };
|
||||
const v2: View = .{ .entries = &.{ .{ .cell = 1, .ts = 3 }, .{ .cell = 2, .ts = 4 } } };
|
||||
const j = try v1.join(v2, a);
|
||||
try std.testing.expectEqual(@as(u64, 2), j.get(0));
|
||||
try std.testing.expectEqual(@as(u64, 3), j.get(1));
|
||||
try std.testing.expectEqual(@as(u64, 4), j.get(2));
|
||||
try std.testing.expectEqual(v1.entries.ptr, (try v1.join(.{}, a)).entries.ptr);
|
||||
}
|
||||
|
||||
test "message passing: an acquire read of a release write sees the earlier relaxed write" {
|
||||
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
|
||||
defer arena.deinit();
|
||||
const a = arena.allocator();
|
||||
var mem: Memory = .{ .weak_reads = true };
|
||||
const x = try mem.create(a, a, .{ .int = .u64 }, 0);
|
||||
const y = try mem.create(a, a, .{ .int = .u64 }, 0);
|
||||
var w: TaskViews = .{};
|
||||
var r: TaskViews = .{};
|
||||
try mem.write(a, &w, x, 1, .relaxed, .{});
|
||||
try mem.write(a, &w, y, 1, .release, .{});
|
||||
// Reading y=1 with acquire forbids x=0 afterwards.
|
||||
_ = try mem.read(a, &r, y, 1, .acquire);
|
||||
const first, const last = mem.readRange(&r, x, .relaxed);
|
||||
try std.testing.expectEqual(@as(u64, 1), first);
|
||||
try std.testing.expectEqual(@as(u64, 1), last);
|
||||
}
|
||||
|
||||
test "store buffering: relaxed reads may read the initial write" {
|
||||
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
|
||||
defer arena.deinit();
|
||||
const a = arena.allocator();
|
||||
var mem: Memory = .{ .weak_reads = true };
|
||||
const x = try mem.create(a, a, .{ .int = .u64 }, 0);
|
||||
const y = try mem.create(a, a, .{ .int = .u64 }, 0);
|
||||
var t0: TaskViews = .{};
|
||||
var t1: TaskViews = .{};
|
||||
try mem.write(a, &t0, x, 1, .relaxed, .{});
|
||||
try mem.write(a, &t1, y, 1, .relaxed, .{});
|
||||
try std.testing.expectEqual(@as(u64, 0), mem.readRange(&t0, y, .relaxed)[0]);
|
||||
try std.testing.expectEqual(@as(u64, 0), mem.readRange(&t1, x, .relaxed)[0]);
|
||||
// With seq_cst only the latest message is readable.
|
||||
try std.testing.expectEqual(@as(u64, 1), mem.readRange(&t0, y, .seq_cst)[0]);
|
||||
}
|
||||
@@ -33,6 +33,11 @@ const usage =
|
||||
\\ print the canonical AIR a source module lowers to;
|
||||
\\ --annotate adds source spans as comments (not canonical);
|
||||
\\ --stats prints source/AIR size and expansion ratio
|
||||
\\ explore [--max-runs N] [--grant P=KIND[:SCOPE]]... <file.air | file.aji>
|
||||
\\ run @main under every schedule and weak-memory choice
|
||||
\\ (depth first, up to N runs, default 100000) and print the
|
||||
\\ distinct outcomes; "complete" is true when the whole
|
||||
\\ choice tree was explored (spec 04 §20.5)
|
||||
\\ report <file.air> verify, then print the audit report (spec 10 §6.1)
|
||||
\\ codes list diagnostic codes as JSON Lines
|
||||
\\ features print supported AIR format, language version and features
|
||||
@@ -177,6 +182,7 @@ fn run(io: std.Io, arena: std.mem.Allocator, args: []const [:0]const u8, out: *s
|
||||
try writeCode(out, c.*);
|
||||
return .accepted;
|
||||
}
|
||||
if (std.mem.eql(u8, cmd, "explore")) return explore(arena, io, args[2..], out);
|
||||
if (std.mem.eql(u8, cmd, "check") or std.mem.eql(u8, cmd, "run")) {
|
||||
var options: aji.interp.Options = .{};
|
||||
var grants: std.ArrayList(aji.interp.Grant) = .empty;
|
||||
@@ -319,6 +325,97 @@ fn run(io: std.Io, arena: std.mem.Allocator, args: []const [:0]const u8, out: *s
|
||||
return usageError("unknown command");
|
||||
}
|
||||
|
||||
/// `aji explore`: exhaustive depth-first exploration of the choice tree
|
||||
/// (scheduler, `select` and weak-memory choices). Instructions other than
|
||||
/// scheduling points are not interleaved: the quantum is unbounded, so the
|
||||
/// tree branches only at synchronization and atomic operations.
|
||||
fn explore(arena: std.mem.Allocator, io: std.Io, argv: []const []const u8, out: *std.Io.Writer) !ExitCode {
|
||||
var max_runs: u64 = 100_000;
|
||||
var grants: std.ArrayList(aji.interp.Grant) = .empty;
|
||||
var rest = argv;
|
||||
while (rest.len >= 2) {
|
||||
if (std.mem.eql(u8, rest[0], "--max-runs")) {
|
||||
max_runs = std.fmt.parseInt(u64, rest[1], 10) catch return usageError("--max-runs takes a positive integer");
|
||||
} else if (std.mem.eql(u8, rest[0], "--grant")) {
|
||||
try grants.append(arena, parseGrant(rest[1]) orelse return usageError("--grant takes <parameter>=<kind>[:<scope>]"));
|
||||
} else break;
|
||||
rest = rest[2..];
|
||||
}
|
||||
if (rest.len != 1) return usageError("explore takes exactly one file");
|
||||
const path = rest[0];
|
||||
const source = std.Io.Dir.cwd().readFileAlloc(io, path, arena, .limited(64 << 20)) catch |err| {
|
||||
std.debug.print("aji: cannot read {s}: {t}\n", .{ path, err });
|
||||
return .usage;
|
||||
};
|
||||
const report = try aji.check.checkFile(arena, path, source);
|
||||
for (report.diagnostics) |d| {
|
||||
try d.writeJson(out);
|
||||
try out.writeByte('\n');
|
||||
}
|
||||
if (report.status != .accepted) return .rejected;
|
||||
const module = report.module.?;
|
||||
|
||||
var counts: std.StringArrayHashMapUnmanaged(u64) = .empty;
|
||||
var prefix: std.ArrayList(u32) = .empty;
|
||||
var runs: u64 = 0;
|
||||
var complete = false;
|
||||
while (runs < max_runs) {
|
||||
var run_arena: std.heap.ArenaAllocator = .init(std.heap.page_allocator);
|
||||
defer run_arena.deinit();
|
||||
var ex: aji.interp.Explore = .{ .prefix = prefix.items };
|
||||
const outcome = aji.interp.run(run_arena.allocator(), module, "main", .{
|
||||
.grants = grants.items,
|
||||
.quantum = std.math.maxInt(u64),
|
||||
.explore = &ex,
|
||||
}) catch |err| switch (err) {
|
||||
error.EntryNotFound => return usageError("module has no @main whose parameters are all capabilities"),
|
||||
error.DuplicateGrant => return usageError("a parameter is granted more than once"),
|
||||
else => |e| return e,
|
||||
};
|
||||
runs += 1;
|
||||
var rec: std.Io.Writer.Allocating = .init(run_arena.allocator());
|
||||
try aji.interp.writeOutcome(module, outcome, null, &rec.writer);
|
||||
const gop = try counts.getOrPut(arena, rec.written());
|
||||
if (!gop.found_existing) {
|
||||
gop.key_ptr.* = try arena.dupe(u8, rec.written());
|
||||
gop.value_ptr.* = 0;
|
||||
}
|
||||
gop.value_ptr.* += 1;
|
||||
// The next path: increment the deepest choice that has an untried
|
||||
// option, and drop everything after it.
|
||||
const widths = ex.widths.items;
|
||||
var i = widths.len;
|
||||
const next = while (i > 0) {
|
||||
i -= 1;
|
||||
const taken: u32 = if (i < prefix.items.len) prefix.items[i] else 0;
|
||||
if (taken + 1 < widths[i]) break i;
|
||||
} else null;
|
||||
const at = next orelse {
|
||||
complete = true;
|
||||
break;
|
||||
};
|
||||
var np: std.ArrayList(u32) = .empty;
|
||||
for (0..at) |k| try np.append(arena, if (k < prefix.items.len) prefix.items[k] else 0);
|
||||
try np.append(arena, (if (at < prefix.items.len) prefix.items[at] else 0) + 1);
|
||||
prefix = np;
|
||||
}
|
||||
const keys = counts.keys();
|
||||
const order = try arena.alloc(usize, keys.len);
|
||||
for (order, 0..) |*o, k| o.* = k;
|
||||
std.mem.sort(usize, order, keys, struct {
|
||||
fn lt(ks: []const []const u8, a: usize, b: usize) bool {
|
||||
return std.mem.lessThan(u8, ks[a], ks[b]);
|
||||
}
|
||||
}.lt);
|
||||
try out.print("{{\"runs\":{d},\"complete\":{},\"outcomes\":[", .{ runs, complete });
|
||||
for (order, 0..) |k, n| {
|
||||
if (n != 0) try out.writeByte(',');
|
||||
try out.print("{{\"outcome\":{s},\"count\":{d}}}", .{ keys[k], counts.values()[k] });
|
||||
}
|
||||
try out.writeAll("]}\n");
|
||||
return if (complete) .accepted else .limit_exceeded;
|
||||
}
|
||||
|
||||
/// The run record; for a `.aji` module a trap also carries its
|
||||
/// `source_location` (spec 15 §10).
|
||||
fn writeRecord(arena: std.mem.Allocator, module: aji.air.Module, outcome: aji.interp.Outcome, captured: ?aji.interp.Output, report: aji.check.Report, path: []const u8, out: *std.Io.Writer) !void {
|
||||
|
||||
+19
-1
@@ -24,6 +24,9 @@ const FnInfo = struct {
|
||||
checks: Checks = .{},
|
||||
proven_bounds: u32 = 0,
|
||||
unsafe_ops: std.ArrayList(struct { block: []const u8, inst: u32, op: []const u8 }) = .empty,
|
||||
/// Atomic memory operations (spec 04 §25): `weak` marks the sites that
|
||||
/// need `atomic.weak`, where interleaving reasoning is not enough.
|
||||
atomic_ops: std.ArrayList(struct { block: []const u8, inst: u32, op: []const u8, ordering: []const u8, weak: bool }) = .empty,
|
||||
/// Effects performed directly (intrinsics, allocation, unsafe operations).
|
||||
direct: std.ArrayList([]const u8) = .empty,
|
||||
/// Fixed point of `direct` over callees.
|
||||
@@ -90,6 +93,19 @@ fn analyze(arena: std.mem.Allocator, m: air.Module, f: air.Function) !FnInfo {
|
||||
if (x.unchecked) {} else if (x.proven) info.proven_bounds += 1 else info.checks.bounds += 1;
|
||||
},
|
||||
.slice_sub, .slice_split, .slice_copy => info.checks.bounds += 1,
|
||||
.atomic_load, .atomic_store, .atomic_rmw, .atomic_cmpxchg, .atomic_fence => {
|
||||
const op: []const u8, const ord: []const u8, const weak = switch (inst.op) {
|
||||
.atomic_load => |x| .{ "atomic.load", @tagName(x.ord), x.ord != .seq_cst },
|
||||
.atomic_store => |x| .{ "atomic.store", @tagName(x.ord), x.ord != .seq_cst },
|
||||
.atomic_rmw => |x| .{ try std.fmt.allocPrint(arena, "atomic.{s}", .{x.op.text()}), @tagName(x.ord), x.ord != .seq_cst },
|
||||
.atomic_cmpxchg => |x| .{ "atomic.cmpxchg", try std.fmt.allocPrint(arena, "{s}.{s}", .{ @tagName(x.success), @tagName(x.failure) }), x.success != .seq_cst or x.failure != .seq_cst },
|
||||
.atomic_fence => |o| .{ "atomic.fence", @tagName(o), false },
|
||||
else => unreachable,
|
||||
};
|
||||
try info.atomic_ops.append(arena, .{ .block = b.name, .inst = @intCast(ii), .op = op, .ordering = ord, .weak = weak });
|
||||
_ = try addOnce(arena, &info.direct, "atomic");
|
||||
if (weak) _ = try addOnce(arena, &info.direct, "atomic.weak");
|
||||
},
|
||||
else => {},
|
||||
}
|
||||
if (unsafe_.unsafeOp(m, inst.op)) |what| {
|
||||
@@ -181,6 +197,8 @@ pub fn write(arena: std.mem.Allocator, m: air.Module, w: *Writer) !void {
|
||||
try s.write(.{ .bounds = i.proven_bounds });
|
||||
try s.objectField("unsafe_operations");
|
||||
try s.write(i.unsafe_ops.items);
|
||||
try s.objectField("atomic_operations");
|
||||
try s.write(i.atomic_ops.items);
|
||||
try s.endObject();
|
||||
}
|
||||
try s.endArray();
|
||||
@@ -248,6 +266,6 @@ test "audit report" {
|
||||
var out: Writer.Allocating = .init(arena);
|
||||
try write(arena, parsed.module.?, &out.writer);
|
||||
try std.testing.expectEqualStrings(
|
||||
\\{"report":"audit","air":0,"module":"demo","features":["arrays","capabilities","effects","ownership","resources","unsafe"],"entry":{"function":"main","capabilities":[{"parameter":"out","kind":"io.write"},{"parameter":"fs","kind":"fs.read"}]},"functions":[{"name":"main","trusted":null,"effects_declared":["fs.read","io.write"],"effects_used":[],"effects_unused":["fs.read","io.write"],"calls":["peek"],"intrinsics":[],"allocations":0,"runtime_checks":{"overflow":1,"division":0,"shift":0,"cast":0,"bounds":0,"assert":0,"guard":0},"proven_checks":{"bounds":0},"unsafe_operations":[]},{"name":"peek","trusted":"only reads","effects_declared":[],"effects_used":["unsafe"],"effects_unused":[],"calls":[],"intrinsics":[],"allocations":0,"runtime_checks":{"overflow":0,"division":0,"shift":0,"cast":0,"bounds":0,"assert":0,"guard":0},"proven_checks":{"bounds":0},"unsafe_operations":[{"block":"entry","inst":1,"op":"assume"}]}],"capability_kinds":["fs.read","io.write"],"unsafe":{"trusted_functions":["peek"],"unsafe_functions":[],"operations":1}}
|
||||
\\{"report":"audit","air":0,"module":"demo","features":["arrays","capabilities","effects","ownership","resources","unsafe"],"entry":{"function":"main","capabilities":[{"parameter":"out","kind":"io.write"},{"parameter":"fs","kind":"fs.read"}]},"functions":[{"name":"main","trusted":null,"effects_declared":["fs.read","io.write"],"effects_used":[],"effects_unused":["fs.read","io.write"],"calls":["peek"],"intrinsics":[],"allocations":0,"runtime_checks":{"overflow":1,"division":0,"shift":0,"cast":0,"bounds":0,"assert":0,"guard":0},"proven_checks":{"bounds":0},"unsafe_operations":[],"atomic_operations":[]},{"name":"peek","trusted":"only reads","effects_declared":[],"effects_used":["unsafe"],"effects_unused":[],"calls":[],"intrinsics":[],"allocations":0,"runtime_checks":{"overflow":0,"division":0,"shift":0,"cast":0,"bounds":0,"assert":0,"guard":0},"proven_checks":{"bounds":0},"unsafe_operations":[{"block":"entry","inst":1,"op":"assume"}],"atomic_operations":[]}],"capability_kinds":["fs.read","io.write"],"unsafe":{"trusted_functions":["peek"],"unsafe_functions":[],"operations":1}}
|
||||
, out.written());
|
||||
}
|
||||
@@ -559,6 +559,7 @@ fn step(w: *Walker, inst: air.Inst) !void {
|
||||
w.live[inst.result.?] = true;
|
||||
},
|
||||
.mutex_take => |m| {
|
||||
if (try takeLent(w, m)) return;
|
||||
try w.consume(m, .closed);
|
||||
if (w.isResource(inst.result.?)) w.live[inst.result.?] = true;
|
||||
},
|
||||
@@ -599,6 +600,14 @@ fn step(w: *Walker, inst: air.Inst) !void {
|
||||
try lendArgs(w, &.{v});
|
||||
w.live[inst.result.?] = true;
|
||||
},
|
||||
// Atomics (spec 04 §23, §28): a cell is a linear value; operations go
|
||||
// through a shared borrow of it (interior mutability), `take` consumes
|
||||
// it and needs every borrow ended.
|
||||
.atomic_new => w.live[inst.result.?] = true,
|
||||
.atomic_take => |v| if (!try takeLent(w, v)) try w.consume(v, .closed),
|
||||
.atomic_load => |x| try w.useThrough(x.cell, .shared),
|
||||
inline .atomic_store, .atomic_rmw => |x| try w.useThrough(x.cell, .shared),
|
||||
.atomic_cmpxchg => |x| try w.useThrough(x.cell, .shared),
|
||||
// Values of these instructions are not borrows; any borrow operand
|
||||
// here was already rejected by the type stage.
|
||||
else => {},
|
||||
@@ -606,6 +615,19 @@ fn step(w: *Walker, inst: air.Inst) !void {
|
||||
_ = f;
|
||||
}
|
||||
|
||||
/// Taking a mutex or an atomic cell while a borrow of it is lent to a live
|
||||
/// task races with that task: `E4101` rather than `E2101` (spec 04 §28, §40).
|
||||
fn takeLent(w: *Walker, v: ValueId) !bool {
|
||||
for (w.loans.items) |l| if (w.live[l.task] and l.root == v) {
|
||||
try w.report("E4101", "taken while a borrow of it is lent to a live task", v, .{ "task", l.task });
|
||||
// Consumed all the same, so the mistake is not reported again as a leak.
|
||||
w.live[v] = false;
|
||||
w.dead[v] = .closed;
|
||||
return true;
|
||||
};
|
||||
return false;
|
||||
}
|
||||
|
||||
/// The critical-section rule (spec 04 §41): no operation that may wait or
|
||||
/// spawn while a lock guard is live.
|
||||
fn noWaitUnderLock(w: *Walker, op: []const u8) !void {
|
||||
|
||||
@@ -30,6 +30,7 @@ pub fn accountedSize(m: air.Module, t: air.Type, depth: usize) ?u64 {
|
||||
.bool => 1,
|
||||
.ref, .mut, .cap, .resource, .own, .region, .scope, .task, .shield, .sender, .receiver, .guard, .island, .frozen, .arc => 8,
|
||||
.iref => 16,
|
||||
.atomic => |inner| accountedSize(m, inner.*, depth + 1),
|
||||
.mutex => |inner| std.math.add(u64, 8, accountedSize(m, inner.*, depth + 1) orelse return null) catch null,
|
||||
.own_array => 16,
|
||||
.slice, .slice_mut => 16,
|
||||
|
||||
@@ -50,6 +50,13 @@ pub fn check(c: *Context) !void {
|
||||
.task_join => if (m.declares("cancellation")) try need(c, f, inst, "task.wait"),
|
||||
.task_join_cancel, .channel_send, .channel_recv, .select, .mutex_lock => try need(c, f, inst, "task.wait"),
|
||||
.channel_make => try need(c, f, inst, "mem.alloc"),
|
||||
// Atomics (spec 04 §25, spec 05 §13): every memory operation needs
|
||||
// `atomic`; a non-`seq_cst` access also needs `atomic.weak`.
|
||||
.atomic_fence => try need(c, f, inst, "atomic"),
|
||||
.atomic_load => |x| try needAtomic(c, f, inst, x.ord != .seq_cst),
|
||||
.atomic_store => |x| try needAtomic(c, f, inst, x.ord != .seq_cst),
|
||||
.atomic_rmw => |x| try needAtomic(c, f, inst, x.ord != .seq_cst),
|
||||
.atomic_cmpxchg => |x| try needAtomic(c, f, inst, x.success != .seq_cst or x.failure != .seq_cst),
|
||||
.own_new, .own_array, .region_create, .region_new, .region_array, .island_create, .island_alloc, .arc_new => if (!contains(f.effects, "mem.alloc")) {
|
||||
try c.report("E3101", inst.span, "allocation requires the effect mem.alloc", &.{
|
||||
.{ .name = "function", .value = .{ .str = f.name } },
|
||||
@@ -68,6 +75,11 @@ pub fn check(c: *Context) !void {
|
||||
}
|
||||
}
|
||||
|
||||
fn needAtomic(c: *Context, f: air.Function, inst: air.Inst, weak: bool) !void {
|
||||
try need(c, f, inst, "atomic");
|
||||
if (weak) try need(c, f, inst, "atomic.weak");
|
||||
}
|
||||
|
||||
/// Adds `suggested_effects` to every E3101 reported for `f` since diagnostic
|
||||
/// `first`: the complete, sorted effect list the function needs (its declared
|
||||
/// effects plus every missing one). Effects stay declared by the programmer;
|
||||
|
||||
+97
-5
@@ -85,9 +85,14 @@ fn wellFormed(c: *Context, span: air.Span, t: Type, pos: Position, owner: []cons
|
||||
.void, .never => pos == .ret,
|
||||
.local => false,
|
||||
.ref, .mut, .slice, .slice_mut => pos != .member and pos != .borrowed,
|
||||
.resource, .own, .own_array, .region, .scope, .task, .shield, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc => pos != .member,
|
||||
.resource, .own, .own_array, .region, .scope, .task, .shield, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .atomic => pos != .member,
|
||||
else => true,
|
||||
};
|
||||
// An atomic cell holds an AtomicScalar (spec 04 §23).
|
||||
if (t == .atomic and !isAtomicScalar(t.atomic.*)) try c.report("E1001", span, "atomic<T> needs bool or an integer of at most 64 bits", &.{
|
||||
.{ .name = "in", .value = .{ .str = owner } },
|
||||
.{ .name = "found", .value = .{ .str = try c.typeName(t.atomic.*) } },
|
||||
});
|
||||
if (!ok) try c.report("E1001", span, "type not allowed in this position", &.{
|
||||
.{ .name = "in", .value = .{ .str = owner } },
|
||||
.{ .name = "position", .value = .{ .str = @tagName(pos) } },
|
||||
@@ -339,6 +344,8 @@ pub fn isSend(m: air.Module, t: Type) bool {
|
||||
.int, .bool, .builtin, .cap, .resource, .region, .sender, .receiver => true,
|
||||
// Graph contents are IslandSafe plain data (spec 03 §22–§24).
|
||||
.island, .frozen, .arc, .iref => true,
|
||||
// Every access to a cell is an atomic operation (spec 04 §23).
|
||||
.atomic => true,
|
||||
.own, .own_array, .mutex => |inner| isSend(m, inner.*),
|
||||
.ref, .slice => |inner| isShare(m, inner.*),
|
||||
.mut, .slice_mut => |inner| isSend(m, inner.*),
|
||||
@@ -352,7 +359,7 @@ pub fn isSend(m: air.Module, t: Type) bool {
|
||||
pub fn isShare(m: air.Module, t: Type) bool {
|
||||
return switch (t) {
|
||||
.int, .bool, .builtin, .cap => true,
|
||||
.frozen, .arc, .iref => true,
|
||||
.frozen, .arc, .iref, .atomic => true,
|
||||
// Its owner may mutate it: freeze to share (spec 04 §35).
|
||||
.island => false,
|
||||
.resource, .region, .mut, .slice_mut, .scope, .task, .shield, .guard, .sender, .receiver, .local, .void, .never => false,
|
||||
@@ -364,6 +371,43 @@ pub fn isShare(m: air.Module, t: Type) bool {
|
||||
};
|
||||
}
|
||||
|
||||
/// A borrow whose pointee is an atomic cell: reached only atomically.
|
||||
fn atomicPointee(t: Type) bool {
|
||||
return (t == .ref or t == .mut) and t.inner().? == .atomic;
|
||||
}
|
||||
|
||||
/// `E4202`: an ordinary load or store of an atomic cell (spec 04 §28).
|
||||
fn ordinaryAtomicAccess(fc: *FnCtx, span: air.Span, v: air.ValueId, use: []const u8) !void {
|
||||
try fc.c.report("E4202", span, "an atomic cell is read and written only by atomic operations", &.{
|
||||
.{ .name = "function", .value = .{ .str = fc.f.name } },
|
||||
.{ .name = "operand", .value = .{ .str = try fc.c.valueName(fc.f, v) } },
|
||||
.{ .name = "found", .value = .{ .str = try fc.c.typeName(fc.typeOf(v)) } },
|
||||
.{ .name = "use", .value = .{ .str = use } },
|
||||
});
|
||||
}
|
||||
|
||||
/// `E4201`: an ordering outside the operation's row (spec 04 §24).
|
||||
fn checkOrdering(fc: *FnCtx, span: air.Span, operation: []const u8, ord: air.Ordering, allowed: []const air.Ordering) !void {
|
||||
if (std.mem.indexOfScalar(air.Ordering, allowed, ord) != null) return;
|
||||
var text: std.Io.Writer.Allocating = .init(fc.c.arena);
|
||||
for (allowed, 0..) |o, i| text.writer.print("{s}{s}", .{ if (i == 0) "" else ", ", @tagName(o) }) catch return error.OutOfMemory;
|
||||
try fc.c.report("E4201", span, "memory ordering not valid for this atomic operation", &.{
|
||||
.{ .name = "function", .value = .{ .str = fc.f.name } },
|
||||
.{ .name = "operation", .value = .{ .str = operation } },
|
||||
.{ .name = "ordering", .value = .{ .str = @tagName(ord) } },
|
||||
.{ .name = "allowed", .value = .{ .str = text.written() } },
|
||||
});
|
||||
}
|
||||
|
||||
/// AtomicScalar (spec 04 §23): `bool` and integers of at most 64 bits.
|
||||
pub fn isAtomicScalar(t: Type) bool {
|
||||
return switch (t) {
|
||||
.bool => true,
|
||||
.int => |it| it.bits() <= 64,
|
||||
else => false,
|
||||
};
|
||||
}
|
||||
|
||||
/// `IslandSafe` (spec 02 §6): plain data and `iref` handles, at any depth.
|
||||
/// `ArcSafe` is the same set in format 0.
|
||||
pub fn isIslandSafe(m: air.Module, t: Type) bool {
|
||||
@@ -527,6 +571,11 @@ fn derivedType(fc: *FnCtx, op: air.Op) !?Type {
|
||||
.slice_split => |x| fc.ty[x.slice] orelse return null,
|
||||
.island_root, .frozen_root, .arc_root, .island_freeze, .arc_from_frozen, .arc_clone => |v| fc.ty[v] orelse return null,
|
||||
inline .island_borrow, .frozen_borrow, .arc_borrow => |x| fc.ty[x.owner] orelse return null,
|
||||
.atomic_new => |v| return .{ .atomic = try boxed(a, fc.ty[v] orelse return null) },
|
||||
.atomic_take => |v| fc.ty[v] orelse return null,
|
||||
.atomic_load => |x| fc.ty[x.cell] orelse return null,
|
||||
.atomic_rmw => |x| fc.ty[x.cell] orelse return null,
|
||||
.atomic_cmpxchg => |x| fc.ty[x.cell] orelse return null,
|
||||
else => return null,
|
||||
};
|
||||
const invalid: Type = .void;
|
||||
@@ -534,7 +583,7 @@ fn derivedType(fc: *FnCtx, op: air.Op) !?Type {
|
||||
.local_load => if (t == .local) t.local.* else invalid,
|
||||
.borrow_ref => switch (t) {
|
||||
.local, .ref, .mut => .{ .ref = try boxed(a, t.inner().?) },
|
||||
.resource, .region, .task, .scope, .sender, .receiver, .mutex, .island, .frozen, .arc => .{ .ref = try boxed(a, t) },
|
||||
.resource, .region, .task, .scope, .sender, .receiver, .mutex, .island, .frozen, .arc, .atomic => .{ .ref = try boxed(a, t) },
|
||||
.own => |inner| .{ .ref = inner },
|
||||
.own_array => |inner| .{ .slice = inner },
|
||||
.slice, .slice_mut => .{ .slice = try boxed(a, t.inner().?) },
|
||||
@@ -598,6 +647,9 @@ fn derivedType(fc: *FnCtx, op: air.Op) !?Type {
|
||||
if (owner == .island and t == .mut and t.mut.* == .island) break :blk Type{ .mut = target };
|
||||
break :blk invalid;
|
||||
},
|
||||
.atomic_take => if (t == .atomic) t.atomic.* else invalid,
|
||||
// Every atomic operation takes `ref<atomic<T>>` (spec 04 §23).
|
||||
.atomic_load, .atomic_rmw, .atomic_cmpxchg => if (t == .ref and t.ref.* == .atomic) t.ref.atomic.* else invalid,
|
||||
else => unreachable,
|
||||
};
|
||||
}
|
||||
@@ -638,7 +690,7 @@ fn checkFunction(c: *Context, f: air.Function) ![]const Type {
|
||||
if (fc.ty[r] != null) continue;
|
||||
if (try derivedType(&fc, inst.op)) |t| {
|
||||
fc.ty[r] = t;
|
||||
if (inst.result2) |r2| fc.ty[r2] = t;
|
||||
if (inst.result2) |r2| fc.ty[r2] = if (inst.op == .atomic_cmpxchg) .bool else t;
|
||||
progress = true;
|
||||
}
|
||||
};
|
||||
@@ -690,9 +742,13 @@ fn checkInst(fc: *FnCtx, inst: air.Inst) !void {
|
||||
.borrow_mut => |v| if (resultOf(fc, inst) == .void) try fc.kindError(span, v, "local<T>, a resource, mut<T> or slice_mut<T>"),
|
||||
.borrow_field => |x| if (resultOf(fc, inst) == .void) try fc.kindError(span, x.borrow, "ref or mut of the named struct"),
|
||||
.borrow_end => |v| if (!fc.typeOf(v).isBorrow()) try fc.kindError(span, v, "a borrow"),
|
||||
.load => |v| if (resultOf(fc, inst) == .void) try fc.kindError(span, v, "ref<T> or mut<T>"),
|
||||
.load => |v| {
|
||||
if (atomicPointee(fc.typeOf(v))) return ordinaryAtomicAccess(fc, span, v, "atomic.load");
|
||||
if (resultOf(fc, inst) == .void) try fc.kindError(span, v, "ref<T> or mut<T>");
|
||||
},
|
||||
.store => |x| {
|
||||
const t = fc.typeOf(x.borrow);
|
||||
if (atomicPointee(t)) return ordinaryAtomicAccess(fc, span, x.borrow, "atomic.store");
|
||||
if (t != .mut) return fc.kindError(span, x.borrow, "mut<T>");
|
||||
try fc.expectValue(span, x.value, t.mut.*);
|
||||
},
|
||||
@@ -912,6 +968,42 @@ fn checkInst(fc: *FnCtx, inst: air.Inst) !void {
|
||||
if (a != .iref) return fc.kindError(span, x.a, "iref<T>");
|
||||
try fc.expectValue(span, x.b, a);
|
||||
},
|
||||
// Atomics (spec 04 §23–§25, §42).
|
||||
.atomic_new => |v| if (!isAtomicScalar(fc.typeOf(v))) try fc.kindError(span, v, "bool or an integer of at most 64 bits"),
|
||||
.atomic_take => |v| if (fc.typeOf(v) != .atomic) try fc.kindError(span, v, "atomic<T>"),
|
||||
.atomic_load => |x| {
|
||||
if (resultOf(fc, inst) == .void) return fc.kindError(span, x.cell, "ref<atomic<T>>");
|
||||
try checkOrdering(fc, span, "atomic.load", x.ord, &.{ .relaxed, .acquire, .seq_cst });
|
||||
},
|
||||
.atomic_store => |x| {
|
||||
const t = fc.typeOf(x.cell);
|
||||
if (t != .ref or t.ref.* != .atomic) return fc.kindError(span, x.cell, "ref<atomic<T>>");
|
||||
try fc.expectValue(span, x.value, t.ref.atomic.*);
|
||||
try checkOrdering(fc, span, "atomic.store", x.ord, &.{ .relaxed, .release, .seq_cst });
|
||||
},
|
||||
.atomic_rmw => |x| {
|
||||
const r = resultOf(fc, inst);
|
||||
if (r == .void) return fc.kindError(span, x.cell, "ref<atomic<T>>");
|
||||
if (r == .bool and (x.op == .add_wrap or x.op == .sub_wrap)) return fc.kindError(span, x.cell, "ref<atomic<T>> with an integer T");
|
||||
try fc.expectValue(span, x.value, r);
|
||||
try checkOrdering(fc, span, try std.fmt.allocPrint(fc.c.arena, "atomic.{s}", .{x.op.text()}), x.ord, &.{ .relaxed, .acquire, .release, .acq_rel, .seq_cst });
|
||||
},
|
||||
.atomic_cmpxchg => |x| {
|
||||
const r = resultOf(fc, inst);
|
||||
if (r == .void) return fc.kindError(span, x.cell, "ref<atomic<T>>");
|
||||
try fc.expectValue(span, x.expected, r);
|
||||
try fc.expectValue(span, x.desired, r);
|
||||
try checkOrdering(fc, span, "atomic.cmpxchg", x.success, &.{ .relaxed, .acquire, .release, .acq_rel, .seq_cst });
|
||||
// A failed compare-exchange is a read, never stronger than the
|
||||
// success ordering (spec 04 §24.1).
|
||||
const failure: []const air.Ordering = switch (x.success) {
|
||||
.relaxed, .release => &.{.relaxed},
|
||||
.acquire, .acq_rel => &.{ .relaxed, .acquire },
|
||||
.seq_cst => &.{ .relaxed, .acquire, .seq_cst },
|
||||
};
|
||||
try checkOrdering(fc, span, "atomic.cmpxchg failure", x.failure, failure);
|
||||
},
|
||||
.atomic_fence => |o| try checkOrdering(fc, span, "atomic.fence", o, &.{ .acquire, .release, .acq_rel, .seq_cst }),
|
||||
.cap_narrow => |x| {
|
||||
const t = fc.typeOf(x.cap);
|
||||
if (t != .cap) return fc.kindError(span, x.cap, "cap<K>");
|
||||
|
||||
Reference in new issue
Block a user