-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcompiler.py
1641 lines (1422 loc) · 43.2 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
#!/usr/bin/python2.7
# -*- coding: utf-8 -*- import requests
import os
import re
import sys
import math
import time
from random import choice
reload(sys)
sizetotype = {8:'.byte', 16:'.half', 32:'.word'}
variable_types = ['sint08','sint16','sint32','uint08','uint16','uint32']
types = variable_types + ['void00']
control_word = ['for', 'while', 'break', 'continue', 'if', 'else', 'return']
reserved_word = types + control_word
register_name = ['$zero','$at','$gp','$sp','$s8','$fp','$ra']
for i in range(2):
register_name.append('$v' + str(i))
for i in range(4):
register_name.append('$a' + str(i))
for i in range(10):
register_name.append('$t' + str(i))
for i in range(8):
register_name.append('$s' + str(i))
for i in range(2):
register_name.append('$k' + str(i))
priority = {
'#':10000,
'!':2, '~':2, '`':2,'$':2,
'*':4, '/':4, '%':4,
'+':5, '-':5,
'<<':6, '>>':6,
'<':7, '<=':7, '>':7, '>=':7,
'==':8, '!=':8,
'&':9,
'^':10,
'|':11,
'&&':12,
'||':13,
'=':15
}
assign_operation = {
'=':15
}
operation_units = {
'#':0,
'!':1, '~':1, '`':1,'$':1,
'*':2, '/':2, '%':2,
'+':2, '-':2,
'<<':2, '>>':2,
'<':2, '<=':2, '>':2, '>=':2,
'==':2, '!=':2,
'&':2,
'^':2,
'|':2,
'&&':2,
'||':2,
'=':2
}
codes = []
raw = []
error_strings = []
outputcode = open('code.asm','w')
errorlog = open('error.txt','w')
prefix_global = 'Global_'
globalVarList = []
globalVarDict = {}
globalArray = []
globalCodes = []
functionNameList = []
functionDict = {}
functionReturnType = {}
functions = []
def swap(a,b):
return b,a
def get_cur_info():
"""Return the frame object for the caller's stack frame."""
try:
raise Exception
except:
f = sys.exc_info()[2].tb_frame.f_back
ret = '(' + str(f.f_code.co_name) + ',' + str(f.f_lineno) + ') '
#return (f.f_code.co_name, f.f_lineno)
return ret
def throw_error(s):
global error_strings
error_strings.append(s)
return 1
def output(s):
outputcode.write(s)
outputcode.flush()
def outputln(s):
outputcode.write(str(s))
outputcode.write('\n')
outputcode.flush()
def errorputln(s):
errorlog.write(s)
errorlog.write('\n')
errorlog.flush()
def find_in_raw_code(s):
l = []
for i in range(len(raw)):
if raw[i].find(s)!=-1:
l.append(i)
if len(l) == 0:
return '?'
ret = ''
for i in l:
ret += "/%d"%(i)
return ret[1:]
class Variable(object):
"""docstring for Variable
type: 0 : register; 1 : RAM,单独变量,占1单元 n(>1):数组,占n单元
"""
def __init__(self, name, vartp):
super(Variable, self).__init__()
self.name = name #name in function
self.vtype = vartp #variable_types = ['sint08','sint16','sint32','uint08','uint16','uint32']
self.sizeof = int(vartp[4:6]) # 8, 16, 32
self.corname = '' # name in .code or register name
self.type = 0 # 0 : register; 1 : RAM单独变量 n(>1):数组,占n单元
def generatecode(self):
if self.type == 1:
tmp = 32/self.sizeof
ret = self.corname + ' ' + sizetotype[self.sizeof]
for i in range(tmp):
ret += ' 0' #32对齐
return 1,ret
elif self.type > 1:
cursize = self.sizeof * self.type
while cursize % 32 != 0:
cursize += self.sizeof
num = cursize / 32
tmp = cursize / self.sizeof
ret = self.corname + ' ' + sizetotype[self.sizeof]
for i in range(tmp):
ret += ' 0' #32对齐
return num,ret
else:
return 0,''
class Function(object):
def __init__(self, codes):
super(Function, self).__init__()
self.codes = []
for i in codes:
i = i.strip()
if i != '':
self.codes.append(i)
tmp = self.codes[0]
name = tmp[tmp.find(' ')+1:tmp.find('(')].strip()
if name == '':
throw_error(get_cur_info() + codes[0])
varstring = tmp[tmp.find('(')+1:tmp.rfind(')')].strip()
self.name = name
self.prefix = name + '_'
self.vtype = self.codes[0][:6] #variable_types = ['void00','sint08','sint16','sint32','uint08','uint16','uint32']
self.sizeof = int(self.vtype[4:6]) # 8, 16, 32
self.params = []
self.vardict = {} # varname -> varclass
if varstring != '' and varstring not in types:
for x in varstring.split(','):
x = x.strip()
tp = x[:6].strip()
name = x[6:].strip()
if name.find('[') != -1:
name = name[:name.find('[')].strip()
self.params.append((name,tp))
self.head = codes[0]
self.vardeclaration = []
self.realcode = []
for i in range(2,len(codes)):
s = self.codes[i]
if len(s) >= 8 and s[:6] in variable_types and s[6] == ' ':
continue
else:
self.vardeclaration = codes[2:i]
self.realcode = codes[i:-1]
break
def printcode(self):
outputln('\n\n' + self.name + '_begin:')
availableVars = self.vardict.copy()
for i,j in globalVarDict.items():
if i not in self.vardict:
availableVars[i] = j
print '\nBegin##################################### ' + self.name
print 'self.name = ',self.name
print 'self.vtype = ',self.codes[0][:6] #variable_types = ['void00','sint08','sint16','sint32','uint08','uint16','uint32']
print 'self.params = ',self.params
self.sizeof = int(self.vtype[4:6]) # 8, 16, 32
print '%s vardict len:%d'%(self.name,len(self.vardict))
print '%s availableVars num: %d'%(self.name,len(availableVars))
for i,j in availableVars.items():
print 'vars %s -- %s'%(i,j.corname)
dealCodes(self.name, self.realcode, availableVars, 0)
rassignr('$v0', '$zero')
outputln('jr $ra')
print '\nEnd##################################### ' + self.name
def get_parenthesis_content(s):
if s == '':
return ''
num = 1
loc = 1
for i in s[1:]:
if i == '(':
num += 1
elif i == ')':
num -= 1
if num == 0:
break
loc += 1
ret = s[:loc + 1]
s = s[loc + 1:].strip()
return (ret, s)
def extract_a_part(s, ret):
if s[0] == '{' or s[0] == '}':
ret.append(s[0])
s = s[1:].strip()
return s
if s == '':
return ''
if re.match('(unsigned )?char |(unsigned )?short |(unsigned )?int ',s):
replace = ''
if s[0] == 'u':
replace += 'u'
s = s[9:]
else:
replace += 's'
replace += 'int'
if s[:4] == 'char':
replace += '08'
s = s[4:]
elif s[:5] == 'short':
replace += '16'
s = s[5:]
elif s[:3] == 'int':
replace += '32'
s = s[3:]
s = replace + s
if re.match('\\bvoid\\b',s):
s = 'void00' + s[4:]
if len(s)>=8 and s[:6] in types:
i = 6
while i < len(s) and ( s[i] == ' ' or s[i] == '\t' ):
i += 1
if i < len(s) and s[i] == '*':
s = s[:i] + s[i+1:]
if s[:3] == 'for':
s = s[3:].strip()
tmp = get_parenthesis_content(s)
ret.append('for' + tmp[0])
s = tmp[1]
if s[0] != '{':
ret.append('{')
s = extract_a_part(s, ret)
ret.append('}')
return s
if s[:5] == 'while':
s = s[5:].strip()
tmp = get_parenthesis_content(s)
ret.append('while' + tmp[0])
s = tmp[1]
if s[0] != '{':
ret.append('{')
s = extract_a_part(s, ret)
ret.append('}')
return s
elif s[:2] == 'if':
s = s[2:].strip()
tmp = get_parenthesis_content(s)
ret.append('if' + tmp[0])
s = tmp[1]
if s[0] != '{':
ret.append('{')
s = extract_a_part(s, ret)
ret.append('}')
if re.match('else[ \\t]+if',s):
tmp = s.find('if')
s = s[tmp:]
ret.append('else')
ret.append('{')
s = extract_a_part(s,ret)
ret.append('}')
elif s[:4] == 'else':
s = s[4:].strip()
ret.append('else')
if s[0] != '{':
ret.append('{')
s = extract_a_part(s, ret)
ret.append('}')
return s
i = 0
for c in s:
if c == ';':
if i:
ret.append(s[:i])
s = s[i + 1:]
break
elif c == '{' or c == '}':
if i:
ret.append(s[:i])
ret.append(s[i])
s = s[i + 1:]
break
i += 1
return s
def init_input():
sys.stdin = open('input.c', 'r')
ret = []
global raw
ss = ''
while True:
try:
s = raw_input().strip()
raw.append(s)
loc = s.find('//')
if loc != -1:
s = s[:loc].strip()
ss += s
except EOFError:
break
while True:
loc = ss.find('/*')
if loc == -1:
break
pre = ss[:loc]
aft = ss[loc + 2:]
loc = aft.find('*/')
if loc != -1:
aft = aft[loc + 2:]
else:
aft = []
ss = pre + aft
tmp = re.search('\\bvoid\\b',ss)
while tmp:
i,j = tmp.span()
ss = ss[:i] + 'void00' + ss[j:]
tmp = re.search('\\bvoid\\b',ss)
tmp = re.search('\\bunsigned char\\b',ss)
while tmp:
i,j = tmp.span()
ss = ss[:i] + 'uint08' + ss[j:]
tmp = re.search('\\bunsigned char\\b',ss)
tmp = re.search('\\bunsigned short\\b',ss)
while tmp:
i,j = tmp.span()
ss = ss[:i] + 'uint16' + ss[j:]
tmp = re.search('\\bunsigned short\\b',ss)
tmp = re.search('\\bunsigned int\\b',ss)
while tmp:
i,j = tmp.span()
ss = ss[:i] + 'uint32' + ss[j:]
tmp = re.search('\\bunsigned int\\b',ss)
tmp = re.search('\\bchar\\b',ss)
while tmp:
i,j = tmp.span()
ss = ss[:i] + 'sint08' + ss[j:]
tmp = re.search('\\bchar\\b',ss)
tmp = re.search('\\bshort\\b',ss)
while tmp:
i,j = tmp.span()
ss = ss[:i] + 'sint16' + ss[j:]
tmp = re.search('\\bshort\\b',ss)
tmp = re.search('\\bint\\b',ss)
while tmp:
i,j = tmp.span()
ss = ss[:i] + 'sint32' + ss[j:]
tmp = re.search('\\bint\\b',ss)
while len(ss) > 0:
# for while if else
ss = extract_a_part(ss, ret)
return ret
def findCurlyContent(codes):
start = -1
ret = []
for i in range(len(codes)):
if codes[i].strip() == '{':
start = i
break
if start == -1 or start >= len(codes) - 2:
return [],0
num = 1
end = start + 1
for s in codes[start+1:]:
if s.strip() == '{':
num += 1
elif s.strip() == '}':
num -= 1
if num == 0:
return codes[start + 1:end],end
end += 1
return codes[start + 1:],len(codes) - 1
pass
#@call var_definition_code, all_code_in_the_function
#@return variable_list(name,type) variable_appear_num{(name,type):num} array_list(name,type)
def scanVarible(codes, allcodes):
variables = []
appearNum = {}
array = []
l = []
if len(codes) == 0:
return variables,appearNum,array
if len(codes[0]) >= 8 and codes[0][:6] in types and re.match('[ \\t]+[A-Za-z][A-Za-z0-9]*\\(.*\\)',codes[0][6:]):
l = codes[1:]
tmp = codes[0].strip()
name = tmp[tmp.find('(')+1:tmp.rfind(')')].strip()
if name not in types and name != '':
for s in name.split(','):
s = s.strip()
tp = s[:6]
name = s[6:].strip()
if name.find('[') != -1:
array.append((name,tp))
else:
variables.append((name,tp))
else:
l = codes
for s in l:
s = s.strip()
if s == '' or s == '{':
continue
tp = s[:6]
name = s[6:].strip()
if '(' in s or '}' in s or s[:s.find(' ')].strip() not in variable_types:
break
if name == '':
throw_error(get_cur_info() + s)
tmp = re.match('[A-Za-z][A-Za-z0-9]*[ \\t]*([ \\t]*,[ \\t]*([A-Za-z][A-Za-z0-9]*))*[ \\t]*;?',name)
if tmp == None or tmp.span()[1] != len(name):
if name.find('[') == -1:
throw_error(get_cur_info() + s)
tmp = [x.strip() for x in name.split(',')]
for v in tmp:
if v in reserved_word:
throw_error(get_cur_info() + s)
break
elif v.find('[') == -1:
variables.append((v,tp))
else:
array.append((v,tp))
for name,tp in variables:
appearNum[(name,tp)] = 0
for s in codes:
s = s.strip()
tmp = '\\b' + name + '\\b'
if re.search(tmp,s):
appearNum[(name,tp)] += 1
return variables,appearNum,array
def dealCodes(funcname, codes, corvar, loopnum):
#throw_error(get_cur_info() + 'dealCodes:'+codes[0])
dealedLineNum = -1
for linenum in range(len(codes)):
outputln('')
if linenum <= dealedLineNum:
continue
s = codes[linenum].strip()
if s == '{' or s == '}' or s == '':
continue
if re.match('^return\\b',s):
tmp = s[6:].strip()
if tmp != '':
dealExpression(tmp, '$v0', funcname, corvar)
#throw_error(get_cur_info() + 'tmp:'+tmp)
outputln('jr $ra')
pass
elif re.match('^while(.+)$',s):
beginLabel = funcname + '_while_start_' + str(loopnum)
endLabel = funcname + '_while_end_' + str(loopnum)
loopnum += 1
state = s[s.find('(')+1:s.rfind(')')].strip()
body,curnum = findCurlyContent(codes[linenum:])
dealedLineNum = linenum + curnum
if state == '':
throw_error(get_cur_info() + s)
continue
outputln(beginLabel + ':')
dealExpression(state,'$t0', funcname, corvar)
outputln('beq $t0,$zero,' + endLabel)
dealCodes(funcname, body, corvar, loopnum)
outputln('j ' + beginLabel)
outputln(endLabel + ':')
outputln('')
pass
elif re.match('^if(.+)$',s):
ifbeginLabel = funcname + '_if_start_' + str(loopnum)
ifendLabel = funcname + '_if_end_' + str(loopnum)
allendLabel = funcname + '_ifelse_end_' + str(loopnum)
state = s[s.find('(')+1:s.rfind(')')].strip()
body,curnum = findCurlyContent(codes[linenum:])
dealedLineNum = linenum + curnum
if state == '':
throw_error(get_cur_info() + s)
continue
outputln(ifbeginLabel + ':')
dealExpression(state,'$t0', funcname, corvar)
outputln('beq $t0,$zero,' + ifendLabel)
dealCodes(funcname, body, corvar, loopnum)
outputln('j ' + allendLabel)
outputln(ifendLabel + ':')
outputln('')
if dealedLineNum + 1 < len(codes) and codes[dealedLineNum + 1].strip() == 'else':
elsebeginLabel = funcname + '_else_start_' + str(loopnum)
elseendLabel = funcname + '_else_end_' + str(loopnum)
body,curnum = findCurlyContent(codes[dealedLineNum + 1:])
dealedLineNum += curnum
if state == '':
throw_error(get_cur_info() + s)
continue
outputln(elsebeginLabel + ':')
dealCodes(funcname, body, corvar, loopnum + 1)
outputln(elseendLabel + ':')
outputln(allendLabel + ':')
outputln('')
loopnum += 1
pass
elif re.match('^for(.*;.*;.*)$',s):
pass
else:# 赋值语句或单条表达式或函数
dealExpression(s,'$v1', funcname, corvar)
pass
#@call string prefuncname, corvar
#@return (a_part, left_string, part_type, part_vtype)
def readapart(s, prefuncname, corvar):
s = s.strip()
if s == '' or s[0] == '(' or s[0] == ')':
return s[0:1].strip(),s[1:].strip(),'parenthesis','NoVtype'
if re.match('[0-9]+\\b|0x[0-9a-fA-F]+\\b',s):
tmp = re.match('[-+]?[0-9]+\\b|[-+]?0x[0-9a-fA-F]+\\b',s).span()[1]
return s[:tmp],s[tmp:].strip(),'const','sint32'
elif re.match('[A-Za-z][A-Za-z0-9]*',s):
tmp = re.match('[A-Za-z][A-Za-z0-9]*',s).span()[1]
if tmp < len(s) and s[tmp] == '(':
num = 1
for i in range(tmp+1, len(s)):
if s[i] == '(':
num += 1
elif s[i] == ')':
num -= 1
if num == 0:
fname = s[:tmp].strip()
return s[:i+1],s[i+1:].strip(),'function',functionReturnType[fname]
elif tmp < len(s) and s[tmp] == '[':
num = 1
for i in range(tmp+1, len(s)):
if s[i] == '[':
num += 1
elif s[i] == ']':
num -= 1
if num == 0:
arrayName = s[:tmp].strip()
return s[:i+1],s[i+1:].strip(),'array',corvar[arrayName].vtype
else:
vname = s[:tmp].strip()
if vname not in corvar:
throw_error(get_cur_info() + s)
return '','','NoType','NoVtype'
else:
return vname,s[tmp:].strip(),'variable',corvar[vname].vtype
elif s[0] in '+-*/=<>!&|^~$%':
i = 0
while i < len(s) and s[:i+1] in priority:
i += 1
return s[:i].strip(),s[i:].strip(),'symbol','NoVtype'
else:
return s,'','NoType','NoVtype'
#@call string, prefuncname, corvar
#@return [(a_part, part_type, part_vtype)]
def toParts(s, prefuncname, corvar):
ret = []
while len(s) > 0:
tmp = readapart(s, prefuncname, corvar)
if tmp[0] != '':
ret.append((tmp[0],tmp[2],tmp[3]))
s = tmp[1].strip()
for i in range(len(ret)):
if ret[i][0] == '-':
if i == 0 or ret[i-1][0] == '(' or ret[i-1][1] == 'symbol':
ret[i] = ('`',ret[i][1],ret[i][2])
if ret[i][0] == '+':
if i == 0 or ret[i-1][0] == '(' or ret[i-1][1] == 'symbol':
ret = ret[:i] + ret[i+1:]
if ret[i][0] == '*':
if i == 0 or ret[i-1][0] == '(' or ret[i-1][1] == 'symbol':
ret[i] = ('$',ret[i][1],ret[i][2])
return ret
def midToSuffix(l):##
ret = []
symbols = [('#','NoType','NoVtype')]
for i,tp,vtype in l:
if tp == 'function' or tp == 'array' or tp == 'const' or tp == 'variable' or tp == 'port':
ret.append((i,tp,vtype))
elif i == '(':
symbols.append((i,tp,vtype))
elif i == ')':
tmp = symbols.pop()
while tmp[0] != '(':
ret.append(tmp)
tmp = symbols.pop()
else:
if symbols[-1][0] == '(':
symbols.append((i,tp,vtype))
elif priority[i] <= priority[symbols[-1][0]]:
symbols.append((i,tp,vtype))
else:
while priority[i] > priority[symbols[-1][0]]:
ret.append(symbols.pop())
symbols.append((i,tp,vtype))
for tmp in reversed(symbols[1:]):
ret.append(tmp)
return ret
def readArrayInData(reg, realArrayName, arrayType, i):
tmpReg = ''
if type(i) == int:
outputln('ori $t0,$zero,%d'%(i))
tmpReg = '$t0'
elif type(i) == str and i in register_name:
tmpReg = i
if arrayType == 'sint08':
outputln('lb %s,%s(%s)'%(reg, realArrayName, tmpReg))
elif arrayType == 'uint08':
outputln('lbu %s,%s(%s)'%(reg, realArrayName, tmpReg ))
elif arrayType == 'sint16':
outputln('sll %s,%s,1'%(tmpReg,tmpReg))
outputln('lh %s,%s(%s)'%(reg, realArrayName, tmpReg ))
elif arrayType == 'uint16':
outputln('sll %s,%s,1'%(tmpReg,tmpReg))
outputln('lhu %s,%s(%s)'%(reg, realArrayName, tmpReg ))
else:
outputln('sll %s,%s,2'%(tmpReg,tmpReg))
outputln('lw %s,%s(%s)'%(reg, realArrayName, tmpReg ))
def saveToArrayInData(reg, realArrayName, arrayType, i):
tmpReg = ''
if type(i) == int:
if i == 0:
tmpReg = '$zero'
else:
outputln('ori $t0,$zero,%d'%(i))
tmpReg = '$t0'
elif type(i) == str and i in register_name:
tmpReg = i
if arrayType == 'sint08' or arrayType == 'uint08':
outputln('sb %s,%s(%s)'%(reg, realArrayName, tmpReg))
elif arrayType == 'sint16' or arrayType == 'uint16':
if not (type(i) == int and i == 0):
outputln('sll %s,%s,1'%(tmpReg,tmpReg))
outputln('sh %s,%s(%s)'%(reg, realArrayName, tmpReg ))
else:
if not (type(i) == int and i == 0):
outputln('sll %s,%s,2'%(tmpReg,tmpReg))
outputln('sw %s,%s(%s)'%(reg, realArrayName, tmpReg ))
#@return successful
def rassignr(regto, regfrom):
if regto not in register_name or regfrom not in register_name:
return False
outputln('ori %s,%s,0'%(regto,regfrom))
return True
#@return successful
def rassignrWithStyle(regto, regfrom, toVstyle = 'sint32', fromVstyle = 'sint32'):
#variable_types = ['sint08','sint16','sint32','uint08','uint16','uint32']
print 'rassignrWithStyle:',regto,regfrom,toVstyle,fromVstyle
if regto not in register_name or regfrom not in register_name or toVstyle not in variable_types or fromVstyle not in variable_types:
print register_name
print variable_types
print 'rassignrWithStyle Failed'
return False
tosize = int(toVstyle[-2:])
fromsize = int(fromVstyle[-2:])
if toVstyle == fromVstyle:
outputln('ori %s,%s,0'%(regto,regfrom))
elif tosize >= fromsize and toVstyle[0] == fromVstyle[0]:
outputln('ori %s,%s,0'%(regto,regfrom))
elif tosize < fromsize and toVstyle[0] == 's' and fromVstyle[0] == 's': ## s<-s, 填充符号位
outputln('ori %s,%s,0'%(regto,regfrom))
num = 32 - int(toVstyle[-2:])
outputln('sll %s,%s,%d'%(regto,regto,num))
outputln('sra %s,%s,%d'%(regto,regto,num))
pass ##
elif tosize < fromsize and toVstyle[0] == 'u' and fromVstyle[0] == 'u': #填0 u<-u, 填充0
outputln('ori %s,%s,0'%(regto,regfrom))
num = 32 - int(toVstyle[-2:])
outputln('sll %s,%s,%d'%(regto,regto,num))
outputln('srl %s,%s,%d'%(regto,regto,num))
elif toVstyle == 's' and fromVstyle[0] == 'u' and toVstyle[-2:] == fromVstyle[-2:]: #s<-u
outputln('ori %s,%s,0'%(regto,regfrom))
num = 32 - int(toVstyle[-2:])
outputln('sll %s,%s,%d'%(regto,regto,num))
outputln('sra %s,%s,%d'%(regto,regto,num))
elif toVstyle == 'u' and fromVstyle[0] == 's' and toVstyle[-2:] == fromVstyle[-2:]: #u<-s
outputln('ori %s,%s,0'%(regto,regfrom))
num = 32 - int(toVstyle[-2:])
outputln('sll %s,%s,%d'%(regto,regto,num))
outputln('srl %s,%s,%d'%(regto,regto,num))
elif toVstyle == 's' and fromVstyle[0] == 'u' and int(toVstyle[-2:]) > int(fromVstyle[-2:]): #s<-u
outputln('ori %s,%s,0'%(regto,regfrom))
elif toVstyle == 's' and fromVstyle[0] == 'u' and int(toVstyle[-2:]) < int(fromVstyle[-2:]): #s<-u
outputln('ori %s,%s,0'%(regto,regfrom))
num = 32 - int(toVstyle[-2:])
outputln('sll %s,%s,%d'%(regto,regto,num))
outputln('sra %s,%s,%d'%(regto,regto,num))
elif toVstyle == 'u' and fromVstyle[0] == 's' and toVstyle[-2:] > fromVstyle[-2:]: #u<-s
outputln('ori %s,%s,0'%(regto,regfrom))
num = 32 - int(toVstyle[-2:])
outputln('sll %s,%s,%d'%(regto,regto,num))
outputln('sra %s,%s,%d'%(regto,regto,num))
elif toVstyle == 'u' and fromVstyle[0] == 's' and toVstyle[-2:] < fromVstyle[-2:]: #u<-s
outputln('ori %s,%s,0'%(regto,regfrom))
num = 32 - int(toVstyle[-2:])
outputln('sll %s,%s,%d'%(regto,regto,num))
outputln('srl %s,%s,%d'%(regto,regto,num))
return True
def regFormat(reg, vtype):
if vtype[0] == 'u':
num = 32 - int(vtype[-2:])
outputln('sll %s,%s,%d'%(reg,reg,num))
outputln('srl %s,%s,%d'%(reg,reg,num))
elif vtype[0] == 's':
num = 32 - int(vtype[-2:])
outputln('sll %s,%s,%d'%(reg,reg,num))
outputln('sra %s,%s,%d'%(reg,reg,num))
#assign the value in x to reg
#@return successful
def assignr(x , reg, prefuncname, corvar):
# x[0] : name x[1] : type x[2] : variable_type (['void00','sint08','sint16','sint32','uint08','uint16','uint32'])
# tp == 'function' or tp == 'array' or tp == 'const' or tp == 'variable' or tp == 'port':
name = x[0]
tp = x[1]
vtype = x[2]
print 'assignr ',x,reg
if tp == 'function':
##prefuncname 调用 x[0] : funcName
##corvar --- functionDict[funcName].vardict
##params 传给 functionDict[funcName].params
funcName = name[:name.find('(')].strip()
params = name[name.find('(')+1:name.rfind(')')].strip()
if params == '':
params = []
else:
params = [x.strip() for x in params.split(',')]
if len(params) != len(functionDict[funcName].params):
throw_error(get_cur_info() + x)
return False
outputln('PUSHA ##'+prefuncname)
f = functionDict[funcName]
##开始传参数
for i in range(len(params)):
here = params[i]
aimName, aimVarType = f.params[i]
aimRealName = f.vardict[aimName].corname
if here in corvar and corvar[here].type > 1 and f.vardict[aimName].type > 1: #传递整个数组
hereRealName = corvar[here].corname
hereVarType = corvar[here].vtype
size = f.vardict[aimName].type
for i in range(size):
readArrayInData('$a0',hereRealName,hereVarType,i)
saveToArrayInData('$a0',aimRealName,aimVarType,i)
continue
elif here in corvar and corvar[here].type > 1 or f.vardict[aimName].type > 1:
throw_error(get_cur_info() + x)
rassignr(reg, '$zero')
return
else: ##aim 必定是0 - reg, 1 - 内存的单个变量两种形式;
ansvtype = dealExpression(here, '$a0', prefuncname, corvar)
var = f.vardict[aimName]
print 'func: aimName:' + aimName,'var:'+aimRealName, ansvtype
if var.type == 0:
rassignrWithStyle(aimRealName, '$a0', var.vtype, ansvtype)
elif var.type == 1:
saveToArrayInData('$a0', aimRealName, aimVarType, 0)
print 'func:var assign end'
#函数执行
outputln('jal ' + funcName + '_begin')
#执行结束, 结果存于$v0
outputln('POPA ##' + prefuncname) #PUSHA, POPA操作不能动$v的值
rassignr('$v0', reg)
elif tp == 'array':
arrayName = x[0][:name.find('[')].strip()
param = name[name.find('[')+1:name.rfind(']')].strip()
dealExpression(param, '$a0', prefuncname, corvar)
realArrayName = corvar[arrayName].corname
readArrayInData(reg, realArrayName, vtype, '$a0')
elif tp == 'const': # vtype must be sint32
exp = x[0]
realnum = 0
if exp.find('x') != -1:
realnum = int(exp,16)
else:
realnum = int(exp,10)
if abs(realnum) <= 65535:
outputln('ori %s,$zero,%s'%(reg,exp))
else:
pre = (realnum >> 16) & ((1 << 16) - 1)
aft = realnum & ((1 << 16) - 1)
pres = ''
afts = ''
for i in range(16):
pres += str(pre & 1)
pre >>= 1
afts += str(aft & 1)
aft >>= 1
pre = int(pres[::-1],2)
aft = int(afts[::-1],2)
outputln('ori %s,$zero,%d'%(reg,pre))
outputln('sll %s,%s,16'%(reg,reg))
outputln('ori %s,$zero,%d'%(reg,aft))
elif tp == 'variable':
var = corvar[name]
if var.type == 0:
rassignr(reg, var.corname)
elif var.type == 1:
if vtype == 'sint08':
outputln('lb %s,%s(%s)'%(reg, var.corname, '$zero'))
pass
elif vtype == 'uint08':
outputln('lbu %s,%s(%s)'%(reg, var.corname, '$zero' ))
pass
elif vtype == 'sint16':
outputln('lh %s,%s(%s)'%(reg, var.corname, '$zero' ))
pass
elif vtype == 'uint16':
outputln('lhu %s,%s(%s)'%(reg, var.corname, '$zero' ))
pass
elif vtype.strip() == 'sint32' or vtype.strip() == 'uint32':
outputln('lw %s,%s(%s)'%(reg, var.corname, '$zero'))
else:
throw_error(get_cur_info() + name)
rassignr(reg, '$zero')
pass
elif tp == 'port':
# var = corvar[name]
# if var.type == 0:
# outputln('lw %s,0(%s)'%(reg,var.corname))
# elif var.type == 1:
# outputln('lw $t0,%s($zero)'%(var.corname))
# outputln('lw %s,0(%s)'%(reg, '$t0'))
#2outputln('lw %s,%s($zero)'%(reg,extractPort(name)))
outputln('POP ' + reg)
outputln('lw %s,0(%s)'%(reg,name))
else:
throw_error(get_cur_info() + x[0])
rassignr(reg, '$zero')
return True
def extractPort(_s):
s = _s
if s[:2] == '0x':
s = s[2:]
if s[0] == '0':
s = s[1:]
if s[:4] == 'ffff' or s[:4] == 'FFFF':
s = s[4:]
if s[-1]!='h' and s[-1]!='H':
s = s + 'h'
return s
pass
#save the value in reg to the (name,tp,vtype)
#@return vtype of the ans
def rassign((reg,regvtype), (name, tp, vtype) , prefuncname, corvar):
#x : (name, tp, vtype) tp must in ['array'(a[num]) , 'variable', 'port']
if tp == 'array':
arrayName = name[:name.find('[')].strip()
num = name[name.find('[')+1:name.rfind(']')].strip()
dealExpression(num, '$a0', prefuncname, corvar)
saveToArrayInData(reg, corvar[arrayName].corname, vtype, '$a0')
elif tp == 'variable':
var = corvar[name]
realName = var.corname
if var.type == 0:
rassignrWithStyle(var.corname, reg, var.vtype, regvtype)
elif var.type == 1:
saveToArrayInData(reg, var.corname, var.vtype, 0)
else:
return ''
elif tp == 'port': ##
# var = corvar[name]
# if var.type == 0:
# outputln('sw %s,0(%s)'%(reg,var.corname))
# elif var.type == 1:
# outputln('lw $t0,%s($zero)'%(var.corname))
# outputln('sw %s,0(%s)'%(reg, '$t0'))
#2outputln('sw %s,%s($zero)'%(reg,extractPort(name)))
outputln('POP ' + reg)
outputln('sw %s,0(%s)'%(reg,name))
else:
return ''
return vtype
#@return vtype of the ans
def calc1((reg,vtype), oper, savereg):
ansvtype = ''
if oper == '!':
outputln('ori %s,$zero,1'%(savereg))
outputln('beq %s,$zero,1'%(reg))
outputln('ori %s,$zero,0'%(savereg))
ansvtype = vtype
elif oper == '~':
outputln('nor %s,%s,%s'%(savereg,reg,reg))