cbackend.py 12.7 KB
Newer Older
Martin Bauer's avatar
Martin Bauer committed
1
import sympy as sp
Martin Bauer's avatar
Martin Bauer committed
2
3
4
5
6
try:
    from sympy.utilities.codegen import CCodePrinter
except ImportError:
    from sympy.printing.ccode import C99CodePrinter as CCodePrinter

7
8
9
10
11
12
13
from collections import namedtuple
from sympy.core.mul import _keep_coeff
from sympy.core import S

from pystencils.astnodes import Node, ResolvedFieldAccess, SympyAssignment
from pystencils.types import createType, PointerType, getTypeOfExpression, VectorType, castFunc
from pystencils.backends.simd_instruction_sets import selectedInstructionSet
14
15


16
def generateC(astNode, signatureOnly=False):
Martin Bauer's avatar
Martin Bauer committed
17
18
19
    """
    Prints the abstract syntax tree as C function
    """
Martin Bauer's avatar
Martin Bauer committed
20
    fieldTypes = set([f.dtype for f in astNode.fieldsAccessed])
21
    useFloatConstants = createType("double") not in fieldTypes
22
23
24

    vectorIS = selectedInstructionSet['double']
    printer = CBackend(constantsAsFloats=useFloatConstants, signatureOnly=signatureOnly, vectorInstructionSet=vectorIS)
25
26
27
    return printer(astNode)


28
29
30
31
32
33
34
35
36
37
38
39
40
41
def getHeaders(astNode):
    headers = set()

    if hasattr(astNode, 'headers'):
        headers.update(astNode.headers)
    elif isinstance(astNode, SympyAssignment):
        if type(getTypeOfExpression(astNode.rhs)) is VectorType:
            headers.update(selectedInstructionSet['double']['headers'])

    for a in astNode.args:
        if isinstance(a, Node):
            headers.update(getHeaders(a))

    return headers
42
43
44
45
46
47
48
49
# --------------------------------------- Backend Specific Nodes -------------------------------------------------------


class CustomCppCode(Node):
    def __init__(self, code, symbolsRead, symbolsDefined):
        self._code = "\n" + code
        self._symbolsRead = set(symbolsRead)
        self._symbolsDefined = set(symbolsDefined)
50
        self.headers = []
51
52
53
54
55
56
57
58
59
60
61
62
63
64

    @property
    def code(self):
        return self._code

    @property
    def args(self):
        return []

    @property
    def symbolsDefined(self):
        return self._symbolsDefined

    @property
65
66
    def undefinedSymbols(self):
        return self.symbolsDefined - self._symbolsRead
67
68
69
70
71
72


class PrintNode(CustomCppCode):
    def __init__(self, symbolToPrint):
        code = '\nstd::cout << "%s  =  " << %s << std::endl; \n' % (symbolToPrint.name, symbolToPrint.name)
        super(PrintNode, self).__init__(code, symbolsRead=[symbolToPrint], symbolsDefined=set())
73
        self.headers.append("<iostream>")
74
75
76
77


# ------------------------------------------- Printer ------------------------------------------------------------------

Michael Kuron's avatar
Michael Kuron committed
78
class CBackend(object):
79

80
    def __init__(self, constantsAsFloats=False, sympyPrinter=None, signatureOnly=False, vectorInstructionSet=None):
81
        if sympyPrinter is None:
Martin Bauer's avatar
Martin Bauer committed
82
            self.sympyPrinter = CustomSympyPrinter(constantsAsFloats)
83
84
85
86
            if vectorInstructionSet is not None:
                self.sympyPrinter = VectorizedCustomSympyPrinter(vectorInstructionSet, constantsAsFloats)
            else:
                self.sympyPrinter = CustomSympyPrinter(constantsAsFloats)
87
88
89
        else:
            self.sympyPrinter = sympyPrinter

90
        self._vectorInstructionSet = vectorInstructionSet
91
        self._indent = "   "
92
        self._signatureOnly = signatureOnly
93
94

    def __call__(self, node):
95
96
97
98
99
        prevIs = VectorType.instructionSet
        VectorType.instructionSet = self._vectorInstructionSet
        result = str(self._print(node))
        VectorType.instructionSet = prevIs
        return result
100
101
102
103
104
105
106
107
108

    def _print(self, node):
        for cls in type(node).__mro__:
            methodName = "_print_" + cls.__name__
            if hasattr(self, methodName):
                return getattr(self, methodName)(node)
        raise NotImplementedError("CBackend does not support node of type " + cls.__name__)

    def _print_KernelFunction(self, node):
109
        functionArguments = ["%s %s" % (str(s.dtype), s.name) for s in node.parameters]
Martin Bauer's avatar
Martin Bauer committed
110
        funcDeclaration = "FUNC_PREFIX void %s(%s)" % (node.functionName, ", ".join(functionArguments))
111
112
113
        if self._signatureOnly:
            return funcDeclaration

114
115
        body = self._print(node.body)
        return funcDeclaration + "\n" + body
116
117

    def _print_Block(self, node):
118
        blockContents = "\n".join([self._print(child) for child in node.args])
Michael Kuron's avatar
Michael Kuron committed
119
        return "{\n%s\n}" % (self._indent + self._indent.join(blockContents.splitlines(True)))
120
121

    def _print_PragmaBlock(self, node):
122
        return "%s\n%s" % (node.pragmaLine, self._print_Block(node))
123
124
125

    def _print_LoopOverCoordinate(self, node):
        counterVar = node.loopCounterName
Martin Bauer's avatar
Martin Bauer committed
126
127
128
        start = "int %s = %s" % (counterVar, self.sympyPrinter.doprint(node.start))
        condition = "%s < %s" % (counterVar, self.sympyPrinter.doprint(node.stop))
        update = "%s += %s" % (counterVar, self.sympyPrinter.doprint(node.step),)
129
        loopStr = "for (%s; %s; %s)" % (start, condition, update)
130
131
132
133
134

        prefix = "\n".join(node.prefixLines)
        if prefix:
            prefix += "\n"
        return "%s%s\n%s" % (prefix, loopStr, self._print(node.body))
135
136
137

    def _print_SympyAssignment(self, node):
        if node.isDeclaration:
138
139
140
141
142
143
144
            dtype = "const " + str(node.lhs.dtype) + " " if node.isConst else str(node.lhs.dtype) + " "
            return "%s %s = %s;" % (dtype, self.sympyPrinter.doprint(node.lhs), self.sympyPrinter.doprint(node.rhs))
        else:
            lhsType = getTypeOfExpression(node.lhs)
            if type(lhsType) is VectorType and node.lhs.func == castFunc:
                return self._vectorInstructionSet['storeU'].format("&" + self.sympyPrinter.doprint(node.lhs.args[0]),
                                                                   self.sympyPrinter.doprint(node.rhs)) + ';'
145
            else:
146
                return "%s = %s;" % (self.sympyPrinter.doprint(node.lhs), self.sympyPrinter.doprint(node.rhs))
147
148

    def _print_TemporaryMemoryAllocation(self, node):
149
150
        return "%s * %s = new %s[%s];" % (node.symbol.dtype, self.sympyPrinter.doprint(node.symbol),
                                         node.symbol.dtype, self.sympyPrinter.doprint(node.size))
151
152

    def _print_TemporaryMemoryFree(self, node):
153
        return "delete [] %s;" % (self.sympyPrinter.doprint(node.symbol),)
154
155

    def _print_CustomCppCode(self, node):
156
        return node.code
157

158
159
160
161
162
163
164
165
166
    def _print_Conditional(self, node):
        conditionExpr = self.sympyPrinter.doprint(node.conditionExpr)
        trueBlock = self._print_Block(node.trueBlock)
        result = "if (%s) \n %s " % (conditionExpr, trueBlock)
        if node.falseBlock:
            falseBlock = self._print_Block(node.falseBlock)
            result += "else " + falseBlock
        return result

167
168
169
170
171

# ------------------------------------------ Helper function & classes -------------------------------------------------


class CustomSympyPrinter(CCodePrinter):
Martin Bauer's avatar
Martin Bauer committed
172
173
174
175
176

    def __init__(self, constantsAsFloats=False):
        self._constantsAsFloats = constantsAsFloats
        super(CustomSympyPrinter, self).__init__()

177
178
179
    def _print_Pow(self, expr):
        """Don't use std::pow function, for small integer exponents, write as multiplication"""
        if expr.exp.is_integer and expr.exp.is_number and 0 < expr.exp < 8:
180
            return "(" + self._print(sp.Mul(*[expr.base] * expr.exp, evaluate=False)) + ")"
181
182
183
184
185
        else:
            return super(CustomSympyPrinter, self)._print_Pow(expr)

    def _print_Rational(self, expr):
        """Evaluate all rationals i.e. print 0.25 instead of 1.0/4.0"""
Martin Bauer's avatar
Martin Bauer committed
186
187
188
189
        res = str(expr.evalf().num)
        if self._constantsAsFloats:
            res += "f"
        return res
190
191
192
193
194
195
196
197

    def _print_Equality(self, expr):
        """Equality operator is not printable in default printer"""
        return '((' + self._print(expr.lhs) + ") == (" + self._print(expr.rhs) + '))'

    def _print_Piecewise(self, expr):
        """Print piecewise in one line (remove newlines)"""
        result = super(CustomSympyPrinter, self)._print_Piecewise(expr)
Martin Bauer's avatar
Martin Bauer committed
198
199
200
201
202
203
204
        return result.replace("\n", "")

    def _print_Float(self, expr):
        res = str(expr)
        if self._constantsAsFloats:
            res += "f"
        return res
205

206
207
208
209
210
    def _print_Function(self, expr):
        name = str(expr.func).lower()
        if name == 'cast':
            arg, type = expr.args
            return "*((%s)(& %s))" % (PointerType(type), self._print(arg))
211
        else:
212
            return super(CustomSympyPrinter, self)._print_Function(expr)
Martin Bauer's avatar
Martin Bauer committed
213

214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331

class VectorizedCustomSympyPrinter(CustomSympyPrinter):
    SummandInfo = namedtuple("SummandInfo", ['sign', 'term'])

    def __init__(self, instructionSet, constantsAsFloats=False):
        super(VectorizedCustomSympyPrinter, self).__init__(constantsAsFloats)
        self.instructionSet = instructionSet

    def _print_Function(self, expr):
        name = str(expr.func).lower()
        if name == 'cast':
            arg, dtype = expr.args
            if type(dtype) is VectorType:
                if type(arg) is ResolvedFieldAccess:
                    return self.instructionSet['loadU'].format("& " + self._print(arg))
                else:
                    return self.instructionSet['makeVec'].format(self._print(arg))

        return super(VectorizedCustomSympyPrinter, self)._print_Function(expr)

    def _print_Add(self, expr, order=None):
        exprType = getTypeOfExpression(expr)
        if type(exprType) is not VectorType:
            return super(VectorizedCustomSympyPrinter, self)._print_Add(expr, order)
        assert self.instructionSet['width'] == exprType.width

        summands = []
        for term in expr.args:
            if term.func == sp.Mul:
                sign, t = self._print_Mul(term, insideAdd=True)
            else:
                t = self._print(term)
                sign = 1
            summands.append(self.SummandInfo(sign, t))
        # Use positive terms first
        summands.sort(key=lambda e: e.sign, reverse=True)
        # if no positive term exists, prepend a zero
        if summands[0].sign == -1:
            summands.insert(0, self.SummandInfo(1, "0"))

        assert len(summands) >= 2
        processed = summands[0].term
        for summand in summands[1:]:
            func = self.instructionSet['-'] if summand.sign == -1 else self.instructionSet['+']
            processed = func.format(processed, summand.term)
        return processed

    def _print_Mul(self, expr, insideAdd=False):
        exprType = getTypeOfExpression(expr)
        if type(exprType) is not VectorType:
            return super(VectorizedCustomSympyPrinter, self)._print_Mul(expr)
        assert self.instructionSet['width'] == exprType.width

        c, e = expr.as_coeff_Mul()
        if c < 0:
            expr = _keep_coeff(-c, e)
            sign = -1
        else:
            sign = 1

        a = []  # items in the numerator
        b = []  # items that are in the denominator (if any)

        # Gather args for numerator/denominator
        for item in expr.as_ordered_factors():
            if item.is_commutative and item.is_Pow and item.exp.is_Rational and item.exp.is_negative:
                if item.exp != -1:
                    b.append(sp.Pow(item.base, -item.exp, evaluate=False))
                else:
                    b.append(sp.Pow(item.base, -item.exp))
            else:
                a.append(item)

        a = a or [S.One]

        a_str = [self._print(x) for x in a]
        b_str = [self._print(x) for x in b]

        result = a_str[0]
        for item in a_str[1:]:
            result = self.intrinsics['*'].format(result, item)

        if len(b) > 0:
            denominator_str = b_str[0]
            for item in b_str[1:]:
                denominator_str = self.intrinsics['*'].format(denominator_str, item)
            result = self.intrinsics['/'].format(result, denominator_str)

        if insideAdd:
            return sign, result
        else:
            if sign < 0:
                return self.intrinsics['*'].format(self._print(S.NegativeOne), result)
            else:
                return result

#    def _print_Piecewise(self, expr):
#        if expr.args[-1].cond != True:
#            # We need the last conditional to be a True, otherwise the resulting
#            # function may not return a result.
#            raise ValueError("All Piecewise expressions must contain an "
#                             "(expr, True) statement to be used as a default "
#                             "condition. Without one, the generated "
#                             "expression may not evaluate to anything under "
#                             "some condition.")
#
#        result = self._print(expr.args[-1][0])
#        for trueExpr, condition in reversed(expr.args[:-1]):
#            result = self.intrinsics['blendv'].format(result, self._print(trueExpr), self._print(condition))
#        return result
#
#    def _print_Relational(self, expr):
#        return self.intrinsics[expr.rel_op].format(expr.lhs, expr.rhs)
#
#    def _print_Equality(self, expr):
#        return self.intrinsics['=='].format(self._print(expr.lhs), self._print(expr.rhs))
#