-
Notifications
You must be signed in to change notification settings - Fork 134
/
Copy pathcpu.py
2618 lines (2235 loc) · 110 KB
/
cpu.py
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
import ast
import copy
import functools
import itertools
import sympy as sp
from six import StringIO
from dace.codegen import cppunparse
import dace
from dace.config import Config
from dace.frontend import operations
from dace import data, subsets, symbolic, types, memlet as mmlt
from dace.codegen.prettycode import CodeIOStream
from dace.codegen.codeobject import CodeObject
from dace.codegen.targets import framecode
from dace.codegen.targets.target import (TargetCodeGenerator, make_absolute,
DefinedType)
from dace.graph import nodes, nxutil
from dace.sdfg import ScopeSubgraphView, SDFG, scope_contains_scope, find_input_arraynode, find_output_arraynode, is_devicelevel
from dace.frontend.python.astutils import ExtNodeTransformer, rname, unparse
from dace.properties import LambdaProperty
from dace.codegen.instrumentation.perfsettings import PerfSettings, PerfUtils, PerfMetaInfo, PerfMetaInfoStatic
_REDUCTION_TYPE_TO_OPENMP = {
types.ReductionType.Max: 'max',
types.ReductionType.Min: 'min',
types.ReductionType.Sum: '+',
types.ReductionType.Product: '*',
types.ReductionType.Bitwise_And: '&',
types.ReductionType.Logical_And: '&&',
types.ReductionType.Bitwise_Or: '|',
types.ReductionType.Logical_Or: '||',
types.ReductionType.Bitwise_Xor: '^',
}
class CPUCodeGen(TargetCodeGenerator):
""" SDFG CPU code generator. """
title = 'CPU'
target_name = 'cpu'
language = 'cpp'
def __init__(self, frame_codegen, sdfg):
self._frame = frame_codegen
self._dispatcher = frame_codegen.dispatcher
dispatcher = self._dispatcher
self._locals = cppunparse.CPPLocals()
# Scope depth (for use of the 'auto' keyword when
# defining locals)
self._ldepth = 0
# FIXME: this allows other code generators to change the CPU
# behavior to assume that arrays point to packed types, thus dividing
# all addresess by the vector length.
self._packed_types = False
# Keep track of traversed nodes
self._generated_nodes = set()
self._allocated_arrays = set()
# Keeps track of generated connectors, so we know how to access them in
# nested scopes
for name, arg_type in sdfg.arglist().items():
if (isinstance(arg_type, dace.data.Scalar)
or isinstance(arg_type, dace.types.typeclass)):
self._dispatcher.defined_vars.add(name, DefinedType.Scalar)
elif isinstance(arg_type, dace.data.Array):
self._dispatcher.defined_vars.add(name, DefinedType.Pointer)
elif isinstance(arg_type, dace.data.Stream):
if arg_type.is_stream_array():
self._dispatcher.defined_vars.add(name,
DefinedType.StreamArray)
else:
self._dispatcher.defined_vars.add(name, DefinedType.Stream)
else:
raise TypeError("Unrecognized argument type: {}".format(
type(arg_type).__name__))
# Register dispatchers
dispatcher.register_node_dispatcher(self)
dispatcher.register_map_dispatcher(
[types.ScheduleType.CPU_Multicore, types.ScheduleType.Sequential],
self)
cpu_storage = [
types.StorageType.CPU_Heap, types.StorageType.CPU_Pinned,
types.StorageType.CPU_Stack, types.StorageType.Register
]
dispatcher.register_array_dispatcher(cpu_storage, self)
# Register CPU copies (all internal pairs)
for src_storage, dst_storage in itertools.product(
cpu_storage, cpu_storage):
dispatcher.register_copy_dispatcher(src_storage, dst_storage, None,
self)
@staticmethod
def cmake_options():
compiler = make_absolute(Config.get("compiler", "cpu", "executable"))
flags = Config.get("compiler", "cpu", "args")
flags += Config.get("compiler", "cpu", "additional_args")
# Args for vectorization output
if PerfSettings.perf_enable_vectorization_analysis():
flags += " -fopt-info-vec-optimized-missed=vecreport.txt "
options = [
"-DCMAKE_CXX_COMPILER=\"{}\"".format(compiler),
"-DCMAKE_CXX_FLAGS=\"{}\"".format(flags),
]
return options
def get_generated_codeobjects(self):
# CPU target generates inline code
return []
@property
def has_initializer(self):
return False
@property
def has_finalizer(self):
return False
def generate_scope(self, sdfg: SDFG, dfg_scope: ScopeSubgraphView,
state_id, function_stream, callsite_stream):
entry_node = dfg_scope.source_nodes()[0]
presynchronize_streams(sdfg, dfg_scope, state_id, entry_node,
callsite_stream)
self.generate_node(sdfg, dfg_scope, state_id, entry_node,
function_stream, callsite_stream)
self._dispatcher.dispatch_subgraph(
sdfg,
dfg_scope,
state_id,
function_stream,
callsite_stream,
skip_entry_node=True)
def generate_node(self, sdfg, dfg, state_id, node, function_stream,
callsite_stream):
# Dynamically obtain node generator according to class name
gen = getattr(self, '_generate_' + type(node).__name__)
gen(sdfg, dfg, state_id, node, function_stream, callsite_stream)
# Mark node as "generated"
self._generated_nodes.add(node)
self._locals.clear_scope(self._ldepth + 1)
def allocate_array(self, sdfg, dfg, state_id, node, function_stream,
callsite_stream):
name = node.data
nodedesc = node.desc(sdfg)
if ((state_id, node.data) in self._allocated_arrays
or (None, node.data) in self._allocated_arrays
or nodedesc.transient == False):
return
self._allocated_arrays.add((state_id, node.data))
# Compute array size
arrsize = ' * '.join([sym2cpp(s) for s in nodedesc.strides])
if isinstance(nodedesc, data.Scalar):
callsite_stream.write("%s %s;\n" % (nodedesc.dtype.ctype, name),
sdfg, state_id, node)
self._dispatcher.defined_vars.add(name, DefinedType.Scalar)
elif isinstance(nodedesc, data.Stream):
###################################################################
# Stream directly connected to an array
if is_array_stream_view(sdfg, dfg, node):
if state_id is None:
raise SyntaxError(
'Stream-view of array may not be defined '
'in more than one state')
arrnode = sdfg.arrays[nodedesc.sink]
state = sdfg.nodes()[state_id]
edges = state.out_edges(node)
if len(edges) > 1:
raise NotImplementedError('Cannot handle streams writing '
'to multiple arrays.')
memlet_path = state.memlet_path(edges[0])
# Allocate the array before its stream view, if necessary
self.allocate_array(sdfg, dfg, state_id, memlet_path[-1].dst,
function_stream, callsite_stream)
array_expr = self.copy_expr(sdfg, nodedesc.sink, edges[0].data)
threadlocal = ''
threadlocal_stores = [
types.StorageType.CPU_Stack, types.StorageType.Register
]
if (sdfg.arrays[nodedesc.sink].storage in threadlocal_stores
or nodedesc.storage in threadlocal_stores):
threadlocal = 'Threadlocal'
callsite_stream.write(
'dace::ArrayStreamView%s<%s> %s (%s);\n' %
(threadlocal, arrnode.dtype.ctype, name, array_expr), sdfg,
state_id, node)
self._dispatcher.defined_vars.add(name, DefinedType.Stream)
return
###################################################################
# Regular stream
dtype = "dace::vec<{}, {}>".format(nodedesc.dtype.ctype,
sym2cpp(nodedesc.veclen))
if nodedesc.buffer_size != 0:
definition = "dace::Stream<{}> {}({});".format(
dtype, name, nodedesc.buffer_size)
else:
definition = "dace::Stream<{}> {};".format(dtype, name)
callsite_stream.write(definition, sdfg, state_id, node)
self._dispatcher.defined_vars.add(name, DefinedType.Stream)
elif (nodedesc.storage == types.StorageType.CPU_Heap
or nodedesc.storage == types.StorageType.Immaterial
): # TODO: immaterial arrays should not allocate memory
callsite_stream.write(
"%s *%s = new %s DACE_ALIGN(64)[%s];\n" %
(nodedesc.dtype.ctype, name, nodedesc.dtype.ctype, arrsize),
sdfg, state_id, node)
self._dispatcher.defined_vars.add(name, DefinedType.Pointer)
if node.setzero:
callsite_stream.write('memset(%s, 0, sizeof(%s)*%s);' %
(name, nodedesc.dtype.ctype, arrsize))
return
elif (nodedesc.storage == types.StorageType.CPU_Stack
or nodedesc.storage == types.StorageType.Register):
if node.setzero:
callsite_stream.write(
"%s %s[%s] DACE_ALIGN(64) = {0};\n" %
(nodedesc.dtype.ctype, name, arrsize), sdfg, state_id,
node)
self._dispatcher.defined_vars.add(name, DefinedType.Pointer)
return
callsite_stream.write(
"%s %s[%s] DACE_ALIGN(64);\n" %
(nodedesc.dtype.ctype, name, arrsize), sdfg, state_id, node)
self._dispatcher.defined_vars.add(name, DefinedType.Pointer)
return
else:
raise NotImplementedError('Unimplemented storage type ' +
str(nodedesc.storage))
def initialize_array(self, sdfg, dfg, state_id, node, function_stream,
callsite_stream):
if isinstance(dfg, SDFG):
result = StringIO()
for sid, state in enumerate(dfg.nodes()):
if node in state.nodes():
self.initialize_array(sdfg, state, sid, node,
function_stream, callsite_stream)
break
return
parent_node = dfg.scope_dict()[node]
nodedesc = node.desc(sdfg)
name = node.data
# Traverse the DFG, looking for WCR with an identity element
def traverse(u, uconn, v, vconn, d):
if d.wcr:
if d.data == name:
if d.wcr_identity is not None:
return d.wcr_identity
return None
identity = None
if parent_node is not None:
for u, uconn, v, vconn, d, s in nxutil.traverse_sdfg_scope(
dfg, parent_node):
identity = traverse(u, uconn, v, vconn, d)
if identity is not None: break
else:
for u, uconn, v, vconn, d in dfg.edges():
identity = traverse(u, uconn, v, vconn, d)
if identity is not None: break
if identity is None:
return
# If we should generate an initialization expression
if isinstance(nodedesc, data.Scalar):
callsite_stream.write('%s = %s;\n' % (name, sym2cpp(identity)),
sdfg, state_id, node)
return
params = [name, sym2cpp(identity)]
shape = [sym2cpp(s) for s in nodedesc.shape]
params.append(' * '.join(shape))
# Faster
if identity == 0:
params[-1] += ' * sizeof(%s[0])' % name
callsite_stream.write('memset(%s);\n' % (', '.join(params)), sdfg,
state_id, node)
return
callsite_stream.write('dace::InitArray(%s);\n' % (', '.join(params)),
sdfg, state_id, node)
def deallocate_array(self, sdfg, dfg, state_id, node, function_stream,
callsite_stream):
nodedesc = node.desc(sdfg)
if isinstance(nodedesc, data.Scalar):
return
elif isinstance(nodedesc, data.Stream):
return
elif nodedesc.storage == types.StorageType.CPU_Heap:
callsite_stream.write("delete[] %s;\n" % node.data, sdfg, state_id,
node)
else:
return
def copy_memory(self, sdfg, dfg, state_id, src_node, dst_node, edge,
function_stream, callsite_stream):
if isinstance(src_node, nodes.Tasklet):
src_storage = types.StorageType.Register
try:
src_parent = dfg.scope_dict()[src_node]
except KeyError:
src_parent = None
dst_schedule = (None
if src_parent is None else src_parent.map.schedule)
else:
src_storage = src_node.desc(sdfg).storage
if isinstance(dst_node, nodes.Tasklet):
dst_storage = types.StorageType.Register
else:
dst_storage = dst_node.desc(sdfg).storage
try:
dst_parent = dfg.scope_dict()[dst_node]
except KeyError:
dst_parent = None
dst_schedule = None if dst_parent is None else dst_parent.map.schedule
state_dfg = sdfg.nodes()[state_id]
# Emit actual copy
self._emit_copy(sdfg, state_id, src_node, src_storage, dst_node,
dst_storage, dst_schedule, edge, state_dfg,
callsite_stream)
def _emit_copy(self, sdfg, state_id, src_node, src_storage, dst_node,
dst_storage, dst_schedule, edge, dfg, stream):
u, uconn, v, vconn, memlet = edge
#############################################################
# Instrumentation: Pre-copy
# For perfcounters, we have to make sure that:
# 1) No other measurements are done for the containing scope (no map operation containing this copy is instrumented)
src_instrumented = PerfUtils.has_surrounding_perfcounters(
src_node, dfg)
dst_instrumented = PerfUtils.has_surrounding_perfcounters(
dst_node, dfg)
# From cuda.py
cpu_storage_types = [
types.StorageType.CPU_Heap, types.StorageType.CPU_Stack,
types.StorageType.CPU_Pinned, types.StorageType.Register
]
perf_cpu_only = (src_storage in cpu_storage_types) and (
dst_storage in cpu_storage_types)
perf_should_instrument = PerfSettings.perf_enable_instrumentation_for(
sdfg) and (not src_instrumented) and (
not dst_instrumented) and perf_cpu_only
#############################################################
# Determine memlet directionality
if (isinstance(src_node, nodes.AccessNode)
and memlet.data == src_node.data):
write = True
elif (isinstance(dst_node, nodes.AccessNode)
and memlet.data == dst_node.data):
write = False
elif isinstance(src_node, nodes.CodeNode) and isinstance(
dst_node, nodes.CodeNode):
# Code->Code copy (not read nor write)
raise RuntimeError(
'Copying between code nodes is only supported as'
' part of the participating nodes')
else:
raise LookupError('Memlet does not point to any of the nodes')
if isinstance(dst_node, nodes.Tasklet):
# Copy into tasklet
stream.write(
' ' + self.memlet_definition(sdfg, memlet, False, vconn),
sdfg, state_id, [src_node, dst_node])
return
elif isinstance(src_node, nodes.Tasklet):
# Copy out of tasklet
stream.write(
' ' + self.memlet_definition(sdfg, memlet, True, uconn),
sdfg, state_id, [src_node, dst_node])
return
else: # Copy array-to-array
src_nodedesc = src_node.desc(sdfg)
dst_nodedesc = dst_node.desc(sdfg)
if write:
vconn = dst_node.data
ctype = 'dace::vec<%s, %d>' % (dst_nodedesc.dtype.ctype,
memlet.veclen)
#############################################
# Corner cases
# Writing one index
if isinstance(memlet.subset,
subsets.Indices) and memlet.wcr is None:
stream.write(
'%s = %s;' % (vconn, self.memlet_ctor(
sdfg, memlet, False)), sdfg, state_id,
[src_node, dst_node])
return
# Writing from/to a stream
if (isinstance(sdfg.arrays[memlet.data], data.Stream) or \
(isinstance(src_node, nodes.AccessNode) and isinstance(src_nodedesc,
data.Stream))):
# Identify whether a stream is writing to an array
if (isinstance(dst_nodedesc, (data.Scalar, data.Array))
and isinstance(src_nodedesc, data.Stream)):
return # Do nothing (handled by ArrayStreamView)
# Array -> Stream - push bulk
if (isinstance(src_nodedesc, (data.Scalar, data.Array))
and isinstance(dst_nodedesc, data.Stream)):
if hasattr(src_nodedesc, 'src'): # ArrayStreamView
stream.write(
'{s}.push({arr});'.format(
s=dst_node.data, arr=src_nodedesc.src), sdfg,
state_id, [src_node, dst_node])
else:
copysize = ' * '.join(
[sym2cpp(s) for s in memlet.subset.size()])
stream.write(
'{s}.push({arr}, {size});'.format(
s=dst_node.data,
arr=src_node.data,
size=copysize), sdfg, state_id,
[src_node, dst_node])
return
else:
# Unknown case
raise NotImplementedError
#############################################
state_dfg = sdfg.nodes()[state_id]
copy_shape, src_strides, dst_strides, src_expr, dst_expr = (
self.memlet_copy_to_absolute_strides(sdfg, memlet, src_node,
dst_node))
# Which numbers to include in the variable argument part
dynshape, dynsrc, dyndst = 1, 1, 1
# Dynamic copy dimensions
if any(symbolic.issymbolic(s, sdfg.constants) for s in copy_shape):
copy_tmpl = 'Dynamic<{type}, {veclen}, {aligned}, {dims}>'.format(
type=ctype,
veclen=1, # Taken care of in "type"
aligned='false',
dims=len(copy_shape))
else: # Static copy dimensions
copy_tmpl = '<{type}, {veclen}, {aligned}, {dims}>'.format(
type=ctype,
veclen=1, # Taken care of in "type"
aligned='false',
dims=', '.join(sym2cpp(copy_shape)))
dynshape = 0
# Constant src/dst dimensions
if not any(
symbolic.issymbolic(s, sdfg.constants)
for s in dst_strides):
# Constant destination
shape_tmpl = 'template ConstDst<%s>' % ', '.join(
sym2cpp(dst_strides))
dyndst = 0
elif not any(
symbolic.issymbolic(s, sdfg.constants)
for s in src_strides):
# Constant source
shape_tmpl = 'template ConstSrc<%s>' % ', '.join(
sym2cpp(src_strides))
dynsrc = 0
else:
# Both dynamic
shape_tmpl = 'Dynamic'
# Parameter pack handling
stride_tmpl_args = [0] * (
dynshape + dynsrc + dyndst) * len(copy_shape)
j = 0
for shape, src, dst in zip(copy_shape, src_strides, dst_strides):
if dynshape > 0:
stride_tmpl_args[j] = shape
j += 1
if dynsrc > 0:
stride_tmpl_args[j] = src
j += 1
if dyndst > 0:
stride_tmpl_args[j] = dst
j += 1
copy_args = ([src_expr, dst_expr] + ([] if memlet.wcr is None else
[unparse_cr(memlet.wcr)]) +
sym2cpp(stride_tmpl_args))
#############################################################
# Instrumentation: Pre-copy 2
unique_cpy_id = PerfSettings.get_unique_number()
if perf_should_instrument:
fac3 = ' * '.join(sym2cpp(copy_shape)) + " / " + '/'.join(
sym2cpp(dst_strides))
copy_size = "sizeof(%s) * %s * (%s)" % (ctype, memlet.veclen,
fac3)
node_id = PerfUtils.unified_id(dfg.node_id(dst_node), state_id)
# Mark a section start (this is not really a section in itself (it would be a section with 1 entry))
stream.write(
"__perf_store.markSectionStart(%d, (long long)%s, PAPI_thread_id());\n"
% (node_id, copy_size), sdfg, state_id,
[src_node, dst_node])
stream.write((
"dace_perf::{pcs} __perf_cpy_{nodeid}_{unique_id};\n" +
"auto& __vs_cpy_{nodeid}_{unique_id} = __perf_store.getNewValueSet(__perf_cpy_{nodeid}_{unique_id}, {nodeid}, PAPI_thread_id(), {size}, dace_perf::ValueSetType::Copy);\n"
+ "__perf_cpy_{nodeid}_{unique_id}.enterCritical();\n"
).format(
pcs=PerfUtils.perf_counter_string(dst_node),
nodeid=node_id,
unique_id=unique_cpy_id,
size=copy_size), sdfg, state_id, [src_node, dst_node])
#############################################################
nc = True
if memlet.wcr is not None:
nc = not is_write_conflicted(dfg, edge)
if nc:
stream.write(
"""
dace::CopyND{copy_tmpl}::{shape_tmpl}::{copy_func}(
{copy_args});""".format(
copy_tmpl=copy_tmpl,
shape_tmpl=shape_tmpl,
copy_func='Copy'
if memlet.wcr is None else 'Accumulate',
copy_args=', '.join(copy_args)), sdfg, state_id,
[src_node, dst_node])
else: # Conflicted WCR
if dynshape == 1:
raise NotImplementedError(
'Accumulation of dynamically-shaped '
'arrays not yet implemented')
elif copy_shape == [
1
]: # Special case: accumulating one element
dst_expr = self.memlet_view_ctor(sdfg, memlet, True)
stream.write(
write_and_resolve_expr(memlet, nc, dst_expr,
'*(' + src_expr + ')'), sdfg,
state_id, [src_node, dst_node])
else:
raise NotImplementedError('Accumulation of arrays '
'with WCR not yet implemented')
#############################################################
# Instrumentation: Post-copy
if perf_should_instrument:
stream.write(("__perf_cpy_%d_%d.leaveCritical(__vs_cpy_%d_%d);\n")
% (node_id, unique_cpy_id, node_id, unique_cpy_id),
sdfg, state_id, [src_node, dst_node])
#############################################################
###########################################################################
# Memlet handling
def process_out_memlets(self, sdfg, state_id, node, dfg, dispatcher,
result, locals_defined, function_stream):
scope_dict = sdfg.nodes()[state_id].scope_dict()
for edge in dfg.out_edges(node):
_, uconn, v, _, memlet = edge
dst_node = dfg.memlet_path(edge)[-1].dst
# Target is neither a data nor a tasklet node
if (isinstance(node, nodes.AccessNode)
and (not isinstance(dst_node, nodes.AccessNode)
and not isinstance(dst_node, nodes.CodeNode))):
continue
# Skip array->code (will be handled as a tasklet input)
if isinstance(node, nodes.AccessNode) and isinstance(
v, nodes.CodeNode):
continue
# code->code (e.g., tasklet to tasklet)
if isinstance(v, nodes.CodeNode):
shared_data_name = 's%d_n%d%s_n%d%s' % (
state_id, dfg.node_id(edge.src), edge.src_conn,
dfg.node_id(edge.dst), edge.dst_conn)
result.write('__%s = %s;' % (shared_data_name, edge.src_conn),
sdfg, state_id, [edge.src, edge.dst])
continue
# If the memlet is not pointing to a data node (e.g. tasklet), then
# the tasklet will take care of the copy
if not isinstance(dst_node, nodes.AccessNode):
continue
# If the memlet is pointing into an array in an inner scope, then
# the inner scope (i.e., the output array) must handle it
if (scope_dict[node] != scope_dict[dst_node]
and scope_contains_scope(scope_dict, node, dst_node)):
continue
# Array to tasklet (path longer than 1, handled at tasklet entry)
if node == dst_node:
continue
# Tasklet -> array
if isinstance(node, nodes.CodeNode):
if not uconn:
raise SyntaxError(
'Cannot copy memlet without a local connector: {} to {}'
.format(str(edge.src), str(edge.dst)))
try:
positive_accesses = bool(memlet.num_accesses >= 0)
except TypeError:
positive_accesses = False
if memlet.subset.data_dims() == 0 and positive_accesses:
out_local_name = ' __' + uconn
in_local_name = uconn
if not locals_defined:
out_local_name = self.memlet_ctor(sdfg, memlet, True)
in_memlets = [
d for _, _, _, _, d in dfg.in_edges(node)
]
assert len(in_memlets) == 1
in_local_name = self.memlet_ctor(
sdfg, in_memlets[0], False)
state_dfg = sdfg.nodes()[state_id]
if memlet.wcr is not None:
nc = not is_write_conflicted(dfg, edge)
result.write(
write_and_resolve_expr(memlet, nc, out_local_name,
in_local_name), sdfg,
state_id, node)
else:
result.write(
'%s.write(%s);\n' % (out_local_name,
in_local_name), sdfg,
state_id, node)
# Dispatch array-to-array outgoing copies here
elif isinstance(node, nodes.AccessNode):
if dst_node != node and not isinstance(dst_node,
nodes.Tasklet):
dispatcher.dispatch_copy(node, dst_node, edge, sdfg, dfg,
state_id, function_stream, result)
def memlet_view_ctor(self, sdfg, memlet, is_output):
memlet_params = []
memlet_name = memlet.data
def_type = self._dispatcher.defined_vars.get(memlet_name)
if def_type == DefinedType.Pointer:
memlet_expr = memlet_name # Common case
elif (def_type == DefinedType.Scalar
or def_type == DefinedType.ScalarView):
memlet_expr = '&' + memlet_name
elif def_type == DefinedType.ArrayView:
memlet_expr = memlet_name + ".ptr()"
else:
raise TypeError("Unsupported connector type {}".format(def_type))
if isinstance(memlet.subset, subsets.Indices):
# FIXME: _packed_types influences how this offset is
# generated from the FPGA codegen. We should find a nicer solution.
if self._packed_types is True:
offset = cpp_array_expr(
sdfg, memlet, False, packed_veclen=memlet.veclen)
else:
offset = cpp_array_expr(sdfg, memlet, False)
# Compute address
memlet_params.append(memlet_expr + ' + ' + offset)
dims = 0
else:
if isinstance(memlet.subset, subsets.Range):
dims = len(memlet.subset.ranges)
# FIXME: _packed_types influences how this offset is
# generated from the FPGA codegen. We should find a nicer
# solution.
if self._packed_types is True:
offset = cpp_offset_expr(
sdfg.arrays[memlet.data],
memlet.subset,
packed_veclen=memlet.veclen)
else:
offset = cpp_offset_expr(sdfg.arrays[memlet.data],
memlet.subset)
if offset == "0":
memlet_params.append(memlet_expr)
else:
if (def_type not in [
DefinedType.Pointer, DefinedType.ArrayView
]):
raise dace.codegen.codegen.CodegenError(
"Cannot offset address of connector {} of type {}".
format(memlet_name, def_type))
memlet_params.append(memlet_expr + ' + ' + offset)
# Dimensions to remove from view (due to having one value)
indexdims = []
# Figure out dimensions for scalar version
for dim, (rb, re, rs) in enumerate(memlet.subset.ranges):
try:
if (re - rb) == 0:
indexdims.append(dim)
except TypeError: # cannot determine truth value of Relational
pass
# Remove index (one scalar) dimensions
dims -= len(indexdims)
if dims > 0:
strides = memlet.subset.absolute_strides(
sdfg.arrays[memlet.data].strides)
# Filter out index dims
strides = [
s for i, s in enumerate(strides) if i not in indexdims
]
# FIXME: _packed_types influences how this offset is
# generated from the FPGA codegen. We should find a nicer
# solution.
if self._packed_types and memlet.veclen > 1:
for i in range(len(strides) - 1):
strides[i] /= memlet.veclen
memlet_params.extend(sym2cpp(strides))
dims = memlet.subset.data_dims()
else:
raise RuntimeError(
'Memlet type "%s" not implemented' % memlet.subset)
if memlet.num_accesses == 1:
num_accesses_str = "1"
else: # symbolic.issymbolic(memlet.num_accesses, sdfg.constants):
num_accesses_str = 'dace::NA_RUNTIME'
return 'dace::ArrayView%s<%s, %d, %s, %s> (%s)' % (
"Out"
if is_output else "In", sdfg.arrays[memlet.data].dtype.ctype, dims,
sym2cpp(memlet.veclen), num_accesses_str, ', '.join(memlet_params))
def memlet_definition(self, sdfg, memlet, output, local_name):
result = ('auto __%s = ' % local_name + self.memlet_ctor(
sdfg, memlet, output) + ';\n')
# Allocate variable type
memlet_type = 'dace::vec<%s, %s>' % (
sdfg.arrays[memlet.data].dtype.ctype, sym2cpp(memlet.veclen))
var_type = self._dispatcher.defined_vars.get(memlet.data)
# ** Concerning aligned vs. non-aligned values:
# We prefer aligned values, so in every case where we are assigning to
# a local _value_, we explicitly assign to an aligned type
# (memlet_type). In all other cases, where we need either a pointer or
# a reference, typically due to variable number of accesses, we have to
# use the underlying type of the ArrayView, be it aligned or unaligned,
# to avoid runtime crashes. We use auto for this, so the ArrayView can
# return whatever it supports.
if var_type == DefinedType.Scalar:
if memlet.num_accesses == 1:
if not output:
# We can pre-read the value
result += "{} {} = __{}.val<{}>();".format(
memlet_type, local_name, local_name, memlet.veclen)
else:
# The value will be written during the tasklet, and will be
# automatically written out after
result += "{} {};".format(memlet_type, local_name)
self._dispatcher.defined_vars.add(local_name,
DefinedType.Scalar)
elif memlet.num_accesses == -1:
if output:
# Variable number of writes: get reference to the target of
# the view to reflect writes at the data
result += "auto &{} = __{}.ref<{}>();".format(
local_name, local_name, memlet.veclen)
else:
# Variable number of reads: get a const reference that can
# be read if necessary
result += "auto const &{} = __{}.ref<{}>();".format(
local_name, local_name, memlet.veclen)
self._dispatcher.defined_vars.add(local_name,
DefinedType.Scalar)
else:
raise dace.codegen.codegen.CodegenError(
"Unsupported number of accesses {} for scalar {}".format(
memlet.num_accesses, local_name))
elif var_type == DefinedType.Pointer:
if memlet.num_accesses == 1:
if output:
result += "{} {};".format(memlet_type, local_name)
else:
result += "{} {} = __{}.val<{}>();".format(
memlet_type, local_name, local_name, memlet.veclen)
self._dispatcher.defined_vars.add(local_name,
DefinedType.Scalar)
else:
if memlet.subset.data_dims() == 0:
# Forward ArrayView
result += "auto &{} = __{}.ref<{}>();".format(
local_name, local_name, memlet.veclen)
self._dispatcher.defined_vars.add(local_name,
DefinedType.Scalar)
else:
result += "auto *{} = __{}.ptr<{}>();".format(
local_name, local_name, memlet.veclen)
self._dispatcher.defined_vars.add(local_name,
DefinedType.Pointer)
elif (var_type == DefinedType.Stream
or var_type == DefinedType.StreamArray):
if memlet.num_accesses == 1:
if output:
result += "{} {};".format(memlet_type, local_name)
else:
result += "auto {} = __{}.pop();".format(
local_name, local_name)
self._dispatcher.defined_vars.add(local_name,
DefinedType.Scalar)
else:
# Just forward actions to the underlying object
result += "auto &{} = __{};".format(local_name, local_name)
self._dispatcher.defined_vars.add(local_name,
DefinedType.Stream)
else:
raise TypeError("Unknown variable type: {}".format(var_type))
return result
def memlet_stream_ctor(self, sdfg, memlet):
stream = sdfg.arrays[memlet.data]
dtype = "dace::vec<{}, {}>".format(stream.dtype.ctype,
symbolic.symstr(memlet.veclen))
return "dace::make_streamview({})".format(memlet.data + (
"[{}]".format(cpp_offset_expr(stream, memlet.subset))
if isinstance(stream, dace.data.Stream)
and stream.is_stream_array() else ""))
def memlet_ctor(self, sdfg, memlet, is_output):
def_type = self._dispatcher.defined_vars.get(memlet.data)
if (def_type == DefinedType.Stream
or def_type == DefinedType.StreamArray):
return self.memlet_stream_ctor(sdfg, memlet)
elif (def_type == DefinedType.Pointer or def_type == DefinedType.Scalar
or def_type == DefinedType.ScalarView
or def_type == DefinedType.ArrayView):
return self.memlet_view_ctor(sdfg, memlet, is_output)
else:
raise NotImplementedError(
"Connector type {} not yet implemented".format(def_type))
def copy_expr(self,
sdfg,
dataname,
memlet,
offset=None,
relative_offset=True,
packed_types=False):
datadesc = sdfg.arrays[dataname]
if relative_offset:
s = memlet.subset
o = offset
else:
if offset is None:
s = None
elif not isinstance(offset, subsets.Subset):
s = subsets.Indices(offset)
else:
s = offset
o = None
if s != None:
offset_cppstr = cpp_offset_expr(
datadesc, s, o, memlet.veclen if packed_types else 1)
else:
offset_cppstr = '0'
dt = ''
if memlet.veclen != 1 and not packed_types:
offset_cppstr = '(%s) / %s' % (offset_cppstr, sym2cpp(
memlet.veclen))
dt = '(dace::vec<%s, %s> *)' % (datadesc.dtype.ctype,
sym2cpp(memlet.veclen))
expr = dataname
def_type = self._dispatcher.defined_vars.get(dataname)
add_offset = (offset_cppstr != "0")
if def_type == DefinedType.Pointer:
return "{}{}{}".format(
dt, expr, " + {}".format(offset_cppstr) if add_offset else "")
elif def_type == DefinedType.ArrayView:
return "{}{}.ptr(){}".format(
dt, expr, " + {}".format(offset_cppstr) if add_offset else "")
elif def_type == DefinedType.StreamArray:
return "{}[{}]".format(expr, offset_cppstr)
elif (def_type == DefinedType.Scalar
or def_type == DefinedType.ScalarView
or def_type == DefinedType.Stream):
if add_offset:
raise TypeError(
"Tried to offset address of scalar {}: {}".format(
dataname, offset_cppstr))
if (def_type == DefinedType.Scalar
or def_type == DefinedType.ScalarView):
return "{}&{}".format(dt, expr)
else:
return dataname
else:
raise NotImplementedError(
"copy_expr not implemented "
"for connector type: {}".format(def_type))
def memlet_copy_to_absolute_strides(self,
sdfg,
memlet,
src_node,
dst_node,
packed_types=False):
# Ignore vectorization flag is a hack to accommmodate FPGA behavior,
# where the pointer type is changed to a vector type, and addresses
# thus shouldn't take vectorization into account.
copy_shape = memlet.subset.size()
copy_shape = [symbolic.overapproximate(s) for s in copy_shape]
src_nodedesc = src_node.desc(sdfg)
dst_nodedesc = dst_node.desc(sdfg)
if memlet.data == src_node.data:
src_expr = self.copy_expr(
sdfg, src_node.data, memlet, packed_types=packed_types)
dst_expr = self.copy_expr(
sdfg,
dst_node.data,
memlet,
None,
False,
packed_types=packed_types)
if memlet.other_subset is not None:
dst_expr = self.copy_expr(
sdfg,
dst_node.data,
memlet,
memlet.other_subset,
False,