镜像站点 · 本页由第三方 GitHub 只读镜像提供,非 GitHub 官方站点,不接受任何登录或凭据输入。前往 github.com
Skip to content

Commit baf5ed9

Browse files
committed
perf(vm): compile synchronized self recurrences (#49)
1 parent e7bc293 commit baf5ed9

1 file changed

Lines changed: 168 additions & 32 deletions

File tree

‎src/vm.zig‎

Lines changed: 168 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -661,6 +661,7 @@ const QuickObservableAddRecurrence = struct {
661661
second_binding_instruction: u32,
662662
counter_read_instruction: u32,
663663
counter_write_instruction: u32,
664+
counter_name: u32,
664665
counter_increment: f64,
665666
};
666667

@@ -1039,6 +1040,7 @@ fn compileQuickObservableRecurrencePlan(chunk: *Chunk) ?QuickObservableAddRecurr
10391040
.second_binding_instruction = 19,
10401041
.counter_read_instruction = 2,
10411042
.counter_write_instruction = 5,
1043+
.counter_name = code[2].a,
10421044
.counter_increment = counter_increment.asNum(),
10431045
};
10441046
}
@@ -1072,11 +1074,21 @@ fn compileQuickRecurrencePlan(chunk: *Chunk) QuickRecurrencePlan {
10721074
} };
10731075
}
10741076

1075-
fn quickRecurrencePlan(chunk: *Chunk) ?*QuickRecurrencePlan {
1076-
if (chunk.quick_recurrence_plan) |raw| return @ptrCast(@alignCast(raw));
1077+
fn quickRecurrencePlan(chunk: *Chunk, parallel_sync: bool) ?*QuickRecurrencePlan {
1078+
if (parallel_sync) {
1079+
if (@atomicLoad(?*anyopaque, &chunk.quick_recurrence_plan, .acquire)) |raw|
1080+
return @ptrCast(@alignCast(raw));
1081+
} else if (chunk.quick_recurrence_plan) |raw| {
1082+
return @ptrCast(@alignCast(raw));
1083+
}
10771084
const plan = chunk.arena.create(QuickRecurrencePlan) catch return null;
10781085
plan.* = compileQuickRecurrencePlan(chunk);
1079-
chunk.quick_recurrence_plan = plan;
1086+
if (parallel_sync) {
1087+
if (@cmpxchgStrong(?*anyopaque, &chunk.quick_recurrence_plan, null, plan, .acq_rel, .acquire)) |published|
1088+
return @ptrCast(@alignCast(published));
1089+
} else {
1090+
chunk.quick_recurrence_plan = plan;
1091+
}
10801092
return plan;
10811093
}
10821094

@@ -1141,7 +1153,81 @@ fn runQuickObservableRecurrence(
11411153
return first + second;
11421154
}
11431155

1144-
inline fn quickRecurrenceCalleeMatches(vm: *Interpreter, chunk: *Chunk, instruction: u32, func: *Function) bool {
1156+
fn quickParallelCounterRead(vm: *Interpreter, state: *value.Object, name: []const u8) EvalError!Value {
1157+
state.lockProperties();
1158+
if (!state.is_array and state.proxy_handler == null and !state.proxy_revoked and
1159+
state.accessors.load(.monotonic) == null and state.attrsMap() == null)
1160+
{
1161+
if (state.shape) |shape| if (shape.lookup(name)) |slot| if (slot < state.slots.items.len) {
1162+
const result = state.slots.items[slot];
1163+
state.unlockProperties();
1164+
return result;
1165+
};
1166+
}
1167+
state.unlockProperties();
1168+
return vm.getProperty(Value.obj(state), name);
1169+
}
1170+
1171+
fn quickParallelCounterWrite(vm: *Interpreter, state: *value.Object, name: []const u8, updated: Value) EvalError!void {
1172+
state.lockProperties();
1173+
if (!state.is_array and state.proxy_handler == null and !state.proxy_revoked and
1174+
state.accessors.load(.monotonic) == null and state.attrsMap() == null)
1175+
{
1176+
if (state.shape) |shape| if (shape.lookup(name)) |slot| if (slot < state.slots.items.len) {
1177+
gc_mod.barrierValueFrom(state, updated);
1178+
state.slots.items[slot] = updated;
1179+
state.unlockProperties();
1180+
return;
1181+
};
1182+
}
1183+
state.unlockProperties();
1184+
try vm.setMember(Value.obj(state), name, updated);
1185+
}
1186+
1187+
fn runQuickObservableRecurrenceParallel(
1188+
vm: *Interpreter,
1189+
recurrence: QuickObservableAddRecurrence,
1190+
state: *value.Object,
1191+
counter_name: []const u8,
1192+
input: u16,
1193+
) EvalError!f64 {
1194+
try advanceQuickObservableSteps(vm, 3); // through get_prop
1195+
const current = try quickParallelCounterRead(vm, state, counter_name);
1196+
try advanceQuickObservableSteps(vm, 2); // constant + add
1197+
const increment = Value.num(recurrence.counter_increment);
1198+
const updated = if (current.isNumber())
1199+
Value.num(current.asNum() + recurrence.counter_increment)
1200+
else
1201+
try vm.applyBinary(.add, current, increment);
1202+
try advanceQuickObservableSteps(vm, 1); // set_prop
1203+
try quickParallelCounterWrite(vm, state, counter_name, updated);
1204+
try advanceQuickObservableSteps(vm, 5); // pop + condition + branch
1205+
if (input < recurrence.threshold) {
1206+
try advanceQuickObservableSteps(vm, 3);
1207+
return @floatFromInt(input);
1208+
}
1209+
1210+
try advanceQuickObservableSteps(vm, 6);
1211+
const first = try runQuickObservableRecurrenceParallel(vm, recurrence, state, counter_name, input - recurrence.first_delta);
1212+
try advanceQuickObservableSteps(vm, 6);
1213+
const second = try runQuickObservableRecurrenceParallel(vm, recurrence, state, counter_name, input - recurrence.second_delta);
1214+
try advanceQuickObservableSteps(vm, 2);
1215+
return first + second;
1216+
}
1217+
1218+
inline fn quickRecurrenceCalleeMatches(vm: *Interpreter, chunk: *Chunk, instruction: u32, func: *Function, parallel_sync: bool) bool {
1219+
if (instruction < chunk.code.items.len) {
1220+
const name_index = chunk.code.items[instruction].a;
1221+
if (name_index < chunk.names.items.len) {
1222+
const name = chunk.names.items[name_index];
1223+
if (func.closure.isFnName(name)) {
1224+
const live = func.closure.getLocal(name) orelse return false;
1225+
const function_object = func.obj orelse return false;
1226+
return live.isObject() and live.asObj() == function_object;
1227+
}
1228+
}
1229+
}
1230+
if (parallel_sync) return false;
11451231
const live = quickGlobalBindingValue(chunk, instruction, vm) orelse return false;
11461232
const function_object = func.obj orelse return false;
11471233
return live.isObject() and live.asObj() == function_object;
@@ -1155,15 +1241,15 @@ fn quickRecurrenceNeededDepth(input: u16, threshold: u16, first_delta: u16, seco
11551241
@as(u32, (input - threshold) / minimum_delta) + 2;
11561242
}
11571243

1158-
fn tryQuickNumericRecurrence(vm: *Interpreter, func: *Function, args: []const Value) EvalError!?Value {
1244+
fn tryQuickNumericRecurrence(vm: *Interpreter, func: *Function, args: []const Value, parallel_sync: bool) EvalError!?Value {
11591245
const chunk = func.chunk orelse return null;
1160-
const plan = quickRecurrencePlan(chunk) orelse return null;
1246+
const plan = quickRecurrencePlan(chunk, parallel_sync) orelse return null;
11611247
return switch (plan.*) {
11621248
.unsupported => null,
11631249
.add => |recurrence| pure: {
11641250
if (args.len == 0) break :pure null;
11651251
const input = exactU16(args[0], true) orelse break :pure null;
1166-
if (input > 255 or !quickRecurrenceCalleeMatches(vm, chunk, recurrence.binding_instruction, func))
1252+
if (input > 255 or !quickRecurrenceCalleeMatches(vm, chunk, recurrence.binding_instruction, func, parallel_sync))
11671253
break :pure null;
11681254
const needed_depth = quickRecurrenceNeededDepth(input, recurrence.threshold, recurrence.first_delta, recurrence.second_delta);
11691255
if (vm.depth + needed_depth > interp.max_call_depth) break :pure null;
@@ -1190,20 +1276,38 @@ fn tryQuickNumericRecurrence(vm: *Interpreter, func: *Function, args: []const Va
11901276
if (args.len < 2) break :observable null;
11911277
const input = exactU16(args[0], true) orelse break :observable null;
11921278
if (input > 255 or
1193-
!quickRecurrenceCalleeMatches(vm, chunk, recurrence.first_binding_instruction, func) or
1194-
!quickRecurrenceCalleeMatches(vm, chunk, recurrence.second_binding_instruction, func))
1195-
break :observable null;
1196-
const state = quickPlainObject(args[1]) orelse break :observable null;
1197-
if (state.proxy_handler != null or state.proxy_revoked or state.is_symbol or state.is_bigint)
1279+
!quickRecurrenceCalleeMatches(vm, chunk, recurrence.first_binding_instruction, func, parallel_sync) or
1280+
!quickRecurrenceCalleeMatches(vm, chunk, recurrence.second_binding_instruction, func, parallel_sync))
11981281
break :observable null;
1199-
const read_slot = quickPropertySlot(chunk, recurrence.counter_read_instruction, state) orelse break :observable null;
1200-
const write_slot = quickPropertySlot(chunk, recurrence.counter_write_instruction, state) orelse break :observable null;
1201-
if (read_slot != write_slot or quickSlotNumber(state, read_slot) == null) break :observable null;
1282+
if (!args[1].isObject()) break :observable null;
1283+
const state = args[1].asObj();
1284+
if (state.is_symbol or state.is_bigint) break :observable null;
12021285
const needed_depth = quickRecurrenceNeededDepth(input, recurrence.threshold, recurrence.first_delta, recurrence.second_delta);
12031286
if (needed_depth > inline_call_depth_limit or vm.depth + needed_depth > interp.max_call_depth)
12041287
break :observable null;
12051288

1206-
const result = try runQuickObservableRecurrence(vm, recurrence, state, read_slot, input);
1289+
const result = if (parallel_sync) parallel: {
1290+
if (recurrence.first_binding_instruction >= chunk.code.items.len) break :observable null;
1291+
const self_name = chunk.code.items[recurrence.first_binding_instruction].a;
1292+
if (self_name >= chunk.names.items.len or !func.closure.isFnName(chunk.names.items[self_name]))
1293+
break :observable null;
1294+
if (recurrence.counter_name >= chunk.names.items.len) break :observable null;
1295+
break :parallel try runQuickObservableRecurrenceParallel(
1296+
vm,
1297+
recurrence,
1298+
state,
1299+
chunk.names.items[recurrence.counter_name],
1300+
input,
1301+
);
1302+
} else isolated: {
1303+
const plain_state = quickPlainObject(args[1]) orelse break :observable null;
1304+
if (plain_state.proxy_handler != null or plain_state.proxy_revoked or plain_state.is_symbol or plain_state.is_bigint)
1305+
break :observable null;
1306+
const read_slot = quickPropertySlot(chunk, recurrence.counter_read_instruction, plain_state) orelse break :observable null;
1307+
const write_slot = quickPropertySlot(chunk, recurrence.counter_write_instruction, plain_state) orelse break :observable null;
1308+
if (read_slot != write_slot or quickSlotNumber(plain_state, read_slot) == null) break :observable null;
1309+
break :isolated try runQuickObservableRecurrence(vm, recurrence, plain_state, read_slot, input);
1310+
};
12071311
if (builtin.is_test) _ = quick_observable_recurrence_hits.fetchAdd(1, .monotonic);
12081312
break :observable Value.num(result);
12091313
},
@@ -2451,22 +2555,20 @@ fn runChunk(vm: *Interpreter, exec: *Exec, chunk: *Chunk, frame: ?*Frame, gen: ?
24512555
const argc = inst.a;
24522556
const base = stack.items.len - argc;
24532557
const callee = stack.items[base - 1];
2454-
if (!parallel_sync) {
2455-
if (jsChunkFn(callee)) |func| {
2456-
if (try tryQuickNumericRecurrence(vm, func, stack.items[base..])) |result| {
2457-
stack.shrinkRetainingCapacity(base - 1);
2458-
try stack.append(stack_alloc, result);
2459-
continue;
2460-
}
2461-
if (func.vm_inline_calls_safe and !vm.vm_inline_calls_disabled) {
2462-
const result = if (vm.vm_inline_call_depth < inline_call_depth_limit)
2463-
try runInlineFunction(vm, func, func.chunk.?, stack.items[base..], Value.undef(), Value.undef())
2464-
else
2465-
try callValueWithInlineCallsDisabled(vm, callee, stack.items[base..], Value.undef());
2466-
stack.shrinkRetainingCapacity(base - 1);
2467-
try stack.append(stack_alloc, result);
2468-
continue;
2469-
}
2558+
if (jsChunkFn(callee)) |func| {
2559+
if (try tryQuickNumericRecurrence(vm, func, stack.items[base..], parallel_sync)) |result| {
2560+
stack.shrinkRetainingCapacity(base - 1);
2561+
try stack.append(stack_alloc, result);
2562+
continue;
2563+
}
2564+
if (!parallel_sync and func.vm_inline_calls_safe and !vm.vm_inline_calls_disabled) {
2565+
const result = if (vm.vm_inline_call_depth < inline_call_depth_limit)
2566+
try runInlineFunction(vm, func, func.chunk.?, stack.items[base..], Value.undef(), Value.undef())
2567+
else
2568+
try callValueWithInlineCallsDisabled(vm, callee, stack.items[base..], Value.undef());
2569+
stack.shrinkRetainingCapacity(base - 1);
2570+
try stack.append(stack_alloc, result);
2571+
continue;
24702572
}
24712573
}
24722574
// Trampoline plain JS→JS calls under the driver: build the callee
@@ -4926,6 +5028,7 @@ test "vm: quickens guarded pure numeric recurrence" {
49265028
}
49275029
}
49285030
try std.testing.expectEqual(run_steps[1], run_steps[0]);
5031+
49295032
}
49305033

49315034
test "vm: compiles observable numeric recurrence without eliding calls" {
@@ -4987,6 +5090,39 @@ test "vm: compiles observable numeric recurrence without eliding calls" {
49875090
}
49885091
}
49895092
try std.testing.expectEqual(run_steps[1], run_steps[0]);
5093+
5094+
// An immutable named-function-expression self binding is safe to compile
5095+
// in shared mode: no worker can replace the recursive callee out from under
5096+
// another. The counter path still performs every synchronized property
5097+
// read and write.
5098+
const named_source =
5099+
\\var recur = function recur(n, state) {
5100+
\\ state.calls = state.calls + 1;
5101+
\\ return n < 2 ? n : recur(n - 1, state) + recur(n - 2, state);
5102+
\\};
5103+
\\var state = { calls: 0 };
5104+
\\recur(8, state) + state.calls
5105+
;
5106+
const shared_hits_before = quick_observable_recurrence_hits.load(.monotonic);
5107+
var named_parser = try Parser.init(allocator, named_source);
5108+
const named_program = try named_parser.parseProgram();
5109+
const named_chunk = try Compiler.compileProgram(allocator, named_program);
5110+
var named_env = Environment{ .arena = allocator, .fn_scope = true };
5111+
const named_root_shape = try @import("shape.zig").Shape.createRoot(allocator);
5112+
try interp.installGlobals(&named_env, named_root_shape);
5113+
const named_global = try gc_mod.allocObj(allocator);
5114+
named_global.* = .{};
5115+
try named_env.put("globalThis", Value.obj(named_global));
5116+
try interp.mirrorGlobalsOnto(&named_env, named_global, named_root_shape);
5117+
var named_machine = Interpreter{
5118+
.arena = allocator,
5119+
.env = &named_env,
5120+
.root_shape = named_root_shape,
5121+
.global_object = named_global,
5122+
.this_value = Value.obj(named_global),
5123+
};
5124+
try std.testing.expectEqual(@as(f64, 88), (try run(&named_machine, named_chunk, null)).asNum());
5125+
try std.testing.expect(quick_observable_recurrence_hits.load(.monotonic) > shared_hits_before);
49905126
}
49915127

49925128
test "vm: quickens packed dense numeric array reads" {

0 commit comments

Comments
 (0)