292
|
1 #!/usr/bin/env python
|
104
|
2
|
287
|
3 import sys
|
|
4 import argparse
|
|
5 import logging
|
|
6
|
313
|
7 from ppci.c3 import Builder, AstPrinter
|
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
|
317
|
16 from ppci.transform import CleanPass, RemoveAddZero
|
253
|
17
|
289
|
18
|
281
|
19 logformat='%(asctime)s|%(levelname)s|%(name)s|%(message)s'
|
|
20
|
289
|
21
|
253
|
22 def logLevel(s):
|
312
|
23 """ Converts a string to a valid logging level """
|
253
|
24 numeric_level = getattr(logging, s.upper(), None)
|
|
25 if not isinstance(numeric_level, int):
|
|
26 raise ValueError('Invalid log level: {}'.format(s))
|
|
27 return numeric_level
|
105
|
28
|
289
|
29
|
312
|
30 class RstFormatter(logging.Formatter):
|
|
31 """ Formatter that tries to create an rst document """
|
|
32 def __init__(self):
|
|
33 super().__init__(fmt=logformat)
|
|
34
|
|
35 def format(self, record):
|
|
36 s = super().format(record)
|
314
|
37 s += '\n'
|
313
|
38 if hasattr(record, 'c3_ast'):
|
|
39 f = io.StringIO()
|
|
40 print('', file=f)
|
|
41 print('', file=f)
|
|
42 print('.. code::', file=f)
|
|
43 print('', file=f)
|
|
44 AstPrinter().printAst(record.c3_ast, f)
|
|
45 print('', file=f)
|
|
46 s += '\n' + f.getvalue()
|
312
|
47 if hasattr(record, 'ircode'):
|
|
48 f = io.StringIO()
|
|
49 print('', file=f)
|
|
50 print('', file=f)
|
|
51 print('.. code::', file=f)
|
|
52 print('', file=f)
|
|
53 Writer(' ').write(record.ircode, f)
|
|
54 print('', file=f)
|
|
55 s += '\n' + f.getvalue()
|
|
56 if hasattr(record, 'irfunc'):
|
|
57 f = io.StringIO()
|
|
58 print('', file=f)
|
|
59 print('', file=f)
|
|
60 print('.. code::', file=f)
|
|
61 print('', file=f)
|
|
62 Writer(' ').write_function(record.irfunc, f)
|
|
63 print('', file=f)
|
|
64 s += '\n' + f.getvalue()
|
|
65 if hasattr(record, 'ppci_frame'):
|
|
66 f = io.StringIO()
|
|
67 frame = record.ppci_frame
|
|
68 print('', file=f)
|
|
69 print('.. code::', file=f)
|
|
70 print('', file=f)
|
|
71 print(' {}'.format(frame.name), file=f)
|
|
72 for i in frame.instructions:
|
|
73 print(' {}'.format(i),file=f)
|
|
74 print('', file=f)
|
|
75 s += '\n' + f.getvalue()
|
|
76 if hasattr(record, 'ra_cfg'):
|
|
77 f = io.StringIO()
|
|
78 print('', file=f)
|
|
79 print('', file=f)
|
|
80 print('.. graphviz::', file=f)
|
|
81 print('', file=f)
|
|
82 print(' digraph G {', file=f)
|
316
|
83 print(' size="8,80";', file=f)
|
312
|
84 cfg = record.ra_cfg
|
|
85 cfg.to_dot(f)
|
|
86 print(' }', file=f)
|
|
87 print('', file=f)
|
|
88 s += '\n' + f.getvalue()
|
314
|
89 if hasattr(record, 'ra_ig'):
|
|
90 f = io.StringIO()
|
|
91 print('', file=f)
|
|
92 print('', file=f)
|
|
93 print('.. graphviz::', file=f)
|
|
94 print('', file=f)
|
|
95 print(' digraph G {', file=f)
|
316
|
96 print(' ratio="compress";', file=f)
|
|
97 print(' size="8,80";', file=f)
|
314
|
98 ig = record.ra_ig
|
|
99 ig.to_dot(f)
|
|
100 print(' }', file=f)
|
|
101 print('', file=f)
|
|
102 s += '\n' + f.getvalue()
|
316
|
103 if hasattr(record, 'zcc_outs'):
|
|
104 f = io.StringIO()
|
|
105 print('', file=f)
|
|
106 print('', file=f)
|
|
107 print('.. code::', file=f)
|
|
108 print('', file=f)
|
|
109 outstream.OutputStreamWriter(' ').dump(record.zcc_outs, f)
|
|
110 print('', file=f)
|
|
111 s += '\n' + f.getvalue()
|
312
|
112 return s
|
|
113
|
|
114
|
322
|
115 targets = {t.name: t for t in target.target_list.target_list}
|
292
|
116 targetnames = list(targets.keys())
|
290
|
117
|
205
|
118 # Parse arguments:
|
204
|
119 parser = argparse.ArgumentParser(description='lcfos Compiler')
|
213
|
120 parser.add_argument('source', type=argparse.FileType('r'), \
|
287
|
121 help='the source file to build', nargs="+")
|
290
|
122 parser.add_argument('-i', '--imp', type=argparse.FileType('r'), \
|
296
|
123 help='Possible import module', action='append', default=[])
|
287
|
124
|
255
|
125 parser.add_argument('--optimize', action='store_true', help="Optimize")
|
290
|
126 parser.add_argument('--target', help="Backend selection",
|
292
|
127 choices=targetnames, required=True)
|
205
|
128 parser.add_argument('-o', '--output', help='Output file', metavar='filename')
|
290
|
129 parser.add_argument('--hexfile', help='Output hexfile',
|
|
130 type=argparse.FileType('w'))
|
315
|
131 parser.add_argument('--log', help='Log level (INFO,DEBUG,[WARN])',
|
|
132 type=logLevel, default='WARN')
|
316
|
133 parser.add_argument('--report',
|
|
134 help='Specify a file to write the compile report to',
|
315
|
135 type=argparse.FileType('w'))
|
104
|
136
|
288
|
137
|
315
|
138 def zcc(srcs, imps, tg, outs, diag):
|
287
|
139 """
|
315
|
140 Compiler driver
|
287
|
141 Compile sources into output stream.
|
|
142 Sources is an iterable of open files.
|
|
143 """
|
316
|
144 logger = logging.getLogger('zcc')
|
|
145 logger.info('Zcc started {}'.format(srcs))
|
207
|
146 # Front end:
|
301
|
147 c3b = Builder(diag, tg)
|
|
148 cg = CodeGenerator(tg)
|
292
|
149
|
|
150 # TODO: remove this arm specifics:
|
|
151 outs.getSection('code').address = 0x08000000
|
|
152 outs.getSection('data').address = 0x20000000
|
|
153
|
|
154 # Emit some custom start code:
|
|
155 tg.startCode(outs)
|
287
|
156 for ircode in c3b.build(srcs, imps):
|
|
157 if not ircode:
|
|
158 return
|
313
|
159
|
|
160 d = {'ircode':ircode}
|
316
|
161 logger.info('Verifying code {}'.format(ircode), extra=d)
|
|
162 Verifier().verify(ircode)
|
|
163
|
|
164 # Optimization passes:
|
|
165 CleanPass().run(ircode)
|
312
|
166 Verifier().verify(ircode)
|
317
|
167 RemoveAddZero().run(ircode)
|
|
168 Verifier().verify(ircode)
|
|
169 CleanPass().run(ircode)
|
|
170 Verifier().verify(ircode)
|
289
|
171
|
287
|
172 # Code generation:
|
312
|
173 d = {'ircode':ircode}
|
316
|
174 logger.info('Starting code generation for {}'.format(ircode), extra=d)
|
292
|
175 cg.generate(ircode, outs)
|
|
176 # TODO: fixup references, do this in another way?
|
|
177 outs.backpatch()
|
|
178 outs.backpatch() # Why two times?
|
288
|
179 return c3b.ok
|
|
180
|
249
|
181
|
|
182 def main(args):
|
315
|
183 # Configure some logging:
|
|
184 logging.getLogger().setLevel(logging.DEBUG)
|
|
185 ch = logging.StreamHandler()
|
|
186 ch.setFormatter(logging.Formatter(logformat))
|
|
187 ch.setLevel(args.log)
|
|
188 logging.getLogger().addHandler(ch)
|
|
189 if args.report:
|
|
190 fh = logging.StreamHandler(stream=args.report)
|
|
191 fh.setFormatter(RstFormatter())
|
|
192 logging.getLogger().addHandler(fh)
|
312
|
193
|
292
|
194 tg = targets[args.target]
|
249
|
195 diag = ppci.DiagnosticsManager()
|
|
196 outs = outstream.TextOutputStream()
|
|
197
|
315
|
198 res = zcc(args.source, args.imp, tg, outs, diag)
|
249
|
199 if not res:
|
293
|
200 diag.printErrors()
|
276
|
201 return 1
|
205
|
202
|
313
|
203 logging.info('Assembly created', extra={'zcc_outs':outs})
|
105
|
204
|
237
|
205 code_bytes = outs.sections['code'].to_bytes()
|
207
|
206 if args.output:
|
|
207 output_filename = args.output
|
287
|
208 with open(output_filename, 'wb') as f:
|
|
209 f.write(code_bytes)
|
104
|
210
|
246
|
211 if args.hexfile:
|
255
|
212 logging.info('Creating hexfile')
|
292
|
213 hf = HexFile()
|
246
|
214 hf.addRegion(0x08000000, code_bytes)
|
|
215 hf.save(args.hexfile)
|
315
|
216
|
|
217 if args.report:
|
|
218 logging.getLogger().removeHandler(fh)
|
|
219 logging.getLogger().removeHandler(ch)
|
276
|
220 return 0
|
246
|
221
|
288
|
222
|
207
|
223 if __name__ == '__main__':
|
213
|
224 arguments = parser.parse_args()
|
276
|
225 sys.exit(main(arguments))
|