Debian Codegraph @

rpython/jit/metainterp/opencoder.py

raw symbols SCIP
1
2 """ Storage format:
3 for each operation (inputargs numbered with negative numbers)
4 <opnum> [size-if-unknown-arity] [<arg0> <arg1> ...] [descr-or-snapshot-index]
5
6 <opnum> is 1 byte
7 size is 1 byte (or 0 if implied by opnum)
8 the args are varsized
9 the index is varsized
10
11 Snapshot index for guards are an index into the _snapshot_data byte array.
12 Snapshots reference arrays of (encoded) boxes, the data of which is stored
13 in _snapshot_array_data.
14
15 Top snapshots start with:
16 vable_array_index
17 vref_array_index
18 ... then continue like a normal snapshot
19
20 regular snapshots:
21 jitcode_index or -1 for empty snapshots
22 pc
23 array_index
24 prev
25
26 prev:
27 an index into _snapshot_data
28 SNAPSHOT_PREV_NONE for the very final snapshot
29 SNAPSHOT_PREV_COMES_NEXT if the prev snapshot comes right *after* the
30 current one
31 """
32
33 from rpython.jit.metainterp.history import (
34 ConstInt, Const, ConstFloat, ConstPtr, new_ref_dict, SwitchToBlackhole,
35 ConstPtrJitCode)
36 from rpython.jit.metainterp.resoperation import AbstractResOp, AbstractInputArg,\
37 ResOperation, oparity, rop, opwithdescr, GuardResOp, IntOp, FloatOp, RefOp,\
38 opclasses
39 from rpython.rlib.rarithmetic import intmask, r_uint
40 from rpython.rlib.objectmodel import we_are_translated, specialize, always_inline
41 from rpython.rlib.jit import Counters
42 from rpython.rtyper.lltypesystem import rffi, lltype, llmemory
43 from rpython.rlib.debug import make_sure_not_resized
44
45 TAGINT, TAGCONSTPTR, TAGCONSTOTHER, TAGBOX = range(4)
46 TAGMASK = 0x3
47 TAGSHIFT = 2
48
49 INIT_SIZE = 4096
50
51 # XXX todos left:
52 # - SnapshotIterator is very inefficient
53 # - fix test_resume
54 # - benchmarks
55
56 MIN_VALUE = -2 ** 30
57 MAX_VALUE = 2 ** 30 - 1
58
59 def encode_varint_signed(i, res):
60 # either encode in 2 bytes or 4 bytes. the topmost bit is not set in the
61 # 2-bytes case
62 startlen = len(res)
63 assert MIN_VALUE <= i <= MAX_VALUE
64 flag = bool(not (-2**14 <= i < 2 ** 14)) << 7
65 res.append(chr((i & 0b1111111) | flag))
66 i >>= 7
67 res.append(chr(i & 0xff))
68 if flag:
69 i >>= 8
70 res.append(chr(i & 0xff))
71 i >>= 8
72 res.append(chr(i & 0xff))
73 return len(res) - startlen
74
75 @always_inline
76 def decode_varint_signed(b, index=0):
77 byte = ord(b[index])
78 lastbyte = ord(b[index + 1])
79 res = (byte & 0b1111111) | (lastbyte << 7)
80 shift = 15
81 index += 2
82 if byte & 0b10000000:
83 lastbyte = ord(b[index + 1])
84 res |= (ord(b[index]) << 15) | (lastbyte << 23)
85 shift = 31
86 index += 2
87 # sign-extend
88 res |= (-bool(lastbyte & 0b10000000)) << shift
89 return res, index
90
91 def skip_varint_signed(b, index, skip=1):
92 assert skip > 0
93 while True:
94 byte = ord(b[index])
95 if byte & 0b10000000:
96 index += 2
97 index += 2
98 skip -= 1
99 if not skip:
100 return index
101
102 def varint_only_decode(b, index, skip=0):
103 if skip:
104 index = skip_varint_signed(b, index, skip)
105 byte = ord(b[index])
106 lastbyte = ord(b[index + 1])
107 res = (byte & 0b1111111) | (lastbyte << 7)
108 shift = 15
109 index += 2
110 if byte & 0b10000000:
111 lastbyte = ord(b[index + 1])
112 res |= (ord(b[index]) << 15) | (lastbyte << 23)
113 shift = 31
114 index += 2
115 # sign-extend
116 res |= (-bool(lastbyte & 0b10000000)) << shift
117 return res
118
119 def tag(kind, pos):
120 res = intmask(r_uint(pos) << TAGSHIFT)
121 assert res >> TAGSHIFT == pos
122 return res | kind
123
124 @specialize.ll()
125 def untag(tagged):
126 return intmask(tagged) & TAGMASK, intmask(tagged) >> TAGSHIFT
127
128 # chosen such that constant ints fit into the four bytes
129 SMALL_INT_STOP = 2**28
130 SMALL_INT_START = -2**28
131 assert encode_varint_signed(tag(TAGINT, SMALL_INT_START), []) <= 4
132 assert encode_varint_signed(tag(TAGINT, SMALL_INT_STOP - 1), []) <= 4
133
134 class BaseTrace(object):
135 pass
136
137 SNAPSHOT_PREV_NEEDS_PATCHING = -3
138 SNAPSHOT_PREV_NONE = -2
139 SNAPSHOT_PREV_COMES_NEXT = -1
140
141 class TopDownSnapshotIterator(object):
142 """ iterates over encoded snapshots, but in top-down order, ie the most
143 recent call frame is returned last. more efficient, because that's the
144 order than things are encoded in."""
145
146 def __init__(self, trace, snapshot_index):
147 self.trace = trace
148
149 self._index = snapshot_index
150 self.vable_array_index = self.decode_snapshot_int()
151 self.vref_array_index = self.decode_snapshot_int()
152 self.snapshot_index = self._index
153
154 def iter_vable_array(self):
155 return BoxArrayIter.make(self.vable_array_index, self.trace._snapshot_array_data)
156
157 def iter_vref_array(self):
158 return BoxArrayIter.make(self.vref_array_index, self.trace._snapshot_array_data)
159
160 def iter_array(self, snapshot_index):
161 array = varint_only_decode(self.trace._snapshot_data, snapshot_index, skip=2)
162 return BoxArrayIter.make(array, self.trace._snapshot_array_data)
163
164 def length(self, snapshot_index):
165 array = varint_only_decode(self.trace._snapshot_data, snapshot_index, skip=2)
166 length = varint_only_decode(self.trace._snapshot_array_data, array)
167 return length
168
169 def prev(self, snapshot_index):
170 self._index = skip_varint_signed(self.trace._snapshot_data, snapshot_index, skip=3)
171 prev = self.decode_snapshot_int()
172 assert prev != SNAPSHOT_PREV_NEEDS_PATCHING
173 if prev == SNAPSHOT_PREV_COMES_NEXT:
174 prev = self._index
175 return prev
176
177 def unpack_jitcode_pc(self, snapshot_index):
178 self._index = snapshot_index
179 jitcode_index = self.decode_snapshot_int()
180 pc = self.decode_snapshot_int()
181 return jitcode_index, pc
182
183 def is_empty_snapshot(self, snapshot_index):
184 # must be a top snapshot. it's empty if the jitcode index is -1
185 return varint_only_decode(self.trace._snapshot_data, snapshot_index, skip=2) == -1
186
187 def decode_snapshot_int(self):
188 result, self._index = decode_varint_signed(self.trace._snapshot_data, self._index)
189 return result
190
191 def __iter__(self):
192 return self
193
194 def next(self):
195 res = self.snapshot_index
196 if res == SNAPSHOT_PREV_NONE:
197 raise StopIteration
198 self.snapshot_index = self.prev(res)
199 return res
200
201
202 class SnapshotIterator(object):
203 def __init__(self, main_iter, snapshot_index):
204 self.main_iter = main_iter
205 # reverse the snapshots and store the vable, vref lists
206 it = TopDownSnapshotIterator(main_iter.trace, snapshot_index)
207 self.topdown_snapshot_iter = it
208 self.vable_array = it.iter_vable_array()
209 self.vref_array = it.iter_vref_array()
210 self.size = self.vable_array.total_length + self.vref_array.total_length + 3
211 self.framestack = []
212 if it.is_empty_snapshot(snapshot_index):
213 return
214 for snapshot_index in it:
215 self.framestack.append(snapshot_index)
216 self.size += it.length(snapshot_index) + 2
217 self.framestack.reverse()
218
219 def iter_array(self, snapshot_index):
220 return self.topdown_snapshot_iter.iter_array(snapshot_index)
221
222 def get(self, index):
223 return self.main_iter._untag(index)
224
225 def unpack_jitcode_pc(self, snapshot_index):
226 return self.topdown_snapshot_iter.unpack_jitcode_pc(snapshot_index)
227
228 def unpack_array(self, arr):
229 # NOT_RPYTHON
230 # for tests only
231 assert isinstance(arr, BoxArrayIter)
232 return [self.get(i) for i in arr]
233
234 def _update_liverange(item, index, liveranges):
235 tag, v = untag(item)
236 if tag == TAGBOX:
237 liveranges[v] = index
238
239 def update_liveranges(snapshot_index, trace, index, liveranges):
240 it = TopDownSnapshotIterator(trace, snapshot_index)
241 for item in it.iter_vable_array():
242 _update_liverange(item, index, liveranges)
243 for item in it.iter_vref_array():
244 _update_liverange(item, index, liveranges)
245 for snapshot_index in it:
246 for item in it.iter_array(snapshot_index):
247 _update_liverange(item, index, liveranges)
248
249 class TraceIterator(BaseTrace):
250 def __init__(self, trace, start, end, force_inputargs=None,
251 metainterp_sd=None):
252 self.trace = trace
253 self.metainterp_sd = metainterp_sd
254 self.all_descr_len = len(metainterp_sd.all_descrs)
255 self._cache = [None] * trace._index
256 if force_inputargs is not None:
257 # the trace here is cut and we're working from
258 # inputargs that are in the middle, shuffle stuff around a bit
259 self.inputargs = [rop.inputarg_from_tp(arg.type) for
260 arg in force_inputargs]
261 for i, arg in enumerate(force_inputargs):
262 self._cache[arg.get_position()] = self.inputargs[i]
263 else:
264 self.inputargs = [rop.inputarg_from_tp(arg.type) for
265 arg in self.trace.inputargs]
266 for i, arg in enumerate(self.inputargs):
267 self._cache[self.trace.inputargs[i].get_position()] = arg
268 self.start = start
269 self.pos = start
270 self._count = start
271 self._index = start
272 self.start_index = start
273 self.end = end
274
275 def get_dead_ranges(self):
276 return self.trace.get_dead_ranges()
277
278 def kill_cache_at(self, pos):
279 if pos:
280 self._cache[pos] = None
281
282 def replace_last_cached(self, oldbox, box):
283 assert self._cache[self._index - 1] is oldbox
284 self._cache[self._index - 1] = box
285
286 def _get(self, i):
287 res = self._cache[i]
288 assert res is not None
289 return res
290
291 def done(self):
292 return self.pos >= self.end
293
294 def _nextbyte(self):
295 if self.done():
296 raise IndexError
297 res = ord(self.trace._ops[self.pos])
298 self.pos += 1
299 return res
300
301 def _next(self):
302 if self.done():
303 raise IndexError
304 b = self.trace._ops
305 index = self.pos
306 byte = ord(b[index])
307 lastbyte = ord(b[index + 1])
308 res = (byte & 0b1111111) | (lastbyte << 7)
309 shift = 15
310 index += 2
311 if byte & 0b10000000:
312 lastbyte = ord(b[index + 1])
313 res |= (ord(b[index]) << 15) | (lastbyte << 23)
314 shift = 31
315 index += 2
316 # sign-extend
317 res |= (-bool(lastbyte & 0b10000000)) << shift
318 self.pos = index
319 return res
320
321 def _untag(self, tagged):
322 tag, v = untag(tagged)
323 if tag == TAGBOX:
324 return self._get(v)
325 elif tag == TAGINT:
326 return ConstInt(v)
327 elif tag == TAGCONSTPTR:
328 return ConstPtr(self.trace._refs[v])
329 elif tag == TAGCONSTOTHER:
330 if v & 1:
331 return ConstFloat(self.trace._floats[v >> 1])
332 else:
333 return ConstInt(self.trace._bigints[v >> 1])
334 else:
335 assert False
336
337 def get_snapshot_iter(self, index):
338 return SnapshotIterator(self, index)
339
340 def next_element_update_live_range(self, index, liveranges):
341 opnum = self._nextbyte()
342 if oparity[opnum] == -1:
343 argnum = self._next()
344 else:
345 argnum = oparity[opnum]
346 for i in range(argnum):
347 tagged = self._next()
348 tag, v = untag(tagged)
349 if tag == TAGBOX:
350 liveranges[v] = index
351 if opclasses[opnum].type != 'v':
352 liveranges[index] = index
353 if opwithdescr[opnum]:
354 descr_index = self._next()
355 if rop.is_guard(opnum):
356 update_liveranges(descr_index, self.trace, index,
357 liveranges)
358 if opclasses[opnum].type != 'v':
359 return index + 1
360 return index
361
362 def next(self):
363 opnum = self._nextbyte()
364 argnum = oparity[opnum]
365 if argnum == -1:
366 argnum = self._next()
367 if not (0 <= oparity[opnum] <= 3):
368 args = [None] * argnum
369 for i in range(argnum):
370 args[i] = self._untag(self._next())
371 res = ResOperation(opnum, args)
372 else:
373 cls = opclasses[opnum]
374 res = cls()
375 argnum = oparity[opnum]
376 if argnum == 0:
377 pass
378 elif argnum == 1:
379 res.setarg(0, self._untag(self._next()))
380 elif argnum == 2:
381 res.setarg(0, self._untag(self._next()))
382 res.setarg(1, self._untag(self._next()))
383 else:
384 assert argnum == 3
385 res.setarg(0, self._untag(self._next()))
386 res.setarg(1, self._untag(self._next()))
387 res.setarg(2, self._untag(self._next()))
388 descr_index = -1
389 if opwithdescr[opnum]:
390 descr_index = self._next()
391 if descr_index == 0 or rop.is_guard(opnum):
392 descr = None
393 else:
394 if descr_index < self.all_descr_len + 1:
395 descr = self.metainterp_sd.all_descrs[descr_index - 1]
396 else:
397 descr = self.trace._descrs[descr_index - self.all_descr_len - 1]
398 res.setdescr(descr)
399 if rop.is_guard(opnum): # all guards have descrs
400 assert isinstance(res, GuardResOp)
401 res.rd_resume_position = descr_index
402 if res.type != 'v':
403 self._cache[self._index] = res
404 self._index += 1
405 self._count += 1
406 return res
407
408 class CutTrace(BaseTrace):
409 def __init__(self, trace, start, count, index, inputargs):
410 self.trace = trace
411 self.start = start
412 self.inputargs = inputargs
413 self.count = count
414 self.index = index
415
416 def cut_at(self, cut):
417 assert cut[1] > self.count
418 self.trace.cut_at(cut)
419
420 def get_iter(self):
421 iter = TraceIterator(self.trace, self.start, self.trace._pos,
422 self.inputargs,
423 metainterp_sd=self.trace.metainterp_sd)
424 iter._count = self.count
425 iter.start_index = self.index
426 iter._index = self.index
427 return iter
428
429 def combine_uint(index1, index2):
430 assert 0 <= index1 < 65536
431 assert 0 <= index2 < 65536
432 return index1 << 16 | index2 # it's ok to return signed here,
433 # we need only 32bit, but 64 is ok for now
434
435 def unpack_uint(packed):
436 return (packed >> 16) & 0xffff, packed & 0xffff
437
438 class BoxArrayIter(object):
439 def __init__(self, index, data):
440 self.length, self.position = decode_varint_signed(data, index)
441 self.total_length = self.length
442 self.data = data
443
444 def __repr__(self):
445 if self.length == 0 and self.data == ['\x00', '\x00']:
446 return "BoxArrayIter.BOXARRAYITER0"
447 return "<BoxArrayIter length=%s>" % self.length
448
449 @staticmethod
450 def make(index, data):
451 if index == 0: # length 0 arrays are always encoded to index 0
452 return BoxArrayIter.BOXARRAYITER0
453 return BoxArrayIter(index, data)
454
455 def __iter__(self):
456 return self
457
458 def next(self):
459 if self.length == 0:
460 raise StopIteration
461 self.length -= 1
462 item, self.position = decode_varint_signed(self.data, self.position)
463 return item
464
465 BoxArrayIter.BOXARRAYITER0 = BoxArrayIter(0, ['\x00', '\x00'])
466
467
468 class Trace(BaseTrace):
469 _deadranges = (-1, None)
470
471 def __init__(self, max_num_inputargs, metainterp_sd):
472 self.metainterp_sd = metainterp_sd
473 self._ops = ['\x00'] * INIT_SIZE
474 make_sure_not_resized(self._ops)
475 self._pos = 0
476 self._consts_bigint = 0
477 self._consts_float = 0
478 self._total_snapshots = 0
479 self._consts_ptr = 0
480 self._consts_ptr_nodict = 0
481 self._descrs = [None]
482 self._refs = [lltype.nullptr(llmemory.GCREF.TO)]
483 self._refs_dict = new_ref_dict()
484 self._bigints = []
485 self._bigints_dict = {}
486 self._floats = []
487 self._snapshot_data = []
488 self._snapshot_array_data = []
489 self.append_snapshot_array_data_int(0) # all 0-length arrays get index 0
490 if not we_are_translated() and isinstance(max_num_inputargs, list): # old api for tests
491 self.inputargs = max_num_inputargs
492 for i, box in enumerate(max_num_inputargs):
493 box.position_and_flags = r_uint(i << 1)
494 max_num_inputargs = len(max_num_inputargs)
495
496 self.max_num_inputargs = max_num_inputargs
497 self._count = max_num_inputargs # total count
498 self._index = max_num_inputargs # "position" of resulting resops
499 self._start = max_num_inputargs
500 self._pos = max_num_inputargs
501 self.tag_overflow = False
502
503 def set_inputargs(self, inputargs):
504 self.inputargs = inputargs
505 if not we_are_translated():
506 set_positions = {box.get_position() for box in inputargs}
507 assert len(set_positions) == len(inputargs)
508 assert not set_positions or max(set_positions) < self.max_num_inputargs
509
510 def _double_ops(self):
511 self._ops = self._ops + ['\x00'] * len(self._ops)
512
513 def append_byte(self, c):
514 assert 0 <= c < 256
515 if self._pos >= len(self._ops):
516 self._double_ops()
517 self._ops[self._pos] = chr(c)
518 self._pos += 1
519
520 def append_int(self, i):
521 if not MIN_VALUE <= i <= MAX_VALUE:
522 self.tag_overflow = True
523 i = 0
524 if self._pos + 4 > len(self._ops):
525 self._double_ops()
526 ops = self._ops
527 pos = self._pos
528 flag = bool(not (-2**14 <= i < 2 ** 14)) << 7
529 ops[pos] = chr((i & 0b1111111) | flag)
530 pos += 1
531 i >>= 7
532 ops[pos] = chr(i & 0xff)
533 pos += 1
534 if flag:
535 i >>= 8
536 ops[pos] = chr(i & 0xff)
537 pos += 1
538 i >>= 8
539 ops[pos] = chr(i & 0xff)
540 pos += 1
541 self._pos = pos
542
543 def tag_overflow_imminent(self):
544 return self._pos > MAX_VALUE * 0.8
545
546 def tracing_done(self):
547 from rpython.rlib.debug import debug_start, debug_stop, debug_print
548 if self.tag_overflow:
549 raise SwitchToBlackhole(Counters.ABORT_TOO_LONG)
550 self._bigints_dict = {}
551 self._refs_dict = new_ref_dict()
552 debug_start("jit-trace-done")
553 debug_print("trace length:", self._pos)
554 debug_print(" number operations:", self._count)
555 debug_print(" total snapshots:", self._total_snapshots)
556 debug_print(" snapshot data:", len(self._snapshot_data))
557 debug_print(" snapshot array data:", len(self._snapshot_array_data))
558 debug_print(" bigint consts: ", self._consts_bigint, len(self._bigints))
559 debug_print(" float consts: ", self._consts_float, len(self._floats))
560 debug_print(" ref consts: ", self._consts_ptr, self._consts_ptr_nodict, len(self._refs))
561 debug_print(" descrs:", len(self._descrs))
562 debug_stop("jit-trace-done")
563
564 def length(self):
565 return self._pos
566
567 def cut_point(self):
568 return self._pos, self._count, self._index, len(self._snapshot_data), len(self._snapshot_array_data)
569
570 def cut_at(self, end):
571 self._pos = end[0]
572 self._count = end[1]
573 index = end[2]
574 assert index >= 0
575 self._index = index
576
577 def cut_trace_from(self, (start, count, index, x, y), inputargs):
578 return CutTrace(self, start, count, index, inputargs)
579
580 def _cached_const_int(self, box):
581 return v
582
583 def _cached_const_ptr(self, box):
584 assert isinstance(box, ConstPtr)
585 addr = box.getref_base()
586 if not addr:
587 return 0
588 if isinstance(box, ConstPtrJitCode):
589 index = box.opencoder_index
590 if index >= 0:
591 self._consts_ptr_nodict += 1
592 assert self._refs[index] == addr
593 return index
594 v = self._refs_dict.get(addr, -1)
595 if v == -1:
596 v = len(self._refs)
597 self._refs_dict[addr] = v
598 self._refs.append(addr)
599 if isinstance(box, ConstPtrJitCode):
600 box.opencoder_index = v
601 return v
602
603 def _encode(self, box):
604 if isinstance(box, Const):
605 if (isinstance(box, ConstInt) and
606 isinstance(box.getint(), int) and # symbolics
607 SMALL_INT_START <= box.getint() < SMALL_INT_STOP):
608 return tag(TAGINT, box.getint())
609 elif isinstance(box, ConstInt):
610 self._consts_bigint += 1
611 value = box.getint()
612 if not isinstance(value, int):
613 # symbolics, for tests, don't worry about caching
614 v = len(self._bigints) << 1
615 self._bigints.append(value)
616 else:
617 v = self._bigints_dict.get(value, -1)
618 if v == -1:
619 v = len(self._bigints) << 1
620 self._bigints_dict[value] = v
621 self._bigints.append(value)
622 return tag(TAGCONSTOTHER, v)
623 elif isinstance(box, ConstFloat):
624 # don't intern float constants
625 self._consts_float += 1
626 v = (len(self._floats) << 1) | 1
627 self._floats.append(box.getfloatstorage())
628 return tag(TAGCONSTOTHER, v)
629 else:
630 self._consts_ptr += 1
631 v = self._cached_const_ptr(box)
632 return tag(TAGCONSTPTR, v)
633 elif isinstance(box, AbstractResOp):
634 position = box.get_position()
635 assert position >= 0
636 # every time something is used we assume that it lives to the
637 # current _index
638 return tag(TAGBOX, position)
639 else:
640 assert False, "unreachable code"
641
642 def _op_start(self, opnum, num_argboxes):
643 old_pos = self._pos
644 self.append_byte(opnum)
645 expected_arity = oparity[opnum]
646 if expected_arity == -1:
647 self.append_int(num_argboxes)
648 else:
649 assert num_argboxes == expected_arity
650 return old_pos
651
652 def _op_end(self, opnum, descr, old_pos):
653 if opwithdescr[opnum]:
654 if descr is None:
655 # guards get a 0 which is later patched. also some tests have
656 # missing descrs
657 self.append_int(0)
658 else:
659 self.append_int(self._encode_descr(descr))
660 self._count += 1
661 if opclasses[opnum].type != 'v':
662 self._index += 1
663
664 def record_op(self, opnum, argboxes, descr=None):
665 pos = self._index
666 old_pos = self._op_start(opnum, len(argboxes))
667 for box in argboxes:
668 self.append_int(self._encode(box))
669 self._op_end(opnum, descr, old_pos)
670 return pos
671
672 def record_op0(self, opnum, descr=None):
673 pos = self._index
674 old_pos = self._op_start(opnum, 0)
675 self._op_end(opnum, descr, old_pos)
676 return pos
677
678 def record_op1(self, opnum, argbox1, descr=None):
679 pos = self._index
680 old_pos = self._op_start(opnum, 1)
681 self.append_int(self._encode(argbox1))
682 self._op_end(opnum, descr, old_pos)
683 return pos
684
685 def record_op2(self, opnum, argbox1, argbox2, descr=None):
686 pos = self._index
687 old_pos = self._op_start(opnum, 2)
688 self.append_int(self._encode(argbox1))
689 self.append_int(self._encode(argbox2))
690 self._op_end(opnum, descr, old_pos)
691 return pos
692
693 def record_op3(self, opnum, argbox1, argbox2, argbox3, descr=None):
694 pos = self._index
695 old_pos = self._op_start(opnum, 3)
696 self.append_int(self._encode(argbox1))
697 self.append_int(self._encode(argbox2))
698 self.append_int(self._encode(argbox3))
699 self._op_end(opnum, descr, old_pos)
700 return pos
701
702 def _encode_descr(self, descr):
703 descr_index = descr.get_descr_index()
704 if descr_index != -1:
705 return descr_index + 1
706 self._descrs.append(descr)
707 return len(self._descrs) - 1 + len(self.metainterp_sd.all_descrs) + 1
708
709 # ____________________________________________________________
710 # snapshots
711
712 def _list_of_boxes(self, boxes):
713 boxes_list_storage = self.new_array(len(boxes))
714 for i in range(len(boxes)):
715 self._add_box_to_storage(boxes[i])
716 return boxes_list_storage
717
718 def _list_of_boxes_virtualizable(self, boxes):
719 if not boxes:
720 return self.new_array(0)
721 boxes_list_storage = self.new_array(len(boxes))
722 # the virtualizable is at the end, move it to the front in the snapshot
723 self._add_box_to_storage(boxes[-1])
724 for i in range(len(boxes) - 1):
725 self._add_box_to_storage(boxes[i])
726 return boxes_list_storage
727
728 def new_array(self, lgt):
729 if lgt == 0:
730 return 0
731 res = len(self._snapshot_array_data)
732 self.append_snapshot_array_data_int(lgt)
733 return res
734
735 def _add_box_to_storage(self, box):
736 self.append_snapshot_array_data_int(self._encode(box))
737
738 def append_snapshot_array_data_int(self, i):
739 if not MIN_VALUE <= i <= MAX_VALUE:
740 self.tag_overflow = True
741 i = 0
742 encode_varint_signed(i, self._snapshot_array_data)
743
744 def append_snapshot_data_int(self, i):
745 if not MIN_VALUE <= i <= MAX_VALUE:
746 self.tag_overflow = True
747 i = 0
748 encode_varint_signed(i, self._snapshot_data)
749
750 def _encode_snapshot(self, index, pc, array, is_last=False):
751 res = len(self._snapshot_data)
752 self.append_snapshot_data_int(index)
753 self.append_snapshot_data_int(pc)
754 # arrays are indexes into self._snapshot_data
755 self.append_snapshot_data_int(array)
756 # for prev. can be SNAPSHOT_PREV_COMES_NEXT, which means the prev
757 # snapshot comes right afterwards in snapshots. or it can be
758 # SNAPSHOT_PREV_NONE, which means there are no more snapshots. or it's
759 # a positive number, which means it's already somewhere in snapshot at
760 # some other index
761 if is_last:
762 self.append_snapshot_data_int(SNAPSHOT_PREV_NONE)
763 else:
764 self.append_snapshot_data_int(SNAPSHOT_PREV_NEEDS_PATCHING)
765 return res
766
767 def create_top_snapshot(self, frame, vable_boxes, vref_boxes, after_residual_call=False, is_last=False):
768 self._total_snapshots += 1
769 array = frame.get_list_of_active_boxes(False, self.new_array, self._add_box_to_storage,
770 after_residual_call=after_residual_call)
771 s = len(self._snapshot_data)
772 vable_array = self._list_of_boxes_virtualizable(vable_boxes)
773 vref_array = self._list_of_boxes(vref_boxes)
774 self.append_snapshot_data_int(vable_array)
775 self.append_snapshot_data_int(vref_array)
776 self._encode_snapshot(
777 frame.jitcode.index,
778 frame.pc,
779 array,
780 is_last=is_last)
781 assert self._ops[self._pos - 2] == '\x00'
782 assert self._ops[self._pos - 1] == '\x00'
783 self._pos -= 2
784 self.append_int(s)
785 return s
786
787 def create_empty_top_snapshot(self, vable_boxes, vref_boxes):
788 self._total_snapshots += 1
789 s = len(self._snapshot_data)
790 array = self._list_of_boxes([])
791 vable_array = self._list_of_boxes_virtualizable(vable_boxes)
792 vref_array = self._list_of_boxes(vref_boxes)
793 self.append_snapshot_data_int(vable_array)
794 self.append_snapshot_data_int(vref_array)
795 self._encode_snapshot(
796 -1,
797 0,
798 array,
799 is_last=True)
800 assert self._ops[self._pos - 2] == '\x00'
801 assert self._ops[self._pos - 1] == '\x00'
802 self._pos -= 2
803 self.append_int(s)
804 return s
805
806 def create_snapshot(self, frame, is_last=False):
807 self._total_snapshots += 1
808 array = frame.get_list_of_active_boxes(True, self.new_array, self._add_box_to_storage)
809 self.snapshot_add_prev(SNAPSHOT_PREV_COMES_NEXT)
810 return self._encode_snapshot(frame.jitcode.index, frame.pc, array, is_last=is_last)
811
812 def snapshot_add_prev(self, prev):
813 assert self._snapshot_data[-2] == '}' # SNAPSHOT_PREV_NEEDS_PATCHING
814 assert self._snapshot_data[-1] == '\xff'
815 self._snapshot_data.pop()
816 self._snapshot_data.pop()
817 self.append_snapshot_data_int(prev)
818
819 def capture_resumedata(self, framestack, virtualizable_boxes, virtualref_boxes, after_residual_call=False):
820 n = len(framestack) - 1
821 if n >= 0:
822 top = framestack[n]
823 result = self.create_top_snapshot(
824 top, virtualizable_boxes,
825 virtualref_boxes,
826 after_residual_call=after_residual_call,
827 is_last=n == 0)
828 self._ensure_parent_resumedata(framestack, n)
829 else:
830 result = self.create_empty_top_snapshot(
831 virtualizable_boxes, virtualref_boxes)
832 return result
833
834 def _ensure_parent_resumedata(self, framestack, n):
835 while n > 0:
836 target = framestack[n]
837 back = framestack[n - 1]
838 if target.parent_snapshot >= 0:
839 self.snapshot_add_prev(target.parent_snapshot)
840 return
841 s = self.create_snapshot(back, is_last=n == 1)
842 target.parent_snapshot = s
843 n -= 1
844
845
846 # ____________________________________________________________
847
848 def get_iter(self):
849 return TraceIterator(self, self._start, self._pos,
850 metainterp_sd=self.metainterp_sd)
851
852 def get_live_ranges(self):
853 t = self.get_iter()
854 liveranges = [0] * self._index
855 index = t._count
856 while not t.done():
857 index = t.next_element_update_live_range(index, liveranges)
858 return liveranges
859
860 def get_dead_ranges(self):
861 """ Same as get_live_ranges, but returns a list of "dying" indexes,
862 such as for each index x, the number found there is for sure dead
863 before x
864 """
865 def insert(ranges, pos, v):
866 # XXX skiplist
867 while ranges[pos]:
868 pos += 1
869 if pos == len(ranges):
870 return
871 ranges[pos] = v
872
873 if self._deadranges != (-1, None):
874 if self._deadranges[0] == self._count:
875 return self._deadranges[1]
876 liveranges = self.get_live_ranges()
877 deadranges = [0] * (self._index + 2)
878 assert len(deadranges) == len(liveranges) + 2
879 for i in range(self._start, len(liveranges)):
880 elem = liveranges[i]
881 if elem:
882 insert(deadranges, elem + 1, i)
883 self._deadranges = (self._count, deadranges)
884 return deadranges
885
886 def unpack(self):
887 iter = self.get_iter()
888 ops = []
889 try:
890 while not iter.done():
891 ops.append(iter.next())
892 except IndexError:
893 pass
894 return iter.inputargs, ops
895