157
|
1 import ppci
|
158
|
2 import ir
|
|
3
|
|
4 class AsmLabel:
|
|
5 def __init__(self, lab):
|
|
6 self.lab = lab
|
|
7 def __repr__(self):
|
|
8 return '{0}:'.format(self.lab)
|
|
9
|
|
10 class Op:
|
|
11 def __init__(self, op, a, b):
|
|
12 self.op = op
|
|
13 self.a = a
|
|
14 self.b = b
|
|
15 def __repr__(self):
|
|
16 return '{0} {1}, {2}'.format(self.op, self.a, self.b)
|
157
|
17
|
|
18 class X86CodeGen:
|
|
19 def __init__(self, diag):
|
|
20 self.diag = diag
|
160
|
21 self.regs = ['rax', 'rbx', 'rcx', 'rdx']
|
157
|
22
|
158
|
23 def emit(self, i):
|
|
24 self.asm.append(i)
|
160
|
25 def allocateReg(self, typ):
|
|
26 return 'ax'
|
|
27 def deallocateReg(self, r):
|
|
28 pass
|
158
|
29
|
157
|
30 def genBin(self, i):
|
158
|
31 self.asm = []
|
|
32 self.genModule(i)
|
157
|
33
|
158
|
34 def genModule(self, m):
|
|
35 for g in m.Globals:
|
|
36 self.emit(AsmLabel(g.name))
|
|
37 # Ignore types for now ..
|
|
38 self.emit('dw 0')
|
|
39 for f in m.Functions:
|
|
40 self.genFunction(f)
|
|
41 def genFunction(self, f):
|
|
42 self.emit('global {0}'.format(f.name))
|
|
43 self.emit(AsmLabel(f.name))
|
|
44 for bb in f.BasicBlocks:
|
|
45 self.genBB(bb)
|
|
46 def genBB(self, bb):
|
|
47 for i in bb.Instructions:
|
|
48 self.genIns(i)
|
|
49 def genIns(self, i):
|
|
50 if type(i) is ir.BinaryOperator:
|
|
51 if i.operation == 'fadd':
|
|
52 r = 'rax'
|
|
53 self.emit(Op('add', r, '11'))
|
160
|
54 elif type(i) is ir.LoadInstruction:
|
|
55 r = 'rbx'
|
|
56 self.emit(Op('mov', r, '{0}'.format(i.value)))
|
158
|
57 elif type(i) is ir.RetInstruction:
|
|
58 self.emit('ret')
|
160
|
59 elif type(i) is ir.CallInstruction:
|
|
60 self.emit('call')
|
158
|
61 else:
|
|
62 print('Unknown ins', i)
|
|
63
|