Debian Codegraph @

rpython/translator/exceptiontransform.py

raw symbols SCIP
1 from rpython.translator.simplify import join_blocks, cleanup_graph
2 from rpython.translator.unsimplify import varoftype
3 from rpython.translator.unsimplify import insert_empty_block, split_block
4 from rpython.translator.backendopt import canraise, inline
5 from rpython.flowspace.model import Block, Constant, Variable, Link, \
6 SpaceOperation, FunctionGraph, mkentrymap
7 from rpython.rtyper.lltypesystem import lltype, llmemory, rffi
8 from rpython.rtyper.lltypesystem import lloperation
9 from rpython.rtyper.rclass import ll_inst_type
10 from rpython.rtyper import rtyper
11 from rpython.rtyper.rmodel import inputconst
12 from rpython.rlib.rarithmetic import r_uint, r_longlong, r_ulonglong
13 from rpython.rlib.rarithmetic import r_singlefloat, r_longfloat
14 from rpython.rlib.debug import ll_assert
15 from rpython.rtyper.llannotation import lltype_to_annotation
16 from rpython.rtyper.annlowlevel import MixLevelHelperAnnotator
17 from rpython.tool.sourcetools import func_with_new_name
18
19 # ~~~ NOTE ~~~
20 # The exact value returned by a function is NOT DEFINED. The returned value is
21 # IGNORED EVERYWHERE in RPython and the question "was_an_exception_raised()"
22 # is implemented by checking the content of the global exc_data.
23 #
24 # The only case in which the returned error value is significant is for
25 # llhelpers which can be called by 3rd-party C functions, such as e.g. the HPy
26 # API. In that case, the error value is specified by @llhelper_error_value.
27 #
28 # The following table defines the default error values to return, but in
29 # general the returned value is not guaranteed. The only case in which it is
30 # guaranteed is for functions decorated with @llhelper_error_value
31
32 PrimitiveErrorValue = {lltype.Signed: -1,
33 lltype.Unsigned: r_uint(-1),
34 lltype.SignedLongLong: r_longlong(-1),
35 lltype.UnsignedLongLong: r_ulonglong(-1),
36 lltype.Float: -1.0,
37 lltype.SingleFloat: r_singlefloat(-1.0),
38 lltype.LongFloat: r_longfloat(-1.0),
39 lltype.Char: chr(255),
40 lltype.UniChar: unichr(0xFFFF), # XXX is this always right?
41 lltype.Bool: True,
42 llmemory.Address: llmemory.NULL,
43 lltype.Void: None}
44
45 for TYPE in rffi.NUMBER_TYPES:
46 PrimitiveErrorValue[TYPE] = lltype.cast_primitive(TYPE, -1)
47 del TYPE
48
49 def default_error_value(T):
50 if isinstance(T, lltype.Primitive):
51 return PrimitiveErrorValue[T]
52 elif isinstance(T, lltype.Ptr):
53 return lltype.nullptr(T.TO)
54 assert 0, "not implemented yet"
55
56 def has_llhelper_error_value(graph):
57 return hasattr(graph, 'func') and hasattr(graph.func, '_llhelper_error_value_')
58
59 def error_value(graph):
60 assert isinstance(graph, FunctionGraph)
61 T = graph.returnblock.inputargs[0].concretetype
62 if has_llhelper_error_value(graph):
63 # custom case
64 errval = graph.func._llhelper_error_value_
65 if lltype.typeOf(errval) != T:
66 raise TypeError('Wrong type for @llhelper_error_value: expected %s '
67 'but got %s' % (T, lltype.typeOf(errval)))
68 return errval
69 # default case
70 return default_error_value(T)
71
72 def error_constant(graph):
73 assert isinstance(graph, FunctionGraph)
74 T = graph.returnblock.inputargs[0].concretetype
75 return Constant(error_value(graph), T)
76
77 def constant_value(llvalue):
78 return Constant(llvalue, lltype.typeOf(llvalue))
79
80 class ExceptionTransformer(object):
81
82 def __init__(self, translator):
83 self.translator = translator
84 self.raise_analyzer = canraise.RaiseAnalyzer(translator)
85 edata = translator.rtyper.exceptiondata
86 self.lltype_of_exception_value = edata.lltype_of_exception_value
87 self.lltype_of_exception_type = edata.lltype_of_exception_type
88 self.mixlevelannotator = MixLevelHelperAnnotator(translator.rtyper)
89 exc_data, null_type, null_value = self.setup_excdata()
90
91 (assertion_error_ll_exc_type,
92 assertion_error_ll_exc) = self.get_builtin_exception(AssertionError)
93 (n_i_error_ll_exc_type,
94 n_i_error_ll_exc) = self.get_builtin_exception(NotImplementedError)
95
96 self.c_assertion_error_ll_exc_type = constant_value(
97 assertion_error_ll_exc_type)
98 self.c_n_i_error_ll_exc_type = constant_value(n_i_error_ll_exc_type)
99
100 def rpyexc_occurred():
101 exc_type = exc_data.exc_type
102 return bool(exc_type)
103
104 def rpyexc_fetch_type():
105 return exc_data.exc_type
106
107 def rpyexc_fetch_value():
108 return exc_data.exc_value
109
110 def rpyexc_clear():
111 exc_data.exc_type = null_type
112 exc_data.exc_value = null_value
113
114 def rpyexc_raise(etype, evalue):
115 # When compiling in debug mode, the following ll_asserts will
116 # crash the program as soon as it raises AssertionError or
117 # NotImplementedError. Useful when you are in a debugger.
118 # When compiling in release mode, AssertionErrors and
119 # NotImplementedErrors are raised normally, and only later
120 # caught by debug_catch_exception and printed, which allows
121 # us to see at least part of the traceback for them.
122 ll_assert(etype != assertion_error_ll_exc_type, "AssertionError")
123 ll_assert(etype != n_i_error_ll_exc_type, "NotImplementedError")
124 exc_data.exc_type = etype
125 exc_data.exc_value = evalue
126 lloperation.llop.debug_start_traceback(lltype.Void, etype)
127
128 def rpyexc_reraise(etype, evalue):
129 exc_data.exc_type = etype
130 exc_data.exc_value = evalue
131 lloperation.llop.debug_reraise_traceback(lltype.Void, etype)
132
133 def rpyexc_fetch_exception():
134 evalue = rpyexc_fetch_value()
135 rpyexc_clear()
136 return evalue
137
138 def rpyexc_restore_exception(evalue):
139 if evalue:
140 exc_data.exc_type = ll_inst_type(evalue)
141 exc_data.exc_value = evalue
142
143 self.rpyexc_occurred_ptr = self.build_func(
144 "RPyExceptionOccurred",
145 rpyexc_occurred,
146 [], lltype.Bool)
147
148 self.rpyexc_fetch_type_ptr = self.build_func(
149 "RPyFetchExceptionType",
150 rpyexc_fetch_type,
151 [], self.lltype_of_exception_type)
152
153 self.rpyexc_fetch_value_ptr = self.build_func(
154 "RPyFetchExceptionValue",
155 rpyexc_fetch_value,
156 [], self.lltype_of_exception_value)
157
158 self.rpyexc_clear_ptr = self.build_func(
159 "RPyClearException",
160 rpyexc_clear,
161 [], lltype.Void)
162
163 self.rpyexc_raise_ptr = self.build_func(
164 "RPyRaiseException",
165 self.noinline(rpyexc_raise),
166 [self.lltype_of_exception_type, self.lltype_of_exception_value],
167 lltype.Void,
168 jitcallkind='rpyexc_raise') # for the JIT
169
170 self.rpyexc_reraise_ptr = self.build_func(
171 "RPyReRaiseException",
172 rpyexc_reraise,
173 [self.lltype_of_exception_type, self.lltype_of_exception_value],
174 lltype.Void,
175 jitcallkind='rpyexc_raise') # for the JIT
176
177 self.rpyexc_fetch_exception_ptr = self.build_func(
178 "RPyFetchException",
179 rpyexc_fetch_exception,
180 [], self.lltype_of_exception_value)
181
182 self.rpyexc_restore_exception_ptr = self.build_func(
183 "RPyRestoreException",
184 self.noinline(rpyexc_restore_exception),
185 [self.lltype_of_exception_value], lltype.Void)
186
187 self.build_extra_funcs()
188
189 self.mixlevelannotator.finish()
190 self.lltype_to_classdef = translator.rtyper.lltype_to_classdef_mapping()
191
192 def noinline(self, fn):
193 fn = func_with_new_name(fn, fn.__name__)
194 fn._dont_inline_ = True
195 return fn
196
197 def build_func(self, name, fn, inputtypes, rettype, **kwds):
198 l2a = lltype_to_annotation
199 graph = self.mixlevelannotator.getgraph(fn, map(l2a, inputtypes), l2a(rettype))
200 return self.constant_func(name, inputtypes, rettype, graph,
201 exception_policy="exc_helper", **kwds)
202
203 def get_builtin_exception(self, Class):
204 edata = self.translator.rtyper.exceptiondata
205 bk = self.translator.annotator.bookkeeper
206 error_def = bk.getuniqueclassdef(Class)
207 error_ll_exc = edata.get_standard_ll_exc_instance(
208 self.translator.rtyper, error_def)
209 error_ll_exc_type = ll_inst_type(error_ll_exc)
210 return error_ll_exc_type, error_ll_exc
211
212 def transform_completely(self):
213 for graph in self.translator.graphs:
214 self.create_exception_handling(graph)
215
216 def create_exception_handling(self, graph):
217 """After an exception in a direct_call (or indirect_call), that is not caught
218 by an explicit
219 except statement, we need to reraise the exception. So after this
220 direct_call we need to test if an exception had occurred. If so, we return
221 from the current graph with a special value (False/-1/-1.0/null).
222 Because of the added exitswitch we need an additional block.
223 """
224 if hasattr(graph, 'exceptiontransformed'):
225 assert self.same_obj(self.exc_data_ptr, graph.exceptiontransformed)
226 return
227 else:
228 self.raise_analyzer.analyze_direct_call(graph)
229 graph.exceptiontransformed = self.exc_data_ptr
230
231 join_blocks(graph)
232 # collect the blocks before changing them
233 n_need_exc_matching_blocks = 0
234 n_gen_exc_checks = 0
235 #
236 entrymap = mkentrymap(graph)
237 if graph.exceptblock in entrymap:
238 for link in entrymap[graph.exceptblock]:
239 self.transform_jump_to_except_block(graph, entrymap, link)
240 #
241 for block in list(graph.iterblocks()):
242 self.replace_fetch_restore_operations(block)
243 need_exc_matching, gen_exc_checks = self.transform_block(graph, block)
244 n_need_exc_matching_blocks += need_exc_matching
245 n_gen_exc_checks += gen_exc_checks
246 cleanup_graph(graph)
247 return n_need_exc_matching_blocks, n_gen_exc_checks
248
249 def replace_fetch_restore_operations(self, block):
250 # the gctransformer will create these operations. It looks as if the
251 # order of transformations is important - but the gctransformer will
252 # put them in a new graph, so all transformations will run again.
253 for i in range(len(block.operations)):
254 opname = block.operations[i].opname
255 if opname == 'gc_fetch_exception':
256 block.operations[i].opname = "direct_call"
257 block.operations[i].args = [self.rpyexc_fetch_exception_ptr]
258
259 elif opname == 'gc_restore_exception':
260 block.operations[i].opname = "direct_call"
261 block.operations[i].args.insert(0, self.rpyexc_restore_exception_ptr)
262 elif opname == 'get_exception_addr': # only for lltype
263 block.operations[i].opname = "direct_call"
264 block.operations[i].args.insert(0, self.rpyexc_get_exception_addr_ptr)
265 elif opname == 'get_exc_value_addr': # only for lltype
266 block.operations[i].opname = "direct_call"
267 block.operations[i].args.insert(0, self.rpyexc_get_exc_value_addr_ptr)
268
269 def transform_block(self, graph, block):
270 need_exc_matching = False
271 n_gen_exc_checks = 0
272 if block is graph.exceptblock:
273 return need_exc_matching, n_gen_exc_checks
274 elif block is graph.returnblock:
275 return need_exc_matching, n_gen_exc_checks
276 last_operation = len(block.operations) - 1
277 if block.canraise:
278 need_exc_matching = True
279 last_operation -= 1
280 elif (len(block.exits) == 1 and
281 block.exits[0].target is graph.returnblock and
282 len(block.operations) and
283 (block.exits[0].args[0].concretetype is lltype.Void or
284 block.exits[0].args[0] is block.operations[-1].result) and
285 block.operations[-1].opname not in ('malloc', 'malloc_varsize') and
286 not has_llhelper_error_value(graph)): # special cases
287 last_operation -= 1
288 lastblock = block
289 for i in range(last_operation, -1, -1):
290 op = block.operations[i]
291 if not self.raise_analyzer.can_raise(op):
292 continue
293
294 splitlink = split_block(block, i+1)
295 afterblock = splitlink.target
296 if lastblock is block:
297 lastblock = afterblock
298
299 self.gen_exc_check(graph, block, graph.returnblock, afterblock)
300 n_gen_exc_checks += 1
301 if need_exc_matching:
302 assert lastblock.canraise
303 if not self.raise_analyzer.can_raise(lastblock.operations[-1]):
304 lastblock.exitswitch = None
305 lastblock.recloseblock(lastblock.exits[0])
306 lastblock.exits[0].exitcase = None
307 else:
308 self.insert_matching(lastblock, graph)
309 return need_exc_matching, n_gen_exc_checks
310
311 def comes_from_last_exception(self, entrymap, link):
312 seen = set()
313 pending = [(link, link.args[1])]
314 while pending:
315 link, v = pending.pop()
316 if (link, v) in seen:
317 continue
318 seen.add((link, v))
319 if link.last_exc_value is not None and v is link.last_exc_value:
320 return True
321 block = link.prevblock
322 if block is None:
323 continue
324 for op in block.operations[::-1]:
325 if v is op.result:
326 if op.opname == 'cast_pointer':
327 v = op.args[0]
328 else:
329 break
330 for link in entrymap.get(block, ()):
331 for v1, v2 in zip(link.args, block.inputargs):
332 if v2 is v:
333 pending.append((link, v1))
334 return False
335
336 def transform_jump_to_except_block(self, graph, entrymap, link):
337 reraise = self.comes_from_last_exception(entrymap, link)
338 result = Variable()
339 result.concretetype = lltype.Void
340 block = Block([v.copy() for v in graph.exceptblock.inputargs])
341 if reraise:
342 block.operations = [
343 SpaceOperation("direct_call",
344 [self.rpyexc_reraise_ptr] + block.inputargs,
345 result),
346 ]
347 else:
348 block.operations = [
349 SpaceOperation("direct_call",
350 [self.rpyexc_raise_ptr] + block.inputargs,
351 result),
352 SpaceOperation('debug_record_traceback', [],
353 varoftype(lltype.Void)),
354 ]
355 link.target = block
356 l = Link([error_constant(graph)], graph.returnblock)
357 block.recloseblock(l)
358
359 def insert_matching(self, block, graph):
360 proxygraph, op = self.create_proxy_graph(block.operations[-1])
361 block.operations[-1] = op
362 #non-exception case
363 block.exits[0].exitcase = block.exits[0].llexitcase = None
364 # use the dangerous second True flag :-)
365 inliner = inline.OneShotInliner(
366 self.translator, graph, self.lltype_to_classdef,
367 inline_guarded_calls=True, inline_guarded_calls_no_matter_what=True,
368 raise_analyzer=self.raise_analyzer)
369 inliner.inline_once(block, len(block.operations)-1)
370 #block.exits[0].exitcase = block.exits[0].llexitcase = False
371
372 def create_proxy_graph(self, op):
373 """ creates a graph which calls the original function, checks for
374 raised exceptions, fetches and then raises them again. If this graph is
375 inlined, the correct exception matching blocks are produced."""
376 # XXX slightly annoying: construct a graph by hand
377 # but better than the alternative
378 result = op.result.copy()
379 opargs = []
380 inputargs = []
381 callargs = []
382 ARGTYPES = []
383 for var in op.args:
384 if isinstance(var, Variable):
385 v = Variable()
386 v.concretetype = var.concretetype
387 inputargs.append(v)
388 opargs.append(v)
389 callargs.append(var)
390 ARGTYPES.append(var.concretetype)
391 else:
392 opargs.append(var)
393 newop = SpaceOperation(op.opname, opargs, result)
394 startblock = Block(inputargs)
395 startblock.operations.append(newop)
396 newgraph = FunctionGraph("dummy_exc1", startblock)
397 startblock.closeblock(Link([result], newgraph.returnblock))
398 newgraph.returnblock.inputargs[0].concretetype = op.result.concretetype
399 self.gen_exc_check(newgraph, startblock, newgraph.returnblock)
400 excblock = Block([])
401
402 llops = rtyper.LowLevelOpList(None)
403 var_value = self.gen_getfield('exc_value', llops)
404 var_type = self.gen_getfield('exc_type' , llops)
405 #
406 c_check1 = self.c_assertion_error_ll_exc_type
407 c_check2 = self.c_n_i_error_ll_exc_type
408 llops.genop('debug_catch_exception', [var_type, c_check1, c_check2])
409 #
410 self.gen_setfield('exc_value', self.c_null_evalue, llops)
411 self.gen_setfield('exc_type', self.c_null_etype, llops)
412 excblock.operations[:] = llops
413 newgraph.exceptblock.inputargs[0].concretetype = self.lltype_of_exception_type
414 newgraph.exceptblock.inputargs[1].concretetype = self.lltype_of_exception_value
415 excblock.closeblock(Link([var_type, var_value], newgraph.exceptblock))
416 startblock.exits[True].target = excblock
417 startblock.exits[True].args = []
418 fptr = self.constant_func("dummy_exc1", ARGTYPES, op.result.concretetype, newgraph)
419 return newgraph, SpaceOperation("direct_call", [fptr] + callargs, op.result)
420
421 def gen_exc_check(self, graph, block, returnblock, normalafterblock=None):
422 llops = rtyper.LowLevelOpList(None)
423
424 spaceop = block.operations[-1]
425 alloc_shortcut = self.check_for_alloc_shortcut(spaceop)
426
427 if alloc_shortcut:
428 var_no_exc = self.gen_nonnull(spaceop.result, llops)
429 else:
430 v_exc_type = self.gen_getfield('exc_type', llops)
431 var_no_exc = self.gen_isnull(v_exc_type, llops)
432 #
433 # We could add a "var_no_exc is likely true" hint, but it seems
434 # not to help, so it was commented out again.
435 #var_no_exc = llops.genop('likely', [var_no_exc], lltype.Bool)
436
437 block.operations.extend(llops)
438
439 block.exitswitch = var_no_exc
440 #exception occurred case
441 b = Block([])
442 b.operations = [SpaceOperation('debug_record_traceback', [],
443 varoftype(lltype.Void))]
444 l = Link([error_constant(graph)], returnblock)
445 b.closeblock(l)
446 l = Link([], b)
447 l.exitcase = l.llexitcase = False
448
449 #non-exception case
450 l0 = block.exits[0]
451 l0.exitcase = l0.llexitcase = True
452
453 block.recloseblock(l0, l)
454 insert_zeroing_op = False
455 if spaceop.opname in ['malloc','malloc_varsize']:
456 flavor = spaceop.args[1].value['flavor']
457 if flavor == 'gc':
458 insert_zeroing_op = True
459 true_zero = spaceop.args[1].value.get('zero', False)
460 # NB. when inserting more special-cases here, keep in mind that
461 # you also need to list the opnames in transform_block()
462 # (see "special cases")
463
464 if insert_zeroing_op:
465 if normalafterblock is None:
466 normalafterblock = insert_empty_block(l0)
467 v_result = spaceop.result
468 if v_result in l0.args:
469 result_i = l0.args.index(v_result)
470 v_result_after = normalafterblock.inputargs[result_i]
471 else:
472 v_result_after = v_result.copy()
473 l0.args.append(v_result)
474 normalafterblock.inputargs.append(v_result_after)
475 if true_zero:
476 opname = "zero_everything_inside"
477 else:
478 opname = "zero_gc_pointers_inside"
479 normalafterblock.operations.insert(
480 0, SpaceOperation(opname, [v_result_after],
481 varoftype(lltype.Void)))
482
483 def setup_excdata(self):
484 EXCDATA = lltype.Struct('ExcData',
485 ('exc_type', self.lltype_of_exception_type),
486 ('exc_value', self.lltype_of_exception_value),
487 hints={'is_excdata': True})
488 self.EXCDATA = EXCDATA
489
490 exc_data = lltype.malloc(EXCDATA, immortal=True)
491 null_type = lltype.nullptr(self.lltype_of_exception_type.TO)
492 null_value = lltype.nullptr(self.lltype_of_exception_value.TO)
493
494 self.exc_data_ptr = exc_data
495 self.cexcdata = Constant(exc_data, lltype.Ptr(self.EXCDATA))
496 self.c_null_etype = Constant(null_type, self.lltype_of_exception_type)
497 self.c_null_evalue = Constant(null_value, self.lltype_of_exception_value)
498
499 return exc_data, null_type, null_value
500
501 def constant_func(self, name, inputtypes, rettype, graph, **kwds):
502 FUNC_TYPE = lltype.FuncType(inputtypes, rettype)
503 fn_ptr = lltype.functionptr(FUNC_TYPE, name, graph=graph, **kwds)
504 return Constant(fn_ptr, lltype.Ptr(FUNC_TYPE))
505
506 def gen_getfield(self, name, llops):
507 c_name = inputconst(lltype.Void, name)
508 return llops.genop('getfield', [self.cexcdata, c_name],
509 resulttype = getattr(self.EXCDATA, name))
510
511 def gen_setfield(self, name, v_value, llops):
512 c_name = inputconst(lltype.Void, name)
513 llops.genop('setfield', [self.cexcdata, c_name, v_value])
514
515 def gen_isnull(self, v, llops):
516 return llops.genop('ptr_iszero', [v], lltype.Bool)
517
518 def gen_nonnull(self, v, llops):
519 return llops.genop('ptr_nonzero', [v], lltype.Bool)
520
521 def same_obj(self, ptr1, ptr2):
522 return ptr1._same_obj(ptr2)
523
524 def check_for_alloc_shortcut(self, spaceop):
525 if spaceop.opname in ('malloc', 'malloc_varsize'):
526 return True
527 elif spaceop.opname == 'direct_call':
528 fnobj = spaceop.args[0].value._obj
529 if hasattr(fnobj, '_callable'):
530 oopspec = getattr(fnobj._callable, 'oopspec', None)
531 if oopspec and oopspec == 'newlist(length)':
532 return True
533 return False
534
535 def build_extra_funcs(self):
536 EXCDATA = self.EXCDATA
537 exc_data = self.exc_data_ptr
538
539 def rpyexc_get_exception_addr():
540 return (llmemory.cast_ptr_to_adr(exc_data) +
541 llmemory.offsetof(EXCDATA, 'exc_type'))
542
543 def rpyexc_get_exc_value_addr():
544 return (llmemory.cast_ptr_to_adr(exc_data) +
545 llmemory.offsetof(EXCDATA, 'exc_value'))
546
547 self.rpyexc_get_exception_addr_ptr = self.build_func(
548 "RPyGetExceptionAddr",
549 rpyexc_get_exception_addr,
550 [], llmemory.Address)
551
552 self.rpyexc_get_exc_value_addr_ptr = self.build_func(
553 "RPyGetExcValueAddr",
554 rpyexc_get_exc_value_addr,
555 [], llmemory.Address)