Debian Codegraph @

rpython/jit/backend/test/test_ll_random.py

raw symbols SCIP
1 import py
2 from rpython.rtyper.lltypesystem import lltype, llmemory, rffi, rstr
3 from rpython.rtyper import rclass
4 from rpython.jit.backend.test import test_random
5 from rpython.jit.backend.test.test_random import getint, getref_base, getref
6 from rpython.jit.metainterp.resoperation import ResOperation, rop, optypes
7 from rpython.jit.metainterp.history import ConstInt, ConstPtr, getkind
8 from rpython.jit.metainterp.support import ptr2int
9 from rpython.jit.codewriter import heaptracker
10 from rpython.jit.codewriter.effectinfo import EffectInfo
11 from rpython.rtyper.annlowlevel import llhelper
12 from rpython.rlib.rarithmetic import intmask
13 from rpython.rtyper.llinterp import LLException
14
15 class LLtypeOperationBuilder(test_random.OperationBuilder):
16 HAVE_SHORT_FIELDS = False
17
18 def __init__(self, *args, **kw):
19 test_random.OperationBuilder.__init__(self, *args, **kw)
20 self.vtable_counter = 0
21 # note: rstrs and runicodes contain either new local strings, or
22 # constants. In other words, all BoxPtrs here were created earlier
23 # by the trace before, and so it should be kind of fine to mutate
24 # them with strsetitem/unicodesetitem.
25 self.rstrs = []
26 self.runicodes = []
27 self.structure_types = []
28 self.structure_types_and_vtables = []
29
30 def fork(self, cpu, loop, vars):
31 fork = test_random.OperationBuilder.fork(self, cpu, loop, vars)
32 fork.structure_types = self.structure_types
33 fork.structure_types_and_vtables = self.structure_types_and_vtables
34 return fork
35
36 def _choose_ptr_vars(self, from_, type, array_of_structs):
37 ptrvars = []
38 for i in range(len(from_)):
39 v, S = from_[i][:2]
40 if not isinstance(S, type):
41 continue
42 if ((isinstance(S, lltype.Array) and
43 isinstance(S.OF, lltype.Struct)) == array_of_structs):
44 ptrvars.append((v, S))
45 return ptrvars
46
47 def get_structptr_var(self, r, must_have_vtable=False, type=lltype.Struct,
48 array_of_structs=False):
49 while True:
50 ptrvars = self._choose_ptr_vars(self.ptrvars, type,
51 array_of_structs)
52 if ptrvars and r.random() < 0.8:
53 v, S = r.choice(ptrvars)
54 else:
55 prebuilt_ptr_consts = self._choose_ptr_vars(
56 self.prebuilt_ptr_consts, type, array_of_structs)
57 if prebuilt_ptr_consts and r.random() < 0.7:
58 v, S = r.choice(prebuilt_ptr_consts)
59 else:
60 if type is lltype.Struct:
61 # create a new constant structure
62 must_have_vtable = must_have_vtable or r.random() < 0.5
63 p = self.get_random_structure(r,
64 has_vtable=must_have_vtable)
65 else:
66 # create a new constant array
67 p = self.get_random_array(r,
68 must_be_array_of_structs=array_of_structs)
69 S = lltype.typeOf(p).TO
70 v = ConstPtr(lltype.cast_opaque_ptr(llmemory.GCREF, p))
71 self.prebuilt_ptr_consts.append((v, S,
72 self.field_values(p)))
73 if not (must_have_vtable and S._names[0] != 'parent'):
74 break
75 return v, S
76
77 def get_arrayptr_var(self, r):
78 return self.get_structptr_var(r, type=lltype.Array)
79
80 def get_random_primitive_type(self, r):
81 rval = r.random()
82 if rval < 0.25:
83 TYPE = lltype.Signed
84 elif rval < 0.5:
85 TYPE = lltype.Char
86 elif rval < 0.75:
87 TYPE = rffi.UCHAR
88 else:
89 TYPE = rffi.SHORT
90 if not self.HAVE_SHORT_FIELDS:
91 TYPE = lltype.Signed
92 return TYPE
93
94 def get_random_structure_type(self, r, with_vtable=None, cache=True,
95 type=lltype.GcStruct):
96 if cache and self.structure_types and r.random() < 0.5:
97 return r.choice(self.structure_types)
98 fields = []
99 kwds = {}
100 if with_vtable:
101 fields.append(('parent', rclass.OBJECT))
102 kwds['hints'] = {'vtable': with_vtable._obj}
103 for i in range(r.randrange(1, 5)):
104 if r.random() < 0.1:
105 kind = 'r'
106 TYPE = llmemory.GCREF
107 else:
108 kind = 'i'
109 TYPE = self.get_random_primitive_type(r)
110 fields.append(('%s%d' % (kind, i), TYPE))
111 S = type('S%d' % self.counter, *fields, **kwds)
112 self.counter += 1
113 if cache:
114 self.structure_types.append(S)
115 return S
116
117 def get_random_structure_type_and_vtable(self, r):
118 if self.structure_types_and_vtables and r.random() < 0.5:
119 return r.choice(self.structure_types_and_vtables)
120 vtable = lltype.malloc(rclass.OBJECT_VTABLE, immortal=True)
121 vtable.subclassrange_min = self.vtable_counter
122 vtable.subclassrange_max = self.vtable_counter
123 self.vtable_counter += 1
124 S = self.get_random_structure_type(r, with_vtable=vtable, cache=False)
125 name = S._name
126 heaptracker.set_testing_vtable_for_gcstruct(S, vtable, name)
127 self.structure_types_and_vtables.append((S, vtable))
128 #
129 return S, vtable
130
131 def get_random_structure(self, r, has_vtable=False):
132 if has_vtable:
133 S, vtable = self.get_random_structure_type_and_vtable(r)
134 p = lltype.malloc(S)
135 p.parent.typeptr = vtable
136 else:
137 S = self.get_random_structure_type(r)
138 p = lltype.malloc(S)
139 for fieldname in lltype.typeOf(p).TO._names:
140 if fieldname != 'parent':
141 TYPE = getattr(S, fieldname)
142 setattr(p, fieldname, rffi.cast(TYPE, r.random_integer()))
143 return p
144
145 def get_random_array_type(self, r, can_be_array_of_struct=False,
146 must_be_array_of_structs=False):
147 if ((can_be_array_of_struct and r.random() < 0.1) or
148 must_be_array_of_structs):
149 TYPE = self.get_random_structure_type(r, cache=False,
150 type=lltype.Struct)
151 else:
152 TYPE = self.get_random_primitive_type(r)
153 return lltype.GcArray(TYPE)
154
155 def get_random_array(self, r, must_be_array_of_structs=False):
156 A = self.get_random_array_type(r,
157 must_be_array_of_structs=must_be_array_of_structs)
158 length = (r.random_integer() // 15) % 300 # length: between 0 and 299
159 # likely to be small
160 p = lltype.malloc(A, length)
161 if isinstance(A.OF, lltype.Primitive):
162 for i in range(length):
163 p[i] = rffi.cast(A.OF, r.random_integer())
164 else:
165 for i in range(length):
166 for fname, TP in A.OF._flds.iteritems():
167 setattr(p[i], fname, rffi.cast(TP, r.random_integer()))
168 return p
169
170 def get_index(self, length, r):
171 if length == 0:
172 raise test_random.CannotProduceOperation
173 v_index = r.choice(self.intvars)
174 if not (0 <= getint(v_index) < length):
175 v_index = ConstInt(r.random_integer() % length)
176 return v_index
177
178 def field_values(self, p):
179 dic = {}
180 S = lltype.typeOf(p).TO
181 if isinstance(S, lltype.Struct):
182 for fieldname in S._names:
183 if fieldname != 'parent':
184 dic[fieldname] = getattr(p, fieldname)
185 else:
186 assert isinstance(S, lltype.Array)
187 if isinstance(S.OF, lltype.Struct):
188 for i in range(len(p)):
189 item = p[i]
190 s1 = {}
191 for fieldname in S.OF._names:
192 s1[fieldname] = getattr(item, fieldname)
193 dic[i] = s1
194 else:
195 for i in range(len(p)):
196 dic[i] = p[i]
197 return dic
198
199 def print_loop_prebuilt(self, names, writevar, s):
200 written = {}
201 for v, S, fields in self.prebuilt_ptr_consts:
202 if S not in written:
203 print >>s, ' %s = lltype.GcStruct(%r,' % (S._name, S._name)
204 for name in S._names:
205 if name == 'parent':
206 print >>s, " ('parent', rclass.OBJECT),"
207 else:
208 print >>s, ' (%r, lltype.Signed),'%(name,)
209 print >>s, ' )'
210 if S._names[0] == 'parent':
211 print >>s, ' %s_vtable = lltype.malloc(rclass.OBJECT_VTABLE, immortal=True)' % (S._name,)
212 written[S] = True
213 print >>s, ' p = lltype.malloc(%s)' % (S._name,)
214 if S._names[0] == 'parent':
215 print >>s, ' p.parent.typeptr = %s_vtable' % (S._name,)
216 for name, value in fields.items():
217 print >>s, ' p.%s = %d' % (name, value)
218 writevar(v, 'preb', 'lltype.cast_opaque_ptr(llmemory.GCREF, p)')
219
220 # ____________________________________________________________
221
222 class GuardClassOperation(test_random.GuardOperation):
223 def gen_guard(self, builder, r):
224 ptrvars = [(v, S) for (v, S) in builder.ptrvars
225 if isinstance(S, lltype.Struct) and
226 S._names[0] == 'parent']
227 if not ptrvars:
228 raise test_random.CannotProduceOperation
229 v, S = r.choice(ptrvars)
230 if r.random() < 0.3 or not builder.produce_failing_guards:
231 v2, S2 = v, S
232 else:
233 v2, S2 = builder.get_structptr_var(r, must_have_vtable=True)
234 vtable = S._hints['vtable']._as_ptr()
235 vtable2 = S2._hints['vtable']._as_ptr()
236 c_vtable2 = ConstInt(ptr2int(vtable2))
237 op = ResOperation(self.opnum, [v, c_vtable2], None)
238 return op, (vtable == vtable2)
239
240 class GuardNonNullClassOperation(GuardClassOperation):
241 def gen_guard(self, builder, r):
242 if r.random() < 0.5:
243 return GuardClassOperation.gen_guard(self, builder, r)
244 else:
245 NULL = lltype.nullptr(llmemory.GCREF.TO)
246 op = ResOperation(rop.SAME_AS_R, [ConstPtr(NULL)])
247 builder.loop.operations.append(op)
248 v2, S2 = builder.get_structptr_var(r, must_have_vtable=True)
249 vtable2 = S2._hints['vtable']._as_ptr()
250 c_vtable2 = ConstInt(ptr2int(vtable2))
251 op = ResOperation(self.opnum, [op, c_vtable2], None)
252 return op, False
253
254 class ZeroPtrFieldOperation(test_random.AbstractOperation):
255 def field_descr(self, builder, r):
256 if getattr(builder.cpu, 'is_llgraph', False):
257 raise test_random.CannotProduceOperation
258 v, S = builder.get_structptr_var(r, )
259 names = S._names
260 if names[0] == 'parent':
261 names = names[1:]
262 choice = []
263 for name in names:
264 FIELD = getattr(S, name)
265 if FIELD is lltype.Signed: # xxx should be a gc ptr, but works too
266 choice.append(name)
267 if not choice:
268 raise test_random.CannotProduceOperation
269 name = r.choice(choice)
270 descr = builder.cpu.fielddescrof(S, name)
271 return v, descr.offset
272
273 def produce_into(self, builder, r):
274 v, offset = self.field_descr(builder, r)
275 builder.do(self.opnum, [v, ConstInt(offset)], None)
276
277 class GetFieldOperation(test_random.AbstractOperation):
278 def field_descr(self, builder, r):
279 v, S = builder.get_structptr_var(r, )
280 names = S._names
281 if names[0] == 'parent':
282 names = names[1:]
283 choice = []
284 kind = optypes[self.opnum]
285 for name in names:
286 FIELD = getattr(S, name)
287 if not isinstance(FIELD, lltype.Ptr):
288 if kind == 'n' or getkind(FIELD)[0] == kind:
289 choice.append(name)
290 if not choice:
291 raise test_random.CannotProduceOperation
292 name = r.choice(choice)
293 descr = builder.cpu.fielddescrof(S, name)
294 descr._random_info = 'cpu.fielddescrof(..., %r)' % (name,)
295 descr._random_type = S
296 TYPE = getattr(S, name)
297 return v, descr, TYPE
298
299 def produce_into(self, builder, r):
300 while True:
301 try:
302 v, descr, _ = self.field_descr(builder, r)
303 self.put(builder, [v], descr)
304 except lltype.UninitializedMemoryAccess:
305 continue
306 break
307
308 class GetInteriorFieldOperation(test_random.AbstractOperation):
309 def field_descr(self, builder, r):
310 v, A = builder.get_structptr_var(r, type=lltype.Array,
311 array_of_structs=True)
312 array = getref(lltype.Ptr(A), v)
313 v_index = builder.get_index(len(array), r)
314 choice = []
315 for name in A.OF._names:
316 FIELD = getattr(A.OF, name)
317 if not isinstance(FIELD, lltype.Ptr):
318 choice.append(name)
319 if not choice:
320 raise test_random.CannotProduceOperation
321 name = r.choice(choice)
322 descr = builder.cpu.interiorfielddescrof(A, name)
323 descr._random_info = 'cpu.interiorfielddescrof(..., %r)' % (name,)
324 descr._random_type = A
325 TYPE = getattr(A.OF, name)
326 return v, v_index, descr, TYPE
327
328 def produce_into(self, builder, r):
329 while True:
330 try:
331 v, v_index, descr, _ = self.field_descr(builder, r)
332 self.put(builder, [v, v_index], descr)
333 except lltype.UninitializedMemoryAccess:
334 continue
335 break
336
337 class SetFieldOperation(GetFieldOperation):
338 def produce_into(self, builder, r):
339 v, descr, TYPE = self.field_descr(builder, r)
340 while True:
341 if r.random() < 0.3:
342 w = ConstInt(r.random_integer())
343 else:
344 w = r.choice(builder.intvars)
345 value = getint(w)
346 if rffi.cast(lltype.Signed, rffi.cast(TYPE, value)) == value:
347 break
348 builder.do(self.opnum, [v, w], descr)
349
350 class SetInteriorFieldOperation(GetInteriorFieldOperation):
351 def produce_into(self, builder, r):
352 v, v_index, descr, TYPE = self.field_descr(builder, r)
353 while True:
354 if r.random() < 0.3:
355 w = ConstInt(r.random_integer())
356 else:
357 w = r.choice(builder.intvars)
358 value = getint(w)
359 if rffi.cast(lltype.Signed, rffi.cast(TYPE, value)) == value:
360 break
361 builder.do(self.opnum, [v, v_index, w], descr)
362
363 class NewOperation(test_random.AbstractOperation):
364 def size_descr(self, builder, S, *vtable):
365 descr = builder.cpu.sizeof(S, *vtable)
366 if vtable:
367 vtable, = vtable
368 descr._random_info = 'cpu.sizeof(..., Ellipsis)'
369 else:
370 descr._random_info = 'cpu.sizeof(...)'
371 descr._random_type = S
372 return descr
373
374 def produce_into(self, builder, r):
375 if self.opnum == rop.NEW_WITH_VTABLE:
376 S, vtable = builder.get_random_structure_type_and_vtable(r)
377 descr = self.size_descr(builder, S, vtable)
378 else:
379 S = builder.get_random_structure_type(r)
380 descr = self.size_descr(builder, S)
381 v_ptr = builder.do(self.opnum, [], descr)
382 builder.ptrvars.append((v_ptr, S))
383
384 class ArrayOperation(test_random.AbstractOperation):
385 def array_descr(self, builder, A):
386 descr = builder.cpu.arraydescrof(A)
387 descr._random_info = 'cpu.arraydescrof(...)'
388 descr._random_type = A
389 return descr
390
391 class GetArrayItemOperation(ArrayOperation):
392 def field_descr(self, builder, r):
393 v, A = builder.get_arrayptr_var(r)
394 array = getref(lltype.Ptr(A), v)
395 v_index = builder.get_index(len(array), r)
396 descr = self.array_descr(builder, A)
397 return v, A, v_index, descr
398
399 def produce_into(self, builder, r):
400 while True:
401 try:
402 v, _, v_index, descr = self.field_descr(builder, r)
403 self.put(builder, [v, v_index], descr)
404 except lltype.UninitializedMemoryAccess:
405 continue
406 break
407
408 class SetArrayItemOperation(GetArrayItemOperation):
409 def produce_into(self, builder, r):
410 v, A, v_index, descr = self.field_descr(builder, r)
411 while True:
412 if r.random() < 0.3:
413 w = ConstInt(r.random_integer())
414 else:
415 w = r.choice(builder.intvars)
416 value = getint(w)
417 if rffi.cast(lltype.Signed, rffi.cast(A.OF, value)) == value:
418 break
419 builder.do(self.opnum, [v, v_index, w], descr)
420
421 class NewArrayOperation(ArrayOperation):
422 def produce_into(self, builder, r):
423 A = builder.get_random_array_type(r, can_be_array_of_struct=True)
424 v_size = builder.get_index(300, r)
425 v_ptr = builder.do(self.opnum, [v_size], self.array_descr(builder, A))
426 builder.ptrvars.append((v_ptr, A))
427
428 class ArrayLenOperation(ArrayOperation):
429 def produce_into(self, builder, r):
430 v, A = builder.get_arrayptr_var(r)
431 descr = self.array_descr(builder, A)
432 self.put(builder, [v], descr)
433
434 class _UnicodeOperation:
435 builder_cache = "runicodes"
436 struct = rstr.UNICODE
437 ptr = lltype.Ptr(struct)
438 alloc = staticmethod(rstr.mallocunicode)
439 # XXX This should really be runicode.MAXUNICODE, but then
440 # lltype.cast_primitive complains.
441 max = py.std.sys.maxunicode
442 primitive = lltype.UniChar
443 set_char = rop.UNICODESETITEM
444
445 class _StrOperation:
446 builder_cache = "rstrs"
447 struct = rstr.STR
448 ptr = lltype.Ptr(struct)
449 alloc = staticmethod(rstr.mallocstr)
450 max = 255
451 primitive = lltype.Char
452 set_char = rop.STRSETITEM
453
454 class NewSeqOperation(test_random.AbstractOperation):
455 def produce_into(self, builder, r):
456 v_length = builder.get_index(10, r)
457 v_ptr = builder.do(self.opnum, [v_length])
458 getattr(builder, self.builder_cache).append(v_ptr)
459 # Initialize the string. Is there a better way to do this?
460 for i in range(getint(v_length)):
461 v_index = ConstInt(i)
462 v_char = ConstInt(r.random_integer() % self.max)
463 builder.do(self.set_char, [v_ptr, v_index, v_char])
464
465 class NewStrOperation(NewSeqOperation, _StrOperation):
466 pass
467
468 class NewUnicodeOperation(NewSeqOperation, _UnicodeOperation):
469 pass
470
471 class AbstractStringOperation(test_random.AbstractOperation):
472 def get_string(self, builder, r):
473 current = getattr(builder, self.builder_cache)
474 if current and r.random() < .8:
475 v_string = r.choice(current)
476 string = getref(self.ptr, v_string)
477 else:
478 string = self.alloc(getint(builder.get_index(500, r)))
479 v_string = ConstPtr(lltype.cast_opaque_ptr(llmemory.GCREF, string))
480 current.append(v_string)
481 for i in range(len(string.chars)):
482 char = r.random_integer() % self.max
483 string.chars[i] = lltype.cast_primitive(self.primitive, char)
484 return v_string
485
486 class AbstractGetItemOperation(AbstractStringOperation):
487 def produce_into(self, builder, r):
488 v_string = self.get_string(builder, r)
489 v_index = builder.get_index(len(getref(self.ptr, v_string).chars), r)
490 builder.do(self.opnum, [v_string, v_index])
491
492 class AbstractSetItemOperation(AbstractStringOperation):
493 def produce_into(self, builder, r):
494 v_string = self.get_string(builder, r)
495 if isinstance(v_string, ConstPtr):
496 raise test_random.CannotProduceOperation # setitem(Const, ...)
497 v_index = builder.get_index(len(getref(self.ptr, v_string).chars), r)
498 v_target = ConstInt(r.random_integer() % self.max)
499 builder.do(self.opnum, [v_string, v_index, v_target])
500
501 class AbstractStringLenOperation(AbstractStringOperation):
502 def produce_into(self, builder, r):
503 v_string = self.get_string(builder, r)
504 builder.do(self.opnum, [v_string])
505
506 class AbstractCopyContentOperation(AbstractStringOperation):
507 def produce_into(self, builder, r):
508 v_srcstring = self.get_string(builder, r)
509 v_dststring = self.get_string(builder, r)
510 src = getref(self.ptr, v_srcstring)
511 dst = getref(self.ptr, v_dststring)
512 if src == dst: # because it's not a
513 raise test_random.CannotProduceOperation # memmove(), but memcpy()
514 srclen = len(src.chars)
515 dstlen = len(dst.chars)
516 v_length = builder.get_index(min(srclen, dstlen), r)
517 v_srcstart = builder.get_index(srclen - getint(v_length) + 1, r)
518 v_dststart = builder.get_index(dstlen - getint(v_length) + 1, r)
519 builder.do(self.opnum, [v_srcstring, v_dststring,
520 v_srcstart, v_dststart, v_length])
521
522 class StrGetItemOperation(AbstractGetItemOperation, _StrOperation):
523 pass
524
525 class UnicodeGetItemOperation(AbstractGetItemOperation, _UnicodeOperation):
526 pass
527
528 class StrSetItemOperation(AbstractSetItemOperation, _StrOperation):
529 pass
530
531 class UnicodeSetItemOperation(AbstractSetItemOperation, _UnicodeOperation):
532 pass
533
534 class StrLenOperation(AbstractStringLenOperation, _StrOperation):
535 pass
536
537 class UnicodeLenOperation(AbstractStringLenOperation, _UnicodeOperation):
538 pass
539
540 class CopyStrContentOperation(AbstractCopyContentOperation, _StrOperation):
541 pass
542
543 class CopyUnicodeContentOperation(AbstractCopyContentOperation,
544 _UnicodeOperation):
545 pass
546
547
548 # there are five options in total:
549 # 1. non raising call and guard_no_exception
550 # 2. raising call and guard_exception
551 # 3. raising call and wrong guard_exception
552 # 4. raising call and guard_no_exception
553 # 5. non raising call and guard_exception
554 # (6. test of a cond_call, always non-raising and guard_no_exception)
555
556 class BaseCallOperation(test_random.AbstractOperation):
557 def non_raising_func_code(self, builder, r):
558 subset = builder.subset_of_intvars(r)
559 funcargs = ", ".join(['arg_%d' % i for i in range(len(subset))])
560 sum = "intmask(%s)" % " + ".join(
561 ['arg_%d' % i for i in range(len(subset))] + ['42'])
562 if self.opnum == rop.CALL_I:
563 result = 'sum'
564 elif self.opnum == rop.CALL_F:
565 result = 'float(sum)'
566 elif self.opnum == rop.CALL_N:
567 result = ''
568 else:
569 raise AssertionError(self.opnum)
570 code = py.code.Source("""
571 def f(%s):
572 sum = %s
573 return %s
574 """ % (funcargs, sum, result)).compile()
575 d = {'intmask': intmask}
576 exec(code, d)
577 return subset, d['f']
578
579 def raising_func_code(self, builder, r):
580 subset = builder.subset_of_intvars(r)
581 funcargs = ", ".join(['arg_%d' % i for i in range(len(subset))])
582 S, v = builder.get_structptr_var(r, must_have_vtable=True)
583
584 code = py.code.Source("""
585 def f(%s):
586 raise LLException(vtable, ptr)
587 """ % funcargs).compile()
588 vtableptr = v._hints['vtable']._as_ptr()
589 d = {
590 'ptr': getref_base(S),
591 'vtable': vtableptr,
592 'LLException': LLException,
593 }
594 exec(code, d)
595 return subset, d['f'], vtableptr
596
597 def getresulttype(self):
598 if self.opnum == rop.CALL_I or self.opnum == rop.COND_CALL_VALUE_I:
599 return lltype.Signed
600 elif self.opnum == rop.CALL_F:
601 return lltype.Float
602 elif self.opnum == rop.CALL_N or self.opnum == rop.COND_CALL:
603 return lltype.Void
604 else:
605 raise AssertionError(self.opnum)
606
607 def getcalldescr(self, builder, TP):
608 assert TP.RESULT == self.getresulttype()
609 ef = EffectInfo.MOST_GENERAL
610 return builder.cpu.calldescrof(TP, TP.ARGS, TP.RESULT, ef)
611
612 # 1. non raising call and guard_no_exception
613 class CallOperation(BaseCallOperation):
614 def produce_into(self, builder, r):
615 fail_subset = builder.subset_of_intvars(r)
616 subset, f = self.non_raising_func_code(builder, r)
617 RES = self.getresulttype()
618 TP = lltype.FuncType([lltype.Signed] * len(subset), RES)
619 ptr = llhelper(lltype.Ptr(TP), f)
620 c_addr = ConstInt(ptr2int(ptr))
621 args = [c_addr] + subset
622 descr = self.getcalldescr(builder, TP)
623 self.put(builder, args, descr)
624 op = ResOperation(rop.GUARD_NO_EXCEPTION, [],
625 descr=builder.getfaildescr())
626 op.setfailargs(fail_subset)
627 builder.loop.operations.append(op)
628
629 # 5. Non raising-call and GUARD_EXCEPTION
630
631 class CallOperationException(BaseCallOperation):
632 def produce_into(self, builder, r):
633 subset, f = self.non_raising_func_code(builder, r)
634 RES = self.getresulttype()
635 TP = lltype.FuncType([lltype.Signed] * len(subset), RES)
636 ptr = llhelper(lltype.Ptr(TP), f)
637 c_addr = ConstInt(ptr2int(ptr))
638 args = [c_addr] + subset
639 descr = self.getcalldescr(builder, TP)
640 self.put(builder, args, descr)
641 _, vtableptr = builder.get_random_structure_type_and_vtable(r)
642 exc_box = ConstInt(ptr2int(vtableptr))
643 op = ResOperation(rop.GUARD_EXCEPTION, [exc_box],
644 descr=builder.getfaildescr())
645 op.setfailargs(builder.subset_of_intvars(r))
646 op._exc_box = None
647 builder.should_fail_by = op
648 builder.guard_op = op
649 builder.loop.operations.append(op)
650
651 # 2. raising call and guard_exception
652
653 class RaisingCallOperation(BaseCallOperation):
654 def produce_into(self, builder, r):
655 fail_subset = builder.subset_of_intvars(r)
656 subset, f, exc = self.raising_func_code(builder, r)
657 TP = lltype.FuncType([lltype.Signed] * len(subset), lltype.Void)
658 ptr = llhelper(lltype.Ptr(TP), f)
659 c_addr = ConstInt(ptr2int(ptr))
660 args = [c_addr] + subset
661 descr = self.getcalldescr(builder, TP)
662 self.put(builder, args, descr)
663 exc_box = ConstInt(ptr2int(exc))
664 op = ResOperation(rop.GUARD_EXCEPTION, [exc_box],
665 descr=builder.getfaildescr())
666 op.setfailargs(fail_subset)
667 builder.loop.operations.append(op)
668
669 # 4. raising call and guard_no_exception
670
671 class RaisingCallOperationGuardNoException(BaseCallOperation):
672 def produce_into(self, builder, r):
673 subset, f, exc = self.raising_func_code(builder, r)
674 TP = lltype.FuncType([lltype.Signed] * len(subset), lltype.Void)
675 ptr = llhelper(lltype.Ptr(TP), f)
676 c_addr = ConstInt(ptr2int(ptr))
677 args = [c_addr] + subset
678 descr = self.getcalldescr(builder, TP)
679 self.put(builder, args, descr)
680 op = ResOperation(rop.GUARD_NO_EXCEPTION, [],
681 descr=builder.getfaildescr())
682 op._exc_box = ConstInt(ptr2int(exc))
683 op.setfailargs(builder.subset_of_intvars(r))
684 builder.should_fail_by = op
685 builder.guard_op = op
686 builder.loop.operations.append(op)
687
688 # 3. raising call and wrong guard_exception
689
690 class RaisingCallOperationWrongGuardException(BaseCallOperation):
691 def produce_into(self, builder, r):
692 subset, f, exc = self.raising_func_code(builder, r)
693 TP = lltype.FuncType([lltype.Signed] * len(subset), lltype.Void)
694 ptr = llhelper(lltype.Ptr(TP), f)
695 c_addr = ConstInt(ptr2int(ptr))
696 args = [c_addr] + subset
697 descr = self.getcalldescr(builder, TP)
698 self.put(builder, args, descr)
699 while True:
700 _, vtableptr = builder.get_random_structure_type_and_vtable(r)
701 if vtableptr != exc:
702 break
703 other_box = ConstInt(ptr2int(vtableptr))
704 op = ResOperation(rop.GUARD_EXCEPTION, [other_box],
705 descr=builder.getfaildescr())
706 op._exc_box = ConstInt(ptr2int(exc))
707 op.setfailargs(builder.subset_of_intvars(r))
708 builder.should_fail_by = op
709 builder.guard_op = op
710 builder.loop.operations.append(op)
711
712 # 6. a conditional call (for now always with no exception raised)
713 class CondCallOperation(BaseCallOperation):
714
715 def produce_into(self, builder, r):
716 fail_subset = builder.subset_of_intvars(r)
717 if self.opnum == rop.COND_CALL:
718 RESULT_TYPE = lltype.Void
719 v_cond = builder.get_bool_var(r)
720 else:
721 RESULT_TYPE = lltype.Signed
722 v_cond = r.choice(builder.intvars)
723 subset = builder.subset_of_intvars(r)[:4]
724 for i in range(len(subset)):
725 if r.random() < 0.35:
726 subset[i] = ConstInt(r.random_integer())
727 #
728 seen = []
729 def call_me(*args):
730 if len(seen) == 0:
731 seen.append(args)
732 else:
733 assert seen[0] == args
734 if RESULT_TYPE is lltype.Signed:
735 return len(args) - 42000
736 #
737 TP = lltype.FuncType([lltype.Signed] * len(subset), RESULT_TYPE)
738 ptr = llhelper(lltype.Ptr(TP), call_me)
739 c_addr = ConstInt(ptr2int(ptr))
740 args = [v_cond, c_addr] + subset
741 descr = self.getcalldescr(builder, TP)
742 self.put(builder, args, descr)
743 op = ResOperation(rop.GUARD_NO_EXCEPTION, [],
744 descr=builder.getfaildescr())
745 op.setfailargs(fail_subset)
746 builder.loop.operations.append(op)
747
748 # ____________________________________________________________
749
750 OPERATIONS = test_random.OPERATIONS[:]
751
752 for i in range(4): # make more common
753 OPERATIONS.append(GetFieldOperation(rop.GETFIELD_GC_I))
754 OPERATIONS.append(GetFieldOperation(rop.GETFIELD_GC_I))
755 OPERATIONS.append(GetInteriorFieldOperation(rop.GETINTERIORFIELD_GC_I))
756 OPERATIONS.append(GetInteriorFieldOperation(rop.GETINTERIORFIELD_GC_I))
757 OPERATIONS.append(SetFieldOperation(rop.SETFIELD_GC))
758 OPERATIONS.append(SetInteriorFieldOperation(rop.SETINTERIORFIELD_GC))
759 OPERATIONS.append(NewOperation(rop.NEW))
760 OPERATIONS.append(NewOperation(rop.NEW_WITH_VTABLE))
761
762 OPERATIONS.append(GetArrayItemOperation(rop.GETARRAYITEM_GC_I))
763 OPERATIONS.append(GetArrayItemOperation(rop.GETARRAYITEM_GC_I))
764 OPERATIONS.append(SetArrayItemOperation(rop.SETARRAYITEM_GC))
765 OPERATIONS.append(NewArrayOperation(rop.NEW_ARRAY_CLEAR))
766 OPERATIONS.append(ArrayLenOperation(rop.ARRAYLEN_GC))
767 OPERATIONS.append(NewStrOperation(rop.NEWSTR))
768 OPERATIONS.append(NewUnicodeOperation(rop.NEWUNICODE))
769 OPERATIONS.append(StrGetItemOperation(rop.STRGETITEM))
770 OPERATIONS.append(UnicodeGetItemOperation(rop.UNICODEGETITEM))
771 OPERATIONS.append(StrSetItemOperation(rop.STRSETITEM))
772 OPERATIONS.append(UnicodeSetItemOperation(rop.UNICODESETITEM))
773 OPERATIONS.append(StrLenOperation(rop.STRLEN))
774 OPERATIONS.append(UnicodeLenOperation(rop.UNICODELEN))
775 OPERATIONS.append(CopyStrContentOperation(rop.COPYSTRCONTENT))
776 OPERATIONS.append(CopyUnicodeContentOperation(rop.COPYUNICODECONTENT))
777
778 for i in range(2):
779 OPERATIONS.append(GuardClassOperation(rop.GUARD_CLASS))
780 OPERATIONS.append(CondCallOperation(rop.COND_CALL))
781 OPERATIONS.append(CondCallOperation(rop.COND_CALL_VALUE_I))
782 OPERATIONS.append(RaisingCallOperation(rop.CALL_N))
783 OPERATIONS.append(RaisingCallOperationGuardNoException(rop.CALL_N))
784 OPERATIONS.append(RaisingCallOperationWrongGuardException(rop.CALL_N))
785 OPERATIONS.append(GuardNonNullClassOperation(rop.GUARD_NONNULL_CLASS))
786
787 for _opnum in [rop.CALL_I, rop.CALL_F, rop.CALL_N]:
788 OPERATIONS.append(CallOperation(_opnum))
789 OPERATIONS.append(CallOperationException(_opnum))
790
791 LLtypeOperationBuilder.OPERATIONS = OPERATIONS
792
793 # ____________________________________________________________
794
795 def test_ll_random_function():
796 test_random.test_random_function(LLtypeOperationBuilder)