astnodes.py 20.1 KB
Newer Older
1
import sympy as sp
2
from sympy.tensor import IndexedBase
3
from pystencils.field import Field
Martin Bauer's avatar
Martin Bauer committed
4
from pystencils.data_types import TypedSymbol, create_type, cast_func
5
from pystencils.kernelparameters import FieldStrideSymbol, FieldPointerSymbol, FieldShapeSymbol
Martin Bauer's avatar
Martin Bauer committed
6
from pystencils.sympyextensions import fast_subs
7
from typing import List, Set, Optional, Union, Any, Sequence
Martin Bauer's avatar
Martin Bauer committed
8
9

NodeOrExpr = Union['Node', sp.Expr]
10
11


12
class Node:
Martin Bauer's avatar
Martin Bauer committed
13
    """Base class for all AST nodes."""
Martin Bauer's avatar
Martin Bauer committed
14

Martin Bauer's avatar
Martin Bauer committed
15
    def __init__(self, parent: Optional['Node'] = None):
16
17
        self.parent = parent

Martin Bauer's avatar
Martin Bauer committed
18
19
20
    @property
    def args(self) -> List[NodeOrExpr]:
        """Returns all arguments/children of this node."""
Martin Bauer's avatar
Martin Bauer committed
21
        raise NotImplementedError()
22
23

    @property
Martin Bauer's avatar
Martin Bauer committed
24
25
    def symbols_defined(self) -> Set[sp.Symbol]:
        """Set of symbols which are defined by this node."""
Martin Bauer's avatar
Martin Bauer committed
26
        raise NotImplementedError()
27
28

    @property
Martin Bauer's avatar
Martin Bauer committed
29
30
    def undefined_symbols(self) -> Set[sp.Symbol]:
        """Symbols which are used but are not defined inside this node."""
31
        raise NotImplementedError()
32

Martin Bauer's avatar
Martin Bauer committed
33
    def subs(self, subs_dict) -> None:
Martin Bauer's avatar
Martin Bauer committed
34
        """Inplace! substitute, similar to sympy's but modifies the AST inplace."""
35
        for a in self.args:
Martin Bauer's avatar
Martin Bauer committed
36
            a.subs(subs_dict)
37

38
39
40
41
    @property
    def func(self):
        return self.__class__

Martin Bauer's avatar
Martin Bauer committed
42
43
    def atoms(self, arg_type) -> Set[Any]:
        """Returns a set of all descendants recursively, which are an instance of the given type."""
44
45
        result = set()
        for arg in self.args:
Martin Bauer's avatar
Martin Bauer committed
46
            if isinstance(arg, arg_type):
47
                result.add(arg)
Martin Bauer's avatar
Martin Bauer committed
48
            result.update(arg.atoms(arg_type))
49
50
51
        return result


52
class Conditional(Node):
Martin Bauer's avatar
Martin Bauer committed
53
54
55
56
57
58
59
60
61
62
63
    """Conditional that maps to a 'if' statement in C/C++.

    Try to avoid using this node inside of loops, since currently this construction can not be vectorized.
    Consider using assignments with sympy.Piecewise in this case.

    Args:
        condition_expr: sympy relational expression
        true_block: block which is run if conditional is true
        false_block: optional block which is run if conditional is false
    """

Martin Bauer's avatar
Martin Bauer committed
64
65
    def __init__(self, condition_expr: sp.Basic, true_block: Union['Block', 'SympyAssignment'],
                 false_block: Optional['Block'] = None) -> None:
Martin Bauer's avatar
Martin Bauer committed
66
67
68
        super(Conditional, self).__init__(parent=None)

        assert condition_expr.is_Boolean or condition_expr.is_Relational
Martin Bauer's avatar
Martin Bauer committed
69
        self.condition_expr = condition_expr
Martin Bauer's avatar
Martin Bauer committed
70
71

        def handle_child(c):
72
73
74
75
76
77
78
            if c is None:
                return None
            if not isinstance(c, Block):
                c = Block([c])
            c.parent = self
            return c

Martin Bauer's avatar
Martin Bauer committed
79
80
        self.true_block = handle_child(true_block)
        self.false_block = handle_child(false_block)
81

Martin Bauer's avatar
Martin Bauer committed
82
83
    def subs(self, subs_dict):
        self.true_block.subs(subs_dict)
Martin Bauer's avatar
Martin Bauer committed
84
        if self.false_block:
Martin Bauer's avatar
Martin Bauer committed
85
86
            self.false_block.subs(subs_dict)
        self.condition_expr = self.condition_expr.subs(subs_dict)
87
88
89

    @property
    def args(self):
Martin Bauer's avatar
Martin Bauer committed
90
91
92
        result = [self.condition_expr, self.true_block]
        if self.false_block:
            result.append(self.false_block)
93
94
95
        return result

    @property
Martin Bauer's avatar
Martin Bauer committed
96
    def symbols_defined(self):
97
98
99
        return set()

    @property
Martin Bauer's avatar
Martin Bauer committed
100
    def undefined_symbols(self):
Martin Bauer's avatar
Martin Bauer committed
101
102
103
104
        result = self.true_block.undefined_symbols
        if self.false_block:
            result.update(self.false_block.undefined_symbols)
        result.update(self.condition_expr.atoms(sp.Symbol))
105
106
107
        return result

    def __str__(self):
Martin Bauer's avatar
Martin Bauer committed
108
        return 'if:({!s}) '.format(self.condition_expr)
109
110

    def __repr__(self):
Martin Bauer's avatar
Martin Bauer committed
111
        return 'if:({!r}) '.format(self.condition_expr)
112

113
114
115
116
117
118
119
120
    def replace_by_true_block(self):
        """Replaces the conditional by its True block"""
        self.parent.replace(self, [self.true_block])

    def replace_by_false_block(self):
        """Replaces the conditional by its False block"""
        self.parent.replace(self, [self.false_block] if self.false_block else [])

121

122
123
class KernelFunction(Node):

124
125
126
127
128
129
130
131
132
133
134
135
136
137
    class Parameter:
        """Function parameter.

        Each undefined symbol in a `KernelFunction` node becomes a parameter to the function.
        Parameters are either symbols introduced by the user that never occur on the left hand side of an
        Assignment, or are related to fields/arrays passed to the function.

        A parameter consists of the typed symbol (symbol property). For field related parameters this is a symbol
        defined in pystencils.kernelparameters.
        If the parameter is related to one or multiple fields, these fields are referenced in the fields property.
        """
        def __init__(self, symbol, fields):
            self.symbol = symbol  # type: TypedSymbol
            self.fields = fields  # type: Sequence[Field]
138

139
        def __repr__(self):
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
            return repr(self.symbol)

        @property
        def is_field_stride(self):
            return isinstance(self.symbol, FieldStrideSymbol)

        @property
        def is_field_shape(self):
            return isinstance(self.symbol, FieldShapeSymbol)

        @property
        def is_field_pointer(self):
            return isinstance(self.symbol, FieldPointerSymbol)

        @property
        def is_field_parameter(self):
            return self.is_field_pointer or self.is_field_shape or self.is_field_stride

        @property
        def field_name(self):
            return self.fields[0].name
161

Martin Bauer's avatar
Martin Bauer committed
162
    def __init__(self, body, ghost_layers=None, function_name="kernel", backend=""):
163
164
        super(KernelFunction, self).__init__()
        self._body = body
165
        body.parent = self
Martin Bauer's avatar
Martin Bauer committed
166
        self.function_name = function_name
167
        self._body.parent = self
Martin Bauer's avatar
Martin Bauer committed
168
        self.compile = None
Martin Bauer's avatar
Martin Bauer committed
169
        self.ghost_layers = ghost_layers
170
        # these variables are assumed to be global, so no automatic parameter is generated for them
Martin Bauer's avatar
Martin Bauer committed
171
        self.global_variables = set()
172
        self.backend = backend
Martin Bauer's avatar
Martin Bauer committed
173
        self.instruction_set = None  # used in `vectorize` function to tell the backend which i.s. (SSE,AVX) to use
174
175

    @property
Martin Bauer's avatar
Martin Bauer committed
176
    def symbols_defined(self):
177
178
179
        return set()

    @property
Martin Bauer's avatar
Martin Bauer committed
180
    def undefined_symbols(self):
181
182
183
184
185
186
187
188
        return set()

    @property
    def body(self):
        return self._body

    @property
    def args(self):
Jan Hoenig's avatar
Jan Hoenig committed
189
        return [self._body]
190

191
    @property
192
    def fields_accessed(self) -> Set['ResolvedFieldAccess']:
193
        """Set of Field instances: fields which are accessed inside this kernel function"""
Martin Bauer's avatar
Martin Bauer committed
194
        return set(o.field for o in self.atoms(ResolvedFieldAccess))
195

196
197
198
199
200
    def get_parameters(self) -> Sequence['KernelFunction.Parameter']:
        """Returns list of parameters for this function.

        This function is expensive, cache the result where possible!
        """
201
        field_map = {f.name: f for f in self.fields_accessed}
202
203
204
205
206
207
208

        def get_fields(symbol):
            if hasattr(symbol, 'field_name'):
                return field_map[symbol.field_name],
            elif hasattr(symbol, 'field_names'):
                return tuple(field_map[fn] for fn in symbol.field_names)
            return ()
209

210
211
212
213
        argument_symbols = self._body.undefined_symbols - self.global_variables
        parameters = [self.Parameter(symbol, get_fields(symbol)) for symbol in argument_symbols]
        parameters.sort(key=lambda p: p.symbol.name)
        return parameters
214

215
    def __str__(self):
216
217
        params = [p.symbol for p in self.get_parameters()]
        return '{0} {1}({2})\n{3}'.format(type(self).__name__, self.function_name, params,
Michael Kuron's avatar
Michael Kuron committed
218
                                          ("\t" + "\t".join(str(self.body).splitlines(True))))
219
220

    def __repr__(self):
221
222
        params = [p.symbol for p in self.get_parameters()]
        return '{0} {1}({2})'.format(type(self).__name__, self.function_name, params)
223

224
225

class Block(Node):
Martin Bauer's avatar
Martin Bauer committed
226
227
228
    def __init__(self, nodes: List[Node]):
        super(Block, self).__init__()
        self._nodes = nodes
229
        self.parent = None
230
231
232
233
234
235
236
        for n in self._nodes:
            n.parent = self

    @property
    def args(self):
        return self._nodes

Martin Bauer's avatar
Martin Bauer committed
237
238
239
240
241
242
243
244
245
246
247
248
    def subs(self, subs_dict) -> None:
        new_args = []
        for a in self.args:
            if isinstance(a, SympyAssignment) and a.is_declaration and a.rhs in subs_dict.keys():
                subs_dict[a.lhs] = subs_dict[a.rhs]
            else:
                new_args.append(a)
        self._nodes = new_args

        for a in self.args:
            a.subs(subs_dict)

Martin Bauer's avatar
Martin Bauer committed
249
    def insert_front(self, node):
250
251
252
        node.parent = self
        self._nodes.insert(0, node)

Martin Bauer's avatar
Martin Bauer committed
253
254
255
    def insert_before(self, new_node, insert_before):
        new_node.parent = self
        idx = self._nodes.index(insert_before)
256
257

        # move all assignment (definitions to the top)
Martin Bauer's avatar
Martin Bauer committed
258
        if isinstance(new_node, SympyAssignment) and new_node.is_declaration:
Martin Bauer's avatar
Martin Bauer committed
259
260
261
262
263
264
            while idx > 0:
                pn = self._nodes[idx - 1]
                if isinstance(pn, LoopOverCoordinate) or isinstance(pn, Conditional):
                    idx -= 1
                else:
                    break
Martin Bauer's avatar
Martin Bauer committed
265
        self._nodes.insert(idx, new_node)
Martin Bauer's avatar
Martin Bauer committed
266

267
    def append(self, node):
268
269
270
271
272
273
274
        if isinstance(node, list) or isinstance(node, tuple):
            for n in node:
                n.parent = self
                self._nodes.append(n)
        else:
            node.parent = self
            self._nodes.append(node)
275

Martin Bauer's avatar
Martin Bauer committed
276
    def take_child_nodes(self):
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
        tmp = self._nodes
        self._nodes = []
        return tmp

    def replace(self, child, replacements):
        idx = self._nodes.index(child)
        del self._nodes[idx]
        if type(replacements) is list:
            for e in replacements:
                e.parent = self
            self._nodes = self._nodes[:idx] + replacements + self._nodes[idx:]
        else:
            replacements.parent = self
            self._nodes.insert(idx, replacements)

    @property
Martin Bauer's avatar
Martin Bauer committed
293
    def symbols_defined(self):
294
295
        result = set()
        for a in self.args:
Martin Bauer's avatar
Martin Bauer committed
296
            result.update(a.symbols_defined)
297
298
299
        return result

    @property
Martin Bauer's avatar
Martin Bauer committed
300
    def undefined_symbols(self):
301
        result = set()
Martin Bauer's avatar
Martin Bauer committed
302
        defined_symbols = set()
303
        for a in self.args:
Martin Bauer's avatar
Martin Bauer committed
304
305
            result.update(a.undefined_symbols)
            defined_symbols.update(a.symbols_defined)
Martin Bauer's avatar
Martin Bauer committed
306
        return result - defined_symbols
307

308
    def __str__(self):
Martin Bauer's avatar
Martin Bauer committed
309
        return "Block " + ''.join('{!s}\n'.format(node) for node in self._nodes)
310
311

    def __repr__(self):
Martin Bauer's avatar
Martin Bauer committed
312
        return "Block"
313

314
315

class PragmaBlock(Block):
Martin Bauer's avatar
Martin Bauer committed
316
317
    def __init__(self, pragma_line, nodes):
        super(PragmaBlock, self).__init__(nodes)
Martin Bauer's avatar
Martin Bauer committed
318
        self.pragma_line = pragma_line
Martin Bauer's avatar
Martin Bauer committed
319
        for n in nodes:
Martin Bauer's avatar
Martin Bauer committed
320
321
322
            n.parent = self

    def __repr__(self):
Martin Bauer's avatar
Martin Bauer committed
323
        return self.pragma_line
324
325
326
327
328


class LoopOverCoordinate(Node):
    LOOP_COUNTER_NAME_PREFIX = "ctr"

Martin Bauer's avatar
Martin Bauer committed
329
330
    def __init__(self, body, coordinate_to_loop_over, start, stop, step=1):
        super(LoopOverCoordinate, self).__init__(parent=None)
331
        self.body = body
332
        body.parent = self
Martin Bauer's avatar
Martin Bauer committed
333
        self.coordinate_to_loop_over = coordinate_to_loop_over
334
335
336
337
        self.start = start
        self.stop = stop
        self.step = step
        self.body.parent = self
Martin Bauer's avatar
Martin Bauer committed
338
        self.prefix_lines = []
339

Martin Bauer's avatar
Martin Bauer committed
340
    def new_loop_with_different_body(self, new_body):
Martin Bauer's avatar
Martin Bauer committed
341
342
        result = LoopOverCoordinate(new_body, self.coordinate_to_loop_over, self.start, self.stop, self.step)
        result.prefix_lines = [l for l in self.prefix_lines]
343
344
        return result

Martin Bauer's avatar
Martin Bauer committed
345
346
    def subs(self, subs_dict):
        self.body.subs(subs_dict)
347
        if hasattr(self.start, "subs"):
Martin Bauer's avatar
Martin Bauer committed
348
            self.start = self.start.subs(subs_dict)
349
        if hasattr(self.stop, "subs"):
Martin Bauer's avatar
Martin Bauer committed
350
            self.stop = self.stop.subs(subs_dict)
351
        if hasattr(self.step, "subs"):
Martin Bauer's avatar
Martin Bauer committed
352
            self.step = self.step.subs(subs_dict)
353

354
355
    @property
    def args(self):
356
357
        result = [self.body]
        for e in [self.start, self.stop, self.step]:
Martin Bauer's avatar
Martin Bauer committed
358
359
            if hasattr(e, "args"):
                result.append(e)
360
361
        return result

362
363
364
365
366
367
368
369
370
371
    def replace(self, child, replacement):
        if child == self.body:
            self.body = replacement
        elif child == self.start:
            self.start = replacement
        elif child == self.step:
            self.step = replacement
        elif child == self.stop:
            self.stop = replacement

372
    @property
Martin Bauer's avatar
Martin Bauer committed
373
374
    def symbols_defined(self):
        return {self.loop_counter_symbol}
375
376

    @property
Martin Bauer's avatar
Martin Bauer committed
377
378
    def undefined_symbols(self):
        result = self.body.undefined_symbols
Martin Bauer's avatar
Martin Bauer committed
379
380
381
        for possible_symbol in [self.start, self.stop, self.step]:
            if isinstance(possible_symbol, Node) or isinstance(possible_symbol, sp.Basic):
                result.update(possible_symbol.atoms(sp.Symbol))
Martin Bauer's avatar
Martin Bauer committed
382
        return result - {self.loop_counter_symbol}
383

Martin Bauer's avatar
Martin Bauer committed
384
    @staticmethod
Martin Bauer's avatar
Martin Bauer committed
385
386
    def get_loop_counter_name(coordinate_to_loop_over):
        return "%s_%s" % (LoopOverCoordinate.LOOP_COUNTER_NAME_PREFIX, coordinate_to_loop_over)
Martin Bauer's avatar
Martin Bauer committed
387

388
    @property
Martin Bauer's avatar
Martin Bauer committed
389
    def loop_counter_name(self):
Martin Bauer's avatar
Martin Bauer committed
390
        return LoopOverCoordinate.get_loop_counter_name(self.coordinate_to_loop_over)
Martin Bauer's avatar
Martin Bauer committed
391

392
    @staticmethod
Martin Bauer's avatar
Martin Bauer committed
393
    def is_loop_counter_symbol(symbol):
394
395
396
        prefix = LoopOverCoordinate.LOOP_COUNTER_NAME_PREFIX
        if not symbol.name.startswith(prefix):
            return None
Martin Bauer's avatar
Martin Bauer committed
397
        if symbol.dtype != create_type('int'):
398
            return None
Martin Bauer's avatar
Martin Bauer committed
399
        coordinate = int(symbol.name[len(prefix) + 1:])
400
401
        return coordinate

Martin Bauer's avatar
Martin Bauer committed
402
    @staticmethod
Martin Bauer's avatar
Martin Bauer committed
403
404
    def get_loop_counter_symbol(coordinate_to_loop_over):
        return TypedSymbol(LoopOverCoordinate.get_loop_counter_name(coordinate_to_loop_over), 'int')
405
406

    @property
Martin Bauer's avatar
Martin Bauer committed
407
    def loop_counter_symbol(self):
Martin Bauer's avatar
Martin Bauer committed
408
        return LoopOverCoordinate.get_loop_counter_symbol(self.coordinate_to_loop_over)
409
410

    @property
Martin Bauer's avatar
Martin Bauer committed
411
    def is_outermost_loop(self):
Martin Bauer's avatar
Martin Bauer committed
412
413
        from pystencils.transformations import get_next_parent_of_type
        return get_next_parent_of_type(self, LoopOverCoordinate) is None
414
415

    @property
Martin Bauer's avatar
Martin Bauer committed
416
    def is_innermost_loop(self):
Martin Bauer's avatar
Martin Bauer committed
417
        return len(self.atoms(LoopOverCoordinate)) == 0
418

419
    def __str__(self):
Martin Bauer's avatar
Martin Bauer committed
420
421
422
        return 'for({!s}={!s}; {!s}<{!s}; {!s}+={!s})\n{!s}'.format(self.loop_counter_name, self.start,
                                                                    self.loop_counter_name, self.stop,
                                                                    self.loop_counter_name, self.step,
423
                                                                    ("\t" + "\t".join(str(self.body).splitlines(True))))
424
425

    def __repr__(self):
Martin Bauer's avatar
Martin Bauer committed
426
427
428
        return 'for({!s}={!s}; {!s}<{!s}; {!s}+={!s})'.format(self.loop_counter_name, self.start,
                                                              self.loop_counter_name, self.stop,
                                                              self.loop_counter_name, self.step)
429

430
431

class SympyAssignment(Node):
Martin Bauer's avatar
Martin Bauer committed
432
433
    def __init__(self, lhs_symbol, rhs_expr, is_const=True):
        super(SympyAssignment, self).__init__(parent=None)
Martin Bauer's avatar
Martin Bauer committed
434
        self._lhs_symbol = lhs_symbol
Martin Bauer's avatar
Martin Bauer committed
435
        self.rhs = rhs_expr
Martin Bauer's avatar
Martin Bauer committed
436
        self._is_const = is_const
Martin Bauer's avatar
Martin Bauer committed
437
438
439
440
441
442
443
444
        self._is_declaration = self.__is_declaration()

    def __is_declaration(self):
        if isinstance(self._lhs_symbol, cast_func):
            return False
        if any(isinstance(self._lhs_symbol, c) for c in (Field.Access, sp.Indexed, TemporaryMemoryAllocation)):
            return False
        return True
445
446
447

    @property
    def lhs(self):
Martin Bauer's avatar
Martin Bauer committed
448
        return self._lhs_symbol
449
450

    @lhs.setter
Martin Bauer's avatar
Martin Bauer committed
451
    def lhs(self, new_value):
Martin Bauer's avatar
Martin Bauer committed
452
        self._lhs_symbol = new_value
Martin Bauer's avatar
Martin Bauer committed
453
        self._is_declaration = self.__is_declaration()
454

Martin Bauer's avatar
Martin Bauer committed
455
456
457
    def subs(self, subs_dict):
        self.lhs = fast_subs(self.lhs, subs_dict)
        self.rhs = fast_subs(self.rhs, subs_dict)
458

459
460
    @property
    def args(self):
Martin Bauer's avatar
Martin Bauer committed
461
        return [self._lhs_symbol, self.rhs]
462
463

    @property
Martin Bauer's avatar
Martin Bauer committed
464
    def symbols_defined(self):
Martin Bauer's avatar
Martin Bauer committed
465
        if not self._is_declaration:
466
            return set()
Martin Bauer's avatar
Martin Bauer committed
467
        return {self._lhs_symbol}
468
469

    @property
Martin Bauer's avatar
Martin Bauer committed
470
    def undefined_symbols(self):
471
        result = self.rhs.atoms(sp.Symbol)
472
        # Add loop counters if there a field accesses
Martin Bauer's avatar
Martin Bauer committed
473
        loop_counters = set()
474
475
476
        for symbol in result:
            if isinstance(symbol, Field.Access):
                for i in range(len(symbol.offsets)):
Martin Bauer's avatar
Martin Bauer committed
477
478
                    loop_counters.add(LoopOverCoordinate.get_loop_counter_symbol(i))
        result.update(loop_counters)
Martin Bauer's avatar
Martin Bauer committed
479
        result.update(self._lhs_symbol.atoms(sp.Symbol))
480
481
482
        return result

    @property
Martin Bauer's avatar
Martin Bauer committed
483
    def is_declaration(self):
Martin Bauer's avatar
Martin Bauer committed
484
        return self._is_declaration
485
486

    @property
Martin Bauer's avatar
Martin Bauer committed
487
    def is_const(self):
Martin Bauer's avatar
Martin Bauer committed
488
        return self._is_const
489

Jan Hoenig's avatar
Jan Hoenig committed
490
491
    def replace(self, child, replacement):
        if child == self.lhs:
492
493
            replacement.parent = self
            self.lhs = replacement
Jan Hoenig's avatar
Jan Hoenig committed
494
495
496
497
498
499
        elif child == self.rhs:
            replacement.parent = self
            self.rhs = replacement
        else:
            raise ValueError('%s is not in args of %s' % (replacement, self.__class__))

500
    def __repr__(self):
501
        return repr(self.lhs) + " ← " + repr(self.rhs)
502

Martin Bauer's avatar
Martin Bauer committed
503
504
505
    def _repr_html_(self):
        printed_lhs = sp.latex(self.lhs)
        printed_rhs = sp.latex(self.rhs)
506
        return "${printed_lhs} \leftarrow {printed_rhs}$".format(printed_lhs=printed_lhs, printed_rhs=printed_rhs)
Martin Bauer's avatar
Martin Bauer committed
507

508

Martin Bauer's avatar
Martin Bauer committed
509
class ResolvedFieldAccess(sp.Indexed):
Martin Bauer's avatar
Martin Bauer committed
510
    def __new__(cls, base, linearized_index, field, offsets, idx_coordinate_values):
Martin Bauer's avatar
Martin Bauer committed
511
512
        if not isinstance(base, IndexedBase):
            base = IndexedBase(base, shape=(1,))
Martin Bauer's avatar
Martin Bauer committed
513
        obj = super(ResolvedFieldAccess, cls).__new__(cls, base, linearized_index)
Martin Bauer's avatar
Martin Bauer committed
514
515
        obj.field = field
        obj.offsets = offsets
Martin Bauer's avatar
Martin Bauer committed
516
        obj.idx_coordinate_values = idx_coordinate_values
Martin Bauer's avatar
Martin Bauer committed
517
518
519
520
521
        return obj

    def _eval_subs(self, old, new):
        return ResolvedFieldAccess(self.args[0],
                                   self.args[1].subs(old, new),
Martin Bauer's avatar
Martin Bauer committed
522
                                   self.field, self.offsets, self.idx_coordinate_values)
Martin Bauer's avatar
Martin Bauer committed
523

Martin Bauer's avatar
Martin Bauer committed
524
525
526
527
528
    def fast_subs(self, substitutions):
        if self in substitutions:
            return substitutions[self]
        return ResolvedFieldAccess(self.args[0].subs(substitutions),
                                   self.args[1].subs(substitutions),
Martin Bauer's avatar
Martin Bauer committed
529
                                   self.field, self.offsets, self.idx_coordinate_values)
Martin Bauer's avatar
Martin Bauer committed
530
531

    def _hashable_content(self):
Martin Bauer's avatar
Martin Bauer committed
532
        super_class_contents = super(ResolvedFieldAccess, self)._hashable_content()
Martin Bauer's avatar
Martin Bauer committed
533
        return super_class_contents + tuple(self.offsets) + (repr(self.idx_coordinate_values), hash(self.field))
Martin Bauer's avatar
Martin Bauer committed
534
535

    @property
Martin Bauer's avatar
Martin Bauer committed
536
    def typed_symbol(self):
Martin Bauer's avatar
Martin Bauer committed
537
538
539
540
        return self.base.label

    def __str__(self):
        top = super(ResolvedFieldAccess, self).__str__()
Martin Bauer's avatar
Martin Bauer committed
541
        return "%s (%s)" % (top, self.typed_symbol.dtype)
Martin Bauer's avatar
Martin Bauer committed
542
543

    def __getnewargs__(self):
Martin Bauer's avatar
Martin Bauer committed
544
        return self.base, self.indices[0], self.field, self.offsets, self.idx_coordinate_values
Martin Bauer's avatar
Martin Bauer committed
545
546


547
class TemporaryMemoryAllocation(Node):
Martin Bauer's avatar
Martin Bauer committed
548
549
550
551
552
553
554
555
556
557
    """Node for temporary memory buffer allocation.

    Always allocates aligned memory.

    Args:
        typed_symbol: symbol used as pointer (has to be typed)
        size: number of elements to allocate
        align_offset: the align_offset's element is aligned
    """
    def __init__(self, typed_symbol: TypedSymbol, size, align_offset):
Martin Bauer's avatar
Martin Bauer committed
558
559
        super(TemporaryMemoryAllocation, self).__init__(parent=None)
        self.symbol = typed_symbol
560
        self.size = size
Martin Bauer's avatar
Martin Bauer committed
561
562
        self.headers = ['<stdlib.h>']
        self._align_offset = align_offset
563
564

    @property
Martin Bauer's avatar
Martin Bauer committed
565
566
    def symbols_defined(self):
        return {self.symbol}
567
568

    @property
Martin Bauer's avatar
Martin Bauer committed
569
    def undefined_symbols(self):
570
571
572
573
        if isinstance(self.size, sp.Basic):
            return self.size.atoms(sp.Symbol)
        else:
            return set()
574
575
576

    @property
    def args(self):
577
        return [self.symbol]
578

Martin Bauer's avatar
Martin Bauer committed
579
580
581
582
583
584
    def offset(self, byte_alignment):
        """Number of ELEMENTS to skip for a pointer that is aligned to byte_alignment."""
        np_dtype = self.symbol.dtype.base_type.numpy_dtype
        assert byte_alignment % np_dtype.itemsize == 0
        return -self._align_offset % (byte_alignment / np_dtype.itemsize)

585
586

class TemporaryMemoryFree(Node):
Martin Bauer's avatar
Martin Bauer committed
587
    def __init__(self, alloc_node):
Martin Bauer's avatar
Martin Bauer committed
588
        super(TemporaryMemoryFree, self).__init__(parent=None)
Martin Bauer's avatar
Martin Bauer committed
589
590
591
592
593
594
595
596
        self.alloc_node = alloc_node

    @property
    def symbol(self):
        return self.alloc_node.symbol

    def offset(self, byte_alignment):
        return self.alloc_node.offset(byte_alignment)
597
598

    @property
Martin Bauer's avatar
Martin Bauer committed
599
    def symbols_defined(self):
600
601
602
        return set()

    @property
Martin Bauer's avatar
Martin Bauer committed
603
    def undefined_symbols(self):
604
605
606
607
608
        return set()

    @property
    def args(self):
        return []