292
|
1 #!/usr/bin/env python
|
104
|
2
|
287
|
3 import sys
|
|
4 import argparse
|
|
5 import logging
|
|
6
|
300
|
7 from ppci.c3 import Builder
|
287
|
8 import ppci
|
312
|
9 from ppci.irutils import Verifier, Writer
|
301
|
10 from ppci.codegen import CodeGenerator
|
205
|
11 import outstream
|
292
|
12 from utils import HexFile
|
290
|
13 import target
|
311
|
14 from ppci import irutils
|
|
15 import io
|
253
|
16
|
289
|
17
|
281
|
18 logformat='%(asctime)s|%(levelname)s|%(name)s|%(message)s'
|
|
19
|
289
|
20
|
253
|
21 def logLevel(s):
|
312
|
22 """ Converts a string to a valid logging level """
|
253
|
23 numeric_level = getattr(logging, s.upper(), None)
|
|
24 if not isinstance(numeric_level, int):
|
|
25 raise ValueError('Invalid log level: {}'.format(s))
|
|
26 return numeric_level
|
105
|
27
|
289
|
28
|
312
|
29 class RstFormatter(logging.Formatter):
|
|
30 """ Formatter that tries to create an rst document """
|
|
31 def __init__(self):
|
|
32 super().__init__(fmt=logformat)
|
|
33
|
|
34 def format(self, record):
|
|
35 s = super().format(record)
|
|
36 if hasattr(record, 'ircode'):
|
|
37 f = io.StringIO()
|
|
38 print('', file=f)
|
|
39 print('', file=f)
|
|
40 print('.. code::', file=f)
|
|
41 print('', file=f)
|
|
42 Writer(' ').write(record.ircode, f)
|
|
43 print('', file=f)
|
|
44 s += '\n' + f.getvalue()
|
|
45 if hasattr(record, 'irfunc'):
|
|
46 f = io.StringIO()
|
|
47 print('', file=f)
|
|
48 print('', file=f)
|
|
49 print('.. code::', file=f)
|
|
50 print('', file=f)
|
|
51 Writer(' ').write_function(record.irfunc, f)
|
|
52 print('', file=f)
|
|
53 s += '\n' + f.getvalue()
|
|
54 if hasattr(record, 'ppci_frame'):
|
|
55 f = io.StringIO()
|
|
56 frame = record.ppci_frame
|
|
57 print('', file=f)
|
|
58 print('.. code::', file=f)
|
|
59 print('', file=f)
|
|
60 print(' {}'.format(frame.name), file=f)
|
|
61 for i in frame.instructions:
|
|
62 print(' {}'.format(i),file=f)
|
|
63 print('', file=f)
|
|
64 s += '\n' + f.getvalue()
|
|
65 if hasattr(record, 'ra_cfg'):
|
|
66 f = io.StringIO()
|
|
67 print('', file=f)
|
|
68 print('', file=f)
|
|
69 print('.. graphviz::', file=f)
|
|
70 print('', file=f)
|
|
71 print(' digraph G {', file=f)
|
|
72 cfg = record.ra_cfg
|
|
73 cfg.to_dot(f)
|
|
74 print(' }', file=f)
|
|
75 print('', file=f)
|
|
76 s += '\n' + f.getvalue()
|
|
77 return s
|
|
78
|
|
79
|
290
|
80 target_list = [target.armtarget]
|
292
|
81 targets = {t.name: t for t in target_list}
|
|
82 targetnames = list(targets.keys())
|
290
|
83
|
205
|
84 # Parse arguments:
|
204
|
85 parser = argparse.ArgumentParser(description='lcfos Compiler')
|
287
|
86 # Input:
|
213
|
87 parser.add_argument('source', type=argparse.FileType('r'), \
|
287
|
88 help='the source file to build', nargs="+")
|
290
|
89 parser.add_argument('-i', '--imp', type=argparse.FileType('r'), \
|
296
|
90 help='Possible import module', action='append', default=[])
|
287
|
91
|
253
|
92 parser.add_argument('--dumpir', action='store_true', help="Dump IR-code")
|
255
|
93 parser.add_argument('--dumpasm', action='store_true', help="Dump ASM-code")
|
|
94 parser.add_argument('--optimize', action='store_true', help="Optimize")
|
290
|
95 parser.add_argument('--target', help="Backend selection",
|
292
|
96 choices=targetnames, required=True)
|
205
|
97 parser.add_argument('-o', '--output', help='Output file', metavar='filename')
|
290
|
98 parser.add_argument('--hexfile', help='Output hexfile',
|
|
99 type=argparse.FileType('w'))
|
253
|
100 parser.add_argument('--log', help='Log level (INFO,DEBUG)', type=logLevel)
|
104
|
101
|
288
|
102
|
292
|
103 def zcc(srcs, imps, tg, outs, diag, dumpir=False):
|
287
|
104 """
|
|
105 Compile sources into output stream.
|
|
106 Sources is an iterable of open files.
|
|
107 """
|
255
|
108 logging.info('Zcc started')
|
207
|
109 # Front end:
|
301
|
110 c3b = Builder(diag, tg)
|
|
111 cg = CodeGenerator(tg)
|
292
|
112
|
|
113 # TODO: remove this arm specifics:
|
|
114 outs.getSection('code').address = 0x08000000
|
|
115 outs.getSection('data').address = 0x20000000
|
|
116
|
|
117 # Emit some custom start code:
|
|
118 tg.startCode(outs)
|
287
|
119 for ircode in c3b.build(srcs, imps):
|
|
120 if not ircode:
|
|
121 return
|
290
|
122 # Optimization passes, TODO
|
312
|
123 Verifier().verify(ircode)
|
289
|
124
|
287
|
125 if dumpir:
|
311
|
126 f = io.StringIO()
|
|
127 irutils.Writer().write(ircode, f)
|
|
128 print(f.getvalue())
|
249
|
129
|
287
|
130 # Code generation:
|
312
|
131 d = {'ircode':ircode}
|
|
132 logging.info('Starting code generation for {}'.format(ircode), extra=d)
|
292
|
133 cg.generate(ircode, outs)
|
|
134 # TODO: fixup references, do this in another way?
|
|
135 outs.backpatch()
|
|
136 outs.backpatch() # Why two times?
|
288
|
137 return c3b.ok
|
|
138
|
249
|
139
|
|
140 def main(args):
|
258
|
141 logging.basicConfig(format=logformat, level=args.log)
|
312
|
142 #logging.getLogger().addHandler(RstLogHandler())
|
|
143 fh = logging.FileHandler('log.rst', mode='w')
|
|
144 fh.setFormatter(RstFormatter())
|
|
145 logging.getLogger().addHandler(fh)
|
|
146
|
292
|
147 tg = targets[args.target]
|
249
|
148 diag = ppci.DiagnosticsManager()
|
|
149 outs = outstream.TextOutputStream()
|
|
150
|
296
|
151 res = zcc(args.source, args.imp, tg, outs, diag, dumpir=args.dumpir)
|
249
|
152 if not res:
|
293
|
153 diag.printErrors()
|
276
|
154 return 1
|
205
|
155
|
255
|
156 if args.dumpasm:
|
|
157 outs.dump()
|
105
|
158
|
237
|
159 code_bytes = outs.sections['code'].to_bytes()
|
207
|
160 if args.output:
|
|
161 output_filename = args.output
|
287
|
162 with open(output_filename, 'wb') as f:
|
|
163 f.write(code_bytes)
|
104
|
164
|
246
|
165 if args.hexfile:
|
255
|
166 logging.info('Creating hexfile')
|
292
|
167 hf = HexFile()
|
246
|
168 hf.addRegion(0x08000000, code_bytes)
|
|
169 hf.save(args.hexfile)
|
276
|
170 return 0
|
246
|
171
|
288
|
172
|
207
|
173 if __name__ == '__main__':
|
213
|
174 arguments = parser.parse_args()
|
276
|
175 sys.exit(main(arguments))
|