From 9b1e93ad23158d657b118880d7562001fe98e867 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Tue, 1 Dec 2026 11:42:54 +0000 Subject: [PATCH 1/2] perf(vm,interp,jit): native call-site cache and single-pass dispatch across backends Co-authored-by: esrrhs --- src/compile/c_runtime_cov.h | 42 ++-- src/interp/func_proto.h | 6 +- src/interp/interpreter.cpp | 136 +++++++++--- src/jit/vm.cpp | 160 +++++++------- src/native/basic/native_basic.cpp | 2 +- src/native/table/native_table.cpp | 2 +- src/state/fakelua.cpp | 2 +- test/test_native.cpp | 333 ++++++++++++++++++++++++++++++ 8 files changed, 554 insertions(+), 129 deletions(-) diff --git a/src/compile/c_runtime_cov.h b/src/compile/c_runtime_cov.h index 4ea985f..bec7027 100644 --- a/src/compile/c_runtime_cov.h +++ b/src/compile/c_runtime_cov.h @@ -970,17 +970,15 @@ static inline CVar FlCallClosure3Fn(State *state, CVar cl_var, CVar a0, CVar a1, #define FlCallClosure3(...) FlCallClosure3Fn(__VA_ARGS__ FL_HINT_ARGS) static inline CVar FlCallNamed0(State *state, const char *name, FlCallCache *cache) { - if (FAKELUA_JIT_TYPE == 1) { - if (LIKELY(cache->version == *fl_vm_version && !cache->is_vararg && cache->expected_args == 0)) { - if (cache->kind == 1) { - FlLuaLoc __fl_saved_loc = *fl_active_loc; - CVar __fl_ret = ((CVar (*)(VarClosure *))(cache->target))(NULL); - *fl_active_loc = __fl_saved_loc; - return __fl_ret; - } - if (cache->kind == 2) { - return FakeluaCallNativeCached(state, cache->target, 0, NULL); - } + if (LIKELY(cache->version == *fl_vm_version)) { + if (cache->kind == 2 && (cache->is_vararg || cache->expected_args == 0)) { + return FakeluaCallNativeCached(state, cache->target, 0, NULL); + } + if (cache->kind == 1 && !cache->is_vararg && cache->expected_args == 0) { + FlLuaLoc __fl_saved_loc = *fl_active_loc; + CVar __fl_ret = ((CVar (*)(VarClosure *))(cache->target))(NULL); + *fl_active_loc = __fl_saved_loc; + return __fl_ret; } } return FakeluaCallByNameCached(state, FAKELUA_JIT_TYPE, name, cache, 0); @@ -988,18 +986,16 @@ static inline CVar FlCallNamed0(State *state, const char *name, FlCallCache *cac #define FL_DEF_CALL_NAMED(N, PARAMS, ARGS, CHK_MULTI, CTYPES) \ static inline CVar FlCallNamed##N(State *state, const char *name, FlCallCache *cache, PARAMS) { \ - if (FAKELUA_JIT_TYPE == 1) { \ - if (LIKELY(cache->version == *fl_vm_version && !cache->is_vararg && cache->expected_args == (N) && (CHK_MULTI))) { \ - if (cache->kind == 1) { \ - FlLuaLoc __fl_saved_loc = *fl_active_loc; \ - CVar __fl_ret = ((CVar (*)(VarClosure *, CTYPES))(cache->target))(NULL, ARGS); \ - *fl_active_loc = __fl_saved_loc; \ - return __fl_ret; \ - } \ - if (cache->kind == 2) { \ - CVar __fl_args[N] = {ARGS}; \ - return FakeluaCallNativeCached(state, cache->target, N, __fl_args); \ - } \ + if (LIKELY(cache->version == *fl_vm_version && (CHK_MULTI))) { \ + if (cache->kind == 2 && (cache->is_vararg || cache->expected_args == (N))) { \ + CVar __fl_args[N] = {ARGS}; \ + return FakeluaCallNativeCached(state, cache->target, N, __fl_args); \ + } \ + if (cache->kind == 1 && !cache->is_vararg && cache->expected_args == (N)) { \ + FlLuaLoc __fl_saved_loc = *fl_active_loc; \ + CVar __fl_ret = ((CVar (*)(VarClosure *, CTYPES))(cache->target))(NULL, ARGS); \ + *fl_active_loc = __fl_saved_loc; \ + return __fl_ret; \ } \ } \ return FakeluaCallByNameCached(state, FAKELUA_JIT_TYPE, name, cache, N, ARGS); \ diff --git a/src/interp/func_proto.h b/src/interp/func_proto.h index e4babea..0fb469d 100644 --- a/src/interp/func_proto.h +++ b/src/interp/func_proto.h @@ -15,6 +15,7 @@ namespace fakelua { struct FuncProto; +struct NativeFuncEntry; // 一次编译单元:持有全部函数原型与文件级全局槽,生命周期绑定到 VmFunction 的 handle。 struct TransparentStringHash { @@ -41,10 +42,11 @@ struct InterpUnit final : JITHandle { std::string file_name; }; -// 命名调用点缓存。vm_version 与 Vm::VersionPtr 一致时 proto 仍然有效; -// RegisterFunction 改变版本号后下一次调用重新解析。proto 为空表示目标不是解释器原型。 +// 命名调用点缓存。vm_version 与 Vm::VersionPtr 一致时 proto / native 仍然有效; +// RegisterFunction / RegisterNativeFunction 改变版本号后下一次调用重新解析。 struct InterpCallCache { FuncProto *proto = nullptr; + const NativeFuncEntry *native = nullptr; uint64_t vm_version = 0; }; diff --git a/src/interp/interpreter.cpp b/src/interp/interpreter.cpp index e8b5a83..b93f98b 100644 --- a/src/interp/interpreter.cpp +++ b/src/interp/interpreter.cpp @@ -33,11 +33,13 @@ std::string_view ConstToName(const CVar &c) { struct NamedCallTarget { FuncProto *proto = nullptr; + const NativeFuncEntry *native = nullptr; bool direct = false; + bool native_direct = false; }; -// 文件级命名调用的调用点缓存。命中且实参个数精确、非变参、末参不是 Multi 时 direct 为真, -// 调用方直接进入解释器帧,不再查 local_funcs / VmFunction。 +// 文件级命名调用的调用点缓存。命中且实参个数精确、非变参、末参不是 Multi 时 direct 为真; +// 目标是原生函数且无 Multi 实参、满足定参/变参要求时 native_direct 为真,直接调回调不再查哈希表。 NamedCallTarget ResolveNamedCall(State *s, FuncProto *caller, const Inst *ip_after, const Inst &inst, int nargs, const CVar *args) { NamedCallTarget out; if (caller == nullptr || ip_after == nullptr || caller->code.empty() || caller->call_cache.empty()) { @@ -49,28 +51,43 @@ NamedCallTarget ResolveNamedCall(State *s, FuncProto *caller, const Inst *ip_aft } InterpCallCache &slot = caller->call_cache[static_cast(off)]; const uint64_t ver = *s->GetVM().VersionPtr(); - if (slot.vm_version != ver) { + if (FL_VM_UNLIKELY(slot.vm_version != ver)) { const std::string_view name = ConstToName(caller->constants[static_cast(inst.sbx)]); - FuncProto *found = nullptr; + FuncProto *found_proto = nullptr; + const NativeFuncEntry *found_native = nullptr; if ((inst.c & kCallLocalUnit) != 0 && caller->unit != nullptr) { if (const auto it = caller->unit->local_funcs.find(name); it != caller->unit->local_funcs.end() && it->second) { - found = it->second; + found_proto = it->second; } } - if (found == nullptr) { + if (found_proto == nullptr) { if (const VmFunction *fn = s->GetVM().FindFunction(name)) { if (void *addr = fn->GetAddr(JIT_INTERP)) { - found = AsInterpProto(addr); + found_proto = AsInterpProto(addr); } + } else { + found_native = s->GetVM().FindNativeFunction(name); } } - slot.proto = found; + slot.proto = found_proto; + slot.native = found_native; slot.vm_version = ver; } out.proto = slot.proto; - const bool last_multi = nargs > 0 && args != nullptr && args[nargs - 1].type_ == static_cast(VarType::Multi); - out.direct = out.proto != nullptr && !out.proto->is_vararg && !last_multi && nargs == out.proto->param_count && - nargs <= static_cast(kMaxFunctionInputParams); + out.native = slot.native; + if (out.proto != nullptr) { + const bool last_multi = nargs > 0 && args != nullptr && args[nargs - 1].type_ == static_cast(VarType::Multi); + out.direct = !out.proto->is_vararg && !last_multi && nargs == out.proto->param_count && nargs <= static_cast(kMaxFunctionInputParams); + } else if (out.native != nullptr) { + bool has_multi = false; + for (int i = 0; i < nargs; ++i) { + if (FL_VM_UNLIKELY(args[i].type_ == static_cast(VarType::Multi))) { + has_multi = true; + break; + } + } + out.native_direct = !has_multi && (out.native->is_vararg || nargs == out.native->arg_count); + } return out; } @@ -155,6 +172,70 @@ CVar InterpExecuteInContext(State *s, FuncProto *proto, const CVar *args, int ar return InterpreterExecute(s, proto, args, arg_count, cl); } +inline CVar InterpCallNativeDirect(State *s, const NativeFuncEntry *native, CVar *args, int nargs) { + if (FL_VM_UNLIKELY(s->CurrentJit() != JIT_INTERP)) { + State::JitContextScope jit_scope(s, JIT_INTERP); + return native->callback(s, args, nargs); + } + return native->callback(s, args, nargs); +} + +int FlattenByNameArgs(const CVar *raw, int arg_num, CVar *flat); + +CVar InterpCallNativeSlow(State *s, const NativeFuncEntry *native, std::string_view name, const CVar *raw, int nargs) { + if (UNLIKELY(native->arg_count < 0 || native->arg_count > static_cast(kMaxFunctionInputParams))) { + ThrowFakeluaException(std::format("FakeluaCallByName: function '{}' declares too many parameters ({}), max is {}", name, native->arg_count, kMaxFunctionInputParams)); + } + CVar flat[kMaxFunctionInputParams]; + const int nflat = FlattenByNameArgs(raw, nargs, flat); + const bool last_is_multi = (nargs > 0 && raw[nargs - 1].type_ == static_cast(VarType::Multi)); + if (UNLIKELY(!native->is_vararg && !last_is_multi && nflat != native->arg_count)) { + ThrowFakeluaException(std::format("FakeluaCallByName: function '{}' expects {} argument(s), got {}", name, native->arg_count, nflat)); + } + return InterpCallNativeDirect(s, native, nflat == 0 ? nullptr : flat, nflat); +} + +template +inline CVar InterpMakeMulti(State *s, CVar *stk, CVar **boxp, int base, int n) { + if constexpr (!HasBoxes) { + return interp_rt::MakeMulti(s, stk + base, static_cast(n)); + } else { + if (FL_VM_LIKELY(n <= static_cast(kMaxFunctionInputParams))) { + CVar vals[kMaxFunctionInputParams]; + for (int i = 0; i < n; ++i) { + vals[i] = interp_rt::VmSlot(stk, boxp, base + i); + } + return interp_rt::MakeMulti(s, vals, static_cast(n)); + } + std::vector vals(static_cast(n)); + for (int i = 0; i < n; ++i) { + vals[static_cast(i)] = interp_rt::VmSlot(stk, boxp, base + i); + } + return interp_rt::MakeMulti(s, vals.data(), static_cast(n)); + } +} + +template +inline CVar InterpCombineMulti(State *s, CVar *stk, CVar **boxp, int base, int nprefix) { + const CVar last = interp_rt::VmSlot(stk, boxp, base + nprefix); + if constexpr (!HasBoxes) { + return interp_rt::CombineMulti(s, stk + base, static_cast(nprefix), last); + } else { + if (FL_VM_LIKELY(nprefix <= static_cast(kMaxFunctionInputParams))) { + CVar prefix[kMaxFunctionInputParams]; + for (int i = 0; i < nprefix; ++i) { + prefix[i] = interp_rt::VmSlot(stk, boxp, base + i); + } + return interp_rt::CombineMulti(s, prefix, static_cast(nprefix), last); + } + std::vector prefix(static_cast(nprefix)); + for (int i = 0; i < nprefix; ++i) { + prefix[static_cast(i)] = interp_rt::VmSlot(stk, boxp, base + i); + } + return interp_rt::CombineMulti(s, prefix.data(), static_cast(nprefix), last); + } +} + // 文件级 / 全局命名调用的快路径:签名匹配且目标是 INTERP 原型时直接 InterpreterExecute, // 跳过 CallByName 的 VmFunction 拷贝、GuardJitEntry 与参数再装箱。 // 变参、末参 Multi、参数个数不一致、原生函数或无 INTERP 地址时返回 false,由调用方走 CallByNameArgs。 @@ -438,8 +519,14 @@ bool InterpDoTailName(State *s, FuncProto *&proto, VarClosure *&cl, CVar *const for (int i = 0; i < nargs; ++i) { raw[i] = interp_rt::VmSlot(stk, boxp, inst.a + i); } - if (const NamedCallTarget hit = ResolveNamedCall(s, proto, ip, inst, nargs, raw); hit.direct) { + if (const NamedCallTarget hit = ResolveNamedCall(s, proto, ip, inst, nargs, raw); hit.native_direct) { + ret = InterpCallNativeDirect(s, hit.native, nargs == 0 ? nullptr : raw, nargs); + return false; + } else if (hit.direct) { return ApplyInterpTail(s, proto, cl, stk, boxp, saved, ip, hit.proto, nullptr, raw, nargs, ret); + } else if (hit.native) { + ret = InterpCallNativeSlow(s, hit.native, name, raw, nargs); + return false; } if ((inst.c & kCallLocalUnit) != 0 && proto->unit) { if (const auto it = proto->unit->local_funcs.find(name); it != proto->unit->local_funcs.end() && it->second) { @@ -900,8 +987,13 @@ CVar InterpreterExecuteT(State *s, FuncProto *proto, const CVar *args, int arg_c } CVar ret; const NamedCallTarget hit = ResolveNamedCall(s, proto, ip, inst, nargs, call_args); - if (hit.direct) { + if (hit.native_direct) { + ret = InterpCallNativeDirect(s, hit.native, nargs == 0 ? nullptr : call_args, nargs); + } else if (hit.direct) { ret = InterpExecuteInContext(s, hit.proto, nargs == 0 ? nullptr : call_args, nargs, nullptr); + } else if (hit.native) { + const std::string_view name = ConstToName(proto->constants[static_cast(inst.sbx)]); + ret = InterpCallNativeSlow(s, hit.native, name, call_args, nargs); } else { const std::string_view name = ConstToName(proto->constants[static_cast(inst.sbx)]); if (hit.proto) { @@ -1035,25 +1127,11 @@ CVar InterpreterExecuteT(State *s, FuncProto *proto, const CVar *args, int arg_c VM_DISPATCH_NEXT(); } VM_CASE(MAKEMULTI) { - { - const int n = inst.b; - std::vector vals(static_cast(n)); - for (int i = 0; i < n; ++i) { - vals[static_cast(i)] = VM_R(inst.a + i); - } - VM_W(inst.a, interp_rt::MakeMulti(s, vals.data(), static_cast(n))); - } + VM_W(inst.a, InterpMakeMulti(s, stk, boxp, inst.a, inst.b)); VM_DISPATCH_NEXT(); } VM_CASE(COMBINE) { - { - const int nprefix = inst.b; - std::vector prefix(static_cast(nprefix)); - for (int i = 0; i < nprefix; ++i) { - prefix[static_cast(i)] = VM_R(inst.a + i); - } - VM_W(inst.a, interp_rt::CombineMulti(s, prefix.data(), static_cast(nprefix), VM_R(inst.a + nprefix))); - } + VM_W(inst.a, InterpCombineMulti(s, stk, boxp, inst.a, inst.b)); VM_DISPATCH_NEXT(); } VM_CASE(THROW) { diff --git a/src/jit/vm.cpp b/src/jit/vm.cpp index be5c7dc..c97fbe8 100644 --- a/src/jit/vm.cpp +++ b/src/jit/vm.cpp @@ -145,38 +145,76 @@ extern "C" __attribute__((used)) CVar FakeluaCallByName(State *state, int jit_ty return GuardJitEntry(state, [&] { return CallByNameImpl(state, jit_type, name, arg_num, raw_arg_arr); }); } -static CVar CallByNameImpl(State *state, int jit_type, std::string_view name, int arg_num, const CVar *raw_arg_arr) { - // 记录"当前 Lua 调用方引擎":native 函数内登记的异步回调据此派回同一引擎。 - // 作用域覆盖整个函数(含嵌套的 Lua 回调),退出时恢复外层引擎。 +static CVar CallNativeEntry(State *state, int jit_type, std::string_view name, const NativeFuncEntry *native_entry, int arg_num, const CVar *raw_arg_arr) { State::JitContextScope jit_scope(state, static_cast(jit_type)); + const bool is_vararg = native_entry->is_vararg; + const int expected_arg_count = native_entry->arg_count; + + if (UNLIKELY(arg_num < 0 || arg_num > static_cast(kMaxFunctionInputParams))) { + ThrowFakeluaException(std::format("FakeluaCallByName: too many arguments ({}) passed for function '{}', max is {}", arg_num, name, kMaxFunctionInputParams)); + } + if (UNLIKELY(expected_arg_count < 0 || expected_arg_count > static_cast(kMaxFunctionInputParams))) { + ThrowFakeluaException(std::format("FakeluaCallByName: function '{}' declares too many parameters ({}), max is {}", name, expected_arg_count, kMaxFunctionInputParams)); + } + + CVar flat_args_buf[kMaxFunctionInputParams]; + int flat_count = 0; + const bool last_is_multi = (arg_num > 0 && raw_arg_arr[arg_num - 1].type_ == static_cast(VarType::Multi)); + for (int i = 0; i < arg_num; ++i) { + if (i == arg_num - 1 && raw_arg_arr[i].type_ == static_cast(VarType::Multi)) { + VarMulti *m = raw_arg_arr[i].data_.m; + const int extra = m ? static_cast(m->GetCount()) : 0; + if (flat_count + extra > static_cast(kMaxFunctionInputParams)) { + ThrowFakeluaException(std::format("FakeluaCallByName: too many arguments ({}), max is {}", flat_count + extra, kMaxFunctionInputParams)); + } + if (m) { + for (uint32_t j = 0; j < m->GetCount(); ++j) { + flat_args_buf[flat_count++] = m->GetVars()[j]; + } + } + } else if (raw_arg_arr[i].type_ == static_cast(VarType::Multi)) { + VarMulti *m = raw_arg_arr[i].data_.m; + if (flat_count >= static_cast(kMaxFunctionInputParams)) { + ThrowFakeluaException(std::format("FakeluaCallByName: too many arguments, max is {}", kMaxFunctionInputParams)); + } + flat_args_buf[flat_count++] = (m && m->GetCount() > 0) ? m->GetVars()[0] : (CVar) {static_cast(VarType::Nil)}; + } else { + if (flat_count >= static_cast(kMaxFunctionInputParams)) { + ThrowFakeluaException(std::format("FakeluaCallByName: too many arguments, max is {}", kMaxFunctionInputParams)); + } + flat_args_buf[flat_count++] = raw_arg_arr[i]; + } + } + + if (UNLIKELY(!is_vararg && !last_is_multi && flat_count != expected_arg_count)) { + ThrowFakeluaException(std::format("FakeluaCallByName: function '{}' expects {} argument(s), got {}", name, expected_arg_count, flat_count)); + } + return native_entry->callback(state, flat_args_buf, flat_count); +} + +static CVar CallByNameImpl(State *state, int jit_type, std::string_view name, int arg_num, const CVar *raw_arg_arr) { // 查找函数:优先 JIT,其次 C++ 原生。FindFunction 避免每次拷贝 VmFunction。 const VmFunction *jit_func = state->GetVM().FindFunction(name); - const bool has_jit = jit_func != nullptr; - - // 确定 is_vararg / expected_arg_count / fixed_arg_count,并提前取出 addr, - // 避免调用期间 RegisterFunction 触发 rehash 后仍持有 jit_func 指针。 - bool is_vararg = false; - int expected_arg_count = 0; - int fixed_arg_count = 0; - const NativeFuncEntry *native_entry = nullptr; - void *jit_addr = nullptr; - - if (has_jit) { - is_vararg = jit_func->IsVararg(); - expected_arg_count = jit_func->GetArgCount(); - fixed_arg_count = is_vararg ? std::max(0, expected_arg_count - 1) : expected_arg_count; - jit_addr = jit_func->GetAddr(static_cast(jit_type)); - jit_func = nullptr; - } else { - native_entry = state->GetVM().FindNativeFunction(name); + if (!jit_func) { + const NativeFuncEntry *native_entry = state->GetVM().FindNativeFunction(name); if (UNLIKELY(!native_entry)) { ThrowFakeluaException(std::format("FakeluaCallByName: function '{}' not found", name)); } - is_vararg = native_entry->is_vararg; - expected_arg_count = native_entry->arg_count; - fixed_arg_count = is_vararg ? std::max(0, expected_arg_count - 1) : expected_arg_count; + return CallNativeEntry(state, jit_type, name, native_entry, arg_num, raw_arg_arr); } + // 记录"当前 Lua 调用方引擎":native 函数内登记的异步回调据此派回同一引擎。 + // 作用域覆盖整个函数(含嵌套的 Lua 回调),退出时恢复外层引擎。 + State::JitContextScope jit_scope(state, static_cast(jit_type)); + + // 确定 is_vararg / expected_arg_count / fixed_arg_count,并提前取出 addr, + // 避免调用期间 RegisterFunction 触发 rehash 后仍持有 jit_func 指针。 + const bool is_vararg = jit_func->IsVararg(); + const int expected_arg_count = jit_func->GetArgCount(); + const int fixed_arg_count = is_vararg ? std::max(0, expected_arg_count - 1) : expected_arg_count; + void *const jit_addr = jit_func->GetAddr(static_cast(jit_type)); + jit_func = nullptr; + if (UNLIKELY(arg_num > static_cast(kMaxFunctionInputParams))) { ThrowFakeluaException(std::format("FakeluaCallByName: too many arguments ({}) passed for function '{}', max is {}", arg_num, name, kMaxFunctionInputParams)); } @@ -249,40 +287,7 @@ static CVar CallByNameImpl(State *state, int jit_type, std::string_view name, in arg_arr = temp_arg_arr; } - // 分发 - // 情形 1:C++ 原生函数 - if (!has_jit) { - CVar flat_args_buf[kMaxFunctionInputParams]; - int flat_count = 0; - for (int i = 0; i < arg_num; ++i) { - if (i == arg_num - 1 && raw_arg_arr[i].type_ == static_cast(VarType::Multi)) { - VarMulti *m = raw_arg_arr[i].data_.m; - const int extra = m ? static_cast(m->GetCount()) : 0; - if (flat_count + extra > static_cast(kMaxFunctionInputParams)) { - ThrowFakeluaException(std::format("FakeluaCallByName: too many arguments ({}), max is {}", flat_count + extra, kMaxFunctionInputParams)); - } - if (m) { - for (uint32_t j = 0; j < m->GetCount(); ++j) { - flat_args_buf[flat_count++] = m->GetVars()[j]; - } - } - } else if (raw_arg_arr[i].type_ == static_cast(VarType::Multi)) { - VarMulti *m = raw_arg_arr[i].data_.m; - if (flat_count >= static_cast(kMaxFunctionInputParams)) { - ThrowFakeluaException(std::format("FakeluaCallByName: too many arguments, max is {}", kMaxFunctionInputParams)); - } - flat_args_buf[flat_count++] = (m && m->GetCount() > 0) ? m->GetVars()[0] : (CVar) {static_cast(VarType::Nil)}; - } else { - if (flat_count >= static_cast(kMaxFunctionInputParams)) { - ThrowFakeluaException(std::format("FakeluaCallByName: too many arguments, max is {}", kMaxFunctionInputParams)); - } - flat_args_buf[flat_count++] = raw_arg_arr[i]; - } - } - return native_entry->callback(state, flat_args_buf, flat_count); - } - - // 情形 2:JIT 编译的 lua 函数 + // 分发:JIT 编译的 lua 函数 if (UNLIKELY(!jit_addr)) { ThrowFakeluaException(std::format("FakeluaCallByName: function '{}' has no address for jit_type {}", name, jit_type)); } @@ -323,23 +328,34 @@ extern "C" __attribute__((used)) CVar FakeluaCallByNameCached(State *state, int } return GuardJitEntry(state, [&] { - if (cache && jit_type == JIT_GCC && name) { + if (cache && (jit_type == JIT_GCC || jit_type == JIT_TCC) && name) { const auto &vm = state->GetVM(); + const uint64_t vm_ver = *vm.VersionPtr(); const std::string_view sv(name); - if (const VmFunction *jf = vm.FindFunction(sv)) { - if (void *addr = jf->GetAddr(JIT_GCC)) { - cache->target = addr; - cache->expected_args = jf->GetArgCount(); - cache->is_vararg = jf->IsVararg() ? 1 : 0; - cache->kind = 1; - cache->version = *vm.VersionPtr(); + if (cache->version == vm_ver && cache->kind == 2 && cache->target != nullptr) { + return CallNativeEntry(state, jit_type, sv, static_cast(cache->target), arg_num, raw_arg_arr); + } + if (cache->version != vm_ver) { + if (const VmFunction *jf = vm.FindFunction(sv)) { + if (void *addr = jf->GetAddr(static_cast(jit_type))) { + cache->target = addr; + cache->expected_args = jf->GetArgCount(); + cache->is_vararg = jf->IsVararg() ? 1 : 0; + cache->kind = 1; + cache->version = vm_ver; + } else { + cache->version = 0; + } + } else if (const NativeFuncEntry *ne = vm.FindNativeFunction(sv)) { + cache->target = const_cast(ne); + cache->expected_args = ne->arg_count; + cache->is_vararg = ne->is_vararg ? 1 : 0; + cache->kind = 2; + cache->version = vm_ver; + return CallNativeEntry(state, jit_type, sv, ne, arg_num, raw_arg_arr); + } else { + cache->version = 0; } - } else if (const NativeFuncEntry *ne = vm.FindNativeFunction(sv)) { - cache->target = const_cast(ne); - cache->expected_args = ne->arg_count; - cache->is_vararg = ne->is_vararg ? 1 : 0; - cache->kind = 2; - cache->version = *vm.VersionPtr(); } } return CallByNameImpl(state, jit_type, name, arg_num, raw_arg_arr); diff --git a/src/native/basic/native_basic.cpp b/src/native/basic/native_basic.cpp index 4f1ca7a..95ae724 100644 --- a/src/native/basic/native_basic.cpp +++ b/src/native/basic/native_basic.cpp @@ -562,7 +562,7 @@ void RegisterBasicLibraryApi(State *s) { void *addr = err_cl->func_ptr; CVar err_result{static_cast(VarType::Nil)}; if (addr != nullptr) { - err_result = inter::DispatchCallClosure(state, err_cl, &err_arg, 1, JIT_TCC); + err_result = inter::DispatchCallClosure(state, err_cl, &err_arg, 1, state->CurrentJit()); } else if (IsSourceLoadClosure(err_cl)) { err_result = FlEvalLoadClosure(state, err_cl, 1, &err_arg); } else { diff --git a/src/native/table/native_table.cpp b/src/native/table/native_table.cpp index 52ad5a8..cb1aea8 100644 --- a/src/native/table/native_table.cpp +++ b/src/native/table/native_table.cpp @@ -1257,7 +1257,7 @@ void RegisterTableLibraryApi(State *s) { CVar res{kNilType}; if (cl->func_ptr) { CVar cmp_args[2] = {a, b}; - res = inter::DispatchCallClosure(state, cl, cmp_args, 2, JIT_TCC); + res = inter::DispatchCallClosure(state, cl, cmp_args, 2, state->CurrentJit()); } else if (IsSourceLoadClosure(cl)) { CVar args_arr[2] = {a, b}; res = FlEvalLoadClosure(state, cl, 2, args_arr); diff --git a/src/state/fakelua.cpp b/src/state/fakelua.cpp index 77aaeee..5735d63 100644 --- a/src/state/fakelua.cpp +++ b/src/state/fakelua.cpp @@ -582,7 +582,7 @@ CVar DispatchCall(State *s, void *addr, const CVar *arg_arr, int arg_count, JITT } // GCC 后端产出的动态库带 .eh_frame,C++ 异常能正常穿过它的帧; // 若调用方显式传 JIT_TCC 请求边界,或闭包本身来自 TCC,则保留 setjmp 边界。 - if (effective_type == JIT_GCC && type == JIT_GCC) { + if (effective_type == JIT_GCC && type == JIT_GCC && (!cl || IsGccClosure(cl))) { return DispatchCallRaw(addr, arg_arr, arg_count, cl); } return RunWithJitErrorBoundary(s, [&] { return DispatchCallRaw(addr, arg_arr, arg_count, cl); }); diff --git a/test/test_native.cpp b/test/test_native.cpp index 878e8a0..22feb99 100644 --- a/test/test_native.cpp +++ b/test/test_native.cpp @@ -1260,3 +1260,336 @@ TEST(test_native, extracted_method_calls_and_destroyed_wrapper_contracts) { Call(state.GetState(), JIT_INTERP, "extracted_method_contracts", result); EXPECT_EQ(result, 1); } + +TEST(test_native, cached_vararg_native_and_multi_expansion_across_backends) { + for (auto backend: AllJitTypes()) { + SCOPED_TRACE(JitTypeName(backend)); + FakeluaStateGuard guard; + State *s = guard.GetState(); + + RegisterNativeFunction(s, "vararg_sum", 0, true, [](State *st, CVar *args, int n) -> CVar { + int64_t sum = 0; + for (int i = 0; i < n; ++i) { + sum += inter::CVarToInteger(inter::GetNativeArg(st, args, n, i), 0); + } + return inter::NativeToFakeluaInt(st, sum); + }); + RegisterNativeFunction(s, "fixed_pair", 2, false, [](State *st, CVar *args, int n) -> CVar { + return inter::NativeToFakeluaInt(st, inter::CVarToInteger(inter::GetNativeArg(st, args, n, 0), 0) * 100 + inter::CVarToInteger(inter::GetNativeArg(st, args, n, 1), 0)); + }); + + CompileConfig cfg{}; + cfg.debug_mode = false; + cfg.disable_jit[JIT_TCC] = (backend != JIT_TCC); + cfg.disable_jit[JIT_GCC] = (backend != JIT_GCC); + cfg.disable_jit[JIT_INTERP] = (backend != JIT_INTERP); + + CompileString(s, R"( + local function two_vals() + return 3, 4 + end + + local function tail_vararg(a, b, c) + return vararg_sum(a, b, c) + end + + local function boxed_multi_and_combine(...) + local captured = 5 + local bump = function() + captured = captured + 1 + return captured + end + local function emit_pair() + return bump(), 20 + end + local function emit_combined(...) + return captured, ... + end + local p1, p2 = emit_pair() + local c1, c2, c3 = emit_combined(10, ...) + return p1 + p2 + c1 + c2 + c3 + end + + local function sum_select(...) + local n = select("#", ...) + local acc = 0 + for i = 1, n do + acc = acc + select(i, ...) + end + return acc + end + + function run_native_fast_path() + local acc = 0 + for i = 1, 5 do + acc = acc + vararg_sum() + vararg_sum(i) + tail_vararg(1, 2, i) + end + local from_multi = vararg_sum(10, two_vals()) + local non_last = fixed_pair(two_vals(), 7) + local from_pair_multi = fixed_pair(two_vals()) + local sel = sum_select(2, 4, 6, 8) + local boxed = boxed_multi_and_combine(30) + return acc * 10000 + from_multi * 100 + non_last + from_pair_multi + sel + boxed + end + + function call_fixed_bad_arity() + local ok = fixed_pair(1, 2) + return ok + fixed_pair(1, 2, 3) + end + )", + cfg); + + int64_t out = 0; + Call(s, backend, "run_native_fast_path", out); + // acc = sum_{i=1..5} (0 + i + (3 + i)) = 15 + 30 = 45 + // from_multi = 10 + 3 + 4 = 17 + // non_last = 3*100 + 7 = 307 + // from_pair_multi = 3*100 + 4 = 304 + // sel = 2 + 4 + 6 + 8 = 20 + // boxed: captured starts 5 -> bump()->6, p1=6, p2=20, c1=6, c2=10, c3=30 => 72 + EXPECT_EQ(out, 45 * 10000 + 17 * 100 + 307 + 304 + 20 + 72); + + // Fixed-arity mismatch must still throw even when the call site uses native caching. + try { + int64_t bad = 0; + Call(s, backend, "call_fixed_bad_arity", bad); + FAIL() << "Expected arity error on " << JitTypeName(backend); + } catch (const FakeluaException &e) { + EXPECT_NE(std::string(e.what()).find("expects 2 argument(s), got 3"), std::string::npos) << e.what(); + } + } +} + +TEST(test_native, cached_native_error_location_and_stack_across_backends) { + for (auto backend: AllJitTypes()) { + SCOPED_TRACE(JitTypeName(backend)); + FakeluaStateGuard guard; + State *s = guard.GetState(); + + RegisterNativeFunction(s, "boom_on_flag", 1, true, [](State *st, CVar *args, int n) -> CVar { + if (inter::CVarToInteger(inter::GetNativeArg(st, args, n, 0), 0) != 0) { + ThrowFakeluaException("cached_native_boom"); + } + return inter::NativeToFakeluaInt(st, n); + }); + + CompileConfig cfg{}; + cfg.debug_mode = false; + cfg.disable_jit[JIT_TCC] = (backend != JIT_TCC); + cfg.disable_jit[JIT_GCC] = (backend != JIT_GCC); + cfg.disable_jit[JIT_INTERP] = (backend != JIT_INTERP); + + CompileString(s, R"( +function inner_direct(flag) + local r = boom_on_flag(flag, 1, 2) + return r + 1 +end + +function outer_direct(flag) + local v = inner_direct(flag) + return v + 1 +end + +function inner_tail(flag) + return boom_on_flag(flag, 1, 2) +end + +function outer_tail(flag) + local v = inner_tail(flag) + return v + 1 +end +)", + cfg); + + // First call succeeds and populates the call-site cache. + int64_t ok = 0; + Call(s, backend, "outer_direct", ok, int64_t{0}); + EXPECT_EQ(ok, 5); + Call(s, backend, "outer_tail", ok, int64_t{0}); + EXPECT_EQ(ok, 4); + + const std::string expected_direct_line = (backend == JIT_GCC) ? ":2" : ":3"; + const std::string expected_tail_line = (backend == JIT_GCC) ? ":12" : ":13"; + + // Second call throws through the cached native path and must keep exact loc + Lua stack. + try { + Call(s, backend, "outer_direct", ok, int64_t{1}); + FAIL() << "Expected exception on outer_direct"; + } catch (const FakeluaException &e) { + EXPECT_EQ(e.Msg(), "cached_native_boom"); + EXPECT_TRUE(e.HasLoc()) << e.what(); + EXPECT_NE(e.Loc().find(expected_direct_line), std::string::npos) << "loc=" << e.Loc(); + EXPECT_NE(e.LuaStack().find("inner_direct"), std::string::npos) << "stack=\n" << e.LuaStack(); + EXPECT_NE(e.LuaStack().find("outer_direct"), std::string::npos) << "stack=\n" << e.LuaStack(); + } + + try { + Call(s, backend, "outer_tail", ok, int64_t{1}); + FAIL() << "Expected exception on outer_tail"; + } catch (const FakeluaException &e) { + EXPECT_EQ(e.Msg(), "cached_native_boom"); + EXPECT_TRUE(e.HasLoc()) << e.what(); + EXPECT_NE(e.Loc().find(expected_tail_line), std::string::npos) << "loc=" << e.Loc(); + EXPECT_NE(e.LuaStack().find("inner_tail"), std::string::npos) << "stack=\n" << e.LuaStack(); + EXPECT_NE(e.LuaStack().find("outer_tail"), std::string::npos) << "stack=\n" << e.LuaStack(); + } + } +} + +TEST(test_native, cached_native_invalidation_on_redefinition_across_backends) { + for (auto backend: AllJitTypes()) { + SCOPED_TRACE(JitTypeName(backend)); + FakeluaStateGuard guard; + State *s = guard.GetState(); + + RegisterNativeFunction(s, "hot_target", 1, true, [](State *st, CVar *args, int n) -> CVar { + return inter::NativeToFakeluaInt(st, inter::CVarToInteger(inter::GetNativeArg(st, args, n, 0), 0) + 1); + }); + + CompileConfig cfg{}; + cfg.debug_mode = false; + cfg.disable_jit[JIT_TCC] = (backend != JIT_TCC); + cfg.disable_jit[JIT_GCC] = (backend != JIT_GCC); + cfg.disable_jit[JIT_INTERP] = (backend != JIT_INTERP); + + CompileString(s, R"( + function invoke_hot(x) + local a = hot_target(x) + local b = hot_target(x) + return a + b + end + )", + cfg); + + int64_t v = 0; + Call(s, backend, "invoke_hot", v, int64_t{5}); + EXPECT_EQ(v, 12); + + // Overwrite native callback: vm_version bump must invalidate cached native entry. + RegisterNativeFunction(s, "hot_target", 1, true, [](State *st, CVar *args, int n) -> CVar { + return inter::NativeToFakeluaInt(st, inter::CVarToInteger(inter::GetNativeArg(st, args, n, 0), 0) + 100); + }); + Call(s, backend, "invoke_hot", v, int64_t{5}); + EXPECT_EQ(v, 210); + + // Shadow native with a Lua function: cached site must switch from native to Lua. + CompileString(s, "function hot_target(x) return x * 3 end", cfg); + Call(s, backend, "invoke_hot", v, int64_t{5}); + EXPECT_EQ(v, 30); + + // Redefine Lua function: cached site must pick up the new definition. + CompileString(s, "function hot_target(x) return x * 7 end", cfg); + Call(s, backend, "invoke_hot", v, int64_t{5}); + EXPECT_EQ(v, 70); + } +} + +TEST(test_native, table_sort_and_xpcall_current_jit_and_cross_backend_closures) { + for (auto backend: AllJitTypes()) { + SCOPED_TRACE(JitTypeName(backend)); + FakeluaStateGuard guard; + State *s = guard.GetState(); + + CompileConfig cfg{}; + cfg.debug_mode = false; + cfg.disable_jit[JIT_TCC] = (backend != JIT_TCC); + cfg.disable_jit[JIT_GCC] = (backend != JIT_GCC); + cfg.disable_jit[JIT_INTERP] = (backend != JIT_INTERP); + + CompileString(s, R"( + function test_sort_and_xpcall() + local t = { 5, 1, 4, 2, 3 } + table.sort(t, function(a, b) return a > b end) + assert(t[1] == 5 and t[2] == 4 and t[3] == 3 and t[4] == 2 and t[5] == 1) + + local sort_ok, sort_err = pcall(function() + table.sort({ 3, 1, 2 }, function(a, b) + error("cmp_boom") + end) + end) + assert(not sort_ok and string.find(sort_err, "cmp_boom", 1, true) ~= nil) + + local xok, xmsg = xpcall(function() + error("xp_boom") + end, function(err) + return "handled:" .. err + end) + assert(not xok and string.find(xmsg, "handled:", 1, true) == 1 and string.find(xmsg, "xp_boom", 1, true) ~= nil) + return 1 + end + )", + cfg); + + int64_t ok = 0; + Call(s, backend, "test_sort_and_xpcall", ok); + EXPECT_EQ(ok, 1); + } + + // Cross-backend safety: a TCC closure passed into GCC table.sort / xpcall must still + // run inside a JIT error boundary so throwing inside the TCC closure is caught cleanly. + FakeluaStateGuard guard; + State *s = guard.GetState(); + CompileConfig tcc_only{}; + tcc_only.debug_mode = false; + tcc_only.disable_jit[JIT_GCC] = true; + tcc_only.disable_jit[JIT_INTERP] = true; + CompileString(s, R"( + function make_tcc_cmp(should_throw) + return function(a, b) + if should_throw then + error("tcc_cmp_boom") + end + return a > b + end + end + function make_tcc_err_handler() + return function(err) + return "tcc_caught:" .. err + end + end + )", + tcc_only); + + CompileConfig gcc_only{}; + gcc_only.debug_mode = false; + gcc_only.disable_jit[JIT_TCC] = true; + gcc_only.disable_jit[JIT_INTERP] = true; + RegisterNativeFunction(s, "get_tcc_cmp", 1, false, [](State *st, CVar *args, int n) -> CVar { + CVar a0 = inter::GetNativeArg(st, args, n, 0); + const VmFunction *fn = st->GetVM().FindFunction("make_tcc_cmp"); + EXPECT_NE(fn, nullptr); + return inter::DispatchCall(st, fn->GetAddr(JIT_TCC), &a0, 1, JIT_TCC); + }); + RegisterNativeFunction(s, "get_tcc_err_handler", 0, false, [](State *st, CVar *, int) -> CVar { + const VmFunction *fn = st->GetVM().FindFunction("make_tcc_err_handler"); + EXPECT_NE(fn, nullptr); + return inter::DispatchCall(st, fn->GetAddr(JIT_TCC), nullptr, 0, JIT_TCC); + }); + CompileString(s, R"( + function run_gcc_with_tcc_closures() + local cmp_ok = get_tcc_cmp(false) + local cmp_throw = get_tcc_cmp(true) + local err_handler = get_tcc_err_handler() + + local t = { 2, 5, 1, 4, 3 } + table.sort(t, cmp_ok) + assert(t[1] == 5 and t[5] == 1) + + local sok, serr = pcall(function() + table.sort({ 2, 1 }, cmp_throw) + end) + assert(not sok and string.find(serr, "tcc_cmp_boom", 1, true) ~= nil) + + local xok, xmsg = xpcall(function() + error("gcc_origin_boom") + end, err_handler) + assert(not xok and string.find(xmsg, "tcc_caught:", 1, true) == 1 and string.find(xmsg, "gcc_origin_boom", 1, true) ~= nil) + return 1 + end + )", + gcc_only); + + int64_t cross_ok = 0; + Call(s, JIT_GCC, "run_gcc_with_tcc_closures", cross_ok); + EXPECT_EQ(cross_ok, 1); +} From 955004ceb087514561167b590815db5b5563d469 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Tue, 1 Dec 2026 12:23:29 +0000 Subject: [PATCH 2/2] fix(test,interp): split inner/outer modules in stack test for Windows PE and mark cold interp helpers noinline Co-authored-by: esrrhs --- src/interp/interpreter.cpp | 50 +++++++++++++++++++++++--------------- test/test_native.cpp | 15 ++++++++---- 2 files changed, 40 insertions(+), 25 deletions(-) diff --git a/src/interp/interpreter.cpp b/src/interp/interpreter.cpp index b93f98b..5ff43f6 100644 --- a/src/interp/interpreter.cpp +++ b/src/interp/interpreter.cpp @@ -38,6 +38,32 @@ struct NamedCallTarget { bool native_direct = false; }; +#if defined(__GNUC__) +__attribute__((noinline)) +#endif +void RefillNamedCallCache(State *s, FuncProto *caller, const Inst &inst, InterpCallCache &slot, uint64_t ver) { + const std::string_view name = ConstToName(caller->constants[static_cast(inst.sbx)]); + FuncProto *found_proto = nullptr; + const NativeFuncEntry *found_native = nullptr; + if ((inst.c & kCallLocalUnit) != 0 && caller->unit != nullptr) { + if (const auto it = caller->unit->local_funcs.find(name); it != caller->unit->local_funcs.end() && it->second) { + found_proto = it->second; + } + } + if (found_proto == nullptr) { + if (const VmFunction *fn = s->GetVM().FindFunction(name)) { + if (void *addr = fn->GetAddr(JIT_INTERP)) { + found_proto = AsInterpProto(addr); + } + } else { + found_native = s->GetVM().FindNativeFunction(name); + } + } + slot.proto = found_proto; + slot.native = found_native; + slot.vm_version = ver; +} + // 文件级命名调用的调用点缓存。命中且实参个数精确、非变参、末参不是 Multi 时 direct 为真; // 目标是原生函数且无 Multi 实参、满足定参/变参要求时 native_direct 为真,直接调回调不再查哈希表。 NamedCallTarget ResolveNamedCall(State *s, FuncProto *caller, const Inst *ip_after, const Inst &inst, int nargs, const CVar *args) { @@ -52,26 +78,7 @@ NamedCallTarget ResolveNamedCall(State *s, FuncProto *caller, const Inst *ip_aft InterpCallCache &slot = caller->call_cache[static_cast(off)]; const uint64_t ver = *s->GetVM().VersionPtr(); if (FL_VM_UNLIKELY(slot.vm_version != ver)) { - const std::string_view name = ConstToName(caller->constants[static_cast(inst.sbx)]); - FuncProto *found_proto = nullptr; - const NativeFuncEntry *found_native = nullptr; - if ((inst.c & kCallLocalUnit) != 0 && caller->unit != nullptr) { - if (const auto it = caller->unit->local_funcs.find(name); it != caller->unit->local_funcs.end() && it->second) { - found_proto = it->second; - } - } - if (found_proto == nullptr) { - if (const VmFunction *fn = s->GetVM().FindFunction(name)) { - if (void *addr = fn->GetAddr(JIT_INTERP)) { - found_proto = AsInterpProto(addr); - } - } else { - found_native = s->GetVM().FindNativeFunction(name); - } - } - slot.proto = found_proto; - slot.native = found_native; - slot.vm_version = ver; + RefillNamedCallCache(s, caller, inst, slot, ver); } out.proto = slot.proto; out.native = slot.native; @@ -182,6 +189,9 @@ inline CVar InterpCallNativeDirect(State *s, const NativeFuncEntry *native, CVar int FlattenByNameArgs(const CVar *raw, int arg_num, CVar *flat); +#if defined(__GNUC__) +__attribute__((noinline)) +#endif CVar InterpCallNativeSlow(State *s, const NativeFuncEntry *native, std::string_view name, const CVar *raw, int nargs) { if (UNLIKELY(native->arg_count < 0 || native->arg_count > static_cast(kMaxFunctionInputParams))) { ThrowFakeluaException(std::format("FakeluaCallByName: function '{}' declares too many parameters ({}), max is {}", name, native->arg_count, kMaxFunctionInputParams)); diff --git a/test/test_native.cpp b/test/test_native.cpp index 22feb99..d76ee68 100644 --- a/test/test_native.cpp +++ b/test/test_native.cpp @@ -1379,21 +1379,26 @@ TEST(test_native, cached_native_error_location_and_stack_across_backends) { cfg.disable_jit[JIT_GCC] = (backend != JIT_GCC); cfg.disable_jit[JIT_INTERP] = (backend != JIT_INTERP); + // Compile inner and outer in separate modules so optimizing compilers (notably MinGW GCC + // on Windows PE/COFF, which lacks ELF symbol interposition) cannot inline inner into outer. CompileString(s, R"( function inner_direct(flag) local r = boom_on_flag(flag, 1, 2) return r + 1 end +function inner_tail(flag) + return boom_on_flag(flag, 1, 2) +end +)", + cfg); + + CompileString(s, R"( function outer_direct(flag) local v = inner_direct(flag) return v + 1 end -function inner_tail(flag) - return boom_on_flag(flag, 1, 2) -end - function outer_tail(flag) local v = inner_tail(flag) return v + 1 @@ -1409,7 +1414,7 @@ end EXPECT_EQ(ok, 4); const std::string expected_direct_line = (backend == JIT_GCC) ? ":2" : ":3"; - const std::string expected_tail_line = (backend == JIT_GCC) ? ":12" : ":13"; + const std::string expected_tail_line = (backend == JIT_GCC) ? ":7" : ":8"; // Second call throws through the cached native path and must keep exact loc + Lua stack. try {