Esempio n. 1
0
    def _generate_map_macros(self):
        g = cgen.Module([cgen.Comment('#### KERNEL_MAP_MACROS ####')])
        for i, dat in enumerate(self._dat_dict.items()):
            if type(dat[1][0]) is cuda_data.GlobalArray or \
                issubclass(type(dat[1][0]), cuda_base.Array):
                g.append(cgen.Define(dat[0] + '(x)', '(' + dat[0] + '[(x)])'))
            if issubclass(type(dat[1][0]), cuda_base.Matrix):
                g.append(cgen.Define(dat[0] + '(y)', dat[0] + '.i[(y)]'))

        self._components['KERNEL_MAP_MACROS'] = g
Esempio n. 2
0
def pluto_include():
    libraries = ['omp.h', 'math.h']
    statements = [cgen.Include(s) for s in libraries]
    statements += [
        cgen.Define("ceild(n,d)", "ceil(((double)(n))/((double)(d)))")
    ]
    statements += [
        cgen.Define("floord(n,d)", "floor(((double)(n))/((double)(d)))")
    ]
    statements += [cgen.Define("max(x,y)", "((x) > (y)? (x) : (y))")]
    statements += [cgen.Define("min(x,y)", "((x) < (y)? (x) : (y))")]
    return statements
Esempio n. 3
0
    def _generate_map_macros(self):

        g = cgen.Module([cgen.Comment('#### KERNEL_MAP_MACROS ####')])

        for i, dat in enumerate(self._dat_dict.items()):
            if issubclass(type(dat[1][0]), host._Array):
                g.append(cgen.Define(dat[0] + '(x)', '(' + dat[0] + '[(x)])'))
            if issubclass(type(dat[1][0]), host.Matrix):
                g.append(cgen.Define(dat[0] + '(x,y)', dat[0] + '_##x(y)'))
                g.append(cgen.Define(dat[0] + '_0(y)', dat[0] + '.i[(y)]'))
                g.append(cgen.Define(dat[0] + '_1(y)', dat[0] + '.j[(y)]'))

        self._components['KERNEL_MAP_MACROS'] = g
Esempio n. 4
0
    def visit_Operator(self, o, mode='all'):
        # Kernel signature and body
        body = flatten(self._visit(i) for i in o.children)
        decls = self._args_decl(o.parameters)
        signature = c.FunctionDeclaration(c.Value(o.retval, o.name), decls)
        retval = [c.Line(), c.Statement("return 0")]
        kernel = c.FunctionBody(signature, c.Block(body + retval))

        # Elemental functions
        esigns = []
        efuncs = [blankline]
        for i in o._func_table.values():
            if i.local:
                prefix = ' '.join(i.root.prefix + (i.root.retval, ))
                esigns.append(
                    c.FunctionDeclaration(c.Value(prefix, i.root.name),
                                          self._args_decl(i.root.parameters)))
                efuncs.extend([self._visit(i.root), blankline])

        # Definitions
        headers = [c.Define(*i) for i in o._headers] + [blankline]

        # Header files
        includes = self._operator_includes(o) + [blankline]

        # Type declarations
        typedecls = self._operator_typedecls(o, mode)
        if mode in ('all', 'public') and o._compiler.src_ext in ('cpp', 'cu'):
            typedecls.append(c.Extern('C', signature))
        typedecls = [i for j in typedecls for i in (j, blankline)]

        return c.Module(headers + includes + typedecls + esigns +
                        [blankline, kernel] + efuncs)
Esempio n. 5
0
 def includes(self):
     statements = includes.copyright()
     statements += [cgen.Define('M_PI', '3.14159265358979323846')]
     statements += includes.common_include()
     if self.io:
         statements += includes.io_include()
     if self.pluto:
         statements += includes.pluto_include()
     if self.profiling:
         statements += includes.profiling_include()
     return cgen.Module(statements)
Esempio n. 6
0
    def code(self):
        iters = []
        statements = []
        node = self._node
        cond = node.condition
        domain = str(node.domain)
        if domain[0] == '[' and '->' in domain:
            domain = domain[domain.find('->') + 3:]

        is_set = '[' in domain and ']' in domain
        if is_set:
            iters = domain.split('[')[1].split(']')[0].replace(' ', '').replace('0', 'z').split(',')
            for stmt in node.statements:
                for iter in iters:
                    cond = re.sub(r"\b%s\b" % iter, '(%s)' % iter, cond)
                    stmt = re.sub(r"\b%s\b" % iter, '(%s)' % iter, stmt)
                statements.append(stmt)
        else:
            statements = node._statements

        stmtlist = ";\\\n".join(statements)
        if len(cond) > 0:
            stmtlist = 'if (%s) {  %s;  }' % (cond, stmtlist)

        define = cg.Define('%s(%s)' % (node.label, ','.join(iters)), stmtlist)
        code = "\n%s" % str(define)

        # TODO: If node reads and writes intersect, reset values. This is mostly a hack in need of refactoring...
        intersection = list(set(node.reads) & set(node.writes))
        if len(intersection) > 0:
            code += "\n"
            for item in intersection:
                name = item.split('(')[0]
                dnode = node.graph[name]
                if dnode.scalar:
                    code += "\n%s = %s;" % (name, dnode.defval)
                else:
                    code += "\nmemset(%s, %s, %s * sizeof(%s));" % (name, dnode.defval, dnode.size, dnode.type)

        if is_set and node.set:
            lines = node.graph.set_factory.codegen(node.set, [node.label]).split("\n")
            if config['skipguard'] and 'if (' in lines[0]:
                braced = (lines[0].find('{') > 0)
                lines = lines[1:]
                if braced:
                    lines = lines[0:len(lines) - 1]
            code = "%s\n\n%s" % (code, "\n".join(lines))
        else:
            code = "%s\n\n  %s();" % (code, node.label)

        code = "%s\n" % code.rstrip()
        self._outer.lines.append(code)
        return code
Esempio n. 7
0
    def emit_extern_global_variables(self, source_file):
        source_file.add(cgen.Pragma("""push_macro("_SFR_IO8")"""))
        source_file.add(cgen.Line("#undef _SFR_IO8"))
        source_file.add(cgen.Define("_SFR_IO8(x)", "x"))

        for name, definition in self.definitions:
            port = definition.port[0]
            assert port in ("A", "B", "C", "D", "E")
            pin = int(definition.port[1])

            source_file.add(
                cgen.Statement(f"static kGPIO<PORT{port},{pin}> {name}"))

        source_file.add(cgen.Pragma("""pop_macro("_SFR_IO8")"""))
Esempio n. 8
0
    def visit_Operator(self, o):
        # Generate the code for the cfile
        ccode = super().visit_Operator(o, mode='private')

        # Generate the code for the hfile
        typedecls = self._operator_typedecls(o, mode='public')
        guarded_typedecls = []
        for i in typedecls:
            guard = "DEVITO_%s" % i.tpname.upper()
            iflines = [c.Define(guard, ""), blankline, i, blankline]
            guarded_typedecl = c.IfNDef(guard, iflines, [])
            guarded_typedecls.extend([guarded_typedecl, blankline])

        decls = self._args_decl(o.parameters)
        signature = c.FunctionDeclaration(c.Value(o.retval, o.name), decls)
        hcode = c.Module(guarded_typedecls + [blankline, signature, blankline])

        return ccode, hcode
Esempio n. 9
0
    def emit_internal_header(self, source_file):
        if self.modbus.rs485_dir_pin is not None:
            source_file.add(
                cgen.Define(f"MODBUS_RS485_DIR_PIN",
                            self.modbus.rs485_dir_pin))

        if self.modbus.missing_as_zero is True:
            source_file.add(cgen.Define(f"MODBUS_MISSING_AS_ZERO", 1))

        cnt = 0
        for func_name in self.modbus.functions:
            if func_name == "read_input":
                source_file.add(cgen.Define(f"MB_FUNC_READ_INPUT_ENABLED", 1))
                cnt += 1
            elif func_name == "read_holding":
                source_file.add(cgen.Define(f"MB_FUNC_READ_HOLDING_ENABLED",
                                            1))
                cnt += 1
            elif func_name == "write_holding":
                source_file.add(
                    cgen.Define(f"MB_FUNC_WRITE_HOLDING_ENABLED", 1))
                cnt += 1
            elif func_name == "write_multiple_holding":
                source_file.add(
                    cgen.Define(f"MB_FUNC_WRITE_MULTIPLE_HOLDING_ENABLED", 1))
                cnt += 1
            elif func_name == "read_coils":
                source_file.add(cgen.Define(f"MB_FUNC_READ_COILS_ENABLED", 1))
                cnt += 1
            elif func_name == "write_coils":
                source_file.add(cgen.Define(f"MB_FUNC_WRITE_COIL_ENABLED", 1))
                cnt += 1
            else:
                print(f"invalid function: {func_name}")
                exit(1)

        source_file.add(cgen.Define(f"MB_FUNC_HANDLERS_MAX", cnt))
Esempio n. 10
0
    def visit_Operator(self, o):
        blankline = c.Line("")

        # Kernel signature and body
        body = flatten(self._visit(i) for i in o.children)
        decls = self._args_decl(o.parameters)
        signature = c.FunctionDeclaration(c.Value(o.retval, o.name), decls)
        retval = [c.Line(), c.Statement("return 0")]
        kernel = c.FunctionBody(signature, c.Block(body + retval))

        # Elemental functions
        esigns = []
        efuncs = [blankline]
        for i in o._func_table.values():
            if i.local:
                esigns.append(
                    c.FunctionDeclaration(c.Value(i.root.retval, i.root.name),
                                          self._args_decl(i.root.parameters)))
                efuncs.extend([i.root.ccode, blankline])

        # Header files, extra definitions, ...
        header = [c.Define(*i) for i in o._headers] + [blankline]
        includes = [
            c.Include(i, system=(False if i.endswith('.h') else True))
            for i in o._includes
        ]
        includes += [blankline]
        cdefs = [
            i._C_typedecl for i in o.parameters if i._C_typedecl is not None
        ]
        for i in o._func_table.values():
            if i.local:
                cdefs.extend([
                    j._C_typedecl for j in i.root.parameters
                    if j._C_typedecl is not None
                ])
        cdefs = filter_sorted(cdefs, key=lambda i: i.tpname)
        if o._compiler.src_ext == 'cpp':
            cdefs += [c.Extern('C', signature)]
        cdefs = [i for j in cdefs for i in (j, blankline)]

        return c.Module(header + includes + cdefs + esigns +
                        [blankline, kernel] + efuncs)
Esempio n. 11
0
    def emit_extern_global_variables(self, source_file):
        source_file.add(cgen.Statement(f"static kModbus Modbus"))

        source_file.add(cgen.Define(f"MODBUS_ENABLED", 1))
Esempio n. 12
0
 def _cgen(self):
     return cgen.Define(self.symbol, self.value)
Esempio n. 13
0
 def _cgen(self):
     return cgen.Define(self.macro.definition, self.macro.value)
Esempio n. 14
0
# INÍCIO BLOCO DE DECLARAÇÃO DE VARIAVEIS GLOBAIS
tempString = c.Assign('int ny', '2')
tempString = append(tempString, c.Assign('int nx', '80'))
tempString = append(tempString, c.Assign('int nt', '100'))
tempString = append(tempString, c.Assign('double nx', '2.0 / (nx + 1.0)'))
tempString = append(tempString, c.Assign('double dy', '2.0 / (ny + 1.0)'))
tempString = append(tempString, c.Assign('double sigma', '0.2'))
tempString = append(tempString, c.Assign('double dt', 'sigma * dx'))
# FIM BLOCO DE DECLARAÇÃO DE VARIAVEIS GLOBAIS

# SALVANDO O VALOR NA STRING PRINCIPAL DE SAÍDA
CodeOutput = tempString

# INÍCIO BLOCO DE INCLUDES E DEFINES
tempString = c.Define("OPS_2D", '')
tempString = append(tempString, c.Include('ops_seq.h', system=True))
tempString = append(tempString, c.Include('iostream', system=True))
tempString = append(tempString, c.Include('fstream', system=True))
tempString = append(tempString, c.Include('convec.h', system=False))
tempString = append(tempString, c.Value('using namespace std', ''))
# FIM BLOCO DE INCLUDES

CodeOutput = append(CodeOutput, tempString)

temp = c.FunctionDeclaration(
    c.Value("", "ops_init"),
    [c.Value("", "argc"),
     c.Value("char", "argv"),
     c.Value("", "1")])
# Array para salvar as operações do Main
Esempio n. 15
0
import cgen as c

code = c.Module([
    c.Include('iostream'),
    c.Include('stdlib.h'),
    c.Include('math.h'),
    c.Line(),
    c.LineComment('Necessary to declare constant for OPS.'),
    c.Value('double', 'dx, dy, dt'),
    c.LineComment('Step for each dimension and time.'),
    c.Value('double', 'nx, ny'),
    c.Line(),
    c.Define('PREVIOUS', '0'),
    c.Define('CURRENT', '1'),
    c.Define('NEXT', '2'),
    c.Define('M_PI', '3.14159265358979323846'),
    c.Define('BORDER_SIZE', '20'),
    c.Define('CPML', '20'),
    c.Define('SOURCE_LOCATION_X', '0'),
    c.Define('SOURCE_LOCATION_Y', '0'),
    c.Define('RICKER_PEAK_FREQUENCY', '5'),
    c.Define('MAX_VELOCITY', '5000'),
    c.Line(),
    c.Define('OPS_2D', ''),
    c.Include('ops_seq.h'),
    c.Include('ops_lib_cpp.h'),
    c.Include('sources.cpp'),
    c.Include('velocity-model.cpp'),
    c.Include('wave-propagation-ops.h'),
    c.Line(),
    c.Statement('using namespace std'),
Esempio n. 16
0
    def setup(self, g):
        if g.is_parent:
            if len(self._path) < 1:
                self._path = '%s/%s.%s' % (os.getcwd(), g.name, self._lang.lower())

            if len(self.includes) > 0:
                for incfile in self.includes:
                    include = cg.Include('%s.h' % incfile)
                    self._lines.append(str(include))
                self._lines.append('')

            if len(self.defines) > 0:
                for tuple in self.defines:
                    (lhs, rhs) = tuple
                    define = cg.Define(lhs, rhs)
                    self._lines.append(str(define))
                self._lines.append('')

            if len(self._typedefs) > 0:
                for tuple in self._typedefs:
                    (lhs, rhs) = tuple
                    typedef = cg.Typedef(cg.Value(lhs, rhs))
                    self._lines.append(str(typedef))
                self._lines.append('')

            if len(self._functions) > 0:
                for tuple in self._functions:
                    (lhs, rhs) = tuple
                    fxndef = 'inline %s { %s }' % (lhs, rhs)
                    self._lines.append(fxndef)
                self._lines.append('')

            if len(self._structs) > 0:
                for structname in self._structs:
                    struct = self._structs[structname]
                    fields = [cg.Value(struct[name], name) for name in struct]
                    struct = cg.Struct('', fields)
                    typedef = cg.Typedef(cg.Value(struct, '%s%s' % (structname, StructNode.suffix())))
                    self._lines.append(str(typedef).replace('} ;', '}'))
                    self._lines.append('')

            if len(g.constants) > 0:
                for const in g.constants:
                    define = cg.Define(const.name, const.value)
                    self._lines.append(str(define))
                self._lines.append('')

            if len(g.includes) > 0:
                for incfile in g.includes:
                    include = cg.Include('%s.h' % incfile)
                    self._lines.append(str(include))
                self._lines.append('')

        if len(g.subgraphs) < 1:
            func = CGenHelper.functionDecl(g.returntype, g.name, g.params)
            decl = str(func)
            self._lines.append(decl)
            self._lines.append('inline %s' % decl.replace(';', ' {'))

        if len(g.constants) > 0:
            structname = self._structname
            if len(structname) < 1:
                structname = g.name.split('_')[0]
            if structname not in self._structs:
                self._structs[structname] = OrderedDict()
            for const in g.constants:
                self._structs[structname][const.name] = const.type  # Add const to struct for later use...
Esempio n. 17
0
# -*- mode: python -*-

from gg.ast import *
from gg.lib.graph import Graph
from gg.lib.wl import Worklist
from gg.ast.params import GraphParam

import cgen

G = Graph("graph")
WL = Worklist()

ast = Module([
    CBlock(["typedef int edge_data_type", "typedef int node_data_type"]),
    CBlock([cgen.Define("MAXFORBID", "32")]),
    Kernel("ipgc_init", [G.param()], [
        ForAll("node", G.nodes(),
               [CBlock(["graph.node_data[node] = 0"]),
                WL.push("node")])
    ]),  #initializing all nodes to color 0        
    Kernel(
        "assignColors",
        [G.param()],
        [
            ForAll(
                "node",
                G.nodes(),
                [
                    CDecl([("int", "FORBIDDEN", ""), ("int", "offset", "=0"),
                           ("bool", "colored", "=false")]),
                    If(