Debian Codegraph @

rpython/jit/codewriter/effectinfo.py

raw symbols SCIP
1 import sys
2 from rpython.rtyper.rclass import OBJECT
3 from rpython.rtyper.lltypesystem import lltype, llmemory
4 from rpython.translator.backendopt.graphanalyze import BoolGraphAnalyzer
5 from rpython.tool.algo import bitstring
6 from rpython.jit.metainterp.support import int2adr
7
8
9 class UnsupportedFieldExc(Exception):
10 pass
11
12
13 class EffectInfo(object):
14 _cache = {}
15
16 # the 'extraeffect' field is one of the following values:
17 EF_ELIDABLE_CANNOT_RAISE = 0 #elidable function (and cannot raise)
18 EF_LOOPINVARIANT = 1 #special: call it only once per loop
19 EF_CANNOT_RAISE = 2 #a function which cannot raise
20 EF_ELIDABLE_OR_MEMORYERROR = 3 #elidable, can only raise MemoryError
21 EF_ELIDABLE_CAN_RAISE = 4 #elidable function (but can raise)
22 EF_CAN_RAISE = 5 #normal function (can raise)
23 EF_FORCES_VIRTUAL_OR_VIRTUALIZABLE = 6 #can raise and force virtualizables
24 EF_RANDOM_EFFECTS = 7 #can do whatever
25
26 # the 'oopspecindex' field is one of the following values:
27 OS_NONE = 0 # normal case, no oopspec
28 OS_ARRAYCOPY = 1 # "list.ll_arraycopy"
29 OS_STR2UNICODE = 2 # "str.str2unicode"
30 OS_SHRINK_ARRAY = 3 # rgc.ll_shrink_array
31 OS_DICT_LOOKUP = 4 # ll_dict_lookup
32 OS_THREADLOCALREF_GET = 5 # llop.threadlocalref_get
33 OS_NOT_IN_TRACE = 8 # for calls not recorded in the jit trace
34 OS_ARRAYMOVE = 9 # "list.ll_arraymove"
35 #
36 OS_INT_PY_DIV = 12 # python signed division (neg. corrected)
37 OS_INT_UDIV = 13 # regular unsigned division
38 OS_INT_PY_MOD = 14 # python signed modulo (neg. corrected)
39 OS_INT_UMOD = 15 # regular unsigned modulo
40 #
41 OS_STR_CONCAT = 22 # "stroruni.concat"
42 OS_STR_SLICE = 23 # "stroruni.slice"
43 OS_STR_EQUAL = 24 # "stroruni.equal"
44 OS_STREQ_SLICE_CHECKNULL = 25 # s2!=NULL and s1[x:x+length]==s2
45 OS_STREQ_SLICE_NONNULL = 26 # s1[x:x+length]==s2 (assert s2!=NULL)
46 OS_STREQ_SLICE_CHAR = 27 # s1[x:x+length]==char
47 OS_STREQ_NONNULL = 28 # s1 == s2 (assert s1!=NULL,s2!=NULL)
48 OS_STREQ_NONNULL_CHAR = 29 # s1 == char (assert s1!=NULL)
49 OS_STREQ_CHECKNULL_CHAR = 30 # s1!=NULL and s1==char
50 OS_STREQ_LENGTHOK = 31 # s1 == s2 (assert len(s1)==len(s2))
51 OS_STR_CMP = 32 # "stroruni.cmp"
52 #
53 OS_UNI_CONCAT = 42 #
54 OS_UNI_SLICE = 43 #
55 OS_UNI_EQUAL = 44 #
56 OS_UNIEQ_SLICE_CHECKNULL = 45 #
57 OS_UNIEQ_SLICE_NONNULL = 46 #
58 OS_UNIEQ_SLICE_CHAR = 47 #
59 OS_UNIEQ_NONNULL = 48 # the same for unicode
60 OS_UNIEQ_NONNULL_CHAR = 49 # (must be the same amount as for
61 OS_UNIEQ_CHECKNULL_CHAR = 50 # STR, in the same order)
62 OS_UNIEQ_LENGTHOK = 51 #
63 OS_UNI_CMP = 52
64 _OS_offset_uni = OS_UNI_CONCAT - OS_STR_CONCAT
65 #
66 OS_LIBFFI_CALL = 62
67 #
68 OS_LLONG_INVERT = 69
69 OS_LLONG_ADD = 70
70 OS_LLONG_SUB = 71
71 OS_LLONG_MUL = 72
72 OS_LLONG_LT = 73
73 OS_LLONG_LE = 74
74 OS_LLONG_EQ = 75
75 OS_LLONG_NE = 76
76 OS_LLONG_GT = 77
77 OS_LLONG_GE = 78
78 OS_LLONG_AND = 79
79 OS_LLONG_OR = 80
80 OS_LLONG_LSHIFT = 81
81 OS_LLONG_RSHIFT = 82
82 OS_LLONG_XOR = 83
83 OS_LLONG_FROM_INT = 84
84 OS_LLONG_TO_INT = 85
85 OS_LLONG_FROM_FLOAT = 86
86 OS_LLONG_TO_FLOAT = 87
87 OS_LLONG_ULT = 88
88 OS_LLONG_ULE = 89
89 OS_LLONG_UGT = 90
90 OS_LLONG_UGE = 91
91 OS_LLONG_URSHIFT = 92
92 OS_LLONG_FROM_UINT = 93
93 OS_LLONG_U_TO_FLOAT = 94
94 #
95 OS_MATH_SQRT = 100
96 OS_MATH_READ_TIMESTAMP = 101
97 #
98 OS_RAW_MALLOC_VARSIZE_CHAR = 110
99 OS_RAW_FREE = 111
100 #
101 OS_STR_COPY_TO_RAW = 112
102 OS_UNI_COPY_TO_RAW = 113
103
104 OS_JIT_FORCE_VIRTUAL = 120
105 OS_JIT_FORCE_VIRTUALIZABLE = 121
106
107 # for debugging:
108 _OS_CANRAISE = set([
109 OS_NONE, OS_STR2UNICODE, OS_LIBFFI_CALL, OS_RAW_MALLOC_VARSIZE_CHAR,
110 OS_JIT_FORCE_VIRTUAL, OS_SHRINK_ARRAY, OS_DICT_LOOKUP,
111 OS_NOT_IN_TRACE,
112 ])
113
114 _NO_CALL_RELEASE_GIL_TARGET = (llmemory.NULL, 0)
115
116 def __new__(cls, readonly_descrs_fields, readonly_descrs_arrays,
117 readonly_descrs_interiorfields,
118 write_descrs_fields, write_descrs_arrays,
119 write_descrs_interiorfields,
120 extraeffect=EF_CAN_RAISE,
121 oopspecindex=OS_NONE,
122 can_invalidate=False,
123 call_release_gil_target=_NO_CALL_RELEASE_GIL_TARGET,
124 extradescrs=None,
125 can_collect=True):
126 readonly_descrs_fields = frozenset_or_none(readonly_descrs_fields)
127 readonly_descrs_arrays = frozenset_or_none(readonly_descrs_arrays)
128 readonly_descrs_interiorfields = frozenset_or_none(
129 readonly_descrs_interiorfields)
130 write_descrs_fields = frozenset_or_none(write_descrs_fields)
131 write_descrs_arrays = frozenset_or_none(write_descrs_arrays)
132 write_descrs_interiorfields = frozenset_or_none(
133 write_descrs_interiorfields)
134 key = (readonly_descrs_fields,
135 readonly_descrs_arrays,
136 readonly_descrs_interiorfields,
137 write_descrs_fields,
138 write_descrs_arrays,
139 write_descrs_interiorfields,
140 extraeffect,
141 oopspecindex,
142 can_invalidate,
143 can_collect)
144 tgt_func, tgt_saveerr = call_release_gil_target
145 if tgt_func:
146 key += (object(),) # don't care about caching in this case
147 if key in cls._cache:
148 return cls._cache[key]
149 if extraeffect == EffectInfo.EF_RANDOM_EFFECTS:
150 assert readonly_descrs_fields is None
151 assert readonly_descrs_arrays is None
152 assert readonly_descrs_interiorfields is None
153 assert write_descrs_fields is None
154 assert write_descrs_arrays is None
155 assert write_descrs_interiorfields is None
156 else:
157 assert readonly_descrs_fields is not None
158 assert readonly_descrs_arrays is not None
159 assert readonly_descrs_interiorfields is not None
160 assert write_descrs_fields is not None
161 assert write_descrs_arrays is not None
162 assert write_descrs_interiorfields is not None
163 result = object.__new__(cls)
164 # the frozensets "._readonly_xxx" and "._write_xxx" should not be
165 # translated.
166 result._readonly_descrs_fields = readonly_descrs_fields
167 result._readonly_descrs_arrays = readonly_descrs_arrays
168 result._readonly_descrs_interiorfields = readonly_descrs_interiorfields
169 if extraeffect == EffectInfo.EF_LOOPINVARIANT or \
170 extraeffect == EffectInfo.EF_ELIDABLE_CANNOT_RAISE or \
171 extraeffect == EffectInfo.EF_ELIDABLE_OR_MEMORYERROR or \
172 extraeffect == EffectInfo.EF_ELIDABLE_CAN_RAISE:
173 # Ignore the writes. Note that this ignores also writes with
174 # no corresponding reads (rarely the case, but possible).
175 result._write_descrs_fields = frozenset()
176 result._write_descrs_arrays = frozenset()
177 result._write_descrs_interiorfields = frozenset()
178 else:
179 result._write_descrs_fields = write_descrs_fields
180 result._write_descrs_arrays = write_descrs_arrays
181 result._write_descrs_interiorfields = write_descrs_interiorfields
182 # initialized later, in compute_bitstrings()
183 # (the goal of this is to make sure we don't build new EffectInfo
184 # instances after compute_bitstrings() is called)
185 result.bitstring_readonly_descrs_fields = Ellipsis
186 result.bitstring_readonly_descrs_arrays = Ellipsis
187 result.bitstring_readonly_descrs_interiorfields = Ellipsis
188 result.bitstring_write_descrs_fields = Ellipsis
189 result.bitstring_write_descrs_arrays = Ellipsis
190 result.bitstring_write_descrs_interiorfields = Ellipsis
191 #
192 result.extraeffect = extraeffect
193 result.can_invalidate = can_invalidate
194 result.can_collect = can_collect
195 result.oopspecindex = oopspecindex
196 result.extradescrs = extradescrs
197 result.call_release_gil_target = call_release_gil_target
198 if result.check_can_raise(ignore_memoryerror=True):
199 assert oopspecindex in cls._OS_CANRAISE
200
201 if (result._write_descrs_arrays is not None and
202 len(result._write_descrs_arrays) == 1):
203 # this is used only for ARRAYCOPY/ARRAYMOVE operations
204 [result.single_write_descr_array] = result._write_descrs_arrays
205 else:
206 result.single_write_descr_array = None
207
208 cls._cache[key] = result
209 return result
210
211 def check_readonly_descr_field(self, fielddescr):
212 return bitstring.bitcheck(self.bitstring_readonly_descrs_fields,
213 fielddescr.get_ei_index())
214 def check_write_descr_field(self, fielddescr):
215 return bitstring.bitcheck(self.bitstring_write_descrs_fields,
216 fielddescr.get_ei_index())
217 def check_readonly_descr_array(self, arraydescr):
218 return bitstring.bitcheck(self.bitstring_readonly_descrs_arrays,
219 arraydescr.get_ei_index())
220 def check_write_descr_array(self, arraydescr):
221 return bitstring.bitcheck(self.bitstring_write_descrs_arrays,
222 arraydescr.get_ei_index())
223 def check_readonly_descr_interiorfield(self, interiorfielddescr):
224 # NOTE: this is not used so far
225 return bitstring.bitcheck(self.bitstring_readonly_descrs_interiorfields,
226 interiorfielddescr.get_ei_index())
227 def check_write_descr_interiorfield(self, interiorfielddescr):
228 # NOTE: this is not used so far
229 return bitstring.bitcheck(self.bitstring_write_descrs_interiorfields,
230 interiorfielddescr.get_ei_index())
231
232 def check_can_raise(self, ignore_memoryerror=False):
233 if ignore_memoryerror:
234 return self.extraeffect > self.EF_ELIDABLE_OR_MEMORYERROR
235 else:
236 return self.extraeffect > self.EF_CANNOT_RAISE
237
238 def check_can_invalidate(self):
239 return self.can_invalidate
240
241 def check_can_collect(self):
242 return self.can_collect
243
244 def check_is_elidable(self):
245 return (self.extraeffect == self.EF_ELIDABLE_CAN_RAISE or
246 self.extraeffect == self.EF_ELIDABLE_OR_MEMORYERROR or
247 self.extraeffect == self.EF_ELIDABLE_CANNOT_RAISE)
248
249 def check_forces_virtual_or_virtualizable(self):
250 return self.extraeffect >= self.EF_FORCES_VIRTUAL_OR_VIRTUALIZABLE
251
252 def has_random_effects(self):
253 return self.extraeffect >= self.EF_RANDOM_EFFECTS
254
255 def is_call_release_gil(self):
256 tgt_func, tgt_saveerr = self.call_release_gil_target
257 return bool(tgt_func)
258
259 def __repr__(self):
260 more = ''
261 if self.oopspecindex:
262 more = ' OS=%r' % (self.oopspecindex,)
263 return '<EffectInfo 0x%x: EF=%r%s>' % (id(self), self.extraeffect, more)
264
265
266 def frozenset_or_none(x):
267 if x is None:
268 return None
269 return frozenset(x)
270
271 EffectInfo.MOST_GENERAL = EffectInfo(None, None, None, None, None, None,
272 EffectInfo.EF_RANDOM_EFFECTS,
273 can_invalidate=True)
274
275
276 def effectinfo_from_writeanalyze(effects, cpu,
277 extraeffect=EffectInfo.EF_CAN_RAISE,
278 oopspecindex=EffectInfo.OS_NONE,
279 can_invalidate=False,
280 call_release_gil_target=
281 EffectInfo._NO_CALL_RELEASE_GIL_TARGET,
282 extradescr=None,
283 can_collect=True):
284 from rpython.translator.backendopt.writeanalyze import top_set
285 if effects is top_set or extraeffect == EffectInfo.EF_RANDOM_EFFECTS:
286 readonly_descrs_fields = None
287 readonly_descrs_arrays = None
288 readonly_descrs_interiorfields = None
289 write_descrs_fields = None
290 write_descrs_arrays = None
291 write_descrs_interiorfields = None
292 extraeffect = EffectInfo.EF_RANDOM_EFFECTS
293 else:
294 readonly_descrs_fields = []
295 readonly_descrs_arrays = []
296 readonly_descrs_interiorfields = []
297 write_descrs_fields = []
298 write_descrs_arrays = []
299 write_descrs_interiorfields = []
300
301 def add_struct(descrs_fields, (_, T, fieldname)):
302 T = T.TO
303 if consider_struct(T, fieldname):
304 descr = cpu.fielddescrof(T, fieldname)
305 descrs_fields.append(descr)
306
307 def add_array(descrs_arrays, (_, T)):
308 ARRAY = T.TO
309 if consider_array(ARRAY):
310 descr = cpu.arraydescrof(ARRAY)
311 descrs_arrays.append(descr)
312
313 def add_interiorfield(descrs_interiorfields, (_, T, fieldname)):
314 T = T.TO
315 if not isinstance(T, lltype.Array):
316 return # let's not consider structs for now
317 if not consider_array(T):
318 return
319 if getattr(T.OF, fieldname) is lltype.Void:
320 return
321 try:
322 descr = cpu.interiorfielddescrof(T, fieldname)
323 except UnsupportedFieldExc:
324 return
325 descrs_interiorfields.append(descr)
326
327 # a read or a write to an interiorfield, inside an array of
328 # structs, is additionally recorded as a read or write of
329 # the array itself
330 extraef = list()
331 for tup in effects:
332 if tup[0] == "interiorfield" or tup[0] == "readinteriorfield":
333 T = tup[1].TO
334 if isinstance(T, lltype.Array) and consider_array(T):
335 val = (tup[0].replace("interiorfield", "array"),
336 tup[1])
337 if val not in effects:
338 extraef.append(val)
339 # preserve order in the added effects issue #2984
340 effects = tuple(effects) + tuple(extraef)
341
342 for tup in effects:
343 if tup[0] == "struct":
344 add_struct(write_descrs_fields, tup)
345 elif tup[0] == "readstruct":
346 tupw = ("struct",) + tup[1:]
347 if tupw not in effects:
348 add_struct(readonly_descrs_fields, tup)
349 elif tup[0] == "interiorfield":
350 add_interiorfield(write_descrs_interiorfields, tup)
351 elif tup[0] == "readinteriorfield":
352 tupw = ('interiorfield',) + tup[1:]
353 if tupw not in effects:
354 add_interiorfield(readonly_descrs_interiorfields, tup)
355 elif tup[0] == "array":
356 add_array(write_descrs_arrays, tup)
357 elif tup[0] == "readarray":
358 tupw = ("array",) + tup[1:]
359 if tupw not in effects:
360 add_array(readonly_descrs_arrays, tup)
361 else:
362 assert 0
363 #
364 if extraeffect >= EffectInfo.EF_FORCES_VIRTUAL_OR_VIRTUALIZABLE:
365 can_collect = True
366 #
367 return EffectInfo(readonly_descrs_fields,
368 readonly_descrs_arrays,
369 readonly_descrs_interiorfields,
370 write_descrs_fields,
371 write_descrs_arrays,
372 write_descrs_interiorfields,
373 extraeffect,
374 oopspecindex,
375 can_invalidate,
376 call_release_gil_target,
377 extradescr,
378 can_collect)
379
380 def consider_struct(TYPE, fieldname):
381 if getattr(TYPE, fieldname) is lltype.Void:
382 return False
383 if not isinstance(TYPE, lltype.GcStruct): # can be a non-GC-struct
384 return False
385 if fieldname == "typeptr" and TYPE is OBJECT:
386 # filter out the typeptr, because
387 # a) it is optimized in different ways
388 # b) it might not be there in C if removetypeptr is specified
389 return False
390 return True
391
392 def consider_array(ARRAY):
393 if ARRAY.OF is lltype.Void:
394 return False
395 if not isinstance(ARRAY, lltype.GcArray): # can be a non-GC-array
396 return False
397 return True
398
399 # ____________________________________________________________
400
401 class VirtualizableAnalyzer(BoolGraphAnalyzer):
402 def analyze_simple_operation(self, op, graphinfo):
403 return op.opname in ('jit_force_virtualizable',
404 'jit_force_virtual')
405
406 class QuasiImmutAnalyzer(BoolGraphAnalyzer):
407 def analyze_simple_operation(self, op, graphinfo):
408 return op.opname == 'jit_force_quasi_immutable'
409
410 class RandomEffectsAnalyzer(BoolGraphAnalyzer):
411 def analyze_external_call(self, funcobj, seen=None):
412 if funcobj.random_effects_on_gcobjs:
413 return True
414 return super(RandomEffectsAnalyzer, self).analyze_external_call(
415 funcobj, seen)
416
417 def analyze_simple_operation(self, op, graphinfo):
418 return False
419
420 # ____________________________________________________________
421
422 class CallInfoCollection(object):
423 def __init__(self):
424 # {oopspecindex: (calldescr, func_as_int)}
425 self._callinfo_for_oopspec = {}
426
427 def _freeze_(self):
428 return True
429
430 def add(self, oopspecindex, calldescr, func_as_int):
431 self._callinfo_for_oopspec[oopspecindex] = calldescr, func_as_int
432
433 def has_oopspec(self, oopspecindex):
434 return oopspecindex in self._callinfo_for_oopspec
435
436 def all_function_addresses_as_int(self):
437 return [func for (_, func) in self._callinfo_for_oopspec.values()]
438
439 def callinfo_for_oopspec(self, oopspecindex):
440 """A function that returns the calldescr and the function
441 address (as an int) of one of the OS_XYZ functions defined above.
442 Don't use this if there might be several implementations of the same
443 OS_XYZ specialized by type, e.g. OS_ARRAYCOPY."""
444 try:
445 return self._callinfo_for_oopspec[oopspecindex]
446 except KeyError:
447 return (None, 0)
448
449 def _funcptr_for_oopspec_memo(self, oopspecindex):
450 _, func_as_int = self.callinfo_for_oopspec(oopspecindex)
451 funcadr = int2adr(func_as_int)
452 return funcadr.ptr
453 _funcptr_for_oopspec_memo._annspecialcase_ = 'specialize:memo'
454
455 def funcptr_for_oopspec(self, oopspecindex):
456 """A memo function that returns a pointer to the function described
457 by OS_XYZ (as a real low-level function pointer)."""
458 funcptr = self._funcptr_for_oopspec_memo(oopspecindex)
459 assert funcptr
460 return funcptr
461 funcptr_for_oopspec._annspecialcase_ = 'specialize:arg(1)'
462
463 # ____________________________________________________________
464
465 def compute_bitstrings(all_descrs):
466 # Compute the bitstrings in the EffectInfo,
467 # bitstring_{readonly,write}_descrs_{fieldd,arrays,interiordescrs},
468 # and for each FieldDescrs and ArrayDescrs compute 'ei_index'.
469 # Each bit in the bitstrings says whether this Descr is present in
470 # this EffectInfo or not. We try to share the value of 'ei_index'
471 # across multiple Descrs if they always give the same answer (in
472 # PyPy, it reduces the length of the bitstrings from 4000+ to
473 # 373).
474 from rpython.jit.codewriter.policy import log
475
476 log("compute_bitstrings:")
477 effectinfos = []
478 descrs = {'fields': set(), 'arrays': set(), 'interiorfields': set()}
479 for descr in all_descrs:
480 if hasattr(descr, 'get_extra_info'):
481 ei = descr.get_extra_info()
482 if ei is None:
483 continue
484 if ei._readonly_descrs_fields is None:
485 for key in descrs:
486 assert getattr(ei, '_readonly_descrs_' + key) is None
487 assert getattr(ei, '_write_descrs_' + key) is None
488 setattr(ei, 'bitstring_readonly_descrs_' + key, None)
489 setattr(ei, 'bitstring_write_descrs_' + key, None)
490 else:
491 effectinfos.append(ei)
492 for key in descrs:
493 descrs[key].update(getattr(ei, '_readonly_descrs_' + key))
494 descrs[key].update(getattr(ei, '_write_descrs_' + key))
495 else:
496 descr.ei_index = sys.maxint
497 log(" %d effectinfos:" % (len(effectinfos),))
498 for key in sorted(descrs):
499 log(" %d descrs for %s" % (len(descrs[key]), key))
500
501 seen = set()
502 for key in descrs:
503 all_sets = []
504 for descr in descrs[key]:
505 eisetr = [ei for ei in effectinfos
506 if descr in getattr(ei, '_readonly_descrs_' + key)]
507 eisetw = [ei for ei in effectinfos
508 if descr in getattr(ei, '_write_descrs_' + key)]
509 # these are the set of all ei such that this descr is in
510 # ei._readonly_descrs or ei._write_descrs
511 eisetr = frozenset(eisetr)
512 eisetw = frozenset(eisetw)
513 all_sets.append((descr, eisetr, eisetw))
514
515 # heuristic to reduce the total size of the bitstrings: start with
516 # numbering the descrs that are seen in many EffectInfos. If instead,
517 # by lack of chance, such a descr had a high number, then all these
518 # EffectInfos' bitstrings would need to store the same high number.
519 def size_of_both_sets((d, r, w)):
520 return len(r) + len(w)
521 all_sets.sort(key=size_of_both_sets, reverse=True)
522
523 mapping = {}
524 for (descr, eisetr, eisetw) in all_sets:
525 assert descr.ei_index == sys.maxint # not modified yet
526 descr.ei_index = mapping.setdefault((eisetr, eisetw), len(mapping))
527
528 for ei in effectinfos:
529 bitstrr = [descr.ei_index
530 for descr in getattr(ei, '_readonly_descrs_' + key)]
531 bitstrw = [descr.ei_index
532 for descr in getattr(ei, '_write_descrs_' + key)]
533 assert sys.maxint not in bitstrr
534 assert sys.maxint not in bitstrw
535 bitstrr = bitstring.make_bitstring(bitstrr)
536 bitstrw = bitstring.make_bitstring(bitstrw)
537 setattr(ei, 'bitstring_readonly_descrs_' + key, bitstrr)
538 setattr(ei, 'bitstring_write_descrs_' + key, bitstrw)
539 seen.add(bitstrr)
540 seen.add(bitstrw)
541
542 if seen:
543 mean_length = float(sum(len(x) for x in seen)) / len(seen)
544 max_length = max(len(x) for x in seen)
545 log("-> %d bitstrings, mean length %.1f, max length %d" % (
546 len(seen), mean_length, max_length))