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