-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcompiler_tuple.py
1205 lines (1095 loc) · 48.3 KB
/
compiler_tuple.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 re import T
import x86_ast
from utils import *
from x86_ast import *
import bitarray
import bitarray.util
from collections import deque
from functools import reduce
import os
from graph import UndirectedAdjList, transpose, topological_sort
from priority_queue import PriorityQueue
import interp_Cif
from typing import List, Set, Dict
from typing import Tuple as Tupling
import type_check_Ltup
from interp_x86.eval_x86 import interp_x86
import type_check_Ctup
Binding = Tupling[Name, expr]
Temporaries = List[Binding]
caller_saved_regs = {Reg('rax'), Reg('rcx'), Reg('rdx'), Reg('rsi'),Reg('rdi'),Reg('r8'),Reg('r9'),
Reg("r10"), Reg('r11')}
callee_saved_regs = {Reg('rsp'), Reg('rbp'), Reg("rbx"), Reg("r12"), Reg("r13"), Reg("r14"),Reg("r15")}
arg_regs = [Reg("rdi"), Reg("rsi"), Reg("rdx"), Reg("rcx"), Reg("r8"), Reg("r9")]
op_dict = {
"==": "e",
"<=": "le",
"<": "l",
">=": "ge",
">": "g",
"!=": "ne",
}
def calculate_tag(size, ty):
tag = bitarray.bitarray(64, endian="little")
tag.setall(0)
p_mask = 7
tag[0] = 1
for i, type in enumerate(ty.types):
# breakpoint()
if isinstance(type, TupleType):
tag[p_mask + i] = 1
else:
tag[p_mask + i] = 0
tag[1:7] = tag[1:7] | bitarray.util.int2ba(size, length=6, endian='little')
print("tags", bitarray.util.ba2base(2, tag))
return bitarray.util.ba2int(tag)
class Compiler:
############################################################################
# Remove Complex Operands
############################################################################
def shrink_exp(self, e: expr) -> expr:
# YOUR CODE HERE
# breakpoint()
match e:
case BoolOp(And(), expr):
return IfExp(expr[0], expr[1], Constant(False))
case BoolOp(Or(), expr):
return IfExp(expr[0], Constant(True), expr[1])
case _:
return e
# case Name(id):
# return e, []
# case BinOp(left, op, right):
# print(left, op, right)
# l_expr, l_tmps = self.rco_exp(left, True)
# r_expr, r_tmps = self.rco_exp(right, True)
# l_tmps.extend(r_tmps)
# return_expr = BinOp(l_expr, op, r_expr)
# if need_atomic:
# tmp = Name(generate_name("tmp"))
# l_tmps.append((tmp, return_expr))
# return tmp, l_tmps
# else:
# return return_expr, l_tmps
# case UnaryOp(USub(), v):
# # one by one
# v_expr, v_tmps = self.rco_exp(v, True)
# print(v_expr, v_tmps)
# return_expr = UnaryOp(USub(), v_expr)
# if need_atomic:
# tmp = Name(generate_name("tmp"))
# v_tmps.append((tmp, return_expr))
# return tmp, v_tmps
# else:
# return return_expr, v_tmps
# case Constant(value):
# return e, []
# case Call(Name('input_int'), []):
# return e, [] # beachse match e was
# case _:
# raise Exception('error in rco_exp, unexpected ' + repr(e))
def shrink_stmt(self, s: stmt) -> stmt:
# YOUR CODE HERE
match s:
case Expr(Call(Name('print'), [arg])):
arg_expr = self.shrink_exp(arg)
result = Expr(Call(Name('print'), [arg_expr]))
case Expr(value):
s_value = self.shrink_exp(value)
result= Expr(s_value)
case Assign([lhs], value):
s_value = self.shrink_exp(value)
result = Assign([lhs], s_value)
case If(test, body, orelse):
test_expr = self.shrink_exp(test)
body = [self.shrink_stmt(s) for s in body]
orelse = [self.shrink_stmt(s) for s in orelse]
result = If(test_expr, body, orelse)
case While(test, body, []):
test_expr = self.shrink_exp(test)
body = [self.shrink_stmt(s) for s in body]
result = While(test_expr, body, [])
case _:
raise Exception('error in rco_stmt, unexpected ' + repr(s))
return result
def shrink(self, p: Module) -> Module:
# YOUR CODE HERE
trace(p)
result = []
match p:
case Module(body):
print(body)
# breakpoint()
for s in body:
result.append(self.shrink_stmt(s))
result = Module(result)
case _:
raise Exception('interp: unexpected ' + repr(p))
# breakpoint()
trace(result)
return result
def expose_allocation_exp(self, exp) -> Tupling[expr, List[stmt]]:
match exp:
case Subscript(value, slice, ctx):
new_value, stmts = self.expose_allocation_exp(value)
return Subscript(new_value, slice, ctx), stmts
case Tuple(exprs):
stmts = []
# do expr
tmp_exprs = []
for expr in exprs:
tmp = generate_name("tmp")
var = Name(tmp)
new_expr, tmp_stmts = self.expose_allocation_exp(expr)
stmts.extend(tmp_stmts)
new_stmt = Assign([var], new_expr)
stmts.append(new_stmt)
tmp_exprs.append(var)
# breakpoint()
n = len(exprs)
stmts.append(
If(Compare(BinOp(GlobalValue("free_ptr"), Add(), Constant(8 * (n+1))), [Lt()], [GlobalValue("fromspace_end")]),
[Expr(Constant(0))],
[Collect(8 * (n+1))])
)
tmp = generate_name("alloc")
var = Name(tmp)
stmts.append(Assign([var], Allocate(n, exp.has_type))) # may exp.has_type.types
for i in range(len(exprs)):
stmts.append(Assign([Subscript(var, Constant(i), Load())], tmp_exprs[i])) # todo the Load is what
return var, stmts
case _:
return exp, []
def expose_allocation_stmt(self, s: stmt) -> List[stmt]:
# result = []
# breakpoint()
match s:
case Expr(Call(Name('print'), [arg])):
new_arg, stmts = self.expose_allocation_exp(arg)
return stmts + [Expr(Call(Name('print'), [new_arg]))]
case Expr(value):
expr, stmts = self.expose_allocation_exp(value)
return stmts + [Expr(expr)]
case Assign([lhs], value):
v_expr , stmts = self.expose_allocation_exp(value)
return stmts + [Assign([lhs], v_expr)]
case If(test, body, orelse):
test_expr, stmts = self.expose_allocation_exp(test)
body_stmts = []
for s in body:
body_stmts.extend(self.expose_allocation_stmt(s))
orelse_stmts = []
for s in orelse:
orelse_stmts.extend(self.expose_allocation_stmt(s))
return stmts + [If(test_expr, body_stmts, orelse_stmts)]
case While(test, body, []):
test_expr, stmts = self.expose_allocation_exp(test)
body_stmts = []
for s in body:
body_stmts.extend(self.expose_allocation_stmt(s))
return stmts + [While(test_expr, body_stmts, [])]
# case _:
# raise Exception('error in rco_stmt, unexpected ' + repr(s))
# return result
def expose_allocation(self, p):
# YOUR CODE HERE
# trace(p)
type_check_Ltup.TypeCheckLtup().type_check(p)
result = []
match p:
case Module(body):
print(body)
# breakpoint()
for s in body:
# breakpoint()
result.extend(self.expose_allocation_stmt(s))
result = Module(result)
case _:
raise Exception('interp: unexpected ' + repr(p))
# breakpoint()
trace(result)
return result
def rco_exp(self, e: expr, need_atomic: bool) -> Tupling[expr, Temporaries]:
# YOUR CODE HERE
match e:
case Name(id):
return e, []
case BinOp(left, op, right):
print(left, op, right)
l_expr, l_tmps = self.rco_exp(left, True)
r_expr, r_tmps = self.rco_exp(right, True)
l_tmps.extend(r_tmps)
return_expr = BinOp(l_expr, op, r_expr)
if need_atomic:
tmp = Name(generate_name("tmp"))
l_tmps.append((tmp, return_expr))
return tmp, l_tmps
else:
return return_expr, l_tmps
case UnaryOp(op, v):
# one by one
v_expr, v_tmps = self.rco_exp(v, True)
print(v_expr, v_tmps)
return_expr = UnaryOp(op, v_expr)
if need_atomic:
tmp = Name(generate_name("tmp"))
v_tmps.append((tmp, return_expr))
return tmp, v_tmps
else:
return return_expr, v_tmps
case GlobalValue(label):
if need_atomic:
tmp = Name(generate_name("tmp"))
# v_tmps.append()
return tmp, [(tmp, e)]
else:
return e, []
case Allocate(length, ty):
if need_atomic:
tmp = Name(generate_name("tmp"))
# v_tmps.append()
return tmp, [(tmp, e)]
else:
return e, []
case Constant(value):
return e, []
case Call(Name('input_int'), []):
return e, [] # beachse match e was
case Compare(left, [cmp], [right]):
left_expr, left_tmps = self.rco_exp(left, True)
right_expr, right_tmps = self.rco_exp(right, True)
left_tmps.extend(right_tmps)
return_expr = Compare(left_expr, [cmp], [right_expr])
if need_atomic:
tmp = Name(generate_name("tmp"))
left_tmps.append((tmp, return_expr))
return tmp, left_tmps
else:
return return_expr, left_tmps
case IfExp(expr_test, expr_body, expr_orelse):
test_expr, test_tmps = self.rco_exp(expr_test, False)
body, body_tmps = self.rco_exp(expr_body, False)
orelse_expr, orelse_tmp = self.rco_exp(expr_orelse, False)
wrap_body = Begin([ Assign([name], expr)for name,expr in body_tmps], body)
wrap_orelse = Begin([Assign([name], expr) for name, expr in orelse_tmp], orelse_expr)
return_expr = IfExp(test_expr, wrap_body, wrap_orelse)
if need_atomic:
tmp = Name(generate_name("tmp"))
test_tmps.append((tmp, return_expr))
return tmp, test_tmps
else:
return return_expr, test_tmps
case Subscript(value, slice, ctx):
value_expr, value_tmps = self.rco_exp(value, True)
slice_expr, slice_tmps = self.rco_exp(slice, True)
return_expr = Subscript(value_expr, slice_expr, ctx)
value_tmps.extend(slice_tmps)
if need_atomic:
tmp = Name(generate_name("tmp"))
value_tmps.append((tmp, return_expr))
return tmp, value_tmps
else:
return return_expr, value_tmps
# return Subscript(new_value, slice, ctx)
# case Begin(body, result):
# pass
case _:
raise Exception('error in rco_exp, unexpected ' + repr(e))
def rco_stmt(self, s: stmt) -> List[stmt]:
# YOUR CODE HERE
result = []
# breakpoint()
match s:
case Expr(Call(Name('print'), [arg])):
arg_expr, arg_tmps = self.rco_exp(arg, True)
for name, expr in arg_tmps:
result.append(Assign([name], expr))
result.append(Expr(Call(Name('print'), [arg_expr])))
case Expr(value):
expr, tmps = self.rco_exp(value, False)
print(expr, tmps)
for name, expr in tmps:
result.append(Assign([name], expr))
result.append(Expr(expr))
case Assign([lhs], value):
v_expr, tmps = self.rco_exp(value, False)
print(v_expr, tmps)
for name, t_expr in tmps:
result.append(Assign([name], t_expr))
result.append(Assign([lhs], v_expr))
case If(test, body, orelse):
test_expr, test_tmps = self.rco_exp(test, False)
body_stmts = []
for name, t_expr in test_tmps:
result.append(Assign([name], t_expr))
for s in body:
body_stmts.extend(self.rco_stmt(s))
orelse_stmts = []
for s in orelse:
orelse_stmts.extend(self.rco_stmt(s))
result.append(If(test_expr, body_stmts, orelse_stmts))
case While(test, body, []):
test_expr, test_tmps = self.rco_exp(test, False)
body_stmts = []
for name, t_expr in test_tmps:
result.append(Assign([name], t_expr))
for s in body:
body_stmts.extend(self.rco_stmt(s))
result.append(While(test_expr, body_stmts, []))
case Collect(size):
result.append(s)
case _:
raise Exception('error in rco_stmt, unexpected ' + repr(s))
return result
def remove_complex_operands(self, p: Module) -> Module:
# YOUR CODE HERE
trace(p)
result = []
match p:
case Module(body):
print(body)
# breakpoint()
for s in body:
result.extend(self.rco_stmt(s))
result = Module(result)
case _:
raise Exception('interp: unexpected ' + repr(p))
# breakpoint()
trace(result)
return result
def explicate_assign(self, rhs: expr, lhs: Variable, cont: List[stmt],
basic_blocks: Dict[str, List[stmt]]) -> List[stmt]:
match rhs:
case IfExp(test, body, orelse):
goto_cont = create_block(cont, basic_blocks)
body_list = self.explicate_assign(body, lhs, [goto_cont], basic_blocks)
orelse_list = self.explicate_assign(orelse, lhs, [goto_cont], basic_blocks)
return self.explicate_pred(test, body_list, orelse_list, basic_blocks)
case Begin(body, result):
print("yyyy")
new_body = [Assign([lhs], result)] + cont
for s in reversed(body):
# the new_body was after s we need do the new_body
new_body = self.explicate_stmt(s, new_body, basic_blocks)
return new_body
case _:
# if str(lhs.id) == 'tmp.0':
# print("xxxx")
return [Assign([lhs], rhs)] + cont
def explicate_effect(self, e: expr, cont: List[stmt],
basic_blocks: Dict[str, List[stmt]]) -> List[stmt]:
match e:
case IfExp(test, body, orelse):
goto_cont = create_block(cont, basic_blocks)
body = self.explicate_effect(body, [goto_cont], basic_blocks)
orelse = self.explicate_effect(orelse, [goto_cont], basic_blocks)
return self.explicate_pred(test, body, orelse, basic_blocks)
case Call(func, args):
print("#####", e)
return [Expr(e)] + cont
case Begin(body, result):
new_body = self.explicate_effect(result, cont, basic_blocks) + [cont]
for s in reversed(body):
# the new_body was after s we need do the new_body
new_body = self.explicate_stmt(s, new_body, basic_blocks)
return new_body
case _:
# print("......", e)
return [] + cont
def explicate_pred(self, cnd: expr, thn: List[stmt], els: List[stmt],
basic_blocks: Dict[str, List[stmt]]) -> List[stmt]:
match cnd:
case Compare(left, [op], [right]):
goto_thn = create_block(thn, basic_blocks)
goto_els = create_block(els, basic_blocks)
return [If(cnd, [goto_thn], [goto_els])]
case Constant(True):
return thn
case Constant(False):
return els
case IfExp(test, body, orelse):
# TODO
goto_thn = create_block(thn, basic_blocks)
goto_els = create_block(els, basic_blocks)
body = self.explicate_pred(body, [goto_thn], [goto_els], basic_blocks)
orelse = self.explicate_pred(orelse, [goto_thn], [goto_els], basic_blocks)
goto_thn_out = create_block(body, basic_blocks)
goto_els_out = create_block(orelse, basic_blocks)
return [If(test, [goto_thn_out], [goto_els_out])]
case Begin(body, result):
goto_thn = create_block(thn, basic_blocks)
goto_els = create_block(els, basic_blocks)
new_body = [If(result, [goto_thn], [goto_els])]
for s in reversed(body):
# the new_body was after s we need do the new_body
new_body = self.explicate_stmt(s, new_body, basic_blocks)
return new_body
case _:
return [If(Compare(cnd, [Eq()], [Constant(False)]),
[create_block(els, basic_blocks)],
[create_block(thn, basic_blocks)])]
def explicate_stmt(self, s: stmt, cont: List[stmt],
basic_blocks: Dict[str, List[stmt]]) -> List[stmt]:
match s:
case Assign([lhs], rhs):
return self.explicate_assign(rhs, lhs, cont, basic_blocks)
case Expr(value):
return self.explicate_effect(value, cont, basic_blocks)
case If(test, body, orelse):
goto_cont = create_block(cont, basic_blocks)
new_body = [goto_cont]
for s in reversed(body):
# the new_body was after s we need do the new_body
new_body = self.explicate_stmt(s, new_body, basic_blocks)
new_orelse = [goto_cont]
for s in reversed(orelse):
# the new_body was after s we need do the new_body
new_orelse = self.explicate_stmt(s, new_orelse, basic_blocks)
return self.explicate_pred(test, new_body, new_orelse, basic_blocks)
case While(test, body, []):
# after_while = create_block(cont, basic_blocks)
# goto_after_while = [after_while]
test_label = label_name(generate_name('block'))
new_body = [Goto(test_label)]
for s in reversed(body):
# the new_body was after s we need do the new_body
new_body = self.explicate_stmt(s, new_body, basic_blocks)
test_stmts = self.explicate_pred(test, new_body, cont, basic_blocks)
basic_blocks[test_label] = test_stmts
return [Goto(test_label)]
case Collect(size):
return [s] + cont
# case Expr(Call(Name('print'), [arg])):
# return [s] + cont
def explicate_control(self, p):
match p:
case Module(body):
basic_blocks = {}
conclusion = []
conclusion.extend([
Return(Constant(0)),
])
basic_blocks[label_name("conclusion")] = conclusion
# blocks[self.sort_cfg[-1]][-1] = Jump(label_name("conclusion"))
new_body = [Goto(label_name("conclusion"))]
# 也许这里是一个 newblock conclude = block(Return(Constant(0))])
# create_block 是 goto 那个 bloc
# conclude 这里是从那里 goto 到这里
for s in reversed(body):
# the new_body was after s we need do the new_body
new_body = self.explicate_stmt(s, new_body, basic_blocks)
basic_blocks[label_name('start')] = new_body
result = CProgram(basic_blocks)
# f = interp_Cif.InterpCif().interp
# breakpoint()
return result
############################################################################
# Select Instructions
############################################################################
def select_arg(self, e: expr) -> arg:
# YOUR CODE HERE
match e:
case Name(name):
return Variable(name)
case GlobalValue(name):
return x86_ast.Global(name)
case Constant(True):
return Immediate(1)
case Constant(False):
return Immediate(0)
case Constant(value):
return Immediate(value)
# case x if isinstance(x, int):
# return Immediate(x)
case _:
raise Exception('error in select_arg, unexpected ' + repr(e))
def select_compare(self, expr, then_label, else_label) -> List[instr]:
# e | ne | l | le | g | ge
match expr:
case Compare(x, [op], [y]):
# breakpoint()
x = self.select_arg(x)
y = self.select_arg(y)
return [
Instr('cmpq', [y, x]),
# Instr('j{}'.format(op_dict[str(op)]), [then_label]),
JumpIf(op_dict[str(op)], then_label),
Jump(else_label)
# Instr('jmp', [else_label])
]
def select_stmt(self, s: stmt) -> List[instr]:
# YOUR CODE HERE
result = []
match s:
case Expr(Call(Name('print'), [arg])):
arg = self.select_arg(arg)
result.append(Instr('movq', [arg, Reg("rdi")]))
result.append(Callq(label_name("print_int"), 1))
case Expr(value):
# don't need do more on value
result.append(Instr('movq', [value, Reg("rax")]))
case Assign([lhs], BinOp(left, Add(), right)):
# breakpoint()
left_arg = self.select_arg(left)
right_arg = self.select_arg(right)
lhs = self.select_arg(lhs)
if lhs == left_arg:
result.append(Instr('addq', [right_arg, lhs]))
elif lhs == right_arg:
result.append(Instr('addq', [left_arg, lhs]))
else:
result.append(Instr('movq', [left_arg, lhs]))
result.append(Instr('addq', [right_arg, lhs]))
case Assign([lhs], BinOp(left, Sub(), right)):
# breakpoint()
left_arg = self.select_arg(left)
right_arg = self.select_arg(right)
lhs = self.select_arg(lhs)
if lhs == left_arg:
result.append(Instr('subq', [right_arg, lhs]))
elif lhs == right_arg:
result.append(Instr('subq', [left_arg, lhs]))
else:
result.append(Instr('movq', [left_arg, lhs]))
result.append(Instr('subq', [right_arg, lhs]))
case Assign([lhs], UnaryOp(USub(), v)):
arg = self.select_arg(v)
lhs = self.select_arg(lhs)
if arg == lhs:
result.append(Instr('negq', [lhs]))
else:
result.append(Instr('movq', [arg, lhs]))
result.append(Instr('negq', [lhs]))
case Assign([lhs], Call(Name('input_int'), [])):
lhs = self.select_arg(lhs)
result.append(Callq(label_name("read_int"), 0))
result.append(Instr('movq', [Reg('rax'), lhs]))
case Assign([lhs], UnaryOp(Not(), rhs)) if rhs == rhs:
lhs = self.select_arg(lhs)
result.append(Instr('xorq',[Immediate(1), lhs]))
case Assign([lhs], UnaryOp(Not(), rhs)):
lhs = self.select_arg(lhs)
arg = self.select_arg(rhs)
result.append(Instr('movq',[arg, lhs]))
result.append(Instr('xorq', [Immediate(1), lhs]))
case Assign([lhs], Compare(x, [op], [y])):
lhs = self.select_arg(lhs)
l = self.select_arg(x)
r = self.select_arg(y)
result.append(Instr('cmpq', [l, r]))
result.append(Instr('set{}'.format(op_dict[str(op)]), [ByteReg('bl')]))
result.append(Instr('movzbq', [ByteReg('bl'), lhs]))
pass
case Assign([lhs], Call(Name('len'), [arg])):
arg = self.select_arg(arg)
result.append(Instr('movq', [arg, Reg('r11')]))
result.append(Instr('movq', [Deref('r11', 0), Reg('r11')]))
result.append(Instr('andq', [Immediate(126), Reg('r11')]))
result.append(Instr('sarq', [Immediate(1), Reg('r11')]))
result.append(Instr('sarq', [Reg('r11'), lhs]))
case Assign([lhs], Subscript(value, slice)):
lhs = self.select_arg(lhs)
value = self.select_arg(value)
slice = self.select_arg(slice) # slice must be int 这里没有必要
result.append(Instr('movq', [value, Reg('r11')]))
result.append(Instr('movq', [Deref('r11', 8 * (slice.value + 1)), lhs]))
case Assign([Subscript(tu, slice)], value):
tu = self.select_arg(tu)
slice = self.select_arg(slice)
value = self.select_arg(value)
result.append(Instr('movq', [tu, Reg('r11')]))
result.append(Instr('movq', [value, Deref('r11', 8 * (slice.value + 1))]))
case Assign([lhs], Allocate(size, ty)):
lhs = self.select_arg(lhs)
# size = self.select_arg(size)
tag = calculate_tag(size, ty)
result.append(Instr("movq", [x86_ast.Global("free_ptr"), Reg('r11')]))
result.append(Instr("addq", [Immediate(8 * (size + 1)), x86_ast.Global("free_ptr")]))
result.append(Instr("movq", [Immediate(tag), Deref('r11', 0)]))
result.append(Instr('movq', [Reg('r11'), lhs]))
case Assign([lhs], value):
lhs = self.select_arg(lhs)
arg = self.select_arg(value)
result.append(Instr('movq', [arg, lhs]))
case Return(Constant(value)):
result.append(Instr('movq', [self.select_arg(Constant(value)), Reg('rax')]))
result.append(Instr('retq', []))
case Goto(label):
result.append(Jump(label))
case If(expr, [Goto(then_label)], [Goto(else_label)]):
if_ = self.select_compare(expr, then_label, else_label)
result.extend(if_)
case Collect(size):
# size = self.select_arg(size)
result.append(Instr('movq', [Reg('r15'), Reg('rdi')]))
result.append(Instr('movq', [Immediate(size), Reg('rsi')]))
result.append(Callq(label_name("collect"), 2))
case _:
raise Exception('error in select_stmt, unexpected ' + repr(s))
return result
pass
def select_instructions(self, p: Module) -> X86Program:
# YOUR CODE HERE
type_check_Ctup.TypeCheckCtup().type_check(p)
# breakpoint()
blocks = {}
match p:
case CProgram(basic_blocks):
for label, body in basic_blocks.items():
instr_body = []
for s in body:
instr_body.extend(self.select_stmt(s))
blocks[label] = instr_body
case _:
raise Exception('interp: unexpected ' + repr(p))
x86 = X86Program(blocks)
x86.var_types = p.var_types
# breakpoint()
# print("......")
# interp_x86(x86)
# print("......")
return x86
############################################################################
# Assign Homes
############################################################################
def assign_homes_arg(self, a: arg, home: Dict[Variable, arg]) -> arg:
match a:
case Variable(name):
if a in home:
return home[a]
index = len(home) + 1
location = -(index * 8)
arg = Deref("rbp", location)
home[a] = arg
return arg
case Immediate(value):
return a
case Reg(value):
return a
case _:
raise Exception('error in assign_homes_arg, unexpected ' + repr(a))
pass
def assign_homes_instr(self, i: instr,
home: Dict[Variable, arg]) -> instr:
match(i):
case Instr(instr, args):
new_args = []
for arg in args:
new_args.append(self.assign_homes_arg(arg, home))
return Instr(instr, new_args)
case Callq(func, num_args):
return i
case _:
raise Exception('error in assign_homes_instr, unexpected ' + repr(i))
pass
def assign_homes_instrs(self, ss: List[instr],
home: Dict[Variable, arg]) -> List[instr]:
result = []
for s in ss:
ns = self.assign_homes_instr(s, home)
result.append(ns)
return result
# def assign_homes(self, p: X86Program) -> X86Program:
# # YOUR CODE HERE
# match(p):
# case X86Program(body):
# home = {}
# result = self.assign_homes_instrs(body, home)
# # breakpoint()
# return X86Program(result)
def read_var(self, i: instr) -> Set[location]:
match (i):
case Instr(cmpq, [s, Variable(t)]):
return {i.args[1]}
case Instr(op, [Variable(s), t]):
return {i.args[0]}
case Instr(op, [Reg(s), t]):
return {i.args[0]}
case Instr(op, [Variable(s)]):
return {i.args[0]}
case Instr(op, [Reg(s)]):
return {i.args[0]}
case Instr(op, [ByteReg(s)]):
return {i.args[0]}
case Callq(func, num_args):
return set(arg_regs[:num_args])
case _:
return set()
def free_var(self, t):
match(t):
case Variable(i):
return t
case Reg(r):
return t
case Deref(r, offset):
return Reg(r)
case _:
return set()
def write_var(self, i) -> Set[location]:
match (i):
case Instr("movq", [s, t]):
return set([self.free_var(t)])
case Callq(func, num_args):
return set(callee_saved_regs)
case _:
return set()
def uncover_live(self, ss: List[instr], live_before_block) -> Dict[instr, Set[location]]:
# pre_instr_set = set()
pre_instr = ss[-1]
match ss[-1]:
case Jump(label):
pre_instr_set = live_before_block[label]
case JumpIf(label):
# jumpif 在最后是没有接着的指令的
print("Never happened")
pre_instr_set = set()
case _:
pre_instr_set = set()
live_after = {
ss[-1]: pre_instr_set
}
for s in list(reversed(ss))[1:]:
match s:
case Jump(label):
pre_instr_set = live_before_block[label]
case JumpIf(cc, label):
tmp = (pre_instr_set - self.write_var(pre_instr)).union(self.read_var(pre_instr))
pre_instr_set = tmp.union(live_before_block[label])
case _:
pre_instr_set = (pre_instr_set - self.write_var(pre_instr)).union(self.read_var(pre_instr))
pre_instr = s
live_after[s] = pre_instr_set
return live_after
def transfer(self,label, live_after_block):
ss = self.blocks[label]
after_instr_set = live_after_block # the set after the block
live_before_block = set()
if not ss:
return set()
self.live_after[ss[-1]] = after_instr_set
s = ss[-1]
match s:
# jump 到别处 通过的是 input 来传岛的
case Jump(label):
before_instr_set = live_after_block
case JumpIf(cc, label):
tmp = (self.live_after[s] - self.write_var(s)).union(self.read_var(s))
before_instr_set = tmp.union(live_after_block)
case _:
before_instr_set = (self.live_after[s] - self.write_var(s)).union(self.read_var(s))
pre_instr = ss[-1]
self.live_before[pre_instr] = before_instr_set
live_before_block = live_before_block.union(before_instr_set)
for s in list(reversed(ss))[1:]:
self.live_after[s] = self.live_before[pre_instr]
match s:
# jump 到别处 通过的是 input 来传岛的
case Jump(label):
before_instr_set = live_after_block
case JumpIf(cc, label):
tmp = (self.live_after[s] - self.write_var(s)).union(self.read_var(s))
before_instr_set = tmp.union(live_after_block)
case _:
before_instr_set = (self.live_after[s] - self.write_var(s)).union(self.read_var(s))
# print("s" , s, before_instr_set)
self.live_before[s] = before_instr_set
live_before_block = live_before_block.union(before_instr_set)
pre_instr = s
# self.live_after[s] = pre_instr_set.union(self.live_after.get(s, set()))
# pre_instr_set = (pre_instr_set - self.write_var(pre_instr)).union(self.read_var(pre_instr))
# print("after_set ", pre_instr_set)
# live_before_block = live_before_block.union(pre_instr_set)
return live_before_block
def analyze_dataflow(self, G, transfer, bottom, join):
trans_G = transpose(G)
mapping = dict((v, bottom) for v in G.vertices())
worklist = deque(G.vertices())
debug = {}
while worklist:
print(worklist)
node = worklist.pop()
inputs = [mapping[v] for v in trans_G.adjacent(node)]
input = reduce(join, inputs, bottom)
output = transfer(node, input)
print("node", node, "input", input, "output", output)
if output != mapping[node]:
worklist.extend(G.adjacent(node))
mapping[node] = output
else:
debug[node] = output
return debug
def build_interference(self, blocks) -> UndirectedAdjList:
cfg = UndirectedAdjList()
for label, body in blocks.items():
for i in body:
if isinstance(i, Jump) or isinstance(i, JumpIf):
# breakpoint()
cfg.add_edge(label, i.label)
t_cfg = transpose(cfg)
interference_graph = UndirectedAdjList()
# self.sort_cfg = topological_sort(cfg)
live_before_block = {}
self.live_after = {}
self.live_before = {}
self.live_before_block = {}
self.blocks = blocks
debug = self.analyze_dataflow(cfg, self.transfer, set(), lambda x,y: x|y)
# breakpoint()
# for label in reversed(self.sort_cfg):
# ss = blocks[label]
# tmp = self.uncover_live(ss, live_before_block)
# # live update bind instr with
# # flow 分析解决的是 block 的分析问题。
# # 在解决 block 的
# live_before_block[label] = tmp[ss[0]]
# live_after.update(tmp)
print("live_after ", self.live_after)
for label, ss in blocks.items():
for s in ss:
match (s):
case Instr("movq", [si, d]):
# si = s.args[0]
d = self.free_var(d)
for v in self.live_after[s]:
if v != d and v != si:
interference_graph.add_edge(d, v)
# case Instr("movq", [Reg(x), t]):
# si = s.args[0]
# for v in live_after[si]:
# if v != d and v != si:
# interference_graph.add_edge(d, v)
case _:
wset = self.write_var(s)
for d in wset:
for v in self.live_after[s]:
if v != d:
interference_graph.add_edge(d, v)
return interference_graph
#def color_graph(self, ss: List[instr], k=100) -> Dict[location, int]:
def color_graph(self, blocks, k=100) -> Dict[location, int]:
# first make it k big enough
valid_colors = list(range(0, k)) # number of colar
# Rdi 的保存问题
color_map = {
Reg('rax'): -1, Reg('rsp'): -2, Reg('rdi'): -3, ByteReg('bl'): -4, Reg('r11'): -5,
Reg('r15'): -6, Reg('rsi'): -7 # rsi 其实可以用来做其他事情。 但如果分配 rsi 9 rsi 的 color
# 算法 color 9 和 可以分配出去reg 的color 0 1 3 矛盾
}
# color_map = {}
saturated = {}
def less(u, v):
nonlocal saturated
# breakpoint()
if v not in saturated:
return True
return len(saturated[u]) < len(saturated[v])
queue = PriorityQueue(less)
interference_graph = self.build_interference(blocks)
dot = interference_graph.show()
# breakpoint()
# dot.view()
# breakpoint()
vsets = interference_graph.vertices()
# breakpoint()
for v in vsets:
saturated[v] = set()
for v in vsets:
queue.push(v)
while not queue.empty():
u = queue.pop()
# print("handing", u)
adj_colors = {color_map[v] for v in interference_graph.adjacent(u) if v in color_map}
print(u, adj_colors)
if left_color := set(valid_colors) - adj_colors:
color = min(left_color)
if u not in color_map:
color_map[u] = color
for v in interference_graph.adjacent(u):
saturated[v].add(color)
# else:
# spill.add(u)
# breakpoint()
return color_map
def allocate_registers(self, p: X86Program) -> X86Program:
# YOUR CODE HERE