Debian Codegraph @

mypyc/ir/pprint.py

raw
1 """Utilities for pretty-printing IR in a human-readable form."""
2
3 from __future__ import annotations
4
5 from collections import defaultdict
6 from collections.abc import Sequence
7 from typing import Any, Final
8
9 from mypyc.common import short_name
10 from mypyc.ir.func_ir import FuncIR, all_values_full
11 from mypyc.ir.module_ir import ModuleIRs
12 from mypyc.ir.ops import (
13 ERR_NEVER,
14 Assign,
15 AssignMulti,
16 BasicBlock,
17 Box,
18 Branch,
19 Call,
20 CallC,
21 Cast,
22 ComparisonOp,
23 ControlOp,
24 CString,
25 DecRef,
26 Extend,
27 Float,
28 FloatComparisonOp,
29 FloatNeg,
30 FloatOp,
31 GetAttr,
32 GetElement,
33 GetElementPtr,
34 Goto,
35 IncRef,
36 InitStatic,
37 Integer,
38 IntOp,
39 KeepAlive,
40 LoadAddress,
41 LoadErrorValue,
42 LoadGlobal,
43 LoadLiteral,
44 LoadMem,
45 LoadStatic,
46 MethodCall,
47 Op,
48 OpVisitor,
49 PrimitiveOp,
50 RaiseStandardError,
51 Register,
52 Return,
53 SetAttr,
54 SetElement,
55 SetMem,
56 Truncate,
57 TupleGet,
58 TupleSet,
59 Unborrow,
60 Unbox,
61 Undef,
62 Unreachable,
63 Value,
64 )
65 from mypyc.ir.rtypes import RType, is_bool_rprimitive, is_int_rprimitive
66
67 ErrorSource = BasicBlock | Op
68
69
70 class IRPrettyPrintVisitor(OpVisitor[str]):
71 """Internal visitor that pretty-prints ops."""
72
73 def __init__(self, names: dict[Value, str]) -> None:
74 # This should contain a name for all values that are shown as
75 # registers in the output. This is not just for Register
76 # instances -- all Ops that produce values need (generated) names.
77 self.names = names
78
79 def visit_goto(self, op: Goto) -> str:
80 return self.format("goto %l", op.label)
81
82 branch_op_names: Final = {Branch.BOOL: ("%r", "bool"), Branch.IS_ERROR: ("is_error(%r)", "")}
83
84 def visit_branch(self, op: Branch) -> str:
85 fmt, typ = self.branch_op_names[op.op]
86 if op.negated:
87 fmt = f"not {fmt}"
88
89 cond = self.format(fmt, op.value)
90 tb = ""
91 if op.traceback_entry:
92 tb = " (error at %s:%d)" % op.traceback_entry
93 fmt = f"if {cond} goto %l{tb} else goto %l"
94 if typ:
95 fmt += f" :: {typ}"
96 return self.format(fmt, op.true, op.false)
97
98 def visit_return(self, op: Return) -> str:
99 return self.format("return %r", op.value)
100
101 def visit_unreachable(self, op: Unreachable) -> str:
102 return "unreachable"
103
104 def visit_assign(self, op: Assign) -> str:
105 return self.format("%r = %r", op.dest, op.src)
106
107 def visit_assign_multi(self, op: AssignMulti) -> str:
108 return self.format("%r = [%s]", op.dest, ", ".join(self.format("%r", v) for v in op.src))
109
110 def visit_load_error_value(self, op: LoadErrorValue) -> str:
111 return self.format("%r = <error> :: %s", op, op.type)
112
113 def visit_load_literal(self, op: LoadLiteral) -> str:
114 prefix = ""
115 # For values that have a potential unboxed representation, make
116 # it explicit that this is a Python object.
117 if isinstance(op.value, int):
118 prefix = "object "
119
120 rvalue = repr(op.value)
121 if isinstance(op.value, frozenset):
122 # We need to generate a string representation that won't vary
123 # run-to-run because sets are unordered, otherwise we may get
124 # spurious irbuild test failures.
125 #
126 # Sorting by the item's string representation is a bit of a
127 # hack, but it's stable and won't cause TypeErrors.
128 formatted_items = [repr(i) for i in sorted(op.value, key=str)]
129 rvalue = "frozenset({" + ", ".join(formatted_items) + "})"
130 return self.format("%r = %s%s", op, prefix, rvalue)
131
132 def visit_get_attr(self, op: GetAttr) -> str:
133 return self.format("%r = %s%r.%s", op, self.borrow_prefix(op), op.obj, op.attr)
134
135 def borrow_prefix(self, op: Op) -> str:
136 if op.is_borrowed:
137 return "borrow "
138 return ""
139
140 def visit_set_attr(self, op: SetAttr) -> str:
141 if op.is_init:
142 assert op.error_kind == ERR_NEVER
143 if op.error_kind == ERR_NEVER:
144 # Initialization and direct struct access can never fail
145 return self.format("%r.%s = %r", op.obj, op.attr, op.src)
146 else:
147 return self.format("%r.%s = %r; %r = is_error", op.obj, op.attr, op.src, op)
148
149 def visit_load_static(self, op: LoadStatic) -> str:
150 ann = f" ({repr(op.ann)})" if op.ann else ""
151 name = op.identifier
152 if op.module_name is not None:
153 name = f"{op.module_name}.{name}"
154 return self.format("%r = %s :: %s%s", op, name, op.namespace, ann)
155
156 def visit_init_static(self, op: InitStatic) -> str:
157 name = op.identifier
158 if op.module_name is not None:
159 name = f"{op.module_name}.{name}"
160 return self.format("%s = %r :: %s", name, op.value, op.namespace)
161
162 def visit_tuple_get(self, op: TupleGet) -> str:
163 return self.format("%r = %s%r[%d]", op, self.borrow_prefix(op), op.src, op.index)
164
165 def visit_tuple_set(self, op: TupleSet) -> str:
166 item_str = ", ".join(self.format("%r", item) for item in op.items)
167 return self.format("%r = (%s)", op, item_str)
168
169 def visit_inc_ref(self, op: IncRef) -> str:
170 s = self.format("inc_ref %r", op.src)
171 # TODO: Remove bool check (it's unboxed)
172 if is_bool_rprimitive(op.src.type) or is_int_rprimitive(op.src.type):
173 s += f" :: {short_name(op.src.type.name)}"
174 return s
175
176 def visit_dec_ref(self, op: DecRef) -> str:
177 s = self.format("%sdec_ref %r", "x" if op.is_xdec else "", op.src)
178 # TODO: Remove bool check (it's unboxed)
179 if is_bool_rprimitive(op.src.type) or is_int_rprimitive(op.src.type):
180 s += f" :: {short_name(op.src.type.name)}"
181 return s
182
183 def visit_call(self, op: Call) -> str:
184 args = ", ".join(self.format("%r", arg) for arg in op.args)
185 # TODO: Display long name?
186 short_name = op.fn.shortname
187 s = f"{short_name}({args})"
188 if not op.is_void:
189 s = self.format("%r = ", op) + s
190 return s
191
192 def visit_method_call(self, op: MethodCall) -> str:
193 args = ", ".join(self.format("%r", arg) for arg in op.args)
194 s = self.format("%r.%s(%s)", op.obj, op.method, args)
195 if not op.is_void:
196 s = self.format("%r = ", op) + s
197 return s
198
199 def visit_cast(self, op: Cast) -> str:
200 if op.is_unchecked:
201 prefix = "unchecked "
202 else:
203 prefix = ""
204 return self.format(
205 "%r = %s%scast(%s, %r)", op, prefix, self.borrow_prefix(op), op.type, op.src
206 )
207
208 def visit_box(self, op: Box) -> str:
209 return self.format("%r = box(%s, %r)", op, op.src.type, op.src)
210
211 def visit_unbox(self, op: Unbox) -> str:
212 return self.format("%r = unbox(%s, %r)", op, op.type, op.src)
213
214 def visit_raise_standard_error(self, op: RaiseStandardError) -> str:
215 if op.value is not None:
216 if isinstance(op.value, str):
217 return self.format("%r = raise %s(%s)", op, op.class_name, repr(op.value))
218 elif isinstance(op.value, Value):
219 return self.format("%r = raise %s(%r)", op, op.class_name, op.value)
220 else:
221 assert False, "value type must be either str or Value"
222 else:
223 return self.format("%r = raise %s", op, op.class_name)
224
225 def visit_call_c(self, op: CallC) -> str:
226 args_str = ", ".join(self.format("%r", arg) for arg in op.args)
227 if op.is_void:
228 return self.format("%s(%s)", op.function_name, args_str)
229 else:
230 return self.format("%r = %s(%s)", op, op.function_name, args_str)
231
232 def visit_primitive_op(self, op: PrimitiveOp) -> str:
233 args_str = ", ".join(self.format("%r", arg) for arg in op.args)
234 if op.is_void:
235 return self.format("%s %s", op.desc.name, args_str)
236 else:
237 return self.format("%r = %s %s", op, op.desc.name, args_str)
238
239 def visit_truncate(self, op: Truncate) -> str:
240 return self.format("%r = truncate %r: %t to %t", op, op.src, op.src_type, op.type)
241
242 def visit_extend(self, op: Extend) -> str:
243 if op.signed:
244 extra = " signed"
245 else:
246 extra = ""
247 return self.format("%r = extend%s %r: %t to %t", op, extra, op.src, op.src_type, op.type)
248
249 def visit_load_global(self, op: LoadGlobal) -> str:
250 ann = f" ({repr(op.ann)})" if op.ann else ""
251 return self.format("%r = load_global %s :: static%s", op, op.identifier, ann)
252
253 def visit_int_op(self, op: IntOp) -> str:
254 return self.format("%r = %r %s %r", op, op.lhs, IntOp.op_str[op.op], op.rhs)
255
256 def visit_comparison_op(self, op: ComparisonOp) -> str:
257 if op.op in (ComparisonOp.SLT, ComparisonOp.SGT, ComparisonOp.SLE, ComparisonOp.SGE):
258 sign_format = " :: signed"
259 elif op.op in (ComparisonOp.ULT, ComparisonOp.UGT, ComparisonOp.ULE, ComparisonOp.UGE):
260 sign_format = " :: unsigned"
261 else:
262 sign_format = ""
263 return self.format(
264 "%r = %r %s %r%s", op, op.lhs, ComparisonOp.op_str[op.op], op.rhs, sign_format
265 )
266
267 def visit_float_op(self, op: FloatOp) -> str:
268 return self.format("%r = %r %s %r", op, op.lhs, FloatOp.op_str[op.op], op.rhs)
269
270 def visit_float_neg(self, op: FloatNeg) -> str:
271 return self.format("%r = -%r", op, op.src)
272
273 def visit_float_comparison_op(self, op: FloatComparisonOp) -> str:
274 return self.format("%r = %r %s %r", op, op.lhs, op.op_str[op.op], op.rhs)
275
276 def visit_load_mem(self, op: LoadMem) -> str:
277 return self.format(
278 "%r = %sload_mem %r :: %t*", op, self.borrow_prefix(op), op.src, op.type
279 )
280
281 def visit_set_mem(self, op: SetMem) -> str:
282 return self.format("set_mem %r, %r :: %t*", op.dest, op.src, op.dest_type)
283
284 def visit_get_element(self, op: GetElement) -> str:
285 return self.format("%r = %r.%s", op, op.src, op.field)
286
287 def visit_get_element_ptr(self, op: GetElementPtr) -> str:
288 return self.format("%r = get_element_ptr %r %s :: %t", op, op.src, op.field, op.src_type)
289
290 def visit_set_element(self, op: SetElement) -> str:
291 return self.format("%r = set_element %r, %s, %r", op, op.src, op.field, op.item)
292
293 def visit_load_address(self, op: LoadAddress) -> str:
294 if isinstance(op.src, Register):
295 return self.format("%r = load_address %r", op, op.src)
296 elif isinstance(op.src, LoadStatic):
297 name = op.src.identifier
298 if op.src.module_name is not None:
299 name = f"{op.src.module_name}.{name}"
300 return self.format("%r = load_address %s :: %s", op, name, op.src.namespace)
301 else:
302 return self.format("%r = load_address %s", op, op.src)
303
304 def visit_keep_alive(self, op: KeepAlive) -> str:
305 if op.steal:
306 steal = "steal "
307 else:
308 steal = ""
309 return self.format(
310 "keep_alive {}{}".format(steal, ", ".join(self.format("%r", v) for v in op.src))
311 )
312
313 def visit_unborrow(self, op: Unborrow) -> str:
314 return self.format("%r = unborrow %r", op, op.src)
315
316 # Helpers
317
318 def format(self, fmt: str, *args: Any) -> str:
319 """Helper for formatting strings.
320
321 These format sequences are supported in fmt:
322
323 %s: arbitrary object converted to string using str()
324 %r: name of IR value/register
325 %d: int
326 %f: float
327 %l: BasicBlock (formatted as label 'Ln')
328 %t: RType
329 """
330 result = []
331 i = 0
332 arglist = list(args)
333 while i < len(fmt):
334 n = fmt.find("%", i)
335 if n < 0:
336 n = len(fmt)
337 result.append(fmt[i:n])
338 if n < len(fmt):
339 typespec = fmt[n + 1]
340 arg = arglist.pop(0)
341 if typespec == "r":
342 # Register/value
343 assert isinstance(arg, Value)
344 if isinstance(arg, Integer):
345 result.append(str(arg.value))
346 elif isinstance(arg, Float):
347 result.append(repr(arg.value))
348 elif isinstance(arg, CString):
349 result.append(f"CString({arg.value!r})")
350 elif isinstance(arg, Undef):
351 result.append(f"undef {arg.type.name}")
352 else:
353 result.append(self.names[arg])
354 elif typespec == "d":
355 # Integer
356 result.append("%d" % arg)
357 elif typespec == "f":
358 # Float
359 result.append("%f" % arg)
360 elif typespec == "l":
361 # Basic block (label)
362 assert isinstance(arg, BasicBlock)
363 result.append("L%s" % arg.label)
364 elif typespec == "t":
365 # RType
366 assert isinstance(arg, RType)
367 result.append(arg.name)
368 elif typespec == "s":
369 # String
370 result.append(str(arg))
371 else:
372 raise ValueError(f"Invalid format sequence %{typespec}")
373 i = n + 2
374 else:
375 i = n
376 return "".join(result)
377
378
379 def format_registers(func_ir: FuncIR, names: dict[Value, str]) -> list[str]:
380 result = []
381 i = 0
382 regs = all_values_full(func_ir.arg_regs, func_ir.blocks)
383 while i < len(regs):
384 i0 = i
385 group = [names[regs[i0]]]
386 while i + 1 < len(regs) and regs[i + 1].type == regs[i0].type:
387 i += 1
388 group.append(names[regs[i]])
389 i += 1
390 result.append("{} :: {}".format(", ".join(group), regs[i0].type))
391 return result
392
393
394 def format_blocks(
395 blocks: list[BasicBlock],
396 names: dict[Value, str],
397 source_to_error: dict[ErrorSource, list[str]],
398 ) -> list[str]:
399 """Format a list of IR basic blocks into a human-readable form."""
400 # First label all of the blocks
401 for i, block in enumerate(blocks):
402 block.label = i
403
404 handler_map: dict[BasicBlock, list[BasicBlock]] = {}
405 for b in blocks:
406 if b.error_handler:
407 handler_map.setdefault(b.error_handler, []).append(b)
408
409 visitor = IRPrettyPrintVisitor(names)
410
411 lines = []
412 for i, block in enumerate(blocks):
413 handler_msg = ""
414 if block in handler_map:
415 labels = sorted("L%d" % b.label for b in handler_map[block])
416 handler_msg = " (handler for {})".format(", ".join(labels))
417
418 lines.append("L%d:%s" % (block.label, handler_msg))
419 if block in source_to_error:
420 for error in source_to_error[block]:
421 lines.append(f" ERROR: {error}")
422 ops = block.ops
423 if (
424 isinstance(ops[-1], Goto)
425 and i + 1 < len(blocks)
426 and ops[-1].label == blocks[i + 1]
427 and not source_to_error.get(ops[-1], [])
428 ):
429 # Hide the last goto if it just goes to the next basic block,
430 # and there are no assocatiated errors with the op.
431 ops = ops[:-1]
432 for op in ops:
433 line = " " + op.accept(visitor)
434 lines.append(line)
435 if op in source_to_error:
436 first = len(lines) - 1
437 # Use emojis to highlight the error
438 for error in source_to_error[op]:
439 lines.append(f" \U0001f446 ERROR: {error}")
440 lines[first] = " \U0000274c " + lines[first][4:]
441
442 if not isinstance(block.ops[-1], (Goto, Branch, Return, Unreachable)):
443 # Each basic block needs to exit somewhere.
444 lines.append(" [MISSING BLOCK EXIT OPCODE]")
445 return lines
446
447
448 def format_func(fn: FuncIR, errors: Sequence[tuple[ErrorSource, str]] = ()) -> list[str]:
449 lines = []
450 cls_prefix = fn.class_name + "." if fn.class_name else ""
451 lines.append(
452 "def {}{}({}):".format(cls_prefix, fn.name, ", ".join(arg.name for arg in fn.args))
453 )
454 names = generate_names_for_ir(fn.arg_regs, fn.blocks)
455 for line in format_registers(fn, names):
456 lines.append(" " + line)
457
458 source_to_error = defaultdict(list)
459 for source, error in errors:
460 source_to_error[source].append(error)
461
462 code = format_blocks(fn.blocks, names, source_to_error)
463 lines.extend(code)
464 return lines
465
466
467 def format_modules(modules: ModuleIRs) -> list[str]:
468 ops = []
469 for module in modules.values():
470 for fn in module.functions:
471 ops.extend(format_func(fn))
472 ops.append("")
473 return ops
474
475
476 def generate_names_for_ir(args: list[Register], blocks: list[BasicBlock]) -> dict[Value, str]:
477 """Generate unique names for IR values.
478
479 Give names such as 'r5' to temp values in IR which are useful when
480 pretty-printing or generating C. Ensure generated names are unique.
481 """
482 names: dict[Value, str] = {}
483 used_names = set()
484
485 temp_index = 0
486
487 for arg in args:
488 names[arg] = arg.name
489 used_names.add(arg.name)
490
491 for block in blocks:
492 for op in block.ops:
493 values = []
494
495 for source in op.sources():
496 if source not in names:
497 values.append(source)
498
499 if isinstance(op, (Assign, AssignMulti)):
500 values.append(op.dest)
501 elif isinstance(op, ControlOp) or op.is_void:
502 continue
503 elif op not in names:
504 values.append(op)
505
506 for value in values:
507 if value in names:
508 continue
509 if isinstance(value, Register) and value.name:
510 name = value.name
511 elif isinstance(value, (Integer, Float, Undef)):
512 continue
513 else:
514 name = "r%d" % temp_index
515 temp_index += 1
516
517 # Append _2, _3, ... if needed to make the name unique.
518 if name in used_names:
519 n = 2
520 while True:
521 candidate = "%s_%d" % (name, n)
522 if candidate not in used_names:
523 name = candidate
524 break
525 n += 1
526
527 names[value] = name
528 used_names.add(name)
529
530 return names