From 33907852b80d5a16eb5f95c13f93c053b9e3d0c7 Mon Sep 17 00:00:00 2001 From: Yichao Yu Date: Mon, 27 Oct 2025 11:19:32 -0400 Subject: [PATCH] Avoid an unnecessary std::function allocation in codegen We already need to manually create a C compatible function pointer and heap allocated data, might as well do so directly without another indirection through std::function. --- src/aotcompile.cpp | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/src/aotcompile.cpp b/src/aotcompile.cpp index 1f1ed18e880a2..acfd0fedd8c96 100644 --- a/src/aotcompile.cpp +++ b/src/aotcompile.cpp @@ -1827,10 +1827,16 @@ static void construct_vars(Module &M, Partition &partition, StringRef suffix) { gidxs_var->setDSOLocal(true); } -extern "C" void lambda_trampoline(void* arg) { - std::function* func = static_cast*>(arg); - (*func)(); - delete func; +template +static inline void schedule_uv_thread(uv_thread_t *worker, CB &&cb) +{ + auto func = new CB(std::move(cb)); + // Use libuv thread to avoid issues with stack sizes + uv_thread_create(worker, [] (void *arg) { + auto func = static_cast(arg); + (*func)(); + delete func; + }, func); } // Entrypoint to optionally-multithreaded image compilation. This handles global coordination of the threading, @@ -1930,7 +1936,7 @@ static SmallVector add_output(Module &M, TargetMachine &TM, Stri JL_TIMING(NATIVE_AOT, NATIVE_Opt); std::vector workers(threads); for (unsigned i = 0; i < threads; i++) { - std::function func = [&, i]() { + schedule_uv_thread(&workers[i], [&, i]() { LLVMContext ctx; ctx.setDiscardValueNames(true); // Lazily deserialize the entire module @@ -1961,9 +1967,7 @@ static SmallVector add_output(Module &M, TargetMachine &TM, Stri timers[i].construct.stopTimer(); outputs[i] = add_output_impl(*M, TM, timers[i], unopt_out, opt_out, obj_out, asm_out); - }; - auto arg = new std::function(func); - uv_thread_create(&workers[i], lambda_trampoline, arg); // Use libuv thread to avoid issues with stack sizes + }); } // Wait for all of the worker threads to finish