Debian Codegraph @

rpython/jit/metainterp/resume.py

raw symbols SCIP
1 from rpython.jit.codewriter.effectinfo import EffectInfo
2 from rpython.jit.metainterp import jitprof
3 from rpython.jit.metainterp.history import (
4 Const, ConstInt, ConstPtr, getkind, INT, REF, FLOAT, CONST_NULL,
5 AbstractDescr, IntFrontendOp, RefFrontendOp, FloatFrontendOp,
6 new_ref_dict)
7 from rpython.jit.metainterp.resoperation import rop
8 from rpython.rlib import rarithmetic, rstack
9 from rpython.rlib.objectmodel import (we_are_translated, specialize,
10 compute_unique_id)
11 from rpython.rlib.debug import ll_assert, debug_print
12 from rpython.rtyper import annlowlevel
13 from rpython.rtyper.lltypesystem import lltype, llmemory, rffi, rstr
14 from rpython.rtyper.rclass import OBJECTPTR
15 from rpython.jit.metainterp.walkvirtual import VirtualVisitor
16 from rpython.jit.metainterp import resumecode
17
18
19 # Logic to encode the chain of frames and the state of the boxes at a
20 # guard operation, and to decode it again. This is a bit advanced,
21 # because it needs to support optimize.py which encodes virtuals with
22 # arbitrary cycles and also to compress the information
23
24 class VectorInfo(object):
25 """
26 prev: the previous VectorInfo or None
27 failargs_pos: the index where to find it in the fail arguments
28 location: the register location (an integer), specified by the backend
29 variable: the original variable that lived at failargs_pos
30 """
31 _attrs_ = ('prev', 'failargs_pos', 'location', 'variable')
32 prev = None
33 failargs_pos = -1
34 location = None
35 variable = None
36
37 def __init__(self, position, variable):
38 self.failargs_pos = position
39 self.variable = variable
40
41 def getpos_in_failargs(self):
42 return self.failargs_pos
43
44 def next(self):
45 return self.prev
46
47 def getoriginal(self):
48 return self.variable
49
50 def clone(self):
51 prev = None
52 if self.prev:
53 prev = self.prev.clone()
54 return self.instance_clone(prev)
55
56 def instance_clone(self, prev):
57 raise NotImplementedError
58
59 class UnpackAtExitInfo(VectorInfo):
60 def instance_clone(self, prev):
61 info = UnpackAtExitInfo(self.failargs_pos, self.variable)
62 info.prev = prev
63 return info
64
65 class AccumInfo(VectorInfo):
66 _attrs_ = ('accum_operation', 'scalar')
67
68 def __init__(self, position, variable, operation):
69 VectorInfo.__init__(self, position, variable)
70 self.accum_operation = operation
71
72 def instance_clone(self, prev):
73 info = AccumInfo(self.failargs_pos, self.variable,
74 self.accum_operation)
75 info.location = self.location
76 info.prev = prev
77 return info
78
79 def __repr__(self):
80 return 'AccumInfo(%s,%s,%s,%s,%s)' % (self.prev is None,
81 self.accum_operation,
82 self.failargs_pos,
83 self.variable,
84 self.location)
85
86
87 PENDINGFIELDSTRUCT = lltype.Struct('PendingField',
88 ('lldescr', OBJECTPTR),
89 ('num', rffi.SHORT),
90 ('fieldnum', rffi.SHORT),
91 ('itemindex', rffi.INT))
92 PENDINGFIELDSP = lltype.Ptr(lltype.GcArray(PENDINGFIELDSTRUCT))
93
94 TAGMASK = 3
95
96 class TagOverflow(Exception):
97 pass
98
99 def tag(value, tagbits):
100 assert 0 <= tagbits <= 3
101 sx = value >> 13
102 if sx != 0 and sx != -1:
103 raise TagOverflow
104 return rffi.r_short(value<<2|tagbits)
105
106 def untag(value):
107 value = rarithmetic.widen(value)
108 tagbits = value & TAGMASK
109 return value >> 2, tagbits
110
111 def tagged_eq(x, y):
112 # please rpython :(
113 return rarithmetic.widen(x) == rarithmetic.widen(y)
114
115 def tagged_list_eq(tl1, tl2):
116 if len(tl1) != len(tl2):
117 return False
118 for i in range(len(tl1)):
119 if not tagged_eq(tl1[i], tl2[i]):
120 return False
121 return True
122
123 TAGCONST = 0
124 TAGINT = 1
125 TAGBOX = 2
126 TAGVIRTUAL = 3
127
128 UNASSIGNED = tag(-1 << 13, TAGBOX)
129 UNASSIGNEDVIRTUAL = tag(-1 << 13, TAGVIRTUAL)
130 NULLREF = tag(-1, TAGCONST)
131 UNINITIALIZED = tag(-2, TAGCONST) # used for uninitialized string characters
132 TAG_CONST_OFFSET = 0
133
134 class NumberingState(resumecode.Writer):
135 def __init__(self, size):
136 resumecode.Writer.__init__(self, size)
137 self.liveboxes = {}
138 self.num_boxes = 0
139 self.num_virtuals = 0
140
141
142 class ResumeDataLoopMemo(object):
143
144 def __init__(self, metainterp_sd):
145 self.metainterp_sd = metainterp_sd
146 self.cpu = metainterp_sd.cpu
147 self.consts = []
148 self.large_ints = {}
149 self.refs = new_ref_dict()
150 self.cached_boxes = {}
151 self.cached_virtuals = {}
152
153 self.nvirtuals = 0
154 self.nvholes = 0
155 self.nvreused = 0
156
157 def getconst(self, const):
158 if const.type == INT:
159 val = const.getint()
160 if not we_are_translated() and not isinstance(val, int):
161 # unhappiness, probably a symbolic
162 return self._newconst(const)
163 try:
164 return tag(val, TAGINT)
165 except TagOverflow:
166 pass
167 tagged = self.large_ints.get(val, UNASSIGNED)
168 if not tagged_eq(tagged, UNASSIGNED):
169 return tagged
170 tagged = self._newconst(const)
171 self.large_ints[val] = tagged
172 return tagged
173 elif const.type == REF:
174 val = const.getref_base()
175 if not val:
176 return NULLREF
177 tagged = self.refs.get(val, UNASSIGNED)
178 if not tagged_eq(tagged, UNASSIGNED):
179 return tagged
180 tagged = self._newconst(const)
181 self.refs[val] = tagged
182 return tagged
183 return self._newconst(const)
184
185 def _newconst(self, const):
186 result = tag(len(self.consts) + TAG_CONST_OFFSET, TAGCONST)
187 self.consts.append(const)
188 return result
189
190 # env numbering
191
192 def _number_boxes(self, iter, iterator, numb_state):
193 """ Number boxes from one snapshot
194 """
195 from rpython.jit.metainterp.optimizeopt.info import (
196 getrawptrinfo, getptrinfo)
197 num_boxes = numb_state.num_boxes
198 num_virtuals = numb_state.num_virtuals
199 liveboxes = numb_state.liveboxes
200 for item in iterator:
201 box = iter.get(rffi.cast(lltype.Signed, item))
202 box = box.get_box_replacement()
203
204 if isinstance(box, Const):
205 tagged = self.getconst(box)
206 else:
207 try:
208 tagged = liveboxes[box]
209 except KeyError:
210 is_virtual = False
211 if box.type == 'r':
212 info = getptrinfo(box)
213 is_virtual = (info is not None and info.is_virtual())
214 if box.type == 'i':
215 info = getrawptrinfo(box)
216 is_virtual = (info is not None and info.is_virtual())
217 if is_virtual:
218 tagged = tag(num_virtuals, TAGVIRTUAL)
219 num_virtuals += 1
220 else:
221 tagged = tag(num_boxes, TAGBOX)
222 num_boxes += 1
223 liveboxes[box] = tagged
224 numb_state.append_short(tagged)
225 numb_state.num_boxes = num_boxes
226 numb_state.num_virtuals = num_virtuals
227
228 def number(self, position, trace, minimum_virtualizable_size=-1):
229 snapshot_iter = trace.get_snapshot_iter(position)
230 numb_state = NumberingState(snapshot_iter.size)
231 numb_state.append_int(0) # patch later: size of resume section
232 numb_state.append_int(0) # patch later: number of failargs
233
234 array_iter = snapshot_iter.vable_array
235
236 if minimum_virtualizable_size != -1:
237 # it's > and not >=, because the virtualizable itself is one entry
238 # in the array too
239 assert array_iter.total_length > minimum_virtualizable_size
240 numb_state.append_int(array_iter.total_length)
241 self._number_boxes(snapshot_iter, array_iter, numb_state)
242
243 array_iter = snapshot_iter.vref_array
244 n = array_iter.total_length
245 assert not (n & 1)
246 numb_state.append_int(n >> 1)
247 self._number_boxes(snapshot_iter, array_iter, numb_state)
248
249 for snapshot in snapshot_iter.framestack:
250 jitcode_index, pc = snapshot_iter.unpack_jitcode_pc(snapshot)
251 numb_state.append_int(jitcode_index)
252 numb_state.append_int(pc)
253 self._number_boxes(snapshot_iter, snapshot_iter.iter_array(snapshot), numb_state)
254 numb_state.patch_current_size(0)
255
256 return numb_state
257
258
259 # caching for virtuals and boxes inside them
260
261 def num_cached_boxes(self):
262 return len(self.cached_boxes)
263
264 def assign_number_to_box(self, box, boxes):
265 # returns a negative number
266 if box in self.cached_boxes:
267 num = self.cached_boxes[box]
268 boxes[-num - 1] = box
269 else:
270 boxes.append(box)
271 num = -len(boxes)
272 self.cached_boxes[box] = num
273 return num
274
275 def num_cached_virtuals(self):
276 return len(self.cached_virtuals)
277
278 def assign_number_to_virtual(self, box):
279 # returns a negative number
280 if box in self.cached_virtuals:
281 num = self.cached_virtuals[box]
282 else:
283 num = self.cached_virtuals[box] = -len(self.cached_virtuals) - 1
284 return num
285
286 def clear_box_virtual_numbers(self):
287 self.cached_boxes.clear()
288 self.cached_virtuals.clear()
289
290 def update_counters(self, profiler):
291 profiler.count(jitprof.Counters.NVIRTUALS, self.nvirtuals)
292 profiler.count(jitprof.Counters.NVHOLES, self.nvholes)
293 profiler.count(jitprof.Counters.NVREUSED, self.nvreused)
294
295 _frame_info_placeholder = (None, 0, 0)
296
297
298 class ResumeDataVirtualAdder(VirtualVisitor):
299
300 def __init__(self, optimizer, storage, guard_op, trace, memo):
301 self.optimizer = optimizer
302 self.trace = trace
303 self.storage = storage
304 self.guard_op = guard_op
305 self.memo = memo
306
307 def make_virtual_info(self, info, fieldnums):
308 assert fieldnums is not None
309 vinfo = info._cached_vinfo
310 if vinfo is not None and vinfo.equals(fieldnums):
311 return vinfo
312 vinfo = info.visitor_dispatch_virtual_type(self)
313 vinfo.set_content(fieldnums)
314 info._cached_vinfo = vinfo
315 return vinfo
316
317 def visit_not_virtual(self, value):
318 assert 0, "unreachable"
319
320 def visit_virtual(self, descr, fielddescrs):
321 return VirtualInfo(descr, fielddescrs)
322
323 def visit_vstruct(self, typedescr, fielddescrs):
324 return VStructInfo(typedescr, fielddescrs)
325
326 def visit_varray(self, arraydescr, clear):
327 if clear:
328 return VArrayInfoClear(arraydescr)
329 else:
330 return VArrayInfoNotClear(arraydescr)
331
332 def visit_varraystruct(self, arraydescr, size, fielddescrs):
333 return VArrayStructInfo(arraydescr, size, fielddescrs)
334
335 def visit_vrawbuffer(self, func, size, offsets, descrs):
336 return VRawBufferInfo(func, size, offsets, descrs)
337
338 def visit_vrawslice(self, offset):
339 return VRawSliceInfo(offset)
340
341 def visit_vstrplain(self, is_unicode=False):
342 if is_unicode:
343 return VUniPlainInfo()
344 else:
345 return VStrPlainInfo()
346
347 def visit_vstrconcat(self, is_unicode=False):
348 if is_unicode:
349 return VUniConcatInfo()
350 else:
351 return VStrConcatInfo()
352
353 def visit_vstrslice(self, is_unicode=False):
354 if is_unicode:
355 return VUniSliceInfo()
356 else:
357 return VStrSliceInfo()
358
359 def register_virtual_fields(self, virtualbox, _fieldboxes):
360 tagged = self.liveboxes_from_env.get(virtualbox, UNASSIGNEDVIRTUAL)
361 self.liveboxes[virtualbox] = tagged
362 fieldboxes = []
363 for box in _fieldboxes:
364 if box is not None:
365 box = box.get_box_replacement()
366 fieldboxes.append(box)
367 self.vfieldboxes[virtualbox] = fieldboxes
368 self._register_boxes(fieldboxes)
369
370 def register_box(self, box):
371 if (box is not None and not isinstance(box, Const)
372 and box not in self.liveboxes_from_env
373 and box not in self.liveboxes):
374 self.liveboxes[box] = UNASSIGNED
375
376 def _register_boxes(self, boxes):
377 for box in boxes:
378 self.register_box(box)
379
380 def already_seen_virtual(self, virtualbox):
381 if virtualbox not in self.liveboxes:
382 assert virtualbox in self.liveboxes_from_env
383 assert untag(self.liveboxes_from_env[virtualbox])[1] == TAGVIRTUAL
384 return False
385 tagged = self.liveboxes[virtualbox]
386 _, tagbits = untag(tagged)
387 return tagbits == TAGVIRTUAL
388
389 def finish(self, pending_setfields=[]):
390 from rpython.jit.metainterp.optimizeopt.info import (
391 getrawptrinfo, getptrinfo)
392 # compute the numbering
393 storage = self.storage
394 # make sure that nobody attached resume data to this guard yet
395 assert not storage.rd_numb
396 resume_position = self.guard_op.rd_resume_position
397 assert resume_position >= 0
398 # count stack depth
399 if self.optimizer.jitdriver_sd.virtualizable_info:
400 minimum_virtualizable_size = self.optimizer.jitdriver_sd.virtualizable_info.minimum_size()
401 else:
402 minimum_virtualizable_size = -1
403 numb_state = self.memo.number(
404 resume_position, self.trace,
405 minimum_virtualizable_size)
406 self.liveboxes_from_env = liveboxes_from_env = numb_state.liveboxes
407 num_virtuals = numb_state.num_virtuals
408 self.liveboxes = {}
409
410 # collect liveboxes and virtuals
411 n = len(liveboxes_from_env) - num_virtuals
412 liveboxes = [None] * n
413 self.vfieldboxes = {}
414 for box, tagged in liveboxes_from_env.iteritems():
415 i, tagbits = untag(tagged)
416 if tagbits == TAGBOX:
417 liveboxes[i] = box
418 else:
419 assert tagbits == TAGVIRTUAL
420 if box.type == 'r':
421 info = getptrinfo(box)
422 else:
423 assert box.type == 'i'
424 info = getrawptrinfo(box)
425 assert info.is_virtual()
426 info.visitor_walk_recursive(box, self)
427
428 for setfield_op in pending_setfields:
429 box = setfield_op.getarg(0)
430 if box is not None:
431 box = box.get_box_replacement()
432 if setfield_op.getopnum() == rop.SETFIELD_GC:
433 fieldbox = setfield_op.getarg(1)
434 else:
435 fieldbox = setfield_op.getarg(2)
436 if fieldbox is not None:
437 fieldbox = fieldbox.get_box_replacement()
438 self.register_box(box)
439 self.register_box(fieldbox)
440 info = getptrinfo(fieldbox)
441 assert info is not None and info.is_virtual()
442 info.visitor_walk_recursive(fieldbox, self)
443
444 self._number_virtuals(liveboxes, num_virtuals)
445 self._add_pending_fields(pending_setfields)
446
447 numb_state.patch(1, len(liveboxes))
448
449 self._add_optimizer_sections(numb_state, liveboxes, liveboxes_from_env)
450 storage.rd_numb = numb_state.create_numbering()
451 storage.rd_consts = self.memo.consts
452 return liveboxes[:]
453
454 def _number_virtuals(self, liveboxes, num_env_virtuals):
455 from rpython.jit.metainterp.optimizeopt.info import (
456 AbstractVirtualPtrInfo, getptrinfo)
457
458 # !! 'liveboxes' is a list that is extend()ed in-place !!
459 memo = self.memo
460 new_liveboxes = [None] * memo.num_cached_boxes()
461 count = 0
462 # So far, self.liveboxes should contain 'tagged' values that are
463 # either UNASSIGNED, UNASSIGNEDVIRTUAL, or a *non-negative* value
464 # with the TAGVIRTUAL. The following loop removes the UNASSIGNED
465 # and UNASSIGNEDVIRTUAL entries, and replaces them with real
466 # negative values.
467 for box, tagged in self.liveboxes.iteritems():
468 i, tagbits = untag(tagged)
469 if tagbits == TAGBOX:
470 assert box not in self.liveboxes_from_env
471 assert tagged_eq(tagged, UNASSIGNED)
472 index = memo.assign_number_to_box(box, new_liveboxes)
473 self.liveboxes[box] = tag(index, TAGBOX)
474 count += 1
475 else:
476 assert tagbits == TAGVIRTUAL
477 if tagged_eq(tagged, UNASSIGNEDVIRTUAL):
478 assert box not in self.liveboxes_from_env
479 index = memo.assign_number_to_virtual(box)
480 self.liveboxes[box] = tag(index, TAGVIRTUAL)
481 else:
482 assert i >= 0
483 new_liveboxes.reverse()
484 liveboxes.extend(new_liveboxes)
485 nholes = len(new_liveboxes) - count
486
487 storage = self.storage
488 storage.rd_virtuals = None
489 vfieldboxes = self.vfieldboxes
490 if vfieldboxes:
491 length = num_env_virtuals + memo.num_cached_virtuals()
492 virtuals = storage.rd_virtuals = [None] * length
493 memo.nvirtuals += length
494 memo.nvholes += length - len(vfieldboxes)
495 for virtualbox, fieldboxes in vfieldboxes.iteritems():
496 num, _ = untag(self.liveboxes[virtualbox])
497 info = getptrinfo(virtualbox)
498 assert info.is_virtual()
499 assert isinstance(info, AbstractVirtualPtrInfo)
500 fieldnums = [self._gettagged(box) for box in fieldboxes]
501 vinfo = self.make_virtual_info(info, fieldnums)
502 # if a new vinfo instance is made, we get the fieldnums list we
503 # pass in as an attribute. hackish.
504 if vinfo.fieldnums is not fieldnums:
505 memo.nvreused += 1
506 virtuals[num] = vinfo
507
508 if self._invalidation_needed(len(liveboxes), nholes):
509 memo.clear_box_virtual_numbers()
510
511 def _invalidation_needed(self, nliveboxes, nholes):
512 memo = self.memo
513 # xxx heuristic a bit out of thin air
514 failargs_limit = memo.metainterp_sd.options.failargs_limit
515 if nliveboxes > (failargs_limit // 2):
516 if nholes > nliveboxes // 3:
517 return True
518 return False
519
520 def _add_pending_fields(self, pending_setfields):
521 from rpython.jit.metainterp.optimizeopt.util import (
522 get_box_replacement)
523 rd_pendingfields = lltype.nullptr(PENDINGFIELDSP.TO)
524 if pending_setfields:
525 n = len(pending_setfields)
526 rd_pendingfields = lltype.malloc(PENDINGFIELDSP.TO, n)
527 for i in range(n):
528 op = pending_setfields[i]
529 box = get_box_replacement(op.getarg(0))
530 descr = op.getdescr()
531 opnum = op.getopnum()
532 if opnum == rop.SETARRAYITEM_GC:
533 fieldbox = op.getarg(2)
534 boxindex = op.getarg(1).get_box_replacement()
535 itemindex = boxindex.getint()
536 # sanity: it's impossible to run code with SETARRAYITEM_GC
537 # with negative index, so this guard cannot ever fail;
538 # but it's possible to try to *build* such invalid code
539 if itemindex < 0:
540 raise TagOverflow
541 elif opnum == rop.SETFIELD_GC:
542 fieldbox = op.getarg(1)
543 itemindex = -1
544 else:
545 raise AssertionError
546 fieldbox = get_box_replacement(fieldbox)
547 lldescr = annlowlevel.cast_instance_to_base_ptr(descr)
548 num = self._gettagged(box)
549 fieldnum = self._gettagged(fieldbox)
550 # the index is limited to 2147483647 (64-bit machines only)
551 if itemindex > 2147483647:
552 raise TagOverflow
553 #
554 rd_pendingfields[i].lldescr = lldescr
555 rd_pendingfields[i].num = num
556 rd_pendingfields[i].fieldnum = fieldnum
557 rd_pendingfields[i].itemindex = rffi.cast(rffi.INT, itemindex)
558 self.storage.rd_pendingfields = rd_pendingfields
559
560 def _gettagged(self, box):
561 if box is None:
562 return UNINITIALIZED
563 if isinstance(box, Const):
564 return self.memo.getconst(box)
565 else:
566 if box in self.liveboxes_from_env:
567 return self.liveboxes_from_env[box]
568 return self.liveboxes[box]
569
570 def _add_optimizer_sections(self, numb_state, liveboxes, liveboxes_from_env):
571 # add extra information about things the optimizer learned
572 from rpython.jit.metainterp.optimizeopt.bridgeopt import serialize_optimizer_knowledge
573 serialize_optimizer_knowledge(
574 self.optimizer, numb_state, liveboxes, liveboxes_from_env, self.memo)
575
576 class AbstractVirtualInfo(object):
577 kind = REF
578 is_about_raw = False
579 #def allocate(self, decoder, index):
580 # raise NotImplementedError
581 def equals(self, fieldnums):
582 return tagged_list_eq(self.fieldnums, fieldnums)
583
584 def set_content(self, fieldnums):
585 self.fieldnums = fieldnums
586
587 def debug_prints(self):
588 raise NotImplementedError
589
590
591 class AbstractVirtualStructInfo(AbstractVirtualInfo):
592 def __init__(self, fielddescrs):
593 self.fielddescrs = fielddescrs
594 #self.fieldnums = ...
595
596 @specialize.argtype(1)
597 def setfields(self, decoder, struct):
598 for i in range(len(self.fielddescrs)):
599 descr = self.fielddescrs[i]
600 num = self.fieldnums[i]
601 if not tagged_eq(num, UNINITIALIZED):
602 decoder.setfield(struct, num, descr)
603 return struct
604
605 def debug_prints(self):
606 assert len(self.fielddescrs) == len(self.fieldnums)
607 for i in range(len(self.fielddescrs)):
608 debug_print("\t\t",
609 str(self.fielddescrs[i]),
610 str(untag(self.fieldnums[i])))
611
612 class VirtualInfo(AbstractVirtualStructInfo):
613 def __init__(self, descr, fielddescrs):
614 AbstractVirtualStructInfo.__init__(self, fielddescrs)
615 self.descr = descr
616
617 @specialize.argtype(1)
618 def allocate(self, decoder, index):
619 struct = decoder.allocate_with_vtable(descr=self.descr)
620 decoder.virtuals_cache.set_ptr(index, struct)
621 return self.setfields(decoder, struct)
622
623 def debug_prints(self):
624 debug_print("\tvirtualinfo", self.known_class.repr_rpython(), " at ", compute_unique_id(self))
625 AbstractVirtualStructInfo.debug_prints(self)
626
627
628 class VStructInfo(AbstractVirtualStructInfo):
629 def __init__(self, typedescr, fielddescrs):
630 AbstractVirtualStructInfo.__init__(self, fielddescrs)
631 self.typedescr = typedescr
632
633 @specialize.argtype(1)
634 def allocate(self, decoder, index):
635 struct = decoder.allocate_struct(self.typedescr)
636 decoder.virtuals_cache.set_ptr(index, struct)
637 return self.setfields(decoder, struct)
638
639 def debug_prints(self):
640 debug_print("\tvstructinfo", self.typedescr.repr_rpython(), " at ", compute_unique_id(self))
641 AbstractVirtualStructInfo.debug_prints(self)
642
643 class AbstractVArrayInfo(AbstractVirtualInfo):
644 def __init__(self, arraydescr):
645 assert arraydescr is not None
646 self.arraydescr = arraydescr
647 #self.fieldnums = ...
648
649 @specialize.argtype(1)
650 def allocate(self, decoder, index):
651 length = len(self.fieldnums)
652 arraydescr = self.arraydescr
653 array = decoder.allocate_array(length, arraydescr, self.clear)
654 decoder.virtuals_cache.set_ptr(index, array)
655 # NB. the check for the kind of array elements is moved out of the loop
656 if arraydescr.is_array_of_pointers():
657 for i in range(length):
658 num = self.fieldnums[i]
659 if not tagged_eq(num, UNINITIALIZED):
660 decoder.setarrayitem_ref(array, i, num, arraydescr)
661 elif arraydescr.is_array_of_floats():
662 for i in range(length):
663 num = self.fieldnums[i]
664 if not tagged_eq(num, UNINITIALIZED):
665 decoder.setarrayitem_float(array, i, num, arraydescr)
666 else:
667 for i in range(length):
668 num = self.fieldnums[i]
669 if not tagged_eq(num, UNINITIALIZED):
670 decoder.setarrayitem_int(array, i, num, arraydescr)
671 return array
672
673 def debug_prints(self):
674 debug_print("\tvarrayinfo", self.arraydescr, " at ",
675 compute_unique_id(self), " clear=", self.clear)
676 for i in self.fieldnums:
677 debug_print("\t\t", str(untag(i)))
678
679
680 class VArrayInfoClear(AbstractVArrayInfo):
681 clear = True
682
683 class VArrayInfoNotClear(AbstractVArrayInfo):
684 clear = False
685
686
687 class VAbstractRawInfo(AbstractVirtualInfo):
688 kind = INT
689 is_about_raw = True
690
691
692 class VRawBufferInfo(VAbstractRawInfo):
693
694 def __init__(self, func, size, offsets, descrs):
695 self.func = func
696 self.size = size
697 self.offsets = offsets
698 self.descrs = descrs
699
700 @specialize.argtype(1)
701 def allocate_int(self, decoder, index):
702 length = len(self.fieldnums)
703 buffer = decoder.allocate_raw_buffer(self.func, self.size)
704 decoder.virtuals_cache.set_int(index, buffer)
705 for i in range(len(self.offsets)):
706 offset = self.offsets[i]
707 descr = self.descrs[i]
708 decoder.setrawbuffer_item(buffer, self.fieldnums[i], offset, descr)
709 return buffer
710
711 def debug_prints(self):
712 debug_print("\tvrawbufferinfo", " at ", compute_unique_id(self))
713 for i in self.fieldnums:
714 debug_print("\t\t", str(untag(i)))
715
716
717 class VRawSliceInfo(VAbstractRawInfo):
718
719 def __init__(self, offset):
720 self.offset = offset
721
722 @specialize.argtype(1)
723 def allocate_int(self, decoder, index):
724 assert len(self.fieldnums) == 1
725 base_buffer = decoder.decode_int(self.fieldnums[0])
726 buffer = decoder.int_add_const(base_buffer, self.offset)
727 decoder.virtuals_cache.set_int(index, buffer)
728 return buffer
729
730 def debug_prints(self):
731 debug_print("\tvrawsliceinfo", " at ", compute_unique_id(self))
732 for i in self.fieldnums:
733 debug_print("\t\t", str(untag(i)))
734
735
736 class VArrayStructInfo(AbstractVirtualInfo):
737 def __init__(self, arraydescr, size, fielddescrs):
738 self.size = size
739 self.arraydescr = arraydescr
740 self.fielddescrs = fielddescrs
741
742 def debug_prints(self):
743 debug_print("\tvarraystructinfo", self.arraydescr, " at ", compute_unique_id(self))
744 for i in self.fieldnums:
745 debug_print("\t\t", str(untag(i)))
746
747 @specialize.argtype(1)
748 def allocate(self, decoder, index):
749 array = decoder.allocate_array(self.size, self.arraydescr,
750 clear=True)
751 decoder.virtuals_cache.set_ptr(index, array)
752 p = 0
753 for i in range(self.size):
754 for j in range(len(self.fielddescrs)):
755 num = self.fieldnums[p]
756 if not tagged_eq(num, UNINITIALIZED):
757 decoder.setinteriorfield(i, array, num,
758 self.fielddescrs[j])
759 p += 1
760 return array
761
762
763 class VStrPlainInfo(AbstractVirtualInfo):
764 """Stands for the string made out of the characters of all fieldnums."""
765
766 @specialize.argtype(1)
767 def allocate(self, decoder, index):
768 length = len(self.fieldnums)
769 string = decoder.allocate_string(length)
770 decoder.virtuals_cache.set_ptr(index, string)
771 for i in range(length):
772 charnum = self.fieldnums[i]
773 if not tagged_eq(charnum, UNINITIALIZED):
774 decoder.string_setitem(string, i, charnum)
775 return string
776
777 def debug_prints(self):
778 debug_print("\tvstrplaininfo length", len(self.fieldnums), " at ", compute_unique_id(self))
779
780
781 class VStrConcatInfo(AbstractVirtualInfo):
782 """Stands for the string made out of the concatenation of two
783 other strings."""
784
785 @specialize.argtype(1)
786 def allocate(self, decoder, index):
787 # xxx for blackhole resuming, this will build all intermediate
788 # strings and throw them away immediately, which is a bit sub-
789 # efficient. Not sure we care.
790 left, right = self.fieldnums
791 string = decoder.concat_strings(left, right)
792 decoder.virtuals_cache.set_ptr(index, string)
793 return string
794
795 def debug_prints(self):
796 debug_print("\tvstrconcatinfo at ", compute_unique_id(self))
797 for i in self.fieldnums:
798 debug_print("\t\t", str(untag(i)))
799
800
801 class VStrSliceInfo(AbstractVirtualInfo):
802 """Stands for the string made out of slicing another string."""
803
804 @specialize.argtype(1)
805 def allocate(self, decoder, index):
806 largerstr, start, length = self.fieldnums
807 string = decoder.slice_string(largerstr, start, length)
808 decoder.virtuals_cache.set_ptr(index, string)
809 return string
810
811 def debug_prints(self):
812 debug_print("\tvstrsliceinfo at ", compute_unique_id(self))
813 for i in self.fieldnums:
814 debug_print("\t\t", str(untag(i)))
815
816
817 class VUniPlainInfo(AbstractVirtualInfo):
818 """Stands for the unicode string made out of the characters of all
819 fieldnums."""
820
821 @specialize.argtype(1)
822 def allocate(self, decoder, index):
823 length = len(self.fieldnums)
824 string = decoder.allocate_unicode(length)
825 decoder.virtuals_cache.set_ptr(index, string)
826 for i in range(length):
827 charnum = self.fieldnums[i]
828 if not tagged_eq(charnum, UNINITIALIZED):
829 decoder.unicode_setitem(string, i, charnum)
830 return string
831
832 def debug_prints(self):
833 debug_print("\tvuniplaininfo length", len(self.fieldnums), " at ", compute_unique_id(self))
834
835
836 class VUniConcatInfo(AbstractVirtualInfo):
837 """Stands for the unicode string made out of the concatenation of two
838 other unicode strings."""
839
840 @specialize.argtype(1)
841 def allocate(self, decoder, index):
842 # xxx for blackhole resuming, this will build all intermediate
843 # strings and throw them away immediately, which is a bit sub-
844 # efficient. Not sure we care.
845 left, right = self.fieldnums
846 string = decoder.concat_unicodes(left, right)
847 decoder.virtuals_cache.set_ptr(index, string)
848 return string
849
850 def debug_prints(self):
851 debug_print("\tvuniconcatinfo at ", compute_unique_id(self))
852 for i in self.fieldnums:
853 debug_print("\t\t", str(untag(i)))
854
855
856 class VUniSliceInfo(AbstractVirtualInfo):
857 """Stands for the unicode string made out of slicing another
858 unicode string."""
859
860 @specialize.argtype(1)
861 def allocate(self, decoder, index):
862 largerstr, start, length = self.fieldnums
863 string = decoder.slice_unicode(largerstr, start, length)
864 decoder.virtuals_cache.set_ptr(index, string)
865 return string
866
867 def debug_prints(self):
868 debug_print("\tvunisliceinfo at ", compute_unique_id(self))
869 for i in self.fieldnums:
870 debug_print("\t\t", str(untag(i)))
871
872 # ____________________________________________________________
873
874 class AbstractVirtualCache(object):
875 pass
876
877 def get_VirtualCache_class(suffix):
878 # we need to create two copy of this class, because virtuals_*_cache will
879 # be lists of different types (one for ResumeDataDirectReader and one for
880 # ResumeDataBoxReader)
881 class VirtualCache(AbstractVirtualCache):
882 def __init__(self, virtuals_ptr_cache, virtuals_int_cache):
883 self.virtuals_ptr_cache = virtuals_ptr_cache
884 self.virtuals_int_cache = virtuals_int_cache
885
886 def get_ptr(self, i):
887 return self.virtuals_ptr_cache[i]
888
889 def get_int(self, i):
890 return self.virtuals_int_cache[i]
891
892 def set_ptr(self, i, v):
893 self.virtuals_ptr_cache[i] = v
894
895 def set_int(self, i, v):
896 self.virtuals_int_cache[i] = v
897
898 VirtualCache.__name__ += suffix
899 return VirtualCache
900
901 class AbstractResumeDataReader(object):
902 """A base mixin containing the logic to reconstruct virtuals out of
903 guard failure. There are two implementations of this mixin:
904 ResumeDataBoxReader for when we are compiling (i.e. when we have a
905 metainterp), and ResumeDataDirectReader for when we are merely
906 blackholing and want the best performance.
907 """
908 _mixin_ = True
909 rd_virtuals = None
910 virtuals_cache = None
911 virtual_ptr_default = None
912 virtual_int_default = None
913
914
915 def _init(self, metainterp_sd, storage):
916 self.cpu = metainterp_sd.cpu
917 self.metainterp_sd = metainterp_sd
918 self.resumecodereader = resumecode.Reader(storage.rd_numb)
919 items_resume_section = self.resumecodereader.next_item()
920 self.items_resume_section = items_resume_section
921 self.count = self.resumecodereader.next_item()
922 self.consts = storage.rd_consts
923
924 def _prepare(self, storage):
925 self._prepare_virtuals(storage.rd_virtuals)
926 self._prepare_pendingfields(storage.rd_pendingfields)
927
928 def read_jitcode_pos_pc(self):
929 jitcode_pos = self.resumecodereader.next_item()
930 pc = self.resumecodereader.next_item()
931 return jitcode_pos, pc
932
933 def next_int(self):
934 return self.decode_int(self.resumecodereader.next_item())
935
936 def next_ref(self):
937 return self.decode_ref(self.resumecodereader.next_item())
938
939 def next_float(self):
940 return self.decode_float(self.resumecodereader.next_item())
941
942 def done_reading(self):
943 return self.resumecodereader.items_read >= self.items_resume_section
944
945 def getvirtual_ptr(self, index):
946 # Returns the index'th virtual, building it lazily if needed.
947 # Note that this may be called recursively; that's why the
948 # allocate() methods must fill in the cache as soon as they
949 # have the object, before they fill its fields.
950 assert self.virtuals_cache is not None
951 v = self.virtuals_cache.get_ptr(index)
952 if not v:
953 assert self.rd_virtuals is not None
954 v = self.rd_virtuals[index].allocate(self, index)
955 ll_assert(v == self.virtuals_cache.get_ptr(index), "resume.py: bad cache")
956 return v
957
958 def getvirtual_int(self, index):
959 assert self.virtuals_cache is not None
960 v = self.virtuals_cache.get_int(index)
961 if not v:
962 v = self.rd_virtuals[index]
963 ll_assert(bool(v), "resume.py: null rd_virtuals[index]")
964 assert v.is_about_raw and isinstance(v, VAbstractRawInfo)
965 v = v.allocate_int(self, index)
966 ll_assert(v == self.virtuals_cache.get_int(index), "resume.py: bad cache")
967 return v
968
969 def force_all_virtuals(self):
970 rd_virtuals = self.rd_virtuals
971 if rd_virtuals:
972 for i in range(len(rd_virtuals)):
973 rd_virtual = rd_virtuals[i]
974 if rd_virtual is not None:
975 if rd_virtual.kind == REF:
976 self.getvirtual_ptr(i)
977 elif rd_virtual.kind == INT:
978 self.getvirtual_int(i)
979 else:
980 assert False
981 return self.virtuals_cache
982
983 def _prepare_virtuals(self, virtuals):
984 if virtuals:
985 self.rd_virtuals = virtuals
986 # XXX: this is suboptimal, because we are creating two lists, one
987 # for REFs and one for INTs: but for each index, we are using
988 # either one or the other, so we should think of a way to
989 # "compact" them
990 self.virtuals_cache = self.VirtualCache([self.virtual_ptr_default] * len(virtuals),
991 [self.virtual_int_default] * len(virtuals))
992
993 def _prepare_pendingfields(self, pendingfields):
994 if pendingfields:
995 for i in range(len(pendingfields)):
996 lldescr = pendingfields[i].lldescr
997 num = pendingfields[i].num
998 fieldnum = pendingfields[i].fieldnum
999 itemindex = pendingfields[i].itemindex
1000 descr = annlowlevel.cast_base_ptr_to_instance(AbstractDescr,
1001 lldescr)
1002 struct = self.decode_ref(num)
1003 itemindex = rffi.cast(lltype.Signed, itemindex)
1004 if itemindex < 0:
1005 self.setfield(struct, fieldnum, descr)
1006 else:
1007 self.setarrayitem(struct, itemindex, fieldnum, descr)
1008
1009 def setarrayitem(self, array, index, fieldnum, arraydescr):
1010 if arraydescr.is_array_of_pointers():
1011 self.setarrayitem_ref(array, index, fieldnum, arraydescr)
1012 elif arraydescr.is_array_of_floats():
1013 self.setarrayitem_float(array, index, fieldnum, arraydescr)
1014 else:
1015 self.setarrayitem_int(array, index, fieldnum, arraydescr)
1016
1017 def _prepare_next_section(self, info):
1018 from rpython.jit.codewriter.jitcode import enumerate_vars
1019 # Use info.enumerate_vars(), normally dispatching to
1020 # rpython.jit.codewriter.jitcode. Some tests give a different 'info'.
1021 enumerate_vars(info,
1022 self.metainterp_sd.liveness_info,
1023 self._callback_i,
1024 self._callback_r,
1025 self._callback_f,
1026 self.unique_id) # <-- annotation hack
1027
1028 def _callback_i(self, register_index):
1029 value = self.next_int()
1030 self.write_an_int(register_index, value)
1031
1032 def _callback_r(self, register_index):
1033 value = self.next_ref()
1034 self.write_a_ref(register_index, value)
1035
1036 def _callback_f(self, register_index):
1037 value = self.next_float()
1038 self.write_a_float(register_index, value)
1039
1040 # ---------- when resuming for pyjitpl.py, make boxes ----------
1041
1042 def rebuild_from_resumedata(metainterp, storage, deadframe,
1043 virtualizable_info, greenfield_info):
1044 resumereader = ResumeDataBoxReader(storage, deadframe, metainterp)
1045 boxes = resumereader.consume_vref_and_vable_boxes(virtualizable_info,
1046 greenfield_info)
1047 virtualizable_boxes, virtualref_boxes = boxes
1048
1049 while not resumereader.done_reading():
1050 jitcode_pos, pc = resumereader.read_jitcode_pos_pc()
1051 jitcode = metainterp.staticdata.jitcodes[jitcode_pos]
1052 f = metainterp.newframe(jitcode)
1053 f.setup_resume_at_op(pc)
1054 resumereader.consume_boxes(f.get_current_position_info(),
1055 f.registers_i, f.registers_r, f.registers_f)
1056 f.handle_rvmprof_enter_on_resume()
1057 return resumereader.liveboxes, virtualizable_boxes, virtualref_boxes
1058
1059
1060 def get_max_num_inputargs(storage):
1061 reader = resumecode.Reader(storage.rd_numb)
1062 reader.next_item()
1063 return reader.next_item()
1064
1065
1066 class ResumeDataBoxReader(AbstractResumeDataReader):
1067 unique_id = lambda: None
1068 VirtualCache = get_VirtualCache_class('BoxReader')
1069
1070 def __init__(self, storage, deadframe, metainterp):
1071 self._init(metainterp.staticdata, storage)
1072 self.deadframe = deadframe
1073 self.metainterp = metainterp
1074 self.liveboxes = [None] * self.count
1075 self._prepare(storage)
1076
1077 def consume_boxes(self, info, boxes_i, boxes_r, boxes_f):
1078 self.boxes_i = boxes_i
1079 self.boxes_r = boxes_r
1080 self.boxes_f = boxes_f
1081 self._prepare_next_section(info)
1082
1083 def consume_virtualizable_boxes(self, vinfo, vable_size):
1084 # we have to ignore the initial part of 'nums' (containing vrefs),
1085 # find the virtualizable from nums[-1], and use it to know how many
1086 # boxes of which type we have to return. This does not write
1087 # anything into the virtualizable.
1088 virtualizablebox = self.next_ref()
1089 virtualizable = vinfo.unwrap_virtualizable_box(virtualizablebox)
1090 assert vinfo.get_total_size(virtualizable) == vable_size - 1
1091 return vinfo.load_list_of_boxes(virtualizable, self, virtualizablebox)
1092
1093 def consume_virtualref_boxes(self):
1094 # Returns a list of boxes, assumed to be all BoxPtrs.
1095 # We leave up to the caller to call vrefinfo.continue_tracing().
1096 size = self.resumecodereader.next_item()
1097 return [self.next_ref() for i in range(size * 2)]
1098
1099 def consume_vref_and_vable_boxes(self, vinfo, ginfo):
1100 vable_size = self.resumecodereader.next_item()
1101 if vinfo is not None:
1102 assert vable_size
1103 virtualizable_boxes = self.consume_virtualizable_boxes(vinfo, vable_size)
1104 elif ginfo is not None:
1105 virtualizable_boxes = [self.next_ref()]
1106 else:
1107 virtualizable_boxes = None
1108 virtualref_boxes = self.consume_virtualref_boxes()
1109 return virtualizable_boxes, virtualref_boxes
1110
1111 def allocate_with_vtable(self, descr=None):
1112 return self.metainterp.execute_new_with_vtable(descr=descr)
1113
1114 def allocate_struct(self, typedescr):
1115 return self.metainterp.execute_new(typedescr)
1116
1117 def allocate_array(self, length, arraydescr, clear):
1118 lengthbox = ConstInt(length)
1119 if clear:
1120 return self.metainterp.execute_new_array_clear(arraydescr,
1121 lengthbox)
1122 return self.metainterp.execute_new_array(arraydescr, lengthbox)
1123
1124 def allocate_raw_buffer(self, func, size):
1125 cic = self.metainterp.staticdata.callinfocollection
1126 calldescr, _ = cic.callinfo_for_oopspec(EffectInfo.OS_RAW_MALLOC_VARSIZE_CHAR)
1127 # Can't use 'func' from callinfo_for_oopspec(), because we have
1128 # several variants (zero/non-zero, memory-pressure or not, etc.)
1129 # and we have to pick the correct one here; that's why we save
1130 # it in the VRawBufferInfo.
1131 return self.metainterp.execute_and_record_varargs(
1132 rop.CALL_I, [ConstInt(func), ConstInt(size)], calldescr)
1133
1134 def allocate_string(self, length):
1135 return self.metainterp.execute_and_record(rop.NEWSTR,
1136 None, ConstInt(length))
1137
1138 def string_setitem(self, strbox, index, charnum):
1139 charbox = self.decode_box(charnum, INT)
1140 self.metainterp.execute_and_record(rop.STRSETITEM, None,
1141 strbox, ConstInt(index), charbox)
1142
1143 def concat_strings(self, str1num, str2num):
1144 cic = self.metainterp.staticdata.callinfocollection
1145 calldescr, func = cic.callinfo_for_oopspec(EffectInfo.OS_STR_CONCAT)
1146 str1box = self.decode_box(str1num, REF)
1147 str2box = self.decode_box(str2num, REF)
1148 return self.metainterp.execute_and_record_varargs(
1149 rop.CALL_R, [ConstInt(func), str1box, str2box], calldescr)
1150
1151 def slice_string(self, strnum, startnum, lengthnum):
1152 cic = self.metainterp.staticdata.callinfocollection
1153 calldescr, func = cic.callinfo_for_oopspec(EffectInfo.OS_STR_SLICE)
1154 strbox = self.decode_box(strnum, REF)
1155 startbox = self.decode_box(startnum, INT)
1156 lengthbox = self.decode_box(lengthnum, INT)
1157 stopbox = self.metainterp.execute_and_record(rop.INT_ADD, None,
1158 startbox, lengthbox)
1159 return self.metainterp.execute_and_record_varargs(
1160 rop.CALL_R, [ConstInt(func), strbox, startbox, stopbox], calldescr)
1161
1162 def allocate_unicode(self, length):
1163 return self.metainterp.execute_and_record(rop.NEWUNICODE,
1164 None, ConstInt(length))
1165
1166 def unicode_setitem(self, strbox, index, charnum):
1167 charbox = self.decode_box(charnum, INT)
1168 self.metainterp.execute_and_record(rop.UNICODESETITEM, None,
1169 strbox, ConstInt(index), charbox)
1170
1171 def concat_unicodes(self, str1num, str2num):
1172 cic = self.metainterp.staticdata.callinfocollection
1173 calldescr, func = cic.callinfo_for_oopspec(EffectInfo.OS_UNI_CONCAT)
1174 str1box = self.decode_box(str1num, REF)
1175 str2box = self.decode_box(str2num, REF)
1176 return self.metainterp.execute_and_record_varargs(
1177 rop.CALL_R, [ConstInt(func), str1box, str2box], calldescr)
1178
1179 def slice_unicode(self, strnum, startnum, lengthnum):
1180 cic = self.metainterp.staticdata.callinfocollection
1181 calldescr, func = cic.callinfo_for_oopspec(EffectInfo.OS_UNI_SLICE)
1182 strbox = self.decode_box(strnum, REF)
1183 startbox = self.decode_box(startnum, INT)
1184 lengthbox = self.decode_box(lengthnum, INT)
1185 stopbox = self.metainterp.execute_and_record(rop.INT_ADD, None,
1186 startbox, lengthbox)
1187 return self.metainterp.execute_and_record_varargs(
1188 rop.CALL_R, [ConstInt(func), strbox, startbox, stopbox], calldescr)
1189
1190 def setfield(self, structbox, fieldnum, descr):
1191 if descr.is_pointer_field():
1192 kind = REF
1193 elif descr.is_float_field():
1194 kind = FLOAT
1195 else:
1196 kind = INT
1197 fieldbox = self.decode_box(fieldnum, kind)
1198 self.metainterp.execute_setfield_gc(descr, structbox, fieldbox)
1199
1200 def setinteriorfield(self, index, array, fieldnum, descr):
1201 if descr.is_pointer_field():
1202 kind = REF
1203 elif descr.is_float_field():
1204 kind = FLOAT
1205 else:
1206 kind = INT
1207 fieldbox = self.decode_box(fieldnum, kind)
1208 self.metainterp.execute_setinteriorfield_gc(descr, array,
1209 ConstInt(index), fieldbox)
1210
1211 def setarrayitem_int(self, arraybox, index, fieldnum, arraydescr):
1212 self._setarrayitem(arraybox, index, fieldnum, arraydescr, INT)
1213
1214 def setarrayitem_ref(self, arraybox, index, fieldnum, arraydescr):
1215 self._setarrayitem(arraybox, index, fieldnum, arraydescr, REF)
1216
1217 def setarrayitem_float(self, arraybox, index, fieldnum, arraydescr):
1218 self._setarrayitem(arraybox, index, fieldnum, arraydescr, FLOAT)
1219
1220 def _setarrayitem(self, arraybox, index, fieldnum, arraydescr, kind):
1221 itembox = self.decode_box(fieldnum, kind)
1222 self.metainterp.execute_setarrayitem_gc(arraydescr, arraybox,
1223 ConstInt(index), itembox)
1224
1225 def setrawbuffer_item(self, bufferbox, fieldnum, offset, arraydescr):
1226 if arraydescr.is_array_of_pointers():
1227 kind = REF
1228 elif arraydescr.is_array_of_floats():
1229 kind = FLOAT
1230 else:
1231 kind = INT
1232 itembox = self.decode_box(fieldnum, kind)
1233 self.metainterp.execute_raw_store(arraydescr, bufferbox,
1234 ConstInt(offset), itembox)
1235
1236 def decode_int(self, tagged):
1237 return self.decode_box(tagged, INT)
1238
1239 def decode_ref(self, tagged):
1240 return self.decode_box(tagged, REF)
1241
1242 def decode_float(self, tagged):
1243 return self.decode_box(tagged, FLOAT)
1244
1245 def decode_box(self, tagged, kind):
1246 num, tag = untag(tagged)
1247 if tag == TAGCONST:
1248 if tagged_eq(tagged, NULLREF):
1249 box = CONST_NULL
1250 else:
1251 box = self.consts[num - TAG_CONST_OFFSET]
1252 elif tag == TAGVIRTUAL:
1253 if kind == INT:
1254 box = self.getvirtual_int(num)
1255 else:
1256 box = self.getvirtual_ptr(num)
1257 elif tag == TAGINT:
1258 box = ConstInt(num)
1259 else:
1260 assert tag == TAGBOX
1261 box = self.liveboxes[num]
1262 if box is None:
1263 box = self.load_box_from_cpu(num, kind)
1264 assert box.type == kind
1265 return box
1266
1267 def load_box_from_cpu(self, num, kind):
1268 if num < 0:
1269 num += len(self.liveboxes)
1270 assert num >= 0
1271 # we create *FrontendOp instances with numbers in the range
1272 # 0..self.count
1273 if kind == INT:
1274 box = IntFrontendOp(num, self.cpu.get_int_value(self.deadframe, num))
1275 elif kind == REF:
1276 box = RefFrontendOp(num, self.cpu.get_ref_value(self.deadframe, num))
1277 elif kind == FLOAT:
1278 box = FloatFrontendOp(num, self.cpu.get_float_value(self.deadframe, num))
1279 else:
1280 assert 0, "bad kind: %d" % ord(kind)
1281 self.liveboxes[num] = box
1282 return box
1283
1284 def next_box_of_type(self, TYPE):
1285 kind = getkind(TYPE)
1286 if kind == 'int':
1287 kind = INT
1288 elif kind == 'ref':
1289 kind = REF
1290 elif kind == 'float':
1291 kind = FLOAT
1292 else:
1293 raise AssertionError(kind)
1294 return self.decode_box(self.resumecodereader.next_item(), kind)
1295 next_box_of_type._annspecialcase_ = 'specialize:arg(1)'
1296
1297 def write_an_int(self, index, box):
1298 self.boxes_i[index] = box
1299
1300 def write_a_ref(self, index, box):
1301 self.boxes_r[index] = box
1302
1303 def write_a_float(self, index, box):
1304 self.boxes_f[index] = box
1305
1306 def int_add_const(self, intbox, offset):
1307 return self.metainterp.execute_and_record(rop.INT_ADD, None, intbox,
1308 ConstInt(offset))
1309
1310 # ---------- when resuming for blackholing, get direct values ----------
1311
1312 def blackhole_from_resumedata(blackholeinterpbuilder, jitcodes,
1313 jitdriver_sd, storage,
1314 deadframe, all_virtuals=None):
1315 # The initialization is stack-critical code: it must not be interrupted by
1316 # StackOverflow, otherwise the jit_virtual_refs are left in a dangling state.
1317 metainterp_sd = blackholeinterpbuilder.metainterp_sd
1318 rstack._stack_criticalcode_start()
1319 try:
1320 resumereader = ResumeDataDirectReader(metainterp_sd,
1321 storage, deadframe, all_virtuals)
1322 vinfo = jitdriver_sd.virtualizable_info
1323 ginfo = jitdriver_sd.greenfield_info
1324 vrefinfo = metainterp_sd.virtualref_info
1325 resumereader.consume_vref_and_vable(vrefinfo, vinfo, ginfo)
1326 finally:
1327 rstack._stack_criticalcode_stop()
1328 #
1329 # First get a chain of blackhole interpreters whose length is given
1330 # by the positions in the numbering. The first one we get must be
1331 # the bottom one, i.e. the last one in the chain, in order to make
1332 # the comment in BlackholeInterpreter.setposition() valid.
1333 curbh = None
1334 while not resumereader.done_reading():
1335 nextbh = blackholeinterpbuilder.acquire_interp()
1336 nextbh.nextblackholeinterp = curbh
1337 curbh = nextbh
1338 jitcode_pos, pc = resumereader.read_jitcode_pos_pc()
1339 jitcode = jitcodes[jitcode_pos]
1340 curbh.setposition(jitcode, pc)
1341 resumereader.consume_one_section(curbh)
1342 curbh.handle_rvmprof_enter()
1343 return curbh
1344
1345 def force_from_resumedata(metainterp_sd, storage, deadframe, vinfo, ginfo):
1346 metainterp_sd.profiler.count(jitprof.Counters.FORCE_VIRTUALIZABLES)
1347 resumereader = ResumeDataDirectReader(metainterp_sd, storage, deadframe)
1348 resumereader.handling_async_forcing()
1349 vrefinfo = metainterp_sd.virtualref_info
1350 resumereader.consume_vref_and_vable(vrefinfo, vinfo, ginfo)
1351 return resumereader.force_all_virtuals()
1352
1353
1354 class ResumeDataDirectReader(AbstractResumeDataReader):
1355 unique_id = lambda: None
1356 virtual_ptr_default = lltype.nullptr(llmemory.GCREF.TO)
1357 virtual_int_default = 0
1358 resume_after_guard_not_forced = 0
1359 VirtualCache = get_VirtualCache_class('DirectReader')
1360 # 0: not a GUARD_NOT_FORCED
1361 # 1: in handle_async_forcing
1362 # 2: resuming from the GUARD_NOT_FORCED
1363
1364 def __init__(self, metainterp_sd, storage, deadframe, all_virtuals=None):
1365 self._init(metainterp_sd, storage)
1366 self.deadframe = deadframe
1367 self.callinfocollection = metainterp_sd.callinfocollection
1368 if all_virtuals is None: # common case
1369 self._prepare(storage)
1370 else:
1371 # special case for resuming after a GUARD_NOT_FORCED: we already
1372 # have the virtuals
1373 self.resume_after_guard_not_forced = 2
1374 self.virtuals_cache = all_virtuals
1375 # self.rd_virtuals can remain None, because virtuals_cache is
1376 # already filled
1377
1378 def handling_async_forcing(self):
1379 self.resume_after_guard_not_forced = 1
1380
1381 def consume_one_section(self, blackholeinterp):
1382 self.blackholeinterp = blackholeinterp
1383 info = blackholeinterp.get_current_position_info()
1384 self._prepare_next_section(info)
1385
1386 def consume_virtualref_info(self, vrefinfo):
1387 # we have to decode a list of references containing pairs
1388 # [..., virtual, vref, ...] and returns the index at the end
1389 size = self.resumecodereader.next_item()
1390 if vrefinfo is None or size == 0:
1391 assert size == 0
1392 return
1393 for i in range(size):
1394 virtual = self.next_ref()
1395 vref = self.next_ref()
1396 # For each pair, we store the virtual inside the vref.
1397 vrefinfo.continue_tracing(vref, virtual)
1398
1399 def consume_vable_info(self, vinfo, vable_size):
1400 # we have to ignore the initial part of 'nums' (containing vrefs),
1401 # find the virtualizable from nums[-1], load all other values
1402 # from the CPU stack, and copy them into the virtualizable
1403 assert vable_size
1404 virtualizable = self.next_ref()
1405 # just reset the token, we'll force it later
1406 assert vinfo.get_total_size(virtualizable) == vable_size - 1
1407 vinfo.reset_token_gcref(virtualizable)
1408 vinfo.write_from_resume_data_partial(virtualizable, self)
1409
1410 def load_next_value_of_type(self, TYPE):
1411 from rpython.jit.metainterp.warmstate import specialize_value
1412 kind = getkind(TYPE)
1413 if kind == 'int':
1414 x = self.next_int()
1415 elif kind == 'ref':
1416 x = self.next_ref()
1417 elif kind == 'float':
1418 x = self.next_float()
1419 else:
1420 raise AssertionError(kind)
1421 return specialize_value(TYPE, x)
1422 load_next_value_of_type._annspecialcase_ = 'specialize:arg(1)'
1423
1424 def consume_vref_and_vable(self, vrefinfo, vinfo, ginfo):
1425 vable_size = self.resumecodereader.next_item()
1426 if self.resume_after_guard_not_forced != 2:
1427 if vinfo is not None:
1428 self.consume_vable_info(vinfo, vable_size)
1429 if ginfo is not None:
1430 _ = self.resumecodereader.next_item()
1431 self.consume_virtualref_info(vrefinfo)
1432 else:
1433 self.resumecodereader.jump(vable_size)
1434 vref_size = self.resumecodereader.next_item()
1435 self.resumecodereader.jump(vref_size * 2)
1436
1437 def allocate_with_vtable(self, descr=None):
1438 from rpython.jit.metainterp.executor import exec_new_with_vtable
1439 return exec_new_with_vtable(self.cpu, descr)
1440
1441 def allocate_struct(self, typedescr):
1442 return self.cpu.bh_new(typedescr)
1443
1444 def allocate_array(self, length, arraydescr, clear):
1445 if clear:
1446 return self.cpu.bh_new_array_clear(length, arraydescr)
1447 return self.cpu.bh_new_array(length, arraydescr)
1448
1449 def allocate_string(self, length):
1450 return self.cpu.bh_newstr(length)
1451
1452 def allocate_raw_buffer(self, func, size):
1453 from rpython.jit.codewriter import heaptracker
1454 cic = self.callinfocollection
1455 calldescr, _ = cic.callinfo_for_oopspec(EffectInfo.OS_RAW_MALLOC_VARSIZE_CHAR)
1456 return self.cpu.bh_call_i(func, [size], None, None, calldescr)
1457
1458 def string_setitem(self, str, index, charnum):
1459 char = self.decode_int(charnum)
1460 self.cpu.bh_strsetitem(str, index, char)
1461
1462 def concat_strings(self, str1num, str2num):
1463 str1 = self.decode_ref(str1num)
1464 str2 = self.decode_ref(str2num)
1465 str1 = lltype.cast_opaque_ptr(lltype.Ptr(rstr.STR), str1)
1466 str2 = lltype.cast_opaque_ptr(lltype.Ptr(rstr.STR), str2)
1467 cic = self.callinfocollection
1468 funcptr = cic.funcptr_for_oopspec(EffectInfo.OS_STR_CONCAT)
1469 result = funcptr(str1, str2)
1470 return lltype.cast_opaque_ptr(llmemory.GCREF, result)
1471
1472 def slice_string(self, strnum, startnum, lengthnum):
1473 str = self.decode_ref(strnum)
1474 start = self.decode_int(startnum)
1475 length = self.decode_int(lengthnum)
1476 str = lltype.cast_opaque_ptr(lltype.Ptr(rstr.STR), str)
1477 cic = self.callinfocollection
1478 funcptr = cic.funcptr_for_oopspec(EffectInfo.OS_STR_SLICE)
1479 result = funcptr(str, start, start + length)
1480 return lltype.cast_opaque_ptr(llmemory.GCREF, result)
1481
1482 def allocate_unicode(self, length):
1483 return self.cpu.bh_newunicode(length)
1484
1485 def unicode_setitem(self, str, index, charnum):
1486 char = self.decode_int(charnum)
1487 self.cpu.bh_unicodesetitem(str, index, char)
1488
1489 def concat_unicodes(self, str1num, str2num):
1490 str1 = self.decode_ref(str1num)
1491 str2 = self.decode_ref(str2num)
1492 str1 = lltype.cast_opaque_ptr(lltype.Ptr(rstr.UNICODE), str1)
1493 str2 = lltype.cast_opaque_ptr(lltype.Ptr(rstr.UNICODE), str2)
1494 cic = self.callinfocollection
1495 funcptr = cic.funcptr_for_oopspec(EffectInfo.OS_UNI_CONCAT)
1496 result = funcptr(str1, str2)
1497 return lltype.cast_opaque_ptr(llmemory.GCREF, result)
1498
1499 def slice_unicode(self, strnum, startnum, lengthnum):
1500 str = self.decode_ref(strnum)
1501 start = self.decode_int(startnum)
1502 length = self.decode_int(lengthnum)
1503 str = lltype.cast_opaque_ptr(lltype.Ptr(rstr.UNICODE), str)
1504 cic = self.callinfocollection
1505 funcptr = cic.funcptr_for_oopspec(EffectInfo.OS_UNI_SLICE)
1506 result = funcptr(str, start, start + length)
1507 return lltype.cast_opaque_ptr(llmemory.GCREF, result)
1508
1509 def setfield(self, struct, fieldnum, descr):
1510 if descr.is_pointer_field():
1511 newvalue = self.decode_ref(fieldnum)
1512 self.cpu.bh_setfield_gc_r(struct, newvalue, descr)
1513 elif descr.is_float_field():
1514 newvalue = self.decode_float(fieldnum)
1515 self.cpu.bh_setfield_gc_f(struct, newvalue, descr)
1516 else:
1517 newvalue = self.decode_int(fieldnum)
1518 self.cpu.bh_setfield_gc_i(struct, newvalue, descr)
1519
1520 def setinteriorfield(self, index, array, fieldnum, descr):
1521 if descr.is_pointer_field():
1522 newvalue = self.decode_ref(fieldnum)
1523 self.cpu.bh_setinteriorfield_gc_r(array, index, newvalue, descr)
1524 elif descr.is_float_field():
1525 newvalue = self.decode_float(fieldnum)
1526 self.cpu.bh_setinteriorfield_gc_f(array, index, newvalue, descr)
1527 else:
1528 newvalue = self.decode_int(fieldnum)
1529 self.cpu.bh_setinteriorfield_gc_i(array, index, newvalue, descr)
1530
1531 def setarrayitem_int(self, array, index, fieldnum, arraydescr):
1532 newvalue = self.decode_int(fieldnum)
1533 self.cpu.bh_setarrayitem_gc_i(array, index, newvalue, arraydescr)
1534
1535 def setarrayitem_ref(self, array, index, fieldnum, arraydescr):
1536 newvalue = self.decode_ref(fieldnum)
1537 self.cpu.bh_setarrayitem_gc_r(array, index, newvalue, arraydescr)
1538
1539 def setarrayitem_float(self, array, index, fieldnum, arraydescr):
1540 newvalue = self.decode_float(fieldnum)
1541 self.cpu.bh_setarrayitem_gc_f(array, index, newvalue, arraydescr)
1542
1543 def setrawbuffer_item(self, buffer, fieldnum, offset, descr):
1544 assert not descr.is_array_of_pointers()
1545 if descr.is_array_of_floats():
1546 newvalue = self.decode_float(fieldnum)
1547 self.cpu.bh_raw_store_f(buffer, offset, newvalue, descr)
1548 else:
1549 newvalue = self.decode_int(fieldnum)
1550 self.cpu.bh_raw_store_i(buffer, offset, newvalue, descr)
1551
1552 def decode_int(self, tagged):
1553 num, tag = untag(tagged)
1554 if tag == TAGCONST:
1555 return self.consts[num - TAG_CONST_OFFSET].getint()
1556 elif tag == TAGINT:
1557 return num
1558 elif tag == TAGVIRTUAL:
1559 return self.getvirtual_int(num)
1560 else:
1561 assert tag == TAGBOX
1562 if num < 0:
1563 num += self.count
1564 return self.cpu.get_int_value(self.deadframe, num)
1565
1566 def decode_ref(self, tagged):
1567 num, tag = untag(tagged)
1568 if tag == TAGCONST:
1569 if tagged_eq(tagged, NULLREF):
1570 return ConstPtr.value
1571 return self.consts[num - TAG_CONST_OFFSET].getref_base()
1572 elif tag == TAGVIRTUAL:
1573 return self.getvirtual_ptr(num)
1574 else:
1575 assert tag == TAGBOX
1576 if num < 0:
1577 num += self.count
1578 return self.cpu.get_ref_value(self.deadframe, num)
1579
1580 def decode_float(self, tagged):
1581 num, tag = untag(tagged)
1582 if tag == TAGCONST:
1583 return self.consts[num - TAG_CONST_OFFSET].getfloatstorage()
1584 else:
1585 assert tag == TAGBOX
1586 if num < 0:
1587 num += self.count
1588 return self.cpu.get_float_value(self.deadframe, num)
1589
1590 def write_an_int(self, index, int):
1591 self.blackholeinterp.setarg_i(index, int)
1592
1593 def write_a_ref(self, index, ref):
1594 self.blackholeinterp.setarg_r(index, ref)
1595
1596 def write_a_float(self, index, float):
1597 self.blackholeinterp.setarg_f(index, float)
1598
1599 def int_add_const(self, base, offset):
1600 return base + offset