Debian Codegraph @

rpython/jit/metainterp/pyjitpl.py

raw symbols SCIP
1 from __future__ import print_function
2
3 import sys
4
5 import py
6
7 from rpython.jit.codewriter import longlong
8 from rpython.jit.codewriter.effectinfo import EffectInfo
9 from rpython.jit.codewriter.jitcode import JitCode, SwitchDictDescr
10 from rpython.jit.codewriter.liveness import OFFSET_SIZE
11 from rpython.jit.metainterp import history, compile, resume, executor, jitexc
12 from rpython.jit.metainterp.heapcache import HeapCache
13 from rpython.jit.metainterp.history import (Const, ConstInt, ConstPtr,
14 ConstFloat, ConstPtrJitCode,
15 CONST_NULL, TargetToken, MissingValue, SwitchToBlackhole)
16 from rpython.jit.metainterp.jitprof import EmptyProfiler
17 from rpython.jit.metainterp.logger import Logger
18 from rpython.jit.metainterp.optimizeopt.util import args_dict
19 from rpython.jit.metainterp.resoperation import rop, OpHelpers, GuardResOp
20 from rpython.jit.metainterp.support import adr2int, ptr2int
21 from rpython.rlib.rjitlog import rjitlog as jl
22 from rpython.rlib import nonconst, rstack
23 from rpython.rlib.debug import debug_start, debug_stop, debug_print
24 from rpython.rlib.debug import have_debug_prints
25 from rpython.rlib.jit import Counters
26 from rpython.rlib.objectmodel import we_are_translated, specialize, always_inline
27 from rpython.rlib.unroll import unrolling_iterable
28 from rpython.rtyper.lltypesystem import lltype, rffi, llmemory
29 from rpython.rtyper import rclass
30
31 SIZE_LIVE_OP = OFFSET_SIZE + 1
32
33 CONST_0 = ConstInt(0)
34 CONST_1 = ConstInt(1)
35
36 # ____________________________________________________________
37
38 def arguments(*args):
39 def decorate(func):
40 func.argtypes = args
41 return func
42 return decorate
43
44
45 special_handlers = {}
46
47 def special_handler(argcodes):
48 def decorate(func):
49 assert func.__name__.startswith("special_")
50 special_handlers[func.__name__[len("special_"):], argcodes] = func
51 return func
52 return decorate
53
54 # ____________________________________________________________
55
56 FASTPATHS_SAME_BOXES = {
57 "ne": "history.CONST_FALSE",
58 "eq": "history.CONST_TRUE",
59 "lt": "history.CONST_FALSE",
60 "le": "history.CONST_TRUE",
61 "gt": "history.CONST_FALSE",
62 "ge": "history.CONST_TRUE",
63 }
64
65 class MIFrame(object):
66 debug = False
67
68 def __init__(self, metainterp):
69 self.metainterp = metainterp
70 self.registers_i = None
71 self.registers_r = None
72 self.registers_f = None
73
74 def setup(self, jitcode, greenkey=None):
75 # if not translated, fill the registers with MissingValue()
76 assert isinstance(jitcode, JitCode)
77 self.jitcode = jitcode
78 self.bytecode = jitcode.code
79 # this is not None for frames that are recursive portal calls
80 self.greenkey = greenkey
81 # create registers_* lists and copy the constants in place
82 num_regs_and_consts_i = jitcode.num_regs_and_consts_i()
83 num_regs_and_consts_r = jitcode.num_regs_and_consts_r()
84 num_regs_and_consts_f = jitcode.num_regs_and_consts_f()
85 if num_regs_and_consts_i:
86 self.registers_i = self.copy_constants(self.registers_i, jitcode.constants_i, jitcode.num_regs_i(), ConstInt)
87 if num_regs_and_consts_r:
88 self.registers_r = self.copy_constants(self.registers_r, jitcode.constants_r, jitcode.num_regs_r(), ConstPtrJitCode)
89 if num_regs_and_consts_f:
90 self.registers_f = self.copy_constants(self.registers_f, jitcode.constants_f, jitcode.num_regs_f(), ConstFloat)
91 self._result_argcode = 'v'
92 # for resume.py operation
93 self.parent_snapshot = -1
94 # counter for unrolling inlined loops
95 self.unroll_iterations = 1
96
97 @specialize.arg(4)
98 def copy_constants(self, registers, constants, targetindex, ConstClass):
99 """Copy jitcode.constants[0] to registers[self.jitcode.num_regs_x() + 0],
100 jitcode.constants[1] to registers[self.jitcode.num_regs_x() + 1],
101 jitcode.constants[2] to registers[self.jitcode.num_regs_x() + 2],
102 etc."""
103 if not we_are_translated():
104 missing = MissingValue()
105 else:
106 missing = None
107 num_regs_and_consts = targetindex + len(constants)
108 # increase size if its too small
109 if registers is None or len(registers) < num_regs_and_consts:
110 registers = [missing] * num_regs_and_consts
111 elif not we_are_translated():
112 for i in range(len(registers)):
113 registers[i] = missing
114 if nonconst.NonConstant(0): # force the right type
115 constants[0] = ConstClass.value # (useful for small tests)
116 for i in range(len(constants)):
117 registers[targetindex] = ConstClass(constants[i])
118 targetindex += 1
119 return registers
120
121 def cleanup_registers(self):
122 # To avoid keeping references alive, this cleans up the registers_r.
123 # It does not clear the references set by copy_constants(), but
124 # these are all prebuilt constants anyway.
125 for i in range(self.jitcode.num_regs_r()):
126 self.registers_r[i] = None
127 self.pushed_box = None
128
129 # ------------------------------
130 # Decoding of the JitCode
131
132 @specialize.arg(5)
133 def prepare_list_of_boxes(self, outvalue, startindex, position, length, argcode):
134 assert argcode in 'IRF'
135 code = self.bytecode
136 for i in range(length):
137 index = ord(code[position+i])
138 if argcode == 'I': reg = self.registers_i[index]
139 elif argcode == 'R': reg = self.registers_r[index]
140 elif argcode == 'F': reg = self.registers_f[index]
141 else: raise AssertionError(argcode)
142 outvalue[startindex+i] = reg
143
144 @specialize.arg(4)
145 def fill_registers(self, f, length, position, argcode):
146 assert argcode in 'IRF'
147 code = self.bytecode
148 for i in range(length):
149 index = ord(code[position+i])
150 if argcode == 'I':
151 reg = self.registers_i[index]
152 f.registers_i[i] = reg
153 elif argcode == 'R':
154 reg = self.registers_r[index]
155 f.registers_r[i] = reg
156 elif argcode == 'F':
157 reg = self.registers_f[index]
158 f.registers_f[i] = reg
159 else:
160 raise AssertionError(argcode)
161
162 def _put_back_list_of_boxes(self, outvalue, startindex, position):
163 code = self.bytecode
164 length = ord(code[position])
165 position += 1
166 for i in range(length):
167 index = ord(code[position+i])
168 box = outvalue[startindex+i]
169 if box.type == history.INT: self.registers_i[index] = box
170 elif box.type == history.REF: self.registers_r[index] = box
171 elif box.type == history.FLOAT: self.registers_f[index] = box
172 else: raise AssertionError(box.type)
173
174 def get_current_position_info(self):
175 return self.jitcode.get_live_vars_info(self.pc, self.metainterp.staticdata.op_live)
176
177 def get_list_of_active_boxes(self, in_a_call, new_array, add_box_to_storage, after_residual_call=False):
178 from rpython.jit.codewriter.liveness import decode_offset
179 from rpython.jit.codewriter.liveness import LivenessIterator
180 if in_a_call:
181 # If we are not the topmost frame, self._result_argcode contains
182 # the type of the result of the call instruction in the bytecode.
183 # We use it to clear the box that will hold the result: this box
184 # is not defined yet.
185 argcode = self._result_argcode
186 index = ord(self.bytecode[self.pc - 1])
187 if argcode == 'i':
188 self.registers_i[index] = history.CONST_FALSE
189 elif argcode == 'r':
190 self.registers_r[index] = CONST_NULL
191 elif argcode == 'f':
192 self.registers_f[index] = history.CONST_FZERO
193 self._result_argcode = '?' # done
194 if in_a_call or after_residual_call:
195 pc = self.pc # live instruction afterwards
196 else:
197 # there needs to be a live instruction before
198 pc = self.pc - SIZE_LIVE_OP
199 assert ord(self.jitcode.code[pc]) == self.metainterp.staticdata.op_live
200 if not we_are_translated():
201 assert pc in self.jitcode._startpoints
202 offset = decode_offset(self.jitcode.code, pc + 1)
203 all_liveness = self.metainterp.staticdata.liveness_info
204 length_i = ord(all_liveness[offset])
205 length_r = ord(all_liveness[offset + 1])
206 length_f = ord(all_liveness[offset + 2])
207 offset += 3
208
209 start_i = 0
210 start_r = start_i + length_i
211 start_f = start_r + length_r
212 total = start_f + length_f
213 # allocate a list of the correct size
214 storage = new_array(total)
215 # fill it now
216 if length_i:
217 it = LivenessIterator(offset, length_i, all_liveness)
218 for index in it:
219 add_box_to_storage(self.registers_i[index])
220 start_i += 1
221 offset = it.offset
222 if length_r:
223 it = LivenessIterator(offset, length_r, all_liveness)
224 for index in it:
225 add_box_to_storage(self.registers_r[index])
226 start_r += 1
227 offset = it.offset
228 if length_f:
229 it = LivenessIterator(offset, length_f, all_liveness)
230 for index in it:
231 add_box_to_storage(self.registers_f[index])
232 start_f += 1
233 offset = it.offset
234 return storage
235
236 def replace_active_box_in_frame(self, oldbox, newbox):
237 if oldbox.type == 'i':
238 count = self.jitcode.num_regs_i()
239 registers = self.registers_i
240 elif oldbox.type == 'r':
241 count = self.jitcode.num_regs_r()
242 registers = self.registers_r
243 elif oldbox.type == 'f':
244 count = self.jitcode.num_regs_f()
245 registers = self.registers_f
246 else:
247 assert 0, oldbox
248 if not count:
249 return
250 for i in range(count):
251 if registers[i] is oldbox:
252 registers[i] = newbox
253 if not we_are_translated():
254 for b in registers[count:]:
255 assert isinstance(b, (MissingValue, Const))
256
257 @specialize.argtype(1)
258 def make_result_of_lastop(self, resultbox):
259 got_type = resultbox.type
260 if not we_are_translated():
261 typeof = {'i': history.INT,
262 'r': history.REF,
263 'f': history.FLOAT}
264 assert typeof[self.jitcode._resulttypes[self.pc]] == got_type
265 target_index = ord(self.bytecode[self.pc-1])
266 if got_type == history.INT:
267 self.registers_i[target_index] = resultbox
268 elif got_type == history.REF:
269 #debug_print(' ->',
270 # llmemory.cast_ptr_to_adr(resultbox.getref_base()))
271 self.registers_r[target_index] = resultbox
272 elif got_type == history.FLOAT:
273 self.registers_f[target_index] = resultbox
274 else:
275 raise AssertionError("bad result box type")
276
277 # ------------------------------
278
279 for _opimpl in ['int_add', 'int_sub', 'int_mul',
280 'int_and', 'int_or', 'int_xor', 'int_signext',
281 'int_rshift', 'int_lshift', 'uint_rshift',
282 'uint_lt', 'uint_le', 'uint_gt', 'uint_ge',
283 'uint_mul_high',
284 'float_add', 'float_sub', 'float_mul', 'float_truediv',
285 'float_lt', 'float_le', 'float_eq',
286 'float_ne', 'float_gt', 'float_ge',
287 ]:
288 exec(py.code.Source('''
289 @arguments("box", "box")
290 def opimpl_%s(self, b1, b2):
291 return self.execute(rop.%s, b1, b2)
292 ''' % (_opimpl, _opimpl.upper())).compile())
293
294 @special_handler("ic>i")
295 def special_int_add(self, position):
296 from rpython.jit.metainterp.blackhole import signedord
297 from rpython.jit.metainterp.history import IntFrontendOp
298 # bit of a micro-optimization: int_add with a constant argument is one
299 # of the most common opcodes in PyPy, and this way we
300 # - allocate one ConstInt fewer in the (common) non-recorded case
301 # - don't wrap and unwrap
302 # - only check one of the arguments for constness
303 assert position >= 0
304 code = self.bytecode
305 position += 1
306 regs = self.registers_i
307 b1 = regs[ord(code[position])]
308 position += 1
309
310 c = signedord(code[position])
311 position += 1
312 profiler = self.metainterp.staticdata.profiler
313 profiler.count_ops(rop.INT_ADD)
314 if b1.is_constant():
315 assert isinstance(b1, ConstInt)
316 val = b1.getint()
317 resvalue = val + c
318 resbox = ConstInt(resvalue)
319 else:
320 assert isinstance(b1, IntFrontendOp)
321 resvalue = b1.getint() + c
322 resbox = self.metainterp._record_helper(rop.INT_ADD, resvalue, None, b1, ConstInt(c))
323 regs[ord(code[position])] = resbox
324 self.pc = position + 1
325
326 for _opimpl in ['int_eq', 'int_ne', 'int_lt', 'int_le', 'int_gt', 'int_ge',
327 'ptr_eq', 'ptr_ne',
328 'instance_ptr_eq', 'instance_ptr_ne']:
329 exec(py.code.Source('''
330 @arguments("box", "box")
331 def opimpl_%s(self, b1, b2):
332 if b1 is b2: # crude fast check
333 return %s
334 return self.execute(rop.%s, b1, b2)
335 ''' % (_opimpl, FASTPATHS_SAME_BOXES[_opimpl.split("_")[-1]], _opimpl.upper())
336 ).compile())
337
338 for (_opimpl, resop) in [
339 ('int_add_jump_if_ovf', 'INT_ADD_OVF'),
340 ('int_sub_jump_if_ovf', 'INT_SUB_OVF'),
341 ('int_mul_jump_if_ovf', 'INT_MUL_OVF')]:
342 exec(py.code.Source('''
343 @arguments("label", "box", "box", "orgpc")
344 def opimpl_%s(self, lbl, b1, b2, orgpc):
345 self.metainterp.ovf_flag = False
346 resbox = self.execute(rop.%s, b1, b2)
347 if not isinstance(resbox, Const):
348 return self.handle_possible_overflow_error(lbl, orgpc,
349 resbox)
350 elif self.metainterp.ovf_flag:
351 self.pc = lbl
352 return None # but don't emit GUARD_OVERFLOW
353 return resbox
354 ''' % (_opimpl, resop)).compile())
355
356 for _opimpl in ['int_is_true', 'int_is_zero', 'int_neg', 'int_invert',
357 'cast_float_to_int', 'cast_int_to_float',
358 'cast_float_to_singlefloat', 'cast_singlefloat_to_float',
359 'float_neg', 'float_abs',
360 'cast_ptr_to_int', 'cast_int_to_ptr',
361 'convert_float_bytes_to_longlong',
362 'convert_longlong_bytes_to_float', 'int_force_ge_zero',
363 ]:
364 exec(py.code.Source('''
365 @arguments("box")
366 def opimpl_%s(self, b):
367 return self.execute(rop.%s, b)
368 ''' % (_opimpl, _opimpl.upper())).compile())
369
370 @arguments("box")
371 def opimpl_int_same_as(self, box):
372 # for tests only: emits a same_as, forcing the result to be in a Box
373 resbox = self.metainterp._record_helper(
374 rop.SAME_AS_I, box.getint(), None, box)
375 return resbox
376
377 @arguments("box")
378 def opimpl_ptr_nonzero(self, box):
379 return self.execute(rop.PTR_NE, box, CONST_NULL)
380
381 @arguments("box")
382 def opimpl_ptr_iszero(self, box):
383 return self.execute(rop.PTR_EQ, box, CONST_NULL)
384
385 @arguments("box")
386 def opimpl_assert_not_none(self, box):
387 if self.metainterp.heapcache.is_nullity_known(box):
388 self.metainterp.staticdata.profiler.count_ops(rop.ASSERT_NOT_NONE, Counters.HEAPCACHED_OPS)
389 return
390 self.execute(rop.ASSERT_NOT_NONE, box)
391 self.metainterp.heapcache.nullity_now_known(box)
392
393 @arguments("box", "box")
394 def opimpl_record_exact_class(self, box, clsbox):
395 from rpython.rtyper.lltypesystem import llmemory
396 if self.metainterp.heapcache.is_class_known(box):
397 self.metainterp.staticdata.profiler.count_ops(rop.RECORD_EXACT_CLASS, Counters.HEAPCACHED_OPS)
398 return
399 if isinstance(clsbox, Const):
400 self.execute(rop.RECORD_EXACT_CLASS, box, clsbox)
401 self.metainterp.heapcache.class_now_known(box)
402 self.metainterp.heapcache.nullity_now_known(box)
403 elif have_debug_prints():
404 if len(self.metainterp.framestack) >= 2:
405 # caller of ll_record_exact_class
406 name = self.metainterp.framestack[-2].jitcode.name
407 else:
408 name = self.jitcode.name
409 loc = self.metainterp.jitdriver_sd.warmstate.get_location_str(self.greenkey)
410 debug_print("record_exact_class with non-constant second argument, ignored",
411 name, loc)
412
413 @arguments("box", "box", "boxes2", "descr", "orgpc")
414 def opimpl_record_known_result_i_ir_v(self, resbox, funcbox, argboxes,
415 calldescr, pc):
416 allboxes = self._build_allboxes(funcbox, argboxes, calldescr, prepend_box=resbox)
417 # this is a weird op! we don't want to execute anything, so just record
418 # an operation
419 self.metainterp._record_helper_varargs(rop.RECORD_KNOWN_RESULT, None, calldescr, allboxes)
420
421 @arguments("box", "box")
422 def opimpl_record_exact_value_r(self, box, const_box):
423 return self._record_exact_value(rop.RECORD_EXACT_VALUE_R, box, const_box)
424
425 @arguments("box", "box")
426 def opimpl_record_exact_value_i(self, box, const_box):
427 return self._record_exact_value(rop.RECORD_EXACT_VALUE_I, box, const_box)
428
429 def _record_exact_value(self, opnum, box, const_box):
430 invalid = False
431 if isinstance(const_box, Const):
432 if not isinstance(box, Const):
433 self.execute(opnum, box, const_box)
434 return
435 elif box.same_constant(const_box):
436 return
437 invalid = True # really an interpreter programming error
438 error = "record_exact_value with two different constant, this is a bug!"
439 else:
440 error = "record_exact_value with non-constant second argument, ignored"
441 if have_debug_prints():
442 if len(self.metainterp.framestack) >= 2:
443 # caller of ll_record_exact_value
444 name = self.metainterp.framestack[-2].jitcode.name
445 else:
446 name = self.jitcode.name
447 metainterp = self.metainterp
448 if not metainterp.current_merge_points:
449 loc = "unknown language location"
450 else:
451 jd_sd = metainterp.jitdriver_sd
452 greenkey = metainterp.current_merge_points[0][0][:jd_sd.num_green_args]
453 loc = jd_sd.warmstate.get_location_str(greenkey)
454 debug_print(error, name, loc)
455 if invalid:
456 raise SwitchToBlackhole(Counters.ABORT_BAD_LOOP)
457
458
459 @arguments("box")
460 def _opimpl_any_return(self, box):
461 self.metainterp.finishframe(box)
462
463 opimpl_int_return = _opimpl_any_return
464 opimpl_ref_return = _opimpl_any_return
465 opimpl_float_return = _opimpl_any_return
466
467 @arguments()
468 def opimpl_void_return(self):
469 self.metainterp.finishframe(None)
470
471 @arguments("box")
472 def _opimpl_any_copy(self, box):
473 return box
474
475 opimpl_int_copy = _opimpl_any_copy
476 opimpl_ref_copy = _opimpl_any_copy
477 opimpl_float_copy = _opimpl_any_copy
478
479 @arguments("box")
480 def _opimpl_any_push(self, box):
481 self.pushed_box = box
482
483 opimpl_int_push = _opimpl_any_push
484 opimpl_ref_push = _opimpl_any_push
485 opimpl_float_push = _opimpl_any_push
486
487 @arguments()
488 def _opimpl_any_pop(self):
489 box = self.pushed_box
490 self.pushed_box = None
491 return box
492
493 opimpl_int_pop = _opimpl_any_pop
494 opimpl_ref_pop = _opimpl_any_pop
495 opimpl_float_pop = _opimpl_any_pop
496
497 @arguments("label")
498 def opimpl_catch_exception(self, target):
499 """This is a no-op when run normally. We can check that
500 last_exc_value is a null ptr; it should have been set to None
501 by the previous instruction. If the previous instruction
502 raised instead, finishframe_exception() should have been
503 called and we would not be there."""
504 assert not self.metainterp.last_exc_value
505
506 @arguments("label")
507 def opimpl_goto(self, target):
508 self.pc = target
509
510 @arguments("box", "label", "orgpc")
511 def opimpl_goto_if_not(self, box, target, orgpc, replace=True):
512 switchcase = box.getint()
513 if switchcase:
514 assert switchcase == 1
515 opnum = rop.GUARD_TRUE
516 promoted_box = CONST_1
517 else:
518 opnum = rop.GUARD_FALSE
519 promoted_box = CONST_0
520 self.metainterp.generate_guard(opnum, box, resumepc=orgpc)
521 if not switchcase:
522 self.pc = target
523 if isinstance(box, Const):
524 return
525 if replace:
526 self.metainterp.replace_box(box, promoted_box)
527
528 @arguments("box", "label", "orgpc")
529 def opimpl_goto_if_not_int_is_true(self, box, target, orgpc):
530 condbox = self.execute(rop.INT_IS_TRUE, box)
531 # does not make sense to replace condbox, because it does not appear
532 # anywhere in any register, we either just made it or it's constant
533 # anyway
534 self.opimpl_goto_if_not(condbox, target, orgpc, replace=False)
535
536 @arguments("box", "label", "orgpc")
537 def opimpl_goto_if_not_int_is_zero(self, box, target, orgpc):
538 condbox = self.execute(rop.INT_IS_ZERO, box)
539 self.opimpl_goto_if_not(condbox, target, orgpc, replace=False)
540
541 for _opimpl in ['int_lt', 'int_le', 'int_eq', 'int_ne', 'int_gt', 'int_ge',
542 'ptr_eq', 'ptr_ne', 'float_lt', 'float_le', 'float_eq',
543 'float_ne', 'float_gt', 'float_ge']:
544 exec(py.code.Source('''
545 @arguments("box", "box", "label", "orgpc")
546 def opimpl_goto_if_not_%s(self, b1, b2, target, orgpc):
547 if %s and b1 is b2:
548 if not %s:
549 self.pc = target
550 return
551 else:
552 condbox = self.execute(rop.%s, b1, b2)
553 self.opimpl_goto_if_not(condbox, target, orgpc, replace=False)
554 ''' % (_opimpl, not _opimpl.startswith('float_'),
555 FASTPATHS_SAME_BOXES[_opimpl.split("_")[-1]] == 'history.CONST_TRUE', _opimpl.upper())
556 ).compile())
557
558 def _establish_nullity(self, box, orgpc):
559 heapcache = self.metainterp.heapcache
560 value = box.nonnull()
561 if heapcache.is_nullity_known(box):
562 self.metainterp.staticdata.profiler.count_ops(rop.GUARD_NONNULL, Counters.HEAPCACHED_OPS)
563 return value
564 if value:
565 if not self.metainterp.heapcache.is_class_known(box):
566 self.metainterp.generate_guard(rop.GUARD_NONNULL, box,
567 resumepc=orgpc)
568 else:
569 if not isinstance(box, Const):
570 self.metainterp.generate_guard(rop.GUARD_ISNULL, box,
571 resumepc=orgpc)
572 promoted_box = executor.constant_from_op(box)
573 self.metainterp.replace_box(box, promoted_box)
574 heapcache.nullity_now_known(box)
575 return value
576
577 @arguments("box", "label", "orgpc")
578 def opimpl_goto_if_not_ptr_nonzero(self, box, target, orgpc):
579 if not self._establish_nullity(box, orgpc):
580 self.pc = target
581
582 @arguments("box", "label", "orgpc")
583 def opimpl_goto_if_not_ptr_iszero(self, box, target, orgpc):
584 if self._establish_nullity(box, orgpc):
585 self.pc = target
586
587 @arguments("box", "box", "box")
588 def opimpl_int_between(self, b1, b2, b3):
589 b5 = self.execute(rop.INT_SUB, b3, b1)
590 if isinstance(b5, ConstInt) and b5.getint() == 1:
591 # the common case of int_between(a, b, a+1) turns into just INT_EQ
592 return self.execute(rop.INT_EQ, b2, b1)
593 else:
594 b4 = self.execute(rop.INT_SUB, b2, b1)
595 return self.execute(rop.UINT_LT, b4, b5)
596
597 @arguments("box", "descr", "orgpc")
598 def opimpl_switch(self, valuebox, switchdict, orgpc):
599 search_value = valuebox.getint()
600 assert isinstance(switchdict, SwitchDictDescr)
601 try:
602 target = switchdict.dict[search_value]
603 except KeyError:
604 # None of the cases match. Fall back to generating a chain
605 # of 'int_eq'.
606 # xxx as a minor optimization, if that's a bridge, then we would
607 # not need the cases that we already tested (and failed) with
608 # 'guard_value'. How to do it is not very clear though.
609 for const1 in switchdict.const_keys_in_order:
610 box = self.execute(rop.INT_EQ, valuebox, const1)
611 assert box.getint() == 0
612 self.metainterp.generate_guard(rop.GUARD_FALSE, box,
613 resumepc=orgpc)
614 else:
615 # found one of the cases
616 self.implement_guard_value(valuebox, orgpc)
617 self.pc = target
618
619 @arguments()
620 def opimpl_unreachable(self):
621 raise AssertionError("unreachable")
622
623 @arguments("descr")
624 def opimpl_new(self, sizedescr):
625 return self.metainterp.execute_new(sizedescr)
626
627 @arguments("descr")
628 def opimpl_new_with_vtable(self, sizedescr):
629 return self.metainterp.execute_new_with_vtable(descr=sizedescr)
630
631 @arguments("box", "descr")
632 def opimpl_new_array(self, lengthbox, itemsizedescr):
633 return self.metainterp.execute_new_array(itemsizedescr, lengthbox)
634
635 @arguments("box", "descr")
636 def opimpl_new_array_clear(self, lengthbox, itemsizedescr):
637 return self.metainterp.execute_new_array_clear(itemsizedescr, lengthbox)
638
639 @specialize.arg(1, 5)
640 def _do_getarrayitem_gc_any(self, op, arraybox, indexbox, arraydescr, typ):
641 tobox = self.metainterp.heapcache.getarrayitem(
642 arraybox, indexbox, arraydescr)
643 if tobox:
644 # sanity check: see whether the current array value
645 # corresponds to what the cache thinks the value is
646 self.metainterp.staticdata.profiler.count_ops(rop.GETARRAYITEM_GC_I, Counters.HEAPCACHED_OPS)
647 resvalue = executor.execute(self.metainterp.cpu, self.metainterp,
648 op, arraydescr, arraybox, indexbox)
649 if typ == 'i':
650 if resvalue != tobox.getint():
651 self.metainterp._record_helper(rop.GETARRAYITEM_GC_I, resvalue, arraydescr, arraybox, indexbox)
652 self.metainterp.staticdata.logger_noopt.log_loop_from_trace(self.metainterp.history.trace, self.metainterp.box_names_memo)
653 print("assertion in GETARRAYITEM_GC_I failed", resvalue, tobox.getint())
654 assert 0
655 elif typ == 'r':
656 if resvalue != tobox.getref_base():
657 self.metainterp._record_helper(rop.GETARRAYITEM_GC_R, resvalue, arraydescr, arraybox, indexbox)
658 self.metainterp.staticdata.logger_noopt.log_loop_from_trace(self.metainterp.history.trace, self.metainterp.box_names_memo)
659 print("assertion in GETARRAYITEM_GC_R failed", resvalue, tobox.getref_base())
660 assert 0
661 elif typ == 'f':
662 if not ConstFloat(resvalue).same_constant(tobox.constbox()):
663 self.metainterp._record_helper(rop.GETARRAYITEM_GC_F, resvalue, arraydescr, arraybox, indexbox)
664 self.metainterp.staticdata.logger_noopt.log_loop_from_trace(self.metainterp.history.trace, self.metainterp.box_names_memo)
665 print("assertion in GETARRAYITEM_GC_F failed", resvalue, tobox.getfloat())
666 assert 0
667 else:
668 assert 0, "unreachable"
669 return tobox
670 resop = self.execute_with_descr(op, arraydescr, arraybox, indexbox)
671 self.metainterp.heapcache.getarrayitem_now_known(
672 arraybox, indexbox, resop, arraydescr)
673 return resop
674
675 @arguments("box", "box", "descr")
676 def opimpl_getarrayitem_gc_i(self, arraybox, indexbox, arraydescr):
677 return self._do_getarrayitem_gc_any(rop.GETARRAYITEM_GC_I, arraybox,
678 indexbox, arraydescr, 'i')
679
680 @arguments("box", "box", "descr")
681 def opimpl_getarrayitem_gc_r(self, arraybox, indexbox, arraydescr):
682 return self._do_getarrayitem_gc_any(rop.GETARRAYITEM_GC_R, arraybox,
683 indexbox, arraydescr, 'r')
684
685 @arguments("box", "box", "descr")
686 def opimpl_getarrayitem_gc_f(self, arraybox, indexbox, arraydescr):
687 return self._do_getarrayitem_gc_any(rop.GETARRAYITEM_GC_F, arraybox,
688 indexbox, arraydescr, 'f')
689
690 @arguments("box", "box", "descr")
691 def opimpl_getarrayitem_raw_i(self, arraybox, indexbox, arraydescr):
692 return self.execute_with_descr(rop.GETARRAYITEM_RAW_I,
693 arraydescr, arraybox, indexbox)
694
695 @arguments("box", "box", "descr")
696 def opimpl_getarrayitem_raw_f(self, arraybox, indexbox, arraydescr):
697 return self.execute_with_descr(rop.GETARRAYITEM_RAW_F,
698 arraydescr, arraybox, indexbox)
699
700 @arguments("box", "box", "descr")
701 def opimpl_getarrayitem_gc_i_pure(self, arraybox, indexbox, arraydescr):
702 if isinstance(arraybox, ConstPtr) and isinstance(indexbox, ConstInt):
703 # if the arguments are directly constants, bypass the heapcache
704 # completely
705 val = executor.execute(self.metainterp.cpu, self.metainterp,
706 rop.GETARRAYITEM_GC_PURE_I, arraydescr,
707 arraybox, indexbox)
708 return executor.wrap_constant(val)
709 return self._do_getarrayitem_gc_any(rop.GETARRAYITEM_GC_PURE_I,
710 arraybox, indexbox, arraydescr, 'i')
711
712 @arguments("box", "box", "descr")
713 def opimpl_getarrayitem_gc_f_pure(self, arraybox, indexbox, arraydescr):
714 if isinstance(arraybox, ConstPtr) and isinstance(indexbox, ConstInt):
715 # if the arguments are directly constants, bypass the heapcache
716 # completely
717 resval = executor.execute(self.metainterp.cpu, self.metainterp,
718 rop.GETARRAYITEM_GC_PURE_F, arraydescr,
719 arraybox, indexbox)
720 return executor.wrap_constant(resval)
721 return self._do_getarrayitem_gc_any(rop.GETARRAYITEM_GC_PURE_F,
722 arraybox, indexbox, arraydescr, 'f')
723
724 @arguments("box", "box", "descr")
725 def opimpl_getarrayitem_gc_r_pure(self, arraybox, indexbox, arraydescr):
726 if isinstance(arraybox, ConstPtr) and isinstance(indexbox, ConstInt):
727 # if the arguments are directly constants, bypass the heapcache
728 # completely
729 val = executor.execute(self.metainterp.cpu, self.metainterp,
730 rop.GETARRAYITEM_GC_PURE_R, arraydescr,
731 arraybox, indexbox)
732 return executor.wrap_constant(val)
733 return self._do_getarrayitem_gc_any(rop.GETARRAYITEM_GC_PURE_R,
734 arraybox, indexbox, arraydescr, 'r')
735
736 @arguments("box", "box", "box", "descr")
737 def _opimpl_setarrayitem_gc_any(self, arraybox, indexbox, itembox,
738 arraydescr):
739 self.metainterp.execute_setarrayitem_gc(arraydescr, arraybox,
740 indexbox, itembox)
741
742 opimpl_setarrayitem_gc_i = _opimpl_setarrayitem_gc_any
743 opimpl_setarrayitem_gc_r = _opimpl_setarrayitem_gc_any
744 opimpl_setarrayitem_gc_f = _opimpl_setarrayitem_gc_any
745
746 @arguments("box", "box", "box", "descr")
747 def _opimpl_setarrayitem_raw_any(self, arraybox, indexbox, itembox,
748 arraydescr):
749 self.execute_with_descr(rop.SETARRAYITEM_RAW, arraydescr, arraybox,
750 indexbox, itembox)
751
752 opimpl_setarrayitem_raw_i = _opimpl_setarrayitem_raw_any
753 opimpl_setarrayitem_raw_f = _opimpl_setarrayitem_raw_any
754
755 @arguments("box", "descr")
756 def opimpl_arraylen_gc(self, arraybox, arraydescr):
757 lengthbox = self.metainterp.heapcache.arraylen(arraybox)
758 if lengthbox is None:
759 lengthbox = self.execute_with_descr(
760 rop.ARRAYLEN_GC, arraydescr, arraybox)
761 self.metainterp.heapcache.arraylen_now_known(arraybox, lengthbox)
762 else:
763 self.metainterp.staticdata.profiler.count_ops(rop.ARRAYLEN_GC, Counters.HEAPCACHED_OPS)
764 return lengthbox
765
766 @arguments("box", "box", "descr", "orgpc")
767 def opimpl_check_neg_index(self, arraybox, indexbox, arraydescr, orgpc):
768 negbox = self.metainterp.execute_and_record(
769 rop.INT_LT, None, indexbox, history.CONST_FALSE)
770 negbox = self.implement_guard_value(negbox, orgpc)
771 if negbox.getint():
772 # the index is < 0; add the array length to it
773 lengthbox = self.opimpl_arraylen_gc(arraybox, arraydescr)
774 indexbox = self.metainterp.execute_and_record(
775 rop.INT_ADD, None, indexbox, lengthbox)
776 return indexbox
777
778 @arguments("box", "descr", "descr", "descr", "descr")
779 def opimpl_newlist(self, sizebox, structdescr, lengthdescr,
780 itemsdescr, arraydescr):
781 sbox = self.opimpl_new(structdescr)
782 self._opimpl_setfield_gc_any(sbox, sizebox, lengthdescr)
783 if (arraydescr.is_array_of_structs() or
784 arraydescr.is_array_of_pointers()):
785 abox = self.opimpl_new_array_clear(sizebox, arraydescr)
786 else:
787 abox = self.opimpl_new_array(sizebox, arraydescr)
788 self._opimpl_setfield_gc_any(sbox, abox, itemsdescr)
789 return sbox
790
791 @arguments("box", "descr", "descr", "descr", "descr")
792 def opimpl_newlist_clear(self, sizebox, structdescr, lengthdescr,
793 itemsdescr, arraydescr):
794 sbox = self.opimpl_new(structdescr)
795 self._opimpl_setfield_gc_any(sbox, sizebox, lengthdescr)
796 abox = self.opimpl_new_array_clear(sizebox, arraydescr)
797 self._opimpl_setfield_gc_any(sbox, abox, itemsdescr)
798 return sbox
799
800 @arguments("box", "descr", "descr", "descr", "descr")
801 def opimpl_newlist_hint(self, sizehintbox, structdescr, lengthdescr,
802 itemsdescr, arraydescr):
803 sbox = self.opimpl_new(structdescr)
804 self._opimpl_setfield_gc_any(sbox, history.CONST_FALSE, lengthdescr)
805 if (arraydescr.is_array_of_structs() or
806 arraydescr.is_array_of_pointers()):
807 abox = self.opimpl_new_array_clear(sizehintbox, arraydescr)
808 else:
809 abox = self.opimpl_new_array(sizehintbox, arraydescr)
810 self._opimpl_setfield_gc_any(sbox, abox, itemsdescr)
811 return sbox
812
813 @arguments("box", "box", "descr", "descr")
814 def opimpl_getlistitem_gc_i(self, listbox, indexbox,
815 itemsdescr, arraydescr):
816 arraybox = self.opimpl_getfield_gc_r(listbox, itemsdescr)
817 return self.opimpl_getarrayitem_gc_i(arraybox, indexbox, arraydescr)
818 @arguments("box", "box", "descr", "descr")
819 def opimpl_getlistitem_gc_r(self, listbox, indexbox,
820 itemsdescr, arraydescr):
821 arraybox = self.opimpl_getfield_gc_r(listbox, itemsdescr)
822 return self.opimpl_getarrayitem_gc_r(arraybox, indexbox, arraydescr)
823 @arguments("box", "box", "descr", "descr")
824 def opimpl_getlistitem_gc_f(self, listbox, indexbox,
825 itemsdescr, arraydescr):
826 arraybox = self.opimpl_getfield_gc_r(listbox, itemsdescr)
827 return self.opimpl_getarrayitem_gc_f(arraybox, indexbox, arraydescr)
828
829 @arguments("box", "box", "box", "descr", "descr")
830 def _opimpl_setlistitem_gc_any(self, listbox, indexbox, valuebox,
831 itemsdescr, arraydescr):
832 arraybox = self.opimpl_getfield_gc_r(listbox, itemsdescr)
833 self._opimpl_setarrayitem_gc_any(arraybox, indexbox, valuebox,
834 arraydescr)
835
836 opimpl_setlistitem_gc_i = _opimpl_setlistitem_gc_any
837 opimpl_setlistitem_gc_r = _opimpl_setlistitem_gc_any
838 opimpl_setlistitem_gc_f = _opimpl_setlistitem_gc_any
839
840 @arguments("box", "box", "descr", "orgpc")
841 def opimpl_check_resizable_neg_index(self, listbox, indexbox,
842 lengthdescr, orgpc):
843 negbox = self.metainterp.execute_and_record(
844 rop.INT_LT, None, indexbox, history.CONST_FALSE)
845 negbox = self.implement_guard_value(negbox, orgpc)
846 if negbox.getint():
847 # the index is < 0; add the array length to it
848 lenbox = self.metainterp.execute_and_record(
849 rop.GETFIELD_GC, lengthdescr, listbox)
850 indexbox = self.metainterp.execute_and_record(
851 rop.INT_ADD, None, indexbox, lenbox)
852 return indexbox
853
854 @arguments("box", "descr")
855 def opimpl_getfield_gc_i(self, box, fielddescr):
856 if fielddescr.is_always_pure() and isinstance(box, ConstPtr):
857 # if 'box' is directly a ConstPtr, bypass the heapcache completely
858 resvalue = executor.execute(self.metainterp.cpu, self.metainterp,
859 rop.GETFIELD_GC_I, fielddescr, box)
860 return ConstInt(resvalue)
861 return self._opimpl_getfield_gc_any_pureornot(
862 rop.GETFIELD_GC_I, box, fielddescr, 'i')
863
864 @arguments("box", "descr")
865 def opimpl_getfield_gc_f(self, box, fielddescr):
866 if fielddescr.is_always_pure() and isinstance(box, ConstPtr):
867 # if 'box' is directly a ConstPtr, bypass the heapcache completely
868 resvalue = executor.execute(self.metainterp.cpu, self.metainterp,
869 rop.GETFIELD_GC_F, fielddescr, box)
870 return ConstFloat(resvalue)
871 return self._opimpl_getfield_gc_any_pureornot(
872 rop.GETFIELD_GC_F, box, fielddescr, 'f')
873
874 @arguments("box", "descr")
875 def opimpl_getfield_gc_r(self, box, fielddescr):
876 if fielddescr.is_always_pure() and isinstance(box, ConstPtr):
877 # if 'box' is directly a ConstPtr, bypass the heapcache completely
878 val = executor.execute(self.metainterp.cpu, self.metainterp,
879 rop.GETFIELD_GC_R, fielddescr, box)
880 return ConstPtr(val)
881 return self._opimpl_getfield_gc_any_pureornot(
882 rop.GETFIELD_GC_R, box, fielddescr, 'r')
883
884 opimpl_getfield_gc_i_pure = opimpl_getfield_gc_i
885 opimpl_getfield_gc_r_pure = opimpl_getfield_gc_r
886 opimpl_getfield_gc_f_pure = opimpl_getfield_gc_f
887
888 @arguments("box", "box", "descr")
889 def opimpl_getinteriorfield_gc_i(self, array, index, descr):
890 return self._opimpl_getinteriorfield_gc_any(
891 rop.GETINTERIORFIELD_GC_I, array,
892 index, descr, 'i')
893 @arguments("box", "box", "descr")
894 def opimpl_getinteriorfield_gc_r(self, array, index, descr):
895 return self._opimpl_getinteriorfield_gc_any(
896 rop.GETINTERIORFIELD_GC_R, array,
897 index, descr, 'r')
898 @arguments("box", "box", "descr")
899 def opimpl_getinteriorfield_gc_f(self, array, index, descr):
900 return self._opimpl_getinteriorfield_gc_any(
901 rop.GETINTERIORFIELD_GC_F, array,
902 index, descr, 'f')
903
904 @specialize.arg(1, 5)
905 def _opimpl_getinteriorfield_gc_any(self, opnum, arraybox, indexbox, descr, typ):
906 # use the getarrayitem heapcache methods, they work also for interior fields
907 tobox = self.metainterp.heapcache.getarrayitem(
908 arraybox, indexbox, descr)
909 if tobox:
910 # sanity check: see whether the current interior field value
911 # corresponds to what the cache thinks the value is
912 self.metainterp.staticdata.profiler.count_ops(opnum, Counters.HEAPCACHED_OPS)
913 resvalue = executor.execute(self.metainterp.cpu, self.metainterp,
914 opnum, descr, arraybox, indexbox)
915 if typ == 'i':
916 assert resvalue == tobox.getint()
917 elif typ == 'r':
918 assert resvalue == tobox.getref_base()
919 elif typ == 'f':
920 # need to be careful due to NaNs etc
921 assert ConstFloat(resvalue).same_constant(tobox.constbox())
922 return tobox
923 resop = self.execute_with_descr(opnum, descr, arraybox, indexbox)
924 self.metainterp.heapcache.getarrayitem_now_known(
925 arraybox, indexbox, resop, descr)
926 return resop
927
928 @specialize.arg(1, 4)
929 def _opimpl_getfield_gc_any_pureornot(self, opnum, box, fielddescr, type):
930 upd = self.metainterp.heapcache.get_field_updater(box, fielddescr)
931 if upd.currfieldbox is not None:
932 # sanity check: see whether the current struct value
933 # corresponds to what the cache thinks the value is
934 resvalue = executor.execute(self.metainterp.cpu, self.metainterp,
935 opnum, fielddescr, box)
936 if type == 'i':
937 assert resvalue == upd.currfieldbox.getint()
938 elif type == 'r':
939 assert resvalue == upd.currfieldbox.getref_base()
940 else:
941 assert type == 'f'
942 # make the comparison more robust again NaNs
943 # see ConstFloat.same_constant
944 assert ConstFloat(resvalue).same_constant(
945 upd.currfieldbox.constbox())
946 self.metainterp.staticdata.profiler.count_ops(rop.GETFIELD_GC_I, Counters.HEAPCACHED_OPS)
947 return upd.currfieldbox
948 resbox = self.execute_with_descr(opnum, fielddescr, box)
949 upd.getfield_now_known(resbox)
950 return resbox
951
952 @arguments("box", "descr", "orgpc")
953 def _opimpl_getfield_gc_greenfield_any(self, box, fielddescr, pc):
954 ginfo = self.metainterp.jitdriver_sd.greenfield_info
955 opnum = OpHelpers.getfield_for_descr(fielddescr)
956 if (ginfo is not None and fielddescr in ginfo.green_field_descrs
957 and not self._nonstandard_virtualizable(pc, box, fielddescr)):
958 # fetch the result, but consider it as a Const box and don't
959 # record any operation
960 return executor.execute_nonspec_const(self.metainterp.cpu,
961 self.metainterp, opnum, [box], fielddescr)
962 # fall-back
963 if fielddescr.is_pointer_field():
964 return self.execute_with_descr(rop.GETFIELD_GC_R, fielddescr, box)
965 elif fielddescr.is_float_field():
966 return self.execute_with_descr(rop.GETFIELD_GC_F, fielddescr, box)
967 else:
968 return self.execute_with_descr(rop.GETFIELD_GC_I, fielddescr, box)
969 opimpl_getfield_gc_i_greenfield = _opimpl_getfield_gc_greenfield_any
970 opimpl_getfield_gc_r_greenfield = _opimpl_getfield_gc_greenfield_any
971 opimpl_getfield_gc_f_greenfield = _opimpl_getfield_gc_greenfield_any
972
973 @arguments("box", "box", "descr")
974 def _opimpl_setfield_gc_any(self, box, valuebox, fielddescr):
975 upd = self.metainterp.heapcache.get_field_updater(box, fielddescr)
976 if upd.currfieldbox is valuebox:
977 self.metainterp.staticdata.profiler.count_ops(rop.SETFIELD_GC, Counters.HEAPCACHED_OPS)
978 return
979 self.metainterp.execute_and_record(rop.SETFIELD_GC, fielddescr, box, valuebox)
980 upd.setfield(valuebox)
981 # The following logic is disabled because buggy. It is supposed
982 # to be: not(we're writing null into a freshly allocated object)
983 # but the bug is that is_unescaped() can be True even after the
984 # field cache is cleared --- see test_ajit:test_unescaped_write_zero
985 #
986 # if tobox is not None or not self.metainterp.heapcache.is_unescaped(box) or not isinstance(valuebox, Const) or valuebox.nonnull():
987 # self.execute_with_descr(rop.SETFIELD_GC, fielddescr, box, valuebox)
988 # self.metainterp.heapcache.setfield(box, valuebox, fielddescr)
989 opimpl_setfield_gc_i = _opimpl_setfield_gc_any
990 opimpl_setfield_gc_r = _opimpl_setfield_gc_any
991 opimpl_setfield_gc_f = _opimpl_setfield_gc_any
992
993 @arguments("box", "box", "box", "descr")
994 def _opimpl_setinteriorfield_gc_any(self, array, index, value, descr):
995 self.metainterp.execute_setinteriorfield_gc(descr, array, index, value)
996 opimpl_setinteriorfield_gc_i = _opimpl_setinteriorfield_gc_any
997 opimpl_setinteriorfield_gc_f = _opimpl_setinteriorfield_gc_any
998 opimpl_setinteriorfield_gc_r = _opimpl_setinteriorfield_gc_any
999
1000
1001 @arguments("box", "descr")
1002 def opimpl_getfield_raw_i(self, box, fielddescr):
1003 return self.execute_with_descr(rop.GETFIELD_RAW_I, fielddescr, box)
1004 @arguments("box", "descr")
1005 def opimpl_getfield_raw_r(self, box, fielddescr): # for pure only
1006 return self.execute_with_descr(rop.GETFIELD_RAW_R, fielddescr, box)
1007 @arguments("box", "descr")
1008 def opimpl_getfield_raw_f(self, box, fielddescr):
1009 return self.execute_with_descr(rop.GETFIELD_RAW_F, fielddescr, box)
1010
1011 @arguments("box", "box", "descr")
1012 def _opimpl_setfield_raw_any(self, box, valuebox, fielddescr):
1013 self.execute_with_descr(rop.SETFIELD_RAW, fielddescr, box, valuebox)
1014 opimpl_setfield_raw_i = _opimpl_setfield_raw_any
1015 opimpl_setfield_raw_f = _opimpl_setfield_raw_any
1016
1017 @arguments("box", "box", "box", "descr")
1018 def _opimpl_raw_store(self, addrbox, offsetbox, valuebox, arraydescr):
1019 self.metainterp.execute_raw_store(arraydescr,
1020 addrbox, offsetbox, valuebox)
1021 opimpl_raw_store_i = _opimpl_raw_store
1022 opimpl_raw_store_f = _opimpl_raw_store
1023
1024 @arguments("box", "box", "descr")
1025 def opimpl_raw_load_i(self, addrbox, offsetbox, arraydescr):
1026 return self.execute_with_descr(rop.RAW_LOAD_I, arraydescr,
1027 addrbox, offsetbox)
1028 @arguments("box", "box", "descr")
1029 def opimpl_raw_load_f(self, addrbox, offsetbox, arraydescr):
1030 return self.execute_with_descr(rop.RAW_LOAD_F, arraydescr,
1031 addrbox, offsetbox)
1032
1033 def _remove_symbolics(self, c):
1034 if not we_are_translated():
1035 from rpython.rtyper.lltypesystem import ll2ctypes
1036 assert isinstance(c, ConstInt)
1037 c = ConstInt(ll2ctypes.lltype2ctypes(c.value))
1038 return c
1039
1040 @arguments("box", "box", "box", "box", "box")
1041 def opimpl_gc_load_indexed_i(self, addrbox, indexbox,
1042 scalebox, baseofsbox, bytesbox):
1043 return self.execute(rop.GC_LOAD_INDEXED_I, addrbox, indexbox,
1044 self._remove_symbolics(scalebox),
1045 self._remove_symbolics(baseofsbox), bytesbox)
1046
1047 @arguments("box", "box", "box", "box", "box")
1048 def opimpl_gc_load_indexed_f(self, addrbox, indexbox,
1049 scalebox, baseofsbox, bytesbox):
1050 return self.execute(rop.GC_LOAD_INDEXED_F, addrbox, indexbox,
1051 self._remove_symbolics(scalebox),
1052 self._remove_symbolics(baseofsbox), bytesbox)
1053
1054 @arguments("box", "box", "box", "box", "box", "box", "descr")
1055 def _opimpl_gc_store_indexed(self, addrbox, indexbox, valuebox,
1056 scalebox, baseofsbox, bytesbox,
1057 arraydescr):
1058 return self.execute_with_descr(rop.GC_STORE_INDEXED,
1059 arraydescr,
1060 addrbox,
1061 indexbox,
1062 valuebox,
1063 self._remove_symbolics(scalebox),
1064 self._remove_symbolics(baseofsbox),
1065 bytesbox)
1066 opimpl_gc_store_indexed_i = _opimpl_gc_store_indexed
1067 opimpl_gc_store_indexed_f = _opimpl_gc_store_indexed
1068
1069 @arguments("box")
1070 def opimpl_hint_force_virtualizable(self, box):
1071 self.metainterp.gen_store_back_in_vable(box)
1072
1073 @arguments("box", "descr", "descr", "orgpc")
1074 def opimpl_record_quasiimmut_field(self, box, fielddescr,
1075 mutatefielddescr, orgpc):
1076 from rpython.jit.metainterp.quasiimmut import QuasiImmutDescr
1077 cpu = self.metainterp.cpu
1078 if self.metainterp.heapcache.is_quasi_immut_known(fielddescr, box):
1079 self.metainterp.staticdata.profiler.count_ops(rop.QUASIIMMUT_FIELD, Counters.HEAPCACHED_OPS)
1080 return
1081 descr = QuasiImmutDescr(cpu, box.getref_base(), fielddescr,
1082 mutatefielddescr)
1083 self.metainterp.heapcache.quasi_immut_now_known(fielddescr, box)
1084 self.metainterp.history.record1(rop.QUASIIMMUT_FIELD, box,
1085 None, descr=descr)
1086 if self.metainterp.heapcache.need_guard_not_invalidated:
1087 self.metainterp.generate_guard(rop.GUARD_NOT_INVALIDATED,
1088 resumepc=orgpc)
1089 self.metainterp.heapcache.need_guard_not_invalidated = False
1090
1091
1092
1093 @arguments("box", "descr", "orgpc")
1094 def opimpl_jit_force_quasi_immutable(self, box, mutatefielddescr, orgpc):
1095 # During tracing, a 'jit_force_quasi_immutable' usually turns into
1096 # the operations that check that the content of 'mutate_xxx' is null.
1097 # If it is actually not null already now, then we abort tracing.
1098 # The idea is that if we use 'jit_force_quasi_immutable' on a freshly
1099 # allocated object, then the GETFIELD_GC will know that the answer is
1100 # null, and the guard will be removed. So the fact that the field is
1101 # quasi-immutable will have no effect, and instead it will work as a
1102 # regular, probably virtual, structure.
1103 if mutatefielddescr.is_pointer_field():
1104 mutatebox = self.execute_with_descr(rop.GETFIELD_GC_R,
1105 mutatefielddescr, box)
1106 elif mutatefielddescr.is_float_field():
1107 mutatebox = self.execute_with_descr(rop.GETFIELD_GC_R,
1108 mutatefielddescr, box)
1109 else:
1110 mutatebox = self.execute_with_descr(rop.GETFIELD_GC_I,
1111 mutatefielddescr, box)
1112 if mutatebox.nonnull():
1113 from rpython.jit.metainterp.quasiimmut import do_force_quasi_immutable
1114 do_force_quasi_immutable(self.metainterp.cpu, box.getref_base(),
1115 mutatefielddescr)
1116 raise SwitchToBlackhole(Counters.ABORT_FORCE_QUASIIMMUT)
1117 self.metainterp.generate_guard(rop.GUARD_ISNULL, mutatebox,
1118 resumepc=orgpc)
1119
1120 def _nonstandard_virtualizable(self, pc, box, fielddescr):
1121 # returns True if 'box' is actually not the "standard" virtualizable
1122 # that is stored in metainterp.virtualizable_boxes[-1]
1123 if self.metainterp.heapcache.is_known_nonstandard_virtualizable(box):
1124 self.metainterp.staticdata.profiler.count_ops(rop.PTR_EQ, Counters.HEAPCACHED_OPS)
1125 return True
1126 if box is self.metainterp.forced_virtualizable:
1127 self.metainterp.forced_virtualizable = None
1128 if (self.metainterp.jitdriver_sd.virtualizable_info is not None or
1129 self.metainterp.jitdriver_sd.greenfield_info is not None):
1130 standard_box = self.metainterp.virtualizable_boxes[-1]
1131 if standard_box is box:
1132 return False
1133 vinfo = self.metainterp.jitdriver_sd.virtualizable_info
1134 if vinfo is fielddescr.get_vinfo():
1135 eqbox = self.metainterp.execute_and_record(rop.PTR_EQ, None,
1136 box, standard_box)
1137 eqbox = self.implement_guard_value(eqbox, pc)
1138 isstandard = eqbox.getint()
1139 if isstandard:
1140 if box.type == 'r':
1141 self.metainterp.replace_box(box, standard_box)
1142 return False
1143 if not self.metainterp.heapcache.is_unescaped(box):
1144 self.emit_force_virtualizable(fielddescr, box)
1145 self.metainterp.heapcache.nonstandard_virtualizables_now_known(box)
1146 return True
1147
1148 def emit_force_virtualizable(self, fielddescr, box):
1149 vinfo = fielddescr.get_vinfo()
1150 assert vinfo is not None
1151 token_descr = vinfo.vable_token_descr
1152 mi = self.metainterp
1153 tokenbox = mi.execute_and_record(rop.GETFIELD_GC_R, token_descr, box)
1154 condbox = mi.execute_and_record(rop.PTR_NE, None, tokenbox, CONST_NULL)
1155 funcbox = ConstInt(rffi.cast(lltype.Signed, vinfo.clear_vable_ptr))
1156 calldescr = vinfo.clear_vable_descr
1157 self.execute_varargs(rop.COND_CALL, [condbox, funcbox, box],
1158 calldescr, False, False)
1159
1160 def _get_virtualizable_field_index(self, fielddescr):
1161 # Get the index of a fielddescr. Must only be called for
1162 # the "standard" virtualizable.
1163 vinfo = self.metainterp.jitdriver_sd.virtualizable_info
1164 return vinfo.static_field_by_descrs[fielddescr]
1165
1166 @arguments("box", "descr", "orgpc")
1167 def opimpl_getfield_vable_i(self, box, fielddescr, pc):
1168 if self._nonstandard_virtualizable(pc, box, fielddescr):
1169 return self.opimpl_getfield_gc_i(box, fielddescr)
1170 self.metainterp.check_synchronized_virtualizable()
1171 index = self._get_virtualizable_field_index(fielddescr)
1172 return self.metainterp.virtualizable_boxes[index]
1173 @arguments("box", "descr", "orgpc")
1174 def opimpl_getfield_vable_r(self, box, fielddescr, pc):
1175 if self._nonstandard_virtualizable(pc, box, fielddescr):
1176 return self.opimpl_getfield_gc_r(box, fielddescr)
1177 self.metainterp.check_synchronized_virtualizable()
1178 index = self._get_virtualizable_field_index(fielddescr)
1179 return self.metainterp.virtualizable_boxes[index]
1180 @arguments("box", "descr", "orgpc")
1181 def opimpl_getfield_vable_f(self, box, fielddescr, pc):
1182 if self._nonstandard_virtualizable(pc, box, fielddescr):
1183 return self.opimpl_getfield_gc_f(box, fielddescr)
1184 self.metainterp.check_synchronized_virtualizable()
1185 index = self._get_virtualizable_field_index(fielddescr)
1186 return self.metainterp.virtualizable_boxes[index]
1187
1188 @arguments("box", "box", "descr", "orgpc")
1189 def _opimpl_setfield_vable(self, box, valuebox, fielddescr, pc):
1190 if self._nonstandard_virtualizable(pc, box, fielddescr):
1191 return self._opimpl_setfield_gc_any(box, valuebox, fielddescr)
1192 index = self._get_virtualizable_field_index(fielddescr)
1193 self.metainterp.virtualizable_boxes[index] = valuebox
1194 self.metainterp.synchronize_virtualizable()
1195 # XXX only the index'th field needs to be synchronized, really
1196
1197 opimpl_setfield_vable_i = _opimpl_setfield_vable
1198 opimpl_setfield_vable_r = _opimpl_setfield_vable
1199 opimpl_setfield_vable_f = _opimpl_setfield_vable
1200
1201 def _get_arrayitem_vable_index(self, pc, arrayfielddescr, indexbox):
1202 # Get the index of an array item: the index'th of the array
1203 # described by arrayfielddescr. Must only be called for
1204 # the "standard" virtualizable.
1205 indexbox = self.implement_guard_value(indexbox, pc)
1206 vinfo = self.metainterp.jitdriver_sd.virtualizable_info
1207 virtualizable_box = self.metainterp.virtualizable_boxes[-1]
1208 virtualizable = vinfo.unwrap_virtualizable_box(virtualizable_box)
1209 arrayindex = vinfo.array_field_by_descrs[arrayfielddescr]
1210 index = indexbox.getint()
1211 # Support for negative index: disabled
1212 # (see codewriter/jtransform.py, _check_no_vable_array).
1213 #if index < 0:
1214 # index += vinfo.get_array_length(virtualizable, arrayindex)
1215 assert 0 <= index < vinfo.get_array_length(virtualizable, arrayindex)
1216 return vinfo.get_index_in_array(virtualizable, arrayindex, index)
1217
1218 @arguments("box", "box", "descr", "descr", "orgpc")
1219 def _opimpl_getarrayitem_vable(self, box, indexbox, fdescr, adescr, pc):
1220 if self._nonstandard_virtualizable(pc, box, fdescr):
1221 arraybox = self.opimpl_getfield_gc_r(box, fdescr)
1222 if adescr.is_array_of_pointers():
1223 return self.opimpl_getarrayitem_gc_r(arraybox, indexbox, adescr)
1224 elif adescr.is_array_of_floats():
1225 return self.opimpl_getarrayitem_gc_f(arraybox, indexbox, adescr)
1226 else:
1227 return self.opimpl_getarrayitem_gc_i(arraybox, indexbox, adescr)
1228 self.metainterp.check_synchronized_virtualizable()
1229 index = self._get_arrayitem_vable_index(pc, fdescr, indexbox)
1230 return self.metainterp.virtualizable_boxes[index]
1231
1232 opimpl_getarrayitem_vable_i = _opimpl_getarrayitem_vable
1233 opimpl_getarrayitem_vable_r = _opimpl_getarrayitem_vable
1234 opimpl_getarrayitem_vable_f = _opimpl_getarrayitem_vable
1235
1236 @arguments("box", "box", "box", "descr", "descr", "orgpc")
1237 def _opimpl_setarrayitem_vable(self, box, indexbox, valuebox,
1238 fdescr, adescr, pc):
1239 if self._nonstandard_virtualizable(pc, box, fdescr):
1240 arraybox = self.opimpl_getfield_gc_r(box, fdescr)
1241 self._opimpl_setarrayitem_gc_any(arraybox, indexbox, valuebox,
1242 adescr)
1243 return
1244 index = self._get_arrayitem_vable_index(pc, fdescr, indexbox)
1245 self.metainterp.virtualizable_boxes[index] = valuebox
1246 self.metainterp.synchronize_virtualizable()
1247 # XXX only the index'th field needs to be synchronized, really
1248
1249 opimpl_setarrayitem_vable_i = _opimpl_setarrayitem_vable
1250 opimpl_setarrayitem_vable_r = _opimpl_setarrayitem_vable
1251 opimpl_setarrayitem_vable_f = _opimpl_setarrayitem_vable
1252
1253 @arguments("box", "descr", "descr", "orgpc")
1254 def opimpl_arraylen_vable(self, box, fdescr, adescr, pc):
1255 if self._nonstandard_virtualizable(pc, box, fdescr):
1256 arraybox = self.opimpl_getfield_gc_r(box, fdescr)
1257 return self.opimpl_arraylen_gc(arraybox, adescr)
1258 vinfo = self.metainterp.jitdriver_sd.virtualizable_info
1259 virtualizable_box = self.metainterp.virtualizable_boxes[-1]
1260 virtualizable = vinfo.unwrap_virtualizable_box(virtualizable_box)
1261 arrayindex = vinfo.array_field_by_descrs[fdescr]
1262 result = vinfo.get_array_length(virtualizable, arrayindex)
1263 return ConstInt(result)
1264
1265 @arguments("newframe")
1266 def _opimpl_inline_call1(self, _):
1267 self._try_tco()
1268 raise ChangeFrame
1269 @arguments("newframe2")
1270 def _opimpl_inline_call2(self, _):
1271 self._try_tco()
1272 raise ChangeFrame
1273 @arguments("newframe3")
1274 def _opimpl_inline_call3(self, _):
1275 self._try_tco()
1276 raise ChangeFrame
1277
1278 def _try_tco(self):
1279 if self.jitcode.jitdriver_sd:
1280 return
1281 argcode = self._result_argcode
1282 pc = self.pc
1283 if argcode == 'v':
1284 target_index = -1
1285 else:
1286 target_index = ord(self.bytecode[pc - 1])
1287 op = ord(self.bytecode[pc])
1288 if op != self.metainterp.staticdata.op_live:
1289 # XXX should really not happen
1290 return
1291 next_pc = pc + SIZE_LIVE_OP
1292 if next_pc >= len(self.bytecode):
1293 return
1294 next_op = ord(self.bytecode[next_pc])
1295 if ((argcode == 'i' and next_op == self.metainterp.staticdata.op_int_return) or
1296 (argcode == 'r' and next_op == self.metainterp.staticdata.op_ref_return) or
1297 (argcode == 'f' and next_op == self.metainterp.staticdata.op_float_return) or
1298 (argcode == 'v' and next_op == self.metainterp.staticdata.op_void_return)
1299 ):
1300 # we have a return of the same type. check whether it's the result register
1301 if (target_index < 0 or
1302 ord(self.bytecode[next_pc + 1]) == target_index):
1303 debug_start("jit-tco")
1304 debug_print("removed frame", self.jitcode.name)
1305 debug_stop("jit-tco")
1306 assert self.metainterp.framestack[-2] is self
1307 del self.metainterp.framestack[-2]
1308 tracelength = self.metainterp.history.length()
1309 if tracelength == self.metainterp.trace_length_at_last_tco:
1310 # gh-5021: fix a pretty obscure problem: we can have
1311 # infinite recursion that is turned into a loop, without a
1312 # single new traced op. this would lead to an infinite
1313 # tail-recursive loop purely in the meta-interp, that isn't
1314 # even interuptible with ctrl-c
1315
1316 # we solve this with tracing a useless same_as. then we
1317 # will run into the tracelimit in this situation.
1318 self.metainterp._record_helper(
1319 rop.SAME_AS_I, tracelength, None, ConstInt(tracelength))
1320 else:
1321 self.metainterp.trace_length_at_last_tco = tracelength
1322
1323 opimpl_inline_call_r_i = _opimpl_inline_call1
1324 opimpl_inline_call_r_r = _opimpl_inline_call1
1325 opimpl_inline_call_r_v = _opimpl_inline_call1
1326 opimpl_inline_call_ir_i = _opimpl_inline_call2
1327 opimpl_inline_call_ir_r = _opimpl_inline_call2
1328 opimpl_inline_call_ir_v = _opimpl_inline_call2
1329 opimpl_inline_call_irf_i = _opimpl_inline_call3
1330 opimpl_inline_call_irf_r = _opimpl_inline_call3
1331 opimpl_inline_call_irf_f = _opimpl_inline_call3
1332 opimpl_inline_call_irf_v = _opimpl_inline_call3
1333
1334 @arguments("box", "boxes", "descr", "orgpc")
1335 def _opimpl_residual_call1(self, funcbox, argboxes, calldescr, pc):
1336 return self.do_residual_or_indirect_call(funcbox, argboxes, calldescr, pc)
1337
1338 @arguments("box", "boxes2", "descr", "orgpc")
1339 def _opimpl_residual_call2(self, funcbox, argboxes, calldescr, pc):
1340 return self.do_residual_or_indirect_call(funcbox, argboxes, calldescr, pc)
1341
1342 @arguments("box", "boxes3", "descr", "orgpc")
1343 def _opimpl_residual_call3(self, funcbox, argboxes, calldescr, pc):
1344 return self.do_residual_or_indirect_call(funcbox, argboxes, calldescr, pc)
1345
1346 opimpl_residual_call_r_i = _opimpl_residual_call1
1347 opimpl_residual_call_r_r = _opimpl_residual_call1
1348 opimpl_residual_call_r_v = _opimpl_residual_call1
1349 opimpl_residual_call_ir_i = _opimpl_residual_call2
1350 opimpl_residual_call_ir_r = _opimpl_residual_call2
1351 opimpl_residual_call_ir_v = _opimpl_residual_call2
1352 opimpl_residual_call_irf_i = _opimpl_residual_call3
1353 opimpl_residual_call_irf_r = _opimpl_residual_call3
1354 opimpl_residual_call_irf_f = _opimpl_residual_call3
1355 opimpl_residual_call_irf_v = _opimpl_residual_call3
1356
1357 @arguments("box", "box", "boxes2", "descr", "orgpc")
1358 def opimpl_conditional_call_ir_v(self, condbox, funcbox, argboxes,
1359 calldescr, pc):
1360 if isinstance(condbox, ConstInt) and condbox.value == 0:
1361 return # so that the heapcache can keep argboxes virtual
1362 self.do_conditional_call(condbox, funcbox, argboxes, calldescr, pc)
1363
1364 @arguments("box", "box", "boxes2", "descr", "orgpc")
1365 def _opimpl_conditional_call_value(self, valuebox, funcbox, argboxes,
1366 calldescr, pc):
1367 if isinstance(valuebox, Const) and valuebox.nonnull():
1368 return valuebox
1369 return self.do_conditional_call(valuebox, funcbox, argboxes,
1370 calldescr, pc, is_value=True)
1371
1372 opimpl_conditional_call_value_ir_i = _opimpl_conditional_call_value
1373 opimpl_conditional_call_value_ir_r = _opimpl_conditional_call_value
1374
1375 @arguments("int", "boxes3", "boxes3", "orgpc")
1376 def _opimpl_recursive_call(self, jdindex, greenboxes, redboxes, pc):
1377 targetjitdriver_sd = self.metainterp.staticdata.jitdrivers_sd[jdindex]
1378 allboxes = greenboxes + redboxes
1379 warmrunnerstate = targetjitdriver_sd.warmstate
1380 assembler_call = False
1381 if warmrunnerstate.inlining:
1382 if warmrunnerstate.can_inline_callable(greenboxes):
1383 # We've found a potentially inlinable function; now we need to
1384 # see if it's already on the stack. In other words: are we about
1385 # to enter recursion? If so, we don't want to inline the
1386 # recursion, which would be equivalent to unrolling a while
1387 # loop.
1388 portal_code = targetjitdriver_sd.mainjitcode
1389 count = 0
1390 for f in self.metainterp.framestack:
1391 if f.jitcode is not portal_code:
1392 continue
1393 gk = f.greenkey
1394 if gk is None:
1395 continue
1396 assert len(gk) == len(greenboxes)
1397 i = 0
1398 for i in range(len(gk)):
1399 if not gk[i].same_constant(greenboxes[i]):
1400 break
1401 else:
1402 count += 1
1403 memmgr = self.metainterp.staticdata.warmrunnerdesc.memory_manager
1404 if count >= memmgr.max_unroll_recursion:
1405 # This function is recursive and has exceeded the
1406 # maximum number of unrollings we allow. We want to stop
1407 # inlining it further and to make sure that, if it
1408 # hasn't happened already, the function is traced
1409 # separately as soon as possible.
1410 if have_debug_prints():
1411 loc = targetjitdriver_sd.warmstate.get_location_str(greenboxes)
1412 debug_print("recursive function (not inlined):", loc)
1413 warmrunnerstate.dont_trace_here(greenboxes)
1414 else:
1415 return self.metainterp.perform_call(portal_code, allboxes,
1416 greenkey=greenboxes)
1417 assembler_call = True
1418 # verify that we have all green args, needed to make sure
1419 # that assembler that we call is still correct
1420 self.verify_green_args(targetjitdriver_sd, greenboxes)
1421 #
1422 return self.do_recursive_call(targetjitdriver_sd, allboxes, pc,
1423 assembler_call)
1424
1425 def do_recursive_call(self, targetjitdriver_sd, allboxes, pc,
1426 assembler_call=False):
1427 portal_code = targetjitdriver_sd.mainjitcode
1428 k = targetjitdriver_sd.portal_runner_adr
1429 funcbox = ConstInt(adr2int(k))
1430 return self.do_residual_call(funcbox, allboxes, portal_code.calldescr, pc,
1431 assembler_call=assembler_call,
1432 assembler_call_jd=targetjitdriver_sd)
1433
1434 opimpl_recursive_call_i = _opimpl_recursive_call
1435 opimpl_recursive_call_r = _opimpl_recursive_call
1436 opimpl_recursive_call_f = _opimpl_recursive_call
1437 opimpl_recursive_call_v = _opimpl_recursive_call
1438
1439 @arguments("box")
1440 def opimpl_strlen(self, strbox):
1441 return self.execute(rop.STRLEN, strbox)
1442
1443 @arguments("box")
1444 def opimpl_unicodelen(self, unicodebox):
1445 return self.execute(rop.UNICODELEN, unicodebox)
1446
1447 @arguments("box", "box")
1448 def opimpl_strgetitem(self, strbox, indexbox):
1449 return self.execute(rop.STRGETITEM, strbox, indexbox)
1450
1451 @arguments("box", "box")
1452 def opimpl_unicodegetitem(self, unicodebox, indexbox):
1453 return self.execute(rop.UNICODEGETITEM, unicodebox, indexbox)
1454
1455 @arguments("box", "box", "box")
1456 def opimpl_strsetitem(self, strbox, indexbox, newcharbox):
1457 return self.execute(rop.STRSETITEM, strbox, indexbox, newcharbox)
1458
1459 @arguments("box", "box", "box")
1460 def opimpl_unicodesetitem(self, unicodebox, indexbox, newcharbox):
1461 self.execute(rop.UNICODESETITEM, unicodebox, indexbox, newcharbox)
1462
1463 @arguments("box")
1464 def opimpl_strhash(self, strbox):
1465 if isinstance(strbox, ConstPtr):
1466 h = self.metainterp.cpu.bh_strhash(strbox.getref_base())
1467 return ConstInt(h)
1468 return self.execute(rop.STRHASH, strbox)
1469
1470 @arguments("box")
1471 def opimpl_unicodehash(self, unicodebox):
1472 if isinstance(unicodebox, ConstPtr):
1473 h = self.metainterp.cpu.bh_unicodehash(unicodebox.getref_base())
1474 return ConstInt(h)
1475 return self.execute(rop.UNICODEHASH, unicodebox)
1476
1477 @arguments("box")
1478 def opimpl_newstr(self, lengthbox):
1479 return self.execute(rop.NEWSTR, lengthbox)
1480
1481 @arguments("box")
1482 def opimpl_newunicode(self, lengthbox):
1483 return self.execute(rop.NEWUNICODE, lengthbox)
1484
1485 @arguments("box", "box", "box", "box", "box")
1486 def opimpl_copystrcontent(self, srcbox, dstbox, srcstartbox, dststartbox, lengthbox):
1487 return self.execute(rop.COPYSTRCONTENT, srcbox, dstbox, srcstartbox, dststartbox, lengthbox)
1488
1489 @arguments("box", "box", "box", "box", "box")
1490 def opimpl_copyunicodecontent(self, srcbox, dstbox, srcstartbox, dststartbox, lengthbox):
1491 return self.execute(rop.COPYUNICODECONTENT, srcbox, dstbox, srcstartbox, dststartbox, lengthbox)
1492
1493 @arguments("box", "orgpc")
1494 def _opimpl_guard_value(self, box, orgpc):
1495 self.implement_guard_value(box, orgpc)
1496
1497 @arguments("box", "box", "descr", "orgpc")
1498 def opimpl_str_guard_value(self, box, funcbox, descr, orgpc):
1499 if isinstance(box, Const):
1500 return box # no promotion needed, already a Const
1501 else:
1502 constbox = ConstPtr(box.getref_base())
1503 resbox = self.do_residual_call(funcbox, [box, constbox], descr, orgpc)
1504 promoted_box = ConstInt(resbox.getint())
1505 # This is GUARD_VALUE because GUARD_TRUE assumes the existance
1506 # of a label when computing resumepc
1507 self.metainterp.generate_guard(rop.GUARD_VALUE, resbox,
1508 promoted_box,
1509 resumepc=orgpc)
1510 self.metainterp.replace_box(box, constbox)
1511 return constbox
1512
1513 opimpl_int_guard_value = _opimpl_guard_value
1514 opimpl_ref_guard_value = _opimpl_guard_value
1515 opimpl_float_guard_value = _opimpl_guard_value
1516
1517 @arguments("box", "orgpc")
1518 def opimpl_guard_class(self, box, orgpc):
1519 clsbox = self.cls_of_box(box)
1520 if not self.metainterp.heapcache.is_class_known(box):
1521 self.metainterp.generate_guard(rop.GUARD_CLASS, box, clsbox,
1522 resumepc=orgpc)
1523 self.metainterp.heapcache.class_now_known(box)
1524 return clsbox
1525
1526 @arguments("int", "orgpc")
1527 def opimpl_loop_header(self, jdindex, orgpc):
1528 self.metainterp.seen_loop_header_for_jdindex = jdindex
1529
1530 def verify_green_args(self, jitdriver_sd, varargs):
1531 num_green_args = jitdriver_sd.num_green_args
1532 assert len(varargs) == num_green_args
1533 for i in range(num_green_args):
1534 assert isinstance(varargs[i], Const)
1535
1536 @arguments("int", "boxes3", "jitcode_position", "boxes3", "orgpc")
1537 def opimpl_jit_merge_point(self, jdindex, greenboxes,
1538 jcposition, redboxes, orgpc):
1539 any_operation = self.metainterp.history.any_operation()
1540 jitdriver_sd = self.metainterp.staticdata.jitdrivers_sd[jdindex]
1541 self.verify_green_args(jitdriver_sd, greenboxes)
1542 self.debug_merge_point(jitdriver_sd, jdindex,
1543 self.metainterp.portal_call_depth,
1544 self.metainterp.call_ids[-1],
1545 greenboxes)
1546
1547 if self.metainterp.seen_loop_header_for_jdindex < 0:
1548 if not any_operation:
1549 return
1550 if not jitdriver_sd.no_loop_header:
1551 if self.metainterp.portal_call_depth:
1552 return
1553 ptoken = self.metainterp.get_procedure_token(greenboxes)
1554 if not has_compiled_targets(ptoken):
1555 return
1556 # automatically add a loop_header if there is none
1557 self.metainterp.seen_loop_header_for_jdindex = jdindex
1558 #
1559 assert self.metainterp.seen_loop_header_for_jdindex == jdindex, (
1560 "found a loop_header for a JitDriver that does not match "
1561 "the following jit_merge_point's")
1562 self.metainterp.seen_loop_header_for_jdindex = -1
1563
1564 #
1565 if not self.metainterp.portal_call_depth:
1566 assert jitdriver_sd is self.metainterp.jitdriver_sd
1567 # Set self.pc to point to jit_merge_point instead of just after:
1568 # if reached_loop_header() raises SwitchToBlackhole, then the
1569 # pc is still at the jit_merge_point, which is a point that is
1570 # much less expensive to blackhole out of.
1571 saved_pc = self.pc
1572 self.pc = orgpc
1573 self.metainterp.reached_loop_header(greenboxes, redboxes)
1574 self.pc = saved_pc
1575 # no exception, which means that the jit_merge_point did not
1576 # close the loop. We have to put the possibly-modified list
1577 # 'redboxes' back into the registers where it comes from.
1578 put_back_list_of_boxes3(self, jcposition, redboxes)
1579 else:
1580 if jitdriver_sd.warmstate.should_unroll_one_iteration(greenboxes):
1581 if self.unroll_iterations > 0:
1582 self.unroll_iterations -= 1
1583 return
1584 # warning! careful here. We have to return from the current
1585 # frame containing the jit_merge_point, and then use
1586 # do_recursive_call() to follow the recursive call. This is
1587 # needed because do_recursive_call() will write its result
1588 # with make_result_of_lastop(), so the lastop must be right:
1589 # it must be the call to 'self', and not the jit_merge_point
1590 # itself, which has no result at all.
1591 assert len(self.metainterp.framestack) >= 2
1592 old_frame = self.metainterp.framestack[-1]
1593 try:
1594 self.metainterp.finishframe(None, leave_portal_frame=False)
1595 except ChangeFrame:
1596 pass
1597 frame = self.metainterp.framestack[-1]
1598 frame.do_recursive_call(jitdriver_sd, greenboxes + redboxes, orgpc,
1599 assembler_call=True)
1600 jd_no = old_frame.jitcode.jitdriver_sd.index
1601 self.metainterp.leave_portal_frame(jd_no)
1602 raise ChangeFrame
1603
1604 def debug_merge_point(self, jitdriver_sd, jd_index, portal_call_depth, current_call_id, greenkey):
1605 # debugging: produce a DEBUG_MERGE_POINT operation
1606 if have_debug_prints():
1607 loc = jitdriver_sd.warmstate.get_location_str(greenkey)
1608 debug_print(loc)
1609 #
1610 # Note: the logger hides the jd_index argument, so we see in the logs:
1611 # debug_merge_point(portal_call_depth, current_call_id, 'location')
1612 #
1613 args = [ConstInt(jd_index), ConstInt(portal_call_depth),
1614 ConstInt(current_call_id)] + greenkey
1615 metainterp = self.metainterp
1616 metainterp.history.record(rop.DEBUG_MERGE_POINT, args, None)
1617 warmrunnerstate = jitdriver_sd.warmstate
1618 if (metainterp.force_finish_trace and
1619 (metainterp.history.length() > warmrunnerstate.trace_limit * 0.8)):
1620 self._create_segmented_trace_and_blackhole()
1621
1622 def _create_segmented_trace_and_blackhole(self):
1623 metainterp = self.metainterp
1624 # close to the trace limit, in a trace we really shouldn't
1625 # abort. finish it now
1626 metainterp.generate_guard(rop.GUARD_ALWAYS_FAILS)
1627 if we_are_translated():
1628 llexception = jitexc.get_llexception(metainterp.cpu, AssertionError())
1629 else:
1630 # fish an AssertionError instance
1631 llexception = jitexc._get_standard_error(metainterp.cpu.rtyper, AssertionError)
1632
1633 # add an unreachable finish that raises an AssertionError
1634 exception_box = ConstInt(ptr2int(llexception.typeptr))
1635 sd = metainterp.staticdata
1636 token = sd.exit_frame_with_exception_descr_ref
1637 metainterp.history.record1(rop.FINISH, exception_box, None, descr=token)
1638
1639 if (metainterp.current_merge_points and
1640 isinstance(metainterp.resumekey, compile.ResumeFromInterpDescr)):
1641 # making a loop. it's important to call compile_simple_loop to make
1642 # sure that a label at the beginning is inserted, otherwise we
1643 # cannot ever close the segmented loop later!
1644 original_boxes, start = metainterp.current_merge_points[0]
1645 jd_sd = metainterp.jitdriver_sd
1646 greenkey = original_boxes[:jd_sd.num_green_args]
1647 enable_opts = jd_sd.warmstate.enable_opts
1648 cut_at = metainterp.history.get_trace_position()
1649 fake_runtime_boxes = None
1650 vinfo = jd_sd.virtualizable_info
1651 if vinfo is not None:
1652 # this is a hack! compile_simple_loop does not actually need
1653 # the runtime boxes. the only thing it does is extract the
1654 # virtualizable box. so pass it that way
1655 fake_runtime_boxes = [None] * (jd_sd.index_of_virtualizable + 1)
1656 fake_runtime_boxes[jd_sd.index_of_virtualizable] = \
1657 metainterp.virtualizable_boxes[-1]
1658 target_token = compile.compile_simple_loop(
1659 metainterp, greenkey, metainterp.history.trace,
1660 fake_runtime_boxes, enable_opts, cut_at,
1661 patch_jumpop_at_end=False)
1662 jd_sd.warmstate.attach_procedure_to_interp(
1663 greenkey, target_token.targeting_jitcell_token)
1664
1665 else:
1666 target_token = compile.compile_trace(metainterp, metainterp.resumekey, [exception_box])
1667 if target_token is not token:
1668 compile.giveup()
1669
1670 # unlike basically any other trace that we can produce, we now need
1671 # to blackhole back to the interpreter instead of jumping to some
1672 # existing code, because we are at a really arbitrary place here!
1673 raise SwitchToBlackhole(Counters.ABORT_SEGMENTED_TRACE)
1674
1675
1676 @arguments("box", "label")
1677 def opimpl_goto_if_exception_mismatch(self, vtablebox, next_exc_target):
1678 metainterp = self.metainterp
1679 last_exc_value = metainterp.last_exc_value
1680 assert last_exc_value
1681 assert metainterp.class_of_last_exc_is_const
1682 cls = llmemory.cast_adr_to_ptr(vtablebox.getaddr(), rclass.CLASSTYPE)
1683 real_instance = rclass.ll_cast_to_object(last_exc_value)
1684 if not rclass.ll_isinstance(real_instance, cls):
1685 self.pc = next_exc_target
1686
1687 @arguments("box", "orgpc")
1688 def opimpl_raise(self, exc_value_box, orgpc):
1689 # xxx hack
1690 if not self.metainterp.heapcache.is_class_known(exc_value_box):
1691 clsbox = self.cls_of_box(exc_value_box)
1692 self.metainterp.generate_guard(rop.GUARD_CLASS, exc_value_box,
1693 clsbox, resumepc=orgpc)
1694 self.metainterp.class_of_last_exc_is_const = True
1695 self.metainterp.last_exc_value = exc_value_box.getref(rclass.OBJECTPTR)
1696 self.metainterp.last_exc_box = exc_value_box
1697 self.metainterp.popframe()
1698 self.metainterp.finishframe_exception()
1699
1700 @arguments()
1701 def opimpl_reraise(self):
1702 assert self.metainterp.last_exc_value
1703 self.metainterp.popframe()
1704 self.metainterp.finishframe_exception()
1705
1706 @arguments()
1707 def opimpl_last_exception(self):
1708 # Same comment as in opimpl_goto_if_exception_mismatch().
1709 exc_value = self.metainterp.last_exc_value
1710 assert exc_value
1711 assert self.metainterp.class_of_last_exc_is_const
1712 exc_cls = rclass.ll_cast_to_object(exc_value).typeptr
1713 return ConstInt(ptr2int(exc_cls))
1714
1715 @arguments()
1716 def opimpl_last_exc_value(self):
1717 exc_value = self.metainterp.last_exc_value
1718 assert exc_value
1719 return self.metainterp.last_exc_box
1720
1721 @arguments("box")
1722 def opimpl_debug_fatalerror(self, box):
1723 from rpython.rtyper.lltypesystem import rstr, lloperation
1724 msg = box.getref(lltype.Ptr(rstr.STR))
1725 lloperation.llop.debug_fatalerror(lltype.Void, msg)
1726
1727 @arguments("box", "box", "box", "box", "box")
1728 def opimpl_jit_debug(self, stringbox, arg1box, arg2box, arg3box, arg4box):
1729 debug_print('jit_debug:', stringbox._get_str(),
1730 arg1box.getint(), arg2box.getint(),
1731 arg3box.getint(), arg4box.getint())
1732 args = [stringbox, arg1box, arg2box, arg3box, arg4box]
1733 i = 4
1734 while i > 0 and args[i].getint() == -sys.maxint-1:
1735 i -= 1
1736 assert i >= 0
1737 op = self.metainterp.history.record(rop.JIT_DEBUG, args[:i+1], None)
1738 self.metainterp.attach_debug_info(op)
1739
1740 @arguments("box")
1741 def opimpl_jit_enter_portal_frame(self, uniqueidbox):
1742 unique_id = uniqueidbox.getint()
1743 jd_no = self.metainterp.jitdriver_sd.mainjitcode.index # fish
1744 self.metainterp.enter_portal_frame(jd_no, unique_id)
1745
1746 @arguments()
1747 def opimpl_jit_leave_portal_frame(self):
1748 jd_no = self.metainterp.jitdriver_sd.mainjitcode.index # fish
1749 self.metainterp.leave_portal_frame(jd_no)
1750
1751 @arguments("box")
1752 def _opimpl_assert_green(self, box):
1753 if not isinstance(box, Const):
1754 msg = "assert_green failed at %s:%d" % (
1755 self.jitcode.name,
1756 self.pc)
1757 if we_are_translated():
1758 from rpython.rtyper.annlowlevel import llstr
1759 from rpython.rtyper.lltypesystem import lloperation
1760 lloperation.llop.debug_fatalerror(lltype.Void, llstr(msg))
1761 else:
1762 from rpython.rlib.jit import AssertGreenFailed
1763 raise AssertGreenFailed(msg)
1764
1765 opimpl_int_assert_green = _opimpl_assert_green
1766 opimpl_ref_assert_green = _opimpl_assert_green
1767 opimpl_float_assert_green = _opimpl_assert_green
1768
1769 @arguments()
1770 def opimpl_current_trace_length(self):
1771 trace_length = self.metainterp.history.length()
1772 return ConstInt(trace_length)
1773
1774 @arguments("box")
1775 def _opimpl_isconstant(self, box):
1776 return ConstInt(isinstance(box, Const))
1777
1778 opimpl_int_isconstant = _opimpl_isconstant
1779 opimpl_ref_isconstant = _opimpl_isconstant
1780 opimpl_float_isconstant = _opimpl_isconstant
1781
1782 @arguments("box")
1783 def _opimpl_isvirtual(self, box):
1784 return ConstInt(self.metainterp.heapcache.is_likely_virtual(box))
1785
1786 opimpl_ref_isvirtual = _opimpl_isvirtual
1787
1788 @arguments("box")
1789 def opimpl_virtual_ref(self, box):
1790 # Details on the content of metainterp.virtualref_boxes:
1791 #
1792 # * it's a list whose items go two by two, containing first the
1793 # virtual box (e.g. the PyFrame) and then the vref box (e.g.
1794 # the 'virtual_ref(frame)').
1795 #
1796 # * if we detect that the virtual box escapes during tracing
1797 # already (by generating a CALL_MAY_FORCE that marks the flags
1798 # in the vref), then we replace the vref in the list with
1799 # ConstPtr(NULL).
1800 #
1801 metainterp = self.metainterp
1802 vrefinfo = metainterp.staticdata.virtualref_info
1803 obj = box.getref_base()
1804 vref = vrefinfo.virtual_ref_during_tracing(obj)
1805 cindex = history.ConstInt(len(metainterp.virtualref_boxes) // 2)
1806 resbox = metainterp.history.record2(rop.VIRTUAL_REF, box, cindex, vref)
1807 self.metainterp.heapcache.new(resbox)
1808 # Note: we allocate a JIT_VIRTUAL_REF here
1809 # (in virtual_ref_during_tracing()), in order to detect when
1810 # the virtual escapes during tracing already. We record it as a
1811 # VIRTUAL_REF operation. Later, optimizeopt.py should either kill
1812 # that operation or replace it with a NEW_WITH_VTABLE followed by
1813 # SETFIELD_GCs.
1814 metainterp.virtualref_boxes.append(box)
1815 metainterp.virtualref_boxes.append(resbox)
1816 return resbox
1817
1818 @arguments("box")
1819 def opimpl_virtual_ref_finish(self, box):
1820 # virtual_ref_finish() assumes that we have a stack-like, last-in
1821 # first-out order.
1822 metainterp = self.metainterp
1823 vrefbox = metainterp.virtualref_boxes.pop()
1824 lastbox = metainterp.virtualref_boxes.pop()
1825 assert box.getref_base() == lastbox.getref_base()
1826 vrefinfo = metainterp.staticdata.virtualref_info
1827 vref = vrefbox.getref_base()
1828 if vrefinfo.is_virtual_ref(vref):
1829 # XXX write a comment about nullbox
1830 nullbox = CONST_NULL
1831 metainterp.history.record2(rop.VIRTUAL_REF_FINISH,
1832 vrefbox, nullbox, None)
1833
1834 @arguments("int", "box")
1835 def opimpl_rvmprof_code(self, leaving, box_unique_id):
1836 from rpython.rlib.rvmprof import cintf
1837 cintf.jit_rvmprof_code(leaving, box_unique_id.getint())
1838
1839 @arguments()
1840 def opimpl_live(self):
1841 self.pc += OFFSET_SIZE
1842
1843 def handle_rvmprof_enter_on_resume(self):
1844 code = self.bytecode
1845 position = self.pc
1846 opcode = ord(code[position])
1847 if opcode == self.metainterp.staticdata.op_live:
1848 position += SIZE_LIVE_OP
1849 opcode = ord(code[position])
1850 if opcode == self.metainterp.staticdata.op_rvmprof_code:
1851 arg1 = self.registers_i[ord(code[position + 1])].getint()
1852 arg2 = self.registers_i[ord(code[position + 2])].getint()
1853 if arg1 == 1:
1854 # we are resuming at a position that will do a
1855 # jit_rvmprof_code(1), when really executed. That's a
1856 # hint for the need for a jit_rvmprof_code(0).
1857 from rpython.rlib.rvmprof import cintf
1858 cintf.jit_rvmprof_code(0, arg2)
1859
1860 # ------------------------------
1861
1862 def setup_call(self, argboxes):
1863 self.pc = 0
1864 count_i = count_r = count_f = 0
1865 for box in argboxes:
1866 if box.type == history.INT:
1867 self.registers_i[count_i] = box
1868 count_i += 1
1869 elif box.type == history.REF:
1870 self.registers_r[count_r] = box
1871 count_r += 1
1872 elif box.type == history.FLOAT:
1873 self.registers_f[count_f] = box
1874 count_f += 1
1875 else:
1876 raise AssertionError(box.type)
1877
1878 def setup_resume_at_op(self, pc):
1879 self.pc = pc
1880
1881 def handle_possible_overflow_error(self, label, orgpc, resbox):
1882 if self.metainterp.ovf_flag:
1883 self.metainterp.generate_guard(rop.GUARD_OVERFLOW,
1884 resumepc=orgpc)
1885 self.pc = label
1886 return None
1887 else:
1888 self.metainterp.generate_guard(rop.GUARD_NO_OVERFLOW,
1889 resumepc=orgpc)
1890 return resbox
1891
1892 def run_one_step(self):
1893 # Execute the frame forward. This method contains a loop that leaves
1894 # whenever the 'opcode_implementations' (which is one of the 'opimpl_'
1895 # methods) raises ChangeFrame. This is the case when the current frame
1896 # changes, due to a call or a return.
1897 try:
1898 staticdata = self.metainterp.staticdata
1899 pc = self.pc
1900 while True:
1901 bytecode = self.bytecode
1902 op = ord(bytecode[pc])
1903 if op == staticdata.op_live:
1904 pc += OFFSET_SIZE + 1
1905 self.pc = pc
1906 continue
1907 elif op == staticdata.op_goto:
1908 pc = ord(bytecode[pc + 1]) | (ord(bytecode[pc + 2])<<8)
1909 self.pc = pc
1910 continue
1911 staticdata.opcode_implementations[op](self, pc)
1912 pc = self.pc
1913 except ChangeFrame:
1914 pass
1915
1916 def implement_guard_value(self, box, orgpc):
1917 """Promote the given Box into a Const. Note: be careful, it's a
1918 bit unclear what occurs if a single opcode needs to generate
1919 several ones and/or ones not near the beginning."""
1920 if isinstance(box, Const):
1921 return box # no promotion needed, already a Const
1922 else:
1923 promoted_box = executor.constant_from_op(box)
1924 self.metainterp.generate_guard(rop.GUARD_VALUE, box, promoted_box,
1925 resumepc=orgpc)
1926 self.metainterp.replace_box(box, promoted_box)
1927 return promoted_box
1928
1929 def cls_of_box(self, box):
1930 return self.metainterp.cpu.cls_of_box(box)
1931
1932 @specialize.arg(1)
1933 def execute(self, opnum, *argboxes):
1934 return self.metainterp.execute_and_record(opnum, None, *argboxes)
1935
1936 @specialize.arg(1)
1937 def execute_with_descr(self, opnum, descr, *argboxes):
1938 return self.metainterp.execute_and_record(opnum, descr, *argboxes)
1939
1940 @specialize.arg(1)
1941 def execute_varargs(self, opnum, argboxes, descr, exc, pure):
1942 self.metainterp.clear_exception()
1943 patch_pos = self.metainterp.history.get_trace_position()
1944 op = self.metainterp.execute_and_record_varargs(opnum, argboxes,
1945 descr=descr)
1946 if pure and not self.metainterp.last_exc_value and op:
1947 op = self.metainterp.record_result_of_call_pure(op, argboxes, descr,
1948 patch_pos, opnum)
1949 exc = exc and not isinstance(op, Const)
1950 if exc:
1951 if op is not None:
1952 self.make_result_of_lastop(op)
1953 # ^^^ this is done before handle_possible_exception() because we
1954 # need the box to show up in get_list_of_active_boxes()
1955 self.metainterp.handle_possible_exception()
1956 else:
1957 self.metainterp.assert_no_exception()
1958 return op
1959
1960 def _build_allboxes(self, funcbox, argboxes, descr, prepend_box=None):
1961 allboxes = [None] * (len(argboxes)+1 + int(prepend_box is not None))
1962 i = 0
1963 if prepend_box is not None:
1964 allboxes[0] = prepend_box
1965 i = 1
1966 allboxes[i] = funcbox
1967 i += 1
1968 src_i = src_r = src_f = 0
1969 for kind in descr.get_arg_types():
1970 if kind == history.INT or kind == 'S': # single float
1971 while True:
1972 box = argboxes[src_i]
1973 src_i += 1
1974 if box.type == history.INT:
1975 break
1976 elif kind == history.REF:
1977 while True:
1978 box = argboxes[src_r]
1979 src_r += 1
1980 if box.type == history.REF:
1981 break
1982 elif kind == history.FLOAT or kind == 'L': # long long
1983 while True:
1984 box = argboxes[src_f]
1985 src_f += 1
1986 if box.type == history.FLOAT:
1987 break
1988 else:
1989 raise AssertionError
1990 allboxes[i] = box
1991 i += 1
1992 assert i == len(allboxes)
1993 return allboxes
1994
1995 def do_residual_call(self, funcbox, argboxes, descr, pc,
1996 assembler_call=False,
1997 assembler_call_jd=None):
1998 # First build allboxes: it may need some reordering from the
1999 # list provided in argboxes, depending on the order in which
2000 # the arguments are expected by the function
2001 #
2002 allboxes = self._build_allboxes(funcbox, argboxes, descr)
2003 effectinfo = descr.get_extra_info()
2004 if effectinfo.oopspecindex == effectinfo.OS_NOT_IN_TRACE:
2005 return self.metainterp.do_not_in_trace_call(allboxes, descr)
2006
2007 if (assembler_call or
2008 effectinfo.check_forces_virtual_or_virtualizable()):
2009 # residual calls require attention to keep virtualizables in-sync
2010 self.metainterp.clear_exception()
2011 if effectinfo.oopspecindex == EffectInfo.OS_JIT_FORCE_VIRTUAL:
2012 resbox = self._do_jit_force_virtual(allboxes, descr, pc)
2013 if resbox is not None:
2014 return resbox
2015
2016 # 1. preparation
2017 self.metainterp.vable_and_vrefs_before_residual_call()
2018
2019 # 2. actually do the call now (we'll have cases later): the
2020 # result is stored into 'c_result' for now, which is a Const
2021 metainterp = self.metainterp
2022 tp = descr.get_normalized_result_type()
2023 if tp == 'i':
2024 opnum1 = rop.CALL_MAY_FORCE_I
2025 value = executor.execute_varargs(metainterp.cpu, metainterp,
2026 opnum1, allboxes, descr)
2027 c_result = ConstInt(value)
2028 elif tp == 'r':
2029 opnum1 = rop.CALL_MAY_FORCE_R
2030 value = executor.execute_varargs(metainterp.cpu, metainterp,
2031 opnum1, allboxes, descr)
2032 c_result = ConstPtr(value)
2033 elif tp == 'f':
2034 opnum1 = rop.CALL_MAY_FORCE_F
2035 value = executor.execute_varargs(metainterp.cpu, metainterp,
2036 opnum1, allboxes, descr)
2037 c_result = ConstFloat(value)
2038 elif tp == 'v':
2039 opnum1 = rop.CALL_MAY_FORCE_N
2040 executor.execute_varargs(metainterp.cpu, metainterp,
2041 opnum1, allboxes, descr)
2042 c_result = None
2043 else:
2044 assert False
2045
2046 # 3. after this call, check the vrefs. If any have been
2047 # forced by the call, then we record in the trace a
2048 # VIRTUAL_REF_FINISH---before we record any CALL
2049 self.metainterp.vrefs_after_residual_call()
2050
2051 # 4. figure out what kind of CALL we need to record
2052 # from the effectinfo and the 'assembler_call' flag
2053 if assembler_call:
2054 vablebox, resbox = self.metainterp.direct_assembler_call(
2055 allboxes, c_result, descr, assembler_call_jd)
2056 else:
2057 vablebox = None
2058 resbox = None
2059 if effectinfo.oopspecindex == effectinfo.OS_LIBFFI_CALL:
2060 resbox = self.metainterp.direct_libffi_call(allboxes, c_result, descr)
2061 # ^^^ may return None to mean "can't handle it myself"
2062 if resbox is None:
2063 if effectinfo.is_call_release_gil():
2064 resbox = self.metainterp.direct_call_release_gil(
2065 allboxes, c_result, descr)
2066 else:
2067 resbox = self.metainterp.direct_call_may_force(
2068 allboxes, c_result, descr)
2069
2070 # 5. invalidate the heapcache based on the CALL_MAY_FORCE
2071 # operation executed above in step 2
2072 self.metainterp.heapcache.invalidate_caches_varargs(opnum1, descr, allboxes)
2073
2074 if resbox.type == 'v':
2075 resbox = None # for void calls, must return None below
2076 else:
2077 self.make_result_of_lastop(resbox)
2078 self.metainterp.vable_after_residual_call(funcbox)
2079 self.metainterp.generate_guard(rop.GUARD_NOT_FORCED)
2080 if vablebox is not None:
2081 self.metainterp.history.record1(rop.KEEPALIVE, vablebox, None)
2082 self.metainterp.handle_possible_exception()
2083 return resbox
2084 else:
2085 effect = effectinfo.extraeffect
2086 tp = descr.get_normalized_result_type()
2087 if effect == effectinfo.EF_LOOPINVARIANT:
2088 res = self.metainterp.heapcache.call_loopinvariant_known_result(allboxes, descr)
2089 if res is not None:
2090 return res
2091 if tp == 'i':
2092 res = self.execute_varargs(rop.CALL_LOOPINVARIANT_I,
2093 allboxes,
2094 descr, False, False)
2095 elif tp == 'r':
2096 res = self.execute_varargs(rop.CALL_LOOPINVARIANT_R,
2097 allboxes,
2098 descr, False, False)
2099 elif tp == 'f':
2100 res = self.execute_varargs(rop.CALL_LOOPINVARIANT_F,
2101 allboxes,
2102 descr, False, False)
2103 elif tp == 'v':
2104 res = self.execute_varargs(rop.CALL_LOOPINVARIANT_N,
2105 allboxes,
2106 descr, False, False)
2107 else:
2108 assert False
2109 self.metainterp.heapcache.call_loopinvariant_now_known(allboxes, descr, res)
2110 return res
2111 exc = effectinfo.check_can_raise()
2112 pure = effectinfo.check_is_elidable()
2113 if tp == 'i':
2114 return self.execute_varargs(rop.CALL_I, allboxes, descr,
2115 exc, pure)
2116 elif tp == 'r':
2117 return self.execute_varargs(rop.CALL_R, allboxes, descr,
2118 exc, pure)
2119 elif tp == 'f':
2120 return self.execute_varargs(rop.CALL_F, allboxes, descr,
2121 exc, pure)
2122 elif tp == 'v':
2123 return self.execute_varargs(rop.CALL_N, allboxes, descr,
2124 exc, pure)
2125 else:
2126 assert False
2127
2128 def do_conditional_call(self, condbox, funcbox, argboxes, descr, pc,
2129 is_value=False):
2130 allboxes = self._build_allboxes(funcbox, argboxes, descr, prepend_box=condbox)
2131 effectinfo = descr.get_extra_info()
2132 assert not effectinfo.check_forces_virtual_or_virtualizable()
2133 exc = effectinfo.check_can_raise()
2134 # COND_CALL cannot be pure (=elidable): it has no result.
2135 # On the other hand, COND_CALL_VALUE is always calling a pure
2136 # function.
2137 if not is_value:
2138 return self.execute_varargs(rop.COND_CALL, allboxes, descr,
2139 exc, pure=False)
2140 else:
2141 opnum = OpHelpers.cond_call_value_for_descr(descr)
2142 # work around the fact that execute_varargs() wants a
2143 # constant for first argument
2144 if opnum == rop.COND_CALL_VALUE_I:
2145 return self.execute_varargs(rop.COND_CALL_VALUE_I, allboxes,
2146 descr, exc, pure=True)
2147 elif opnum == rop.COND_CALL_VALUE_R:
2148 return self.execute_varargs(rop.COND_CALL_VALUE_R, allboxes,
2149 descr, exc, pure=True)
2150 else:
2151 raise AssertionError
2152
2153 def _do_jit_force_virtual(self, allboxes, descr, pc):
2154 assert len(allboxes) == 2
2155 if (self.metainterp.jitdriver_sd.virtualizable_info is None and
2156 self.metainterp.jitdriver_sd.greenfield_info is None):
2157 # can occur in case of multiple JITs
2158 return None
2159 vref_box = allboxes[1]
2160 standard_box = self.metainterp.virtualizable_boxes[-1]
2161 if standard_box is vref_box:
2162 return vref_box
2163 if self.metainterp.heapcache.is_known_nonstandard_virtualizable(vref_box):
2164 self.metainterp.staticdata.profiler.count_ops(rop.PTR_EQ, Counters.HEAPCACHED_OPS)
2165 return None
2166 eqbox = self.metainterp.execute_and_record(rop.PTR_EQ, None, vref_box, standard_box)
2167 eqbox = self.implement_guard_value(eqbox, pc)
2168 isstandard = eqbox.getint()
2169 if isstandard:
2170 return standard_box
2171 else:
2172 return None
2173
2174 def do_residual_or_indirect_call(self, funcbox, argboxes, calldescr, pc):
2175 """The 'residual_call' operation is emitted in two cases:
2176 when we have to generate a residual CALL operation, but also
2177 to handle an indirect_call that may need to be inlined."""
2178 if isinstance(funcbox, Const):
2179 sd = self.metainterp.staticdata
2180 key = funcbox.getaddr()
2181 jitcode = sd.bytecode_for_address(key)
2182 if jitcode is not None:
2183 # we should follow calls to this graph
2184 return self.metainterp.perform_call(jitcode, argboxes)
2185 # but we should not follow calls to that graph
2186 return self.do_residual_call(funcbox, argboxes, calldescr, pc)
2187
2188 # ____________________________________________________________
2189
2190 class MetaInterpStaticData(object):
2191 logger_noopt = None
2192 logger_ops = None
2193
2194 def __init__(self, cpu, options,
2195 ProfilerClass=EmptyProfiler, warmrunnerdesc=None):
2196 self.cpu = cpu
2197 self.stats = self.cpu.stats
2198 self.options = options
2199 self.jitlog = jl.JitLogger(self.cpu)
2200 self.logger_noopt = Logger(self)
2201 self.logger_ops = Logger(self, guard_number=True)
2202 # legacy loggers
2203 self.jitlog.logger_noopt = self.logger_noopt
2204 self.jitlog.logger_ops = self.logger_ops
2205
2206 self.profiler = ProfilerClass()
2207 self.profiler.cpu = cpu
2208 self.warmrunnerdesc = warmrunnerdesc
2209 if warmrunnerdesc:
2210 self.config = warmrunnerdesc.translator.config
2211 else:
2212 from rpython.config.translationoption import get_combined_translation_config
2213 self.config = get_combined_translation_config(translating=True)
2214
2215 backendmodule = self.cpu.__module__
2216 backendmodule = backendmodule.split('.')[-2]
2217 self.jit_starting_line = 'JIT starting (%s)' % backendmodule
2218
2219 self._addr2name_keys = []
2220 self._addr2name_values = []
2221
2222 compile.make_and_attach_done_descrs([self, cpu])
2223
2224 def _freeze_(self):
2225 return True
2226
2227 def setup_insns(self, insns):
2228 self.opcode_names = ['?'] * len(insns)
2229 self.opcode_implementations = [None] * len(insns)
2230 for key, value in insns.items():
2231 assert self.opcode_implementations[value] is None
2232 self.opcode_names[value] = key
2233 name, argcodes = key.split('/')
2234 opimpl = _get_opimpl_method(name, argcodes)
2235 self.opcode_implementations[value] = opimpl
2236 self.op_live = insns.get('live/', -1)
2237 self.op_goto = insns.get('goto/L', -1)
2238 self.op_catch_exception = insns.get('catch_exception/L', -1)
2239 self.op_rvmprof_code = insns.get('rvmprof_code/ii', -1)
2240 self.op_int_return = insns.get('int_return/i', -1)
2241 self.op_ref_return = insns.get('ref_return/r', -1)
2242 self.op_float_return = insns.get('float_return/f', -1)
2243 self.op_void_return = insns.get('void_return/', -1)
2244
2245 def setup_descrs(self, descrs):
2246 self.opcode_descrs = descrs
2247
2248 def setup_indirectcalltargets(self, indirectcalltargets):
2249 self.indirectcalltargets = list(indirectcalltargets)
2250
2251 def setup_list_of_addr2name(self, list_of_addr2name):
2252 self._addr2name_keys = [key for key, value in list_of_addr2name]
2253 self._addr2name_values = [value for key, value in list_of_addr2name]
2254
2255 def finish_setup(self, codewriter, optimizer=None):
2256 from rpython.jit.metainterp.blackhole import BlackholeInterpBuilder
2257 self.blackholeinterpbuilder = BlackholeInterpBuilder(codewriter, self)
2258 #
2259 asm = codewriter.assembler
2260 self.setup_insns(asm.insns)
2261 self.setup_descrs(asm.descrs)
2262 self.setup_indirectcalltargets(asm.indirectcalltargets)
2263 self.setup_list_of_addr2name(asm.list_of_addr2name)
2264 self.liveness_info = "".join(asm.all_liveness)
2265 #
2266 self.jitdrivers_sd = codewriter.callcontrol.jitdrivers_sd
2267 self.virtualref_info = codewriter.callcontrol.virtualref_info
2268 self.callinfocollection = codewriter.callcontrol.callinfocollection
2269 self.has_libffi_call = codewriter.callcontrol.has_libffi_call
2270 #
2271 # store this information for fastpath of call_assembler
2272 # (only the paths that can actually be taken)
2273 exc_descr = compile.PropagateExceptionDescr()
2274 for jd in self.jitdrivers_sd:
2275 name = {history.INT: 'int',
2276 history.REF: 'ref',
2277 history.FLOAT: 'float',
2278 history.VOID: 'void'}[jd.result_type]
2279 token = getattr(self, 'done_with_this_frame_descr_%s' % name)
2280 jd.portal_finishtoken = token
2281 jd.propagate_exc_descr = exc_descr
2282 #
2283 self.cpu.propagate_exception_descr = exc_descr
2284 #
2285 self.globaldata = MetaInterpGlobalData(self)
2286
2287 def finish_setup_descrs(self):
2288 from rpython.jit.codewriter import effectinfo
2289 self.all_descrs = self.cpu.setup_descrs()
2290 effectinfo.compute_bitstrings(self.all_descrs)
2291
2292 def _setup_once(self):
2293 """Runtime setup needed by the various components of the JIT."""
2294 if not self.globaldata.initialized:
2295 self.jitlog.setup_once()
2296 debug_print(self.jit_starting_line)
2297 self.cpu.setup_once()
2298 if self.cpu.vector_ext:
2299 self.cpu.vector_ext.setup_once(self.cpu.assembler)
2300 if not self.profiler.initialized:
2301 self.profiler.start()
2302 self.profiler.initialized = True
2303 self.globaldata.initialized = True
2304
2305 def get_name_from_address(self, addr):
2306 # for debugging only
2307 if we_are_translated():
2308 d = self.globaldata.addr2name
2309 if d is None:
2310 # Build the dictionary at run-time. This is needed
2311 # because the keys are function/class addresses, so they
2312 # can change from run to run.
2313 d = {}
2314 keys = self._addr2name_keys
2315 values = self._addr2name_values
2316 for i in range(len(keys)):
2317 d[keys[i]] = values[i]
2318 self.globaldata.addr2name = d
2319 return d.get(addr, '')
2320 else:
2321 for i in range(len(self._addr2name_keys)):
2322 if addr == self._addr2name_keys[i]:
2323 return self._addr2name_values[i]
2324 return ''
2325
2326 def bytecode_for_address(self, fnaddress):
2327 if we_are_translated():
2328 d = self.globaldata.indirectcall_dict
2329 if d is None:
2330 # Build the dictionary at run-time. This is needed
2331 # because the keys are function addresses, so they
2332 # can change from run to run.
2333 d = {}
2334 for jitcode in self.indirectcalltargets:
2335 assert jitcode.fnaddr not in d
2336 d[jitcode.fnaddr] = jitcode
2337 self.globaldata.indirectcall_dict = d
2338 return d.get(fnaddress, None)
2339 else:
2340 for jitcode in self.indirectcalltargets:
2341 if jitcode.fnaddr == fnaddress:
2342 return jitcode
2343 return None
2344
2345 def try_to_free_some_loops(self):
2346 # Increase here the generation recorded by the memory manager.
2347 if self.warmrunnerdesc is not None: # for tests
2348 self.warmrunnerdesc.memory_manager.next_generation()
2349
2350 # ---------------- logging ------------------------
2351
2352 def log(self, msg):
2353 debug_print(msg)
2354
2355 def _try_find_typeid_for_vtable(self, known_class):
2356 # this doesn't work for all vtables, only those where the JIT built a
2357 # descr (ie sees the allocation). it's only used in the optimizer to
2358 # try to detect invalid loops/bridges early. if not found, it raises
2359 # KeyError
2360 d = self.globaldata.vtable2typeid
2361 if d is None:
2362 # Build the dictionary at run-time. This is needed
2363 # because the keys are vtable addresses, so they
2364 # can change from run to run.
2365 d = {}
2366 for descr in self.opcode_descrs:
2367 vtable = descr.get_vtable()
2368 typeid = descr.get_type_id()
2369 if vtable and typeid >= 0:
2370 # using the hash as the key is safe, it's just the pointer
2371 # value of the vtable
2372 d[ConstInt(vtable)._get_hash_()] = typeid
2373 self.globaldata.vtable2typeid = d
2374 if not d: # happens in a few backend tests eg test_ztranslation_jit_stats.py
2375 raise KeyError
2376 return d[known_class._get_hash_()]
2377
2378 # ____________________________________________________________
2379
2380 class MetaInterpGlobalData(object):
2381 """This object contains the JIT's global, mutable data.
2382
2383 Warning: for any data that you put here, think that there might be
2384 multiple MetaInterps accessing it at the same time. As usual we are
2385 safe from corruption thanks to the GIL, but keep in mind that any
2386 MetaInterp might modify any of these fields while another MetaInterp
2387 is, say, currently in a residual call to a function. Multiple
2388 MetaInterps occur either with threads or, in single-threaded cases,
2389 with recursion. This is a case that is not well-tested, so please
2390 be careful :-( But thankfully this is one of the very few places
2391 where multiple concurrent MetaInterps may interact with each other.
2392 """
2393 def __init__(self, staticdata):
2394 self.initialized = False
2395 self.indirectcall_dict = None
2396 self.addr2name = None
2397 self.vtable2typeid = None
2398
2399 # ____________________________________________________________
2400
2401 class MetaInterp(object):
2402 portal_call_depth = 0
2403 cancel_count = 0
2404 exported_state = None
2405 last_exc_box = None
2406 _last_op = None
2407
2408 def __init__(self, staticdata, jitdriver_sd, force_finish_trace=False):
2409 self.staticdata = staticdata
2410 self.cpu = staticdata.cpu
2411 self.jitdriver_sd = jitdriver_sd
2412 # Note: self.jitdriver_sd is the JitDriverStaticData that corresponds
2413 # to the current loop -- the outermost one. Be careful, because
2414 # during recursion we can also see other jitdrivers.
2415 self.portal_trace_positions = []
2416 self.free_frames_list = []
2417 self.last_exc_value = lltype.nullptr(rclass.OBJECT)
2418 self.forced_virtualizable = None
2419 self.partial_trace = None
2420 self.retracing_from = (-1, -1, -1, -1, -1)
2421 self.call_pure_results = args_dict()
2422 self.heapcache = HeapCache()
2423
2424 self.call_ids = []
2425 self.current_call_id = 0
2426
2427 self.box_names_memo = {}
2428
2429 self.aborted_tracing_jitdriver = None
2430 self.aborted_tracing_greenkey = None
2431
2432 # set to true if we really should finish the trace
2433 # with a GUARD_ALWAYS_FAILS (and an unreachable finish that raises
2434 # AssertionError)
2435 self.force_finish_trace = force_finish_trace
2436 self.trace_length_at_last_tco = -1
2437
2438 def retrace_needed(self, trace, exported_state):
2439 self.partial_trace = trace
2440 self.retracing_from = self.potential_retrace_position
2441 self.exported_state = exported_state
2442 self.heapcache.reset()
2443
2444
2445 def perform_call(self, jitcode, boxes, greenkey=None):
2446 # causes the metainterp to enter the given subfunction
2447 f = self.newframe(jitcode, greenkey)
2448 f.setup_call(boxes)
2449 raise ChangeFrame
2450
2451 def is_main_jitcode(self, jitcode):
2452 return (jitcode.jitdriver_sd is not None and
2453 jitcode.jitdriver_sd.jitdriver.is_recursive)
2454 #return self.jitdriver_sd is not None and jitcode is self.jitdriver_sd.mainjitcode
2455
2456 def newframe(self, jitcode, greenkey=None):
2457 if jitcode.jitdriver_sd:
2458 self.portal_call_depth += 1
2459 self.call_ids.append(self.current_call_id)
2460 unique_id = -1
2461 if greenkey is not None:
2462 unique_id = jitcode.jitdriver_sd.warmstate.get_unique_id(
2463 greenkey)
2464 jd_no = jitcode.jitdriver_sd.index
2465 self.enter_portal_frame(jd_no, unique_id)
2466 self.current_call_id += 1
2467 if greenkey is not None and self.is_main_jitcode(jitcode):
2468 self.portal_trace_positions.append(
2469 (jitcode.jitdriver_sd, greenkey, self.history.get_trace_position()))
2470 if len(self.free_frames_list) > 0:
2471 f = self.free_frames_list.pop()
2472 else:
2473 f = MIFrame(self)
2474 f.setup(jitcode, greenkey)
2475 self.framestack.append(f)
2476 return f
2477
2478 def enter_portal_frame(self, jd_no, unique_id):
2479 self.history.record2(rop.ENTER_PORTAL_FRAME,
2480 ConstInt(jd_no), ConstInt(unique_id), None)
2481
2482 def leave_portal_frame(self, jd_no):
2483 self.history.record1(rop.LEAVE_PORTAL_FRAME, ConstInt(jd_no), None)
2484
2485
2486 def popframe(self, leave_portal_frame=True):
2487 frame = self.framestack.pop()
2488 jitcode = frame.jitcode
2489 if jitcode.jitdriver_sd:
2490 self.portal_call_depth -= 1
2491 if leave_portal_frame:
2492 self.leave_portal_frame(jitcode.jitdriver_sd.index)
2493 self.call_ids.pop()
2494 if frame.greenkey is not None and self.is_main_jitcode(jitcode):
2495 self.portal_trace_positions.append(
2496 (jitcode.jitdriver_sd, None, self.history.get_trace_position()))
2497 # we save the freed MIFrames to avoid needing to re-create new
2498 # MIFrame objects all the time; they are a bit big, with their
2499 # up to 3*256 register entries.
2500 frame.cleanup_registers()
2501 self.free_frames_list.append(frame)
2502
2503 def finishframe(self, resultbox, leave_portal_frame=True):
2504 # handle a non-exceptional return from the current frame
2505 self.last_exc_value = lltype.nullptr(rclass.OBJECT)
2506 self.popframe(leave_portal_frame=leave_portal_frame)
2507 if self.framestack:
2508 if resultbox is not None:
2509 self.framestack[-1].make_result_of_lastop(resultbox)
2510 raise ChangeFrame
2511 else:
2512 try:
2513 self.compile_done_with_this_frame(resultbox)
2514 except SwitchToBlackhole as stb:
2515 self.aborted_tracing(stb.reason)
2516 sd = self.staticdata
2517 result_type = self.jitdriver_sd.result_type
2518 if result_type == history.VOID:
2519 assert resultbox is None
2520 raise jitexc.DoneWithThisFrameVoid()
2521 elif result_type == history.INT:
2522 raise jitexc.DoneWithThisFrameInt(int(resultbox.getint()))
2523 elif result_type == history.REF:
2524 raise jitexc.DoneWithThisFrameRef(resultbox.getref_base())
2525 elif result_type == history.FLOAT:
2526 raise jitexc.DoneWithThisFrameFloat(resultbox.getfloatstorage())
2527 else:
2528 assert False
2529
2530 def finishframe_exception(self):
2531 excvalue = self.last_exc_value
2532 while self.framestack:
2533 frame = self.framestack[-1]
2534 code = frame.bytecode
2535 position = frame.pc # <-- just after the insn that raised
2536 if position < len(code):
2537 opcode = ord(code[position])
2538 if opcode == self.staticdata.op_live: # live, skip it
2539 position += SIZE_LIVE_OP
2540 opcode = ord(code[position])
2541 if opcode == self.staticdata.op_catch_exception:
2542 # found a 'catch_exception' instruction;
2543 # jump to the handler
2544 target = ord(code[position+1]) | (ord(code[position+2])<<8)
2545 frame.pc = target
2546 raise ChangeFrame
2547 if opcode == self.staticdata.op_rvmprof_code:
2548 # call the 'jit_rvmprof_code(1)' for rvmprof, but then
2549 # continue popping frames. Decode the 'rvmprof_code' insn
2550 # manually here.
2551 from rpython.rlib.rvmprof import cintf
2552 arg1 = frame.registers_i[ord(code[position + 1])].getint()
2553 arg2 = frame.registers_i[ord(code[position + 2])].getint()
2554 assert arg1 == 1
2555 cintf.jit_rvmprof_code(arg1, arg2)
2556 self.popframe()
2557 try:
2558 self.compile_exit_frame_with_exception(self.last_exc_box)
2559 except SwitchToBlackhole as stb:
2560 self.aborted_tracing(stb.reason)
2561 raise jitexc.ExitFrameWithExceptionRef(
2562 lltype.cast_opaque_ptr(llmemory.GCREF, excvalue))
2563
2564 def check_recursion_invariant(self):
2565 portal_call_depth = -1
2566 for frame in self.framestack:
2567 jitcode = frame.jitcode
2568 if jitcode.jitdriver_sd:
2569 portal_call_depth += 1
2570 if portal_call_depth != self.portal_call_depth:
2571 print("portal_call_depth problem!!!")
2572 print(portal_call_depth, self.portal_call_depth)
2573 for frame in self.framestack:
2574 jitcode = frame.jitcode
2575 if jitcode.jitdriver_sd:
2576 print("P", end=" ")
2577 else:
2578 print(" ", end=" ")
2579 print(jitcode.name)
2580 raise AssertionError
2581
2582 def generate_guard(self, opnum, box=None, extraarg=None, resumepc=-1):
2583 if isinstance(box, Const): # no need for a guard
2584 return
2585 if opnum == rop.GUARD_EXCEPTION:
2586 assert box is None
2587 assert extraarg is not None
2588 guard_op = self.history.record1(opnum, extraarg,
2589 lltype.nullptr(llmemory.GCREF.TO))
2590 else:
2591 if box is not None and extraarg is not None:
2592 guard_op = self.history.record2(opnum, box, extraarg, None)
2593 elif box is not None:
2594 guard_op = self.history.record1(opnum, box, None)
2595 elif extraarg is not None:
2596 guard_op = self.history.record1(opnum, extraarg, None)
2597 else:
2598 guard_op = self.history.record0(opnum, None)
2599 after_residual_call = (opnum == rop.GUARD_EXCEPTION or
2600 opnum == rop.GUARD_NO_EXCEPTION or
2601 opnum == rop.GUARD_NOT_FORCED or
2602 opnum == rop.GUARD_ALWAYS_FAILS)
2603 self.capture_resumedata(resumepc, after_residual_call)
2604 # ^^^ records extra to history
2605 self.staticdata.profiler.count_ops(opnum, Counters.GUARDS)
2606 # count
2607 #self.attach_debug_info(guard_op)
2608 return guard_op
2609
2610 def capture_resumedata(self, resumepc, after_residual_call=False):
2611 virtualizable_boxes = None
2612 if (self.jitdriver_sd.virtualizable_info is not None or
2613 self.jitdriver_sd.greenfield_info is not None):
2614 virtualizable_boxes = self.virtualizable_boxes
2615 saved_pc = 0
2616 if self.framestack:
2617 frame = self.framestack[-1]
2618 saved_pc = frame.pc
2619 if resumepc >= 0:
2620 frame.pc = resumepc
2621 self.history.trace.capture_resumedata(
2622 self.framestack, virtualizable_boxes,
2623 self.virtualref_boxes,
2624 after_residual_call)
2625 if self.framestack:
2626 self.framestack[-1].pc = saved_pc
2627
2628 def create_empty_history(self, inputargs):
2629 self.history = history.History(len(inputargs), self.staticdata)
2630 self.history.set_inputargs(inputargs)
2631 self.staticdata.stats.set_history(self.history)
2632
2633 def create_history(self, max_num_inputargs):
2634 self.history = history.History(max_num_inputargs, self.staticdata)
2635
2636 def _all_constants(self, *boxes):
2637 if len(boxes) == 0:
2638 return True
2639 return isinstance(boxes[0], Const) and self._all_constants(*boxes[1:])
2640
2641 def _all_constants_varargs(self, boxes):
2642 for box in boxes:
2643 if not isinstance(box, Const):
2644 return False
2645 return True
2646
2647 @specialize.arg(1)
2648 def execute_and_record(self, opnum, descr, *argboxes):
2649 history.check_descr(descr)
2650 assert not (rop._CANRAISE_FIRST <= opnum <= rop._CANRAISE_LAST)
2651 # execute the operation
2652 profiler = self.staticdata.profiler
2653 profiler.count_ops(opnum)
2654 resvalue = executor.execute(self.cpu, self, opnum, descr, *argboxes)
2655 canfold = False
2656 if (OpHelpers.is_pure_with_descr(opnum, descr) or # pure case
2657 (rop._OVF_FIRST <= opnum <= rop._OVF_LAST and # ovf case
2658 not self.last_exc_value)):
2659 canfold = self._all_constants(*argboxes)
2660 if canfold:
2661 return executor.wrap_constant(resvalue)
2662 return self._record_helper(opnum, resvalue, descr, *argboxes)
2663
2664 @specialize.arg(1)
2665 def execute_and_record_varargs(self, opnum, argboxes, descr=None):
2666 history.check_descr(descr)
2667 # execute the operation
2668 profiler = self.staticdata.profiler
2669 profiler.count_ops(opnum)
2670 resvalue = executor.execute_varargs(self.cpu, self,
2671 opnum, argboxes, descr)
2672 # check if the operation can be constant-folded away
2673 argboxes = list(argboxes)
2674 assert not rop._ALWAYS_PURE_FIRST <= opnum <= rop._ALWAYS_PURE_LAST
2675 return self._record_helper_varargs(opnum, resvalue, descr,
2676 argboxes)
2677
2678 @specialize.argtype(2)
2679 def _record_helper_varargs(self, opnum, resvalue, descr, argboxes):
2680 # record the operation
2681 profiler = self.staticdata.profiler
2682 profiler.count_ops(opnum, Counters.RECORDED_OPS)
2683 self.heapcache.invalidate_caches_varargs(opnum, descr, argboxes)
2684 op = self.history.record(opnum, argboxes, resvalue, descr)
2685 self.attach_debug_info(op)
2686 if op.type != 'v':
2687 return op
2688
2689 @specialize.arg(1)
2690 def _record_helper(self, opnum, resvalue, descr, *argboxes):
2691 # record the operation
2692 profiler = self.staticdata.profiler
2693 profiler.count_ops(opnum, Counters.RECORDED_OPS)
2694 self.heapcache.invalidate_caches(opnum, descr, *argboxes)
2695 if len(argboxes) == 0:
2696 op = self.history.record0(
2697 opnum, resvalue, descr)
2698 elif len(argboxes) == 1:
2699 op = self.history.record1(
2700 opnum, argboxes[0], resvalue, descr)
2701 elif len(argboxes) == 2:
2702 op = self.history.record2(
2703 opnum, argboxes[0], argboxes[1], resvalue, descr)
2704 elif len(argboxes) == 3:
2705 op = self.history.record3(
2706 opnum, argboxes[0], argboxes[1], argboxes[2], resvalue, descr)
2707 else:
2708 op = self.history.record(
2709 opnum, list(argboxes), resvalue, descr)
2710 self.attach_debug_info(op)
2711 if op.type != 'v':
2712 return op
2713
2714 def execute_new_with_vtable(self, descr):
2715 resbox = self.execute_and_record(rop.NEW_WITH_VTABLE, descr)
2716 self.heapcache.new(resbox)
2717 self.heapcache.class_now_known(resbox)
2718 return resbox
2719
2720 def execute_new(self, typedescr):
2721 resbox = self.execute_and_record(rop.NEW, typedescr)
2722 self.heapcache.new(resbox)
2723 return resbox
2724
2725 def execute_new_array(self, itemsizedescr, lengthbox):
2726 resbox = self.execute_and_record(rop.NEW_ARRAY, itemsizedescr,
2727 lengthbox)
2728 self.heapcache.new_array(resbox, lengthbox)
2729 return resbox
2730
2731 def execute_new_array_clear(self, itemsizedescr, lengthbox):
2732 resbox = self.execute_and_record(rop.NEW_ARRAY_CLEAR, itemsizedescr,
2733 lengthbox)
2734 self.heapcache.new_array(resbox, lengthbox)
2735 return resbox
2736
2737 def execute_setfield_gc(self, fielddescr, box, valuebox):
2738 self.execute_and_record(rop.SETFIELD_GC, fielddescr, box, valuebox)
2739 self.heapcache.setfield(box, valuebox, fielddescr)
2740
2741 def execute_setarrayitem_gc(self, arraydescr, arraybox, indexbox, itembox):
2742 self.execute_and_record(rop.SETARRAYITEM_GC, arraydescr,
2743 arraybox, indexbox, itembox)
2744 self.heapcache.setarrayitem(arraybox, indexbox, itembox, arraydescr)
2745
2746 def execute_setinteriorfield_gc(self, descr, array, index, value):
2747 self.execute_and_record(rop.SETINTERIORFIELD_GC, descr,
2748 array, index, value)
2749 # use setarrayitem heapcache method, works for interior fields too
2750 self.heapcache.setarrayitem(array, index, value, descr)
2751
2752 def execute_raw_store(self, arraydescr, addrbox, offsetbox, valuebox):
2753 self.execute_and_record(rop.RAW_STORE, arraydescr,
2754 addrbox, offsetbox, valuebox)
2755
2756
2757 def attach_debug_info(self, op):
2758 if (not we_are_translated() and op is not None
2759 and getattr(self, 'framestack', None)):
2760 op.pc = self.framestack[-1].pc
2761 op.name = self.framestack[-1].jitcode.name
2762
2763 def execute_raised(self, exception, constant=False):
2764 if isinstance(exception, jitexc.JitException):
2765 raise exception # go through
2766 llexception = jitexc.get_llexception(self.cpu, exception)
2767 self.execute_ll_raised(llexception, constant)
2768
2769 def execute_ll_raised(self, llexception, constant=False):
2770 # Exception handling: when execute.do_call() gets an exception it
2771 # calls metainterp.execute_raised(), which puts it into
2772 # 'self.last_exc_value'. This is used shortly afterwards
2773 # to generate either GUARD_EXCEPTION or GUARD_NO_EXCEPTION, and also
2774 # to handle the following opcodes 'goto_if_exception_mismatch'.
2775 self.last_exc_value = llexception
2776 self.class_of_last_exc_is_const = constant
2777 # 'class_of_last_exc_is_const' means that the class of the value
2778 # stored in the exc_value Box can be assumed to be a Const. This
2779 # is only True after a GUARD_EXCEPTION or GUARD_CLASS.
2780
2781 def clear_exception(self):
2782 self.last_exc_value = lltype.nullptr(rclass.OBJECT)
2783
2784 def aborted_tracing(self, reason):
2785 self.staticdata.profiler.count(reason)
2786 debug_print('~~~ ABORTING TRACING %s' % Counters.counter_names[reason])
2787 jd_sd = self.jitdriver_sd
2788 if not self.current_merge_points:
2789 greenkey = None # we're in the bridge
2790 else:
2791 greenkey = self.current_merge_points[0][0][:jd_sd.num_green_args]
2792 hooks = self.staticdata.warmrunnerdesc.hooks
2793 if hooks.are_hooks_enabled():
2794 hooks.on_abort(reason,
2795 jd_sd.jitdriver, greenkey,
2796 jd_sd.warmstate.get_location_str(greenkey),
2797 self.staticdata.logger_ops._make_log_operations(
2798 self.box_names_memo),
2799 self.history.trace.unpack()[1])
2800 if self.aborted_tracing_jitdriver is not None:
2801 jd_sd = self.aborted_tracing_jitdriver
2802 greenkey = self.aborted_tracing_greenkey
2803 if hooks.are_hooks_enabled():
2804 hooks.on_trace_too_long(
2805 jd_sd.jitdriver, greenkey,
2806 jd_sd.warmstate.get_location_str(greenkey))
2807 # no ops for now
2808 self.aborted_tracing_jitdriver = None
2809 self.aborted_tracing_greenkey = None
2810 self.staticdata.stats.aborted()
2811
2812 def blackhole_if_trace_too_long(self):
2813 warmrunnerstate = self.jitdriver_sd.warmstate
2814 length = self.history.length()
2815 if (length > warmrunnerstate.trace_limit or
2816 self.history.trace_tag_overflow()):
2817 jd_sd, greenkey_of_huge_function = self.find_biggest_function()
2818 self.staticdata.stats.record_aborted(greenkey_of_huge_function)
2819 self.portal_trace_positions = None
2820 if greenkey_of_huge_function is not None:
2821 jd_sd.warmstate.disable_noninlinable_function(
2822 greenkey_of_huge_function)
2823 self.aborted_tracing_jitdriver = jd_sd
2824 self.aborted_tracing_greenkey = greenkey_of_huge_function
2825 if self.current_merge_points:
2826 jd_sd = self.jitdriver_sd
2827 greenkey = self.current_merge_points[0][0][:jd_sd.num_green_args]
2828 warmrunnerstate.JitCell.trace_next_iteration(greenkey)
2829 else:
2830 self.prepare_trace_segmenting()
2831 raise SwitchToBlackhole(Counters.ABORT_TOO_LONG)
2832
2833 def prepare_trace_segmenting(self):
2834 warmrunnerstate = self.jitdriver_sd.warmstate
2835 # huge function, not due to inlining. the next time we trace
2836 # it, force a trace to be created
2837 debug_start("jit-disableinlining")
2838 debug_print("no inlinable function found!")
2839 if self.current_merge_points:
2840 # loop
2841 jd_sd = self.jitdriver_sd
2842 greenkey = self.current_merge_points[0][0][:jd_sd.num_green_args]
2843 warmrunnerstate.JitCell.trace_next_iteration(greenkey)
2844 jd_sd.warmstate.mark_force_finish_tracing(greenkey)
2845 # bizarrely enough, this means *do trace here* ??!
2846 jd_sd.warmstate.dont_trace_here(greenkey)
2847 loc = jd_sd.warmstate.get_location_str(greenkey)
2848 debug_print("force tracing loop next time", loc)
2849 if not isinstance(self.resumekey, compile.ResumeFromInterpDescr):
2850 # we're tracing a bridge. there are no bits left in
2851 # ResumeGuardDescr to store that we should force a bridge
2852 # creation the next time. therefore, set a flag on the loop
2853 # token that will then apply to all bridges from that token
2854 # (bit crude, but creating a segmented bridge is generally
2855 # quite safe)
2856 loop_token = self.resumekey_original_loop_token
2857 loop_token.retraced_count |= loop_token.FORCE_BRIDGE_SEGMENTING
2858 debug_print("enable bridge segmenting of base loop")
2859 debug_stop("jit-disableinlining")
2860
2861 def _interpret(self):
2862 # Execute the frames forward until we raise a DoneWithThisFrame,
2863 # a ExitFrameWithException, or a ContinueRunningNormally exception.
2864 self.staticdata.stats.entered()
2865 while True:
2866 self.framestack[-1].run_one_step()
2867 self.blackhole_if_trace_too_long()
2868 if not we_are_translated():
2869 self.check_recursion_invariant()
2870
2871 def interpret(self):
2872 if we_are_translated():
2873 self._interpret()
2874 else:
2875 try:
2876 self._interpret()
2877 except:
2878 import sys
2879 if sys.exc_info()[0] is not None:
2880 self.staticdata.log(sys.exc_info()[0].__name__)
2881 raise
2882
2883 @specialize.arg(1)
2884 def compile_and_run_once(self, jitdriver_sd, *args):
2885 # NB. we pass explicity 'jitdriver_sd' around here, even though it
2886 # is also available as 'self.jitdriver_sd', because we need to
2887 # specialize this function and a few other ones for the '*args'.
2888 debug_start('jit-tracing')
2889 self.staticdata._setup_once()
2890 self.staticdata.profiler.start_tracing()
2891 assert jitdriver_sd is self.jitdriver_sd
2892 self.staticdata.try_to_free_some_loops()
2893 try:
2894 original_boxes = self.initialize_original_boxes(jitdriver_sd, *args)
2895 return self._compile_and_run_once(original_boxes)
2896 finally:
2897 self.staticdata.profiler.end_tracing()
2898 debug_stop('jit-tracing')
2899
2900 def _compile_and_run_once(self, original_boxes):
2901 self.initialize_state_from_start(original_boxes)
2902 self.current_merge_points = [(original_boxes, (0, 0, 0, 0, 0))]
2903 num_green_args = self.jitdriver_sd.num_green_args
2904 original_greenkey = original_boxes[:num_green_args]
2905 self.resumekey = compile.ResumeFromInterpDescr(original_greenkey)
2906 self.seen_loop_header_for_jdindex = -1
2907 try:
2908 self.create_empty_history(original_boxes[num_green_args:])
2909 self.interpret()
2910 except SwitchToBlackhole as stb:
2911 self.run_blackhole_interp_to_cancel_tracing(stb)
2912 assert False, "should always raise"
2913
2914 def handle_guard_failure(self, resumedescr, deadframe):
2915 debug_start('jit-tracing')
2916 self.staticdata.profiler.start_tracing()
2917 key = resumedescr.get_resumestorage()
2918 assert isinstance(key, compile.ResumeGuardDescr)
2919 # store the resumekey.wref_original_loop_token() on 'self' to make
2920 # sure that it stays alive as long as this MetaInterp
2921 self.resumekey_original_loop_token = resumedescr.rd_loop_token.loop_token_wref()
2922 if self.resumekey_original_loop_token is None:
2923 raise compile.giveup() # should be rare
2924 self.staticdata.try_to_free_some_loops()
2925 self.create_history(resume.get_max_num_inputargs(key))
2926 try:
2927 excdata = self._prepare_exception_resumption(deadframe, resumedescr)
2928 inputargs = self.initialize_state_from_guard_failure(key, deadframe)
2929 return self._handle_guard_failure(resumedescr, key, inputargs, deadframe, excdata)
2930 except SwitchToBlackhole as stb:
2931 self.run_blackhole_interp_to_cancel_tracing(stb)
2932 finally:
2933 self.resumekey_original_loop_token = None
2934 self.staticdata.profiler.end_tracing()
2935 debug_stop('jit-tracing')
2936
2937 def _handle_guard_failure(self, resumedescr, key, inputargs, deadframe, excdata):
2938 self.current_merge_points = []
2939 self.resumekey = resumedescr
2940 self.seen_loop_header_for_jdindex = -1
2941 if isinstance(key, compile.ResumeAtPositionDescr):
2942 self.seen_loop_header_for_jdindex = self.jitdriver_sd.index
2943 self.prepare_resume_from_failure(deadframe, inputargs, resumedescr, excdata)
2944 if self.resumekey_original_loop_token is None: # very rare case
2945 raise SwitchToBlackhole(Counters.ABORT_BRIDGE)
2946 self.interpret()
2947 assert False, "should always raise"
2948
2949 def run_blackhole_interp_to_cancel_tracing(self, stb):
2950 # We got a SwitchToBlackhole exception. Convert the framestack into
2951 # a stack of blackhole interpreters filled with the same values, and
2952 # run it.
2953 from rpython.jit.metainterp.blackhole import convert_and_run_from_pyjitpl
2954 self.aborted_tracing(stb.reason)
2955 convert_and_run_from_pyjitpl(self, stb.raising_exception)
2956 assert False # ^^^ must raise
2957
2958 def remove_consts_and_duplicates(self, boxes, endindex, duplicates):
2959 for i in range(endindex):
2960 box = boxes[i]
2961 if isinstance(box, Const) or box in duplicates:
2962 boxes[i] = self.history.record_same_as(box)
2963 else:
2964 duplicates[box] = None
2965
2966 def cancelled_too_many_times(self):
2967 if self.staticdata.warmrunnerdesc:
2968 memmgr = self.staticdata.warmrunnerdesc.memory_manager
2969 if memmgr:
2970 if self.cancel_count > memmgr.max_unroll_loops:
2971 return True
2972 return False
2973
2974 def reached_loop_header(self, greenboxes, redboxes):
2975 self.heapcache.reset() #reset_virtuals=False)
2976 #self.heapcache.reset_keep_likely_virtuals()
2977
2978 duplicates = {}
2979 self.remove_consts_and_duplicates(redboxes, len(redboxes),
2980 duplicates)
2981 live_arg_boxes = greenboxes + redboxes
2982 if self.jitdriver_sd.virtualizable_info is not None:
2983 # we use pop() to remove the last item, which is the virtualizable
2984 # itself
2985 self.remove_consts_and_duplicates(self.virtualizable_boxes,
2986 len(self.virtualizable_boxes)-1,
2987 duplicates)
2988 live_arg_boxes += self.virtualizable_boxes
2989 live_arg_boxes.pop()
2990
2991 # generate a dummy guard just before the JUMP so that unroll can use it
2992 # when it's creating artificial guards.
2993 self.generate_guard(rop.GUARD_FUTURE_CONDITION)
2994
2995 assert len(self.virtualref_boxes) == 0, "missing virtual_ref_finish()?"
2996 # Called whenever we reach the 'loop_header' hint.
2997 # First, attempt to make a bridge:
2998 # - if self.resumekey is a ResumeGuardDescr, it starts from a guard
2999 # that failed;
3000 # - if self.resumekey is a ResumeFromInterpDescr, it starts directly
3001 # from the interpreter.
3002 num_green_args = self.jitdriver_sd.num_green_args
3003 if not self.partial_trace:
3004 # FIXME: Support a retrace to be a bridge as well as a loop
3005 ptoken = self.get_procedure_token(greenboxes)
3006 if has_compiled_targets(ptoken):
3007 self.compile_trace(live_arg_boxes, ptoken)
3008
3009 # raises in case it works -- which is the common case, hopefully,
3010 # at least for bridges starting from a guard.
3011
3012 # Search in current_merge_points for original_boxes with compatible
3013 # green keys, representing the beginning of the same loop as the one
3014 # we end now.
3015
3016 can_use_unroll = (self.staticdata.cpu.supports_guard_gc_type and
3017 'unroll' in self.jitdriver_sd.warmstate.enable_opts)
3018 for j in range(len(self.current_merge_points)-1, -1, -1):
3019 original_boxes, start = self.current_merge_points[j]
3020 assert len(original_boxes) == len(live_arg_boxes)
3021 if not same_greenkey(original_boxes, live_arg_boxes, num_green_args):
3022 continue
3023 if self.partial_trace:
3024 if start != self.retracing_from:
3025 raise SwitchToBlackhole(Counters.ABORT_BAD_LOOP) # For now
3026 # Found! Compile it as a loop.
3027 # raises in case it works -- which is the common case
3028 self.history.trace.tracing_done()
3029 if self.partial_trace:
3030 target_token = self.compile_retrace(
3031 original_boxes, live_arg_boxes, start)
3032 self.raise_if_successful(live_arg_boxes, target_token)
3033 # creation of the loop was cancelled!
3034 self.cancel_count += 1
3035 if self.cancelled_too_many_times():
3036 self.staticdata.log('cancelled too many times!')
3037 raise SwitchToBlackhole(Counters.ABORT_BAD_LOOP)
3038 else:
3039 target_token = self.compile_loop(
3040 original_boxes, live_arg_boxes, start,
3041 use_unroll=can_use_unroll)
3042 self.raise_if_successful(live_arg_boxes, target_token)
3043 # creation of the loop was cancelled!
3044 self.cancel_count += 1
3045 if self.cancelled_too_many_times():
3046 if can_use_unroll:
3047 # try one last time without unrolling
3048 target_token = self.compile_loop(
3049 original_boxes, live_arg_boxes, start,
3050 use_unroll=False)
3051 self.raise_if_successful(live_arg_boxes, target_token)
3052 #
3053 self.staticdata.log('cancelled too many times!')
3054 raise SwitchToBlackhole(Counters.ABORT_BAD_LOOP)
3055 self.exported_state = None
3056 self.staticdata.log('cancelled, tracing more...')
3057
3058 # Otherwise, no loop found so far, so continue tracing.
3059 start = self.history.get_trace_position()
3060 self.current_merge_points.append((live_arg_boxes, start))
3061
3062 def _unpack_boxes(self, boxes, start, stop):
3063 ints = []; refs = []; floats = []
3064 for i in range(start, stop):
3065 box = boxes[i]
3066 if box.type == history.INT: ints.append(box.getint())
3067 elif box.type == history.REF: refs.append(box.getref_base())
3068 elif box.type == history.FLOAT:floats.append(box.getfloatstorage())
3069 else: assert 0
3070 return ints[:], refs[:], floats[:]
3071
3072 def raise_continue_running_normally(self, live_arg_boxes, loop_token):
3073 self.history.inputargs = None
3074 self.history.operations = None
3075 # For simplicity, we just raise ContinueRunningNormally here and
3076 # ignore the loop_token passed in. It means that we go back to
3077 # interpreted mode, but it should come back very quickly to the
3078 # JIT, find probably the same 'loop_token', and execute it.
3079 if we_are_translated():
3080 num_green_args = self.jitdriver_sd.num_green_args
3081 gi, gr, gf = self._unpack_boxes(live_arg_boxes, 0, num_green_args)
3082 ri, rr, rf = self._unpack_boxes(live_arg_boxes, num_green_args,
3083 len(live_arg_boxes))
3084 CRN = jitexc.ContinueRunningNormally
3085 raise CRN(gi, gr, gf, ri, rr, rf)
3086 else:
3087 # However, in order to keep the existing tests working
3088 # (which are based on the assumption that 'loop_token' is
3089 # directly used here), a bit of custom non-translatable code...
3090 self._nontranslated_run_directly(live_arg_boxes, loop_token)
3091 assert 0, "unreachable"
3092
3093 def _nontranslated_run_directly(self, live_arg_boxes, loop_token):
3094 "NOT_RPYTHON"
3095 args = []
3096 num_green_args = self.jitdriver_sd.num_green_args
3097 num_red_args = self.jitdriver_sd.num_red_args
3098 for box in live_arg_boxes[num_green_args:num_green_args+num_red_args]:
3099 if box.type == history.INT:
3100 args.append(box.getint())
3101 elif box.type == history.REF:
3102 args.append(box.getref_base())
3103 elif box.type == history.FLOAT:
3104 args.append(box.getfloatstorage())
3105 else:
3106 assert 0
3107 res = self.jitdriver_sd.warmstate.execute_assembler(loop_token, *args)
3108 kind = history.getkind(lltype.typeOf(res))
3109 if kind == 'void':
3110 raise jitexc.DoneWithThisFrameVoid()
3111 if kind == 'int':
3112 raise jitexc.DoneWithThisFrameInt(res)
3113 if kind == 'ref':
3114 raise jitexc.DoneWithThisFrameRef(res)
3115 if kind == 'float':
3116 raise jitexc.DoneWithThisFrameFloat(res)
3117 raise AssertionError(kind)
3118
3119 def raise_if_successful(self, live_arg_boxes, target_token):
3120 if target_token is not None: # raise if it *worked* correctly
3121 assert isinstance(target_token, TargetToken)
3122 jitcell_token = target_token.targeting_jitcell_token
3123 self.raise_continue_running_normally(live_arg_boxes, jitcell_token)
3124
3125 def _prepare_exception_resumption(self, deadframe, resumedescr):
3126 exception = self.cpu.grab_exc_value(deadframe)
3127 if (isinstance(resumedescr, compile.ResumeGuardExcDescr) or
3128 isinstance(resumedescr, compile.ResumeGuardCopiedExcDescr)):
3129 # Add a GUARD_EXCEPTION or GUARD_NO_EXCEPTION at the start
3130 # of the bridge---except it is not really the start, because
3131 # the history aleady contains operations from resume.py.
3132 # The optimizer should remove these operations. However,
3133 # 'test_guard_no_exception_incorrectly_removed_from_bridge'
3134 # shows a corner case in which just putting GUARD_NO_EXCEPTION
3135 # here is a bad idea: the optimizer might remove it too.
3136 # So we put a SAVE_EXCEPTION at the start, and a RESTORE_EXCEPTION
3137 # just before the guard (done in prepare_resume_from_failure).
3138 # rewrite.py will remove the two if they end up consecutive.
3139
3140 # XXX too much jumps between older and newer models; clean up
3141 # by killing SAVE_EXC_CLASS, RESTORE_EXCEPTION and GUARD_EXCEPTION
3142
3143 exception_obj = lltype.cast_opaque_ptr(rclass.OBJECTPTR, exception)
3144 if exception_obj:
3145 exc_class = ptr2int(exception_obj.typeptr)
3146 else:
3147 exc_class = 0
3148 assert self.history.trace._pos == self.history.trace._start
3149 op1 = self.history.record0(rop.SAVE_EXC_CLASS, exc_class)
3150 op2 = self.history.record0(rop.SAVE_EXCEPTION, exception)
3151 return exception, op1, op2
3152 else:
3153 assert not exception
3154 return exception, None, None
3155
3156 def prepare_resume_from_failure(self, deadframe, inputargs, resumedescr, excdata):
3157 if (isinstance(resumedescr, compile.ResumeGuardExcDescr) or
3158 isinstance(resumedescr, compile.ResumeGuardCopiedExcDescr)):
3159 exception, op1, op2 = excdata
3160 exception_obj = lltype.cast_opaque_ptr(rclass.OBJECTPTR, exception)
3161
3162 self.history.record2(rop.RESTORE_EXCEPTION, op1, op2, None)
3163 self.history.set_inputargs(inputargs)
3164 if exception_obj:
3165 self.execute_ll_raised(exception_obj)
3166 else:
3167 self.clear_exception()
3168 try:
3169 self.handle_possible_exception()
3170 except ChangeFrame:
3171 pass
3172 else:
3173 self.history.set_inputargs(inputargs)
3174
3175 def get_procedure_token(self, greenkey):
3176 JitCell = self.jitdriver_sd.warmstate.JitCell
3177 cell = JitCell.get_jit_cell_at_key(greenkey)
3178 if cell is None:
3179 return None
3180 return cell.get_procedure_token()
3181
3182 def compile_loop(self, original_boxes, live_arg_boxes, start, use_unroll):
3183 num_green_args = self.jitdriver_sd.num_green_args
3184 greenkey = original_boxes[:num_green_args]
3185 ptoken = self.get_procedure_token(greenkey)
3186 if has_compiled_targets(ptoken):
3187 # XXX this path not tested, but shown to occur on pypy-c :-(
3188 self.staticdata.log('cancelled: we already have a token now')
3189 raise SwitchToBlackhole(Counters.ABORT_BAD_LOOP)
3190 target_token = compile.compile_loop(
3191 self, greenkey, start, original_boxes[num_green_args:],
3192 live_arg_boxes[num_green_args:], use_unroll=use_unroll)
3193 if target_token is not None:
3194 assert isinstance(target_token, TargetToken)
3195 self.jitdriver_sd.warmstate.attach_procedure_to_interp(
3196 greenkey, target_token.targeting_jitcell_token)
3197 self.staticdata.stats.add_jitcell_token(
3198 target_token.targeting_jitcell_token)
3199 return target_token
3200
3201 def compile_retrace(self, original_boxes, live_arg_boxes, start):
3202 num_green_args = self.jitdriver_sd.num_green_args
3203 greenkey = original_boxes[:num_green_args]
3204 return compile.compile_retrace(
3205 self, greenkey, start, original_boxes[num_green_args:],
3206 live_arg_boxes[num_green_args:], self.partial_trace,
3207 self.resumekey, self.exported_state)
3208
3209 def compile_trace(self, live_arg_boxes, ptoken):
3210 num_green_args = self.jitdriver_sd.num_green_args
3211 cut_at = self.history.get_trace_position()
3212 self.potential_retrace_position = cut_at
3213 self.history.record(rop.JUMP, live_arg_boxes[num_green_args:], None,
3214 descr=ptoken)
3215 try:
3216 target_token = compile.compile_trace(self, self.resumekey,
3217 live_arg_boxes[num_green_args:], ends_with_jump=True)
3218 finally:
3219 self.history.cut(cut_at) # pop the jump
3220 self.raise_if_successful(live_arg_boxes, target_token)
3221
3222 def compile_done_with_this_frame(self, exitbox):
3223 self.store_token_in_vable()
3224 sd = self.staticdata
3225 result_type = self.jitdriver_sd.result_type
3226 if result_type == history.VOID:
3227 assert exitbox is None
3228 exits = []
3229 token = sd.done_with_this_frame_descr_void
3230 elif result_type == history.INT:
3231 exits = [exitbox]
3232 token = sd.done_with_this_frame_descr_int
3233 elif result_type == history.REF:
3234 exits = [exitbox]
3235 token = sd.done_with_this_frame_descr_ref
3236 elif result_type == history.FLOAT:
3237 exits = [exitbox]
3238 token = sd.done_with_this_frame_descr_float
3239 else:
3240 assert False
3241 self.history.record(rop.FINISH, exits, None, descr=token)
3242 target_token = compile.compile_trace(self, self.resumekey, exits)
3243 if target_token is not token:
3244 compile.giveup()
3245
3246 def store_token_in_vable(self):
3247 vinfo = self.jitdriver_sd.virtualizable_info
3248 if vinfo is None:
3249 return
3250 vbox = self.virtualizable_boxes[-1]
3251 if vbox is self.forced_virtualizable:
3252 return # we already forced it by hand
3253 # in case the force_token has not been recorded, record it here
3254 # to make sure we know the virtualizable can be broken. However, the
3255 # contents of the virtualizable should be generally correct
3256 force_token = self.history.record0(rop.FORCE_TOKEN,
3257 lltype.nullptr(llmemory.GCREF.TO))
3258 self.history.record2(rop.SETFIELD_GC, vbox, force_token,
3259 None, descr=vinfo.vable_token_descr)
3260 self.generate_guard(rop.GUARD_NOT_FORCED_2)
3261
3262 def compile_exit_frame_with_exception(self, valuebox):
3263 self.store_token_in_vable()
3264 sd = self.staticdata
3265 token = sd.exit_frame_with_exception_descr_ref
3266 self.history.record1(rop.FINISH, valuebox, None, descr=token)
3267 target_token = compile.compile_trace(self, self.resumekey, [valuebox])
3268 if target_token is not token:
3269 compile.giveup()
3270
3271 @specialize.arg(1)
3272 def initialize_original_boxes(self, jitdriver_sd, *args):
3273 original_boxes = [None] * len(args)
3274 self._fill_original_boxes(jitdriver_sd, original_boxes, 0,
3275 *args)
3276 return original_boxes
3277
3278 @specialize.arg(1)
3279 @always_inline
3280 def _fill_original_boxes(self, jitdriver_sd, original_boxes,
3281 position, *args):
3282 if args:
3283 from rpython.jit.metainterp.warmstate import wrap
3284 box = wrap(self.cpu, args[0],
3285 position - jitdriver_sd.num_green_args)
3286 original_boxes[position] = box
3287 self._fill_original_boxes(jitdriver_sd, original_boxes,
3288 position + 1, *args[1:])
3289
3290 def initialize_state_from_start(self, original_boxes):
3291 # ----- make a new frame -----
3292 self.portal_call_depth = -1 # always one portal around
3293 self.framestack = []
3294 f = self.newframe(self.jitdriver_sd.mainjitcode)
3295 f.setup_call(original_boxes)
3296 assert self.portal_call_depth == 0
3297 self.virtualref_boxes = []
3298 self.initialize_withgreenfields(original_boxes)
3299 self.initialize_virtualizable(original_boxes)
3300
3301 def initialize_state_from_guard_failure(self, resumedescr, deadframe):
3302 # guard failure: rebuild a complete MIFrame stack
3303 # This is stack-critical code: it must not be interrupted by StackOverflow,
3304 # otherwise the jit_virtual_refs are left in a dangling state.
3305 rstack._stack_criticalcode_start()
3306 try:
3307 self.portal_call_depth = -1 # always one portal around
3308 inputargs_and_holes = self.rebuild_state_after_failure(resumedescr,
3309 deadframe)
3310 return [box for box in inputargs_and_holes if box]
3311 finally:
3312 rstack._stack_criticalcode_stop()
3313
3314 def initialize_virtualizable(self, original_boxes):
3315 vinfo = self.jitdriver_sd.virtualizable_info
3316 if vinfo is not None:
3317 index = (self.jitdriver_sd.num_green_args +
3318 self.jitdriver_sd.index_of_virtualizable)
3319 virtualizable_box = original_boxes[index]
3320 virtualizable = vinfo.unwrap_virtualizable_box(virtualizable_box)
3321 # First force the virtualizable if needed!
3322 vinfo.clear_vable_token(virtualizable)
3323 # The field 'virtualizable_boxes' is not even present
3324 # if 'virtualizable_info' is None. Check for that first.
3325 startindex = len(original_boxes) - self.jitdriver_sd.num_green_args
3326 self.virtualizable_boxes = vinfo.read_boxes(self.cpu,
3327 virtualizable,
3328 startindex)
3329 original_boxes += self.virtualizable_boxes
3330 self.virtualizable_boxes.append(virtualizable_box)
3331 self.check_synchronized_virtualizable()
3332
3333 def initialize_withgreenfields(self, original_boxes):
3334 ginfo = self.jitdriver_sd.greenfield_info
3335 if ginfo is not None:
3336 assert self.jitdriver_sd.virtualizable_info is None
3337 index = (self.jitdriver_sd.num_green_args +
3338 ginfo.red_index)
3339 self.virtualizable_boxes = [original_boxes[index]]
3340
3341 def vable_and_vrefs_before_residual_call(self):
3342 vrefinfo = self.staticdata.virtualref_info
3343 for i in range(1, len(self.virtualref_boxes), 2):
3344 vrefbox = self.virtualref_boxes[i]
3345 vref = vrefbox.getref_base()
3346 vrefinfo.tracing_before_residual_call(vref)
3347 # the FORCE_TOKEN is already set at runtime in each vref when
3348 # it is created, by optimizeopt.py.
3349 #
3350 vinfo = self.jitdriver_sd.virtualizable_info
3351 if vinfo is not None:
3352 virtualizable_box = self.virtualizable_boxes[-1]
3353 virtualizable = vinfo.unwrap_virtualizable_box(virtualizable_box)
3354 vinfo.tracing_before_residual_call(virtualizable)
3355 #
3356 force_token = self.history.record0(rop.FORCE_TOKEN,
3357 lltype.nullptr(llmemory.GCREF.TO))
3358 self.history.record2(rop.SETFIELD_GC, virtualizable_box, force_token,
3359 None, descr=vinfo.vable_token_descr)
3360
3361 def vrefs_after_residual_call(self):
3362 vrefinfo = self.staticdata.virtualref_info
3363 for i in range(0, len(self.virtualref_boxes), 2):
3364 vrefbox = self.virtualref_boxes[i+1]
3365 vref = vrefbox.getref_base()
3366 if vrefinfo.tracing_after_residual_call(vref):
3367 # this vref was really a virtual_ref, but it escaped
3368 # during this CALL_MAY_FORCE. Mark this fact by
3369 # generating a VIRTUAL_REF_FINISH on it and replacing
3370 # it by ConstPtr(NULL).
3371 self.stop_tracking_virtualref(i)
3372
3373 def vable_after_residual_call(self, funcbox):
3374 vinfo = self.jitdriver_sd.virtualizable_info
3375 if vinfo is not None:
3376 virtualizable_box = self.virtualizable_boxes[-1]
3377 virtualizable = vinfo.unwrap_virtualizable_box(virtualizable_box)
3378 if vinfo.tracing_after_residual_call(virtualizable):
3379 # the virtualizable escaped during CALL_MAY_FORCE.
3380 self.load_fields_from_virtualizable()
3381 target_name = self.staticdata.get_name_from_address(funcbox.getaddr())
3382 if target_name:
3383 target_name = "ConstClass(%s)" % target_name
3384 else:
3385 target_name = str(funcbox.getaddr())
3386 debug_print('vable escaped during a call in %s to %s' % (
3387 self.framestack[-1].jitcode.name, target_name
3388 ))
3389 raise SwitchToBlackhole(Counters.ABORT_ESCAPE,
3390 raising_exception=True)
3391 # ^^^ we set 'raising_exception' to True because we must still
3392 # have the eventual exception raised (this is normally done
3393 # after the call to vable_after_residual_call()).
3394
3395 def stop_tracking_virtualref(self, i):
3396 virtualbox = self.virtualref_boxes[i]
3397 vrefbox = self.virtualref_boxes[i+1]
3398 # record VIRTUAL_REF_FINISH here, which is before the actual
3399 # CALL_xxx is recorded
3400 self.history.record2(rop.VIRTUAL_REF_FINISH, vrefbox, virtualbox, None)
3401 # mark this situation by replacing the vrefbox with ConstPtr(NULL)
3402 self.virtualref_boxes[i+1] = CONST_NULL
3403
3404 def handle_possible_exception(self):
3405 if self.last_exc_value:
3406 exception_box = ConstInt(ptr2int(self.last_exc_value.typeptr))
3407 op = self.generate_guard(rop.GUARD_EXCEPTION,
3408 None, exception_box)
3409 val = lltype.cast_opaque_ptr(llmemory.GCREF, self.last_exc_value)
3410 if self.class_of_last_exc_is_const:
3411 self.last_exc_box = ConstPtr(val)
3412 else:
3413 self.last_exc_box = op
3414 op.setref_base(val)
3415 assert op is not None
3416 self.class_of_last_exc_is_const = True
3417 self.finishframe_exception()
3418 else:
3419 self.generate_guard(rop.GUARD_NO_EXCEPTION)
3420
3421 def assert_no_exception(self):
3422 assert not self.last_exc_value
3423
3424 def rebuild_state_after_failure(self, resumedescr, deadframe):
3425 vinfo = self.jitdriver_sd.virtualizable_info
3426 ginfo = self.jitdriver_sd.greenfield_info
3427 self.framestack = []
3428 boxlists = resume.rebuild_from_resumedata(self, resumedescr, deadframe,
3429 vinfo, ginfo)
3430 inputargs_and_holes, virtualizable_boxes, virtualref_boxes = boxlists
3431 #
3432 # virtual refs: make the vrefs point to the freshly allocated virtuals
3433 self.virtualref_boxes = virtualref_boxes
3434 vrefinfo = self.staticdata.virtualref_info
3435 for i in range(0, len(virtualref_boxes), 2):
3436 virtualbox = virtualref_boxes[i]
3437 vrefbox = virtualref_boxes[i+1]
3438 vrefinfo.continue_tracing(vrefbox.getref_base(),
3439 virtualbox.getref_base())
3440 #
3441 # virtualizable: synchronize the real virtualizable and the local
3442 # boxes, in whichever direction is appropriate
3443 if vinfo is not None:
3444 self.virtualizable_boxes = virtualizable_boxes
3445 # just jumped away from assembler (case 4 in the comment in
3446 # virtualizable.py) into tracing (case 2); if we get the
3447 # virtualizable from somewhere strange it might not be forced,
3448 # do it
3449 virtualizable_box = self.virtualizable_boxes[-1]
3450 virtualizable = vinfo.unwrap_virtualizable_box(virtualizable_box)
3451 if vinfo.is_token_nonnull_gcref(virtualizable):
3452 vinfo.reset_token_gcref(virtualizable)
3453 # fill the virtualizable with the local boxes
3454 self.synchronize_virtualizable()
3455 #
3456 elif self.jitdriver_sd.greenfield_info:
3457 self.virtualizable_boxes = virtualizable_boxes
3458 else:
3459 assert not virtualizable_boxes
3460 #
3461 return inputargs_and_holes
3462
3463 def check_synchronized_virtualizable(self):
3464 if not we_are_translated():
3465 vinfo = self.jitdriver_sd.virtualizable_info
3466 virtualizable_box = self.virtualizable_boxes[-1]
3467 virtualizable = vinfo.unwrap_virtualizable_box(virtualizable_box)
3468 vinfo.check_boxes(virtualizable, self.virtualizable_boxes)
3469
3470 def synchronize_virtualizable(self):
3471 vinfo = self.jitdriver_sd.virtualizable_info
3472 virtualizable_box = self.virtualizable_boxes[-1]
3473 virtualizable = vinfo.unwrap_virtualizable_box(virtualizable_box)
3474 vinfo.write_boxes(virtualizable, self.virtualizable_boxes)
3475
3476 def load_fields_from_virtualizable(self):
3477 # Force a reload of the virtualizable fields into the local
3478 # boxes (called only in escaping cases). Only call this function
3479 # just before SwitchToBlackhole.
3480 vinfo = self.jitdriver_sd.virtualizable_info
3481 if vinfo is not None:
3482 virtualizable_box = self.virtualizable_boxes[-1]
3483 virtualizable = vinfo.unwrap_virtualizable_box(virtualizable_box)
3484 self.virtualizable_boxes = vinfo.read_boxes(self.cpu,
3485 virtualizable,
3486 0)
3487 self.virtualizable_boxes.append(virtualizable_box)
3488
3489 def gen_store_back_in_vable(self, box):
3490 vinfo = self.jitdriver_sd.virtualizable_info
3491 if vinfo is not None:
3492 # xxx only write back the fields really modified
3493 vbox = self.virtualizable_boxes[-1]
3494 if vbox is not box:
3495 # ignore the hint on non-standard virtualizable
3496 # specifically, ignore it on a virtual
3497 return
3498 if self.forced_virtualizable is not None:
3499 # this can happen only in strange cases, but we don't care
3500 # it was already forced
3501 return
3502 self.forced_virtualizable = vbox
3503 for i in range(vinfo.num_static_extra_boxes):
3504 fieldbox = self.virtualizable_boxes[i]
3505 descr = vinfo.static_field_descrs[i]
3506 self.execute_and_record(rop.SETFIELD_GC, descr, vbox, fieldbox)
3507 i = vinfo.num_static_extra_boxes
3508 virtualizable = vinfo.unwrap_virtualizable_box(vbox)
3509 for k in range(vinfo.num_arrays):
3510 descr = vinfo.array_field_descrs[k]
3511 abox = self.execute_and_record(rop.GETFIELD_GC_R, descr, vbox)
3512 descr = vinfo.array_descrs[k]
3513 for j in range(vinfo.get_array_length(virtualizable, k)):
3514 itembox = self.virtualizable_boxes[i]
3515 i += 1
3516 self.execute_and_record(rop.SETARRAYITEM_GC, descr,
3517 abox, ConstInt(j), itembox)
3518 assert i + 1 == len(self.virtualizable_boxes)
3519 # we're during tracing, so we should not execute it
3520 self.history.record2(rop.SETFIELD_GC, vbox, CONST_NULL,
3521 None, descr=vinfo.vable_token_descr)
3522
3523 def replace_box(self, oldbox, newbox):
3524 for frame in self.framestack:
3525 frame.replace_active_box_in_frame(oldbox, newbox)
3526 boxes = self.virtualref_boxes
3527 for i in range(len(boxes)):
3528 if boxes[i] is oldbox:
3529 boxes[i] = newbox
3530 if (self.jitdriver_sd.virtualizable_info is not None or
3531 self.jitdriver_sd.greenfield_info is not None):
3532 boxes = self.virtualizable_boxes
3533 for i in range(len(boxes)):
3534 if boxes[i] is oldbox:
3535 boxes[i] = newbox
3536 self.heapcache.replace_box(oldbox, newbox)
3537
3538 def find_biggest_function(self):
3539 start_stack = []
3540 max_size = 0
3541 max_key = None
3542 max_jdsd = None
3543 r = ''
3544 debug_start("jit-abort-longest-function")
3545 for elem in self.portal_trace_positions:
3546 jitdriver_sd, key, pos = elem
3547 if key is not None:
3548 start_stack.append(elem)
3549 else:
3550 jitdriver_sd, greenkey, startpos = start_stack.pop()
3551 warmstate = jitdriver_sd.warmstate
3552 size = pos[0] - startpos[0]
3553 if size > max_size:
3554 if warmstate is not None:
3555 r = warmstate.get_location_str(greenkey)
3556 debug_print("found new longest: %s %d" % (r, size))
3557 max_size = size
3558 max_jdsd = jitdriver_sd
3559 max_key = greenkey
3560 if start_stack:
3561 jitdriver_sd, key, pos = start_stack[0]
3562 warmstate = jitdriver_sd.warmstate
3563 size = self.history.get_trace_position()[0] - pos[0]
3564 if size > max_size:
3565 if warmstate is not None:
3566 r = warmstate.get_location_str(key)
3567 debug_print("found new longest: %s %d" % (r, size))
3568 max_size = size
3569 max_jdsd = jitdriver_sd
3570 max_key = key
3571 if self.portal_trace_positions: # tests
3572 self.staticdata.logger_ops.log_abort_loop(self.history.trace,
3573 self.box_names_memo)
3574 debug_stop("jit-abort-longest-function")
3575 return max_jdsd, max_key
3576
3577 def record_result_of_call_pure(self, op, argboxes, descr, patch_pos, opnum):
3578 """ Patch a CALL into a CALL_PURE.
3579 """
3580 resbox_as_const = executor.constant_from_op(op)
3581 is_cond_value = OpHelpers.is_cond_call_value(opnum)
3582 if is_cond_value:
3583 normargboxes = argboxes[1:] # ingore the 'value' arg
3584 else:
3585 normargboxes = argboxes
3586 for argbox in normargboxes:
3587 if not isinstance(argbox, Const):
3588 break
3589 else:
3590 # all-constants: remove the CALL operation now and propagate a
3591 # constant result
3592 self.history.cut(patch_pos)
3593 return resbox_as_const
3594 # not all constants (so far): turn CALL into CALL_PURE, which might
3595 # be either removed later by optimizeopt or turned back into CALL.
3596 arg_consts = [executor.constant_from_op(a) for a in normargboxes]
3597 self.call_pure_results[arg_consts] = resbox_as_const
3598 if is_cond_value:
3599 return op # but COND_CALL_VALUE remains
3600 opnum = OpHelpers.call_pure_for_descr(descr)
3601 self.history.cut(patch_pos)
3602 newop = self.history.record_nospec(opnum, argboxes, resbox_as_const, descr)
3603 return newop
3604
3605 def direct_call_may_force(self, argboxes, valueconst, calldescr):
3606 """ Common case: record in the history a CALL_MAY_FORCE with
3607 'c_result' as the result of that call. (The actual call has
3608 already been done.)
3609 """
3610 opnum = rop.call_may_force_for_descr(calldescr)
3611 return self.history.record_nospec(opnum, argboxes, valueconst, calldescr)
3612
3613 def direct_assembler_call(self, arglist, valueconst, calldescr, targetjitdriver_sd):
3614 """ Record in the history a direct call to assembler for portal
3615 entry point.
3616 """
3617 num_green_args = targetjitdriver_sd.num_green_args
3618 greenargs = arglist[1:num_green_args+1]
3619 args = arglist[num_green_args+1:]
3620 assert len(args) == targetjitdriver_sd.num_red_args
3621 warmrunnerstate = targetjitdriver_sd.warmstate
3622 token = warmrunnerstate.get_assembler_token(greenargs)
3623 opnum = OpHelpers.call_assembler_for_descr(calldescr)
3624 op = self.history.record_nospec(opnum, args, valueconst, descr=token)
3625 #
3626 # To fix an obscure issue, make sure the vable stays alive
3627 # longer than the CALL_ASSEMBLER operation. We do it by
3628 # inserting explicitly an extra KEEPALIVE operation.
3629 jd = token.outermost_jitdriver_sd
3630 if jd.index_of_virtualizable >= 0:
3631 return args[jd.index_of_virtualizable], op
3632 else:
3633 return None, op
3634
3635 def direct_libffi_call(self, argboxes, valueconst, orig_calldescr):
3636 """Generate a direct call to C code using jit_ffi_call()
3637 """
3638 # an 'assert' that constant-folds away the rest of this function
3639 # if the codewriter didn't produce any OS_LIBFFI_CALL at all.
3640 assert self.staticdata.has_libffi_call
3641 #
3642 from rpython.rtyper.lltypesystem import llmemory
3643 from rpython.rlib.jit_libffi import CIF_DESCRIPTION_P
3644 from rpython.jit.backend.llsupport.ffisupport import get_arg_descr
3645 #
3646 box_cif_description = argboxes[1]
3647 if not isinstance(box_cif_description, ConstInt):
3648 return None # cannot be handled by direct_libffi_call()
3649 cif_description = box_cif_description.getint()
3650 cif_description = llmemory.cast_int_to_adr(cif_description)
3651 cif_description = llmemory.cast_adr_to_ptr(cif_description,
3652 CIF_DESCRIPTION_P)
3653 extrainfo = orig_calldescr.get_extra_info()
3654 calldescr = self.cpu.calldescrof_dynamic(cif_description, extrainfo)
3655 if calldescr is None:
3656 return None # cannot be handled by direct_libffi_call()
3657 #
3658 box_exchange_buffer = argboxes[3]
3659 arg_boxes = []
3660
3661 for i in range(cif_description.nargs):
3662 kind, descr, itemsize = get_arg_descr(self.cpu,
3663 cif_description.atypes[i])
3664 ofs = cif_description.exchange_args[i]
3665 assert ofs % itemsize == 0 # alignment check
3666 if kind == 'i':
3667 box_arg = self.history.record2(
3668 rop.GETARRAYITEM_RAW_I,
3669 box_exchange_buffer,
3670 ConstInt(ofs // itemsize),
3671 0, descr)
3672 elif kind == 'f':
3673 box_arg = self.history.record2(
3674 rop.GETARRAYITEM_RAW_F,
3675 box_exchange_buffer,
3676 ConstInt(ofs // itemsize),
3677 longlong.ZEROF, descr)
3678 else:
3679 assert kind == 'v'
3680 continue
3681 arg_boxes.append(box_arg)
3682 #
3683 # for now, any call via libffi saves and restores everything
3684 # (that is, errno and SetLastError/GetLastError on Windows)
3685 # Note these flags match the ones in clibffi.ll_callback
3686 c_saveall = ConstInt(rffi.RFFI_ERR_ALL | rffi.RFFI_ALT_ERRNO)
3687 opnum = rop.call_release_gil_for_descr(orig_calldescr)
3688 assert opnum == rop.call_release_gil_for_descr(calldescr)
3689 return self.history.record_nospec(opnum,
3690 [c_saveall, argboxes[2]] + arg_boxes,
3691 valueconst, calldescr)
3692 # note that the result is written back to the exchange_buffer by the
3693 # following operation, which should be a raw_store
3694
3695 def direct_call_release_gil(self, argboxes, valueconst, calldescr):
3696 if not we_are_translated(): # for llgraph
3697 calldescr._original_func_ = argboxes[0].getint()
3698 effectinfo = calldescr.get_extra_info()
3699 realfuncaddr, saveerr = effectinfo.call_release_gil_target
3700 funcbox = ConstInt(adr2int(realfuncaddr))
3701 savebox = ConstInt(saveerr)
3702 opnum = rop.call_release_gil_for_descr(calldescr)
3703 return self.history.record_nospec(opnum,
3704 [savebox, funcbox] + argboxes[1:],
3705 valueconst, calldescr)
3706
3707 def do_not_in_trace_call(self, allboxes, descr):
3708 self.clear_exception()
3709 executor.execute_varargs(self.cpu, self, rop.CALL_N,
3710 allboxes, descr)
3711 if self.last_exc_value:
3712 # cannot trace this! it raises, so we have to follow the
3713 # exception-catching path, but the trace doesn't contain
3714 # the call at all
3715 raise SwitchToBlackhole(Counters.ABORT_ESCAPE,
3716 raising_exception=True)
3717 return None
3718
3719 # ____________________________________________________________
3720
3721 class ChangeFrame(jitexc.JitException):
3722 """Raised after we mutated metainterp.framestack, in order to force
3723 it to reload the current top-of-stack frame that gets interpreted."""
3724
3725 # ____________________________________________________________
3726
3727 def _get_opimpl_method(name, argcodes):
3728 from rpython.jit.metainterp.blackhole import signedord
3729 if (name, argcodes) in special_handlers:
3730 return special_handlers[name, argcodes]
3731 #
3732 def handler(self, position):
3733 assert position >= 0
3734 args = ()
3735 next_argcode = 0
3736 code = self.bytecode
3737 orgpc = position
3738 position += 1
3739 for argtype in argtypes:
3740 if argtype == "box": # a box, of whatever type
3741 argcode = argcodes[next_argcode]
3742 next_argcode = next_argcode + 1
3743 if argcode == 'i':
3744 value = self.registers_i[ord(code[position])]
3745 elif argcode == 'c':
3746 value = ConstInt(signedord(code[position]))
3747 elif argcode == 'r':
3748 value = self.registers_r[ord(code[position])]
3749 elif argcode == 'f':
3750 value = self.registers_f[ord(code[position])]
3751 else:
3752 raise AssertionError("bad argcode")
3753 position += 1
3754 elif argtype == "descr" or argtype == "jitcode":
3755 assert argcodes[next_argcode] == 'd'
3756 next_argcode = next_argcode + 1
3757 index = ord(code[position]) | (ord(code[position+1])<<8)
3758 value = self.metainterp.staticdata.opcode_descrs[index]
3759 if argtype == "jitcode":
3760 assert isinstance(value, JitCode)
3761 position += 2
3762 elif argtype == "label":
3763 assert argcodes[next_argcode] == 'L'
3764 next_argcode = next_argcode + 1
3765 value = ord(code[position]) | (ord(code[position+1])<<8)
3766 position += 2
3767 elif argtype == "boxes": # a list of boxes of some type
3768 length = ord(code[position])
3769 value = [None] * length
3770 self.prepare_list_of_boxes(value, 0, position + 1, length,
3771 argcodes[next_argcode])
3772 next_argcode = next_argcode + 1
3773 position += 1 + length
3774 elif argtype == "boxes2": # two lists of boxes merged into one
3775 length1 = ord(code[position])
3776 position2 = position + 1 + length1
3777 length2 = ord(code[position2])
3778 value = [None] * (length1 + length2)
3779 self.prepare_list_of_boxes(value, 0, position + 1, length1,
3780 argcodes[next_argcode])
3781 self.prepare_list_of_boxes(value, length1, position2 + 1, length2,
3782 argcodes[next_argcode + 1])
3783 next_argcode = next_argcode + 2
3784 position = position2 + 1 + length2
3785 elif argtype == "boxes3": # three lists of boxes merged into one
3786 length1 = ord(code[position])
3787 position2 = position + 1 + length1
3788 length2 = ord(code[position2])
3789 position3 = position2 + 1 + length2
3790 length3 = ord(code[position3])
3791 value = [None] * (length1 + length2 + length3)
3792 self.prepare_list_of_boxes(value, 0, position + 1, length1,
3793 argcodes[next_argcode])
3794 self.prepare_list_of_boxes(value, length1, position2 + 1, length2,
3795 argcodes[next_argcode + 1])
3796 self.prepare_list_of_boxes(value, length1 + length2, position3 + 1,
3797 length3,
3798 argcodes[next_argcode + 2])
3799 next_argcode = next_argcode + 3
3800 position = position3 + 1 + length3
3801 elif argtype == "newframe" or argtype == "newframe2" or argtype == "newframe3":
3802 # this and the next two are basically equivalent to
3803 # jitcode boxes/boxes2/boxes3
3804 # instead of allocating the list of boxes, just put everything
3805 # into the correct position of a new MIFrame
3806
3807 # first get the jitcode
3808 assert argcodes[next_argcode] == 'd'
3809 next_argcode = next_argcode + 1
3810 index = ord(code[position]) | (ord(code[position+1])<<8)
3811 jitcode = self.metainterp.staticdata.opcode_descrs[index]
3812 assert isinstance(jitcode, JitCode)
3813 position += 2
3814 # make a new frame
3815 value = self.metainterp.newframe(jitcode)
3816 value.pc = 0
3817
3818 # now put boxes into the right places
3819 length = ord(code[position])
3820 self.fill_registers(value, length, position + 1,
3821 argcodes[next_argcode])
3822 next_argcode = next_argcode + 1
3823 position += 1 + length
3824 if argtype != "newframe": # 2/3 lists of boxes
3825 length = ord(code[position])
3826 self.fill_registers(value, length, position + 1,
3827 argcodes[next_argcode])
3828 next_argcode = next_argcode + 1
3829 position += 1 + length
3830 if argtype == "newframe3": # 3 lists of boxes
3831 length = ord(code[position])
3832 self.fill_registers(value, length, position + 1,
3833 argcodes[next_argcode])
3834 next_argcode = next_argcode + 1
3835 position += 1 + length
3836 elif argtype == "orgpc":
3837 value = orgpc
3838 elif argtype == "int":
3839 argcode = argcodes[next_argcode]
3840 next_argcode = next_argcode + 1
3841 if argcode == 'i':
3842 value = self.registers_i[ord(code[position])].getint()
3843 elif argcode == 'c':
3844 value = signedord(code[position])
3845 else:
3846 raise AssertionError("bad argcode")
3847 position += 1
3848 elif argtype == "jitcode_position":
3849 value = position
3850 else:
3851 raise AssertionError("bad argtype: %r" % (argtype,))
3852 args += (value,)
3853 #
3854 num_return_args = len(argcodes) - next_argcode
3855 assert num_return_args == 0 or num_return_args == 2
3856 if num_return_args:
3857 # Save the type of the resulting box. This is needed if there is
3858 # a get_list_of_active_boxes(). See comments there.
3859 self._result_argcode = argcodes[next_argcode + 1]
3860 position += 1
3861 else:
3862 self._result_argcode = 'v'
3863 self.pc = position
3864 #
3865 if not we_are_translated():
3866 if self.debug:
3867 print('\tpyjitpl: %s(%s)' % (name, ', '.join(map(repr, args))), end=" ")
3868 try:
3869 resultbox = unboundmethod(self, *args)
3870 except Exception as e:
3871 if self.debug:
3872 print('-> %s!' % e.__class__.__name__)
3873 raise
3874 if num_return_args == 0:
3875 if self.debug:
3876 print()
3877 assert resultbox is None
3878 else:
3879 if self.debug:
3880 print('-> %r' % (resultbox,))
3881 assert argcodes[next_argcode] == '>'
3882 result_argcode = argcodes[next_argcode + 1]
3883 if 'ovf' not in name:
3884 assert resultbox.type == {'i': history.INT,
3885 'r': history.REF,
3886 'f': history.FLOAT}[result_argcode]
3887 else:
3888 resultbox = unboundmethod(self, *args)
3889 #
3890 if resultbox is not None:
3891 self.make_result_of_lastop(resultbox)
3892 elif not we_are_translated():
3893 assert self._result_argcode in 'v?' or 'ovf' in name
3894 #
3895 unboundmethod = getattr(MIFrame, 'opimpl_' + name).im_func
3896 argtypes = unrolling_iterable(unboundmethod.argtypes)
3897 handler.__name__ = 'handler_' + name
3898 return handler
3899
3900 def put_back_list_of_boxes3(frame, position, newvalue):
3901 code = frame.bytecode
3902 length1 = ord(code[position])
3903 position2 = position + 1 + length1
3904 length2 = ord(code[position2])
3905 position3 = position2 + 1 + length2
3906 length3 = ord(code[position3])
3907 assert len(newvalue) == length1 + length2 + length3
3908 frame._put_back_list_of_boxes(newvalue, 0, position)
3909 frame._put_back_list_of_boxes(newvalue, length1, position2)
3910 frame._put_back_list_of_boxes(newvalue, length1 + length2, position3)
3911
3912 def same_greenkey(original_boxes, live_arg_boxes, num_green_args):
3913 for i in range(num_green_args):
3914 box1 = original_boxes[i]
3915 box2 = live_arg_boxes[i]
3916 assert isinstance(box1, Const)
3917 if not box1.same_constant(box2):
3918 return False
3919 else:
3920 return True
3921
3922 def has_compiled_targets(token):
3923 return bool(token) and bool(token.target_tokens)