/usr/lib/python2.7/dist-packages/numba/compiler.py is in python-numba 0.34.0-3.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 | from __future__ import print_function, division, absolute_import
import os
import inspect
from contextlib import contextmanager
from collections import namedtuple, defaultdict
from pprint import pprint
import sys
import warnings
import traceback
import threading
from .tracing import trace, event
from numba import (bytecode, interpreter, funcdesc, postproc,
typing, typeinfer, lowering, objmode, utils, config,
errors, types, ir, types, rewrites, transforms)
from numba.targets import cpu, callconv
from numba.annotations import type_annotations
from numba.parfor import ParforPass
from numba.inline_closurecall import InlineClosureCallPass
# Lock for the preventing multiple compiler execution
lock_compiler = threading.RLock()
class Flags(utils.ConfigOptions):
# These options are all false by default, but the defaults are
# different with the @jit decorator (see targets.options.TargetOptions).
OPTIONS = {
# Enable loop-lifting
'enable_looplift': False,
# Enable pyobject mode (in general)
'enable_pyobject': False,
# Enable pyobject mode inside lifted loops
'enable_pyobject_looplift': False,
# Force pyobject mode inside the whole function
'force_pyobject': False,
# Release GIL inside the native function
'release_gil': False,
'no_compile': False,
'debuginfo': False,
'boundcheck': False,
'forceinline': False,
'no_cpython_wrapper': False,
'auto_parallel': False,
'nrt': False,
'no_rewrites': False,
'error_model': 'python',
'fastmath': False,
}
DEFAULT_FLAGS = Flags()
DEFAULT_FLAGS.set('nrt')
CR_FIELDS = ["typing_context",
"target_context",
"entry_point",
"typing_error",
"type_annotation",
"signature",
"objectmode",
"lifted",
"fndesc",
"interpmode",
"library",
"call_helper",
"environment",
"has_dynamic_globals"]
class CompileResult(namedtuple("_CompileResult", CR_FIELDS)):
__slots__ = ()
def _reduce(self):
"""
Reduce a CompileResult to picklable components.
"""
libdata = self.library.serialize_using_object_code()
# Make it (un)picklable efficiently
typeann = str(self.type_annotation)
fndesc = self.fndesc
# Those don't need to be pickled and may fail
fndesc.typemap = fndesc.calltypes = None
return (libdata, self.fndesc, self.environment, self.signature,
self.objectmode, self.interpmode, self.lifted, typeann)
@classmethod
def _rebuild(cls, target_context, libdata, fndesc, env,
signature, objectmode, interpmode, lifted, typeann):
library = target_context.codegen().unserialize_library(libdata)
cfunc = target_context.get_executable(library, fndesc, env)
cr = cls(target_context=target_context,
typing_context=target_context.typing_context,
library=library,
environment=env,
entry_point=cfunc,
fndesc=fndesc,
type_annotation=typeann,
signature=signature,
objectmode=objectmode,
interpmode=interpmode,
lifted=lifted,
typing_error=None,
call_helper=None,
has_dynamic_globals=False, # by definition
)
return cr
_LowerResult = namedtuple("_LowerResult", [
"fndesc",
"call_helper",
"cfunc",
"env",
"has_dynamic_globals",
])
def compile_result(**kws):
keys = set(kws.keys())
fieldset = set(CR_FIELDS)
badnames = keys - fieldset
if badnames:
raise NameError(*badnames)
missing = fieldset - keys
for k in missing:
kws[k] = None
# Avoid keeping alive traceback variables
if sys.version_info >= (3,):
err = kws['typing_error']
if err is not None:
kws['typing_error'] = err.with_traceback(None)
return CompileResult(**kws)
def compile_isolated(func, args, return_type=None, flags=DEFAULT_FLAGS,
locals={}):
"""
Compile the function in an isolated environment (typing and target context).
Good for testing.
"""
from .targets.registry import cpu_target
typingctx = typing.Context()
targetctx = cpu.CPUContext(typingctx)
# Register the contexts in case for nested @jit or @overload calls
with cpu_target.nested_context(typingctx, targetctx):
return compile_extra(typingctx, targetctx, func, args, return_type,
flags, locals)
def run_frontend(func):
"""
Run the compiler frontend over the given Python function, and return
the function's canonical Numba IR.
"""
# XXX make this a dedicated Pipeline?
func_id = bytecode.FunctionIdentity.from_function(func)
interp = interpreter.Interpreter(func_id)
bc = bytecode.ByteCode(func_id=func_id)
func_ir = interp.interpret(bc)
post_proc = postproc.PostProcessor(func_ir)
post_proc.run()
return func_ir
class _CompileStatus(object):
"""
Used like a C record
"""
__slots__ = ['fail_reason', 'can_fallback', 'can_giveup']
def __init__(self, can_fallback, can_giveup):
self.fail_reason = None
self.can_fallback = can_fallback
self.can_giveup = can_giveup
def __repr__(self):
vals = []
for k in self.__slots__:
vals.append("{k}={v}".format(k=k, v=getattr(self, k)))
return ', '.join(vals)
class _EarlyPipelineCompletion(Exception):
def __init__(self, result):
self.result = result
class _PipelineManager(object):
def __init__(self):
self.pipeline_order = []
self.pipeline_stages = {}
self._finalized = False
def create_pipeline(self, pipeline_name):
assert not self._finalized, "Pipelines can no longer be added"
self.pipeline_order.append(pipeline_name)
self.pipeline_stages[pipeline_name] = []
self.current = pipeline_name
def add_stage(self, stage_function, stage_description):
assert not self._finalized, "Stages can no longer be added."
current_pipeline_name = self.pipeline_order[-1]
func_desc_tuple = (stage_function, stage_description)
self.pipeline_stages[current_pipeline_name].append(func_desc_tuple)
def finalize(self):
self._finalized = True
def _patch_error(self, desc, exc):
"""
Patches the error to show the stage that it arose in.
"""
newmsg = "{desc}\n{exc}".format(desc=desc, exc=exc)
# For python2, attach the traceback of the previous exception.
if not utils.IS_PY3:
fmt = "Caused By:\n{tb}\n{newmsg}"
newmsg = fmt.format(tb=traceback.format_exc(), newmsg=newmsg)
exc.args = (newmsg,)
return exc
def run(self, status):
assert self._finalized, "PM must be finalized before run()"
res = None
for pipeline_name in self.pipeline_order:
event(pipeline_name)
is_final_pipeline = pipeline_name == self.pipeline_order[-1]
for stage, stage_name in self.pipeline_stages[pipeline_name]:
try:
event(stage_name)
stage()
except _EarlyPipelineCompletion as e:
return e.result
except BaseException as e:
msg = "Failed at %s (%s)" % (pipeline_name, stage_name)
patched_exception = self._patch_error(msg, e)
# No more fallback pipelines?
if is_final_pipeline:
raise patched_exception
# Go to next fallback pipeline
else:
status.fail_reason = patched_exception
break
else:
return None
# TODO save all error information
raise CompilerError("All pipelines have failed")
class Pipeline(object):
"""
Stores and manages states for the compiler pipeline
"""
def __init__(self, typingctx, targetctx, library, args, return_type, flags,
locals):
# Make sure the environment is reloaded
config.reload_config()
typingctx.refresh()
targetctx.refresh()
self.typingctx = typingctx
self.targetctx = _make_subtarget(targetctx, flags)
self.library = library
self.args = args
self.return_type = return_type
self.flags = flags
self.locals = locals
# Results of various steps of the compilation pipeline
self.bc = None
self.func_id = None
self.func_ir = None
self.func_ir_original = None # used for fallback
self.lifted = None
self.lifted_from = None
self.typemap = None
self.calltypes = None
self.type_annotation = None
self.status = _CompileStatus(
can_fallback=self.flags.enable_pyobject,
can_giveup=config.COMPATIBILITY_MODE
)
@contextmanager
def fallback_context(self, msg):
"""
Wraps code that would signal a fallback to object mode
"""
try:
yield
except BaseException as e:
if not self.status.can_fallback:
raise
else:
if utils.PYVERSION >= (3,):
# Clear all references attached to the traceback
e = e.with_traceback(None)
warnings.warn_explicit('%s: %s' % (msg, e),
errors.NumbaWarning,
self.func_id.filename,
self.func_id.firstlineno)
raise
@contextmanager
def giveup_context(self, msg):
"""
Wraps code that would signal a fallback to interpreter mode
"""
try:
yield
except BaseException as e:
if not self.status.can_giveup:
raise
else:
if utils.PYVERSION >= (3,):
# Clear all references attached to the traceback
e = e.with_traceback(None)
warnings.warn_explicit('%s: %s' % (msg, e),
errors.NumbaWarning,
self.func_id.filename,
self.func_id.firstlineno)
raise
def extract_bytecode(self, func_id):
"""
Extract bytecode from function
"""
bc = bytecode.ByteCode(func_id)
if config.DUMP_BYTECODE:
print(bc.dump())
return bc
def compile_extra(self, func):
self.func_id = bytecode.FunctionIdentity.from_function(func)
try:
bc = self.extract_bytecode(self.func_id)
except BaseException as e:
if self.status.can_giveup:
self.stage_compile_interp_mode()
return self.cr
else:
raise e
self.bc = bc
self.lifted = ()
self.lifted_from = None
return self._compile_bytecode()
def compile_ir(self, func_ir, lifted=(), lifted_from=None):
self.func_id = func_ir.func_id
self.lifted = lifted
self.lifted_from = lifted_from
self._set_and_check_ir(func_ir)
return self._compile_ir()
def stage_analyze_bytecode(self):
"""
Analyze bytecode and translating to Numba IR
"""
func_ir = translate_stage(self.func_id, self.bc)
self._set_and_check_ir(func_ir)
def _set_and_check_ir(self, func_ir):
self.func_ir = func_ir
self.nargs = self.func_ir.arg_count
if not self.args and self.flags.force_pyobject:
# Allow an empty argument types specification when object mode
# is explicitly requested.
self.args = (types.pyobject,) * self.nargs
elif len(self.args) != self.nargs:
raise TypeError("Signature mismatch: %d argument types given, "
"but function takes %d arguments"
% (len(self.args), self.nargs))
def stage_process_ir(self):
ir_processing_stage(self.func_ir)
def stage_preserve_ir(self):
self.func_ir_original = self.func_ir.copy()
def frontend_looplift(self):
"""
Loop lifting analysis and transformation
"""
loop_flags = self.flags.copy()
outer_flags = self.flags.copy()
# Do not recursively loop lift
outer_flags.unset('enable_looplift')
loop_flags.unset('enable_looplift')
if not self.flags.enable_pyobject_looplift:
loop_flags.unset('enable_pyobject')
main, loops = transforms.loop_lifting(self.func_ir,
typingctx=self.typingctx,
targetctx=self.targetctx,
locals=self.locals,
flags=loop_flags)
if loops:
# Some loops were extracted
if config.DEBUG_FRONTEND or config.DEBUG:
for loop in loops:
print("Lifting loop", loop.get_source_location())
cres = compile_ir(self.typingctx, self.targetctx, main,
self.args, self.return_type,
outer_flags, self.locals,
lifted=tuple(loops), lifted_from=None)
return cres
def stage_objectmode_frontend(self):
"""
Front-end: Analyze bytecode, generate Numba IR, infer types
"""
self.func_ir = self.func_ir_original or self.func_ir
if self.flags.enable_looplift:
assert not self.lifted
cres = self.frontend_looplift()
if cres is not None:
raise _EarlyPipelineCompletion(cres)
# Fallback typing: everything is a python object
self.typemap = defaultdict(lambda: types.pyobject)
self.calltypes = defaultdict(lambda: types.pyobject)
self.return_type = types.pyobject
def stage_nopython_frontend(self):
"""
Type inference and legalization
"""
with self.fallback_context('Function "%s" failed type inference'
% (self.func_id.func_name,)):
# Type inference
self.typemap, self.return_type, self.calltypes = type_inference_stage(
self.typingctx,
self.func_ir,
self.args,
self.return_type,
self.locals)
with self.fallback_context('Function "%s" has invalid return type'
% (self.func_id.func_name,)):
legalize_return_type(self.return_type, self.func_ir,
self.targetctx)
def stage_generic_rewrites(self):
"""
Perform any intermediate representation rewrites before type
inference.
"""
assert self.func_ir
with self.fallback_context('Internal error in pre-inference rewriting '
'pass encountered during compilation of '
'function "%s"' % (self.func_id.func_name,)):
rewrites.rewrite_registry.apply('before-inference',
self, self.func_ir)
def stage_nopython_rewrites(self):
"""
Perform any intermediate representation rewrites after type
inference.
"""
# Ensure we have an IR and type information.
assert self.func_ir
assert isinstance(getattr(self, 'typemap', None), dict)
assert isinstance(getattr(self, 'calltypes', None), dict)
with self.fallback_context('Internal error in post-inference rewriting '
'pass encountered during compilation of '
'function "%s"' % (self.func_id.func_name,)):
rewrites.rewrite_registry.apply('after-inference',
self, self.func_ir)
def stage_parfor_pass(self):
"""
Convert data-parallel computations into Parfor nodes
"""
# Ensure we have an IR and type information.
assert self.func_ir
parfor_pass = ParforPass(self.func_ir, self.type_annotation.typemap,
self.type_annotation.calltypes, self.return_type)
parfor_pass.run()
def stage_inline_pass(self):
"""
Inline calls to locally defined closures.
"""
# Ensure we have an IR and type information.
assert self.func_ir
inline_pass = InlineClosureCallPass(self.func_ir, run_frontend)
inline_pass.run()
# Remove all Dels, and re-run postproc
post_proc = postproc.PostProcessor(self.func_ir)
post_proc.run()
if config.DEBUG or config.DUMP_IR:
name = self.func_ir.func_id.func_qualname
print(("IR DUMP: %s" % name).center(80, "-"))
self.func_ir.dump()
def stage_annotate_type(self):
"""
Create type annotation after type inference
"""
self.type_annotation = type_annotations.TypeAnnotation(
func_ir=self.func_ir,
typemap=self.typemap,
calltypes=self.calltypes,
lifted=self.lifted,
lifted_from=self.lifted_from,
args=self.args,
return_type=self.return_type,
html_output=config.HTML)
if config.ANNOTATE:
print("ANNOTATION".center(80, '-'))
print(self.type_annotation)
print('=' * 80)
if config.HTML:
with open(config.HTML, 'w') as fout:
self.type_annotation.html_annotate(fout)
def backend_object_mode(self):
"""
Object mode compilation
"""
with self.giveup_context("Function %s failed at object mode lowering"
% (self.func_id.func_name,)):
if len(self.args) != self.nargs:
# append missing
self.args = (tuple(self.args) + (types.pyobject,) *
(self.nargs - len(self.args)))
return py_lowering_stage(self.targetctx,
self.library,
self.func_ir,
self.flags)
def backend_nopython_mode(self):
"""Native mode compilation"""
with self.fallback_context("Function %s failed at nopython "
"mode lowering" % (self.func_id.func_name,)):
return native_lowering_stage(
self.targetctx,
self.library,
self.func_ir,
self.typemap,
self.return_type,
self.calltypes,
self.flags)
def _backend(self, lowerfn, objectmode):
"""
Back-end: Generate LLVM IR from Numba IR, compile to machine code
"""
if self.library is None:
codegen = self.targetctx.codegen()
self.library = codegen.create_library(self.func_id.func_qualname)
# Enable object caching upfront, so that the library can
# be later serialized.
self.library.enable_object_caching()
lowered = lowerfn()
signature = typing.signature(self.return_type, *self.args)
self.cr = compile_result(typing_context=self.typingctx,
target_context=self.targetctx,
entry_point=lowered.cfunc,
typing_error=self.status.fail_reason,
type_annotation=self.type_annotation,
library=self.library,
call_helper=lowered.call_helper,
signature=signature,
objectmode=objectmode,
interpmode=False,
lifted=self.lifted,
fndesc=lowered.fndesc,
environment=lowered.env,
has_dynamic_globals=lowered.has_dynamic_globals,
)
def stage_objectmode_backend(self):
"""
Lowering for object mode
"""
lowerfn = self.backend_object_mode
self._backend(lowerfn, objectmode=True)
# Warn if compiled function in object mode and force_pyobject not set
if not self.flags.force_pyobject:
if len(self.lifted) > 0:
warn_msg = 'Function "%s" was compiled in object mode without forceobj=True, but has lifted loops.' % (self.func_id.func_name,)
else:
warn_msg = 'Function "%s" was compiled in object mode without forceobj=True.' % (self.func_id.func_name,)
warnings.warn_explicit(warn_msg, errors.NumbaWarning,
self.func_id.filename,
self.func_id.firstlineno)
if self.flags.release_gil:
warn_msg = "Code running in object mode won't allow parallel execution despite nogil=True."
warnings.warn_explicit(warn_msg, errors.NumbaWarning,
self.func_id.filename,
self.func_id.firstlineno)
def stage_nopython_backend(self):
"""
Do lowering for nopython
"""
lowerfn = self.backend_nopython_mode
self._backend(lowerfn, objectmode=False)
def stage_compile_interp_mode(self):
"""
Just create a compile result for interpreter mode
"""
args = [types.pyobject] * len(self.args)
signature = typing.signature(types.pyobject, *args)
self.cr = compile_result(typing_context=self.typingctx,
target_context=self.targetctx,
entry_point=self.func_id.func,
typing_error=self.status.fail_reason,
type_annotation="<Interpreter mode function>",
signature=signature,
objectmode=False,
interpmode=True,
lifted=(),
fndesc=None,)
def stage_cleanup(self):
"""
Cleanup intermediate results to release resources.
"""
def _compile_core(self):
"""
Populate and run compiler pipeline
"""
pm = _PipelineManager()
if not self.flags.force_pyobject:
pm.create_pipeline("nopython")
if self.func_ir is None:
pm.add_stage(self.stage_analyze_bytecode, "analyzing bytecode")
pm.add_stage(self.stage_process_ir, "processing IR")
if not self.flags.no_rewrites:
if self.status.can_fallback:
pm.add_stage(self.stage_preserve_ir, "preserve IR for fallback")
pm.add_stage(self.stage_generic_rewrites, "nopython rewrites")
pm.add_stage(self.stage_inline_pass, "inline calls to locally defined closures")
pm.add_stage(self.stage_nopython_frontend, "nopython frontend")
pm.add_stage(self.stage_annotate_type, "annotate type")
if not self.flags.no_rewrites:
pm.add_stage(self.stage_nopython_rewrites, "nopython rewrites")
if self.flags.auto_parallel:
pm.add_stage(self.stage_parfor_pass, "convert to parfors")
pm.add_stage(self.stage_nopython_backend, "nopython mode backend")
pm.add_stage(self.stage_cleanup, "cleanup intermediate results")
if self.status.can_fallback or self.flags.force_pyobject:
pm.create_pipeline("object")
if self.func_ir is None:
pm.add_stage(self.stage_analyze_bytecode, "analyzing bytecode")
pm.add_stage(self.stage_process_ir, "processing IR")
pm.add_stage(self.stage_objectmode_frontend, "object mode frontend")
pm.add_stage(self.stage_annotate_type, "annotate type")
pm.add_stage(self.stage_objectmode_backend, "object mode backend")
pm.add_stage(self.stage_cleanup, "cleanup intermediate results")
if self.status.can_giveup:
pm.create_pipeline("interp")
pm.add_stage(self.stage_compile_interp_mode, "compiling with interpreter mode")
pm.add_stage(self.stage_cleanup, "cleanup intermediate results")
pm.finalize()
res = pm.run(self.status)
if res is not None:
# Early pipeline completion
return res
else:
assert self.cr is not None
return self.cr
def _compile_bytecode(self):
"""
Populate and run pipeline for bytecode input
"""
assert self.func_ir is None
return self._compile_core()
def _compile_ir(self):
"""
Populate and run pipeline for IR input
"""
assert self.func_ir is not None
return self._compile_core()
def _make_subtarget(targetctx, flags):
"""
Make a new target context from the given target context and flags.
"""
subtargetoptions = {}
if flags.debuginfo:
subtargetoptions['enable_debuginfo'] = True
if flags.boundcheck:
subtargetoptions['enable_boundcheck'] = True
if flags.nrt:
subtargetoptions['enable_nrt'] = True
if flags.auto_parallel:
subtargetoptions['auto_parallel'] = True
if flags.fastmath:
subtargetoptions['enable_fastmath'] = True
error_model = callconv.create_error_model(flags.error_model, targetctx)
subtargetoptions['error_model'] = error_model
return targetctx.subtarget(**subtargetoptions)
def compile_extra(typingctx, targetctx, func, args, return_type, flags,
locals, library=None):
"""
Args
----
- return_type
Use ``None`` to indicate
"""
pipeline = Pipeline(typingctx, targetctx, library,
args, return_type, flags, locals)
return pipeline.compile_extra(func)
def compile_ir(typingctx, targetctx, func_ir, args, return_type, flags,
locals, lifted=(), lifted_from=None, library=None):
"""
Compile a function with the given IR.
For internal use only.
"""
pipeline = Pipeline(typingctx, targetctx, library,
args, return_type, flags, locals)
return pipeline.compile_ir(func_ir=func_ir, lifted=lifted,
lifted_from=lifted_from)
def compile_internal(typingctx, targetctx, library,
func, args, return_type, flags, locals):
"""
For internal use only.
"""
pipeline = Pipeline(typingctx, targetctx, library,
args, return_type, flags, locals)
return pipeline.compile_extra(func)
def legalize_return_type(return_type, interp, targetctx):
"""
Only accept array return type iff it is passed into the function.
Reject function object return types if in nopython mode.
"""
if not targetctx.enable_nrt and isinstance(return_type, types.Array):
# Walk IR to discover all arguments and all return statements
retstmts = []
caststmts = {}
argvars = set()
for bid, blk in interp.blocks.items():
for inst in blk.body:
if isinstance(inst, ir.Return):
retstmts.append(inst.value.name)
elif isinstance(inst, ir.Assign):
if (isinstance(inst.value, ir.Expr)
and inst.value.op == 'cast'):
caststmts[inst.target.name] = inst.value
elif isinstance(inst.value, ir.Arg):
argvars.add(inst.target.name)
assert retstmts, "No return statements?"
for var in retstmts:
cast = caststmts.get(var)
if cast is None or cast.value.name not in argvars:
raise TypeError("Only accept returning of array passed into the "
"function as argument")
elif (isinstance(return_type, types.Function) or
isinstance(return_type, types.Phantom)):
raise TypeError("Can't return function object in nopython mode")
def translate_stage(func_id, bytecode):
interp = interpreter.Interpreter(func_id)
return interp.interpret(bytecode)
def ir_processing_stage(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 func_ir
def type_inference_stage(typingctx, interp, args, return_type, locals={}):
if len(args) != interp.arg_count:
raise TypeError("Mismatch number of argument types")
warnings = errors.WarningsFixer(errors.NumbaWarning)
infer = typeinfer.TypeInferer(typingctx, interp, warnings)
with typingctx.callstack.register(infer, interp.func_id, args):
# Seed argument types
for index, (name, ty) in enumerate(zip(interp.arg_names, args)):
infer.seed_argument(name, index, ty)
# Seed return type
if return_type is not None:
infer.seed_return(return_type)
# Seed local types
for k, v in locals.items():
infer.seed_type(k, v)
infer.build_constraint()
infer.propagate()
typemap, restype, calltypes = infer.unify()
# Output all Numba warnings
warnings.flush()
return typemap, restype, calltypes
def native_lowering_stage(targetctx, library, interp, typemap, restype,
calltypes, flags):
# Lowering
fndesc = funcdesc.PythonFunctionDescriptor.from_specialized_function(
interp, typemap, restype, calltypes, mangler=targetctx.mangler,
inline=flags.forceinline)
lower = lowering.Lower(targetctx, library, fndesc, interp)
lower.lower()
if not flags.no_cpython_wrapper:
lower.create_cpython_wrapper(flags.release_gil)
env = lower.env
call_helper = lower.call_helper
has_dynamic_globals = lower.has_dynamic_globals
del lower
if flags.no_compile:
return _LowerResult(fndesc, call_helper, cfunc=None, env=env,
has_dynamic_globals=has_dynamic_globals)
else:
# Prepare for execution
cfunc = targetctx.get_executable(library, fndesc, env)
# Insert native function for use by other jitted-functions.
# We also register its library to allow for inlining.
targetctx.insert_user_function(cfunc, fndesc, [library])
return _LowerResult(fndesc, call_helper, cfunc=cfunc, env=env,
has_dynamic_globals=has_dynamic_globals)
def py_lowering_stage(targetctx, library, interp, flags):
fndesc = funcdesc.PythonFunctionDescriptor.from_object_mode_function(interp)
lower = objmode.PyLower(targetctx, library, fndesc, interp)
lower.lower()
if not flags.no_cpython_wrapper:
lower.create_cpython_wrapper()
env = lower.env
call_helper = lower.call_helper
has_dynamic_globals = lower.has_dynamic_globals
del lower
if flags.no_compile:
return _LowerResult(fndesc, call_helper, cfunc=None, env=env,
has_dynamic_globals=has_dynamic_globals)
else:
# Prepare for execution
cfunc = targetctx.get_executable(library, fndesc, env)
return _LowerResult(fndesc, call_helper, cfunc=cfunc, env=env,
has_dynamic_globals=has_dynamic_globals)
|