transformations.py 36.4 KB
Newer Older
1
from collections import defaultdict, OrderedDict
2
from copy import deepcopy
Jan Hoenig's avatar
Jan Hoenig committed
3

4
5
import sympy as sp
from sympy.logic.boolalg import Boolean
6
from sympy.tensor import IndexedBase
Martin Bauer's avatar
Martin Bauer committed
7

8
from pystencils.assignment import Assignment
Martin Bauer's avatar
Martin Bauer committed
9
10
11
from pystencils.field import Field, FieldType, offset_component_to_direction_string
from pystencils.data_types import TypedSymbol, create_type, PointerType, StructType, get_base_type, cast_func
from pystencils.slicing import normalize_slice
Martin Bauer's avatar
Martin Bauer committed
12
import pystencils.astnodes as ast
13
14


Martin Bauer's avatar
Martin Bauer committed
15
def filtered_tree_iteration(node, node_type):
16
    for arg in node.args:
Martin Bauer's avatar
Martin Bauer committed
17
        if isinstance(arg, node_type):
18
            yield arg
Martin Bauer's avatar
Martin Bauer committed
19
        yield from filtered_tree_iteration(arg, node_type)
20
21


Martin Bauer's avatar
Martin Bauer committed
22
def get_common_shape(field_set):
23
24
    """Takes a set of pystencils Fields and returns their common spatial shape if it exists. Otherwise
    ValueError is raised"""
Martin Bauer's avatar
Martin Bauer committed
25
26
27
28
29
30
31
32
    nr_of_fixed_shaped_fields = 0
    for f in field_set:
        if f.has_fixed_shape:
            nr_of_fixed_shaped_fields += 1

    if nr_of_fixed_shaped_fields > 0 and nr_of_fixed_shaped_fields != len(field_set):
        fixed_field_names = ",".join([f.name for f in field_set if f.has_fixed_shape])
        var_field_names = ",".join([f.name for f in field_set if not f.has_fixed_shape])
33
        msg = "Mixing fixed-shaped and variable-shape fields in a single kernel is not possible\n"
Martin Bauer's avatar
Martin Bauer committed
34
        msg += "Variable shaped: %s \nFixed shaped:    %s" % (var_field_names, fixed_field_names)
35
36
        raise ValueError(msg)

Martin Bauer's avatar
Martin Bauer committed
37
38
39
40
    shape_set = set([f.spatial_shape for f in field_set])
    if nr_of_fixed_shaped_fields == len(field_set):
        if len(shape_set) != 1:
            raise ValueError("Differently sized field accesses in loop body: " + str(shape_set))
41

Martin Bauer's avatar
Martin Bauer committed
42
    shape = list(sorted(shape_set, key=lambda e: str(e[0])))[0]
43
44
45
    return shape


Martin Bauer's avatar
Martin Bauer committed
46
47
48
49
50
51
52
53
54
55
56
57
58
59
def make_loop_over_domain(body, function_name, iteration_slice=None, ghost_layers=None, loop_order=None):
    """Uses :class:`pystencils.field.Field.Access` to create (multiple) loops around given AST.

    Args:
        body: list of nodes
        function_name: name of generated C function
        iteration_slice: if not None, iteration is done only over this slice of the field
        ghost_layers: a sequence of pairs for each coordinate with lower and upper nr of ghost layers
             if None, the number of ghost layers is determined automatically and assumed to be equal for a
             all dimensions
        loop_order: loop ordering from outer to inner loop (optimal ordering is same as layout)

    Returns:
        :class:`LoopOverCoordinate` instance with nested loops, ordered according to field layouts
60
61
    """
    # find correct ordering by inspecting participating FieldAccesses
Martin Bauer's avatar
Martin Bauer committed
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
    field_accesses = body.atoms(Field.Access)
    # exclude accesses to buffers from field_list, because buffers are treated separately
    field_list = [e.field for e in field_accesses if not FieldType.is_buffer(e.field)]
    fields = set(field_list)
    num_buffer_accesses = len(field_accesses) - len(field_list)

    if loop_order is None:
        loop_order = get_optimal_loop_ordering(fields)

    shape = get_common_shape(list(fields))

    if iteration_slice is not None:
        iteration_slice = normalize_slice(iteration_slice, shape)

    if ghost_layers is None:
        required_ghost_layers = max([fa.required_ghost_layers for fa in field_accesses])
        ghost_layers = [(required_ghost_layers, required_ghost_layers)] * len(loop_order)
    if isinstance(ghost_layers, int):
        ghost_layers = [(ghost_layers, ghost_layers)] * len(loop_order)

    def get_loop_stride(loop_begin, loop_end, step):
        return (loop_end - loop_begin) / step

    loop_strides = []
    loop_vars = []
    current_body = body
Martin Bauer's avatar
Martin Bauer committed
88
    for i, loop_coordinate in enumerate(reversed(loop_order)):
Martin Bauer's avatar
Martin Bauer committed
89
        if iteration_slice is None:
Martin Bauer's avatar
Martin Bauer committed
90
91
92
            begin = ghost_layers[loop_coordinate][0]
            end = shape[loop_coordinate] - ghost_layers[loop_coordinate][1]
            new_loop = ast.LoopOverCoordinate(current_body, loop_coordinate, begin, end, 1)
Martin Bauer's avatar
Martin Bauer committed
93
94
95
            current_body = ast.Block([new_loop])
            loop_strides.append(get_loop_stride(begin, end, 1))
            loop_vars.append(new_loop.loop_counter_symbol)
Martin Bauer's avatar
Martin Bauer committed
96
        else:
Martin Bauer's avatar
Martin Bauer committed
97
            slice_component = iteration_slice[loop_coordinate]
Martin Bauer's avatar
Martin Bauer committed
98
99
            if type(slice_component) is slice:
                sc = slice_component
Martin Bauer's avatar
Martin Bauer committed
100
                new_loop = ast.LoopOverCoordinate(current_body, loop_coordinate, sc.start, sc.stop, sc.step)
Martin Bauer's avatar
Martin Bauer committed
101
102
103
                current_body = ast.Block([new_loop])
                loop_strides.append(get_loop_stride(sc.start, sc.stop, sc.step))
                loop_vars.append(new_loop.loop_counter_symbol)
Martin Bauer's avatar
Martin Bauer committed
104
            else:
Martin Bauer's avatar
Martin Bauer committed
105
                assignment = ast.SympyAssignment(ast.LoopOverCoordinate.get_loop_counter_symbol(loop_coordinate),
Martin Bauer's avatar
Martin Bauer committed
106
107
                                                 sp.sympify(slice_component))
                current_body.insert_front(assignment)
108

Martin Bauer's avatar
Martin Bauer committed
109
110
111
    loop_vars = [num_buffer_accesses * var for var in loop_vars]
    ast_node = ast.KernelFunction(current_body, ghost_layers=ghost_layers, function_name=function_name, backend='cpu')
    return ast_node, loop_strides, loop_vars
112
113


Martin Bauer's avatar
Martin Bauer committed
114
def create_intermediate_base_pointer(field_access, coordinates, previous_ptr):
Martin Bauer's avatar
Martin Bauer committed
115
116
117
118
119
120
    r"""
    Addressing elements in structured arrays are done with :math:`ptr\left[ \sum_i c_i \cdot s_i \right]`
    where :math:`c_i` is the coordinate value and :math:`s_i` the stride of a coordinate.
    The sum can be split up into multiple parts, such that parts of it can be pulled before loops.
    This function creates such an access for coordinates :math:`i \in \mbox{coordinates}`.
    Returns a new typed symbol, where the name encodes which coordinates have been resolved.
Martin Bauer's avatar
Martin Bauer committed
121
    :param field_access: instance of :class:`pystencils.field.Field.Access` which provides strides and offsets
Martin Bauer's avatar
Martin Bauer committed
122
    :param coordinates: mapping of coordinate ids to its value, where stride*value is calculated
Martin Bauer's avatar
Martin Bauer committed
123
    :param previous_ptr: the pointer which is de-referenced
Martin Bauer's avatar
Martin Bauer committed
124
125
126
    :return: tuple with the new pointer symbol and the calculated offset

    Example:
Martin Bauer's avatar
Martin Bauer committed
127
        >>> field = Field.create_generic('myfield', spatial_dimensions=2, index_dimensions=1)
Martin Bauer's avatar
Martin Bauer committed
128
        >>> x, y = sp.symbols("x y")
Martin Bauer's avatar
Martin Bauer committed
129
130
        >>> prev_pointer = TypedSymbol("ptr", "double")
        >>> create_intermediate_base_pointer(field[1,-2](5), {0: x}, prev_pointer)
Martin Bauer's avatar
Martin Bauer committed
131
        (ptr_E, x*fstride_myfield[0] + fstride_myfield[0])
Martin Bauer's avatar
Martin Bauer committed
132
        >>> create_intermediate_base_pointer(field[1,-2](5), {0: x, 1 : y }, prev_pointer)
Martin Bauer's avatar
Martin Bauer committed
133
134
        (ptr_E_2S, x*fstride_myfield[0] + y*fstride_myfield[1] + fstride_myfield[0] - 2*fstride_myfield[1])
    """
Martin Bauer's avatar
Martin Bauer committed
135
    field = field_access.field
136
137
    offset = 0
    name = ""
Martin Bauer's avatar
Martin Bauer committed
138
    list_to_hash = []
Martin Bauer's avatar
Martin Bauer committed
139
140
    for coordinate_id, coordinate_value in coordinates.items():
        offset += field.strides[coordinate_id] * coordinate_value
141

Martin Bauer's avatar
Martin Bauer committed
142
143
144
145
        if coordinate_id < field.spatial_dimensions:
            offset += field.strides[coordinate_id] * field_access.offsets[coordinate_id]
            if type(field_access.offsets[coordinate_id]) is int:
                offset_comp = offset_component_to_direction_string(coordinate_id, field_access.offsets[coordinate_id])
146
                name += "_"
Martin Bauer's avatar
Martin Bauer committed
147
                name += offset_comp if offset_comp else "C"
148
            else:
Martin Bauer's avatar
Martin Bauer committed
149
                list_to_hash.append(field_access.offsets[coordinate_id])
150
        else:
Martin Bauer's avatar
Martin Bauer committed
151
152
            if type(coordinate_value) is int:
                name += "_%d" % (coordinate_value,)
153
            else:
Martin Bauer's avatar
Martin Bauer committed
154
                list_to_hash.append(coordinate_value)
155

Martin Bauer's avatar
Martin Bauer committed
156
157
    if len(list_to_hash) > 0:
        name += "%0.6X" % (abs(hash(tuple(list_to_hash))))
158

Martin Bauer's avatar
Martin Bauer committed
159
    new_ptr = TypedSymbol(previous_ptr.name + name, previous_ptr.dtype)
160

Martin Bauer's avatar
Martin Bauer committed
161
    return new_ptr, offset
162
163


Martin Bauer's avatar
Martin Bauer committed
164
def parse_base_pointer_info(base_pointer_specification, loop_order, field):
165
    """
Martin Bauer's avatar
Martin Bauer committed
166
    Creates base pointer specification for :func:`resolve_field_accesses` function.
Martin Bauer's avatar
Martin Bauer committed
167
168
169
170
171
172

    Specification of how many and which intermediate pointers are created for a field access.
    For example [ (0), (2,3,)]  creates on base pointer for coordinates 2 and 3 and writes the offset for coordinate
    zero directly in the field access. These specifications are more sensible defined dependent on the loop ordering.
    This function translates more readable version into the specification above.

173
    Allowed specifications:
Martin Bauer's avatar
Martin Bauer committed
174
175
176
177
178
179
        - "spatialInner<int>" spatialInner0 is the innermost loop coordinate,
          spatialInner1 the loop enclosing the innermost
        - "spatialOuter<int>" spatialOuter0 is the outermost loop
        - "index<int>": index coordinate
        - "<int>": specifying directly the coordinate

Martin Bauer's avatar
Martin Bauer committed
180
181
182
183
184
185
186
    Args:
        base_pointer_specification: nested list with above specifications
        loop_order: list with ordering of loops from outer to inner
        field:

    Returns:
        list of tuples that can be passed to :func:`resolve_field_accesses`
187
188
    """
    result = []
Martin Bauer's avatar
Martin Bauer committed
189
190
    specified_coordinates = set()
    loop_order = list(reversed(loop_order))
Martin Bauer's avatar
Martin Bauer committed
191
    for spec_group in base_pointer_specification:
Martin Bauer's avatar
Martin Bauer committed
192
193
194
195
196
197
198
199
200
        new_group = []

        def add_new_element(elem):
            if elem >= field.spatial_dimensions + field.index_dimensions:
                raise ValueError("Coordinate %d does not exist" % (elem,))
            new_group.append(elem)
            if elem in specified_coordinates:
                raise ValueError("Coordinate %d specified two times" % (elem,))
            specified_coordinates.add(elem)
Martin Bauer's avatar
Martin Bauer committed
201
        for element in spec_group:
202
            if type(element) is int:
Martin Bauer's avatar
Martin Bauer committed
203
                add_new_element(element)
204
205
206
207
            elif element.startswith("spatial"):
                element = element[len("spatial"):]
                if element.startswith("Inner"):
                    index = int(element[len("Inner"):])
Martin Bauer's avatar
Martin Bauer committed
208
                    add_new_element(loop_order[index])
209
210
                elif element.startswith("Outer"):
                    index = int(element[len("Outer"):])
Martin Bauer's avatar
Martin Bauer committed
211
                    add_new_element(loop_order[-index])
212
                elif element == "all":
Martin Bauer's avatar
Martin Bauer committed
213
214
                    for i in range(field.spatial_dimensions):
                        add_new_element(i)
215
216
217
218
                else:
                    raise ValueError("Could not parse " + element)
            elif element.startswith("index"):
                index = int(element[len("index"):])
Martin Bauer's avatar
Martin Bauer committed
219
                add_new_element(field.spatial_dimensions + index)
220
221
222
            else:
                raise ValueError("Unknown specification %s" % (element,))

Martin Bauer's avatar
Martin Bauer committed
223
        result.append(new_group)
224

Martin Bauer's avatar
Martin Bauer committed
225
226
    all_coordinates = set(range(field.spatial_dimensions + field.index_dimensions))
    rest = all_coordinates - specified_coordinates
227
228
    if rest:
        result.append(list(rest))
229

230
231
232
    return result


Martin Bauer's avatar
Martin Bauer committed
233
234
def substitute_array_accesses_with_constants(ast_node):
    """Substitutes all instances of Indexed (array accesses) that are not field accesses with constants.
235
236
237
238
239
240
    Benchmarks showed that using an array access as loop bound or in pointer computations cause some compilers to do 
    less optimizations.  
    This transformation should be after field accesses have been resolved (since they introduce array accesses) and 
    before constants are moved before the loops.
    """

Martin Bauer's avatar
Martin Bauer committed
241
    def handle_sympy_expression(expr, parent_block):
242
243
244
245
246
247
        """Returns sympy expression where array accesses have been replaced with constants, together with a list
        of assignments that define these constants"""
        if not isinstance(expr, sp.Expr):
            return expr

        # get all indexed expressions that are not field accesses
Martin Bauer's avatar
Martin Bauer committed
248
        indexed_expressions = [e for e in expr.atoms(sp.Indexed) if not isinstance(e, ast.ResolvedFieldAccess)]
249
250

        # special case: right hand side is a single indexed expression, then nothing has to be done
Martin Bauer's avatar
Martin Bauer committed
251
        if len(indexed_expressions) == 1 and expr == indexed_expressions[0]:
252
253
            return expr

Martin Bauer's avatar
Martin Bauer committed
254
255
        constants_definitions = []
        constant_substitutions = {}
Martin Bauer's avatar
Martin Bauer committed
256
257
        for indexed_expr in indexed_expressions:
            base, idx = indexed_expr.args
Martin Bauer's avatar
Martin Bauer committed
258
259
260
261
            typed_symbol = base.args[0]
            base_type = deepcopy(get_base_type(typed_symbol.dtype))
            base_type.const = False
            constant_replacing_indexed = TypedSymbol(typed_symbol.name + str(idx), base_type)
Martin Bauer's avatar
Martin Bauer committed
262
263
            constants_definitions.append(ast.SympyAssignment(constant_replacing_indexed, indexed_expr))
            constant_substitutions[indexed_expr] = constant_replacing_indexed
Martin Bauer's avatar
Martin Bauer committed
264
265
266
        constants_definitions.sort(key=lambda e: e.lhs.name)

        already_defined = parent_block.symbols_defined
Martin Bauer's avatar
Martin Bauer committed
267
268
269
        for new_assignment in constants_definitions:
            if new_assignment.lhs not in already_defined:
                parent_block.insert_before(new_assignment, ast_node)
Martin Bauer's avatar
Martin Bauer committed
270
271
272
273
274
275
276
277
278
279
280

        return expr.subs(constant_substitutions)

    if isinstance(ast_node, ast.SympyAssignment):
        ast_node.rhs = handle_sympy_expression(ast_node.rhs, ast_node.parent)
        ast_node.lhs = handle_sympy_expression(ast_node.lhs, ast_node.parent)
    elif isinstance(ast_node, ast.LoopOverCoordinate):
        ast_node.start = handle_sympy_expression(ast_node.start, ast_node.parent)
        ast_node.stop = handle_sympy_expression(ast_node.stop, ast_node.parent)
        ast_node.step = handle_sympy_expression(ast_node.step, ast_node.parent)
        substitute_array_accesses_with_constants(ast_node.body)
281
    else:
Martin Bauer's avatar
Martin Bauer committed
282
283
        for a in ast_node.args:
            substitute_array_accesses_with_constants(a)
284

Martin Bauer's avatar
Martin Bauer committed
285

Martin Bauer's avatar
Martin Bauer committed
286
287
def resolve_buffer_accesses(ast_node, base_buffer_index, read_only_field_names=set()):
    def visit_sympy_expr(expr, enclosing_block, sympy_assignment):
288
        if isinstance(expr, Field.Access):
Martin Bauer's avatar
Martin Bauer committed
289
            field_access = expr
290
291

            # Do not apply transformation if field is not a buffer
Martin Bauer's avatar
Martin Bauer committed
292
            if not FieldType.is_buffer(field_access.field):
293
294
                return expr

Martin Bauer's avatar
Martin Bauer committed
295
            buffer = field_access.field
296

Martin Bauer's avatar
Martin Bauer committed
297
298
            dtype = PointerType(buffer.dtype, const=buffer.name in read_only_field_names, restrict=True)
            field_ptr = TypedSymbol("%s%s" % (Field.DATA_PREFIX, symbol_name_to_variable_name(buffer.name)), dtype)
299

Martin Bauer's avatar
Martin Bauer committed
300
301
            buffer_index = base_buffer_index
            if len(field_access.index) > 1:
302
303
                raise RuntimeError('Only indexing dimensions up to 1 are currently supported in buffers!')

Martin Bauer's avatar
Martin Bauer committed
304
305
306
            if len(field_access.index) > 0:
                cell_index = field_access.index[0]
                buffer_index += cell_index
307

Martin Bauer's avatar
Martin Bauer committed
308
309
            result = ast.ResolvedFieldAccess(field_ptr, buffer_index, field_access.field, field_access.offsets,
                                             field_access.index)
310

Martin Bauer's avatar
Martin Bauer committed
311
            return visit_sympy_expr(result, enclosing_block, sympy_assignment)
312
313
314
315
        else:
            if isinstance(expr, ast.ResolvedFieldAccess):
                return expr

Martin Bauer's avatar
Martin Bauer committed
316
            new_args = [visit_sympy_expr(e, enclosing_block, sympy_assignment) for e in expr.args]
317
            kwargs = {'evaluate': False} if type(expr) in (sp.Add, sp.Mul, sp.Piecewise) else {}
Martin Bauer's avatar
Martin Bauer committed
318
319
320
321
322
323
324
325
            return expr.func(*new_args, **kwargs) if new_args else expr

    def visit_node(sub_ast):
        if isinstance(sub_ast, ast.SympyAssignment):
            enclosing_block = sub_ast.parent
            assert type(enclosing_block) is ast.Block
            sub_ast.lhs = visit_sympy_expr(sub_ast.lhs, enclosing_block, sub_ast)
            sub_ast.rhs = visit_sympy_expr(sub_ast.rhs, enclosing_block, sub_ast)
326
        else:
Martin Bauer's avatar
Martin Bauer committed
327
328
            for i, a in enumerate(sub_ast.args):
                visit_node(a)
329

Martin Bauer's avatar
Martin Bauer committed
330
    return visit_node(ast_node)
331

332

Martin Bauer's avatar
Martin Bauer committed
333
334
def resolve_field_accesses(ast_node, read_only_field_names=set(),
                           field_to_base_pointer_info={}, field_to_fixed_coordinates={}):
Martin Bauer's avatar
Martin Bauer committed
335
336
337
    """
    Substitutes :class:`pystencils.field.Field.Access` nodes by array indexing

Martin Bauer's avatar
Martin Bauer committed
338
339
    :param ast_node: the AST root
    :param read_only_field_names: set of field names which are considered read-only
Martin Bauer's avatar
Martin Bauer committed
340
    :param field_to_base_pointer_info: a list of tuples indicating which intermediate base pointers should be created
Martin Bauer's avatar
Martin Bauer committed
341
                                   for details see :func:`parse_base_pointer_info`
Martin Bauer's avatar
Martin Bauer committed
342
    :param field_to_fixed_coordinates: map of field name to a tuple of coordinate symbols. Instead of using the loop
Martin Bauer's avatar
Martin Bauer committed
343
344
345
                                    counters to index the field these symbols are used as coordinates
    :return: transformed AST
    """
Martin Bauer's avatar
Martin Bauer committed
346
347
    field_to_base_pointer_info = OrderedDict(sorted(field_to_base_pointer_info.items(), key=lambda pair: pair[0]))
    field_to_fixed_coordinates = OrderedDict(sorted(field_to_fixed_coordinates.items(), key=lambda pair: pair[0]))
348

Martin Bauer's avatar
Martin Bauer committed
349
    def visit_sympy_expr(expr, enclosing_block, sympy_assignment):
350
        if isinstance(expr, Field.Access):
Martin Bauer's avatar
Martin Bauer committed
351
352
            field_access = expr
            field = field_access.field
353

Martin Bauer's avatar
Martin Bauer committed
354
355
            if field.name in field_to_base_pointer_info:
                base_pointer_info = field_to_base_pointer_info[field.name]
356
            else:
Martin Bauer's avatar
Martin Bauer committed
357
                base_pointer_info = [list(range(field.index_dimensions + field.spatial_dimensions))]
358

Martin Bauer's avatar
Martin Bauer committed
359
360
            dtype = PointerType(field.dtype, const=field.name in read_only_field_names, restrict=True)
            field_ptr = TypedSymbol("%s%s" % (Field.DATA_PREFIX, symbol_name_to_variable_name(field.name)), dtype)
361

Martin Bauer's avatar
Martin Bauer committed
362
363
364
365
            def create_coordinate_dict(group_param):
                coordinates = {}
                for e in group_param:
                    if e < field.spatial_dimensions:
Martin Bauer's avatar
Martin Bauer committed
366
                        if field.name in field_to_fixed_coordinates:
Martin Bauer's avatar
Martin Bauer committed
367
                            coordinates[e] = field_to_fixed_coordinates[field.name][e]
368
                        else:
Martin Bauer's avatar
Martin Bauer committed
369
                            ctr_name = ast.LoopOverCoordinate.LOOP_COUNTER_NAME_PREFIX
Martin Bauer's avatar
Martin Bauer committed
370
371
                            coordinates[e] = TypedSymbol("%s_%d" % (ctr_name, e), 'int')
                        coordinates[e] *= field.dtype.item_size
372
                    else:
373
                        if isinstance(field.dtype, StructType):
Martin Bauer's avatar
Martin Bauer committed
374
                            assert field.index_dimensions == 1
Martin Bauer's avatar
Martin Bauer committed
375
376
                            accessed_field_name = field_access.index[0]
                            assert isinstance(accessed_field_name, str)
Martin Bauer's avatar
Martin Bauer committed
377
                            coordinates[e] = field.dtype.get_element_offset(accessed_field_name)
378
                        else:
Martin Bauer's avatar
Martin Bauer committed
379
                            coordinates[e] = field_access.index[e - field.spatial_dimensions]
380

Martin Bauer's avatar
Martin Bauer committed
381
                return coordinates
382

Martin Bauer's avatar
Martin Bauer committed
383
            last_pointer = field_ptr
384

Martin Bauer's avatar
Martin Bauer committed
385
386
            for group in reversed(base_pointer_info[1:]):
                coord_dict = create_coordinate_dict(group)
Martin Bauer's avatar
Martin Bauer committed
387
                new_ptr, offset = create_intermediate_base_pointer(field_access, coord_dict, last_pointer)
Martin Bauer's avatar
Martin Bauer committed
388
389
390
391
                if new_ptr not in enclosing_block.symbols_defined:
                    new_assignment = ast.SympyAssignment(new_ptr, last_pointer + offset, is_const=False)
                    enclosing_block.insert_before(new_assignment, sympy_assignment)
                last_pointer = new_ptr
392

Martin Bauer's avatar
Martin Bauer committed
393
            coord_dict = create_coordinate_dict(base_pointer_info[0])
394

Martin Bauer's avatar
Martin Bauer committed
395
            _, offset = create_intermediate_base_pointer(field_access, coord_dict, last_pointer)
Martin Bauer's avatar
Martin Bauer committed
396
397
            result = ast.ResolvedFieldAccess(last_pointer, offset, field_access.field,
                                             field_access.offsets, field_access.index)
398

Martin Bauer's avatar
Martin Bauer committed
399
400
            if isinstance(get_base_type(field_access.field.dtype), StructType):
                new_type = field_access.field.dtype.get_element_type(field_access.index[0])
Martin Bauer's avatar
Martin Bauer committed
401
                result = cast_func(result, new_type)
402

Martin Bauer's avatar
Martin Bauer committed
403
            return visit_sympy_expr(result, enclosing_block, sympy_assignment)
404
        else:
Martin Bauer's avatar
Martin Bauer committed
405
406
            if isinstance(expr, ast.ResolvedFieldAccess):
                return expr
407

Martin Bauer's avatar
Martin Bauer committed
408
            new_args = [visit_sympy_expr(e, enclosing_block, sympy_assignment) for e in expr.args]
409
            kwargs = {'evaluate': False} if type(expr) in (sp.Add, sp.Mul, sp.Piecewise) else {}
Martin Bauer's avatar
Martin Bauer committed
410
411
412
413
414
415
416
417
            return expr.func(*new_args, **kwargs) if new_args else expr

    def visit_node(sub_ast):
        if isinstance(sub_ast, ast.SympyAssignment):
            enclosing_block = sub_ast.parent
            assert type(enclosing_block) is ast.Block
            sub_ast.lhs = visit_sympy_expr(sub_ast.lhs, enclosing_block, sub_ast)
            sub_ast.rhs = visit_sympy_expr(sub_ast.rhs, enclosing_block, sub_ast)
418
        else:
Martin Bauer's avatar
Martin Bauer committed
419
420
            for i, a in enumerate(sub_ast.args):
                visit_node(a)
421

Martin Bauer's avatar
Martin Bauer committed
422
    return visit_node(ast_node)
423
424


Martin Bauer's avatar
Martin Bauer committed
425
def move_constants_before_loop(ast_node):
Martin Bauer's avatar
Martin Bauer committed
426
427
    """
    Moves :class:`pystencils.ast.SympyAssignment` nodes out of loop body if they are iteration independent.
Martin Bauer's avatar
Martin Bauer committed
428
429
    Call this after creating the loop structure with :func:`make_loop_over_domain`
    :param ast_node:
Martin Bauer's avatar
Martin Bauer committed
430
431
    :return:
    """
Martin Bauer's avatar
Martin Bauer committed
432
    def find_block_to_move_to(node):
Martin Bauer's avatar
Martin Bauer committed
433
434
        """
        Traverses parents of node as long as the symbols are independent and returns a (parent) block
435
        the assignment can be safely moved to
Martin Bauer's avatar
Martin Bauer committed
436
437
438
        :param node: SympyAssignment inside a Block
        :return blockToInsertTo, childOfBlockToInsertBefore
        """
439
440
441
        assert isinstance(node, ast.SympyAssignment)
        assert isinstance(node.parent, ast.Block)

Martin Bauer's avatar
Martin Bauer committed
442
443
        last_block = node.parent
        last_block_child = node
444
        element = node.parent
Martin Bauer's avatar
Martin Bauer committed
445
        prev_element = node
446
447
        while element:
            if isinstance(element, ast.Block):
Martin Bauer's avatar
Martin Bauer committed
448
449
                last_block = element
                last_block_child = prev_element
450
451

            if isinstance(element, ast.Conditional):
Martin Bauer's avatar
Martin Bauer committed
452
                critical_symbols = element.condition_expr.atoms(sp.Symbol)
453
            else:
Martin Bauer's avatar
Martin Bauer committed
454
455
                critical_symbols = element.symbols_defined
            if node.undefined_symbols.intersection(critical_symbols):
456
                break
Martin Bauer's avatar
Martin Bauer committed
457
            prev_element = element
458
            element = element.parent
Martin Bauer's avatar
Martin Bauer committed
459
        return last_block, last_block_child
460

Martin Bauer's avatar
Martin Bauer committed
461
462
    def check_if_assignment_already_in_block(assignment, target_block):
        for arg in target_block.args:
463
464
465
466
467
468
            if type(arg) is not ast.SympyAssignment:
                continue
            if arg.lhs == assignment.lhs:
                return arg
        return None

Martin Bauer's avatar
Martin Bauer committed
469
    def get_blocks(node, result_list):
470
        if isinstance(node, ast.Block):
Martin Bauer's avatar
Martin Bauer committed
471
            result_list.insert(0, node)
472
473
        if isinstance(node, ast.Node):
            for a in node.args:
Martin Bauer's avatar
Martin Bauer committed
474
                get_blocks(a, result_list)
475

Martin Bauer's avatar
Martin Bauer committed
476
477
478
    all_blocks = []
    get_blocks(ast_node, all_blocks)
    for block in all_blocks:
Martin Bauer's avatar
Martin Bauer committed
479
        children = block.take_child_nodes()
480
481
482
483
        for child in children:
            if not isinstance(child, ast.SympyAssignment):
                block.append(child)
            else:
Martin Bauer's avatar
Martin Bauer committed
484
                target, child_to_insert_before = find_block_to_move_to(child)
485
486
487
                if target == block:     # movement not possible
                    target.append(child)
                else:
Martin Bauer's avatar
Martin Bauer committed
488
489
490
                    existing_assignment = check_if_assignment_already_in_block(child, target)
                    if not existing_assignment:
                        target.insert_before(child, child_to_insert_before)
491
                    else:
Martin Bauer's avatar
Martin Bauer committed
492
                        assert existing_assignment.rhs == child.rhs, "Symbol with same name exists already"
493
494


Martin Bauer's avatar
Martin Bauer committed
495
def split_inner_loop(ast_node: ast.Node, symbol_groups):
Martin Bauer's avatar
Martin Bauer committed
496
497
    """
    Splits inner loop into multiple loops to minimize the amount of simultaneous load/store streams
498

Martin Bauer's avatar
Martin Bauer committed
499
500
501
502
503
    Args:
        ast_node: AST root
        symbol_groups: sequence of symbol sequences: for each symbol sequence a new inner loop is created which
                       updates these symbols and their dependent symbols. Symbols which are in none of the symbolGroups
                       and which no symbol in a symbol group depends on, are not updated!
Martin Bauer's avatar
Martin Bauer committed
504
    """
Martin Bauer's avatar
Martin Bauer committed
505
506
507
508
509
510
511
512
513
514
515
516
517
    all_loops = ast_node.atoms(ast.LoopOverCoordinate)
    inner_loop = [l for l in all_loops if l.is_innermost_loop]
    assert len(inner_loop) == 1, "Error in AST: multiple innermost loops. Was split transformation already called?"
    inner_loop = inner_loop[0]
    assert type(inner_loop.body) is ast.Block
    outer_loop = [l for l in all_loops if l.is_outermost_loop]
    assert len(outer_loop) == 1, "Error in AST, multiple outermost loops."
    outer_loop = outer_loop[0]

    symbols_with_temporary_array = OrderedDict()
    assignment_map = OrderedDict((a.lhs, a) for a in inner_loop.body.args)

    assignment_groups = []
Martin Bauer's avatar
Martin Bauer committed
518
    for symbol_group in symbol_groups:
519
        # get all dependent symbols
Martin Bauer's avatar
Martin Bauer committed
520
        symbols_to_process = list(symbol_group)
Martin Bauer's avatar
Martin Bauer committed
521
522
523
524
        symbols_resolved = set()
        while symbols_to_process:
            s = symbols_to_process.pop()
            if s in symbols_resolved:
525
526
                continue

Martin Bauer's avatar
Martin Bauer committed
527
            if s in assignment_map:  # if there is no assignment inside the loop body it is independent already
Martin Bauer's avatar
Martin Bauer committed
528
529
530
                for new_symbol in assignment_map[s].rhs.atoms(sp.Symbol):
                    if type(new_symbol) is not Field.Access and new_symbol not in symbols_with_temporary_array:
                        symbols_to_process.append(new_symbol)
Martin Bauer's avatar
Martin Bauer committed
531
            symbols_resolved.add(s)
532

Martin Bauer's avatar
Martin Bauer committed
533
        for symbol in symbol_group:
534
535
            if type(symbol) is not Field.Access:
                assert type(symbol) is TypedSymbol
Martin Bauer's avatar
Martin Bauer committed
536
537
                new_ts = TypedSymbol(symbol.name, PointerType(symbol.dtype))
                symbols_with_temporary_array[symbol] = IndexedBase(new_ts, shape=(1,))[inner_loop.loop_counter_symbol]
538

Martin Bauer's avatar
Martin Bauer committed
539
540
541
542
        assignment_group = []
        for assignment in inner_loop.body.args:
            if assignment.lhs in symbols_resolved:
                new_rhs = assignment.rhs.subs(symbols_with_temporary_array.items())
Martin Bauer's avatar
Martin Bauer committed
543
                if type(assignment.lhs) is not Field.Access and assignment.lhs in symbol_group:
544
                    assert type(assignment.lhs) is TypedSymbol
Martin Bauer's avatar
Martin Bauer committed
545
546
                    new_ts = TypedSymbol(assignment.lhs.name, PointerType(assignment.lhs.dtype))
                    new_lhs = IndexedBase(new_ts, shape=(1,))[inner_loop.loop_counter_symbol]
547
                else:
Martin Bauer's avatar
Martin Bauer committed
548
549
550
                    new_lhs = assignment.lhs
                assignment_group.append(ast.SympyAssignment(new_lhs, new_rhs))
        assignment_groups.append(assignment_group)
551

Martin Bauer's avatar
Martin Bauer committed
552
553
    new_loops = [inner_loop.new_loop_with_different_body(ast.Block(group)) for group in assignment_groups]
    inner_loop.parent.replace(inner_loop, ast.Block(new_loops))
554

Martin Bauer's avatar
Martin Bauer committed
555
556
    for tmp_array in symbols_with_temporary_array:
        tmp_array_pointer = TypedSymbol(tmp_array.name, PointerType(tmp_array.dtype))
Martin Bauer's avatar
Martin Bauer committed
557
558
        outer_loop.parent.insert_front(ast.TemporaryMemoryAllocation(tmp_array_pointer, inner_loop.stop))
        outer_loop.parent.append(ast.TemporaryMemoryFree(tmp_array_pointer))
559
560


Martin Bauer's avatar
Martin Bauer committed
561
def cut_loop(loop_node, cutting_points):
562
    """Cuts loop at given cutting points, that means one loop is transformed into len(cuttingPoints)+1 new loops
Martin Bauer's avatar
Martin Bauer committed
563
    that range from  old_begin to cutting_points[1], ..., cutting_points[-1] to old_end"""
Martin Bauer's avatar
Martin Bauer committed
564
    if loop_node.step != 1:
565
        raise NotImplementedError("Can only split loops that have a step of 1")
Martin Bauer's avatar
Martin Bauer committed
566
567
568
    new_loops = []
    new_start = loop_node.start
    cutting_points = list(cutting_points) + [loop_node.stop]
Martin Bauer's avatar
Martin Bauer committed
569
570
    for new_end in cutting_points:
        if new_end - new_start == 1:
Martin Bauer's avatar
Martin Bauer committed
571
572
573
            new_body = deepcopy(loop_node.body)
            new_body.subs({loop_node.loop_counter_symbol: new_start})
            new_loops.append(new_body)
574
        else:
Martin Bauer's avatar
Martin Bauer committed
575
576
            new_loop = ast.LoopOverCoordinate(deepcopy(loop_node.body), loop_node.coordinate_to_loop_over,
                                              new_start, new_end, loop_node.step)
Martin Bauer's avatar
Martin Bauer committed
577
            new_loops.append(new_loop)
Martin Bauer's avatar
Martin Bauer committed
578
        new_start = new_end
Martin Bauer's avatar
Martin Bauer committed
579
    loop_node.parent.replace(loop_node, new_loops)
580
581


Martin Bauer's avatar
Martin Bauer committed
582
def is_condition_necessary(condition, pre_condition, symbol):
583
584
585
586
    """
    Determines if a logical condition of a single variable is already contained in a stronger preCondition
    so if from preCondition follows that condition is always true, then this condition is not necessary
    :param condition: sympy relational of one variable
Martin Bauer's avatar
Martin Bauer committed
587
    :param pre_condition: logical expression that is known to be true
588
589
590
591
592
593
    :param symbol: the single symbol of interest
    :return: returns  not (preCondition => condition) where "=>" is logical implication
    """
    from sympy.solvers.inequalities import reduce_rational_inequalities
    from sympy.logic.boolalg import to_dnf

Martin Bauer's avatar
Martin Bauer committed
594
    def to_dnf_list(expr):
595
596
        result = to_dnf(expr)
        if isinstance(result, sp.Or):
Martin Bauer's avatar
Martin Bauer committed
597
            return [or_term.args for or_term in result.args]
598
599
600
601
602
        elif isinstance(result, sp.And):
            return [result.args]
        else:
            return result

Martin Bauer's avatar
Martin Bauer committed
603
604
    t1 = reduce_rational_inequalities(to_dnf_list(sp.And(condition, pre_condition)), symbol)
    t2 = reduce_rational_inequalities(to_dnf_list(pre_condition), symbol)
605
606
607
    return t1 != t2


Martin Bauer's avatar
Martin Bauer committed
608
def simplify_boolean_expression(expr, single_variable_ranges):
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
    """Simplification of boolean expression using known ranges of variables
    The singleVariableRanges parameter is a dict mapping a variable name to a sympy logical expression that
    contains only this variable and defines a range for it. For example with a being a symbol
    { a: sp.And(a >=0, a < 10) }
    """
    from sympy.core.relational import Relational
    from sympy.logic.boolalg import to_dnf

    expr = to_dnf(expr)

    def visit(e):
        if isinstance(e, Relational):
            symbols = e.atoms(sp.Symbol)
            if len(symbols) == 1:
                symbol = symbols.pop()
Martin Bauer's avatar
Martin Bauer committed
624
625
                if symbol in single_variable_ranges:
                    if not is_condition_necessary(e, single_variable_ranges[symbol], symbol):
626
627
628
                        return sp.true
            return e
        else:
Martin Bauer's avatar
Martin Bauer committed
629
630
            new_args = [visit(a) for a in e.args]
            return e.func(*new_args) if new_args else e
631
632
633
634

    return visit(expr)


Martin Bauer's avatar
Martin Bauer committed
635
def simplify_conditionals(node, loop_conditionals={}):
636
637
    """Simplifies/Removes conditions inside loops that depend on the loop counter."""
    if isinstance(node, ast.LoopOverCoordinate):
Martin Bauer's avatar
Martin Bauer committed
638
639
640
641
        ctr_sym = node.loop_counter_symbol
        loop_conditionals[ctr_sym] = sp.And(ctr_sym >= node.start, ctr_sym < node.stop)
        simplify_conditionals(node.body)
        del loop_conditionals[ctr_sym]
642
    elif isinstance(node, ast.Conditional):
Martin Bauer's avatar
Martin Bauer committed
643
644
645
646
647
648
649
650
        node.condition_expr = simplify_boolean_expression(node.condition_expr, loop_conditionals)
        simplify_conditionals(node.true_block)
        if node.false_block:
            simplify_conditionals(node.false_block)
        if node.condition_expr == sp.true:
            node.parent.replace(node, [node.true_block])
        if node.condition_expr == sp.false:
            node.parent.replace(node, [node.false_block] if node.false_block else [])
651
652
    elif isinstance(node, ast.Block):
        for a in list(node.args):
Martin Bauer's avatar
Martin Bauer committed
653
            simplify_conditionals(a)
654
655
656
657
658
659
    elif isinstance(node, ast.SympyAssignment):
        return node
    else:
        raise ValueError("Can not handle node", type(node))


Martin Bauer's avatar
Martin Bauer committed
660
def cleanup_blocks(node):
661
662
663
664
665
    """Curly Brace Removal: Removes empty blocks, and replaces blocks with a single child by its child """
    if isinstance(node, ast.SympyAssignment):
        return
    elif isinstance(node, ast.Block):
        for a in list(node.args):
Martin Bauer's avatar
Martin Bauer committed
666
            cleanup_blocks(a)
667
668
669
670
671
        if len(node.args) <= 1 and isinstance(node.parent, ast.Block):
            node.parent.replace(node, node.args)
            return
    else:
        for a in node.args:
Martin Bauer's avatar
Martin Bauer committed
672
            cleanup_blocks(a)
673
674


Martin Bauer's avatar
Martin Bauer committed
675
def symbol_name_to_variable_name(symbol_name):
676
    """Replaces characters which are allowed in sympy symbol names but not in C/C++ variable names"""
Martin Bauer's avatar
Martin Bauer committed
677
    return symbol_name.replace("^", "_")
678
679


Martin Bauer's avatar
Martin Bauer committed
680
def type_all_equations(eqs, type_for_symbol):
Martin Bauer's avatar
Martin Bauer committed
681
682
683
684
685
    """
    Traverses AST and replaces every :class:`sympy.Symbol` by a :class:`pystencils.typedsymbol.TypedSymbol`.
    Additionally returns sets of all fields which are read/written

    :param eqs: list of equations
Martin Bauer's avatar
Martin Bauer committed
686
687
    :param type_for_symbol: dict mapping symbol names to types. Types are strings of C types like 'int' or 'double'
    :return: ``fields_read, fields_written, typed_equations`` set of read fields, set of written fields, list of equations
Martin Bauer's avatar
Martin Bauer committed
688
689
               where symbols have been replaced by typed symbols
    """
Martin Bauer's avatar
Martin Bauer committed
690
691
    if isinstance(type_for_symbol, str) or not hasattr(type_for_symbol, '__getitem__'):
        type_for_symbol = typing_from_sympy_inspection(eqs, type_for_symbol)
692

Martin Bauer's avatar
Martin Bauer committed
693
694
    fields_written = set()
    fields_read = set()
695

Martin Bauer's avatar
Martin Bauer committed
696
    def process_rhs(term):
697
698
699
700
        """Replaces Symbols by:
            - TypedSymbol if symbol is not a field access
        """
        if isinstance(term, Field.Access):
Martin Bauer's avatar
Martin Bauer committed
701
            fields_read.add(term.field)
702
            return term
703
704
        elif isinstance(term, TypedSymbol):
            return term
705
        elif isinstance(term, sp.Symbol):
Martin Bauer's avatar
Martin Bauer committed
706
            return TypedSymbol(symbol_name_to_variable_name(term.name), type_for_symbol[term.name])
707
        else:
Martin Bauer's avatar
Martin Bauer committed
708
709
            new_args = [process_rhs(arg) for arg in term.args]
            return term.func(*new_args) if new_args else term
710

Martin Bauer's avatar
Martin Bauer committed
711
    def process_lhs(term):
712
713
        """Replaces symbol by TypedSymbol and adds field to fieldsWriten"""
        if isinstance(term, Field.Access):
Martin Bauer's avatar
Martin Bauer committed
714
            fields_written.add(term.field)
715
            return term
716
717
        elif isinstance(term, TypedSymbol):
            return term
718
        elif isinstance(term, sp.Symbol):
Martin Bauer's avatar
Martin Bauer committed
719
            return TypedSymbol(term.name, type_for_symbol[term.name])
720
721
722
        else:
            assert False, "Expected a symbol as left-hand-side"

Martin Bauer's avatar
Martin Bauer committed
723
724
725
726
727
728
729
730
    def visit(obj):
        if isinstance(obj, list) or isinstance(obj, tuple):
            return [visit(e) for e in obj]
        if isinstance(obj, sp.Eq) or isinstance(obj, ast.SympyAssignment) or isinstance(obj, Assignment):
            new_lhs = process_lhs(obj.lhs)
            new_rhs = process_rhs(obj.rhs)
            return ast.SympyAssignment(new_lhs, new_rhs)
        elif isinstance(obj, ast.Conditional):
Martin Bauer's avatar
Martin Bauer committed
731
732
733
            false_block = None if obj.false_block is None else visit(obj.false_block)
            return ast.Conditional(process_rhs(obj.condition_expr),
                                   true_block=visit(obj.true_block), false_block=false_block)
Martin Bauer's avatar
Martin Bauer committed
734
735
        elif isinstance(obj, ast.Block):
            return ast.Block([visit(e) for e in obj.args])
736
        else:
Martin Bauer's avatar
Martin Bauer committed
737
            return obj
738

Martin Bauer's avatar
Martin Bauer committed
739
    typed_equations = visit(eqs)
740

Martin Bauer's avatar
Martin Bauer committed
741
    return fields_read, fields_written, typed_equations
742
743


Martin Bauer's avatar
Martin Bauer committed
744
745
746
# --------------------------------------- Helper Functions -------------------------------------------------------------


Martin Bauer's avatar
Martin Bauer committed
747
def typing_from_sympy_inspection(eqs, default_type="double"):
Martin Bauer's avatar
Martin Bauer committed
748
749
750
751
    """
    Creates a default symbol name to type mapping.
    If a sympy Boolean is assigned to a symbol it is assumed to be 'bool' otherwise the default type, usually ('double')
    :param eqs: list of equations
Martin Bauer's avatar
Martin Bauer committed
752
    :param default_type: the type for non-boolean symbols
Martin Bauer's avatar
Martin Bauer committed
753
754
    :return: dictionary, mapping symbol name to type
    """
Martin Bauer's avatar
Martin Bauer committed
755
    result = defaultdict(lambda: default_type)
756
    for eq in eqs:
757
758
        if isinstance(eq, ast.Node):
            continue
759
760
761
        # problematic case here is when rhs is a symbol: then it is impossible to decide here without
        # further information what type the left hand side is - default fallback is the dict value then
        if isinstance(eq.rhs, Boolean) and not isinstance(eq.rhs, sp.Symbol):
762
763
764
765
            result[eq.lhs.name] = "bool"
    return result


Martin Bauer's avatar
Martin Bauer committed
766
def get_next_parent_of_type(node, parent_type):
Martin Bauer's avatar
Martin Bauer committed
767
768
769
    """
    Traverses the AST nodes parents until a parent of given type was found. If no such parent is found, None is returned
    """
770
771
    parent = node.parent
    while parent is not None:
Martin Bauer's avatar
Martin Bauer committed
772
        if isinstance(parent, parent_type):
773
774
775
776
777
            return parent
        parent = parent.parent
    return None


Martin Bauer's avatar
Martin Bauer committed
778
def get_optimal_loop_ordering(fields):
Martin Bauer's avatar
Martin Bauer committed
779
780
781
782
    """
    Determines the optimal loop order for a given set of fields.
    If the fields have different memory layout or different sizes an exception is thrown.
    :param fields: sequence of fields
783
    :return: list of coordinate ids, where the first list entry should be the outermost loop
Martin Bauer's avatar
Martin Bauer committed
784
    """
785
    assert len(fields) > 0
Martin Bauer's avatar
Martin Bauer committed
786
    ref_field = next(iter(fields))
787
    for field in fields:
Martin Bauer's avatar
Martin Bauer committed
788
        if field.spatial_dimensions != ref_field.spatial_dimensions:
789
            raise ValueError("All fields have to have the same number of spatial dimensions. Spatial field dimensions: "
Martin Bauer's avatar
Martin Bauer committed
790
                             + str({f.name: f.spatial_shape for f in fields}))
791
792
793

    layouts = set([field.layout for field in fields])
    if len(layouts) > 1:
794
795
        raise ValueError("Due to different layout of the fields no optimal loop ordering exists " +
                         str({f.name: f.layout for f in fields}))
796
    layout = list(layouts)[0]
797
    return list(layout)
798
799


Martin Bauer's avatar
Martin Bauer committed
800
def get_loop_hierarchy(ast_node):
Martin Bauer's avatar
Martin Bauer committed
801
    """Determines the loop structure around a given AST node.
Martin Bauer's avatar
Martin Bauer committed
802
    :param ast_node: the AST node
Martin Bauer's avatar
Martin Bauer committed
803
804
    :return: list of coordinate ids, where the first list entry is the innermost loop
    """
805
    result = []
Martin Bauer's avatar
Martin Bauer committed
806
    node = ast_node
807
    while node is not None:
Martin Bauer's avatar
Martin Bauer committed
808
        node = get_next_parent_of_type(node, ast.LoopOverCoordinate)
809
        if node:
Martin Bauer's avatar
Martin Bauer committed
810
            result.append(node.coordinate_to_loop_over)
811
    return reversed(result)