Debian Codegraph @

pypy/module/_cppyy/test/test_zjit.py

raw symbols SCIP
1 import py, os, sys
2 from .support import setup_make, soext
3
4 from rpython.jit.metainterp.test.support import LLJitMixin
5 from rpython.rlib.objectmodel import specialize, instantiate
6 from rpython.rlib import rarithmetic, rbigint, jit
7 from rpython.rtyper.lltypesystem import rffi, lltype
8 from rpython.rtyper import llinterp
9 from pypy.interpreter.baseobjspace import InternalSpaceCache, W_Root
10
11 from pypy.module._cppyy import interp_cppyy, capi, executor
12
13 if os.getenv("CPPYY_DISABLE_FASTPATH"):
14 py.test.skip("fast path is disabled by CPPYY_DISABLE_FASTPATH envar")
15
16 # load cpyext early, or its global vars are counted as leaks in the test
17 # (note that the module is not otherwise used in the test itself)
18 import pypy.module.cpyext
19
20 # add missing alt_errno (??)
21 def get_tlobj(self):
22 try:
23 return self._tlobj
24 except AttributeError:
25 from rpython.rtyper.lltypesystem import rffi
26 PERRNO = rffi.CArrayPtr(rffi.INT)
27 fake_p_errno = lltype.malloc(PERRNO.TO, 1, flavor='raw', zero=True,
28 track_allocation=False)
29 self._tlobj = {'RPY_TLOFS_p_errno': fake_p_errno,
30 'RPY_TLOFS_alt_errno': rffi.cast(rffi.INT, 0),
31 #'thread_ident': ...,
32 }
33 return self._tlobj
34 llinterp.LLInterpreter.get_tlobj = get_tlobj
35
36 currpath = py.path.local(__file__).dirpath()
37 test_dct = str(currpath.join("example01Dict"))+soext
38
39 def setup_module(mod):
40 setup_make("example01")
41
42
43 class FakeBase(W_Root):
44 typename = None
45
46 class FakeInt(FakeBase):
47 typename = "int"
48 def __init__(self, val):
49 self.val = val
50 FakeBool = FakeInt
51 class FakeLong(FakeBase):
52 typename = "long"
53 def __init__(self, val):
54 self.val = val
55 class FakeFloat(FakeBase):
56 typename = "float"
57 def __init__(self, val):
58 self.val = val
59 class FakeComplex(FakeBase):
60 typename = "complex"
61 def __init__(self, rval, ival):
62 self.obj = (rval, ival)
63 class FakeString(FakeBase):
64 typename = "str"
65 def __init__(self, val):
66 self.val = val
67 class FakeUnicode(FakeBase):
68 typename = "unicode"
69 def __init__(self, val):
70 self.val = val
71 class FakeTuple(FakeBase):
72 typename = "tuple"
73 def __init__(self, val):
74 self.val = val
75 class FakeType(FakeBase):
76 typename = "type"
77 def __init__(self, name):
78 self.name = name
79 self.__name__ = name
80 def getname(self, space, name):
81 return self.name
82 class FakeBuffer(FakeBase):
83 typedname = "buffer"
84 def __init__(self, val):
85 self.val = val
86 def get_raw_address(self):
87 raise ValueError("no raw buffer")
88 class FakeException(FakeType):
89 def __init__(self, space, name):
90 FakeType.__init__(self, name)
91 self.msg = name
92 self.space = space
93
94 class FakeUserDelAction(object):
95 def __init__(self, space):
96 pass
97
98 def register_callback(self, w_obj, callback, descrname):
99 pass
100
101 def perform(self, executioncontext, frame):
102 pass
103
104 class FakeState(object):
105 def __init__(self, space):
106 self.slowcalls = 0
107
108 class FakeFinalizerQueue(object):
109 def register_finalizer(self, obj):
110 pass
111
112 class FakeConfig(object):
113 pass
114
115 class FakeSpace(object):
116 fake = True
117
118 w_None = None
119 w_str = FakeType("str")
120 w_text = FakeType("str")
121 w_bytes = FakeType("str")
122 w_int = FakeType("int")
123 w_float = FakeType("float")
124
125 def __init__(self):
126 self.finalizer_queue = FakeFinalizerQueue()
127
128 self.fromcache = InternalSpaceCache(self).getorbuild
129 self.user_del_action = FakeUserDelAction(self)
130 self.config = FakeConfig()
131 self.config.translating = False
132
133 # kill calls to c_call_i (i.e. slow path)
134 def c_call_i(space, cppmethod, cppobject, nargs, args):
135 assert not "slow path called"
136 return capi.c_call_i(space, cppmethod, cppobject, nargs, args)
137 executor.get_executor(self, 'int').__class__.c_stubcall = staticmethod(c_call_i)
138
139 self.w_AttributeError = FakeException(self, "AttributeError")
140 self.w_Exception = FakeException(self, "Exception")
141 self.w_ImportError = FakeException(self, "ImportError")
142 self.w_KeyError = FakeException(self, "KeyError")
143 self.w_LookupError = FakeException(self, "LookupError")
144 self.w_NotImplementedError = FakeException(self, "NotImplementedError")
145 self.w_OSError = FakeException(self, "OSError")
146 self.w_ReferenceError = FakeException(self, "ReferenceError")
147 self.w_RuntimeError = FakeException(self, "RuntimeError")
148 self.w_SystemError = FakeException(self, "SystemError")
149 self.w_TypeError = FakeException(self, "TypeError")
150 self.w_ValueError = FakeException(self, "ValueError")
151
152 self.w_True = FakeBool(True)
153 self.w_False = FakeBool(False)
154
155 def issequence_w(self, w_obj):
156 return True
157
158 def wrap(self, obj):
159 assert 0
160
161 @specialize.argtype(1)
162 def newbool(self, obj):
163 return FakeBool(obj)
164
165 @specialize.argtype(1)
166 def newint(self, obj):
167 if not isinstance(obj, int):
168 return FakeLong(rbigint.rbigint.fromrarith_int(obj))
169 return FakeInt(obj)
170
171 @specialize.argtype(1)
172 def newlong(self, obj):
173 return FakeLong(rbigint.rbigint.fromint(obj))
174
175 @specialize.argtype(1)
176 def newlong_from_rarith_int(self, obj):
177 return FakeLong(rbigint.rbigint.fromrarith_int(obj))
178
179 def newlong_from_rbigint(self, val):
180 return FakeLong(obj)
181
182 @specialize.argtype(1)
183 def newfloat(self, obj):
184 return FakeFloat(obj)
185
186 @specialize.argtype(1)
187 def newcomplex(self, rval, ival):
188 return FakeComplex(rval, ival)
189
190 @specialize.argtype(1)
191 def newbytes(self, obj):
192 return FakeString(obj)
193
194 @specialize.argtype(1)
195 def newtext(self, obj):
196 return FakeString(obj)
197
198 @specialize.argtype(1)
199 def newtuple(self, obj):
200 return FakeTuple(obj)
201
202 def getitem(self, coll, i):
203 return coll.val[i.val]
204
205 def float_w(self, w_obj, allow_conversion=True):
206 assert isinstance(w_obj, FakeFloat)
207 return w_obj.val
208
209 def newutf8(self, obj, sz):
210 return FakeUnicode(obj)
211
212 def unicode_from_object(self, w_obj):
213 if isinstance (w_obj, FakeUnicode):
214 return w_obj
215 return FakeUnicode(w_obj.utf8_w(self))
216
217 def utf8_len_w(self, w_obj):
218 assert isinstance(w_obj, FakeUnicode)
219 return w_obj.val, len(w_obj.val)
220
221 @specialize.arg(1)
222 def interp_w(self, RequiredClass, w_obj, can_be_None=False):
223 if can_be_None and w_obj is None:
224 return None
225 if not isinstance(w_obj, RequiredClass):
226 raise TypeError
227 return w_obj
228
229 def getarg_w(self, code, w_obj): # for retrieving buffers
230 return FakeBuffer(w_obj)
231
232 def exception_match(self, typ, sub):
233 return typ is sub
234
235 @specialize.argtype(1)
236 def is_none(self, w_obj):
237 return w_obj is None
238
239 def is_w(self, w_one, w_two):
240 return w_one is w_two
241
242 def bool_w(self, w_obj, allow_conversion=True):
243 assert isinstance(w_obj, FakeBool)
244 return w_obj.val
245
246 def int_w(self, w_obj, allow_conversion=True):
247 assert isinstance(w_obj, FakeInt)
248 return w_obj.val
249
250 def uint_w(self, w_obj):
251 assert isinstance(w_obj, FakeLong)
252 return rarithmetic.r_uint(w_obj.val.touint())
253
254 def bytes_w(self, w_obj):
255 assert isinstance(w_obj, FakeString)
256 return w_obj.val
257
258 def fsencode_w(self, w_obj):
259 return self.bytes_w(w_obj)
260
261 def text_w(self, w_obj):
262 assert isinstance(w_obj, FakeString)
263 return w_obj.val
264
265 def str(self, obj):
266 assert isinstance(obj, str)
267 return obj
268
269 def len_w(self, obj):
270 assert isinstance(obj, str)
271 return (obj)
272
273 c_int_w = int_w
274 c_uint_w = uint_w
275 r_longlong_w = int_w
276 r_ulonglong_w = uint_w
277
278 def is_(self, w_obj1, w_obj2):
279 return w_obj1 is w_obj2
280
281 def isinstance_w(self, w_obj, w_type):
282 assert isinstance(w_obj, FakeBase)
283 return w_obj.typename == w_type.name
284
285 def is_true(self, w_obj):
286 return not not w_obj
287
288 def type(self, w_obj):
289 return FakeType("fake")
290
291 def getattr(self, w_obj, w_name):
292 assert isinstance(w_obj, FakeException)
293 assert self.text_w(w_name) == "__name__"
294 return FakeString(w_obj.name)
295
296 def findattr(self, w_obj, w_name):
297 return None
298
299 def allocate_instance(self, cls, w_type):
300 return instantiate(cls)
301
302 def call_function(self, w_func, *args_w):
303 return None
304
305 def call_obj_args(self, w_callable, w_obj, args):
306 return w_callable.call_args([w_obj]+args)
307
308 def _freeze_(self):
309 return True
310
311
312 class TestFastPathJIT(LLJitMixin):
313 def setup_class(cls):
314 import ctypes
315 return ctypes.CDLL(test_dct, ctypes.RTLD_GLOBAL)
316
317 def _run_zjit(self, method_name):
318 space = FakeSpace()
319 drv = jit.JitDriver(greens=[], reds=["i", "inst", "cppmethod"])
320 def f():
321 cls = interp_cppyy.scope_byname(space, "example01")
322 inst = interp_cppyy._bind_object(space, FakeInt(0), cls, True)
323 cls.get_overload("__init__").descr_get(inst, []).call_args([FakeInt(0)])
324 cppmethod = cls.get_overload(method_name)
325 assert isinstance(inst, interp_cppyy.W_CPPInstance)
326 i = 10
327 while i > 0:
328 drv.jit_merge_point(inst=inst, cppmethod=cppmethod, i=i)
329 cppmethod.descr_get(inst, []).call_args([FakeInt(i)])
330 i -= 1
331 return 7
332 f()
333 space = FakeSpace()
334 result = self.meta_interp(f, [], listops=True, backendopt=True, listcomp=True)
335 self.check_jitcell_token_count(1)
336 # rely on replacement of capi calls to raise exception instead (see FakeSpace.__init__)
337
338 @py.test.mark.dont_track_allocations("cppmethod.cif_descr kept 'leaks'")
339 def test01_simple(self):
340 """Test fast path being taken for methods"""
341
342 self._run_zjit("addDataToInt")
343
344 @py.test.mark.dont_track_allocations("cppmethod.cif_descr kept 'leaks'")
345 def test02_overload(self):
346 """Test fast path being taken for overloaded methods"""
347
348 self._run_zjit("overloadedAddDataToInt")
349
350 @py.test.mark.dont_track_allocations("cppmethod.cif_descr kept 'leaks'")
351 def test03_const_ref(self):
352 """Test fast path being taken for methods with const ref arguments"""
353
354 self._run_zjit("addDataToIntConstRef")