Closures and inline functions
Function types
A function type (A, B) -> R (also A.(B) -> R) is a MIR interface kotlin.FunctionN with a single method invoke(Any?, ...): Any?. The ABI is erased: primitives are boxed across a function-value call and unboxed on the other side, and Unit results are null.
Lambdas become classes
Every lambda literal or function reference that is not inlined gets its own class $closure<N> that implements the interface. A closure is an ordinary reference-counted object with one field per captured value and a generated dispose that releases the captures. From closure.kt:
// Used on "How it works: Closures and inline" and "Generics" to show closures, bridges and inline expansion.
fun adder(k: Int): (Int) -> Int = { x -> x + k }
inline fun twice(action: () -> Unit) {
action()
action()
}
class Box<T>(val value: T) {
fun get(): T = value
}
fun main() {
val add5 = adder(5)
println(add5(10))
var n = 0
twice { n += 1 }
println(n)
println(Box(41).get() + 1)
}The class generated for { x -> x + k } captures the Int k in f_c0 and lists the Function1 interface in its itable:
/* class adder.<lambda>$0 */
static const MkTypeInfo *const kc__x0024closure0_ifs[] = {&kc_kotlin_DFunction1_ti};
struct kc__x0024closure0 {
MkObject header;
MkInt f_c0;
};
#if UINTPTR_MAX == 0xffffffffffffffffu
_Static_assert(sizeof(struct kc__x0024closure0) == 24, "object layout");
_Static_assert(offsetof(struct kc__x0024closure0, f_c0) == 16, "object layout");
#endif
static void *const kc__x0024closure0_it0[] = {(void *)kc__x0024closure0_Minvoke_AQLmk_Any_E};
static void *const kc__x0024closure0_vt[] = {(void *)mk_any_to_string, (void *)mk_any_equals, (void *)mk_any_hash_code, (void *)kc__x0024closure0_it0};
static const MkTypeInfo kc__x0024closure0_ti = {"adder.<lambda>$0", sizeof(struct kc__x0024closure0), &mk_type_Any, NULL, kc__x0024closure0_vt, 4, kc__x0024closure0_ifs, 1, NULL};adder just allocates it, and invoke unboxes the argument, adds the captured value and boxes the result:
/* adder */
MKH_STATIC MkObject * kt_adder_AI(MkInt v_k_0) {
{
MkObject * r = kc__x0024closure0_C_AI_new(v_k_0);
return r;
}
}/* adder.<lambda>$0.invoke */
MKH_STATIC MkObject * kc__x0024closure0_Minvoke_AQLmk_Any_E(MkObject * v_this_0, MkObject * v_p0_1) {
MkInt v_cap0_2 = (((struct kc__x0024closure0 *)v_this_0)->f_c0);
MkInt v_x_3 = ({ MkObject *mkc3 = ((MkObject *)v_p0_1); MkInt mkr3; if (__builtin_expect(mkc3 != NULL && mkc3->type == &mk_type_Int, 1)) mkr3 = ((const struct { MkObject h; MkInt v; } *)mkc3)->v; else { mkr3 = mk_checked_unbox_int(mkc3); if (mk_pending_exception != NULL) { return NULL; } } mkr3; });
{
MkObject * r = mk_box_int((MkInt)((uint32_t)v_x_3 + (uint32_t)v_cap0_2));
return r;
}
}Captured variables
- Captured
vals and parameters are copied into the closure. - A captured
varlives in a heap cell (aRef<T>class with one fieldvalue, one class per MIR type) shared by the declaring function and every closure that captures it.ClosureAnalysisboxes exactly thevars that some closure captures. - Local functions are lambda-lifted: a C function whose leading parameters are the captured values. Calls to them are direct, so recursion works;
::localcreates a closure object.
Closures go through the normal allocation path. A reference cycle such as a closure stored in a field of the object it captures leaks under reference counting.
Inline functions
K2 keeps calls of inline fun in its IR. When the callee has a body (all user code and the stdlib compiled from source), Ir2MirInline expands it in place: the body is lowered in the caller's function with parameters bound to fresh locals, and a lambda passed for an inline parameter is not turned into an object, its body is expanded at the call. In the example, twice { n += 1 } becomes two copies of n += 1 wrapped in labelled loops that implement return from the inline function, and n is an ordinary C local with no heap cell:
MkInt v_n_4 = 0;
for (;;) {
for (;;) {
v_n_4 = (MkInt)((uint32_t)v_n_4 + (uint32_t)1);
goto brk_1;
}
brk_1:;
for (;;) {
v_n_4 = (MkInt)((uint32_t)v_n_4 + (uint32_t)1);
goto brk_2;
}
brk_2:;
goto brk_0;
}
brk_0:;Consequences:
returninside such a lambda is a non-local return from the enclosing function.reifiedtype parameters work because the type arguments are substituted during expansion. Functions withreifiedparameters only exist expanded.- Inline functions are also compiled as ordinary functions taking function objects, so they can be used as values (
twiceabove has akt_twice_...version that callsinvokethrough the itable). - Limit: an inline lambda parameter may only be invoked or forwarded to another inline function. Store it with
noinline.crossinlinelambdas are compiled as closures.