2015-08-09 20:47:29 +08:00
|
|
|
import os, sys, tempfile, subprocess
|
2015-11-17 05:23:34 +08:00
|
|
|
from artiq.compiler import types
|
2015-07-30 01:35:16 +08:00
|
|
|
from llvmlite_artiq import ir as ll, binding as llvm
|
|
|
|
|
|
|
|
llvm.initialize()
|
|
|
|
llvm.initialize_all_targets()
|
|
|
|
llvm.initialize_all_asmprinters()
|
|
|
|
|
2015-08-10 20:12:22 +08:00
|
|
|
class RunTool:
|
|
|
|
def __init__(self, pattern, **tempdata):
|
|
|
|
self.files = []
|
|
|
|
self.pattern = pattern
|
|
|
|
self.tempdata = tempdata
|
|
|
|
|
|
|
|
def maketemp(self, data):
|
|
|
|
f = tempfile.NamedTemporaryFile()
|
|
|
|
f.write(data)
|
|
|
|
f.flush()
|
|
|
|
self.files.append(f)
|
|
|
|
return f
|
|
|
|
|
|
|
|
def __enter__(self):
|
|
|
|
tempfiles = {}
|
|
|
|
tempnames = {}
|
|
|
|
for key in self.tempdata:
|
|
|
|
tempfiles[key] = self.maketemp(self.tempdata[key])
|
|
|
|
tempnames[key] = tempfiles[key].name
|
|
|
|
|
|
|
|
cmdline = []
|
|
|
|
for argument in self.pattern:
|
|
|
|
cmdline.append(argument.format(**tempnames))
|
|
|
|
|
|
|
|
process = subprocess.Popen(cmdline, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
|
|
|
stdout, stderr = process.communicate()
|
|
|
|
if process.returncode != 0:
|
|
|
|
raise Exception("{} invocation failed: {}".
|
|
|
|
format(cmdline[0], stderr.decode('utf-8')))
|
|
|
|
|
|
|
|
tempfiles["__stdout__"] = stdout.decode('utf-8')
|
|
|
|
return tempfiles
|
|
|
|
|
|
|
|
def __exit__(self, exc_typ, exc_value, exc_trace):
|
|
|
|
for f in self.files:
|
|
|
|
f.close()
|
|
|
|
|
2016-02-25 01:13:17 +08:00
|
|
|
def _dump(target, kind, suffix, content):
|
|
|
|
if target is not None:
|
|
|
|
print("====== {} DUMP ======".format(kind.upper()), file=sys.stderr)
|
2016-03-29 21:02:14 +08:00
|
|
|
content_value = content()
|
|
|
|
if isinstance(content_value, str):
|
|
|
|
content_value = bytes(content_value, 'utf-8')
|
2016-02-25 01:13:17 +08:00
|
|
|
if target == "":
|
2016-02-25 05:43:46 +08:00
|
|
|
file = tempfile.NamedTemporaryFile(suffix=suffix, delete=False)
|
2016-02-25 01:13:17 +08:00
|
|
|
else:
|
|
|
|
file = open(target + suffix, "wb")
|
2016-03-29 21:02:14 +08:00
|
|
|
file.write(content_value)
|
2016-02-25 01:13:17 +08:00
|
|
|
file.close()
|
|
|
|
print("{} dumped as {}".format(kind, file.name), file=sys.stderr)
|
|
|
|
|
2015-07-30 01:35:16 +08:00
|
|
|
class Target:
|
|
|
|
"""
|
|
|
|
A description of the target environment where the binaries
|
2015-07-30 15:33:54 +08:00
|
|
|
generated by the ARTIQ compiler will be deployed.
|
2015-07-30 01:35:16 +08:00
|
|
|
|
|
|
|
:var triple: (string)
|
|
|
|
LLVM target triple, e.g. ``"or1k"``
|
2015-08-09 19:39:21 +08:00
|
|
|
:var data_layout: (string)
|
|
|
|
LLVM target data layout, e.g. ``"E-m:e-p:32:32-i64:32-f64:32-v64:32-v128:32-a:0:32-n32"``
|
2015-07-30 01:35:16 +08:00
|
|
|
:var features: (list of string)
|
|
|
|
LLVM target CPU features, e.g. ``["mul", "div", "ffl1"]``
|
|
|
|
:var print_function: (string)
|
|
|
|
Name of a formatted print functions (with the signature of ``printf``)
|
|
|
|
provided by the target, e.g. ``"printf"``.
|
|
|
|
"""
|
|
|
|
triple = "unknown"
|
2015-08-09 19:39:21 +08:00
|
|
|
data_layout = ""
|
2015-07-30 01:35:16 +08:00
|
|
|
features = []
|
2016-03-18 12:42:06 +08:00
|
|
|
print_function = "printf"
|
2015-07-30 01:35:16 +08:00
|
|
|
|
2015-08-10 20:12:22 +08:00
|
|
|
|
2015-07-30 01:35:16 +08:00
|
|
|
def __init__(self):
|
|
|
|
self.llcontext = ll.Context()
|
|
|
|
|
2016-03-26 21:20:23 +08:00
|
|
|
def target_machine(self):
|
|
|
|
lltarget = llvm.Target.from_triple(self.triple)
|
2016-04-01 17:34:51 +08:00
|
|
|
llmachine = lltarget.create_target_machine(
|
2016-03-26 21:20:23 +08:00
|
|
|
features=",".join(["+{}".format(f) for f in self.features]),
|
|
|
|
reloc="pic", codemodel="default")
|
2016-11-08 20:58:20 +08:00
|
|
|
llmachine.set_verbose(True)
|
2016-04-01 17:34:51 +08:00
|
|
|
return llmachine
|
2016-03-26 21:20:23 +08:00
|
|
|
|
|
|
|
def optimize(self, llmodule):
|
2016-11-08 20:58:20 +08:00
|
|
|
llmachine = self.target_machine()
|
2016-03-26 21:20:23 +08:00
|
|
|
llpassmgr = llvm.create_module_pass_manager()
|
2016-11-08 20:58:20 +08:00
|
|
|
llmachine.target_data.add_pass(llpassmgr)
|
|
|
|
llmachine.add_analysis_passes(llpassmgr)
|
2016-03-27 05:20:28 +08:00
|
|
|
|
2016-03-28 10:52:15 +08:00
|
|
|
# Register our alias analysis passes.
|
|
|
|
llpassmgr.add_basic_alias_analysis_pass()
|
|
|
|
llpassmgr.add_type_based_alias_analysis_pass()
|
|
|
|
|
2016-03-27 05:20:28 +08:00
|
|
|
# Start by cleaning up after our codegen and exposing as much
|
|
|
|
# information to LLVM as possible.
|
2016-03-26 21:20:23 +08:00
|
|
|
llpassmgr.add_constant_merge_pass()
|
|
|
|
llpassmgr.add_cfg_simplification_pass()
|
|
|
|
llpassmgr.add_instruction_combining_pass()
|
|
|
|
llpassmgr.add_sroa_pass()
|
|
|
|
llpassmgr.add_dead_code_elimination_pass()
|
2016-03-27 04:01:51 +08:00
|
|
|
llpassmgr.add_function_attrs_pass()
|
2016-03-27 05:20:28 +08:00
|
|
|
llpassmgr.add_global_optimizer_pass()
|
|
|
|
|
|
|
|
# Now, actually optimize the code.
|
2016-03-27 09:08:13 +08:00
|
|
|
llpassmgr.add_function_inlining_pass(275)
|
2016-03-27 10:00:05 +08:00
|
|
|
llpassmgr.add_ipsccp_pass()
|
2016-03-27 05:20:28 +08:00
|
|
|
llpassmgr.add_instruction_combining_pass()
|
2016-03-27 10:00:05 +08:00
|
|
|
llpassmgr.add_gvn_pass()
|
2016-03-27 09:02:15 +08:00
|
|
|
llpassmgr.add_cfg_simplification_pass()
|
2016-03-28 08:44:32 +08:00
|
|
|
llpassmgr.add_licm_pass()
|
2016-03-27 10:00:05 +08:00
|
|
|
|
|
|
|
# Clean up after optimizing.
|
2016-03-27 09:02:15 +08:00
|
|
|
llpassmgr.add_dead_arg_elimination_pass()
|
2016-03-27 05:20:28 +08:00
|
|
|
llpassmgr.add_global_dce_pass()
|
|
|
|
|
2016-03-26 21:20:23 +08:00
|
|
|
llpassmgr.run(llmodule)
|
|
|
|
|
2015-07-30 01:35:16 +08:00
|
|
|
def compile(self, module):
|
|
|
|
"""Compile the module to a relocatable object for this target."""
|
2015-08-09 20:47:29 +08:00
|
|
|
|
2015-08-28 15:22:35 +08:00
|
|
|
if os.getenv("ARTIQ_DUMP_SIG"):
|
|
|
|
print("====== MODULE_SIGNATURE DUMP ======", file=sys.stderr)
|
|
|
|
print(module, file=sys.stderr)
|
|
|
|
|
2016-02-25 01:13:17 +08:00
|
|
|
type_printer = types.TypePrinter()
|
|
|
|
_dump(os.getenv("ARTIQ_DUMP_IR"), "ARTIQ IR", ".txt",
|
|
|
|
lambda: "\n".join(fn.as_entity(type_printer) for fn in module.artiq_ir))
|
2015-08-09 20:47:29 +08:00
|
|
|
|
2015-07-30 01:35:16 +08:00
|
|
|
llmod = module.build_llvm_ir(self)
|
2016-01-02 22:51:04 +08:00
|
|
|
|
|
|
|
try:
|
|
|
|
llparsedmod = llvm.parse_assembly(str(llmod))
|
|
|
|
llparsedmod.verify()
|
|
|
|
except RuntimeError:
|
2016-02-25 01:13:17 +08:00
|
|
|
_dump("", "LLVM IR (broken)", ".ll", lambda: str(llmod))
|
2016-01-02 22:51:04 +08:00
|
|
|
raise
|
2015-07-30 01:35:16 +08:00
|
|
|
|
2016-02-25 01:13:17 +08:00
|
|
|
_dump(os.getenv("ARTIQ_DUMP_UNOPT_LLVM"), "LLVM IR (generated)", "_unopt.ll",
|
|
|
|
lambda: str(llparsedmod))
|
2015-08-09 20:47:29 +08:00
|
|
|
|
2016-03-26 21:20:23 +08:00
|
|
|
self.optimize(llparsedmod)
|
2015-07-30 01:35:16 +08:00
|
|
|
|
2016-02-25 01:13:17 +08:00
|
|
|
_dump(os.getenv("ARTIQ_DUMP_LLVM"), "LLVM IR (optimized)", ".ll",
|
|
|
|
lambda: str(llparsedmod))
|
2015-08-09 20:47:29 +08:00
|
|
|
|
2016-02-25 06:34:34 +08:00
|
|
|
return llparsedmod
|
|
|
|
|
|
|
|
def assemble(self, llmodule):
|
2016-03-26 21:20:23 +08:00
|
|
|
llmachine = self.target_machine()
|
2015-08-09 20:47:29 +08:00
|
|
|
|
2016-02-25 01:13:17 +08:00
|
|
|
_dump(os.getenv("ARTIQ_DUMP_ASM"), "Assembly", ".s",
|
2016-02-25 06:34:34 +08:00
|
|
|
lambda: llmachine.emit_assembly(llmodule))
|
2015-08-09 20:47:29 +08:00
|
|
|
|
2016-02-25 06:34:34 +08:00
|
|
|
return llmachine.emit_object(llmodule)
|
2015-07-30 01:35:16 +08:00
|
|
|
|
2016-10-17 00:24:25 +08:00
|
|
|
def link(self, objects):
|
2015-08-10 20:12:22 +08:00
|
|
|
"""Link the relocatable objects into a shared library for this target."""
|
2016-10-17 00:24:25 +08:00
|
|
|
with RunTool([self.triple + "-ld", "-shared", "--eh-frame-hdr"] +
|
2015-08-10 20:12:22 +08:00
|
|
|
["{{obj{}}}".format(index) for index in range(len(objects))] +
|
|
|
|
["-o", "{output}"],
|
|
|
|
output=b"",
|
|
|
|
**{"obj{}".format(index): obj for index, obj in enumerate(objects)}) \
|
|
|
|
as results:
|
|
|
|
library = results["output"].read()
|
|
|
|
|
2016-08-17 18:20:04 +08:00
|
|
|
_dump(os.getenv("ARTIQ_DUMP_ELF"), "Shared library", ".elf",
|
2016-02-25 01:13:17 +08:00
|
|
|
lambda: library)
|
2015-08-10 20:12:22 +08:00
|
|
|
|
|
|
|
return library
|
|
|
|
|
2015-07-30 01:35:16 +08:00
|
|
|
def compile_and_link(self, modules):
|
2016-10-17 00:24:25 +08:00
|
|
|
return self.link([self.assemble(self.compile(module)) for module in modules])
|
2015-07-30 01:35:16 +08:00
|
|
|
|
2015-08-10 20:12:22 +08:00
|
|
|
def strip(self, library):
|
|
|
|
with RunTool([self.triple + "-strip", "--strip-debug", "{library}", "-o", "{output}"],
|
|
|
|
library=library, output=b"") \
|
|
|
|
as results:
|
|
|
|
return results["output"].read()
|
|
|
|
|
|
|
|
def symbolize(self, library, addresses):
|
2016-01-11 02:04:10 +08:00
|
|
|
if addresses == []:
|
|
|
|
return []
|
|
|
|
|
2016-02-25 01:53:13 +08:00
|
|
|
# We got a list of return addresses, i.e. addresses of instructions
|
|
|
|
# just after the call. Offset them back to get an address somewhere
|
|
|
|
# inside the call instruction (or its delay slot), since that's what
|
|
|
|
# the backtrace entry should point at.
|
|
|
|
offset_addresses = [hex(addr - 1) for addr in addresses]
|
2016-02-25 01:44:07 +08:00
|
|
|
with RunTool([self.triple + "-addr2line", "--addresses", "--functions", "--inlines",
|
2016-05-14 20:52:28 +08:00
|
|
|
"--demangle", "--exe={library}"] + offset_addresses,
|
2015-08-10 20:12:22 +08:00
|
|
|
library=library) \
|
|
|
|
as results:
|
2016-02-25 01:44:07 +08:00
|
|
|
lines = iter(results["__stdout__"].rstrip().split("\n"))
|
2015-08-10 20:12:22 +08:00
|
|
|
backtrace = []
|
2016-02-25 01:44:07 +08:00
|
|
|
while True:
|
|
|
|
try:
|
|
|
|
address_or_function = next(lines)
|
|
|
|
except StopIteration:
|
|
|
|
break
|
|
|
|
if address_or_function[:2] == "0x":
|
2016-02-25 01:53:13 +08:00
|
|
|
address = int(address_or_function[2:], 16) + 1 # remove offset
|
2016-02-25 01:44:07 +08:00
|
|
|
function = next(lines)
|
|
|
|
else:
|
|
|
|
address = backtrace[-1][4] # inlined
|
|
|
|
function = address_or_function
|
|
|
|
location = next(lines)
|
|
|
|
|
2015-08-10 20:12:22 +08:00
|
|
|
filename, line = location.rsplit(":", 1)
|
2016-02-25 01:44:07 +08:00
|
|
|
if filename == "??" or filename == "<synthesized>":
|
2015-08-28 14:43:46 +08:00
|
|
|
continue
|
2015-08-10 20:12:22 +08:00
|
|
|
# can't get column out of addr2line D:
|
2016-02-25 01:44:07 +08:00
|
|
|
backtrace.append((filename, int(line), -1, function, address))
|
2015-08-10 20:12:22 +08:00
|
|
|
return backtrace
|
|
|
|
|
2016-05-14 20:52:28 +08:00
|
|
|
def demangle(self, names):
|
|
|
|
with RunTool([self.triple + "-c++filt"] + names) as results:
|
|
|
|
return results["__stdout__"].rstrip().split("\n")
|
|
|
|
|
2015-07-30 01:35:16 +08:00
|
|
|
class NativeTarget(Target):
|
|
|
|
def __init__(self):
|
|
|
|
super().__init__()
|
|
|
|
self.triple = llvm.get_default_triple()
|
|
|
|
|
|
|
|
class OR1KTarget(Target):
|
|
|
|
triple = "or1k-linux"
|
2016-03-31 14:40:25 +08:00
|
|
|
data_layout = "E-m:e-p:32:32-i8:8:8-i16:16:16-i64:32:32-" \
|
|
|
|
"f64:32:32-v64:32:32-v128:32:32-a0:0:32-n32"
|
2015-08-10 20:47:44 +08:00
|
|
|
features = ["mul", "div", "ffl1", "cmov", "addc"]
|
2016-03-18 12:42:06 +08:00
|
|
|
print_function = "core_log"
|