astnodes.py 18.6 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
Martin Bauer's avatar
Martin Bauer committed
5
from pystencils.sympyextensions import fast_subs
Martin Bauer's avatar
Martin Bauer committed
6
7
8
from typing import List, Set, Optional, Union, Any

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


11
class Node(object):
Martin Bauer's avatar
Martin Bauer committed
12
    """Base class for all AST nodes."""
Martin Bauer's avatar
Martin Bauer committed
13

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

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

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

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

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

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

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


51
class Conditional(Node):
Martin Bauer's avatar
Martin Bauer committed
52
53
54
55
56
57
58
59
60
61
62
    """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
63
64
    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
65
66
67
        super(Conditional, self).__init__(parent=None)

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

        def handle_child(c):
71
72
73
74
75
76
77
            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
78
79
        self.true_block = handle_child(true_block)
        self.false_block = handle_child(false_block)
80
81

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

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

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

    @property
Martin Bauer's avatar
Martin Bauer committed
99
    def undefined_symbols(self):
Martin Bauer's avatar
Martin Bauer committed
100
101
102
103
        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))
104
105
106
        return result

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

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


113
114
115
class KernelFunction(Node):

    class Argument:
Martin Bauer's avatar
Martin Bauer committed
116
        def __init__(self, name, dtype, symbol, kernel_function_node):
Martin Bauer's avatar
Martin Bauer committed
117
            from pystencils.transformations import symbol_name_to_variable_name
118
            self.name = name
119
            self.dtype = dtype
Martin Bauer's avatar
Martin Bauer committed
120
121
122
123
            self.is_field_ptr_argument = False
            self.is_field_shape_argument = False
            self.is_field_stride_argument = False
            self.is_field_argument = False
Martin Bauer's avatar
Martin Bauer committed
124
            self.field_name = ""
125
            self.coordinate = None
126
            self.symbol = symbol
127
128

            if name.startswith(Field.DATA_PREFIX):
Martin Bauer's avatar
Martin Bauer committed
129
130
                self.is_field_ptr_argument = True
                self.is_field_argument = True
Martin Bauer's avatar
Martin Bauer committed
131
                self.field_name = name[len(Field.DATA_PREFIX):]
132
            elif name.startswith(Field.SHAPE_PREFIX):
Martin Bauer's avatar
Martin Bauer committed
133
134
                self.is_field_shape_argument = True
                self.is_field_argument = True
Martin Bauer's avatar
Martin Bauer committed
135
                self.field_name = name[len(Field.SHAPE_PREFIX):]
136
            elif name.startswith(Field.STRIDE_PREFIX):
Martin Bauer's avatar
Martin Bauer committed
137
138
                self.is_field_stride_argument = True
                self.is_field_argument = True
Martin Bauer's avatar
Martin Bauer committed
139
                self.field_name = name[len(Field.STRIDE_PREFIX):]
140

141
            self.field = None
Martin Bauer's avatar
Martin Bauer committed
142
            if self.is_field_argument:
Martin Bauer's avatar
Martin Bauer committed
143
144
                field_map = {symbol_name_to_variable_name(f.name): f for f in kernel_function_node.fields_accessed}
                self.field = field_map[self.field_name]
145

146
147
        def __lt__(self, other):
            def score(l):
Martin Bauer's avatar
Martin Bauer committed
148
                if l.is_field_ptr_argument:
149
                    return -4
Martin Bauer's avatar
Martin Bauer committed
150
                elif l.is_field_shape_argument:
151
                    return -3
Martin Bauer's avatar
Martin Bauer committed
152
                elif l.is_field_stride_argument:
153
154
155
156
157
158
159
160
161
162
                    return -2
                return 0

            if score(self) < score(other):
                return True
            elif score(self) == score(other):
                return self.name < other.name
            else:
                return False

163
164
165
        def __repr__(self):
            return '<{0} {1}>'.format(self.dtype, self.name)

Martin Bauer's avatar
Martin Bauer committed
166
    def __init__(self, body, ghost_layers=None, function_name="kernel", backend=""):
167
168
        super(KernelFunction, self).__init__()
        self._body = body
169
        body.parent = self
170
        self._parameters = None
Martin Bauer's avatar
Martin Bauer committed
171
        self.function_name = function_name
172
        self._body.parent = self
Martin Bauer's avatar
Martin Bauer committed
173
        self.compile = None
Martin Bauer's avatar
Martin Bauer committed
174
        self.ghost_layers = ghost_layers
175
        # these variables are assumed to be global, so no automatic parameter is generated for them
Martin Bauer's avatar
Martin Bauer committed
176
        self.global_variables = set()
177
        self.backend = backend
178
179

    @property
Martin Bauer's avatar
Martin Bauer committed
180
    def symbols_defined(self):
181
182
183
        return set()

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

    @property
    def parameters(self):
Martin Bauer's avatar
Martin Bauer committed
189
        self._update_parameters()
190
191
192
193
194
195
196
197
        return self._parameters

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

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

200
    @property
Martin Bauer's avatar
Martin Bauer committed
201
    def fields_accessed(self):
202
        """Set of Field instances: fields which are accessed inside this kernel function"""
Martin Bauer's avatar
Martin Bauer committed
203
        return set(o.field for o in self.atoms(ResolvedFieldAccess))
204

Martin Bauer's avatar
Martin Bauer committed
205
    def _update_parameters(self):
Martin Bauer's avatar
Martin Bauer committed
206
        undefined_symbols = self._body.undefined_symbols - self.global_variables
Martin Bauer's avatar
Martin Bauer committed
207
        self._parameters = [KernelFunction.Argument(s.name, s.dtype, s, self) for s in undefined_symbols]
208
209

        self._parameters.sort()
210

211
    def __str__(self):
Martin Bauer's avatar
Martin Bauer committed
212
        self._update_parameters()
Martin Bauer's avatar
Martin Bauer committed
213
        return '{0} {1}({2})\n{3}'.format(type(self).__name__, self.function_name, self.parameters,
Michael Kuron's avatar
Michael Kuron committed
214
                                          ("\t" + "\t".join(str(self.body).splitlines(True))))
215
216

    def __repr__(self):
Martin Bauer's avatar
Martin Bauer committed
217
        self._update_parameters()
Martin Bauer's avatar
Martin Bauer committed
218
        return '{0} {1}({2})'.format(type(self).__name__, self.function_name, self.parameters)
219

220
221

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

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

Martin Bauer's avatar
Martin Bauer committed
233
    def insert_front(self, node):
234
235
236
        node.parent = self
        self._nodes.insert(0, node)

Martin Bauer's avatar
Martin Bauer committed
237
238
239
    def insert_before(self, new_node, insert_before):
        new_node.parent = self
        idx = self._nodes.index(insert_before)
240
241

        # move all assignment (definitions to the top)
Martin Bauer's avatar
Martin Bauer committed
242
        if isinstance(new_node, SympyAssignment) and new_node.is_declaration:
Martin Bauer's avatar
Martin Bauer committed
243
244
245
246
247
248
            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
249
        self._nodes.insert(idx, new_node)
Martin Bauer's avatar
Martin Bauer committed
250

251
    def append(self, node):
252
253
254
255
256
257
258
        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)
259

Martin Bauer's avatar
Martin Bauer committed
260
    def take_child_nodes(self):
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
        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
277
    def symbols_defined(self):
278
279
        result = set()
        for a in self.args:
Martin Bauer's avatar
Martin Bauer committed
280
            result.update(a.symbols_defined)
281
282
283
        return result

    @property
Martin Bauer's avatar
Martin Bauer committed
284
    def undefined_symbols(self):
285
        result = set()
Martin Bauer's avatar
Martin Bauer committed
286
        defined_symbols = set()
287
        for a in self.args:
Martin Bauer's avatar
Martin Bauer committed
288
289
            result.update(a.undefined_symbols)
            defined_symbols.update(a.symbols_defined)
Martin Bauer's avatar
Martin Bauer committed
290
        return result - defined_symbols
291

292
    def __str__(self):
Martin Bauer's avatar
Martin Bauer committed
293
        return "Block " + ''.join('{!s}\n'.format(node) for node in self._nodes)
294
295

    def __repr__(self):
Martin Bauer's avatar
Martin Bauer committed
296
        return "Block"
297

298
299

class PragmaBlock(Block):
Martin Bauer's avatar
Martin Bauer committed
300
301
    def __init__(self, pragma_line, nodes):
        super(PragmaBlock, self).__init__(nodes)
Martin Bauer's avatar
Martin Bauer committed
302
        self.pragma_line = pragma_line
Martin Bauer's avatar
Martin Bauer committed
303
        for n in nodes:
Martin Bauer's avatar
Martin Bauer committed
304
305
306
            n.parent = self

    def __repr__(self):
Martin Bauer's avatar
Martin Bauer committed
307
        return self.pragma_line
308
309
310
311
312


class LoopOverCoordinate(Node):
    LOOP_COUNTER_NAME_PREFIX = "ctr"

Martin Bauer's avatar
Martin Bauer committed
313
314
    def __init__(self, body, coordinate_to_loop_over, start, stop, step=1):
        super(LoopOverCoordinate, self).__init__(parent=None)
315
        self.body = body
316
        body.parent = self
Martin Bauer's avatar
Martin Bauer committed
317
        self.coordinate_to_loop_over = coordinate_to_loop_over
318
319
320
321
        self.start = start
        self.stop = stop
        self.step = step
        self.body.parent = self
Martin Bauer's avatar
Martin Bauer committed
322
        self.prefix_lines = []
323

Martin Bauer's avatar
Martin Bauer committed
324
    def new_loop_with_different_body(self, new_body):
Martin Bauer's avatar
Martin Bauer committed
325
326
        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]
327
328
        return result

329
330
331
332
333
334
335
336
337
    def subs(self, *args, **kwargs):
        self.body.subs(*args, **kwargs)
        if hasattr(self.start, "subs"):
            self.start = self.start.subs(*args, **kwargs)
        if hasattr(self.stop, "subs"):
            self.stop = self.stop.subs(*args, **kwargs)
        if hasattr(self.step, "subs"):
            self.step = self.step.subs(*args, **kwargs)

338
339
    @property
    def args(self):
340
341
        result = [self.body]
        for e in [self.start, self.stop, self.step]:
Martin Bauer's avatar
Martin Bauer committed
342
343
            if hasattr(e, "args"):
                result.append(e)
344
345
        return result

346
347
348
349
350
351
352
353
354
355
    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

356
    @property
Martin Bauer's avatar
Martin Bauer committed
357
358
    def symbols_defined(self):
        return {self.loop_counter_symbol}
359
360

    @property
Martin Bauer's avatar
Martin Bauer committed
361
362
    def undefined_symbols(self):
        result = self.body.undefined_symbols
Martin Bauer's avatar
Martin Bauer committed
363
364
365
        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
366
        return result - {self.loop_counter_symbol}
367

Martin Bauer's avatar
Martin Bauer committed
368
    @staticmethod
Martin Bauer's avatar
Martin Bauer committed
369
370
    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
371

372
    @property
Martin Bauer's avatar
Martin Bauer committed
373
    def loop_counter_name(self):
Martin Bauer's avatar
Martin Bauer committed
374
        return LoopOverCoordinate.get_loop_counter_name(self.coordinate_to_loop_over)
Martin Bauer's avatar
Martin Bauer committed
375

376
    @staticmethod
Martin Bauer's avatar
Martin Bauer committed
377
    def is_loop_counter_symbol(symbol):
378
379
380
        prefix = LoopOverCoordinate.LOOP_COUNTER_NAME_PREFIX
        if not symbol.name.startswith(prefix):
            return None
Martin Bauer's avatar
Martin Bauer committed
381
        if symbol.dtype != create_type('int'):
382
            return None
Martin Bauer's avatar
Martin Bauer committed
383
        coordinate = int(symbol.name[len(prefix) + 1:])
384
385
        return coordinate

Martin Bauer's avatar
Martin Bauer committed
386
    @staticmethod
Martin Bauer's avatar
Martin Bauer committed
387
388
    def get_loop_counter_symbol(coordinate_to_loop_over):
        return TypedSymbol(LoopOverCoordinate.get_loop_counter_name(coordinate_to_loop_over), 'int')
389
390

    @property
Martin Bauer's avatar
Martin Bauer committed
391
    def loop_counter_symbol(self):
Martin Bauer's avatar
Martin Bauer committed
392
        return LoopOverCoordinate.get_loop_counter_symbol(self.coordinate_to_loop_over)
393
394

    @property
Martin Bauer's avatar
Martin Bauer committed
395
    def is_outermost_loop(self):
Martin Bauer's avatar
Martin Bauer committed
396
397
        from pystencils.transformations import get_next_parent_of_type
        return get_next_parent_of_type(self, LoopOverCoordinate) is None
398
399

    @property
Martin Bauer's avatar
Martin Bauer committed
400
    def is_innermost_loop(self):
Martin Bauer's avatar
Martin Bauer committed
401
        return len(self.atoms(LoopOverCoordinate)) == 0
402

403
    def __str__(self):
Martin Bauer's avatar
Martin Bauer committed
404
405
406
        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,
407
                                                                    ("\t" + "\t".join(str(self.body).splitlines(True))))
408
409

    def __repr__(self):
Martin Bauer's avatar
Martin Bauer committed
410
411
412
        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)
413

414
415

class SympyAssignment(Node):
Martin Bauer's avatar
Martin Bauer committed
416
417
    def __init__(self, lhs_symbol, rhs_expr, is_const=True):
        super(SympyAssignment, self).__init__(parent=None)
Martin Bauer's avatar
Martin Bauer committed
418
        self._lhs_symbol = lhs_symbol
Martin Bauer's avatar
Martin Bauer committed
419
        self.rhs = rhs_expr
Martin Bauer's avatar
Martin Bauer committed
420
421
422
423
424
        self._is_declaration = True
        is_cast = self._lhs_symbol.func == cast_func
        if isinstance(self._lhs_symbol, Field.Access) or isinstance(self._lhs_symbol, ResolvedFieldAccess) or is_cast:
            self._is_declaration = False
        self._is_const = is_const
425
426
427

    @property
    def lhs(self):
Martin Bauer's avatar
Martin Bauer committed
428
        return self._lhs_symbol
429
430

    @lhs.setter
Martin Bauer's avatar
Martin Bauer committed
431
    def lhs(self, new_value):
Martin Bauer's avatar
Martin Bauer committed
432
433
434
435
436
        self._lhs_symbol = new_value
        self._is_declaration = True
        is_cast = self._lhs_symbol.func == cast_func
        if isinstance(self._lhs_symbol, Field.Access) or isinstance(self._lhs_symbol, sp.Indexed) or is_cast:
            self._is_declaration = False
437

438
    def subs(self, *args, **kwargs):
Martin Bauer's avatar
Martin Bauer committed
439
440
        self.lhs = fast_subs(self.lhs, *args, **kwargs)
        self.rhs = fast_subs(self.rhs, *args, **kwargs)
441

442
443
    @property
    def args(self):
Martin Bauer's avatar
Martin Bauer committed
444
        return [self._lhs_symbol, self.rhs]
445
446

    @property
Martin Bauer's avatar
Martin Bauer committed
447
    def symbols_defined(self):
Martin Bauer's avatar
Martin Bauer committed
448
        if not self._is_declaration:
449
            return set()
Martin Bauer's avatar
Martin Bauer committed
450
        return {self._lhs_symbol}
451
452

    @property
Martin Bauer's avatar
Martin Bauer committed
453
    def undefined_symbols(self):
454
        result = self.rhs.atoms(sp.Symbol)
455
        # Add loop counters if there a field accesses
Martin Bauer's avatar
Martin Bauer committed
456
        loop_counters = set()
457
458
459
        for symbol in result:
            if isinstance(symbol, Field.Access):
                for i in range(len(symbol.offsets)):
Martin Bauer's avatar
Martin Bauer committed
460
461
                    loop_counters.add(LoopOverCoordinate.get_loop_counter_symbol(i))
        result.update(loop_counters)
Martin Bauer's avatar
Martin Bauer committed
462
        result.update(self._lhs_symbol.atoms(sp.Symbol))
463
464
465
        return result

    @property
Martin Bauer's avatar
Martin Bauer committed
466
    def is_declaration(self):
Martin Bauer's avatar
Martin Bauer committed
467
        return self._is_declaration
468
469

    @property
Martin Bauer's avatar
Martin Bauer committed
470
    def is_const(self):
Martin Bauer's avatar
Martin Bauer committed
471
        return self._is_const
472

Jan Hoenig's avatar
Jan Hoenig committed
473
474
    def replace(self, child, replacement):
        if child == self.lhs:
475
476
            replacement.parent = self
            self.lhs = replacement
Jan Hoenig's avatar
Jan Hoenig committed
477
478
479
480
481
482
        elif child == self.rhs:
            replacement.parent = self
            self.rhs = replacement
        else:
            raise ValueError('%s is not in args of %s' % (replacement, self.__class__))

483
    def __repr__(self):
484
        return repr(self.lhs) + " ← " + repr(self.rhs)
485

Martin Bauer's avatar
Martin Bauer committed
486
487
488
    def _repr_html_(self):
        printed_lhs = sp.latex(self.lhs)
        printed_rhs = sp.latex(self.rhs)
489
        return f"${printed_lhs} \leftarrow {printed_rhs}$"
Martin Bauer's avatar
Martin Bauer committed
490

491

Martin Bauer's avatar
Martin Bauer committed
492
class ResolvedFieldAccess(sp.Indexed):
Martin Bauer's avatar
Martin Bauer committed
493
    def __new__(cls, base, linearized_index, field, offsets, idx_coordinate_values):
Martin Bauer's avatar
Martin Bauer committed
494
495
        if not isinstance(base, IndexedBase):
            base = IndexedBase(base, shape=(1,))
Martin Bauer's avatar
Martin Bauer committed
496
        obj = super(ResolvedFieldAccess, cls).__new__(cls, base, linearized_index)
Martin Bauer's avatar
Martin Bauer committed
497
498
        obj.field = field
        obj.offsets = offsets
Martin Bauer's avatar
Martin Bauer committed
499
        obj.idx_coordinate_values = idx_coordinate_values
Martin Bauer's avatar
Martin Bauer committed
500
501
502
503
504
        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
505
                                   self.field, self.offsets, self.idx_coordinate_values)
Martin Bauer's avatar
Martin Bauer committed
506

Martin Bauer's avatar
Martin Bauer committed
507
508
509
510
511
    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
512
                                   self.field, self.offsets, self.idx_coordinate_values)
Martin Bauer's avatar
Martin Bauer committed
513
514

    def _hashable_content(self):
Martin Bauer's avatar
Martin Bauer committed
515
        super_class_contents = super(ResolvedFieldAccess, self)._hashable_content()
Martin Bauer's avatar
Martin Bauer committed
516
        return super_class_contents + tuple(self.offsets) + (repr(self.idx_coordinate_values), hash(self.field))
Martin Bauer's avatar
Martin Bauer committed
517
518

    @property
Martin Bauer's avatar
Martin Bauer committed
519
    def typed_symbol(self):
Martin Bauer's avatar
Martin Bauer committed
520
521
522
523
        return self.base.label

    def __str__(self):
        top = super(ResolvedFieldAccess, self).__str__()
Martin Bauer's avatar
Martin Bauer committed
524
        return "%s (%s)" % (top, self.typed_symbol.dtype)
Martin Bauer's avatar
Martin Bauer committed
525
526

    def __getnewargs__(self):
Martin Bauer's avatar
Martin Bauer committed
527
        return self.base, self.indices[0], self.field, self.offsets, self.idx_coordinate_values
Martin Bauer's avatar
Martin Bauer committed
528
529


530
class TemporaryMemoryAllocation(Node):
Martin Bauer's avatar
Martin Bauer committed
531
532
533
    def __init__(self, typed_symbol, size):
        super(TemporaryMemoryAllocation, self).__init__(parent=None)
        self.symbol = typed_symbol
534
535
536
        self.size = size

    @property
Martin Bauer's avatar
Martin Bauer committed
537
538
    def symbols_defined(self):
        return {self.symbol}
539
540

    @property
Martin Bauer's avatar
Martin Bauer committed
541
    def undefined_symbols(self):
542
543
544
545
        if isinstance(self.size, sp.Basic):
            return self.size.atoms(sp.Symbol)
        else:
            return set()
546
547
548

    @property
    def args(self):
549
        return [self.symbol]
550
551
552


class TemporaryMemoryFree(Node):
Martin Bauer's avatar
Martin Bauer committed
553
554
555
    def __init__(self, typed_symbol):
        super(TemporaryMemoryFree, self).__init__(parent=None)
        self.symbol = typed_symbol
556
557

    @property
Martin Bauer's avatar
Martin Bauer committed
558
    def symbols_defined(self):
559
560
561
        return set()

    @property
Martin Bauer's avatar
Martin Bauer committed
562
    def undefined_symbols(self):
563
564
565
566
567
        return set()

    @property
    def args(self):
        return []