Back to Kotlin Foundation
GSoC 2026

Tail call support in the Kotlin/Wasm backend

WebAssembly's call stack limit is unspecified by the spec and varies across host environments. As a result, any Kotlin/Wasm program that uses mutual recursion or deep tail calls is vulnerable to stack overflow at runtime, with no way to guarantee safe execution across browsers and runtimes. Kotlin's existing tailrec modifier mitigates this for simple self-recursion by rewriting functions as loops, but it cannot handle mutual recursion or indirect calls, and requires an explicit annotation that many developers will not add. The WebAssembly Tail Call proposal (standardized and part of the Baseline target since 2024) addresses this at the instruction level with return_call and return_call_ref, which discard the current stack frame before transferring control and reduce stack consumption from O(n) to O(1) regardless of recursion structure. This project integrates that proposal into the Kotlin/Wasm compiler backend. The work covers adding the missing RETURN_CALL opcode to the Wasm IR layer, detecting tail call positions in the code generation pipeline and emitting return_call and return_call_ref in place of the current call + return two-instruction sequence, writing a test suite covering mutual recursion and virtual dispatch across multiple host environments, and benchmarking return_call against the existing loop transformation to evaluate the tradeoffs.

Project details

Contributor

Ayako Hayasaka

Mentors

Not available

Technologies

Not listed in the archive