Repository navigation
Expand file tree
/
Copy pathuntyped_passes.py
More file actions
1722 lines (1469 loc) · 69 KB
/
Copy pathuntyped_passes.py
File metadata and controls
1722 lines (1469 loc) · 69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from collections import defaultdict, namedtuple
from contextlib import contextmanager
from copy import deepcopy, copy
import warnings
from numba.core.compiler_machinery import (FunctionPass, AnalysisPass,
SSACompliantMixin, register_pass)
from numba.core import (errors, types, ir, bytecode, postproc, rewrites, config,
transforms)
from numba.misc.special import literal_unroll
from numba.core.analysis import (dead_branch_prune, rewrite_semantic_constants,
find_literally_calls, compute_cfg_from_blocks,
compute_use_defs)
from numba.core.ir_utils import (guard, resolve_func_from_module, simplify_CFG,
GuardException, convert_code_obj_to_function,
mk_unique_var, build_definitions,
replace_var_names, get_name_var_table,
compile_to_numba_ir, get_definition,
find_max_label, rename_labels,
transfer_scope, fixup_var_define_in_scope,
)
from numba.core.ssa import reconstruct_ssa
from numba.core import interpreter
@contextmanager
def fallback_context(state, msg):
"""
Wraps code that would signal a fallback to object mode
"""
try:
yield
except Exception as e:
if not state.status.can_fallback:
raise
else:
# Clear all references attached to the traceback
e = e.with_traceback(None)
# this emits a warning containing the error message body in the
# case of fallback from npm to objmode
loop_lift = '' if state.flags.enable_looplift else 'OUT'
msg_rewrite = ("\nCompilation is falling back to object mode "
"WITH%s looplifting enabled because %s"
% (loop_lift, msg))
warnings.warn_explicit('%s due to: %s' % (msg_rewrite, e),
errors.NumbaWarning,
state.func_id.filename,
state.func_id.firstlineno)
raise
@register_pass(mutates_CFG=True, analysis_only=False)
class ExtractByteCode(FunctionPass):
_name = "extract_bytecode"
def __init__(self):
FunctionPass.__init__(self)
def run_pass(self, state):
"""
Extract bytecode from function
"""
func_id = state['func_id']
bc = bytecode.ByteCode(func_id)
if config.DUMP_BYTECODE:
print(bc.dump())
state['bc'] = bc
return True
@register_pass(mutates_CFG=True, analysis_only=False)
class TranslateByteCode(FunctionPass):
_name = "translate_bytecode"
def __init__(self):
FunctionPass.__init__(self)
def run_pass(self, state):
"""
Analyze bytecode and translating to Numba IR
"""
func_id = state['func_id']
bc = state['bc']
interp = interpreter.Interpreter(func_id)
func_ir = interp.interpret(bc)
state["func_ir"] = func_ir
return True
@register_pass(mutates_CFG=True, analysis_only=False)
class FixupArgs(FunctionPass):
_name = "fixup_args"
def __init__(self):
FunctionPass.__init__(self)
def run_pass(self, state):
state['nargs'] = state['func_ir'].arg_count
if not state['args'] and state['flags'].force_pyobject:
# Allow an empty argument types specification when object mode
# is explicitly requested.
state['args'] = (types.pyobject,) * state['nargs']
elif len(state['args']) != state['nargs']:
raise TypeError("Signature mismatch: %d argument types given, "
"but function takes %d arguments"
% (len(state['args']), state['nargs']))
return True
@register_pass(mutates_CFG=True, analysis_only=False)
class IRProcessing(FunctionPass):
_name = "ir_processing"
def __init__(self):
FunctionPass.__init__(self)
def run_pass(self, state):
func_ir = state['func_ir']
post_proc = postproc.PostProcessor(func_ir)
post_proc.run()
if config.DEBUG or config.DUMP_IR:
name = func_ir.func_id.func_qualname
print(("IR DUMP: %s" % name).center(80, "-"))
func_ir.dump()
if func_ir.is_generator:
print(("GENERATOR INFO: %s" % name).center(80, "-"))
func_ir.dump_generator_info()
return True
@register_pass(mutates_CFG=True, analysis_only=False)
class RewriteSemanticConstants(FunctionPass):
_name = "rewrite_semantic_constants"
def __init__(self):
FunctionPass.__init__(self)
def run_pass(self, state):
"""
This prunes dead branches, a dead branch is one which is derivable as
not taken at compile time purely based on const/literal evaluation.
"""
assert state.func_ir
msg = ('Internal error in pre-inference dead branch pruning '
'pass encountered during compilation of '
'function "%s"' % (state.func_id.func_name,))
with fallback_context(state, msg):
rewrite_semantic_constants(state.func_ir, state.args)
return True
@register_pass(mutates_CFG=True, analysis_only=False)
class DeadBranchPrune(SSACompliantMixin, FunctionPass):
_name = "dead_branch_prune"
def __init__(self):
FunctionPass.__init__(self)
def run_pass(self, state):
"""
This prunes dead branches, a dead branch is one which is derivable as
not taken at compile time purely based on const/literal evaluation.
"""
# purely for demonstration purposes, obtain the analysis from a pass
# declare as a required dependent
semantic_const_analysis = self.get_analysis(type(self)) # noqa
assert state.func_ir
msg = ('Internal error in pre-inference dead branch pruning '
'pass encountered during compilation of '
'function "%s"' % (state.func_id.func_name,))
with fallback_context(state, msg):
dead_branch_prune(state.func_ir, state.args)
return True
def get_analysis_usage(self, AU):
AU.add_required(RewriteSemanticConstants)
@register_pass(mutates_CFG=True, analysis_only=False)
class InlineClosureLikes(FunctionPass):
_name = "inline_closure_likes"
def __init__(self):
FunctionPass.__init__(self)
def run_pass(self, state):
# Ensure we have an IR and type information.
assert state.func_ir
# if the return type is a pyobject, there's no type info available and
# no ability to resolve certain typed function calls in the array
# inlining code, use this variable to indicate
typed_pass = not isinstance(state.return_type, types.misc.PyObject)
from numba.core.inline_closurecall import InlineClosureCallPass
inline_pass = InlineClosureCallPass(
state.func_ir,
state.flags.auto_parallel,
state.parfor_diagnostics.replaced_fns,
typed_pass)
inline_pass.run()
# Remove all Dels, and re-run postproc
post_proc = postproc.PostProcessor(state.func_ir)
post_proc.run()
fixup_var_define_in_scope(state.func_ir.blocks)
return True
@register_pass(mutates_CFG=True, analysis_only=False)
class GenericRewrites(FunctionPass):
_name = "generic_rewrites"
def __init__(self):
FunctionPass.__init__(self)
def run_pass(self, state):
"""
Perform any intermediate representation rewrites before type
inference.
"""
assert state.func_ir
msg = ('Internal error in pre-inference rewriting '
'pass encountered during compilation of '
'function "%s"' % (state.func_id.func_name,))
with fallback_context(state, msg):
rewrites.rewrite_registry.apply('before-inference', state)
return True
@register_pass(mutates_CFG=True, analysis_only=False)
class WithLifting(FunctionPass):
_name = "with_lifting"
def __init__(self):
FunctionPass.__init__(self)
def run_pass(self, state):
"""
Extract with-contexts
"""
main, withs = transforms.with_lifting(
func_ir=state.func_ir,
typingctx=state.typingctx,
targetctx=state.targetctx,
flags=state.flags,
locals=state.locals,
)
if withs:
from numba.core.compiler import compile_ir, _EarlyPipelineCompletion
cres = compile_ir(state.typingctx, state.targetctx, main,
state.args, state.return_type,
state.flags, state.locals,
lifted=tuple(withs), lifted_from=None,
pipeline_class=type(state.pipeline))
raise _EarlyPipelineCompletion(cres)
return True
@register_pass(mutates_CFG=True, analysis_only=False)
class InlineInlinables(FunctionPass):
"""
This pass will inline a function wrapped by the numba.jit decorator directly
into the site of its call depending on the value set in the 'inline' kwarg
to the decorator.
This is an untyped pass. CFG simplification is performed at the end of the
pass but no block level clean up is performed on the mutated IR (typing
information is not available to do so).
"""
_name = "inline_inlinables"
_DEBUG = False
def __init__(self):
FunctionPass.__init__(self)
def run_pass(self, state):
"""Run inlining of inlinables
"""
if self._DEBUG:
print('before inline'.center(80, '-'))
print(state.func_ir.dump())
print(''.center(80, '-'))
from numba.core.inline_closurecall import (InlineWorker,
callee_ir_validator)
inline_worker = InlineWorker(state.typingctx,
state.targetctx,
state.locals,
state.pipeline,
state.flags,
validator=callee_ir_validator)
modified = False
# use a work list, look for call sites via `ir.Expr.op == call` and
# then pass these to `self._do_work` to make decisions about inlining.
work_list = list(state.func_ir.blocks.items())
while work_list:
label, block = work_list.pop()
for i, instr in enumerate(block.body):
if isinstance(instr, ir.Assign):
expr = instr.value
if isinstance(expr, ir.Expr) and expr.op == 'call':
if guard(self._do_work, state, work_list, block, i,
expr, inline_worker):
modified = True
break # because block structure changed
if modified:
# clean up unconditional branches that appear due to inlined
# functions introducing blocks
cfg = compute_cfg_from_blocks(state.func_ir.blocks)
for dead in cfg.dead_nodes():
del state.func_ir.blocks[dead]
post_proc = postproc.PostProcessor(state.func_ir)
post_proc.run()
state.func_ir.blocks = simplify_CFG(state.func_ir.blocks)
if self._DEBUG:
print('after inline'.center(80, '-'))
print(state.func_ir.dump())
print(''.center(80, '-'))
return True
def _do_work(self, state, work_list, block, i, expr, inline_worker):
from numba.core.compiler import run_frontend
from numba.core.cpu import InlineOptions
# try and get a definition for the call, this isn't always possible as
# it might be a eval(str)/part generated awaiting update etc. (parfors)
to_inline = None
try:
to_inline = state.func_ir.get_definition(expr.func)
except Exception:
if self._DEBUG:
print("Cannot find definition for %s" % expr.func)
return False
# do not handle closure inlining here, another pass deals with that.
if getattr(to_inline, 'op', False) == 'make_function':
return False
# see if the definition is a "getattr", in which case walk the IR to
# try and find the python function via the module from which it's
# imported, this should all be encoded in the IR.
if getattr(to_inline, 'op', False) == 'getattr':
val = resolve_func_from_module(state.func_ir, to_inline)
else:
# This is likely a freevar or global
#
# NOTE: getattr 'value' on a call may fail if it's an ir.Expr as
# getattr is overloaded to look in _kws.
try:
val = getattr(to_inline, 'value', False)
except Exception:
raise GuardException
# if something was found...
if val:
# check it's dispatcher-like, the targetoptions attr holds the
# kwargs supplied in the jit decorator and is where 'inline' will
# be if it is present.
topt = getattr(val, 'targetoptions', False)
if topt:
inline_type = topt.get('inline', None)
# has 'inline' been specified?
if inline_type is not None:
inline_opt = InlineOptions(inline_type)
# Could this be inlinable?
if not inline_opt.is_never_inline:
# yes, it could be inlinable
do_inline = True
pyfunc = val.py_func
# Has it got an associated cost model?
if inline_opt.has_cost_model:
# yes, it has a cost model, use it to determine
# whether to do the inline
py_func_ir = run_frontend(pyfunc)
do_inline = inline_type(expr, state.func_ir,
py_func_ir)
# if do_inline is True then inline!
if do_inline:
_, _, _, new_blocks = \
inline_worker.inline_function(state.func_ir,
block, i, pyfunc,)
if work_list is not None:
for blk in new_blocks:
work_list.append(blk)
return True
return False
@register_pass(mutates_CFG=False, analysis_only=False)
class PreserveIR(AnalysisPass):
"""
Preserves the IR in the metadata
"""
_name = "preserve_ir"
def __init__(self):
AnalysisPass.__init__(self)
def run_pass(self, state):
state.metadata['preserved_ir'] = state.func_ir.copy()
return False
@register_pass(mutates_CFG=False, analysis_only=True)
class FindLiterallyCalls(FunctionPass):
"""Find calls to `numba.literally()` and signal if its requirement is not
satisfied.
"""
_name = "find_literally"
def __init__(self):
FunctionPass.__init__(self)
def run_pass(self, state):
find_literally_calls(state.func_ir, state.args)
return False
@register_pass(mutates_CFG=True, analysis_only=False)
class CanonicalizeLoopExit(FunctionPass):
"""A pass to canonicalize loop exit by splitting it from function exit.
"""
_name = "canonicalize_loop_exit"
def __init__(self):
FunctionPass.__init__(self)
def run_pass(self, state):
fir = state.func_ir
cfg = compute_cfg_from_blocks(fir.blocks)
status = False
for loop in cfg.loops().values():
for exit_label in loop.exits:
if exit_label in cfg.exit_points():
self._split_exit_block(fir, cfg, exit_label)
status = True
fir._reset_analysis_variables()
vlt = postproc.VariableLifetime(fir.blocks)
fir.variable_lifetime = vlt
return status
def _split_exit_block(self, fir, cfg, exit_label):
curblock = fir.blocks[exit_label]
newlabel = exit_label + 1
newlabel = find_max_label(fir.blocks) + 1
fir.blocks[newlabel] = curblock
newblock = ir.Block(scope=curblock.scope, loc=curblock.loc)
newblock.append(ir.Jump(newlabel, loc=curblock.loc))
fir.blocks[exit_label] = newblock
# Rename all labels
fir.blocks = rename_labels(fir.blocks)
@register_pass(mutates_CFG=True, analysis_only=False)
class CanonicalizeLoopEntry(FunctionPass):
"""A pass to canonicalize loop header by splitting it from function entry.
This is needed for loop-lifting; esp in py3.8
"""
_name = "canonicalize_loop_entry"
def __init__(self):
FunctionPass.__init__(self)
def run_pass(self, state):
fir = state.func_ir
cfg = compute_cfg_from_blocks(fir.blocks)
status = False
for loop in cfg.loops().values():
if len(loop.entries) == 1:
[entry_label] = loop.entries
if entry_label == cfg.entry_point():
self._split_entry_block(fir, cfg, loop, entry_label)
status = True
fir._reset_analysis_variables()
vlt = postproc.VariableLifetime(fir.blocks)
fir.variable_lifetime = vlt
return status
def _split_entry_block(self, fir, cfg, loop, entry_label):
# Find iterator inputs into the for-loop header
header_block = fir.blocks[loop.header]
deps = set()
for expr in header_block.find_exprs(op="iternext"):
deps.add(expr.value)
# Find the getiter for each iterator
entry_block = fir.blocks[entry_label]
# Find the start of loop entry statement that needs to be included.
startpt = None
list_of_insts = list(entry_block.find_insts(ir.Assign))
for assign in reversed(list_of_insts):
if assign.target in deps:
rhs = assign.value
if isinstance(rhs, ir.Var):
if rhs.is_temp:
deps.add(rhs)
elif isinstance(rhs, ir.Expr):
expr = rhs
if expr.op == 'getiter':
startpt = assign
if expr.value.is_temp:
deps.add(expr.value)
elif expr.op == 'call':
defn = guard(get_definition, fir, expr.func)
if isinstance(defn, ir.Global):
if expr.func.is_temp:
deps.add(expr.func)
elif isinstance(rhs, ir.Global) and rhs.value is range:
startpt = assign
if startpt is None:
return
splitpt = entry_block.body.index(startpt)
new_block = entry_block.copy()
new_block.body = new_block.body[splitpt:]
new_block.loc = new_block.body[0].loc
new_label = find_max_label(fir.blocks) + 1
entry_block.body = entry_block.body[:splitpt]
entry_block.append(ir.Jump(new_label, loc=new_block.loc))
fir.blocks[new_label] = new_block
# Rename all labels
fir.blocks = rename_labels(fir.blocks)
@register_pass(mutates_CFG=False, analysis_only=True)
class PrintIRCFG(FunctionPass):
_name = "print_ir_cfg"
def __init__(self):
FunctionPass.__init__(self)
self._ver = 0
def run_pass(self, state):
fir = state.func_ir
self._ver += 1
fir.render_dot(filename_prefix='v{}'.format(self._ver)).render()
return False
@register_pass(mutates_CFG=True, analysis_only=False)
class MakeFunctionToJitFunction(FunctionPass):
"""
This swaps an ir.Expr.op == "make_function" i.e. a closure, for a compiled
function containing the closure body and puts it in ir.Global. It's a 1:1
statement value swap. `make_function` is already untyped
"""
_name = "make_function_op_code_to_jit_function"
def __init__(self):
FunctionPass.__init__(self)
def run_pass(self, state):
from numba import njit
func_ir = state.func_ir
mutated = False
for idx, blk in func_ir.blocks.items():
for stmt in blk.body:
if isinstance(stmt, ir.Assign):
if isinstance(stmt.value, ir.Expr):
if stmt.value.op == "make_function":
node = stmt.value
getdef = func_ir.get_definition
kw_default = getdef(node.defaults)
ok = False
if (kw_default is None or
isinstance(kw_default, ir.Const)):
ok = True
elif isinstance(kw_default, tuple):
ok = all([isinstance(getdef(x), ir.Const)
for x in kw_default])
elif isinstance(kw_default, ir.Expr):
if kw_default.op != "build_tuple":
continue
ok = all([isinstance(getdef(x), ir.Const)
for x in kw_default.items])
if not ok:
continue
pyfunc = convert_code_obj_to_function(node, func_ir)
func = njit()(pyfunc)
new_node = ir.Global(node.code.co_name, func,
stmt.loc)
stmt.value = new_node
mutated |= True
# if a change was made the del ordering is probably wrong, patch up
if mutated:
post_proc = postproc.PostProcessor(func_ir)
post_proc.run()
return mutated
@register_pass(mutates_CFG=True, analysis_only=False)
class TransformLiteralUnrollConstListToTuple(FunctionPass):
""" This pass spots a `literal_unroll([<constant values>])` and rewrites it
as a `literal_unroll(tuple(<constant values>))`.
"""
_name = "transform_literal_unroll_const_list_to_tuple"
_accepted_types = (types.BaseTuple, types.LiteralList)
def __init__(self):
FunctionPass.__init__(self)
def run_pass(self, state):
mutated = False
func_ir = state.func_ir
for label, blk in func_ir.blocks.items():
calls = [_ for _ in blk.find_exprs('call')]
for call in calls:
glbl = guard(get_definition, func_ir, call.func)
if glbl and isinstance(glbl, (ir.Global, ir.FreeVar)):
# find a literal_unroll
if glbl.value is literal_unroll:
if len(call.args) > 1:
msg = "literal_unroll takes one argument, found %s"
raise errors.UnsupportedError(msg % len(call.args),
call.loc)
# get the arg, make sure its a build_list
unroll_var = call.args[0]
to_unroll = guard(get_definition, func_ir, unroll_var)
if (isinstance(to_unroll, ir.Expr) and
to_unroll.op == "build_list"):
# make sure they are all const items in the list
for i, item in enumerate(to_unroll.items):
val = guard(get_definition, func_ir, item)
if not val:
msg = ("multiple definitions for variable "
"%s, cannot resolve constant")
raise errors.UnsupportedError(msg % item,
to_unroll.loc)
if not isinstance(val, ir.Const):
msg = ("Found non-constant value at "
"position %s in a list argument to "
"literal_unroll" % i)
raise errors.UnsupportedError(msg,
to_unroll.loc)
# The above appears ok, now swap the build_list for
# a built tuple.
# find the assignment for the unroll target
to_unroll_lhs = guard(get_definition, func_ir,
unroll_var, lhs_only=True)
if to_unroll_lhs is None:
msg = ("multiple definitions for variable "
"%s, cannot resolve constant")
raise errors.UnsupportedError(msg % unroll_var,
to_unroll.loc)
# scan all blocks looking for the LHS
for b in func_ir.blocks.values():
asgn = b.find_variable_assignment(
to_unroll_lhs.name)
if asgn is not None:
break
else:
msg = ("Cannot find assignment for known "
"variable %s") % to_unroll_lhs.name
raise errors.CompilerError(msg, to_unroll.loc)
# Create a tuple with the list items as contents
tup = ir.Expr.build_tuple(to_unroll.items,
to_unroll.loc)
# swap the list for the tuple
asgn.value = tup
mutated = True
elif (isinstance(to_unroll, ir.Expr) and
to_unroll.op == "build_tuple"):
# this is fine, do nothing
pass
elif (isinstance(to_unroll, (ir.Global, ir.FreeVar)) and
isinstance(to_unroll.value, tuple)):
# this is fine, do nothing
pass
elif isinstance(to_unroll, ir.Arg):
# this is only fine if the arg is a tuple
ty = state.typemap[to_unroll.name]
if not isinstance(ty, self._accepted_types):
msg = ("Invalid use of literal_unroll with a "
"function argument, only tuples are "
"supported as function arguments, found "
"%s") % ty
raise errors.UnsupportedError(msg,
to_unroll.loc)
else:
extra = None
if isinstance(to_unroll, ir.Expr):
# probably a slice
if to_unroll.op == "getitem":
ty = state.typemap[to_unroll.value.name]
# check if this is a tuple slice
if not isinstance(ty, self._accepted_types):
extra = "operation %s" % to_unroll.op
loc = to_unroll.loc
elif isinstance(to_unroll, ir.Arg):
extra = "non-const argument %s" % to_unroll.name
loc = to_unroll.loc
else:
if to_unroll is None:
extra = ('multiple definitions of '
'variable "%s".' % unroll_var.name)
loc = unroll_var.loc
else:
loc = to_unroll.loc
extra = "unknown problem"
if extra:
msg = ("Invalid use of literal_unroll, "
"argument should be a tuple or a list "
"of constant values. Failure reason: "
"found %s" % extra)
raise errors.UnsupportedError(msg, loc)
return mutated
@register_pass(mutates_CFG=True, analysis_only=False)
class MixedContainerUnroller(FunctionPass):
_name = "mixed_container_unroller"
_DEBUG = False
_accepted_types = (types.BaseTuple, types.LiteralList)
def __init__(self):
FunctionPass.__init__(self)
def analyse_tuple(self, tup):
"""
Returns a map of type->list(indexes) for a typed tuple
"""
d = defaultdict(list)
for i, ty in enumerate(tup):
d[ty].append(i)
return d
def add_offset_to_labels_w_ignore(self, blocks, offset, ignore=None):
"""add an offset to all block labels and jump/branch targets
don't add an offset to anything in the ignore list
"""
if ignore is None:
ignore = set()
new_blocks = {}
for l, b in blocks.items():
# some parfor last blocks might be empty
term = None
if b.body:
term = b.body[-1]
if isinstance(term, ir.Jump):
if term.target not in ignore:
b.body[-1] = ir.Jump(term.target + offset, term.loc)
if isinstance(term, ir.Branch):
if term.truebr not in ignore:
new_true = term.truebr + offset
else:
new_true = term.truebr
if term.falsebr not in ignore:
new_false = term.falsebr + offset
else:
new_false = term.falsebr
b.body[-1] = ir.Branch(term.cond, new_true, new_false, term.loc)
new_blocks[l + offset] = b
return new_blocks
def inject_loop_body(self, switch_ir, loop_ir, caller_max_label,
dont_replace, switch_data):
"""
Injects the "loop body" held in `loop_ir` into `switch_ir` where ever
there is a statement of the form `SENTINEL.<int> = RHS`. It also:
* Finds and then deliberately does not relabel non-local jumps so as to
make the switch table suitable for injection into the IR from which
the loop body was derived.
* Looks for `typed_getitem` and wires them up to loop body version
specific variables or, if possible, directly writes in their constant
value at their use site.
Args:
- switch_ir, the switch table with SENTINELS as generated by
self.gen_switch
- loop_ir, the IR of the loop blocks (derived from the original func_ir)
- caller_max_label, the maximum label in the func_ir caller
- dont_replace, variables that should not be renamed (to handle
references to variables that are incoming at the loop head/escaping at
the loop exit.
- switch_data, the switch table data used to generated the switch_ir,
can be generated by self.analyse_tuple.
Returns:
- A type specific switch table with each case containing a versioned
loop body suitable for injection as a replacement for the loop_ir.
"""
# Switch IR came from code gen, immediately relabel to prevent
# collisions with IR derived from the user code (caller)
switch_ir.blocks = self.add_offset_to_labels_w_ignore(
switch_ir.blocks, caller_max_label + 1)
# Find the sentinels and validate the form
sentinel_exits = set()
sentinel_blocks = []
for lbl, blk in switch_ir.blocks.items():
for i, stmt in enumerate(blk.body):
if isinstance(stmt, ir.Assign):
if "SENTINEL" in stmt.target.name:
sentinel_blocks.append(lbl)
sentinel_exits.add(blk.body[-1].target)
break
assert len(sentinel_exits) == 1 # should only be 1 exit
switch_ir.blocks.pop(sentinel_exits.pop()) # kill the exit, it's dead
# find jumps that are non-local, we won't relabel these
ignore_set = set()
local_lbl = [x for x in loop_ir.blocks.keys()]
for lbl, blk in loop_ir.blocks.items():
for i, stmt in enumerate(blk.body):
if isinstance(stmt, ir.Jump):
if stmt.target not in local_lbl:
ignore_set.add(stmt.target)
if isinstance(stmt, ir.Branch):
if stmt.truebr not in local_lbl:
ignore_set.add(stmt.truebr)
if stmt.falsebr not in local_lbl:
ignore_set.add(stmt.falsebr)
# make sure the generated switch table matches the switch data
assert len(sentinel_blocks) == len(switch_data)
# replace the sentinel_blocks with the loop body
for lbl, branch_ty in zip(sentinel_blocks, switch_data.keys()):
loop_blocks = deepcopy(loop_ir.blocks)
# relabel blocks WRT switch table, each block replacement will shift
# the maximum label
max_label = max(switch_ir.blocks.keys())
loop_blocks = self.add_offset_to_labels_w_ignore(
loop_blocks, max_label + 1, ignore_set)
# start label
loop_start_lbl = min(loop_blocks.keys())
# fix the typed_getitem locations in the loop blocks
for blk in loop_blocks.values():
new_body = []
for stmt in blk.body:
if isinstance(stmt, ir.Assign):
if (isinstance(stmt.value, ir.Expr) and
stmt.value.op == "typed_getitem"):
if isinstance(branch_ty, types.Literal):
new_const_name = mk_unique_var("branch_const")
new_const_var = ir.Var(
blk.scope, new_const_name, stmt.loc)
new_const_val = ir.Const(
branch_ty.literal_value, stmt.loc)
const_assign = ir.Assign(
new_const_val, new_const_var, stmt.loc)
new_assign = ir.Assign(
new_const_var, stmt.target, stmt.loc)
new_body.append(const_assign)
new_body.append(new_assign)
dont_replace.append(new_const_name)
else:
orig = stmt.value
new_typed_getitem = ir.Expr.typed_getitem(
value=orig.value, dtype=branch_ty,
index=orig.index, loc=orig.loc)
new_assign = ir.Assign(
new_typed_getitem, stmt.target, stmt.loc)
new_body.append(new_assign)
else:
new_body.append(stmt)
else:
new_body.append(stmt)
blk.body = new_body
# rename
var_table = get_name_var_table(loop_blocks)
drop_keys = []
for k, v in var_table.items():
if v.name in dont_replace:
drop_keys.append(k)
for k in drop_keys:
var_table.pop(k)
new_var_dict = {}
for name, var in var_table.items():
new_var_dict[name] = mk_unique_var(name)
replace_var_names(loop_blocks, new_var_dict)
# clobber the sentinel body and then stuff in the rest
switch_ir.blocks[lbl] = deepcopy(loop_blocks[loop_start_lbl])
remaining_keys = [y for y in loop_blocks.keys()]
remaining_keys.remove(loop_start_lbl)
for k in remaining_keys:
switch_ir.blocks[k] = deepcopy(loop_blocks[k])
if self._DEBUG:
print("-" * 80 + "EXIT STUFFER")
switch_ir.dump()
print("-" * 80)
return switch_ir
def gen_switch(self, data, index):
"""
Generates a function with a switch table like
def foo():
if PLACEHOLDER_INDEX in (<integers>):
SENTINEL = None
elif PLACEHOLDER_INDEX in (<integers>):
SENTINEL = None
...
else:
raise RuntimeError
The data is a map of (type : indexes) for example:
(int64, int64, float64)
might give:
{int64: [0, 1], float64: [2]}
The index is the index variable for the driving range loop over the
mixed tuple.
"""
elif_tplt = "\n\telif PLACEHOLDER_INDEX in (%s,):\n\t\tSENTINEL = None"
# Note regarding the insertion of the garbage/defeat variables below:
# These values have been designed and inserted to defeat a specific
# behaviour of the cpython optimizer. The optimization was introduced
# in Python 3.10.
# The URL for the BPO is:
# https://bugs.python.org/issue44626
# The code for the optimization can be found at:
# https://github.com/python/cpython/blob/d41abe8/Python/compile.c#L7533-L7557
# Essentially the CPython optimizer will inline the exit block under
# certain circumstances and thus replace the jump with a return if the
# exit block is small enough. This is an issue for unroller, as it
# looks for a jump, not a return, when it inserts the generated switch
# table.
# Part of the condition for this optimization to be applied is that the
# exit block not exceed a certain (4 at the time of writing) number of
# bytecode instructions. We defeat the optimizer by inserting a
# sufficient number of instructions so that the exit block is big
# enough. We don't care about this garbage, because the generated exit
# block is discarded anyway when we smash the switch table into the
# original function and so all the inserted garbage is dropped again.
# The final lines of the stacktrace w/o this will look like:
#
# File "/numba/numba/core/untyped_passes.py", line 830, \
# in inject_loop_body
# sentinel_exits.add(blk.body[-1].target)
# AttributeError: Failed in nopython mode pipeline \
# (step: handles literal_unroll)
# Failed in literal_unroll_subpipeline mode pipeline \
# (step: performs mixed container unroll)
# 'Return' object has no attribute 'target'
#
# Which indicates that a Return has been found instead of a Jump
b = ('def foo():\n\tif PLACEHOLDER_INDEX in (%s,):\n\t\t'
'SENTINEL = None\n%s\n\telse:\n\t\t'
'raise RuntimeError("Unreachable")\n\t'
'py310_defeat1 = 1\n\t'
'py310_defeat2 = 2\n\t'
'py310_defeat3 = 3\n\t'
'py310_defeat4 = 4\n\t'
)
keys = [k for k in data.keys()]
elifs = []
for i in range(1, len(keys)):
elifs.append(elif_tplt % ','.join(map(str, data[keys[i]])))
src = b % (','.join(map(str, data[keys[0]])), ''.join(elifs))
wstr = src
l = {}
exec(wstr, {}, l)
bfunc = l['foo']
branches = compile_to_numba_ir(bfunc, {})