PageRenderTime 57ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 0ms

/rpython/rlib/jit.py

https://bitbucket.org/kcr/pypy
Python | 1032 lines | 1027 code | 5 blank | 0 comment | 6 complexity | 8032162c35cd44a36ffea308885b7426 MD5 | raw file
Possible License(s): Apache-2.0
  1. import sys
  2. import py
  3. from rpython.rlib.nonconst import NonConstant
  4. from rpython.rlib.objectmodel import CDefinedIntSymbolic, keepalive_until_here, specialize
  5. from rpython.rlib.unroll import unrolling_iterable
  6. from rpython.rtyper.extregistry import ExtRegistryEntry
  7. from rpython.tool.sourcetools import rpython_wrapper
  8. DEBUG_ELIDABLE_FUNCTIONS = False
  9. def elidable(func):
  10. """ Decorate a function as "trace-elidable". Usually this means simply that
  11. the function is constant-foldable, i.e. is pure and has no side-effects.
  12. In some situations it is ok to use this decorator if the function *has*
  13. side effects, as long as these side-effects are idempotent. A typical
  14. example for this would be a cache.
  15. To be totally precise:
  16. (1) the result of the call should not change if the arguments are
  17. the same (same numbers or same pointers)
  18. (2) it's fine to remove the call completely if we can guess the result
  19. according to rule 1
  20. (3) the function call can be moved around by optimizer,
  21. but only so it'll be called earlier and not later.
  22. Most importantly it doesn't mean that an elidable function has no observable
  23. side effect, but those side effects are idempotent (ie caching).
  24. If a particular call to this function ends up raising an exception, then it
  25. is handled like a normal function call (this decorator is ignored).
  26. """
  27. if DEBUG_ELIDABLE_FUNCTIONS:
  28. cache = {}
  29. oldfunc = func
  30. def func(*args):
  31. result = oldfunc(*args) # if it raises, no caching
  32. try:
  33. oldresult = cache.setdefault(args, result)
  34. except TypeError:
  35. pass # unhashable args
  36. else:
  37. assert oldresult == result
  38. return result
  39. func._elidable_function_ = True
  40. return func
  41. def purefunction(*args, **kwargs):
  42. import warnings
  43. warnings.warn("purefunction is deprecated, use elidable instead", DeprecationWarning)
  44. return elidable(*args, **kwargs)
  45. def hint(x, **kwds):
  46. """ Hint for the JIT
  47. possible arguments are:
  48. * promote - promote the argument from a variable into a constant
  49. * promote_string - same, but promote string by *value*
  50. * access_directly - directly access a virtualizable, as a structure
  51. and don't treat it as a virtualizable
  52. * fresh_virtualizable - means that virtualizable was just allocated.
  53. Useful in say Frame.__init__ when we do want
  54. to store things directly on it. Has to come with
  55. access_directly=True
  56. """
  57. return x
  58. @specialize.argtype(0)
  59. def promote(x):
  60. return hint(x, promote=True)
  61. def promote_string(x):
  62. return hint(x, promote_string=True)
  63. def dont_look_inside(func):
  64. """ Make sure the JIT does not trace inside decorated function
  65. (it becomes a call instead)
  66. """
  67. func._jit_look_inside_ = False
  68. return func
  69. def unroll_safe(func):
  70. """ JIT can safely unroll loops in this function and this will
  71. not lead to code explosion
  72. """
  73. func._jit_unroll_safe_ = True
  74. return func
  75. def loop_invariant(func):
  76. """ Describes a function with no argument that returns an object that
  77. is always the same in a loop.
  78. Use it only if you know what you're doing.
  79. """
  80. dont_look_inside(func)
  81. func._jit_loop_invariant_ = True
  82. return func
  83. def _get_args(func):
  84. import inspect
  85. args, varargs, varkw, defaults = inspect.getargspec(func)
  86. assert varargs is None and varkw is None
  87. assert not defaults
  88. return args
  89. def elidable_promote(promote_args='all'):
  90. """ A decorator that promotes all arguments and then calls the supplied
  91. function
  92. """
  93. def decorator(func):
  94. elidable(func)
  95. args = _get_args(func)
  96. argstring = ", ".join(args)
  97. code = ["def f(%s):\n" % (argstring, )]
  98. if promote_args != 'all':
  99. args = [args[int(i)] for i in promote_args.split(",")]
  100. for arg in args:
  101. code.append(" %s = hint(%s, promote=True)\n" % (arg, arg))
  102. code.append(" return _orig_func_unlikely_name(%s)\n" % (argstring, ))
  103. d = {"_orig_func_unlikely_name": func, "hint": hint}
  104. exec py.code.Source("\n".join(code)).compile() in d
  105. result = d["f"]
  106. result.func_name = func.func_name + "_promote"
  107. return result
  108. return decorator
  109. def purefunction_promote(*args, **kwargs):
  110. import warnings
  111. warnings.warn("purefunction_promote is deprecated, use elidable_promote instead", DeprecationWarning)
  112. return elidable_promote(*args, **kwargs)
  113. def look_inside_iff(predicate):
  114. """
  115. look inside (including unrolling loops) the target function, if and only if
  116. predicate(*args) returns True
  117. """
  118. def inner(func):
  119. func = unroll_safe(func)
  120. # When we return the new function, it might be specialized in some
  121. # way. We "propogate" this specialization by using
  122. # specialize:call_location on relevant functions.
  123. for thing in [func, predicate]:
  124. thing._annspecialcase_ = "specialize:call_location"
  125. args = _get_args(func)
  126. predicateargs = _get_args(predicate)
  127. assert len(args) == len(predicateargs), "%s and predicate %s need the same numbers of arguments" % (func, predicate)
  128. d = {
  129. "dont_look_inside": dont_look_inside,
  130. "predicate": predicate,
  131. "func": func,
  132. "we_are_jitted": we_are_jitted,
  133. }
  134. exec py.code.Source("""
  135. @dont_look_inside
  136. def trampoline(%(arguments)s):
  137. return func(%(arguments)s)
  138. if hasattr(func, "oopspec"):
  139. trampoline.oopspec = func.oopspec
  140. del func.oopspec
  141. trampoline.__name__ = func.__name__ + "_trampoline"
  142. trampoline._annspecialcase_ = "specialize:call_location"
  143. def f(%(arguments)s):
  144. if not we_are_jitted() or predicate(%(arguments)s):
  145. return func(%(arguments)s)
  146. else:
  147. return trampoline(%(arguments)s)
  148. f.__name__ = func.__name__ + "_look_inside_iff"
  149. f._always_inline = True
  150. """ % {"arguments": ", ".join(args)}).compile() in d
  151. return d["f"]
  152. return inner
  153. def oopspec(spec):
  154. def decorator(func):
  155. func.oopspec = spec
  156. return func
  157. return decorator
  158. @oopspec("jit.isconstant(value)")
  159. def isconstant(value):
  160. """
  161. While tracing, returns whether or not the value is currently known to be
  162. constant. This is not perfect, values can become constant later. Mostly for
  163. use with @look_inside_iff.
  164. This is for advanced usage only.
  165. """
  166. return NonConstant(False)
  167. isconstant._annspecialcase_ = "specialize:call_location"
  168. @oopspec("jit.isvirtual(value)")
  169. def isvirtual(value):
  170. """
  171. Returns if this value is virtual, while tracing, it's relatively
  172. conservative and will miss some cases.
  173. This is for advanced usage only.
  174. """
  175. return NonConstant(False)
  176. isvirtual._annspecialcase_ = "specialize:call_location"
  177. LIST_CUTOFF = 2
  178. @specialize.call_location()
  179. def loop_unrolling_heuristic(lst, size):
  180. """ In which cases iterating over items of lst can be unrolled
  181. """
  182. return isvirtual(lst) or (isconstant(size) and size <= LIST_CUTOFF)
  183. class Entry(ExtRegistryEntry):
  184. _about_ = hint
  185. def compute_result_annotation(self, s_x, **kwds_s):
  186. from rpython.annotator import model as annmodel
  187. s_x = annmodel.not_const(s_x)
  188. access_directly = 's_access_directly' in kwds_s
  189. fresh_virtualizable = 's_fresh_virtualizable' in kwds_s
  190. if access_directly or fresh_virtualizable:
  191. assert access_directly, "lone fresh_virtualizable hint"
  192. if isinstance(s_x, annmodel.SomeInstance):
  193. from rpython.flowspace.model import Constant
  194. classdesc = s_x.classdef.classdesc
  195. virtualizable = classdesc.read_attribute('_virtualizable2_',
  196. Constant(None)).value
  197. if virtualizable is not None:
  198. flags = s_x.flags.copy()
  199. flags['access_directly'] = True
  200. if fresh_virtualizable:
  201. flags['fresh_virtualizable'] = True
  202. s_x = annmodel.SomeInstance(s_x.classdef,
  203. s_x.can_be_None,
  204. flags)
  205. return s_x
  206. def specialize_call(self, hop, **kwds_i):
  207. from rpython.rtyper.lltypesystem import lltype
  208. hints = {}
  209. for key, index in kwds_i.items():
  210. s_value = hop.args_s[index]
  211. if not s_value.is_constant():
  212. from rpython.rtyper.error import TyperError
  213. raise TyperError("hint %r is not constant" % (key,))
  214. assert key.startswith('i_')
  215. hints[key[2:]] = s_value.const
  216. v = hop.inputarg(hop.args_r[0], arg=0)
  217. c_hint = hop.inputconst(lltype.Void, hints)
  218. hop.exception_cannot_occur()
  219. return hop.genop('hint', [v, c_hint], resulttype=v.concretetype)
  220. def we_are_jitted():
  221. """ Considered as true during tracing and blackholing,
  222. so its consquences are reflected into jitted code """
  223. return False
  224. _we_are_jitted = CDefinedIntSymbolic('0 /* we are not jitted here */',
  225. default=0)
  226. class Entry(ExtRegistryEntry):
  227. _about_ = we_are_jitted
  228. def compute_result_annotation(self):
  229. from rpython.annotator import model as annmodel
  230. return annmodel.SomeInteger(nonneg=True)
  231. def specialize_call(self, hop):
  232. from rpython.rtyper.lltypesystem import lltype
  233. hop.exception_cannot_occur()
  234. return hop.inputconst(lltype.Signed, _we_are_jitted)
  235. def current_trace_length():
  236. """During JIT tracing, returns the current trace length (as a constant).
  237. If not tracing, returns -1."""
  238. if NonConstant(False):
  239. return 73
  240. return -1
  241. current_trace_length.oopspec = 'jit.current_trace_length()'
  242. def jit_debug(string, arg1=-sys.maxint-1, arg2=-sys.maxint-1,
  243. arg3=-sys.maxint-1, arg4=-sys.maxint-1):
  244. """When JITted, cause an extra operation JIT_DEBUG to appear in
  245. the graphs. Should not be left after debugging."""
  246. keepalive_until_here(string) # otherwise the whole function call is removed
  247. jit_debug.oopspec = 'jit.debug(string, arg1, arg2, arg3, arg4)'
  248. def assert_green(value):
  249. """Very strong assert: checks that 'value' is a green
  250. (a JIT compile-time constant)."""
  251. keepalive_until_here(value)
  252. assert_green._annspecialcase_ = 'specialize:argtype(0)'
  253. assert_green.oopspec = 'jit.assert_green(value)'
  254. class AssertGreenFailed(Exception):
  255. pass
  256. def jit_callback(name):
  257. """Use as a decorator for C callback functions, to insert a
  258. jitdriver.jit_merge_point() at the start. Only for callbacks
  259. that typically invoke more app-level Python code.
  260. """
  261. def decorate(func):
  262. from rpython.tool.sourcetools import compile2
  263. #
  264. def get_printable_location():
  265. return name
  266. jitdriver = JitDriver(get_printable_location=get_printable_location,
  267. greens=[], reds='auto', name=name)
  268. #
  269. args = ','.join(['a%d' % i for i in range(func.func_code.co_argcount)])
  270. source = """def callback_with_jitdriver(%(args)s):
  271. jitdriver.jit_merge_point()
  272. return real_callback(%(args)s)""" % locals()
  273. miniglobals = {
  274. 'jitdriver': jitdriver,
  275. 'real_callback': func,
  276. }
  277. exec compile2(source) in miniglobals
  278. return miniglobals['callback_with_jitdriver']
  279. return decorate
  280. # ____________________________________________________________
  281. # VRefs
  282. def virtual_ref(x):
  283. """Creates a 'vref' object that contains a reference to 'x'. Calls
  284. to virtual_ref/virtual_ref_finish must be properly nested. The idea
  285. is that the object 'x' is supposed to be JITted as a virtual between
  286. the calls to virtual_ref and virtual_ref_finish, but the 'vref'
  287. object can escape at any point in time. If at runtime it is
  288. dereferenced (by the call syntax 'vref()'), it returns 'x', which is
  289. then forced."""
  290. return DirectJitVRef(x)
  291. virtual_ref.oopspec = 'virtual_ref(x)'
  292. def virtual_ref_finish(vref, x):
  293. """See docstring in virtual_ref(x)"""
  294. keepalive_until_here(x) # otherwise the whole function call is removed
  295. _virtual_ref_finish(vref, x)
  296. virtual_ref_finish.oopspec = 'virtual_ref_finish(x)'
  297. def non_virtual_ref(x):
  298. """Creates a 'vref' that just returns x when called; nothing more special.
  299. Used for None or for frames outside JIT scope."""
  300. return DirectVRef(x)
  301. class InvalidVirtualRef(Exception):
  302. """
  303. Raised if we try to call a non-forced virtualref after the call to
  304. virtual_ref_finish
  305. """
  306. # ---------- implementation-specific ----------
  307. class DirectVRef(object):
  308. def __init__(self, x):
  309. self._x = x
  310. self._state = 'non-forced'
  311. def __call__(self):
  312. if self._state == 'non-forced':
  313. self._state = 'forced'
  314. elif self._state == 'invalid':
  315. raise InvalidVirtualRef
  316. return self._x
  317. @property
  318. def virtual(self):
  319. """A property that is True if the vref contains a virtual that would
  320. be forced by the '()' operator."""
  321. return self._state == 'non-forced'
  322. def _finish(self):
  323. if self._state == 'non-forced':
  324. self._state = 'invalid'
  325. class DirectJitVRef(DirectVRef):
  326. def __init__(self, x):
  327. assert x is not None, "virtual_ref(None) is not allowed"
  328. DirectVRef.__init__(self, x)
  329. def _virtual_ref_finish(vref, x):
  330. assert vref._x is x, "Invalid call to virtual_ref_finish"
  331. vref._finish()
  332. class Entry(ExtRegistryEntry):
  333. _about_ = (non_virtual_ref, DirectJitVRef)
  334. def compute_result_annotation(self, s_obj):
  335. from rpython.rlib import _jit_vref
  336. return _jit_vref.SomeVRef(s_obj)
  337. def specialize_call(self, hop):
  338. return hop.r_result.specialize_call(hop)
  339. class Entry(ExtRegistryEntry):
  340. _type_ = DirectVRef
  341. def compute_annotation(self):
  342. from rpython.rlib import _jit_vref
  343. assert isinstance(self.instance, DirectVRef)
  344. s_obj = self.bookkeeper.immutablevalue(self.instance())
  345. return _jit_vref.SomeVRef(s_obj)
  346. class Entry(ExtRegistryEntry):
  347. _about_ = _virtual_ref_finish
  348. def compute_result_annotation(self, s_vref, s_obj):
  349. pass
  350. def specialize_call(self, hop):
  351. hop.exception_cannot_occur()
  352. vref_None = non_virtual_ref(None)
  353. # ____________________________________________________________
  354. # User interface for the warmspot JIT policy
  355. class JitHintError(Exception):
  356. """Inconsistency in the JIT hints."""
  357. ENABLE_ALL_OPTS = (
  358. 'intbounds:rewrite:virtualize:string:earlyforce:pure:heap:unroll')
  359. PARAMETER_DOCS = {
  360. 'threshold': 'number of times a loop has to run for it to become hot',
  361. 'function_threshold': 'number of times a function must run for it to become traced from start',
  362. 'trace_eagerness': 'number of times a guard has to fail before we start compiling a bridge',
  363. 'trace_limit': 'number of recorded operations before we abort tracing with ABORT_TOO_LONG',
  364. 'inlining': 'inline python functions or not (1/0)',
  365. 'loop_longevity': 'a parameter controlling how long loops will be kept before being freed, an estimate',
  366. 'retrace_limit': 'how many times we can try retracing before giving up',
  367. 'max_retrace_guards': 'number of extra guards a retrace can cause',
  368. 'max_unroll_loops': 'number of extra unrollings a loop can cause',
  369. 'enable_opts': 'INTERNAL USE ONLY (MAY NOT WORK OR LEAD TO CRASHES): '
  370. 'optimizations to enable, or all = %s' % ENABLE_ALL_OPTS,
  371. }
  372. PARAMETERS = {'threshold': 1039, # just above 1024, prime
  373. 'function_threshold': 1619, # slightly more than one above, also prime
  374. 'trace_eagerness': 200,
  375. 'trace_limit': 6000,
  376. 'inlining': 1,
  377. 'loop_longevity': 1000,
  378. 'retrace_limit': 5,
  379. 'max_retrace_guards': 15,
  380. 'max_unroll_loops': 0,
  381. 'enable_opts': 'all',
  382. }
  383. unroll_parameters = unrolling_iterable(PARAMETERS.items())
  384. # ____________________________________________________________
  385. class JitDriver(object):
  386. """Base class to declare fine-grained user control on the JIT. So
  387. far, there must be a singleton instance of JitDriver. This style
  388. will allow us (later) to support a single RPython program with
  389. several independent JITting interpreters in it.
  390. """
  391. active = True # if set to False, this JitDriver is ignored
  392. virtualizables = []
  393. name = 'jitdriver'
  394. inline_jit_merge_point = False
  395. def __init__(self, greens=None, reds=None, virtualizables=None,
  396. get_jitcell_at=None, set_jitcell_at=None,
  397. get_printable_location=None, confirm_enter_jit=None,
  398. can_never_inline=None, should_unroll_one_iteration=None,
  399. name='jitdriver', check_untranslated=True):
  400. if greens is not None:
  401. self.greens = greens
  402. self.name = name
  403. if reds == 'auto':
  404. self.autoreds = True
  405. self.reds = []
  406. self.numreds = None # see warmspot.autodetect_jit_markers_redvars
  407. assert confirm_enter_jit is None, (
  408. "reds='auto' is not compatible with confirm_enter_jit")
  409. else:
  410. if reds is not None:
  411. self.reds = reds
  412. self.autoreds = False
  413. self.numreds = len(self.reds)
  414. if not hasattr(self, 'greens') or not hasattr(self, 'reds'):
  415. raise AttributeError("no 'greens' or 'reds' supplied")
  416. if virtualizables is not None:
  417. self.virtualizables = virtualizables
  418. for v in self.virtualizables:
  419. assert v in self.reds
  420. # if reds are automatic, they won't be passed to jit_merge_point, so
  421. # _check_arguments will receive only the green ones (i.e., the ones
  422. # which are listed explicitly). So, it is fine to just ignore reds
  423. self._somelivevars = set([name for name in
  424. self.greens + (self.reds or [])
  425. if '.' not in name])
  426. self._heuristic_order = {} # check if 'reds' and 'greens' are ordered
  427. self._make_extregistryentries()
  428. self.get_jitcell_at = get_jitcell_at
  429. self.set_jitcell_at = set_jitcell_at
  430. self.get_printable_location = get_printable_location
  431. self.confirm_enter_jit = confirm_enter_jit
  432. self.can_never_inline = can_never_inline
  433. self.should_unroll_one_iteration = should_unroll_one_iteration
  434. self.check_untranslated = check_untranslated
  435. def _freeze_(self):
  436. return True
  437. def _check_arguments(self, livevars):
  438. assert set(livevars) == self._somelivevars
  439. # check heuristically that 'reds' and 'greens' are ordered as
  440. # the JIT will need them to be: first INTs, then REFs, then
  441. # FLOATs.
  442. if len(self._heuristic_order) < len(livevars):
  443. from rpython.rlib.rarithmetic import (r_singlefloat, r_longlong,
  444. r_ulonglong, r_uint)
  445. added = False
  446. for var, value in livevars.items():
  447. if var not in self._heuristic_order:
  448. if (r_ulonglong is not r_uint and
  449. isinstance(value, (r_longlong, r_ulonglong))):
  450. assert 0, ("should not pass a r_longlong argument for "
  451. "now, because on 32-bit machines it needs "
  452. "to be ordered as a FLOAT but on 64-bit "
  453. "machines as an INT")
  454. elif isinstance(value, (int, long, r_singlefloat)):
  455. kind = '1:INT'
  456. elif isinstance(value, float):
  457. kind = '3:FLOAT'
  458. elif isinstance(value, (str, unicode)) and len(value) != 1:
  459. kind = '2:REF'
  460. elif isinstance(value, (list, dict)):
  461. kind = '2:REF'
  462. elif (hasattr(value, '__class__')
  463. and value.__class__.__module__ != '__builtin__'):
  464. if hasattr(value, '_freeze_'):
  465. continue # value._freeze_() is better not called
  466. elif getattr(value, '_alloc_flavor_', 'gc') == 'gc':
  467. kind = '2:REF'
  468. else:
  469. kind = '1:INT'
  470. else:
  471. continue
  472. self._heuristic_order[var] = kind
  473. added = True
  474. if added:
  475. for color in ('reds', 'greens'):
  476. lst = getattr(self, color)
  477. allkinds = [self._heuristic_order.get(name, '?')
  478. for name in lst]
  479. kinds = [k for k in allkinds if k != '?']
  480. assert kinds == sorted(kinds), (
  481. "bad order of %s variables in the jitdriver: "
  482. "must be INTs, REFs, FLOATs; got %r" %
  483. (color, allkinds))
  484. def jit_merge_point(_self, **livevars):
  485. # special-cased by ExtRegistryEntry
  486. if _self.check_untranslated:
  487. _self._check_arguments(livevars)
  488. def can_enter_jit(_self, **livevars):
  489. if _self.autoreds:
  490. raise TypeError, "Cannot call can_enter_jit on a driver with reds='auto'"
  491. # special-cased by ExtRegistryEntry
  492. if _self.check_untranslated:
  493. _self._check_arguments(livevars)
  494. def loop_header(self):
  495. # special-cased by ExtRegistryEntry
  496. pass
  497. def inline(self, call_jit_merge_point):
  498. assert False, "@inline off: see skipped failures in test_warmspot."
  499. #
  500. assert self.autoreds, "@inline works only with reds='auto'"
  501. self.inline_jit_merge_point = True
  502. def decorate(func):
  503. template = """
  504. def {name}({arglist}):
  505. {call_jit_merge_point}({arglist})
  506. return {original}({arglist})
  507. """
  508. templateargs = {'call_jit_merge_point': call_jit_merge_point.__name__}
  509. globaldict = {call_jit_merge_point.__name__: call_jit_merge_point}
  510. result = rpython_wrapper(func, template, templateargs, **globaldict)
  511. result._inline_jit_merge_point_ = call_jit_merge_point
  512. return result
  513. return decorate
  514. def clone(self):
  515. assert self.inline_jit_merge_point, 'JitDriver.clone works only after @inline'
  516. newdriver = object.__new__(self.__class__)
  517. newdriver.__dict__ = self.__dict__.copy()
  518. return newdriver
  519. def _make_extregistryentries(self):
  520. # workaround: we cannot declare ExtRegistryEntries for functions
  521. # used as methods of a frozen object, but we can attach the
  522. # bound methods back to 'self' and make ExtRegistryEntries
  523. # specifically for them.
  524. self.jit_merge_point = self.jit_merge_point
  525. self.can_enter_jit = self.can_enter_jit
  526. self.loop_header = self.loop_header
  527. class Entry(ExtEnterLeaveMarker):
  528. _about_ = (self.jit_merge_point, self.can_enter_jit)
  529. class Entry(ExtLoopHeader):
  530. _about_ = self.loop_header
  531. def _set_param(driver, name, value):
  532. # special-cased by ExtRegistryEntry
  533. # (internal, must receive a constant 'name')
  534. # if value is None, sets the default value.
  535. assert name in PARAMETERS
  536. @specialize.arg(0, 1)
  537. def set_param(driver, name, value):
  538. """Set one of the tunable JIT parameter. Driver can be None, then all
  539. drivers have this set """
  540. _set_param(driver, name, value)
  541. @specialize.arg(0, 1)
  542. def set_param_to_default(driver, name):
  543. """Reset one of the tunable JIT parameters to its default value."""
  544. _set_param(driver, name, None)
  545. def set_user_param(driver, text):
  546. """Set the tunable JIT parameters from a user-supplied string
  547. following the format 'param=value,param=value', or 'off' to
  548. disable the JIT. For programmatic setting of parameters, use
  549. directly JitDriver.set_param().
  550. """
  551. if text == 'off':
  552. set_param(driver, 'threshold', -1)
  553. set_param(driver, 'function_threshold', -1)
  554. return
  555. if text == 'default':
  556. for name1, _ in unroll_parameters:
  557. set_param_to_default(driver, name1)
  558. return
  559. for s in text.split(','):
  560. s = s.strip(' ')
  561. parts = s.split('=')
  562. if len(parts) != 2:
  563. raise ValueError
  564. name = parts[0]
  565. value = parts[1]
  566. if name == 'enable_opts':
  567. set_param(driver, 'enable_opts', value)
  568. else:
  569. for name1, _ in unroll_parameters:
  570. if name1 == name and name1 != 'enable_opts':
  571. try:
  572. set_param(driver, name1, int(value))
  573. except ValueError:
  574. raise
  575. break
  576. else:
  577. raise ValueError
  578. set_user_param._annspecialcase_ = 'specialize:arg(0)'
  579. # ____________________________________________________________
  580. #
  581. # Annotation and rtyping of some of the JitDriver methods
  582. class BaseJitCell(object):
  583. __slots__ = ()
  584. class ExtEnterLeaveMarker(ExtRegistryEntry):
  585. # Replace a call to myjitdriver.jit_merge_point(**livevars)
  586. # with an operation jit_marker('jit_merge_point', myjitdriver, livevars...)
  587. # Also works with can_enter_jit.
  588. def compute_result_annotation(self, **kwds_s):
  589. from rpython.annotator import model as annmodel
  590. if self.instance.__name__ == 'jit_merge_point':
  591. self.annotate_hooks(**kwds_s)
  592. driver = self.instance.im_self
  593. keys = kwds_s.keys()
  594. keys.sort()
  595. expected = ['s_' + name for name in driver.greens + driver.reds
  596. if '.' not in name]
  597. expected.sort()
  598. if keys != expected:
  599. raise JitHintError("%s expects the following keyword "
  600. "arguments: %s" % (self.instance,
  601. expected))
  602. try:
  603. cache = self.bookkeeper._jit_annotation_cache[driver]
  604. except AttributeError:
  605. cache = {}
  606. self.bookkeeper._jit_annotation_cache = {driver: cache}
  607. except KeyError:
  608. cache = {}
  609. self.bookkeeper._jit_annotation_cache[driver] = cache
  610. for key, s_value in kwds_s.items():
  611. s_previous = cache.get(key, annmodel.s_ImpossibleValue)
  612. s_value = annmodel.unionof(s_previous, s_value) # where="mixing incompatible types in argument %s of jit_merge_point/can_enter_jit" % key[2:]
  613. cache[key] = s_value
  614. # add the attribute _dont_reach_me_in_del_ (see rpython.rtyper.rclass)
  615. try:
  616. graph = self.bookkeeper.position_key[0]
  617. graph.func._dont_reach_me_in_del_ = True
  618. except (TypeError, AttributeError):
  619. pass
  620. return annmodel.s_None
  621. def annotate_hooks(self, **kwds_s):
  622. driver = self.instance.im_self
  623. s_jitcell = self.bookkeeper.valueoftype(BaseJitCell)
  624. h = self.annotate_hook
  625. h(driver.get_jitcell_at, driver.greens, **kwds_s)
  626. h(driver.set_jitcell_at, driver.greens, [s_jitcell], **kwds_s)
  627. h(driver.get_printable_location, driver.greens, **kwds_s)
  628. def annotate_hook(self, func, variables, args_s=[], **kwds_s):
  629. if func is None:
  630. return
  631. bk = self.bookkeeper
  632. s_func = bk.immutablevalue(func)
  633. uniquekey = 'jitdriver.%s' % func.func_name
  634. args_s = args_s[:]
  635. for name in variables:
  636. if '.' not in name:
  637. s_arg = kwds_s['s_' + name]
  638. else:
  639. objname, fieldname = name.split('.')
  640. s_instance = kwds_s['s_' + objname]
  641. attrdef = s_instance.classdef.find_attribute(fieldname)
  642. position = self.bookkeeper.position_key
  643. attrdef.read_locations[position] = True
  644. s_arg = attrdef.getvalue()
  645. assert s_arg is not None
  646. args_s.append(s_arg)
  647. bk.emulate_pbc_call(uniquekey, s_func, args_s)
  648. def get_getfield_op(self, rtyper):
  649. if rtyper.type_system.name == 'ootypesystem':
  650. return 'oogetfield'
  651. else:
  652. return 'getfield'
  653. def specialize_call(self, hop, **kwds_i):
  654. # XXX to be complete, this could also check that the concretetype
  655. # of the variables are the same for each of the calls.
  656. from rpython.rtyper.lltypesystem import lltype
  657. driver = self.instance.im_self
  658. greens_v = []
  659. reds_v = []
  660. for name in driver.greens:
  661. if '.' not in name:
  662. i = kwds_i['i_' + name]
  663. r_green = hop.args_r[i]
  664. v_green = hop.inputarg(r_green, arg=i)
  665. else:
  666. objname, fieldname = name.split('.') # see test_green_field
  667. assert objname in driver.reds
  668. i = kwds_i['i_' + objname]
  669. s_red = hop.args_s[i]
  670. r_red = hop.args_r[i]
  671. while True:
  672. try:
  673. mangled_name, r_field = r_red._get_field(fieldname)
  674. break
  675. except KeyError:
  676. pass
  677. assert r_red.rbase is not None, (
  678. "field %r not found in %r" % (name,
  679. r_red.lowleveltype.TO))
  680. r_red = r_red.rbase
  681. if hop.rtyper.type_system.name == 'ootypesystem':
  682. GTYPE = r_red.lowleveltype
  683. else:
  684. GTYPE = r_red.lowleveltype.TO
  685. assert GTYPE._immutable_field(mangled_name), (
  686. "field %r must be declared as immutable" % name)
  687. if not hasattr(driver, 'll_greenfields'):
  688. driver.ll_greenfields = {}
  689. driver.ll_greenfields[name] = GTYPE, mangled_name
  690. #
  691. v_red = hop.inputarg(r_red, arg=i)
  692. c_llname = hop.inputconst(lltype.Void, mangled_name)
  693. getfield_op = self.get_getfield_op(hop.rtyper)
  694. v_green = hop.genop(getfield_op, [v_red, c_llname],
  695. resulttype=r_field)
  696. s_green = s_red.classdef.about_attribute(fieldname)
  697. assert s_green is not None
  698. hop.rtyper.annotator.setbinding(v_green, s_green)
  699. greens_v.append(v_green)
  700. for name in driver.reds:
  701. i = kwds_i['i_' + name]
  702. r_red = hop.args_r[i]
  703. v_red = hop.inputarg(r_red, arg=i)
  704. reds_v.append(v_red)
  705. hop.exception_cannot_occur()
  706. vlist = [hop.inputconst(lltype.Void, self.instance.__name__),
  707. hop.inputconst(lltype.Void, driver)]
  708. vlist.extend(greens_v)
  709. vlist.extend(reds_v)
  710. return hop.genop('jit_marker', vlist,
  711. resulttype=lltype.Void)
  712. class ExtLoopHeader(ExtRegistryEntry):
  713. # Replace a call to myjitdriver.loop_header()
  714. # with an operation jit_marker('loop_header', myjitdriver).
  715. def compute_result_annotation(self, **kwds_s):
  716. from rpython.annotator import model as annmodel
  717. return annmodel.s_None
  718. def specialize_call(self, hop):
  719. from rpython.rtyper.lltypesystem import lltype
  720. driver = self.instance.im_self
  721. hop.exception_cannot_occur()
  722. vlist = [hop.inputconst(lltype.Void, 'loop_header'),
  723. hop.inputconst(lltype.Void, driver)]
  724. return hop.genop('jit_marker', vlist,
  725. resulttype=lltype.Void)
  726. class ExtSetParam(ExtRegistryEntry):
  727. _about_ = _set_param
  728. def compute_result_annotation(self, s_driver, s_name, s_value):
  729. from rpython.annotator import model as annmodel
  730. assert s_name.is_constant()
  731. if s_name.const == 'enable_opts':
  732. assert annmodel.SomeString(can_be_None=True).contains(s_value)
  733. else:
  734. assert (s_value == annmodel.s_None or
  735. annmodel.SomeInteger().contains(s_value))
  736. return annmodel.s_None
  737. def specialize_call(self, hop):
  738. from rpython.rtyper.lltypesystem import lltype
  739. from rpython.rtyper.lltypesystem.rstr import string_repr
  740. from rpython.flowspace.model import Constant
  741. hop.exception_cannot_occur()
  742. driver = hop.inputarg(lltype.Void, arg=0)
  743. name = hop.args_s[1].const
  744. if name == 'enable_opts':
  745. repr = string_repr
  746. else:
  747. repr = lltype.Signed
  748. if (isinstance(hop.args_v[2], Constant) and
  749. hop.args_v[2].value is None):
  750. value = PARAMETERS[name]
  751. v_value = hop.inputconst(repr, value)
  752. else:
  753. v_value = hop.inputarg(repr, arg=2)
  754. vlist = [hop.inputconst(lltype.Void, "set_param"),
  755. driver,
  756. hop.inputconst(lltype.Void, name),
  757. v_value]
  758. return hop.genop('jit_marker', vlist,
  759. resulttype=lltype.Void)
  760. class AsmInfo(object):
  761. """ An addition to JitDebugInfo concerning assembler. Attributes:
  762. ops_offset - dict of offsets of operations or None
  763. asmaddr - (int) raw address of assembler block
  764. asmlen - assembler block length
  765. """
  766. def __init__(self, ops_offset, asmaddr, asmlen):
  767. self.ops_offset = ops_offset
  768. self.asmaddr = asmaddr
  769. self.asmlen = asmlen
  770. class JitDebugInfo(object):
  771. """ An object representing debug info. Attributes meanings:
  772. greenkey - a list of green boxes or None for bridge
  773. logger - an instance of jit.metainterp.logger.LogOperations
  774. type - either 'loop', 'entry bridge' or 'bridge'
  775. looptoken - description of a loop
  776. fail_descr - fail descr or None
  777. asminfo - extra assembler information
  778. """
  779. asminfo = None
  780. def __init__(self, jitdriver_sd, logger, looptoken, operations, type,
  781. greenkey=None, fail_descr=None):
  782. self.jitdriver_sd = jitdriver_sd
  783. self.logger = logger
  784. self.looptoken = looptoken
  785. self.operations = operations
  786. self.type = type
  787. if type == 'bridge':
  788. assert fail_descr is not None
  789. else:
  790. assert greenkey is not None
  791. self.greenkey = greenkey
  792. self.fail_descr = fail_descr
  793. def get_jitdriver(self):
  794. """ Return where the jitdriver on which the jitting started
  795. """
  796. return self.jitdriver_sd.jitdriver
  797. def get_greenkey_repr(self):
  798. """ Return the string repr of a greenkey
  799. """
  800. return self.jitdriver_sd.warmstate.get_location_str(self.greenkey)
  801. class JitHookInterface(object):
  802. """ This is the main connector between the JIT and the interpreter.
  803. Several methods on this class will be invoked at various stages
  804. of JIT running like JIT loops compiled, aborts etc.
  805. An instance of this class will be available as policy.jithookiface.
  806. """
  807. def on_abort(self, reason, jitdriver, greenkey, greenkey_repr):
  808. """ A hook called each time a loop is aborted with jitdriver and
  809. greenkey where it started, reason is a string why it got aborted
  810. """
  811. #def before_optimize(self, debug_info):
  812. # """ A hook called before optimizer is run, called with instance of
  813. # JitDebugInfo. Overwrite for custom behavior
  814. # """
  815. # DISABLED
  816. def before_compile(self, debug_info):
  817. """ A hook called after a loop is optimized, before compiling assembler,
  818. called with JitDebugInfo instance. Overwrite for custom behavior
  819. """
  820. def after_compile(self, debug_info):
  821. """ A hook called after a loop has compiled assembler,
  822. called with JitDebugInfo instance. Overwrite for custom behavior
  823. """
  824. #def before_optimize_bridge(self, debug_info):
  825. # operations, fail_descr_no):
  826. # """ A hook called before a bridge is optimized.
  827. # Called with JitDebugInfo instance, overwrite for
  828. # custom behavior
  829. # """
  830. # DISABLED
  831. def before_compile_bridge(self, debug_info):
  832. """ A hook called before a bridge is compiled, but after optimizations
  833. are performed. Called with instance of debug_info, overwrite for
  834. custom behavior
  835. """
  836. def after_compile_bridge(self, debug_info):
  837. """ A hook called after a bridge is compiled, called with JitDebugInfo
  838. instance, overwrite for custom behavior
  839. """
  840. def record_known_class(value, cls):
  841. """
  842. Assure the JIT that value is an instance of cls. This is not a precise
  843. class check, unlike a guard_class.
  844. """
  845. assert isinstance(value, cls)
  846. class Entry(ExtRegistryEntry):
  847. _about_ = record_known_class
  848. def compute_result_annotation(self, s_inst, s_cls):
  849. from rpython.annotator import model as annmodel
  850. assert s_cls.is_constant()
  851. assert not s_inst.can_be_none()
  852. assert isinstance(s_inst, annmodel.SomeInstance)
  853. def specialize_call(self, hop):
  854. from rpython.rtyper.lltypesystem import rclass, lltype
  855. classrepr = rclass.get_type_repr(hop.rtyper)
  856. hop.exception_cannot_occur()
  857. v_inst = hop.inputarg(hop.args_r[0], arg=0)
  858. v_cls = hop.inputarg(classrepr, arg=1)
  859. return hop.genop('jit_record_known_class', [v_inst, v_cls],
  860. resulttype=lltype.Void)
  861. class Counters(object):
  862. counters="""
  863. TRACING
  864. BACKEND
  865. OPS
  866. RECORDED_OPS
  867. GUARDS
  868. OPT_OPS
  869. OPT_GUARDS
  870. OPT_FORCINGS
  871. ABORT_TOO_LONG
  872. ABORT_BRIDGE
  873. ABORT_BAD_LOOP
  874. ABORT_ESCAPE
  875. ABORT_FORCE_QUASIIMMUT
  876. NVIRTUALS
  877. NVHOLES
  878. NVREUSED
  879. TOTAL_COMPILED_LOOPS
  880. TOTAL_COMPILED_BRIDGES
  881. TOTAL_FREED_LOOPS
  882. TOTAL_FREED_BRIDGES
  883. """
  884. counter_names = []
  885. @staticmethod
  886. def _setup():
  887. names = Counters.counters.split()
  888. for i, name in enumerate(names):
  889. setattr(Counters, name, i)
  890. Counters.counter_names.append(name)
  891. Counters.ncounters = len(names)
  892. Counters._setup()