Debian Codegraph @

mypyc/codegen/emitfunc.py

raw
1 """Code generation for native function bodies."""
2
3 from __future__ import annotations
4
5 from typing import Final
6
7 from mypyc.analysis.blockfreq import frequently_executed_blocks
8 from mypyc.codegen.emit import (
9 DEBUG_ERRORS,
10 PREFIX_MAP,
11 Emitter,
12 TracebackAndGotoHandler,
13 c_array_initializer,
14 )
15 from mypyc.common import GENERATOR_ATTRIBUTE_PREFIX, HAVE_IMMORTAL, NATIVE_PREFIX, REG_PREFIX
16 from mypyc.ir.class_ir import ClassIR
17 from mypyc.ir.func_ir import FUNC_CLASSMETHOD, FUNC_STATICMETHOD, FuncDecl, FuncIR, all_values
18 from mypyc.ir.ops import (
19 ERR_FALSE,
20 NAMESPACE_TYPE,
21 Assign,
22 AssignMulti,
23 BasicBlock,
24 Box,
25 Branch,
26 Call,
27 CallC,
28 Cast,
29 ComparisonOp,
30 ControlOp,
31 CString,
32 DecRef,
33 Extend,
34 Float,
35 FloatComparisonOp,
36 FloatNeg,
37 FloatOp,
38 GetAttr,
39 GetElement,
40 GetElementPtr,
41 Goto,
42 IncRef,
43 InitStatic,
44 Integer,
45 IntOp,
46 KeepAlive,
47 LoadAddress,
48 LoadErrorValue,
49 LoadGlobal,
50 LoadLiteral,
51 LoadMem,
52 LoadStatic,
53 MethodCall,
54 Op,
55 OpVisitor,
56 PrimitiveOp,
57 RaiseStandardError,
58 Register,
59 Return,
60 SetAttr,
61 SetElement,
62 SetMem,
63 Truncate,
64 TupleGet,
65 TupleSet,
66 Unborrow,
67 Unbox,
68 Undef,
69 Unreachable,
70 Value,
71 )
72 from mypyc.ir.pprint import generate_names_for_ir
73 from mypyc.ir.rtypes import (
74 RArray,
75 RInstance,
76 RStruct,
77 RTuple,
78 RType,
79 RVec,
80 is_bool_or_bit_rprimitive,
81 is_int32_rprimitive,
82 is_int64_rprimitive,
83 is_int_rprimitive,
84 is_none_rprimitive,
85 is_pointer_rprimitive,
86 is_tagged,
87 )
88
89 VEC_ITEMS_C_TYPE: Final = {
90 "VecI64": "int64_t *",
91 "VecI32": "int32_t *",
92 "VecI16": "int16_t *",
93 "VecU8": "uint8_t *",
94 "VecFloat": "double *",
95 "VecBool": "char *",
96 "VecT": "PyObject **",
97 "VecNested": "VecNestedBufItem *",
98 "VecNestedBufItem": "void *",
99 }
100
101
102 def native_function_type(fn: FuncIR, emitter: Emitter) -> str:
103 return native_function_type_from_decl(fn.decl, emitter)
104
105
106 def native_function_type_from_decl(decl: FuncDecl, emitter: Emitter) -> str:
107 args = ", ".join(emitter.ctype(arg.type) for arg in decl.sig.args) or "void"
108 ret = emitter.ctype(decl.sig.ret_type)
109 return f"{ret} (*)({args})"
110
111
112 def native_function_header(fn: FuncDecl, emitter: Emitter) -> str:
113 args = []
114 for arg in fn.sig.args:
115 args.append(f"{emitter.ctype_spaced(arg.type)}{REG_PREFIX}{arg.name}")
116
117 return "{ret_type}{name}({args})".format(
118 ret_type=emitter.ctype_spaced(fn.sig.ret_type),
119 name=emitter.native_function_name(fn),
120 args=", ".join(args) or "void",
121 )
122
123
124 def generate_native_function(
125 fn: FuncIR, emitter: Emitter, source_path: str, module_name: str
126 ) -> None:
127 declarations = Emitter(emitter.context)
128 names = generate_names_for_ir(fn.arg_regs, fn.blocks)
129 body = Emitter(emitter.context, names)
130 visitor = FunctionEmitterVisitor(body, declarations, source_path, module_name)
131
132 declarations.emit_line(f"{native_function_header(fn.decl, emitter)} {{")
133 body.indent()
134
135 for r in all_values(fn.arg_regs, fn.blocks):
136 if isinstance(r.type, RTuple):
137 emitter.declare_tuple_struct(r.type)
138 if isinstance(r.type, RArray):
139 continue # Special: declared on first assignment
140
141 if r in fn.arg_regs:
142 continue # Skip the arguments
143
144 ctype = emitter.ctype_spaced(r.type)
145 init = ""
146 declarations.emit_line(
147 "{ctype}{prefix}{name}{init};".format(
148 ctype=ctype, prefix=REG_PREFIX, name=names[r], init=init
149 )
150 )
151
152 # Before we emit the blocks, give them all labels
153 blocks = fn.blocks
154 for i, block in enumerate(blocks):
155 block.label = i
156
157 # Find blocks that are never jumped to or are only jumped to from the
158 # block directly above it. This allows for more labels and gotos to be
159 # eliminated during code generation.
160 for block in fn.blocks:
161 terminator = block.terminator
162 assert isinstance(terminator, ControlOp), terminator
163
164 for target in terminator.targets():
165 is_next_block = target.label == block.label + 1
166
167 # Always emit labels for GetAttr error checks since the emit code that
168 # generates them will add instructions between the branch and the
169 # next label, causing the label to be wrongly removed. A better
170 # solution would be to change the IR so that it adds a basic block
171 # in between the calls.
172 is_problematic_op = isinstance(terminator, Branch) and any(
173 isinstance(s, GetAttr) for s in terminator.sources()
174 )
175
176 if not is_next_block or is_problematic_op:
177 fn.blocks[target.label].referenced = True
178
179 common = frequently_executed_blocks(fn.blocks[0])
180
181 for i in range(len(blocks)):
182 block = blocks[i]
183 visitor.rare = block not in common
184 next_block = None
185 if i + 1 < len(blocks):
186 next_block = blocks[i + 1]
187 body.emit_label(block)
188 visitor.next_block = next_block
189
190 ops = block.ops
191 visitor.ops = ops
192 visitor.op_index = 0
193 while visitor.op_index < len(ops):
194 ops[visitor.op_index].accept(visitor)
195 visitor.op_index += 1
196
197 body.emit_line("}")
198
199 emitter.emit_from_emitter(declarations)
200 emitter.emit_from_emitter(body)
201
202
203 class FunctionEmitterVisitor(OpVisitor[None]):
204 def __init__(
205 self, emitter: Emitter, declarations: Emitter, source_path: str, module_name: str
206 ) -> None:
207 self.emitter = emitter
208 self.names = emitter.names
209 self.declarations = declarations
210 self.source_path = source_path
211 self.module_name = module_name
212 self.literals = emitter.context.literals
213 self.rare = False
214 # Next basic block to be processed after the current one (if any), set by caller
215 self.next_block: BasicBlock | None = None
216 # Ops in the basic block currently being processed, set by caller
217 self.ops: list[Op] = []
218 # Current index within ops; visit methods can increment this to skip/merge ops
219 self.op_index = 0
220
221 def temp_name(self) -> str:
222 return self.emitter.temp_name()
223
224 def visit_goto(self, op: Goto) -> None:
225 if op.label is not self.next_block:
226 self.emit_line("goto %s;" % self.label(op.label))
227
228 def error_value_check(self, value: Value, compare: str) -> str:
229 typ = value.type
230 if isinstance(typ, RTuple):
231 # TODO: What about empty tuple?
232 return self.emitter.tuple_undefined_check_cond(
233 typ, self.reg(value), self.c_error_value, compare
234 )
235 elif isinstance(typ, RVec):
236 # Error values for vecs are represented by a negative length.
237 vec_compare = ">=" if compare == "!=" else "<"
238 return f"{self.reg(value)}.len {vec_compare} 0"
239 else:
240 return f"{self.reg(value)} {compare} {self.c_error_value(typ)}"
241
242 def visit_branch(self, op: Branch) -> None:
243 true, false = op.true, op.false
244 negated = op.negated
245 negated_rare = False
246 if true is self.next_block and op.traceback_entry is None:
247 # Switch true/false since it avoids an else block.
248 true, false = false, true
249 negated = not negated
250 negated_rare = True
251
252 neg = "!" if negated else ""
253 cond = ""
254 if op.op == Branch.BOOL:
255 expr_result = self.reg(op.value)
256 cond = f"{neg}{expr_result}"
257 elif op.op == Branch.IS_ERROR:
258 compare = "!=" if negated else "=="
259 cond = self.error_value_check(op.value, compare)
260 else:
261 assert False, "Invalid branch"
262
263 # For error checks, tell the compiler the branch is unlikely
264 if op.traceback_entry is not None or op.rare:
265 if not negated_rare:
266 cond = f"unlikely({cond})"
267 else:
268 cond = f"likely({cond})"
269
270 if false is self.next_block:
271 if op.traceback_entry is None:
272 if true is not self.next_block:
273 self.emit_line(f"if ({cond}) goto {self.label(true)};")
274 else:
275 self.emit_line(f"if ({cond}) {{")
276 self.emit_traceback(op)
277 self.emit_lines("goto %s;" % self.label(true), "}")
278 else:
279 self.emit_line(f"if ({cond}) {{")
280 self.emit_traceback(op)
281
282 if true is not self.next_block:
283 self.emit_line("goto %s;" % self.label(true))
284
285 self.emit_lines("} else", " goto %s;" % self.label(false))
286
287 def visit_return(self, op: Return) -> None:
288 value_str = self.reg(op.value)
289 self.emit_line("return %s;" % value_str)
290
291 def visit_tuple_set(self, op: TupleSet) -> None:
292 dest = self.reg(op)
293 tuple_type = op.tuple_type
294 self.emitter.declare_tuple_struct(tuple_type)
295 if len(op.items) == 0: # empty tuple
296 self.emit_line(f"{dest}.empty_struct_error_flag = 0;")
297 else:
298 for i, item in enumerate(op.items):
299 self.emit_line(f"{dest}.f{i} = {self.reg(item)};")
300
301 def visit_assign(self, op: Assign) -> None:
302 dest = self.reg(op.dest)
303 src = self.reg(op.src)
304 # clang whines about self assignment (which we might generate
305 # for some casts), so don't emit it.
306 if dest != src:
307 src_type = op.src.type
308 dest_type = op.dest.type
309 if src_type.is_unboxed and not dest_type.is_unboxed:
310 # We sometimes assign from an integer prepresentation of a pointer
311 # to a real pointer, and C compilers insist on a cast.
312 src = f"(void *){src}"
313 elif not src_type.is_unboxed and dest_type.is_unboxed:
314 # We sometimes assign a pointer to an integer type (e.g. to create
315 # tagged pointers), and here we need an explicit cast.
316 src = f"({self.emitter.ctype(dest_type)}){src}"
317 self.emit_line(f"{dest} = {src};")
318
319 def visit_assign_multi(self, op: AssignMulti) -> None:
320 typ = op.dest.type
321 assert isinstance(typ, RArray), typ
322 dest = self.reg(op.dest)
323 # RArray values can only be assigned to once, so we can always
324 # declare them on initialization.
325 self.emit_line(
326 "%s%s[%d] = %s;"
327 % (
328 self.emitter.ctype_spaced(typ.item_type),
329 dest,
330 len(op.src),
331 c_array_initializer([self.reg(s) for s in op.src], indented=True),
332 )
333 )
334
335 def visit_load_error_value(self, op: LoadErrorValue) -> None:
336 reg = self.reg(op)
337 if isinstance(op.type, RTuple):
338 values = [self.c_undefined_value(item) for item in op.type.types]
339 tmp = self.temp_name()
340 self.emit_line("{} {} = {{ {} }};".format(self.ctype(op.type), tmp, ", ".join(values)))
341 self.emit_line(f"{reg} = {tmp};")
342 elif isinstance(op.type, RVec):
343 self.emitter.set_undefined_value(reg, op.type)
344 else:
345 self.emit_line(f"{self.reg(op)} = {self.c_error_value(op.type)};")
346
347 def visit_load_literal(self, op: LoadLiteral) -> None:
348 index = self.literals.literal_index(op.value)
349 if not is_int_rprimitive(op.type):
350 self.emit_line("%s = CPyStatics[%d];" % (self.reg(op), index), ann=op.value)
351 else:
352 self.emit_line(
353 "%s = (CPyTagged)CPyStatics[%d] | 1;" % (self.reg(op), index), ann=op.value
354 )
355
356 def get_attr_expr(self, obj: str, op: GetAttr | SetAttr, decl_cl: ClassIR) -> str:
357 """Generate attribute accessor for normal (non-property) access.
358
359 This either has a form like obj->attr_name for attributes defined in non-trait
360 classes, and *(obj + attr_offset) for attributes defined by traits. We also
361 insert all necessary C casts here.
362 """
363 # The struct cast below needs the defining group's __native.h
364 # included by the consuming .c file. Record both the receiver
365 # and declaring classes as cross-group deps.
366 self.emitter.register_group_dep(op.class_type.class_ir)
367 self.emitter.register_group_dep(decl_cl)
368 cast = f"({op.class_type.struct_name(self.emitter.names)} *)"
369 if decl_cl.is_trait and op.class_type.class_ir.is_trait:
370 # For pure trait access find the offset first, offsets
371 # are ordered by attribute position in the cl.attributes dict.
372 # TODO: pre-calculate the mapping to make this faster.
373 trait_attr_index = list(decl_cl.attributes).index(op.attr)
374 # TODO: reuse these names somehow?
375 offset = self.emitter.temp_name()
376 self.declarations.emit_line(f"size_t {offset};")
377 self.emitter.emit_line(
378 "{} = {};".format(
379 offset,
380 "CPy_FindAttrOffset({}, {}, {})".format(
381 self.emitter.type_struct_name(decl_cl),
382 f"({cast}{obj})->vtable",
383 trait_attr_index,
384 ),
385 )
386 )
387 attr_cast = f"({self.ctype(op.class_type.attr_type(op.attr))} *)"
388 return f"*{attr_cast}((char *){obj} + {offset})"
389 else:
390 # Cast to something non-trait. Note: for this to work, all struct
391 # members for non-trait classes must obey monotonic linear growth.
392 if op.class_type.class_ir.is_trait:
393 assert not decl_cl.is_trait
394 cast = f"({decl_cl.struct_name(self.emitter.names)} *)"
395 return f"({cast}{obj})->{self.emitter.attr(op.attr)}"
396
397 def visit_get_attr(self, op: GetAttr) -> None:
398 if op.allow_error_value:
399 self.get_attr_with_allow_error_value(op)
400 return
401 dest = self.reg(op)
402 obj = self.reg(op.obj)
403 rtype = op.class_type
404 cl = rtype.class_ir
405 attr_rtype, decl_cl = cl.attr_details(op.attr)
406 prefer_method = cl.is_trait and attr_rtype.error_overlap
407 if cl.get_method(op.attr, prefer_method=prefer_method):
408 # Properties are essentially methods, so use vtable access for them
409 # (except for non-ext classes, which have no vtable — see emit_method_call).
410 if not cl.is_ext_class or cl.is_method_final(op.attr):
411 self.emit_method_call(f"{dest} = ", op.obj, op.attr, [])
412 else:
413 version = "_TRAIT" if cl.is_trait else ""
414 self.emit_line(
415 "%s = CPY_GET_ATTR%s(%s, %s, %d, %s, %s); /* %s */"
416 % (
417 dest,
418 version,
419 obj,
420 self.emitter.type_struct_name(rtype.class_ir),
421 rtype.getter_index(op.attr),
422 rtype.struct_name(self.names),
423 self.ctype(rtype.attr_type(op.attr)),
424 op.attr,
425 )
426 )
427 else:
428 # Otherwise, use direct or offset struct access.
429 attr_expr = self.get_attr_expr(obj, op, decl_cl)
430 self.emitter.emit_line(f"{dest} = {attr_expr};")
431 always_defined = cl.is_always_defined(op.attr)
432 merged_branch = None
433 if not always_defined:
434 self.emitter.emit_undefined_attr_check(
435 attr_rtype, dest, "==", obj, op.attr, cl, unlikely=True
436 )
437 branch = self.next_branch()
438 if branch is not None:
439 if (
440 branch.value is op
441 and branch.op == Branch.IS_ERROR
442 and branch.traceback_entry is not None
443 and not branch.negated
444 ):
445 # Generate code for the following branch here to avoid
446 # redundant branches in the generated code.
447 self.emit_attribute_error(branch, cl.name, op.attr)
448 self.emit_line("goto %s;" % self.label(branch.true))
449 merged_branch = branch
450 self.emitter.emit_line("}")
451 if not merged_branch:
452 exc_class = "PyExc_AttributeError"
453 self.emitter.emit_line(
454 'PyErr_SetString({}, "attribute {} of {} undefined");'.format(
455 exc_class,
456 repr(op.attr.removeprefix(GENERATOR_ATTRIBUTE_PREFIX)),
457 repr(cl.name),
458 )
459 )
460
461 if attr_rtype.is_refcounted and not op.is_borrowed:
462 if not merged_branch and not always_defined:
463 self.emitter.emit_line("} else {")
464 self.emitter.emit_inc_ref(dest, attr_rtype)
465 if merged_branch:
466 if merged_branch.false is not self.next_block:
467 self.emit_line("goto %s;" % self.label(merged_branch.false))
468 self.op_index += 1
469 elif not always_defined:
470 self.emitter.emit_line("}")
471
472 def get_attr_with_allow_error_value(self, op: GetAttr) -> None:
473 """Handle GetAttr with allow_error_value=True.
474
475 This allows NULL or other error value without raising AttributeError.
476 """
477 dest = self.reg(op)
478 obj = self.reg(op.obj)
479 rtype = op.class_type
480 cl = rtype.class_ir
481 attr_rtype, decl_cl = cl.attr_details(op.attr)
482
483 # Direct struct access without NULL check
484 attr_expr = self.get_attr_expr(obj, op, decl_cl)
485 self.emitter.emit_line(f"{dest} = {attr_expr};")
486
487 # Only emit inc_ref if not NULL
488 if attr_rtype.is_refcounted and not op.is_borrowed:
489 check = self.error_value_check(op, "!=")
490 self.emitter.emit_line(f"if ({check}) {{")
491 self.emitter.emit_inc_ref(dest, attr_rtype)
492 self.emitter.emit_line("}")
493
494 def next_branch(self) -> Branch | None:
495 if self.op_index + 1 < len(self.ops):
496 next_op = self.ops[self.op_index + 1]
497 if isinstance(next_op, Branch):
498 return next_op
499 return None
500
501 def visit_set_attr(self, op: SetAttr) -> None:
502 if op.error_kind == ERR_FALSE:
503 dest = self.reg(op)
504 obj = self.reg(op.obj)
505 src = self.reg(op.src)
506 rtype = op.class_type
507 cl = rtype.class_ir
508 attr_rtype, decl_cl = cl.attr_details(op.attr)
509 if op.is_propset:
510 # Again, use vtable access for properties...
511 assert not op.is_init and op.error_kind == ERR_FALSE, "%s %d %d %s" % (
512 op.attr,
513 op.is_init,
514 op.error_kind,
515 rtype,
516 )
517 version = "_TRAIT" if cl.is_trait else ""
518 self.emit_line(
519 "%s = CPY_SET_ATTR%s(%s, %s, %d, %s, %s, %s); /* %s */"
520 % (
521 dest,
522 version,
523 obj,
524 self.emitter.type_struct_name(rtype.class_ir),
525 rtype.setter_index(op.attr),
526 src,
527 rtype.struct_name(self.names),
528 self.ctype(rtype.attr_type(op.attr)),
529 op.attr,
530 )
531 )
532 else:
533 # ...and struct access for normal attributes.
534 attr_expr = self.get_attr_expr(obj, op, decl_cl)
535 if not op.is_init and attr_rtype.is_refcounted:
536 # This is not an initialization (where we know that the attribute was
537 # previously undefined), so decref the old value.
538 always_defined = cl.is_always_defined(op.attr)
539 if not always_defined:
540 self.emitter.emit_undefined_attr_check(
541 attr_rtype, attr_expr, "!=", obj, op.attr, cl
542 )
543 self.emitter.emit_dec_ref(attr_expr, attr_rtype)
544 if not always_defined:
545 self.emitter.emit_line("}")
546 elif attr_rtype.error_overlap and not cl.is_always_defined(op.attr):
547 # If there is overlap with the error value, update bitmap to mark
548 # attribute as defined.
549 self.emitter.emit_attr_bitmap_set(src, obj, attr_rtype, cl, op.attr)
550
551 # This steals the reference to src, so we don't need to increment the arg
552 self.emitter.emit_line(f"{attr_expr} = {src};")
553 if op.error_kind == ERR_FALSE:
554 self.emitter.emit_line(f"{dest} = 1;")
555
556 def visit_load_static(self, op: LoadStatic) -> None:
557 dest = self.reg(op)
558 prefix = PREFIX_MAP[op.namespace]
559 name = self.emitter.static_name(op.identifier, op.module_name, prefix)
560 if op.namespace == NAMESPACE_TYPE:
561 name = "(PyObject *)%s" % name
562 self.emit_line(f"{dest} = {name};", ann=op.ann)
563
564 def visit_init_static(self, op: InitStatic) -> None:
565 value = self.reg(op.value)
566 prefix = PREFIX_MAP[op.namespace]
567 name = self.emitter.static_name(op.identifier, op.module_name, prefix)
568 if op.namespace == NAMESPACE_TYPE:
569 value = "(PyTypeObject *)%s" % value
570 self.emit_line(f"{name} = {value};")
571 self.emit_inc_ref(name, op.value.type)
572
573 def visit_tuple_get(self, op: TupleGet) -> None:
574 dest = self.reg(op)
575 src = self.reg(op.src)
576 self.emit_line(f"{dest} = {src}.f{op.index};")
577 if not op.is_borrowed and op.type.is_refcounted:
578 self.emit_inc_ref(dest, op.type)
579
580 def get_dest_assign(self, dest: Value) -> str:
581 if not dest.is_void:
582 return self.reg(dest) + " = "
583 else:
584 return ""
585
586 def visit_call(self, op: Call) -> None:
587 """Call native function."""
588 dest = self.get_dest_assign(op)
589 args = ", ".join(self.reg(arg) for arg in op.args)
590 lib = self.emitter.get_group_prefix(op.fn)
591 cname = op.fn.cname(self.names)
592 self.emit_line(f"{dest}{lib}{NATIVE_PREFIX}{cname}({args});")
593
594 def visit_method_call(self, op: MethodCall) -> None:
595 """Call native method."""
596 dest = self.get_dest_assign(op)
597 self.emit_method_call(dest, op.obj, op.method, op.args)
598
599 def emit_method_call(self, dest: str, op_obj: Value, name: str, op_args: list[Value]) -> None:
600 obj = self.reg(op_obj)
601 rtype = op_obj.type
602 assert isinstance(rtype, RInstance), rtype
603 class_ir = rtype.class_ir
604 # Use method_decl (not get_method) because under separate compilation the
605 # FuncIR body may live in a different group — only its declaration is
606 # visible here, and a decl is all we need to emit a direct C call
607 # (the symbol resolves through that group's exports table).
608 method_decl = rtype.class_ir.method_decl(name)
609
610 # Can we call the method directly, bypassing vtable? Non-extension classes
611 # don't have a vtable (compute_vtable is skipped for them), so the only
612 # way to dispatch is a direct C call.
613 is_direct = not class_ir.is_ext_class or class_ir.is_method_final(name)
614
615 # The first argument gets omitted for static methods and
616 # turned into the class for class methods
617 obj_args = (
618 []
619 if method_decl.kind == FUNC_STATICMETHOD
620 else [f"(PyObject *)Py_TYPE({obj})"] if method_decl.kind == FUNC_CLASSMETHOD else [obj]
621 )
622 args = ", ".join(obj_args + [self.reg(arg) for arg in op_args])
623 mtype = native_function_type_from_decl(method_decl, self.emitter)
624 version = "_TRAIT" if rtype.class_ir.is_trait else ""
625 if is_direct:
626 # Directly call method, without going through the vtable.
627 self.emit_line(f"{dest}{self.emitter.native_function_call(method_decl)}({args});")
628 else:
629 # Call using vtable.
630 method_idx = rtype.method_index(name)
631 self.emit_line(
632 "{}CPY_GET_METHOD{}({}, {}, {}, {}, {})({}); /* {} */".format(
633 dest,
634 version,
635 obj,
636 self.emitter.type_struct_name(rtype.class_ir),
637 method_idx,
638 rtype.struct_name(self.names),
639 mtype,
640 args,
641 name,
642 )
643 )
644
645 def visit_inc_ref(self, op: IncRef) -> None:
646 if (
647 isinstance(op.src, Box)
648 and (is_none_rprimitive(op.src.src.type) or is_bool_or_bit_rprimitive(op.src.src.type))
649 and HAVE_IMMORTAL
650 ):
651 # On Python 3.12+, None/True/False are immortal, and we can skip inc ref
652 return
653
654 if isinstance(op.src, LoadLiteral) and HAVE_IMMORTAL:
655 value = op.src.value
656 # We can skip inc ref for immortal literals on Python 3.12+
657 if type(value) is int and -5 <= value <= 256:
658 # Small integers are immortal
659 return
660
661 src = self.reg(op.src)
662 self.emit_inc_ref(src, op.src.type)
663
664 def visit_dec_ref(self, op: DecRef) -> None:
665 src = self.reg(op.src)
666 self.emit_dec_ref(src, op.src.type, is_xdec=op.is_xdec)
667
668 def visit_box(self, op: Box) -> None:
669 self.emitter.emit_box(self.reg(op.src), self.reg(op), op.src.type, can_borrow=True)
670
671 def visit_cast(self, op: Cast) -> None:
672 if op.is_unchecked and op.is_borrowed:
673 self.emit_line(f"{self.reg(op)} = {self.reg(op.src)};")
674 return
675 branch = self.next_branch()
676 handler = None
677 if branch is not None:
678 if (
679 branch.value is op
680 and branch.op == Branch.IS_ERROR
681 and branch.traceback_entry is not None
682 and not branch.negated
683 and branch.false is self.next_block
684 ):
685 # Generate code also for the following branch here to avoid
686 # redundant branches in the generated code.
687 handler = TracebackAndGotoHandler(
688 self.label(branch.true),
689 self.source_path,
690 self.module_name,
691 branch.traceback_entry,
692 )
693 self.op_index += 1
694
695 self.emitter.emit_cast(
696 self.reg(op.src), self.reg(op), op.type, src_type=op.src.type, error=handler
697 )
698
699 def visit_unbox(self, op: Unbox) -> None:
700 self.emitter.emit_unbox(self.reg(op.src), self.reg(op), op.type)
701
702 def visit_unreachable(self, op: Unreachable) -> None:
703 self.emitter.emit_line("CPy_Unreachable();")
704
705 def visit_raise_standard_error(self, op: RaiseStandardError) -> None:
706 # TODO: Better escaping of backspaces and such
707 if op.value is not None:
708 if isinstance(op.value, str):
709 message = op.value.replace('"', '\\"')
710 self.emitter.emit_line(f'PyErr_SetString(PyExc_{op.class_name}, "{message}");')
711 elif isinstance(op.value, Value):
712 self.emitter.emit_line(
713 "PyErr_SetObject(PyExc_{}, {});".format(
714 op.class_name, self.emitter.reg(op.value)
715 )
716 )
717 else:
718 assert False, "op value type must be either str or Value"
719 else:
720 self.emitter.emit_line(f"PyErr_SetNone(PyExc_{op.class_name});")
721 self.emitter.emit_line(f"{self.reg(op)} = 0;")
722
723 def visit_call_c(self, op: CallC) -> None:
724 if op.is_void:
725 dest = ""
726 else:
727 dest = self.get_dest_assign(op)
728 args = ", ".join(self.reg(arg) for arg in op.args)
729 self.emitter.emit_line(f"{dest}{op.function_name}({args});")
730
731 def visit_primitive_op(self, op: PrimitiveOp) -> None:
732 raise RuntimeError(
733 f"unexpected PrimitiveOp {op.desc.name}: they must be lowered before codegen"
734 )
735
736 def visit_truncate(self, op: Truncate) -> None:
737 dest = self.reg(op)
738 value = self.reg(op.src)
739 # for C backend the generated code are straight assignments
740 self.emit_line(f"{dest} = {value};")
741
742 def visit_extend(self, op: Extend) -> None:
743 dest = self.reg(op)
744 value = self.reg(op.src)
745 if op.signed:
746 src_cast = self.emit_signed_int_cast(op.src.type)
747 else:
748 src_cast = self.emit_unsigned_int_cast(op.src.type)
749 self.emit_line(f"{dest} = {src_cast}{value};")
750
751 def visit_load_global(self, op: LoadGlobal) -> None:
752 dest = self.reg(op)
753 self.emit_line(f"{dest} = {op.identifier};", ann=op.ann)
754
755 def visit_int_op(self, op: IntOp) -> None:
756 dest = self.reg(op)
757 lhs = self.reg(op.lhs)
758 rhs = self.reg(op.rhs)
759 if op.op == IntOp.RIGHT_SHIFT:
760 # Signed right shift
761 lhs = self.emit_signed_int_cast(op.lhs.type) + lhs
762 rhs = self.emit_signed_int_cast(op.rhs.type) + rhs
763 self.emit_line(f"{dest} = {lhs} {op.op_str[op.op]} {rhs};")
764
765 def visit_comparison_op(self, op: ComparisonOp) -> None:
766 dest = self.reg(op)
767 lhs = self.reg(op.lhs)
768 rhs = self.reg(op.rhs)
769 lhs_cast = ""
770 rhs_cast = ""
771 if op.op in (ComparisonOp.SLT, ComparisonOp.SGT, ComparisonOp.SLE, ComparisonOp.SGE):
772 # Always signed comparison op
773 lhs_cast = self.emit_signed_int_cast(op.lhs.type)
774 rhs_cast = self.emit_signed_int_cast(op.rhs.type)
775 elif op.op in (ComparisonOp.ULT, ComparisonOp.UGT, ComparisonOp.ULE, ComparisonOp.UGE):
776 # Always unsigned comparison op
777 lhs_cast = self.emit_unsigned_int_cast(op.lhs.type)
778 rhs_cast = self.emit_unsigned_int_cast(op.rhs.type)
779 elif isinstance(op.lhs, Integer) and op.lhs.value < 0:
780 # Force signed ==/!= with negative operand
781 rhs_cast = self.emit_signed_int_cast(op.rhs.type)
782 elif isinstance(op.rhs, Integer) and op.rhs.value < 0:
783 # Force signed ==/!= with negative operand
784 lhs_cast = self.emit_signed_int_cast(op.lhs.type)
785 self.emit_line(f"{dest} = {lhs_cast}{lhs} {op.op_str[op.op]} {rhs_cast}{rhs};")
786
787 def visit_float_op(self, op: FloatOp) -> None:
788 dest = self.reg(op)
789 lhs = self.reg(op.lhs)
790 rhs = self.reg(op.rhs)
791 if op.op != FloatOp.MOD:
792 self.emit_line(f"{dest} = {lhs} {op.op_str[op.op]} {rhs};")
793 else:
794 # TODO: This may set errno as a side effect, that is a little sketchy.
795 self.emit_line(f"{dest} = fmod({lhs}, {rhs});")
796
797 def visit_float_neg(self, op: FloatNeg) -> None:
798 dest = self.reg(op)
799 src = self.reg(op.src)
800 self.emit_line(f"{dest} = -{src};")
801
802 def visit_float_comparison_op(self, op: FloatComparisonOp) -> None:
803 dest = self.reg(op)
804 lhs = self.reg(op.lhs)
805 rhs = self.reg(op.rhs)
806 self.emit_line(f"{dest} = {lhs} {op.op_str[op.op]} {rhs};")
807
808 def visit_load_mem(self, op: LoadMem) -> None:
809 dest = self.reg(op)
810 src = self.reg(op.src)
811 # TODO: we shouldn't dereference to type that are pointer type so far
812 type = self.ctype(op.type)
813 self.emit_line(f"{dest} = *({type} *){src};")
814 if not op.is_borrowed and op.type.is_refcounted:
815 self.emit_inc_ref(dest, op.type)
816
817 def visit_set_mem(self, op: SetMem) -> None:
818 dest = self.reg(op.dest)
819 src = self.reg(op.src)
820 dest_type = self.ctype(op.dest_type)
821 # clang whines about self assignment (which we might generate
822 # for some casts), so don't emit it.
823 if dest != src:
824 self.emit_line(f"*({dest_type} *){dest} = {src};")
825
826 def visit_get_element(self, op: GetElement) -> None:
827 dest = self.reg(op)
828 src = self.reg(op.src)
829 dest_type = self.ctype(op.type)
830 self.emit_line(f"{dest} = ({dest_type}){src}.{op.field};")
831
832 def visit_get_element_ptr(self, op: GetElementPtr) -> None:
833 dest = self.reg(op)
834 src = self.reg(op.src)
835 # TODO: support tuple type
836 assert isinstance(op.src_type, RStruct), op.src_type
837 assert op.field in op.src_type.names, "Invalid field name."
838 # Use offsetof to avoid undefined behavior when src is NULL
839 # (e.g., vec buf pointer for empty vecs). The &((T*)p)->field
840 # pattern is UB when p is NULL, which GCC -O3 can exploit.
841 self.emit_line(
842 "{} = ({})((CPyPtr){} + offsetof({}, {}));".format(
843 dest, op.type._ctype, src, op.src_type.name, op.field
844 )
845 )
846
847 def visit_set_element(self, op: SetElement) -> None:
848 dest = self.reg(op)
849 field = op.field
850 item = self.set_element_item(op.src.type, field, self.reg(op.item))
851 if isinstance(op.src, Undef):
852 # First assignment to an undefined struct is trivial.
853 self.emit_line(f"{dest}.{field} = {item};")
854 else:
855 # In the general case create a copy of the struct with a single
856 # item modified.
857 #
858 # TODO: Can we do better if only a subset of fields are initialized?
859 # TODO: Make this less verbose in the common case
860 # TODO: Support tuples (or use RStruct for tuples)?
861 src = self.reg(op.src)
862 src_type = op.src.type
863 assert isinstance(src_type, (RStruct, RVec)), src_type
864 init_items = []
865 for n in src_type.names:
866 if n != field:
867 init_items.append(f"{src}.{n}")
868 else:
869 init_items.append(item)
870 self.emit_line(f"{dest} = ({self.ctype(src_type)}) {{ {', '.join(init_items)} }};")
871
872 def set_element_item(self, src_type: RType, field: str, item: str) -> str:
873 if field == "items" and src_type._ctype in VEC_ITEMS_C_TYPE:
874 return f"({VEC_ITEMS_C_TYPE[src_type._ctype]}){item}"
875 return item
876
877 def visit_load_address(self, op: LoadAddress) -> None:
878 typ = op.type
879 dest = self.reg(op)
880 if isinstance(op.src, Register):
881 src = self.reg(op.src)
882 elif isinstance(op.src, LoadStatic):
883 prefix = PREFIX_MAP[op.src.namespace]
884 src = self.emitter.static_name(op.src.identifier, op.src.module_name, prefix)
885 else:
886 src = op.src
887 self.emit_line(f"{dest} = ({typ._ctype})&{src};")
888
889 def visit_keep_alive(self, op: KeepAlive) -> None:
890 # This is a no-op.
891 pass
892
893 def visit_unborrow(self, op: Unborrow) -> None:
894 # This is a no-op that propagates the source value.
895 dest = self.reg(op)
896 src = self.reg(op.src)
897 self.emit_line(f"{dest} = {src};")
898
899 # Helpers
900
901 def label(self, label: BasicBlock) -> str:
902 return self.emitter.label(label)
903
904 def reg(self, reg: Value) -> str:
905 if isinstance(reg, Integer):
906 val = reg.value
907 if val == 0 and is_pointer_rprimitive(reg.type):
908 return "NULL"
909 s = str(val)
910 if val >= (1 << 31):
911 # Avoid overflowing signed 32-bit int
912 if val >= (1 << 63):
913 s += "ULL"
914 else:
915 s += "LL"
916 elif val == -(1 << 63):
917 # Avoid overflowing C integer literal
918 s = "(-9223372036854775807LL - 1)"
919 elif val <= -(1 << 31):
920 s += "LL"
921 return s
922 elif isinstance(reg, Float):
923 r = repr(reg.value)
924 if r == "inf":
925 return "INFINITY"
926 elif r == "-inf":
927 return "-INFINITY"
928 elif r == "nan":
929 return "NAN"
930 return r
931 elif isinstance(reg, CString):
932 return '"' + encode_c_string_literal(reg.value) + '"'
933 else:
934 return self.emitter.reg(reg)
935
936 def ctype(self, rtype: RType) -> str:
937 return self.emitter.ctype(rtype)
938
939 def c_error_value(self, rtype: RType) -> str:
940 return self.emitter.c_error_value(rtype)
941
942 def c_undefined_value(self, rtype: RType) -> str:
943 return self.emitter.c_undefined_value(rtype)
944
945 def emit_line(self, line: str, *, ann: object = None) -> None:
946 self.emitter.emit_line(line, ann=ann)
947
948 def emit_lines(self, *lines: str) -> None:
949 self.emitter.emit_lines(*lines)
950
951 def emit_inc_ref(self, dest: str, rtype: RType) -> None:
952 self.emitter.emit_inc_ref(dest, rtype, rare=self.rare)
953
954 def emit_dec_ref(self, dest: str, rtype: RType, is_xdec: bool) -> None:
955 self.emitter.emit_dec_ref(dest, rtype, is_xdec=is_xdec, rare=self.rare)
956
957 def emit_declaration(self, line: str) -> None:
958 self.declarations.emit_line(line)
959
960 def emit_traceback(self, op: Branch) -> None:
961 if op.traceback_entry is not None:
962 self.emitter.emit_traceback(self.source_path, self.module_name, op.traceback_entry)
963
964 def emit_attribute_error(self, op: Branch, class_name: str, attr: str) -> None:
965 assert op.traceback_entry is not None
966 if self.emitter.context.strict_traceback_checks:
967 assert (
968 op.traceback_entry[1] >= 0
969 ), "AttributeError traceback cannot have a negative line number"
970 globals_static = self.emitter.static_name("globals", self.module_name)
971 self.emit_line(
972 'CPy_AttributeError("%s", "%s", "%s", "%s", %d, %s);'
973 % (
974 self.source_path.replace("\\", "\\\\"),
975 op.traceback_entry[0],
976 class_name,
977 attr.removeprefix(GENERATOR_ATTRIBUTE_PREFIX),
978 op.traceback_entry[1],
979 globals_static,
980 )
981 )
982 if DEBUG_ERRORS:
983 self.emit_line('assert(PyErr_Occurred() != NULL && "failure w/o err!");')
984
985 def emit_signed_int_cast(self, type: RType) -> str:
986 if is_tagged(type):
987 return "(Py_ssize_t)"
988 else:
989 return ""
990
991 def emit_unsigned_int_cast(self, type: RType) -> str:
992 if is_int32_rprimitive(type):
993 return "(uint32_t)"
994 elif is_int64_rprimitive(type):
995 return "(uint64_t)"
996 else:
997 return ""
998
999
1000 _translation_table: Final[dict[int, str]] = {}
1001
1002
1003 def encode_c_string_literal(b: bytes) -> str:
1004 """Convert bytestring to the C string literal syntax (with necessary escaping).
1005
1006 For example, b'foo\n' gets converted to 'foo\\n' (note that double quotes are not added).
1007 """
1008 if not _translation_table:
1009 # Initialize the translation table on the first call.
1010 d = {
1011 ord("\n"): "\\n",
1012 ord("\r"): "\\r",
1013 ord("\t"): "\\t",
1014 ord('"'): '\\"',
1015 ord("\\"): "\\\\",
1016 }
1017 for i in range(256):
1018 if i not in d:
1019 if i < 32 or i >= 127:
1020 d[i] = "\\x%.2x" % i
1021 else:
1022 d[i] = chr(i)
1023 _translation_table.update(str.maketrans(d))
1024 return b.decode("latin1").translate(_translation_table)