-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy patharray_analysis.py
3207 lines (2939 loc) · 121 KB
/
array_analysis.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
#
# Copyright (c) 2017 Intel Corporation
# SPDX-License-Identifier: BSD-2-Clause
#
import numpy
import operator
from numba.core import types, ir, config, cgutils, errors
from numba.core.ir_utils import (
mk_unique_var,
find_topo_order,
dprint_func_ir,
get_global_func_typ,
guard,
require,
get_definition,
find_callname,
find_build_sequence,
find_const,
is_namedtuple_class,
build_definitions,
find_potential_aliases,
get_canonical_alias,
GuardException,
)
from numba.core.analysis import compute_cfg_from_blocks
from numba.core.typing import npydecl, signature
import copy
from numba.core.extending import intrinsic
import llvmlite
UNKNOWN_CLASS = -1
CONST_CLASS = 0
MAP_TYPES = [numpy.ufunc]
array_analysis_extensions = {}
# declaring call classes
array_creation = ["empty", "zeros", "ones", "full"]
random_int_args = ["rand", "randn"]
random_1arg_size = [
"ranf",
"random_sample",
"sample",
"random",
"standard_normal",
]
random_2arg_sizelast = [
"chisquare",
"weibull",
"power",
"geometric",
"exponential",
"poisson",
"rayleigh",
]
random_3arg_sizelast = [
"normal",
"uniform",
"beta",
"binomial",
"f",
"gamma",
"lognormal",
"laplace",
]
random_calls = (
random_int_args
+ random_1arg_size
+ random_2arg_sizelast
+ random_3arg_sizelast
+ ["randint", "triangular"]
)
@intrinsic
def wrap_index(typingctx, idx, size):
"""
Calculate index value "idx" relative to a size "size" value as
(idx % size), where "size" is known to be positive.
Note that we use the mod(%) operation here instead of
(idx < 0 ? idx + size : idx) because we may have situations
where idx > size due to the way indices are calculated
during slice/range analysis.
Both idx and size have to be Integer types.
size should be from the array size vars that array_analysis
adds and the bitwidth should match the platform maximum.
"""
require(isinstance(idx, types.scalars.Integer))
require(isinstance(size, types.scalars.Integer))
# We need both idx and size to be platform size so that we can compare.
unified_ty = types.intp if size.signed else types.uintp
idx_unified = types.intp if idx.signed else types.uintp
def codegen(context, builder, sig, args):
ll_idx_unified_ty = context.get_data_type(idx_unified)
ll_unified_ty = context.get_data_type(unified_ty)
if idx_unified.signed:
idx = builder.sext(args[0], ll_idx_unified_ty)
else:
idx = builder.zext(args[0], ll_idx_unified_ty)
if unified_ty.signed:
size = builder.sext(args[1], ll_unified_ty)
else:
size = builder.zext(args[1], ll_unified_ty)
neg_size = builder.neg(size)
zero = llvmlite.ir.Constant(ll_unified_ty, 0)
# If idx is unsigned then these signed comparisons will fail in those
# cases where the idx has the highest bit set, namely more than 2**63
# on 64-bit platforms.
idx_negative = builder.icmp_signed("<", idx, zero)
pos_oversize = builder.icmp_signed(">=", idx, size)
neg_oversize = builder.icmp_signed("<=", idx, neg_size)
pos_res = builder.select(pos_oversize, size, idx)
neg_res = builder.select(neg_oversize, zero, builder.add(idx, size))
mod = builder.select(idx_negative, neg_res, pos_res)
return mod
return signature(unified_ty, idx, size), codegen
def wrap_index_literal(idx, size):
if idx < 0:
if idx <= -size:
return 0
else:
return idx + size
else:
if idx >= size:
return size
else:
return idx
@intrinsic
def assert_equiv(typingctx, *val):
"""
A function that asserts the inputs are of equivalent size,
and throws runtime error when they are not. The input is
a vararg that contains an error message, followed by a set
of objects of either array, tuple or integer.
"""
if len(val) > 1:
# Make sure argument is a single tuple type. Note that this only
# happens when IR containing assert_equiv call is being compiled
# (and going through type inference) again.
val = (types.StarArgTuple(val),)
assert len(val[0]) > 1
# Arguments must be either array, tuple, or integer
assert all(
isinstance(a, (
types.ArrayCompatible,
types.BaseTuple,
types.SliceType,
types.Integer
))
for a in val[0][1:]
)
if not isinstance(val[0][0], types.StringLiteral):
raise errors.TypingError('first argument must be a StringLiteral')
def codegen(context, builder, sig, args):
assert len(args) == 1 # it is a vararg tuple
tup = cgutils.unpack_tuple(builder, args[0])
tup_type = sig.args[0]
msg = sig.args[0][0].literal_value
def unpack_shapes(a, aty):
if isinstance(aty, types.ArrayCompatible):
ary = context.make_array(aty)(context, builder, a)
return cgutils.unpack_tuple(builder, ary.shape)
elif isinstance(aty, types.BaseTuple):
return cgutils.unpack_tuple(builder, a)
else: # otherwise it is a single integer
return [a]
def pairwise(a, aty, b, bty):
ashapes = unpack_shapes(a, aty)
bshapes = unpack_shapes(b, bty)
assert len(ashapes) == len(bshapes)
for (m, n) in zip(ashapes, bshapes):
m_eq_n = builder.icmp_unsigned('==', m, n)
with builder.if_else(m_eq_n) as (then, orelse):
with then:
pass
with orelse:
context.call_conv.return_user_exc(
builder, AssertionError, (msg,)
)
for i in range(1, len(tup_type) - 1):
pairwise(tup[i], tup_type[i], tup[i + 1], tup_type[i + 1])
r = context.get_constant_generic(builder, types.NoneType, None)
return r
return signature(types.none, *val), codegen
class EquivSet(object):
"""EquivSet keeps track of equivalence relations between
a set of objects.
"""
def __init__(self, obj_to_ind=None, ind_to_obj=None, next_ind=0):
"""Create a new EquivSet object. Optional keyword arguments are for
internal use only.
"""
# obj_to_ind maps object to equivalence index (sometimes also called
# equivalence class) is a non-negative number that uniquely identifies
# a set of objects that are equivalent.
self.obj_to_ind = obj_to_ind if obj_to_ind else {}
# ind_to_obj maps equivalence index to a list of objects.
self.ind_to_obj = ind_to_obj if ind_to_obj else {}
# next index number that is incremented each time a new equivalence
# relation is created.
self.next_ind = next_ind
def empty(self):
"""Return an empty EquivSet object.
"""
return EquivSet()
def clone(self):
"""Return a new copy.
"""
return EquivSet(
obj_to_ind=copy.deepcopy(self.obj_to_ind),
ind_to_obj=copy.deepcopy(self.ind_to_obj),
next_id=self.next_ind,
)
def __repr__(self):
return "EquivSet({})".format(self.ind_to_obj)
def is_empty(self):
"""Return true if the set is empty, or false otherwise.
"""
return self.obj_to_ind == {}
def _get_ind(self, x):
"""Return the internal index (greater or equal to 0) of the given
object, or -1 if not found.
"""
return self.obj_to_ind.get(x, -1)
def _get_or_add_ind(self, x):
"""Return the internal index (greater or equal to 0) of the given
object, or create a new one if not found.
"""
if x in self.obj_to_ind:
i = self.obj_to_ind[x]
else:
i = self.next_ind
self.next_ind += 1
return i
def _insert(self, objs):
"""Base method that inserts a set of equivalent objects by modifying
self.
"""
assert len(objs) > 1
inds = tuple(self._get_or_add_ind(x) for x in objs)
ind = min(inds)
if config.DEBUG_ARRAY_OPT >= 2:
print("_insert:", objs, inds)
if not (ind in self.ind_to_obj):
self.ind_to_obj[ind] = []
for i, obj in zip(inds, objs):
if i == ind:
if not (obj in self.ind_to_obj[ind]):
self.ind_to_obj[ind].append(obj)
self.obj_to_ind[obj] = ind
else:
if i in self.ind_to_obj:
# those already existing are reassigned
for x in self.ind_to_obj[i]:
self.obj_to_ind[x] = ind
self.ind_to_obj[ind].append(x)
del self.ind_to_obj[i]
else:
# those that are new are assigned.
self.obj_to_ind[obj] = ind
self.ind_to_obj[ind].append(obj)
def is_equiv(self, *objs):
"""Try to derive if given objects are equivalent, return true
if so, or false otherwise.
"""
inds = [self._get_ind(x) for x in objs]
ind = max(inds)
if ind != -1:
return all(i == ind for i in inds)
else:
return all([x == objs[0] for x in objs])
def get_equiv_const(self, obj):
"""Check if obj is equivalent to some int constant, and return
the constant if found, or None otherwise.
"""
ind = self._get_ind(obj)
if ind >= 0:
objs = self.ind_to_obj[ind]
for x in objs:
if isinstance(x, int):
return x
return None
def get_equiv_set(self, obj):
"""Return the set of equivalent objects.
"""
ind = self._get_ind(obj)
if ind >= 0:
return set(self.ind_to_obj[ind])
return set()
def insert_equiv(self, *objs):
"""Insert a set of equivalent objects by modifying self. This
method can be overloaded to transform object type before insertion.
"""
return self._insert(objs)
def intersect(self, equiv_set):
""" Return the intersection of self and the given equiv_set,
without modifying either of them. The result will also keep
old equivalence indices unchanged.
"""
new_set = self.empty()
new_set.next_ind = self.next_ind
for objs in equiv_set.ind_to_obj.values():
inds = tuple(self._get_ind(x) for x in objs)
ind_to_obj = {}
for i, x in zip(inds, objs):
if i in ind_to_obj:
ind_to_obj[i].append(x)
elif i >= 0:
ind_to_obj[i] = [x]
for v in ind_to_obj.values():
if len(v) > 1:
new_set._insert(v)
return new_set
class ShapeEquivSet(EquivSet):
"""Just like EquivSet, except that it accepts only numba IR variables
and constants as objects, guided by their types. Arrays are considered
equivalent as long as their shapes are equivalent. Scalars are
equivalent only when they are equal in value. Tuples are equivalent
when they are of the same size, and their elements are equivalent.
"""
def __init__(
self,
typemap,
defs=None,
ind_to_var=None,
obj_to_ind=None,
ind_to_obj=None,
next_id=0,
ind_to_const=None,
):
"""Create a new ShapeEquivSet object, where typemap is a dictionary
that maps variable names to their types, and it will not be modified.
Optional keyword arguments are for internal use only.
"""
self.typemap = typemap
# defs maps variable name to an int, where
# 1 means the variable is defined only once, and numbers greater
# than 1 means defined more than once.
self.defs = defs if defs else {}
# ind_to_var maps index number to a list of variables (of ir.Var type).
# It is used to retrieve defined shape variables given an equivalence
# index.
self.ind_to_var = ind_to_var if ind_to_var else {}
# ind_to_const maps index number to a constant, if known.
self.ind_to_const = ind_to_const if ind_to_const else {}
super(ShapeEquivSet, self).__init__(obj_to_ind, ind_to_obj, next_id)
def empty(self):
"""Return an empty ShapeEquivSet.
"""
return ShapeEquivSet(self.typemap, {})
def clone(self):
"""Return a new copy.
"""
return ShapeEquivSet(
self.typemap,
defs=copy.copy(self.defs),
ind_to_var=copy.copy(self.ind_to_var),
obj_to_ind=copy.deepcopy(self.obj_to_ind),
ind_to_obj=copy.deepcopy(self.ind_to_obj),
next_id=self.next_ind,
ind_to_const=copy.deepcopy(self.ind_toconst),
)
def __repr__(self):
return "ShapeEquivSet({}, ind_to_var={}, ind_to_const={})".format(
self.ind_to_obj, self.ind_to_var, self.ind_to_const
)
def _get_names(self, obj):
"""Return a set of names for the given obj, where array and tuples
are broken down to their individual shapes or elements. This is
safe because both Numba array shapes and Python tuples are immutable.
"""
if isinstance(obj, ir.Var) or isinstance(obj, str):
name = obj if isinstance(obj, str) else obj.name
if name not in self.typemap:
return (name,)
typ = self.typemap[name]
if isinstance(typ, (types.BaseTuple, types.ArrayCompatible)):
ndim = (typ.ndim
if isinstance(typ, types.ArrayCompatible)
else len(typ))
# Treat 0d array as if it were a scalar.
if ndim == 0:
return (name,)
else:
return tuple("{}#{}".format(name, i) for i in range(ndim))
else:
return (name,)
elif isinstance(obj, ir.Const):
if isinstance(obj.value, tuple):
return obj.value
else:
return (obj.value,)
elif isinstance(obj, tuple):
def get_names(x):
names = self._get_names(x)
if len(names) != 0:
return names[0]
return names
return tuple(get_names(x) for x in obj)
elif isinstance(obj, int):
return (obj,)
if config.DEBUG_ARRAY_OPT >= 1:
print(
f"Ignoring untracked object type {type(obj)} in ShapeEquivSet")
return ()
def is_equiv(self, *objs):
"""Overload EquivSet.is_equiv to handle Numba IR variables and
constants.
"""
assert len(objs) > 1
obj_names = [self._get_names(x) for x in objs]
obj_names = [x for x in obj_names if x != ()] # rule out 0d shape
if len(obj_names) <= 1:
return False
ndims = [len(names) for names in obj_names]
ndim = ndims[0]
if not all(ndim == x for x in ndims):
if config.DEBUG_ARRAY_OPT >= 1:
print("is_equiv: Dimension mismatch for {}".format(objs))
return False
for i in range(ndim):
names = [obj_name[i] for obj_name in obj_names]
if not super(ShapeEquivSet, self).is_equiv(*names):
return False
return True
def get_equiv_const(self, obj):
"""If the given object is equivalent to a constant scalar,
return the scalar value, or None otherwise.
"""
names = self._get_names(obj)
if len(names) != 1:
return None
return super(ShapeEquivSet, self).get_equiv_const(names[0])
def get_equiv_var(self, obj):
"""If the given object is equivalent to some defined variable,
return the variable, or None otherwise.
"""
names = self._get_names(obj)
if len(names) != 1:
return None
ind = self._get_ind(names[0])
vs = self.ind_to_var.get(ind, [])
return vs[0] if vs != [] else None
def get_equiv_set(self, obj):
"""Return the set of equivalent objects.
"""
names = self._get_names(obj)
if len(names) != 1:
return None
return super(ShapeEquivSet, self).get_equiv_set(names[0])
def _insert(self, objs):
"""Overload EquivSet._insert to manage ind_to_var dictionary.
"""
inds = []
for obj in objs:
if obj in self.obj_to_ind:
inds.append(self.obj_to_ind[obj])
varlist = []
constval = None
names = set()
for i in sorted(inds):
if i in self.ind_to_var:
for x in self.ind_to_var[i]:
if not (x.name in names):
varlist.append(x)
names.add(x.name)
if i in self.ind_to_const:
assert constval is None
constval = self.ind_to_const[i]
super(ShapeEquivSet, self)._insert(objs)
new_ind = self.obj_to_ind[objs[0]]
for i in set(inds):
if i in self.ind_to_var:
del self.ind_to_var[i]
self.ind_to_var[new_ind] = varlist
if constval is not None:
self.ind_to_const[new_ind] = constval
def insert_equiv(self, *objs):
"""Overload EquivSet.insert_equiv to handle Numba IR variables and
constants. Input objs are either variable or constant, and at least
one of them must be variable.
"""
assert len(objs) > 1
obj_names = [self._get_names(x) for x in objs]
obj_names = [x for x in obj_names if x != ()] # rule out 0d shape
if len(obj_names) <= 1:
return
names = sum([list(x) for x in obj_names], [])
ndims = [len(x) for x in obj_names]
ndim = ndims[0]
assert all(
ndim == x for x in ndims
), "Dimension mismatch for {}".format(objs)
varlist = []
constlist = []
for obj in objs:
if not isinstance(obj, tuple):
obj = (obj,)
for var in obj:
if isinstance(var, ir.Var) and not (var.name in varlist):
# favor those already defined, move to front of varlist
if var.name in self.defs:
varlist.insert(0, var)
else:
varlist.append(var)
if isinstance(var, ir.Const) and not (var.value in constlist):
constlist.append(var.value)
# try to populate ind_to_var if variables are present
for obj in varlist:
name = obj.name
if name in names and not (name in self.obj_to_ind):
self.ind_to_obj[self.next_ind] = [name]
self.obj_to_ind[name] = self.next_ind
self.ind_to_var[self.next_ind] = [obj]
self.next_ind += 1
# create equivalence classes for previously unseen constants
for const in constlist:
if const in names and not (const in self.obj_to_ind):
self.ind_to_obj[self.next_ind] = [const]
self.obj_to_ind[const] = self.next_ind
self.ind_to_const[self.next_ind] = const
self.next_ind += 1
some_change = False
for i in range(ndim):
names = [obj_name[i] for obj_name in obj_names]
ie_res = super(ShapeEquivSet, self).insert_equiv(*names)
some_change = some_change or ie_res
return some_change
def has_shape(self, name):
"""Return true if the shape of the given variable is available.
"""
return self.get_shape(name) is not None
def get_shape(self, name):
"""Return a tuple of variables that corresponds to the shape
of the given array, or None if not found.
"""
return guard(self._get_shape, name)
def _get_shape(self, name):
"""Return a tuple of variables that corresponds to the shape
of the given array, or raise GuardException if not found.
"""
inds = self.get_shape_classes(name)
require(inds != ())
shape = []
for i in inds:
require(i in self.ind_to_var)
vs = self.ind_to_var[i]
if vs != []:
shape.append(vs[0])
else:
require(i in self.ind_to_const)
vs = self.ind_to_const[i]
shape.append(vs)
return tuple(shape)
def get_shape_classes(self, name):
"""Instead of the shape tuple, return tuple of int, where
each int is the corresponding class index of the size object.
Unknown shapes are given class index -1. Return empty tuple
if the input name is a scalar variable.
"""
if isinstance(name, ir.Var):
name = name.name
typ = self.typemap[name] if name in self.typemap else None
if not (
isinstance(typ, (
types.BaseTuple, types.SliceType, types.ArrayCompatible
))
):
return []
# Treat 0d arrays like scalars.
if isinstance(typ, types.ArrayCompatible) and typ.ndim == 0:
return []
names = self._get_names(name)
inds = tuple(self._get_ind(name) for name in names)
return inds
def intersect(self, equiv_set):
"""Overload the intersect method to handle ind_to_var.
"""
newset = super(ShapeEquivSet, self).intersect(equiv_set)
ind_to_var = {}
for i, objs in newset.ind_to_obj.items():
assert len(objs) > 0
obj = objs[0]
assert obj in self.obj_to_ind
assert obj in equiv_set.obj_to_ind
j = self.obj_to_ind[obj]
k = equiv_set.obj_to_ind[obj]
assert j in self.ind_to_var
assert k in equiv_set.ind_to_var
varlist = []
names = [x.name for x in equiv_set.ind_to_var[k]]
for x in self.ind_to_var[j]:
if x.name in names:
varlist.append(x)
ind_to_var[i] = varlist
newset.ind_to_var = ind_to_var
return newset
def define(self, name, redefined):
"""Increment the internal count of how many times a variable is being
defined. Most variables in Numba IR are SSA, i.e., defined only once,
but not all of them. When a variable is being re-defined, it must
be removed from the equivalence relation and added to the redefined
set but only if that redefinition is not known to have the same
equivalence classes. Those variables redefined are removed from all
the blocks' equivalence sets later.
Arrays passed to define() use their whole name but these do not
appear in the equivalence sets since they are stored there per
dimension. Calling _get_names() here converts array names to
dimensional names.
This function would previously invalidate if there were any multiple
definitions of a variable. However, we realized that this behavior
is overly restrictive. You need only invalidate on multiple
definitions if they are not known to be equivalent. So, the
equivalence insertion functions now return True if some change was
made (meaning the definition was not equivalent) and False
otherwise. If no change was made, then define() need not be
called. For no change to have been made, the variable must
already be present. If the new definition of the var has the
case where lhs and rhs are in the same equivalence class then
again, no change will be made and define() need not be called
or the variable invalidated.
"""
if isinstance(name, ir.Var):
name = name.name
if name in self.defs:
self.defs[name] += 1
name_res = list(self._get_names(name))
for one_name in name_res:
# NOTE: variable being redefined, must invalidate previous
# equivalences. Believe it is a rare case, and only happens to
# scalar accumuators.
if one_name in self.obj_to_ind:
redefined.add(
one_name
) # remove this var from all equiv sets
i = self.obj_to_ind[one_name]
del self.obj_to_ind[one_name]
self.ind_to_obj[i].remove(one_name)
if self.ind_to_obj[i] == []:
del self.ind_to_obj[i]
assert i in self.ind_to_var
names = [x.name for x in self.ind_to_var[i]]
if name in names:
j = names.index(name)
del self.ind_to_var[i][j]
if self.ind_to_var[i] == []:
del self.ind_to_var[i]
# no more size variables, remove equivalence too
if i in self.ind_to_obj:
for obj in self.ind_to_obj[i]:
del self.obj_to_ind[obj]
del self.ind_to_obj[i]
else:
self.defs[name] = 1
def union_defs(self, defs, redefined):
"""Union with the given defs dictionary. This is meant to handle
branch join-point, where a variable may have been defined in more
than one branches.
"""
for k, v in defs.items():
if v > 0:
self.define(k, redefined)
class SymbolicEquivSet(ShapeEquivSet):
"""Just like ShapeEquivSet, except that it also reasons about variable
equivalence symbolically by using their arithmetic definitions.
The goal is to automatically derive the equivalence of array ranges
(slicing). For instance, a[1:m] and a[0:m-1] shall be considered
size-equivalence.
"""
def __init__(
self,
typemap,
def_by=None,
ref_by=None,
ext_shapes=None,
defs=None,
ind_to_var=None,
obj_to_ind=None,
ind_to_obj=None,
next_id=0,
):
"""Create a new SymbolicEquivSet object, where typemap is a dictionary
that maps variable names to their types, and it will not be modified.
Optional keyword arguments are for internal use only.
"""
# A "defined-by" table that maps A to a tuple of (B, i), which
# means A is defined as: A = B + i, where A,B are variable names,
# and i is an integer constants.
self.def_by = def_by if def_by else {}
# A "referred-by" table that maps A to a list of [(B, i), (C, j) ...],
# which implies a sequence of definitions: B = A - i, C = A - j, and
# so on, where A,B,C,... are variable names, and i,j,... are
# integer constants.
self.ref_by = ref_by if ref_by else {}
# A extended shape table that can map an arbitrary object to a shape,
# currently used to remember shapes for SetItem IR node, and wrapped
# indices for Slice objects.
self.ext_shapes = ext_shapes if ext_shapes else {}
# rel_map keeps a map of relative sizes that we have seen so
# that if we compute the same relative sizes different times
# in different ways we can associate those two instances
# of the same relative size to the same equivalence class.
self.rel_map = {}
# wrap_index() computes the effectual index given a slice and a
# dimension's size. We need to be able to know that two wrap_index
# calls are equivalent. They are known to be equivalent if the slice
# and dimension sizes of the two wrap_index calls are equivalent.
# wrap_map maps from a tuple of equivalence class ids for a slice and
# a dimension size to some new equivalence class id for the output size.
self.wrap_map = {}
super(SymbolicEquivSet, self).__init__(
typemap, defs, ind_to_var, obj_to_ind, ind_to_obj, next_id
)
def empty(self):
"""Return an empty SymbolicEquivSet.
"""
return SymbolicEquivSet(self.typemap)
def __repr__(self):
return (
"SymbolicEquivSet({}, ind_to_var={}, def_by={}, "
"ref_by={}, ext_shapes={})".format(
self.ind_to_obj,
self.ind_to_var,
self.def_by,
self.ref_by,
self.ext_shapes,
)
)
def clone(self):
"""Return a new copy.
"""
return SymbolicEquivSet(
self.typemap,
def_by=copy.copy(self.def_by),
ref_by=copy.copy(self.ref_by),
ext_shapes=copy.copy(self.ext_shapes),
defs=copy.copy(self.defs),
ind_to_var=copy.copy(self.ind_to_var),
obj_to_ind=copy.deepcopy(self.obj_to_ind),
ind_to_obj=copy.deepcopy(self.ind_to_obj),
next_id=self.next_ind,
)
def get_rel(self, name):
"""Retrieve a definition pair for the given variable,
or return None if it is not available.
"""
return guard(self._get_or_set_rel, name)
def _get_or_set_rel(self, name, func_ir=None):
"""Retrieve a definition pair for the given variable,
and if it is not already available, try to look it up
in the given func_ir, and remember it for future use.
"""
if isinstance(name, ir.Var):
name = name.name
require(self.defs.get(name, 0) == 1)
if name in self.def_by:
return self.def_by[name]
else:
require(func_ir is not None)
def plus(x, y):
x_is_const = isinstance(x, int)
y_is_const = isinstance(y, int)
if x_is_const:
if y_is_const:
return x + y
else:
(var, offset) = y
return (var, x + offset)
else:
(var, offset) = x
if y_is_const:
return (var, y + offset)
else:
return None
def minus(x, y):
if isinstance(y, int):
return plus(x, -y)
elif (
isinstance(x, tuple)
and isinstance(y, tuple)
and x[0] == y[0]
):
return minus(x[1], y[1])
else:
return None
expr = get_definition(func_ir, name)
value = (name, 0) # default to its own name
if isinstance(expr, ir.Expr):
if expr.op == "call":
fname, mod_name = find_callname(
func_ir, expr, typemap=self.typemap
)
if (
fname == "wrap_index"
and mod_name == "numba.parfors.array_analysis"
):
index = tuple(
self.obj_to_ind.get(x.name, -1) for x in expr.args
)
# If wrap_index for a slice works on a variable
# that is not analyzable (e.g., multiple definitions)
# then we have to return None here since we can't know
# how that size will compare to others if we can't
# analyze some part of the slice.
if -1 in index:
return None
names = self.ext_shapes.get(index, [])
names.append(name)
if len(names) > 0:
self._insert(names)
self.ext_shapes[index] = names
elif expr.op == "binop":
lhs = self._get_or_set_rel(expr.lhs, func_ir)
rhs = self._get_or_set_rel(expr.rhs, func_ir)
# If either the lhs or rhs is not analyzable
# then don't try to record information this var.
if lhs is None or rhs is None:
return None
elif expr.fn == operator.add:
value = plus(lhs, rhs)
elif expr.fn == operator.sub:
value = minus(lhs, rhs)
elif isinstance(expr, ir.Const) and isinstance(expr.value, int):
value = expr.value
require(value is not None)
# update def_by table
self.def_by[name] = value
if isinstance(value, int) or (
isinstance(value, tuple)
and (value[0] != name or value[1] != 0)
):
# update ref_by table too
if isinstance(value, tuple):
(var, offset) = value
if not (var in self.ref_by):
self.ref_by[var] = []
self.ref_by[var].append((name, -offset))
# insert new equivalence if found
ind = self._get_ind(var)
if ind >= 0:
objs = self.ind_to_obj[ind]
names = []
for obj in objs:
if obj in self.ref_by:
names += [
x
for (x, i) in self.ref_by[obj]
if i == -offset
]
if len(names) > 1:
super(SymbolicEquivSet, self)._insert(names)
return value
def define(self, var, redefined, func_ir=None, typ=None):
"""Besides incrementing the definition count of the given variable
name, it will also retrieve and simplify its definition from func_ir,
and remember the result for later equivalence comparison. Supported
operations are:
1. arithmetic plus and minus with constants
2. wrap_index (relative to some given size)
"""
if isinstance(var, ir.Var):
name = var.name
else:
name = var
super(SymbolicEquivSet, self).define(name, redefined)
if (
func_ir
and self.defs.get(name, 0) == 1
and isinstance(typ, types.Number)
):
value = guard(self._get_or_set_rel, name, func_ir)
# turn constant definition into equivalence
if isinstance(value, int):
self._insert([name, value])
if isinstance(var, ir.Var):
ind = self._get_or_add_ind(name)
if not (ind in self.ind_to_obj):
self.ind_to_obj[ind] = [name]
self.obj_to_ind[name] = ind
if ind in self.ind_to_var:
self.ind_to_var[ind].append(var)
else:
self.ind_to_var[ind] = [var]
return True
def _insert(self, objs):
"""Overload _insert method to handle ind changes between relative
objects. Returns True if some change is made, false otherwise.
"""
indset = set()
uniqs = set()
for obj in objs:
ind = self._get_ind(obj)
if ind == -1:
uniqs.add(obj)
elif not (ind in indset):
uniqs.add(obj)
indset.add(ind)
if len(uniqs) <= 1:
return False
uniqs = list(uniqs)
super(SymbolicEquivSet, self)._insert(uniqs)
objs = self.ind_to_obj[self._get_ind(uniqs[0])]
# New equivalence guided by def_by and ref_by
offset_dict = {}
def get_or_set(d, k):
if k in d:
v = d[k]
else: