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)
|
313
|
36 if hasattr(record, 'c3_ast'):
|
|
37 f = io.StringIO()
|
|
38 print('', file=f)
|
|
39 print('', file=f)
|
|
40 print('.. code::', file=f)
|
|
41 print('', file=f)
|
|
42 AstPrinter().printAst(record.c3_ast, f)
|
|
43 #Writer(' ').write(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()
|
|
87 return s
|
|
88
|
|
89
|
290
|
90 target_list = [target.armtarget]
|
292
|
91 targets = {t.name: t for t in target_list}
|
|
92 targetnames = list(targets.keys())
|
290
|
93
|
205
|
94 # Parse arguments:
|
204
|
95 parser = argparse.ArgumentParser(description='lcfos Compiler')
|
287
|
96 # Input:
|
213
|
97 parser.add_argument('source', type=argparse.FileType('r'), \
|
287
|
98 help='the source file to build', nargs="+")
|
290
|
99 parser.add_argument('-i', '--imp', type=argparse.FileType('r'), \
|
296
|
100 help='Possible import module', action='append', default=[])
|
287
|
101
|
253
|
102 parser.add_argument('--dumpir', action='store_true', help="Dump IR-code")
|
255
|
103 parser.add_argument('--optimize', action='store_true', help="Optimize")
|
290
|
104 parser.add_argument('--target', help="Backend selection",
|
292
|
105 choices=targetnames, required=True)
|
205
|
106 parser.add_argument('-o', '--output', help='Output file', metavar='filename')
|
290
|
107 parser.add_argument('--hexfile', help='Output hexfile',
|
|
108 type=argparse.FileType('w'))
|
253
|
109 parser.add_argument('--log', help='Log level (INFO,DEBUG)', type=logLevel)
|
104
|
110
|
288
|
111
|
292
|
112 def zcc(srcs, imps, tg, outs, diag, dumpir=False):
|
287
|
113 """
|
|
114 Compile sources into output stream.
|
|
115 Sources is an iterable of open files.
|
|
116 """
|
255
|
117 logging.info('Zcc started')
|
207
|
118 # Front end:
|
301
|
119 c3b = Builder(diag, tg)
|
|
120 cg = CodeGenerator(tg)
|
292
|
121
|
|
122 # TODO: remove this arm specifics:
|
|
123 outs.getSection('code').address = 0x08000000
|
|
124 outs.getSection('data').address = 0x20000000
|
|
125
|
|
126 # Emit some custom start code:
|
|
127 tg.startCode(outs)
|
287
|
128 for ircode in c3b.build(srcs, imps):
|
|
129 if not ircode:
|
|
130 return
|
313
|
131
|
|
132 d = {'ircode':ircode}
|
|
133 logging.info('Verifying code {}'.format(ircode), extra=d)
|
290
|
134 # Optimization passes, TODO
|
312
|
135 Verifier().verify(ircode)
|
289
|
136
|
287
|
137 # Code generation:
|
312
|
138 d = {'ircode':ircode}
|
|
139 logging.info('Starting code generation for {}'.format(ircode), extra=d)
|
292
|
140 cg.generate(ircode, outs)
|
|
141 # TODO: fixup references, do this in another way?
|
|
142 outs.backpatch()
|
|
143 outs.backpatch() # Why two times?
|
288
|
144 return c3b.ok
|
|
145
|
249
|
146
|
|
147 def main(args):
|
313
|
148 #logging.getLogger().setLevel(logging.DEBUG)
|
312
|
149 #logging.getLogger().addHandler(RstLogHandler())
|
313
|
150 #fh = logging.FileHandler('log.rst', mode='w')
|
|
151 #fh.setFormatter(RstFormatter())
|
|
152 #logging.getLogger().addHandler(fh)
|
312
|
153
|
292
|
154 tg = targets[args.target]
|
249
|
155 diag = ppci.DiagnosticsManager()
|
|
156 outs = outstream.TextOutputStream()
|
|
157
|
296
|
158 res = zcc(args.source, args.imp, tg, outs, diag, dumpir=args.dumpir)
|
249
|
159 if not res:
|
293
|
160 diag.printErrors()
|
276
|
161 return 1
|
205
|
162
|
313
|
163 logging.info('Assembly created', extra={'zcc_outs':outs})
|
105
|
164
|
237
|
165 code_bytes = outs.sections['code'].to_bytes()
|
207
|
166 if args.output:
|
|
167 output_filename = args.output
|
287
|
168 with open(output_filename, 'wb') as f:
|
|
169 f.write(code_bytes)
|
104
|
170
|
246
|
171 if args.hexfile:
|
255
|
172 logging.info('Creating hexfile')
|
292
|
173 hf = HexFile()
|
246
|
174 hf.addRegion(0x08000000, code_bytes)
|
|
175 hf.save(args.hexfile)
|
276
|
176 return 0
|
246
|
177
|
288
|
178
|
207
|
179 if __name__ == '__main__':
|
213
|
180 arguments = parser.parse_args()
|
276
|
181 sys.exit(main(arguments))
|