예제 #1
0
파일: __init__.py 프로젝트: inaimathi/pykit
def install(env,
            opt=3,
            llvm_engine=None,
            llvm_module=None,
            llvm_target_machine=None,
            temper=make_temper()):
    """Install llvm code generator in environment"""
    llvm_target_machine = llvm_target_machine or target_machine(opt)
    llvm_module = llvm_module or module(temper("temp_module"))
    llvm_engine = llvm_engine or execution_engine(llvm_module,
                                                  llvm_target_machine)

    # -------------------------------------------------
    # Codegen passes

    env["pipeline.codegen"].extend([
        "passes.llvm.postpasses",
        "passes.llvm.ctypes",
    ])

    env["passes.codegen"] = codegen
    env["passes.llvm.postpasses"] = llvm_postpasses
    env["passes.llvm.ctypes"] = get_ctypes

    env["codegen.impl"] = llvm_codegen

    # -------------------------------------------------
    # Codegen state

    env["codegen.llvm.opt"] = opt
    env["codegen.llvm.engine"] = llvm_engine
    env["codegen.llvm.module"] = llvm_module
    env["codegen.llvm.machine"] = llvm_target_machine
예제 #2
0
파일: __init__.py 프로젝트: B-Rich/pykit
def install(env, opt=3, llvm_engine=None, llvm_module=None,
            llvm_target_machine=None, temper=make_temper()):
    """Install llvm code generator in environment"""
    llvm_target_machine = llvm_target_machine or target_machine(opt)
    llvm_module = llvm_module or module(temper("temp_module"))
    llvm_engine = llvm_engine or execution_engine(llvm_module,
                                                  llvm_target_machine)

    # -------------------------------------------------
    # Codegen passes

    env["pipeline.codegen"].extend([
        "passes.llvm.postpasses",
        "passes.llvm.ctypes",
    ])

    env["passes.codegen"] = codegen
    env["passes.llvm.postpasses"] = llvm_postpasses
    env["passes.llvm.ctypes"] = get_ctypes

    env["codegen.impl"] = llvm_codegen

    # -------------------------------------------------
    # Codegen state

    env["codegen.llvm.opt"] = opt
    env["codegen.llvm.engine"] = llvm_engine
    env["codegen.llvm.module"] = llvm_module
    env["codegen.llvm.machine"] = llvm_target_machine
예제 #3
0
파일: copying.py 프로젝트: inaimathi/pykit
def copy_function(func, temper=None, module=None):
    """Copy a Function. `temper` may be given to"""
    temper = temper or make_temper()
    f = Function(func.name, list(func.argnames), func.type, temper=temper)
    valuemap = {}
    lookup = partial(_lookup, module or func.module, f, valuemap)

    ### Construct new Blocks
    for block in func.blocks:
        new_block = Block(temper(block.name), f)
        valuemap[block] = new_block
        f.add_block(new_block)

    ### Construct new Operations
    for block in func.blocks:
        new_block = valuemap[block]
        for op in block.ops:
            new_op = Op(op.opcode, op.type, nestedmap(lookup, op.args),
                        result=temper(op.result), parent=new_block)
            # assert new_op.result != op.result

            valuemap[op] = new_op
            new_block.append(new_op)

    return f
예제 #4
0
    def __init__(self, globals=None, functions=None, temper=None):
        self.globals = globals or {}
        self.functions = functions or {}
        self.temp = temper or make_temper()

        for value in chain(self.globals.values(), self.functions.values()):
            assert value.parent is None, (value, value.parent)
            value.parent = self
예제 #5
0
파일: value.py 프로젝트: flypy/pykit
    def __init__(self, globals=None, functions=None, temper=None):
        self.globals = globals or {}
        self.functions = functions or {}
        self.temp = temper or make_temper()

        for value in chain(self.globals.values(), self.functions.values()):
            assert value.parent is None, (value, value.parent)
            value.parent = self
예제 #6
0
def install(env, opt=3, temper=make_temper()):
    """Install C code generator in environment"""

    # -------------------------------------------------
    # Codegen passes

    env["pipeline.codegen"].extend([
        "passes.llvm.postpasses",
        "passes.llvm.ctypes",
    ])

    env["passes.codegen"] = codegen
    env["codegen.impl"] = c_codegen
예제 #7
0
def install(env, opt=3, llvm_engine=None, llvm_module=None,
            llvm_target_machine=None, temper=make_temper()):
    """Install llvm code generator in environment"""
    llvm_target_machine = llvm_target_machine or target_machine(opt)
    llvm_module = llvm_module or module(temper("temp_module"))
    llvm_engine = llvm_engine or execution_engine(llvm_module,
                                                  llvm_target_machine)
    env["pipeline.codegen"].append("passes.llvm.postpasses")
    env["passes.codegen"] = run
    env["passes.llvm.postpasses"] = llvm_postpasses
    env["codegen.llvm.opt"] = opt
    env["codegen.llvm.engine"] = llvm_engine
    env["codegen.llvm.module"] = llvm_module
    env["codegen.llvm.machine"] = llvm_target_machine
예제 #8
0
파일: cppgen.py 프로젝트: pombreda/flypy
def generate(cls, emit=print):
    if not hasattr(cls, 'layout'):
        raise TypeError(
            "Class has to attribute 'layout', is this a flypy type?")

    ctor = cls.__init__.py_func
    argspec = inspect.getargspec(ctor)

    if argspec.varargs or argspec.keywords or argspec.defaults:
        raise TypeError(
            "Varargs, keyword arguments or default values not supported")

    temp = make_temper()
    for keyword in reserved:
        temp(keyword)

    classname = cls.__name__
    attrs = []
    params = []
    typevars = [tvar.symbol for tvar in cls.type.parameters]
    templates = ["typename %s" % (tvar, ) for tvar in typevars]
    argnames = [temp(argname) for argname in argspec.args[1:]]
    initializers = []

    for attr, type in cls.type.resolved_layout.items():
        params.append("%s %s" % (format_type(type), attr))
        attrs.append("%s %s;" % (format_type(type), attr))
    for arg in argnames:
        initializers.append("this._data.%s = %s;" % (arg, arg))

    emit(
        textwrap.dedent("""
    template<%(typevars)s>
    class %(classname)s {
        struct {
    %(attrs)s
        } _data;

      public:
        %(classname)s(%(params)s) {
    %(initializers)s
        }
    };
    """) % {
            'typevars': ", ".join(templates),
            'classname': classname,
            'attrs': "\n".join("        " + a for a in attrs),
            'params': ", ".join(params),
            'initializers': "\n".join("        " + i for i in initializers),
        })
예제 #9
0
파일: cppgen.py 프로젝트: filmackay/flypy
def generate(cls, emit=print):
    if not hasattr(cls, 'layout'):
        raise TypeError("Class has to attribute 'layout', is this a flypy type?")

    ctor = cls.__init__.py_func
    argspec = inspect.getargspec(ctor)

    if argspec.varargs or argspec.keywords or argspec.defaults:
        raise TypeError(
            "Varargs, keyword arguments or default values not supported")

    temp = make_temper()
    for keyword in reserved:
        temp(keyword)

    classname = cls.__name__
    attrs = []
    params = []
    typevars = [tvar.symbol for tvar in cls.type.parameters]
    templates = ["typename %s" % (tvar,) for tvar in typevars]
    argnames = [temp(argname) for argname in argspec.args[1:]]
    initializers = []

    for attr, type in cls.type.resolved_layout.items():
        params.append("%s %s" % (format_type(type), attr))
        attrs.append("%s %s;" % (format_type(type), attr))
    for arg in argnames:
        initializers.append("this._data.%s = %s;" % (arg, arg))

    emit(textwrap.dedent("""
    template<%(typevars)s>
    class %(classname)s {
        struct {
    %(attrs)s
        } _data;

      public:
        %(classname)s(%(params)s) {
    %(initializers)s
        }
    };
    """) % {
        'typevars':     ", ".join(templates),
        'classname':    classname,
        'attrs':        "\n".join("        " + a for a in attrs),
        'params':       ", ".join(params),
        'initializers': "\n".join("        " + i for i in initializers),
    })
예제 #10
0
파일: value.py 프로젝트: flypy/pykit
    def __init__(self, name, argnames, type, temper=None):
        self.module = None
        self.name = name
        self.type = type
        self.temp = temper or make_temper()

        self.blocks = LinkedList()
        self.blockmap = dict((block.name, block) for block in self.blocks)
        self.argnames = argnames
        self.argdict = {}

        self.uses = defaultdict(set)

        # reserve names
        for argname in argnames:
            self.temp(argname)
예제 #11
0
    def __init__(self, name, argnames, type, temper=None):
        self.module = None
        self.name = name
        self.type = type
        self.temp = temper or make_temper()

        self.blocks = LinkedList()
        self.blockmap = dict((block.name, block) for block in self.blocks)
        self.argnames = argnames
        self.argdict = {}

        self.uses = defaultdict(set)

        # reserve names
        for argname in argnames:
            self.temp(argname)
예제 #12
0
def copy_function(func, temper=None, module=None):
    """Copy a Function. `temper` may be given to"""
    temper = temper or make_temper()
    f = Function(func.name, list(func.argnames), func.type, temper=temper)
    valuemap = {}
    lookup = partial(_lookup, module or func.module, f, valuemap)

    ### Construct new Blocks
    for block in func.blocks:
        new_block = f.new_block(block.name)
        valuemap[block] = new_block

    ### Construct new Operations
    for block in func.blocks:
        new_block = valuemap[block]
        for op in block.ops:
            if op.opcode == 'phi':
                # Phi nodes may be circular, or may simply precede some of
                # their arguments
                args = []
            else:
                args = nestedmap(lookup, op.args)

            new_op = Op(op.opcode,
                        op.type,
                        args,
                        result=temper(op.result),
                        parent=new_block)

            new_op.add_metadata(op.metadata)
            # assert new_op.result != op.result

            valuemap[op] = new_op
            new_block.append(new_op)

    for old_op in func.ops:
        if old_op.opcode == 'phi':
            new_op = valuemap[old_op]
            new_op.set_args(nestedmap(lookup, old_op.args))

    return f, valuemap
예제 #13
0
파일: copying.py 프로젝트: aterrel/pykit
def copy_function(func, temper=None, module=None):
    """Copy a Function. `temper` may be given to"""
    temper = temper or make_temper()
    f = Function(func.name, list(func.argnames), func.type, temper=temper)
    valuemap = {}
    lookup = partial(_lookup, module or func.module, f, valuemap)

    ### Construct new Blocks
    for block in func.blocks:
        new_block = Block(temper(block.name), f)
        valuemap[block] = new_block
        f.add_block(new_block)

    ### Construct new Operations
    for block in func.blocks:
        new_block = valuemap[block]
        for op in block.ops:
            if op.opcode == 'phi':
                # Phi nodes may be circular, or may simply precede some of
                # their arguments
                args = []
            else:
                args = nestedmap(lookup, op.args)

            new_op = Op(op.opcode, op.type, args,
                        result=temper(op.result), parent=new_block)

            new_op.add_metadata(op.metadata)
            # assert new_op.result != op.result

            valuemap[op] = new_op
            new_block.append(new_op)

    for old_op in func.ops:
        if old_op.opcode == 'phi':
            new_op = valuemap[old_op]
            new_op.set_args(nestedmap(lookup, old_op.args))

    return f
예제 #14
0
파일: copying.py 프로젝트: filmackay/flypy
# -*- coding: utf-8 -*-

"""
Copy functions to a function with a new name.
"""

from __future__ import print_function, division, absolute_import

from pykit.ir import copy_function, vmap, Function
from pykit.analysis import callgraph
from pykit.utils import make_temper

temper = make_temper()

def copy_graph(func, env, funcs=None, graph=None):
    """
    Copy a function graph.
    """
    if funcs is None:
        funcs = {}

    graph = graph or callgraph.callgraph(func)
    envs = env['flypy.state.envs']

    copy_functions(graph, funcs, envs)
    update_callgraph(graph, funcs)

    return funcs

def copy_functions(graph, funcs, envs):
    """
예제 #15
0
파일: c_codegen.py 프로젝트: flypy/pykit
                "Cannot create constant pointer to value '%s'" % (value,))
    elif type(ty) == Integral:
        return str(value)
    elif type(ty) == Real:
        return str(value)
    elif type(ty) == Boolean:
        return str(int(value))
    elif type(ty) == Struct:
        raise NotImplementedError
    else:
        raise NotImplementedError("Constants for", type(ty))

#===------------------------------------------------------------------===
# Entry points
#===------------------------------------------------------------------===

mangle = make_temper()

def initialize(func, env):
    return func

def translate(func, env, _):
    emit = lambda s, *args: sys.stdout.write(format(s, *args) + "\n")

    # -- Create visitor -- #
    translator = Translator(func, env, emit)
    visitor = opgrouper(translator)

    # -- Codegen -- #
    argloader = CArgLoader()
    valuemap = vvisit(visitor, func, argloader)
예제 #16
0
파일: copying.py 프로젝트: pombreda/flypy
# -*- coding: utf-8 -*-

"""
Copy functions to a function with a new name.
"""

from __future__ import print_function, division, absolute_import

from pykit.ir import copy_function, vmap, Function
from pykit.analysis import callgraph
from pykit.utils import make_temper

temper = make_temper()

def copy_graph(func, env, funcs=None, graph=None):
    """
    Copy a function graph.
    """
    if funcs is None:
        funcs = {}

    graph = graph or callgraph.callgraph(func)
    envs = env['flypy.state.envs']

    copy_functions(graph, funcs, envs)
    update_callgraph(graph, funcs)

    return funcs

def copy_functions(graph, funcs, envs):
    """
예제 #17
0
    elif type(ty) == Boolean:
        return lc.Constant.int(lty, value)
    elif type(ty) == Struct:
        return lc.Constant.struct([make_constant(unwrap(c), c.type)
                                       for c in value.values])
    elif ty.is_vector:
        const = make_constant(value, ty.base)
        return lc.Constant.vector([const] * ty.count)
    else:
        raise NotImplementedError("Constants for", type(ty))

#===------------------------------------------------------------------===
# Entry points
#===------------------------------------------------------------------===

mangle = make_temper()

def initialize(func, env):
    verify_lowlevel(func)
    llvm_module = env["codegen.llvm.module"]
    return llvm_module.add_function(llvm_type(func.type), mangle(func.name))

def translate(func, env, lfunc):
    engine, llvm_module = env["codegen.llvm.engine"], env["codegen.llvm.module"]
    blockmap = allocate_blocks(lfunc, func)

    ### Create visitor ###
    translator = Translator(func, env, lfunc, llvm_type, llvm_module)
    visitor = opgrouper(translator)

    ### Codegen ###