-
Notifications
You must be signed in to change notification settings - Fork 2
/
compiler.py
1971 lines (1728 loc) · 83.1 KB
/
compiler.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
import ast
from ast import *
from utils import *
from x86_ast import *
from graph import *
from collections import deque
from priority_queue import *
import os
import types
from functools import *
from typing import List, Set, Dict
import typing
import type_check_Llambda
# Type notes
Binding = typing.Tuple[Name, expr]
Temporaries = List[Binding]
# Global register categorization
# Register used for argument passing
arg_passing = ['rdi', 'rsi', 'rdx', 'rcx', 'r8', 'r9', ]
caller_saved = arg_passing + ['rax', 'r10', 'r11']
callee_saved = ['rsp', 'rbp', 'rbx', 'r12', 'r13', 'r14', 'r15']
# Allocatable registers = all - rsp - rbp - rax - r11 - r15
allocatable = callee_saved + caller_saved
# TODO: use a list: reserved_regs = ['rsp', 'rbp', 'rbx', 'rax', 'r11', 'r15']
allocatable.remove('rsp')
allocatable.remove('rbp')
allocatable.remove('rax')
allocatable.remove('r11')
allocatable.remove('r15')
def force(promise):
if isinstance(promise, types.FunctionType):
return force(promise())
else:
return promise
def analyze_dataflow(G: DirectedAdjList, transfer: FunctionType, bottom, join: FunctionType):
"""return a mapping from vertices in G to their dataflow result"""
trans_G = transpose(G)
mapping = {}
for v in G.vertices():
mapping[v] = bottom
worklist = deque()
for v in G.vertices():
worklist.append(v)
while worklist:
node = worklist.pop()
input = reduce(join, [mapping[v] for v in G.out[node]], bottom)
# input = reduce(join, [mapping[v] for v in trans_G.adjacent(node)], bottom)
output = transfer(node, input)
if output != mapping[node]:
mapping[node] = output
# for v in G.adjacent(node):
for v in G.ins[node]:
worklist.append(v)
return mapping
class Compiler:
"""compile the whole program, and for each function, call methods in `CompileFunction`"""
# TODO: How to ref CompileFunction.arg_passing?
# num_arg_passing_regs = len(CompileFunction.arg_passing)
num_arg_passing_regs = 6
def __init__(self):
self.functions = []
# function -> CompileFunction instance
self.function_compilers = {}
# function -> {original_name: new_name}
self.function_limit_renames = {}
self.num_uniquified_counter = 0
self.closure_count: int = 0
def shrink(self, p: Module) -> Module:
"""create main function, making the module body a series of function definitions"""
assert(isinstance(p, Module))
# main_args = arguments([], [], [], [], [])
main = FunctionDef('main', args=[], body=[],
decorator_list=[], returns=int)
new_module = []
for c in p.body:
match c:
case FunctionDef(name, _args, _body, _deco_list, _rv_type):
new_module.append(c)
self.functions.append(name)
# print("DEBUG, function: ", name, "args: ", args.args, body, _deco_list, _rv_type)
case stmt():
main.body.append(c)
main.body.append(Return(Constant(0)))
new_module.append(main)
# print("DEBUG, new module: ", new_module)
return Module(new_module)
def uniquify(self, p: Module) -> Module:
# this function should be able to be move to `CompileFunction`
# if `self.num_uniquified_counter` is accessible by `CompileFunction`
class Uniquify(NodeTransformer):
def __init__(self, outer: Compiler, mapping: dict):
self.outer_instance = outer
self.uniquify_mapping = mapping
super().__init__()
def visit_Lambda(self, node):
self.generic_visit(node)
match node:
case Lambda(args, body_expr):
new_mapping = self.uniquify_mapping.copy()
new_args = []
for v in args:
new_v = v + "_" + \
str(self.outer_instance.num_uniquified_counter)
# find the new name in the previous mapping
if v in new_mapping:
new_mapping[new_mapping[v]] = new_v
# delete the old mapping
del new_mapping[v]
else:
new_mapping[v] = new_v
new_args.append(new_v)
self.outer_instance.num_uniquified_counter += 1
new_uniquifier = Uniquify(
self.outer_instance, new_mapping)
new_body_expr = new_uniquifier.visit(body_expr)
return Lambda(new_args, new_body_expr)
case _:
return node
def visit_Name(self, node):
self.generic_visit(node)
match node:
case Name(id):
if id in self.uniquify_mapping:
return Name(self.uniquify_mapping[id])
else:
return node
case _:
return node
def do_uniquify(stmts: list, uniquify_mapping: dict) -> list:
"""change the variable names of statements in place according to the uniquify_mapping"""
uniquifier = Uniquify(self, uniquify_mapping)
new_body = []
for s in stmts:
new_body.append(uniquifier.visit(s))
return new_body
assert(isinstance(p, Module))
for f in p.body:
assert(isinstance(f, FunctionDef))
uniquify_mapping = {}
new_args = []
for v in f.args:
# print("DEBUG, v: ", v[0], "type: ", type(v[0]))
new_arg_name = v[0] + "_" + str(self.num_uniquified_counter)
uniquify_mapping[v[0]] = new_arg_name
new_args.append((new_arg_name, v[1], ))
self.num_uniquified_counter += 1
f.args = new_args
f.body = do_uniquify(f.body, uniquify_mapping)
return p
def convert_assignments(self, p: Module) -> Module:
assert(isinstance(p, Module))
for f in p.body:
assert(isinstance(f, FunctionDef))
self.function_compilers[f.name] = CompileFunction(f.name)
bounded_vars = set([v[0] for v in f.args])
# print("DEBUG, bounded_vars: ", bounded_vars)
(f.body, af) = self.function_compilers[f.name].convert_assignments(
f.body, bounded_vars)
args = [v[0] for v in f.args]
for v in af:
if v in args:
f.body.insert(
0, Assign([Name(v + '_')], Tuple([Name(v)], Load())))
else:
# assign a dummy value
f.body.insert(
0, Assign([Name(v + '_')], Tuple([Constant(10086)], Load())))
return p
def reveal_functions(self, p: Module) -> Module:
"""change `Name(f)` to `FunRef(f)` for functions defined in the module"""
class RevealFunction(NodeTransformer):
def __init__(self, outer: Compiler):
self.outer_instance = outer
super().__init__()
def visit_Name(self, node):
self.generic_visit(node)
match node:
case Name(f) if f in self.outer_instance.functions:
# TODO: iterable `FunRef`
# what if f is a builtin function? guard needed
self.generic_visit(node)
return FunRef(f)
case _:
return node
assert(isinstance(p, Module))
# Why this does't work?
# new_body = RevealFunction(self).visit_Call(p)
# p.body = new_body
for f in p.body:
new_body = []
for s in f.body:
new_line = RevealFunction(self).visit_Name(s)
new_body.append(new_line)
# print("DEBUG, new node: ", ast.dump(n))
f.body = new_body
type_check_Llambda.TypeCheckLlambda().type_check(p)
return p
def convert_to_closures(self, p: Module) -> Module:
def translateType(t): # TODO: fix for nested too (when make lambdas and return type)
"""repair return types of functions"""
match t:
case FunctionType(argTypes, returnType):
fixed_return = translateType(returnType)
return TupleType( [FunctionType( [TupleType([])] + argTypes, fixed_return )] )
case _:
return t
# TupleType( [FunctionType( [TupleType([])] + argTypes, returnType )] )
class ConvertToClosure(NodeTransformer):
def __init__(self, outer: Compiler):
self.outer_instance = outer
self.newFunctionDefs = []
self.bound_lambda_vars = {} # lambda_name : [bound vars (str)]
super().__init__()
def visit_Lambda(self, node):
class FreeVars(NodeTransformer):
def __init__(self, outer: ConvertToClosure, boundArgs: list[str]):
self.outer_instance = outer
self.bound_args = [Name(v) for v in boundArgs]
self.args_occurred: list[Name] = []
super().__init__()
# TODO: maybe delete the lambdas case
def visit_Lambda(self, node):
"""visit nested lambdas and put their args in bound_args"""
self.generic_visit(node)
match node:
case Lambda(args, body_expr):
for arg in args:
self.bound_args.append(Name(arg))
return node
def visit_FunRef(self, node):
"""visit nested lambdas (now FunRefs) and put their args in bound_args"""
self.generic_visit(node)
match node:
case FunRef(f) if f.startswith('lambda_'):
for v in self.outer_instance.bound_lambda_vars[f]:
self.bound_args.append(Name(v))
return node
def visit_Name(self, node):
"""put all non-(known)bound Name()s in args_occured"""
self.generic_visit(node)
match node:
case Name(var) if node not in self.bound_args:
self.args_occurred.append(node)
return node
def free_vars(boundArgs: list[str], bodyNode) -> list[Name]:
"""returns a list of the free variables of a lambda expression"""
free_vars_finder = FreeVars(self, boundArgs)
free_vars_finder.visit(bodyNode)
freeVars = [v for v in free_vars_finder.args_occurred if v not in free_vars_finder.bound_args]
return freeVars
self.generic_visit(node)
match node:
case Lambda(args, body_expr):
# generate names for lambda function and the closure arg
name = "lambda_" + str(self.outer_instance.closure_count)
self.outer_instance.closure_count += 1
closureArgName = "fvs_" + str(self.outer_instance.closure_count)
self.outer_instance.closure_count += 1
# add args to the bound list
self.bound_lambda_vars[name] = args
# process free vars for closure and function def
closureLst = [FunRef(name)]
closureArgTypes = [Bottom()]
newFunBody = []
argCt = 1
for v in free_vars(args, body_expr):
# print("\t" + repr(v) + "\tType: " + str(v.has_type))
closureLst.append(v) # appending name nodes
closureArgTypes.append(v.has_type)
# assign closure args to local variables in the new lambda function
newFunBody.append(Assign([v], Subscript(Name(closureArgName), Constant(argCt), Load())))
argCt += 1
newFunBody.append(Return(body_expr)) # body nodes already visited automatically with all the other nodes of the ast
newFunArgs = [(closureArgName, TupleType(closureArgTypes))] # function args are (string, type)
# create new typed function definition for the lambda
match node.has_type:
case FunctionType(argTypes, returnType):
# put bound vars with types into args for new function
i = 0
for arg in args:
newFunArgs.append((arg, argTypes[i]))
i += 1
# create new function
self.newFunctionDefs.append(FunctionDef(name, args=newFunArgs, body=newFunBody, decorator_list=[], returns=translateType(returnType)))
# print("LAMBDA,\t" + name + "\t" + str(translateType(returnType)))
self.outer_instance.functions.append(name)
case _:
raise Exception('error in visit_Lambda of closure conversion, unsupported lambda type ' + node.has_type)
return Tuple(closureLst, Load()) # return closure
case _:
return node
def visit_Call(self, node: Call):
self.generic_visit(node)
match node:
case Call(fun, args) if not (fun == Name('print') or fun == Name('len') or fun == Name('input_int')):
tmp = "clos_" + str(self.outer_instance.closure_count)
self.outer_instance.closure_count += 1
return Let(Name(tmp), fun, Call(Subscript(Name(tmp), Constant(0), Load()), [Name(tmp)] + args))
case _:
return node
def visit_FunRef(self, node):
self.generic_visit(node)
match node:
case FunRef(f):
return Tuple([FunRef(f)], Load())
case _:
return node
def visit_AnnAssign(self, node):
self.generic_visit(node)
match node:
case AnnAssign(var, t, exp, o):
return Assign([var], exp)
case _:
return node
assert(isinstance(p, Module))
type_check_Llambda.TypeCheckLlambda().type_check(p)
new_module = []
for f in p.body:
assert isinstance(f, FunctionDef)
# process body
closure_converter = ConvertToClosure(self)
new_body = []
for s in f.body:
new_body.append(closure_converter.visit(s))
f.body = new_body
# add possible created lambda functions to the module
new_module += closure_converter.newFunctionDefs
# add closure argument because all functions are now closures
if f.name != 'main':
closureArgName = "fvs_" + str(self.closure_count)
self.closure_count += 1
new_arg = [(closureArgName, Bottom())]
f.args = new_arg + f.args
match f:
case FunctionDef(name, args, body, dec_list, returnType):
new_args = []
for arg in args:
new_args.append((arg[0], translateType(arg[1])))
new_module.append(FunctionDef(name, new_args, body, dec_list, translateType(returnType)))
# print("outter,\t" + name + "\t" + str(translateType(returnType)) + "\n\tBefore:\t" + str(returnType))
case _:
# print("ERROR in closure conversion")
pass
# new_module.append(f)
# new_new_module = [] # module with fixed return types
# # repair return types of functions
# for f in new_module:
# match f:
# case FunctionDef(name, args, body, dec_list, returnType):
# new_args = []
# for arg in args:
# new_args.append((arg[0], translateType(arg[1])))
# new_new_module.append(FunctionDef(name, new_args, body, dec_list, translateType(returnType)))
# print("outter,\t" + name + "\t" + str(translateType(returnType)) + "\n\tBefore:\t" + str(returnType))
# case _:
# print("ERROR in closure conversion")
# return Module(new_new_module)
return Module(new_module)
def limit_functions(self, p: Module) -> Module:
"""limit functions to 6 arguments, anything more gets put into a 6th tuple-type argument"""
class LimitFunction(NodeTransformer):
# limit call sites & convert name of args
def __init__(self, outer: Compiler, mapping: dict = {}):
self.outer_instance = outer
self.mapping = mapping
super().__init__()
def visit_Name(self, node):
# substitute the >5th arguments with subscript of a tuple
self.generic_visit(node)
match node:
case Name(n) if n in self.mapping.keys():
return self.mapping[n]
case _:
return node
def visit_Call(self, node):
self.generic_visit(node)
match node:
case Call(FunRef(f), args) if len(args) > Compiler.num_arg_passing_regs:
# print("DEBUG, HIT in visit_FunRef: ", ast.dump(node))
new_args = args[:Compiler.num_arg_passing_regs - 1]
new_args.append(
Tuple(args[Compiler.num_arg_passing_regs - 1:], Load()))
return Call(FunRef(f), new_args)
case _:
return node
def args_need_limit(args):
if isinstance(args, list):
# print("DEBUG, args: ", args, type(args))
# print("DEBUG, argsAST: ", args[1][0])
return len(args) > Compiler.num_arg_passing_regs
# else:
# print("DEBUG, args: ", ast.dump(args))
return False
assert(isinstance(p, Module))
# limit defines
for f in p.body:
match f:
case FunctionDef(_name, args, _body, _deco_list, _rv_type) if args_need_limit(args):
# args = args.args
new_args = args[:5]
arg_tup = ('tup_arg', TupleType([a[1] for a in args[5:]]))
alias_mapping = {}
for i in range(5, len(args)):
# TODO: How is this allocated on the heap or appears in shadow stack?
# print("DEBUG, dump arg[i]: ", ast.dump(args.args[i]))
alias_mapping[args[i][0]] = Subscript(
Name('tup_arg'), Constant(i - 5), Load())
# print("DEBUG, alias_mapping: ", alias_mapping)
new_args.append(arg_tup)
# print("DEBUG, new_args: ", new_args)
f.args = new_args
new_body = []
for s in f.body:
# new_line is new node
new_line = LimitFunction(
self, alias_mapping).visit_Name(s)
# print("DEBUG, new_line: ", new_line)
new_body.append(new_line)
# print("DEBUG, new_body: ", new_body)
f.body = new_body
case _:
assert(isinstance(f, FunctionDef))
new_body = []
for s in f.body:
new_line = LimitFunction(self).visit_Call(s)
new_body.append(new_line)
f.body = new_body
# force the autograder to re-evaluate the types in function definition
# should be removed in production
type_check_Llambda.TypeCheckLlambda().type_check(p)
return p
def remove_complex_operands(self, p: Module) -> Module:
assert(isinstance(p, Module))
for f in p.body:
assert(isinstance(f, FunctionDef))
self.function_compilers[f.name] = CompileFunction(f.name)
f.body = self.function_compilers[f.name].remove_complex_operands(
Module(f.body))
return p
def explicate_control(self, p: Module) -> CProgramDefs:
match p:
case Module(defs):
for f in p.body:
assert(isinstance(f, FunctionDef))
f.body = self.function_compilers[f.name].explicate_control(
Module(f.body))
return CProgramDefs(p.body)
def select_instructions(self, p: CProgramDefs) -> X86ProgramDefs:
assert(isinstance(p, CProgramDefs))
for f in p.defs:
assert(isinstance(f, FunctionDef))
# select instructions
f.body = self.function_compilers[f.name].select_instructions(
CProgram(f.body))
new_start_block = []
i = 0
# add instr to move each register into arg in at the beginning of the block
for arg in f.args:
match arg[0]:
case var if isinstance(var, str):
new_start_block.append(
Instr('movq', [Reg(arg_passing[i]), Variable(var)]))
i += 1
case _:
# print("DEBUG in selecting ARG: " + str(type(arg[0])))
pass
# fix the block
new_start_block += f.body[f.name + "start"]
f.body[f.name + "start"] = new_start_block
# fix function definition
f.args = []
# TODO: why?
f.returns = int
return X86ProgramDefs(p.defs)
def assign_homes(self, p: X86ProgramDefs) -> X86ProgramDefs:
# assert(isinstance(p, X86ProgramDefs))
# for f in p.defs:
# assert(isinstance(f, FunctionDef))
# f.body = self.function_compilers[f.name].select_instructions(X86Program(f.body))
# print("finished assigning homes")
# return X86ProgramDefs(p.defs)
assert(isinstance(p, X86ProgramDefs))
for f in p.defs:
assert(isinstance(f, FunctionDef))
f.body = self.function_compilers[f.name].assign_homes(
X86Program(f.body))
return X86ProgramDefs(p.defs)
def patch_instructions(self, p: X86ProgramDefs) -> X86ProgramDefs:
assert(isinstance(p, X86ProgramDefs))
for f in p.defs:
assert(isinstance(f, FunctionDef))
f.body = self.function_compilers[f.name].patch_instructions(
X86Program(f.body))
return X86ProgramDefs(p.defs)
def prelude_and_conclusion(self, p: X86ProgramDefs) -> X86Program:
assert(isinstance(p, X86ProgramDefs))
new_body = {}
for f in p.defs:
assert(isinstance(f, FunctionDef))
f.body = self.function_compilers[f.name].prelude_and_conclusion(
X86Program(f.body))
# print("DEBUG, f.body: ", f.body)
new_body.update(f.body)
return X86Program(new_body)
class CompileFunction:
"""compile a single function"""
temp_count: int = 0
tup_temp_count: int = 0
# used for tracking static stack usage
normal_stack_count: int = 0
shadow_stack_count: int = 0
tuple_vars = []
# `calllq`: include first `arg_num` registers in its read-set R
arg_passing = [Reg(x) for x in arg_passing]
# `callq`: include all caller_saved registers in write-set W
caller_saved = [Reg(x) for x in caller_saved]
callee_saved = [Reg(x) for x in callee_saved]
builtin_functions = ['input_int', 'print', 'len']
builtin_functions = [Name(i) for i in builtin_functions]
def __init__(self, name: str):
self.name = name
self.basic_blocks = {}
# mappings from a single instruction to a set
self.read_set_dict = {}
self.write_set_dict = {}
self.live_before_set_dict = {}
self.live_after_set_dict = {}
# this list can be changed for testing spilling
self.allocatable = [Reg(x) for x in allocatable]
all_reg = [Reg('r11'), Reg('r15'), Reg('rsp'), Reg(
'rbp'), Reg('rax')] + self.allocatable
self.int_graph = UndirectedAdjList()
self.move_graph = UndirectedAdjList()
self.control_flow_graph = DirectedAdjList()
self.live_before_block = {}
self.prelude_label = self.name
# assign this when iterating CFG
self.conclusion_label = self.name + 'conclusion'
self.basic_blocks[self.conclusion_label] = []
# make the initial conclusion non-empty to avoid errors
# TODO: come up with a more elegant solution, maybe from `live_before_block`
# self.basic_blocks[self.conclusion_label] = [Expr(Call(Name('input_int'), []))]
# why need this?
self.sorted_control_flow_graph = []
self.used_callee = set()
self.stack_frame_size: int
self.shadow_stack_size: int
# Reserved registers
self.color_reg_map = {}
color_from = -5
for reg in all_reg:
self.color_reg_map[color_from] = reg
color_from += 1
def extend_reg(r: Reg) -> Reg:
match r:
case Reg(name) if len(name) == 3 and name[0] == 'r':
return r
case Reg(name) if len(name) == 3 and name[0] == 'e':
return Reg('r' + name[1:])
case Reg(name) if len(name) == 2:
return Reg('r' + name[0] + 'x')
case _:
raise Exception(
'error in extend_reg, unsupported register name ' + repr(r))
############################################################################
# Assignment Conversion
############################################################################
def convert_assignments(self, p: list, bounded: set) -> tuple[list, list]:
"""convert assignments to instructions"""
# def
class AssignmentTraverse(NodeVisitor):
def __init__(self, bounded_vars: set):
self.bounded_vars = bounded_vars
self.free_vars = []
self.free_vars_lambda = {}
self.assigned_vars = []
super().__init__()
def visit_Assign(self, node):
# it doesn't matter if the Lambda node is traversed.
self.generic_visit(node)
match node:
case Assign([Name(var)], _):
# print("DEBUG, hit in visit_Assign, node: ", node)
self.assigned_vars.append(var)
def visit_Lambda(self, node):
self.generic_visit(node)
match node:
case Lambda(args, body_expr):
# print("DEBUG, hit in visit_Lambda, node: ", node)
new_assignment_converter = AssignmentTraverse(
set(args))
new_assignment_converter.visit_Name(body_expr)
self.free_vars_lambda[node] = new_assignment_converter.free_vars
return node
def visit_Name(self, node):
self.generic_visit(node)
match node:
case Name(var):
if var not in self.bounded_vars:
self.free_vars.append(var)
return Name(var)
def visit_Call(self, node):
# mask visits to calls
pass
class AssignmentConvert(NodeTransformer):
# convention: the varibales that are AssignmentConvert'ed are added a suffix '_'
def __init__(self, af_vars: set):
self.af = af_vars
super().__init__()
def visit_Assign(self, node):
# print("DEBUG, visit_Assign, node: ", node)
match node:
case Assign([Name(var)], rhs) if var in self.af:
return Assign([Subscript(Name(var + '_'), Constant(0), Store())], self.generic_visit(rhs))
case _:
self.generic_visit(node)
return node
def visit_Name(self, node):
match node:
case Name(var) if var in self.af:
return Subscript(Name(var + '_'), Constant(0), Load())
case _:
self.generic_visit(node)
return node
assert(isinstance(p, list))
traverser = AssignmentTraverse(bounded)
for s in p:
traverser.visit(s)
assigned_vars = set(traverser.assigned_vars)
free_vars_in_lambda = []
for (_, vs) in traverser.free_vars_lambda.items():
free_vars_in_lambda += vs
free_vars_in_lambda = set(free_vars_in_lambda)
af_vars = free_vars_in_lambda.intersection(assigned_vars)
# print("TRACE, free_vars_in_lambda: ", free_vars_in_lambda)
# print("TRACE, assigned_vars: ", assigned_vars)
# print("TRACE, af_vars: ", af_vars)
converter = AssignmentConvert(af_vars)
new_p = []
for s in p:
new_s = converter.visit(s)
# print("TRACE, converted s: ", new_s)
new_p.append(new_s)
return (new_p, af_vars)
############################################################################
# Expose Allocation
############################################################################
def expose_allocation_hide(self, t: Tuple) -> Begin:
# Autograder call `expose_allocation` in a wrong way, so this is hidden from the autograder
"""convert a tuple creation into a begin"""
assert(isinstance(t, Tuple))
content = t.elts
body = []
for i in range(len(content)):
if not CompileFunction.is_atm(content[i]):
# print("DEBUG: ???")
temp_name = 'temp_tup' + \
str(self.tup_temp_count) + 'X' + str(i)
body.append(Assign([Name(temp_name)], content[i]))
tup_bytes = (len(content) + 1) * 8
if_cond = Compare(BinOp(GlobalValue('free_ptr'), Add(), Constant(tup_bytes)), [
Lt()], [GlobalValue('fromspace_end')])
body.append(If(if_cond, [], [Collect(tup_bytes)]))
var = Name("pyc_temp_tup_" + str(self.tup_temp_count))
body.append(Assign([var], Allocate(len(content), t.has_type)))
for i in range(len(content)):
if not CompileFunction.is_atm(content[i]):
body.append(Assign([Subscript(var, Constant(i), Store())], Name(
'temp_tup' + str(self.tup_temp_count) + 'X' + str(i))))
else:
body.append(
Assign([Subscript(var, Constant(i), Store())], content[i]))
self.tup_temp_count += 1
return Begin(body, var)
############################################################################
# Remove Complex Operands
############################################################################
def is_atm(e: expr):
"""helper function to check if `e` is an `atm` """
match e:
case Constant(c):
return True
return isinstance(c, bool) or isinstance(c, int)
case Name(_):
return True
return False
def letize(self, exp: expr) -> expr:
"""using `let`s to remove complex in an expression"""
# TODO: also allow some `exp`s rather than atoms only
(tail, temps) = self.rco_exp(exp, False)
for var in reversed(temps):
tail = Let(var[0], var[1], tail)
return tail
def rco_exp(self, e: expr, need_atomic: bool) -> typing.Tuple[expr, Temporaries]:
temps = []
# tail must be assigned in the match cases
if CompileFunction.is_atm(e):
"""nothing need to do if it's already an `atm`"""
return (e, temps)
match e:
# recursively call rco_exp on each op
# shrink `and` & `or`
case BoolOp(And(), args):
return self.rco_exp(IfExp(args[0], args[1], Constant(False)), need_atomic)
case BoolOp(Or(), args):
return self.rco_exp(IfExp(args[0], Constant(True), args[1]), need_atomic)
# call expose_allocation for tuple creation
case Tuple(_, Load()):
# TODO: may need to consider temps and bindings
return self.rco_exp(self.expose_allocation_hide(e), need_atomic)
case Begin(body, result):
# TODO
new_body = [
new_stat for s in body for new_stat in self.rco_stmt(s)]
tail = Begin(new_body, result)
case UnaryOp(uniop, exp):
# `Not()` and `USub`
if CompileFunction.is_atm(exp):
tail = e
else:
(atm, temps) = self.rco_exp(exp, True)
tail = UnaryOp(uniop, atm)
case BinOp(exp1, binop, exp2):
"""Sub() and Add()"""
if CompileFunction.is_atm(exp1):
(exp1_atm, exp1_temps) = (exp1, [])
else:
(exp1_atm, exp1_temps) = self.rco_exp(exp1, True)
if CompileFunction.is_atm(exp2):
(exp2_atm, exp2_temps) = (exp2, [])
else:
(exp2_atm, exp2_temps) = self.rco_exp(exp2, True)
tail = BinOp(exp1_atm, binop, exp2_atm)
temps = exp1_temps + exp2_temps
case Compare(left, [cmp], [right]):
# similar to `BinOp` case
if CompileFunction.is_atm(left):
(left_atm, left_temps) = (left, [])
else:
(left_atm, left_temps) = self.rco_exp(left, True)
if CompileFunction.is_atm(right):
(right_atm, right_temps) = (right, [])
else:
(right_atm, right_temps) = self.rco_exp(right, True)
tail = Compare(left_atm, [cmp], [right_atm])
temps = left_temps + right_temps
case IfExp(exp_test, exp_body, exp_else):
(tail, test_temps) = self.rco_exp(exp_test, False)
tail = IfExp(tail, self.letize(
exp_body), self.letize(exp_else))
temps = test_temps
case Call(Name('input_int'), []):
tail = e
case Call(Name('len')):
# TODO not sure if more needs to be done
tail = e
case GlobalValue(v):
# TODO: create a temp to hold it
tail = e
case Allocate(len, type_list):
# TODO: ???
tail = e
case Subscript(var, idx, Load()):
(var_rcoed, var_temps) = self.rco_exp(var, True)
(idx_rcoed, idx_temps) = self.rco_exp(idx, True)
tail = Subscript(var_rcoed, idx_rcoed, Load())
temps = var_temps + idx_temps
case Call(funRef, args):
(funRef_rcoed, funRef_temps) = self.rco_exp(funRef, True)
# print("DEBUG, in rco_exp, call match case: ", funRef_rcoed)
args_rcoed = []
args_temps = []
for arg in args: # make sure all args are atomic
(arg_rcoed, arg_temps) = self.rco_exp(arg, True)
args_rcoed.append(arg_rcoed)
args_temps += arg_temps
tail = Call(funRef_rcoed, args_rcoed)
temps = args_temps + funRef_temps
case FunRef(f):
tail = e
case Let(var, rhs, let_body):
(tup_rcoed, tup_temps) = self.rco_exp(rhs, False)
new_body = self.letize(let_body)
tail = Let(var, tup_rcoed, new_body)
temps = tup_temps
case _:
raise Exception(
'error in rco_exp, unsupported expression ' + repr(e))
if need_atomic:
var = Name("pyc_temp_var_" + str(self.temp_count))
temps.append((var, tail))
self.temp_count += 1
tail = var
return (tail, temps)
def rco_stmt(self, s: stmt) -> List[stmt]:
result = []
temps = []
match s:
case Expr(Call(Name('print'), [exp])):
(atm, temps) = self.rco_exp(exp, True)
tail = Expr(Call(Name('print'), [atm]))
case Expr(exp):
(exp_rcoed, temps) = self.rco_exp(exp, False)
tail = Expr(exp_rcoed)
case Assign([Name(var)], exp):
# Record all tuples here
if isinstance(exp, Tuple):
# print("DEBUG: hit tuple, ", var, type(var))
self.tuple_vars.append(var)
(exp_rcoed, temps) = self.rco_exp(exp, False)
tail = Assign([Name(var)], exp_rcoed)
case If(exp, stmts_body, stmts_else):
# need test
(exp_rcoed, temps) = self.rco_exp(exp, False)
body_rcoed = [
new_stat for s in stmts_body for new_stat in self.rco_stmt(s)]
else_rcoed = [
new_stat for s in stmts_else for new_stat in self.rco_stmt(s)]
tail = If(exp_rcoed, body_rcoed, else_rcoed)
case While(exp, stmts_body, []):
exp_rcoed = self.letize(exp)
# (exp_rcoed, temps) = self.rco_exp(exp, False)
body_rcoed = [
new_stat for s in stmts_body for new_stat in self.rco_stmt(s)]
tail = While(exp_rcoed, body_rcoed, [])
case Collect(bytes):
# TODO: ???
tail = s
case Assign([Subscript(var, idx, Store())], exp):
(var_rcoed, var_temps) = self.rco_exp(var, True)
(idx_rcoed, idx_temps) = self.rco_exp(idx, True)
(exp_rcoed, exp_temps) = self.rco_exp(exp, False)
tail = Assign(
[Subscript(var_rcoed, idx_rcoed, Store())], exp_rcoed)
temps = var_temps + idx_temps + exp_temps
case Return(exp):
(atm, temps) = self.rco_exp(exp, False)
tail = Return(atm)
case _:
raise Exception(
'error in rco_stmt, stmt not supported ' + repr(s))
for binding in temps:
# print("DEBUG, binding: ", binding)
result.append(Assign([binding[0]], binding[1]))
result.append(tail)
return result
def remove_complex_operands(self, p: Module) -> List:
match p:
case Module(stmts):
new_stmts = [
new_stat for s in stmts for new_stat in self.rco_stmt(s)]
return new_stmts
############################################################################
# Explicate Control
############################################################################