Skip to content

pp_split: assign to temp AV in @ary = split(...) optimisation #18090

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 34 additions & 1 deletion pp.c
Original file line number Diff line number Diff line change
Expand Up @@ -5995,12 +5995,14 @@ PP(pp_split)
I32 trailing_empty = 0;
const char *orig;
const IV origlimit = limit;
AV *tmp4ary;
I32 realarray = 0;
I32 base;
const U8 gimme = GIMME_V;
bool gimme_scalar;
I32 oldsave = PL_savestack_ix;
U32 make_mortal = SVs_TEMP;
bool switchstack = 0;
bool multiline = 0;
MAGIC *mg = NULL;

Expand Down Expand Up @@ -6052,8 +6054,14 @@ PP(pp_split)
AvARRAY(ary)[i] = &PL_sv_undef; /* don't free mere refs */
}
/* temporarily switch stacks */
SAVESWITCHSTACK(PL_curstack, ary);
make_mortal = 0;
switchstack = 1;
/* tmp4ary is used as a placeholder, in case ary is modified */
/* during the split, which could otherwise result in segfault */
/* or panic. */
tmp4ary = newAV();
av_extend(tmp4ary, 0);
SAVESWITCHSTACK(PL_curstack, tmp4ary);
}
}

Expand Down Expand Up @@ -6384,6 +6392,31 @@ PP(pp_split)
LEAVE_SCOPE(oldsave); /* may undo an earlier SWITCHSTACK */
SPAGAIN;
if (realarray) {
if (switchstack) {
/* The in-place optimization was triggered. */
/* tmp4ary contains the *SV array resulting from the split. */
/* The *SV arrays of tmp4ary and ary must now be swapped over.*/

SV** tmp1 = AvARRAY(ary);
SV** tmp2 = AvALLOC(ary);
SSize_t tmp3 = AvMAX(ary);
SSize_t tmp4 = AvFILLp(ary);

AvARRAY(ary) = AvARRAY(tmp4ary);
AvARRAY(tmp4ary) = tmp1;

AvALLOC(ary) = AvALLOC(tmp4ary);
AvALLOC(tmp4ary) = tmp2;

AvMAX(ary) = AvMAX(tmp4ary);
AvMAX(tmp4ary) = tmp3;

AvFILLp(ary) = AvFILLp(tmp4ary);
AvFILLp(tmp4ary) = tmp4;

(void)sv_2mortal((SV*)tmp4ary);
}

if (!mg) {
if (SvSMAGICAL(ary)) {
PUTBACK;
Expand Down
9 changes: 8 additions & 1 deletion t/op/split.t
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ BEGIN {
set_up_inc('../lib');
}

plan tests => 176;
plan tests => 178;

$FS = ':';

Expand Down Expand Up @@ -667,3 +667,10 @@ CODE
ok(eq_array(\@result,['a','b']), "Resulting in ('a','b')");
}
}

# check that the (@ary = split) optimisation survives @ary being modified

fresh_perl_is('my @ary; @ary = split(/\w(?{ @ary[1000] = 1 })/, "abc");',
'',{},'(@ary = split ...) survives @ary being Renew()ed');
fresh_perl_is('my @ary; @ary = split(/\w(?{ undef @ary })/, "abc");',
'',{},'(@ary = split ...) survives an (undef @ary)');