Debian Codegraph @

mypyc/transform/exceptions.py

raw
1 """Transform that inserts error checks after opcodes.
2
3 When initially building the IR, the code doesn't perform error checks
4 for exceptions. This module is used to insert all required error checks
5 afterwards. Each Op describes how it indicates an error condition (if
6 at all).
7
8 We need to split basic blocks on each error check since branches can
9 only be placed at the end of a basic block.
10 """
11
12 from __future__ import annotations
13
14 from mypyc.ir.func_ir import FuncIR
15 from mypyc.ir.ops import (
16 ERR_ALWAYS,
17 ERR_FALSE,
18 ERR_MAGIC,
19 ERR_MAGIC_OVERLAPPING,
20 ERR_NEVER,
21 NO_TRACEBACK_LINE_NO,
22 BasicBlock,
23 Branch,
24 CallC,
25 ComparisonOp,
26 Float,
27 GetAttr,
28 Integer,
29 LoadErrorValue,
30 Op,
31 RegisterOp,
32 Return,
33 SetAttr,
34 TupleGet,
35 Value,
36 )
37 from mypyc.ir.rtypes import RTuple, bool_rprimitive, is_float_rprimitive
38 from mypyc.primitives.exc_ops import err_occurred_op
39 from mypyc.primitives.registry import CFunctionDescription
40
41
42 def insert_exception_handling(ir: FuncIR, strict_traceback_checks: bool) -> None:
43 # Generate error block if any ops may raise an exception. If an op
44 # fails without its own error handler, we'll branch to this
45 # block. The block just returns an error value.
46 error_label: BasicBlock | None = None
47 for block in ir.blocks:
48 adjust_error_kinds(block)
49 if error_label is None and any(op.can_raise() for op in block.ops):
50 error_label = add_default_handler_block(ir)
51 if error_label:
52 ir.blocks = split_blocks_at_errors(
53 ir.blocks, error_label, ir.traceback_name, strict_traceback_checks
54 )
55
56
57 def add_default_handler_block(ir: FuncIR) -> BasicBlock:
58 block = BasicBlock()
59 ir.blocks.append(block)
60 op = LoadErrorValue(ir.ret_type)
61 block.ops.append(op)
62 block.ops.append(Return(op))
63 return block
64
65
66 def split_blocks_at_errors(
67 blocks: list[BasicBlock],
68 default_error_handler: BasicBlock,
69 func_name: str | None,
70 strict_traceback_checks: bool,
71 ) -> list[BasicBlock]:
72 new_blocks: list[BasicBlock] = []
73
74 # First split blocks on ops that may raise.
75 for block in blocks:
76 ops = block.ops
77 block.ops = []
78 cur_block = block
79 new_blocks.append(cur_block)
80
81 # If the block has an error handler specified, use it. Otherwise
82 # fall back to the default.
83 error_label = block.error_handler or default_error_handler
84 block.error_handler = None
85
86 for op in ops:
87 target: Value = op
88 cur_block.ops.append(op)
89 if isinstance(op, RegisterOp) and op.error_kind != ERR_NEVER:
90 # Split
91 new_block = BasicBlock()
92 new_blocks.append(new_block)
93
94 if op.error_kind == ERR_MAGIC:
95 # Op returns an error value on error that depends on result RType.
96 variant = Branch.IS_ERROR
97 negated = False
98 elif op.error_kind == ERR_FALSE:
99 # Op returns a C false value on error.
100 variant = Branch.BOOL
101 negated = True
102 elif op.error_kind == ERR_ALWAYS:
103 variant = Branch.BOOL
104 negated = True
105 # this is a hack to represent the always fail
106 # semantics, using a temporary bool with value false
107 target = Integer(0, bool_rprimitive)
108 elif op.error_kind == ERR_MAGIC_OVERLAPPING:
109 comp = insert_overlapping_error_value_check(cur_block.ops, target)
110 new_block2 = BasicBlock()
111 new_blocks.append(new_block2)
112 branch = Branch(
113 comp,
114 true_label=new_block2,
115 false_label=new_block,
116 op=Branch.BOOL,
117 rare=True,
118 )
119 cur_block.ops.append(branch)
120 cur_block = new_block2
121 target = primitive_call(err_occurred_op, [], target.line)
122 cur_block.ops.append(target)
123 variant = Branch.IS_ERROR
124 negated = True
125 else:
126 assert False, "unknown error kind %d" % op.error_kind
127
128 # Void ops can't generate errors since error is always
129 # indicated by a special value stored in a register.
130 if op.error_kind != ERR_ALWAYS:
131 assert not op.is_void, "void op generating errors?"
132
133 branch = Branch(
134 target, true_label=error_label, false_label=new_block, op=variant, line=op.line
135 )
136 branch.negated = negated
137 if op.line != NO_TRACEBACK_LINE_NO and func_name is not None:
138 if strict_traceback_checks:
139 assert (
140 op.line >= 0
141 ), f"Cannot add a traceback entry with a negative line number for op {op}"
142 branch.traceback_entry = (func_name, op.line)
143 cur_block.ops.append(branch)
144 cur_block = new_block
145
146 return new_blocks
147
148
149 def primitive_call(desc: CFunctionDescription, args: list[Value], line: int) -> CallC:
150 return CallC(
151 desc.c_function_name,
152 [],
153 desc.return_type,
154 desc.steals,
155 desc.is_borrowed,
156 desc.error_kind,
157 line,
158 dependencies=desc.dependencies,
159 )
160
161
162 def adjust_error_kinds(block: BasicBlock) -> None:
163 """Infer more precise error_kind attributes for ops.
164
165 We have access here to more information than what was available
166 when the IR was initially built.
167 """
168 for op in block.ops:
169 if isinstance(op, GetAttr):
170 if op.class_type.class_ir.is_always_defined(op.attr):
171 op.error_kind = ERR_NEVER
172 if isinstance(op, SetAttr):
173 if op.class_type.class_ir.is_always_defined(op.attr):
174 op.error_kind = ERR_NEVER
175
176
177 def insert_overlapping_error_value_check(ops: list[Op], target: Value) -> ComparisonOp:
178 """Append to ops to check for an overlapping error value."""
179 typ = target.type
180 if isinstance(typ, RTuple):
181 item = TupleGet(target, 0)
182 ops.append(item)
183 return insert_overlapping_error_value_check(ops, item)
184 else:
185 errvalue: Value
186 if is_float_rprimitive(target.type):
187 errvalue = Float(float(typ.c_undefined))
188 else:
189 errvalue = Integer(int(typ.c_undefined), rtype=typ)
190 op = ComparisonOp(target, errvalue, ComparisonOp.EQ)
191 ops.append(op)
192 return op