From 9b9272ae758e23653c81c94031ec03892d31622a Mon Sep 17 00:00:00 2001 From: Logan Hunt <39638017+dosisod@users.noreply.github.com> Date: Mon, 12 Jun 2023 03:57:23 -0700 Subject: [PATCH] [mypyc] Don't explicitly assign `NULL` values in setup functions (#15379) While investigating something unrelated I stumbled across the `*_setup` functions, and I noticed that they contain a lot of code that looks like this: ```c self->abc = NULL; self->xyz = NULL; // ... ``` Something told me that assigning `NULL` to a bunch of fields is propably not needed, and when looking at the docs for `tp_alloc()` I found this reference to [`allocfunc`](https://docs.python.org/3/c-api/typeobj.html#c.allocfunc), the typedef for `tp_alloc()`: > It should return a pointer to a block of memory of adequate length for the instance, suitably aligned, ***and initialized to zeros***, ... Emphasis is mine. Basically I added a simple check that removes lines that assigns `NULL` values in setup functions. This removes about ~4100 lines from the C file when self-compiling. --- mypyc/codegen/emitclass.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/mypyc/codegen/emitclass.py b/mypyc/codegen/emitclass.py index 6a272d1aee2b..eac7a2207972 100644 --- a/mypyc/codegen/emitclass.py +++ b/mypyc/codegen/emitclass.py @@ -578,7 +578,12 @@ def generate_setup_for_class( for base in reversed(cl.base_mro): for attr, rtype in base.attributes.items(): - emitter.emit_line(rf"self->{emitter.attr(attr)} = {emitter.c_undefined_value(rtype)};") + value = emitter.c_undefined_value(rtype) + + # We don't need to set this field to NULL since tp_alloc() already + # zero-initializes `self`. + if value != "NULL": + emitter.emit_line(rf"self->{emitter.attr(attr)} = {value};") # Initialize attributes to default values, if necessary if defaults_fn is not None: