forked from sampsyo/bril
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gc-brili.ts
1147 lines (1028 loc) · 30.5 KB
/
gc-brili.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
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
import * as bril from "./bril-ts/bril.ts";
import { readStdin, unreachable } from "./bril-ts/util.ts";
/**
* An interpreter error to print to the console.
*/
class BriliError extends Error {
constructor(message?: string) {
super(message);
Object.setPrototypeOf(this, new.target.prototype);
this.name = BriliError.name;
}
}
/**
* Create an interpreter error object to throw.
*/
function error(message: string): BriliError {
return new BriliError(message);
}
function isPointer(val: Value): Boolean {
return typeof val === "object" && "loc" in val && "type" in val;
}
/**
* An abstract key class used to access the heap.
* This allows for "pointer arithmetic" on keys,
* while still allowing lookups based on the based pointer of each allocation.
*/
export class Key {
readonly base: number;
// we can allocate an array, so it has a offset
readonly offset: number;
constructor(b: number, o: number) {
this.base = b;
this.offset = o;
}
add(offset: number) {
return new Key(this.base, this.offset + offset);
}
}
/**
* A Heap maps Keys to arrays of a given type.
*/
export class Heap<X> {
private readonly storage: Map<number, X[]>;
private readonly ref_count: Map<number, number>;
private readonly ref_to: Map<number, number[]>;
constructor() {
this.storage = new Map();
this.ref_count = new Map();
this.ref_to = new Map();
}
isEmpty(): boolean {
return this.storage.size == 0;
}
private count = 0;
private getNewBase(): number {
let val = this.count;
this.count++;
return val;
}
private freeKey(key: Key) {
return;
}
alloc(amt: number): Key {
if (amt <= 0) {
throw error(`cannot allocate ${amt} entries`);
}
let base = this.getNewBase();
this.storage.set(base, new Array(amt));
// TODO: set ref_count here?
this.ref_count.set(base, 0);
return new Key(base, 0);
}
auto_free() {
for (let key of Array.from(this.storage.keys())) {
if (this.ref_count.get(key) && this.ref_count[key] == 0) {
// TODO: can we make sure storage and ref_count are consistent?
this.storage.delete(key);
this.ref_count.delete(key);
// this.ref_to.delete(key);
}
}
}
free(key: Key) {
if (this.storage.has(key.base) && key.offset == 0) {
this.freeKey(key);
this.storage.delete(key.base);
this.ref_count.delete(key.base);
// this.ref_to.delete(key.base);
} else {
throw error(
`Tried to free illegal memory location base: ${key.base}, offset: ${key.offset}. Offset must be 0.`
);
}
}
write(key: Key, val: X) {
let data = this.storage.get(key.base);
if (data && data.length > key.offset && key.offset >= 0) {
data[key.offset] = val;
} else {
throw error(
`Uninitialized heap location ${key.base} and/or illegal offset ${key.offset}`
);
}
}
read(key: Key): X {
let data = this.storage.get(key.base);
if (data && data.length > key.offset && key.offset >= 0) {
return data[key.offset];
} else {
throw error(
`Uninitialized heap location ${key.base} and/or illegal offset ${key.offset}`
);
}
}
incRefCount(base: number, ref: number | undefined = undefined) {
let prev = this.ref_count.get(base);
this.ref_count.set(base, prev ? prev + 1 : 1);
console.log("before inc", base, this.ref_count);
// this.ref_count.set(base, prev + 1);
// if (ref) {
// this.ref_to[base].append(ref);
// }
console.log("after inc", base, this.ref_count);
}
decRefCount(base: number) {
// let base = key.base;
// if (this.ref_count[base] <= 0) {
// this.free(key);
// return;
// }
let bef_cnt = this.ref_count.get(base) ? this.ref_count.get(base) : 0;
console.log("before dec", base, bef_cnt);
this.ref_count.set(base, bef_cnt ? bef_cnt - 1 : 0);
// decrement recursively if becomes 0
console.log("ref_count is", this.ref_count.get(base));
if (bef_cnt && bef_cnt - 1 <= 0) {
// let value_list = this.storage[base];
// del storage[base]
// let data = this.ref_to.get(base);
// if (data) {
// for (let i = 0; i < data.length; i++) {
// this.decRefCount(data[i]);
// }
// }
// this.ref_to.delete(base);
let value_list = this.storage.get(base);
if (value_list) {
for (let i = 0; i < value_list.length; i++) {
if (isPointer(value_list[i])) {
let ptr_val = value_list[i] as Pointer;
this.decRefCount(ptr_val.loc.base);
}
}
}
console.log("before delete storage", this.storage);
this.storage.delete(base);
console.log("after delete storage", this.storage);
console.log("before delete ref_count", this.ref_count);
this.ref_count.delete(base);
console.log("after delete ref_count", this.ref_count);
}
console.log("after", this.ref_count);
}
}
const argCounts: { [key in bril.OpCode]: number | null } = {
add: 2,
mul: 2,
sub: 2,
div: 2,
id: 1,
lt: 2,
le: 2,
gt: 2,
ge: 2,
eq: 2,
not: 1,
and: 2,
or: 2,
fadd: 2,
fmul: 2,
fsub: 2,
fdiv: 2,
flt: 2,
fle: 2,
fgt: 2,
fge: 2,
feq: 2,
print: null, // Any number of arguments.
br: 1,
jmp: 0,
ret: null, // (Should be 0 or 1.)
nop: 0,
call: null,
alloc: 1,
free: 1,
store: 2,
load: 1,
ptradd: 2,
phi: null,
speculate: 0,
guard: 1,
commit: 0,
ceq: 2,
clt: 2,
cle: 2,
cgt: 2,
cge: 2,
char2int: 1,
int2char: 1,
};
type Pointer = {
loc: Key;
type: bril.Type;
};
type Value = boolean | BigInt | Pointer | number | string;
type Env = Map<bril.Ident, Value>;
/**
* Check whether a run-time value matches the given static type.
*/
function typeCheck(val: Value, typ: bril.Type): boolean {
if (typ === "int") {
return typeof val === "bigint";
} else if (typ === "bool") {
return typeof val === "boolean";
} else if (typ === "float") {
return typeof val === "number";
} else if (typeof typ === "object" && typ.hasOwnProperty("ptr")) {
return val.hasOwnProperty("loc");
} else if (typ === "char") {
return typeof val === "string";
}
throw error(`unknown type ${typ}`);
}
/**
* Check whether the types are equal.
*/
function typeCmp(lhs: bril.Type, rhs: bril.Type): boolean {
if (lhs === "int" || lhs == "bool" || lhs == "float" || lhs == "char") {
return lhs == rhs;
} else {
if (typeof rhs === "object" && rhs.hasOwnProperty("ptr")) {
return typeCmp(lhs.ptr, rhs.ptr);
} else {
return false;
}
}
}
function get(env: Env, ident: bril.Ident) {
let val = env.get(ident);
if (typeof val === "undefined") {
throw error(`undefined variable ${ident}`);
}
return val;
}
function findFunc(func: bril.Ident, funcs: readonly bril.Function[]) {
let matches = funcs.filter(function (f: bril.Function) {
return f.name === func;
});
if (matches.length == 0) {
throw error(`no function of name ${func} found`);
} else if (matches.length > 1) {
throw error(`multiple functions of name ${func} found`);
}
return matches[0];
}
function alloc(
ptrType: bril.ParamType,
amt: number,
heap: Heap<Value>
): Pointer {
if (typeof ptrType != "object") {
throw error(`unspecified pointer type ${ptrType}`);
} else if (amt <= 0) {
throw error(`must allocate a positive amount of memory: ${amt} <= 0`);
} else {
let loc = heap.alloc(amt);
let dataType = ptrType.ptr;
return {
loc: loc,
type: dataType,
};
}
}
/**
* Ensure that the instruction has exactly `count` arguments,
* throw an exception otherwise.
*/
function checkArgs(instr: bril.Operation, count: number) {
let found = instr.args ? instr.args.length : 0;
if (found != count) {
throw error(`${instr.op} takes ${count} argument(s); got ${found}`);
}
}
function getPtr(instr: bril.Operation, env: Env, index: number): Pointer {
let val = getArgument(instr, env, index);
if (typeof val !== "object" || val instanceof BigInt) {
throw `${instr.op} argument ${index} must be a Pointer`;
}
return val;
}
function getArgument(
instr: bril.Operation,
env: Env,
index: number,
typ?: bril.Type
) {
let args = instr.args || [];
if (args.length <= index) {
throw error(
`${instr.op} expected at least ${index + 1} arguments; got ${args.length}`
);
}
let val = get(env, args[index]);
if (typ && !typeCheck(val, typ)) {
throw error(`${instr.op} argument ${index} must be a ${typ}`);
}
return val;
}
function getInt(instr: bril.Operation, env: Env, index: number): bigint {
return getArgument(instr, env, index, "int") as bigint;
}
function getBool(instr: bril.Operation, env: Env, index: number): boolean {
return getArgument(instr, env, index, "bool") as boolean;
}
function getFloat(instr: bril.Operation, env: Env, index: number): number {
return getArgument(instr, env, index, "float") as number;
}
function getChar(instr: bril.Operation, env: Env, index: number): string {
return getArgument(instr, env, index, "char") as string;
}
function getLabel(instr: bril.Operation, index: number): bril.Ident {
if (!instr.labels) {
throw error(`missing labels; expected at least ${index + 1}`);
}
if (instr.labels.length <= index) {
throw error(`expecting ${index + 1} labels; found ${instr.labels.length}`);
}
return instr.labels[index];
}
function getFunc(instr: bril.Operation, index: number): bril.Ident {
if (!instr.funcs) {
throw error(`missing functions; expected at least ${index + 1}`);
}
if (instr.funcs.length <= index) {
throw error(
`expecting ${index + 1} functions; found ${instr.funcs.length}`
);
}
return instr.funcs[index];
}
/**
* The thing to do after interpreting an instruction: this is how `evalInstr`
* communicates control-flow actions back to the top-level interpreter loop.
*/
type Action =
| { action: "next" } // Normal execution: just proceed to next instruction.
| { action: "jump"; label: bril.Ident }
| { action: "end"; ret: Value | null }
| { action: "speculate" }
| { action: "commit" }
| { action: "abort"; label: bril.Ident };
let NEXT: Action = { action: "next" };
/**
* The interpreter state that's threaded through recursive calls.
*/
type State = {
env: Env;
readonly heap: Heap<Value>;
readonly funcs: readonly bril.Function[];
pointer_stack: Array<number>;
// For profiling: a total count of the number of instructions executed.
icount: bigint;
// For SSA (phi-node) execution: keep track of recently-seen labels.j
curlabel: string | null;
lastlabel: string | null;
// For speculation: the state at the point where speculation began.
specparent: State | null;
};
/**
* Interpet a call instruction.
*/
function evalCall(instr: bril.Operation, state: State): Action {
// Which function are we calling?
let funcName = getFunc(instr, 0);
let func = findFunc(funcName, state.funcs);
if (func === null) {
throw error(`undefined function ${funcName}`);
}
let newEnv: Env = new Map();
// Check arity of arguments and definition.
let params = func.args || [];
let args = instr.args || [];
if (params.length !== args.length) {
throw error(
`function expected ${params.length} arguments, got ${args.length}`
);
}
let pointer_stack = new Array<number>();
for (let i = 0; i < params.length; i++) {
// Look up the variable in the current (calling) environment.
let value = get(state.env, args[i]);
// Check argument types
if (!typeCheck(value, params[i].type)) {
throw error(`function argument type mismatch`);
}
// Set the value of the arg in the new (function) environment.
newEnv.set(params[i].name, value);
if (isPointer(value)) {
let ptr_val = value as Pointer;
state.heap.incRefCount(ptr_val.loc.base);
pointer_stack.push(ptr_val.loc.base);
}
}
console.log("pointer stack before", pointer_stack);
// Invoke the interpreter on the function.
let newState: State = {
env: newEnv,
heap: state.heap,
// TODO: is this pass by reference?
pointer_stack: pointer_stack,
funcs: state.funcs,
icount: state.icount,
lastlabel: null,
curlabel: null,
specparent: null, // Speculation not allowed.
};
let retVal = evalFunc(func, newState);
state.icount = newState.icount;
// for (let i = 0; i < pointer_stack.length; i++) {
// state.heap.decRefCount(pointer_stack[i]);
// }
// Dynamically check the function's return value and type.
if (!("dest" in instr)) {
// `instr` is an `EffectOperation`.
// Expected void function
if (retVal !== null) {
throw error(`unexpected value returned without destination`);
}
if (func.type !== undefined) {
throw error(
`non-void function (type: ${func.type}) doesn't return anything`
);
}
} else {
// `instr` is a `ValueOperation`.
// Expected non-void function
if (instr.type === undefined) {
throw error(`function call must include a type if it has a destination`);
}
if (instr.dest === undefined) {
throw error(`function call must include a destination if it has a type`);
}
if (retVal === null) {
throw error(
`non-void function (type: ${func.type}) doesn't return anything`
);
}
if (!typeCheck(retVal, instr.type)) {
throw error(
`type of value returned by function does not match destination type`
);
}
if (func.type === undefined) {
throw error(`function with void return type used in value call`);
}
if (!typeCmp(instr.type, func.type)) {
throw error(
`type of value returned by function does not match declaration`
);
}
state.env.set(instr.dest, retVal);
if (isPointer(retVal)) {
let ptr_val = retVal as Pointer;
state.heap.incRefCount(ptr_val.loc.base);
state.pointer_stack.push(ptr_val.loc.base);
}
}
console.log("pointer stack after func", pointer_stack);
for (let i = 0; i < pointer_stack.length; i++) {
state.heap.decRefCount(pointer_stack[i]);
}
state.heap.auto_free();
return NEXT;
}
/**
* Interpret an instruction in a given environment, possibly updating the
* environment. If the instruction branches to a new label, return that label;
* otherwise, return "next" to indicate that we should proceed to the next
* instruction or "end" to terminate the function.
*/
function evalInstr(instr: bril.Instruction, state: State): Action {
state.icount += BigInt(1);
// Check that we have the right number of arguments.
if (instr.op !== "const") {
let count = argCounts[instr.op];
if (count === undefined) {
throw error("unknown opcode " + instr.op);
} else if (count !== null) {
checkArgs(instr, count);
}
}
// Function calls are not (currently) supported during speculation.
// It would be cool to add, but aborting from inside a function call
// would require explicit stack management.
if (state.specparent && ["call", "ret"].includes(instr.op)) {
throw error(`${instr.op} not allowed during speculation`);
}
switch (instr.op) {
case "const":
// Interpret JSON numbers as either ints or floats.
let value: Value;
if (typeof instr.value === "number") {
if (instr.type === "float") value = instr.value;
else value = BigInt(Math.floor(instr.value));
} else if (typeof instr.value === "string") {
if ([...instr.value].length !== 1)
throw error(`char must have one character`);
value = instr.value;
} else {
value = instr.value;
}
state.env.set(instr.dest, value);
return NEXT;
case "id": {
let val = getArgument(instr, state.env, 0);
state.env.set(instr.dest, val);
if (isPointer(val)) {
let ptr_val = val as Pointer;
state.pointer_stack.push(ptr_val.loc.base);
state.heap.incRefCount(ptr_val.loc.base);
}
return NEXT;
}
case "add": {
let val = getInt(instr, state.env, 0) + getInt(instr, state.env, 1);
val = BigInt.asIntN(64, val);
state.env.set(instr.dest, val);
return NEXT;
}
case "mul": {
let val = getInt(instr, state.env, 0) * getInt(instr, state.env, 1);
val = BigInt.asIntN(64, val);
state.env.set(instr.dest, val);
return NEXT;
}
case "sub": {
let val = getInt(instr, state.env, 0) - getInt(instr, state.env, 1);
val = BigInt.asIntN(64, val);
state.env.set(instr.dest, val);
return NEXT;
}
case "div": {
let lhs = getInt(instr, state.env, 0);
let rhs = getInt(instr, state.env, 1);
if (rhs === BigInt(0)) {
throw error(`division by zero`);
}
let val = lhs / rhs;
val = BigInt.asIntN(64, val);
state.env.set(instr.dest, val);
return NEXT;
}
case "le": {
let val = getInt(instr, state.env, 0) <= getInt(instr, state.env, 1);
state.env.set(instr.dest, val);
return NEXT;
}
case "lt": {
let val = getInt(instr, state.env, 0) < getInt(instr, state.env, 1);
state.env.set(instr.dest, val);
return NEXT;
}
case "gt": {
let val = getInt(instr, state.env, 0) > getInt(instr, state.env, 1);
state.env.set(instr.dest, val);
return NEXT;
}
case "ge": {
let val = getInt(instr, state.env, 0) >= getInt(instr, state.env, 1);
state.env.set(instr.dest, val);
return NEXT;
}
case "eq": {
let val = getInt(instr, state.env, 0) === getInt(instr, state.env, 1);
state.env.set(instr.dest, val);
return NEXT;
}
case "not": {
let val = !getBool(instr, state.env, 0);
state.env.set(instr.dest, val);
return NEXT;
}
case "and": {
let val = getBool(instr, state.env, 0) && getBool(instr, state.env, 1);
state.env.set(instr.dest, val);
return NEXT;
}
case "or": {
let val = getBool(instr, state.env, 0) || getBool(instr, state.env, 1);
state.env.set(instr.dest, val);
return NEXT;
}
case "fadd": {
let val = getFloat(instr, state.env, 0) + getFloat(instr, state.env, 1);
state.env.set(instr.dest, val);
return NEXT;
}
case "fsub": {
let val = getFloat(instr, state.env, 0) - getFloat(instr, state.env, 1);
state.env.set(instr.dest, val);
return NEXT;
}
case "fmul": {
let val = getFloat(instr, state.env, 0) * getFloat(instr, state.env, 1);
state.env.set(instr.dest, val);
return NEXT;
}
case "fdiv": {
let val = getFloat(instr, state.env, 0) / getFloat(instr, state.env, 1);
state.env.set(instr.dest, val);
return NEXT;
}
case "fle": {
let val = getFloat(instr, state.env, 0) <= getFloat(instr, state.env, 1);
state.env.set(instr.dest, val);
return NEXT;
}
case "flt": {
let val = getFloat(instr, state.env, 0) < getFloat(instr, state.env, 1);
state.env.set(instr.dest, val);
return NEXT;
}
case "fgt": {
let val = getFloat(instr, state.env, 0) > getFloat(instr, state.env, 1);
state.env.set(instr.dest, val);
return NEXT;
}
case "fge": {
let val = getFloat(instr, state.env, 0) >= getFloat(instr, state.env, 1);
state.env.set(instr.dest, val);
return NEXT;
}
case "feq": {
let val = getFloat(instr, state.env, 0) === getFloat(instr, state.env, 1);
state.env.set(instr.dest, val);
return NEXT;
}
case "print": {
let args = instr.args || [];
let values = args.map(function (i) {
let val = get(state.env, i);
if (Object.is(-0, val)) {
return "-0.00000000000000000";
}
if (typeof val == "number") {
return val.toFixed(17);
} else {
return val.toString();
}
});
console.log(...values);
return NEXT;
}
case "jmp": {
return { action: "jump", label: getLabel(instr, 0) };
}
case "br": {
let cond = getBool(instr, state.env, 0);
if (cond) {
return { action: "jump", label: getLabel(instr, 0) };
} else {
return { action: "jump", label: getLabel(instr, 1) };
}
}
case "ret": {
let args = instr.args || [];
if (args.length == 0) {
return { action: "end", ret: null };
} else if (args.length == 1) {
let val = get(state.env, args[0]);
return { action: "end", ret: val };
} else {
throw error(`ret takes 0 or 1 argument(s); got ${args.length}`);
}
}
case "nop": {
return NEXT;
}
case "call": {
return evalCall(instr, state);
}
case "alloc": {
let amt = getInt(instr, state.env, 0);
let typ = instr.type;
if (!(typeof typ === "object" && typ.hasOwnProperty("ptr"))) {
throw error(`cannot allocate non-pointer type ${instr.type}`);
}
let ptr = alloc(typ, Number(amt), state.heap);
let ptr_old = state.env.get(instr.dest);
if (ptr_old !== undefined) {
ptr_old = ptr_old as Pointer;
console.log("dec old loc");
state.heap.decRefCount(ptr_old.loc.base);
}
state.env.set(instr.dest, ptr);
state.pointer_stack.push(ptr.loc.base);
state.heap.incRefCount(ptr.loc.base);
console.log("heap", state.heap);
return NEXT;
}
case "free": {
let val = getPtr(instr, state.env, 0);
state.heap.free(val.loc);
return NEXT;
}
case "store": {
let target = getPtr(instr, state.env, 0);
let val: Value = getArgument(instr, state.env, 1, target.type);
state.heap.write(target.loc, val);
// make sure it is a Pointer
if (isPointer(val)) {
let ptr_val = val as Pointer;
state.pointer_stack.push(ptr_val.loc.base);
state.heap.incRefCount(ptr_val.loc.base);
}
return NEXT;
}
case "load": {
let ptr = getPtr(instr, state.env, 0);
let val = state.heap.read(ptr.loc);
if (val === undefined || val === null) {
throw error(`Pointer ${instr.args![0]} points to uninitialized data`);
} else {
state.env.set(instr.dest, val);
if (isPointer(val)) {
let ptr_val = val as Pointer;
state.pointer_stack.push(ptr_val.loc.base);
state.heap.incRefCount(ptr_val.loc.base);
}
}
return NEXT;
}
case "ptradd": {
let ptr = getPtr(instr, state.env, 0);
let val = getInt(instr, state.env, 1);
let key = ptr.loc.add(Number(val));
state.env.set(instr.dest, { loc: key, type: ptr.type });
state.pointer_stack.push(key.base);
state.heap.incRefCount(key.base, ptr.loc.base);
return NEXT;
}
case "phi": {
let labels = instr.labels || [];
let args = instr.args || [];
if (labels.length != args.length) {
throw error(`phi node has unequal numbers of labels and args`);
}
if (!state.lastlabel) {
throw error(`phi node executed with no last label`);
}
let idx = labels.indexOf(state.lastlabel);
if (idx === -1) {
// Last label not handled. Leave uninitialized.
state.env.delete(instr.dest);
} else {
// Copy the right argument (including an undefined one).
if (!instr.args || idx >= instr.args.length) {
throw error(`phi node needed at least ${idx + 1} arguments`);
}
let src = instr.args[idx];
let val = state.env.get(src);
if (val === undefined) {
state.env.delete(instr.dest);
} else {
state.env.set(instr.dest, val);
}
}
return NEXT;
}
// Begin speculation.
case "speculate": {
return { action: "speculate" };
}
// Abort speculation if the condition is false.
case "guard": {
if (getBool(instr, state.env, 0)) {
return NEXT;
} else {
return { action: "abort", label: getLabel(instr, 0) };
}
}
// Resolve speculation, making speculative state real.
case "commit": {
return { action: "commit" };
}
case "ceq": {
let val = getChar(instr, state.env, 0) === getChar(instr, state.env, 1);
state.env.set(instr.dest, val);
return NEXT;
}
case "clt": {
let val = getChar(instr, state.env, 0) < getChar(instr, state.env, 1);
state.env.set(instr.dest, val);
return NEXT;
}
case "cle": {
let val = getChar(instr, state.env, 0) <= getChar(instr, state.env, 1);
state.env.set(instr.dest, val);
return NEXT;
}
case "cgt": {
let val = getChar(instr, state.env, 0) > getChar(instr, state.env, 1);
state.env.set(instr.dest, val);
return NEXT;
}
case "cge": {
let val = getChar(instr, state.env, 0) >= getChar(instr, state.env, 1);
state.env.set(instr.dest, val);
return NEXT;
}
case "char2int": {
let code = getChar(instr, state.env, 0).codePointAt(0);
let val = BigInt.asIntN(64, BigInt(code as number));
state.env.set(instr.dest, val);
return NEXT;
}
case "int2char": {
let i = getInt(instr, state.env, 0);
if (i > 1114111 || i < 0 || (55295 < i && i < 57344)) {
throw error(`value ${i} cannot be converted to char`);
}
let val = String.fromCodePoint(Number(i));
state.env.set(instr.dest, val);
return NEXT;
}
}
unreachable(instr);
throw error(`unhandled opcode ${(instr as any).op}`);
}
function evalFunc(func: bril.Function, state: State): Value | null {
for (let i = 0; i < func.instrs.length; ++i) {
let line = func.instrs[i];
if ("op" in line) {
// Run an instruction.
let action = evalInstr(line, state);
// Take the prescribed action.
switch (action.action) {
case "end": {
// Return from this function.
return action.ret;
}
case "speculate": {
// Begin speculation.
state.specparent = { ...state };
state.env = new Map(state.env);
break;
}
case "commit": {
// Resolve speculation.
if (!state.specparent) {
throw error(`commit in non-speculative state`);
}
state.specparent = null;
break;
}
case "abort": {
// Restore state.
if (!state.specparent) {
throw error(`abort in non-speculative state`);
}
// We do *not* restore `icount` from the saved state to ensure that we
// count "aborted" instructions.
Object.assign(state, {
env: state.specparent.env,
lastlabel: state.specparent.lastlabel,
curlabel: state.specparent.curlabel,
specparent: state.specparent.specparent,
});
break;
}
case "next":
case "jump":
break;
default:
unreachable(action);
throw error(`unhandled action ${(action as any).action}`);
}
// Move to a label.
if ("label" in action) {
// Search for the label and transfer control.
for (i = 0; i < func.instrs.length; ++i) {
let sLine = func.instrs[i];
if ("label" in sLine && sLine.label === action.label) {
--i; // Execute the label next.
break;
}
}
if (i === func.instrs.length) {