/
parfor_lowering.py
2042 lines (1818 loc) · 84.8 KB
/
parfor_lowering.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 copy
import operator
import types as pytypes
import operator
import warnings
from dataclasses import make_dataclass
import llvmlite.ir
import numpy as np
import numba
from numba.parfors import parfor
from numba.core import types, ir, config, compiler, sigutils, cgutils
from numba.core.ir_utils import (
add_offset_to_labels,
replace_var_names,
remove_dels,
legalize_names,
rename_labels,
get_name_var_table,
visit_vars_inner,
get_definition,
guard,
get_call_table,
is_pure,
get_np_ufunc_typ,
get_unused_var_name,
is_const_call,
fixup_var_define_in_scope,
transfer_scope,
find_max_label,
get_global_func_typ,
)
from numba.core.typing import signature
from numba.core import lowering
from numba.parfors.parfor import ensure_parallel_support
from numba.core.errors import (
NumbaParallelSafetyWarning, NotDefinedError, CompilerError, InternalError,
)
from numba.parfors.parfor_lowering_utils import ParforLoweringBuilder
class ParforLower(lowering.Lower):
"""This is a custom lowering class that extends standard lowering so as
to accommodate parfor.Parfor nodes."""
# custom instruction lowering to handle parfor nodes
def lower_inst(self, inst):
if isinstance(inst, parfor.Parfor):
_lower_parfor_parallel(self, inst)
else:
super().lower_inst(inst)
@property
def _disable_sroa_like_opt(self):
"""
Force disable this because Parfor use-defs is incompatible---it only
considers use-defs in blocks that must be executing.
See https://github.com/numba/numba/commit/017e2ff9db87fc34149b49dd5367ecbf0bb45268
"""
return True
def _lower_parfor_parallel(lowerer, parfor):
if parfor.lowerer is None:
return _lower_parfor_parallel_std(lowerer, parfor)
else:
return parfor.lowerer(lowerer, parfor)
def _lower_parfor_parallel_std(lowerer, parfor):
"""Lowerer that handles LLVM code generation for parfor.
This function lowers a parfor IR node to LLVM.
The general approach is as follows:
1) The code from the parfor's init block is lowered normally
in the context of the current function.
2) The body of the parfor is transformed into a gufunc function.
3) Code is inserted into the main function that calls do_scheduling
to divide the iteration space for each thread, allocates
reduction arrays, calls the gufunc function, and then invokes
the reduction function across the reduction arrays to produce
the final reduction values.
"""
from numba.np.ufunc.parallel import get_thread_count
ensure_parallel_support()
typingctx = lowerer.context.typing_context
targetctx = lowerer.context
builder = lowerer.builder
# We copy the typemap here because for race condition variable we'll
# update their type to array so they can be updated by the gufunc.
orig_typemap = lowerer.fndesc.typemap
# replace original typemap with copy and restore the original at the end.
lowerer.fndesc.typemap = copy.copy(orig_typemap)
if config.DEBUG_ARRAY_OPT:
print("lowerer.fndesc", lowerer.fndesc, type(lowerer.fndesc))
typemap = lowerer.fndesc.typemap
varmap = lowerer.varmap
if config.DEBUG_ARRAY_OPT:
print("_lower_parfor_parallel")
parfor.dump()
loc = parfor.init_block.loc
scope = parfor.init_block.scope
# produce instructions for init_block
if config.DEBUG_ARRAY_OPT:
print("init_block = ", parfor.init_block, " ", type(parfor.init_block))
for instr in parfor.init_block.body:
if config.DEBUG_ARRAY_OPT:
print("lower init_block instr = ", instr)
lowerer.lower_inst(instr)
for racevar in parfor.races:
if racevar not in varmap:
rvtyp = typemap[racevar]
rv = ir.Var(scope, racevar, loc)
lowerer._alloca_var(rv.name, rvtyp)
alias_map = {}
arg_aliases = {}
numba.parfors.parfor.find_potential_aliases_parfor(parfor, parfor.params, typemap,
lowerer.func_ir, alias_map, arg_aliases)
if config.DEBUG_ARRAY_OPT:
print("alias_map", alias_map)
print("arg_aliases", arg_aliases)
# run get_parfor_outputs() and get_parfor_reductions() before gufunc creation
# since Jumps are modified so CFG of loop_body dict will become invalid
assert parfor.params is not None
parfor_output_arrays = numba.parfors.parfor.get_parfor_outputs(
parfor, parfor.params)
parfor_redvars, parfor_reddict = parfor.redvars, parfor.reddict
if config.DEBUG_ARRAY_OPT:
print("parfor_redvars:", parfor_redvars)
print("parfor_reddict:", parfor_reddict)
# init reduction array allocation here.
nredvars = len(parfor_redvars)
redarrs = {}
to_cleanup = []
if nredvars > 0:
# reduction arrays outer dimension equal to thread count
scope = parfor.init_block.scope
loc = parfor.init_block.loc
pfbdr = ParforLoweringBuilder(lowerer=lowerer, scope=scope, loc=loc)
# Get the Numba internal function to call to get the thread count.
get_num_threads = pfbdr.bind_global_function(
fobj=numba.np.ufunc.parallel._iget_num_threads,
ftype=get_global_func_typ(numba.np.ufunc.parallel._iget_num_threads),
args=()
)
# Insert the call to assign the thread count to a variable.
num_threads_var = pfbdr.assign(
rhs=pfbdr.call(get_num_threads, args=[]),
typ=types.intp,
name="num_threads_var")
# For each reduction variable...
for i in range(nredvars):
red_name = parfor_redvars[i]
# Get the type of the reduction variable.
redvar_typ = lowerer.fndesc.typemap[red_name]
# Get the ir.Var for the reduction variable.
redvar = ir.Var(scope, red_name, loc)
# Get the type of the array that holds the per-thread
# reduction variables.
redarrvar_typ = redtyp_to_redarraytype(redvar_typ)
reddtype = redarrvar_typ.dtype
if config.DEBUG_ARRAY_OPT:
print(
"reduction_info",
red_name,
redvar_typ,
redarrvar_typ,
reddtype,
types.DType(reddtype),
num_threads_var,
type(num_threads_var)
)
# If this is reduction over an array,
# the reduction array has just one added per-worker dimension.
if isinstance(redvar_typ, types.npytypes.Array):
redarrdim = redvar_typ.ndim + 1
else:
redarrdim = 1
# Reduction array is created and initialized to the initial reduction value.
# First create a var for the numpy empty ufunc.
glbl_np_empty = pfbdr.bind_global_function(
fobj=np.empty,
ftype=get_np_ufunc_typ(np.empty),
args=(
types.UniTuple(types.intp, redarrdim),
),
kws={'dtype': types.DType(reddtype)}
)
size_var_list = [num_threads_var]
# If this is a reduction over an array...
if isinstance(redvar_typ, types.npytypes.Array):
# Add code to get the shape of the array being reduced over.
redshape_var = pfbdr.assign(
rhs=ir.Expr.getattr(redvar, "shape", loc),
typ=types.UniTuple(types.intp, redvar_typ.ndim),
name="redarr_shape",
)
# Add the dimension sizes of the array being reduced over to the tuple of sizes pass to empty.
for j in range(redvar_typ.ndim):
onedimvar = pfbdr.assign(
rhs=ir.Expr.static_getitem(redshape_var, j, None, loc),
typ=types.intp,
name="redshapeonedim",
)
size_var_list.append(onedimvar)
# Empty call takes tuple of sizes. Create here and fill in outer dimension (num threads).
size_var = pfbdr.make_tuple_variable(
size_var_list, name='tuple_size_var',
)
# Resolve dtype
cval = pfbdr._typingctx.resolve_value_type(reddtype)
dt = pfbdr.make_const_variable(cval=cval, typ=types.DType(reddtype))
# Add call to empty passing the size var tuple.
empty_call = pfbdr.call(glbl_np_empty, args=[size_var, dt])
redarr_var = pfbdr.assign(
rhs=empty_call, typ=redarrvar_typ, name="redarr",
)
# Remember mapping of original reduction array to the newly created per-worker reduction array.
redarrs[redvar.name] = redarr_var
to_cleanup.append(redarr_var)
init_val = parfor_reddict[red_name].init_val
if init_val is not None:
if isinstance(redvar_typ, types.npytypes.Array):
# Create an array of identity values for the reduction.
# First, create a variable for np.full.
full_func_node = pfbdr.bind_global_function(
fobj=np.full,
ftype=get_np_ufunc_typ(np.full),
args=(
types.UniTuple(types.intp, redvar_typ.ndim),
reddtype,
),
kws={'dtype': types.DType(reddtype)},
)
# Then create a var with the identify value.
init_val_var = pfbdr.make_const_variable(
cval=init_val,
typ=reddtype,
name="init_val",
)
# Then, call np.full with the shape of the reduction array and the identity value.
full_call = pfbdr.call(
full_func_node, args=[redshape_var, init_val_var, dt],
)
redtoset = pfbdr.assign(
rhs=full_call,
typ=redvar_typ,
name="redtoset",
)
# rettoset is an array from np.full() and must be released
to_cleanup.append(redtoset)
else:
redtoset = pfbdr.make_const_variable(
cval=init_val,
typ=reddtype,
name="redtoset",
)
else:
redtoset = redvar
if config.DEBUG_ARRAY_OPT_RUNTIME:
res_print_str = "res_print1 for redvar " + str(redvar) + ":"
strconsttyp = types.StringLiteral(res_print_str)
lhs = pfbdr.make_const_variable(
cval=res_print_str,
typ=strconsttyp,
name="str_const",
)
res_print = ir.Print(args=[lhs, redvar],
vararg=None, loc=loc)
lowerer.fndesc.calltypes[res_print] = signature(types.none,
typemap[lhs.name],
typemap[redvar.name])
print("res_print_redvar", res_print)
lowerer.lower_inst(res_print)
# For each thread, initialize the per-worker reduction array to
# the current reduction array value.
# Get the Numba type of the variable that holds the thread count.
num_thread_type = typemap[num_threads_var.name]
# Get the LLVM type of the thread count variable.
ntllvm_type = targetctx.get_value_type(num_thread_type)
# Create a LLVM variable to hold the loop index.
alloc_loop_var = cgutils.alloca_once(builder, ntllvm_type)
# Associate this LLVM variable to a Numba IR variable so that
# we can use setitem IR builder.
# Create a Numba IR variable.
numba_ir_loop_index_var = scope.redefine("$loop_index", loc)
# Give that variable the right type.
typemap[numba_ir_loop_index_var.name] = num_thread_type
# Associate this Numba variable to the LLVM variable in the
# lowerer's varmap.
lowerer.varmap[numba_ir_loop_index_var.name] = alloc_loop_var
# Insert a loop into the outputed LLVM that goes from 0 to
# the current thread count.
with cgutils.for_range(builder, lowerer.loadvar(num_threads_var.name), intp=ntllvm_type) as loop:
# Store the loop index into the alloca'd LLVM loop index variable.
builder.store(loop.index, alloc_loop_var)
# Initialize one element of the reduction array using the Numba
# IR variable associated with this loop's index.
pfbdr.setitem(obj=redarr_var, index=numba_ir_loop_index_var, val=redtoset)
# compile parfor body as a separate function to be used with GUFuncWrapper
flags = parfor.flags.copy()
flags.error_model = "numpy"
# Can't get here unless flags.auto_parallel == ParallelOptions(True)
index_var_typ = typemap[parfor.loop_nests[0].index_variable.name]
# index variables should have the same type, check rest of indices
for l in parfor.loop_nests[1:]:
assert typemap[l.index_variable.name] == index_var_typ
numba.parfors.parfor.sequential_parfor_lowering = True
try:
(func,
func_args,
func_sig,
func_arg_types,
exp_name_to_tuple_var) = _create_gufunc_for_parfor_body(
lowerer, parfor, typemap, typingctx, targetctx, flags, {},
bool(alias_map), index_var_typ, parfor.races)
finally:
numba.parfors.parfor.sequential_parfor_lowering = False
# get the shape signature
func_args = ['sched'] + func_args
num_reductions = len(parfor_redvars)
num_inputs = len(func_args) - len(parfor_output_arrays) - num_reductions
if config.DEBUG_ARRAY_OPT:
print("func_args = ", func_args)
print("num_inputs = ", num_inputs)
print("parfor_outputs = ", parfor_output_arrays)
print("parfor_redvars = ", parfor_redvars)
print("num_reductions = ", num_reductions)
gu_signature = _create_shape_signature(
parfor.get_shape_classes,
num_inputs,
num_reductions,
func_args,
func_sig,
parfor.races,
typemap)
if config.DEBUG_ARRAY_OPT:
print("gu_signature = ", gu_signature)
# call the func in parallel by wrapping it with ParallelGUFuncBuilder
loop_ranges = [(l.start, l.stop, l.step) for l in parfor.loop_nests]
if config.DEBUG_ARRAY_OPT:
print("loop_nests = ", parfor.loop_nests)
print("loop_ranges = ", loop_ranges)
call_parallel_gufunc(
lowerer,
func,
gu_signature,
func_sig,
func_args,
func_arg_types,
loop_ranges,
parfor_redvars,
parfor_reddict,
redarrs,
parfor.init_block,
index_var_typ,
parfor.races,
exp_name_to_tuple_var)
if nredvars > 0:
_parfor_lowering_finalize_reduction(
parfor, redarrs, lowerer, parfor_reddict, num_threads_var,
)
# Cleanup reduction variable
for v in to_cleanup:
lowerer.lower_inst(ir.Del(v.name, loc=loc))
# Restore the original typemap of the function that was replaced temporarily at the
# Beginning of this function.
lowerer.fndesc.typemap = orig_typemap
if config.DEBUG_ARRAY_OPT:
print("_lower_parfor_parallel done")
_ReductionInfo = make_dataclass(
"_ReductionInfo",
[
"redvar_info",
"redvar_name",
"redvar_typ",
"redarr_var",
"redarr_typ",
"init_val",
],
frozen=True,
)
def _parfor_lowering_finalize_reduction(
parfor,
redarrs,
lowerer,
parfor_reddict,
thread_count_var,
):
"""Emit code to finalize the reduction from the intermediate values of
each thread.
"""
# For each reduction variable
for redvar_name, redarr_var in redarrs.items():
# Pseudo-code for this loop body:
# tmp = redarr[0]
# for i in range(1, thread_count):
# tmp = reduce_op(redarr[i], tmp)
# reduction_result = tmp
redvar_typ = lowerer.fndesc.typemap[redvar_name]
redarr_typ = lowerer.fndesc.typemap[redarr_var.name]
init_val = lowerer.loadvar(redvar_name)
reduce_info = _ReductionInfo(
redvar_info = parfor_reddict[redvar_name],
redvar_name=redvar_name,
redvar_typ=redvar_typ,
redarr_var=redarr_var,
redarr_typ=redarr_typ,
init_val=init_val,
)
# generate code for combining reduction variable with thread output
handler = (_lower_trivial_inplace_binops
if reduce_info.redvar_info.redop is not None
else _lower_non_trivial_reduce)
handler(parfor, lowerer, thread_count_var, reduce_info)
class ParforsUnexpectedReduceNodeError(InternalError):
def __init__(self, inst):
super().__init__(f"Unknown reduce instruction node: {inst}")
def _lower_trivial_inplace_binops(parfor, lowerer, thread_count_var, reduce_info):
"""Lower trivial inplace-binop reduction.
"""
for inst in reduce_info.redvar_info.reduce_nodes:
# Var assigns to Var?
if _lower_var_to_var_assign(lowerer, inst):
pass
# Is inplace-binop for the reduction?
elif _is_right_op_and_rhs_is_init(inst, reduce_info.redvar_name, "inplace_binop"):
fn = inst.value.fn
redvar_result = _emit_binop_reduce_call(
fn, lowerer, thread_count_var, reduce_info,
)
lowerer.storevar(redvar_result, name=inst.target.name)
# Is binop for the reduction?
elif _is_right_op_and_rhs_is_init(inst, reduce_info.redvar_name, "binop"):
fn = inst.value.fn
redvar_result = _emit_binop_reduce_call(
fn, lowerer, thread_count_var, reduce_info,
)
lowerer.storevar(redvar_result, name=inst.target.name)
# Otherwise?
else:
raise ParforsUnexpectedReduceNodeError(inst)
# XXX: This seems like a hack to stop the loop with this condition.
if _fix_redvar_name_ssa_mismatch(parfor, lowerer, inst,
reduce_info.redvar_name):
break
if config.DEBUG_ARRAY_OPT_RUNTIME:
varname = reduce_info.redvar_name
lowerer.print_variable(
f"{parfor.loc}: parfor {fn.__name__} reduction {varname} =",
varname,
)
def _lower_non_trivial_reduce(parfor, lowerer, thread_count_var, reduce_info):
"""Lower non-trivial reduction such as call to `functools.reduce()`.
"""
init_name = f"{reduce_info.redvar_name}#init"
# The init_name variable is not defined at this point.
lowerer.fndesc.typemap.setdefault(init_name, reduce_info.redvar_typ)
# Emit a sequence of the reduction operation for each intermediate result
# of each thread.
num_thread_llval = lowerer.loadvar(thread_count_var.name)
with cgutils.for_range(lowerer.builder, num_thread_llval) as loop:
tid = loop.index
for inst in reduce_info.redvar_info.reduce_nodes:
# Var assigns to Var?
if _lower_var_to_var_assign(lowerer, inst):
pass
# The reduction operation?
elif (isinstance(inst, ir.Assign)
and any(var.name == init_name for var in inst.list_vars())):
elem = _emit_getitem_call(tid, lowerer, reduce_info)
lowerer.storevar(elem, init_name)
lowerer.lower_inst(inst)
# Otherwise?
else:
raise ParforsUnexpectedReduceNodeError(inst)
# XXX: This seems like a hack to stop the loop with this condition.
if _fix_redvar_name_ssa_mismatch(parfor, lowerer, inst,
reduce_info.redvar_name):
break
if config.DEBUG_ARRAY_OPT_RUNTIME:
varname = reduce_info.redvar_name
lowerer.print_variable(
f"{parfor.loc}: parfor non-trivial reduction {varname} =",
varname,
)
def _lower_var_to_var_assign(lowerer, inst):
"""Lower Var->Var assignment.
Returns True if-and-only-if `inst` is a Var->Var assignment.
"""
if isinstance(inst, ir.Assign) and isinstance(inst.value, ir.Var):
loaded = lowerer.loadvar(inst.value.name)
lowerer.storevar(loaded, name=inst.target.name)
return True
return False
def _emit_getitem_call(idx, lowerer, reduce_info):
"""Emit call to ``redarr_var[idx]``
"""
def reducer_getitem(redarr, index):
return redarr[index]
builder = lowerer.builder
ctx = lowerer.context
redarr_typ = reduce_info.redarr_typ
arg_arr = lowerer.loadvar(reduce_info.redarr_var.name)
args = (arg_arr, idx)
sig = signature(reduce_info.redvar_typ, redarr_typ, types.intp)
elem = ctx.compile_internal(builder, reducer_getitem, sig, args)
return elem
def _emit_binop_reduce_call(binop, lowerer, thread_count_var, reduce_info):
"""Emit call to the ``binop`` for the reduction variable.
"""
def reduction_add(thread_count, redarr, init):
c = init
for i in range(thread_count):
c += redarr[i]
return c
def reduction_mul(thread_count, redarr, init):
c = init
for i in range(thread_count):
c *= redarr[i]
return c
kernel = {
operator.iadd: reduction_add,
operator.isub: reduction_add,
operator.add: reduction_add,
operator.sub: reduction_add,
operator.imul: reduction_mul,
operator.ifloordiv: reduction_mul,
operator.itruediv: reduction_mul,
operator.mul: reduction_mul,
operator.floordiv: reduction_mul,
operator.truediv: reduction_mul,
}[binop]
ctx = lowerer.context
builder = lowerer.builder
redarr_typ = reduce_info.redarr_typ
arg_arr = lowerer.loadvar(reduce_info.redarr_var.name)
if config.DEBUG_ARRAY_OPT_RUNTIME:
init_var = reduce_info.redarr_var.scope.get(reduce_info.redvar_name)
res_print = ir.Print(
args=[reduce_info.redarr_var, init_var], vararg=None,
loc=lowerer.loc,
)
typemap = lowerer.fndesc.typemap
lowerer.fndesc.calltypes[res_print] = signature(
types.none, typemap[reduce_info.redarr_var.name],
typemap[init_var.name],
)
lowerer.lower_inst(res_print)
arg_thread_count = lowerer.loadvar(thread_count_var.name)
args = (arg_thread_count, arg_arr, reduce_info.init_val)
sig = signature(
reduce_info.redvar_typ, types.uintp, redarr_typ, reduce_info.redvar_typ,
)
redvar_result = ctx.compile_internal(builder, kernel, sig, args)
return redvar_result
def _is_right_op_and_rhs_is_init(inst, redvar_name, op):
"""Is ``inst`` an inplace-binop and the RHS is the reduction init?
"""
if not isinstance(inst, ir.Assign):
return False
rhs = inst.value
if not isinstance(rhs, ir.Expr):
return False
if rhs.op != op:
return False
if rhs.rhs.name != f"{redvar_name}#init":
return False
return True
def _fix_redvar_name_ssa_mismatch(parfor, lowerer, inst, redvar_name):
"""Fix reduction variable name mismatch due to SSA.
"""
# Only process reduction statements post-gufunc execution
# until we see an assignment with a left-hand side to the
# reduction variable's name. This fixes problems with
# cases where there are multiple assignments to the
# reduction variable in the parfor.
scope = parfor.init_block.scope
if isinstance(inst, ir.Assign):
try:
reduction_var = scope.get_exact(redvar_name)
except NotDefinedError:
# Ideally, this shouldn't happen. The redvar name
# missing from scope indicates an error from
# other rewrite passes.
is_same_source_var = redvar_name == inst.target.name
else:
# Because of SSA, the redvar and target var of
# the current assignment would be different even
# though they refer to the same source-level var.
redvar_unver_name = reduction_var.unversioned_name
target_unver_name = inst.target.unversioned_name
is_same_source_var = redvar_unver_name == target_unver_name
if is_same_source_var:
# If redvar is different from target var, add an
# assignment to put target var into redvar.
if redvar_name != inst.target.name:
val = lowerer.loadvar(inst.target.name)
lowerer.storevar(val, name=redvar_name)
return True
return False
def _create_shape_signature(
get_shape_classes,
num_inputs,
num_reductions,
args,
func_sig,
races,
typemap):
'''Create shape signature for GUFunc
'''
if config.DEBUG_ARRAY_OPT:
print("_create_shape_signature", num_inputs, num_reductions, args, races)
for i in args[1:]:
print("argument", i, type(i), get_shape_classes(i, typemap=typemap))
num_inouts = len(args) - num_reductions
# maximum class number for array shapes
classes = [get_shape_classes(var, typemap=typemap) if var not in races else (-1,) for var in args[1:]]
class_set = set()
for _class in classes:
if _class:
for i in _class:
class_set.add(i)
max_class = max(class_set) + 1 if class_set else 0
classes.insert(0, (max_class,)) # force set the class of 'sched' argument
class_set.add(max_class)
thread_num_class = max_class + 1
class_set.add(thread_num_class)
class_map = {}
# TODO: use prefix + class number instead of single char
alphabet = ord('a')
for n in class_set:
if n >= 0:
class_map[n] = chr(alphabet)
alphabet += 1
threadcount_ordinal = chr(alphabet)
alpha_dict = {'latest_alpha' : alphabet}
def bump_alpha(c, class_map):
if c >= 0:
return class_map[c]
else:
alpha_dict['latest_alpha'] += 1
return chr(alpha_dict['latest_alpha'])
gu_sin = []
gu_sout = []
count = 0
syms_sin = ()
if config.DEBUG_ARRAY_OPT:
print("args", args)
print("classes", classes)
print("threadcount_ordinal", threadcount_ordinal)
for cls, arg in zip(classes, args):
count = count + 1
if cls:
dim_syms = tuple(bump_alpha(c, class_map) for c in cls)
else:
dim_syms = ()
if (count > num_inouts):
# Add the threadcount_ordinal to represent the thread count
# to the start of the reduction array.
gu_sin.append(tuple([threadcount_ordinal] + list(dim_syms[1:])))
else:
gu_sin.append(dim_syms)
syms_sin += dim_syms
return (gu_sin, gu_sout)
def _print_block(block):
for i, inst in enumerate(block.body):
print(" ", i, " ", inst)
def _print_body(body_dict):
'''Pretty-print a set of IR blocks.
'''
for label, block in body_dict.items():
print("label: ", label)
_print_block(block)
def wrap_loop_body(loop_body):
blocks = loop_body.copy() # shallow copy is enough
first_label = min(blocks.keys())
last_label = max(blocks.keys())
loc = blocks[last_label].loc
blocks[last_label].body.append(ir.Jump(first_label, loc))
return blocks
def unwrap_loop_body(loop_body):
last_label = max(loop_body.keys())
loop_body[last_label].body = loop_body[last_label].body[:-1]
def add_to_def_once_sets(a_def, def_once, def_more):
'''If the variable is already defined more than once, do nothing.
Else if defined exactly once previously then transition this
variable to the defined more than once set (remove it from
def_once set and add to def_more set).
Else this must be the first time we've seen this variable defined
so add to def_once set.
'''
if a_def in def_more:
pass
elif a_def in def_once:
def_more.add(a_def)
def_once.remove(a_def)
else:
def_once.add(a_def)
def compute_def_once_block(block, def_once, def_more, getattr_taken, typemap, module_assigns):
'''Effect changes to the set of variables defined once or more than once
for a single block.
block - the block to process
def_once - set of variable names known to be defined exactly once
def_more - set of variable names known to be defined more than once
getattr_taken - dict mapping variable name to tuple of object and attribute taken
module_assigns - dict mapping variable name to the Global that they came from
'''
# The only "defs" occur in assignments, so find such instructions.
assignments = block.find_insts(ir.Assign)
# For each assignment...
for one_assign in assignments:
# Get the LHS/target of the assignment.
a_def = one_assign.target.name
# Add variable to def sets.
add_to_def_once_sets(a_def, def_once, def_more)
rhs = one_assign.value
if isinstance(rhs, ir.Global):
# Remember assignments of the form "a = Global(...)"
# Is this a module?
if isinstance(rhs.value, pytypes.ModuleType):
module_assigns[a_def] = rhs.value.__name__
if isinstance(rhs, ir.Expr) and rhs.op == 'getattr' and rhs.value.name in def_once:
# Remember assignments of the form "a = b.c"
getattr_taken[a_def] = (rhs.value.name, rhs.attr)
if isinstance(rhs, ir.Expr) and rhs.op == 'call' and rhs.func.name in getattr_taken:
# If "a" is being called then lookup the getattr definition of "a"
# as above, getting the module variable "b" (base_obj)
# and the attribute "c" (base_attr).
base_obj, base_attr = getattr_taken[rhs.func.name]
if base_obj in module_assigns:
# If we know the definition of the module variable then get the module
# name from module_assigns.
base_mod_name = module_assigns[base_obj]
if not is_const_call(base_mod_name, base_attr):
# Calling a method on an object could modify the object and is thus
# like a def of that object. We call is_const_call to see if this module/attribute
# combination is known to not modify the module state. If we don't know that
# the combination is safe then we have to assume there could be a modification to
# the module and thus add the module variable as defined more than once.
add_to_def_once_sets(base_obj, def_once, def_more)
else:
# Assume the worst and say that base_obj could be modified by the call.
add_to_def_once_sets(base_obj, def_once, def_more)
if isinstance(rhs, ir.Expr) and rhs.op == 'call':
# If a mutable object is passed to a function, then it may be changed and
# therefore can't be hoisted.
# For each argument to the function...
for argvar in rhs.args:
# Get the argument's type.
if isinstance(argvar, ir.Var):
argvar = argvar.name
avtype = typemap[argvar]
# If that type doesn't have a mutable attribute or it does and it's set to
# not mutable then this usage is safe for hoisting.
if getattr(avtype, 'mutable', False):
# Here we have a mutable variable passed to a function so add this variable
# to the def lists.
add_to_def_once_sets(argvar, def_once, def_more)
def compute_def_once_internal(loop_body, def_once, def_more, getattr_taken, typemap, module_assigns):
'''Compute the set of variables defined exactly once in the given set of blocks
and use the given sets for storing which variables are defined once, more than
once and which have had a getattr call on them.
'''
# For each block...
for label, block in loop_body.items():
# Scan this block and effect changes to def_once, def_more, and getattr_taken
# based on the instructions in that block.
compute_def_once_block(block, def_once, def_more, getattr_taken, typemap, module_assigns)
# Have to recursively process parfors manually here.
for inst in block.body:
if isinstance(inst, parfor.Parfor):
# Recursively compute for the parfor's init block.
compute_def_once_block(inst.init_block, def_once, def_more, getattr_taken, typemap, module_assigns)
# Recursively compute for the parfor's loop body.
compute_def_once_internal(inst.loop_body, def_once, def_more, getattr_taken, typemap, module_assigns)
def compute_def_once(loop_body, typemap):
'''Compute the set of variables defined exactly once in the given set of blocks.
'''
def_once = set() # set to hold variables defined exactly once
def_more = set() # set to hold variables defined more than once
getattr_taken = {}
module_assigns = {}
compute_def_once_internal(loop_body, def_once, def_more, getattr_taken, typemap, module_assigns)
return def_once, def_more
def find_vars(var, varset):
assert isinstance(var, ir.Var)
varset.add(var.name)
return var
def _hoist_internal(inst, dep_on_param, call_table, hoisted, not_hoisted,
typemap, stored_arrays):
if inst.target.name in stored_arrays:
not_hoisted.append((inst, "stored array"))
if config.DEBUG_ARRAY_OPT >= 1:
print("Instruction", inst, " could not be hoisted because the created array is stored.")
return False
uses = set()
visit_vars_inner(inst.value, find_vars, uses)
diff = uses.difference(dep_on_param)
if config.DEBUG_ARRAY_OPT >= 1:
print("_hoist_internal:", inst, "uses:", uses, "diff:", diff)
if len(diff) == 0 and is_pure(inst.value, None, call_table):
if config.DEBUG_ARRAY_OPT >= 1:
print("Will hoist instruction", inst, typemap[inst.target.name])
hoisted.append(inst)
if not isinstance(typemap[inst.target.name], types.npytypes.Array):
dep_on_param += [inst.target.name]
return True
else:
if len(diff) > 0:
not_hoisted.append((inst, "dependency"))
if config.DEBUG_ARRAY_OPT >= 1:
print("Instruction", inst, " could not be hoisted because of a dependency.")
else:
not_hoisted.append((inst, "not pure"))
if config.DEBUG_ARRAY_OPT >= 1:
print("Instruction", inst, " could not be hoisted because it isn't pure.")
return False
def find_setitems_block(setitems, itemsset, block, typemap):
for inst in block.body:
if isinstance(inst, (ir.StaticSetItem, ir.SetItem)):
setitems.add(inst.target.name)
# If we store a non-mutable object into an array then that is safe to hoist.
# If the stored object is mutable and you hoist then multiple entries in the
# outer array could reference the same object and changing one index would then
# change other indices.
if getattr(typemap[inst.value.name], "mutable", False):
itemsset.add(inst.value.name)
elif isinstance(inst, parfor.Parfor):
find_setitems_block(setitems, itemsset, inst.init_block, typemap)
find_setitems_body(setitems, itemsset, inst.loop_body, typemap)
elif isinstance(inst, ir.Assign):
# If something of mutable type is given to a build_tuple or
# used in a call then consider it unanalyzable and so
# unavailable for hoisting.
rhs = inst.value
if isinstance(rhs, ir.Expr):
if rhs.op in ["build_tuple", "build_list", "build_set", "build_map"]:
for item in rhs.items:
if getattr(typemap[item.name], "mutable", False):
itemsset.add(item.name)
elif rhs.op == "call":
for item in list(rhs.args) + [x[1] for x in rhs.kws]:
if getattr(typemap[item.name], "mutable", False):
itemsset.add(item.name)
def find_setitems_body(setitems, itemsset, loop_body, typemap):
"""
Find the arrays that are written into (goes into setitems) and the
mutable objects (mostly arrays) that are written into other arrays
(goes into itemsset).
"""
for label, block in loop_body.items():
find_setitems_block(setitems, itemsset, block, typemap)
def empty_container_allocator_hoist(inst, dep_on_param, call_table, hoisted,
not_hoisted, typemap, stored_arrays):
if (isinstance(inst, ir.Assign) and
isinstance(inst.value, ir.Expr) and
inst.value.op == 'call' and
inst.value.func.name in call_table):
call_list = call_table[inst.value.func.name]
if call_list == ['empty', np]:
return _hoist_internal(inst, dep_on_param, call_table, hoisted,
not_hoisted, typemap, stored_arrays)
return False
def hoist(parfor_params, loop_body, typemap, wrapped_blocks):
dep_on_param = copy.copy(parfor_params)
hoisted = []
not_hoisted = []
# Compute the set of variable defined exactly once in the loop body.
def_once, def_more = compute_def_once(loop_body, typemap)
(call_table, reverse_call_table) = get_call_table(wrapped_blocks)
setitems = set()
itemsset = set()
find_setitems_body(setitems, itemsset, loop_body, typemap)
dep_on_param = list(set(dep_on_param).difference(setitems))
if config.DEBUG_ARRAY_OPT >= 1:
print("hoist - def_once:", def_once, "setitems:", setitems, "itemsset:", itemsset, "dep_on_param:", dep_on_param, "parfor_params:", parfor_params)
for si in setitems:
add_to_def_once_sets(si, def_once, def_more)
for label, block in loop_body.items():
new_block = []
for inst in block.body:
if empty_container_allocator_hoist(inst, dep_on_param, call_table,
hoisted, not_hoisted, typemap, itemsset):
continue
elif isinstance(inst, ir.Assign) and inst.target.name in def_once:
if _hoist_internal(inst, dep_on_param, call_table,
hoisted, not_hoisted, typemap, itemsset):
# don't add this instruction to the block since it is
# hoisted
continue
elif isinstance(inst, parfor.Parfor):
new_init_block = []
if config.DEBUG_ARRAY_OPT >= 1:
print("parfor")
inst.dump()
for ib_inst in inst.init_block.body:
if empty_container_allocator_hoist(ib_inst, dep_on_param,
call_table, hoisted, not_hoisted, typemap, itemsset):
continue
elif (isinstance(ib_inst, ir.Assign) and