104
|
1 #!/usr/bin/python
|
|
2
|
213
|
3 import sys, argparse
|
205
|
4 import c3, ppci, codegen
|
|
5 import codegenarm
|
253
|
6 from optimize import optimize
|
205
|
7 import outstream
|
246
|
8 import hexfile
|
253
|
9 import logging
|
|
10
|
|
11 def logLevel(s):
|
|
12 numeric_level = getattr(logging, s.upper(), None)
|
|
13 if not isinstance(numeric_level, int):
|
|
14 raise ValueError('Invalid log level: {}'.format(s))
|
|
15 return numeric_level
|
105
|
16
|
205
|
17 # Parse arguments:
|
204
|
18 parser = argparse.ArgumentParser(description='lcfos Compiler')
|
213
|
19 parser.add_argument('source', type=argparse.FileType('r'), \
|
|
20 help='the source file to build')
|
253
|
21 parser.add_argument('--dumpir', action='store_true', help="Dump IR-code")
|
255
|
22 parser.add_argument('--dumpasm', action='store_true', help="Dump ASM-code")
|
|
23 parser.add_argument('--optimize', action='store_true', help="Optimize")
|
205
|
24 parser.add_argument('-o', '--output', help='Output file', metavar='filename')
|
246
|
25 parser.add_argument('--hexfile', help='Output hexfile', type=argparse.FileType('w'))
|
253
|
26 parser.add_argument('--log', help='Log level (INFO,DEBUG)', type=logLevel)
|
104
|
27
|
255
|
28 def zcc(src, outs, diag, dumpir=False, do_optimize=False):
|
|
29 logging.info('Zcc started')
|
207
|
30 # Front end:
|
|
31 c3b = c3.Builder(diag)
|
|
32 ircode = c3b.build(src)
|
|
33 if not ircode:
|
249
|
34 return
|
104
|
35
|
219
|
36 # Optimization passes:
|
255
|
37 if do_optimize:
|
|
38 optimize(ircode)
|
219
|
39
|
249
|
40 if dumpir:
|
207
|
41 ircode.dump()
|
249
|
42
|
207
|
43 # Code generation:
|
|
44 cg = codegenarm.ArmCodeGenerator(outs)
|
|
45 obj = cg.generate(ircode)
|
249
|
46 return True
|
|
47
|
|
48 def main(args):
|
255
|
49 logging.basicConfig(format='%(asctime)s %(levelname)s %(name)s %(message)s', level=args.log)
|
249
|
50 src = args.source.read()
|
|
51 args.source.close()
|
|
52 diag = ppci.DiagnosticsManager()
|
|
53 outs = outstream.TextOutputStream()
|
|
54
|
|
55 # Invoke compiler:
|
255
|
56 res = zcc(src, outs, diag, dumpir=args.dumpir, do_optimize=args.optimize)
|
249
|
57 if not res:
|
|
58 diag.printErrors(src)
|
|
59 sys.exit(1)
|
205
|
60
|
255
|
61 if args.dumpasm:
|
|
62 outs.dump()
|
105
|
63
|
237
|
64 code_bytes = outs.sections['code'].to_bytes()
|
238
|
65 #print('bytes:', code_bytes)
|
207
|
66 if args.output:
|
|
67 output_filename = args.output
|
|
68 else:
|
237
|
69 output_filename = 'b.output'
|
249
|
70
|
237
|
71 with open(output_filename, 'wb') as f:
|
|
72 f.write(code_bytes)
|
104
|
73
|
246
|
74 if args.hexfile:
|
255
|
75 logging.info('Creating hexfile')
|
246
|
76 hf = hexfile.HexFile()
|
|
77 hf.addRegion(0x08000000, code_bytes)
|
|
78 hf.save(args.hexfile)
|
|
79
|
207
|
80 if __name__ == '__main__':
|
213
|
81 arguments = parser.parse_args()
|
|
82 main(arguments)
|
205
|
83
|