Debian Codegraph @

mypyc/analysis/dataflow.py

raw
1 """Data-flow analyses."""
2
3 from __future__ import annotations
4
5 from abc import abstractmethod
6 from collections.abc import Iterable, Iterator, Set as AbstractSet
7 from typing import Any, Generic, TypeVar
8
9 from mypyc.ir.ops import (
10 Assign,
11 AssignMulti,
12 BasicBlock,
13 Box,
14 Branch,
15 Call,
16 CallC,
17 Cast,
18 ComparisonOp,
19 ControlOp,
20 DecRef,
21 Extend,
22 Float,
23 FloatComparisonOp,
24 FloatNeg,
25 FloatOp,
26 GetAttr,
27 GetElement,
28 GetElementPtr,
29 Goto,
30 IncRef,
31 InitStatic,
32 Integer,
33 IntOp,
34 KeepAlive,
35 LoadAddress,
36 LoadErrorValue,
37 LoadGlobal,
38 LoadLiteral,
39 LoadMem,
40 LoadStatic,
41 MethodCall,
42 Op,
43 OpVisitor,
44 PrimitiveOp,
45 RaiseStandardError,
46 RegisterOp,
47 Return,
48 SetAttr,
49 SetElement,
50 SetMem,
51 Truncate,
52 TupleGet,
53 TupleSet,
54 Unborrow,
55 Unbox,
56 Undef,
57 Unreachable,
58 Value,
59 )
60
61
62 class CFG:
63 """Control-flow graph.
64
65 Node 0 is always assumed to be the entry point. There must be a
66 non-empty set of exits.
67 """
68
69 def __init__(
70 self,
71 succ: dict[BasicBlock, list[BasicBlock]],
72 pred: dict[BasicBlock, list[BasicBlock]],
73 exits: set[BasicBlock],
74 ) -> None:
75 assert exits
76 self.succ = succ
77 self.pred = pred
78 self.exits = exits
79
80 def __str__(self) -> str:
81 exits = sorted(self.exits, key=lambda e: int(e.label))
82 return f"exits: {exits}\nsucc: {self.succ}\npred: {self.pred}"
83
84
85 def get_cfg(blocks: list[BasicBlock], *, use_yields: bool = False) -> CFG:
86 """Calculate basic block control-flow graph.
87
88 If use_yields is set, then we treat returns inserted by yields as gotos
89 instead of exits.
90 """
91 succ_map = {}
92 pred_map: dict[BasicBlock, list[BasicBlock]] = {}
93 exits = set()
94 for block in blocks:
95 assert not any(
96 isinstance(op, ControlOp) for op in block.ops[:-1]
97 ), "Control-flow ops must be at the end of blocks"
98
99 if use_yields and isinstance(block.terminator, Return) and block.terminator.yield_target:
100 succ = [block.terminator.yield_target]
101 else:
102 succ = list(block.terminator.targets())
103 if not succ:
104 exits.add(block)
105
106 # Errors can occur anywhere inside a block, which means that
107 # we can't assume that the entire block has executed before
108 # jumping to the error handler. In our CFG construction, we
109 # model this as saying that a block can jump to its error
110 # handler or the error handlers of any of its normal
111 # successors (to represent an error before that next block
112 # completes). This works well for analyses like "must
113 # defined", where it implies that registers assigned in a
114 # block may be undefined in its error handler, but is in
115 # general not a precise representation of reality; any
116 # analyses that require more fidelity must wait until after
117 # exception insertion.
118 for error_point in [block] + succ:
119 if error_point.error_handler:
120 succ.append(error_point.error_handler)
121
122 succ_map[block] = succ
123 pred_map[block] = []
124 for prev, nxt in succ_map.items():
125 for label in nxt:
126 pred_map[label].append(prev)
127 return CFG(succ_map, pred_map, exits)
128
129
130 def get_real_target(label: BasicBlock) -> BasicBlock:
131 if len(label.ops) == 1 and isinstance(label.ops[-1], Goto):
132 label = label.ops[-1].label
133 return label
134
135
136 def cleanup_cfg(blocks: list[BasicBlock]) -> None:
137 """Cleanup the control flow graph.
138
139 This eliminates obviously dead basic blocks and eliminates blocks that contain
140 nothing but a single jump.
141
142 There is a lot more that could be done.
143 """
144 changed = True
145 while changed:
146 # First collapse any jumps to basic block that only contain a goto
147 for block in blocks:
148 for i, tgt in enumerate(block.terminator.targets()):
149 block.terminator.set_target(i, get_real_target(tgt))
150
151 # Then delete any blocks that have no predecessors
152 changed = False
153 cfg = get_cfg(blocks)
154 orig_blocks = blocks.copy()
155 blocks.clear()
156 for i, block in enumerate(orig_blocks):
157 if i == 0 or cfg.pred[block]:
158 blocks.append(block)
159 else:
160 changed = True
161
162
163 T = TypeVar("T")
164
165 AnalysisDict = dict[tuple[BasicBlock, int], set[T]]
166
167
168 class AnalysisResult(Generic[T]):
169 def __init__(self, before: AnalysisDict[T], after: AnalysisDict[T]) -> None:
170 self.before = before
171 self.after = after
172
173 def __str__(self) -> str:
174 return f"before: {self.before}\nafter: {self.after}\n"
175
176
177 GenAndKill = tuple[AbstractSet[T], AbstractSet[T]]
178
179 _EMPTY: tuple[frozenset[Any], frozenset[Any]] = (frozenset(), frozenset())
180
181
182 class BaseAnalysisVisitor(OpVisitor[GenAndKill[T]]):
183 def visit_goto(self, op: Goto) -> GenAndKill[T]:
184 return _EMPTY
185
186 @abstractmethod
187 def visit_register_op(self, op: RegisterOp) -> GenAndKill[T]:
188 raise NotImplementedError
189
190 @abstractmethod
191 def visit_assign(self, op: Assign) -> GenAndKill[T]:
192 raise NotImplementedError
193
194 @abstractmethod
195 def visit_assign_multi(self, op: AssignMulti) -> GenAndKill[T]:
196 raise NotImplementedError
197
198 @abstractmethod
199 def visit_set_mem(self, op: SetMem) -> GenAndKill[T]:
200 raise NotImplementedError
201
202 def visit_inc_ref(self, op: IncRef) -> GenAndKill[T]:
203 return self.visit_register_op(op)
204
205 def visit_dec_ref(self, op: DecRef) -> GenAndKill[T]:
206 return self.visit_register_op(op)
207
208 def visit_call(self, op: Call) -> GenAndKill[T]:
209 return self.visit_register_op(op)
210
211 def visit_method_call(self, op: MethodCall) -> GenAndKill[T]:
212 return self.visit_register_op(op)
213
214 def visit_load_error_value(self, op: LoadErrorValue) -> GenAndKill[T]:
215 return self.visit_register_op(op)
216
217 def visit_load_literal(self, op: LoadLiteral) -> GenAndKill[T]:
218 return self.visit_register_op(op)
219
220 def visit_get_attr(self, op: GetAttr) -> GenAndKill[T]:
221 return self.visit_register_op(op)
222
223 def visit_set_attr(self, op: SetAttr) -> GenAndKill[T]:
224 return self.visit_register_op(op)
225
226 def visit_load_static(self, op: LoadStatic) -> GenAndKill[T]:
227 return self.visit_register_op(op)
228
229 def visit_init_static(self, op: InitStatic) -> GenAndKill[T]:
230 return self.visit_register_op(op)
231
232 def visit_tuple_get(self, op: TupleGet) -> GenAndKill[T]:
233 return self.visit_register_op(op)
234
235 def visit_tuple_set(self, op: TupleSet) -> GenAndKill[T]:
236 return self.visit_register_op(op)
237
238 def visit_box(self, op: Box) -> GenAndKill[T]:
239 return self.visit_register_op(op)
240
241 def visit_unbox(self, op: Unbox) -> GenAndKill[T]:
242 return self.visit_register_op(op)
243
244 def visit_cast(self, op: Cast) -> GenAndKill[T]:
245 return self.visit_register_op(op)
246
247 def visit_raise_standard_error(self, op: RaiseStandardError) -> GenAndKill[T]:
248 return self.visit_register_op(op)
249
250 def visit_call_c(self, op: CallC) -> GenAndKill[T]:
251 return self.visit_register_op(op)
252
253 def visit_primitive_op(self, op: PrimitiveOp) -> GenAndKill[T]:
254 return self.visit_register_op(op)
255
256 def visit_truncate(self, op: Truncate) -> GenAndKill[T]:
257 return self.visit_register_op(op)
258
259 def visit_extend(self, op: Extend) -> GenAndKill[T]:
260 return self.visit_register_op(op)
261
262 def visit_load_global(self, op: LoadGlobal) -> GenAndKill[T]:
263 return self.visit_register_op(op)
264
265 def visit_int_op(self, op: IntOp) -> GenAndKill[T]:
266 return self.visit_register_op(op)
267
268 def visit_float_op(self, op: FloatOp) -> GenAndKill[T]:
269 return self.visit_register_op(op)
270
271 def visit_float_neg(self, op: FloatNeg) -> GenAndKill[T]:
272 return self.visit_register_op(op)
273
274 def visit_comparison_op(self, op: ComparisonOp) -> GenAndKill[T]:
275 return self.visit_register_op(op)
276
277 def visit_float_comparison_op(self, op: FloatComparisonOp) -> GenAndKill[T]:
278 return self.visit_register_op(op)
279
280 def visit_load_mem(self, op: LoadMem) -> GenAndKill[T]:
281 return self.visit_register_op(op)
282
283 def visit_get_element(self, op: GetElement) -> GenAndKill[T]:
284 return self.visit_register_op(op)
285
286 def visit_get_element_ptr(self, op: GetElementPtr) -> GenAndKill[T]:
287 return self.visit_register_op(op)
288
289 def visit_set_element(self, op: SetElement) -> GenAndKill[T]:
290 return self.visit_register_op(op)
291
292 def visit_load_address(self, op: LoadAddress) -> GenAndKill[T]:
293 return self.visit_register_op(op)
294
295 def visit_keep_alive(self, op: KeepAlive) -> GenAndKill[T]:
296 return self.visit_register_op(op)
297
298 def visit_unborrow(self, op: Unborrow) -> GenAndKill[T]:
299 return self.visit_register_op(op)
300
301
302 class DefinedVisitor(BaseAnalysisVisitor[Value]):
303 """Visitor for finding defined registers.
304
305 Note that this only deals with registers and not temporaries, on
306 the assumption that we never access temporaries when they might be
307 undefined.
308
309 If strict_errors is True, then we regard any use of LoadErrorValue
310 as making a register undefined. Otherwise we only do if
311 `undefines` is set on the error value.
312
313 This lets us only consider the things we care about during
314 uninitialized variable checking while capturing all possibly
315 undefined things for refcounting.
316 """
317
318 def __init__(self, strict_errors: bool = False) -> None:
319 self.strict_errors = strict_errors
320
321 def visit_branch(self, op: Branch) -> GenAndKill[Value]:
322 return _EMPTY
323
324 def visit_return(self, op: Return) -> GenAndKill[Value]:
325 return _EMPTY
326
327 def visit_unreachable(self, op: Unreachable) -> GenAndKill[Value]:
328 return _EMPTY
329
330 def visit_register_op(self, op: RegisterOp) -> GenAndKill[Value]:
331 return _EMPTY
332
333 def visit_assign(self, op: Assign) -> GenAndKill[Value]:
334 # Loading an error value may undefine the register.
335 if isinstance(op.src, LoadErrorValue) and (op.src.undefines or self.strict_errors):
336 return set(), {op.dest}
337 else:
338 return {op.dest}, set()
339
340 def visit_assign_multi(self, op: AssignMulti) -> GenAndKill[Value]:
341 # Array registers are special and we don't track the definedness of them.
342 return _EMPTY
343
344 def visit_set_mem(self, op: SetMem) -> GenAndKill[Value]:
345 return _EMPTY
346
347
348 def analyze_maybe_defined_regs(
349 blocks: list[BasicBlock], cfg: CFG, initial_defined: set[Value]
350 ) -> AnalysisResult[Value]:
351 """Calculate potentially defined registers at each CFG location.
352
353 A register is defined if it has a value along some path from the initial location.
354 """
355 return run_analysis(
356 blocks=blocks,
357 cfg=cfg,
358 gen_and_kill=DefinedVisitor(),
359 initial=initial_defined,
360 backward=False,
361 kind=MAYBE_ANALYSIS,
362 )
363
364
365 def analyze_must_defined_regs(
366 blocks: list[BasicBlock],
367 cfg: CFG,
368 initial_defined: set[Value],
369 regs: Iterable[Value],
370 strict_errors: bool = False,
371 ) -> AnalysisResult[Value]:
372 """Calculate always defined registers at each CFG location.
373
374 This analysis can work before exception insertion, since it is a
375 sound assumption that registers defined in a block might not be
376 initialized in its error handler.
377
378 A register is defined if it has a value along all paths from the
379 initial location.
380 """
381 return run_analysis(
382 blocks=blocks,
383 cfg=cfg,
384 gen_and_kill=DefinedVisitor(strict_errors=strict_errors),
385 initial=initial_defined,
386 backward=False,
387 kind=MUST_ANALYSIS,
388 universe=set(regs),
389 )
390
391
392 class BorrowedArgumentsVisitor(BaseAnalysisVisitor[Value]):
393 def __init__(self, args: set[Value]) -> None:
394 self.args = args
395
396 def visit_branch(self, op: Branch) -> GenAndKill[Value]:
397 return _EMPTY
398
399 def visit_return(self, op: Return) -> GenAndKill[Value]:
400 return _EMPTY
401
402 def visit_unreachable(self, op: Unreachable) -> GenAndKill[Value]:
403 return _EMPTY
404
405 def visit_register_op(self, op: RegisterOp) -> GenAndKill[Value]:
406 return _EMPTY
407
408 def visit_assign(self, op: Assign) -> GenAndKill[Value]:
409 if op.dest in self.args:
410 return set(), {op.dest}
411 return _EMPTY
412
413 def visit_assign_multi(self, op: AssignMulti) -> GenAndKill[Value]:
414 return _EMPTY
415
416 def visit_set_mem(self, op: SetMem) -> GenAndKill[Value]:
417 return _EMPTY
418
419
420 def analyze_borrowed_arguments(
421 blocks: list[BasicBlock], cfg: CFG, borrowed: set[Value]
422 ) -> AnalysisResult[Value]:
423 """Calculate arguments that can use references borrowed from the caller.
424
425 When assigning to an argument, it no longer is borrowed.
426 """
427 return run_analysis(
428 blocks=blocks,
429 cfg=cfg,
430 gen_and_kill=BorrowedArgumentsVisitor(borrowed),
431 initial=borrowed,
432 backward=False,
433 kind=MUST_ANALYSIS,
434 universe=borrowed,
435 )
436
437
438 class UndefinedVisitor(BaseAnalysisVisitor[Value]):
439 def visit_branch(self, op: Branch) -> GenAndKill[Value]:
440 return _EMPTY
441
442 def visit_return(self, op: Return) -> GenAndKill[Value]:
443 return _EMPTY
444
445 def visit_unreachable(self, op: Unreachable) -> GenAndKill[Value]:
446 return _EMPTY
447
448 def visit_register_op(self, op: RegisterOp) -> GenAndKill[Value]:
449 return set(), {op} if not op.is_void else set()
450
451 def visit_assign(self, op: Assign) -> GenAndKill[Value]:
452 return set(), {op.dest}
453
454 def visit_assign_multi(self, op: AssignMulti) -> GenAndKill[Value]:
455 return set(), {op.dest}
456
457 def visit_set_mem(self, op: SetMem) -> GenAndKill[Value]:
458 return _EMPTY
459
460
461 def non_trivial_sources(op: Op) -> set[Value]:
462 result = set()
463 for source in op.sources():
464 if not isinstance(source, (Integer, Float, Undef)):
465 result.add(source)
466 return result
467
468
469 class LivenessVisitor(BaseAnalysisVisitor[Value]):
470 def visit_branch(self, op: Branch) -> GenAndKill[Value]:
471 return non_trivial_sources(op), set()
472
473 def visit_return(self, op: Return) -> GenAndKill[Value]:
474 if not isinstance(op.value, (Integer, Float)):
475 return {op.value}, set()
476 else:
477 return _EMPTY
478
479 def visit_unreachable(self, op: Unreachable) -> GenAndKill[Value]:
480 return _EMPTY
481
482 def visit_register_op(self, op: RegisterOp) -> GenAndKill[Value]:
483 gen = non_trivial_sources(op)
484 if not op.is_void:
485 return gen, {op}
486 else:
487 return gen, set()
488
489 def visit_assign(self, op: Assign) -> GenAndKill[Value]:
490 return non_trivial_sources(op), {op.dest}
491
492 def visit_assign_multi(self, op: AssignMulti) -> GenAndKill[Value]:
493 return non_trivial_sources(op), {op.dest}
494
495 def visit_set_mem(self, op: SetMem) -> GenAndKill[Value]:
496 return non_trivial_sources(op), set()
497
498 def visit_inc_ref(self, op: IncRef) -> GenAndKill[Value]:
499 return _EMPTY
500
501 def visit_dec_ref(self, op: DecRef) -> GenAndKill[Value]:
502 return _EMPTY
503
504
505 def analyze_live_regs(blocks: list[BasicBlock], cfg: CFG) -> AnalysisResult[Value]:
506 """Calculate live registers at each CFG location.
507
508 A register is live at a location if it can be read along some CFG path starting
509 from the location.
510 """
511 return run_analysis(
512 blocks=blocks,
513 cfg=cfg,
514 gen_and_kill=LivenessVisitor(),
515 initial=set(),
516 backward=True,
517 kind=MAYBE_ANALYSIS,
518 )
519
520
521 # Analysis kinds
522 MUST_ANALYSIS = 0
523 MAYBE_ANALYSIS = 1
524
525
526 def run_analysis(
527 blocks: list[BasicBlock],
528 cfg: CFG,
529 gen_and_kill: OpVisitor[GenAndKill[T]],
530 initial: set[T],
531 kind: int,
532 backward: bool,
533 universe: set[T] | None = None,
534 ) -> AnalysisResult[T]:
535 """Run a general set-based data flow analysis.
536
537 Args:
538 blocks: All basic blocks
539 cfg: Control-flow graph for the code
540 gen_and_kill: Implementation of gen and kill functions for each op
541 initial: Value of analysis for the entry points (for a forward analysis) or the
542 exit points (for a backward analysis)
543 kind: MUST_ANALYSIS or MAYBE_ANALYSIS
544 backward: If False, the analysis is a forward analysis; it's backward otherwise
545 universe: For a must analysis, the set of all possible values. This is the starting
546 value for the work list algorithm, which will narrow this down until reaching a
547 fixed point. For a maybe analysis the iteration always starts from an empty set
548 and this argument is ignored.
549
550 Return analysis results: (before, after)
551 """
552 block_gen = {}
553 block_kill = {}
554
555 # Calculate kill and gen sets for entire basic blocks.
556 for block in blocks:
557 gen: set[T] = set()
558 kill: set[T] = set()
559 ops = block.ops
560 if backward:
561 ops = list(reversed(ops))
562 for op in ops:
563 opgen, opkill = op.accept(gen_and_kill)
564 if opkill:
565 gen -= opkill
566
567 if opgen:
568 gen |= opgen
569 kill -= opgen
570
571 if opkill:
572 kill |= opkill
573
574 block_gen[block] = gen
575 block_kill[block] = kill
576
577 # Set up initial state for worklist algorithm.
578 worklist = list(blocks)
579 if not backward:
580 worklist.reverse() # Reverse for a small performance improvement
581 workset = set(worklist)
582 before: dict[BasicBlock, set[T]] = {}
583 after: dict[BasicBlock, set[T]] = {}
584 for block in blocks:
585 if kind == MAYBE_ANALYSIS:
586 before[block] = set()
587 after[block] = set()
588 else:
589 assert universe is not None, "Universe must be defined for a must analysis"
590 before[block] = set(universe)
591 after[block] = set(universe)
592
593 if backward:
594 pred_map = cfg.succ
595 succ_map = cfg.pred
596 else:
597 pred_map = cfg.pred
598 succ_map = cfg.succ
599
600 # Run work list algorithm to generate in and out sets for each basic block.
601 while worklist:
602 label = worklist.pop()
603 workset.remove(label)
604 if pred_map[label]:
605 new_before: set[T] | None = None
606 for pred in pred_map[label]:
607 if new_before is None:
608 new_before = set(after[pred])
609 elif kind == MAYBE_ANALYSIS:
610 new_before |= after[pred]
611 else:
612 new_before &= after[pred]
613 assert new_before is not None
614 else:
615 new_before = set(initial)
616 before[label] = new_before
617 new_after = (new_before - block_kill[label]) | block_gen[label]
618 if new_after != after[label]:
619 for succ in succ_map[label]:
620 if succ not in workset:
621 worklist.append(succ)
622 workset.add(succ)
623 after[label] = new_after
624
625 # Run algorithm for each basic block to generate opcode-level sets.
626 op_before: dict[tuple[BasicBlock, int], set[T]] = {}
627 op_after: dict[tuple[BasicBlock, int], set[T]] = {}
628 for block in blocks:
629 label = block
630 cur = before[label]
631 ops_enum: Iterator[tuple[int, Op]] = enumerate(block.ops)
632 if backward:
633 ops_enum = reversed(list(ops_enum))
634 for idx, op in ops_enum:
635 op_before[label, idx] = cur
636 opgen, opkill = op.accept(gen_and_kill)
637 if opkill:
638 cur = cur - opkill
639 if opgen:
640 cur = cur | opgen
641 op_after[label, idx] = cur
642 if backward:
643 op_after, op_before = op_before, op_after
644
645 return AnalysisResult(op_before, op_after)