ffi M1.2 A.4b.i: __sx_state ivar registration

Class-pair init constructor now registers a single hidden ivar
on each sx-defined class:

  class_addIvar(cls, "__sx_state", 8, 3, "^v")

before objc_registerClassPair. After the class is registered,
the constructor calls class_getInstanceVariable to fetch the
runtime Ivar handle and stores it in a per-class global
'__<ClassName>_state_ivar : *void'. Trampolines (A.4b.ii) will
read this global to 'object_getIvar' the state struct pointer.

lower.zig declares the per-class global at scan time
(declareObjcDefinedStateIvarGlobal) so emit_llvm finds it by
name when populating. Encoding '^v' = void* (a generic pointer
— the runtime treats it as opaque storage). log2 alignment = 3
for 8-byte pointer alignment on 64-bit.

144-objc-class-ivar-registration.sx exercises the round-trip:
after main starts, class_getInstanceVariable(SxFoo, "__sx_state")
returns non-null. Runs against the real Obj-C runtime on macOS.

142's IR snapshot refreshed to include the new constructor body
(class_addIvar + class_getInstanceVariable + ivar-global store).

173 example tests pass (+1 from 144). zig build test green.
This commit is contained in:
agra
2026-05-25 22:23:59 +03:00
parent b98a22e3f9
commit c2178c062b
6 changed files with 124 additions and 4 deletions

View File

@@ -542,26 +542,31 @@ pub const LLVMEmitter = struct {
/// For each entry in `objc_defined_class_cache`:
/// super_cls = objc_getClass("<ParentName>") // default NSObject
/// cls = objc_allocateClassPair(super_cls, "<ClassName>", 0)
/// class_addIvar(cls, "__sx_state", 8, 3, "^v") // M1.2 A.4b.i
/// objc_registerClassPair(cls)
/// g_<ClassName>_state_ivar = class_getInstanceVariable(cls, "__sx_state")
///
/// Method IMPs, the `__sx_state` ivar, and the `+alloc` /
/// `-dealloc` overrides come in A.4b / A.5 / A.6 — this slice
/// just makes the class exist in the runtime so `objc_getClass`
/// finds it.
/// Method IMPs (`class_addMethod`) and the `+alloc` / `-dealloc`
/// overrides come in A.4b.ii / A.5 / A.6.
fn emitObjcDefinedClassInit(self: *LLVMEmitter) void {
if (self.ir_mod.objc_defined_class_cache.items.len == 0) return;
const ptr_ty = self.cached_ptr;
const i32_ty = self.cached_i32;
const i64_ty = self.cached_i64;
const i8_ty = c.LLVMInt8TypeInContext(self.context);
// Lazy-declare the Obj-C runtime APIs the constructor calls.
// objc_getClass(name: *u8) -> *void.
const get_class_fn, const get_class_ty = self.lazyDeclareCRuntime("objc_getClass", &[_]c.LLVMTypeRef{ptr_ty}, ptr_ty, 0);
// objc_allocateClassPair(super: *void, name: *u8, extra: usize) -> *void.
const alloc_pair_fn, const alloc_pair_ty = self.lazyDeclareCRuntime("objc_allocateClassPair", &[_]c.LLVMTypeRef{ ptr_ty, ptr_ty, i64_ty }, ptr_ty, 0);
// class_addIvar(cls: *void, name: *u8, size: u64, log2align: u8, type: *u8) -> bool.
const add_ivar_fn, const add_ivar_ty = self.lazyDeclareCRuntime("class_addIvar", &[_]c.LLVMTypeRef{ ptr_ty, ptr_ty, i64_ty, i8_ty, ptr_ty }, i8_ty, 0);
// objc_registerClassPair(cls: *void) -> void.
const register_fn, const register_ty = self.lazyDeclareCRuntime("objc_registerClassPair", &[_]c.LLVMTypeRef{ptr_ty}, self.cached_void, 0);
// class_getInstanceVariable(cls: *void, name: *u8) -> *Ivar.
const get_iv_fn, const get_iv_ty = self.lazyDeclareCRuntime("class_getInstanceVariable", &[_]c.LLVMTypeRef{ ptr_ty, ptr_ty }, ptr_ty, 0);
// Constructor: void __sx_objc_defined_class_init().
var no_params: [0]c.LLVMTypeRef = .{};
@@ -571,6 +576,10 @@ pub const LLVMEmitter = struct {
const entry = c.LLVMAppendBasicBlockInContext(self.context, ctor, "entry");
c.LLVMPositionBuilderAtEnd(self.builder, entry);
// Reusable C-string globals for ivar metadata (same across classes).
const sx_state_name_global = self.emitPrivateCString("__sx_state", "OBJC_IVAR_NAME_");
const sx_state_enc_global = self.emitPrivateCString("^v", "OBJC_IVAR_TYPE_");
for (self.ir_mod.objc_defined_class_cache.items) |entry_kv| {
const fcd = entry_kv.decl;
const class_name = fcd.name;
@@ -595,9 +604,37 @@ pub const LLVMEmitter = struct {
var alloc_args: [3]c.LLVMValueRef = .{ super_val, class_str_global, c.LLVMConstInt(i64_ty, 0, 0) };
const cls_val = c.LLVMBuildCall2(self.builder, alloc_pair_ty, alloc_pair_fn, &alloc_args, 3, "cls");
// class_addIvar(cls, "__sx_state", 8, 3, "^v")
// size = 8 (pointer) — sizeof(*void) on 64-bit
// log2align = 3 — alignof(*void) = 8 = 2^3
// type = "^v" (encoded *void)
var ivar_args: [5]c.LLVMValueRef = .{
cls_val,
sx_state_name_global,
c.LLVMConstInt(i64_ty, 8, 0),
c.LLVMConstInt(i8_ty, 3, 0),
sx_state_enc_global,
};
_ = c.LLVMBuildCall2(self.builder, add_ivar_ty, add_ivar_fn, &ivar_args, 5, "");
// objc_registerClassPair(cls)
var reg_args: [1]c.LLVMValueRef = .{cls_val};
_ = c.LLVMBuildCall2(self.builder, register_ty, register_fn, &reg_args, 1, "");
// Cache the ivar handle in the per-class global so trampolines
// can read the __sx_state ivar without re-looking-it-up. The
// global is declared by lower.zig (M1.2 A.4b.i) and starts as
// null; the constructor fills it in here.
const ivar_global_name = std.fmt.allocPrint(self.alloc, "__{s}_state_ivar", .{class_name}) catch continue;
defer self.alloc.free(ivar_global_name);
const ivar_global_z = self.alloc.dupeZ(u8, ivar_global_name) catch continue;
defer self.alloc.free(ivar_global_z);
const ivar_global = c.LLVMGetNamedGlobal(self.llvm_module, ivar_global_z.ptr);
if (ivar_global != null) {
var iv_args: [2]c.LLVMValueRef = .{ cls_val, sx_state_name_global };
const iv_val = c.LLVMBuildCall2(self.builder, get_iv_ty, get_iv_fn, &iv_args, 2, "iv");
_ = c.LLVMBuildStore(self.builder, iv_val, ivar_global);
}
}
_ = c.LLVMBuildRetVoid(self.builder);

View File

@@ -9617,11 +9617,31 @@ pub const Lowering = struct {
if (!fcd.is_foreign and fcd.runtime == .objc_class) {
if (self.module.lookupObjcDefinedClass(fcd.name) == null) {
self.module.appendObjcDefinedClass(fcd.name, fcd);
// M1.2 A.4b.i: per-class ivar handle global. The class-pair
// init constructor (emit_llvm) populates it via
// class_getInstanceVariable after the class is registered;
// IMP trampolines read it to find the __sx_state ivar.
self.declareObjcDefinedStateIvarGlobal(fcd.name);
}
self.registerObjcDefinedClassMethods(fcd);
}
}
/// Declare a per-class global `__<ClassName>_state_ivar : *void = null`.
/// emit_llvm's `emitObjcDefinedClassInit` constructor fills it in via
/// `class_getInstanceVariable(cls, "__sx_state")` once per module load.
fn declareObjcDefinedStateIvarGlobal(self: *Lowering, class_name: []const u8) void {
const gname = std.fmt.allocPrint(self.alloc, "__{s}_state_ivar", .{class_name}) catch return;
const name_id = self.module.types.internString(gname);
_ = self.module.addGlobal(.{
.name = name_id,
.ty = self.module.types.ptrTo(.void),
.init_val = .null_val,
.is_extern = false,
.is_const = false,
});
}
/// For each bodied instance method on an sx-defined `#objc_class`,
/// synthesize an `FnDecl` from the `ForeignMethodDecl`, register it
/// in `fn_ast_map` under `<ClassName>.<methodName>`, and declare