-
Notifications
You must be signed in to change notification settings - Fork 257
Expand file tree
/
Copy pathvisitors.py
More file actions
1633 lines (1311 loc) · 54.5 KB
/
Copy pathvisitors.py
File metadata and controls
1633 lines (1311 loc) · 54.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Visitor hierarchy to inspect and/or create IETs.
The main Visitor class is adapted from https://github.com/coneoproject/COFFEE.
"""
import ctypes
from collections import OrderedDict
from collections.abc import Callable, Generator, Iterable, Iterator, Sequence
from itertools import chain, groupby
from typing import Any, Generic, TypeVar
import cgen as c
from sympy import IndexedBase
from sympy.core.function import Application
from devito.exceptions import CompilationError
from devito.ir.iet.nodes import (
BlankLine, Call, Expression, ExpressionBundle, Iteration, Lambda, ListMajor, Node,
Section
)
from devito.ir.support.space import Backward
from devito.symbolics import (
FieldFromComposite, FieldFromPointer, ListInitializer, uxreplace
)
from devito.symbolics.extended_dtypes import NoDeclStruct
from devito.tools import (
GenericVisitor, as_tuple, c_restrict_void_p, filter_ordered, filter_sorted, flatten,
is_external_ctype, sorted_priority
)
from devito.types import (
ArrayObject, CompositeObject, DeviceMap, Dimension, IndexedData, Pointer
)
from devito.types.basic import AbstractFunction, AbstractSymbol, Basic
__all__ = [
'CGen',
'CInterface',
'FindApplications',
'FindNodes',
'FindSections',
'FindSymbols',
'FindWithin',
'IsPerfectIteration',
'MapExprStmts',
'MapHaloSpots',
'MapNodes',
'Transformer',
'Uxreplace',
'printAST',
]
class Visitor(GenericVisitor):
def visit_Node(self, o, **kwargs):
return self._visit(o.children, **kwargs)
def reuse(self, o, *args, **kwargs):
"""A visit method to reuse a node, ignoring children."""
return o
def maybe_rebuild(self, o, *args, **kwargs):
"""A visit method that rebuilds nodes if their children have changed."""
ops, okwargs = o.operands()
new_ops = [self._visit(op, *args, **kwargs) for op in ops]
if all(a is b for a, b in zip(ops, new_ops, strict=True)):
return o
return o._rebuild(*new_ops, **okwargs)
def always_rebuild(self, o, *args, **kwargs):
"""A visit method that always rebuilds nodes."""
ops, okwargs = o.operands()
new_ops = [self._visit(op, *args, **kwargs) for op in ops]
return o._rebuild(*new_ops, **okwargs)
# Type variables for LazyVisitor
YieldType = TypeVar('YieldType', covariant=True)
FlagType = TypeVar('FlagType', covariant=True)
ResultType = TypeVar('ResultType', covariant=True)
# Describes the return type of a LazyVisitor visit method which yields objects of
# type YieldType and returns a FlagType (or NoneType)
LazyVisit = Generator[YieldType, None, FlagType]
class LazyVisitor(GenericVisitor, Generic[YieldType, ResultType, FlagType]):
"""
A generic visitor that lazily yields results instead of flattening results
from children at every step. Intermediate visit methods may return a flag
of type FlagType in addition to yielding results; by default, the last flag
returned by a child is the one propagated.
Subclass-defined visit methods should be generators.
"""
def lookup_method(self, instance) \
-> Callable[..., LazyVisit[YieldType, FlagType]]:
return super().lookup_method(instance)
def _visit(self, o, *args, **kwargs) -> LazyVisit[YieldType, FlagType]:
meth = self.lookup_method(o)
flag = yield from meth(o, *args, **kwargs)
return flag # noqa: B901
def _post_visit(self, ret: LazyVisit[YieldType, FlagType]) -> ResultType:
return list(ret)
def visit_object(self, o: object, **kwargs) -> LazyVisit[YieldType, FlagType]:
yield from ()
def visit_Node(self, o: Node, **kwargs) -> LazyVisit[YieldType, FlagType]:
flag = yield from self._visit(o.children, **kwargs)
return flag # noqa: B901
def visit_tuple(self, o: Sequence[Any], **kwargs) -> LazyVisit[YieldType, FlagType]:
flag: FlagType = None
for i in o:
flag = yield from self._visit(i, **kwargs)
return flag # noqa: B901
visit_list = visit_tuple
class PrintAST(Visitor):
_depth = 0
"""
Return a representation of the Iteration/Expression tree as a string,
highlighting tree structure and node properties while dropping non-essential
information.
"""
def __init__(self, verbose=True):
super().__init__()
self.verbose = verbose
@classmethod
def default_retval(cls):
return "<>"
@property
def indent(self):
return ' ' * self._depth
def visit_Node(self, o):
return self.indent + f'<{o.__class__.__name__}>'
def visit_Generable(self, o):
body = f" {str(o) if self.verbose else ''}"
return self.indent + f'<C.{o.__class__.__name__}{body}>'
def visit_Callable(self, o):
self._depth += 1
body = self._visit(o.children)
self._depth -= 1
return self.indent + f'<Callable {o.name}>\n{body}'
def visit_CallableBody(self, o):
self._depth += 1
body = [self._visit(o.init), self._visit(o.unpacks), self._visit(o.body)]
self._depth -= 1
cbody = '\n'.join([i for i in body if i])
return self.indent + f"{o.__repr__()}\n{cbody}"
def visit_list(self, o):
return ('\n').join([self._visit(i) for i in o])
def visit_tuple(self, o):
return '\n'.join([self._visit(i) for i in o])
def visit_List(self, o):
self._depth += 1
if self.verbose:
body = [self._visit(o.header), self._visit(o.body), self._visit(o.footer)]
else:
body = [self._visit(o.body)]
self._depth -= 1
cbody = '\n'.join(body)
return self.indent + f"{o.__repr__()}\n{cbody}"
def visit_TimedList(self, o):
self._depth += 1
body = [self._visit(o.body)]
self._depth -= 1
cbody = '\n'.join(body)
return self.indent + f"{o.__repr__()}\n{cbody}"
def visit_Iteration(self, o):
self._depth += 1
body = self._visit(o.children)
self._depth -= 1
if self.verbose:
detail = f'::{o.index}::{o.limits}'
props = [str(i) for i in o.properties]
if props:
cprops = ','.join(props)
props = f'[{cprops}] '
else:
props = ''
else:
detail, props = '', ''
return self.indent + f"<{props}Iteration {o.dim.name}{detail}>\n{body}"
def visit_While(self, o):
self._depth += 1
body = self._visit(o.children)
self._depth -= 1
return self.indent + f"<While {o.condition}>\n{body}"
def visit_Expression(self, o):
if self.verbose:
body = f"{o.expr.lhs} = {o.expr.rhs}"
return self.indent + f"<Expression {body}>"
else:
return self.indent + str(o)
def visit_AugmentedExpression(self, o):
if self.verbose:
body = f"{o.expr.lhs} {o.op}= {o.expr.rhs}"
return self.indent + f"<{o.__class__.__name__} {body}>"
else:
return self.indent + str(o)
def visit_HaloSpot(self, o):
self._depth += 1
body = self._visit(o.children)
self._depth -= 1
return self.indent + f"{o.__repr__()}\n{body}"
def visit_Conditional(self, o):
self._depth += 1
then_body = self._visit(o.then_body)
self._depth -= 1
if o.else_body:
else_body = self._visit(o.else_body)
return self.indent + f"<If {o.condition}>\n{then_body}\n<Else>\n{else_body}"
else:
return self.indent + f"<If {o.condition}>\n{then_body}"
class CGen(Visitor):
"""
Return a representation of the Iteration/Expression tree as a :module:`cgen` tree.
"""
def __init__(self, *args, printer=None, **kwargs):
super().__init__(*args, **kwargs)
if printer is None:
from devito.passes.iet.languages.C import CPrinter
printer = CPrinter
self.printer = printer
def ccode(self, expr, **kwargs):
return self.printer(settings=kwargs).doprint(expr, None)
@property
def _qualifiers_mapper(self):
return self.printer._qualifiers_mapper
@property
def _restrict_keyword(self):
return self.printer._restrict_keyword
def _gen_struct_decl(self, obj, masked=()):
"""
Convert ctypes.Struct -> cgen.Structure.
"""
ctype = obj._C_ctype
try:
while issubclass(ctype, ctypes._Pointer):
ctype = ctype._type_
if not issubclass(ctype, ctypes.Structure) or \
issubclass(ctype, NoDeclStruct):
return None
except TypeError:
# E.g., `ctype` is of type `dtypes_lowering.CustomDtype`
return None
try:
return obj._C_typedecl
except AttributeError:
pass
# Most of the times we end up here -- a generic procedure to
# automatically derive a cgen.Structure from the object _C_ctype
try:
fields = obj.fields
except AttributeError:
fields = (None,)*len(ctype._fields_)
entries = []
for i, (n, ct) in zip(fields, ctype._fields_, strict=True):
try:
entries.append(self._gen_value(i, 0, masked=('const',)))
except AttributeError:
cstr = self.ccode(ct)
if ct is c_restrict_void_p:
cstr = f'{cstr}{self._restrict_keyword}'
entries.append(c.Value(cstr, n))
return c.Struct(ctype.__name__, entries)
def _gen_value(self, obj, mode=1, masked=()):
"""
Convert a devito.types.Basic object into a cgen declaration/definition.
A Basic object may need to be declared and optionally defined in three
different ways, which correspond to the three possible values of `mode`:
* 0: Simple. E.g., `int a = 1`;
* 1: Comprehensive. E.g., `const int *restrict a`, `int a[10]`;
* 2: Declaration suitable for a function parameter list.
"""
qualifiers = [v for k, v in self._qualifiers_mapper.items()
if getattr(obj.function, k, False) and v not in masked]
if (obj._mem_stack or obj._mem_constant) and mode == 1:
strtype = self.ccode(obj._C_typedata)
strshape = ''.join(f'[{self.ccode(i)}]' for i in obj.symbolic_shape)
else:
strtype = self.ccode(obj._C_ctype)
strshape = ''
if isinstance(obj, (AbstractFunction, IndexedData)) \
and mode >= 1 \
and not obj._mem_stack:
strtype = f'{strtype}{self._restrict_keyword}'
strtype = ' '.join(qualifiers + [strtype])
if obj.is_LocalObject and obj._C_modifier is not None and mode == 2:
strtype += obj._C_modifier
strname = obj._C_name
strobj = f'{strname}{strshape}'
if obj.is_LocalObject and obj.cargs and mode == 1:
arguments = [self.ccode(i) for i in obj.cargs]
strobj = MultilineCall(strobj, arguments, True)
value = c.Value(strtype, strobj)
try:
if obj.is_AbstractFunction and obj._data_alignment and mode == 1:
value = c.AlignedAttribute(obj._data_alignment, value)
except AttributeError:
pass
if obj.is_Array and obj.initvalue is not None and mode == 1:
init = ListInitializer(obj.initvalue)
if not obj._mem_constant or init.is_numeric:
value = c.Initializer(value, self.ccode(init))
elif obj.is_LocalObject and obj.initvalue is not None and mode == 1:
value = c.Initializer(value, self.ccode(obj.initvalue))
return value
def _gen_rettype(self, obj):
try:
return self._gen_value(obj, 0).typename
except AttributeError:
pass
if isinstance(obj, str):
return obj
elif isinstance(obj, (FieldFromComposite, FieldFromPointer)):
return self._gen_value(obj.function.base, 0).typename
else:
try:
return obj._type_.__name__
except AttributeError:
return None
def _args_decl(self, args):
"""Generate cgen declarations from an iterable of symbols and expressions."""
return [self._gen_value(i, 2) for i in args]
def _args_call(self, args):
"""
Generate cgen function call arguments from an iterable of symbols and expressions.
"""
ret = []
for i in args:
try:
if isinstance(i, Call):
ret.append(self._visit(i, nested_call=True))
elif isinstance(i, Lambda):
ret.append(self._visit(i))
else:
ret.append(i._C_name)
except AttributeError:
ret.append(self.ccode(i))
return ret
def _gen_signature(self, o, is_declaration=False):
decls = self._args_decl(o.parameters)
prefix = ' '.join(o.prefix + (self._gen_rettype(o.retval),))
# NOTE: ugly, but I can't bother extending `c.FunctionDeclaration`
# for such a tiny thing
v = f"{' '.join(o.attributes)} {o.name}" if o.attributes else o.name
signature = c.FunctionDeclaration(c.Value(prefix, v), decls)
if o.templates:
tparams = ', '.join([i.inline() for i in self._args_decl(o.templates)])
if is_declaration:
signature = TemplateDecl(tparams, signature)
else:
signature = c.Template(tparams, signature)
return signature
def _blankline_logic(self, children):
"""
Generate cgen blank lines in between logical units.
"""
candidates = (Expression, ExpressionBundle, Iteration, Section,
ListMajor)
processed = []
for child in children:
prev = None
rebuilt = []
for k, group in groupby(child, key=type):
g = list(group)
if k in (ExpressionBundle, Section) and len(g) >= 2:
# Separate consecutive Sections/ExpressionBundles with
# BlankLine
for i in g[:-1]:
rebuilt.append(i)
rebuilt.append(BlankLine)
rebuilt.append(g[-1])
elif (k is Iteration and
prev is ExpressionBundle and
all(i.dim.is_Stencil for i in g)):
rebuilt.extend(g)
elif (prev in candidates and k in candidates) or \
(prev is not None and k in (ListMajor, Section)) or \
(prev in (ListMajor, Section)):
rebuilt.append(BlankLine)
rebuilt.extend(g)
else:
rebuilt.extend(g)
prev = k
processed.append(tuple(rebuilt))
return tuple(processed)
def visit_object(self, o):
return o
visit_Generable = visit_object
visit_Collection = visit_object
def visit_tuple(self, o):
return tuple(self._visit(i) for i in o)
def visit_PointerCast(self, o):
f = o.function
i = f.indexed
cstr = self.ccode(i._C_typedata)
if f.is_PointerArray:
# lvalue
lvalue = c.Value(cstr, f'**{f.name}')
# rvalue
if isinstance(o.obj, ArrayObject):
v = f'{o.obj.name}->{f._C_name}'
elif isinstance(o.obj, IndexedData):
v = f._C_name
else:
raise TypeError('rvalue is not a recognised type')
rvalue = f'({cstr}**) {v}'
else:
# lvalue
if f.is_DiscreteFunction or (f.is_Array and f._mem_mapped):
v = o.obj.name
else:
v = f.name
if o.flat is None:
shape = ''.join(f"[{self.ccode(i)}]" for i in o.castshape)
rshape = f'(*){shape}'
if shape:
lvalue = c.Value(cstr, f'(*{self._restrict_keyword} {v}){shape}')
else:
lvalue = c.Value(cstr, f'*{self._restrict_keyword} {v}')
else:
rshape = '*'
lvalue = c.Value(cstr, f'*{v}')
if o.alignment and f._data_alignment:
lvalue = c.AlignedAttribute(f._data_alignment, lvalue)
# rvalue
if f.is_DiscreteFunction or (f.is_Array and f._mem_mapped):
if isinstance(o.obj, IndexedData):
v = f._C_field_data
elif isinstance(o.obj, DeviceMap):
v = f._C_field_dmap
else:
raise TypeError('rvalue is not a recognised type')
rvalue = f'({cstr} {rshape}) {f._C_name}->{v}'
else:
v = o.obj.name if isinstance(o.obj, Pointer) else f._C_name
rvalue = f'({cstr} {rshape}) {v}'
return c.Initializer(lvalue, rvalue)
def visit_Dereference(self, o):
a0, a1 = o.functions
ptr = f'({a1.name} + {o.offset})' if o.offset else a1.name
if a0.is_AbstractFunction:
cstr = self.ccode(a0.indexed._C_typedata)
try:
# Special AbstractFunctions such as PointerArray or TempFunction
cdim = f'[{a1.dim.name}]'
except AttributeError:
cdim = ''
if o.flat is None:
shape = ''.join(f"[{self.ccode(i)}]" for i in a0.symbolic_shape[1:])
rvalue = f'({cstr} (*){shape}) {ptr}{cdim}'
lvalue = c.Value(cstr, f'(*{self._restrict_keyword} {a0.name}){shape}')
else:
rvalue = f'({cstr} *) {ptr}{cdim}'
lvalue = c.Value(cstr, f'*{self._restrict_keyword} {a0.name}')
else:
rvalue = f'*{ptr}' if a1.is_Symbol else f'{ptr}->{a0._C_name}'
lvalue = self._gen_value(a0, 0)
return c.Initializer(lvalue, rvalue)
def visit_Block(self, o):
body = flatten(self._visit(i) for i in self._blankline_logic(o.children))
return c.Module(o.header + (c.Block(body),) + o.footer)
def visit_List(self, o):
body = flatten(self._visit(i) for i in self._blankline_logic(o.children))
body = c.Line(' '.join(str(i) for i in body)) if o.inline else c.Collection(body)
return c.Module(o.header + (body,) + o.footer)
def visit_Section(self, o):
body = flatten(self._visit(i) for i in o.children)
return c.Module(body)
def visit_Break(self, o):
return c.Statement('break')
def visit_Return(self, o):
v = 'return'
if o.value is not None:
v += f' {self.ccode(o.value)}'
return c.Statement(v)
def visit_Definition(self, o):
return self._gen_value(o.function)
def visit_Expression(self, o):
lhs = self.ccode(o.expr.lhs, dtype=o.dtype)
rhs = self.ccode(o.expr.rhs, dtype=o.dtype)
if o.init:
code = c.Initializer(self._gen_value(o.expr.lhs, 0), rhs)
else:
code = c.Assign(lhs, rhs)
if o.pragmas:
code = c.Module(self._visit(o.pragmas) + (code,))
return code
def visit_AugmentedExpression(self, o):
c_lhs = self.ccode(o.expr.lhs, dtype=o.dtype)
c_rhs = self.ccode(o.expr.rhs, dtype=o.dtype)
code = c.Statement(f"{c_lhs} {o.op}= {c_rhs}")
if o.pragmas:
code = c.Module(self._visit(o.pragmas) + (code,))
return code
def visit_Call(self, o, nested_call=False):
retobj = o.retobj
rettype = self._gen_rettype(retobj)
cast = o.cast and rettype
arguments = self._args_call(o.arguments)
if retobj is None:
return MultilineCall(o.name, arguments, nested_call, o.is_indirect,
cast, o.templates)
else:
call = MultilineCall(o.name, arguments, True, o.is_indirect, cast,
o.templates)
if retobj.is_Indexed or \
isinstance(retobj, (FieldFromComposite, FieldFromPointer)):
return c.Assign(self.ccode(retobj), call)
else:
return c.Initializer(c.Value(rettype, retobj._C_name), call)
def visit_Conditional(self, o):
try:
then_body, else_body = self._blankline_logic(o.children)
except ValueError:
# Some special subclasses of Conditional such as ThreadedProdder
# have zero children actually
then_body, else_body = o.then_body, o.else_body
then_body = c.Block(self._visit(then_body))
if else_body:
else_body = c.Block(self._visit(else_body))
return c.If(self.ccode(o.condition), then_body, else_body)
else:
return c.If(self.ccode(o.condition), then_body)
def visit_Switch(self, o):
condition = self.ccode(o.condition)
mapper = {k: self._visit(v) for k, v in o.as_mapper.items()}
return Switch(condition, mapper)
def visit_Iteration(self, o):
body = flatten(self._visit(i) for i in self._blankline_logic(o.children))
_min = o.limits[0]
_max = o.limits[1]
# For backward direction flip loop bounds
if o.direction == Backward:
loop_init = f'int {o.index} = {self.ccode(_max)}'
loop_cond = f'{o.index} >= {self.ccode(_min)}'
loop_inc = f'{o.index} -= {o.limits[2]}'
else:
loop_init = f'int {o.index} = {self.ccode(_min)}'
loop_cond = f'{o.index} <= {self.ccode(_max)}'
loop_inc = f'{o.index} += {o.limits[2]}'
# Append unbounded indices, if any
if o.uindices and o.pragmas:
# When pragmas are present (e.g., OpenMP parallel for), the
# for-loop header must be in canonical form: a single loop
# variable in init/cond/incr. Compute uindex values inside
# the loop body instead, where they are automatically
# thread-private
uinit_stmts = []
for i in o.uindices:
if i.is_Modulo:
# Modulo dimensions: symbolic_incr computes the
# value from the parent dimension (the loop variable)
value = i.symbolic_incr
else:
# IncrDimension: derive value from loop variable
# position relative to loop start
if o.direction == Backward:
n_iters = _max - o.dim
else:
n_iters = o.dim - _min
_step = o.limits[2]
if _step != 1:
n_iters = n_iters / _step
if i.symbolic_incr != 1:
value = i.symbolic_min + n_iters * i.symbolic_incr
else:
value = i.symbolic_min + n_iters
uinit_stmts.append(
c.Statement(f'int {i.name} = {self.ccode(value)}')
)
body = list(uinit_stmts) + list(body)
elif o.uindices:
uinit = [f'{i.name} = {self.ccode(i.symbolic_min)}'
for i in o.uindices]
loop_init = c.Line(', '.join([loop_init] + uinit))
ustep = []
for i in o.uindices:
op = '=' if i.is_Modulo else '+='
ustep.append(
f'{i.name} {op} {self.ccode(i.symbolic_incr)}'
)
loop_inc = c.Line(', '.join([loop_inc] + ustep))
# Create For header+body
handle = c.For(loop_init, loop_cond, loop_inc, c.Block(body))
# Attach pragmas, if any
if o.pragmas:
pragmas = tuple(self._visit(i) for i in o.pragmas)
handle = c.Module(pragmas + (handle,))
return handle
def visit_Pragma(self, o):
return c.Pragma(o._generate)
def visit_While(self, o):
condition = self.ccode(o.condition)
if o.body:
body = flatten(self._visit(i) for i in o.children)
return c.While(condition, c.Block(body))
else:
# Hack: cgen doesn't support body-less while-loops, i.e. `while(...);`
return c.Statement(f'while({condition})')
def visit_Callable(self, o):
body = flatten(self._visit(i) for i in o.children)
signature = self._gen_signature(o)
return c.FunctionBody(signature, c.Block(body))
def visit_MultiTraversable(self, o):
body = []
prev = None
for i in o.children:
v = self._visit(i)
if v:
if prev:
body.append(c.Line())
prev = v
body.extend(as_tuple(v))
return c.Collection(body)
def visit_Using(self, o):
return c.Statement(f'using {str(o.name)}')
def visit_UsingNamespace(self, o):
return c.Statement(f'using namespace {str(o.namespace)}')
def visit_Lambda(self, o):
body = []
for i in o.children:
v = self._visit(i)
if v:
if body:
body.append(c.Line())
body.extend(as_tuple(v))
captures = [str(i) for i in o.captures]
decls = [i.inline() for i in self._args_decl(o.parameters)]
extra = []
if o.special:
extra.append(' ')
extra.append(' '.join(str(i) for i in o.special))
if o.attributes:
extra.append(' ')
extra.append(' '.join(f'[[{i}]]' for i in o.attributes))
top = c.Line(f"[{', '.join(captures)}]({', '.join(decls)}){''.join(extra)}")
return LambdaCollection([top, c.Block(body)])
def visit_HaloSpot(self, o):
body = flatten(self._visit(i) for i in o.children)
return c.Collection(body)
def visit_KernelLaunch(self, o):
templates = f"<{','.join([str(i) for i in o.templates])}>" if o.templates else ''
launch_args = [o.grid, o.block]
if o.shm is not None:
launch_args.append(o.shm)
if o.stream is not None:
launch_args.append(o.stream)
launch_config = ','.join(str(i) for i in launch_args)
arguments = self._args_call(o.arguments)
arguments = ','.join(arguments)
return c.Statement(f'{o.name}{templates}<<<{launch_config}>>>({arguments})')
# Operator-handle machinery
def _operator_description(self, o):
"""
Generate cgen description from an iterable of symbols and expressions.
"""
if o.description:
if isinstance(o.description, str):
return [c.Comment(o.description), blankline]
elif isinstance(o.description, Iterable):
return [c.MultilineComment(o.description), blankline]
else:
return [c.Comment("Devito generated operator"), blankline]
def _operator_includes(self, o):
"""
Generate cgen includes from an iterable of symbols and expressions.
"""
return [c.Include(i, system=(not i.endswith('.h')))
for i in o.includes] + [blankline]
def _operator_namespaces(self, o):
"""
Generate cgen namespaces from an iterable of symbols and expressions.
"""
namespaces = [self._visit(i) for i in o.namespaces]
if namespaces:
namespaces.append(blankline)
return namespaces
def _operator_headers(self, o):
"""
Generate cgen headers from an iterable of symbols and expressions.
"""
headers = [c.Define(*as_tuple(i)) for i in o.headers]
if headers:
headers.append(blankline)
return headers
def _operator_typedecls(self, o, mode='all'):
xfilter0 = lambda i: self._gen_struct_decl(i) is not None
if mode == 'all':
xfilter1 = xfilter0
else:
public_types = (AbstractFunction, CompositeObject)
if mode == 'public':
xfilter1 = lambda i: xfilter0(i) and isinstance(i, public_types)
else:
xfilter1 = lambda i: xfilter0(i) and not isinstance(i, public_types)
# This is essentially to rule out vector types which are declared already
# in some external headers
xfilter = lambda i: (xfilter1(i) and
not is_external_ctype(i._C_ctype, o._includes))
candidates = o.parameters + tuple(o._dspace.parts)
typedecls = [self._gen_struct_decl(i) for i in candidates if xfilter(i)]
for i in o._func_table.values():
if not i.local:
continue
typedecls.extend([self._gen_struct_decl(j) for j in i.root.parameters
if xfilter(j)])
typedecls = filter_sorted(typedecls, key=lambda i: i.tpname)
return typedecls
def _operator_globals(self, o, mode='all'):
# Sorting for deterministic code generation
v = sorted(o._globals, key=lambda i: i.name)
return [self._gen_value(i) for i in v]
def visit_Operator(self, o, mode='all'):
# Kernel signature and body
body = flatten(self._visit(i) for i in o.children)
signature = self._gen_signature(o)
# Honor the `retstmt` flag if set
retval = [] if o.body.retstmt else [c.Line(), c.Statement("return 0")]
kernel = c.FunctionBody(signature, c.Block(body + retval))
# Elemental functions
esigns = []
efuncs = [blankline]
items = [i.root for i in o._func_table.values() if i.local]
for i in sorted_efuncs(items):
esigns.append(self._gen_signature(i, is_declaration=True))
efuncs.extend([self._visit(i), blankline])
# Top description
description = self._operator_description(o)
# Definitions
headers = self._operator_headers(o)
# Header files
includes = self._operator_includes(o)
# Namespaces
namespaces = self._operator_namespaces(o)
# Type declarations
typedecls = self._operator_typedecls(o, mode)
if mode in ('all', 'public') and o._compiler.src_ext in ('cpp', 'cu'):
typedecls.append(c.Extern('C', signature))
typedecls = [i for j in typedecls for i in (j, blankline)]
# Global variables
globs = self._operator_globals(o, mode)
if globs:
globs.append(blankline)
return c.Module(description + headers + includes + namespaces + typedecls
+ globs + esigns + [blankline, kernel] + efuncs)
class CInterface(CGen):
def _operator_includes(self, o):
includes = super()._operator_includes(o)
includes.append(c.Include(f"{o.name}.h", system=False))
return includes
def visit_Operator(self, o):
# Generate the code for the cfile
ccode = super().visit_Operator(o, mode='private')
# Generate the code for the hfile
typedecls = self._operator_typedecls(o, mode='public')
guarded_typedecls = []
for i in typedecls:
guard = f"DEVITO_{i.tpname.upper()}"
iflines = [c.Define(guard, ""), blankline, i, blankline]
guarded_typedecl = c.IfNDef(guard, iflines, [])
guarded_typedecls.extend([guarded_typedecl, blankline])
signature = self._gen_signature(o)
hcode = c.Module(guarded_typedecls + [blankline, signature, blankline])
return ccode, hcode
class FindSections(Visitor):
@classmethod
def default_retval(cls):
return OrderedDict()
"""
Find all sections in an Iteration/Expression tree. A section is a map
from an Iteration nest to the enclosed statements (e.g., Expressions,
Conditionals, Calls, ...).
"""
def visit_object(self, o, ret=None, queue=None):
return ret
def visit_tuple(self, o, ret=None, queue=None):
if ret is None:
ret = self.default_retval()
for i in o:
ret = self._visit(i, ret=ret, queue=queue)
return ret
visit_list = visit_tuple
def visit_Node(self, o, ret=None, queue=None):
if ret is None:
ret = self.default_retval()
for i in o.children:
ret = self._visit(i, ret=ret, queue=queue)
return ret
def visit_Iteration(self, o, ret=None, queue=None):
if queue is None:
queue = [o]
else:
queue.append(o)
for i in o.children:
ret = self._visit(i, ret=ret, queue=queue)
queue.remove(o)
return ret
def visit_ExprStmt(self, o, ret=None, queue=None):
if ret is None:
ret = self.default_retval()
if queue is not None:
ret.setdefault(tuple(queue), []).append(o)
return ret
def visit_Conditional(self, o, ret=None, queue=None):
# Essentially like visit_ExprStmt, but also go down through the children
if ret is None:
ret = self.default_retval()
if queue is not None:
ret.setdefault(tuple(queue), []).append(o)
for i in o.children:
ret = self._visit(i, ret=ret, queue=queue)
return ret
visit_Call = visit_Conditional
class MapKind(FindSections):
"""
Base class to construct mappers from Nodes of given type to their enclosing
scope of Nodes.
"""
# NOTE: Ideally, we would use a metaclass that dynamically constructs mappers
# for the kind supplied by the caller, but it'd be overkill at the moment
def visit_dummy(self, o, ret=None, queue=None):
if ret is None:
ret = self.default_retval()
ret[o] = as_tuple(queue)
return ret