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
|
290
|
115 target_list = [target.armtarget]
|
292
|
116 targets = {t.name: t for t in target_list}
|
|
117 targetnames = list(targets.keys())
|
290
|
118
|
205
|
119 # Parse arguments:
|
204
|
120 parser = argparse.ArgumentParser(description='lcfos Compiler')
|
213
|
121 parser.add_argument('source', type=argparse.FileType('r'), \
|
287
|
122 help='the source file to build', nargs="+")
|
290
|
123 parser.add_argument('-i', '--imp', type=argparse.FileType('r'), \
|
296
|
124 help='Possible import module', action='append', default=[])
|
287
|
125
|
255
|
126 parser.add_argument('--optimize', action='store_true', help="Optimize")
|
290
|
127 parser.add_argument('--target', help="Backend selection",
|
292
|
128 choices=targetnames, required=True)
|
205
|
129 parser.add_argument('-o', '--output', help='Output file', metavar='filename')
|
290
|
130 parser.add_argument('--hexfile', help='Output hexfile',
|
|
131 type=argparse.FileType('w'))
|
315
|
132 parser.add_argument('--log', help='Log level (INFO,DEBUG,[WARN])',
|
|
133 type=logLevel, default='WARN')
|
316
|
134 parser.add_argument('--report',
|
|
135 help='Specify a file to write the compile report to',
|
315
|
136 type=argparse.FileType('w'))
|
104
|
137
|
288
|
138
|
315
|
139 def zcc(srcs, imps, tg, outs, diag):
|
287
|
140 """
|
315
|
141 Compiler driver
|
287
|
142 Compile sources into output stream.
|
|
143 Sources is an iterable of open files.
|
|
144 """
|
316
|
145 logger = logging.getLogger('zcc')
|
|
146 logger.info('Zcc started {}'.format(srcs))
|
207
|
147 # Front end:
|
301
|
148 c3b = Builder(diag, tg)
|
|
149 cg = CodeGenerator(tg)
|
292
|
150
|
|
151 # TODO: remove this arm specifics:
|
|
152 outs.getSection('code').address = 0x08000000
|
|
153 outs.getSection('data').address = 0x20000000
|
|
154
|
|
155 # Emit some custom start code:
|
|
156 tg.startCode(outs)
|
287
|
157 for ircode in c3b.build(srcs, imps):
|
|
158 if not ircode:
|
|
159 return
|
313
|
160
|
|
161 d = {'ircode':ircode}
|
316
|
162 logger.info('Verifying code {}'.format(ircode), extra=d)
|
|
163 Verifier().verify(ircode)
|
|
164
|
|
165 # Optimization passes:
|
|
166 CleanPass().run(ircode)
|
312
|
167 Verifier().verify(ircode)
|
317
|
168 RemoveAddZero().run(ircode)
|
|
169 Verifier().verify(ircode)
|
|
170 CleanPass().run(ircode)
|
|
171 Verifier().verify(ircode)
|
289
|
172
|
287
|
173 # Code generation:
|
312
|
174 d = {'ircode':ircode}
|
316
|
175 logger.info('Starting code generation for {}'.format(ircode), extra=d)
|
292
|
176 cg.generate(ircode, outs)
|
|
177 # TODO: fixup references, do this in another way?
|
|
178 outs.backpatch()
|
|
179 outs.backpatch() # Why two times?
|
288
|
180 return c3b.ok
|
|
181
|
249
|
182
|
|
183 def main(args):
|
315
|
184 # Configure some logging:
|
|
185 logging.getLogger().setLevel(logging.DEBUG)
|
|
186 ch = logging.StreamHandler()
|
|
187 ch.setFormatter(logging.Formatter(logformat))
|
|
188 ch.setLevel(args.log)
|
|
189 logging.getLogger().addHandler(ch)
|
|
190 if args.report:
|
|
191 fh = logging.StreamHandler(stream=args.report)
|
|
192 fh.setFormatter(RstFormatter())
|
|
193 logging.getLogger().addHandler(fh)
|
312
|
194
|
292
|
195 tg = targets[args.target]
|
249
|
196 diag = ppci.DiagnosticsManager()
|
|
197 outs = outstream.TextOutputStream()
|
|
198
|
315
|
199 res = zcc(args.source, args.imp, tg, outs, diag)
|
249
|
200 if not res:
|
293
|
201 diag.printErrors()
|
276
|
202 return 1
|
205
|
203
|
313
|
204 logging.info('Assembly created', extra={'zcc_outs':outs})
|
105
|
205
|
237
|
206 code_bytes = outs.sections['code'].to_bytes()
|
207
|
207 if args.output:
|
|
208 output_filename = args.output
|
287
|
209 with open(output_filename, 'wb') as f:
|
|
210 f.write(code_bytes)
|
104
|
211
|
246
|
212 if args.hexfile:
|
255
|
213 logging.info('Creating hexfile')
|
292
|
214 hf = HexFile()
|
246
|
215 hf.addRegion(0x08000000, code_bytes)
|
|
216 hf.save(args.hexfile)
|
315
|
217
|
|
218 if args.report:
|
|
219 logging.getLogger().removeHandler(fh)
|
|
220 logging.getLogger().removeHandler(ch)
|
276
|
221 return 0
|
246
|
222
|
288
|
223
|
207
|
224 if __name__ == '__main__':
|
213
|
225 arguments = parser.parse_args()
|
276
|
226 sys.exit(main(arguments))
|