diff --git a/src/interp/interpreter.cpp b/src/interp/interpreter.cpp index 5ff43f6..2188563 100644 --- a/src/interp/interpreter.cpp +++ b/src/interp/interpreter.cpp @@ -12,6 +12,7 @@ #include "var/var_closure.h" #include "var/var_multi.h" #include "var/var_string.h" +#include "var/var_table.h" #include #include #include @@ -205,6 +206,46 @@ CVar InterpCallNativeSlow(State *s, const NativeFuncEntry *native, std::string_v return InterpCallNativeDirect(s, native, nflat == 0 ? nullptr : flat, nflat); } +[[noreturn]] +#if defined(__GNUC__) +__attribute__((noinline, cold)) +#endif +void InterpThrowIndexError(bool non_table) { + if (non_table) { + ThrowFakeluaException("attempt to index a non-table value"); + } + ThrowFakeluaException("table index is nil"); +} + +#if defined(__GNUC__) +__attribute__((noinline)) +#endif +CVar InterpGetTableSlow(State *s, CVar t, CVar k) { + if (UNLIKELY(t.type_ != interp_rt::kTable)) { + InterpThrowIndexError(true); + } + if (UNLIKELY(k.type_ == interp_rt::kNil)) { + InterpThrowIndexError(false); + } + if (k.type_ == interp_rt::kInt) { + return table::TableHelper::GetTableInt(s, t, k.data_.i); + } + return table::TableHelper::GetTable(s, t, k); +} + +#if defined(__GNUC__) +__attribute__((noinline)) +#endif +void InterpSetTableSlow(State *s, CVar t, CVar k, CVar v) { + if (UNLIKELY(t.type_ != interp_rt::kTable)) { + InterpThrowIndexError(true); + } + if (UNLIKELY(k.type_ == interp_rt::kNil)) { + InterpThrowIndexError(false); + } + table::TableHelper::SetTable(s, t, k, v); +} + template inline CVar InterpMakeMulti(State *s, CVar *stk, CVar **boxp, int base, int n) { if constexpr (!HasBoxes) { @@ -806,23 +847,108 @@ CVar InterpreterExecuteT(State *s, FuncProto *proto, const CVar *args, int arg_c VM_DISPATCH_NEXT(); } VM_CASE(GETTABLE) { - const CVar t = VM_R(inst.b); - const CVar k = VM_R(inst.c); - if (FL_VM_UNLIKELY(t.type_ != interp_rt::kTable)) { - ThrowFakeluaException("attempt to index a non-table value"); - } - if (FL_VM_UNLIKELY(k.type_ == interp_rt::kNil)) { - ThrowFakeluaException("table index is nil"); - } - if (k.type_ == interp_rt::kInt) { - VM_W(inst.a, table::TableHelper::GetTableInt(s, t, k.data_.i)); - } else { - VM_W(inst.a, table::TableHelper::GetTable(s, t, k)); + const CVar &t = VM_R(inst.b); + const CVar &k = VM_R(inst.c); + if (FL_VM_LIKELY(t.type_ == interp_rt::kTable && t.data_.t != nullptr)) { + const VarTable *const tbl = t.data_.t; + if (k.type_ == interp_rt::kInt) { + const uint64_t idx = static_cast(k.data_.i) - 1; + if (FL_VM_LIKELY(idx < tbl->arr_size_)) { + VM_W(inst.a, tbl->arr_[idx]); + VM_DISPATCH_NEXT(); + } + if (tbl->spec_get == nullptr && tbl->spec_count == 0 && tbl->bucket_count_ == 0) { + const int64_t ki = k.data_.i; + const uint32_t n = tbl->count_; + for (uint32_t i = 0; i < n; ++i) { + const auto &qd = tbl->quick_data_[i]; + if (qd.key.type_ == interp_rt::kInt && qd.key.data_.i == ki) { + VM_W(inst.a, qd.val); + VM_DISPATCH_NEXT(); + } + } + VM_W(inst.a, interp_rt::Nil()); + VM_DISPATCH_NEXT(); + } + } else if (k.type_ == interp_rt::kStringId && tbl->spec_get == nullptr && tbl->spec_count == 0 && tbl->bucket_count_ == 0) { + const int64_t sid = k.data_.i; + const uint32_t h = sid != 0 ? reinterpret_cast(sid)->CachedHash() : 0u; + if (FL_VM_LIKELY(h != 0)) { + const uint32_t n = tbl->count_; + bool hash_miss = true; + for (uint32_t i = 0; i < n; ++i) { + const auto &qd = tbl->quick_data_[i]; + if (qd.hash == h) { + if (FL_VM_LIKELY(qd.key.type_ == interp_rt::kStringId && qd.key.data_.i == sid)) { + VM_W(inst.a, qd.val); + VM_DISPATCH_NEXT(); + } + hash_miss = false; + break; + } + } + if (FL_VM_LIKELY(hash_miss)) { + VM_W(inst.a, interp_rt::Nil()); + VM_DISPATCH_NEXT(); + } + } + } } + VM_W(inst.a, InterpGetTableSlow(s, t, k)); VM_DISPATCH_NEXT(); } VM_CASE(SETTABLE) { - interp_rt::SetTable(s, VM_R(inst.a), VM_R(inst.b), VM_R(inst.c)); + const CVar &t = VM_R(inst.a); + const CVar &k = VM_R(inst.b); + const CVar &v = VM_R(inst.c); + if (FL_VM_LIKELY(t.type_ == interp_rt::kTable && (t.flag_ & interp_rt::kConstFlag) == 0 && t.data_.t != nullptr)) { + VarTable *const tbl = t.data_.t; + if (k.type_ == interp_rt::kInt) { + const uint64_t idx = static_cast(k.data_.i) - 1; + if (FL_VM_LIKELY(idx < tbl->arr_size_)) { + if (FL_VM_LIKELY(v.type_ != interp_rt::kNil && tbl->arr_[idx].type_ != interp_rt::kNil)) { + tbl->arr_[idx] = v; + VM_DISPATCH_NEXT(); + } + } else if (idx == tbl->arr_size_ && tbl->arr_size_ < tbl->arr_cap_ && tbl->count_ == 0 && v.type_ != interp_rt::kNil) { + // spec tables never allocate arr_, so arr_cap_ > 0 guarantees a plain table; + // count_ == 0 guarantees no hash entries follow arr_size_ for migration or #t. + tbl->arr_[idx] = v; + tbl->arr_size_ = static_cast(idx) + 1; + if (tbl->seq_len_valid_ != 0 && tbl->seq_len_ == static_cast(idx)) { + tbl->seq_len_ = k.data_.i; + } + VM_DISPATCH_NEXT(); + } + } else if (k.type_ == interp_rt::kStringId && v.type_ != interp_rt::kNil && tbl->spec_set == nullptr && tbl->spec_count == 0 && tbl->bucket_count_ == 0) { + const int64_t sid = k.data_.i; + const uint32_t h = sid != 0 ? reinterpret_cast(sid)->CachedHash() : 0u; + if (FL_VM_LIKELY(h != 0)) { + const uint32_t n = tbl->count_; + bool hash_miss = true; + for (uint32_t i = 0; i < n; ++i) { + auto &qd = tbl->quick_data_[i]; + if (qd.hash == h) { + if (FL_VM_LIKELY(qd.key.type_ == interp_rt::kStringId && qd.key.data_.i == sid)) { + static_cast(qd.val) = v; + VM_DISPATCH_NEXT(); + } + hash_miss = false; + break; + } + } + if (FL_VM_LIKELY(hash_miss && n < VarTable::QUICK_DATA_SIZE)) { + auto &qd = tbl->quick_data_[n]; + static_cast(qd.key) = k; + static_cast(qd.val) = v; + qd.hash = h; + tbl->count_ = n + 1; + VM_DISPATCH_NEXT(); + } + } + } + } + InterpSetTableSlow(s, t, k, v); VM_DISPATCH_NEXT(); } VM_CASE(NEWTABLE) { diff --git a/src/var/var_string.h b/src/var/var_string.h index cbaccd5..de39221 100644 --- a/src/var/var_string.h +++ b/src/var/var_string.h @@ -36,6 +36,10 @@ class VarString { return (hash_val == 0) ? 1 : hash_val; } + [[nodiscard]] uint32_t CachedHash() const { + return hash_; + } + [[nodiscard]] uint32_t Hash() const { if (hash_ == 0) { hash_ = HashOf(Str()); diff --git a/test/test_table.cpp b/test/test_table.cpp index c57051c..6a18ac4 100644 --- a/test/test_table.cpp +++ b/test/test_table.cpp @@ -8,8 +8,10 @@ #include #include "fakelua.h" +#include "native/object/native_object.h" #include "native/table/native_table.h" #include "test_jit.h" +#include "util/exception.h" #include "var/var.h" #include "var/var_multi.h" @@ -713,3 +715,318 @@ TEST(test_table, loaded_source_comparator_and_unpack_type_contract) { CallAll(state.GetState(), "test_loaded_sort_comparator", result); EXPECT_EQ(result, 1); } + +TEST(test_table, interp_table_fastpath_edge_cases_across_backends) { + for (auto backend: AllJitTypes()) { + SCOPED_TRACE(JitTypeName(backend)); + FakeluaStateGuard guard; + State *s = guard.GetState(); + + // Synthetic ABI spec table (spec_count > 0 without spec_get) + wrapped NativeObject spec table. + VarTable abi_spec{}; + abi_spec.free_list_idx_ = VarTable::INVALID_INDEX; + CVar tag_key{}; + tag_key.type_ = static_cast(VarType::StringId); + tag_key.data_.i = s->GetConstString().Alloc("tag"); + std::array spec_keys{inter::NativeToFakeluaInt(s, 1), tag_key}; + std::array spec_vals{inter::NativeToFakeluaInt(s, 77), inter::NativeToFakeluaInt(s, 88)}; + abi_spec.spec_keys = spec_keys.data(); + abi_spec.spec_vals = spec_vals.data(); + abi_spec.spec_count = static_cast(spec_keys.size()); + CVar abi_spec_cv{}; + abi_spec_cv.type_ = static_cast(VarType::Table); + abi_spec_cv.data_.t = &abi_spec; + + RegisterNativeFunction(s, "get_abi_spec_table", 0, false, [abi_spec_cv](State *, CVar *, int) { return abi_spec_cv; }); + RegisterNativeFunction(s, "check_abi_spec", 0, false, [backend](State *st, CVar *, int) { + return inter::NativeToFakeluaInt(st, backend == JIT_INTERP ? 1 : 0); + }); + auto &obj_mgr = s->GetNativeObjectManager(); + const int64_t obj_gid = obj_mgr.CreateGroup(); + NativeObject *spec_obj = obj_mgr.Create(obj_gid, "fastpath_spec", 1); + spec_obj->SetInt("x", 111); + spec_obj->SetInt("1", 222); + RegisterNativeFunction(s, "get_native_spec_table", 0, false, [spec_obj](State *st, CVar *, int) { + return spec_obj->Wrap(st); + }); + + CompileConfig cfg{}; + 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 const_arr = { 10, 20, 30, 40, 50 } +local const_rec = { x = 7, y = 8, ab = 9 } + +function test_fastpath_edges() + -- 1. Const table reads (arr_ and quick_data_) + assert(const_arr[1] == 10 and const_arr[5] == 50 and const_arr[6] == nil) + assert(const_arr[0] == nil and const_arr[-1] == nil) + assert(const_rec.x == 7 and const_rec.y == 8 and const_rec.ab == 9) + assert(const_rec.bA == nil and const_rec.missing == nil) + + -- 2. Dense arr_ sequential append across cap growths (4 -> 8 -> 16 -> 32) + #t tracking + local a = {} + for i = 1, 20 do + a[i] = i * 3 + assert(#a == i) + end + assert(a[1] == 3 and a[20] == 60 and a[21] == nil) + -- In-bounds overwrite keeps #a intact + a[5] = 500 + assert(a[5] == 500 and #a == 20) + -- Writing nil at arr_size_ + 1 must not grow arr_size_ or change #a + a[21] = nil + assert(#a == 20 and a[21] == nil) + -- Nil deletion inside arr_ shrinks #a; appending at arr_size_ + 1 must not advance #a past hole + a[10] = nil + assert(a[10] == nil and #a == 9) + a[21] = 63 + assert(a[21] == 63 and #a == 9) + -- Refilling hole restores full #a + a[10] = 30 + assert(a[10] == 30 and #a == 21) + + -- 3. Float keys aliasing int keys (1.0, 2.0, -0.0) + non-integer float keys (1.5) + local f = { 100, 200 } + assert(f[1.0] == 100 and f[2.0] == 200) + f[1.0] = 101 + assert(f[1] == 101 and f[1.0] == 101) + f[-0.0] = 55 + assert(f[0] == 55 and f[-0.0] == 55) + f[1.5] = 15 + assert(f[1.5] == 15 and f[1] == 101) + + -- 4. Negative / zero / OOB / extreme int keys in quick_data_ + local q = {} + assert(q[0] == nil and q[-1] == nil and q[100] == nil) + q[0] = 11 + q[-1] = 22 + q[1000] = 33 + q[math.mininteger] = 44 + q[math.maxinteger] = 55 + assert(q[0] == 11 and q[-1] == 22 and q[1000] == 33) + assert(q[math.mininteger] == 44 and q[math.maxinteger] == 55) + assert(q[1] == nil and q[-2] == nil) + q[-1] = nil + assert(q[-1] == nil and q[0] == 11) + + -- 5. quick_data_ StringId hits, misses, djb2 collisions ("ab" vs "bA"), dynamic String aliasing, and 8 -> 9 rehash + local s = {} + assert(s.ab == nil and s.bA == nil) + s.ab = 1 + assert(s.ab == 1 and s.bA == nil and s.zz == nil) + s.bA = 2 + assert(s.ab == 1 and s.bA == 2 and s.zz == nil) + s.ab = 10 + assert(s.ab == 10 and s.bA == 2) + s.ab = nil + assert(s.ab == nil and s.bA == 2) + + local dyn = {} + local kdyn = "he" .. "llo" + dyn[kdyn] = 123 + assert(dyn.hello == 123) + dyn.hello = 456 + assert(dyn[kdyn] == 456 and dyn.hello == 456) + local cnt = 0 + for _, _ in pairs(dyn) do cnt = cnt + 1 end + assert(cnt == 1) + dyn[kdyn] = 789 + assert(dyn.hello == 789) + + local grow = {} + grow.k1 = 1 + grow.k2 = 2 + grow.k3 = 3 + grow.k4 = 4 + grow.k5 = 5 + grow.k6 = 6 + grow.k7 = 7 + grow.k8 = 8 + grow.k9 = 9 + grow.k10 = 10 + assert(grow.k1 == 1 and grow.k8 == 8 and grow.k9 == 9 and grow.k10 == 10 and grow.k11 == nil) + grow.k5 = 55 + assert(grow.k5 == 55) + + -- 6. Self-aliasing GETTABLE (cur = cur.a, idx = map[idx]) + local n3 = { v = 99 } + local n2 = { a = n3 } + local n1 = { a = n2 } + local cur = n1 + while cur.a do cur = cur.a end + assert(cur.v == 99) + local map = { 2, 3, 4, 1 } + local idx = 1 + idx = map[idx] + idx = map[idx] + assert(idx == 3) + + -- 7. Boxed locals (exercises InterpreterExecuteT) + local boxed_t = { 5, 6, 7, p = 10 } + local boxed_k = 2 + local function bump() + boxed_t[boxed_k] = boxed_t[boxed_k] + 1 + boxed_t.p = boxed_t.p + boxed_t[1] + boxed_t.q = 42 + return boxed_t[boxed_k] + boxed_t.p + boxed_t.q + end + assert(bump() == (7 + 15 + 42)) + + -- 8. ABI spec table read (spec_count > 0) and NativeObject spec table (spec_get/spec_set != nil, spec_count == 0) + if check_abi_spec() ~= 0 then + local sp = get_abi_spec_table() + assert(sp[1] == 77 and sp.tag == 88 and sp.none == nil) + end + local nsp = get_native_spec_table() + assert(nsp.x == 111 and nsp.missing == nil) + nsp.x = 333 + nsp.y = 444 + assert(nsp.x == 333 and nsp.y == 444) + + return 1 +end +)", + cfg); + + int64_t result = 0; + Call(s, backend, "test_fastpath_edges", result); + EXPECT_EQ(result, 1); + EXPECT_EQ(spec_obj->GetInt("x"), 333); + EXPECT_EQ(spec_obj->GetInt("y"), 444); + obj_mgr.DestroyGroup(obj_gid); + } +} + +TEST(test_table, interp_table_error_location_and_stack_across_backends) { + 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"( +local const_arr = { 10, 20 } +local const_rec = { x = 1 } + +function inner_get_nontable(x) + return x[1] +end + +function inner_set_nontable(x) + x[1] = 2 + return 0 +end + +function inner_get_nilkey() + local t = { 1, 2 } + local k = nil + return t[k] +end + +function inner_set_nilkey() + local t = { 1, 2 } + local k = nil + t[k] = 3 + return 0 +end + +function inner_get_nankey() + local t = { 1, 2 } + local k = 0.0 / 0.0 + return t[k] +end + +function inner_set_nankey() + local t = { 1, 2 } + local k = 0.0 / 0.0 + t[k] = 3 + return 0 +end + +function inner_const_arr_overwrite() + const_arr[1] = 99 + return 0 +end + +function inner_const_arr_append() + const_arr[3] = 30 + return 0 +end + +function inner_const_rec_update() + const_rec.x = 2 + return 0 +end + +function inner_const_rec_insert() + const_rec.y = 2 + return 0 +end +)", + cfg); + + CompileString(s, R"( +function outer_get_nontable(x) local v = inner_get_nontable(x) return v + 1 end +function outer_set_nontable(x) local v = inner_set_nontable(x) return v + 1 end +function outer_get_nilkey() local v = inner_get_nilkey() return v + 1 end +function outer_set_nilkey() local v = inner_set_nilkey() return v + 1 end +function outer_get_nankey() local v = inner_get_nankey() return v + 1 end +function outer_set_nankey() local v = inner_set_nankey() return v + 1 end +function outer_const_arr_overwrite() local v = inner_const_arr_overwrite() return v + 1 end +function outer_const_arr_append() local v = inner_const_arr_append() return v + 1 end +function outer_const_rec_update() local v = inner_const_rec_update() return v + 1 end +function outer_const_rec_insert() local v = inner_const_rec_insert() return v + 1 end +)", + cfg); + + struct ErrorCase { + const char *outer_fn; + const char *inner_fn; + const char *expected_msg; + int expected_interp_line; + bool pass_int_arg; + }; + const ErrorCase cases[] = { + {"outer_get_nontable", "inner_get_nontable", "attempt to index a non-table value", 6, true}, + {"outer_set_nontable", "inner_set_nontable", "attempt to index a non-table value", 10, true}, + {"outer_get_nilkey", "inner_get_nilkey", "table index is nil", 17, false}, + {"outer_set_nilkey", "inner_set_nilkey", "table index is nil", 23, false}, + {"outer_get_nankey", "inner_get_nankey", "table index is NaN", 30, false}, + {"outer_set_nankey", "inner_set_nankey", "table index is NaN", 36, false}, + {"outer_const_arr_overwrite", "inner_const_arr_overwrite", "attempt to modify a const table", 41, false}, + {"outer_const_arr_append", "inner_const_arr_append", "attempt to modify a const table", 46, false}, + {"outer_const_rec_update", "inner_const_rec_update", "attempt to modify a const table", 51, false}, + {"outer_const_rec_insert", "inner_const_rec_insert", "attempt to modify a const table", 56, false}, + }; + + for (const auto &c: cases) { + SCOPED_TRACE(c.outer_fn); + int64_t ret = 0; + try { + if (c.pass_int_arg) { + Call(s, backend, c.outer_fn, ret, int64_t{42}); + } else { + Call(s, backend, c.outer_fn, ret); + } + FAIL() << "Expected exception for " << c.outer_fn; + } catch (const FakeluaException &e) { + EXPECT_NE(e.Msg().find(c.expected_msg), std::string::npos) << "msg=" << e.Msg(); + EXPECT_TRUE(e.HasLoc()) << e.what(); + if (backend == JIT_INTERP) { + const std::string line_suffix = ":" + std::to_string(c.expected_interp_line); + EXPECT_NE(e.Loc().find(line_suffix), std::string::npos) << "loc=" << e.Loc(); + } + EXPECT_NE(e.LuaStack().find(c.inner_fn), std::string::npos) << "stack=\n" << e.LuaStack(); + EXPECT_NE(e.LuaStack().find(c.outer_fn), std::string::npos) << "stack=\n" << e.LuaStack(); + } + } + } +}