Commit 96c8b057

96c8b057fb19Merged

Yukihiro "Matz" Matsumoto <[email protected]> · 5 months ago · 3 files · +2 added · ~1 modified

Description

codegen: GC-root array-concat destination + eval rhs once

[x] + foo() lowered to dst = dup(lhs); for (i < length(foo())) push(dst, get(foo(), i)). Two bugs: the dup'd destination was never SP_GC_ROOT'd, and the rhs was emitted inline in the loop header so a side-effecting/allocating rhs (a method call) re-ran every iteration — and any allocation freed the unrooted destination mid-loop, corrupting its length (non-deterministically 1/2/11/12 instead of 10).

Evaluate the rhs once into a rooted temp and root the destination before the push loop. SP_GC_ROOT is scope-cleanup'd so it pops at the end of each loop iteration (no root leak).

Fixes #1020

Co-Authored-By: Claude Opus 4.7 [email protected]

Details

Commit
96c8b057fb19
Parent
4416079b19ce

spinel_codegen.rbmodifiedView file

@@ -18921,14 +18921,24 @@
1892118921 emit(" { for (mrb_int _i = 0; _i < sp_" + rt_pfx_p + "_length(" + arg + "); _i++) sp_PolyArray_push(" + tmp + ", " + rt_box + "); }")
1892218922 return tmp
1892318923 end
18924+ # Array `lhs + rhs` (same element type). Issue #1020: the dup'd
18925+ # destination must be GC-rooted across the push loop, and the rhs
18926+ # must be evaluated ONCE into a rooted temp — emitting it inline in
18927+ # the loop header re-ran a side-effecting/allocating rhs (e.g.
18928+ # `[x] + foo()`) every iteration, and any allocation freed the
18929+ # unrooted destination mid-loop, corrupting the result length.
18930+ @needs_gc = 1
1892418931 rc = compile_expr_gc_rooted(recv)
18925- arg = compile_arg0(nid)
1892618932 pfx = array_c_prefix(lt)
1892718933 tmp = new_temp
18934+ argt = new_temp
1892818935 itmp = new_temp
18936+ emit(" " + c_type(lt) + argt + " = " + compile_arg0(nid) + ";")
18937+ emit(" SP_GC_ROOT(" + argt + ");")
1892918938 emit(" " + c_type(lt) + tmp + " = sp_" + pfx + "_dup(" + rc + ");")
18930- emit(" for (mrb_int " + itmp + " = 0; " + itmp + " < sp_" + pfx + "_length(" + arg + "); " + itmp + "++)")
18931- emit(" sp_" + pfx + "_push(" + tmp + ", sp_" + pfx + "_get(" + arg + ", " + itmp + "));")
18939+ emit(" SP_GC_ROOT(" + tmp + ");")
18940+ emit(" for (mrb_int " + itmp + " = 0; " + itmp + " < sp_" + pfx + "_length(" + argt + "); " + itmp + "++)")
18941+ emit(" sp_" + pfx + "_push(" + tmp + ", sp_" + pfx + "_get(" + argt + ", " + itmp + "));")
1893218942 return tmp
1893318943 end
1893418944 if lt == "complex"