PageRenderTime 53ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/rpython/rlib/jit.py

https://bitbucket.org/pjenvey/pypy-mq
Python | 1284 lines | 1279 code | 5 blank | 0 comment | 17 complexity | 42c1b3656ff82c3af613a30e1e746542 MD5 | raw file
Possible License(s): Apache-2.0, AGPL-3.0, BSD-3-Clause
  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. This also has the effect that the inside of the function will never be
  13. traced.
  14. In some situations it is ok to use this decorator if the function *has*
  15. side effects, as long as these side-effects are idempotent. A typical
  16. example for this would be a cache.
  17. To be totally precise:
  18. (1) the result of the call should not change if the arguments are
  19. the same (same numbers or same pointers)
  20. (2) it's fine to remove the call completely if we can guess the result
  21. according to rule 1
  22. (3) the function call can be moved around by optimizer,
  23. but only so it'll be called earlier and not later.
  24. Most importantly it doesn't mean that an elidable function has no observable
  25. side effect, but those side effects are idempotent (ie caching).
  26. If a particular call to this function ends up raising an exception, then it
  27. is handled like a normal function call (this decorator is ignored).
  28. Note also that this optimisation will only take effect if the arguments
  29. to the function are proven constant. By this we mean each argument
  30. is either:
  31. 1) a constant from the RPython source code (e.g. "x = 2")
  32. 2) easily shown to be constant by the tracer
  33. 3) a promoted variable (see @jit.promote)
  34. Examples of condition 2:
  35. * i1 = int_eq(i0, 0), guard_true(i1)
  36. * i1 = getfield_pc_pure(<constant>, "immutable_field")
  37. In both cases, the tracer will deduce that i1 is constant.
  38. Failing the above conditions, the function is not traced into (as if the
  39. function were decorated with @jit.dont_look_inside). Generally speaking,
  40. it is a bad idea to liberally sprinkle @jit.elidable without a concrete
  41. need.
  42. """
  43. if DEBUG_ELIDABLE_FUNCTIONS:
  44. cache = {}
  45. oldfunc = func
  46. def func(*args):
  47. result = oldfunc(*args) # if it raises, no caching
  48. try:
  49. oldresult = cache.setdefault(args, result)
  50. except TypeError:
  51. pass # unhashable args
  52. else:
  53. assert oldresult == result
  54. return result
  55. if getattr(func, '_jit_unroll_safe_', False):
  56. raise TypeError("it does not make sense for %s to be both elidable and unroll_safe" % func)
  57. func._elidable_function_ = True
  58. return func
  59. def purefunction(*args, **kwargs):
  60. import warnings
  61. warnings.warn("purefunction is deprecated, use elidable instead", DeprecationWarning)
  62. return elidable(*args, **kwargs)
  63. def hint(x, **kwds):
  64. """ Hint for the JIT
  65. possible arguments are:
  66. * promote - promote the argument from a variable into a constant
  67. * promote_string - same, but promote string by *value*
  68. * access_directly - directly access a virtualizable, as a structure
  69. and don't treat it as a virtualizable
  70. * fresh_virtualizable - means that virtualizable was just allocated.
  71. Useful in say Frame.__init__ when we do want
  72. to store things directly on it. Has to come with
  73. access_directly=True
  74. * force_virtualizable - a performance hint to force the virtualizable early
  75. (useful e.g. for python generators that are going
  76. to be read later anyway)
  77. """
  78. return x
  79. @specialize.argtype(0)
  80. def promote(x):
  81. """
  82. Promotes a variable in a trace to a constant.
  83. When a variable is promoted, a guard is inserted that assumes the value
  84. of the variable is constant. In other words, the value of the variable
  85. is checked to be the same as it was at trace collection time. Once the
  86. variable is assumed constant, more aggressive constant folding may be
  87. possible.
  88. If however, the guard fails frequently, a bridge will be generated
  89. this time assuming the constancy of the variable under its new value.
  90. This optimisation should be used carefully, as in extreme cases, where
  91. the promoted variable is not very constant at all, code explosion can
  92. occur. In turn this leads to poor performance.
  93. Overpromotion is characterised by a cascade of bridges branching from
  94. very similar guard_value opcodes, each guarding the same variable under
  95. a different value.
  96. Note that promoting a string with @jit.promote will promote by pointer.
  97. To promote a string by value, see @jit.promote_string.
  98. """
  99. return hint(x, promote=True)
  100. def promote_string(x):
  101. return hint(x, promote_string=True)
  102. def dont_look_inside(func):
  103. """ Make sure the JIT does not trace inside decorated function
  104. (it becomes a call instead)
  105. """
  106. if getattr(func, '_jit_unroll_safe_', False):
  107. raise TypeError("it does not make sense for %s to be both dont_look_inside and unroll_safe" % func)
  108. func._jit_look_inside_ = False
  109. return func
  110. def look_inside(func):
  111. """ Make sure the JIT traces inside decorated function, even
  112. if the rest of the module is not visible to the JIT
  113. """
  114. import warnings
  115. warnings.warn("look_inside is deprecated", DeprecationWarning)
  116. func._jit_look_inside_ = True
  117. return func
  118. def unroll_safe(func):
  119. """ JIT can safely unroll loops in this function and this will
  120. not lead to code explosion
  121. """
  122. if getattr(func, '_elidable_function_', False):
  123. raise TypeError("it does not make sense for %s to be both elidable and unroll_safe" % func)
  124. if not getattr(func, '_jit_look_inside_', True):
  125. raise TypeError("it does not make sense for %s to be both elidable and dont_look_inside" % func)
  126. func._jit_unroll_safe_ = True
  127. return func
  128. def loop_invariant(func):
  129. """ Describes a function with no argument that returns an object that
  130. is always the same in a loop.
  131. Use it only if you know what you're doing.
  132. """
  133. dont_look_inside(func)
  134. func._jit_loop_invariant_ = True
  135. return func
  136. def _get_args(func):
  137. import inspect
  138. args, varargs, varkw, defaults = inspect.getargspec(func)
  139. assert varargs is None and varkw is None
  140. assert not defaults
  141. return args
  142. def elidable_promote(promote_args='all'):
  143. """ A decorator that promotes all arguments and then calls the supplied
  144. function
  145. """
  146. def decorator(func):
  147. elidable(func)
  148. args = _get_args(func)
  149. argstring = ", ".join(args)
  150. code = ["def f(%s):\n" % (argstring, )]
  151. if promote_args != 'all':
  152. args = [args[int(i)] for i in promote_args.split(",")]
  153. for arg in args:
  154. code.append( #use both hints, and let jtransform pick the right one
  155. " %s = hint(%s, promote=True, promote_string=True)\n" %
  156. (arg, arg))
  157. code.append(" return _orig_func_unlikely_name(%s)\n" % (argstring, ))
  158. d = {"_orig_func_unlikely_name": func, "hint": hint}
  159. exec py.code.Source("\n".join(code)).compile() in d
  160. result = d["f"]
  161. result.func_name = func.func_name + "_promote"
  162. return result
  163. return decorator
  164. def purefunction_promote(*args, **kwargs):
  165. import warnings
  166. warnings.warn("purefunction_promote is deprecated, use elidable_promote instead", DeprecationWarning)
  167. return elidable_promote(*args, **kwargs)
  168. def look_inside_iff(predicate):
  169. """
  170. look inside (including unrolling loops) the target function, if and only if
  171. predicate(*args) returns True
  172. """
  173. def inner(func):
  174. func = unroll_safe(func)
  175. # When we return the new function, it might be specialized in some
  176. # way. We "propogate" this specialization by using
  177. # specialize:call_location on relevant functions.
  178. for thing in [func, predicate]:
  179. thing._annspecialcase_ = "specialize:call_location"
  180. args = _get_args(func)
  181. predicateargs = _get_args(predicate)
  182. assert len(args) == len(predicateargs), "%s and predicate %s need the same numbers of arguments" % (func, predicate)
  183. d = {
  184. "dont_look_inside": dont_look_inside,
  185. "predicate": predicate,
  186. "func": func,
  187. "we_are_jitted": we_are_jitted,
  188. }
  189. exec py.code.Source("""
  190. @dont_look_inside
  191. def trampoline(%(arguments)s):
  192. return func(%(arguments)s)
  193. if hasattr(func, "oopspec"):
  194. trampoline.oopspec = func.oopspec
  195. del func.oopspec
  196. trampoline.__name__ = func.__name__ + "_trampoline"
  197. trampoline._annspecialcase_ = "specialize:call_location"
  198. def f(%(arguments)s):
  199. if not we_are_jitted() or predicate(%(arguments)s):
  200. return func(%(arguments)s)
  201. else:
  202. return trampoline(%(arguments)s)
  203. f.__name__ = func.__name__ + "_look_inside_iff"
  204. """ % {"arguments": ", ".join(args)}).compile() in d
  205. return d["f"]
  206. return inner
  207. def oopspec(spec):
  208. def decorator(func):
  209. func.oopspec = spec
  210. return func
  211. return decorator
  212. def not_in_trace(func):
  213. """A decorator for a function with no return value. It makes the
  214. function call disappear from the jit traces. It is still called in
  215. interpreted mode, and by the jit tracing and blackholing, but not
  216. by the final assembler."""
  217. func.oopspec = "jit.not_in_trace()" # note that 'func' may take arguments
  218. return func
  219. def call_shortcut(func):
  220. """A decorator to ensure that a function has a fast-path.
  221. Only useful on functions that the JIT doesn't normally look inside.
  222. It still replaces residual calls to that function with inline code
  223. that checks for a fast path, and only does the call if not. For
  224. now, graphs made by the following kinds of functions are detected:
  225. def func(x, y, z): def func(x, y, z):
  226. if y.field: r = y.field
  227. return y.field if r is None:
  228. ... ...
  229. return r
  230. Fast-path detection is always on, but this decorator makes the
  231. codewriter complain if it cannot find the promized fast-path.
  232. """
  233. func._call_shortcut_ = True
  234. return func
  235. @oopspec("jit.isconstant(value)")
  236. def isconstant(value):
  237. """
  238. While tracing, returns whether or not the value is currently known to be
  239. constant. This is not perfect, values can become constant later. Mostly for
  240. use with @look_inside_iff.
  241. This is for advanced usage only.
  242. """
  243. return NonConstant(False)
  244. isconstant._annspecialcase_ = "specialize:call_location"
  245. @oopspec("jit.isvirtual(value)")
  246. def isvirtual(value):
  247. """
  248. Returns if this value is virtual, while tracing, it's relatively
  249. conservative and will miss some cases.
  250. This is for advanced usage only.
  251. """
  252. return NonConstant(False)
  253. isvirtual._annspecialcase_ = "specialize:call_location"
  254. @specialize.call_location()
  255. def loop_unrolling_heuristic(lst, size, cutoff=2):
  256. """ In which cases iterating over items of lst can be unrolled
  257. """
  258. return size == 0 or isvirtual(lst) or (isconstant(size) and size <= cutoff)
  259. class Entry(ExtRegistryEntry):
  260. _about_ = hint
  261. def compute_result_annotation(self, s_x, **kwds_s):
  262. from rpython.annotator import model as annmodel
  263. s_x = annmodel.not_const(s_x)
  264. access_directly = 's_access_directly' in kwds_s
  265. fresh_virtualizable = 's_fresh_virtualizable' in kwds_s
  266. if access_directly or fresh_virtualizable:
  267. assert access_directly, "lone fresh_virtualizable hint"
  268. if isinstance(s_x, annmodel.SomeInstance):
  269. from rpython.flowspace.model import Constant
  270. classdesc = s_x.classdef.classdesc
  271. virtualizable = classdesc.get_param('_virtualizable_')
  272. if virtualizable is not None:
  273. flags = s_x.flags.copy()
  274. flags['access_directly'] = True
  275. if fresh_virtualizable:
  276. flags['fresh_virtualizable'] = True
  277. s_x = annmodel.SomeInstance(s_x.classdef,
  278. s_x.can_be_None,
  279. flags)
  280. return s_x
  281. def specialize_call(self, hop, **kwds_i):
  282. from rpython.rtyper.lltypesystem import lltype
  283. hints = {}
  284. for key, index in kwds_i.items():
  285. s_value = hop.args_s[index]
  286. if not s_value.is_constant():
  287. from rpython.rtyper.error import TyperError
  288. raise TyperError("hint %r is not constant" % (key,))
  289. assert key.startswith('i_')
  290. hints[key[2:]] = s_value.const
  291. v = hop.inputarg(hop.args_r[0], arg=0)
  292. c_hint = hop.inputconst(lltype.Void, hints)
  293. hop.exception_cannot_occur()
  294. return hop.genop('hint', [v, c_hint], resulttype=v.concretetype)
  295. def we_are_jitted():
  296. """ Considered as true during tracing and blackholing,
  297. so its consquences are reflected into jitted code """
  298. return False
  299. _we_are_jitted = CDefinedIntSymbolic('0 /* we are not jitted here */',
  300. default=0)
  301. def _get_virtualizable_token(frame):
  302. """ An obscure API to get vable token.
  303. Used by _vmprof
  304. """
  305. from rpython.rtyper.lltypesystem import lltype, llmemory
  306. return lltype.nullptr(llmemory.GCREF.TO)
  307. class GetVirtualizableTokenEntry(ExtRegistryEntry):
  308. _about_ = _get_virtualizable_token
  309. def compute_result_annotation(self, s_arg):
  310. from rpython.rtyper.llannotation import SomePtr
  311. from rpython.rtyper.lltypesystem import llmemory
  312. return SomePtr(llmemory.GCREF)
  313. def specialize_call(self, hop):
  314. from rpython.rtyper.lltypesystem import lltype, llmemory
  315. hop.exception_cannot_occur()
  316. T = hop.args_r[0].lowleveltype.TO
  317. v = hop.inputarg(hop.args_r[0], arg=0)
  318. while not hasattr(T, 'vable_token'):
  319. if not hasattr(T, 'super'):
  320. # we're not really in a jitted build
  321. return hop.inputconst(llmemory.GCREF,
  322. lltype.nullptr(llmemory.GCREF.TO))
  323. T = T.super
  324. v = hop.genop('cast_pointer', [v], resulttype=lltype.Ptr(T))
  325. c_vable_token = hop.inputconst(lltype.Void, 'vable_token')
  326. return hop.genop('getfield', [v, c_vable_token],
  327. resulttype=llmemory.GCREF)
  328. class Entry(ExtRegistryEntry):
  329. _about_ = we_are_jitted
  330. def compute_result_annotation(self):
  331. from rpython.annotator import model as annmodel
  332. return annmodel.SomeInteger(nonneg=True)
  333. def specialize_call(self, hop):
  334. from rpython.rtyper.lltypesystem import lltype
  335. hop.exception_cannot_occur()
  336. return hop.inputconst(lltype.Signed, _we_are_jitted)
  337. def current_trace_length():
  338. """During JIT tracing, returns the current trace length (as a constant).
  339. If not tracing, returns -1."""
  340. if NonConstant(False):
  341. return 73
  342. return -1
  343. current_trace_length.oopspec = 'jit.current_trace_length()'
  344. def jit_debug(string, arg1=-sys.maxint-1, arg2=-sys.maxint-1,
  345. arg3=-sys.maxint-1, arg4=-sys.maxint-1):
  346. """When JITted, cause an extra operation JIT_DEBUG to appear in
  347. the graphs. Should not be left after debugging."""
  348. keepalive_until_here(string) # otherwise the whole function call is removed
  349. jit_debug.oopspec = 'jit.debug(string, arg1, arg2, arg3, arg4)'
  350. def assert_green(value):
  351. """Very strong assert: checks that 'value' is a green
  352. (a JIT compile-time constant)."""
  353. keepalive_until_here(value)
  354. assert_green._annspecialcase_ = 'specialize:argtype(0)'
  355. assert_green.oopspec = 'jit.assert_green(value)'
  356. class AssertGreenFailed(Exception):
  357. pass
  358. def jit_callback(name):
  359. """Use as a decorator for C callback functions, to insert a
  360. jitdriver.jit_merge_point() at the start. Only for callbacks
  361. that typically invoke more app-level Python code.
  362. """
  363. def decorate(func):
  364. from rpython.tool.sourcetools import compile2
  365. #
  366. def get_printable_location():
  367. return name
  368. jitdriver = JitDriver(get_printable_location=get_printable_location,
  369. greens=[], reds='auto', name=name)
  370. #
  371. args = ','.join(['a%d' % i for i in range(func.func_code.co_argcount)])
  372. source = """def callback_with_jitdriver(%(args)s):
  373. jitdriver.jit_merge_point()
  374. return real_callback(%(args)s)""" % locals()
  375. miniglobals = {
  376. 'jitdriver': jitdriver,
  377. 'real_callback': func,
  378. }
  379. exec compile2(source) in miniglobals
  380. return miniglobals['callback_with_jitdriver']
  381. return decorate
  382. # ____________________________________________________________
  383. # VRefs
  384. @specialize.argtype(0)
  385. def virtual_ref(x):
  386. """Creates a 'vref' object that contains a reference to 'x'. Calls
  387. to virtual_ref/virtual_ref_finish must be properly nested. The idea
  388. is that the object 'x' is supposed to be JITted as a virtual between
  389. the calls to virtual_ref and virtual_ref_finish, but the 'vref'
  390. object can escape at any point in time. If at runtime it is
  391. dereferenced (by the call syntax 'vref()'), it returns 'x', which is
  392. then forced."""
  393. return DirectJitVRef(x)
  394. virtual_ref.oopspec = 'virtual_ref(x)'
  395. @specialize.argtype(1)
  396. def virtual_ref_finish(vref, x):
  397. """See docstring in virtual_ref(x)"""
  398. keepalive_until_here(x) # otherwise the whole function call is removed
  399. _virtual_ref_finish(vref, x)
  400. virtual_ref_finish.oopspec = 'virtual_ref_finish(x)'
  401. def non_virtual_ref(x):
  402. """Creates a 'vref' that just returns x when called; nothing more special.
  403. Used for None or for frames outside JIT scope."""
  404. return DirectVRef(x)
  405. class InvalidVirtualRef(Exception):
  406. """
  407. Raised if we try to call a non-forced virtualref after the call to
  408. virtual_ref_finish
  409. """
  410. # ---------- implementation-specific ----------
  411. class DirectVRef(object):
  412. def __init__(self, x):
  413. self._x = x
  414. self._state = 'non-forced'
  415. def __call__(self):
  416. if self._state == 'non-forced':
  417. self._state = 'forced'
  418. elif self._state == 'invalid':
  419. raise InvalidVirtualRef
  420. return self._x
  421. @property
  422. def virtual(self):
  423. """A property that is True if the vref contains a virtual that would
  424. be forced by the '()' operator."""
  425. return self._state == 'non-forced'
  426. def _finish(self):
  427. if self._state == 'non-forced':
  428. self._state = 'invalid'
  429. class DirectJitVRef(DirectVRef):
  430. def __init__(self, x):
  431. assert x is not None, "virtual_ref(None) is not allowed"
  432. DirectVRef.__init__(self, x)
  433. def _virtual_ref_finish(vref, x):
  434. assert vref._x is x, "Invalid call to virtual_ref_finish"
  435. vref._finish()
  436. class Entry(ExtRegistryEntry):
  437. _about_ = (non_virtual_ref, DirectJitVRef)
  438. def compute_result_annotation(self, s_obj):
  439. from rpython.rlib import _jit_vref
  440. return _jit_vref.SomeVRef(s_obj)
  441. def specialize_call(self, hop):
  442. return hop.r_result.specialize_call(hop)
  443. class Entry(ExtRegistryEntry):
  444. _type_ = DirectVRef
  445. def compute_annotation(self):
  446. from rpython.rlib import _jit_vref
  447. assert isinstance(self.instance, DirectVRef)
  448. s_obj = self.bookkeeper.immutablevalue(self.instance())
  449. return _jit_vref.SomeVRef(s_obj)
  450. class Entry(ExtRegistryEntry):
  451. _about_ = _virtual_ref_finish
  452. def compute_result_annotation(self, s_vref, s_obj):
  453. pass
  454. def specialize_call(self, hop):
  455. hop.exception_cannot_occur()
  456. vref_None = non_virtual_ref(None)
  457. # ____________________________________________________________
  458. # User interface for the warmspot JIT policy
  459. class JitHintError(Exception):
  460. """Inconsistency in the JIT hints."""
  461. ENABLE_ALL_OPTS = (
  462. 'intbounds:rewrite:virtualize:string:pure:earlyforce:heap:unroll')
  463. PARAMETER_DOCS = {
  464. 'threshold': 'number of times a loop has to run for it to become hot',
  465. 'function_threshold': 'number of times a function must run for it to become traced from start',
  466. 'trace_eagerness': 'number of times a guard has to fail before we start compiling a bridge',
  467. 'decay': 'amount to regularly decay counters by (0=none, 1000=max)',
  468. 'trace_limit': 'number of recorded operations before we abort tracing with ABORT_TOO_LONG',
  469. 'inlining': 'inline python functions or not (1/0)',
  470. 'loop_longevity': 'a parameter controlling how long loops will be kept before being freed, an estimate',
  471. 'retrace_limit': 'how many times we can try retracing before giving up',
  472. 'max_retrace_guards': 'number of extra guards a retrace can cause',
  473. 'max_unroll_loops': 'number of extra unrollings a loop can cause',
  474. 'disable_unrolling': 'after how many operations we should not unroll',
  475. 'enable_opts': 'INTERNAL USE ONLY (MAY NOT WORK OR LEAD TO CRASHES): '
  476. 'optimizations to enable, or all = %s' % ENABLE_ALL_OPTS,
  477. 'max_unroll_recursion': 'how many levels deep to unroll a recursive function',
  478. 'vec': 'turn on the vectorization optimization (vecopt). requires sse4.1',
  479. 'vec_all': 'try to vectorize trace loops that occur outside of the numpy library.',
  480. 'vec_cost': 'threshold for which traces to bail. 0 means the costs.',
  481. 'vec_length': 'the amount of instructions allowed in "all" traces.',
  482. 'vec_ratio': 'an integer (0-10 transfored into a float by X / 10.0) statements that have vector equivalents '
  483. 'divided by the total number of trace instructions.',
  484. 'vec_guard_ratio': 'an integer (0-10 transfored into a float by X / 10.0) divided by the'
  485. ' total number of trace instructions.',
  486. }
  487. PARAMETERS = {'threshold': 1039, # just above 1024, prime
  488. 'function_threshold': 1619, # slightly more than one above, also prime
  489. 'trace_eagerness': 200,
  490. 'decay': 40,
  491. 'trace_limit': 6000,
  492. 'inlining': 1,
  493. 'loop_longevity': 1000,
  494. 'retrace_limit': 0,
  495. 'max_retrace_guards': 15,
  496. 'max_unroll_loops': 0,
  497. 'disable_unrolling': 200,
  498. 'enable_opts': 'all',
  499. 'max_unroll_recursion': 7,
  500. 'vec': 0,
  501. 'vec_all': 0,
  502. 'vec_cost': 0,
  503. 'vec_length': 60,
  504. 'vec_ratio': 2,
  505. 'vec_guard_ratio': 5,
  506. }
  507. unroll_parameters = unrolling_iterable(PARAMETERS.items())
  508. # ____________________________________________________________
  509. class JitDriver(object):
  510. """Base class to declare fine-grained user control on the JIT. So
  511. far, there must be a singleton instance of JitDriver. This style
  512. will allow us (later) to support a single RPython program with
  513. several independent JITting interpreters in it.
  514. """
  515. active = True # if set to False, this JitDriver is ignored
  516. virtualizables = []
  517. name = 'jitdriver'
  518. inline_jit_merge_point = False
  519. _store_last_enter_jit = None
  520. def __init__(self, greens=None, reds=None, virtualizables=None,
  521. get_jitcell_at=None, set_jitcell_at=None,
  522. get_printable_location=None, confirm_enter_jit=None,
  523. can_never_inline=None, should_unroll_one_iteration=None,
  524. name='jitdriver', check_untranslated=True, vectorize=False,
  525. get_unique_id=None, is_recursive=False, get_location=None):
  526. """ NOT_RPYTHON
  527. get_location:
  528. The return value is designed to provide enough information to express the
  529. state of an interpreter when invoking jit_merge_point.
  530. For a bytecode interperter such as PyPy this includes, filename, line number,
  531. function name, and more information. However, it should also be able to express
  532. the same state for an interpreter that evaluates an AST.
  533. return paremter:
  534. 0 -> filename. An absolute path specifying the file the interpreter invoked.
  535. If the input source is no file it should start with the
  536. prefix: "string://<name>"
  537. 1 -> line number. The line number in filename. This should at least point to
  538. the enclosing name. It can however point to the specific
  539. source line of the instruction executed by the interpreter.
  540. 2 -> enclosing name. E.g. the function name.
  541. 3 -> index. 64 bit number indicating the execution progress. It can either be
  542. an offset to byte code, or an index to the node in an AST
  543. 4 -> operation name. a name further describing the current program counter.
  544. this can be either a byte code name or the name of an AST node
  545. """
  546. if greens is not None:
  547. self.greens = greens
  548. self.name = name
  549. if reds == 'auto':
  550. self.autoreds = True
  551. self.reds = []
  552. self.numreds = None # see warmspot.autodetect_jit_markers_redvars
  553. assert confirm_enter_jit is None, (
  554. "reds='auto' is not compatible with confirm_enter_jit")
  555. else:
  556. if reds is not None:
  557. self.reds = reds
  558. self.autoreds = False
  559. self.numreds = len(self.reds)
  560. if not hasattr(self, 'greens') or not hasattr(self, 'reds'):
  561. raise AttributeError("no 'greens' or 'reds' supplied")
  562. if virtualizables is not None:
  563. self.virtualizables = virtualizables
  564. if get_unique_id is not None:
  565. assert is_recursive, "get_unique_id and is_recursive must be specified at the same time"
  566. for v in self.virtualizables:
  567. assert v in self.reds
  568. # if reds are automatic, they won't be passed to jit_merge_point, so
  569. # _check_arguments will receive only the green ones (i.e., the ones
  570. # which are listed explicitly). So, it is fine to just ignore reds
  571. self._somelivevars = set([name for name in
  572. self.greens + (self.reds or [])
  573. if '.' not in name])
  574. self._heuristic_order = {} # check if 'reds' and 'greens' are ordered
  575. self._make_extregistryentries()
  576. assert get_jitcell_at is None, "get_jitcell_at no longer used"
  577. assert set_jitcell_at is None, "set_jitcell_at no longer used"
  578. self.get_printable_location = get_printable_location
  579. self.get_location = get_location
  580. if get_unique_id is None:
  581. get_unique_id = lambda *args: 0
  582. self.get_unique_id = get_unique_id
  583. self.confirm_enter_jit = confirm_enter_jit
  584. self.can_never_inline = can_never_inline
  585. self.should_unroll_one_iteration = should_unroll_one_iteration
  586. self.check_untranslated = check_untranslated
  587. self.is_recursive = is_recursive
  588. self.vec = vectorize
  589. def _freeze_(self):
  590. return True
  591. def _check_arguments(self, livevars, is_merge_point):
  592. assert set(livevars) == self._somelivevars
  593. # check heuristically that 'reds' and 'greens' are ordered as
  594. # the JIT will need them to be: first INTs, then REFs, then
  595. # FLOATs.
  596. if len(self._heuristic_order) < len(livevars):
  597. from rpython.rlib.rarithmetic import (r_singlefloat, r_longlong,
  598. r_ulonglong, r_uint)
  599. added = False
  600. for var, value in livevars.items():
  601. if var not in self._heuristic_order:
  602. if (r_ulonglong is not r_uint and
  603. isinstance(value, (r_longlong, r_ulonglong))):
  604. assert 0, ("should not pass a r_longlong argument for "
  605. "now, because on 32-bit machines it needs "
  606. "to be ordered as a FLOAT but on 64-bit "
  607. "machines as an INT")
  608. elif isinstance(value, (int, long, r_singlefloat)):
  609. kind = '1:INT'
  610. elif isinstance(value, float):
  611. kind = '3:FLOAT'
  612. elif isinstance(value, (str, unicode)) and len(value) != 1:
  613. kind = '2:REF'
  614. elif isinstance(value, (list, dict)):
  615. kind = '2:REF'
  616. elif (hasattr(value, '__class__')
  617. and value.__class__.__module__ != '__builtin__'):
  618. if hasattr(value, '_freeze_'):
  619. continue # value._freeze_() is better not called
  620. elif getattr(value, '_alloc_flavor_', 'gc') == 'gc':
  621. kind = '2:REF'
  622. else:
  623. kind = '1:INT'
  624. else:
  625. continue
  626. self._heuristic_order[var] = kind
  627. added = True
  628. if added:
  629. for color in ('reds', 'greens'):
  630. lst = getattr(self, color)
  631. allkinds = [self._heuristic_order.get(name, '?')
  632. for name in lst]
  633. kinds = [k for k in allkinds if k != '?']
  634. assert kinds == sorted(kinds), (
  635. "bad order of %s variables in the jitdriver: "
  636. "must be INTs, REFs, FLOATs; got %r" %
  637. (color, allkinds))
  638. if is_merge_point:
  639. if self._store_last_enter_jit:
  640. if livevars != self._store_last_enter_jit:
  641. raise JitHintError(
  642. "Bad can_enter_jit() placement: there should *not* "
  643. "be any code in between can_enter_jit() -> jit_merge_point()" )
  644. self._store_last_enter_jit = None
  645. else:
  646. self._store_last_enter_jit = livevars
  647. def jit_merge_point(_self, **livevars):
  648. # special-cased by ExtRegistryEntry
  649. if _self.check_untranslated:
  650. _self._check_arguments(livevars, True)
  651. def can_enter_jit(_self, **livevars):
  652. if _self.autoreds:
  653. raise TypeError("Cannot call can_enter_jit on a driver with reds='auto'")
  654. # special-cased by ExtRegistryEntry
  655. if _self.check_untranslated:
  656. _self._check_arguments(livevars, False)
  657. def loop_header(self):
  658. # special-cased by ExtRegistryEntry
  659. pass
  660. def inline(self, call_jit_merge_point):
  661. assert False, "@inline off: see skipped failures in test_warmspot."
  662. #
  663. assert self.autoreds, "@inline works only with reds='auto'"
  664. self.inline_jit_merge_point = True
  665. def decorate(func):
  666. template = """
  667. def {name}({arglist}):
  668. {call_jit_merge_point}({arglist})
  669. return {original}({arglist})
  670. """
  671. templateargs = {'call_jit_merge_point': call_jit_merge_point.__name__}
  672. globaldict = {call_jit_merge_point.__name__: call_jit_merge_point}
  673. result = rpython_wrapper(func, template, templateargs, **globaldict)
  674. result._inline_jit_merge_point_ = call_jit_merge_point
  675. return result
  676. return decorate
  677. def clone(self):
  678. assert self.inline_jit_merge_point, 'JitDriver.clone works only after @inline'
  679. newdriver = object.__new__(self.__class__)
  680. newdriver.__dict__ = self.__dict__.copy()
  681. return newdriver
  682. def _make_extregistryentries(self):
  683. # workaround: we cannot declare ExtRegistryEntries for functions
  684. # used as methods of a frozen object, but we can attach the
  685. # bound methods back to 'self' and make ExtRegistryEntries
  686. # specifically for them.
  687. self.jit_merge_point = self.jit_merge_point
  688. self.can_enter_jit = self.can_enter_jit
  689. self.loop_header = self.loop_header
  690. class Entry(ExtEnterLeaveMarker):
  691. _about_ = (self.jit_merge_point, self.can_enter_jit)
  692. class Entry(ExtLoopHeader):
  693. _about_ = self.loop_header
  694. def _set_param(driver, name, value):
  695. # special-cased by ExtRegistryEntry
  696. # (internal, must receive a constant 'name')
  697. # if value is None, sets the default value.
  698. assert name in PARAMETERS
  699. @specialize.arg(0, 1)
  700. def set_param(driver, name, value):
  701. """Set one of the tunable JIT parameter. Driver can be None, then all
  702. drivers have this set """
  703. _set_param(driver, name, value)
  704. @specialize.arg(0, 1)
  705. def set_param_to_default(driver, name):
  706. """Reset one of the tunable JIT parameters to its default value."""
  707. _set_param(driver, name, None)
  708. class TraceLimitTooHigh(Exception):
  709. """ This is raised when the trace limit is too high for the chosen
  710. opencoder model, recompile your interpreter with 'big' as
  711. jit_opencoder_model
  712. """
  713. def set_user_param(driver, text):
  714. """Set the tunable JIT parameters from a user-supplied string
  715. following the format 'param=value,param=value', or 'off' to
  716. disable the JIT. For programmatic setting of parameters, use
  717. directly JitDriver.set_param().
  718. """
  719. if text == 'off':
  720. set_param(driver, 'threshold', -1)
  721. set_param(driver, 'function_threshold', -1)
  722. return
  723. if text == 'default':
  724. for name1, _ in unroll_parameters:
  725. set_param_to_default(driver, name1)
  726. return
  727. for s in text.split(','):
  728. s = s.strip(' ')
  729. parts = s.split('=')
  730. if len(parts) != 2:
  731. raise ValueError
  732. name = parts[0]
  733. value = parts[1]
  734. if name == 'enable_opts':
  735. set_param(driver, 'enable_opts', value)
  736. else:
  737. for name1, _ in unroll_parameters:
  738. if name1 == name and name1 != 'enable_opts':
  739. try:
  740. if name1 == 'trace_limit' and int(value) > 2**14:
  741. raise TraceLimitTooHigh
  742. set_param(driver, name1, int(value))
  743. except ValueError:
  744. raise
  745. break
  746. else:
  747. raise ValueError
  748. set_user_param._annspecialcase_ = 'specialize:arg(0)'
  749. # ____________________________________________________________
  750. #
  751. # Annotation and rtyping of some of the JitDriver methods
  752. class ExtEnterLeaveMarker(ExtRegistryEntry):
  753. # Replace a call to myjitdriver.jit_merge_point(**livevars)
  754. # with an operation jit_marker('jit_merge_point', myjitdriver, livevars...)
  755. # Also works with can_enter_jit.
  756. def compute_result_annotation(self, **kwds_s):
  757. from rpython.annotator import model as annmodel
  758. if self.instance.__name__ == 'jit_merge_point':
  759. self.annotate_hooks(**kwds_s)
  760. driver = self.instance.im_self
  761. keys = kwds_s.keys()
  762. keys.sort()
  763. expected = ['s_' + name for name in driver.greens + driver.reds
  764. if '.' not in name]
  765. expected.sort()
  766. if keys != expected:
  767. raise JitHintError("%s expects the following keyword "
  768. "arguments: %s" % (self.instance,
  769. expected))
  770. try:
  771. cache = self.bookkeeper._jit_annotation_cache[driver]
  772. except AttributeError:
  773. cache = {}
  774. self.bookkeeper._jit_annotation_cache = {driver: cache}
  775. except KeyError:
  776. cache = {}
  777. self.bookkeeper._jit_annotation_cache[driver] = cache
  778. for key, s_value in kwds_s.items():
  779. s_previous = cache.get(key, annmodel.s_ImpossibleValue)
  780. s_value = annmodel.unionof(s_previous, s_value) # where="mixing incompatible types in argument %s of jit_merge_point/can_enter_jit" % key[2:]
  781. cache[key] = s_value
  782. # add the attribute _dont_reach_me_in_del_ (see rpython.rtyper.rclass)
  783. try:
  784. graph = self.bookkeeper.position_key[0]
  785. graph.func._dont_reach_me_in_del_ = True
  786. except (TypeError, AttributeError):
  787. pass
  788. return annmodel.s_None
  789. def annotate_hooks(self, **kwds_s):
  790. driver = self.instance.im_self
  791. h = self.annotate_hook
  792. h(driver.get_printable_location, driver.greens, **kwds_s)
  793. h(driver.get_location, driver.greens, **kwds_s)
  794. def annotate_hook(self, func, variables, args_s=[], **kwds_s):
  795. if func is None:
  796. return
  797. bk = self.bookkeeper
  798. s_func = bk.immutablevalue(func)
  799. uniquekey = 'jitdriver.%s' % func.func_name
  800. args_s = args_s[:]
  801. for name in variables:
  802. if '.' not in name:
  803. s_arg = kwds_s['s_' + name]
  804. else:
  805. objname, fieldname = name.split('.')
  806. s_instance = kwds_s['s_' + objname]
  807. classdesc = s_instance.classdef.classdesc
  808. bk.record_getattr(classdesc, fieldname)
  809. attrdef = s_instance.classdef.find_attribute(fieldname)
  810. s_arg = attrdef.s_value
  811. assert s_arg is not None
  812. args_s.append(s_arg)
  813. bk.emulate_pbc_call(uniquekey, s_func, args_s)
  814. def specialize_call(self, hop, **kwds_i):
  815. # XXX to be complete, this could also check that the concretetype
  816. # of the variables are the same for each of the calls.
  817. from rpython.rtyper.lltypesystem import lltype
  818. driver = self.instance.im_self
  819. greens_v = []
  820. reds_v = []
  821. for name in driver.greens:
  822. if '.' not in name:
  823. i = kwds_i['i_' + name]
  824. r_green = hop.args_r[i]
  825. v_green = hop.inputarg(r_green, arg=i)
  826. else:
  827. objname, fieldname = name.split('.') # see test_green_field
  828. assert objname in driver.reds
  829. i = kwds_i['i_' + objname]
  830. s_red = hop.args_s[i]
  831. r_red = hop.args_r[i]
  832. while True:
  833. try:
  834. mangled_name, r_field = r_red._get_field(fieldname)
  835. break
  836. except KeyError:
  837. pass
  838. assert r_red.rbase is not None, (
  839. "field %r not found in %r" % (name,
  840. r_red.lowleveltype.TO))
  841. r_red = r_red.rbase
  842. GTYPE = r_red.lowleveltype.TO
  843. assert GTYPE._immutable_field(mangled_name), (
  844. "field %r must be declared as immutable" % name)
  845. if not hasattr(driver, 'll_greenfields'):
  846. driver.ll_greenfields = {}
  847. driver.ll_greenfields[name] = GTYPE, mangled_name
  848. #
  849. v_red = hop.inputarg(r_red, arg=i)
  850. c_llname = hop.inputconst(lltype.Void, mangled_name)
  851. v_green = hop.genop('getfield', [v_red, c_llname],
  852. resulttype=r_field)
  853. s_green = s_red.classdef.about_attribute(fieldname)
  854. assert s_green is not None
  855. hop.rtyper.annotator.setbinding(v_green, s_green)
  856. greens_v.append(v_green)
  857. for name in driver.reds:
  858. i = kwds_i['i_' + name]
  859. r_red = hop.args_r[i]
  860. v_red = hop.inputarg(r_red, arg=i)
  861. reds_v.append(v_red)
  862. hop.exception_cannot_occur()
  863. vlist = [hop.inputconst(lltype.Void, self.instance.__name__),
  864. hop.inputconst(lltype.Void, driver)]
  865. vlist.extend(greens_v)
  866. vlist.extend(reds_v)
  867. return hop.genop('jit_marker', vlist,
  868. resulttype=lltype.Void)
  869. class ExtLoopHeader(ExtRegistryEntry):
  870. # Replace a call to myjitdriver.loop_header()
  871. # with an operation jit_marker('loop_header', myjitdriver).
  872. def compute_result_annotation(self, **kwds_s):
  873. from rpython.annotator import model as annmodel
  874. return annmodel.s_None
  875. def specialize_call(self, hop):
  876. from rpython.rtyper.lltypesystem import lltype
  877. driver = self.instance.im_self
  878. hop.exception_cannot_occur()
  879. vlist = [hop.inputconst(lltype.Void, 'loop_header'),
  880. hop.inputconst(lltype.Void, driver)]
  881. return hop.genop('jit_marker', vlist,
  882. resulttype=lltype.Void)
  883. class ExtSetParam(ExtRegistryEntry):
  884. _about_ = _set_param
  885. def compute_result_annotation(self, s_driver, s_name, s_value):
  886. from rpython.annotator import model as annmodel
  887. assert s_name.is_constant()
  888. if s_name.const == 'enable_opts':
  889. assert annmodel.SomeString(can_be_None=True).contains(s_value)
  890. else:
  891. assert (s_value == annmodel.s_None or
  892. annmodel.SomeInteger().contains(s_value))
  893. return annmodel.s_None
  894. def specialize_call(self, hop):
  895. from rpython.rtyper.lltypesystem import lltype
  896. from rpython.rtyper.lltypesystem.rstr import string_repr
  897. from rpython.flowspace.model import Constant
  898. hop.exception_cannot_occur()
  899. driver = hop.inputarg(lltype.Void, arg=0)
  900. name = hop.args_s[1].const
  901. if name == 'enable_opts':
  902. repr = string_repr
  903. else:
  904. repr = lltype.Signed
  905. if (isinstance(hop.args_v[2], Constant) and
  906. hop.args_v[2].value is None):
  907. value = PARAMETERS[name]
  908. v_value = hop.inputconst(repr, value)
  909. else:
  910. v_value = hop.inputarg(repr, arg=2)
  911. vlist = [hop.inputconst(lltype.Void, "set_param"),
  912. driver,
  913. hop.inputconst(lltype.Void, name),
  914. v_value]
  915. return hop.genop('jit_marker', vlist,
  916. resulttype=lltype.Void)
  917. class AsmInfo(object):
  918. """ An addition to JitDebugInfo concerning assembler. Attributes:
  919. ops_offset - dict of offsets of operations or None
  920. asmaddr - (int) raw address of assembler block
  921. asmlen - assembler block length
  922. rawstart - address a guard can jump to
  923. """
  924. def __init__(self, ops_offset, asmaddr, asmlen, rawstart=0):
  925. self.ops_offset = ops_offset
  926. self.asmaddr = asmaddr
  927. self.asmlen = asmlen
  928. self.rawstart = rawstart
  929. class JitDebugInfo(object):
  930. """ An object representing debug info. Attributes meanings:
  931. greenkey - a list of green boxes or None for bridge
  932. logger - an instance of jit.metainterp.logger.LogOperations
  933. type - either 'loop', 'entry bridge' or 'bridge'
  934. looptoken - description of a loop
  935. fail_descr - fail descr or None
  936. asminfo - extra assembler information
  937. """
  938. asminfo = None
  939. def __init__(self, jitdriver_sd, logger, looptoken, operations, type,
  940. greenkey=None, fail_descr=None):
  941. self.jitdriver_sd = jitdriver_sd
  942. self.logger = logger
  943. self.looptoken = looptoken
  944. self.operations = operations
  945. self.type = type
  946. if type == 'bridge':
  947. assert fail_descr is not None
  948. else:
  949. assert greenkey is not None
  950. self.greenkey = greenkey
  951. self.fail_descr = fail_descr
  952. def get_jitdriver(self):
  953. """ Return where the jitdriver on which the jitting started
  954. """
  955. return self.jitdriver_sd.jitdriver
  956. def get_greenkey_repr(self):
  957. """ Return the string repr of a greenkey
  958. """
  959. return self.jitdriver_sd.warmstate.get_location_str(self.greenkey)
  960. class JitHookInterface(object):
  961. """ This is the main connector between the JIT and the interpreter.
  962. Several methods on this class will be invoked at various stages
  963. of JIT running like JIT loops compiled, aborts etc.
  964. An instance of this class will be available as policy.jithookiface.
  965. """
  966. # WARNING: You should make a single prebuilt instance of a subclass
  967. # of this class. You can, before translation, initialize some
  968. # attributes on this instance, and then read or change these
  969. # attributes inside the methods of the subclass. But this prebuilt
  970. # instance *must not* be seen during the normal annotation/rtyping
  971. # of the program! A line like ``pypy_hooks.foo = ...`` must not
  972. # appear inside your interpreter's RPython code.
  973. def on_abort(self, reason, jitdriver, greenkey, greenkey_repr, logops, operations):
  974. """ A hook called each time a loop is aborted with jitdriver and
  975. greenkey where it started, reason is a string why it got aborted
  976. """
  977. def on_trace_too_long(self, jitdriver, greenkey, greenkey_repr):
  978. """ A hook called each time we abort the trace because it's too
  979. long with the greenkey being the one responsible for the
  980. disabled function
  981. """
  982. #def before_optimize(self, debug_info):
  983. # """ A hook called before optimizer is run, called with instance of
  984. # JitDebugInfo. Overwrite for custom behavior
  985. # """
  986. # DISABLED
  987. def before_compile(self, debug_info):
  988. """ A hook called after a loop is optimized, before compiling assembler,
  989. called with JitDebugInfo instance. Overwrite for custom behavior
  990. """
  991. def after_compile(self, debug_info):
  992. """ A hook called after a loop has compiled assembler,
  993. called with JitDebugInfo instance. Overwrite for custom behavior
  994. """
  995. #def before_optimize_bridge(self, debug_info):
  996. # operations, fail_descr_no):
  997. # """ A hook called before a bridge is optimized.
  998. # Called with JitDebugInfo instance, overwrite for
  999. # custom behavior
  1000. # """
  1001. # DISABLED
  1002. def before_compile_bridge(self, debug_info):
  1003. """ A hook called before a bridge is compiled, but after optimizations
  1004. are performed. Called with instance of debug_info, overwrite for
  1005. custom behavior
  1006. """
  1007. def after_compile_bridge(self, debug_info):
  1008. """ A hook called after a bridge is compiled, called with JitDebugInfo
  1009. instance, overwrite for custom behavior
  1010. """
  1011. def record_exact_class(value, cls):
  1012. """
  1013. Assure the JIT that value is an instance of cls. This is a precise
  1014. class check, like a guard_class.
  1015. """
  1016. assert type(value) is cls
  1017. def ll_record_exact_class(ll_value, ll_cls):
  1018. from rpython.rlib.debug import ll_assert
  1019. from rpython.rtyper.lltypesystem.lloperation import llop
  1020. from rpython.rtyper.lltypesystem import lltype
  1021. from rpython.rtyper.rclass import ll_type
  1022. ll_assert(ll_value != lltype.nullptr(lltype.typeOf(ll_value).TO), "record_exact_class called with None argument")
  1023. ll_assert(ll_type(ll_value) is ll_cls, "record_exact_class called with invalid arguments")
  1024. llop.jit_record_exact_class(lltype.Void, ll_value, ll_cls)
  1025. class Entry(ExtRegistryEntry):
  1026. _about_ = record_exact_class
  1027. def compute_result_annotation(self, s_inst, s_cls):
  1028. from rpython.annotator import model as annmodel
  1029. assert not s_inst.can_be_none()
  1030. assert isinstance(s_inst, annmodel.SomeInstance)
  1031. def specialize_call(self, hop):
  1032. from rpython.rtyper.lltypesystem import lltype
  1033. from rpython.rtyper import rclass
  1034. classrepr = rclass.get_type_repr(hop.rtyper)
  1035. v_inst = hop.inputarg(hop.args_r[0], arg=0)
  1036. v_cls = hop.inputarg(classrepr, arg=1)
  1037. hop.exception_is_here()
  1038. return hop.gendirectcall(ll_record_exact_class, v_inst, v_cls)
  1039. def _jit_conditional_call(condition, function, *args):
  1040. pass
  1041. @specialize.call_location()
  1042. def conditional_call(condition, function, *args):
  1043. if we_are_jitted():
  1044. _jit_conditional_call(condition, function, *args)
  1045. else:
  1046. if condition:
  1047. function(*args)
  1048. conditional_call._always_inline_ = True
  1049. class ConditionalCallEntry(ExtRegistryEntry):
  1050. _about_ = _jit_conditional_call
  1051. def compute_result_annotation(self, *args_s):
  1052. self.bookkeeper.emulate_pbc_call(self.bookkeeper.position_key,
  1053. args_s[1], args_s[2:])
  1054. def specialize_call(self, hop):
  1055. from rpython.rtyper.lltypesystem import lltype
  1056. args_v = hop.inputargs(lltype.Bool, lltype.Void, *hop.args_r[2:])
  1057. args_v[1] = hop.args_r[1].get_concrete_llfn(hop.args_s[1],
  1058. hop.args_s[2:], hop.spaceop)
  1059. hop.exception_is_here()
  1060. return hop.genop('jit_conditional_call', args_v)
  1061. def enter_portal_frame(unique_id):
  1062. """call this when starting to interpret a function. calling this is not
  1063. necessary for almost all interpreters. The only exception is stackless
  1064. interpreters where the portal never calls itself.
  1065. """
  1066. from rpython.rtyper.lltypesystem import lltype
  1067. from rpython.rtyper.lltypesystem.lloperation import llop
  1068. llop.jit_enter_portal_frame(lltype.Void, unique_id)
  1069. def leave_portal_frame():
  1070. """call this after the end of executing a function. calling this is not
  1071. necessary for almost all interpreters. The only exception is stackless
  1072. interpreters where the portal never calls itself.
  1073. """
  1074. from rpython.rtyper.lltypesystem import lltype
  1075. from rpython.rtyper.lltypesystem.lloperation import llop
  1076. llop.jit_leave_portal_frame(lltype.Void)
  1077. class Counters(object):
  1078. counters="""
  1079. TRACING
  1080. BACKEND
  1081. OPS
  1082. RECORDED_OPS
  1083. GUARDS
  1084. OPT_OPS
  1085. OPT_GUARDS
  1086. OPT_GUARDS_SHARED
  1087. OPT_FORCINGS
  1088. OPT_VECTORIZE_TRY
  1089. OPT_VECTORIZED
  1090. ABORT_TOO_LONG
  1091. ABORT_BRIDGE
  1092. ABORT_BAD_LOOP
  1093. ABORT_ESCAPE
  1094. ABORT_FORCE_QUASIIMMUT
  1095. NVIRTUALS
  1096. NVHOLES
  1097. NVREUSED
  1098. TOTAL_COMPILED_LOOPS
  1099. TOTAL_COMPILED_BRIDGES
  1100. TOTAL_FREED_LOOPS
  1101. TOTAL_FREED_BRIDGES
  1102. """
  1103. counter_names = []
  1104. @staticmethod
  1105. def _setup():
  1106. names = Counters.counters.split()
  1107. for i, name in enumerate(names):
  1108. setattr(Counters, name, i)
  1109. Counters.counter_names.append(name)
  1110. Counters.ncounters = len(names)
  1111. Counters._setup()