Debian Codegraph @

mypyc/transform/spill.py

raw
1 """Insert spills for values that are live across yields."""
2
3 from __future__ import annotations
4
5 from collections.abc import Collection
6 from typing import cast
7
8 from mypyc.analysis.dataflow import AnalysisResult, analyze_live_regs, get_cfg
9 from mypyc.common import TEMP_ATTR_NAME
10 from mypyc.ir.class_ir import ClassIR
11 from mypyc.ir.func_ir import FuncIR
12 from mypyc.ir.ops import (
13 BasicBlock,
14 Branch,
15 DecRef,
16 GetAttr,
17 IncRef,
18 LoadErrorValue,
19 Op,
20 Register,
21 SetAttr,
22 Value,
23 )
24
25
26 def insert_spills(ir: FuncIR, env: ClassIR) -> None:
27 cfg = get_cfg(ir.blocks, use_yields=True)
28 live = analyze_live_regs(ir.blocks, cfg)
29 entry_live = live.before[ir.blocks[0], 0]
30
31 entry_live = {op for op in entry_live if not (isinstance(op, Register) and op.is_arg)}
32 # TODO: Actually for now, no Registers at all -- we keep the manual spills
33 entry_live = {op for op in entry_live if not isinstance(op, Register)}
34
35 ir.blocks = spill_regs(ir.blocks, env, entry_live, live, ir.arg_regs[0])
36
37
38 def sort_values(values: Collection[Op], blocks: list[BasicBlock]) -> list[Op]:
39 if len(values) > 1:
40 order = {}
41 i = 0
42 for block in blocks:
43 for op in block.ops:
44 order[op] = i
45 i += 1
46 return sorted(values, key=lambda v: order[v])
47 else:
48 return list(values)
49
50
51 def spill_regs(
52 blocks: list[BasicBlock],
53 env: ClassIR,
54 to_spill: set[Value],
55 live: AnalysisResult[Value],
56 self_reg: Register,
57 ) -> list[BasicBlock]:
58 env_reg: Value
59 for op in blocks[0].ops:
60 if isinstance(op, GetAttr) and op.attr == "__mypyc_env__":
61 env_reg = op
62 break
63 else:
64 # Environment has been merged into generator object
65 env_reg = self_reg
66
67 spill_locs = {}
68 # Sort values to make the order deterministic. All the spilled values are
69 # known to be Op instances, so the cast is safe.
70 for i, val in enumerate(sort_values(cast(set[Op], to_spill), blocks)):
71 name = f"{TEMP_ATTR_NAME}2_{i}"
72 env.attributes[name] = val.type
73 if val.type.error_overlap:
74 # We can safely treat as always initialized, since the type has no pointers.
75 # This way we also don't need to manage the defined attribute bitfield.
76 env._always_initialized_attrs.add(name)
77 spill_locs[val] = name
78
79 for block in blocks:
80 ops = block.ops
81 block.ops = []
82
83 for i, op in enumerate(ops):
84 to_decref = []
85
86 if isinstance(op, IncRef) and op.src in spill_locs:
87 raise AssertionError("not sure what to do with an incref of a spill...")
88 if isinstance(op, DecRef) and op.src in spill_locs:
89 # When we decref a spilled value, we turn that into
90 # NULLing out the attribute, but only if the spilled
91 # value is not live *when we include yields in the
92 # CFG*. (The original decrefs are computed without that.)
93 #
94 # We also skip a decref is the env register is not
95 # live. That should only happen when an exception is
96 # being raised, so everything should be handled there.
97 if op.src not in live.after[block, i] and env_reg in live.after[block, i]:
98 # Skip the DecRef but null out the spilled location
99 null = LoadErrorValue(op.src.type)
100 block.ops.extend([null, SetAttr(env_reg, spill_locs[op.src], null, op.line)])
101 continue
102
103 if (
104 any(src in spill_locs for src in op.sources())
105 # N.B: IS_ERROR should be before a spill happens
106 # XXX: but could we have a regular branch?
107 and not (isinstance(op, Branch) and op.op == Branch.IS_ERROR)
108 ):
109 new_sources: list[Value] = []
110 stolen = op.stolen()
111 for src in op.sources():
112 if src in spill_locs:
113 read = GetAttr(env_reg, spill_locs[src], op.line)
114 block.ops.append(read)
115 new_sources.append(read)
116 if src.type.is_refcounted and src not in stolen:
117 to_decref.append(read)
118 else:
119 new_sources.append(src)
120
121 op.set_sources(new_sources)
122
123 block.ops.append(op)
124
125 for dec in to_decref:
126 block.ops.append(DecRef(dec))
127
128 if op in spill_locs:
129 # XXX: could we set uninit?
130 block.ops.append(SetAttr(env_reg, spill_locs[op], op, op.line))
131
132 return blocks