Skip to content

Commit

Permalink
[K/N] Introduce RuntimeInitializer type in the code generation
Browse files Browse the repository at this point in the history
Kotlin/Native runtime has a concept of `Initializer` (see the type
declaration in `Runtime.h`).

The code generator generates functions of this type. But the
implementation is convoluted, with many different things called "init"
or "initializer".

This commit encapsulates `Initializer` functions to the new
`RuntimeInitializer` type in the code generator, making the
implementation easier to reason about.

^KT-74764
  • Loading branch information
SvyatoslavScherbina authored and Space Team committed Jan 29, 2025
1 parent 28fcf22 commit b23da31
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -641,3 +641,9 @@ internal class CodegenLlvmHelpers(private val generationState: NativeGenerationS
}

class IrStaticInitializer(val konanLibrary: KotlinLibrary?, val initializer: LlvmCallable)

/**
* Function of the [CodeGeneratorVisitor.kInitFuncType] type (aka `Initializer` in `Runtime.h`).
*/
@JvmInline
value class RuntimeInitializer(val llvmCallable: LlvmCallable)
Original file line number Diff line number Diff line change
Expand Up @@ -445,9 +445,8 @@ internal class CodeGeneratorVisitor(
val FILE_NOT_INITIALIZED = 0
val FILE_INITIALIZED = 2

private fun createInitBody(state: ScopeInitializersGenerationState): LlvmCallable {
val initFunctionProto = kInitFuncType.toProto("", null, LLVMLinkage.LLVMPrivateLinkage)
return generateFunction(codegen, initFunctionProto) {
private fun createInitBody(state: ScopeInitializersGenerationState): RuntimeInitializer {
return generateRuntimeInitializer {
using(FunctionScope(function, this)) {
val bbInit = basicBlock("init", null)
val bbLocalInit = basicBlock("local_init", null)
Expand Down Expand Up @@ -510,10 +509,16 @@ internal class CodeGeneratorVisitor(
}
}

private fun generateRuntimeInitializer(block: FunctionGenerationContext.() -> Unit): RuntimeInitializer {
val initFunctionProto = kInitFuncType.toProto("", null, LLVMLinkage.LLVMPrivateLinkage)
return RuntimeInitializer(generateFunction(codegen, initFunctionProto, code = block))
}

//-------------------------------------------------------------------------//
// Creates static struct InitNode $nodeName = {$initName, NULL};

private fun createInitNode(initFunction: LlvmCallable): LLVMValueRef {
private fun createInitNode(runtimeInitializer: RuntimeInitializer): LLVMValueRef {
val initFunction = runtimeInitializer.llvmCallable
val nextInitNode = LLVMConstNull(pointerType(kNodeInitType))
val argList = cValuesOf(initFunction.toConstPointer().llvm, nextInitNode)
// Create static object of class InitNode.
Expand Down

0 comments on commit b23da31

Please sign in to comment.