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