//! Borrow verification for frame storage (spec 08 §11). //! Reports E2101, E2102, E2105, E2106, E2107, E2108. //! //! Every borrow value has static provenance fixed at its definition (root, //! path, mode, parent). The only flow-sensitive state is the set of live //! owned borrows. It must be identical on every edge into a block (§11.4), //! so one walk over the reverse postorder decides each function. The walk //! covers blocks reachable from the entry block; other blocks never execute. const std = @import("std"); const air = @import("../air.zig"); const verifier = @import("../verifier.zig"); const ssa = @import("ssa.zig"); const diag = @import("../diag.zig"); const Context = verifier.Context; const ValueId = air.ValueId; /// One step of a path from a root (§11.2). const Seg = union(enum) { field: u32, /// One side of a `slice.split`, keyed by the split's left result. split: struct { key: ValueId, side: u1 }, /// An element or sub-range; overlaps every sibling. elem, /// A region allocation, keyed by its `ok` parameter; disjoint from /// every other allocation (spec 03 §20.2). alloc: ValueId, }; const Mode = enum { shared, exclusive }; const Loan = struct { task: ValueId, borrow: ValueId, root: ValueId, path: []const Seg, mode: Mode, /// Diagnostic provenance only; never participates in borrow/liveness state. spawn: air.Span, }; /// Why a resource is no longer live (spec 06 §6.3). const Dead = enum { none, closed, moved }; const Info = struct { /// Owned borrows are created in this function; lent ones are parameters. owned: bool, mode: Mode, /// A local (`local.alloc` result) or a lent parameter. root: ValueId, path: []const Seg, /// Owned borrow or lent parameter this borrow was derived from. parent: ?ValueId, }; pub fn check(c: *Context) !void { // Signatures first: a borrow return needs `from` (§11.3). for (c.module.functions) |f| { if (f.ret.isBorrow() and f.ret_from == null) { try c.report("E2102", f.span, "a function returning a borrow must name its source with `from`", &.{ .{ .name = "function", .value = .{ .str = f.name } }, }); } } if (c.diags.items.len != 0) return; for (c.module.functions, c.value_types) |f, types| try checkFunction(c, f, types); } const Walker = struct { c: *Context, f: air.Function, types: []const air.Type, info: []?Info, /// Live owned borrows and live owned resources at the current point. live: []bool, /// How a resource stopped being live, for diagnostics. dead: []Dead, /// Borrows lent to tasks (spec 04 §34). A loan is active while its task /// handle is live, so it is part of the per-path state through `live`. loans: std.ArrayList(Loan) = .empty, /// Scope of each task handle value. task_scope: []?ValueId, /// Number of shields live when each shield began (spec 04 §37.3). shield_depth: []u32, /// The `ref>` each guard was locked through (spec 04 §40). guard_parent: []?ValueId, block: u32 = 0, index: u32 = 0, span: air.Span = .{ .line = 0, .col = 0 }, fn name(w: *Walker, v: ValueId) ![]const u8 { return w.c.valueName(w.f, v); } fn report(w: *Walker, code: []const u8, message: []const u8, borrow: ValueId, extra: ?struct { []const u8, ValueId }) !void { return w.reportWithOrigin(code, message, borrow, extra, null); } fn reportWithOrigin(w: *Walker, code: []const u8, message: []const u8, borrow: ValueId, extra: ?struct { []const u8, ValueId }, spawn: ?air.Span) !void { if (extra) |e| { var related: [1]diag.RelatedLocation = undefined; const context: []const diag.RelatedLocation = if ((std.mem.eql(u8, code, "E2101") or std.mem.eql(u8, code, "E2104")) and std.mem.eql(u8, e[0], "conflicts_with")) blk: { const sp = w.f.values[e[1]].span; related[0] = .{ .role = .conflicting_borrow, .value = try w.name(e[1]), .span = .{ .file = w.c.file, .line = sp.line, .col = sp.col } }; break :blk &related; } else if (spawn) |sp| blk: { related[0] = .{ .role = .task_spawn, .value = try w.name(e[1]), .span = .{ .file = w.c.file, .line = sp.line, .col = sp.col } }; break :blk &related; } else &.{}; try w.c.reportRelated(code, w.span, message, &.{ .{ .name = "function", .value = .{ .str = w.f.name } }, .{ .name = "block", .value = .{ .str = w.f.blocks[w.block].name } }, .{ .name = "inst", .value = .{ .int = w.index } }, .{ .name = "borrow", .value = .{ .str = try w.name(borrow) } }, .{ .name = e[0], .value = .{ .str = try w.name(e[1]) } }, }, context); } else { try w.c.report(code, w.span, message, &.{ .{ .name = "function", .value = .{ .str = w.f.name } }, .{ .name = "block", .value = .{ .str = w.f.blocks[w.block].name } }, .{ .name = "inst", .value = .{ .int = w.index } }, .{ .name = "borrow", .value = .{ .str = try w.name(borrow) } }, }); } } fn isAncestor(w: *Walker, anc: ValueId, of: ValueId) bool { var x: ?ValueId = of; while (x) |v| { if (v == anc) return true; x = if (w.info[v]) |i| i.parent else null; } return false; } /// Checks that `v`, used as a borrow, has not been ended (E2106). fn usable(w: *Walker, v: ValueId) !bool { const i = w.info[v].?; if (!i.owned or w.live[v]) return true; try w.report("E2106", "borrow used after it was ended", v, null); return false; } /// An access to `path` under `root` with `mode`, performed through /// `through` (a borrow whose ancestors do not conflict) or directly on a /// local (`through == null`). Reports the first conflict (E2101). fn access(w: *Walker, root: ValueId, path: []const Seg, mode: Mode, via: ?ValueId, who: ValueId) !void { return w.accessCode(root, path, mode, via, who, "E2101", "conflicting borrow or access"); } fn accessCode(w: *Walker, root: ValueId, path: []const Seg, mode: Mode, via: ?ValueId, who: ValueId, code: []const u8, message: []const u8) !void { for (w.live, 0..) |is_live, cv| { if (!is_live) continue; const ci = w.info[cv] orelse continue; // live resources are not borrows if (ci.root != root) continue; if (via) |t| if (w.isAncestor(@intCast(cv), t)) continue; if (mode == .shared and ci.mode == .shared) continue; if (!overlap(path, ci.path)) continue; try w.report(code, message, who, .{ "conflicts_with", @intCast(cv) }); return; } // Borrows lent to live tasks are accessed concurrently (spec 04 §34). for (w.loans.items) |l| { if (!w.live[l.task] or l.root != root) continue; if (mode == .shared and l.mode == .shared) continue; if (!overlap(path, l.path)) continue; try w.report("E4101", "conflicts with a borrow lent to a live task", who, .{ "task", l.task }); return; } } /// Records a new owned borrow and checks it against live borrows. fn create(w: *Walker, v: ValueId, parent: ?ValueId, root: ValueId, path: []const Seg) !void { const mode: Mode = if (w.types[v].isMutBorrow()) .exclusive else .shared; w.info[v] = .{ .owned = true, .mode = mode, .root = root, .path = path, .parent = parent }; try w.access(root, path, mode, parent, v); w.live[v] = true; } /// Creates a borrow derived from borrow `p` with an extra path step. fn derive(w: *Walker, v: ValueId, p: ValueId, seg: ?Seg) !void { if (!try w.usable(p)) return w.poison(v, p); const pi = w.info[p].?; try w.create(v, p, pi.root, try w.extend(pi.path, seg)); } /// After an error, give `v` provenance so later uses do not cascade. fn poison(w: *Walker, v: ValueId, p: ValueId) void { const pi = w.info[p].?; w.info[v] = .{ .owned = true, .mode = .shared, .root = pi.root, .path = pi.path, .parent = p }; w.live[v] = true; } fn extend(w: *Walker, path: []const Seg, seg: ?Seg) ![]const Seg { const s = seg orelse return path; const out = try w.c.arena.alloc(Seg, path.len + 1); @memcpy(out[0..path.len], path); out[path.len] = s; return out; } /// Read or write through borrow `b` (load, store, slice.copy). fn useThrough(w: *Walker, b: ValueId, mode: Mode) !void { if (!try w.usable(b)) return; const bi = w.info[b].?; try w.access(bi.root, bi.path, mode, b, b); } fn isLocal(w: *Walker, v: ValueId) bool { return w.types[v] == .local; } /// Linear values: resources, owners and regions (spec 06 §6, spec 03 §19–§20). fn isResource(w: *Walker, v: ValueId) bool { return w.c.module.isLinearType(w.types[v]); } /// A non-consuming use of resource `v` (a borrow of it). fn resourceUsable(w: *Walker, v: ValueId) !bool { if (w.live[v]) return true; switch (w.dead[v]) { .closed => try w.report("E3001", "linear value used after it was closed, freed or destroyed", v, null), .moved => try w.report("E2001", "linear value used after its ownership was transferred", v, null), .none => try w.report("E3001", "linear value used before it is owned", v, null), } return false; } /// Consumes resource `v` by closing or by transfer (spec 06 §6.2). fn consume(w: *Walker, v: ValueId, how: Dead) !void { if (!w.live[v]) { return w.report("E2002", "linear value consumed twice", v, null); } // Consumption is an exclusive access to the whole resource. try w.access(v, &.{}, .exclusive, null, v); w.live[v] = false; w.dead[v] = how; } }; pub fn overlap(a: []const Seg, b: []const Seg) bool { for (a[0..@min(a.len, b.len)], b[0..@min(a.len, b.len)]) |x, y| { switch (x) { .field => |fx| if (y == .field) { if (fx != y.field) return false; continue; }, .split => |sx| if (y == .split and sx.key == y.split.key) { if (sx.side != y.split.side) return false; continue; }, .alloc => |ka| if (y == .alloc) { if (ka != y.alloc) return false; continue; }, .elem => {}, } return true; } return true; // one path is a prefix of the other } const Edge = struct { target: u32, args: []const ValueId }; fn edges(op: air.Op, out: *std.ArrayList(Edge), arena: std.mem.Allocator) !void { if (op.bufferTargets()) |t| { try out.append(arena, .{ .target = t.ok, .args = &.{} }); try out.append(arena, .{ .target = t.err, .args = &.{} }); return; } switch (op) { .br => |t| try out.append(arena, .{ .target = t.block, .args = t.args }), .cbr => |x| { try out.append(arena, .{ .target = x.then.block, .args = x.then.args }); try out.append(arena, .{ .target = x.@"else".block, .args = x.@"else".args }); }, .@"switch" => |x| { for (x.cases) |c| try out.append(arena, .{ .target = c.target.block, .args = c.target.args }); try out.append(arena, .{ .target = x.default.block, .args = x.default.args }); }, inline .enum_switch, .enum_take => |x| { for (x.arms) |a| try out.append(arena, .{ .target = a.block, .args = &.{} }); if (x.default) |d| try out.append(arena, .{ .target = d.block, .args = d.args }); }, .aggregate_unpack => |x| try out.append(arena, .{ .target = x.next, .args = &.{} }), .cap_narrow => |x| { try out.append(arena, .{ .target = x.ok, .args = &.{} }); try out.append(arena, .{ .target = x.err, .args = &.{} }); }, .intrinsic => |x| if (x.ok) |ok| { try out.append(arena, .{ .target = ok, .args = &.{} }); try out.append(arena, .{ .target = x.err.?, .args = &.{} }); }, inline .own_new, .own_pack, .own_array, .region_create, .region_new, .region_array, .island_create, .island_alloc, .arc_new => { const t = air.allocTargets(op).?; try out.append(arena, .{ .target = t.ok, .args = &.{} }); try out.append(arena, .{ .target = t.err, .args = &.{} }); }, // Values these terminators consume are consumed on every edge, by // `step`, before propagation; results arrive as block parameters. else => for (try air.waitTargets(op, arena)) |t| try out.append(arena, .{ .target = t.block, .args = &.{} }), } } fn checkFunction(c: *Context, f: air.Function, types: []const air.Type) !void { var w: Walker = .{ .c = c, .f = f, .types = types, .info = try c.arena.alloc(?Info, f.values.len), .live = try c.arena.alloc(bool, f.values.len), .dead = try c.arena.alloc(Dead, f.values.len), .task_scope = try c.arena.alloc(?ValueId, f.values.len), .shield_depth = try c.arena.alloc(u32, f.values.len), .guard_parent = try c.arena.alloc(?ValueId, f.values.len), }; @memset(w.task_scope, null); @memset(w.shield_depth, 0); @memset(w.guard_parent, null); @memset(w.info, null); @memset(w.live, false); @memset(w.dead, .none); for (f.params) |p| { if (p.ty.isBorrow()) w.info[p.value] = .{ .owned = false, .mode = if (p.ty.isMutBorrow()) .exclusive else .shared, .root = p.value, .path = &.{}, .parent = null, }; // Linear parameters were moved in: the function owns them (spec 06 §6.3). if (c.module.isLinearType(p.ty)) w.live[p.value] = true; } const dom = try ssa.dominators(c.arena, f); const entry_state = try c.arena.alloc(?[]bool, f.blocks.len); @memset(entry_state, null); entry_state[0] = try c.arena.dupe(bool, w.live); var reported_join = try c.arena.alloc(bool, f.blocks.len); @memset(reported_join, false); var out: std.ArrayList(Edge) = .empty; for (dom.rpo) |b| { @memcpy(w.live, entry_state[b].?); const blk = f.blocks[b]; // Linear block parameters own their argument from here on; the // parameter of a region allocation's `ok` target is a live borrow. for (blk.params) |p| if (c.module.isLinearType(p.ty) or (p.ty.isBorrow() and w.info[p.value] != null)) { w.live[p.value] = true; w.dead[p.value] = .none; }; w.block = b; for (blk.insts, 0..) |inst, ii| { w.index = @intCast(ii); w.span = inst.span; try step(&w, inst); } // Propagate along every edge; branch arguments of resource type are // moved on their own edge only (§11.4, spec 06 §6.2). out.clearRetainingCapacity(); try edges(blk.insts[blk.insts.len - 1].op, &out, c.arena); const base = try c.arena.dupe(bool, w.live); const base_dead = try c.arena.dupe(Dead, w.dead); for (out.items) |e| { @memcpy(w.live, base); @memcpy(w.dead, base_dead); for (e.args) |a| if (c.module.isLinearType(types[a])) try w.consume(a, .moved); // A linear parameter of the target that is still live on this // edge would be overwritten: that instance leaks. Parameters are // not part of the incoming state; they come alive in the block. for (f.blocks[e.target].params) |p| { if (c.module.isLinearType(p.ty) and w.live[p.value]) try w.report("E3002", "linear value not consumed before it is redefined", p.value, null); w.live[p.value] = false; } if (entry_state[e.target]) |expected| { if (!std.mem.eql(bool, expected, w.live) and !reported_join[e.target]) { reported_join[e.target] = true; for (expected, w.live, 0..) |a, x, v| if (a != x) { const is_res = c.module.isLinearType(types[v]); try c.report(if (is_res) "E3002" else "E2105", f.blocks[e.target].span, if (is_res) "resource state differs between edges into this block" else "borrow state differs between edges into this block", &.{ .{ .name = "function", .value = .{ .str = f.name } }, .{ .name = "block", .value = .{ .str = f.blocks[e.target].name } }, .{ .name = if (is_res) "resource" else "borrow", .value = .{ .str = try c.valueName(f, @intCast(v)) } }, }); break; }; } } else entry_state[e.target] = try c.arena.dupe(bool, w.live); } } } fn step(w: *Walker, inst: air.Inst) !void { const f = w.f; switch (inst.op) { .local_store => |x| try w.access(x.local, &.{}, .exclusive, null, x.local), .local_zero => |v| try w.access(v, &.{}, .exclusive, null, v), .local_load => |v| try w.access(v, &.{}, .shared, null, v), .borrow_ref, .borrow_mut => |x| { const r = inst.result.?; if (w.isLocal(x)) { try w.create(r, null, x, &.{}); } else if (w.isResource(x)) { if (!try w.resourceUsable(x)) { w.info[r] = .{ .owned = true, .mode = .shared, .root = x, .path = &.{}, .parent = null }; w.live[r] = true; return; } try w.create(r, null, x, &.{}); } else try w.derive(r, x, null); }, .borrow_field => |x| try w.derive(inst.result.?, x.borrow, .{ .field = x.field }), .borrow_index => |x| try w.derive(inst.result.?, x.borrow, .elem), .buffer_view, .slice_make => |v| try w.derive(inst.result.?, v, null), .slice_sub => |x| try w.derive(inst.result.?, x.slice, .elem), .slice_split => |x| { const l = inst.result.?; try w.derive(l, x.slice, .{ .split = .{ .key = l, .side = 0 } }); try w.derive(inst.result2.?, x.slice, .{ .split = .{ .key = l, .side = 1 } }); }, .slice_len => |v| _ = try w.usable(v), // metadata: no access to elements .load => |v| try w.useThrough(v, .shared), .store => |x| try w.useThrough(x.borrow, .exclusive), .slice_copy => |x| { try w.useThrough(x.src, .shared); try w.useThrough(x.dst, .exclusive); }, .borrow_end => |v| { const i = w.info[v].?; if (!i.owned) return w.report("E2107", "a borrow parameter is lent by the caller and cannot be ended", v, null); if (!w.live[v]) return w.report("E2106", "borrow ended twice", v, null); // Ended even when rejected, so one mistake yields one diagnostic. defer w.live[v] = false; for (w.loans.items) |l| if (w.live[l.task] and (l.borrow == v or w.isAncestor(v, l.borrow))) { return w.reportWithOrigin("E4302", "borrow ended while it is lent to a live task", v, .{ "task", l.task }, l.spawn); }; for (w.live, 0..) |is_live, g| if (is_live and w.guard_parent[g] != null and w.isAncestor(v, w.guard_parent[g].?)) { return w.report("E2102", "mutex borrow ended while a guard locked through it is live", v, .{ "guard", @intCast(g) }); }; for (w.live, 0..) |is_live, cv| { if (is_live and w.info[cv] != null and w.info[cv].?.parent == v) { return w.report("E2102", "borrow ended while a borrow derived from it is live", v, .{ "child", @intCast(cv) }); } } }, .call => |x| { try lendArgs(w, x.args); const callee = w.c.module.functions[x.callee]; for (callee.effects) |e| if (std.mem.eql(u8, e, "task.wait") or std.mem.eql(u8, e, "task.spawn")) { try noWaitUnderLock(w, "call of a function that may wait or spawn"); break; }; for (x.args) |a| if (w.isResource(a)) try w.consume(a, .moved); if (callee.ret_from) |p| { // The result borrows from the argument passed for `from` (§11.3). const a = x.args[p]; if (w.types[a].isBorrow() and w.info[a] != null) try w.derive(inst.result.?, a, .elem); } if (inst.result) |r| if (w.isResource(r)) { w.live[r] = true; }; }, inline .struct_make, .enum_make, .array_make => |x| { for (x.args) |v| if (w.isResource(v)) try w.consume(v, .moved); if (inst.result) |r| { if (w.isResource(r)) w.live[r] = true; } }, .struct_get => |x| { if (w.isResource(x.a)) { _ = try w.resourceUsable(x.a); try w.access(x.a, &.{.{ .field = x.field }}, .shared, null, x.a); } }, .aggregate_unpack => |x| { if (w.isResource(x.value)) try w.consume(x.value, .moved); }, .enum_take => |x| { if (w.isResource(x.value)) try w.consume(x.value, .moved); }, .buffer_new => {}, .buffer_len, .buffer_capacity => |v| try w.useThrough(v, .shared), .buffer_reserve => |x| try w.useThrough(x.borrow, .exclusive), .buffer_push => |x| { try w.useThrough(x.borrow, .exclusive); if (w.isResource(x.value)) try w.consume(x.value, .moved); }, .buffer_pop => |x| try w.useThrough(x.value, .exclusive), .buffer_free => |x| try w.consume(x.value, .moved), .own_pack => |x| { if (w.isResource(x.value)) try w.consume(x.value, .moved); }, .value_swap => |x| { try w.useThrough(x.borrow, .exclusive); if (w.isResource(x.value)) try w.consume(x.value, .moved); if (inst.result) |r| { if (w.isResource(r)) w.live[r] = true; } }, .own_free, .own_take => |v| { try w.consume(v, .closed); if (inst.result) |r| { if (w.isResource(r)) w.live[r] = true; } }, .task_scope_begin => w.live[inst.result.?] = true, .task_spawn => |x| { try noWaitUnderLock(w, "task.spawn"); const t = inst.result.?; w.task_scope[t] = x.scope; for (x.args) |a| { if (w.types[a].isBorrow()) { if (!try w.usable(a)) continue; const ai = w.info[a].?; // The loan must not conflict with live borrows or loans. try w.accessCode(ai.root, ai.path, ai.mode, a, a, "E4101", "lending a borrow that conflicts with a live borrow"); try w.loans.append(w.c.arena, .{ .task = t, .borrow = a, .root = ai.root, .path = ai.path, .mode = ai.mode, .spawn = inst.span }); } else if (w.isResource(a)) try w.consume(a, .moved); } w.live[t] = true; }, .task_join => |t| { try noWaitUnderLock(w, "task.join"); // Joining ends the task's loans (they are active only while `t` lives). try w.consume(t, .closed); if (inst.result) |r| if (w.isResource(r)) { w.live[r] = true; }; }, .task_cancel => |t| _ = try w.resourceUsable(t), .task_scope_end => |s| { for (w.live, 0..) |is_live, v| { if (is_live and w.task_scope[v] != null and w.task_scope[v].? == s) { try w.report("E4301", "scope ends while a task spawned from it is not joined", @intCast(v), .{ "scope", s }); w.live[v] = false; // reported once, in preference to E3002 } } try w.consume(s, .closed); }, .region_reset => |v| { if (!try w.resourceUsable(v)) return; // Reset invalidates the generation: no reference may be live. try w.accessCode(v, &.{}, .exclusive, null, v, "E2104", "region reset would invalidate a live reference into the region"); }, .region_destroy => |v| { if (w.live[v]) try w.accessCode(v, &.{}, .exclusive, null, v, "E2104", "region destroy would invalidate a live reference into the region"); if (!w.live[v]) return w.report("E2002", "linear value consumed twice", v, null); w.live[v] = false; w.dead[v] = .closed; }, .region_new, .region_array => { const rb = switch (inst.op) { .region_new => |x| x.region, .region_array => |x| x.region, else => unreachable, }; if (!try w.usable(rb)) return; // The allocation is a fresh exclusive child of the shared region // borrow; it comes alive on the `ok` edge (spec 03 §20.2). const ok = air.allocTargets(inst.op).?.ok; const p = w.f.blocks[ok].params[0].value; const ri = w.info[rb].?; w.info[p] = .{ .owned = true, .mode = .exclusive, .root = ri.root, .path = try w.extend(ri.path, .{ .alloc = p }), .parent = rb }; }, .intrinsic => |x| { try lendArgs(w, x.args); // Closing intrinsics consume on both edges, so before propagation. for (x.args, air.authority.intrinsics[x.index].operands) |a, o| if (o == .consumed) try w.consume(a, .closed); }, .ret => |v| try retStep(w, v), .task_join_cancel => |x| { try noWaitUnderLock(w, "task.join.cancel"); const t = x.task; const back = w.f.blocks[x.cancelled].params[0].value; // On `cancelled` the same task comes back: its scope and loans // move to the new handle value (spec 04 §37.3). w.task_scope[back] = w.task_scope[t]; const n = w.loans.items.len; for (0..n) |i| { const l = w.loans.items[i]; if (l.task == t) { var transferred = l; transferred.task = back; try w.loans.append(w.c.arena, transferred); } } try w.consume(t, .closed); }, .task_shield_begin => { const r = inst.result.?; var depth: u32 = 0; for (w.live, 0..) |is_live, v| depth += @intFromBool(is_live and w.types[v] == .shield); w.shield_depth[r] = depth; w.live[r] = true; }, .task_shield_end => |sh| { if (w.live[sh]) for (w.live, 0..) |is_live, v| if (is_live and w.types[v] == .shield and w.shield_depth[v] > w.shield_depth[sh]) { try w.report("E4305", "shield ended while a more inner shield is live", sh, .{ "inner", @intCast(v) }); break; }; try w.consume(sh, .closed); }, .channel_dup => |v| { try lendArgs(w, &.{v}); w.live[inst.result.?] = true; }, .channel_send => |x| { try noWaitUnderLock(w, "channel.send"); try lendArgs(w, &.{x.sender}); if (w.isResource(x.value)) try w.consume(x.value, .moved); }, .channel_recv => |x| { try noWaitUnderLock(w, "channel.recv"); try lendArgs(w, &.{x.receiver}); }, .channel_close_sender => |v| try w.consume(v, .closed), .channel_close_receiver => |x| try w.consume(x.receiver, .closed), .select => |x| { try noWaitUnderLock(w, "select"); // Only one arm runs, so arms may name the same endpoint borrow. for (x.arms, 0..) |arm, i| { const seen = for (x.arms[0..i]) |prev| { if (prev.endpoint == arm.endpoint) break true; } else false; if (!seen) try lendArgs(w, &.{arm.endpoint}); } const buf = try w.c.arena.alloc(ValueId, x.arms.len); for (air.Op.selectValues(x.arms, buf)) |v| if (w.isResource(v)) try w.consume(v, .moved); }, .mutex_make => |v| { if (w.isResource(v)) try w.consume(v, .moved); 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; }, .mutex_lock => |x| { try noWaitUnderLock(w, "mutex.lock"); try lendArgs(w, &.{x.mutex}); w.guard_parent[w.f.blocks[x.ok].params[0].value] = x.mutex; }, .mutex_borrow => |g| { const r = inst.result.?; if (!try w.resourceUsable(g)) { w.info[r] = .{ .owned = true, .mode = .exclusive, .root = g, .path = &.{}, .parent = null }; w.live[r] = true; return; } try w.create(r, null, g, &.{}); }, .mutex_unlock => |g| { if (!w.live[g]) return w.report("E2002", "linear value consumed twice", g, null); for (w.live, 0..) |is_live, b| if (is_live and w.info[b] != null and w.info[b].?.root == g) { try w.report("E2102", "guard unlocked while a borrow from it is live", @intCast(b), .{ "guard", g }); break; }; w.live[g] = false; w.dead[g] = .closed; }, // Graphs (spec 03 §22–§24). An access is a child borrow of the // container borrow; a `mut` child is exclusive for the whole island. .island_alloc => |x| try w.useThrough(x.island, .exclusive), .island_root, .frozen_root, .arc_root => |v| _ = try w.usable(v), inline .island_borrow, .frozen_borrow, .arc_borrow => |x| try w.derive(inst.result.?, x.owner, .elem), .island_freeze, .arc_from_frozen => |v| { try w.consume(v, .moved); w.live[inst.result.?] = true; }, .island_destroy, .frozen_release, .arc_release => |v| try w.consume(v, .closed), .arc_clone => |v| { 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 => {}, } _ = 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 { for (w.live, 0..) |is_live, g| if (is_live and w.types[g] == .guard) { return w.c.report("E4304", w.span, "operation that may wait or spawn while a lock guard is live", &.{ .{ .name = "function", .value = .{ .str = w.f.name } }, .{ .name = "block", .value = .{ .str = w.f.blocks[w.block].name } }, .{ .name = "inst", .value = .{ .int = w.index } }, .{ .name = "guard", .value = .{ .str = try w.name(@intCast(g)) } }, .{ .name = "op", .value = .{ .str = op } }, }); }; } /// Borrow arguments of a call or intrinsic are lent for its duration and /// must not alias each other when one is exclusive (§11.2). fn lendArgs(w: *Walker, args: []const ValueId) !void { // Arguments already reported; a conflict involving one of them is the // same mistake and is not reported again. const reported = try w.c.arena.alloc(bool, args.len); @memset(reported, false); for (args, 0..) |a, i| { if (!w.types[a].isBorrow()) continue; if (!try w.usable(a)) continue; const ai = w.info[a].?; // The argument is lent for the call: checked like a use of `a`. const before = w.c.diags.items.len; try w.access(ai.root, ai.path, ai.mode, a, a); if (w.c.diags.items.len != before) { reported[i] = true; continue; } // Arguments must not alias each other if either is exclusive (§11.2). for (args[0..i], 0..) |b, j| { if (reported[j]) continue; if (!w.types[b].isBorrow()) continue; const bi = w.info[b].?; if (bi.root != ai.root) continue; if (ai.mode == .shared and bi.mode == .shared) continue; if (overlap(ai.path, bi.path)) { try w.report("E2101", "call arguments alias and one of them is exclusive", a, .{ "conflicts_with", b }); break; } } } } fn retStep(w: *Walker, value: ?ValueId) !void { const f = w.f; var transferred: ?ValueId = null; if (value) |v| if (w.isResource(v)) try w.consume(v, .moved); if (f.ret_from) |p| { const pv = f.params[p].value; const b = value.?; if (!try w.usable(b)) return; const bi = w.info[b].?; if (bi.root != pv) { if (w.isLocal(bi.root)) { return w.report("E2108", "borrow of frame storage escapes its function", b, .{ "local", bi.root }); } return w.report("E2102", "returned borrow does not derive from the `from` parameter", b, .{ "from", pv }); } transferred = b; } // Only the returned borrow and its owned ancestors may remain live. for (w.live, 0..) |is_live, v| { if (!is_live) continue; if (transferred) |t| if (w.isAncestor(@intCast(v), t)) continue; if (w.isResource(@intCast(v))) { try w.report("E3002", "resource not consumed before return", @intCast(v), null); } else try w.report("E2105", "borrow not ended before return", @intCast(v), null); } } // ---------------------------------------------------------------- tests const h = "module t\nair 0\nlang 0.1\nfeatures [arrays, ownership]\n"; fn fun(comptime sig: []const u8, comptime body: []const u8) []const u8 { return h ++ "fn @f" ++ sig ++ "\neffects []\nentry:\n" ++ body; } const local_x = " %x = local.alloc u8\n local.zero %x\n"; test "exclusive XOR shared" { try verifier.expectCodes(comptime fun("() -> void", local_x ++ " %a = borrow.mut %x\n %b = borrow.ref %x\n borrow.end %b\n borrow.end %a\n ret\n"), &.{"E2101"}); try verifier.expectCodes(comptime fun("() -> void", local_x ++ " %a = borrow.ref %x\n %b = borrow.ref %x\n borrow.end %b\n borrow.end %a\n ret\n"), &.{}); try verifier.expectCodes(comptime fun("() -> void", local_x ++ " %a = borrow.ref %x\n %one = const.u8 1\n local.store %x, %one\n borrow.end %a\n ret\n"), &.{"E2101"}); try verifier.expectCodes(comptime fun("() -> u8", local_x ++ " %a = borrow.ref %x\n %v = local.load %x\n borrow.end %a\n ret %v\n"), &.{}); try verifier.expectCodes(comptime fun("() -> u8", local_x ++ " %a = borrow.mut %x\n %v = local.load %x\n borrow.end %a\n ret %v\n"), &.{"E2101"}); } test "reborrow freezes the parent" { // Reading through a mut borrow while a shared child is live is fine; // writing is not. try verifier.expectCodes(comptime fun("() -> u8", local_x ++ " %m = borrow.mut %x\n %r = borrow.ref %m\n %v = load %m\n borrow.end %r\n borrow.end %m\n ret %v\n"), &.{}); try verifier.expectCodes(comptime fun("() -> void", local_x ++ " %m = borrow.mut %x\n %r = borrow.ref %m\n %z = const.u8 0\n store %m, %z\n borrow.end %r\n borrow.end %m\n ret\n"), &.{"E2101"}); try verifier.expectCodes(comptime fun("() -> void", local_x ++ " %m = borrow.mut %x\n %r = borrow.ref %m\n borrow.end %m\n borrow.end %r\n ret\n"), &.{"E2102"}); } test "fields and split halves are disjoint" { const s = h ++ "type @P = struct { a: u8, b: u8 }\n"; try verifier.expectCodes(s ++ "fn @f() -> void\neffects []\nentry:\n %x = local.alloc @P\n local.zero %x\n %m = borrow.mut %x\n %fa = borrow.field @P.a, %m\n %fb = borrow.field @P.b, %m\n borrow.end %fa\n borrow.end %fb\n borrow.end %m\n ret\n", &.{}); try verifier.expectCodes(s ++ "fn @f() -> void\neffects []\nentry:\n %x = local.alloc @P\n local.zero %x\n %m = borrow.mut %x\n %fa = borrow.field @P.a, %m\n %fb = borrow.field @P.a, %m\n borrow.end %fa\n borrow.end %fb\n borrow.end %m\n ret\n", &.{"E2101"}); const arr = " %x = local.alloc array\n local.zero %x\n %m = borrow.mut %x\n %s = slice.make %m\n %k = const.usize 4\n %l, %r = slice.split %s, %k\n"; const ends = " borrow.end %l\n borrow.end %r\n borrow.end %s\n borrow.end %m\n ret\n"; try verifier.expectCodes(comptime fun("() -> void", arr ++ " %lr = borrow.ref %l\n slice.copy %r, %lr\n borrow.end %lr\n" ++ ends), &.{}); // Two element borrows of the same parent overlap. try verifier.expectCodes(comptime fun("() -> void", arr ++ " %z = const.usize 0\n %e1 = borrow.index %l, %z\n %e2 = borrow.index %l, %z\n borrow.end %e1\n borrow.end %e2\n" ++ ends), &.{"E2101"}); // slice.copy within one slice: source and destination overlap. try verifier.expectCodes(comptime fun("() -> void", arr ++ " %lr = borrow.ref %l\n slice.copy %l, %lr\n borrow.end %lr\n" ++ ends), &.{"E2101"}); } test "path linearity" { try verifier.expectCodes(comptime fun("(%c: bool) -> void", local_x ++ " %a = borrow.ref %x\n cbr %c, @p(), @q()\np:\n borrow.end %a\n ret\nq:\n borrow.end %a\n ret\n"), &.{}); try verifier.expectCodes(comptime fun("(%c: bool) -> void", local_x ++ " %a = borrow.ref %x\n cbr %c, @p(), @q()\np:\n borrow.end %a\n ret\nq:\n ret\n"), &.{"E2105"}); try verifier.expectCodes(comptime fun("(%c: bool) -> void", local_x ++ " %a = borrow.ref %x\n cbr %c, @p(), @q()\np:\n borrow.end %a\n br @j()\nq:\n br @j()\nj:\n ret\n"), &.{ "E2105", "E2105" }); try verifier.expectCodes(comptime fun("() -> void", local_x ++ " %a = borrow.ref %x\n borrow.end %a\n borrow.end %a\n ret\n"), &.{"E2106"}); try verifier.expectCodes(comptime fun("() -> u8", local_x ++ " %a = borrow.ref %x\n borrow.end %a\n %v = load %a\n ret %v\n"), &.{"E2106"}); // trap paths carry no obligation. try verifier.expectCodes(comptime fun("() -> void", local_x ++ " %a = borrow.ref %x\n trap\n"), &.{}); } test "loops end their borrows before the back edge" { try verifier.expectCodes(comptime fun("(%c: bool) -> void", local_x ++ " br @loop()\nloop:\n %a = borrow.ref %x\n borrow.end %a\n cbr %c, @loop(), @out()\nout:\n ret\n"), &.{}); try verifier.expectCodes(comptime fun("(%c: bool) -> void", local_x ++ " br @loop()\nloop:\n %a = borrow.ref %x\n cbr %c, @loop(), @out()\nout:\n borrow.end %a\n ret\n"), &.{"E2105"}); } test "returning borrows" { try verifier.expectCodes(h ++ "fn @first(%s: slice) -> ref from %s\neffects []\nentry:\n %z = const.usize 0\n %e = borrow.index %s, %z\n ret %e\n", &.{}); try verifier.expectCodes(h ++ "fn @f(%s: slice) -> ref\neffects []\nentry:\n %z = const.usize 0\n %e = borrow.index %s, %z\n ret %e\n", &.{"E2102"}); try verifier.expectCodes(h ++ "fn @f(%p: ref) -> ref from %p\neffects []\nentry:\n" ++ local_x ++ " %b = borrow.ref %x\n ret %b\n", &.{"E2108"}); try verifier.expectCodes(h ++ "fn @f(%p: ref, %q: ref) -> ref from %p\neffects []\nentry:\n %b = borrow.ref %q\n ret %b\n", &.{"E2102"}); try verifier.expectCodes(h ++ "fn @f(%p: ref) -> void\neffects []\nentry:\n borrow.end %p\n ret\n", &.{"E2107"}); } test "call results keep their source alive; mut arguments do not alias" { const first = "fn @first(%s: slice) -> ref from %s\neffects []\nentry:\n %z = const.usize 0\n %e = borrow.index %s, %z\n ret %e\n"; const caller = "fn @f() -> u8\neffects []\nentry:\n %x = local.alloc array\n local.zero %x\n %r = borrow.ref %x\n %s = slice.make %r\n %e = call @first(%s)\n"; try verifier.expectCodes(h ++ caller ++ " %v = load %e\n borrow.end %e\n borrow.end %s\n borrow.end %r\n ret %v\n" ++ first, &.{}); try verifier.expectCodes(h ++ caller ++ " borrow.end %s\n %v = load %e\n borrow.end %e\n borrow.end %r\n ret %v\n" ++ first, &.{"E2102"}); const two = "fn @g(%a: mut, %b: ref) -> void\neffects []\nentry:\n ret\n"; try verifier.expectCodes(h ++ "fn @f() -> void\neffects []\nentry:\n" ++ local_x ++ " %m = borrow.mut %x\n %r = borrow.ref %m\n call @g(%m, %r)\n borrow.end %r\n borrow.end %m\n ret\n" ++ two, &.{"E2101"}); }