Commit 3b1f6171

3b1f6171d54eMerged

Yukihiro "Matz" Matsumoto <[email protected]> · 5 months ago · 4 files · ~4 modified

Description

Hoist loop-invariant string length out of while loops

while i < s.length re-ran sp_str_length (an O(n) strlen) every iteration because the C compiler cannot prove the string is unchanged across the allocating calls in the body. Legacy computes the length once before the loop and reuses it.

In emit_while, when the predicate tests s.length/s.size for a string local s that the body never mutates (reassignment or an in-place mutating method, per legacy's body_mutates_var?), emit mrb_int _t = sp_str_length(s) before the loop and substitute the temp for matching s.length reads inside. Hoist state is saved/restored for nested loops.

bm_template: 1.09x -> 1.03x vs legacy, output matches. General win for any string-scanning while loop. make test 845, make bench 57, optcarrot checksum 59662, self-host bootstrap IR+C fixpoint OK.

Co-Authored-By: Claude Opus 4.8 (1M context) [email protected]

Details

Commit
3b1f6171d54e
Parent
8433e129a114

src/codegen_call.cmodifiedView file

@@ -7353,7 +7353,13 @@
73537353 buf_printf(b, "sp_re_scan_poly(sp_re_pat_%d, %s)", re_lit_index(c, argv[0]), r);
73547354 }
73557355 else if (!strcmp(name, "to_sym") || !strcmp(name, "intern")) buf_printf(b, "sp_sym_intern(%s)", r);
7356- else if (!strcmp(name, "length") || !strcmp(name, "size")) buf_printf(b, "sp_str_length(%s)", r);
7356+ else if (!strcmp(name, "length") || !strcmp(name, "size")) {
7357+ if (g_hoist_len_var && g_hoist_len_recv && recv >= 0 && nt_type(nt, recv) &&
7358+ !strcmp(nt_type(nt, recv), "LocalVariableReadNode") && nt_str(nt, recv, "name") &&
7359+ !strcmp(nt_str(nt, recv, "name"), g_hoist_len_recv))
7360+ buf_puts(b, g_hoist_len_var);
7361+ else buf_printf(b, "sp_str_length(%s)", r);
7362+ }
73577363 else if (!strcmp(name, "bytesize")) buf_printf(b, "(mrb_int)sp_str_byte_len(%s)", r);
73587364 else if (!strcmp(name, "upcase")) buf_printf(b, "sp_str_upcase(%s)", r);
73597365 else if (!strcmp(name, "downcase")) buf_printf(b, "sp_str_downcase(%s)", r);