Debian Codegraph @

mypyc/transform/uninit.py

raw
1 """Insert checks for uninitialized values."""
2
3 from __future__ import annotations
4
5 from mypyc.analysis.dataflow import AnalysisDict, analyze_must_defined_regs, cleanup_cfg, get_cfg
6 from mypyc.common import BITMAP_BITS
7 from mypyc.ir.func_ir import FuncIR, all_values
8 from mypyc.ir.ops import (
9 Assign,
10 BasicBlock,
11 Branch,
12 ComparisonOp,
13 Integer,
14 IntOp,
15 LoadAddress,
16 LoadErrorValue,
17 Op,
18 RaiseStandardError,
19 Register,
20 Unreachable,
21 Value,
22 )
23 from mypyc.ir.rtypes import bitmap_rprimitive
24
25
26 def insert_uninit_checks(ir: FuncIR, strict_traceback_checks: bool) -> None:
27 # Remove dead blocks from the CFG, which helps avoid spurious
28 # checks due to unused error handling blocks.
29 cleanup_cfg(ir.blocks)
30
31 cfg = get_cfg(ir.blocks)
32 must_defined = analyze_must_defined_regs(
33 ir.blocks, cfg, set(ir.arg_regs), all_values(ir.arg_regs, ir.blocks)
34 )
35
36 ir.blocks = split_blocks_at_uninits(ir.blocks, must_defined.before, strict_traceback_checks)
37
38
39 def split_blocks_at_uninits(
40 blocks: list[BasicBlock], pre_must_defined: AnalysisDict[Value], strict_traceback_checks: bool
41 ) -> list[BasicBlock]:
42 new_blocks: list[BasicBlock] = []
43
44 init_registers = []
45 init_registers_set = set()
46 bitmap_registers: list[Register] = [] # Init status bitmaps
47 bitmap_backed: list[Register] = [] # These use bitmaps to track init status
48
49 # First split blocks on ops that may raise.
50 for block in blocks:
51 ops = block.ops
52 block.ops = []
53 cur_block = block
54 new_blocks.append(cur_block)
55
56 for i, op in enumerate(ops):
57 defined = pre_must_defined[block, i]
58 for src in op.unique_sources():
59 # If a register operand is not guaranteed to be
60 # initialized is an operand to something other than a
61 # check that it is defined, insert a check.
62
63 # Note that for register operand in a LoadAddress op,
64 # we should be able to use it without initialization
65 # as we may need to use its address to update itself
66 if (
67 isinstance(src, Register)
68 and src not in defined
69 and not (isinstance(op, Branch) and op.op == Branch.IS_ERROR)
70 and not isinstance(op, LoadAddress)
71 ):
72 if src not in init_registers_set:
73 init_registers.append(src)
74 init_registers_set.add(src)
75
76 # XXX: if src.name is empty, it should be a
77 # temp... and it should be OK??
78 if not src.name:
79 continue
80
81 new_block, error_block = BasicBlock(), BasicBlock()
82 new_block.error_handler = error_block.error_handler = cur_block.error_handler
83 new_blocks += [error_block, new_block]
84
85 if not src.type.error_overlap:
86 cur_block.ops.append(
87 Branch(
88 src,
89 true_label=error_block,
90 false_label=new_block,
91 op=Branch.IS_ERROR,
92 line=op.line,
93 )
94 )
95 else:
96 # We need to use bitmap for this one.
97 check_for_uninit_using_bitmap(
98 cur_block.ops,
99 src,
100 bitmap_registers,
101 bitmap_backed,
102 error_block,
103 new_block,
104 op.line,
105 )
106
107 if strict_traceback_checks:
108 assert (
109 op.line >= 0
110 ), f"Cannot raise an error with a negative line number for op {op}"
111 raise_std = RaiseStandardError(
112 RaiseStandardError.UNBOUND_LOCAL_ERROR,
113 f'local variable "{src.name}" referenced before assignment',
114 op.line,
115 )
116 error_block.ops.append(raise_std)
117 error_block.ops.append(Unreachable())
118 cur_block = new_block
119 cur_block.ops.append(op)
120
121 if bitmap_backed:
122 update_register_assignments_to_set_bitmap(new_blocks, bitmap_registers, bitmap_backed)
123
124 if init_registers:
125 new_ops: list[Op] = []
126 for reg in init_registers:
127 err = LoadErrorValue(reg.type, undefines=True)
128 new_ops.append(err)
129 new_ops.append(Assign(reg, err))
130 for reg in bitmap_registers:
131 new_ops.append(Assign(reg, Integer(0, bitmap_rprimitive)))
132 new_blocks[0].ops[0:0] = new_ops
133
134 return new_blocks
135
136
137 def check_for_uninit_using_bitmap(
138 ops: list[Op],
139 src: Register,
140 bitmap_registers: list[Register],
141 bitmap_backed: list[Register],
142 error_block: BasicBlock,
143 ok_block: BasicBlock,
144 line: int,
145 ) -> None:
146 """Check if src is defined using a bitmap.
147
148 Modifies ops, bitmap_registers and bitmap_backed.
149 """
150 if src not in bitmap_backed:
151 # Set up a new bitmap backed register.
152 bitmap_backed.append(src)
153 n = (len(bitmap_backed) - 1) // BITMAP_BITS
154 if len(bitmap_registers) <= n:
155 bitmap_registers.append(Register(bitmap_rprimitive, f"__locals_bitmap{n}"))
156
157 index = bitmap_backed.index(src)
158 masked = IntOp(
159 bitmap_rprimitive,
160 bitmap_registers[index // BITMAP_BITS],
161 Integer(1 << (index & (BITMAP_BITS - 1)), bitmap_rprimitive),
162 IntOp.AND,
163 line,
164 )
165 ops.append(masked)
166 chk = ComparisonOp(masked, Integer(0, bitmap_rprimitive), ComparisonOp.EQ)
167 ops.append(chk)
168 ops.append(Branch(chk, error_block, ok_block, Branch.BOOL))
169
170
171 def update_register_assignments_to_set_bitmap(
172 blocks: list[BasicBlock], bitmap_registers: list[Register], bitmap_backed: list[Register]
173 ) -> None:
174 """Update some assignments to registers to also set a bit in a bitmap.
175
176 The bitmaps are used to track if a local variable has been assigned to.
177
178 Modifies blocks.
179 """
180 for block in blocks:
181 if any(isinstance(op, Assign) and op.dest in bitmap_backed for op in block.ops):
182 new_ops: list[Op] = []
183 for op in block.ops:
184 if isinstance(op, Assign) and op.dest in bitmap_backed:
185 index = bitmap_backed.index(op.dest)
186 new_ops.append(op)
187 reg = bitmap_registers[index // BITMAP_BITS]
188 new = IntOp(
189 bitmap_rprimitive,
190 reg,
191 Integer(1 << (index & (BITMAP_BITS - 1)), bitmap_rprimitive),
192 IntOp.OR,
193 op.line,
194 )
195 new_ops.append(new)
196 new_ops.append(Assign(reg, new))
197 else:
198 new_ops.append(op)
199 block.ops = new_ops