-
Notifications
You must be signed in to change notification settings - Fork 4
/
reg.py
executable file
·2331 lines (1929 loc) · 91.5 KB
/
reg.py
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
#! /usr/bin/env python3
"""A more efficient compiler, using the "temp" segment as a set of registers to reduce stack usage.
Something like 50% of the opcodes produced by the standard compiler "push" values onto the stack.
The majority of those values are then consumed by the next opcode (or the one after); only a few
stay on the stack across a function call. If some of those short-lived values are stored
elsewhere, the stack pointer can be updated much less often, which saves a lot of instructions and
cycles.
The compiler has complete knowledge of which values actually need to appear on the stack
(essentially, the arguments of "call" ops.) All other values can potentially be stored elsewhere.
In particular, the 8 locations in the "temp" segment are otherwise unused, and can be treated as a
set of registers. Accessing one of them is much simpler than pushing/popping, because a) there's no
need to look up the current location of the top of the stack and b) there's no need to update the
stack pointer.
This compiler/translator starts with the normal Jack AST and analyzes it one method at a time.
Expressions are flattened through the use of temporary variables, so that no statement does
more than a single step. Then the lifetime (liveness) of each local/temporary variable is analyzed,
and each one is assigned a storage location that doesn't collide with any other variable whose
value is needed at the same time. Variables that need to retain their values across subroutine
calls are stored in the "local" space; all other variables are stored in "registers" — fixed
locations in low-memory that can be accessed without the overhead of updating the stack pointer.
Note: this compiler does not use the standard VM opcodes; instead, it translates to its own
IR (intermediate representation), which is more suited to analysis. Its Translator then converts
the IR directly to assembly. That makes the calling sequence a bit different from the rest of the
implementations.
Other differences:
- Subroutine results are stored in @12 (aka r7)
- Return addresses are stored at @4 (aka THAT)
- Each call site just pushes arguments, stashes the return address and then jumps to the "function"
address. It's up to each function to do any saving of registers and adjustment of the stack
that it wants to. That makes it possible do less work in the case of a simple function.
Note: it also means that things go (more) haywire if a call provides the wrong number of args.
These changes mean that the debug/trace logging done by some test cases doesn't always show the
correct arguments, locals, return addresses, and result values.
Extensions:
Two additional primitives are provided, to support dynamic dispatch (that is, storing the address
of a function or method and invoking it later):
- Jack.symbol(<string>): address of the given label.
- Jack.invoke(ptr): call the function referred to by the pointer.
For example, this code sequence:
var int fooPtr; // the type doesn't matter
let fooPtr = Jack.symbol("main.foo");
...
do Jack.invoke(fooPtr);
has the same effect as this simple call:
do Main.foo();
"""
from collections import Counter
import itertools
from os import name
from typing import Dict, Generic, List, NamedTuple, Optional, Sequence, Set, Tuple, TypeVar, Union
from nand import jack_ast
from nand.platform import Platform, BUNDLED_PLATFORM
from nand.translate import AssemblySource
from nand.solutions import solved_07, solved_11
from nand.solutions.solved_11 import SymbolTable, VarKind
OPTIMIZE_LEAF_FUNCTIONS = True
"""If True, a simpler call/return sequence is used for functions that do not need to manipulate the
stack (because they don't call any subroutines).
Saves ~30 instructions per leaf function in ROM, plus another ~30 at runtime. For small functions like
Math.min/max/abs, this might save ~50% of the space and ~70% of the time.
Possibly makes tracing/debugging confusing or useless in these functions.
"""
PRINT_LIVENESS = False
"""Print each function before assigning variables to registers.
Each statement is annotated with the set of variables which are 'live' at the beginning of
that statement. A live variable contains a value that will be used later; it must not be overwritten
at that point."""
PRINT_IR = False
"""Print each function immediately before emitting code.
Variables have been assigned to concrete locations, and each statement represents a unit
of work for which code can be generated directly.
"""
# IR
#
# A simplified AST for statements and expressions:
# - no nested expressions; each statement does a single calculation
# - if and while are still here, to simplify control-flow analysis
# - separate representations for local variables, which are not at first assigned to a specific
# location, and other variables, for which the location is fixed in the symbol table.
# - after analysis, local variables either get turned into references to the "local" space,
# or to specific registers (stored in the same memory the authors' VM calls the "temp" space)
#
# It doesn't have:
# - array indexing (it's been rewritten to explicit pointer arithmetic and Load/Store operations)
# - several of the address spaces of the author's VM aren't used as such "this", "that", "pointer",
# "temp".
#
# The stack is only used for subroutine arguments and results. The "local" space (also on the stack)
# is used for local variables that cannot be stored only in registers.
#
# This AST is low-level enough that it seems to make sense to call it the VM language and "translate"
# directly to assembly from it.
class Eval(NamedTuple):
"""Evaluate an expression and store the result somewhere."""
dest: "Local" # Actually Reg or Static after rewriting
expr: "Expr"
class IndirectWrite(NamedTuple):
"""Copy a value to the location given by address, aka poke()."""
address: "Value"
value: "Value"
class Store(NamedTuple):
"""Store a value to a location identified by segment and index (i.e. argument or local)."""
location: "Location"
value: "Value"
Cmp = str # requires 3.8: Literal["!="] # Meaning "non-zero"; TODO: the rest of the codes
class If(NamedTuple):
value: "Value"
cmp: Cmp
when_true: Sequence["Stmt"]
when_false: Optional[Sequence["Stmt"]]
class While(NamedTuple):
test: Sequence["Stmt"]
value: "Value"
cmp: Cmp
body: Sequence["Stmt"]
class Return(NamedTuple):
"""Evaluate expr (if present), store the value in the "RESULT" register, and return to the caller."""
expr: Optional["Expr"]
class Push(NamedTuple):
"""Used only with Subroutine calls. Acts like Eval, but the destination is the stack."""
expr: "Expr"
class Discard(NamedTuple):
"""Call a subroutine, then pop the stack, discarding the result."""
expr: Union["CallSub", "Invoke"]
Stmt = Union[Eval, IndirectWrite, Store, If, While, Push, Discard]
class CallSub(NamedTuple):
"""Call a subroutine (whose arguments have already been pushed onto the stack), and
recover the result from the "RESULT" register."""
class_name: str
sub_name: str
num_args: int
class Const(NamedTuple):
value: int # any value that fits in a word, including negatives
class Local(NamedTuple):
"""A variable which is local to the subroutine scope. May or may not end up actually
being stored on the stack in the "local" space."""
name: str # TODO: parameterize, so we can annotate, etc.?
class Location(NamedTuple):
"""A location identified by segment (argument/local) and index."""
kind: VarKind
idx: int
name: str # For debugging
class Reg(NamedTuple):
"""A variable which is local the the subroutine scope, does not need to persist
across subroutine calls, and has been assigned to a register."""
idx: int
name: str # include for debugging purposes
class Static(NamedTuple):
"""A static variable; just as efficient to access as Reg."""
name: str
class Temp(NamedTuple):
"""Pseudo-register location used when we know a variable is live only between adjacent
instructions, and it's safe to simply store it in D."""
name: str # for debugging
Value = Union[Const, Local, Reg, Static]
"""A value that's eligible to be referenced in any statement or expression."""
class Binary(NamedTuple):
left: "Value"
op: jack_ast.Op
right: "Value"
class Unary(NamedTuple):
op: jack_ast.Op
value: "Value"
class IndirectRead(NamedTuple):
"""Get the value given an address, aka peek()."""
address: "Value"
# Extensions:
class Symbol(NamedTuple):
"""Address of an arbitrary symbol."""
name: str
class Invoke(NamedTuple):
"""Call a subroutine given the address of its entry point."""
ptr: "Value"
# numArgs?
Expr = Union[CallSub, Const, Local, Location, Reg, Static, Binary, Unary, IndirectRead, Symbol, Invoke]
class Subroutine(NamedTuple):
name: str
num_args: int
num_vars: int
body: List[Stmt]
class Class(NamedTuple):
name: str
subroutines: List[Subroutine]
def flatten_class(ast: jack_ast.Class) -> Class:
"""Convert each subroutine to the "flattened" IR, which eliminates nested expressions and
other compound behavior, so that each statement does one thing, more or less.
"""
symbol_table = SymbolTable(ast.name)
solved_11.handle_class_var_declarations(ast, symbol_table)
return Class(ast.name, [flatten_subroutine(s, symbol_table) for s in ast.subroutineDecs])
def flatten_subroutine(ast: jack_ast.SubroutineDec, symbol_table: SymbolTable) -> Subroutine:
"""Rewrite the body of a subroutine so that it contains no complex/nested expressions,
by introducing a temporary variable to hold the result of each sub-expression.
Note: *not* converting to SSA form here. That would improve register allocation, but
it blows up the IR somewhat so holding off for now.
"""
solved_11.handle_subroutine_var_declarations(ast, symbol_table)
extra_var_count = 0
def next_var(name: Optional[str] = None) -> Local:
nonlocal extra_var_count
name = f"${name or ''}{extra_var_count}"
extra_var_count += 1
return Local(name)
if ast.kind == "method":
this_expr = Location("argument", 0, "this")
elif ast.kind == "constructor":
this_expr = next_var("this")
def resolve_name(name: str) -> Union[Local, Location, Static]:
# TODO: this makes sense for locals, arguments, and statics, but "this" needs to get flattened.
# How to deal with that?
kind = symbol_table.kind_of(name)
if kind == "local":
return Local(name)
elif kind == "static":
return Static(name)
else:
index = symbol_table.index_of(name)
return Location(kind, index, name)
def flatten_statement(stmt: jack_ast.Statement) -> List[Stmt]:
if isinstance(stmt, jack_ast.LetStatement):
if stmt.array_index is None:
loc = resolve_name(stmt.name)
if isinstance(loc, Local):
expr_stmts, expr = flatten_expression(stmt.expr, force=False)
let_stmt = Eval(dest=loc, expr=expr)
return expr_stmts + [let_stmt]
elif isinstance(loc, Static):
# Note: writing to a static is simple (no need to generate target address), so the
# RHS doesn't need to be in a register.
expr_stmts, expr = flatten_expression(stmt.expr, force=False)
let_stmt = Eval(loc, expr)
return expr_stmts + [let_stmt]
elif loc.kind == "this":
if isinstance(this_expr, Local):
this_var = this_expr
this_stmts = []
else:
this_var = next_var("this")
this_stmts = [Eval(this_var, Location("argument", 0, "self"))]
if loc.idx == 0:
addr_var = this_var
addr_stmts = []
else:
addr_var = next_var(loc.name)
addr_stmts = [Eval(addr_var, Binary(this_var, jack_ast.Op("+"), Const(loc.idx)))]
value_stmts, value_expr = flatten_expression(stmt.expr)
return value_stmts + this_stmts + addr_stmts + [IndirectWrite(addr_var, value_expr)]
else:
expr_stmts, expr = flatten_expression(stmt.expr, force=True)
let_stmt = Store(loc, expr)
return expr_stmts + [let_stmt]
else:
value_stmts, value_expr = flatten_expression(stmt.expr)
if stmt.array_index == jack_ast.IntegerConstant(0):
# Index 0 is the most common case:
address = jack_ast.VarRef(stmt.name)
else:
address = jack_ast.BinaryExpression(jack_ast.VarRef(stmt.name), jack_ast.Op("+"), stmt.array_index)
address_stmts, address_expr = flatten_expression(address)
return value_stmts + address_stmts + [IndirectWrite(address_expr, value_expr)]
elif isinstance(stmt, jack_ast.IfStatement):
test_stmts, test_value, test_cmp = flatten_condition(stmt.cond)
when_true = [fs for s in stmt.when_true for fs in flatten_statement(s)]
if stmt.when_false is not None:
when_false = [fs for s in stmt.when_false for fs in flatten_statement(s)]
else:
when_false = None
return test_stmts + [If(test_value, test_cmp, when_true, when_false)]
elif isinstance(stmt, jack_ast.WhileStatement):
test_stmts, test_value, test_cmp = flatten_condition(stmt.cond)
body_stmts = [fs for s in stmt.body for fs in flatten_statement(s)]
return [While(test_stmts, test_value, test_cmp, body_stmts)]
elif isinstance(stmt, jack_ast.DoStatement):
stmts, expr = flatten_expression(stmt.expr, force=False)
return stmts + [Discard(expr)]
elif isinstance(stmt, jack_ast.ReturnStatement):
if stmt.expr is not None:
stmts, expr = flatten_expression(stmt.expr, force=False)
return stmts + [Return(expr)]
else:
return [Return(None)]
else:
raise Exception(f"Unknown statement: {stmt}")
def flatten_condition(expr: jack_ast.Expression) -> Tuple[List[Stmt], Expr, Cmp]:
"""Inspect an expression used as the condition of if/while, and reduce it to some statements
preparing a value to be compared with zero.
"""
# First apply AST-level simplification, which reduces the number of possible shapes:
expr = simplify_expression(expr)
# Collapse anything that's become a comparison between two values:
if isinstance(expr, jack_ast.BinaryExpression) and expr.op.symbol in ("<", ">", "=", "<=", ">=", "!="):
if expr.right == jack_ast.IntegerConstant(0):
left_stmts, left_value = flatten_expression(expr.left)
return left_stmts, left_value, expr.op.symbol
else:
left_stmts, left_value = flatten_expression(expr.left)
right_stmts, right_value = flatten_expression(expr.right)
diff_var = next_var()
diff_stmt = Eval(diff_var, Binary(left_value, jack_ast.Op("-"), right_value))
return left_stmts + right_stmts + [diff_stmt], diff_var, expr.op.symbol
elif isinstance(expr, jack_ast.UnaryExpression) and expr.op.symbol == "~":
expr_stmts, expr_value = flatten_expression(expr.expr)
return expr_stmts, expr_value, "="
else:
expr_stmts, expr_value = flatten_expression(expr)
return expr_stmts, expr_value, "!="
def negate_cmp(cmp: Cmp) -> Cmp:
"""Negate the value."""
return {"<": ">=", ">": "<=", "=": "!=", "<=": ">", ">=": "<", "!=": "="}[cmp]
def invert_cmp(cmp: Cmp) -> Cmp:
"""Reverse the operand order."""
return {"<": ">", ">": "<", "=": "=", "<=": ">=", ">=": "<=", "!=": "!="}[cmp]
def flatten_expression(expr: jack_ast.Expression, force=True) -> Tuple[List[Stmt], Expr]:
"""Reduce an expression to something that's definitely trivial, possibly preceded
by some LetStatements introducing temporary vars.
If force is True, the resulting expression is always a "Value" (that is, either a constant
or a local.) If not, it may be an expression which can only appear as the right-hand side
of Eval or Push.
"""
expr = simplify_expression(expr)
if isinstance(expr, jack_ast.IntegerConstant):
return [], Const(expr.value)
elif isinstance(expr, jack_ast.KeywordConstant):
if expr.value == True:
return [], Const(-1) # Never wrapped
elif expr.value == False:
return [], Const(0) # Never wrapped
elif expr.value == None:
return [], Const(0) # Never wrapped
elif expr.value == "this":
stmts = []
flat_expr = this_expr
else:
raise Exception(f"Unknown keyword constant: {expr}")
elif isinstance(expr, jack_ast.VarRef):
loc = resolve_name(expr.name)
if isinstance(loc, (Local, Static)):
return [], loc # Never wrapped
elif loc.kind == "this":
if isinstance(this_expr, Local):
this_var = this_expr
this_stmts = []
else:
this_var = next_var("this")
this_stmts = [Eval(this_var, Location("argument", 0, "self"))]
if loc.idx == 0:
addr_var = this_var
addr_stmts = []
else:
addr_var = next_var(loc.name)
addr_stmts = [Eval(addr_var, Binary(this_var, jack_ast.Op("+"), Const(loc.idx)))]
stmts = this_stmts + addr_stmts
flat_expr = IndirectRead(addr_var)
else:
stmts = []
flat_expr = loc
elif isinstance(expr, jack_ast.StringConstant):
# Tricky: the result of each call is the string, which is the first argument to the
# next. "Push(CallSub(...))" logically means make the call, pop the result, then
# push it onto the stack. The actual implementation will be
stmts = (
[ Push(Const(len(expr.value))),
Push(CallSub("String", "new", 1)),
]
+ [s for c in expr.value for s in
[
# Note: the implicit first arg is already on the stack from the previous call
Push(Const(ord(c))),
Push(CallSub("String", "appendChar", 2)),
]])
last_push, stmts = stmts[-1], stmts[:-1]
flat_expr = last_push.expr
elif isinstance(expr, jack_ast.ArrayRef):
if expr.array_index == jack_ast.IntegerConstant(0):
# Index 0, probably the most common case:
address = jack_ast.VarRef(expr.name)
else:
address = jack_ast.BinaryExpression(jack_ast.VarRef(expr.name), jack_ast.Op("+"), expr.array_index)
address_stmts, address_expr = flatten_expression(address)
stmts = address_stmts
flat_expr = IndirectRead(address_expr)
elif isinstance(expr, jack_ast.SubroutineCall):
if expr.class_name == "Jack" and expr.sub_name == "symbol":
assert len(expr.args) == 1 and isinstance(expr.args[0], jack_ast.StringConstant)
stmts = []
flat_expr = Symbol(expr.args[0].value)
elif expr.class_name == "Jack" and expr.sub_name == "invoke":
# TODO: handle arguments, when someone needsw them
assert len(expr.args) == 1
target_stmts, target_expr = flatten_expression(expr.args[0])
stmts = target_stmts
flat_expr = Invoke(target_expr)
else:
pairs = [flatten_expression(a, force=False) for a in expr.args]
arg_stmts = [s for ss, x in pairs for s in ss + [Push(x)]]
if expr.class_name is not None:
stmts = arg_stmts
flat_expr = CallSub(expr.class_name, expr.sub_name, len(expr.args))
elif expr.var_name is not None:
instance_stmts, instance_expr = flatten_expression(jack_ast.VarRef(expr.var_name), force=False)
stmts = instance_stmts + [Push(instance_expr)] + arg_stmts
target_class = symbol_table.type_of(expr.var_name)
flat_expr = CallSub(target_class, expr.sub_name, len(expr.args) + 1)
else:
stmts = [Push(this_expr)] + arg_stmts
target_class = symbol_table.class_name
flat_expr = CallSub(target_class, expr.sub_name, len(expr.args) + 1)
elif isinstance(expr, jack_ast.BinaryExpression):
left_stmts, left_expr = flatten_expression(expr.left)
right_stmts, right_expr = flatten_expression(expr.right)
stmts = left_stmts + right_stmts
flat_expr = Binary(left_expr, expr.op, right_expr)
elif isinstance(expr, jack_ast.UnaryExpression):
stmts, child_expr = flatten_expression(expr.expr)
flat_expr = Unary(expr.op, child_expr)
else:
raise Exception(f"Unknown expression: {expr}")
if force:
var = next_var()
let_stmt = Eval(var, flat_expr)
return stmts + [let_stmt], var
else:
return stmts, flat_expr
if ast.kind == "function":
preamble_stmts = []
elif ast.kind == "method":
preamble_stmts = []
elif ast.kind == "constructor":
instance_word_count = symbol_table.count("this")
preamble_stmts = [
Push(Const(instance_word_count)),
Eval(this_expr, CallSub("Memory", "alloc", 1)),
]
else:
raise Exception(f"Unknown subroutine kind: {ast}")
statements = preamble_stmts + [ fs
for s in ast.body.statements
for fs in flatten_statement(s)
]
num_args = symbol_table.count("argument")
num_vars = None # bogus, but this isn't meaningful until the next phase anyway
return Subroutine(ast.name, num_args, num_vars, statements)
def simplify_expression(expr: jack_ast.Expression) -> jack_ast.BinaryExpression:
"""Reduce/canonicalize conditions to a more regular form:
Replace * and / expressions with calls to multiply/divide.
For comparison expressions:
- if there's a constant, it's on the right
- if the constant can be re-written to 0, it is
- flatten negated conditions and negative integer constants
"""
if isinstance(expr, jack_ast.UnaryExpression) and expr.op.symbol == "~":
if isinstance(expr.expr, jack_ast.BinaryExpression) and expr.expr.op.symbol == "<":
expr = jack_ast.BinaryExpression(expr.expr.left, jack_ast.Op(">="), expr.expr.right)
elif isinstance(expr.expr, jack_ast.BinaryExpression) and expr.expr.op.symbol == ">":
expr = jack_ast.BinaryExpression(expr.expr.left, jack_ast.Op("<="), expr.expr.right)
elif isinstance(expr.expr, jack_ast.BinaryExpression) and expr.expr.op.symbol == "=":
expr = jack_ast.BinaryExpression(expr.expr.left, jack_ast.Op("!="), expr.expr.right)
def simplify_constant(x: jack_ast.Expression) -> Optional[int]:
"""If possible, reduce the expression to a (possibly negative) constant."""
if isinstance(x, jack_ast.UnaryExpression) and x.op.symbol == "-" and isinstance(x.expr, jack_ast.IntegerConstant):
return -x.expr.value
elif isinstance(x, jack_ast.IntegerConstant):
return x.value
else:
return None
if isinstance(expr, jack_ast.BinaryExpression):
left = simplify_expression(expr.left)
right = simplify_expression(expr.right)
# TODO: this transformation is the same as the standard compiler; share that code?
if expr.op.symbol == "*":
return jack_ast.SubroutineCall("Math", None, "multiply", [left, right])
elif expr.op.symbol == "/":
return jack_ast.SubroutineCall("Math", None, "divide", [left, right])
elif expr.op.symbol in ("<", ">", "=", "<=", ">=", "!="):
def invert_cmp(cmp: Cmp) -> Cmp:
"""Reverse the operand order."""
return {"<": ">", ">": "<", "=": "=", "<=": ">=", ">=": "<=", "!=": "!="}[cmp]
simple_left = simplify_constant(expr.left)
simple_right = simplify_constant(expr.right)
if simple_left is not None and simple_right is None:
# Constant on the left; reverse the order:
return simplify_expression(jack_ast.BinaryExpression(expr.right,
jack_ast.Op(invert_cmp(expr.op.symbol)),
expr.left))
elif simple_right is not None:
# Constant on the right; match some common cases:
# The idea is to compare with 0 whenever possible, because that's what the chip
# actually provides directly.
zero = jack_ast.IntegerConstant(0)
if expr.op.symbol == "<" and simple_right == 1:
return jack_ast.BinaryExpression(expr.left, jack_ast.Op("<="), zero)
elif expr.op.symbol == ">=" and simple_right == 1:
return jack_ast.BinaryExpression(expr.left, jack_ast.Op(">"), zero)
elif expr.op.symbol == ">" and simple_right == -1:
return jack_ast.BinaryExpression(expr.left, jack_ast.Op(">="), zero)
elif expr.op.symbol == "<=" and simple_right == -1:
return jack_ast.BinaryExpression(expr.left, jack_ast.Op("<"), zero)
else:
return jack_ast.BinaryExpression(expr.left,
expr.op,
jack_ast.IntegerConstant(simple_right))
else:
return jack_ast.BinaryExpression(left, expr.op, right)
elif (isinstance(expr, jack_ast.UnaryExpression)
and expr.op.symbol == "-"
and isinstance(expr.expr, jack_ast.IntegerConstant)):
return jack_ast.IntegerConstant(-expr.expr.value)
# Nothing matched:
return expr
class LiveStmt(NamedTuple):
statement: Stmt
before: Set[str]
during: Set[str]
after: Set[str]
def analyze_liveness(stmts: Sequence[Stmt], live_at_end: Set[str] = set()) -> List[LiveStmt]:
"""Analyze variable lifetimes; a variable is live within all statements which
follow an assignment (not including the assignment), up to the last statement
that uses the value (including that statement.)
The point is that the value has to be stored somewhere at those points in the
program, and that location has to be somewhere that's not overwritten by the
statements.
This is the first step to allocating variables to locations (i.e. registers.)
Because I can't figure out how this should work, currently producing three results:
"live before" (e.g. the arguments of a subroutine call are live before the call is
performed) and "live after" (e.g. the arguments are no longer live once the call
happens, unless they're otherwise needed.) For now, the "after" of one statement is
identical to the "before" of the next. "during" may be different from them both,
in the case that the statement both reads and writes the same variable.
Update: now that the IR is much simpler, the difference is no longer very interesting
and it seems like "before" is good enough: we're only going to want to know what's
live when a CallSub happens, and CallSubs don't read anything now, so their before
and during are the same.
"""
def analyze_if(stmt: If, live_at_end: Set[str]) -> Tuple[Stmt, Set[str]]:
"""Nothing especially tricky here; it's just a pain that there may or may not
be an "else" block to thread the information through.
"""
when_true_liveness = analyze_liveness(stmt.when_true, live_at_end=live_at_end)
if len(when_true_liveness) > 0:
live_at_when_true_start = when_true_liveness[0].before
else:
live_at_when_true_start = live_at_end
if stmt.when_false is not None:
when_false_liveness = analyze_liveness(stmt.when_false, live_at_end=live_at_end)
if len(when_false_liveness) > 0:
live_at_when_false_start = when_false_liveness[0].before
else:
live_at_when_false_start = live_at_end
else:
when_false_liveness = None
live_at_when_false_start = live_at_end
live_at_body_start = live_at_when_true_start.union(live_at_when_false_start)
stmt = If(stmt.value, stmt.cmp, when_true_liveness, when_false_liveness)
live = live_at_body_start.union(refs(stmt.value))
return stmt, live
def analyze_while(stmt: While, live_at_end) -> Tuple[While, Set[str]]:
"""While is tricky because variables that are live at the beginning of the loop
therefore are also live at the end, which creates a circularity in the analysis.
Fortunately there's not much going on and simply repeating the same analysis should
arrive at a fixed point after one more pass.
"""
body_liveness = analyze_liveness(stmt.body, live_at_end=live_at_end)
if len(body_liveness) > 0:
live_at_body_start = body_liveness[0].before
else:
live_at_body_start = live_at_end
live_at_test_end = live_at_body_start.union(refs(stmt.value))
test_liveness = analyze_liveness(stmt.test, live_at_end=live_at_test_end)
if len(test_liveness) > 0:
live_at_test_start = test_liveness[0].before
else:
live_at_test_start = live_at_test_end
stmt = While(test_liveness, stmt.value, stmt.cmp, body_liveness)
live = live_at_test_start
return stmt, live.copy()
result = []
live_set = live_at_end.copy()
for stmt in reversed(stmts):
# Tricky: when analysis is repeated, strip out previous annotations
if isinstance(stmt, LiveStmt):
stmt = stmt.statement
written = set()
read = set()
if isinstance(stmt, Eval):
read.update(refs(stmt.expr))
written.update(refs(stmt.dest))
elif isinstance(stmt, IndirectWrite):
read.update(refs(stmt.address))
read.update(refs(stmt.value))
elif isinstance(stmt, Store):
read.update(refs(stmt.value))
elif isinstance(stmt, If):
# Note: overwriting stmt (and live_set) here:
stmt, live_set = analyze_if(stmt, live_set)
elif isinstance(stmt, While):
stmt1, live_set_at_top1 = analyze_while(stmt, live_set)
stmt2, live_set_at_top2 = analyze_while(stmt1, live_set_at_top1)
assert live_set_at_top2 == live_set_at_top1, "Liveness fixed point not reached"
# Note: overwriting stmt (and live_set) here:
stmt, live_set = stmt2, live_set_at_top2
elif isinstance(stmt, Return):
read.update(refs(stmt.expr))
elif isinstance(stmt, Push):
read.update(refs(stmt.expr))
elif isinstance(stmt, Discard):
read.update(refs(stmt.expr))
else:
raise Exception(f"Unknown statement: {stmt}")
after = live_set.copy()
live_set.difference_update(written)
during = live_set.copy()
live_set.update(read)
before = live_set.copy()
result.insert(0, LiveStmt(stmt, before, during, after))
return result
def refs(expr: Expr) -> Set[str]:
if isinstance(expr, Local):
return set([expr.name])
elif isinstance(expr, Binary):
return refs(expr.left).union(refs(expr.right))
elif isinstance(expr, Unary):
return refs(expr.value)
elif isinstance(expr, IndirectRead):
return refs(expr.address)
elif isinstance(expr, Invoke):
return refs(expr.ptr)
else:
return set()
def need_saving(liveness: Sequence[LiveStmt]) -> Set[str]:
"""Identify variables that need to be stored in a location that won't be
overwritten by a subroutine call (because at some time or other, their value
is "live" when a subroutine call occurs.)
"""
result = set()
for l in liveness:
if isinstance(l.statement, (Eval, Push, Discard)) and isinstance(l.statement.expr, (CallSub, Invoke)):
result.update(l.during)
elif isinstance(l.statement, If):
result.update(need_saving(l.statement.when_true))
if l.statement.when_false is not None:
result.update(need_saving(l.statement.when_false))
elif isinstance(l.statement, While):
result.update(need_saving(l.statement.test))
result.update(need_saving(l.statement.body))
else:
pass
return result
def promote_locals(stmts: Sequence[Stmt], map: Dict[Local, Location], prefix: str) -> List[Stmt]:
"""Rewrite statements and expressions, updating references to locals to refer to the given
locations. Where necessary, additional statements are introduced to move values around.
`prefix` has to be unique across calls; it ensures that names generated in different passes
don't collide.
"""
extra_var_count = 0
def next_var(name: Optional[str] = None) -> Local:
nonlocal extra_var_count
name = f"${prefix}{name or ''}{extra_var_count}"
extra_var_count += 1
return Local(name)
def rewrite_value(value: Value) -> Tuple[Sequence[Stmt], Value]:
if value in map:
var = next_var(map[value].name)
return [Eval(var, map[value])], var
else:
return [], value
def rewrite_expr(expr: Expr) -> Tuple[List[Stmt], Expr]:
if isinstance(expr, (CallSub, Const, Location, Static)):
return [], expr
elif isinstance(expr, Local):
if expr in map:
return [], map[expr]
else:
return [], expr
elif isinstance(expr, Binary):
left_stmts, left_value = rewrite_value(expr.left)
right_stmts, right_value = rewrite_value(expr.right)
return left_stmts + right_stmts, Binary(left_value, expr.op, right_value)
elif isinstance(expr, Unary):
stmts, value = rewrite_value(expr.value)
return stmts, Unary(expr.op, value)
elif isinstance(expr, IndirectRead):
stmts, address = rewrite_value(expr.address)
return stmts, IndirectRead(address)
elif isinstance(expr, Symbol):
return [], expr
elif isinstance(expr, Invoke):
stmts, ptr = rewrite_value(expr.ptr)
return stmts, Invoke(ptr)
else:
raise Exception(f"Unknown Expr: {expr}")
def rewrite_statement(stmt: Stmt) -> List[Stmt]:
if isinstance(stmt, Eval):
expr_stmts, expr = rewrite_expr(stmt.expr)
if stmt.dest in map:
if isinstance(expr, (Const, Local)):
return expr_stmts + [Store(map[stmt.dest], expr)]
else:
var = next_var(map[stmt.dest].name)
return expr_stmts + [Eval(var, expr), Store(map[stmt.dest], var)]
else:
return expr_stmts + [Eval(stmt.dest, expr)]
elif isinstance(stmt, IndirectWrite):
address_stmts, address_value = rewrite_value(stmt.address)
value_stmts, value_value = rewrite_value(stmt.value)
return address_stmts + value_stmts + [IndirectWrite(address_value, value_value)]
elif isinstance(stmt, Store):
value_stmts, value = rewrite_expr(stmt.value)
return value_stmts + [Store(stmt.location, value)]
elif isinstance(stmt, If):
value_stmts, value = rewrite_expr(stmt.value)
when_true = rewrite_statements(stmt.when_true)
when_false = rewrite_statements(stmt.when_false)
return value_stmts + [If(value, stmt.cmp, when_true, when_false)]
elif isinstance(stmt, While):
test = rewrite_statements(stmt.test)
value_stmts, value = rewrite_expr(stmt.value)
body = rewrite_statements(stmt.body)
return [While(test + value_stmts, value, stmt.cmp, body)]
elif isinstance(stmt, Return):
if stmt.expr is not None:
value_stmts, value = rewrite_expr(stmt.expr)
return value_stmts + [Return(value)]
else:
return [Return(None)]
elif isinstance(stmt, Push):
expr_stmts, expr = rewrite_expr(stmt.expr)
return expr_stmts + [Push(expr)]
elif isinstance(stmt, Discard):
expr_stmts, expr = rewrite_expr(stmt.expr)
return expr_stmts + [Discard(expr)]
else:
raise Exception(f"Unknown Stmt: {stmt}")
def rewrite_statements(stmts: Optional[Sequence[Stmt]]) -> Optional[List[Stmt]]:
if stmts is not None:
return [rs for s in stmts for rs in rewrite_statement(s)]
else:
return None
return rewrite_statements(stmts)
# Next step: assign variables to locations (aka register allocation)
# - consult the symbol table: anything not "local" already has its place
# - any variable that needs saving gets asigned an index in "local" space
# - what's left is local variables that can potentially be assigned to registers
#
# Now, try to assign each un-allocated local variable a color such that:
# - no two variables that are live at the same time have the same color
# - one of: as few colors as possible; a reasonably small number of colors; no more than eight colors
#
# Choose no more than eight colors to be assigned to "registers". The remaining
# get mapped to "local".
#
#
V = TypeVar("V")
def color_graph(vertices: Sequence[V], edges: Sequence[Tuple[V, V]]) -> List[Set[V]]:
"""Given a collection of vertices, and a collection of edges, each connecting
two vertices of a graph, assign each vertex a color such that no vertex has the
same color as any other vertex with which it shares an edge.
There may be unconnected vertices, but there must be no edges that refer to
vertices that aren't present.
Return a set of sets, each containing vertices of a particular color. Note:
the colors are purely conceptual; there's no actual color value associated with
each set.
In theory, you would want this to return the optimal result: the smallest possible
number of colors. At the moment, it doesn't try very hard, but it shouldn't produce
a trivially bad result; there won't be any two colors that could be merged together.
Beyond that, it tends to put vertices in the first possible set, so the color groups
should get smaller as you get further into the result.
It's also probably not fast. At worst O(v*c + e), v = # of vertices, e = # of edges,
c = # of colors. Wikipedia says you can get the same result faster by reversing the
nesting of loops (https://en.wikipedia.org/wiki/Greedy_coloring).
>>> color_graph(vertices=[1,2,3,4], edges=[(1,2), (2,3)])
[{1, 3, 4}, {2}]
"""
# Set of connected vertices for each vertex (bidirectionally):
adjacency: Dict[V, Set[V]] = { v: set() for v in vertices }
for x, y in edges:
adjacency[x].add(y)
adjacency[y].add(x)
# Visit each vertex in order. Assign each vertex to the lowest-numbered color
# which it is still possible for it have, based on the color assignments that have
# been made so far. Note: this should always give the same result, when the vertices
# are supplied in the same order. The order of edges is irrelevant.
prohibited_colors: Dict[V, Set[int]] = { v: set() for v in vertices }
color_sets: List[Set[V]] = []
for v in vertices:
color = [c for c in range(len(color_sets)+1) if (c not in prohibited_colors[v])][0]
if color == len(color_sets):
color_sets.append(set())
color_sets[color].add(v)
for a in adjacency[v]:
prohibited_colors[a].add(color)
return color_sets
def color_locals(liveness: Sequence[LiveStmt]) -> List[Set[Local]]:
"""Color the liveness graph (in a super dumb way), grouping locals such that:
- no two locals that are alive at the same time are in the same set
- TODO: when one local is the source and another the destination of a particular operation,
they're in the same group
But mostly the first thing.
"""
vars: Set[Local] = set()
overlaps: Set[Tuple[Local, Local]] = set()
def add_live_set(live: Sequence[Local]):
for l in live: vars.add(l)
for pair in itertools.combinations(live, 2):
overlaps.add(pair)
def visit_stmt(stmt: LiveStmt):
add_live_set([Local(n) for n in stmt.before])
if isinstance(stmt.statement, If):
visit_stmts(stmt.statement.when_true)
visit_stmts(stmt.statement.when_false)
elif isinstance(stmt.statement, While):
visit_stmts(stmt.statement.test)
visit_stmts(stmt.statement.body)
# Arg: the value being tested may not otherwise ever be live, but it needs to be accounted for
if isinstance(stmt.statement.value, Local):
add_live_set([stmt.statement.value] + [Local(l) for l in stmt.statement.body[0].before])
def visit_stmts(stmts: Optional[Sequence[LiveStmt]]):
if stmts is not None:
for stmt in stmts:
visit_stmt(stmt)
visit_stmts(liveness)
# Sort the vars so that named vars get assigned to registers first, mostly to make the result
# more predictable for test assertions.
sorted_vars = sorted(vars, key=lambda lcl: (lcl.name.startswith("$"), lcl.name))
color_sets = color_graph(vertices=sorted_vars, edges=overlaps)
# import pprint
# pprint.pprint(color_sets)