-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvm.zig
More file actions
7625 lines (7233 loc) · 345 KB
/
Copy pathvm.zig
File metadata and controls
7625 lines (7233 loc) · 345 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Tier-1 bytecode VM for zig-js.
//!
//! Executes a compiled `Chunk` against an `Interpreter`'s live state — the same
//! `Environment` chain, `this`, `exception`, and helper routines the tree-walker
//! uses. That sharing is deliberate: the VM is a faster *execution strategy*,
//! not a second semantics. Variable access still goes through the environment
//! (turning names into slot indexes is the next perf tier); what we remove here
//! is AST recursion and per-node dispatch.
//!
//! Plain VM-to-VM calls use an explicit heap activation stack so logical JS
//! recursion does not consume the host stack. Tree-walk-only and native callees
//! are delegated to `Interpreter`; generator/async bodies retain their own
//! resumable execution state.
const std = @import("std");
const builtin = @import("builtin");
const gc_mod = @import("gc.zig");
const ast = @import("ast.zig");
const bc = @import("bytecode.zig");
const value = @import("value.zig");
const interp = @import("interpreter.zig");
const promise = @import("promise.zig");
const agent = @import("agent.zig");
const gc_runtime = @import("gc_runtime.zig");
const jit = @import("jit.zig");
const jit_compiler = @import("jit/compiler.zig");
const Value = value.Value;
const Chunk = bc.Chunk;
const Shape = @import("shape.zig").Shape;
const Interpreter = interp.Interpreter;
const Environment = interp.Environment;
const Function = interp.Function;
const EvalError = interp.EvalError;
const async_gen_request_reserve_granularity: usize = 16;
const native_tier_entry_threshold: u32 = 3;
const eager_native_tier_entry_threshold: u32 = 1;
const inline_call_depth_limit: u8 = 32;
fn bindThisForCall(vm: *Interpreter, func: *Function, this_val: Value) EvalError!Value {
if (func.is_arrow) return func.arrow_this;
if (func.is_strict) return this_val;
if (this_val.isNull() or this_val.isUndefined()) {
if (func.realm_global) |global| return Value.obj(global);
if (vm.env.get("globalThis")) |gt| if (gt.isObject()) return gt;
return if (vm.global_object) |g| Value.obj(g) else this_val;
}
if (!this_val.isObject() or this_val.asObj().is_symbol or this_val.asObj().is_bigint)
return Value.obj(try vm.toObject(this_val));
return this_val;
}
/// A function activation's flat local store. `slots` holds parameters then
/// function-scoped declarations (indexes assigned by the compiler); `parent` is
/// the *defining* function's frame, walked to resolve upvalues. Heap-allocated
/// so a closure can outlive the call that created it. Globals live in the
/// Environment, not here.
pub const Frame = struct {
slots: []Value,
parent: ?*Frame,
// Once a closure captures this frame (`makeClosure` walks the chain marking
// `escaped`), its slots can be read/written concurrently: the defining
// function via load/store_local on its own frame, and any escaped closure via
// load/store_upval walking into it. So slot access on an escaped frame is
// serialized by `slot_lock`. Non-escaped frames (the vast majority — never
// captured) take no lock at all; and the whole thing is additionally gated on
// the parallel flag, so the GIL/single-threaded engine pays nothing.
escaped: std.atomic.Value(bool) = .init(false),
slot_lock: std.atomic.Mutex = .unlocked,
// `pub` so the GC's parallel root trace can take the same lock when it reads
// an escaped frame's slots via a cross-thread captured-frame walk; see
// `gc.traceInterpreterRoots`.
pub inline fn lockSlots(self: *Frame, enabled: bool) bool {
// `enabled` is the parallel-mode flag, hoisted out of the opcode loop by
// the caller. When false (default engine) this is a single register branch.
// Monotonic `escaped` is enough: a closure reaching this frame on another
// thread already synchronized via the closure object's publication.
if (!enabled or !self.escaped.load(.monotonic)) return false;
var spins: usize = 0;
while (!self.slot_lock.tryLock()) : (spins += 1) {
if ((spins & 0xff) == 0) std.Thread.yield() catch {} else std.atomic.spinLoopHint();
}
return true;
}
pub fn unlockSlots(self: *Frame, held: bool) void {
if (held) self.slot_lock.unlock();
}
/// Mark this frame and every ancestor as escaped — a closure capturing this
/// frame can reach them all through the upvalue walk.
fn markEscapedChain(self: *Frame) void {
var f: ?*Frame = self;
while (f) |fr| : (f = fr.parent) {
if (fr.escaped.load(.monotonic)) break; // chain already marked
fr.escaped.store(true, .release);
}
}
};
/// The VM operand stack has a much hotter append path than a general-purpose
/// ArrayList: almost every bytecode instruction pushes at least one Value. The
/// standard unmanaged append calls ensureTotalCapacity even when capacity is
/// already available; profiles attributed roughly a third of arithmetic VM
/// samples to that call/check boundary. Keep ArrayList growth semantics on the
/// rare full-capacity path, but make the common append one inlined comparison
/// and one store.
const OperandStack = struct {
items: []Value = &.{},
capacity: usize = 0,
pub const empty: OperandStack = .{};
pub inline fn append(self: *OperandStack, allocator: std.mem.Allocator, item: Value) std.mem.Allocator.Error!void {
if (self.items.len == self.capacity) try self.grow(allocator);
self.items.len += 1;
self.items[self.items.len - 1] = item;
}
noinline fn grow(self: *OperandStack, allocator: std.mem.Allocator) std.mem.Allocator.Error!void {
var list: std.ArrayListUnmanaged(Value) = .{
.items = self.items,
.capacity = self.capacity,
};
try list.ensureTotalCapacity(allocator, self.items.len + 1);
self.items = list.items;
self.capacity = list.capacity;
}
pub inline fn pop(self: *OperandStack) ?Value {
if (self.items.len == 0) return null;
const item = self.items[self.items.len - 1];
self.items.len -= 1;
return item;
}
pub inline fn shrinkRetainingCapacity(self: *OperandStack, new_len: usize) void {
std.debug.assert(new_len <= self.items.len);
self.items.len = new_len;
}
pub inline fn clearRetainingCapacity(self: *OperandStack) void {
self.items.len = 0;
}
pub fn deinit(self: *OperandStack, allocator: std.mem.Allocator) void {
var list: std.ArrayListUnmanaged(Value) = .{
.items = self.items,
.capacity = self.capacity,
};
list.deinit(allocator);
self.* = .empty;
}
};
/// A resumable execution state: the operand stack, completion accumulator, and
/// instruction pointer. For a normal call this lives on the host stack and is
/// thrown away when `run` returns; for a generator it lives in the `Generator`
/// and persists across `yield`/resume, which is what makes suspension faithful
/// (the whole operand stack is saved, so a `yield` can sit mid-expression).
pub const Exec = struct {
stack: OperandStack = .empty,
acc: Value = Value.undef(),
ip: usize = 0,
/// The activation frame this Exec is running (null for env-mode bodies:
/// program/generator/async). Recorded so a mid-script collection can trace
/// the frame's `slots` (and its captured-frame parent chain) as precise GC
/// roots — like `stack`/`acc`, the slots are arena-backed and invisible to
/// both the precise object graph and the conservative native-stack scan, so
/// an object live only through a VM local would otherwise be swept.
frame: ?*Frame = null,
/// Active try/catch handlers, innermost last. Lives in `Exec` so it persists
/// across a generator's `yield`/resume (a `yield` can sit inside a `try`).
handlers: std.ArrayListUnmanaged(Handler) = .empty,
};
/// A live try handler: where to resume on a throw and the operand-stack depth
/// to unwind to first (everything pushed inside the `try` is discarded). A
/// throw goes to `catch_pc` if present (pushing the exception for the binding);
/// otherwise, if there's a `finally_pc`, it runs the finally carrying a "throw"
/// completion that is re-thrown after. `none` (u32 max) means that arm is absent.
pub const Handler = struct {
catch_pc: u32,
finally_pc: u32 = none,
stack_depth: u32,
pub const none: u32 = std.math.maxInt(u32);
};
/// A finally block's completion kind (the `kind` half of the record left on the
/// stack for `end_finally`): fall through, re-throw, or return.
const Completion = enum(u8) { normal = 0, throw = 1, ret = 2, break_ = 3, continue_ = 4 };
fn looksLikeCompletionKind(v: Value) bool {
if (!v.isNumber()) return false;
const n = v.asNum();
if (@trunc(n) != n) return false;
return n >= 0 and n <= @as(f64, @floatFromInt(@intFromEnum(Completion.continue_)));
}
fn completionKindBelowTop(stack: *const OperandStack) ?Completion {
if (stack.items.len == 0) return null;
const v = stack.items[stack.items.len - 1];
if (!looksLikeCompletionKind(v)) return null;
return @enumFromInt(@as(u8, @intFromFloat(v.asNum())));
}
/// Unwind `exec.handlers` (innermost-first) to the next `finally`, carrying an
/// abrupt completion `[cval, kind]` so the finally runs and `end_finally`
/// re-propagates it. Returns the finally's PC, or null if none remains (the
/// caller performs the terminal action: return / jump-to-target / re-throw).
fn unwindToFinally(vm: *Interpreter, gen: ?*Generator, exec: *Exec, cval: Value, kind: Completion) !?u32 {
const stack_alloc = generatorStackAllocator(vm, gen);
while (exec.handlers.items.len > 0) {
const h = exec.handlers.pop().?;
if (h.finally_pc != Handler.none) {
exec.stack.shrinkRetainingCapacity(h.stack_depth);
try exec.stack.append(stack_alloc, cval);
try exec.stack.append(stack_alloc, Value.num(@floatFromInt(@intFromEnum(kind))));
return h.finally_pc;
}
}
return null;
}
/// A suspended `function*` activation: its compiled body, persistent execution
/// state, and the `Environment` its body resolves names against (a child of the
/// closure, holding the params/locals across yields). Driven by `genNext`.
pub const Generator = struct {
pub const BackingFlags = packed struct {
stack: bool = false,
handlers: bool = false,
requests: bool = false,
};
backing_allocator: ?std.mem.Allocator = null,
backing_stores_live: ?*usize = null,
backing_flags: BackingFlags = .{},
// `backingFor` is reached from both the request path (`requests_mutex`) and
// the resume path (`resume_mutex`); under `parallel_js` an enqueue on one
// thread races a resume on another on the packed `backing_flags` byte. Its
// own lock serializes the lazy flag-set (rare — once per backing kind).
backing_lock: std.atomic.Mutex = .unlocked,
chunk: *Chunk,
exec: Exec = .{},
env: *Environment,
this_value: Value = Value.undef(),
home_object: ?*value.Object = null,
super_ctor: ?*value.Object = null,
import_meta_slot: ?*interp.ImportMetaSlot = null,
module_referrer: []const u8 = "",
started: bool = false,
done: bool = false,
suspended: bool = false,
resume_mutex: std.Io.Mutex = .init,
/// Resume ownership. Ordinary generators also hold `resume_mutex` to
/// preserve the re-entrant TypeError; async functions use this atomic as a
/// release/acquire handoff between promise jobs drained by different
/// shared-realm threads.
running: std.atomic.Value(bool) = .init(false),
/// An async function activation (vs a `function*`). It is driven by promise
/// settlement rather than `.next()`: each `await` suspends like a `yield`,
/// and `result` is the promise the call returned, settled on completion.
is_async: bool = false,
result: ?*value.Object = null,
/// Whether the last suspension was an `await` (resume on promise settlement)
/// or a `yield` (resume on the next request) — set by the suspend opcode so
/// the async-generator driver can tell them apart.
suspend_kind: enum { yield, await } = .yield,
/// True while suspended at a `yield*` delegation point (`gen_yield_star`). A
/// `.throw(e)`/`.return(v)` resume must then be *forwarded* to the inner
/// iterator by the desugared loop (rather than injected/completed here), so
/// the resume pushes `[value, kind]` and re-enters the body. Cleared at every
/// plain `yield`/`await` (those resume points are not delegation points).
delegating: bool = false,
/// `async function*` activation: each `.next()`/`.return()`/`.throw()`
/// enqueues a request (a result promise + an action) that the driver pumps.
is_async_gen: bool = false,
requests_mutex: std.Io.Mutex = .init,
requests: std.ArrayListUnmanaged(AsyncGenRequest) = .empty,
requests_head: usize = 0,
pumping: bool = false,
fn lockRequests(self: *Generator) void {
self.requests_mutex.lockUncancelable(agent.engineIo());
gc_runtime.enterTraceSensitiveLock();
}
fn unlockRequests(self: *Generator) void {
gc_runtime.leaveTraceSensitiveLock();
self.requests_mutex.unlock(agent.engineIo());
}
fn claimAsyncResume(self: *Generator) void {
var spins: usize = 0;
while (self.running.cmpxchgWeak(false, true, .acquire, .monotonic) != null) : (spins += 1) {
if ((spins & 0xff) == 0) std.Thread.yield() catch {} else std.atomic.spinLoopHint();
}
}
fn releaseAsyncResume(self: *Generator) void {
self.running.store(false, .release);
}
fn backingFor(self: *Generator, fallback: std.mem.Allocator, comptime field: []const u8) std.mem.Allocator {
const a = self.backing_allocator orelse return fallback;
var spins: usize = 0;
while (!self.backing_lock.tryLock()) : (spins += 1) {
if ((spins & 0xff) == 0) std.Thread.yield() catch {} else std.atomic.spinLoopHint();
}
defer self.backing_lock.unlock();
if (!@field(self.backing_flags, field)) {
@field(self.backing_flags, field) = true;
if (self.backing_stores_live) |live| _ = @atomicRmw(usize, live, .Add, 1, .monotonic);
}
return a;
}
pub fn stackAllocator(self: *Generator, fallback: std.mem.Allocator) std.mem.Allocator {
return self.backingFor(fallback, "stack");
}
pub fn handlersAllocator(self: *Generator, fallback: std.mem.Allocator) std.mem.Allocator {
return self.backingFor(fallback, "handlers");
}
pub fn requestsAllocator(self: *Generator, fallback: std.mem.Allocator) std.mem.Allocator {
return self.backingFor(fallback, "requests");
}
pub fn pendingRequests(self: *const Generator) []const AsyncGenRequest {
if (self.requests_head >= self.requests.items.len) return self.requests.items[0..0];
return self.requests.items[self.requests_head..];
}
fn hasPendingRequest(self: *const Generator) bool {
return self.requests_head < self.requests.items.len;
}
fn compactRequests(self: *Generator) void {
if (self.requests_head == 0) return;
const pending = self.pendingRequests();
if (pending.len > 0) std.mem.copyForwards(AsyncGenRequest, self.requests.items[0..pending.len], pending);
self.requests.shrinkRetainingCapacity(pending.len);
self.requests_head = 0;
}
fn reserveRequests(self: *Generator, fallback: std.mem.Allocator, additional: usize) !void {
if (additional == 0) return;
var spare = self.requests.capacity - self.requests.items.len;
if (spare < additional and self.requests_head > 0) {
self.compactRequests();
spare = self.requests.capacity - self.requests.items.len;
}
if (spare >= additional) return;
const extra = @max(additional, async_gen_request_reserve_granularity);
try self.requests.ensureTotalCapacity(self.requestsAllocator(fallback), self.requests.items.len + extra);
}
fn appendRequest(self: *Generator, fallback: std.mem.Allocator, req: AsyncGenRequest) !void {
try self.reserveRequests(fallback, 1);
self.requests.appendAssumeCapacity(req);
}
fn frontRequest(self: *const Generator) ?AsyncGenRequest {
if (!self.hasPendingRequest()) return null;
return self.requests.items[self.requests_head];
}
fn popRequest(self: *Generator) ?AsyncGenRequest {
if (!self.hasPendingRequest()) {
self.requests.clearRetainingCapacity();
self.requests_head = 0;
return null;
}
const req = self.requests.items[self.requests_head];
self.requests.items[self.requests_head] = undefined;
self.requests_head += 1;
if (self.requests_head == self.requests.items.len) {
self.requests.clearRetainingCapacity();
self.requests_head = 0;
}
return req;
}
};
/// A queued async-generator request: how to resume the body and the promise to
/// settle with the resulting `{ value, done }` (or rejection).
pub const AsyncGenRequest = struct {
kind: ResumeKind,
value: Value,
result: *value.Object,
};
test "async generator request queue uses a head cursor and compacting reserve" {
var g = Generator{
.chunk = undefined,
.env = undefined,
};
defer g.requests.deinit(std.testing.allocator);
const dummy_result: *value.Object = undefined;
var i: usize = 0;
while (i < async_gen_request_reserve_granularity) : (i += 1) {
try g.appendRequest(std.testing.allocator, .{
.kind = .send,
.value = Value.num(@floatFromInt(i)),
.result = dummy_result,
});
}
const first_capacity = g.requests.capacity;
try std.testing.expect(first_capacity >= async_gen_request_reserve_granularity);
while (i < first_capacity) : (i += 1) {
try g.appendRequest(std.testing.allocator, .{
.kind = .send,
.value = Value.num(@floatFromInt(i)),
.result = dummy_result,
});
}
try std.testing.expectEqual(first_capacity, g.pendingRequests().len);
const first = g.popRequest().?;
try std.testing.expectEqual(@as(f64, 0), first.value.asNum());
try std.testing.expectEqual(@as(usize, 1), g.requests_head);
try std.testing.expectEqual(first_capacity, g.requests.items.len);
try g.appendRequest(std.testing.allocator, .{
.kind = .return_,
.value = Value.num(99),
.result = dummy_result,
});
try std.testing.expectEqual(first_capacity, g.requests.capacity);
try std.testing.expectEqual(@as(usize, 0), g.requests_head);
try std.testing.expectEqual(first_capacity, g.requests.items.len);
try std.testing.expectEqual(@as(f64, 1), g.frontRequest().?.value.asNum());
try std.testing.expectEqual(@as(f64, 99), g.requests.items[g.requests.items.len - 1].value.asNum());
var expected: f64 = 1;
while (g.popRequest()) |req| {
if (g.hasPendingRequest())
try std.testing.expectEqual(expected, req.value.asNum())
else
try std.testing.expectEqual(@as(f64, 99), req.value.asNum());
expected += 1;
}
try std.testing.expectEqual(@as(usize, 0), g.requests_head);
try std.testing.expectEqual(@as(usize, 0), g.requests.items.len);
try std.testing.expectEqual(first_capacity, g.requests.capacity);
}
test "async generator request lock is trace-sensitive" {
var g = Generator{
.chunk = undefined,
.env = undefined,
};
try std.testing.expect(!gc_runtime.inTraceSensitiveLock());
g.lockRequests();
defer g.unlockRequests();
try std.testing.expect(gc_runtime.inTraceSensitiveLock());
}
test "async function resume ownership is a release acquire handoff" {
if (@import("builtin").single_threaded) return error.SkipZigTest;
var g: Generator = undefined;
g.running = .init(false);
var completed: usize = 0;
const Runner = struct {
fn run(gen: *Generator, count: *usize) void {
var i: usize = 0;
while (i < 1000) : (i += 1) {
gen.claimAsyncResume();
count.* += 1;
gen.releaseAsyncResume();
}
}
};
var threads: [4]std.Thread = undefined;
for (&threads) |*thread| thread.* = try std.Thread.spawn(.{}, Runner.run, .{ &g, &completed });
for (&threads) |*thread| thread.join();
try std.testing.expectEqual(@as(usize, 4000), completed);
}
/// Property-key string for a computed index: a Symbol uses its unique internal
/// encoding (matching the tree-walker's `memberKey`); everything else coerces
/// to string.
fn propKey(vm: *Interpreter, key: Value) EvalError![]const u8 {
// ToPropertyKey: an object key is first ToPrimitive(key, string) — running its
// `[Symbol.toPrimitive]`/`toString`/`valueOf` — and a Symbol key is registered
// so it round-trips through getOwnPropertySymbols/proxy traps. Shared with the
// tree-walker so a computed `{[obj]: …}` / `o[obj]` coerces identically.
return vm.keyOf(key);
}
/// Number remainder keeps the full IEEE/ECMAScript path for zero (including
/// negative zero), negative/fractional values, infinities, and large integers.
/// Hot loop counters and positive small moduli can use integer remainder,
/// avoiding the out-of-line fmod call while producing the same exact Number.
inline fn numberRemainder(a: f64, b: f64) f64 {
const max_u32: f64 = @floatFromInt(std.math.maxInt(u32));
if (a > 0 and a <= max_u32 and b > 0 and b <= max_u32 and @trunc(a) == a and @trunc(b) == b) {
const lhs: u32 = @intFromFloat(a);
const rhs: u32 = @intFromFloat(b);
return @floatFromInt(lhs % rhs);
}
return @rem(a, b);
}
const max_quick_property_instructions: usize = 20;
const max_quick_property_stack: usize = 8;
const max_quick_property_ops: usize = 8;
const QuickPropertyUpdate = struct {
extra_steps: u8,
next_ip: usize,
};
const QuickPropertyOperand = struct {
local: u32,
instruction: u32,
};
const QuickNumericOp = union(enum) {
constant: f64,
local: u32,
property: QuickPropertyOperand,
add,
sub,
mul,
div,
mod,
};
const QuickLoopTail = struct {
counter_local: u32,
delta: f64,
arithmetic: bc.Op,
bound: f64,
comparison: bc.Op,
body_ip: u32,
exit_ip: u32,
};
const QuickPropertyLocalMod = struct {
property: QuickPropertyOperand,
local: u32,
modulus: f64,
};
const QuickPropertyConstant = struct {
property: QuickPropertyOperand,
constant: f64,
};
const QuickPropertyPair = struct {
left: QuickPropertyOperand,
right: QuickPropertyOperand,
};
const QuickPropertySpecialization = union(enum) {
generic,
property_local_add_mod: QuickPropertyLocalMod,
property_add_constant: QuickPropertyConstant,
property_pair_add: QuickPropertyPair,
property_pair_sub: QuickPropertyPair,
};
const QuickResolvedSlots = struct {
first: usize,
second: usize,
target: usize,
};
const QuickPropertyPlan = struct {
target_local: u32,
target_instruction: u32,
ops: [max_quick_property_ops]QuickNumericOp,
op_count: u8,
executed: u8,
next_ip: u32,
tail: ?QuickLoopTail,
specialization: QuickPropertySpecialization,
resolved_shape: ?*Shape,
resolved_read_slots: [2]u32,
resolved_target_slot: u32,
};
const QuickPropertyKernelPlan = union(enum) {
unsupported,
four_property_loop: struct {
object_local: u32,
counter_local: u32,
bound: f64,
modulus: f64,
property_increment: f64,
counter_increment: f64,
read_instructions: [6]u32,
write_instructions: [4]u32,
exit_ip: u32,
},
};
const QuickPropertyKernelUpdate = struct {
extra_steps: u64,
next_ip: usize,
};
const QuickPackedArraySumLoop = struct {
index_local: u32,
array_local: u32,
total_local: u32,
increment: f64,
};
const max_quick_array_expression_ops = 16;
const max_quick_array_expression_stack = 8;
const QuickArrayNumericOp = union(enum) {
constant: f64,
local: u32,
add,
sub,
mul,
div,
mod,
bit_and,
};
const QuickArrayBound = union(enum) {
constant: f64,
local: u32,
};
const QuickArrayAdd3BitAnd = struct {
locals: [3]u32,
mask: i32,
};
const QuickArrayExpressionSpecialization = union(enum) {
generic,
add3_bit_and: QuickArrayAdd3BitAnd,
};
const QuickPackedArrayPushLoop = struct {
index_local: u32,
array_local: u32,
bound: QuickArrayBound,
increment: f64,
get_prop_instruction: u32,
ops: [max_quick_array_expression_ops]QuickArrayNumericOp,
op_count: u8,
specialization: QuickArrayExpressionSpecialization,
executed: u8,
};
const QuickPolymorphicPropertyLoop = struct {
index_local: u32,
array_local: u32,
object_local: u32,
value_local: u32,
checksum_local: u32,
extra_local: u32,
bound: QuickArrayBound,
selector_mask: i32,
modulus: f64,
checksum_mask: i32,
increment: f64,
get_prop_instruction: u32,
set_prop_instruction: u32,
exit_ip: u32,
};
const QuickObjectAllocationLoop = struct {
counter_local: u32,
array_local: u32,
index_local: u32,
displaced_local: u32,
value_local: u32,
fresh_local: u32,
total_local: u32,
extra_local: u32,
bound: QuickArrayBound,
selector_mask: i32,
stamp_mask: i32,
checksum_mask: i32,
modulus: f64,
increment: f64,
displaced_property_instruction: u32,
literal_instructions: [3]u32,
exit_ip: u32,
};
const QuickArrayPlan = union(enum) {
unsupported,
packed_sum: QuickPackedArraySumLoop,
packed_push: QuickPackedArrayPushLoop,
polymorphic_property: QuickPolymorphicPropertyLoop,
object_allocation: QuickObjectAllocationLoop,
};
const max_quick_leaf_ops = 16;
const max_quick_leaf_stack = 8;
const QuickLeafOp = union(enum) {
argument: u8,
constant: f64,
captured_local,
receiver_property,
add,
sub,
mul,
div,
mod,
};
const QuickLeafAddMod = struct {
left: u8,
right: u8,
modulus: f64,
};
const QuickLeafReceiverAddMod = struct {
first: u8,
second: u8,
modulus: f64,
};
const QuickLeafCapturedAddMod = struct {
argument: u8,
modulus: f64,
};
const QuickLeafSpecialization = union(enum) {
generic,
add_mod: QuickLeafAddMod,
captured_add_mod: QuickLeafCapturedAddMod,
receiver_add_mod: QuickLeafReceiverAddMod,
};
const QuickNumericLeaf = struct {
ops: [max_quick_leaf_ops]QuickLeafOp,
op_count: u8,
executed: u8,
captured_local: ?u32,
receiver_property_instruction: ?u32,
specialization: QuickLeafSpecialization,
};
const QuickLeafPlan = union(enum) {
unsupported,
numeric: QuickNumericLeaf,
};
const QuickCallCallee = union(enum) {
global_instruction: u32,
local: u32,
method: struct {
receiver_local: u32,
get_prop_instruction: u32,
},
closure_template: u32,
};
const QuickNumericCallLoop = struct {
index_local: u32,
value_local: u32,
bound: QuickArrayBound,
increment: f64,
callee: QuickCallCallee,
caller_steps: u8,
exit_ip: u32,
};
const QuickCallLoopPlan = union(enum) {
unsupported,
numeric_leaf: QuickNumericCallLoop,
};
const QuickCallLoopUpdate = struct {
extra_steps: u64,
next_ip: usize,
};
const QuickGlobalBinding = union(enum) {
object: struct {
env: *Environment,
object: *value.Object,
shape: *Shape,
slot: u32,
},
environment: struct {
start: *Environment,
binding: *Environment,
name: []const u8,
},
};
const QuickAddRecurrence = struct {
threshold: u16,
first_delta: u16,
second_delta: u16,
binding_instruction: u32,
};
const QuickObservableAddRecurrence = struct {
threshold: u16,
first_delta: u16,
second_delta: u16,
first_binding_instruction: u32,
second_binding_instruction: u32,
counter_read_instruction: u32,
counter_write_instruction: u32,
counter_name: u32,
counter_increment: f64,
};
const QuickRecurrencePlan = union(enum) {
unsupported,
add: QuickAddRecurrence,
observable_add: QuickObservableAddRecurrence,
};
// Test-only observations enforce that the optimized path remains reachable.
// The fetchAdd call is compile-time removed from production builds.
var quick_property_update_hits: std.atomic.Value(u64) = .init(0);
var quick_property_loop_tail_hits: std.atomic.Value(u64) = .init(0);
var quick_property_specialized_hits: std.atomic.Value(u64) = .init(0);
var quick_property_kernel_hits: std.atomic.Value(u64) = .init(0);
var quick_property_plan_decode_attempts: std.atomic.Value(u64) = .init(0);
var quick_dense_array_index_hits: std.atomic.Value(u64) = .init(0);
var quick_dense_array_store_hits: std.atomic.Value(u64) = .init(0);
var quick_array_length_hits: std.atomic.Value(u64) = .init(0);
var quick_array_prototype_data_hits: std.atomic.Value(u64) = .init(0);
var quick_array_push_hits: std.atomic.Value(u64) = .init(0);
var quick_packed_array_sum_loop_hits: std.atomic.Value(u64) = .init(0);
var quick_packed_array_push_loop_hits: std.atomic.Value(u64) = .init(0);
var quick_packed_array_specialized_expression_hits: std.atomic.Value(u64) = .init(0);
var quick_polymorphic_property_loop_hits: std.atomic.Value(u64) = .init(0);
var quick_object_allocation_loop_hits: std.atomic.Value(u64) = .init(0);
pub fn quickObjectAllocationLoopHitsForTesting() u64 {
std.debug.assert(builtin.is_test);
return quick_object_allocation_loop_hits.load(.monotonic);
}
var quick_global_binding_hits: std.atomic.Value(u64) = .init(0);
var quick_literal_transition_hits: std.atomic.Value(u64) = .init(0);
var quick_native_direct_call_hits: std.atomic.Value(u64) = .init(0);
var quick_numeric_call_loop_hits: std.atomic.Value(u64) = .init(0);
var quick_numeric_arguments_call_loop_hits: std.atomic.Value(u64) = .init(0);
var quick_numeric_arguments_direct_call_hits: std.atomic.Value(u64) = .init(0);
var quick_numeric_closure_call_loop_hits: std.atomic.Value(u64) = .init(0);
var quick_reusable_immediate_closure_hits: std.atomic.Value(u64) = .init(0);
var quick_numeric_method_call_loop_hits: std.atomic.Value(u64) = .init(0);
var fast_number_bitwise_hits: std.atomic.Value(u64) = .init(0);
var quick_numeric_call_loop_test_enabled: std.atomic.Value(bool) = .init(true);
var quick_numeric_recurrence_hits: std.atomic.Value(u64) = .init(0);
var quick_observable_recurrence_hits: std.atomic.Value(u64) = .init(0);
inline fn quickPlainObject(value_: Value) ?*value.Object {
if (!value_.isObject()) return null;
const object = value_.asObj();
if (object.is_array or object.accessors.load(.monotonic) != null or object.attrsMap() != null) return null;
return object;
}
/// Resolve a direct data property on an Array prototype without walking the
/// full generic [[Get]] machinery. In shared mode both the receiver's own-data
/// exclusion and the prototype slot read are short property-lock snapshots;
/// the IC itself uses its seqlock publication mode.
fn quickArrayPrototypeData(
chunk: *Chunk,
instruction: usize,
array: *value.Object,
name: []const u8,
parallel_sync: bool,
) ?Value {
if (parallel_sync) array.lockProperties();
const plain_receiver = array.accessors.load(.monotonic) == null and array.attrsMap() == null;
const own_data = if (plain_receiver) if (array.shape) |shape| shape.lookup(name) else null else null;
if (parallel_sync) array.unlockProperties();
if (!plain_receiver or own_data != null) return null;
const prototype = array.protoAtomic() orelse return null;
if (prototype.proxy_handler != null or prototype.proxy_revoked) return null;
if (parallel_sync) prototype.lockProperties();
defer if (parallel_sync) prototype.unlockProperties();
if (prototype.accessors.load(.monotonic) != null) return null;
if (instruction >= chunk.ics.len) return null;
const ic = &chunk.ics[instruction];
const slot = ic.lookupSlotMode(prototype.shape, parallel_sync) orelse slot: {
const shape = prototype.shape orelse return null;
const resolved = shape.lookup(name) orelse return null;
ic.recordMode(shape, resolved, parallel_sync);
break :slot resolved;
};
if (slot >= prototype.slots.items.len) return null;
return prototype.slots.items[slot];
}
inline fn quickArrayIndex(key: Value) ?usize {
if (!key.isNumber()) return null;
const number = key.asNum();
if (!std.math.isFinite(number) or number < 0 or number >= 4294967295 or @trunc(number) != number) return null;
return @intFromFloat(number);
}
inline fn quickDenseArrayStore(vm: *Interpreter, receiver: Value, key: Value, stored: Value) EvalError!bool {
if (!receiver.isObject()) return false;
const index = quickArrayIndex(key) orelse return false;
const object = receiver.asObj();
if (!object.is_array or object.is_arguments or object.proxy_handler != null or object.proxy_revoked or
object.accessors.load(.monotonic) != null or object.attrsMap() != null or
object.has_indexed_property.load(.monotonic))
return false;
try vm.checkRestricted(object);
return object.replaceDenseElement(index, stored);
}
fn specializeQuickArrayExpression(ops: []const QuickArrayNumericOp) QuickArrayExpressionSpecialization {
if (ops.len == 7) {
const first = switch (ops[0]) {
.local => |local| local,
else => return .generic,
};
const second = switch (ops[1]) {
.local => |local| local,
else => return .generic,
};
if (ops[2] != .add) return .generic;
const third = switch (ops[3]) {
.local => |local| local,
else => return .generic,
};
if (ops[4] != .add) return .generic;
const mask = switch (ops[5]) {
.constant => |number| number,
else => return .generic,
};
if (ops[6] != .bit_and) return .generic;
return .{ .add3_bit_and = .{
.locals = .{ first, second, third },
.mask = Value.num(mask).toInt32(),
} };
}
return .generic;
}
fn compileQuickPackedArrayPushLoop(chunk: *Chunk, start: usize) ?QuickPackedArrayPushLoop {
const code = chunk.code.items;
if (start + 16 > code.len or
code[start].op != .load_local or
(code[start + 1].op != .load_const and code[start + 1].op != .load_local) or
code[start + 2].op != .lt or
code[start + 3].op != .jump_if_false or
code[start + 4].op != .load_local or
code[start + 5].op != .dup or
code[start + 6].op != .get_prop or code[start + 6].a >= chunk.names.items.len or
!std.mem.eql(u8, chunk.names.items[code[start + 6].a], "push") or
code[start + 7].op != .swap)
return null;
const bound: QuickArrayBound = switch (code[start + 1].op) {
.load_local => .{ .local = code[start + 1].a },
.load_const => constant: {
if (code[start + 1].a >= chunk.consts.items.len) return null;
const value_ = chunk.consts.items[code[start + 1].a];
if (!value_.isNumber()) return null;
break :constant .{ .constant = value_.asNum() };
},
else => unreachable,
};
var ops: [max_quick_array_expression_ops]QuickArrayNumericOp = undefined;
var op_count: usize = 0;
var depth: usize = 0;
var cursor = start + 8;
while (cursor < code.len and code[cursor].op != .call_with_this) : (cursor += 1) {
if (op_count == ops.len) return null;
const op: QuickArrayNumericOp = switch (code[cursor].op) {
.load_local => local: {
depth += 1;
break :local .{ .local = code[cursor].a };
},
.load_const => constant: {
if (code[cursor].a >= chunk.consts.items.len) return null;
const value_ = chunk.consts.items[code[cursor].a];
if (!value_.isNumber()) return null;
depth += 1;
break :constant .{ .constant = value_.asNum() };
},
.add, .sub, .mul, .div, .mod, .bit_and => binary: {
if (depth < 2) return null;
depth -= 1;
break :binary switch (code[cursor].op) {
.add => .add,
.sub => .sub,
.mul => .mul,