PageRenderTime 74ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 0ms

/rpython/jit/metainterp/pyjitpl.py

https://bitbucket.org/bwesterb/pypy
Python | 2786 lines | 2582 code | 94 blank | 110 comment | 86 complexity | 42be5ecbec7c31db0c02eaf417a83a27 MD5 | raw file
  1. import py, sys
  2. from rpython.rtyper.lltypesystem import lltype, rclass
  3. from rpython.rlib.objectmodel import we_are_translated
  4. from rpython.rlib.unroll import unrolling_iterable
  5. from rpython.rlib.debug import debug_start, debug_stop, debug_print
  6. from rpython.rlib.debug import make_sure_not_resized
  7. from rpython.rlib import nonconst, rstack
  8. from rpython.jit.metainterp import history, compile, resume
  9. from rpython.jit.metainterp.history import Const, ConstInt, ConstPtr, ConstFloat
  10. from rpython.jit.metainterp.history import Box, TargetToken
  11. from rpython.jit.metainterp.resoperation import rop
  12. from rpython.jit.metainterp import executor
  13. from rpython.jit.metainterp.logger import Logger
  14. from rpython.jit.metainterp.jitprof import EmptyProfiler
  15. from rpython.rlib.jit import Counters
  16. from rpython.jit.metainterp.jitexc import JitException, get_llexception
  17. from rpython.jit.metainterp.heapcache import HeapCache
  18. from rpython.rlib.objectmodel import specialize
  19. from rpython.jit.codewriter.jitcode import JitCode, SwitchDictDescr
  20. from rpython.jit.codewriter import heaptracker
  21. from rpython.jit.metainterp.optimizeopt.util import args_dict_box
  22. # ____________________________________________________________
  23. def arguments(*args):
  24. def decorate(func):
  25. func.argtypes = args
  26. return func
  27. return decorate
  28. # ____________________________________________________________
  29. class MIFrame(object):
  30. debug = False
  31. def __init__(self, metainterp):
  32. self.metainterp = metainterp
  33. self.registers_i = [None] * 256
  34. self.registers_r = [None] * 256
  35. self.registers_f = [None] * 256
  36. def setup(self, jitcode, greenkey=None):
  37. assert isinstance(jitcode, JitCode)
  38. self.jitcode = jitcode
  39. self.bytecode = jitcode.code
  40. # this is not None for frames that are recursive portal calls
  41. self.greenkey = greenkey
  42. # copy the constants in place
  43. self.copy_constants(self.registers_i, jitcode.constants_i, ConstInt)
  44. self.copy_constants(self.registers_r, jitcode.constants_r, ConstPtr)
  45. self.copy_constants(self.registers_f, jitcode.constants_f, ConstFloat)
  46. self._result_argcode = 'v'
  47. # for resume.py operation
  48. self.parent_resumedata_snapshot = None
  49. self.parent_resumedata_frame_info_list = None
  50. # counter for unrolling inlined loops
  51. self.unroll_iterations = 1
  52. @specialize.arg(3)
  53. def copy_constants(self, registers, constants, ConstClass):
  54. """Copy jitcode.constants[0] to registers[255],
  55. jitcode.constants[1] to registers[254],
  56. jitcode.constants[2] to registers[253], etc."""
  57. if nonconst.NonConstant(0): # force the right type
  58. constants[0] = ConstClass.value # (useful for small tests)
  59. i = len(constants) - 1
  60. while i >= 0:
  61. j = 255 - i
  62. assert j >= 0
  63. registers[j] = ConstClass(constants[i])
  64. i -= 1
  65. def cleanup_registers(self):
  66. # To avoid keeping references alive, this cleans up the registers_r.
  67. # It does not clear the references set by copy_constants(), but
  68. # these are all prebuilt constants anyway.
  69. for i in range(self.jitcode.num_regs_r()):
  70. self.registers_r[i] = None
  71. # ------------------------------
  72. # Decoding of the JitCode
  73. @specialize.arg(4)
  74. def prepare_list_of_boxes(self, outvalue, startindex, position, argcode):
  75. assert argcode in 'IRF'
  76. code = self.bytecode
  77. length = ord(code[position])
  78. position += 1
  79. for i in range(length):
  80. index = ord(code[position+i])
  81. if argcode == 'I': reg = self.registers_i[index]
  82. elif argcode == 'R': reg = self.registers_r[index]
  83. elif argcode == 'F': reg = self.registers_f[index]
  84. else: raise AssertionError(argcode)
  85. outvalue[startindex+i] = reg
  86. def _put_back_list_of_boxes(self, outvalue, startindex, position):
  87. code = self.bytecode
  88. length = ord(code[position])
  89. position += 1
  90. for i in range(length):
  91. index = ord(code[position+i])
  92. box = outvalue[startindex+i]
  93. if box.type == history.INT: self.registers_i[index] = box
  94. elif box.type == history.REF: self.registers_r[index] = box
  95. elif box.type == history.FLOAT: self.registers_f[index] = box
  96. else: raise AssertionError(box.type)
  97. def get_current_position_info(self):
  98. return self.jitcode.get_live_vars_info(self.pc)
  99. def get_list_of_active_boxes(self, in_a_call):
  100. if in_a_call:
  101. # If we are not the topmost frame, self._result_argcode contains
  102. # the type of the result of the call instruction in the bytecode.
  103. # We use it to clear the box that will hold the result: this box
  104. # is not defined yet.
  105. argcode = self._result_argcode
  106. index = ord(self.bytecode[self.pc - 1])
  107. if argcode == 'i': self.registers_i[index] = history.CONST_FALSE
  108. elif argcode == 'r': self.registers_r[index] = history.CONST_NULL
  109. elif argcode == 'f': self.registers_f[index] = history.CONST_FZERO
  110. self._result_argcode = '?' # done
  111. #
  112. info = self.get_current_position_info()
  113. start_i = 0
  114. start_r = start_i + info.get_register_count_i()
  115. start_f = start_r + info.get_register_count_r()
  116. total = start_f + info.get_register_count_f()
  117. # allocate a list of the correct size
  118. env = [None] * total
  119. make_sure_not_resized(env)
  120. # fill it now
  121. for i in range(info.get_register_count_i()):
  122. index = info.get_register_index_i(i)
  123. env[start_i + i] = self.registers_i[index]
  124. for i in range(info.get_register_count_r()):
  125. index = info.get_register_index_r(i)
  126. env[start_r + i] = self.registers_r[index]
  127. for i in range(info.get_register_count_f()):
  128. index = info.get_register_index_f(i)
  129. env[start_f + i] = self.registers_f[index]
  130. return env
  131. def replace_active_box_in_frame(self, oldbox, newbox):
  132. if isinstance(oldbox, history.BoxInt):
  133. count = self.jitcode.num_regs_i()
  134. registers = self.registers_i
  135. elif isinstance(oldbox, history.BoxPtr):
  136. count = self.jitcode.num_regs_r()
  137. registers = self.registers_r
  138. elif isinstance(oldbox, history.BoxFloat):
  139. count = self.jitcode.num_regs_f()
  140. registers = self.registers_f
  141. else:
  142. assert 0, oldbox
  143. for i in range(count):
  144. if registers[i] is oldbox:
  145. registers[i] = newbox
  146. if not we_are_translated():
  147. for b in registers[count:]:
  148. assert not oldbox.same_box(b)
  149. def make_result_of_lastop(self, resultbox):
  150. got_type = resultbox.type
  151. # XXX disabled for now, conflicts with str_guard_value
  152. #if not we_are_translated():
  153. # typeof = {'i': history.INT,
  154. # 'r': history.REF,
  155. # 'f': history.FLOAT}
  156. # assert typeof[self.jitcode._resulttypes[self.pc]] == got_type
  157. target_index = ord(self.bytecode[self.pc-1])
  158. if got_type == history.INT:
  159. self.registers_i[target_index] = resultbox
  160. elif got_type == history.REF:
  161. #debug_print(' ->',
  162. # llmemory.cast_ptr_to_adr(resultbox.getref_base()))
  163. self.registers_r[target_index] = resultbox
  164. elif got_type == history.FLOAT:
  165. self.registers_f[target_index] = resultbox
  166. else:
  167. raise AssertionError("bad result box type")
  168. # ------------------------------
  169. for _opimpl in ['int_add', 'int_sub', 'int_mul', 'int_floordiv', 'int_mod',
  170. 'int_lt', 'int_le', 'int_eq',
  171. 'int_ne', 'int_gt', 'int_ge',
  172. 'int_and', 'int_or', 'int_xor',
  173. 'int_rshift', 'int_lshift', 'uint_rshift',
  174. 'uint_lt', 'uint_le', 'uint_gt', 'uint_ge',
  175. 'uint_floordiv',
  176. 'float_add', 'float_sub', 'float_mul', 'float_truediv',
  177. 'float_lt', 'float_le', 'float_eq',
  178. 'float_ne', 'float_gt', 'float_ge',
  179. 'ptr_eq', 'ptr_ne', 'instance_ptr_eq', 'instance_ptr_ne',
  180. ]:
  181. exec py.code.Source('''
  182. @arguments("box", "box")
  183. def opimpl_%s(self, b1, b2):
  184. return self.execute(rop.%s, b1, b2)
  185. ''' % (_opimpl, _opimpl.upper())).compile()
  186. for _opimpl in ['int_add_ovf', 'int_sub_ovf', 'int_mul_ovf']:
  187. exec py.code.Source('''
  188. @arguments("box", "box")
  189. def opimpl_%s(self, b1, b2):
  190. self.metainterp.clear_exception()
  191. resbox = self.execute(rop.%s, b1, b2)
  192. self.make_result_of_lastop(resbox) # same as execute_varargs()
  193. if not isinstance(resbox, Const):
  194. self.metainterp.handle_possible_overflow_error()
  195. return resbox
  196. ''' % (_opimpl, _opimpl.upper())).compile()
  197. for _opimpl in ['int_is_true', 'int_is_zero', 'int_neg', 'int_invert',
  198. 'cast_float_to_int', 'cast_int_to_float',
  199. 'cast_float_to_singlefloat', 'cast_singlefloat_to_float',
  200. 'float_neg', 'float_abs',
  201. 'cast_ptr_to_int', 'cast_int_to_ptr',
  202. 'convert_float_bytes_to_longlong',
  203. 'convert_longlong_bytes_to_float', 'int_force_ge_zero',
  204. ]:
  205. exec py.code.Source('''
  206. @arguments("box")
  207. def opimpl_%s(self, b):
  208. return self.execute(rop.%s, b)
  209. ''' % (_opimpl, _opimpl.upper())).compile()
  210. @arguments("box")
  211. def opimpl_ptr_nonzero(self, box):
  212. return self.execute(rop.PTR_NE, box, history.CONST_NULL)
  213. @arguments("box")
  214. def opimpl_ptr_iszero(self, box):
  215. return self.execute(rop.PTR_EQ, box, history.CONST_NULL)
  216. @arguments("box")
  217. def opimpl_mark_opaque_ptr(self, box):
  218. return self.execute(rop.MARK_OPAQUE_PTR, box)
  219. @arguments("box", "box")
  220. def opimpl_record_known_class(self, box, clsbox):
  221. from rpython.rtyper.lltypesystem import llmemory
  222. if self.metainterp.heapcache.is_class_known(box):
  223. return
  224. adr = clsbox.getaddr()
  225. bounding_class = llmemory.cast_adr_to_ptr(adr, rclass.CLASSTYPE)
  226. if bounding_class.subclassrange_max - bounding_class.subclassrange_min == 1:
  227. # precise class knowledge, this can be used
  228. self.execute(rop.RECORD_KNOWN_CLASS, box, clsbox)
  229. self.metainterp.heapcache.class_now_known(box)
  230. @arguments("box")
  231. def _opimpl_any_return(self, box):
  232. self.metainterp.finishframe(box)
  233. opimpl_int_return = _opimpl_any_return
  234. opimpl_ref_return = _opimpl_any_return
  235. opimpl_float_return = _opimpl_any_return
  236. @arguments()
  237. def opimpl_void_return(self):
  238. self.metainterp.finishframe(None)
  239. @arguments("box")
  240. def _opimpl_any_copy(self, box):
  241. return box
  242. opimpl_int_copy = _opimpl_any_copy
  243. opimpl_ref_copy = _opimpl_any_copy
  244. opimpl_float_copy = _opimpl_any_copy
  245. @arguments("box")
  246. def _opimpl_any_push(self, box):
  247. self.pushed_box = box
  248. opimpl_int_push = _opimpl_any_push
  249. opimpl_ref_push = _opimpl_any_push
  250. opimpl_float_push = _opimpl_any_push
  251. @arguments()
  252. def _opimpl_any_pop(self):
  253. box = self.pushed_box
  254. self.pushed_box = None
  255. return box
  256. opimpl_int_pop = _opimpl_any_pop
  257. opimpl_ref_pop = _opimpl_any_pop
  258. opimpl_float_pop = _opimpl_any_pop
  259. @arguments("label")
  260. def opimpl_catch_exception(self, target):
  261. """This is a no-op when run normally. We can check that
  262. last_exc_value_box is None; it should have been set to None
  263. by the previous instruction. If the previous instruction
  264. raised instead, finishframe_exception() should have been
  265. called and we would not be there."""
  266. assert self.metainterp.last_exc_value_box is None
  267. @arguments("label")
  268. def opimpl_goto(self, target):
  269. self.pc = target
  270. @arguments("box", "label")
  271. def opimpl_goto_if_not(self, box, target):
  272. switchcase = box.getint()
  273. if switchcase:
  274. opnum = rop.GUARD_TRUE
  275. else:
  276. opnum = rop.GUARD_FALSE
  277. self.generate_guard(opnum, box)
  278. if not switchcase:
  279. self.pc = target
  280. @arguments("box", "label")
  281. def opimpl_goto_if_not_int_is_true(self, box, target):
  282. condbox = self.execute(rop.INT_IS_TRUE, box)
  283. self.opimpl_goto_if_not(condbox, target)
  284. @arguments("box", "label")
  285. def opimpl_goto_if_not_int_is_zero(self, box, target):
  286. condbox = self.execute(rop.INT_IS_ZERO, box)
  287. self.opimpl_goto_if_not(condbox, target)
  288. for _opimpl in ['int_lt', 'int_le', 'int_eq', 'int_ne', 'int_gt', 'int_ge',
  289. 'ptr_eq', 'ptr_ne']:
  290. exec py.code.Source('''
  291. @arguments("box", "box", "label")
  292. def opimpl_goto_if_not_%s(self, b1, b2, target):
  293. condbox = self.execute(rop.%s, b1, b2)
  294. self.opimpl_goto_if_not(condbox, target)
  295. ''' % (_opimpl, _opimpl.upper())).compile()
  296. def _establish_nullity(self, box, orgpc):
  297. value = box.nonnull()
  298. if value:
  299. if not self.metainterp.heapcache.is_class_known(box):
  300. self.generate_guard(rop.GUARD_NONNULL, box, resumepc=orgpc)
  301. else:
  302. if not isinstance(box, Const):
  303. self.generate_guard(rop.GUARD_ISNULL, box, resumepc=orgpc)
  304. promoted_box = box.constbox()
  305. self.metainterp.replace_box(box, promoted_box)
  306. return value
  307. @arguments("box", "label", "orgpc")
  308. def opimpl_goto_if_not_ptr_nonzero(self, box, target, orgpc):
  309. if not self._establish_nullity(box, orgpc):
  310. self.pc = target
  311. @arguments("box", "label", "orgpc")
  312. def opimpl_goto_if_not_ptr_iszero(self, box, target, orgpc):
  313. if self._establish_nullity(box, orgpc):
  314. self.pc = target
  315. @arguments("box", "box", "box")
  316. def opimpl_int_between(self, b1, b2, b3):
  317. b5 = self.execute(rop.INT_SUB, b3, b1)
  318. if isinstance(b5, ConstInt) and b5.getint() == 1:
  319. # the common case of int_between(a, b, a+1) turns into just INT_EQ
  320. return self.execute(rop.INT_EQ, b2, b1)
  321. else:
  322. b4 = self.execute(rop.INT_SUB, b2, b1)
  323. return self.execute(rop.UINT_LT, b4, b5)
  324. @arguments("box", "descr", "orgpc")
  325. def opimpl_switch(self, valuebox, switchdict, orgpc):
  326. box = self.implement_guard_value(valuebox, orgpc)
  327. search_value = box.getint()
  328. assert isinstance(switchdict, SwitchDictDescr)
  329. try:
  330. self.pc = switchdict.dict[search_value]
  331. except KeyError:
  332. pass
  333. @arguments()
  334. def opimpl_unreachable(self):
  335. raise AssertionError("unreachable")
  336. @arguments("descr")
  337. def opimpl_new(self, sizedescr):
  338. resbox = self.execute_with_descr(rop.NEW, sizedescr)
  339. self.metainterp.heapcache.new(resbox)
  340. return resbox
  341. @arguments("descr")
  342. def opimpl_new_with_vtable(self, sizedescr):
  343. cpu = self.metainterp.cpu
  344. cls = heaptracker.descr2vtable(cpu, sizedescr)
  345. resbox = self.execute(rop.NEW_WITH_VTABLE, ConstInt(cls))
  346. self.metainterp.heapcache.new(resbox)
  347. self.metainterp.heapcache.class_now_known(resbox)
  348. return resbox
  349. @arguments("box", "descr")
  350. def opimpl_new_array(self, lengthbox, itemsizedescr):
  351. resbox = self.execute_with_descr(rop.NEW_ARRAY, itemsizedescr, lengthbox)
  352. self.metainterp.heapcache.new_array(resbox, lengthbox)
  353. return resbox
  354. @specialize.arg(1)
  355. def _do_getarrayitem_gc_any(self, op, arraybox, indexbox, arraydescr):
  356. tobox = self.metainterp.heapcache.getarrayitem(
  357. arraybox, indexbox, arraydescr)
  358. if tobox:
  359. # sanity check: see whether the current array value
  360. # corresponds to what the cache thinks the value is
  361. resbox = executor.execute(self.metainterp.cpu, self.metainterp, op,
  362. arraydescr, arraybox, indexbox)
  363. assert resbox.constbox().same_constant(tobox.constbox())
  364. return tobox
  365. resbox = self.execute_with_descr(op, arraydescr, arraybox, indexbox)
  366. self.metainterp.heapcache.getarrayitem_now_known(
  367. arraybox, indexbox, resbox, arraydescr)
  368. return resbox
  369. @arguments("box", "box", "descr")
  370. def _opimpl_getarrayitem_gc_any(self, arraybox, indexbox, arraydescr):
  371. return self._do_getarrayitem_gc_any(rop.GETARRAYITEM_GC, arraybox,
  372. indexbox, arraydescr)
  373. opimpl_getarrayitem_gc_i = _opimpl_getarrayitem_gc_any
  374. opimpl_getarrayitem_gc_r = _opimpl_getarrayitem_gc_any
  375. opimpl_getarrayitem_gc_f = _opimpl_getarrayitem_gc_any
  376. @arguments("box", "box", "descr")
  377. def _opimpl_getarrayitem_raw_any(self, arraybox, indexbox, arraydescr):
  378. return self.execute_with_descr(rop.GETARRAYITEM_RAW,
  379. arraydescr, arraybox, indexbox)
  380. opimpl_getarrayitem_raw_i = _opimpl_getarrayitem_raw_any
  381. opimpl_getarrayitem_raw_f = _opimpl_getarrayitem_raw_any
  382. @arguments("box", "box", "descr")
  383. def _opimpl_getarrayitem_raw_pure_any(self, arraybox, indexbox,
  384. arraydescr):
  385. return self.execute_with_descr(rop.GETARRAYITEM_RAW_PURE,
  386. arraydescr, arraybox, indexbox)
  387. opimpl_getarrayitem_raw_i_pure = _opimpl_getarrayitem_raw_pure_any
  388. opimpl_getarrayitem_raw_f_pure = _opimpl_getarrayitem_raw_pure_any
  389. @arguments("box", "box", "descr")
  390. def _opimpl_getarrayitem_gc_pure_any(self, arraybox, indexbox, arraydescr):
  391. if isinstance(arraybox, ConstPtr) and isinstance(indexbox, ConstInt):
  392. # if the arguments are directly constants, bypass the heapcache
  393. # completely
  394. resbox = executor.execute(self.metainterp.cpu, self.metainterp,
  395. rop.GETARRAYITEM_GC_PURE, arraydescr,
  396. arraybox, indexbox)
  397. return resbox.constbox()
  398. return self._do_getarrayitem_gc_any(rop.GETARRAYITEM_GC_PURE, arraybox,
  399. indexbox, arraydescr)
  400. opimpl_getarrayitem_gc_i_pure = _opimpl_getarrayitem_gc_pure_any
  401. opimpl_getarrayitem_gc_r_pure = _opimpl_getarrayitem_gc_pure_any
  402. opimpl_getarrayitem_gc_f_pure = _opimpl_getarrayitem_gc_pure_any
  403. @arguments("box", "box", "box", "descr")
  404. def _opimpl_setarrayitem_gc_any(self, arraybox, indexbox, itembox,
  405. arraydescr):
  406. self.execute_with_descr(rop.SETARRAYITEM_GC, arraydescr, arraybox,
  407. indexbox, itembox)
  408. self.metainterp.heapcache.setarrayitem(
  409. arraybox, indexbox, itembox, arraydescr)
  410. opimpl_setarrayitem_gc_i = _opimpl_setarrayitem_gc_any
  411. opimpl_setarrayitem_gc_r = _opimpl_setarrayitem_gc_any
  412. opimpl_setarrayitem_gc_f = _opimpl_setarrayitem_gc_any
  413. @arguments("box", "box", "box", "descr")
  414. def _opimpl_setarrayitem_raw_any(self, arraybox, indexbox, itembox,
  415. arraydescr):
  416. self.execute_with_descr(rop.SETARRAYITEM_RAW, arraydescr, arraybox,
  417. indexbox, itembox)
  418. opimpl_setarrayitem_raw_i = _opimpl_setarrayitem_raw_any
  419. opimpl_setarrayitem_raw_f = _opimpl_setarrayitem_raw_any
  420. @arguments("box", "descr")
  421. def opimpl_arraylen_gc(self, arraybox, arraydescr):
  422. lengthbox = self.metainterp.heapcache.arraylen(arraybox)
  423. if lengthbox is None:
  424. lengthbox = self.execute_with_descr(
  425. rop.ARRAYLEN_GC, arraydescr, arraybox)
  426. self.metainterp.heapcache.arraylen_now_known(arraybox, lengthbox)
  427. return lengthbox
  428. @arguments("box", "box", "descr", "orgpc")
  429. def opimpl_check_neg_index(self, arraybox, indexbox, arraydescr, orgpc):
  430. negbox = self.metainterp.execute_and_record(
  431. rop.INT_LT, None, indexbox, history.CONST_FALSE)
  432. negbox = self.implement_guard_value(negbox, orgpc)
  433. if negbox.getint():
  434. # the index is < 0; add the array length to it
  435. lengthbox = self.opimpl_arraylen_gc(arraybox, arraydescr)
  436. indexbox = self.metainterp.execute_and_record(
  437. rop.INT_ADD, None, indexbox, lengthbox)
  438. return indexbox
  439. @arguments("box", "descr", "descr", "descr", "descr")
  440. def opimpl_newlist(self, sizebox, structdescr, lengthdescr,
  441. itemsdescr, arraydescr):
  442. sbox = self.opimpl_new(structdescr)
  443. self._opimpl_setfield_gc_any(sbox, sizebox, lengthdescr)
  444. abox = self.opimpl_new_array(sizebox, arraydescr)
  445. self._opimpl_setfield_gc_any(sbox, abox, itemsdescr)
  446. return sbox
  447. @arguments("box", "descr", "descr", "descr", "descr")
  448. def opimpl_newlist_hint(self, sizehintbox, structdescr, lengthdescr,
  449. itemsdescr, arraydescr):
  450. sbox = self.opimpl_new(structdescr)
  451. self._opimpl_setfield_gc_any(sbox, history.CONST_FALSE, lengthdescr)
  452. abox = self.opimpl_new_array(sizehintbox, arraydescr)
  453. self._opimpl_setfield_gc_any(sbox, abox, itemsdescr)
  454. return sbox
  455. @arguments("box", "box", "descr", "descr")
  456. def _opimpl_getlistitem_gc_any(self, listbox, indexbox,
  457. itemsdescr, arraydescr):
  458. arraybox = self._opimpl_getfield_gc_any(listbox, itemsdescr)
  459. return self._opimpl_getarrayitem_gc_any(arraybox, indexbox, arraydescr)
  460. opimpl_getlistitem_gc_i = _opimpl_getlistitem_gc_any
  461. opimpl_getlistitem_gc_r = _opimpl_getlistitem_gc_any
  462. opimpl_getlistitem_gc_f = _opimpl_getlistitem_gc_any
  463. @arguments("box", "box", "box", "descr", "descr")
  464. def _opimpl_setlistitem_gc_any(self, listbox, indexbox, valuebox,
  465. itemsdescr, arraydescr):
  466. arraybox = self._opimpl_getfield_gc_any(listbox, itemsdescr)
  467. self._opimpl_setarrayitem_gc_any(arraybox, indexbox, valuebox,
  468. arraydescr)
  469. opimpl_setlistitem_gc_i = _opimpl_setlistitem_gc_any
  470. opimpl_setlistitem_gc_r = _opimpl_setlistitem_gc_any
  471. opimpl_setlistitem_gc_f = _opimpl_setlistitem_gc_any
  472. @arguments("box", "box", "descr", "orgpc")
  473. def opimpl_check_resizable_neg_index(self, listbox, indexbox,
  474. lengthdescr, orgpc):
  475. negbox = self.metainterp.execute_and_record(
  476. rop.INT_LT, None, indexbox, history.CONST_FALSE)
  477. negbox = self.implement_guard_value(negbox, orgpc)
  478. if negbox.getint():
  479. # the index is < 0; add the array length to it
  480. lenbox = self.metainterp.execute_and_record(
  481. rop.GETFIELD_GC, lengthdescr, listbox)
  482. indexbox = self.metainterp.execute_and_record(
  483. rop.INT_ADD, None, indexbox, lenbox)
  484. return indexbox
  485. @arguments("box", "descr")
  486. def _opimpl_getfield_gc_any(self, box, fielddescr):
  487. return self._opimpl_getfield_gc_any_pureornot(
  488. rop.GETFIELD_GC, box, fielddescr)
  489. opimpl_getfield_gc_i = _opimpl_getfield_gc_any
  490. opimpl_getfield_gc_r = _opimpl_getfield_gc_any
  491. opimpl_getfield_gc_f = _opimpl_getfield_gc_any
  492. @arguments("box", "descr")
  493. def _opimpl_getfield_gc_pure_any(self, box, fielddescr):
  494. if isinstance(box, ConstPtr):
  495. # if 'box' is directly a ConstPtr, bypass the heapcache completely
  496. resbox = executor.execute(self.metainterp.cpu, self.metainterp,
  497. rop.GETFIELD_GC_PURE, fielddescr, box)
  498. return resbox.constbox()
  499. return self._opimpl_getfield_gc_any_pureornot(
  500. rop.GETFIELD_GC_PURE, box, fielddescr)
  501. opimpl_getfield_gc_i_pure = _opimpl_getfield_gc_pure_any
  502. opimpl_getfield_gc_r_pure = _opimpl_getfield_gc_pure_any
  503. opimpl_getfield_gc_f_pure = _opimpl_getfield_gc_pure_any
  504. @arguments("box", "box", "descr")
  505. def _opimpl_getinteriorfield_gc_any(self, array, index, descr):
  506. return self.execute_with_descr(rop.GETINTERIORFIELD_GC, descr,
  507. array, index)
  508. opimpl_getinteriorfield_gc_i = _opimpl_getinteriorfield_gc_any
  509. opimpl_getinteriorfield_gc_f = _opimpl_getinteriorfield_gc_any
  510. opimpl_getinteriorfield_gc_r = _opimpl_getinteriorfield_gc_any
  511. @specialize.arg(1)
  512. def _opimpl_getfield_gc_any_pureornot(self, opnum, box, fielddescr):
  513. tobox = self.metainterp.heapcache.getfield(box, fielddescr)
  514. if tobox is not None:
  515. # sanity check: see whether the current struct value
  516. # corresponds to what the cache thinks the value is
  517. #resbox = executor.execute(self.metainterp.cpu, self.metainterp,
  518. # rop.GETFIELD_GC, fielddescr, box)
  519. # XXX the sanity check does not seem to do anything, remove?
  520. return tobox
  521. resbox = self.execute_with_descr(opnum, fielddescr, box)
  522. self.metainterp.heapcache.getfield_now_known(box, fielddescr, resbox)
  523. return resbox
  524. @arguments("box", "descr", "orgpc")
  525. def _opimpl_getfield_gc_greenfield_any(self, box, fielddescr, pc):
  526. ginfo = self.metainterp.jitdriver_sd.greenfield_info
  527. if (ginfo is not None and fielddescr in ginfo.green_field_descrs
  528. and not self._nonstandard_virtualizable(pc, box)):
  529. # fetch the result, but consider it as a Const box and don't
  530. # record any operation
  531. resbox = executor.execute(self.metainterp.cpu, self.metainterp,
  532. rop.GETFIELD_GC_PURE, fielddescr, box)
  533. return resbox.constbox()
  534. # fall-back
  535. return self.execute_with_descr(rop.GETFIELD_GC_PURE, fielddescr, box)
  536. opimpl_getfield_gc_i_greenfield = _opimpl_getfield_gc_greenfield_any
  537. opimpl_getfield_gc_r_greenfield = _opimpl_getfield_gc_greenfield_any
  538. opimpl_getfield_gc_f_greenfield = _opimpl_getfield_gc_greenfield_any
  539. @arguments("box", "box", "descr")
  540. def _opimpl_setfield_gc_any(self, box, valuebox, fielddescr):
  541. tobox = self.metainterp.heapcache.getfield(box, fielddescr)
  542. if tobox is valuebox:
  543. return
  544. self.execute_with_descr(rop.SETFIELD_GC, fielddescr, box, valuebox)
  545. self.metainterp.heapcache.setfield(box, valuebox, fielddescr)
  546. opimpl_setfield_gc_i = _opimpl_setfield_gc_any
  547. opimpl_setfield_gc_r = _opimpl_setfield_gc_any
  548. opimpl_setfield_gc_f = _opimpl_setfield_gc_any
  549. @arguments("box", "box", "box", "descr")
  550. def _opimpl_setinteriorfield_gc_any(self, array, index, value, descr):
  551. self.execute_with_descr(rop.SETINTERIORFIELD_GC, descr,
  552. array, index, value)
  553. opimpl_setinteriorfield_gc_i = _opimpl_setinteriorfield_gc_any
  554. opimpl_setinteriorfield_gc_f = _opimpl_setinteriorfield_gc_any
  555. opimpl_setinteriorfield_gc_r = _opimpl_setinteriorfield_gc_any
  556. @arguments("box", "descr")
  557. def _opimpl_getfield_raw_any(self, box, fielddescr):
  558. return self.execute_with_descr(rop.GETFIELD_RAW, fielddescr, box)
  559. opimpl_getfield_raw_i = _opimpl_getfield_raw_any
  560. opimpl_getfield_raw_r = _opimpl_getfield_raw_any
  561. opimpl_getfield_raw_f = _opimpl_getfield_raw_any
  562. @arguments("box", "descr")
  563. def _opimpl_getfield_raw_pure_any(self, box, fielddescr):
  564. return self.execute_with_descr(rop.GETFIELD_RAW_PURE, fielddescr, box)
  565. opimpl_getfield_raw_i_pure = _opimpl_getfield_raw_pure_any
  566. opimpl_getfield_raw_r_pure = _opimpl_getfield_raw_pure_any
  567. opimpl_getfield_raw_f_pure = _opimpl_getfield_raw_pure_any
  568. @arguments("box", "box", "descr")
  569. def _opimpl_setfield_raw_any(self, box, valuebox, fielddescr):
  570. self.execute_with_descr(rop.SETFIELD_RAW, fielddescr, box, valuebox)
  571. opimpl_setfield_raw_i = _opimpl_setfield_raw_any
  572. opimpl_setfield_raw_r = _opimpl_setfield_raw_any
  573. opimpl_setfield_raw_f = _opimpl_setfield_raw_any
  574. @arguments("box", "box", "box", "descr")
  575. def _opimpl_raw_store(self, addrbox, offsetbox, valuebox, arraydescr):
  576. self.execute_with_descr(rop.RAW_STORE, arraydescr,
  577. addrbox, offsetbox, valuebox)
  578. opimpl_raw_store_i = _opimpl_raw_store
  579. opimpl_raw_store_f = _opimpl_raw_store
  580. @arguments("box", "box", "descr")
  581. def _opimpl_raw_load(self, addrbox, offsetbox, arraydescr):
  582. return self.execute_with_descr(rop.RAW_LOAD, arraydescr,
  583. addrbox, offsetbox)
  584. opimpl_raw_load_i = _opimpl_raw_load
  585. opimpl_raw_load_f = _opimpl_raw_load
  586. @arguments("box", "descr", "descr", "orgpc")
  587. def opimpl_record_quasiimmut_field(self, box, fielddescr,
  588. mutatefielddescr, orgpc):
  589. from rpython.jit.metainterp.quasiimmut import QuasiImmutDescr
  590. cpu = self.metainterp.cpu
  591. descr = QuasiImmutDescr(cpu, box, fielddescr, mutatefielddescr)
  592. self.metainterp.history.record(rop.QUASIIMMUT_FIELD, [box],
  593. None, descr=descr)
  594. self.generate_guard(rop.GUARD_NOT_INVALIDATED, resumepc=orgpc)
  595. @arguments("box", "descr", "orgpc")
  596. def opimpl_jit_force_quasi_immutable(self, box, mutatefielddescr, orgpc):
  597. # During tracing, a 'jit_force_quasi_immutable' usually turns into
  598. # the operations that check that the content of 'mutate_xxx' is null.
  599. # If it is actually not null already now, then we abort tracing.
  600. # The idea is that if we use 'jit_force_quasi_immutable' on a freshly
  601. # allocated object, then the GETFIELD_GC will know that the answer is
  602. # null, and the guard will be removed. So the fact that the field is
  603. # quasi-immutable will have no effect, and instead it will work as a
  604. # regular, probably virtual, structure.
  605. mutatebox = self.execute_with_descr(rop.GETFIELD_GC,
  606. mutatefielddescr, box)
  607. if mutatebox.nonnull():
  608. from rpython.jit.metainterp.quasiimmut import do_force_quasi_immutable
  609. do_force_quasi_immutable(self.metainterp.cpu, box.getref_base(),
  610. mutatefielddescr)
  611. raise SwitchToBlackhole(Counters.ABORT_FORCE_QUASIIMMUT)
  612. self.generate_guard(rop.GUARD_ISNULL, mutatebox, resumepc=orgpc)
  613. def _nonstandard_virtualizable(self, pc, box):
  614. # returns True if 'box' is actually not the "standard" virtualizable
  615. # that is stored in metainterp.virtualizable_boxes[-1]
  616. if (self.metainterp.jitdriver_sd.virtualizable_info is None and
  617. self.metainterp.jitdriver_sd.greenfield_info is None):
  618. return True # can occur in case of multiple JITs
  619. standard_box = self.metainterp.virtualizable_boxes[-1]
  620. if standard_box is box:
  621. return False
  622. if self.metainterp.heapcache.is_nonstandard_virtualizable(box):
  623. return True
  624. eqbox = self.metainterp.execute_and_record(rop.PTR_EQ, None,
  625. box, standard_box)
  626. eqbox = self.implement_guard_value(eqbox, pc)
  627. isstandard = eqbox.getint()
  628. if isstandard:
  629. self.metainterp.replace_box(box, standard_box)
  630. else:
  631. self.metainterp.heapcache.nonstandard_virtualizables_now_known(box)
  632. return not isstandard
  633. def _get_virtualizable_field_index(self, fielddescr):
  634. # Get the index of a fielddescr. Must only be called for
  635. # the "standard" virtualizable.
  636. vinfo = self.metainterp.jitdriver_sd.virtualizable_info
  637. return vinfo.static_field_by_descrs[fielddescr]
  638. @arguments("box", "descr", "orgpc")
  639. def _opimpl_getfield_vable(self, box, fielddescr, pc):
  640. if self._nonstandard_virtualizable(pc, box):
  641. return self._opimpl_getfield_gc_any(box, fielddescr)
  642. self.metainterp.check_synchronized_virtualizable()
  643. index = self._get_virtualizable_field_index(fielddescr)
  644. return self.metainterp.virtualizable_boxes[index]
  645. opimpl_getfield_vable_i = _opimpl_getfield_vable
  646. opimpl_getfield_vable_r = _opimpl_getfield_vable
  647. opimpl_getfield_vable_f = _opimpl_getfield_vable
  648. @arguments("box", "box", "descr", "orgpc")
  649. def _opimpl_setfield_vable(self, box, valuebox, fielddescr, pc):
  650. if self._nonstandard_virtualizable(pc, box):
  651. return self._opimpl_setfield_gc_any(box, valuebox, fielddescr)
  652. index = self._get_virtualizable_field_index(fielddescr)
  653. self.metainterp.virtualizable_boxes[index] = valuebox
  654. self.metainterp.synchronize_virtualizable()
  655. # XXX only the index'th field needs to be synchronized, really
  656. opimpl_setfield_vable_i = _opimpl_setfield_vable
  657. opimpl_setfield_vable_r = _opimpl_setfield_vable
  658. opimpl_setfield_vable_f = _opimpl_setfield_vable
  659. def _get_arrayitem_vable_index(self, pc, arrayfielddescr, indexbox):
  660. # Get the index of an array item: the index'th of the array
  661. # described by arrayfielddescr. Must only be called for
  662. # the "standard" virtualizable.
  663. indexbox = self.implement_guard_value(indexbox, pc)
  664. vinfo = self.metainterp.jitdriver_sd.virtualizable_info
  665. virtualizable_box = self.metainterp.virtualizable_boxes[-1]
  666. virtualizable = vinfo.unwrap_virtualizable_box(virtualizable_box)
  667. arrayindex = vinfo.array_field_by_descrs[arrayfielddescr]
  668. index = indexbox.getint()
  669. # Support for negative index: disabled
  670. # (see codewriter/jtransform.py, _check_no_vable_array).
  671. #if index < 0:
  672. # index += vinfo.get_array_length(virtualizable, arrayindex)
  673. assert 0 <= index < vinfo.get_array_length(virtualizable, arrayindex)
  674. return vinfo.get_index_in_array(virtualizable, arrayindex, index)
  675. @arguments("box", "box", "descr", "descr", "orgpc")
  676. def _opimpl_getarrayitem_vable(self, box, indexbox, fdescr, adescr, pc):
  677. if self._nonstandard_virtualizable(pc, box):
  678. arraybox = self._opimpl_getfield_gc_any(box, fdescr)
  679. return self._opimpl_getarrayitem_gc_any(arraybox, indexbox, adescr)
  680. self.metainterp.check_synchronized_virtualizable()
  681. index = self._get_arrayitem_vable_index(pc, fdescr, indexbox)
  682. return self.metainterp.virtualizable_boxes[index]
  683. opimpl_getarrayitem_vable_i = _opimpl_getarrayitem_vable
  684. opimpl_getarrayitem_vable_r = _opimpl_getarrayitem_vable
  685. opimpl_getarrayitem_vable_f = _opimpl_getarrayitem_vable
  686. @arguments("box", "box", "box", "descr", "descr", "orgpc")
  687. def _opimpl_setarrayitem_vable(self, box, indexbox, valuebox,
  688. fdescr, adescr, pc):
  689. if self._nonstandard_virtualizable(pc, box):
  690. arraybox = self._opimpl_getfield_gc_any(box, fdescr)
  691. self._opimpl_setarrayitem_gc_any(arraybox, indexbox, valuebox,
  692. adescr)
  693. return
  694. index = self._get_arrayitem_vable_index(pc, fdescr, indexbox)
  695. self.metainterp.virtualizable_boxes[index] = valuebox
  696. self.metainterp.synchronize_virtualizable()
  697. # XXX only the index'th field needs to be synchronized, really
  698. opimpl_setarrayitem_vable_i = _opimpl_setarrayitem_vable
  699. opimpl_setarrayitem_vable_r = _opimpl_setarrayitem_vable
  700. opimpl_setarrayitem_vable_f = _opimpl_setarrayitem_vable
  701. @arguments("box", "descr", "descr", "orgpc")
  702. def opimpl_arraylen_vable(self, box, fdescr, adescr, pc):
  703. if self._nonstandard_virtualizable(pc, box):
  704. arraybox = self._opimpl_getfield_gc_any(box, fdescr)
  705. return self.opimpl_arraylen_gc(arraybox, adescr)
  706. vinfo = self.metainterp.jitdriver_sd.virtualizable_info
  707. virtualizable_box = self.metainterp.virtualizable_boxes[-1]
  708. virtualizable = vinfo.unwrap_virtualizable_box(virtualizable_box)
  709. arrayindex = vinfo.array_field_by_descrs[fdescr]
  710. result = vinfo.get_array_length(virtualizable, arrayindex)
  711. return ConstInt(result)
  712. @arguments("jitcode", "boxes")
  713. def _opimpl_inline_call1(self, jitcode, argboxes):
  714. return self.metainterp.perform_call(jitcode, argboxes)
  715. @arguments("jitcode", "boxes2")
  716. def _opimpl_inline_call2(self, jitcode, argboxes):
  717. return self.metainterp.perform_call(jitcode, argboxes)
  718. @arguments("jitcode", "boxes3")
  719. def _opimpl_inline_call3(self, jitcode, argboxes):
  720. return self.metainterp.perform_call(jitcode, argboxes)
  721. opimpl_inline_call_r_i = _opimpl_inline_call1
  722. opimpl_inline_call_r_r = _opimpl_inline_call1
  723. opimpl_inline_call_r_v = _opimpl_inline_call1
  724. opimpl_inline_call_ir_i = _opimpl_inline_call2
  725. opimpl_inline_call_ir_r = _opimpl_inline_call2
  726. opimpl_inline_call_ir_v = _opimpl_inline_call2
  727. opimpl_inline_call_irf_i = _opimpl_inline_call3
  728. opimpl_inline_call_irf_r = _opimpl_inline_call3
  729. opimpl_inline_call_irf_f = _opimpl_inline_call3
  730. opimpl_inline_call_irf_v = _opimpl_inline_call3
  731. @arguments("box", "boxes", "descr")
  732. def _opimpl_residual_call1(self, funcbox, argboxes, calldescr):
  733. return self.do_residual_or_indirect_call(funcbox, argboxes, calldescr)
  734. @arguments("box", "boxes2", "descr")
  735. def _opimpl_residual_call2(self, funcbox, argboxes, calldescr):
  736. return self.do_residual_or_indirect_call(funcbox, argboxes, calldescr)
  737. @arguments("box", "boxes3", "descr")
  738. def _opimpl_residual_call3(self, funcbox, argboxes, calldescr):
  739. return self.do_residual_or_indirect_call(funcbox, argboxes, calldescr)
  740. opimpl_residual_call_r_i = _opimpl_residual_call1
  741. opimpl_residual_call_r_r = _opimpl_residual_call1
  742. opimpl_residual_call_r_v = _opimpl_residual_call1
  743. opimpl_residual_call_ir_i = _opimpl_residual_call2
  744. opimpl_residual_call_ir_r = _opimpl_residual_call2
  745. opimpl_residual_call_ir_v = _opimpl_residual_call2
  746. opimpl_residual_call_irf_i = _opimpl_residual_call3
  747. opimpl_residual_call_irf_r = _opimpl_residual_call3
  748. opimpl_residual_call_irf_f = _opimpl_residual_call3
  749. opimpl_residual_call_irf_v = _opimpl_residual_call3
  750. @arguments("int", "boxes3", "boxes3")
  751. def _opimpl_recursive_call(self, jdindex, greenboxes, redboxes):
  752. targetjitdriver_sd = self.metainterp.staticdata.jitdrivers_sd[jdindex]
  753. allboxes = greenboxes + redboxes
  754. warmrunnerstate = targetjitdriver_sd.warmstate
  755. assembler_call = False
  756. if warmrunnerstate.inlining:
  757. if warmrunnerstate.can_inline_callable(greenboxes):
  758. portal_code = targetjitdriver_sd.mainjitcode
  759. return self.metainterp.perform_call(portal_code, allboxes,
  760. greenkey=greenboxes)
  761. assembler_call = True
  762. # verify that we have all green args, needed to make sure
  763. # that assembler that we call is still correct
  764. self.verify_green_args(targetjitdriver_sd, greenboxes)
  765. #
  766. return self.do_recursive_call(targetjitdriver_sd, allboxes,
  767. assembler_call)
  768. def do_recursive_call(self, targetjitdriver_sd, allboxes,
  769. assembler_call=False):
  770. portal_code = targetjitdriver_sd.mainjitcode
  771. k = targetjitdriver_sd.portal_runner_adr
  772. funcbox = ConstInt(heaptracker.adr2int(k))
  773. return self.do_residual_call(funcbox, allboxes, portal_code.calldescr,
  774. assembler_call=assembler_call,
  775. assembler_call_jd=targetjitdriver_sd)
  776. opimpl_recursive_call_i = _opimpl_recursive_call
  777. opimpl_recursive_call_r = _opimpl_recursive_call
  778. opimpl_recursive_call_f = _opimpl_recursive_call
  779. opimpl_recursive_call_v = _opimpl_recursive_call
  780. @arguments("box")
  781. def opimpl_strlen(self, strbox):
  782. return self.execute(rop.STRLEN, strbox)
  783. @arguments("box")
  784. def opimpl_unicodelen(self, unicodebox):
  785. return self.execute(rop.UNICODELEN, unicodebox)
  786. @arguments("box", "box")
  787. def opimpl_strgetitem(self, strbox, indexbox):
  788. return self.execute(rop.STRGETITEM, strbox, indexbox)
  789. @arguments("box", "box")
  790. def opimpl_unicodegetitem(self, unicodebox, indexbox):
  791. return self.execute(rop.UNICODEGETITEM, unicodebox, indexbox)
  792. @arguments("box", "box", "box")
  793. def opimpl_strsetitem(self, strbox, indexbox, newcharbox):
  794. return self.execute(rop.STRSETITEM, strbox, indexbox, newcharbox)
  795. @arguments("box", "box", "box")
  796. def opimpl_unicodesetitem(self, unicodebox, indexbox, newcharbox):
  797. self.execute(rop.UNICODESETITEM, unicodebox, indexbox, newcharbox)
  798. @arguments("box")
  799. def opimpl_newstr(self, lengthbox):
  800. return self.execute(rop.NEWSTR, lengthbox)
  801. @arguments("box")
  802. def opimpl_newunicode(self, lengthbox):
  803. return self.execute(rop.NEWUNICODE, lengthbox)
  804. @arguments("box", "box", "box", "box", "box")
  805. def opimpl_copystrcontent(self, srcbox, dstbox, srcstartbox, dststartbox, lengthbox):
  806. return self.execute(rop.COPYSTRCONTENT, srcbox, dstbox, srcstartbox, dststartbox, lengthbox)
  807. @arguments("box", "box", "box", "box", "box")
  808. def opimpl_copyunicodecontent(self, srcbox, dstbox, srcstartbox, dststartbox, lengthbox):
  809. return self.execute(rop.COPYUNICODECONTENT, srcbox, dstbox, srcstartbox, dststartbox, lengthbox)
  810. @arguments("box", "orgpc")
  811. def _opimpl_guard_value(self, box, orgpc):
  812. self.implement_guard_value(box, orgpc)
  813. @arguments("box", "box", "descr", "orgpc")
  814. def opimpl_str_guard_value(self, box, funcbox, descr, orgpc):
  815. if isinstance(box, Const):
  816. return box # no promotion needed, already a Const
  817. else:
  818. constbox = box.constbox()
  819. resbox = self.do_residual_call(funcbox, [box, constbox], descr)
  820. promoted_box = resbox.constbox()
  821. # This is GUARD_VALUE because GUARD_TRUE assumes the existance
  822. # of a label when computing resumepc
  823. self.generate_guard(rop.GUARD_VALUE, resbox, [promoted_box],
  824. resumepc=orgpc)
  825. self.metainterp.replace_box(box, constbox)
  826. return constbox
  827. opimpl_int_guard_value = _opimpl_guard_value
  828. opimpl_ref_guard_value = _opimpl_guard_value
  829. opimpl_float_guard_value = _opimpl_guard_value
  830. @arguments("box", "orgpc")
  831. def opimpl_guard_class(self, box, orgpc):
  832. clsbox = self.cls_of_box(box)
  833. if not self.metainterp.heapcache.is_class_known(box):
  834. self.generate_guard(rop.GUARD_CLASS, box, [clsbox], resumepc=orgpc)
  835. self.metainterp.heapcache.class_now_known(box)
  836. return clsbox
  837. @arguments("int", "orgpc")
  838. def opimpl_loop_header(self, jdindex, orgpc):
  839. self.metainterp.seen_loop_header_for_jdindex = jdindex
  840. def verify_green_args(self, jitdriver_sd, varargs):
  841. num_green_args = jitdriver_sd.num_green_args
  842. assert len(varargs) == num_green_args
  843. for i in range(num_green_args):
  844. assert isinstance(varargs[i], Const)
  845. @arguments("int", "boxes3", "jitcode_position", "boxes3", "orgpc")
  846. def opimpl_jit_merge_point(self, jdindex, greenboxes,
  847. jcposition, redboxes, orgpc):
  848. resumedescr = compile.ResumeAtPositionDescr()
  849. self.capture_resumedata(resumedescr, orgpc)
  850. any_operation = len(self.metainterp.history.operations) > 0
  851. jitdriver_sd = self.metainterp.staticdata.jitdrivers_sd[jdindex]
  852. self.verify_green_args(jitdriver_sd, greenboxes)
  853. self.debug_merge_point(jitdriver_sd, jdindex,
  854. self.metainterp.portal_call_depth,
  855. self.metainterp.call_ids[-1],
  856. greenboxes)
  857. if self.metainterp.seen_loop_header_for_jdindex < 0:
  858. if not any_operation:
  859. return
  860. if self.metainterp.portal_call_depth or not self.metainterp.get_procedure_token(greenboxes, True):
  861. if not jitdriver_sd.no_loop_header:
  862. return
  863. # automatically add a loop_header if there is none
  864. self.metainterp.seen_loop_header_for_jdindex = jdindex
  865. #
  866. assert self.metainterp.seen_loop_header_for_jdindex == jdindex, (
  867. "found a loop_header for a JitDriver that does not match "
  868. "the following jit_merge_point's")
  869. self.metainterp.seen_loop_header_for_jdindex = -1
  870. #
  871. if not self.metainterp.portal_call_depth:
  872. assert jitdriver_sd is self.metainterp.jitdriver_sd
  873. # Set self.pc to point to jit_merge_point instead of just after:
  874. # if reached_loop_header() raises SwitchToBlackhole, then the
  875. # pc is still at the jit_merge_point, which is a point that is
  876. # much less expensive to blackhole out of.
  877. saved_pc = self.pc
  878. self.pc = orgpc
  879. self.metainterp.reached_loop_header(greenboxes, redboxes, resumedescr)
  880. self.pc = saved_pc
  881. # no exception, which means that the jit_merge_point did not
  882. # close the loop. We have to put the possibly-modified list
  883. # 'redboxes' back into the registers where it comes from.
  884. put_back_list_of_boxes3(self, jcposition, redboxes)
  885. else:
  886. if jitdriver_sd.warmstate.should_unroll_one_iteration(greenboxes):
  887. if self.unroll_iterations > 0:
  888. self.unroll_iterations -= 1
  889. return
  890. # warning! careful here. We have to return from the current
  891. # frame containing the jit_merge_point, and then use
  892. # do_recursive_call() to follow the recursive call. This is
  893. # needed because do_recursive_call() will write its result
  894. # with make_result_of_lastop(), so the lastop must be right:
  895. # it must be the call to 'self', and not the jit_merge_point
  896. # itself, which has no result at all.
  897. assert len(self.metainterp.framestack) >= 2
  898. try:
  899. self.metainterp.finishframe(None)
  900. except ChangeFrame:
  901. pass
  902. frame = self.metainterp.framestack[-1]
  903. frame.do_recursive_call(jitdriver_sd, greenboxes + redboxes,
  904. assembler_call=True)
  905. raise ChangeFrame
  906. def debug_merge_point(self, jitdriver_sd, jd_index, portal_call_depth, current_call_id, greenkey):
  907. # debugging: produce a DEBUG_MERGE_POINT operation
  908. loc = jitdriver_sd.warmstate.get_location_str(greenkey)
  909. debug_print(loc)
  910. args = [ConstInt(jd_index), ConstInt(portal_call_depth), ConstInt(current_call_id)] + greenkey
  911. self.metainterp.history.record(rop.DEBUG_MERGE_POINT, args, None)
  912. @arguments("box", "label")
  913. def opimpl_goto_if_exception_mismatch(self, vtablebox, next_exc_target):
  914. metainterp = self.metainterp
  915. last_exc_value_box = metainterp.last_exc_value_box
  916. assert last_exc_value_box is not None
  917. assert metainterp.class_of_last_exc_is_const
  918. if not metainterp.cpu.ts.instanceOf(last_exc_value_box, vtablebox):
  919. self.pc = next_exc_target
  920. @arguments("box", "orgpc")
  921. def opimpl_raise(self, exc_value_box, orgpc):
  922. # xxx hack
  923. clsbox = self.cls_of_box(exc_value_box)
  924. self.generate_guard(rop.GUARD_CLASS, exc_value_box, [clsbox],
  925. resumepc=orgpc)
  926. self.metainterp.class_of_last_exc_is_const = True
  927. self.metainterp.last_exc_value_box = exc_value_box
  928. self.metainterp.popframe()
  929. self.metainterp.finishframe_exception()
  930. @arguments()
  931. def opimpl_reraise(self):
  932. assert self.metainterp.last_exc_value_box is not None
  933. self.metainterp.popframe()
  934. self.metainterp.finishframe_exception()
  935. @arguments()
  936. def opimpl_last_exception(self):
  937. # Same comment as in opimpl_goto_if_exception_mismatch().
  938. exc_value_box = self.metainterp.last_exc_value_box
  939. assert exc_value_box is not None
  940. assert self.metainterp.class_of_last_exc_is_const
  941. return self.metainterp.cpu.ts.cls_of_box(exc_value_box)
  942. @arguments()
  943. def opimpl_last_exc_value(self):
  944. exc_value_box = self.metainterp.last_exc_value_box
  945. assert exc_value_box is not None
  946. return exc_value_box
  947. @arguments("box")
  948. def opimpl_debug_fatalerror(self, box):
  949. from rpython.rtyper.lltypesystem import rstr, lloperation
  950. msg = box.getref(lltype.Ptr(rstr.STR))
  951. lloperation.llop.debug_fatalerror(msg)
  952. @arguments("box", "box", "box", "box", "box")
  953. def opimpl_jit_debug(self, stringbox, arg1box, arg2box, arg3box, arg4box):
  954. from rpython.rtyper.lltypesystem import rstr
  955. from rpython.rtyper.annlowlevel import hlstr
  956. msg = stringbox.getref(lltype.Ptr(rstr.STR))
  957. debug_print('jit_debug:', hlstr(msg),
  958. arg1box.getint(), arg2box.getint(),
  959. arg3box.getint(), arg4box.getint())
  960. args = [stringbox, arg1box, arg2box, arg3box, arg4box]
  961. i = 4
  962. while i > 0 and args[i].getint() == -sys.maxint-1:
  963. i -= 1
  964. assert i >= 0
  965. op = self.metainterp.history.record(rop.JIT_DEBUG, args[:i+1], None)
  966. self.metainterp.attach_debug_info(op)
  967. @arguments("box")
  968. def _opimpl_assert_green(self, box):
  969. if not isinstance(box, Const):
  970. msg = "assert_green failed at %s:%d" % (
  971. self.jitcode.name,
  972. self.pc)
  973. if we_are_translated():
  974. from rpython.rtyper.annlowlevel import llstr
  975. from rpython.rtyper.lltypesystem import lloperation
  976. lloperation.llop.debug_fatalerror(lltype.Void, llstr(msg))
  977. else:
  978. from rpython.rlib.jit import AssertGreenFailed
  979. raise AssertGreenFailed(msg)
  980. opimpl_int_assert_green = _opimpl_assert_green
  981. opimpl_ref_assert_green = _opimpl_assert_green
  982. opimpl_float_assert_green = _opimpl_assert_green
  983. @arguments()
  984. def opimpl_current_trace_length(self):
  985. trace_length = len(self.metainterp.history.operations)
  986. return ConstInt(trace_length)
  987. @arguments("box")
  988. def _opimpl_isconstant(self, box):
  989. return ConstInt(isinstance(box, Const))
  990. opimpl_int_isconstant = opimpl_ref_isconstant = _opimpl_isconstant
  991. @arguments("box")
  992. def _opimpl_isvirtual(self, box):
  993. return ConstInt(self.metainterp.heapcache.is_unescaped(box))
  994. opimpl_ref_isvirtual = _opimpl_isvirtual
  995. @arguments("box")
  996. def opimpl_virtual_ref(self, box):
  997. # Details on the content of metainterp.virtualref_boxes:
  998. #
  999. # * it's a list whose items go two by two, containing first the
  1000. # virtual box (e.g. the PyFrame) and then the vref box (e.g.
  1001. # the 'virtual_ref(frame)').
  1002. #
  1003. # * if we detect that the virtual box escapes during tracing
  1004. # already (by generating a CALL_MAY_FORCE that marks the flags
  1005. # in the vref), then we replace the vref in the list with
  1006. # ConstPtr(NULL).
  1007. #
  1008. metainterp = self.metainterp
  1009. vrefinfo = metainterp.staticdata.virtualref_info
  1010. obj = box.getref_base()
  1011. vref = vrefinfo.virtual_ref_during_tracing(obj)
  1012. resbox = history.BoxPtr(vref)
  1013. cindex = history.ConstInt(len(metainterp.virtualref_boxes) // 2)
  1014. metainterp.history.record(rop.VIRTUAL_REF, [box, cindex], resbox)
  1015. # Note: we allocate a JIT_VIRTUAL_REF here
  1016. # (in virtual_ref_during_tracing()), in order to detect when
  1017. # the virtual escapes during tracing already. We record it as a
  1018. # VIRTUAL_REF operation. Later, optimizeopt.py should either kill
  1019. # that operation or replace it with a NEW_WITH_VTABLE followed by
  1020. # SETFIELD_GCs.
  1021. metainterp.virtualref_boxes.append(box)
  1022. metainterp.virtualref_boxes.append(resbox)
  1023. return resbox
  1024. @arguments("box")
  1025. def opimpl_virtual_ref_finish(self, box):
  1026. # virtual_ref_finish() assumes that we have a stack-like, last-in
  1027. # first-out order.
  1028. metainterp = self.metainterp
  1029. vrefbox = metainterp.virtualref_boxes.pop()
  1030. lastbox = metainterp.virtualref_boxes.pop()
  1031. assert box.getref_base() == lastbox.getref_base()
  1032. vrefinfo = metainterp.staticdata.virtualref_info
  1033. vref = vrefbox.getref_base()
  1034. if vrefinfo.is_virtual_ref(vref):
  1035. # XXX write a comment about nullbox
  1036. nullbox = self.metainterp.cpu.ts.CONST_NULL
  1037. metainterp.history.record(rop.VIRTUAL_REF_FINISH,
  1038. [vrefbox, nullbox], None)
  1039. @arguments()
  1040. def opimpl_ll_read_timestamp(self):
  1041. return self.metainterp.execute_and_record(rop.READ_TIMESTAMP, None)
  1042. # ------------------------------
  1043. def setup_call(self, argboxes):
  1044. self.pc = 0
  1045. count_i = count_r = count_f = 0
  1046. for box in argboxes:
  1047. if box.type == history.INT:
  1048. self.registers_i[count_i] = box
  1049. count_i += 1
  1050. elif box.type == history.REF:
  1051. self.registers_r[count_r] = box
  1052. count_r += 1
  1053. elif box.type == history.FLOAT:
  1054. self.registers_f[count_f] = box
  1055. count_f += 1
  1056. else:
  1057. raise AssertionError(box.type)
  1058. def setup_resume_at_op(self, pc):
  1059. self.pc = pc
  1060. ## values = ' '.join([box.repr_rpython() for box in self.env])
  1061. ## log('setup_resume_at_op %s:%d [%s] %d' % (self.jitcode.name,
  1062. ## self.pc, values,
  1063. ## self.exception_target))
  1064. def run_one_step(self):
  1065. # Execute the frame forward. This method contains a loop that leaves
  1066. # whenever the 'opcode_implementations' (which is one of the 'opimpl_'
  1067. # methods) raises ChangeFrame. This is the case when the current frame
  1068. # changes, due to a call or a return.
  1069. try:
  1070. staticdata = self.metainterp.staticdata
  1071. while True:
  1072. pc = self.pc
  1073. op = ord(self.bytecode[pc])
  1074. #debug_print(self.jitcode.name, pc)
  1075. #print staticdata.opcode_names[op]
  1076. staticdata.opcode_implementations[op](self, pc)
  1077. except ChangeFrame:
  1078. pass
  1079. def generate_guard(self, opnum, box=None, extraargs=[], resumepc=-1):
  1080. if isinstance(box, Const): # no need for a guard
  1081. return
  1082. metainterp = self.metainterp
  1083. if box is not None:
  1084. moreargs = [box] + extraargs
  1085. else:
  1086. moreargs = list(extraargs)
  1087. metainterp_sd = metainterp.staticdata
  1088. if opnum == rop.GUARD_NOT_FORCED:
  1089. resumedescr = compile.ResumeGuardForcedDescr(metainterp_sd,
  1090. metainterp.jitdriver_sd)
  1091. elif opnum == rop.GUARD_NOT_INVALIDATED:
  1092. resumedescr = compile.ResumeGuardNotInvalidated()
  1093. else:
  1094. resumedescr = compile.ResumeGuardDescr()
  1095. guard_op = metainterp.history.record(opnum, moreargs, None,
  1096. descr=resumedescr)
  1097. self.capture_resumedata(resumedescr, resumepc)
  1098. self.metainterp.staticdata.profiler.count_ops(opnum, Counters.GUARDS)
  1099. # count
  1100. metainterp.attach_debug_info(guard_op)
  1101. return guard_op
  1102. def capture_resumedata(self, resumedescr, resumepc=-1):
  1103. metainterp = self.metainterp
  1104. virtualizable_boxes = None
  1105. if (metainterp.jitdriver_sd.virtualizable_info is not None or
  1106. metainterp.jitdriver_sd.greenfield_info is not None):
  1107. virtualizable_boxes = metainterp.virtualizable_boxes
  1108. saved_pc = self.pc
  1109. if resumepc >= 0:
  1110. self.pc = resumepc
  1111. resume.capture_resumedata(metainterp.framestack, virtualizable_boxes,
  1112. metainterp.virtualref_boxes, resumedescr)
  1113. self.pc = saved_pc
  1114. def implement_guard_value(self, box, orgpc):
  1115. """Promote the given Box into a Const. Note: be careful, it's a
  1116. bit unclear what occurs if a single opcode needs to generate
  1117. several ones and/or ones not near the beginning."""
  1118. if isinstance(box, Const):
  1119. return box # no promotion needed, already a Const
  1120. else:
  1121. promoted_box = box.constbox()
  1122. self.generate_guard(rop.GUARD_VALUE, box, [promoted_box],
  1123. resumepc=orgpc)
  1124. self.metainterp.replace_box(box, promoted_box)
  1125. return promoted_box
  1126. def cls_of_box(self, box):
  1127. return self.metainterp.cpu.ts.cls_of_box(box)
  1128. @specialize.arg(1)
  1129. def execute(self, opnum, *argboxes):
  1130. return self.metainterp.execute_and_record(opnum, None, *argboxes)
  1131. @specialize.arg(1)
  1132. def execute_with_descr(self, opnum, descr, *argboxes):
  1133. return self.metainterp.execute_and_record(opnum, descr, *argboxes)
  1134. @specialize.arg(1)
  1135. def execute_varargs(self, opnum, argboxes, descr, exc, pure):
  1136. self.metainterp.clear_exception()
  1137. resbox = self.metainterp.execute_and_record_varargs(opnum, argboxes,
  1138. descr=descr)
  1139. if resbox is not None:
  1140. self.make_result_of_lastop(resbox)
  1141. # ^^^ this is done before handle_possible_exception() because we
  1142. # need the box to show up in get_list_of_active_boxes()
  1143. if pure and self.metainterp.last_exc_value_box is None:
  1144. resbox = self.metainterp.record_result_of_call_pure(resbox)
  1145. exc = exc and not isinstance(resbox, Const)
  1146. if exc:
  1147. self.metainterp.handle_possible_exception()
  1148. else:
  1149. self.metainterp.assert_no_exception()
  1150. return resbox
  1151. def do_residual_call(self, funcbox, argboxes, descr,
  1152. assembler_call=False,
  1153. assembler_call_jd=None):
  1154. # First build allboxes: it may need some reordering from the
  1155. # list provided in argboxes, depending on the order in which
  1156. # the arguments are expected by the function
  1157. allboxes = [None] * (len(argboxes)+1)
  1158. allboxes[0] = funcbox
  1159. src_i = src_r = src_f = 0
  1160. i = 1
  1161. for kind in descr.get_arg_types():
  1162. if kind == history.INT or kind == 'S': # single float
  1163. while True:
  1164. box = argboxes[src_i]
  1165. src_i += 1
  1166. if box.type == history.INT:
  1167. break
  1168. elif kind == history.REF:
  1169. while True:
  1170. box = argboxes[src_r]
  1171. src_r += 1
  1172. if box.type == history.REF:
  1173. break
  1174. elif kind == history.FLOAT or kind == 'L': # long long
  1175. while True:
  1176. box = argboxes[src_f]
  1177. src_f += 1
  1178. if box.type == history.FLOAT:
  1179. break
  1180. else:
  1181. raise AssertionError
  1182. allboxes[i] = box
  1183. i += 1
  1184. assert i == len(allboxes)
  1185. #
  1186. effectinfo = descr.get_extra_info()
  1187. if (assembler_call or
  1188. effectinfo.check_forces_virtual_or_virtualizable()):
  1189. # residual calls require attention to keep virtualizables in-sync
  1190. self.metainterp.clear_exception()
  1191. self.metainterp.vable_and_vrefs_before_residual_call()
  1192. resbox = self.metainterp.execute_and_record_varargs(
  1193. rop.CALL_MAY_FORCE, allboxes, descr=descr)
  1194. if effectinfo.is_call_release_gil():
  1195. self.metainterp.direct_call_release_gil()
  1196. self.metainterp.vrefs_after_residual_call()
  1197. vablebox = None
  1198. if assembler_call:
  1199. vablebox = self.metainterp.direct_assembler_call(
  1200. assembler_call_jd)
  1201. if resbox is not None:
  1202. self.make_result_of_lastop(resbox)
  1203. self.metainterp.vable_after_residual_call()
  1204. self.generate_guard(rop.GUARD_NOT_FORCED, None)
  1205. if vablebox is not None:
  1206. self.metainterp.history.record(rop.KEEPALIVE, [vablebox], None)
  1207. self.metainterp.handle_possible_exception()
  1208. # XXX refactor: direct_libffi_call() is a hack
  1209. if effectinfo.oopspecindex == effectinfo.OS_LIBFFI_CALL:
  1210. self.metainterp.direct_libffi_call()
  1211. return resbox
  1212. else:
  1213. effect = effectinfo.extraeffect
  1214. if effect == effectinfo.EF_LOOPINVARIANT:
  1215. return self.execute_varargs(rop.CALL_LOOPINVARIANT, allboxes,
  1216. descr, False, False)
  1217. exc = effectinfo.check_can_raise()
  1218. pure = effectinfo.check_is_elidable()
  1219. return self.execute_varargs(rop.CALL, allboxes, descr, exc, pure)
  1220. def do_residual_or_indirect_call(self, funcbox, argboxes, calldescr):
  1221. """The 'residual_call' operation is emitted in two cases:
  1222. when we have to generate a residual CALL operation, but also
  1223. to handle an indirect_call that may need to be inlined."""
  1224. if isinstance(funcbox, Const):
  1225. sd = self.metainterp.staticdata
  1226. key = sd.cpu.ts.getaddr_for_box(funcbox)
  1227. jitcode = sd.bytecode_for_address(key)
  1228. if jitcode is not None:
  1229. # we should follow calls to this graph
  1230. return self.metainterp.perform_call(jitcode, argboxes)
  1231. # but we should not follow calls to that graph
  1232. return self.do_residual_call(funcbox, argboxes, calldescr)
  1233. # ____________________________________________________________
  1234. class MetaInterpStaticData(object):
  1235. logger_noopt = None
  1236. logger_ops = None
  1237. def __init__(self, cpu, options,
  1238. ProfilerClass=EmptyProfiler, warmrunnerdesc=None):
  1239. self.cpu = cpu
  1240. self.stats = self.cpu.stats
  1241. self.options = options
  1242. self.logger_noopt = Logger(self)
  1243. self.logger_ops = Logger(self, guard_number=True)
  1244. self.profiler = ProfilerClass()
  1245. self.profiler.cpu = cpu
  1246. self.warmrunnerdesc = warmrunnerdesc
  1247. if warmrunnerdesc:
  1248. self.config = warmrunnerdesc.translator.config
  1249. else:
  1250. from rpython.config.translationoption import get_combined_translation_config
  1251. self.config = get_combined_translation_config(translating=True)
  1252. backendmodule = self.cpu.__module__
  1253. backendmodule = backendmodule.split('.')[-2]
  1254. self.jit_starting_line = 'JIT starting (%s)' % backendmodule
  1255. self._addr2name_keys = []
  1256. self._addr2name_values = []
  1257. self.__dict__.update(compile.make_done_loop_tokens())
  1258. def _freeze_(self):
  1259. return True
  1260. def setup_insns(self, insns):
  1261. self.opcode_names = ['?'] * len(insns)
  1262. self.opcode_implementations = [None] * len(insns)
  1263. for key, value in insns.items():
  1264. assert self.opcode_implementations[value] is None
  1265. self.opcode_names[value] = key
  1266. name, argcodes = key.split('/')
  1267. opimpl = _get_opimpl_method(name, argcodes)
  1268. self.opcode_implementations[value] = opimpl
  1269. self.op_catch_exception = insns.get('catch_exception/L', -1)
  1270. def setup_descrs(self, descrs):
  1271. self.opcode_descrs = descrs
  1272. def setup_indirectcalltargets(self, indirectcalltargets):
  1273. self.indirectcalltargets = list(indirectcalltargets)
  1274. def setup_list_of_addr2name(self, list_of_addr2name):
  1275. self._addr2name_keys = [key for key, value in list_of_addr2name]
  1276. self._addr2name_values = [value for key, value in list_of_addr2name]
  1277. def finish_setup(self, codewriter, optimizer=None):
  1278. from rpython.jit.metainterp.blackhole import BlackholeInterpBuilder
  1279. self.blackholeinterpbuilder = BlackholeInterpBuilder(codewriter, self)
  1280. #
  1281. asm = codewriter.assembler
  1282. self.setup_insns(asm.insns)
  1283. self.setup_descrs(asm.descrs)
  1284. self.setup_indirectcalltargets(asm.indirectcalltargets)
  1285. self.setup_list_of_addr2name(asm.list_of_addr2name)
  1286. #
  1287. self.jitdrivers_sd = codewriter.callcontrol.jitdrivers_sd
  1288. self.virtualref_info = codewriter.callcontrol.virtualref_info
  1289. self.callinfocollection = codewriter.callcontrol.callinfocollection
  1290. self.has_libffi_call = codewriter.callcontrol.has_libffi_call
  1291. #
  1292. # store this information for fastpath of call_assembler
  1293. # (only the paths that can actually be taken)
  1294. exc_descr = compile.PropagateExceptionDescr()
  1295. for jd in self.jitdrivers_sd:
  1296. name = {history.INT: 'int',
  1297. history.REF: 'ref',
  1298. history.FLOAT: 'float',
  1299. history.VOID: 'void'}[jd.result_type]
  1300. tokens = getattr(self, 'loop_tokens_done_with_this_frame_%s' % name)
  1301. jd.portal_finishtoken = tokens[0].finishdescr
  1302. num = self.cpu.get_fail_descr_number(tokens[0].finishdescr)
  1303. setattr(self.cpu, 'done_with_this_frame_%s_v' % name, num)
  1304. jd.propagate_exc_descr = exc_descr
  1305. #
  1306. num = self.cpu.get_fail_descr_number(exc_descr)
  1307. self.cpu.propagate_exception_v = num
  1308. #
  1309. self.globaldata = MetaInterpGlobalData(self)
  1310. def _setup_once(self):
  1311. """Runtime setup needed by the various components of the JIT."""
  1312. if not self.globaldata.initialized:
  1313. debug_print(self.jit_starting_line)
  1314. self.cpu.setup_once()
  1315. if not self.profiler.initialized:
  1316. self.profiler.start()
  1317. self.profiler.initialized = True
  1318. self.globaldata.initialized = True
  1319. def get_name_from_address(self, addr):
  1320. # for debugging only
  1321. if we_are_translated():
  1322. d = self.globaldata.addr2name
  1323. if d is None:
  1324. # Build the dictionary at run-time. This is needed
  1325. # because the keys are function/class addresses, so they
  1326. # can change from run to run.
  1327. d = {}
  1328. keys = self._addr2name_keys
  1329. values = self._addr2name_values
  1330. for i in range(len(keys)):
  1331. d[keys[i]] = values[i]
  1332. self.globaldata.addr2name = d
  1333. return d.get(addr, '')
  1334. else:
  1335. for i in range(len(self._addr2name_keys)):
  1336. if addr == self._addr2name_keys[i]:
  1337. return self._addr2name_values[i]
  1338. return ''
  1339. def bytecode_for_address(self, fnaddress):
  1340. if we_are_translated():
  1341. d = self.globaldata.indirectcall_dict
  1342. if d is None:
  1343. # Build the dictionary at run-time. This is needed
  1344. # because the keys are function addresses, so they
  1345. # can change from run to run.
  1346. d = {}
  1347. for jitcode in self.indirectcalltargets:
  1348. assert jitcode.fnaddr not in d
  1349. d[jitcode.fnaddr] = jitcode
  1350. self.globaldata.indirectcall_dict = d
  1351. return d.get(fnaddress, None)
  1352. else:
  1353. for jitcode in self.indirectcalltargets:
  1354. if jitcode.fnaddr == fnaddress:
  1355. return jitcode
  1356. return None
  1357. def try_to_free_some_loops(self):
  1358. # Increase here the generation recorded by the memory manager.
  1359. if self.warmrunnerdesc is not None: # for tests
  1360. self.warmrunnerdesc.memory_manager.next_generation()
  1361. # ---------------- logging ------------------------
  1362. def log(self, msg):
  1363. debug_print(msg)
  1364. # ____________________________________________________________
  1365. class MetaInterpGlobalData(object):
  1366. """This object contains the JIT's global, mutable data.
  1367. Warning: for any data that you put here, think that there might be
  1368. multiple MetaInterps accessing it at the same time. As usual we are
  1369. safe from corruption thanks to the GIL, but keep in mind that any
  1370. MetaInterp might modify any of these fields while another MetaInterp
  1371. is, say, currently in a residual call to a function. Multiple
  1372. MetaInterps occur either with threads or, in single-threaded cases,
  1373. with recursion. This is a case that is not well-tested, so please
  1374. be careful :-( But thankfully this is one of the very few places
  1375. where multiple concurrent MetaInterps may interact with each other.
  1376. """
  1377. def __init__(self, staticdata):
  1378. self.initialized = False
  1379. self.indirectcall_dict = None
  1380. self.addr2name = None
  1381. self.loopnumbering = 0
  1382. # ____________________________________________________________
  1383. class MetaInterp(object):
  1384. portal_call_depth = 0
  1385. cancel_count = 0
  1386. def __init__(self, staticdata, jitdriver_sd):
  1387. self.staticdata = staticdata
  1388. self.cpu = staticdata.cpu
  1389. self.jitdriver_sd = jitdriver_sd
  1390. # Note: self.jitdriver_sd is the JitDriverStaticData that corresponds
  1391. # to the current loop -- the outermost one. Be careful, because
  1392. # during recursion we can also see other jitdrivers.
  1393. self.portal_trace_positions = []
  1394. self.free_frames_list = []
  1395. self.last_exc_value_box = None
  1396. self.partial_trace = None
  1397. self.retracing_from = -1
  1398. self.call_pure_results = args_dict_box()
  1399. self.heapcache = HeapCache()
  1400. self.call_ids = []
  1401. self.current_call_id = 0
  1402. def retrace_needed(self, trace):
  1403. self.partial_trace = trace
  1404. self.retracing_from = len(self.history.operations) - 1
  1405. self.heapcache.reset()
  1406. def perform_call(self, jitcode, boxes, greenkey=None):
  1407. # causes the metainterp to enter the given subfunction
  1408. f = self.newframe(jitcode, greenkey)
  1409. f.setup_call(boxes)
  1410. raise ChangeFrame
  1411. def is_main_jitcode(self, jitcode):
  1412. return self.jitdriver_sd is not None and jitcode is self.jitdriver_sd.mainjitcode
  1413. def newframe(self, jitcode, greenkey=None):
  1414. if jitcode.is_portal:
  1415. self.portal_call_depth += 1
  1416. self.call_ids.append(self.current_call_id)
  1417. self.current_call_id += 1
  1418. if greenkey is not None and self.is_main_jitcode(jitcode):
  1419. self.portal_trace_positions.append(
  1420. (greenkey, len(self.history.operations)))
  1421. if len(self.free_frames_list) > 0:
  1422. f = self.free_frames_list.pop()
  1423. else:
  1424. f = MIFrame(self)
  1425. f.setup(jitcode, greenkey)
  1426. self.framestack.append(f)
  1427. return f
  1428. def popframe(self):
  1429. frame = self.framestack.pop()
  1430. jitcode = frame.jitcode
  1431. if jitcode.is_portal:
  1432. self.portal_call_depth -= 1
  1433. self.call_ids.pop()
  1434. if frame.greenkey is not None and self.is_main_jitcode(jitcode):
  1435. self.portal_trace_positions.append(
  1436. (None, len(self.history.operations)))
  1437. # we save the freed MIFrames to avoid needing to re-create new
  1438. # MIFrame objects all the time; they are a bit big, with their
  1439. # 3*256 register entries.
  1440. frame.cleanup_registers()
  1441. self.free_frames_list.append(frame)
  1442. def finishframe(self, resultbox):
  1443. # handle a non-exceptional return from the current frame
  1444. self.last_exc_value_box = None
  1445. self.popframe()
  1446. if self.framestack:
  1447. if resultbox is not None:
  1448. self.framestack[-1].make_result_of_lastop(resultbox)
  1449. raise ChangeFrame
  1450. else:
  1451. try:
  1452. self.compile_done_with_this_frame(resultbox)
  1453. except SwitchToBlackhole, stb:
  1454. self.aborted_tracing(stb.reason)
  1455. sd = self.staticdata
  1456. result_type = self.jitdriver_sd.result_type
  1457. if result_type == history.VOID:
  1458. assert resultbox is None
  1459. raise sd.DoneWithThisFrameVoid()
  1460. elif result_type == history.INT:
  1461. raise sd.DoneWithThisFrameInt(resultbox.getint())
  1462. elif result_type == history.REF:
  1463. raise sd.DoneWithThisFrameRef(self.cpu, resultbox.getref_base())
  1464. elif result_type == history.FLOAT:
  1465. raise sd.DoneWithThisFrameFloat(resultbox.getfloatstorage())
  1466. else:
  1467. assert False
  1468. def finishframe_exception(self):
  1469. excvaluebox = self.last_exc_value_box
  1470. while self.framestack:
  1471. frame = self.framestack[-1]
  1472. code = frame.bytecode
  1473. position = frame.pc # <-- just after the insn that raised
  1474. if position < len(code):
  1475. opcode = ord(code[position])
  1476. if opcode == self.staticdata.op_catch_exception:
  1477. # found a 'catch_exception' instruction;
  1478. # jump to the handler
  1479. target = ord(code[position+1]) | (ord(code[position+2])<<8)
  1480. frame.pc = target
  1481. raise ChangeFrame
  1482. self.popframe()
  1483. try:
  1484. self.compile_exit_frame_with_exception(excvaluebox)
  1485. except SwitchToBlackhole, stb:
  1486. self.aborted_tracing(stb.reason)
  1487. raise self.staticdata.ExitFrameWithExceptionRef(self.cpu, excvaluebox.getref_base())
  1488. def check_recursion_invariant(self):
  1489. portal_call_depth = -1
  1490. for frame in self.framestack:
  1491. jitcode = frame.jitcode
  1492. assert jitcode.is_portal == len([
  1493. jd for jd in self.staticdata.jitdrivers_sd
  1494. if jd.mainjitcode is jitcode])
  1495. if jitcode.is_portal:
  1496. portal_call_depth += 1
  1497. if portal_call_depth != self.portal_call_depth:
  1498. print "portal_call_depth problem!!!"
  1499. print portal_call_depth, self.portal_call_depth
  1500. for frame in self.framestack:
  1501. jitcode = frame.jitcode
  1502. if jitcode.is_portal:
  1503. print "P",
  1504. else:
  1505. print " ",
  1506. print jitcode.name
  1507. raise AssertionError
  1508. def create_empty_history(self):
  1509. self.history = history.History()
  1510. self.staticdata.stats.set_history(self.history)
  1511. def _all_constants(self, *boxes):
  1512. if len(boxes) == 0:
  1513. return True
  1514. return isinstance(boxes[0], Const) and self._all_constants(*boxes[1:])
  1515. def _all_constants_varargs(self, boxes):
  1516. for box in boxes:
  1517. if not isinstance(box, Const):
  1518. return False
  1519. return True
  1520. @specialize.arg(1)
  1521. def execute_and_record(self, opnum, descr, *argboxes):
  1522. history.check_descr(descr)
  1523. assert not (rop._CANRAISE_FIRST <= opnum <= rop._CANRAISE_LAST)
  1524. # execute the operation
  1525. profiler = self.staticdata.profiler
  1526. profiler.count_ops(opnum)
  1527. resbox = executor.execute(self.cpu, self, opnum, descr, *argboxes)
  1528. if rop._ALWAYS_PURE_FIRST <= opnum <= rop._ALWAYS_PURE_LAST:
  1529. return self._record_helper_pure(opnum, resbox, descr, *argboxes)
  1530. else:
  1531. return self._record_helper_nonpure_varargs(opnum, resbox, descr,
  1532. list(argboxes))
  1533. @specialize.arg(1)
  1534. def execute_and_record_varargs(self, opnum, argboxes, descr=None):
  1535. history.check_descr(descr)
  1536. # execute the operation
  1537. profiler = self.staticdata.profiler
  1538. profiler.count_ops(opnum)
  1539. resbox = executor.execute_varargs(self.cpu, self,
  1540. opnum, argboxes, descr)
  1541. # check if the operation can be constant-folded away
  1542. argboxes = list(argboxes)
  1543. if rop._ALWAYS_PURE_FIRST <= opnum <= rop._ALWAYS_PURE_LAST:
  1544. resbox = self._record_helper_pure_varargs(opnum, resbox, descr, argboxes)
  1545. else:
  1546. resbox = self._record_helper_nonpure_varargs(opnum, resbox, descr, argboxes)
  1547. return resbox
  1548. def _record_helper_pure(self, opnum, resbox, descr, *argboxes):
  1549. canfold = self._all_constants(*argboxes)
  1550. if canfold:
  1551. resbox = resbox.constbox() # ensure it is a Const
  1552. return resbox
  1553. else:
  1554. resbox = resbox.nonconstbox() # ensure it is a Box
  1555. return self._record_helper_nonpure_varargs(opnum, resbox, descr, list(argboxes))
  1556. def _record_helper_pure_varargs(self, opnum, resbox, descr, argboxes):
  1557. canfold = self._all_constants_varargs(argboxes)
  1558. if canfold:
  1559. resbox = resbox.constbox() # ensure it is a Const
  1560. return resbox
  1561. else:
  1562. resbox = resbox.nonconstbox() # ensure it is a Box
  1563. return self._record_helper_nonpure_varargs(opnum, resbox, descr, argboxes)
  1564. def _record_helper_nonpure_varargs(self, opnum, resbox, descr, argboxes):
  1565. assert resbox is None or isinstance(resbox, Box)
  1566. if (rop._OVF_FIRST <= opnum <= rop._OVF_LAST and
  1567. self.last_exc_value_box is None and
  1568. self._all_constants_varargs(argboxes)):
  1569. return resbox.constbox()
  1570. # record the operation
  1571. profiler = self.staticdata.profiler
  1572. profiler.count_ops(opnum, Counters.RECORDED_OPS)
  1573. self.heapcache.invalidate_caches(opnum, descr, argboxes)
  1574. op = self.history.record(opnum, argboxes, resbox, descr)
  1575. self.attach_debug_info(op)
  1576. return resbox
  1577. def attach_debug_info(self, op):
  1578. if (not we_are_translated() and op is not None
  1579. and getattr(self, 'framestack', None)):
  1580. op.pc = self.framestack[-1].pc
  1581. op.name = self.framestack[-1].jitcode.name
  1582. def execute_raised(self, exception, constant=False):
  1583. if isinstance(exception, JitException):
  1584. raise JitException, exception # go through
  1585. llexception = get_llexception(self.cpu, exception)
  1586. self.execute_ll_raised(llexception, constant)
  1587. def execute_ll_raised(self, llexception, constant=False):
  1588. # Exception handling: when execute.do_call() gets an exception it
  1589. # calls metainterp.execute_raised(), which puts it into
  1590. # 'self.last_exc_value_box'. This is used shortly afterwards
  1591. # to generate either GUARD_EXCEPTION or GUARD_NO_EXCEPTION, and also
  1592. # to handle the following opcodes 'goto_if_exception_mismatch'.
  1593. llexception = self.cpu.ts.cast_to_ref(llexception)
  1594. exc_value_box = self.cpu.ts.get_exc_value_box(llexception)
  1595. if constant:
  1596. exc_value_box = exc_value_box.constbox()
  1597. self.last_exc_value_box = exc_value_box
  1598. self.class_of_last_exc_is_const = constant
  1599. # 'class_of_last_exc_is_const' means that the class of the value
  1600. # stored in the exc_value Box can be assumed to be a Const. This
  1601. # is only True after a GUARD_EXCEPTION or GUARD_CLASS.
  1602. def clear_exception(self):
  1603. self.last_exc_value_box = None
  1604. def aborted_tracing(self, reason):
  1605. self.staticdata.profiler.count(reason)
  1606. debug_print('~~~ ABORTING TRACING')
  1607. jd_sd = self.jitdriver_sd
  1608. if not self.current_merge_points:
  1609. greenkey = None # we're in the bridge
  1610. else:
  1611. greenkey = self.current_merge_points[0][0][:jd_sd.num_green_args]
  1612. self.staticdata.warmrunnerdesc.hooks.on_abort(reason,
  1613. jd_sd.jitdriver,
  1614. greenkey,
  1615. jd_sd.warmstate.get_location_str(greenkey))
  1616. self.staticdata.stats.aborted()
  1617. def blackhole_if_trace_too_long(self):
  1618. warmrunnerstate = self.jitdriver_sd.warmstate
  1619. if len(self.history.operations) > warmrunnerstate.trace_limit:
  1620. greenkey_of_huge_function = self.find_biggest_function()
  1621. self.staticdata.stats.record_aborted(greenkey_of_huge_function)
  1622. self.portal_trace_positions = None
  1623. if greenkey_of_huge_function is not None:
  1624. warmrunnerstate.disable_noninlinable_function(
  1625. greenkey_of_huge_function)
  1626. raise SwitchToBlackhole(Counters.ABORT_TOO_LONG)
  1627. def _interpret(self):
  1628. # Execute the frames forward until we raise a DoneWithThisFrame,
  1629. # a ExitFrameWithException, or a ContinueRunningNormally exception.
  1630. self.staticdata.stats.entered()
  1631. while True:
  1632. self.framestack[-1].run_one_step()
  1633. self.blackhole_if_trace_too_long()
  1634. if not we_are_translated():
  1635. self.check_recursion_invariant()
  1636. def interpret(self):
  1637. if we_are_translated():
  1638. self._interpret()
  1639. else:
  1640. try:
  1641. self._interpret()
  1642. except:
  1643. import sys
  1644. if sys.exc_info()[0] is not None:
  1645. self.staticdata.log(sys.exc_info()[0].__name__)
  1646. raise
  1647. @specialize.arg(1)
  1648. def compile_and_run_once(self, jitdriver_sd, *args):
  1649. # NB. we pass explicity 'jitdriver_sd' around here, even though it
  1650. # is also available as 'self.jitdriver_sd', because we need to
  1651. # specialize this function and a few other ones for the '*args'.
  1652. debug_start('jit-tracing')
  1653. self.staticdata._setup_once()
  1654. self.staticdata.profiler.start_tracing()
  1655. assert jitdriver_sd is self.jitdriver_sd
  1656. self.staticdata.try_to_free_some_loops()
  1657. self.create_empty_history()
  1658. try:
  1659. original_boxes = self.initialize_original_boxes(jitdriver_sd, *args)
  1660. return self._compile_and_run_once(original_boxes)
  1661. finally:
  1662. self.staticdata.profiler.end_tracing()
  1663. debug_stop('jit-tracing')
  1664. def _compile_and_run_once(self, original_boxes):
  1665. self.initialize_state_from_start(original_boxes)
  1666. self.current_merge_points = [(original_boxes, 0)]
  1667. num_green_args = self.jitdriver_sd.num_green_args
  1668. original_greenkey = original_boxes[:num_green_args]
  1669. self.resumekey = compile.ResumeFromInterpDescr(original_greenkey)
  1670. self.history.inputargs = original_boxes[num_green_args:]
  1671. self.seen_loop_header_for_jdindex = -1
  1672. try:
  1673. self.interpret()
  1674. except SwitchToBlackhole, stb:
  1675. self.run_blackhole_interp_to_cancel_tracing(stb)
  1676. assert False, "should always raise"
  1677. def handle_guard_failure(self, key, deadframe):
  1678. debug_start('jit-tracing')
  1679. self.staticdata.profiler.start_tracing()
  1680. assert isinstance(key, compile.ResumeGuardDescr)
  1681. # store the resumekey.wref_original_loop_token() on 'self' to make
  1682. # sure that it stays alive as long as this MetaInterp
  1683. self.resumekey_original_loop_token = key.wref_original_loop_token()
  1684. self.staticdata.try_to_free_some_loops()
  1685. self.initialize_state_from_guard_failure(key, deadframe)
  1686. try:
  1687. return self._handle_guard_failure(key, deadframe)
  1688. finally:
  1689. self.resumekey_original_loop_token = None
  1690. self.staticdata.profiler.end_tracing()
  1691. debug_stop('jit-tracing')
  1692. def _handle_guard_failure(self, key, deadframe):
  1693. self.current_merge_points = []
  1694. self.resumekey = key
  1695. self.seen_loop_header_for_jdindex = -1
  1696. if isinstance(key, compile.ResumeAtPositionDescr):
  1697. self.seen_loop_header_for_jdindex = self.jitdriver_sd.index
  1698. dont_change_position = True
  1699. else:
  1700. dont_change_position = False
  1701. try:
  1702. self.prepare_resume_from_failure(key.guard_opnum,
  1703. dont_change_position,
  1704. deadframe)
  1705. if self.resumekey_original_loop_token is None: # very rare case
  1706. raise SwitchToBlackhole(Counters.ABORT_BRIDGE)
  1707. self.interpret()
  1708. except SwitchToBlackhole, stb:
  1709. self.run_blackhole_interp_to_cancel_tracing(stb)
  1710. assert False, "should always raise"
  1711. def run_blackhole_interp_to_cancel_tracing(self, stb):
  1712. # We got a SwitchToBlackhole exception. Convert the framestack into
  1713. # a stack of blackhole interpreters filled with the same values, and
  1714. # run it.
  1715. from rpython.jit.metainterp.blackhole import convert_and_run_from_pyjitpl
  1716. self.aborted_tracing(stb.reason)
  1717. convert_and_run_from_pyjitpl(self, stb.raising_exception)
  1718. assert False # ^^^ must raise
  1719. def remove_consts_and_duplicates(self, boxes, endindex, duplicates):
  1720. for i in range(endindex):
  1721. box = boxes[i]
  1722. if isinstance(box, Const) or box in duplicates:
  1723. oldbox = box
  1724. box = oldbox.clonebox()
  1725. boxes[i] = box
  1726. self.history.record(rop.SAME_AS, [oldbox], box)
  1727. else:
  1728. duplicates[box] = None
  1729. def reached_loop_header(self, greenboxes, redboxes, resumedescr):
  1730. self.heapcache.reset()
  1731. duplicates = {}
  1732. self.remove_consts_and_duplicates(redboxes, len(redboxes),
  1733. duplicates)
  1734. live_arg_boxes = greenboxes + redboxes
  1735. if self.jitdriver_sd.virtualizable_info is not None:
  1736. # we use pop() to remove the last item, which is the virtualizable
  1737. # itself
  1738. self.remove_consts_and_duplicates(self.virtualizable_boxes,
  1739. len(self.virtualizable_boxes)-1,
  1740. duplicates)
  1741. live_arg_boxes += self.virtualizable_boxes
  1742. live_arg_boxes.pop()
  1743. #
  1744. assert len(self.virtualref_boxes) == 0, "missing virtual_ref_finish()?"
  1745. # Called whenever we reach the 'loop_header' hint.
  1746. # First, attempt to make a bridge:
  1747. # - if self.resumekey is a ResumeGuardDescr, it starts from a guard
  1748. # that failed;
  1749. # - if self.resumekey is a ResumeFromInterpDescr, it starts directly
  1750. # from the interpreter.
  1751. if not self.partial_trace:
  1752. # FIXME: Support a retrace to be a bridge as well as a loop
  1753. self.compile_trace(live_arg_boxes, resumedescr)
  1754. # raises in case it works -- which is the common case, hopefully,
  1755. # at least for bridges starting from a guard.
  1756. # Search in current_merge_points for original_boxes with compatible
  1757. # green keys, representing the beginning of the same loop as the one
  1758. # we end now.
  1759. num_green_args = self.jitdriver_sd.num_green_args
  1760. for j in range(len(self.current_merge_points)-1, -1, -1):
  1761. original_boxes, start = self.current_merge_points[j]
  1762. assert len(original_boxes) == len(live_arg_boxes)
  1763. for i in range(num_green_args):
  1764. box1 = original_boxes[i]
  1765. box2 = live_arg_boxes[i]
  1766. assert isinstance(box1, Const)
  1767. if not box1.same_constant(box2):
  1768. break
  1769. else:
  1770. # Found! Compile it as a loop.
  1771. # raises in case it works -- which is the common case
  1772. if self.partial_trace:
  1773. if start != self.retracing_from:
  1774. raise SwitchToBlackhole(Counters.ABORT_BAD_LOOP) # For now
  1775. self.compile_loop(original_boxes, live_arg_boxes, start, resumedescr)
  1776. # creation of the loop was cancelled!
  1777. self.cancel_count += 1
  1778. if self.staticdata.warmrunnerdesc:
  1779. memmgr = self.staticdata.warmrunnerdesc.memory_manager
  1780. if memmgr:
  1781. if self.cancel_count > memmgr.max_unroll_loops:
  1782. self.compile_loop_or_abort(original_boxes,
  1783. live_arg_boxes,
  1784. start, resumedescr)
  1785. self.staticdata.log('cancelled, tracing more...')
  1786. # Otherwise, no loop found so far, so continue tracing.
  1787. start = len(self.history.operations)
  1788. self.current_merge_points.append((live_arg_boxes, start))
  1789. def _unpack_boxes(self, boxes, start, stop):
  1790. ints = []; refs = []; floats = []
  1791. for i in range(start, stop):
  1792. box = boxes[i]
  1793. if box.type == history.INT: ints.append(box.getint())
  1794. elif box.type == history.REF: refs.append(box.getref_base())
  1795. elif box.type == history.FLOAT:floats.append(box.getfloatstorage())
  1796. else: assert 0
  1797. return ints[:], refs[:], floats[:]
  1798. def raise_continue_running_normally(self, live_arg_boxes, loop_token):
  1799. self.history.inputargs = None
  1800. self.history.operations = None
  1801. # For simplicity, we just raise ContinueRunningNormally here and
  1802. # ignore the loop_token passed in. It means that we go back to
  1803. # interpreted mode, but it should come back very quickly to the
  1804. # JIT, find probably the same 'loop_token', and execute it.
  1805. if we_are_translated():
  1806. num_green_args = self.jitdriver_sd.num_green_args
  1807. gi, gr, gf = self._unpack_boxes(live_arg_boxes, 0, num_green_args)
  1808. ri, rr, rf = self._unpack_boxes(live_arg_boxes, num_green_args,
  1809. len(live_arg_boxes))
  1810. CRN = self.staticdata.ContinueRunningNormally
  1811. raise CRN(gi, gr, gf, ri, rr, rf)
  1812. else:
  1813. # However, in order to keep the existing tests working
  1814. # (which are based on the assumption that 'loop_token' is
  1815. # directly used here), a bit of custom non-translatable code...
  1816. self._nontranslated_run_directly(live_arg_boxes, loop_token)
  1817. assert 0, "unreachable"
  1818. def _nontranslated_run_directly(self, live_arg_boxes, loop_token):
  1819. "NOT_RPYTHON"
  1820. args = []
  1821. num_green_args = self.jitdriver_sd.num_green_args
  1822. num_red_args = self.jitdriver_sd.num_red_args
  1823. for box in live_arg_boxes[num_green_args:num_green_args+num_red_args]:
  1824. if box.type == history.INT: args.append(box.getint())
  1825. elif box.type == history.REF: args.append(box.getref_base())
  1826. elif box.type == history.FLOAT: args.append(box.getfloatstorage())
  1827. else: assert 0
  1828. self.jitdriver_sd.warmstate.execute_assembler(loop_token, *args)
  1829. def prepare_resume_from_failure(self, opnum, dont_change_position,
  1830. deadframe):
  1831. frame = self.framestack[-1]
  1832. if opnum == rop.GUARD_TRUE: # a goto_if_not that jumps only now
  1833. if not dont_change_position:
  1834. frame.pc = frame.jitcode.follow_jump(frame.pc)
  1835. elif opnum == rop.GUARD_FALSE: # a goto_if_not that stops jumping
  1836. pass
  1837. elif opnum == rop.GUARD_VALUE or opnum == rop.GUARD_CLASS:
  1838. pass # the pc is already set to the *start* of the opcode
  1839. elif (opnum == rop.GUARD_NONNULL or
  1840. opnum == rop.GUARD_ISNULL or
  1841. opnum == rop.GUARD_NONNULL_CLASS):
  1842. pass # the pc is already set to the *start* of the opcode
  1843. elif opnum == rop.GUARD_NO_EXCEPTION or opnum == rop.GUARD_EXCEPTION:
  1844. exception = self.cpu.grab_exc_value(deadframe)
  1845. if exception:
  1846. self.execute_ll_raised(lltype.cast_opaque_ptr(rclass.OBJECTPTR,
  1847. exception))
  1848. else:
  1849. self.clear_exception()
  1850. try:
  1851. self.handle_possible_exception()
  1852. except ChangeFrame:
  1853. pass
  1854. elif opnum == rop.GUARD_NOT_INVALIDATED:
  1855. pass # XXX we want to do something special in resume descr,
  1856. # but not now
  1857. elif opnum == rop.GUARD_NO_OVERFLOW: # an overflow now detected
  1858. if not dont_change_position:
  1859. self.execute_raised(OverflowError(), constant=True)
  1860. try:
  1861. self.finishframe_exception()
  1862. except ChangeFrame:
  1863. pass
  1864. elif opnum == rop.GUARD_OVERFLOW: # no longer overflowing
  1865. self.clear_exception()
  1866. else:
  1867. from rpython.jit.metainterp.resoperation import opname
  1868. raise NotImplementedError(opname[opnum])
  1869. def get_procedure_token(self, greenkey, with_compiled_targets=False):
  1870. cell = self.jitdriver_sd.warmstate.jit_cell_at_key(greenkey)
  1871. token = cell.get_procedure_token()
  1872. if with_compiled_targets:
  1873. if not token:
  1874. return None
  1875. if not token.target_tokens:
  1876. return None
  1877. return token
  1878. def compile_loop(self, original_boxes, live_arg_boxes, start,
  1879. resume_at_jump_descr, try_disabling_unroll=False):
  1880. num_green_args = self.jitdriver_sd.num_green_args
  1881. greenkey = original_boxes[:num_green_args]
  1882. if not self.partial_trace:
  1883. assert self.get_procedure_token(greenkey) is None or \
  1884. self.get_procedure_token(greenkey).target_tokens is None
  1885. if self.partial_trace:
  1886. target_token = compile.compile_retrace(self, greenkey, start,
  1887. original_boxes[num_green_args:],
  1888. live_arg_boxes[num_green_args:],
  1889. resume_at_jump_descr, self.partial_trace,
  1890. self.resumekey)
  1891. else:
  1892. target_token = compile.compile_loop(self, greenkey, start,
  1893. original_boxes[num_green_args:],
  1894. live_arg_boxes[num_green_args:],
  1895. resume_at_jump_descr,
  1896. try_disabling_unroll=try_disabling_unroll)
  1897. if target_token is not None:
  1898. assert isinstance(target_token, TargetToken)
  1899. self.jitdriver_sd.warmstate.attach_procedure_to_interp(greenkey, target_token.targeting_jitcell_token)
  1900. self.staticdata.stats.add_jitcell_token(target_token.targeting_jitcell_token)
  1901. if target_token is not None: # raise if it *worked* correctly
  1902. assert isinstance(target_token, TargetToken)
  1903. jitcell_token = target_token.targeting_jitcell_token
  1904. self.raise_continue_running_normally(live_arg_boxes, jitcell_token)
  1905. def compile_loop_or_abort(self, original_boxes, live_arg_boxes,
  1906. start, resume_at_jump_descr):
  1907. """Called after we aborted more than 'max_unroll_loops' times.
  1908. As a last attempt, try to compile the loop with unrolling disabled.
  1909. """
  1910. if not self.partial_trace:
  1911. self.compile_loop(original_boxes, live_arg_boxes, start,
  1912. resume_at_jump_descr, try_disabling_unroll=True)
  1913. #
  1914. self.staticdata.log('cancelled too many times!')
  1915. raise SwitchToBlackhole(Counters.ABORT_BAD_LOOP)
  1916. def compile_trace(self, live_arg_boxes, resume_at_jump_descr):
  1917. num_green_args = self.jitdriver_sd.num_green_args
  1918. greenkey = live_arg_boxes[:num_green_args]
  1919. target_jitcell_token = self.get_procedure_token(greenkey, True)
  1920. if not target_jitcell_token:
  1921. return
  1922. self.history.record(rop.JUMP, live_arg_boxes[num_green_args:], None,
  1923. descr=target_jitcell_token)
  1924. try:
  1925. target_token = compile.compile_trace(self, self.resumekey, resume_at_jump_descr)
  1926. finally:
  1927. self.history.operations.pop() # remove the JUMP
  1928. if target_token is not None: # raise if it *worked* correctly
  1929. assert isinstance(target_token, TargetToken)
  1930. jitcell_token = target_token.targeting_jitcell_token
  1931. self.raise_continue_running_normally(live_arg_boxes, jitcell_token)
  1932. def compile_done_with_this_frame(self, exitbox):
  1933. self.gen_store_back_in_virtualizable()
  1934. # temporarily put a JUMP to a pseudo-loop
  1935. sd = self.staticdata
  1936. result_type = self.jitdriver_sd.result_type
  1937. if result_type == history.VOID:
  1938. assert exitbox is None
  1939. exits = []
  1940. loop_tokens = sd.loop_tokens_done_with_this_frame_void
  1941. elif result_type == history.INT:
  1942. exits = [exitbox]
  1943. loop_tokens = sd.loop_tokens_done_with_this_frame_int
  1944. elif result_type == history.REF:
  1945. exits = [exitbox]
  1946. loop_tokens = sd.loop_tokens_done_with_this_frame_ref
  1947. elif result_type == history.FLOAT:
  1948. exits = [exitbox]
  1949. loop_tokens = sd.loop_tokens_done_with_this_frame_float
  1950. else:
  1951. assert False
  1952. # FIXME: kill TerminatingLoopToken?
  1953. # FIXME: can we call compile_trace?
  1954. token = loop_tokens[0].finishdescr
  1955. self.history.record(rop.FINISH, exits, None, descr=token)
  1956. target_token = compile.compile_trace(self, self.resumekey)
  1957. if target_token is not token:
  1958. compile.giveup()
  1959. def compile_exit_frame_with_exception(self, valuebox):
  1960. self.gen_store_back_in_virtualizable()
  1961. sd = self.staticdata
  1962. token = sd.loop_tokens_exit_frame_with_exception_ref[0].finishdescr
  1963. self.history.record(rop.FINISH, [valuebox], None, descr=token)
  1964. target_token = compile.compile_trace(self, self.resumekey)
  1965. if target_token is not token:
  1966. compile.giveup()
  1967. @specialize.arg(1)
  1968. def initialize_original_boxes(self, jitdriver_sd, *args):
  1969. original_boxes = []
  1970. self._fill_original_boxes(jitdriver_sd, original_boxes,
  1971. jitdriver_sd.num_green_args, *args)
  1972. return original_boxes
  1973. @specialize.arg(1)
  1974. def _fill_original_boxes(self, jitdriver_sd, original_boxes,
  1975. num_green_args, *args):
  1976. if args:
  1977. from rpython.jit.metainterp.warmstate import wrap
  1978. box = wrap(self.cpu, args[0], num_green_args > 0)
  1979. original_boxes.append(box)
  1980. self._fill_original_boxes(jitdriver_sd, original_boxes,
  1981. num_green_args-1, *args[1:])
  1982. def initialize_state_from_start(self, original_boxes):
  1983. # ----- make a new frame -----
  1984. self.portal_call_depth = -1 # always one portal around
  1985. self.framestack = []
  1986. f = self.newframe(self.jitdriver_sd.mainjitcode)
  1987. f.setup_call(original_boxes)
  1988. assert self.portal_call_depth == 0
  1989. self.virtualref_boxes = []
  1990. self.initialize_withgreenfields(original_boxes)
  1991. self.initialize_virtualizable(original_boxes)
  1992. def initialize_state_from_guard_failure(self, resumedescr, deadframe):
  1993. # guard failure: rebuild a complete MIFrame stack
  1994. # This is stack-critical code: it must not be interrupted by StackOverflow,
  1995. # otherwise the jit_virtual_refs are left in a dangling state.
  1996. rstack._stack_criticalcode_start()
  1997. try:
  1998. self.portal_call_depth = -1 # always one portal around
  1999. self.history = history.History()
  2000. inputargs_and_holes = self.rebuild_state_after_failure(resumedescr,
  2001. deadframe)
  2002. self.history.inputargs = [box for box in inputargs_and_holes if box]
  2003. finally:
  2004. rstack._stack_criticalcode_stop()
  2005. def initialize_virtualizable(self, original_boxes):
  2006. vinfo = self.jitdriver_sd.virtualizable_info
  2007. if vinfo is not None:
  2008. index = (self.jitdriver_sd.num_green_args +
  2009. self.jitdriver_sd.index_of_virtualizable)
  2010. virtualizable_box = original_boxes[index]
  2011. virtualizable = vinfo.unwrap_virtualizable_box(virtualizable_box)
  2012. # The field 'virtualizable_boxes' is not even present
  2013. # if 'virtualizable_info' is None. Check for that first.
  2014. self.virtualizable_boxes = vinfo.read_boxes(self.cpu,
  2015. virtualizable)
  2016. original_boxes += self.virtualizable_boxes
  2017. self.virtualizable_boxes.append(virtualizable_box)
  2018. self.initialize_virtualizable_enter()
  2019. def initialize_withgreenfields(self, original_boxes):
  2020. ginfo = self.jitdriver_sd.greenfield_info
  2021. if ginfo is not None:
  2022. assert self.jitdriver_sd.virtualizable_info is None
  2023. index = (self.jitdriver_sd.num_green_args +
  2024. ginfo.red_index)
  2025. self.virtualizable_boxes = [original_boxes[index]]
  2026. def initialize_virtualizable_enter(self):
  2027. vinfo = self.jitdriver_sd.virtualizable_info
  2028. virtualizable_box = self.virtualizable_boxes[-1]
  2029. virtualizable = vinfo.unwrap_virtualizable_box(virtualizable_box)
  2030. vinfo.clear_vable_token(virtualizable)
  2031. def vable_and_vrefs_before_residual_call(self):
  2032. vrefinfo = self.staticdata.virtualref_info
  2033. for i in range(1, len(self.virtualref_boxes), 2):
  2034. vrefbox = self.virtualref_boxes[i]
  2035. vref = vrefbox.getref_base()
  2036. vrefinfo.tracing_before_residual_call(vref)
  2037. # the FORCE_TOKEN is already set at runtime in each vref when
  2038. # it is created, by optimizeopt.py.
  2039. #
  2040. vinfo = self.jitdriver_sd.virtualizable_info
  2041. if vinfo is not None:
  2042. virtualizable_box = self.virtualizable_boxes[-1]
  2043. virtualizable = vinfo.unwrap_virtualizable_box(virtualizable_box)
  2044. vinfo.tracing_before_residual_call(virtualizable)
  2045. #
  2046. force_token_box = history.BoxInt()
  2047. self.history.record(rop.FORCE_TOKEN, [], force_token_box)
  2048. self.history.record(rop.SETFIELD_GC, [virtualizable_box,
  2049. force_token_box],
  2050. None, descr=vinfo.vable_token_descr)
  2051. def vrefs_after_residual_call(self):
  2052. vrefinfo = self.staticdata.virtualref_info
  2053. for i in range(0, len(self.virtualref_boxes), 2):
  2054. vrefbox = self.virtualref_boxes[i+1]
  2055. vref = vrefbox.getref_base()
  2056. if vrefinfo.tracing_after_residual_call(vref):
  2057. # this vref was really a virtual_ref, but it escaped
  2058. # during this CALL_MAY_FORCE. Mark this fact by
  2059. # generating a VIRTUAL_REF_FINISH on it and replacing
  2060. # it by ConstPtr(NULL).
  2061. self.stop_tracking_virtualref(i)
  2062. def vable_after_residual_call(self):
  2063. vinfo = self.jitdriver_sd.virtualizable_info
  2064. if vinfo is not None:
  2065. virtualizable_box = self.virtualizable_boxes[-1]
  2066. virtualizable = vinfo.unwrap_virtualizable_box(virtualizable_box)
  2067. if vinfo.tracing_after_residual_call(virtualizable):
  2068. # the virtualizable escaped during CALL_MAY_FORCE.
  2069. self.load_fields_from_virtualizable()
  2070. raise SwitchToBlackhole(Counters.ABORT_ESCAPE,
  2071. raising_exception=True)
  2072. # ^^^ we set 'raising_exception' to True because we must still
  2073. # have the eventual exception raised (this is normally done
  2074. # after the call to vable_after_residual_call()).
  2075. def stop_tracking_virtualref(self, i):
  2076. virtualbox = self.virtualref_boxes[i]
  2077. vrefbox = self.virtualref_boxes[i+1]
  2078. # record VIRTUAL_REF_FINISH just before the current CALL_MAY_FORCE
  2079. call_may_force_op = self.history.operations.pop()
  2080. assert call_may_force_op.getopnum() == rop.CALL_MAY_FORCE
  2081. self.history.record(rop.VIRTUAL_REF_FINISH,
  2082. [vrefbox, virtualbox], None)
  2083. self.history.operations.append(call_may_force_op)
  2084. # mark by replacing it with ConstPtr(NULL)
  2085. self.virtualref_boxes[i+1] = self.cpu.ts.CONST_NULL
  2086. def handle_possible_exception(self):
  2087. frame = self.framestack[-1]
  2088. if self.last_exc_value_box is not None:
  2089. exception_box = self.cpu.ts.cls_of_box(self.last_exc_value_box)
  2090. op = frame.generate_guard(rop.GUARD_EXCEPTION,
  2091. None, [exception_box])
  2092. assert op is not None
  2093. op.result = self.last_exc_value_box
  2094. self.class_of_last_exc_is_const = True
  2095. self.finishframe_exception()
  2096. else:
  2097. frame.generate_guard(rop.GUARD_NO_EXCEPTION, None, [])
  2098. def handle_possible_overflow_error(self):
  2099. frame = self.framestack[-1]
  2100. if self.last_exc_value_box is not None:
  2101. frame.generate_guard(rop.GUARD_OVERFLOW, None)
  2102. assert isinstance(self.last_exc_value_box, Const)
  2103. assert self.class_of_last_exc_is_const
  2104. self.finishframe_exception()
  2105. else:
  2106. frame.generate_guard(rop.GUARD_NO_OVERFLOW, None)
  2107. def assert_no_exception(self):
  2108. assert self.last_exc_value_box is None
  2109. def rebuild_state_after_failure(self, resumedescr, deadframe):
  2110. vinfo = self.jitdriver_sd.virtualizable_info
  2111. ginfo = self.jitdriver_sd.greenfield_info
  2112. self.framestack = []
  2113. boxlists = resume.rebuild_from_resumedata(self, resumedescr, deadframe,
  2114. vinfo, ginfo)
  2115. inputargs_and_holes, virtualizable_boxes, virtualref_boxes = boxlists
  2116. #
  2117. # virtual refs: make the vrefs point to the freshly allocated virtuals
  2118. self.virtualref_boxes = virtualref_boxes
  2119. vrefinfo = self.staticdata.virtualref_info
  2120. for i in range(0, len(virtualref_boxes), 2):
  2121. virtualbox = virtualref_boxes[i]
  2122. vrefbox = virtualref_boxes[i+1]
  2123. vrefinfo.continue_tracing(vrefbox.getref_base(),
  2124. virtualbox.getref_base())
  2125. #
  2126. # virtualizable: synchronize the real virtualizable and the local
  2127. # boxes, in whichever direction is appropriate
  2128. if vinfo is not None:
  2129. self.virtualizable_boxes = virtualizable_boxes
  2130. # just jumped away from assembler (case 4 in the comment in
  2131. # virtualizable.py) into tracing (case 2); check that vable_token
  2132. # is and stays 0. Note the call to reset_vable_token() in
  2133. # warmstate.py.
  2134. virtualizable_box = self.virtualizable_boxes[-1]
  2135. virtualizable = vinfo.unwrap_virtualizable_box(virtualizable_box)
  2136. assert not vinfo.is_token_nonnull_gcref(virtualizable)
  2137. # fill the virtualizable with the local boxes
  2138. self.synchronize_virtualizable()
  2139. #
  2140. elif self.jitdriver_sd.greenfield_info:
  2141. self.virtualizable_boxes = virtualizable_boxes
  2142. else:
  2143. assert not virtualizable_boxes
  2144. #
  2145. return inputargs_and_holes
  2146. def check_synchronized_virtualizable(self):
  2147. if not we_are_translated():
  2148. vinfo = self.jitdriver_sd.virtualizable_info
  2149. virtualizable_box = self.virtualizable_boxes[-1]
  2150. virtualizable = vinfo.unwrap_virtualizable_box(virtualizable_box)
  2151. vinfo.check_boxes(virtualizable, self.virtualizable_boxes)
  2152. def synchronize_virtualizable(self):
  2153. vinfo = self.jitdriver_sd.virtualizable_info
  2154. virtualizable_box = self.virtualizable_boxes[-1]
  2155. virtualizable = vinfo.unwrap_virtualizable_box(virtualizable_box)
  2156. vinfo.write_boxes(virtualizable, self.virtualizable_boxes)
  2157. def load_fields_from_virtualizable(self):
  2158. # Force a reload of the virtualizable fields into the local
  2159. # boxes (called only in escaping cases). Only call this function
  2160. # just before SwitchToBlackhole.
  2161. vinfo = self.jitdriver_sd.virtualizable_info
  2162. if vinfo is not None:
  2163. virtualizable_box = self.virtualizable_boxes[-1]
  2164. virtualizable = vinfo.unwrap_virtualizable_box(virtualizable_box)
  2165. self.virtualizable_boxes = vinfo.read_boxes(self.cpu,
  2166. virtualizable)
  2167. self.virtualizable_boxes.append(virtualizable_box)
  2168. def gen_store_back_in_virtualizable(self):
  2169. vinfo = self.jitdriver_sd.virtualizable_info
  2170. if vinfo is not None:
  2171. # xxx only write back the fields really modified
  2172. vbox = self.virtualizable_boxes[-1]
  2173. for i in range(vinfo.num_static_extra_boxes):
  2174. fieldbox = self.virtualizable_boxes[i]
  2175. descr = vinfo.static_field_descrs[i]
  2176. self.execute_and_record(rop.SETFIELD_GC, descr, vbox, fieldbox)
  2177. i = vinfo.num_static_extra_boxes
  2178. virtualizable = vinfo.unwrap_virtualizable_box(vbox)
  2179. for k in range(vinfo.num_arrays):
  2180. descr = vinfo.array_field_descrs[k]
  2181. abox = self.execute_and_record(rop.GETFIELD_GC, descr, vbox)
  2182. descr = vinfo.array_descrs[k]
  2183. for j in range(vinfo.get_array_length(virtualizable, k)):
  2184. itembox = self.virtualizable_boxes[i]
  2185. i += 1
  2186. self.execute_and_record(rop.SETARRAYITEM_GC, descr,
  2187. abox, ConstInt(j), itembox)
  2188. assert i + 1 == len(self.virtualizable_boxes)
  2189. def replace_box(self, oldbox, newbox):
  2190. assert isinstance(oldbox, Box)
  2191. for frame in self.framestack:
  2192. frame.replace_active_box_in_frame(oldbox, newbox)
  2193. boxes = self.virtualref_boxes
  2194. for i in range(len(boxes)):
  2195. if boxes[i] is oldbox:
  2196. boxes[i] = newbox
  2197. if (self.jitdriver_sd.virtualizable_info is not None or
  2198. self.jitdriver_sd.greenfield_info is not None):
  2199. boxes = self.virtualizable_boxes
  2200. for i in range(len(boxes)):
  2201. if boxes[i] is oldbox:
  2202. boxes[i] = newbox
  2203. self.heapcache.replace_box(oldbox, newbox)
  2204. def find_biggest_function(self):
  2205. start_stack = []
  2206. max_size = 0
  2207. max_key = None
  2208. for pair in self.portal_trace_positions:
  2209. key, pos = pair
  2210. if key is not None:
  2211. start_stack.append(pair)
  2212. else:
  2213. greenkey, startpos = start_stack.pop()
  2214. size = pos - startpos
  2215. if size > max_size:
  2216. max_size = size
  2217. max_key = greenkey
  2218. if start_stack:
  2219. key, pos = start_stack[0]
  2220. size = len(self.history.operations) - pos
  2221. if size > max_size:
  2222. max_size = size
  2223. max_key = key
  2224. return max_key
  2225. def record_result_of_call_pure(self, resbox):
  2226. """ Patch a CALL into a CALL_PURE.
  2227. """
  2228. op = self.history.operations[-1]
  2229. assert op.getopnum() == rop.CALL
  2230. resbox_as_const = resbox.constbox()
  2231. for i in range(op.numargs()):
  2232. if not isinstance(op.getarg(i), Const):
  2233. break
  2234. else:
  2235. # all-constants: remove the CALL operation now and propagate a
  2236. # constant result
  2237. self.history.operations.pop()
  2238. return resbox_as_const
  2239. # not all constants (so far): turn CALL into CALL_PURE, which might
  2240. # be either removed later by optimizeopt or turned back into CALL.
  2241. arg_consts = [a.constbox() for a in op.getarglist()]
  2242. self.call_pure_results[arg_consts] = resbox_as_const
  2243. newop = op.copy_and_change(rop.CALL_PURE, args=op.getarglist())
  2244. self.history.operations[-1] = newop
  2245. return resbox
  2246. def direct_assembler_call(self, targetjitdriver_sd):
  2247. """ Generate a direct call to assembler for portal entry point,
  2248. patching the CALL_MAY_FORCE that occurred just now.
  2249. """
  2250. op = self.history.operations.pop()
  2251. assert op.getopnum() == rop.CALL_MAY_FORCE
  2252. num_green_args = targetjitdriver_sd.num_green_args
  2253. arglist = op.getarglist()
  2254. greenargs = arglist[1:num_green_args+1]
  2255. args = arglist[num_green_args+1:]
  2256. assert len(args) == targetjitdriver_sd.num_red_args
  2257. warmrunnerstate = targetjitdriver_sd.warmstate
  2258. token = warmrunnerstate.get_assembler_token(greenargs)
  2259. op = op.copy_and_change(rop.CALL_ASSEMBLER, args=args, descr=token)
  2260. self.history.operations.append(op)
  2261. #
  2262. # To fix an obscure issue, make sure the vable stays alive
  2263. # longer than the CALL_ASSEMBLER operation. We do it by
  2264. # inserting explicitly an extra KEEPALIVE operation.
  2265. jd = token.outermost_jitdriver_sd
  2266. if jd.index_of_virtualizable >= 0:
  2267. return args[jd.index_of_virtualizable]
  2268. else:
  2269. return None
  2270. def direct_libffi_call(self):
  2271. """Generate a direct call to C code, patching the CALL_MAY_FORCE
  2272. to jit_ffi_call() that occurred just now.
  2273. """
  2274. # an 'assert' that constant-folds away the rest of this function
  2275. # if the codewriter didn't produce any OS_LIBFFI_CALL at all.
  2276. assert self.staticdata.has_libffi_call
  2277. #
  2278. from rpython.rtyper.lltypesystem import llmemory
  2279. from rpython.rlib.jit_libffi import CIF_DESCRIPTION_P
  2280. from rpython.jit.backend.llsupport.ffisupport import get_arg_descr
  2281. #
  2282. num_extra_guards = 0
  2283. while True:
  2284. op = self.history.operations[-1-num_extra_guards]
  2285. if op.getopnum() == rop.CALL_MAY_FORCE:
  2286. break
  2287. assert op.is_guard()
  2288. num_extra_guards += 1
  2289. #
  2290. box_cif_description = op.getarg(1)
  2291. if not isinstance(box_cif_description, ConstInt):
  2292. return
  2293. cif_description = box_cif_description.getint()
  2294. cif_description = llmemory.cast_int_to_adr(cif_description)
  2295. cif_description = llmemory.cast_adr_to_ptr(cif_description,
  2296. CIF_DESCRIPTION_P)
  2297. extrainfo = op.getdescr().get_extra_info()
  2298. calldescr = self.cpu.calldescrof_dynamic(cif_description, extrainfo)
  2299. if calldescr is None:
  2300. return
  2301. #
  2302. extra_guards = []
  2303. for i in range(num_extra_guards):
  2304. extra_guards.append(self.history.operations.pop())
  2305. extra_guards.reverse()
  2306. #
  2307. box_exchange_buffer = op.getarg(3)
  2308. self.history.operations.pop()
  2309. arg_boxes = []
  2310. for i in range(cif_description.nargs):
  2311. kind, descr = get_arg_descr(self.cpu, cif_description.atypes[i])
  2312. if kind == 'i':
  2313. box_arg = history.BoxInt()
  2314. elif kind == 'f':
  2315. box_arg = history.BoxFloat()
  2316. else:
  2317. assert kind == 'v'
  2318. continue
  2319. ofs = cif_description.exchange_args[i]
  2320. box_argpos = history.BoxInt()
  2321. self.history.record(rop.INT_ADD,
  2322. [box_exchange_buffer, ConstInt(ofs)],
  2323. box_argpos)
  2324. self.history.record(rop.GETARRAYITEM_RAW,
  2325. [box_argpos, ConstInt(0)],
  2326. box_arg, descr)
  2327. arg_boxes.append(box_arg)
  2328. #
  2329. kind, descr = get_arg_descr(self.cpu, cif_description.rtype)
  2330. if kind == 'i':
  2331. box_result = history.BoxInt()
  2332. elif kind == 'f':
  2333. box_result = history.BoxFloat()
  2334. else:
  2335. assert kind == 'v'
  2336. box_result = None
  2337. self.history.record(rop.CALL_RELEASE_GIL,
  2338. [op.getarg(2)] + arg_boxes,
  2339. box_result, calldescr)
  2340. #
  2341. self.history.operations.extend(extra_guards)
  2342. #
  2343. if box_result is not None:
  2344. ofs = cif_description.exchange_result
  2345. box_resultpos = history.BoxInt()
  2346. self.history.record(rop.INT_ADD,
  2347. [box_exchange_buffer, ConstInt(ofs)],
  2348. box_resultpos)
  2349. self.history.record(rop.SETARRAYITEM_RAW,
  2350. [box_resultpos, ConstInt(0), box_result],
  2351. None, descr)
  2352. def direct_call_release_gil(self):
  2353. op = self.history.operations.pop()
  2354. assert op.opnum == rop.CALL_MAY_FORCE
  2355. descr = op.getdescr()
  2356. effectinfo = descr.get_extra_info()
  2357. realfuncaddr = effectinfo.call_release_gil_target
  2358. funcbox = ConstInt(heaptracker.adr2int(realfuncaddr))
  2359. self.history.record(rop.CALL_RELEASE_GIL,
  2360. [funcbox] + op.getarglist()[1:],
  2361. op.result, descr)
  2362. if not we_are_translated(): # for llgraph
  2363. descr._original_func_ = op.getarg(0).value
  2364. # ____________________________________________________________
  2365. class ChangeFrame(JitException):
  2366. """Raised after we mutated metainterp.framestack, in order to force
  2367. it to reload the current top-of-stack frame that gets interpreted."""
  2368. class SwitchToBlackhole(JitException):
  2369. def __init__(self, reason, raising_exception=False):
  2370. self.reason = reason
  2371. self.raising_exception = raising_exception
  2372. # ^^^ must be set to True if the SwitchToBlackhole is raised at a
  2373. # point where the exception on metainterp.last_exc_value_box
  2374. # is supposed to be raised. The default False means that it
  2375. # should just be copied into the blackhole interp, but not raised.
  2376. # ____________________________________________________________
  2377. def _get_opimpl_method(name, argcodes):
  2378. from rpython.jit.metainterp.blackhole import signedord
  2379. #
  2380. def handler(self, position):
  2381. assert position >= 0
  2382. args = ()
  2383. next_argcode = 0
  2384. code = self.bytecode
  2385. orgpc = position
  2386. position += 1
  2387. for argtype in argtypes:
  2388. if argtype == "box": # a box, of whatever type
  2389. argcode = argcodes[next_argcode]
  2390. next_argcode = next_argcode + 1
  2391. if argcode == 'i':
  2392. value = self.registers_i[ord(code[position])]
  2393. elif argcode == 'c':
  2394. value = ConstInt(signedord(code[position]))
  2395. elif argcode == 'r':
  2396. value = self.registers_r[ord(code[position])]
  2397. elif argcode == 'f':
  2398. value = self.registers_f[ord(code[position])]
  2399. else:
  2400. raise AssertionError("bad argcode")
  2401. position += 1
  2402. elif argtype == "descr" or argtype == "jitcode":
  2403. assert argcodes[next_argcode] == 'd'
  2404. next_argcode = next_argcode + 1
  2405. index = ord(code[position]) | (ord(code[position+1])<<8)
  2406. value = self.metainterp.staticdata.opcode_descrs[index]
  2407. if argtype == "jitcode":
  2408. assert isinstance(value, JitCode)
  2409. position += 2
  2410. elif argtype == "label":
  2411. assert argcodes[next_argcode] == 'L'
  2412. next_argcode = next_argcode + 1
  2413. value = ord(code[position]) | (ord(code[position+1])<<8)
  2414. position += 2
  2415. elif argtype == "boxes": # a list of boxes of some type
  2416. length = ord(code[position])
  2417. value = [None] * length
  2418. self.prepare_list_of_boxes(value, 0, position,
  2419. argcodes[next_argcode])
  2420. next_argcode = next_argcode + 1
  2421. position += 1 + length
  2422. elif argtype == "boxes2": # two lists of boxes merged into one
  2423. length1 = ord(code[position])
  2424. position2 = position + 1 + length1
  2425. length2 = ord(code[position2])
  2426. value = [None] * (length1 + length2)
  2427. self.prepare_list_of_boxes(value, 0, position,
  2428. argcodes[next_argcode])
  2429. self.prepare_list_of_boxes(value, length1, position2,
  2430. argcodes[next_argcode + 1])
  2431. next_argcode = next_argcode + 2
  2432. position = position2 + 1 + length2
  2433. elif argtype == "boxes3": # three lists of boxes merged into one
  2434. length1 = ord(code[position])
  2435. position2 = position + 1 + length1
  2436. length2 = ord(code[position2])
  2437. position3 = position2 + 1 + length2
  2438. length3 = ord(code[position3])
  2439. value = [None] * (length1 + length2 + length3)
  2440. self.prepare_list_of_boxes(value, 0, position,
  2441. argcodes[next_argcode])
  2442. self.prepare_list_of_boxes(value, length1, position2,
  2443. argcodes[next_argcode + 1])
  2444. self.prepare_list_of_boxes(value, length1 + length2, position3,
  2445. argcodes[next_argcode + 2])
  2446. next_argcode = next_argcode + 3
  2447. position = position3 + 1 + length3
  2448. elif argtype == "orgpc":
  2449. value = orgpc
  2450. elif argtype == "int":
  2451. argcode = argcodes[next_argcode]
  2452. next_argcode = next_argcode + 1
  2453. if argcode == 'i':
  2454. value = self.registers_i[ord(code[position])].getint()
  2455. elif argcode == 'c':
  2456. value = signedord(code[position])
  2457. else:
  2458. raise AssertionError("bad argcode")
  2459. position += 1
  2460. elif argtype == "jitcode_position":
  2461. value = position
  2462. else:
  2463. raise AssertionError("bad argtype: %r" % (argtype,))
  2464. args += (value,)
  2465. #
  2466. num_return_args = len(argcodes) - next_argcode
  2467. assert num_return_args == 0 or num_return_args == 2
  2468. if num_return_args:
  2469. # Save the type of the resulting box. This is needed if there is
  2470. # a get_list_of_active_boxes(). See comments there.
  2471. self._result_argcode = argcodes[next_argcode + 1]
  2472. position += 1
  2473. else:
  2474. self._result_argcode = 'v'
  2475. self.pc = position
  2476. #
  2477. if not we_are_translated():
  2478. if self.debug:
  2479. print '\tpyjitpl: %s(%s)' % (name, ', '.join(map(repr, args))),
  2480. try:
  2481. resultbox = unboundmethod(self, *args)
  2482. except Exception, e:
  2483. if self.debug:
  2484. print '-> %s!' % e.__class__.__name__
  2485. raise
  2486. if num_return_args == 0:
  2487. if self.debug:
  2488. print
  2489. assert resultbox is None
  2490. else:
  2491. if self.debug:
  2492. print '-> %r' % (resultbox,)
  2493. assert argcodes[next_argcode] == '>'
  2494. result_argcode = argcodes[next_argcode + 1]
  2495. assert resultbox.type == {'i': history.INT,
  2496. 'r': history.REF,
  2497. 'f': history.FLOAT}[result_argcode]
  2498. else:
  2499. resultbox = unboundmethod(self, *args)
  2500. #
  2501. if resultbox is not None:
  2502. self.make_result_of_lastop(resultbox)
  2503. elif not we_are_translated():
  2504. assert self._result_argcode in 'v?'
  2505. #
  2506. unboundmethod = getattr(MIFrame, 'opimpl_' + name).im_func
  2507. argtypes = unrolling_iterable(unboundmethod.argtypes)
  2508. handler.func_name = 'handler_' + name
  2509. return handler
  2510. def put_back_list_of_boxes3(frame, position, newvalue):
  2511. code = frame.bytecode
  2512. length1 = ord(code[position])
  2513. position2 = position + 1 + length1
  2514. length2 = ord(code[position2])
  2515. position3 = position2 + 1 + length2
  2516. length3 = ord(code[position3])
  2517. assert len(newvalue) == length1 + length2 + length3
  2518. frame._put_back_list_of_boxes(newvalue, 0, position)
  2519. frame._put_back_list_of_boxes(newvalue, length1, position2)
  2520. frame._put_back_list_of_boxes(newvalue, length1 + length2, position3)