This repository has been archived by the owner on Jun 1, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ir.py
1198 lines (974 loc) · 35.9 KB
/
ir.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
"""Intermediate Representation
Could be improved by relying less on class hierarchy and more on string tags
and/or duck typing. Includes lowering and flattening functions. Every node must
have a lowering function or a code generation function (codegen functions are
in a separate module though)."""
from codegenhelp import *
# UTILITIES
# as the same may suggest, count how many
# temporaries have been instantiated so far
tempcount = 0
def new_temporary(symtab, type):
global tempcount
temp = Symbol(name="t" + str(tempcount), stype=type, alloct="reg")
tempcount += 1
return temp
# TYPES
# NOTE: the type system is very simple, so that we don't need explicit cast
# instructions or too much handling in the codegen phase.
# Basically, the type system always behaves as every term of an expression was
# casted to the biggest type available, and the result is then casted to the
# biggest of the types of the terms.
# Also, no handling for primitive types that do not fit in a single machine
# register is provided.
BASE_TYPES = ["Int", "Label", "Struct", "Function"]
TYPE_QUALIFIERS = ["unsigned"]
class Type:
def __init__(self, name, size, basetype, qualifiers=None):
if qualifiers is None:
qualifiers = []
self.size = size
self.basetype = basetype
self.qual_list = qualifiers
self.name = name if name else self.default_name()
def default_name(self):
n = ""
if "unsigned" in self.qual_list:
n += "u"
n += "int" # no float types exist at the moment
n += repr(self.size)
n += "_t"
return n
class ArrayType(Type):
def __init__(self, name, dims, basetype):
"""dims is a list of dimensions: dims = [5]: array of 5 elements;
dims = [5, 5]: 5x5 matrix; and so on"""
self.dims = dims
super().__init__(
name, reduce(lambda a, b: a * b, dims) * basetype.size, basetype
)
self.name = name if name else self.default_name()
def default_name(self):
return self.basetype.name + repr(self.dims)
class StructType(Type): # currently unused
def __init__(self, name, size, fields):
self.fields = fields
realsize = sum([f.size for f in self.fields])
super().__init__(name, realsize, "Struct", [])
def get_size(self):
return sum([f.size for f in self.fields])
class LabelType(Type):
def __init__(self):
super().__init__("label", 0, "Label", [])
self.ids = 0
def __call__(self, target=None):
self.ids += 1
return Symbol(name="label" + repr(self.ids), stype=self, value=target)
class FunctionType(Type):
def __init__(self):
super().__init__("function", 0, "Function", [])
class PointerType(Type):
def __init__(self, ptrto):
"""ptrto is the type of the object that this pointer points to."""
super().__init__("&" + ptrto.name, 32, "Int", ["unsigned"])
self.pointstotype = ptrto
TYPENAMES = {
"int": Type("int", 32, "Int"),
"short": Type("short", 16, "Int"),
"char": Type("char", 8, "Int"),
"uchar": Type("uchar", 8, "Int", ["unsigned"]),
"uint": Type("uint", 32, "Int", ["unsigned"]),
"ushort": Type("ushort", 16, "Int", ["unsigned"]),
# 'float': Type('float', 32, 'Float'),
"label": LabelType(),
"function": FunctionType(),
}
ALLOC_CLASSES = ["global", "auto", "reg", "imm"]
# SYMBOL ALLOCATION
class Symbol:
"""
4 classes of allocation for symbols:
1. reg: allocation to a register
2. auto: allocation to an arbitrary memory location in the current stack frame
3. global: allocation to an arbitrary memory location in the data section
4. imm: allocation to an immediate
"""
def __init__(self, name, stype, npar=None, value=None, alloct="auto"):
self.name = name
self.stype = stype
self.value = value # if not None, it is a constant
self.alloct = alloct
self.allocinfo = None
# number of parameters in case this symbol is a function
self.npar = npar
def set_alloc_info(self, allocinfo):
self.allocinfo = allocinfo
def __repr__(self):
base = (
self.alloct
+ " "
+ self.stype.name
+ " "
+ self.name
+ (self.value if type(self.value) == str else "")
)
if self.allocinfo is not None:
base = base + "; " + repr(self.allocinfo)
return base
# SYMBOL TABLE
# data structure created used to store about
# the occurrence of various entities such as
# variable names
class SymbolTable(list):
def find(self, name):
print("Looking up", name)
for s in self:
if s.name == name:
return s
print("Looking up failed!")
return None
def __repr__(self):
res = "SymbolTable:\n"
for s in self:
res += repr(s) + "\n"
return res
def exclude(self, barred_types):
return [symb for symb in self if symb.stype not in barred_types]
# IRNODE
# structure of a generic IR node
class IRNode: # abstract
def __init__(self, parent=None, children=None, symtab=None):
self.parent = parent
if children:
self.children = children[:]
for c in self.children:
try:
c.parent = self
except Exception:
pass
else:
self.children = []
self.symtab = symtab
def __repr__(self):
try:
label = self.get_label().name + ": "
except Exception:
label = ""
pass
try:
hre = self.human_repr()
return label + hre
except Exception:
pass
attrs = {
"body",
"cond",
"value",
"thenpart",
"elsepart",
"symbol",
"call",
"step",
"expr",
"target",
"defs",
"global_symtab",
"local_symtab",
"offset",
} & set(dir(self))
res = repr(type(self)) + " " + repr(id(self)) + " {\n"
if self.parent is not None:
res += "parent = " + repr(id(self.parent)) + "\n"
else:
# a missing parent is not a bug only for the root node, but at this
# level of abstraction there is no way to distinguish between the root
# node and a node with a missing parent
res += " <<<<<----- BUG? MISSING PARENT\n"
res = label + res
# print 'NODE', type(self), id(self)
if "children" in dir(self) and len(self.children):
res += "\tchildren:\n"
for node in self.children:
rep = repr(node)
res += "\n".join(["\t" + s for s in rep.split("\n")]) + "\n"
for d in attrs:
node = getattr(self, d)
rep = repr(node)
res += (
"\t" + d + ": " + "\n".join(["\t" + s for s in rep.split("\n")]) + "\n"
)
res += "}"
return res
def navigate(self, action):
attrs = {
"body",
"cond",
"value",
"thenpart",
"elsepart",
"symbol",
"call",
"step",
"expr",
"target",
"defs",
"global_symtab",
"local_symtab",
"offset",
} & set(dir(self))
if "children" in dir(self) and len(self.children):
print("navigating children of", type(self), id(self), len(self.children))
for node in self.children:
try:
node.navigate(action)
except Exception:
pass
for d in attrs:
try:
getattr(self, d).navigate(action)
print("successfully navigated attr ", d, " of", type(self), id(self))
except Exception:
pass
action(self)
def replace(self, old, new):
new.parent = self
if "children" in dir(self) and len(self.children) and old in self.children:
self.children[self.children.index(old)] = new
return True
attrs = {
"body",
"cond",
"value",
"thenpart",
"elsepart",
"symbol",
"call",
"step",
"expr",
"target",
"defs",
"global_symtab",
"local_symtab",
"offset",
} & set(dir(self))
for d in attrs:
try:
if getattr(self, d) == old:
setattr(self, d, new)
return True
except Exception:
pass
return False
def get_function(self):
if not self.parent:
return "global"
elif type(self.parent) == FunctionDef:
return self.parent
else:
return self.parent.get_function()
def get_label(self):
raise NotImplementedError
def human_repr(self):
raise NotImplementedError
# CONST and VAR
class Const(IRNode):
def __init__(self, parent=None, value=0, symb=None, symtab=None):
super().__init__(parent, None, symtab)
self.value = value
self.symbol = symb
def lower(self):
if self.symbol is None:
new = new_temporary(self.symtab, TYPENAMES["int"])
loadst = LoadImmStat(
dest=new, val=self.value, symtab=self.symtab
) # constant lowered into an load immediate stmt
else:
new = new_temporary(self.symtab, self.symbol.stype)
loadst = LoadStat(
dest=new, symbol=self.symbol, symtab=self.symtab
) # variable lowered into a load statement
return self.parent.replace(
self, StatList(children=[loadst], symtab=self.symtab)
)
class Var(IRNode):
"""loads in a temporary the value pointed to by the symbol"""
def __init__(self, parent=None, var=None, symtab=None):
super().__init__(parent, None, symtab)
self.symbol = var
def collect_uses(self):
return [self.symbol]
def lower(self):
"""Var translates to a load statement to the same temporary that is used in
a following stage for doing the computations (destination())"""
new = new_temporary(self.symtab, self.symbol.stype)
loadst = LoadStat(dest=new, symbol=self.symbol, symtab=self.symtab)
return self.parent.replace(
self, StatList(children=[loadst], symtab=self.symtab)
)
class ArrayElement(IRNode):
"""loads in a temporary the value pointed by: the symbol + the index"""
def __init__(self, parent=None, var=None, offset=None, symtab=None):
"""offset can NOT be a list of exps in case of multi-d arrays; it should
have already been flattened beforehand"""
super().__init__(parent, [offset], symtab)
self.symbol = var
self.offset = offset
def collect_uses(self):
a = [self.symbol]
a += self.offset.collect_uses()
return a
def lower(self):
global TYPENAMES
dest = new_temporary(self.symtab, self.symbol.stype.basetype)
off = self.offset.destination()
statl = [self.offset]
ptrreg = new_temporary(self.symtab, PointerType(self.symbol.stype.basetype))
loadptr = LoadPtrToSym(dest=ptrreg, symbol=self.symbol, symtab=self.symtab)
src = new_temporary(self.symtab, PointerType(self.symbol.stype.basetype))
add = BinStat(dest=src, op="plus", srca=ptrreg, srcb=off, symtab=self.symtab)
statl += [loadptr, add]
statl += [LoadStat(dest=dest, symbol=src, symtab=self.symtab)]
return self.parent.replace(self, StatList(children=statl, symtab=self.symtab))
# EXPRESSIONS
class Expr(IRNode): # abstract
def get_operator(self):
return self.children[0]
def collect_uses(self):
uses = []
for c in self.children:
try:
uses += c.collect_uses()
except AttributeError:
pass
return uses
class BinExpr(Expr):
def get_operands(self):
return self.children[1:]
def lower(self):
srca = self.children[1].destination()
srcb = self.children[2].destination()
# Type promotion.
if ("unsigned" in srca.stype.qual_list) and (
"unsigned" in srcb.stype.qual_list
):
desttype = Type(
None, max(srca.stype.size, srcb.stype.size), "Int", ["unsigned"]
)
else:
desttype = Type(None, max(srca.stype.size, srcb.stype.size), "Int")
dest = new_temporary(self.symtab, desttype)
stmt = BinStat(
dest=dest, op=self.children[0], srca=srca, srcb=srcb, symtab=self.symtab
)
statl = [self.children[1], self.children[2], stmt]
return self.parent.replace(self, StatList(children=statl, symtab=self.symtab))
class UnExpr(Expr):
def get_operand(self):
return self.children[1]
def lower(self):
src = self.children[1].destination()
dest = new_temporary(self.symtab, src.stype)
stmt = UnaryStat(dest=dest, op=self.children[0], src=src, symtab=self.symtab)
statl = [self.children[1], stmt]
return self.parent.replace(self, StatList(children=statl, symtab=self.symtab))
# looks like this is just a jump to a label
class CallExpr(Expr):
def __init__(self, parent=None, function=None, parameters=None, symtab=None):
super().__init__(parent, [], symtab)
self.symbol = function
# parameters are ignored
if parameters:
self.children = parameters[:]
else:
self.children = []
for c in self.children:
c.parent = self
# STATEMENTS
class Stat(IRNode): # abstract
def __init__(self, parent=None, children=None, symtab=None):
super().__init__(parent, children, symtab)
self.label = None
def set_label(self, label):
self.label = label
label.value = self # set target
def get_label(self):
return self.label
def collect_uses(self):
return []
def collect_kills(self):
return []
class CallStat(Stat):
"""Procedure call"""
def __init__(self, parent=None, call_expr=None, symtab=None):
super().__init__(parent, [], symtab)
self.call = call_expr
self.call.parent = self
def collect_uses(self):
return self.call.collect_uses() + self.symtab.exclude(
[TYPENAMES["function"], TYPENAMES["label"]]
)
def lower(self):
dest = self.call.symbol
bst = BranchStat(target=dest, symtab=self.symtab, returns=True)
return self.parent.replace(self, bst)
class IfStat(Stat):
def __init__(
self, parent=None, cond=None, thenpart=None, elsepart=None, symtab=None
):
super().__init__(parent, [], symtab)
self.cond = cond
self.thenpart = thenpart
self.elsepart = elsepart
self.cond.parent = self
self.thenpart.parent = self
if self.elsepart:
self.elsepart.parent = self
def lower(self):
exit_label = TYPENAMES["label"]()
exit_stat = EmptyStat(self.parent, symtab=self.symtab)
exit_stat.set_label(exit_label)
if self.elsepart:
then_label = TYPENAMES["label"]()
self.thenpart.set_label(then_label)
branch_to_then = BranchStat(
None, self.cond.destination(), then_label, self.symtab
)
branch_to_exit = BranchStat(None, None, exit_label, self.symtab)
stat_list = StatList(
self.parent,
[
self.cond,
branch_to_then,
self.elsepart,
branch_to_exit,
self.thenpart,
exit_stat,
],
self.symtab,
)
return self.parent.replace(self, stat_list)
else:
branch_to_exit = BranchStat(
None, self.cond.destination(), exit_label, self.symtab, negcond=True
)
stat_list = StatList(
self.parent,
[self.cond, branch_to_exit, self.thenpart, exit_stat],
self.symtab,
)
return self.parent.replace(self, stat_list)
class WhileStat(Stat):
def __init__(self, parent=None, cond=None, body=None, symtab=None):
super().__init__(parent, [], symtab)
self.cond = cond
self.body = body
self.cond.parent = self
self.body.parent = self
def lower(self):
entry_label = TYPENAMES["label"]()
exit_label = TYPENAMES["label"]()
exit_stat = EmptyStat(self.parent, symtab=self.symtab)
exit_stat.set_label(exit_label)
self.cond.set_label(entry_label)
branch = BranchStat(
None, self.cond.destination(), exit_label, self.symtab, negcond=True
)
loop = BranchStat(None, None, entry_label, self.symtab)
stat_list = StatList(
self.parent, [self.cond, branch, self.body, loop, exit_stat], self.symtab
)
return self.parent.replace(self, stat_list)
class ForStat(Stat):
def __init__(
self, parent=None, init=None, cond=None, step=None, body=None, symtab=None
):
super().__init__(parent, [], symtab)
self.init = init
self.cond = cond
self.step = step
self.body = body
self.init.parent = self
self.cond.parent = self
self.step.parent = self
self.body.parent = self
"""
for loop lowering:
1. init (to be added)
2. cond (lowered) with label LOOP
3. branch to OUT
4. body
5. step (to be added)
6. branch to LOOP
7. empty stat (label OUT should be pointing here)
WhileStat:
1. cond
2. body
ForStat:
1. init
2. cond
3. step
4. body
"""
def lower(self):
# LOOP label
loop_label = TYPENAMES["label"]()
self.cond.set_label(loop_label)
loop = BranchStat(None, None, loop_label, self.symtab)
# OUT label
out_label = TYPENAMES["label"]()
exit_stat = EmptyStat(self.parent, symtab=self.symtab)
exit_stat.set_label(out_label)
"""cond == None -> branch always taken.
If negcond is True and Cond != None, the branch is taken when cond is false,
otherwise the branch is taken when cond is true.
If returns is True, this is a branch-and-link instruction."""
branch = BranchStat(
None, self.cond.destination(), out_label, self.symtab, negcond=True
)
# StatList to give as output
stat_list = StatList(
self.parent,
[self.init, self.cond, branch, self.body, self.step, loop, exit_stat],
self.symtab,
)
return self.parent.replace(self, stat_list)
class AssignStat(Stat):
def __init__(self, parent=None, target=None, offset=None, expr=None, symtab=None):
super().__init__(parent, [], symtab)
self.symbol = target
try:
self.symbol.parent = self
except AttributeError:
pass
self.expr = expr
self.expr.parent = self
self.offset = offset
if self.offset is not None:
self.offset.parent = self
def collect_uses(self):
try:
a = self.symbol.collect_uses()
except AttributeError:
a = []
try:
a += self.offset.collect_uses()
except AttributeError:
pass
try:
return a + self.expr.collect_uses()
except AttributeError:
return a
def collect_kills(self):
return [self.symbol]
def lower(self):
"""Assign statements translate to a store stmt, with the symbol and a
temporary as parameters."""
src = self.expr.destination()
dst = self.symbol
stats = [self.expr]
if self.offset:
off = self.offset.destination()
desttype = dst.stype
if type(desttype) is ArrayType: # this is always true at the moment
desttype = desttype.basetype
ptrreg = new_temporary(self.symtab, PointerType(desttype))
loadptr = LoadPtrToSym(dest=ptrreg, symbol=dst, symtab=self.symtab)
dst = new_temporary(self.symtab, PointerType(desttype))
add = BinStat(
dest=dst, op="plus", srca=ptrreg, srcb=off, symtab=self.symtab
)
stats += [self.offset, loadptr, add]
stats += [StoreStat(dest=dst, symbol=src, symtab=self.symtab)]
return self.parent.replace(self, StatList(children=stats, symtab=self.symtab))
class ReturnStat(Stat):
def __init__(self, parent=None, exp=None, symtab=None):
super().__init__(parent, [], symtab)
self.expr = exp
self.ret_param_symbol = None
self.expr.parent = self
self.end_label = None
def set_end_label(self, label):
self.end_label = label
def set_ret_param_symbol(self, sym):
self.ret_param_symbol = sym
def lower(self):
print("[DEBUG] ReturnStat.expr : ", self.expr)
# evaluate exp
# store value in ret param
stlist = [
self.expr,
StoreStat(dest=self.ret_param_symbol, symbol=self.expr.destination(), symtab=self.symtab)
]
stlist += [RetStat(use=self.ret_param_symbol)]
stlist = StatList(children=stlist, symtab=self.symtab)
return self.parent.replace(self, stlist)
class RetStat(Stat): # low-level node
def __init__(self, use=None, parent=None, children=None, symtab=None):
super().__init__(parent, children, symtab)
self.use = use
def collect_uses(self):
return [self.use]
class PrintStat(Stat):
def __init__(self, parent=None, exp=None, symtab=None):
super().__init__(parent, [exp], symtab)
self.expr = exp
def collect_uses(self):
return self.expr.collect_uses()
def lower(self):
pc = PrintCommand(src=self.expr.destination(), symtab=self.symtab)
stlist = StatList(children=[self.expr, pc], symtab=self.symtab)
return self.parent.replace(self, stlist)
class PrintCommand(Stat): # low-level node
def __init__(self, parent=None, src=None, symtab=None):
super().__init__(parent, [], symtab)
self.src = src
if src.alloct != "reg":
raise RuntimeError("value not in register")
def collect_uses(self):
return [self.src]
def human_repr(self):
return "print " + repr(self.src)
class ReadStat(Stat):
def __init__(self, parent=None, symtab=None):
super().__init__(parent, [], symtab)
def lower(self):
tmp = new_temporary(self.symtab, TYPENAMES["int"])
read = ReadCommand(dest=tmp, symtab=self.symtab)
stlist = StatList(children=[read], symtab=self.symtab)
return self.parent.replace(self, stlist)
class ReadCommand(Stat): # low-level node
def __init__(self, parent=None, dest=None, symtab=None):
super().__init__(parent, [], symtab)
self.dest = dest
if dest.alloct != "reg":
raise RuntimeError("read not to register")
def destination(self):
return self.dest
def collect_uses(self):
return []
def collect_kills(self):
return [self.dest]
def human_repr(self):
return "read " + repr(self.dest)
class BranchStat(Stat): # low-level node
def __init__(
self,
parent=None,
cond=None,
target=None,
symtab=None,
returns=False,
negcond=False,
):
"""cond == None -> branch always taken.
If negcond is True and Cond != None, the branch is taken when cond is false,
otherwise the branch is taken when cond is true.
If returns is True, this is a branch-and-link instruction."""
super().__init__(parent, [], symtab)
self.cond = cond
self.negcond = negcond
if not (self.cond is None) and self.cond.alloct != "reg":
raise RuntimeError("condition not in register")
self.target = target
self.returns = returns
def collect_uses(self):
if not (self.cond is None):
return [self.cond]
return []
def is_unconditional(self):
if self.cond is None:
return True
return False
def human_repr(self):
if self.returns:
h = "call "
else:
h = "branch "
if not (self.cond is None):
c = "on " + ("not " if self.negcond else "") + repr(self.cond)
else:
c = ""
return h + c + " to " + repr(self.target)
class EmptyStat(Stat): # low-level node
pass
def collect_uses(self):
return []
class LoadPtrToSym(Stat): # low-level node
def __init__(self, parent=None, dest=None, symbol=None, symtab=None):
"""Loads to the 'dest' symbol the location in memory (as an absolute
address) of 'symbol'. This instruction is used as a starting point for
lowering nodes which need any kind of pointer arithmetic."""
super().__init__(parent, [], symtab)
self.symbol = symbol
self.dest = dest
if self.symbol.alloct == "reg":
raise RuntimeError("symbol not in memory")
if self.dest.alloct != "reg":
raise RuntimeError("dest not to register")
def collect_uses(self):
return [self.symbol]
def collect_kills(self):
return [self.dest]
def destination(self):
return self.dest
def human_repr(self):
return repr(self.dest) + " <- &(" + repr(self.symbol) + ")"
class StoreStat(Stat): # low-level node
# store the symbol to the specified destination + offset
def __init__(self, parent=None, dest=None, symbol=None, killhint=None, symtab=None):
"""Stores the value in the 'symbol' temporary (register) to 'dest' which
can be a symbol allocated in memory, or a temporary (symbol allocated to a
register). In the first case, the store is done to the symbol itself; in
the second case the dest symbol is used as a pointer to an arbitrary
location in memory."""
super().__init__(parent, [], symtab)
self.symbol = symbol
if self.symbol.alloct != "reg":
raise RuntimeError("store not from register")
self.dest = dest
self.killhint = killhint
def collect_uses(self):
if self.dest.alloct == "reg":
return [self.symbol, self.dest]
return [self.symbol]
def collect_kills(self):
if self.dest.alloct == "reg":
if self.killhint:
return [self.killhint]
else:
return []
return [self.dest]
def destination(self):
return self.dest
def human_repr(self):
if self.dest.alloct == "reg":
return "[" + repr(self.dest) + "] <- " + repr(self.symbol)
return repr(self.dest) + " <- " + repr(self.symbol)
class LoadStat(Stat): # low-level node
def __init__(self, parent=None, dest=None, symbol=None, usehint=None, symtab=None):
"""Loads the value in symbol to dest, which must be a temporary. 'symbol'
can be a symbol allocated in memory, or a temporary (symbol allocated to a
register). In the first case, the value contained in the symbol itself is
loaded; in the second case the symbol is used as a pointer to an arbitrary
location in memory."""
super().__init__(parent, [], symtab)
self.symbol = symbol
self.dest = dest
self.usehint = usehint
if self.dest.alloct != "reg":
raise RuntimeError("load not to register")
def collect_uses(self):
if self.usehint:
return [self.symbol, self.usehint]
return [self.symbol]
def collect_kills(self):
return [self.dest]
def destination(self):
return self.dest
def human_repr(self):
if self.symbol.alloct == "reg":
return repr(self.dest) + " <- [" + repr(self.symbol) + "]"
else:
return repr(self.dest) + " <- " + repr(self.symbol)
class LoadImmStat(Stat): # low-level node
def __init__(self, parent=None, dest=None, val=0, symtab=None):
super().__init__(parent, [], symtab)
self.val = val
self.dest = dest
if self.dest.alloct != "reg":
raise RuntimeError("load not to register")
def collect_uses(self):
return []
def collect_kills(self):
return [self.dest]
def destination(self):
return self.dest
def human_repr(self):
return repr(self.dest) + " <- " + repr(self.val)
class BinStat(Stat): # low-level node
def __init__(
self, parent=None, dest=None, op=None, srca=None, srcb=None, symtab=None
):
super().__init__(parent, [], symtab)
self.dest = dest # symbol
self.op = op
self.srca = srca # symbol
self.srcb = srcb # symbol
if self.dest.alloct != "reg":
raise RuntimeError("binstat dest not to register")
if self.srca.alloct != "reg" or self.srcb.alloct != "reg":
raise RuntimeError("binstat src not in register")
def collect_kills(self):
return [self.dest]
def collect_uses(self):
return [self.srca, self.srcb]
def destination(self):
return self.dest
def human_repr(self):
return (
repr(self.dest)
+ " <- "
+ repr(self.srca)
+ " "
+ self.op
+ " "
+ repr(self.srcb)