PageRenderTime 62ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/rpython/jit/metainterp/pyjitpl.py

https://bitbucket.org/kcr/pypy
Python | 2788 lines | 2584 code | 94 blank | 110 comment | 86 complexity | 66d59713339bae352d9c3b056ff06f53 MD5 | raw file
Possible License(s): Apache-2.0
  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(lltype.Void, 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 and resbox:
  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. for val in ['int', 'float', 'ref', 'void']:
  1259. fullname = 'done_with_this_frame_descr_' + val
  1260. setattr(self.cpu, fullname, getattr(self, fullname))
  1261. d = self.exit_frame_with_exception_descr_ref
  1262. self.cpu.exit_frame_with_exception_descr_ref = d
  1263. def _freeze_(self):
  1264. return True
  1265. def setup_insns(self, insns):
  1266. self.opcode_names = ['?'] * len(insns)
  1267. self.opcode_implementations = [None] * len(insns)
  1268. for key, value in insns.items():
  1269. assert self.opcode_implementations[value] is None
  1270. self.opcode_names[value] = key
  1271. name, argcodes = key.split('/')
  1272. opimpl = _get_opimpl_method(name, argcodes)
  1273. self.opcode_implementations[value] = opimpl
  1274. self.op_catch_exception = insns.get('catch_exception/L', -1)
  1275. def setup_descrs(self, descrs):
  1276. self.opcode_descrs = descrs
  1277. def setup_indirectcalltargets(self, indirectcalltargets):
  1278. self.indirectcalltargets = list(indirectcalltargets)
  1279. def setup_list_of_addr2name(self, list_of_addr2name):
  1280. self._addr2name_keys = [key for key, value in list_of_addr2name]
  1281. self._addr2name_values = [value for key, value in list_of_addr2name]
  1282. def finish_setup(self, codewriter, optimizer=None):
  1283. from rpython.jit.metainterp.blackhole import BlackholeInterpBuilder
  1284. self.blackholeinterpbuilder = BlackholeInterpBuilder(codewriter, self)
  1285. #
  1286. asm = codewriter.assembler
  1287. self.setup_insns(asm.insns)
  1288. self.setup_descrs(asm.descrs)
  1289. self.setup_indirectcalltargets(asm.indirectcalltargets)
  1290. self.setup_list_of_addr2name(asm.list_of_addr2name)
  1291. #
  1292. self.jitdrivers_sd = codewriter.callcontrol.jitdrivers_sd
  1293. self.virtualref_info = codewriter.callcontrol.virtualref_info
  1294. self.callinfocollection = codewriter.callcontrol.callinfocollection
  1295. self.has_libffi_call = codewriter.callcontrol.has_libffi_call
  1296. #
  1297. # store this information for fastpath of call_assembler
  1298. # (only the paths that can actually be taken)
  1299. exc_descr = compile.PropagateExceptionDescr()
  1300. for jd in self.jitdrivers_sd:
  1301. name = {history.INT: 'int',
  1302. history.REF: 'ref',
  1303. history.FLOAT: 'float',
  1304. history.VOID: 'void'}[jd.result_type]
  1305. tokens = getattr(self, 'loop_tokens_done_with_this_frame_%s' % name)
  1306. jd.portal_finishtoken = tokens[0].finishdescr
  1307. jd.propagate_exc_descr = exc_descr
  1308. #
  1309. self.cpu.propagate_exception_descr = exc_descr
  1310. #
  1311. self.globaldata = MetaInterpGlobalData(self)
  1312. def _setup_once(self):
  1313. """Runtime setup needed by the various components of the JIT."""
  1314. if not self.globaldata.initialized:
  1315. debug_print(self.jit_starting_line)
  1316. self.cpu.setup_once()
  1317. if not self.profiler.initialized:
  1318. self.profiler.start()
  1319. self.profiler.initialized = True
  1320. self.globaldata.initialized = True
  1321. def get_name_from_address(self, addr):
  1322. # for debugging only
  1323. if we_are_translated():
  1324. d = self.globaldata.addr2name
  1325. if d is None:
  1326. # Build the dictionary at run-time. This is needed
  1327. # because the keys are function/class addresses, so they
  1328. # can change from run to run.
  1329. d = {}
  1330. keys = self._addr2name_keys
  1331. values = self._addr2name_values
  1332. for i in range(len(keys)):
  1333. d[keys[i]] = values[i]
  1334. self.globaldata.addr2name = d
  1335. return d.get(addr, '')
  1336. else:
  1337. for i in range(len(self._addr2name_keys)):
  1338. if addr == self._addr2name_keys[i]:
  1339. return self._addr2name_values[i]
  1340. return ''
  1341. def bytecode_for_address(self, fnaddress):
  1342. if we_are_translated():
  1343. d = self.globaldata.indirectcall_dict
  1344. if d is None:
  1345. # Build the dictionary at run-time. This is needed
  1346. # because the keys are function addresses, so they
  1347. # can change from run to run.
  1348. d = {}
  1349. for jitcode in self.indirectcalltargets:
  1350. assert jitcode.fnaddr not in d
  1351. d[jitcode.fnaddr] = jitcode
  1352. self.globaldata.indirectcall_dict = d
  1353. return d.get(fnaddress, None)
  1354. else:
  1355. for jitcode in self.indirectcalltargets:
  1356. if jitcode.fnaddr == fnaddress:
  1357. return jitcode
  1358. return None
  1359. def try_to_free_some_loops(self):
  1360. # Increase here the generation recorded by the memory manager.
  1361. if self.warmrunnerdesc is not None: # for tests
  1362. self.warmrunnerdesc.memory_manager.next_generation()
  1363. # ---------------- logging ------------------------
  1364. def log(self, msg):
  1365. debug_print(msg)
  1366. # ____________________________________________________________
  1367. class MetaInterpGlobalData(object):
  1368. """This object contains the JIT's global, mutable data.
  1369. Warning: for any data that you put here, think that there might be
  1370. multiple MetaInterps accessing it at the same time. As usual we are
  1371. safe from corruption thanks to the GIL, but keep in mind that any
  1372. MetaInterp might modify any of these fields while another MetaInterp
  1373. is, say, currently in a residual call to a function. Multiple
  1374. MetaInterps occur either with threads or, in single-threaded cases,
  1375. with recursion. This is a case that is not well-tested, so please
  1376. be careful :-( But thankfully this is one of the very few places
  1377. where multiple concurrent MetaInterps may interact with each other.
  1378. """
  1379. def __init__(self, staticdata):
  1380. self.initialized = False
  1381. self.indirectcall_dict = None
  1382. self.addr2name = None
  1383. self.loopnumbering = 0
  1384. # ____________________________________________________________
  1385. class MetaInterp(object):
  1386. portal_call_depth = 0
  1387. cancel_count = 0
  1388. def __init__(self, staticdata, jitdriver_sd):
  1389. self.staticdata = staticdata
  1390. self.cpu = staticdata.cpu
  1391. self.jitdriver_sd = jitdriver_sd
  1392. # Note: self.jitdriver_sd is the JitDriverStaticData that corresponds
  1393. # to the current loop -- the outermost one. Be careful, because
  1394. # during recursion we can also see other jitdrivers.
  1395. self.portal_trace_positions = []
  1396. self.free_frames_list = []
  1397. self.last_exc_value_box = None
  1398. self.partial_trace = None
  1399. self.retracing_from = -1
  1400. self.call_pure_results = args_dict_box()
  1401. self.heapcache = HeapCache()
  1402. self.call_ids = []
  1403. self.current_call_id = 0
  1404. def retrace_needed(self, trace):
  1405. self.partial_trace = trace
  1406. self.retracing_from = len(self.history.operations) - 1
  1407. self.heapcache.reset()
  1408. def perform_call(self, jitcode, boxes, greenkey=None):
  1409. # causes the metainterp to enter the given subfunction
  1410. f = self.newframe(jitcode, greenkey)
  1411. f.setup_call(boxes)
  1412. raise ChangeFrame
  1413. def is_main_jitcode(self, jitcode):
  1414. return self.jitdriver_sd is not None and jitcode is self.jitdriver_sd.mainjitcode
  1415. def newframe(self, jitcode, greenkey=None):
  1416. if jitcode.is_portal:
  1417. self.portal_call_depth += 1
  1418. self.call_ids.append(self.current_call_id)
  1419. self.current_call_id += 1
  1420. if greenkey is not None and self.is_main_jitcode(jitcode):
  1421. self.portal_trace_positions.append(
  1422. (greenkey, len(self.history.operations)))
  1423. if len(self.free_frames_list) > 0:
  1424. f = self.free_frames_list.pop()
  1425. else:
  1426. f = MIFrame(self)
  1427. f.setup(jitcode, greenkey)
  1428. self.framestack.append(f)
  1429. return f
  1430. def popframe(self):
  1431. frame = self.framestack.pop()
  1432. jitcode = frame.jitcode
  1433. if jitcode.is_portal:
  1434. self.portal_call_depth -= 1
  1435. self.call_ids.pop()
  1436. if frame.greenkey is not None and self.is_main_jitcode(jitcode):
  1437. self.portal_trace_positions.append(
  1438. (None, len(self.history.operations)))
  1439. # we save the freed MIFrames to avoid needing to re-create new
  1440. # MIFrame objects all the time; they are a bit big, with their
  1441. # 3*256 register entries.
  1442. frame.cleanup_registers()
  1443. self.free_frames_list.append(frame)
  1444. def finishframe(self, resultbox):
  1445. # handle a non-exceptional return from the current frame
  1446. self.last_exc_value_box = None
  1447. self.popframe()
  1448. if self.framestack:
  1449. if resultbox is not None:
  1450. self.framestack[-1].make_result_of_lastop(resultbox)
  1451. raise ChangeFrame
  1452. else:
  1453. try:
  1454. self.compile_done_with_this_frame(resultbox)
  1455. except SwitchToBlackhole, stb:
  1456. self.aborted_tracing(stb.reason)
  1457. sd = self.staticdata
  1458. result_type = self.jitdriver_sd.result_type
  1459. if result_type == history.VOID:
  1460. assert resultbox is None
  1461. raise sd.DoneWithThisFrameVoid()
  1462. elif result_type == history.INT:
  1463. raise sd.DoneWithThisFrameInt(resultbox.getint())
  1464. elif result_type == history.REF:
  1465. raise sd.DoneWithThisFrameRef(self.cpu, resultbox.getref_base())
  1466. elif result_type == history.FLOAT:
  1467. raise sd.DoneWithThisFrameFloat(resultbox.getfloatstorage())
  1468. else:
  1469. assert False
  1470. def finishframe_exception(self):
  1471. excvaluebox = self.last_exc_value_box
  1472. while self.framestack:
  1473. frame = self.framestack[-1]
  1474. code = frame.bytecode
  1475. position = frame.pc # <-- just after the insn that raised
  1476. if position < len(code):
  1477. opcode = ord(code[position])
  1478. if opcode == self.staticdata.op_catch_exception:
  1479. # found a 'catch_exception' instruction;
  1480. # jump to the handler
  1481. target = ord(code[position+1]) | (ord(code[position+2])<<8)
  1482. frame.pc = target
  1483. raise ChangeFrame
  1484. self.popframe()
  1485. try:
  1486. self.compile_exit_frame_with_exception(excvaluebox)
  1487. except SwitchToBlackhole, stb:
  1488. self.aborted_tracing(stb.reason)
  1489. raise self.staticdata.ExitFrameWithExceptionRef(self.cpu, excvaluebox.getref_base())
  1490. def check_recursion_invariant(self):
  1491. portal_call_depth = -1
  1492. for frame in self.framestack:
  1493. jitcode = frame.jitcode
  1494. assert jitcode.is_portal == len([
  1495. jd for jd in self.staticdata.jitdrivers_sd
  1496. if jd.mainjitcode is jitcode])
  1497. if jitcode.is_portal:
  1498. portal_call_depth += 1
  1499. if portal_call_depth != self.portal_call_depth:
  1500. print "portal_call_depth problem!!!"
  1501. print portal_call_depth, self.portal_call_depth
  1502. for frame in self.framestack:
  1503. jitcode = frame.jitcode
  1504. if jitcode.is_portal:
  1505. print "P",
  1506. else:
  1507. print " ",
  1508. print jitcode.name
  1509. raise AssertionError
  1510. def create_empty_history(self):
  1511. self.history = history.History()
  1512. self.staticdata.stats.set_history(self.history)
  1513. def _all_constants(self, *boxes):
  1514. if len(boxes) == 0:
  1515. return True
  1516. return isinstance(boxes[0], Const) and self._all_constants(*boxes[1:])
  1517. def _all_constants_varargs(self, boxes):
  1518. for box in boxes:
  1519. if not isinstance(box, Const):
  1520. return False
  1521. return True
  1522. @specialize.arg(1)
  1523. def execute_and_record(self, opnum, descr, *argboxes):
  1524. history.check_descr(descr)
  1525. assert not (rop._CANRAISE_FIRST <= opnum <= rop._CANRAISE_LAST)
  1526. # execute the operation
  1527. profiler = self.staticdata.profiler
  1528. profiler.count_ops(opnum)
  1529. resbox = executor.execute(self.cpu, self, opnum, descr, *argboxes)
  1530. if rop._ALWAYS_PURE_FIRST <= opnum <= rop._ALWAYS_PURE_LAST:
  1531. return self._record_helper_pure(opnum, resbox, descr, *argboxes)
  1532. else:
  1533. return self._record_helper_nonpure_varargs(opnum, resbox, descr,
  1534. list(argboxes))
  1535. @specialize.arg(1)
  1536. def execute_and_record_varargs(self, opnum, argboxes, descr=None):
  1537. history.check_descr(descr)
  1538. # execute the operation
  1539. profiler = self.staticdata.profiler
  1540. profiler.count_ops(opnum)
  1541. resbox = executor.execute_varargs(self.cpu, self,
  1542. opnum, argboxes, descr)
  1543. # check if the operation can be constant-folded away
  1544. argboxes = list(argboxes)
  1545. if rop._ALWAYS_PURE_FIRST <= opnum <= rop._ALWAYS_PURE_LAST:
  1546. resbox = self._record_helper_pure_varargs(opnum, resbox, descr, argboxes)
  1547. else:
  1548. resbox = self._record_helper_nonpure_varargs(opnum, resbox, descr, argboxes)
  1549. return resbox
  1550. def _record_helper_pure(self, opnum, resbox, descr, *argboxes):
  1551. canfold = self._all_constants(*argboxes)
  1552. if canfold:
  1553. resbox = resbox.constbox() # ensure it is a Const
  1554. return resbox
  1555. else:
  1556. resbox = resbox.nonconstbox() # ensure it is a Box
  1557. return self._record_helper_nonpure_varargs(opnum, resbox, descr, list(argboxes))
  1558. def _record_helper_pure_varargs(self, opnum, resbox, descr, argboxes):
  1559. canfold = self._all_constants_varargs(argboxes)
  1560. if canfold:
  1561. resbox = resbox.constbox() # ensure it is a Const
  1562. return resbox
  1563. else:
  1564. resbox = resbox.nonconstbox() # ensure it is a Box
  1565. return self._record_helper_nonpure_varargs(opnum, resbox, descr, argboxes)
  1566. def _record_helper_nonpure_varargs(self, opnum, resbox, descr, argboxes):
  1567. assert resbox is None or isinstance(resbox, Box)
  1568. if (rop._OVF_FIRST <= opnum <= rop._OVF_LAST and
  1569. self.last_exc_value_box is None and
  1570. self._all_constants_varargs(argboxes)):
  1571. return resbox.constbox()
  1572. # record the operation
  1573. profiler = self.staticdata.profiler
  1574. profiler.count_ops(opnum, Counters.RECORDED_OPS)
  1575. self.heapcache.invalidate_caches(opnum, descr, argboxes)
  1576. op = self.history.record(opnum, argboxes, resbox, descr)
  1577. self.attach_debug_info(op)
  1578. return resbox
  1579. def attach_debug_info(self, op):
  1580. if (not we_are_translated() and op is not None
  1581. and getattr(self, 'framestack', None)):
  1582. op.pc = self.framestack[-1].pc
  1583. op.name = self.framestack[-1].jitcode.name
  1584. def execute_raised(self, exception, constant=False):
  1585. if isinstance(exception, JitException):
  1586. raise JitException, exception # go through
  1587. llexception = get_llexception(self.cpu, exception)
  1588. self.execute_ll_raised(llexception, constant)
  1589. def execute_ll_raised(self, llexception, constant=False):
  1590. # Exception handling: when execute.do_call() gets an exception it
  1591. # calls metainterp.execute_raised(), which puts it into
  1592. # 'self.last_exc_value_box'. This is used shortly afterwards
  1593. # to generate either GUARD_EXCEPTION or GUARD_NO_EXCEPTION, and also
  1594. # to handle the following opcodes 'goto_if_exception_mismatch'.
  1595. llexception = self.cpu.ts.cast_to_ref(llexception)
  1596. exc_value_box = self.cpu.ts.get_exc_value_box(llexception)
  1597. if constant:
  1598. exc_value_box = exc_value_box.constbox()
  1599. self.last_exc_value_box = exc_value_box
  1600. self.class_of_last_exc_is_const = constant
  1601. # 'class_of_last_exc_is_const' means that the class of the value
  1602. # stored in the exc_value Box can be assumed to be a Const. This
  1603. # is only True after a GUARD_EXCEPTION or GUARD_CLASS.
  1604. def clear_exception(self):
  1605. self.last_exc_value_box = None
  1606. def aborted_tracing(self, reason):
  1607. self.staticdata.profiler.count(reason)
  1608. debug_print('~~~ ABORTING TRACING')
  1609. jd_sd = self.jitdriver_sd
  1610. if not self.current_merge_points:
  1611. greenkey = None # we're in the bridge
  1612. else:
  1613. greenkey = self.current_merge_points[0][0][:jd_sd.num_green_args]
  1614. self.staticdata.warmrunnerdesc.hooks.on_abort(reason,
  1615. jd_sd.jitdriver,
  1616. greenkey,
  1617. jd_sd.warmstate.get_location_str(greenkey))
  1618. self.staticdata.stats.aborted()
  1619. def blackhole_if_trace_too_long(self):
  1620. warmrunnerstate = self.jitdriver_sd.warmstate
  1621. if len(self.history.operations) > warmrunnerstate.trace_limit:
  1622. greenkey_of_huge_function = self.find_biggest_function()
  1623. self.staticdata.stats.record_aborted(greenkey_of_huge_function)
  1624. self.portal_trace_positions = None
  1625. if greenkey_of_huge_function is not None:
  1626. warmrunnerstate.disable_noninlinable_function(
  1627. greenkey_of_huge_function)
  1628. raise SwitchToBlackhole(Counters.ABORT_TOO_LONG)
  1629. def _interpret(self):
  1630. # Execute the frames forward until we raise a DoneWithThisFrame,
  1631. # a ExitFrameWithException, or a ContinueRunningNormally exception.
  1632. self.staticdata.stats.entered()
  1633. while True:
  1634. self.framestack[-1].run_one_step()
  1635. self.blackhole_if_trace_too_long()
  1636. if not we_are_translated():
  1637. self.check_recursion_invariant()
  1638. def interpret(self):
  1639. if we_are_translated():
  1640. self._interpret()
  1641. else:
  1642. try:
  1643. self._interpret()
  1644. except:
  1645. import sys
  1646. if sys.exc_info()[0] is not None:
  1647. self.staticdata.log(sys.exc_info()[0].__name__)
  1648. raise
  1649. @specialize.arg(1)
  1650. def compile_and_run_once(self, jitdriver_sd, *args):
  1651. # NB. we pass explicity 'jitdriver_sd' around here, even though it
  1652. # is also available as 'self.jitdriver_sd', because we need to
  1653. # specialize this function and a few other ones for the '*args'.
  1654. debug_start('jit-tracing')
  1655. self.staticdata._setup_once()
  1656. self.staticdata.profiler.start_tracing()
  1657. assert jitdriver_sd is self.jitdriver_sd
  1658. self.staticdata.try_to_free_some_loops()
  1659. self.create_empty_history()
  1660. try:
  1661. original_boxes = self.initialize_original_boxes(jitdriver_sd, *args)
  1662. return self._compile_and_run_once(original_boxes)
  1663. finally:
  1664. self.staticdata.profiler.end_tracing()
  1665. debug_stop('jit-tracing')
  1666. def _compile_and_run_once(self, original_boxes):
  1667. self.initialize_state_from_start(original_boxes)
  1668. self.current_merge_points = [(original_boxes, 0)]
  1669. num_green_args = self.jitdriver_sd.num_green_args
  1670. original_greenkey = original_boxes[:num_green_args]
  1671. self.resumekey = compile.ResumeFromInterpDescr(original_greenkey)
  1672. self.history.inputargs = original_boxes[num_green_args:]
  1673. self.seen_loop_header_for_jdindex = -1
  1674. try:
  1675. self.interpret()
  1676. except SwitchToBlackhole, stb:
  1677. self.run_blackhole_interp_to_cancel_tracing(stb)
  1678. assert False, "should always raise"
  1679. def handle_guard_failure(self, key, deadframe):
  1680. debug_start('jit-tracing')
  1681. self.staticdata.profiler.start_tracing()
  1682. assert isinstance(key, compile.ResumeGuardDescr)
  1683. # store the resumekey.wref_original_loop_token() on 'self' to make
  1684. # sure that it stays alive as long as this MetaInterp
  1685. self.resumekey_original_loop_token = key.wref_original_loop_token()
  1686. self.staticdata.try_to_free_some_loops()
  1687. self.initialize_state_from_guard_failure(key, deadframe)
  1688. try:
  1689. return self._handle_guard_failure(key, deadframe)
  1690. finally:
  1691. self.resumekey_original_loop_token = None
  1692. self.staticdata.profiler.end_tracing()
  1693. debug_stop('jit-tracing')
  1694. def _handle_guard_failure(self, key, deadframe):
  1695. self.current_merge_points = []
  1696. self.resumekey = key
  1697. self.seen_loop_header_for_jdindex = -1
  1698. if isinstance(key, compile.ResumeAtPositionDescr):
  1699. self.seen_loop_header_for_jdindex = self.jitdriver_sd.index
  1700. dont_change_position = True
  1701. else:
  1702. dont_change_position = False
  1703. try:
  1704. self.prepare_resume_from_failure(key.guard_opnum,
  1705. dont_change_position,
  1706. deadframe)
  1707. if self.resumekey_original_loop_token is None: # very rare case
  1708. raise SwitchToBlackhole(Counters.ABORT_BRIDGE)
  1709. self.interpret()
  1710. except SwitchToBlackhole, stb:
  1711. self.run_blackhole_interp_to_cancel_tracing(stb)
  1712. assert False, "should always raise"
  1713. def run_blackhole_interp_to_cancel_tracing(self, stb):
  1714. # We got a SwitchToBlackhole exception. Convert the framestack into
  1715. # a stack of blackhole interpreters filled with the same values, and
  1716. # run it.
  1717. from rpython.jit.metainterp.blackhole import convert_and_run_from_pyjitpl
  1718. self.aborted_tracing(stb.reason)
  1719. convert_and_run_from_pyjitpl(self, stb.raising_exception)
  1720. assert False # ^^^ must raise
  1721. def remove_consts_and_duplicates(self, boxes, endindex, duplicates):
  1722. for i in range(endindex):
  1723. box = boxes[i]
  1724. if isinstance(box, Const) or box in duplicates:
  1725. oldbox = box
  1726. box = oldbox.clonebox()
  1727. boxes[i] = box
  1728. self.history.record(rop.SAME_AS, [oldbox], box)
  1729. else:
  1730. duplicates[box] = None
  1731. def reached_loop_header(self, greenboxes, redboxes, resumedescr):
  1732. self.heapcache.reset()
  1733. duplicates = {}
  1734. self.remove_consts_and_duplicates(redboxes, len(redboxes),
  1735. duplicates)
  1736. live_arg_boxes = greenboxes + redboxes
  1737. if self.jitdriver_sd.virtualizable_info is not None:
  1738. # we use pop() to remove the last item, which is the virtualizable
  1739. # itself
  1740. self.remove_consts_and_duplicates(self.virtualizable_boxes,
  1741. len(self.virtualizable_boxes)-1,
  1742. duplicates)
  1743. live_arg_boxes += self.virtualizable_boxes
  1744. live_arg_boxes.pop()
  1745. #
  1746. assert len(self.virtualref_boxes) == 0, "missing virtual_ref_finish()?"
  1747. # Called whenever we reach the 'loop_header' hint.
  1748. # First, attempt to make a bridge:
  1749. # - if self.resumekey is a ResumeGuardDescr, it starts from a guard
  1750. # that failed;
  1751. # - if self.resumekey is a ResumeFromInterpDescr, it starts directly
  1752. # from the interpreter.
  1753. if not self.partial_trace:
  1754. # FIXME: Support a retrace to be a bridge as well as a loop
  1755. self.compile_trace(live_arg_boxes, resumedescr)
  1756. # raises in case it works -- which is the common case, hopefully,
  1757. # at least for bridges starting from a guard.
  1758. # Search in current_merge_points for original_boxes with compatible
  1759. # green keys, representing the beginning of the same loop as the one
  1760. # we end now.
  1761. num_green_args = self.jitdriver_sd.num_green_args
  1762. for j in range(len(self.current_merge_points)-1, -1, -1):
  1763. original_boxes, start = self.current_merge_points[j]
  1764. assert len(original_boxes) == len(live_arg_boxes)
  1765. for i in range(num_green_args):
  1766. box1 = original_boxes[i]
  1767. box2 = live_arg_boxes[i]
  1768. assert isinstance(box1, Const)
  1769. if not box1.same_constant(box2):
  1770. break
  1771. else:
  1772. # Found! Compile it as a loop.
  1773. # raises in case it works -- which is the common case
  1774. if self.partial_trace:
  1775. if start != self.retracing_from:
  1776. raise SwitchToBlackhole(Counters.ABORT_BAD_LOOP) # For now
  1777. self.compile_loop(original_boxes, live_arg_boxes, start, resumedescr)
  1778. # creation of the loop was cancelled!
  1779. self.cancel_count += 1
  1780. if self.staticdata.warmrunnerdesc:
  1781. memmgr = self.staticdata.warmrunnerdesc.memory_manager
  1782. if memmgr:
  1783. if self.cancel_count > memmgr.max_unroll_loops:
  1784. self.compile_loop_or_abort(original_boxes,
  1785. live_arg_boxes,
  1786. start, resumedescr)
  1787. self.staticdata.log('cancelled, tracing more...')
  1788. # Otherwise, no loop found so far, so continue tracing.
  1789. start = len(self.history.operations)
  1790. self.current_merge_points.append((live_arg_boxes, start))
  1791. def _unpack_boxes(self, boxes, start, stop):
  1792. ints = []; refs = []; floats = []
  1793. for i in range(start, stop):
  1794. box = boxes[i]
  1795. if box.type == history.INT: ints.append(box.getint())
  1796. elif box.type == history.REF: refs.append(box.getref_base())
  1797. elif box.type == history.FLOAT:floats.append(box.getfloatstorage())
  1798. else: assert 0
  1799. return ints[:], refs[:], floats[:]
  1800. def raise_continue_running_normally(self, live_arg_boxes, loop_token):
  1801. self.history.inputargs = None
  1802. self.history.operations = None
  1803. # For simplicity, we just raise ContinueRunningNormally here and
  1804. # ignore the loop_token passed in. It means that we go back to
  1805. # interpreted mode, but it should come back very quickly to the
  1806. # JIT, find probably the same 'loop_token', and execute it.
  1807. if we_are_translated():
  1808. num_green_args = self.jitdriver_sd.num_green_args
  1809. gi, gr, gf = self._unpack_boxes(live_arg_boxes, 0, num_green_args)
  1810. ri, rr, rf = self._unpack_boxes(live_arg_boxes, num_green_args,
  1811. len(live_arg_boxes))
  1812. CRN = self.staticdata.ContinueRunningNormally
  1813. raise CRN(gi, gr, gf, ri, rr, rf)
  1814. else:
  1815. # However, in order to keep the existing tests working
  1816. # (which are based on the assumption that 'loop_token' is
  1817. # directly used here), a bit of custom non-translatable code...
  1818. self._nontranslated_run_directly(live_arg_boxes, loop_token)
  1819. assert 0, "unreachable"
  1820. def _nontranslated_run_directly(self, live_arg_boxes, loop_token):
  1821. "NOT_RPYTHON"
  1822. args = []
  1823. num_green_args = self.jitdriver_sd.num_green_args
  1824. num_red_args = self.jitdriver_sd.num_red_args
  1825. for box in live_arg_boxes[num_green_args:num_green_args+num_red_args]:
  1826. if box.type == history.INT: args.append(box.getint())
  1827. elif box.type == history.REF: args.append(box.getref_base())
  1828. elif box.type == history.FLOAT: args.append(box.getfloatstorage())
  1829. else: assert 0
  1830. self.jitdriver_sd.warmstate.execute_assembler(loop_token, *args)
  1831. def prepare_resume_from_failure(self, opnum, dont_change_position,
  1832. deadframe):
  1833. frame = self.framestack[-1]
  1834. if opnum == rop.GUARD_TRUE: # a goto_if_not that jumps only now
  1835. if not dont_change_position:
  1836. frame.pc = frame.jitcode.follow_jump(frame.pc)
  1837. elif opnum == rop.GUARD_FALSE: # a goto_if_not that stops jumping
  1838. pass
  1839. elif opnum == rop.GUARD_VALUE or opnum == rop.GUARD_CLASS:
  1840. pass # the pc is already set to the *start* of the opcode
  1841. elif (opnum == rop.GUARD_NONNULL or
  1842. opnum == rop.GUARD_ISNULL or
  1843. opnum == rop.GUARD_NONNULL_CLASS):
  1844. pass # the pc is already set to the *start* of the opcode
  1845. elif opnum == rop.GUARD_NO_EXCEPTION or opnum == rop.GUARD_EXCEPTION:
  1846. exception = self.cpu.grab_exc_value(deadframe)
  1847. if exception:
  1848. self.execute_ll_raised(lltype.cast_opaque_ptr(rclass.OBJECTPTR,
  1849. exception))
  1850. else:
  1851. self.clear_exception()
  1852. try:
  1853. self.handle_possible_exception()
  1854. except ChangeFrame:
  1855. pass
  1856. elif opnum == rop.GUARD_NOT_INVALIDATED:
  1857. pass # XXX we want to do something special in resume descr,
  1858. # but not now
  1859. elif opnum == rop.GUARD_NO_OVERFLOW: # an overflow now detected
  1860. if not dont_change_position:
  1861. self.execute_raised(OverflowError(), constant=True)
  1862. try:
  1863. self.finishframe_exception()
  1864. except ChangeFrame:
  1865. pass
  1866. elif opnum == rop.GUARD_OVERFLOW: # no longer overflowing
  1867. self.clear_exception()
  1868. else:
  1869. from rpython.jit.metainterp.resoperation import opname
  1870. raise NotImplementedError(opname[opnum])
  1871. def get_procedure_token(self, greenkey, with_compiled_targets=False):
  1872. cell = self.jitdriver_sd.warmstate.jit_cell_at_key(greenkey)
  1873. token = cell.get_procedure_token()
  1874. if with_compiled_targets:
  1875. if not token:
  1876. return None
  1877. if not token.target_tokens:
  1878. return None
  1879. return token
  1880. def compile_loop(self, original_boxes, live_arg_boxes, start,
  1881. resume_at_jump_descr, try_disabling_unroll=False):
  1882. num_green_args = self.jitdriver_sd.num_green_args
  1883. greenkey = original_boxes[:num_green_args]
  1884. if not self.partial_trace:
  1885. ptoken = self.get_procedure_token(greenkey)
  1886. if ptoken is not None and ptoken.target_tokens is not None:
  1887. # XXX this path not tested, but shown to occur on pypy-c :-(
  1888. self.staticdata.log('cancelled: we already have a token now')
  1889. raise SwitchToBlackhole(Counters.ABORT_BAD_LOOP)
  1890. if self.partial_trace:
  1891. target_token = compile.compile_retrace(self, greenkey, start,
  1892. original_boxes[num_green_args:],
  1893. live_arg_boxes[num_green_args:],
  1894. resume_at_jump_descr, self.partial_trace,
  1895. self.resumekey)
  1896. else:
  1897. target_token = compile.compile_loop(self, greenkey, start,
  1898. original_boxes[num_green_args:],
  1899. live_arg_boxes[num_green_args:],
  1900. resume_at_jump_descr,
  1901. try_disabling_unroll=try_disabling_unroll)
  1902. if target_token is not None:
  1903. assert isinstance(target_token, TargetToken)
  1904. self.jitdriver_sd.warmstate.attach_procedure_to_interp(greenkey, target_token.targeting_jitcell_token)
  1905. self.staticdata.stats.add_jitcell_token(target_token.targeting_jitcell_token)
  1906. if target_token is not None: # raise if it *worked* correctly
  1907. assert isinstance(target_token, TargetToken)
  1908. jitcell_token = target_token.targeting_jitcell_token
  1909. self.raise_continue_running_normally(live_arg_boxes, jitcell_token)
  1910. def compile_loop_or_abort(self, original_boxes, live_arg_boxes,
  1911. start, resume_at_jump_descr):
  1912. """Called after we aborted more than 'max_unroll_loops' times.
  1913. As a last attempt, try to compile the loop with unrolling disabled.
  1914. """
  1915. if not self.partial_trace:
  1916. self.compile_loop(original_boxes, live_arg_boxes, start,
  1917. resume_at_jump_descr, try_disabling_unroll=True)
  1918. #
  1919. self.staticdata.log('cancelled too many times!')
  1920. raise SwitchToBlackhole(Counters.ABORT_BAD_LOOP)
  1921. def compile_trace(self, live_arg_boxes, resume_at_jump_descr):
  1922. num_green_args = self.jitdriver_sd.num_green_args
  1923. greenkey = live_arg_boxes[:num_green_args]
  1924. target_jitcell_token = self.get_procedure_token(greenkey, True)
  1925. if not target_jitcell_token:
  1926. return
  1927. self.history.record(rop.JUMP, live_arg_boxes[num_green_args:], None,
  1928. descr=target_jitcell_token)
  1929. try:
  1930. target_token = compile.compile_trace(self, self.resumekey, resume_at_jump_descr)
  1931. finally:
  1932. self.history.operations.pop() # remove the JUMP
  1933. if target_token is not None: # raise if it *worked* correctly
  1934. assert isinstance(target_token, TargetToken)
  1935. jitcell_token = target_token.targeting_jitcell_token
  1936. self.raise_continue_running_normally(live_arg_boxes, jitcell_token)
  1937. def compile_done_with_this_frame(self, exitbox):
  1938. self.gen_store_back_in_virtualizable()
  1939. # temporarily put a JUMP to a pseudo-loop
  1940. sd = self.staticdata
  1941. result_type = self.jitdriver_sd.result_type
  1942. if result_type == history.VOID:
  1943. assert exitbox is None
  1944. exits = []
  1945. loop_tokens = sd.loop_tokens_done_with_this_frame_void
  1946. elif result_type == history.INT:
  1947. exits = [exitbox]
  1948. loop_tokens = sd.loop_tokens_done_with_this_frame_int
  1949. elif result_type == history.REF:
  1950. exits = [exitbox]
  1951. loop_tokens = sd.loop_tokens_done_with_this_frame_ref
  1952. elif result_type == history.FLOAT:
  1953. exits = [exitbox]
  1954. loop_tokens = sd.loop_tokens_done_with_this_frame_float
  1955. else:
  1956. assert False
  1957. # FIXME: kill TerminatingLoopToken?
  1958. # FIXME: can we call compile_trace?
  1959. token = loop_tokens[0].finishdescr
  1960. self.history.record(rop.FINISH, exits, None, descr=token)
  1961. target_token = compile.compile_trace(self, self.resumekey)
  1962. if target_token is not token:
  1963. compile.giveup()
  1964. def compile_exit_frame_with_exception(self, valuebox):
  1965. self.gen_store_back_in_virtualizable()
  1966. sd = self.staticdata
  1967. token = sd.loop_tokens_exit_frame_with_exception_ref[0].finishdescr
  1968. self.history.record(rop.FINISH, [valuebox], None, descr=token)
  1969. target_token = compile.compile_trace(self, self.resumekey)
  1970. if target_token is not token:
  1971. compile.giveup()
  1972. @specialize.arg(1)
  1973. def initialize_original_boxes(self, jitdriver_sd, *args):
  1974. original_boxes = []
  1975. self._fill_original_boxes(jitdriver_sd, original_boxes,
  1976. jitdriver_sd.num_green_args, *args)
  1977. return original_boxes
  1978. @specialize.arg(1)
  1979. def _fill_original_boxes(self, jitdriver_sd, original_boxes,
  1980. num_green_args, *args):
  1981. if args:
  1982. from rpython.jit.metainterp.warmstate import wrap
  1983. box = wrap(self.cpu, args[0], num_green_args > 0)
  1984. original_boxes.append(box)
  1985. self._fill_original_boxes(jitdriver_sd, original_boxes,
  1986. num_green_args-1, *args[1:])
  1987. def initialize_state_from_start(self, original_boxes):
  1988. # ----- make a new frame -----
  1989. self.portal_call_depth = -1 # always one portal around
  1990. self.framestack = []
  1991. f = self.newframe(self.jitdriver_sd.mainjitcode)
  1992. f.setup_call(original_boxes)
  1993. assert self.portal_call_depth == 0
  1994. self.virtualref_boxes = []
  1995. self.initialize_withgreenfields(original_boxes)
  1996. self.initialize_virtualizable(original_boxes)
  1997. def initialize_state_from_guard_failure(self, resumedescr, deadframe):
  1998. # guard failure: rebuild a complete MIFrame stack
  1999. # This is stack-critical code: it must not be interrupted by StackOverflow,
  2000. # otherwise the jit_virtual_refs are left in a dangling state.
  2001. rstack._stack_criticalcode_start()
  2002. try:
  2003. self.portal_call_depth = -1 # always one portal around
  2004. self.history = history.History()
  2005. inputargs_and_holes = self.rebuild_state_after_failure(resumedescr,
  2006. deadframe)
  2007. self.history.inputargs = [box for box in inputargs_and_holes if box]
  2008. finally:
  2009. rstack._stack_criticalcode_stop()
  2010. def initialize_virtualizable(self, original_boxes):
  2011. vinfo = self.jitdriver_sd.virtualizable_info
  2012. if vinfo is not None:
  2013. index = (self.jitdriver_sd.num_green_args +
  2014. self.jitdriver_sd.index_of_virtualizable)
  2015. virtualizable_box = original_boxes[index]
  2016. virtualizable = vinfo.unwrap_virtualizable_box(virtualizable_box)
  2017. # The field 'virtualizable_boxes' is not even present
  2018. # if 'virtualizable_info' is None. Check for that first.
  2019. self.virtualizable_boxes = vinfo.read_boxes(self.cpu,
  2020. virtualizable)
  2021. original_boxes += self.virtualizable_boxes
  2022. self.virtualizable_boxes.append(virtualizable_box)
  2023. self.initialize_virtualizable_enter()
  2024. def initialize_withgreenfields(self, original_boxes):
  2025. ginfo = self.jitdriver_sd.greenfield_info
  2026. if ginfo is not None:
  2027. assert self.jitdriver_sd.virtualizable_info is None
  2028. index = (self.jitdriver_sd.num_green_args +
  2029. ginfo.red_index)
  2030. self.virtualizable_boxes = [original_boxes[index]]
  2031. def initialize_virtualizable_enter(self):
  2032. vinfo = self.jitdriver_sd.virtualizable_info
  2033. virtualizable_box = self.virtualizable_boxes[-1]
  2034. virtualizable = vinfo.unwrap_virtualizable_box(virtualizable_box)
  2035. vinfo.clear_vable_token(virtualizable)
  2036. def vable_and_vrefs_before_residual_call(self):
  2037. vrefinfo = self.staticdata.virtualref_info
  2038. for i in range(1, len(self.virtualref_boxes), 2):
  2039. vrefbox = self.virtualref_boxes[i]
  2040. vref = vrefbox.getref_base()
  2041. vrefinfo.tracing_before_residual_call(vref)
  2042. # the FORCE_TOKEN is already set at runtime in each vref when
  2043. # it is created, by optimizeopt.py.
  2044. #
  2045. vinfo = self.jitdriver_sd.virtualizable_info
  2046. if vinfo is not None:
  2047. virtualizable_box = self.virtualizable_boxes[-1]
  2048. virtualizable = vinfo.unwrap_virtualizable_box(virtualizable_box)
  2049. vinfo.tracing_before_residual_call(virtualizable)
  2050. #
  2051. force_token_box = history.BoxPtr()
  2052. self.history.record(rop.FORCE_TOKEN, [], force_token_box)
  2053. self.history.record(rop.SETFIELD_GC, [virtualizable_box,
  2054. force_token_box],
  2055. None, descr=vinfo.vable_token_descr)
  2056. def vrefs_after_residual_call(self):
  2057. vrefinfo = self.staticdata.virtualref_info
  2058. for i in range(0, len(self.virtualref_boxes), 2):
  2059. vrefbox = self.virtualref_boxes[i+1]
  2060. vref = vrefbox.getref_base()
  2061. if vrefinfo.tracing_after_residual_call(vref):
  2062. # this vref was really a virtual_ref, but it escaped
  2063. # during this CALL_MAY_FORCE. Mark this fact by
  2064. # generating a VIRTUAL_REF_FINISH on it and replacing
  2065. # it by ConstPtr(NULL).
  2066. self.stop_tracking_virtualref(i)
  2067. def vable_after_residual_call(self):
  2068. vinfo = self.jitdriver_sd.virtualizable_info
  2069. if vinfo is not None:
  2070. virtualizable_box = self.virtualizable_boxes[-1]
  2071. virtualizable = vinfo.unwrap_virtualizable_box(virtualizable_box)
  2072. if vinfo.tracing_after_residual_call(virtualizable):
  2073. # the virtualizable escaped during CALL_MAY_FORCE.
  2074. self.load_fields_from_virtualizable()
  2075. raise SwitchToBlackhole(Counters.ABORT_ESCAPE,
  2076. raising_exception=True)
  2077. # ^^^ we set 'raising_exception' to True because we must still
  2078. # have the eventual exception raised (this is normally done
  2079. # after the call to vable_after_residual_call()).
  2080. def stop_tracking_virtualref(self, i):
  2081. virtualbox = self.virtualref_boxes[i]
  2082. vrefbox = self.virtualref_boxes[i+1]
  2083. # record VIRTUAL_REF_FINISH just before the current CALL_MAY_FORCE
  2084. call_may_force_op = self.history.operations.pop()
  2085. assert call_may_force_op.getopnum() == rop.CALL_MAY_FORCE
  2086. self.history.record(rop.VIRTUAL_REF_FINISH,
  2087. [vrefbox, virtualbox], None)
  2088. self.history.operations.append(call_may_force_op)
  2089. # mark by replacing it with ConstPtr(NULL)
  2090. self.virtualref_boxes[i+1] = self.cpu.ts.CONST_NULL
  2091. def handle_possible_exception(self):
  2092. frame = self.framestack[-1]
  2093. if self.last_exc_value_box is not None:
  2094. exception_box = self.cpu.ts.cls_of_box(self.last_exc_value_box)
  2095. op = frame.generate_guard(rop.GUARD_EXCEPTION,
  2096. None, [exception_box])
  2097. assert op is not None
  2098. op.result = self.last_exc_value_box
  2099. self.class_of_last_exc_is_const = True
  2100. self.finishframe_exception()
  2101. else:
  2102. frame.generate_guard(rop.GUARD_NO_EXCEPTION, None, [])
  2103. def handle_possible_overflow_error(self):
  2104. frame = self.framestack[-1]
  2105. if self.last_exc_value_box is not None:
  2106. frame.generate_guard(rop.GUARD_OVERFLOW, None)
  2107. assert isinstance(self.last_exc_value_box, Const)
  2108. assert self.class_of_last_exc_is_const
  2109. self.finishframe_exception()
  2110. else:
  2111. frame.generate_guard(rop.GUARD_NO_OVERFLOW, None)
  2112. def assert_no_exception(self):
  2113. assert self.last_exc_value_box is None
  2114. def rebuild_state_after_failure(self, resumedescr, deadframe):
  2115. vinfo = self.jitdriver_sd.virtualizable_info
  2116. ginfo = self.jitdriver_sd.greenfield_info
  2117. self.framestack = []
  2118. boxlists = resume.rebuild_from_resumedata(self, resumedescr, deadframe,
  2119. vinfo, ginfo)
  2120. inputargs_and_holes, virtualizable_boxes, virtualref_boxes = boxlists
  2121. #
  2122. # virtual refs: make the vrefs point to the freshly allocated virtuals
  2123. self.virtualref_boxes = virtualref_boxes
  2124. vrefinfo = self.staticdata.virtualref_info
  2125. for i in range(0, len(virtualref_boxes), 2):
  2126. virtualbox = virtualref_boxes[i]
  2127. vrefbox = virtualref_boxes[i+1]
  2128. vrefinfo.continue_tracing(vrefbox.getref_base(),
  2129. virtualbox.getref_base())
  2130. #
  2131. # virtualizable: synchronize the real virtualizable and the local
  2132. # boxes, in whichever direction is appropriate
  2133. if vinfo is not None:
  2134. self.virtualizable_boxes = virtualizable_boxes
  2135. # just jumped away from assembler (case 4 in the comment in
  2136. # virtualizable.py) into tracing (case 2); check that vable_token
  2137. # is and stays NULL. Note the call to reset_vable_token() in
  2138. # warmstate.py.
  2139. virtualizable_box = self.virtualizable_boxes[-1]
  2140. virtualizable = vinfo.unwrap_virtualizable_box(virtualizable_box)
  2141. assert not vinfo.is_token_nonnull_gcref(virtualizable)
  2142. # fill the virtualizable with the local boxes
  2143. self.synchronize_virtualizable()
  2144. #
  2145. elif self.jitdriver_sd.greenfield_info:
  2146. self.virtualizable_boxes = virtualizable_boxes
  2147. else:
  2148. assert not virtualizable_boxes
  2149. #
  2150. return inputargs_and_holes
  2151. def check_synchronized_virtualizable(self):
  2152. if not we_are_translated():
  2153. vinfo = self.jitdriver_sd.virtualizable_info
  2154. virtualizable_box = self.virtualizable_boxes[-1]
  2155. virtualizable = vinfo.unwrap_virtualizable_box(virtualizable_box)
  2156. vinfo.check_boxes(virtualizable, self.virtualizable_boxes)
  2157. def synchronize_virtualizable(self):
  2158. vinfo = self.jitdriver_sd.virtualizable_info
  2159. virtualizable_box = self.virtualizable_boxes[-1]
  2160. virtualizable = vinfo.unwrap_virtualizable_box(virtualizable_box)
  2161. vinfo.write_boxes(virtualizable, self.virtualizable_boxes)
  2162. def load_fields_from_virtualizable(self):
  2163. # Force a reload of the virtualizable fields into the local
  2164. # boxes (called only in escaping cases). Only call this function
  2165. # just before SwitchToBlackhole.
  2166. vinfo = self.jitdriver_sd.virtualizable_info
  2167. if vinfo is not None:
  2168. virtualizable_box = self.virtualizable_boxes[-1]
  2169. virtualizable = vinfo.unwrap_virtualizable_box(virtualizable_box)
  2170. self.virtualizable_boxes = vinfo.read_boxes(self.cpu,
  2171. virtualizable)
  2172. self.virtualizable_boxes.append(virtualizable_box)
  2173. def gen_store_back_in_virtualizable(self):
  2174. vinfo = self.jitdriver_sd.virtualizable_info
  2175. if vinfo is not None:
  2176. # xxx only write back the fields really modified
  2177. vbox = self.virtualizable_boxes[-1]
  2178. for i in range(vinfo.num_static_extra_boxes):
  2179. fieldbox = self.virtualizable_boxes[i]
  2180. descr = vinfo.static_field_descrs[i]
  2181. self.execute_and_record(rop.SETFIELD_GC, descr, vbox, fieldbox)
  2182. i = vinfo.num_static_extra_boxes
  2183. virtualizable = vinfo.unwrap_virtualizable_box(vbox)
  2184. for k in range(vinfo.num_arrays):
  2185. descr = vinfo.array_field_descrs[k]
  2186. abox = self.execute_and_record(rop.GETFIELD_GC, descr, vbox)
  2187. descr = vinfo.array_descrs[k]
  2188. for j in range(vinfo.get_array_length(virtualizable, k)):
  2189. itembox = self.virtualizable_boxes[i]
  2190. i += 1
  2191. self.execute_and_record(rop.SETARRAYITEM_GC, descr,
  2192. abox, ConstInt(j), itembox)
  2193. assert i + 1 == len(self.virtualizable_boxes)
  2194. def replace_box(self, oldbox, newbox):
  2195. assert isinstance(oldbox, Box)
  2196. for frame in self.framestack:
  2197. frame.replace_active_box_in_frame(oldbox, newbox)
  2198. boxes = self.virtualref_boxes
  2199. for i in range(len(boxes)):
  2200. if boxes[i] is oldbox:
  2201. boxes[i] = newbox
  2202. if (self.jitdriver_sd.virtualizable_info is not None or
  2203. self.jitdriver_sd.greenfield_info is not None):
  2204. boxes = self.virtualizable_boxes
  2205. for i in range(len(boxes)):
  2206. if boxes[i] is oldbox:
  2207. boxes[i] = newbox
  2208. self.heapcache.replace_box(oldbox, newbox)
  2209. def find_biggest_function(self):
  2210. start_stack = []
  2211. max_size = 0
  2212. max_key = None
  2213. for pair in self.portal_trace_positions:
  2214. key, pos = pair
  2215. if key is not None:
  2216. start_stack.append(pair)
  2217. else:
  2218. greenkey, startpos = start_stack.pop()
  2219. size = pos - startpos
  2220. if size > max_size:
  2221. max_size = size
  2222. max_key = greenkey
  2223. if start_stack:
  2224. key, pos = start_stack[0]
  2225. size = len(self.history.operations) - pos
  2226. if size > max_size:
  2227. max_size = size
  2228. max_key = key
  2229. return max_key
  2230. def record_result_of_call_pure(self, resbox):
  2231. """ Patch a CALL into a CALL_PURE.
  2232. """
  2233. op = self.history.operations[-1]
  2234. assert op.getopnum() == rop.CALL
  2235. resbox_as_const = resbox.constbox()
  2236. for i in range(op.numargs()):
  2237. if not isinstance(op.getarg(i), Const):
  2238. break
  2239. else:
  2240. # all-constants: remove the CALL operation now and propagate a
  2241. # constant result
  2242. self.history.operations.pop()
  2243. return resbox_as_const
  2244. # not all constants (so far): turn CALL into CALL_PURE, which might
  2245. # be either removed later by optimizeopt or turned back into CALL.
  2246. arg_consts = [a.constbox() for a in op.getarglist()]
  2247. self.call_pure_results[arg_consts] = resbox_as_const
  2248. newop = op.copy_and_change(rop.CALL_PURE, args=op.getarglist())
  2249. self.history.operations[-1] = newop
  2250. return resbox
  2251. def direct_assembler_call(self, targetjitdriver_sd):
  2252. """ Generate a direct call to assembler for portal entry point,
  2253. patching the CALL_MAY_FORCE that occurred just now.
  2254. """
  2255. op = self.history.operations.pop()
  2256. assert op.getopnum() == rop.CALL_MAY_FORCE
  2257. num_green_args = targetjitdriver_sd.num_green_args
  2258. arglist = op.getarglist()
  2259. greenargs = arglist[1:num_green_args+1]
  2260. args = arglist[num_green_args+1:]
  2261. assert len(args) == targetjitdriver_sd.num_red_args
  2262. warmrunnerstate = targetjitdriver_sd.warmstate
  2263. token = warmrunnerstate.get_assembler_token(greenargs)
  2264. op = op.copy_and_change(rop.CALL_ASSEMBLER, args=args, descr=token)
  2265. self.history.operations.append(op)
  2266. #
  2267. # To fix an obscure issue, make sure the vable stays alive
  2268. # longer than the CALL_ASSEMBLER operation. We do it by
  2269. # inserting explicitly an extra KEEPALIVE operation.
  2270. jd = token.outermost_jitdriver_sd
  2271. if jd.index_of_virtualizable >= 0:
  2272. return args[jd.index_of_virtualizable]
  2273. else:
  2274. return None
  2275. def direct_libffi_call(self):
  2276. """Generate a direct call to C code, patching the CALL_MAY_FORCE
  2277. to jit_ffi_call() that occurred just now.
  2278. """
  2279. # an 'assert' that constant-folds away the rest of this function
  2280. # if the codewriter didn't produce any OS_LIBFFI_CALL at all.
  2281. assert self.staticdata.has_libffi_call
  2282. #
  2283. from rpython.rtyper.lltypesystem import llmemory
  2284. from rpython.rlib.jit_libffi import CIF_DESCRIPTION_P
  2285. from rpython.jit.backend.llsupport.ffisupport import get_arg_descr
  2286. #
  2287. num_extra_guards = 0
  2288. while True:
  2289. op = self.history.operations[-1-num_extra_guards]
  2290. if op.getopnum() == rop.CALL_MAY_FORCE:
  2291. break
  2292. assert op.is_guard()
  2293. num_extra_guards += 1
  2294. #
  2295. box_cif_description = op.getarg(1)
  2296. if not isinstance(box_cif_description, ConstInt):
  2297. return
  2298. cif_description = box_cif_description.getint()
  2299. cif_description = llmemory.cast_int_to_adr(cif_description)
  2300. cif_description = llmemory.cast_adr_to_ptr(cif_description,
  2301. CIF_DESCRIPTION_P)
  2302. extrainfo = op.getdescr().get_extra_info()
  2303. calldescr = self.cpu.calldescrof_dynamic(cif_description, extrainfo)
  2304. if calldescr is None:
  2305. return
  2306. #
  2307. extra_guards = []
  2308. for i in range(num_extra_guards):
  2309. extra_guards.append(self.history.operations.pop())
  2310. extra_guards.reverse()
  2311. #
  2312. box_exchange_buffer = op.getarg(3)
  2313. self.history.operations.pop()
  2314. arg_boxes = []
  2315. for i in range(cif_description.nargs):
  2316. kind, descr, itemsize = get_arg_descr(self.cpu,
  2317. cif_description.atypes[i])
  2318. if kind == 'i':
  2319. box_arg = history.BoxInt()
  2320. elif kind == 'f':
  2321. box_arg = history.BoxFloat()
  2322. else:
  2323. assert kind == 'v'
  2324. continue
  2325. ofs = cif_description.exchange_args[i]
  2326. assert ofs % itemsize == 0 # alignment check
  2327. self.history.record(rop.GETARRAYITEM_RAW,
  2328. [box_exchange_buffer,
  2329. ConstInt(ofs // itemsize)],
  2330. box_arg, descr)
  2331. arg_boxes.append(box_arg)
  2332. #
  2333. kind, descr, itemsize = get_arg_descr(self.cpu, cif_description.rtype)
  2334. if kind == 'i':
  2335. box_result = history.BoxInt()
  2336. elif kind == 'f':
  2337. box_result = history.BoxFloat()
  2338. else:
  2339. assert kind == 'v'
  2340. box_result = None
  2341. self.history.record(rop.CALL_RELEASE_GIL,
  2342. [op.getarg(2)] + arg_boxes,
  2343. box_result, calldescr)
  2344. #
  2345. self.history.operations.extend(extra_guards)
  2346. #
  2347. if box_result is not None:
  2348. ofs = cif_description.exchange_result
  2349. assert ofs % itemsize == 0 # alignment check (result)
  2350. self.history.record(rop.SETARRAYITEM_RAW,
  2351. [box_exchange_buffer,
  2352. ConstInt(ofs // itemsize), box_result],
  2353. None, descr)
  2354. def direct_call_release_gil(self):
  2355. op = self.history.operations.pop()
  2356. assert op.opnum == rop.CALL_MAY_FORCE
  2357. descr = op.getdescr()
  2358. effectinfo = descr.get_extra_info()
  2359. realfuncaddr = effectinfo.call_release_gil_target
  2360. funcbox = ConstInt(heaptracker.adr2int(realfuncaddr))
  2361. self.history.record(rop.CALL_RELEASE_GIL,
  2362. [funcbox] + op.getarglist()[1:],
  2363. op.result, descr)
  2364. if not we_are_translated(): # for llgraph
  2365. descr._original_func_ = op.getarg(0).value
  2366. # ____________________________________________________________
  2367. class ChangeFrame(JitException):
  2368. """Raised after we mutated metainterp.framestack, in order to force
  2369. it to reload the current top-of-stack frame that gets interpreted."""
  2370. class SwitchToBlackhole(JitException):
  2371. def __init__(self, reason, raising_exception=False):
  2372. self.reason = reason
  2373. self.raising_exception = raising_exception
  2374. # ^^^ must be set to True if the SwitchToBlackhole is raised at a
  2375. # point where the exception on metainterp.last_exc_value_box
  2376. # is supposed to be raised. The default False means that it
  2377. # should just be copied into the blackhole interp, but not raised.
  2378. # ____________________________________________________________
  2379. def _get_opimpl_method(name, argcodes):
  2380. from rpython.jit.metainterp.blackhole import signedord
  2381. #
  2382. def handler(self, position):
  2383. assert position >= 0
  2384. args = ()
  2385. next_argcode = 0
  2386. code = self.bytecode
  2387. orgpc = position
  2388. position += 1
  2389. for argtype in argtypes:
  2390. if argtype == "box": # a box, of whatever type
  2391. argcode = argcodes[next_argcode]
  2392. next_argcode = next_argcode + 1
  2393. if argcode == 'i':
  2394. value = self.registers_i[ord(code[position])]
  2395. elif argcode == 'c':
  2396. value = ConstInt(signedord(code[position]))
  2397. elif argcode == 'r':
  2398. value = self.registers_r[ord(code[position])]
  2399. elif argcode == 'f':
  2400. value = self.registers_f[ord(code[position])]
  2401. else:
  2402. raise AssertionError("bad argcode")
  2403. position += 1
  2404. elif argtype == "descr" or argtype == "jitcode":
  2405. assert argcodes[next_argcode] == 'd'
  2406. next_argcode = next_argcode + 1
  2407. index = ord(code[position]) | (ord(code[position+1])<<8)
  2408. value = self.metainterp.staticdata.opcode_descrs[index]
  2409. if argtype == "jitcode":
  2410. assert isinstance(value, JitCode)
  2411. position += 2
  2412. elif argtype == "label":
  2413. assert argcodes[next_argcode] == 'L'
  2414. next_argcode = next_argcode + 1
  2415. value = ord(code[position]) | (ord(code[position+1])<<8)
  2416. position += 2
  2417. elif argtype == "boxes": # a list of boxes of some type
  2418. length = ord(code[position])
  2419. value = [None] * length
  2420. self.prepare_list_of_boxes(value, 0, position,
  2421. argcodes[next_argcode])
  2422. next_argcode = next_argcode + 1
  2423. position += 1 + length
  2424. elif argtype == "boxes2": # two lists of boxes merged into one
  2425. length1 = ord(code[position])
  2426. position2 = position + 1 + length1
  2427. length2 = ord(code[position2])
  2428. value = [None] * (length1 + length2)
  2429. self.prepare_list_of_boxes(value, 0, position,
  2430. argcodes[next_argcode])
  2431. self.prepare_list_of_boxes(value, length1, position2,
  2432. argcodes[next_argcode + 1])
  2433. next_argcode = next_argcode + 2
  2434. position = position2 + 1 + length2
  2435. elif argtype == "boxes3": # three lists of boxes merged into one
  2436. length1 = ord(code[position])
  2437. position2 = position + 1 + length1
  2438. length2 = ord(code[position2])
  2439. position3 = position2 + 1 + length2
  2440. length3 = ord(code[position3])
  2441. value = [None] * (length1 + length2 + length3)
  2442. self.prepare_list_of_boxes(value, 0, position,
  2443. argcodes[next_argcode])
  2444. self.prepare_list_of_boxes(value, length1, position2,
  2445. argcodes[next_argcode + 1])
  2446. self.prepare_list_of_boxes(value, length1 + length2, position3,
  2447. argcodes[next_argcode + 2])
  2448. next_argcode = next_argcode + 3
  2449. position = position3 + 1 + length3
  2450. elif argtype == "orgpc":
  2451. value = orgpc
  2452. elif argtype == "int":
  2453. argcode = argcodes[next_argcode]
  2454. next_argcode = next_argcode + 1
  2455. if argcode == 'i':
  2456. value = self.registers_i[ord(code[position])].getint()
  2457. elif argcode == 'c':
  2458. value = signedord(code[position])
  2459. else:
  2460. raise AssertionError("bad argcode")
  2461. position += 1
  2462. elif argtype == "jitcode_position":
  2463. value = position
  2464. else:
  2465. raise AssertionError("bad argtype: %r" % (argtype,))
  2466. args += (value,)
  2467. #
  2468. num_return_args = len(argcodes) - next_argcode
  2469. assert num_return_args == 0 or num_return_args == 2
  2470. if num_return_args:
  2471. # Save the type of the resulting box. This is needed if there is
  2472. # a get_list_of_active_boxes(). See comments there.
  2473. self._result_argcode = argcodes[next_argcode + 1]
  2474. position += 1
  2475. else:
  2476. self._result_argcode = 'v'
  2477. self.pc = position
  2478. #
  2479. if not we_are_translated():
  2480. if self.debug:
  2481. print '\tpyjitpl: %s(%s)' % (name, ', '.join(map(repr, args))),
  2482. try:
  2483. resultbox = unboundmethod(self, *args)
  2484. except Exception, e:
  2485. if self.debug:
  2486. print '-> %s!' % e.__class__.__name__
  2487. raise
  2488. if num_return_args == 0:
  2489. if self.debug:
  2490. print
  2491. assert resultbox is None
  2492. else:
  2493. if self.debug:
  2494. print '-> %r' % (resultbox,)
  2495. assert argcodes[next_argcode] == '>'
  2496. result_argcode = argcodes[next_argcode + 1]
  2497. assert resultbox.type == {'i': history.INT,
  2498. 'r': history.REF,
  2499. 'f': history.FLOAT}[result_argcode]
  2500. else:
  2501. resultbox = unboundmethod(self, *args)
  2502. #
  2503. if resultbox is not None:
  2504. self.make_result_of_lastop(resultbox)
  2505. elif not we_are_translated():
  2506. assert self._result_argcode in 'v?'
  2507. #
  2508. unboundmethod = getattr(MIFrame, 'opimpl_' + name).im_func
  2509. argtypes = unrolling_iterable(unboundmethod.argtypes)
  2510. handler.func_name = 'handler_' + name
  2511. return handler
  2512. def put_back_list_of_boxes3(frame, position, newvalue):
  2513. code = frame.bytecode
  2514. length1 = ord(code[position])
  2515. position2 = position + 1 + length1
  2516. length2 = ord(code[position2])
  2517. position3 = position2 + 1 + length2
  2518. length3 = ord(code[position3])
  2519. assert len(newvalue) == length1 + length2 + length3
  2520. frame._put_back_list_of_boxes(newvalue, 0, position)
  2521. frame._put_back_list_of_boxes(newvalue, length1, position2)
  2522. frame._put_back_list_of_boxes(newvalue, length1 + length2, position3)