-
Notifications
You must be signed in to change notification settings - Fork 187
/
low-level.ts
445 lines (367 loc) · 10.6 KB
/
low-level.ts
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
import type {
CleanStack,
DebugStack,
ErrorHandler,
Expand,
InternalStack,
MutableReactiveCell,
Nullable,
Result,
RuntimeHeap,
RuntimeOp,
RuntimeProgram,
TargetState,
} from '@glimmer/interfaces';
import { check, CheckNumber } from '@glimmer/debug';
import { LOCAL_DEBUG } from '@glimmer/local-debug-flags';
import { assert, expect, UserException } from '@glimmer/util';
import { $fp, $pc, $ra, $sp, $up, Op } from '@glimmer/vm';
import type { VM } from './append';
import { APPEND_OPCODES } from '../opcodes';
import { debugAround } from './debug/debug';
import { UnwindTarget } from './unwind';
export type PackedRegisters = Expand<
[$pc: number, $ra: number, $fp: number, $sp: number, $up: UnwindTarget]
>;
export function PackedRegisters(...registers: PackedRegisters): PackedRegisters {
assert(registers.length === 5, `Invalid registers: ${JSON.stringify(registers)}`);
assert(
registers.slice(0, -1).every((register) => typeof register === 'number'),
`Invalid registers: ${JSON.stringify(registers)} ($pc, $ra, $fp, and $sp should be numbers)`
);
assert(
registers.at(-1) instanceof UnwindTarget,
`Invalid $up register: Should be a UnwindTarget`
);
return registers;
}
export type FrameInfo = Expand<[$ra: number, $fp: number]>;
export class Registers {
readonly #packed: PackedRegisters;
constructor(packed: PackedRegisters) {
this.#packed = PackedRegisters(...packed);
}
get debug() {
return {
pc: this.#packed[$pc],
ra: this.#packed[$ra],
fp: this.#packed[$fp],
sp: this.#packed[$sp],
up: this.#packed[$up],
};
}
// @premerge consolidate
goto(pc: number): void {
assert(typeof pc === 'number', `Invalid pc: ${typeof pc}`);
assert(!isNaN(pc), `Invalid pc: NaN`);
this.#packed[$pc] = pc;
}
// @premerge consolidate
call(pc: number): void {
this.#packed[$ra] = this.#packed[$pc];
this.goto(pc);
}
// @premerge consolidate
returnTo(pc: number): void {
this.#packed[$ra] = check(pc, CheckNumber);
}
// @premerge consolidate
return() {
this.#packed[$pc] = this.#packed[$ra];
}
// @premerge consolidate
advance(size: number) {
this.#packed[$pc] += size;
check(this.#packed[$pc], CheckNumber);
return size;
}
// @premerge consolidate
advanceSp(size: number) {
this.#packed[$sp] += size;
check(this.#packed[$sp], CheckNumber);
return size;
}
// @premerge consolidate
push(): number {
return ++this.#packed[$sp];
}
// @premerge consolidate
pop(n = 1): number {
return (this.#packed[$sp] -= check(n, CheckNumber));
}
// @premerge consolidate
peek(offset = 0): number {
return this.#packed[$sp] - check(offset, CheckNumber);
}
// @premerge consolidate
/**
* Remember the previous $fp, then update $fp to point to $sp. Return the previous $fp so it can
* be pushed onto the stack.
*
* This creates a linked list of $fps on the stack.
*/
pushFp() {
let prevFp = this.#packed[$fp];
// the current $sp contains the $ra we already pushed, so the $fp will point to the tuple of
// $ra and $fp
this.#packed[$fp] = this.#packed[$sp];
return prevFp;
}
// @premerge consolidate
popTo(ra: number, fp: number): void {
// when popping a frame, we want to restore the $sp to the position immediately before we pushed
// the $ra and $fp onto the stack, which will effectively continue execution at that point.
let to = this.#packed[$fp] - 1;
this.#packed[$ra] = check(ra, CheckNumber);
this.#packed[$fp] = check(fp, CheckNumber);
this.#packed[$sp] = check(to, CheckNumber);
}
/**
* @deprecated Direct access to .packed will be removed once all use-cases are handled via
* semantic methods.
*/
get packed(): PackedRegisters {
return this.#packed;
}
get pc(): number {
return this.#packed[$pc];
}
get ra(): number {
return this.#packed[$ra];
}
get sp(): number {
return this.#packed[$sp];
}
get fp(): number {
return this.#packed[$fp];
}
get up(): UnwindTarget {
return this.#packed[$up];
}
try(catchPc: number, error: MutableReactiveCell<number>, handler: ErrorHandler | null) {
this.#packed[$up] = this.#packed[$up].child({
ip: catchPc,
ra: this.#packed[$ra],
fp: this.#packed[$fp],
error,
handler,
});
}
catch(error: unknown): TargetState {
return this.#packed[$up].catch(error);
}
finally() {
this.#packed[$up] = expect(
this.#packed[$up].finally(),
"Since the $up starts initialized, and finally() is always paired with try(), it shouldn't be possible to pop the last $up."
);
}
}
export interface ArgumentsStack extends InternalStack, DebugStack {
readonly registers: Registers;
// @premerge consolidate (these are only used in Arguments)
copy(from: number, to: number): void;
set(value: unknown, offset: number, base?: number): void;
slice<T = unknown>(start: number, end: number): T[];
capture(items: number): unknown[];
frame(): unknown[];
}
export interface Externs {
debug: VM;
}
export interface LowLevelVmDebugState {
readonly registers: Registers;
readonly currentPc: number;
readonly stack: DebugStack;
readonly threw: Error | undefined;
}
let THROWN:
| { unset: () => void; set: (value: Error) => void; check: () => Error | undefined }
| undefined;
if (import.meta.env.DEV) {
let MARKER: Error | undefined = undefined;
THROWN = {
unset: () => {
MARKER = undefined;
},
set: (error: Error) => {
MARKER = error;
},
check: () => MARKER,
};
}
export class LowLevelVM {
static create(
stack: ArgumentsStack,
heap: RuntimeHeap,
program: RuntimeProgram,
externs: Externs,
registers: Registers
): LowLevelVM {
return new LowLevelVM(stack, heap, program, externs, registers);
}
#currentOpSize = 0;
readonly #registers: Registers;
readonly #heap: RuntimeHeap;
readonly #program: RuntimeProgram;
readonly #stack: ArgumentsStack;
declare threw?: () => boolean;
private constructor(
stack: ArgumentsStack,
heap: RuntimeHeap,
program: RuntimeProgram,
readonly externs: Externs,
registers: Registers
) {
this.#stack = stack;
this.#heap = heap;
this.#program = program;
this.#registers = registers;
if (import.meta.env.DEV) {
Object.defineProperty(this, 'threw', () => THROWN?.check());
}
}
get result(): Result<void> {
return this.#registers.up.unhandled;
}
capture(): { unwind: UnwindTarget } {
return { unwind: this.#registers.up };
}
// @premerge consolidate
get stack(): CleanStack {
return this.#stack;
}
// @premerge consolidate
get internalStack(): InternalStack {
return this.#stack;
}
// @premerge consolidate
get forArguments(): ArgumentsStack {
return this.#stack;
}
/**
* @mutable
*/
get debug(): LowLevelVmDebugState {
return {
currentPc: this.#registers.pc - this.#currentOpSize,
registers: this.#registers,
stack: this.#stack,
threw: THROWN?.check(),
};
}
get pc(): number {
return this.#registers.pc;
}
get sp(): number {
return this.#registers.sp;
}
get fp(): number {
return this.#registers.fp;
}
get up(): UnwindTarget {
return this.#registers.up;
}
/**
* `begin` takes an absolute instruction.
*/
begin(instruction: number, error: MutableReactiveCell<number>, handler: Nullable<ErrorHandler>) {
this.#registers.try(instruction, error, handler);
}
catch(error: unknown): TargetState {
if (import.meta.env.DEV) {
THROWN?.set(UserException.from(error, `A user exception occurred`));
}
const target = this.#registers.catch(error);
this.#registers.popTo(target.ra, target.fp);
this.#registers.goto(target.ip);
return target;
}
finally() {
this.#registers.finally();
}
// Start a new frame and save $ra and $fp on the stack
pushFrame() {
this.#stack.push(this.#registers.ra);
this.#stack.push(this.#registers.pushFp());
}
// Restore $ra, $sp and $fp
popFrame() {
let fp = this.#registers.fp;
// get the previous $ra and $fp from the stack (relative to the *current* $fp), and restore them
// to the registers.
this.#registers.popTo(this.#stack.get(0, fp), this.#stack.get(1, fp));
}
// Jump to an address in `program`
goto(offset: number) {
let pc = this.target(offset);
assert(typeof pc === 'number', `expected pc to be a number, but it was ${typeof pc}`);
assert(!isNaN(pc), 'expected pc to not be NaN, but it was');
this.#registers.goto(pc);
}
target(offset: number) {
return this.#registers.pc + offset - this.#currentOpSize;
}
// Save $pc into $ra, then jump to a new address in `program` (jal in MIPS)
call(handle: number) {
assert(handle < 0xffffffff, `Jumping to placeholder address`);
this.#registers.call(this.#heap.getaddr(handle));
}
// Put a specific `program` address in $ra
returnTo(offset: number) {
this.#registers.returnTo(this.target(offset));
}
// Return to the `program` address stored in $ra
return() {
this.#registers.return();
}
nextStatement(): Nullable<RuntimeOp> {
if (import.meta.env.DEV) {
THROWN?.unset();
}
let program = this.#program;
let registers = this.#registers;
let pc = registers.pc;
assert(typeof pc === 'number', 'pc is a number');
if (pc === -1) {
return null;
}
// We have to save off the current operations size so that
// when we do a jump we can calculate the correct offset
// to where we are going. We can't simply ask for the size
// in a jump because we have have already incremented the
// program counter to the next instruction prior to executing.
let opcode = program.opcode(pc);
this.#currentOpSize = this.#registers.advance(opcode.size);
return opcode;
}
evaluateOuter(opcode: RuntimeOp, vm: VM) {
if (LOCAL_DEBUG) {
debugAround(vm, opcode, () => this.#evaluateInner(opcode, vm));
} else {
this.#evaluateInner(opcode, vm);
}
}
#evaluateInner(opcode: RuntimeOp, vm: VM) {
if (opcode.isMachine) {
this.#evaluateMachine(opcode);
} else {
this.#evaluateSyscall(opcode, vm);
}
}
#evaluateMachine(opcode: RuntimeOp) {
switch (opcode.type) {
case Op.PushFrame:
return this.pushFrame();
case Op.PopFrame:
return this.popFrame();
case Op.Jump:
return this.goto(opcode.op1);
case Op.ReturnTo:
return this.returnTo(opcode.op1);
}
}
#evaluateSyscall(opcode: RuntimeOp, vm: VM) {
APPEND_OPCODES.evaluate(vm, opcode, opcode.type);
}
}