cbackend.py 21.6 KB
Newer Older
Martin Bauer's avatar
Martin Bauer committed
1
import sympy as sp
Martin Bauer's avatar
Martin Bauer committed
2
3
from collections import namedtuple
from sympy.core import S
4
from typing import Set
5
from sympy.printing.ccode import C89CodePrinter
6

7
from pystencils.cpu.vectorization import vec_any, vec_all
8
9
from pystencils.fast_approximation import fast_division, fast_sqrt, fast_inv_sqrt

Martin Bauer's avatar
Martin Bauer committed
10
11
try:
    from sympy.printing.ccode import C99CodePrinter as CCodePrinter
Martin Bauer's avatar
Martin Bauer committed
12
13
except ImportError:
    from sympy.printing.ccode import CCodePrinter  # for sympy versions < 1.1
Martin Bauer's avatar
Martin Bauer committed
14

Martin Bauer's avatar
Martin Bauer committed
15
from pystencils.integer_functions import bitwise_xor, bit_shift_right, bit_shift_left, bitwise_and, \
Martin Bauer's avatar
Martin Bauer committed
16
    bitwise_or, modulo_ceil
17
from pystencils.astnodes import Node, KernelFunction
Martin Bauer's avatar
Martin Bauer committed
18
from pystencils.data_types import create_type, PointerType, get_type_of_expression, VectorType, cast_func, \
19
    vector_memory_access, reinterpret_cast_func, get_base_type
20

21
__all__ = ['generate_c', 'CustomCodeNode', 'PrintNode', 'get_headers', 'CustomSympyPrinter']
22

Martin Bauer's avatar
Martin Bauer committed
23

24
25
KERNCRAFT_NO_TERNARY_MODE = False

26
def generate_c(ast_node: Node, signature_only: bool = False, dialect='c') -> str:
Martin Bauer's avatar
Martin Bauer committed
27
28
29
30
31
32
33
34
35
    """Prints an abstract syntax tree node as C or CUDA code.

    This function does not need to distinguish between C, C++ or CUDA code, it just prints 'C-like' code as encoded
    in the abstract syntax tree (AST). The AST is built differently for C or CUDA by calling different create_kernel
    functions.

    Args:
        ast_node:
        signature_only:
36
        dialect: 'c' or 'cuda'
Martin Bauer's avatar
Martin Bauer committed
37
38
    Returns:
        C-like code for the ast node and its descendants
Martin Bauer's avatar
Martin Bauer committed
39
    """
40
    printer = CBackend(signature_only=signature_only,
41
42
                       vector_instruction_set=ast_node.instruction_set,
                       dialect=dialect)
Martin Bauer's avatar
Martin Bauer committed
43
    return printer(ast_node)
44
45


Martin Bauer's avatar
Martin Bauer committed
46
47
def get_headers(ast_node: Node) -> Set[str]:
    """Return a set of header files, necessary to compile the printed C-like code."""
48
49
    headers = set()

Martin Bauer's avatar
Martin Bauer committed
50
51
52
    if isinstance(ast_node, KernelFunction) and ast_node.instruction_set:
        headers.update(ast_node.instruction_set['headers'])

Martin Bauer's avatar
Martin Bauer committed
53
54
55
    if hasattr(ast_node, 'headers'):
        headers.update(ast_node.headers)
    for a in ast_node.args:
56
        if isinstance(a, Node):
Martin Bauer's avatar
Martin Bauer committed
57
            headers.update(get_headers(a))
58
59

    return headers
60
61


62
63
64
# --------------------------------------- Backend Specific Nodes -------------------------------------------------------


65
class CustomCodeNode(Node):
Martin Bauer's avatar
Martin Bauer committed
66
    def __init__(self, code, symbols_read, symbols_defined, parent=None):
67
        super(CustomCodeNode, self).__init__(parent=parent)
68
        self._code = "\n" + code
Martin Bauer's avatar
Martin Bauer committed
69
70
        self._symbolsRead = set(symbols_read)
        self._symbolsDefined = set(symbols_defined)
71
        self.headers = []
72

73
    def get_code(self, dialect, vector_instruction_set):
74
75
76
77
78
79
80
        return self._code

    @property
    def args(self):
        return []

    @property
Martin Bauer's avatar
Martin Bauer committed
81
    def symbols_defined(self):
82
83
84
        return self._symbolsDefined

    @property
Martin Bauer's avatar
Martin Bauer committed
85
86
    def undefined_symbols(self):
        return self.symbols_defined - self._symbolsRead
87
88


89
class PrintNode(CustomCodeNode):
Martin Bauer's avatar
Martin Bauer committed
90
91
92
93
    # noinspection SpellCheckingInspection
    def __init__(self, symbol_to_print):
        code = '\nstd::cout << "%s  =  " << %s << std::endl; \n' % (symbol_to_print.name, symbol_to_print.name)
        super(PrintNode, self).__init__(code, symbols_read=[symbol_to_print], symbols_defined=set())
94
        self.headers.append("<iostream>")
95
96
97
98


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

99

Martin Bauer's avatar
Martin Bauer committed
100
101
# noinspection PyPep8Naming
class CBackend:
102

Martin Bauer's avatar
Martin Bauer committed
103
    def __init__(self, sympy_printer=None, signature_only=False, vector_instruction_set=None, dialect='c'):
Martin Bauer's avatar
Martin Bauer committed
104
105
        if sympy_printer is None:
            if vector_instruction_set is not None:
106
                self.sympy_printer = VectorizedCustomSympyPrinter(vector_instruction_set, dialect)
107
            else:
108
                self.sympy_printer = CustomSympyPrinter(dialect)
109
        else:
Martin Bauer's avatar
Martin Bauer committed
110
            self.sympy_printer = sympy_printer
111

112
        self._vector_instruction_set = vector_instruction_set
113
        self._indent = "   "
114
        self._dialect = dialect
Martin Bauer's avatar
Martin Bauer committed
115
        self._signatureOnly = signature_only
116
117

    def __call__(self, node):
Martin Bauer's avatar
Martin Bauer committed
118
        prev_is = VectorType.instruction_set
119
        VectorType.instruction_set = self._vector_instruction_set
120
        result = str(self._print(node))
Martin Bauer's avatar
Martin Bauer committed
121
        VectorType.instruction_set = prev_is
122
        return result
123
124
125

    def _print(self, node):
        for cls in type(node).__mro__:
Martin Bauer's avatar
Martin Bauer committed
126
127
128
129
            method_name = "_print_" + cls.__name__
            if hasattr(self, method_name):
                return getattr(self, method_name)(node)
        raise NotImplementedError("CBackend does not support node of type " + str(type(node)))
130
131

    def _print_KernelFunction(self, node):
132
        function_arguments = ["%s %s" % (str(s.symbol.dtype), s.symbol.name) for s in node.get_parameters()]
Martin Bauer's avatar
Martin Bauer committed
133
        func_declaration = "FUNC_PREFIX void %s(%s)" % (node.function_name, ", ".join(function_arguments))
134
        if self._signatureOnly:
Martin Bauer's avatar
Martin Bauer committed
135
            return func_declaration
136

137
        body = self._print(node.body)
Martin Bauer's avatar
Martin Bauer committed
138
        return func_declaration + "\n" + body
139
140

    def _print_Block(self, node):
Martin Bauer's avatar
Martin Bauer committed
141
142
        block_contents = "\n".join([self._print(child) for child in node.args])
        return "{\n%s\n}" % (self._indent + self._indent.join(block_contents.splitlines(True)))
143
144

    def _print_PragmaBlock(self, node):
Martin Bauer's avatar
Martin Bauer committed
145
        return "%s\n%s" % (node.pragma_line, self._print_Block(node))
146
147

    def _print_LoopOverCoordinate(self, node):
Martin Bauer's avatar
Martin Bauer committed
148
        counter_symbol = node.loop_counter_name
Martin Bauer's avatar
Martin Bauer committed
149
150
151
152
        start = "int %s = %s" % (counter_symbol, self.sympy_printer.doprint(node.start))
        condition = "%s < %s" % (counter_symbol, self.sympy_printer.doprint(node.stop))
        update = "%s += %s" % (counter_symbol, self.sympy_printer.doprint(node.step),)
        loop_str = "for (%s; %s; %s)" % (start, condition, update)
153

Martin Bauer's avatar
Martin Bauer committed
154
        prefix = "\n".join(node.prefix_lines)
155
156
        if prefix:
            prefix += "\n"
Martin Bauer's avatar
Martin Bauer committed
157
        return "%s%s\n%s" % (prefix, loop_str, self._print(node.body))
158
159

    def _print_SympyAssignment(self, node):
Martin Bauer's avatar
Martin Bauer committed
160
161
        if node.is_declaration:
            data_type = "const " + str(node.lhs.dtype) + " " if node.is_const else str(node.lhs.dtype) + " "
162
163
            return "%s%s = %s;" % (data_type, self.sympy_printer.doprint(node.lhs),
                                   self.sympy_printer.doprint(node.rhs))
164
        else:
Martin Bauer's avatar
Martin Bauer committed
165
            lhs_type = get_type_of_expression(node.lhs)
Martin Bauer's avatar
Martin Bauer committed
166
167
168
169
170
171
            if type(lhs_type) is VectorType and isinstance(node.lhs, cast_func):
                arg, data_type, aligned, nontemporal = node.lhs.args
                instr = 'storeU'
                if aligned:
                    instr = 'stream' if nontemporal else 'storeA'

172
173
174
175
176
177
                rhs_type = get_type_of_expression(node.rhs)
                if type(rhs_type) is not VectorType:
                    rhs = cast_func(node.rhs, VectorType(rhs_type))
                else:
                    rhs = node.rhs

178
179
                return self._vector_instruction_set[instr].format("&" + self.sympy_printer.doprint(node.lhs.args[0]),
                                                                  self.sympy_printer.doprint(rhs)) + ';'
180
            else:
Martin Bauer's avatar
Martin Bauer committed
181
                return "%s = %s;" % (self.sympy_printer.doprint(node.lhs), self.sympy_printer.doprint(node.rhs))
182
183

    def _print_TemporaryMemoryAllocation(self, node):
184
        align = 64
Martin Bauer's avatar
Martin Bauer committed
185
186
187
188
189
190
        np_dtype = node.symbol.dtype.base_type.numpy_dtype
        required_size = np_dtype.itemsize * node.size + align
        size = modulo_ceil(required_size, align)
        code = "{dtype} {name}=({dtype})aligned_alloc({align}, {size}) + {offset};"
        return code.format(dtype=node.symbol.dtype,
                           name=self.sympy_printer.doprint(node.symbol.name),
191
                           size=self.sympy_printer.doprint(size),
Martin Bauer's avatar
Martin Bauer committed
192
193
                           offset=int(node.offset(align)),
                           align=align)
194
195

    def _print_TemporaryMemoryFree(self, node):
196
        align = 64
Martin Bauer's avatar
Martin Bauer committed
197
        return "free(%s - %d);" % (self.sympy_printer.doprint(node.symbol.name), node.offset(align))
198

Martin Bauer's avatar
Martin Bauer committed
199
200
201
202
203
204
    def _print_SkipIteration(self, _):
        if self._dialect == 'cuda':
            return "return;"
        else:
            return "continue;"

205
206
    def _print_CustomCodeNode(self, node):
        return node.get_code(self._dialect, self._vector_instruction_set)
207

208
    def _print_Conditional(self, node):
209
210
211
        cond_type = get_type_of_expression(node.condition_expr)
        if isinstance(cond_type, VectorType):
            raise ValueError("Problem with Conditional inside vectorized loop - use vec_any or vec_all")
Martin Bauer's avatar
Martin Bauer committed
212
213
        condition_expr = self.sympy_printer.doprint(node.condition_expr)
        true_block = self._print_Block(node.true_block)
Martin Bauer's avatar
Martin Bauer committed
214
        result = "if (%s)\n%s " % (condition_expr, true_block)
Martin Bauer's avatar
Martin Bauer committed
215
216
        if node.false_block:
            false_block = self._print_Block(node.false_block)
Martin Bauer's avatar
Martin Bauer committed
217
            result += "else " + false_block
218
219
        return result

220
221
222
223

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


Martin Bauer's avatar
Martin Bauer committed
224
# noinspection PyPep8Naming
225
class CustomSympyPrinter(CCodePrinter):
Martin Bauer's avatar
Martin Bauer committed
226

227
    def __init__(self, dialect):
Martin Bauer's avatar
Martin Bauer committed
228
        super(CustomSympyPrinter, self).__init__()
229
        self._float_type = create_type("float32")
230
        self._dialect = dialect
231
232
233
234
        if 'Min' in self.known_functions:
            del self.known_functions['Min']
        if 'Max' in self.known_functions:
            del self.known_functions['Max']
Martin Bauer's avatar
Martin Bauer committed
235

236
237
238
    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:
239
            return "(" + self._print(sp.Mul(*[expr.base] * expr.exp, evaluate=False)) + ")"
240
241
        elif expr.exp.is_integer and expr.exp.is_number and - 8 < expr.exp < 0:
            return "1 / ({})".format(self._print(sp.Mul(*[expr.base] * (-expr.exp), evaluate=False)))
242
243
244
245
246
        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
247
248
        res = str(expr.evalf().num)
        return res
249
250
251
252
253
254
255
256

    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
257
258
        return result.replace("\n", "")

259
    def _print_Function(self, expr):
260
        infix_functions = {
Martin Bauer's avatar
Martin Bauer committed
261
262
263
264
265
            bitwise_xor: '^',
            bit_shift_right: '>>',
            bit_shift_left: '<<',
            bitwise_or: '|',
            bitwise_and: '&',
Martin Bauer's avatar
Martin Bauer committed
266
        }
Martin Bauer's avatar
Martin Bauer committed
267
268
        if hasattr(expr, 'to_c'):
            return expr.to_c(self._print)
269
270
271
272
        if isinstance(expr, reinterpret_cast_func):
            arg, data_type = expr.args
            return "*((%s)(& %s))" % (PointerType(data_type, restrict=False), self._print(arg))
        elif isinstance(expr, cast_func):
Martin Bauer's avatar
Martin Bauer committed
273
            arg, data_type = expr.args
274
275
276
            if isinstance(arg, sp.Number):
                return self._typed_number(arg, data_type)
            else:
277
278
279
280
281
282
283
284
285
286
287
                return "((%s)(%s))" % (data_type, self._print(arg))
        elif isinstance(expr, fast_division):
            if self._dialect == "cuda":
                return "__fdividef(%s, %s)" % tuple(self._print(a) for a in expr.args)
            else:
                return "({})".format(self._print(expr.args[0] / expr.args[1]))
        elif isinstance(expr, fast_sqrt):
            if self._dialect == "cuda":
                return "__fsqrt_rn(%s)" % tuple(self._print(a) for a in expr.args)
            else:
                return "({})".format(self._print(sp.sqrt(expr.args[0])))
288
289
        elif isinstance(expr, vec_any) or isinstance(expr, vec_all):
            return self._print(expr.args[0])
290
291
292
293
294
        elif isinstance(expr, fast_inv_sqrt):
            if self._dialect == "cuda":
                return "__frsqrt_rn(%s)" % tuple(self._print(a) for a in expr.args)
            else:
                return "({})".format(self._print(1 / sp.sqrt(expr.args[0])))
295
296
        elif expr.func in infix_functions:
            return "(%s %s %s)" % (self._print(expr.args[0]), infix_functions[expr.func], self._print(expr.args[1]))
297
        else:
298
            return super(CustomSympyPrinter, self)._print_Function(expr)
Martin Bauer's avatar
Martin Bauer committed
299

300
301
    def _typed_number(self, number, dtype):
        res = self._print(number)
302
        if dtype.is_float():
303
304
305
306
307
308
309
310
            if dtype == self._float_type:
                if '.' not in res:
                    res += ".0f"
                else:
                    res += "f"
            return res
        else:
            return res
311

312
313
314
    _print_Max = C89CodePrinter._print_Max
    _print_Min = C89CodePrinter._print_Min

315

Martin Bauer's avatar
Martin Bauer committed
316
# noinspection PyPep8Naming
317
318
319
class VectorizedCustomSympyPrinter(CustomSympyPrinter):
    SummandInfo = namedtuple("SummandInfo", ['sign', 'term'])

320
321
    def __init__(self, instruction_set, dialect):
        super(VectorizedCustomSympyPrinter, self).__init__(dialect=dialect)
Martin Bauer's avatar
Martin Bauer committed
322
        self.instruction_set = instruction_set
323

Martin Bauer's avatar
Martin Bauer committed
324
325
326
327
    def _scalarFallback(self, func_name, expr, *args, **kwargs):
        expr_type = get_type_of_expression(expr)
        if type(expr_type) is not VectorType:
            return getattr(super(VectorizedCustomSympyPrinter, self), func_name)(expr, *args, **kwargs)
328
        else:
Martin Bauer's avatar
Martin Bauer committed
329
            assert self.instruction_set['width'] == expr_type.width
330
331
            return None

332
    def _print_Function(self, expr):
333
        if isinstance(expr, vector_memory_access):
Martin Bauer's avatar
Martin Bauer committed
334
335
336
            arg, data_type, aligned, _ = expr.args
            instruction = self.instruction_set['loadA'] if aligned else self.instruction_set['loadU']
            return instruction.format("& " + self._print(arg))
337
        elif isinstance(expr, cast_func):
Martin Bauer's avatar
Martin Bauer committed
338
339
            arg, data_type = expr.args
            if type(data_type) is VectorType:
Martin Bauer's avatar
Martin Bauer committed
340
                return self.instruction_set['makeVec'].format(self._print(arg))
341
        elif expr.func == fast_division:
342
343
            result = self._scalarFallback('_print_Function', expr)
            if not result:
344
345
                result = self.instruction_set['/'].format(self._print(expr.args[0]), self._print(expr.args[1]))
            return result
346
347
348
        elif expr.func == fast_sqrt:
            return "({})".format(self._print(sp.sqrt(expr.args[0])))
        elif expr.func == fast_inv_sqrt:
349
350
351
352
353
354
            result = self._scalarFallback('_print_Function', expr)
            if not result:
                if self.instruction_set['rsqrt']:
                    return self.instruction_set['rsqrt'].format(self._print(expr.args[0]))
                else:
                    return "({})".format(self._print(1 / sp.sqrt(expr.args[0])))
355
356
357
358
359
360
361
362
363
364
365
366
367
        elif isinstance(expr, vec_any):
            expr_type = get_type_of_expression(expr.args[0])
            if type(expr_type) is not VectorType:
                return self._print(expr.args[0])
            else:
                return self.instruction_set['any'].format(self._print(expr.args[0]))
        elif isinstance(expr, vec_all):
            expr_type = get_type_of_expression(expr.args[0])
            if type(expr_type) is not VectorType:
                return self._print(expr.args[0])
            else:
                return self.instruction_set['all'].format(self._print(expr.args[0]))

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

370
371
372
373
374
    def _print_And(self, expr):
        result = self._scalarFallback('_print_And', expr)
        if result:
            return result

Martin Bauer's avatar
Martin Bauer committed
375
376
377
378
        arg_strings = [self._print(a) for a in expr.args]
        assert len(arg_strings) > 0
        result = arg_strings[0]
        for item in arg_strings[1:]:
Martin Bauer's avatar
Martin Bauer committed
379
            result = self.instruction_set['&'].format(result, item)
380
381
382
383
384
385
386
        return result

    def _print_Or(self, expr):
        result = self._scalarFallback('_print_Or', expr)
        if result:
            return result

Martin Bauer's avatar
Martin Bauer committed
387
388
389
390
        arg_strings = [self._print(a) for a in expr.args]
        assert len(arg_strings) > 0
        result = arg_strings[0]
        for item in arg_strings[1:]:
Martin Bauer's avatar
Martin Bauer committed
391
            result = self.instruction_set['|'].format(result, item)
392
393
        return result

394
    def _print_Add(self, expr, order=None):
395
396
397
        result = self._scalarFallback('_print_Add', expr)
        if result:
            return result
398
399
400
401

        summands = []
        for term in expr.args:
            if term.func == sp.Mul:
Martin Bauer's avatar
Martin Bauer committed
402
                sign, t = self._print_Mul(term, inside_add=True)
403
404
405
406
407
408
409
410
411
412
413
414
415
            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:]:
Martin Bauer's avatar
Martin Bauer committed
416
            func = self.instruction_set['-'] if summand.sign == -1 else self.instruction_set['+']
417
418
419
            processed = func.format(processed, summand.term)
        return processed

420
    def _print_Pow(self, expr):
421
422
423
        result = self._scalarFallback('_print_Pow', expr)
        if result:
            return result
424

425
426
        one = self.instruction_set['makeVec'].format(1.0)

427
428
        if expr.exp.is_integer and expr.exp.is_number and 0 < expr.exp < 8:
            return "(" + self._print(sp.Mul(*[expr.base] * expr.exp, evaluate=False)) + ")"
429
430
431
432
433
        elif expr.exp == -1:
            one = self.instruction_set['makeVec'].format(1.0)
            return self.instruction_set['/'].format(one, self._print(expr.base))
        elif expr.exp == 0.5:
            return self.instruction_set['sqrt'].format(self._print(expr.base))
434
435
436
        elif expr.exp == -0.5:
            root = self.instruction_set['sqrt'].format(self._print(expr.base))
            return self.instruction_set['/'].format(one, root)
437
438
439
        elif expr.exp.is_integer and expr.exp.is_number and - 8 < expr.exp < 0:
            return self.instruction_set['/'].format(one,
                                                    self._print(sp.Mul(*[expr.base] * (-expr.exp), evaluate=False)))
440
        else:
441
            raise ValueError("Generic exponential not supported: " + str(expr))
442

Martin Bauer's avatar
Martin Bauer committed
443
444
445
446
    def _print_Mul(self, expr, inside_add=False):
        # noinspection PyProtectedMember
        from sympy.core.mul import _keep_coeff

447
448
449
        result = self._scalarFallback('_print_Mul', expr)
        if result:
            return result
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477

        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:]:
Martin Bauer's avatar
Martin Bauer committed
478
            result = self.instruction_set['*'].format(result, item)
479
480
481
482

        if len(b) > 0:
            denominator_str = b_str[0]
            for item in b_str[1:]:
Martin Bauer's avatar
Martin Bauer committed
483
484
                denominator_str = self.instruction_set['*'].format(denominator_str, item)
            result = self.instruction_set['/'].format(result, denominator_str)
485

Martin Bauer's avatar
Martin Bauer committed
486
        if inside_add:
487
488
489
            return sign, result
        else:
            if sign < 0:
Martin Bauer's avatar
Martin Bauer committed
490
                return self.instruction_set['*'].format(self._print(S.NegativeOne), result)
491
492
493
            else:
                return result

494
    def _print_Relational(self, expr):
495
496
497
        result = self._scalarFallback('_print_Relational', expr)
        if result:
            return result
Martin Bauer's avatar
Martin Bauer committed
498
        return self.instruction_set[expr.rel_op].format(self._print(expr.lhs), self._print(expr.rhs))
499
500

    def _print_Equality(self, expr):
501
502
503
        result = self._scalarFallback('_print_Equality', expr)
        if result:
            return result
Martin Bauer's avatar
Martin Bauer committed
504
        return self.instruction_set['=='].format(self._print(expr.lhs), self._print(expr.rhs))
505
506

    def _print_Piecewise(self, expr):
507
508
509
        result = self._scalarFallback('_print_Piecewise', expr)
        if result:
            return result
510

Martin Bauer's avatar
Martin Bauer committed
511
        if expr.args[-1].cond.args[0] is not sp.sympify(True):
512
513
514
515
516
517
518
519
520
            # 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])
Martin Bauer's avatar
Martin Bauer committed
521
        for true_expr, condition in reversed(expr.args[:-1]):
522
            if isinstance(condition, cast_func) and get_type_of_expression(condition.args[0]) == create_type("bool"):
523
524
525
526
527
                if not KERNCRAFT_NO_TERNARY_MODE:
                    result = "(({}) ? ({}) : ({}))".format(self._print(condition.args[0]), self._print(true_expr),
                                                           result)
                else:
                    print("Warning - skipping ternary op")
528
529
530
            else:
                # noinspection SpellCheckingInspection
                result = self.instruction_set['blendv'].format(result, self._print(true_expr), self._print(condition))
531
        return result