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