Debian Codegraph @

rpython/jit/backend/llsupport/gc.py

raw symbols SCIP
1 import os
2 from rpython.rlib import rgc
3 from rpython.rlib.objectmodel import we_are_translated, specialize
4 from rpython.rlib.rarithmetic import ovfcheck
5 from rpython.rtyper.lltypesystem import lltype, llmemory, rffi, rstr
6 from rpython.rtyper import rclass
7 from rpython.rtyper.lltypesystem import llgroup
8 from rpython.rtyper.lltypesystem.lloperation import llop
9 from rpython.rtyper.annlowlevel import llhelper, cast_instance_to_gcref
10 from rpython.translator.tool.cbuild import ExternalCompilationInfo
11 from rpython.jit.codewriter import heaptracker
12 from rpython.jit.metainterp.history import ConstPtr, AbstractDescr, ConstInt
13 from rpython.jit.metainterp.resoperation import rop, ResOperation
14 from rpython.jit.metainterp.support import ptr2int
15 from rpython.jit.backend.llsupport import symbolic, jitframe
16 from rpython.jit.backend.llsupport.symbolic import WORD
17 from rpython.jit.backend.llsupport.memcpy import memcpy_fn
18 from rpython.jit.backend.llsupport.descr import SizeDescr, ArrayDescr, FieldDescr
19 from rpython.jit.backend.llsupport.descr import GcCache, get_field_descr
20 from rpython.jit.backend.llsupport.descr import get_array_descr
21 from rpython.jit.backend.llsupport.descr import get_call_descr
22 from rpython.jit.backend.llsupport.descr import unpack_arraydescr
23 from rpython.jit.backend.llsupport.rewrite import GcRewriterAssembler
24 from rpython.jit.codewriter.effectinfo import EffectInfo
25
26 # ____________________________________________________________
27
28 class GcLLDescription(GcCache):
29
30 def __init__(self, gcdescr, translator=None, rtyper=None):
31 GcCache.__init__(self, translator is not None, rtyper)
32 self.gcdescr = gcdescr
33 if translator and translator.config.translation.gcremovetypeptr:
34 self.fielddescr_vtable = None
35 else:
36 self.fielddescr_vtable = get_field_descr(self, rclass.OBJECT,
37 'typeptr')
38 self._generated_functions = []
39 self.memcpy_fn = memcpy_fn
40 self.memcpy_descr = get_call_descr(self,
41 [lltype.Signed, lltype.Signed, lltype.Signed], lltype.Void,
42 EffectInfo([], [], [], [], [], [], EffectInfo.EF_CANNOT_RAISE,
43 can_collect=False))
44
45 def _setup_str(self):
46 self.str_descr = get_array_descr(self, rstr.STR)
47 self.unicode_descr = get_array_descr(self, rstr.UNICODE)
48 self.str_hash_descr = get_field_descr(self, rstr.STR, 'hash')
49 self.unicode_hash_descr = get_field_descr(self, rstr.UNICODE, 'hash')
50
51 def generate_function(self, funcname, func, ARGS, RESULT=llmemory.GCREF):
52 """Generates a variant of malloc with the given name and the given
53 arguments. It should return NULL if out of memory. If it raises
54 anything, it must be an optional MemoryError.
55 """
56 FUNCPTR = lltype.Ptr(lltype.FuncType(ARGS, RESULT))
57 # Note: the call may invoke the GC, which may run finalizers.
58 # Finalizers are constrained in what they can do, but we can't
59 # really express that in a useful way here.
60 descr = get_call_descr(self, ARGS, RESULT, EffectInfo.MOST_GENERAL)
61 setattr(self, funcname, func)
62 setattr(self, funcname + '_FUNCPTR', FUNCPTR)
63 setattr(self, funcname + '_descr', descr)
64 self._generated_functions.append(funcname)
65
66 @specialize.arg(1)
67 def get_malloc_fn(self, funcname):
68 func = getattr(self, funcname)
69 FUNC = getattr(self, funcname + '_FUNCPTR')
70 return llhelper(FUNC, func)
71
72 @specialize.arg(1)
73 def get_malloc_fn_addr(self, funcname):
74 ll_func = self.get_malloc_fn(funcname)
75 return ptr2int(ll_func)
76
77 def _freeze_(self):
78 return True
79 def initialize(self):
80 pass
81 def can_use_nursery_malloc(self, size):
82 return False
83 def has_write_barrier_class(self):
84 return None
85 def get_nursery_free_addr(self):
86 raise NotImplementedError
87 def get_nursery_top_addr(self):
88 raise NotImplementedError
89
90 def freeing_block(self, rawstart, rawstop):
91 pass
92
93 def gc_malloc(self, sizedescr):
94 """Blackhole: do a 'bh_new'. Also used for 'bh_new_with_vtable',
95 with the vtable pointer set manually afterwards."""
96 assert isinstance(sizedescr, SizeDescr)
97 return self._bh_malloc(sizedescr)
98
99 def gc_malloc_array(self, num_elem, arraydescr):
100 assert isinstance(arraydescr, ArrayDescr)
101 return self._bh_malloc_array(num_elem, arraydescr)
102
103 def gc_malloc_str(self, num_elem):
104 return self._bh_malloc_array(num_elem, self.str_descr)
105
106 def gc_malloc_unicode(self, num_elem):
107 return self._bh_malloc_array(num_elem, self.unicode_descr)
108
109 def rewrite_assembler(self, cpu, operations, gcrefs_output_list):
110 rewriter = GcRewriterAssembler(self, cpu, len(operations))
111 newops = rewriter.rewrite(operations, gcrefs_output_list)
112 return newops
113
114 @specialize.memo()
115 def getframedescrs(self, cpu):
116 descrs = JitFrameDescrs()
117 descrs.arraydescr = cpu.arraydescrof(jitframe.JITFRAME)
118 for name in ['jf_descr', 'jf_guard_exc', 'jf_force_descr',
119 'jf_frame_info', 'jf_gcmap',
120 'jf_savedata', 'jf_forward']:
121 setattr(descrs, name, cpu.fielddescrof(jitframe.JITFRAME, name))
122 descrs.jfi_frame_size = cpu.fielddescrof(jitframe.JITFRAMEINFO,
123 'jfi_frame_size')
124 descrs.jfi_frame_depth = cpu.fielddescrof(jitframe.JITFRAMEINFO,
125 'jfi_frame_depth')
126 return descrs
127
128 def getarraydescr_for_frame(self, type):
129 """ This functions retuns an arraydescr of type for the JITFRAME"""
130 raise NotImplementedError
131
132 def malloc_jitframe(self, frame_info):
133 """ Allocate a new frame, overwritten by tests
134 """
135 return jitframe.JITFRAME.allocate(frame_info)
136
137 def make_gcref_tracer(self, array_base_addr, gcrefs):
138 # for tests, or for Boehm. Overridden for framework GCs
139 from rpython.jit.backend.llsupport import gcreftracer
140 return gcreftracer.make_boehm_tracer(array_base_addr, gcrefs)
141
142 def clear_gcref_tracer(self, tracer):
143 pass # nothing needed unless overridden
144
145 class JitFrameDescrs:
146 def _freeze_(self):
147 return True
148
149 # ____________________________________________________________
150
151 class GcLLDescr_boehm(GcLLDescription):
152 kind = 'boehm'
153 malloc_zero_filled = True
154 moving_gc = False
155 round_up = False
156 write_barrier_descr = None
157 fielddescr_tid = None
158 gcrootmap = None
159 str_type_id = 0
160 unicode_type_id = 0
161 get_malloc_slowpath_addr = None
162 supports_guard_gc_type = False
163
164 def is_shadow_stack(self):
165 return False
166
167 @classmethod
168 def configure_boehm_once(cls):
169 """ Configure boehm only once, since we don't cache failures
170 """
171 if hasattr(cls, 'malloc_fn_ptr'):
172 return cls.malloc_fn_ptr
173 from rpython.rtyper.tool import rffi_platform
174 compilation_info = rffi_platform.configure_boehm()
175
176 # on some platform GC_init is required before any other
177 # GC_* functions, call it here for the benefit of tests
178 # XXX move this to tests
179 init_fn_ptr = rffi.llexternal("GC_init",
180 [], lltype.Void,
181 compilation_info=compilation_info,
182 sandboxsafe=True,
183 _nowrapper=True)
184 init_fn_ptr()
185
186 # Versions 6.x of libgc needs to use GC_local_malloc().
187 # Versions 7.x of libgc removed this function; GC_malloc() has
188 # the same behavior if libgc was compiled with
189 # THREAD_LOCAL_ALLOC.
190 class CConfig:
191 _compilation_info_ = compilation_info
192 HAS_LOCAL_MALLOC = rffi_platform.Has("GC_local_malloc")
193 config = rffi_platform.configure(CConfig)
194 if config['HAS_LOCAL_MALLOC']:
195 GC_MALLOC = "GC_local_malloc"
196 else:
197 GC_MALLOC = "GC_malloc"
198 malloc_fn_ptr = rffi.llexternal(GC_MALLOC,
199 [lltype.Signed], # size_t, but good enough
200 llmemory.GCREF,
201 compilation_info=compilation_info,
202 sandboxsafe=True,
203 _nowrapper=True)
204 cls.malloc_fn_ptr = malloc_fn_ptr
205 return malloc_fn_ptr
206
207 def __init__(self, gcdescr, translator, rtyper):
208 GcLLDescription.__init__(self, gcdescr, translator, rtyper)
209 # grab a pointer to the Boehm 'malloc' function
210 self.malloc_fn_ptr = self.configure_boehm_once()
211 self._setup_str()
212 self._make_functions()
213 self.memory = 0
214
215 def _make_functions(self):
216
217 def malloc_fixedsize(size):
218 return self.malloc_fn_ptr(size)
219 self.generate_function('malloc_fixedsize', malloc_fixedsize,
220 [lltype.Signed])
221
222 def malloc_array(basesize, num_elem, itemsize, ofs_length):
223 try:
224 totalsize = ovfcheck(basesize + ovfcheck(itemsize * num_elem))
225 except OverflowError:
226 return lltype.nullptr(llmemory.GCREF.TO)
227 res = self.malloc_fn_ptr(totalsize)
228 if res:
229 arrayptr = rffi.cast(rffi.CArrayPtr(lltype.Signed), res)
230 arrayptr[ofs_length/WORD] = num_elem
231 return res
232 self.generate_function('malloc_array', malloc_array,
233 [lltype.Signed] * 4)
234
235 def _bh_malloc(self, sizedescr):
236 return self.malloc_fixedsize(sizedescr.size)
237
238 def _bh_malloc_array(self, num_elem, arraydescr):
239 return self.malloc_array(arraydescr.basesize, num_elem,
240 arraydescr.itemsize,
241 arraydescr.lendescr.offset)
242
243 # ____________________________________________________________
244 # All code below is for the hybrid or minimark GC
245
246 class GcRootMap_shadowstack(object):
247 is_shadow_stack = True
248
249 def __init__(self, gcdescr):
250 pass
251
252 def register_asm_addr(self, start, mark):
253 pass
254
255 def get_root_stack_top_addr(self):
256 rst_addr = llop.gc_adr_of_root_stack_top(llmemory.Address)
257 return rffi.cast(lltype.Signed, rst_addr)
258
259 class WriteBarrierDescr(AbstractDescr):
260 def __init__(self, gc_ll_descr):
261 self.llop1 = gc_ll_descr.llop1
262 self.WB_FUNCPTR = gc_ll_descr.WB_FUNCPTR
263 self.fielddescr_tid = gc_ll_descr.fielddescr_tid
264 #
265 GCClass = gc_ll_descr.GCClass
266 if GCClass is None: # for tests
267 return
268 self.jit_wb_if_flag = GCClass.JIT_WB_IF_FLAG
269 self.jit_wb_if_flag_byteofs, self.jit_wb_if_flag_singlebyte = (
270 self.extract_flag_byte(self.jit_wb_if_flag))
271 #
272 if hasattr(GCClass, 'JIT_WB_CARDS_SET'):
273 self.jit_wb_cards_set = GCClass.JIT_WB_CARDS_SET
274 self.jit_wb_card_page_shift = GCClass.JIT_WB_CARD_PAGE_SHIFT
275 self.jit_wb_cards_set_byteofs, self.jit_wb_cards_set_singlebyte = (
276 self.extract_flag_byte(self.jit_wb_cards_set))
277 #
278 # the x86 backend uses the following "accidental" facts to
279 # avoid one instruction:
280 assert self.jit_wb_cards_set_byteofs == self.jit_wb_if_flag_byteofs
281 assert self.jit_wb_cards_set_singlebyte == -0x80
282 else:
283 self.jit_wb_cards_set = 0
284
285 def extract_flag_byte(self, flag_word):
286 # if convenient for the backend, we compute the info about
287 # the flag as (byte-offset, single-byte-flag).
288 import struct
289 value = struct.pack(lltype.SignedFmt, flag_word)
290 assert value.count('\x00') == len(value) - 1 # only one byte is != 0
291 i = 0
292 while value[i] == '\x00': i += 1
293 return (i, struct.unpack('b', value[i])[0])
294
295 def get_write_barrier_fn(self, cpu):
296 llop1 = self.llop1
297 funcptr = llop1.get_write_barrier_failing_case(self.WB_FUNCPTR)
298 funcaddr = llmemory.cast_ptr_to_adr(funcptr)
299 return cpu.cast_adr_to_int(funcaddr)
300
301 def get_write_barrier_from_array_fn(self, cpu):
302 # returns a function with arguments [array, index, newvalue]
303 llop1 = self.llop1
304 funcptr = llop1.get_write_barrier_from_array_failing_case(
305 self.WB_FUNCPTR)
306 funcaddr = llmemory.cast_ptr_to_adr(funcptr)
307 return cpu.cast_adr_to_int(funcaddr) # this may return 0
308
309 def has_write_barrier_from_array(self, cpu):
310 return self.get_write_barrier_from_array_fn(cpu) != 0
311
312
313 class GcLLDescr_framework(GcLLDescription):
314 DEBUG = False # forced to True by x86/test/test_zrpy_gc.py
315 kind = 'framework'
316 round_up = True
317 layoutbuilder = None
318 supports_guard_gc_type = True
319
320 def is_shadow_stack(self):
321 return self.gcrootmap.is_shadow_stack
322
323 def __init__(self, gcdescr, translator, rtyper, llop1=llop,
324 really_not_translated=False):
325 GcLLDescription.__init__(self, gcdescr, translator, rtyper)
326 self.translator = translator
327 self.llop1 = llop1
328 if really_not_translated:
329 assert not self.translate_support_code # but half does not work
330 self._initialize_for_tests()
331 else:
332 assert self.translate_support_code,"required with the framework GC"
333 self._check_valid_gc()
334 self._make_layoutbuilder()
335 self._make_gcrootmap()
336 self._setup_gcclass()
337 self._setup_tid()
338 self._setup_guard_is_object()
339 self._setup_write_barrier()
340 self._setup_str()
341 self._make_functions(really_not_translated)
342
343 def _make_gcrootmap(self):
344 # to find roots in the assembler, make a GcRootMap
345 name = self.gcdescr.config.translation.gcrootfinder
346 try:
347 cls = globals()['GcRootMap_' + name]
348 except KeyError:
349 raise NotImplementedError("--gcrootfinder=%s not implemented"
350 " with the JIT" % (name,))
351 gcrootmap = cls(self.gcdescr)
352 self.gcrootmap = gcrootmap
353
354 def _initialize_for_tests(self):
355 self.layoutbuilder = None
356 self.fielddescr_tid = FieldDescr("test_tid",0,8,0)
357 self.max_size_of_young_obj = 1000
358 self.GCClass = None
359
360 def _check_valid_gc(self):
361 # we need the hybrid or minimark GC for rgc._make_sure_does_not_move()
362 # to work. 'hybrid' could work but isn't tested with the JIT.
363 if self.gcdescr.config.translation.gc not in ('minimark',
364 'incminimark'):
365 raise NotImplementedError("--gc=%s not implemented with the JIT" %
366 (self.gcdescr.config.translation.gc,))
367
368 def _make_layoutbuilder(self):
369 # make a TransformerLayoutBuilder and save it on the translator
370 # where it can be fished and reused by the FrameworkGCTransformer
371 from rpython.memory.gctransform import framework
372 translator = self.translator
373 self.layoutbuilder = framework.TransformerLayoutBuilder(translator)
374 self.layoutbuilder.delay_encoding()
375 if not hasattr(translator, '_jit2gc'):
376 translator._jit2gc = {}
377 translator._jit2gc['layoutbuilder'] = self.layoutbuilder
378
379 def _setup_gcclass(self):
380 from rpython.memory.gcheader import GCHeaderBuilder
381 self.GCClass = self.layoutbuilder.GCClass
382 self.moving_gc = self.GCClass.moving_gc
383 self.malloc_zero_filled = self.GCClass.malloc_zero_filled
384 self.HDRPTR = lltype.Ptr(self.GCClass.HDR)
385 self.gcheaderbuilder = GCHeaderBuilder(self.HDRPTR.TO)
386 self.max_size_of_young_obj = self.GCClass.JIT_max_size_of_young_obj()
387 self.minimal_size_in_nursery=self.GCClass.JIT_minimal_size_in_nursery()
388
389 # for the fast path of mallocs, the following must be true, at least
390 assert self.GCClass.inline_simple_malloc
391 assert self.GCClass.inline_simple_malloc_varsize
392
393 def _setup_tid(self):
394 self.fielddescr_tid = get_field_descr(self, self.GCClass.HDR, 'tid')
395 frame_tid = self.layoutbuilder.get_type_id(jitframe.JITFRAME)
396 self.translator._jit2gc['frame_tid'] = frame_tid
397
398 def _setup_write_barrier(self):
399 self.WB_FUNCPTR = lltype.Ptr(lltype.FuncType(
400 [llmemory.Address], lltype.Void))
401 self.write_barrier_descr = WriteBarrierDescr(self)
402
403 def _make_functions(self, really_not_translated):
404 from rpython.memory.gctypelayout import check_typeid
405 llop1 = self.llop1
406 (self.standard_array_basesize, _, self.standard_array_length_ofs) = \
407 symbolic.get_array_token(lltype.GcArray(lltype.Signed),
408 not really_not_translated)
409
410 def malloc_nursery_slowpath(size):
411 """Allocate 'size' null bytes out of the nursery.
412 Note that the fast path is typically inlined by the backend."""
413 assert size >= self.minimal_size_in_nursery
414 if self.DEBUG:
415 self._random_usage_of_xmm_registers()
416 type_id = rffi.cast(llgroup.HALFWORD, 0) # missing here
417 return llop1.do_malloc_fixedsize(llmemory.GCREF,
418 type_id, size,
419 False, False, False)
420
421 self.generate_function('malloc_nursery', malloc_nursery_slowpath,
422 [lltype.Signed])
423
424 def malloc_array(itemsize, tid, num_elem):
425 """Allocate an array with a variable-size num_elem.
426 Only works for standard arrays."""
427 assert num_elem >= 0, 'num_elem should be >= 0'
428 type_id = llop.extract_ushort(llgroup.HALFWORD, tid)
429 check_typeid(type_id)
430 return llop1.do_malloc_varsize_clear(
431 llmemory.GCREF,
432 type_id, num_elem, self.standard_array_basesize, itemsize,
433 self.standard_array_length_ofs)
434 self.generate_function('malloc_array', malloc_array,
435 [lltype.Signed] * 3)
436
437 def malloc_array_nonstandard(basesize, itemsize, lengthofs, tid,
438 num_elem):
439 """For the rare case of non-standard arrays, i.e. arrays where
440 self.standard_array_{basesize,length_ofs} is wrong. It can
441 occur e.g. with arrays of floats on Win32."""
442 type_id = llop.extract_ushort(llgroup.HALFWORD, tid)
443 check_typeid(type_id)
444 return llop1.do_malloc_varsize_clear(
445 llmemory.GCREF,
446 type_id, num_elem, basesize, itemsize, lengthofs)
447 self.generate_function('malloc_array_nonstandard',
448 malloc_array_nonstandard,
449 [lltype.Signed] * 5)
450
451 str_type_id = self.str_descr.tid
452 str_basesize = self.str_descr.basesize
453 str_itemsize = self.str_descr.itemsize
454 str_ofs_length = self.str_descr.lendescr.offset
455 unicode_type_id = self.unicode_descr.tid
456 unicode_basesize = self.unicode_descr.basesize
457 unicode_itemsize = self.unicode_descr.itemsize
458 unicode_ofs_length = self.unicode_descr.lendescr.offset
459
460 def malloc_str(length):
461 type_id = llop.extract_ushort(llgroup.HALFWORD, str_type_id)
462 return llop1.do_malloc_varsize(
463 llmemory.GCREF,
464 type_id, length, str_basesize, str_itemsize,
465 str_ofs_length)
466 self.generate_function('malloc_str', malloc_str,
467 [lltype.Signed])
468
469 def malloc_unicode(length):
470 type_id = llop.extract_ushort(llgroup.HALFWORD, unicode_type_id)
471 return llop1.do_malloc_varsize(
472 llmemory.GCREF,
473 type_id, length, unicode_basesize, unicode_itemsize,
474 unicode_ofs_length)
475 self.generate_function('malloc_unicode', malloc_unicode,
476 [lltype.Signed])
477
478 # Never called as far as I can tell, but there for completeness:
479 # allocate a fixed-size object, but not in the nursery, because
480 # it is too big.
481 def malloc_big_fixedsize(size, tid):
482 if self.DEBUG:
483 self._random_usage_of_xmm_registers()
484 type_id = llop.extract_ushort(llgroup.HALFWORD, tid)
485 check_typeid(type_id)
486 return llop1.do_malloc_fixedsize_clear(llmemory.GCREF,
487 type_id, size,
488 False, False, False)
489 self.generate_function('malloc_big_fixedsize', malloc_big_fixedsize,
490 [lltype.Signed] * 2)
491
492 def _bh_malloc(self, sizedescr):
493 from rpython.memory.gctypelayout import check_typeid
494 llop1 = self.llop1
495 type_id = llop.extract_ushort(llgroup.HALFWORD, sizedescr.tid)
496 check_typeid(type_id)
497 return llop1.do_malloc_fixedsize_clear(llmemory.GCREF,
498 type_id, sizedescr.size,
499 False, False, False)
500
501 def _bh_malloc_array(self, num_elem, arraydescr):
502 from rpython.memory.gctypelayout import check_typeid
503 llop1 = self.llop1
504 type_id = llop.extract_ushort(llgroup.HALFWORD, arraydescr.tid)
505 check_typeid(type_id)
506 return llop1.do_malloc_varsize_clear(llmemory.GCREF,
507 type_id, num_elem,
508 arraydescr.basesize,
509 arraydescr.itemsize,
510 arraydescr.lendescr.offset)
511
512
513 class ForTestOnly:
514 pass
515 for_test_only = ForTestOnly()
516 for_test_only.x = 1.23
517
518 def _random_usage_of_xmm_registers(self):
519 x0 = self.for_test_only.x
520 x1 = x0 * 0.1
521 x2 = x0 * 0.2
522 x3 = x0 * 0.3
523 self.for_test_only.x = x0 + x1 + x2 + x3
524
525 def get_nursery_free_addr(self):
526 nurs_addr = llop.gc_adr_of_nursery_free(llmemory.Address)
527 return rffi.cast(lltype.Signed, nurs_addr)
528
529 def get_nursery_top_addr(self):
530 nurs_top_addr = llop.gc_adr_of_nursery_top(llmemory.Address)
531 return rffi.cast(lltype.Signed, nurs_top_addr)
532
533 def initialize(self):
534 pass
535 #self.gcrootmap.initialize()
536
537 def init_size_descr(self, S, descr):
538 if not isinstance(S, lltype.GcStruct):
539 return
540 if self.layoutbuilder is not None:
541 type_id = self.layoutbuilder.get_type_id(S)
542 descr.tid = llop.combine_ushort(lltype.Signed, type_id, 0)
543
544 def init_array_descr(self, A, descr):
545 if not isinstance(A, (lltype.GcArray, lltype.GcStruct)):
546 return
547 if self.layoutbuilder is not None:
548 type_id = self.layoutbuilder.get_type_id(A)
549 descr.tid = llop.combine_ushort(lltype.Signed, type_id, 0)
550
551 def can_use_nursery_malloc(self, size):
552 return size < self.max_size_of_young_obj
553
554 def has_write_barrier_class(self):
555 return WriteBarrierDescr
556
557 def get_malloc_slowpath_addr(self):
558 return self.get_malloc_fn_addr('malloc_nursery')
559
560 def get_malloc_slowpath_array_addr(self):
561 return self.get_malloc_fn_addr('malloc_array')
562
563 def get_typeid_from_classptr_if_gcremovetypeptr(self, classptr):
564 """Returns the typeid corresponding from a vtable pointer 'classptr'.
565 This function only works if cpu.vtable_offset is None, i.e. in
566 a translation with --gcremovetypeptr.
567 """
568 from rpython.memory.gctypelayout import GCData
569 assert self.gcdescr.config.translation.gcremovetypeptr
570
571 # hard-coded assumption: to go from an object to its class
572 # we would use the following algorithm:
573 # - read the typeid from mem(locs[0]), i.e. at offset 0;
574 # this is a complete word (N=4 bytes on 32-bit, N=8 on
575 # 64-bits)
576 # - keep the lower half of what is read there (i.e.
577 # truncate to an unsigned 'N / 2' bytes value)
578 # - multiply by 4 (on 32-bits only) and use it as an
579 # offset in type_info_group
580 # - add 16/32 bytes, to go past the TYPE_INFO structure
581 # here, we have to go back from 'classptr' back to the typeid,
582 # so we do (part of) these computations in reverse.
583
584 sizeof_ti = rffi.sizeof(GCData.TYPE_INFO)
585 type_info_group = llop.gc_get_type_info_group(llmemory.Address)
586 type_info_group = rffi.cast(lltype.Signed, type_info_group)
587 expected_typeid = classptr - sizeof_ti - type_info_group
588 if WORD == 4:
589 expected_typeid >>= 2
590 return expected_typeid
591
592 def get_translated_info_for_typeinfo(self):
593 from rpython.memory.gctypelayout import GCData
594 type_info_group = llop.gc_get_type_info_group(llmemory.Address)
595 type_info_group = rffi.cast(lltype.Signed, type_info_group)
596 if WORD == 4:
597 shift_by = 2
598 elif WORD == 8:
599 shift_by = 0
600 sizeof_ti = rffi.sizeof(GCData.TYPE_INFO)
601 return (type_info_group, shift_by, sizeof_ti)
602
603 def _setup_guard_is_object(self):
604 from rpython.memory.gctypelayout import GCData, T_IS_RPYTHON_INSTANCE
605 import struct
606 infobits_offset, _ = symbolic.get_field_token(GCData.TYPE_INFO,
607 'infobits', True)
608 # compute the offset to the actual *byte*, and the byte mask
609 mask = struct.pack("l", T_IS_RPYTHON_INSTANCE)
610 assert mask.count('\x00') == len(mask) - 1
611 infobits_offset_plus = 0
612 while mask.startswith('\x00'):
613 infobits_offset_plus += 1
614 mask = mask[1:]
615 self._infobits_offset = infobits_offset
616 self._infobits_offset_plus = infobits_offset_plus
617 self._T_IS_RPYTHON_INSTANCE_BYTE = ord(mask[0])
618
619 def get_translated_info_for_guard_is_object(self):
620 infobits_offset = rffi.cast(lltype.Signed, self._infobits_offset)
621 infobits_offset += self._infobits_offset_plus
622 return (infobits_offset, self._T_IS_RPYTHON_INSTANCE_BYTE)
623
624 def get_actual_typeid(self, gcptr):
625 # Read the whole GC header word. Return the typeid from the
626 # lower half-word.
627 hdr = rffi.cast(self.HDRPTR, gcptr)
628 type_id = llop.extract_ushort(llgroup.HALFWORD, hdr.tid)
629 return llop.combine_ushort(lltype.Signed, type_id, 0)
630
631 def check_is_object(self, gcptr):
632 # read the typeid, fetch one byte of the field 'infobits' from
633 # the big typeinfo table, and check the flag 'T_IS_RPYTHON_INSTANCE'.
634 typeid = self.get_actual_typeid(gcptr)
635 #
636 base_type_info, shift_by, sizeof_ti = (
637 self.get_translated_info_for_typeinfo())
638 infobits_offset, IS_OBJECT_FLAG = (
639 self.get_translated_info_for_guard_is_object())
640 p = base_type_info + (typeid << shift_by) + infobits_offset
641 p = rffi.cast(rffi.CCHARP, p)
642 return (ord(p[0]) & IS_OBJECT_FLAG) != 0
643
644 def make_gcref_tracer(self, array_base_addr, gcrefs):
645 from rpython.jit.backend.llsupport import gcreftracer
646 return gcreftracer.make_framework_tracer(array_base_addr, gcrefs)
647
648 def clear_gcref_tracer(self, tracer):
649 tracer.array_length = 0
650
651 # ____________________________________________________________
652
653 def get_ll_description(gcdescr, translator=None, rtyper=None):
654 # translator is None if translate_support_code is False.
655 if gcdescr is not None:
656 name = gcdescr.config.translation.gctransformer
657 else:
658 name = "boehm"
659 try:
660 cls = globals()['GcLLDescr_' + name]
661 except KeyError:
662 raise NotImplementedError("GC transformer %r not supported by "
663 "the JIT backend" % (name,))
664 return cls(gcdescr, translator, rtyper)