forked from davidar/lljvm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lljvm-cc
executable file
·235 lines (205 loc) · 8.44 KB
/
lljvm-cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
#!/usr/bin/python
# Copyright (c) 2009-2010 David Roberts <[email protected]>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
import os
import sys
import subprocess
__version__ = '0.3dev'
# LLJVM root directory
lljvm_dir = os.path.abspath(os.path.dirname(sys.argv.pop(0)))
# dummy file
# TODO: make system-independent
fnull = open('/dev/null', 'w')
def command_exists(name):
"""Returns true iff a command with the given name exists."""
# TODO: make system-independent
return subprocess.call(['which', name], stdout=fnull) == 0
# C Compiler
if command_exists('llvm-gcc'): cc = 'llvm-gcc'
elif command_exists('clang'): cc = 'clang'
else: cc = None
# default flags to pass to the compiler
default_cflags = (
'-D__LLJVM__',
'-I' + os.path.join(lljvm_dir, 'include', 'lljvm'),
'-I' + os.path.join(lljvm_dir, 'include', 'newlib'),
'-fno-builtin',
'-m32',
)
if cc == 'llvm-gcc':
default_cflags = default_cflags + ('-malign-double',)
# default java classes to link against
default_java_libs = (
'lljvm.runtime.System',
'lljvm.runtime.IO',
'lljvm.runtime.Posix',
'lljvm.runtime.Error',
'lljvm.runtime.Memory',
'lljvm.runtime.Jump',
)
# (partial) list of flags that take an argument
# TODO: complete list
takes_argument = ('-MF', '-MT', '-MQ', '-include')
# (partial) list of flags not recognised by llvm-ld
# TODO: need a better way of filtering out invalid flags
invalid_ld_flags = ('-pthread', '-shared', '-nostdlib', '-lgcc',
'-static-libgcc', '-link', '-MF', '-MT', '-MQ', '-include')
# template for the launcher script
script_template = \
'#!/bin/sh\n' \
'export CLASSPATH="`dirname "$0"`:%s:${CLASSPATH-.}"\n' \
'exec java %s "$0" ${1+"$@"}\n'
def die(message, status=1):
"""Print the given message to stderr and terminate with the given
status."""
sys.stderr.write(message)
sys.stderr.write('\n')
sys.exit(status)
def element_startswith(l, s):
"""Returns true iff any of the elements in the given list begin with the
given string."""
return reduce(lambda x, y: x or y.startswith(s), l, False)
def startswith_element(s, l):
"""Returns true iff the given string begins with any of the elements in the
given list."""
return reduce(lambda x, y: x or s.startswith(y), l, False)
def remove_filext(s):
"""Remove the file extension from the given string."""
dot = s.rfind('.')
if dot == -1: return s
return s[:dot]
def call_e(*popenargs, **kwargs):
"""Call the given command, exiting if it has a non-zero return code."""
p = subprocess.Popen(*popenargs, **kwargs)
if p.wait() != 0: sys.exit(p.returncode)
def parse_argv(separate_sources=True):
"""Parse sys.argv, returning the flags and the output file, and separating
the sources from the flags if required."""
flags = []
output = 'a.out'
if separate_sources: srcs = []
while sys.argv:
arg = sys.argv.pop(0)
if separate_sources and arg[0] != '-':
srcs.append(arg)
elif arg == '-o':
output = sys.argv.pop(0)
elif arg in takes_argument:
flags.append(arg)
flags.append(sys.argv.pop(0))
else:
flags.append(arg)
if separate_sources:
return flags, output, srcs
return flags, output
def filter_flags(flags, fn):
"""Filter the given list of flags according to the given function,
respecting takes_argument."""
newflags = []
oldflags = list(flags)
while oldflags:
flag = oldflags.pop(0)
arg = oldflags.pop(0) if flag in takes_argument else None
if fn(flag):
newflags.append(flag)
if arg: newflags.append(arg)
return newflags
def filter_cc_flags(flags):
"""Remove arguments from the given list that should be passed to the
backend instead of cc, and return the new list of arguments."""
return filter_flags(flags,
lambda x: not startswith_element(x, ('-classname','-g','-l')))
def filter_ld_flags(flags):
"""Remove arguments not recognised by llvm-ld from the given list, and
return the new list of arguments."""
return filter_flags(flags,
lambda x: x not in invalid_ld_flags
and not startswith_element(x,
('-classname','-f','-g','-D','-I','-L','-O','-W'))
and (not x.startswith('-l') or x in ('-link','-link-as-library')))
def filter_backend_flags(flags):
"""Return a list of only those flags accepted by lljvm-backend."""
return filter_flags(flags,
lambda x: startswith_element(x, ('-classname','-g')))
def bc2class(output, flags):
"""Generate {output}.class from {output}.bc and unlink {output}.bc"""
classpath = [os.path.join(lljvm_dir, 'lljvm-' + __version__ + '.jar')]
java_libs = list(default_java_libs)
if '-nostdlib' not in flags:
java_libs.append('lljvm.lib.c')
for flag in flags:
if flag.startswith('-L'):
classpath.append(os.path.abspath(flag[2:]))
elif flag == '-lm':
java_libs += ['java.lang.Math', 'lljvm.runtime.Math']
elif flag.startswith('-l') \
and flag not in ('-link','-link-as-library'):
java_libs.append('lib' + flag[2:])
output_j = open(output + '.j', 'w')
backend_process = subprocess.Popen(
[os.path.join(lljvm_dir, 'lljvm-backend'), output + '.bc']
+ filter_backend_flags(flags),
stdout=subprocess.PIPE)
env = {'CLASSPATH': ':'.join(classpath+[os.environ.get('CLASSPATH','.')])}
linker_returncode = subprocess.Popen(
['java', 'lljvm.tools.ld.Main'] + java_libs,
env=env, stdin=backend_process.stdout, stdout=output_j).wait()
output_j.close()
if linker_returncode != 0:
backend_process.kill()
sys.exit(linker_returncode)
if backend_process.wait() != 0:
sys.exit(backend_process.returncode)
os.unlink(output + '.bc')
outpath = os.path.dirname(output) or '.'
call_e(['java', 'jasmin.Main', '-d', outpath, output + '.j'], stdout=fnull)
if '-g3' not in flags:
os.unlink(output + '.j')
if '-link-as-library' not in flags:
classname = os.path.basename(output).replace('.', '_')
for flag in flags:
if flag.startswith('-classname='):
classname = flag[len('-classname='):]
script = open(output, 'w')
script.write(script_template % (':'.join(classpath), classname))
script.close()
os.chmod(output, 0755)
def link(flags, output):
"""Call llvm-ld with the given flags, and call bc2class on the output."""
if '-link-as-library' in flags: flags += ['-o', output + '.bc']
else: flags += ['-o', output]
call_e(['llvm-ld', '-disable-opt'] + filter_ld_flags(flags))
if '-link-as-library' not in flags:
os.unlink(output)
bc2class(output, flags)
def main():
if not cc: die("Error: either llvm-gcc or clang must be installed")
if '-link' in sys.argv or '-link-as-library' in sys.argv:
link(*parse_argv(False)); return
if '-c' in sys.argv or '-E' in sys.argv:
flags = filter_cc_flags(sys.argv)
call_e([cc, '-emit-llvm'] + list(default_cflags) + flags); return
flags, output, srcs = parse_argv()
objs = map(lambda src: remove_filext(os.path.basename(src)) + '.o', srcs)
call_e([cc, '-emit-llvm', '-c'] + list(default_cflags)
+ filter_cc_flags(flags) + srcs)
link(flags + objs, output)
map(os.unlink, objs)
if __name__ == '__main__': main()