followup to magic/overload fix
[p5sagit/p5-mst-13.2.git] / pp.c
1 /*    pp.c
2  *
3  *    Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
4  *    2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008 by Larry Wall and others
5  *
6  *    You may distribute under the terms of either the GNU General Public
7  *    License or the Artistic License, as specified in the README file.
8  *
9  */
10
11 /*
12  * 'It's a big house this, and very peculiar.  Always a bit more
13  *  to discover, and no knowing what you'll find round a corner.
14  *  And Elves, sir!'                            --Samwise Gamgee
15  *
16  *     [p.225 of _The Lord of the Rings_, II/i: "Many Meetings"]
17  */
18
19 /* This file contains general pp ("push/pop") functions that execute the
20  * opcodes that make up a perl program. A typical pp function expects to
21  * find its arguments on the stack, and usually pushes its results onto
22  * the stack, hence the 'pp' terminology. Each OP structure contains
23  * a pointer to the relevant pp_foo() function.
24  */
25
26 #include "EXTERN.h"
27 #define PERL_IN_PP_C
28 #include "perl.h"
29 #include "keywords.h"
30
31 #include "reentr.h"
32
33 /* XXX I can't imagine anyone who doesn't have this actually _needs_
34    it, since pid_t is an integral type.
35    --AD  2/20/1998
36 */
37 #ifdef NEED_GETPID_PROTO
38 extern Pid_t getpid (void);
39 #endif
40
41 /*
42  * Some BSDs and Cygwin default to POSIX math instead of IEEE.
43  * This switches them over to IEEE.
44  */
45 #if defined(LIBM_LIB_VERSION)
46     _LIB_VERSION_TYPE _LIB_VERSION = _IEEE_;
47 #endif
48
49 /* variations on pp_null */
50
51 PP(pp_stub)
52 {
53     dVAR;
54     dSP;
55     if (GIMME_V == G_SCALAR)
56         XPUSHs(&PL_sv_undef);
57     RETURN;
58 }
59
60 /* Pushy stuff. */
61
62 PP(pp_padav)
63 {
64     dVAR; dSP; dTARGET;
65     I32 gimme;
66     assert(SvTYPE(TARG) == SVt_PVAV);
67     if (PL_op->op_private & OPpLVAL_INTRO)
68         if (!(PL_op->op_private & OPpPAD_STATE))
69             SAVECLEARSV(PAD_SVl(PL_op->op_targ));
70     EXTEND(SP, 1);
71     if (PL_op->op_flags & OPf_REF) {
72         PUSHs(TARG);
73         RETURN;
74     } else if (LVRET) {
75         if (GIMME == G_SCALAR)
76             Perl_croak(aTHX_ "Can't return array to lvalue scalar context");
77         PUSHs(TARG);
78         RETURN;
79     }
80     gimme = GIMME_V;
81     if (gimme == G_ARRAY) {
82         const I32 maxarg = AvFILL(MUTABLE_AV(TARG)) + 1;
83         EXTEND(SP, maxarg);
84         if (SvMAGICAL(TARG)) {
85             U32 i;
86             for (i=0; i < (U32)maxarg; i++) {
87                 SV * const * const svp = av_fetch(MUTABLE_AV(TARG), i, FALSE);
88                 SP[i+1] = (svp) ? *svp : &PL_sv_undef;
89             }
90         }
91         else {
92             Copy(AvARRAY((const AV *)TARG), SP+1, maxarg, SV*);
93         }
94         SP += maxarg;
95     }
96     else if (gimme == G_SCALAR) {
97         SV* const sv = sv_newmortal();
98         const I32 maxarg = AvFILL(MUTABLE_AV(TARG)) + 1;
99         sv_setiv(sv, maxarg);
100         PUSHs(sv);
101     }
102     RETURN;
103 }
104
105 PP(pp_padhv)
106 {
107     dVAR; dSP; dTARGET;
108     I32 gimme;
109
110     assert(SvTYPE(TARG) == SVt_PVHV);
111     XPUSHs(TARG);
112     if (PL_op->op_private & OPpLVAL_INTRO)
113         if (!(PL_op->op_private & OPpPAD_STATE))
114             SAVECLEARSV(PAD_SVl(PL_op->op_targ));
115     if (PL_op->op_flags & OPf_REF)
116         RETURN;
117     else if (LVRET) {
118         if (GIMME == G_SCALAR)
119             Perl_croak(aTHX_ "Can't return hash to lvalue scalar context");
120         RETURN;
121     }
122     gimme = GIMME_V;
123     if (gimme == G_ARRAY) {
124         RETURNOP(do_kv());
125     }
126     else if (gimme == G_SCALAR) {
127         SV* const sv = Perl_hv_scalar(aTHX_ MUTABLE_HV(TARG));
128         SETs(sv);
129     }
130     RETURN;
131 }
132
133 /* Translations. */
134
135 static const char S_no_symref_sv[] =
136     "Can't use string (\"%" SVf32 "\"%s) as %s ref while \"strict refs\" in use";
137
138 PP(pp_rv2gv)
139 {
140     dVAR; dSP; dTOPss;
141
142     if (SvROK(sv)) {
143       wasref:
144         tryAMAGICunDEREF(to_gv);
145
146         sv = SvRV(sv);
147         if (SvTYPE(sv) == SVt_PVIO) {
148             GV * const gv = MUTABLE_GV(sv_newmortal());
149             gv_init(gv, 0, "", 0, 0);
150             GvIOp(gv) = MUTABLE_IO(sv);
151             SvREFCNT_inc_void_NN(sv);
152             sv = MUTABLE_SV(gv);
153         }
154         else if (!isGV_with_GP(sv))
155             DIE(aTHX_ "Not a GLOB reference");
156     }
157     else {
158         if (!isGV_with_GP(sv)) {
159             if (SvGMAGICAL(sv)) {
160                 mg_get(sv);
161                 if (SvROK(sv))
162                     goto wasref;
163             }
164             if (!SvOK(sv) && sv != &PL_sv_undef) {
165                 /* If this is a 'my' scalar and flag is set then vivify
166                  * NI-S 1999/05/07
167                  */
168                 if (SvREADONLY(sv))
169                     Perl_croak(aTHX_ "%s", PL_no_modify);
170                 if (PL_op->op_private & OPpDEREF) {
171                     GV *gv;
172                     if (cUNOP->op_targ) {
173                         STRLEN len;
174                         SV * const namesv = PAD_SV(cUNOP->op_targ);
175                         const char * const name = SvPV(namesv, len);
176                         gv = MUTABLE_GV(newSV(0));
177                         gv_init(gv, CopSTASH(PL_curcop), name, len, 0);
178                     }
179                     else {
180                         const char * const name = CopSTASHPV(PL_curcop);
181                         gv = newGVgen(name);
182                     }
183                     prepare_SV_for_RV(sv);
184                     SvRV_set(sv, MUTABLE_SV(gv));
185                     SvROK_on(sv);
186                     SvSETMAGIC(sv);
187                     goto wasref;
188                 }
189                 if (PL_op->op_flags & OPf_REF ||
190                     PL_op->op_private & HINT_STRICT_REFS)
191                     DIE(aTHX_ PL_no_usym, "a symbol");
192                 if (ckWARN(WARN_UNINITIALIZED))
193                     report_uninit(sv);
194                 RETSETUNDEF;
195             }
196             if ((PL_op->op_flags & OPf_SPECIAL) &&
197                 !(PL_op->op_flags & OPf_MOD))
198             {
199                 SV * const temp = MUTABLE_SV(gv_fetchsv(sv, 0, SVt_PVGV));
200                 if (!temp
201                     && (!is_gv_magical_sv(sv,0)
202                         || !(sv = MUTABLE_SV(gv_fetchsv(sv, GV_ADD,
203                                                         SVt_PVGV))))) {
204                     RETSETUNDEF;
205                 }
206                 sv = temp;
207             }
208             else {
209                 if (PL_op->op_private & HINT_STRICT_REFS)
210                     DIE(aTHX_ S_no_symref_sv, sv, (SvPOK(sv) && SvCUR(sv)>32 ? "..." : ""), "a symbol");
211                 if ((PL_op->op_private & (OPpLVAL_INTRO|OPpDONT_INIT_GV))
212                     == OPpDONT_INIT_GV) {
213                     /* We are the target of a coderef assignment.  Return
214                        the scalar unchanged, and let pp_sasssign deal with
215                        things.  */
216                     RETURN;
217                 }
218                 sv = MUTABLE_SV(gv_fetchsv(sv, GV_ADD, SVt_PVGV));
219             }
220         }
221     }
222     if (PL_op->op_private & OPpLVAL_INTRO)
223         save_gp(MUTABLE_GV(sv), !(PL_op->op_flags & OPf_SPECIAL));
224     SETs(sv);
225     RETURN;
226 }
227
228 /* Helper function for pp_rv2sv and pp_rv2av  */
229 GV *
230 Perl_softref2xv(pTHX_ SV *const sv, const char *const what,
231                 const svtype type, SV ***spp)
232 {
233     dVAR;
234     GV *gv;
235
236     PERL_ARGS_ASSERT_SOFTREF2XV;
237
238     if (PL_op->op_private & HINT_STRICT_REFS) {
239         if (SvOK(sv))
240             Perl_die(aTHX_ S_no_symref_sv, sv, (SvPOK(sv) && SvCUR(sv)>32 ? "..." : ""), what);
241         else
242             Perl_die(aTHX_ PL_no_usym, what);
243     }
244     if (!SvOK(sv)) {
245         if (PL_op->op_flags & OPf_REF)
246             Perl_die(aTHX_ PL_no_usym, what);
247         if (ckWARN(WARN_UNINITIALIZED))
248             report_uninit(sv);
249         if (type != SVt_PV && GIMME_V == G_ARRAY) {
250             (*spp)--;
251             return NULL;
252         }
253         **spp = &PL_sv_undef;
254         return NULL;
255     }
256     if ((PL_op->op_flags & OPf_SPECIAL) &&
257         !(PL_op->op_flags & OPf_MOD))
258         {
259             gv = gv_fetchsv(sv, 0, type);
260             if (!gv
261                 && (!is_gv_magical_sv(sv,0)
262                     || !(gv = gv_fetchsv(sv, GV_ADD, type))))
263                 {
264                     **spp = &PL_sv_undef;
265                     return NULL;
266                 }
267         }
268     else {
269         gv = gv_fetchsv(sv, GV_ADD, type);
270     }
271     return gv;
272 }
273
274 PP(pp_rv2sv)
275 {
276     dVAR; dSP; dTOPss;
277     GV *gv = NULL;
278
279     if (SvROK(sv)) {
280       wasref:
281         tryAMAGICunDEREF(to_sv);
282
283         sv = SvRV(sv);
284         switch (SvTYPE(sv)) {
285         case SVt_PVAV:
286         case SVt_PVHV:
287         case SVt_PVCV:
288         case SVt_PVFM:
289         case SVt_PVIO:
290             DIE(aTHX_ "Not a SCALAR reference");
291         default: NOOP;
292         }
293     }
294     else {
295         gv = MUTABLE_GV(sv);
296
297         if (!isGV_with_GP(gv)) {
298             if (SvGMAGICAL(sv)) {
299                 mg_get(sv);
300                 if (SvROK(sv))
301                     goto wasref;
302             }
303             gv = Perl_softref2xv(aTHX_ sv, "a SCALAR", SVt_PV, &sp);
304             if (!gv)
305                 RETURN;
306         }
307         sv = GvSVn(gv);
308     }
309     if (PL_op->op_flags & OPf_MOD) {
310         if (PL_op->op_private & OPpLVAL_INTRO) {
311             if (cUNOP->op_first->op_type == OP_NULL)
312                 sv = save_scalar(MUTABLE_GV(TOPs));
313             else if (gv)
314                 sv = save_scalar(gv);
315             else
316                 Perl_croak(aTHX_ "%s", PL_no_localize_ref);
317         }
318         else if (PL_op->op_private & OPpDEREF)
319             vivify_ref(sv, PL_op->op_private & OPpDEREF);
320     }
321     SETs(sv);
322     RETURN;
323 }
324
325 PP(pp_av2arylen)
326 {
327     dVAR; dSP;
328     AV * const av = MUTABLE_AV(TOPs);
329     const I32 lvalue = PL_op->op_flags & OPf_MOD || LVRET;
330     if (lvalue) {
331         SV ** const sv = Perl_av_arylen_p(aTHX_ MUTABLE_AV(av));
332         if (!*sv) {
333             *sv = newSV_type(SVt_PVMG);
334             sv_magic(*sv, MUTABLE_SV(av), PERL_MAGIC_arylen, NULL, 0);
335         }
336         SETs(*sv);
337     } else {
338         SETs(sv_2mortal(newSViv(
339             AvFILL(MUTABLE_AV(av)) + CopARYBASE_get(PL_curcop)
340         )));
341     }
342     RETURN;
343 }
344
345 PP(pp_pos)
346 {
347     dVAR; dSP; dTARGET; dPOPss;
348
349     if (PL_op->op_flags & OPf_MOD || LVRET) {
350         if (SvTYPE(TARG) < SVt_PVLV) {
351             sv_upgrade(TARG, SVt_PVLV);
352             sv_magic(TARG, NULL, PERL_MAGIC_pos, NULL, 0);
353         }
354
355         LvTYPE(TARG) = '.';
356         if (LvTARG(TARG) != sv) {
357             SvREFCNT_dec(LvTARG(TARG));
358             LvTARG(TARG) = SvREFCNT_inc_simple(sv);
359         }
360         PUSHs(TARG);    /* no SvSETMAGIC */
361         RETURN;
362     }
363     else {
364         if (SvTYPE(sv) >= SVt_PVMG && SvMAGIC(sv)) {
365             const MAGIC * const mg = mg_find(sv, PERL_MAGIC_regex_global);
366             if (mg && mg->mg_len >= 0) {
367                 I32 i = mg->mg_len;
368                 if (DO_UTF8(sv))
369                     sv_pos_b2u(sv, &i);
370                 PUSHi(i + CopARYBASE_get(PL_curcop));
371                 RETURN;
372             }
373         }
374         RETPUSHUNDEF;
375     }
376 }
377
378 PP(pp_rv2cv)
379 {
380     dVAR; dSP;
381     GV *gv;
382     HV *stash_unused;
383     const I32 flags = (PL_op->op_flags & OPf_SPECIAL)
384         ? 0
385         : ((PL_op->op_private & (OPpLVAL_INTRO|OPpMAY_RETURN_CONSTANT)) == OPpMAY_RETURN_CONSTANT)
386             ? GV_ADD|GV_NOEXPAND
387             : GV_ADD;
388     /* We usually try to add a non-existent subroutine in case of AUTOLOAD. */
389     /* (But not in defined().) */
390
391     CV *cv = sv_2cv(TOPs, &stash_unused, &gv, flags);
392     if (cv) {
393         if (CvCLONE(cv))
394             cv = MUTABLE_CV(sv_2mortal(MUTABLE_SV(cv_clone(cv))));
395         if ((PL_op->op_private & OPpLVAL_INTRO)) {
396             if (gv && GvCV(gv) == cv && (gv = gv_autoload4(GvSTASH(gv), GvNAME(gv), GvNAMELEN(gv), FALSE)))
397                 cv = GvCV(gv);
398             if (!CvLVALUE(cv))
399                 DIE(aTHX_ "Can't modify non-lvalue subroutine call");
400         }
401     }
402     else if ((flags == (GV_ADD|GV_NOEXPAND)) && gv && SvROK(gv)) {
403         cv = MUTABLE_CV(gv);
404     }    
405     else
406         cv = MUTABLE_CV(&PL_sv_undef);
407     SETs(MUTABLE_SV(cv));
408     RETURN;
409 }
410
411 PP(pp_prototype)
412 {
413     dVAR; dSP;
414     CV *cv;
415     HV *stash;
416     GV *gv;
417     SV *ret = &PL_sv_undef;
418
419     if (SvPOK(TOPs) && SvCUR(TOPs) >= 7) {
420         const char * s = SvPVX_const(TOPs);
421         if (strnEQ(s, "CORE::", 6)) {
422             const int code = keyword(s + 6, SvCUR(TOPs) - 6, 1);
423             if (code < 0) {     /* Overridable. */
424 #define MAX_ARGS_OP ((sizeof(I32) - 1) * 2)
425                 int i = 0, n = 0, seen_question = 0, defgv = 0;
426                 I32 oa;
427                 char str[ MAX_ARGS_OP * 2 + 2 ]; /* One ';', one '\0' */
428
429                 if (code == -KEY_chop || code == -KEY_chomp
430                         || code == -KEY_exec || code == -KEY_system)
431                     goto set;
432                 if (code == -KEY_mkdir) {
433                     ret = newSVpvs_flags("_;$", SVs_TEMP);
434                     goto set;
435                 }
436                 if (code == -KEY_keys || code == -KEY_values || code == -KEY_each) {
437                     ret = newSVpvs_flags("\\[@%]", SVs_TEMP);
438                     goto set;
439                 }
440                 if (code == -KEY_readpipe) {
441                     s = "CORE::backtick";
442                 }
443                 while (i < MAXO) {      /* The slow way. */
444                     if (strEQ(s + 6, PL_op_name[i])
445                         || strEQ(s + 6, PL_op_desc[i]))
446                     {
447                         goto found;
448                     }
449                     i++;
450                 }
451                 goto nonesuch;          /* Should not happen... */
452               found:
453                 defgv = PL_opargs[i] & OA_DEFGV;
454                 oa = PL_opargs[i] >> OASHIFT;
455                 while (oa) {
456                     if (oa & OA_OPTIONAL && !seen_question && !defgv) {
457                         seen_question = 1;
458                         str[n++] = ';';
459                     }
460                     if ((oa & (OA_OPTIONAL - 1)) >= OA_AVREF
461                         && (oa & (OA_OPTIONAL - 1)) <= OA_SCALARREF
462                         /* But globs are already references (kinda) */
463                         && (oa & (OA_OPTIONAL - 1)) != OA_FILEREF
464                     ) {
465                         str[n++] = '\\';
466                     }
467                     str[n++] = ("?$@@%&*$")[oa & (OA_OPTIONAL - 1)];
468                     oa = oa >> 4;
469                 }
470                 if (defgv && str[n - 1] == '$')
471                     str[n - 1] = '_';
472                 str[n++] = '\0';
473                 ret = newSVpvn_flags(str, n - 1, SVs_TEMP);
474             }
475             else if (code)              /* Non-Overridable */
476                 goto set;
477             else {                      /* None such */
478               nonesuch:
479                 DIE(aTHX_ "Can't find an opnumber for \"%s\"", s+6);
480             }
481         }
482     }
483     cv = sv_2cv(TOPs, &stash, &gv, 0);
484     if (cv && SvPOK(cv))
485         ret = newSVpvn_flags(SvPVX_const(cv), SvCUR(cv), SVs_TEMP);
486   set:
487     SETs(ret);
488     RETURN;
489 }
490
491 PP(pp_anoncode)
492 {
493     dVAR; dSP;
494     CV *cv = MUTABLE_CV(PAD_SV(PL_op->op_targ));
495     if (CvCLONE(cv))
496         cv = MUTABLE_CV(sv_2mortal(MUTABLE_SV(cv_clone(cv))));
497     EXTEND(SP,1);
498     PUSHs(MUTABLE_SV(cv));
499     RETURN;
500 }
501
502 PP(pp_srefgen)
503 {
504     dVAR; dSP;
505     *SP = refto(*SP);
506     RETURN;
507 }
508
509 PP(pp_refgen)
510 {
511     dVAR; dSP; dMARK;
512     if (GIMME != G_ARRAY) {
513         if (++MARK <= SP)
514             *MARK = *SP;
515         else
516             *MARK = &PL_sv_undef;
517         *MARK = refto(*MARK);
518         SP = MARK;
519         RETURN;
520     }
521     EXTEND_MORTAL(SP - MARK);
522     while (++MARK <= SP)
523         *MARK = refto(*MARK);
524     RETURN;
525 }
526
527 STATIC SV*
528 S_refto(pTHX_ SV *sv)
529 {
530     dVAR;
531     SV* rv;
532
533     PERL_ARGS_ASSERT_REFTO;
534
535     if (SvTYPE(sv) == SVt_PVLV && LvTYPE(sv) == 'y') {
536         if (LvTARGLEN(sv))
537             vivify_defelem(sv);
538         if (!(sv = LvTARG(sv)))
539             sv = &PL_sv_undef;
540         else
541             SvREFCNT_inc_void_NN(sv);
542     }
543     else if (SvTYPE(sv) == SVt_PVAV) {
544         if (!AvREAL((const AV *)sv) && AvREIFY((const AV *)sv))
545             av_reify(MUTABLE_AV(sv));
546         SvTEMP_off(sv);
547         SvREFCNT_inc_void_NN(sv);
548     }
549     else if (SvPADTMP(sv) && !IS_PADGV(sv))
550         sv = newSVsv(sv);
551     else {
552         SvTEMP_off(sv);
553         SvREFCNT_inc_void_NN(sv);
554     }
555     rv = sv_newmortal();
556     sv_upgrade(rv, SVt_IV);
557     SvRV_set(rv, sv);
558     SvROK_on(rv);
559     return rv;
560 }
561
562 PP(pp_ref)
563 {
564     dVAR; dSP; dTARGET;
565     const char *pv;
566     SV * const sv = POPs;
567
568     if (sv)
569         SvGETMAGIC(sv);
570
571     if (!sv || !SvROK(sv))
572         RETPUSHNO;
573
574     pv = sv_reftype(SvRV(sv),TRUE);
575     PUSHp(pv, strlen(pv));
576     RETURN;
577 }
578
579 PP(pp_bless)
580 {
581     dVAR; dSP;
582     HV *stash;
583
584     if (MAXARG == 1)
585         stash = CopSTASH(PL_curcop);
586     else {
587         SV * const ssv = POPs;
588         STRLEN len;
589         const char *ptr;
590
591         if (ssv && !SvGMAGICAL(ssv) && !SvAMAGIC(ssv) && SvROK(ssv))
592             Perl_croak(aTHX_ "Attempt to bless into a reference");
593         ptr = SvPV_const(ssv,len);
594         if (len == 0)
595             Perl_ck_warner(aTHX_ packWARN(WARN_MISC),
596                            "Explicit blessing to '' (assuming package main)");
597         stash = gv_stashpvn(ptr, len, GV_ADD);
598     }
599
600     (void)sv_bless(TOPs, stash);
601     RETURN;
602 }
603
604 PP(pp_gelem)
605 {
606     dVAR; dSP;
607
608     SV *sv = POPs;
609     const char * const elem = SvPV_nolen_const(sv);
610     GV * const gv = MUTABLE_GV(POPs);
611     SV * tmpRef = NULL;
612
613     sv = NULL;
614     if (elem) {
615         /* elem will always be NUL terminated.  */
616         const char * const second_letter = elem + 1;
617         switch (*elem) {
618         case 'A':
619             if (strEQ(second_letter, "RRAY"))
620                 tmpRef = MUTABLE_SV(GvAV(gv));
621             break;
622         case 'C':
623             if (strEQ(second_letter, "ODE"))
624                 tmpRef = MUTABLE_SV(GvCVu(gv));
625             break;
626         case 'F':
627             if (strEQ(second_letter, "ILEHANDLE")) {
628                 /* finally deprecated in 5.8.0 */
629                 deprecate("*glob{FILEHANDLE}");
630                 tmpRef = MUTABLE_SV(GvIOp(gv));
631             }
632             else
633                 if (strEQ(second_letter, "ORMAT"))
634                     tmpRef = MUTABLE_SV(GvFORM(gv));
635             break;
636         case 'G':
637             if (strEQ(second_letter, "LOB"))
638                 tmpRef = MUTABLE_SV(gv);
639             break;
640         case 'H':
641             if (strEQ(second_letter, "ASH"))
642                 tmpRef = MUTABLE_SV(GvHV(gv));
643             break;
644         case 'I':
645             if (*second_letter == 'O' && !elem[2])
646                 tmpRef = MUTABLE_SV(GvIOp(gv));
647             break;
648         case 'N':
649             if (strEQ(second_letter, "AME"))
650                 sv = newSVhek(GvNAME_HEK(gv));
651             break;
652         case 'P':
653             if (strEQ(second_letter, "ACKAGE")) {
654                 const HV * const stash = GvSTASH(gv);
655                 const HEK * const hek = stash ? HvNAME_HEK(stash) : NULL;
656                 sv = hek ? newSVhek(hek) : newSVpvs("__ANON__");
657             }
658             break;
659         case 'S':
660             if (strEQ(second_letter, "CALAR"))
661                 tmpRef = GvSVn(gv);
662             break;
663         }
664     }
665     if (tmpRef)
666         sv = newRV(tmpRef);
667     if (sv)
668         sv_2mortal(sv);
669     else
670         sv = &PL_sv_undef;
671     XPUSHs(sv);
672     RETURN;
673 }
674
675 /* Pattern matching */
676
677 PP(pp_study)
678 {
679     dVAR; dSP; dPOPss;
680     register unsigned char *s;
681     register I32 pos;
682     register I32 ch;
683     register I32 *sfirst;
684     register I32 *snext;
685     STRLEN len;
686
687     if (sv == PL_lastscream) {
688         if (SvSCREAM(sv))
689             RETPUSHYES;
690     }
691     s = (unsigned char*)(SvPV(sv, len));
692     pos = len;
693     if (pos <= 0 || !SvPOK(sv) || SvUTF8(sv)) {
694         /* No point in studying a zero length string, and not safe to study
695            anything that doesn't appear to be a simple scalar (and hence might
696            change between now and when the regexp engine runs without our set
697            magic ever running) such as a reference to an object with overloaded
698            stringification.  */
699         RETPUSHNO;
700     }
701
702     if (PL_lastscream) {
703         SvSCREAM_off(PL_lastscream);
704         SvREFCNT_dec(PL_lastscream);
705     }
706     PL_lastscream = SvREFCNT_inc_simple(sv);
707
708     s = (unsigned char*)(SvPV(sv, len));
709     pos = len;
710     if (pos <= 0)
711         RETPUSHNO;
712     if (pos > PL_maxscream) {
713         if (PL_maxscream < 0) {
714             PL_maxscream = pos + 80;
715             Newx(PL_screamfirst, 256, I32);
716             Newx(PL_screamnext, PL_maxscream, I32);
717         }
718         else {
719             PL_maxscream = pos + pos / 4;
720             Renew(PL_screamnext, PL_maxscream, I32);
721         }
722     }
723
724     sfirst = PL_screamfirst;
725     snext = PL_screamnext;
726
727     if (!sfirst || !snext)
728         DIE(aTHX_ "do_study: out of memory");
729
730     for (ch = 256; ch; --ch)
731         *sfirst++ = -1;
732     sfirst -= 256;
733
734     while (--pos >= 0) {
735         register const I32 ch = s[pos];
736         if (sfirst[ch] >= 0)
737             snext[pos] = sfirst[ch] - pos;
738         else
739             snext[pos] = -pos;
740         sfirst[ch] = pos;
741     }
742
743     SvSCREAM_on(sv);
744     /* piggyback on m//g magic */
745     sv_magic(sv, NULL, PERL_MAGIC_regex_global, NULL, 0);
746     RETPUSHYES;
747 }
748
749 PP(pp_trans)
750 {
751     dVAR; dSP; dTARG;
752     SV *sv;
753
754     if (PL_op->op_flags & OPf_STACKED)
755         sv = POPs;
756     else if (PL_op->op_private & OPpTARGET_MY)
757         sv = GETTARGET;
758     else {
759         sv = DEFSV;
760         EXTEND(SP,1);
761     }
762     TARG = sv_newmortal();
763     PUSHi(do_trans(sv));
764     RETURN;
765 }
766
767 /* Lvalue operators. */
768
769 PP(pp_schop)
770 {
771     dVAR; dSP; dTARGET;
772     do_chop(TARG, TOPs);
773     SETTARG;
774     RETURN;
775 }
776
777 PP(pp_chop)
778 {
779     dVAR; dSP; dMARK; dTARGET; dORIGMARK;
780     while (MARK < SP)
781         do_chop(TARG, *++MARK);
782     SP = ORIGMARK;
783     XPUSHTARG;
784     RETURN;
785 }
786
787 PP(pp_schomp)
788 {
789     dVAR; dSP; dTARGET;
790     SETi(do_chomp(TOPs));
791     RETURN;
792 }
793
794 PP(pp_chomp)
795 {
796     dVAR; dSP; dMARK; dTARGET;
797     register I32 count = 0;
798
799     while (SP > MARK)
800         count += do_chomp(POPs);
801     XPUSHi(count);
802     RETURN;
803 }
804
805 PP(pp_undef)
806 {
807     dVAR; dSP;
808     SV *sv;
809
810     if (!PL_op->op_private) {
811         EXTEND(SP, 1);
812         RETPUSHUNDEF;
813     }
814
815     sv = POPs;
816     if (!sv)
817         RETPUSHUNDEF;
818
819     SV_CHECK_THINKFIRST_COW_DROP(sv);
820
821     switch (SvTYPE(sv)) {
822     case SVt_NULL:
823         break;
824     case SVt_PVAV:
825         av_undef(MUTABLE_AV(sv));
826         break;
827     case SVt_PVHV:
828         hv_undef(MUTABLE_HV(sv));
829         break;
830     case SVt_PVCV:
831         if (cv_const_sv((const CV *)sv))
832             Perl_ck_warner(aTHX_ packWARN(WARN_MISC), "Constant subroutine %s undefined",
833                            CvANON((const CV *)sv) ? "(anonymous)"
834                            : GvENAME(CvGV((const CV *)sv)));
835         /* FALLTHROUGH */
836     case SVt_PVFM:
837         {
838             /* let user-undef'd sub keep its identity */
839             GV* const gv = CvGV((const CV *)sv);
840             cv_undef(MUTABLE_CV(sv));
841             CvGV((const CV *)sv) = gv;
842         }
843         break;
844     case SVt_PVGV:
845         if (SvFAKE(sv)) {
846             SvSetMagicSV(sv, &PL_sv_undef);
847             break;
848         }
849         else if (isGV_with_GP(sv)) {
850             GP *gp;
851             HV *stash;
852
853             /* undef *Foo:: */
854             if((stash = GvHV((const GV *)sv)) && HvNAME_get(stash))
855                 mro_isa_changed_in(stash);
856             /* undef *Pkg::meth_name ... */
857             else if(GvCVu((const GV *)sv) && (stash = GvSTASH((const GV *)sv))
858                     && HvNAME_get(stash))
859                 mro_method_changed_in(stash);
860
861             gp_free(MUTABLE_GV(sv));
862             Newxz(gp, 1, GP);
863             GvGP(sv) = gp_ref(gp);
864             GvSV(sv) = newSV(0);
865             GvLINE(sv) = CopLINE(PL_curcop);
866             GvEGV(sv) = MUTABLE_GV(sv);
867             GvMULTI_on(sv);
868             break;
869         }
870         /* FALL THROUGH */
871     default:
872         if (SvTYPE(sv) >= SVt_PV && SvPVX_const(sv) && SvLEN(sv)) {
873             SvPV_free(sv);
874             SvPV_set(sv, NULL);
875             SvLEN_set(sv, 0);
876         }
877         SvOK_off(sv);
878         SvSETMAGIC(sv);
879     }
880
881     RETPUSHUNDEF;
882 }
883
884 PP(pp_predec)
885 {
886     dVAR; dSP;
887     if (SvTYPE(TOPs) >= SVt_PVAV || isGV_with_GP(TOPs))
888         DIE(aTHX_ "%s", PL_no_modify);
889     if (!SvREADONLY(TOPs) && SvIOK_notUV(TOPs) && !SvNOK(TOPs) && !SvPOK(TOPs)
890         && SvIVX(TOPs) != IV_MIN)
891     {
892         SvIV_set(TOPs, SvIVX(TOPs) - 1);
893         SvFLAGS(TOPs) &= ~(SVp_NOK|SVp_POK);
894     }
895     else
896         sv_dec(TOPs);
897     SvSETMAGIC(TOPs);
898     return NORMAL;
899 }
900
901 PP(pp_postinc)
902 {
903     dVAR; dSP; dTARGET;
904     if (SvTYPE(TOPs) >= SVt_PVAV || isGV_with_GP(TOPs))
905         DIE(aTHX_ "%s", PL_no_modify);
906     sv_setsv(TARG, TOPs);
907     if (!SvREADONLY(TOPs) && SvIOK_notUV(TOPs) && !SvNOK(TOPs) && !SvPOK(TOPs)
908         && SvIVX(TOPs) != IV_MAX)
909     {
910         SvIV_set(TOPs, SvIVX(TOPs) + 1);
911         SvFLAGS(TOPs) &= ~(SVp_NOK|SVp_POK);
912     }
913     else
914         sv_inc_nomg(TOPs);
915     SvSETMAGIC(TOPs);
916     /* special case for undef: see thread at 2003-03/msg00536.html in archive */
917     if (!SvOK(TARG))
918         sv_setiv(TARG, 0);
919     SETs(TARG);
920     return NORMAL;
921 }
922
923 PP(pp_postdec)
924 {
925     dVAR; dSP; dTARGET;
926     if (SvTYPE(TOPs) >= SVt_PVAV || isGV_with_GP(TOPs))
927         DIE(aTHX_ "%s", PL_no_modify);
928     sv_setsv(TARG, TOPs);
929     if (!SvREADONLY(TOPs) && SvIOK_notUV(TOPs) && !SvNOK(TOPs) && !SvPOK(TOPs)
930         && SvIVX(TOPs) != IV_MIN)
931     {
932         SvIV_set(TOPs, SvIVX(TOPs) - 1);
933         SvFLAGS(TOPs) &= ~(SVp_NOK|SVp_POK);
934     }
935     else
936         sv_dec_nomg(TOPs);
937     SvSETMAGIC(TOPs);
938     SETs(TARG);
939     return NORMAL;
940 }
941
942 /* Ordinary operators. */
943
944 PP(pp_pow)
945 {
946     dVAR; dSP; dATARGET; SV *svl, *svr;
947 #ifdef PERL_PRESERVE_IVUV
948     bool is_int = 0;
949 #endif
950     tryAMAGICbin_MG(pow_amg, AMGf_assign|AMGf_numeric);
951     svr = TOPs;
952     svl = TOPm1s;
953 #ifdef PERL_PRESERVE_IVUV
954     /* For integer to integer power, we do the calculation by hand wherever
955        we're sure it is safe; otherwise we call pow() and try to convert to
956        integer afterwards. */
957     {
958         SvIV_please_nomg(svr);
959         if (SvIOK(svr)) {
960             SvIV_please_nomg(svl);
961             if (SvIOK(svl)) {
962                 UV power;
963                 bool baseuok;
964                 UV baseuv;
965
966                 if (SvUOK(svr)) {
967                     power = SvUVX(svr);
968                 } else {
969                     const IV iv = SvIVX(svr);
970                     if (iv >= 0) {
971                         power = iv;
972                     } else {
973                         goto float_it; /* Can't do negative powers this way.  */
974                     }
975                 }
976
977                 baseuok = SvUOK(svl);
978                 if (baseuok) {
979                     baseuv = SvUVX(svl);
980                 } else {
981                     const IV iv = SvIVX(svl);
982                     if (iv >= 0) {
983                         baseuv = iv;
984                         baseuok = TRUE; /* effectively it's a UV now */
985                     } else {
986                         baseuv = -iv; /* abs, baseuok == false records sign */
987                     }
988                 }
989                 /* now we have integer ** positive integer. */
990                 is_int = 1;
991
992                 /* foo & (foo - 1) is zero only for a power of 2.  */
993                 if (!(baseuv & (baseuv - 1))) {
994                     /* We are raising power-of-2 to a positive integer.
995                        The logic here will work for any base (even non-integer
996                        bases) but it can be less accurate than
997                        pow (base,power) or exp (power * log (base)) when the
998                        intermediate values start to spill out of the mantissa.
999                        With powers of 2 we know this can't happen.
1000                        And powers of 2 are the favourite thing for perl
1001                        programmers to notice ** not doing what they mean. */
1002                     NV result = 1.0;
1003                     NV base = baseuok ? baseuv : -(NV)baseuv;
1004
1005                     if (power & 1) {
1006                         result *= base;
1007                     }
1008                     while (power >>= 1) {
1009                         base *= base;
1010                         if (power & 1) {
1011                             result *= base;
1012                         }
1013                     }
1014                     SP--;
1015                     SETn( result );
1016                     SvIV_please_nomg(svr);
1017                     RETURN;
1018                 } else {
1019                     register unsigned int highbit = 8 * sizeof(UV);
1020                     register unsigned int diff = 8 * sizeof(UV);
1021                     while (diff >>= 1) {
1022                         highbit -= diff;
1023                         if (baseuv >> highbit) {
1024                             highbit += diff;
1025                         }
1026                     }
1027                     /* we now have baseuv < 2 ** highbit */
1028                     if (power * highbit <= 8 * sizeof(UV)) {
1029                         /* result will definitely fit in UV, so use UV math
1030                            on same algorithm as above */
1031                         register UV result = 1;
1032                         register UV base = baseuv;
1033                         const bool odd_power = cBOOL(power & 1);
1034                         if (odd_power) {
1035                             result *= base;
1036                         }
1037                         while (power >>= 1) {
1038                             base *= base;
1039                             if (power & 1) {
1040                                 result *= base;
1041                             }
1042                         }
1043                         SP--;
1044                         if (baseuok || !odd_power)
1045                             /* answer is positive */
1046                             SETu( result );
1047                         else if (result <= (UV)IV_MAX)
1048                             /* answer negative, fits in IV */
1049                             SETi( -(IV)result );
1050                         else if (result == (UV)IV_MIN) 
1051                             /* 2's complement assumption: special case IV_MIN */
1052                             SETi( IV_MIN );
1053                         else
1054                             /* answer negative, doesn't fit */
1055                             SETn( -(NV)result );
1056                         RETURN;
1057                     } 
1058                 }
1059             }
1060         }
1061     }
1062   float_it:
1063 #endif    
1064     {
1065         NV right = SvNV_nomg(svr);
1066         NV left  = SvNV_nomg(svl);
1067         (void)POPs;
1068
1069 #if defined(USE_LONG_DOUBLE) && defined(HAS_AIX_POWL_NEG_BASE_BUG)
1070     /*
1071     We are building perl with long double support and are on an AIX OS
1072     afflicted with a powl() function that wrongly returns NaNQ for any
1073     negative base.  This was reported to IBM as PMR #23047-379 on
1074     03/06/2006.  The problem exists in at least the following versions
1075     of AIX and the libm fileset, and no doubt others as well:
1076
1077         AIX 4.3.3-ML10      bos.adt.libm 4.3.3.50
1078         AIX 5.1.0-ML04      bos.adt.libm 5.1.0.29
1079         AIX 5.2.0           bos.adt.libm 5.2.0.85
1080
1081     So, until IBM fixes powl(), we provide the following workaround to
1082     handle the problem ourselves.  Our logic is as follows: for
1083     negative bases (left), we use fmod(right, 2) to check if the
1084     exponent is an odd or even integer:
1085
1086         - if odd,  powl(left, right) == -powl(-left, right)
1087         - if even, powl(left, right) ==  powl(-left, right)
1088
1089     If the exponent is not an integer, the result is rightly NaNQ, so
1090     we just return that (as NV_NAN).
1091     */
1092
1093         if (left < 0.0) {
1094             NV mod2 = Perl_fmod( right, 2.0 );
1095             if (mod2 == 1.0 || mod2 == -1.0) {  /* odd integer */
1096                 SETn( -Perl_pow( -left, right) );
1097             } else if (mod2 == 0.0) {           /* even integer */
1098                 SETn( Perl_pow( -left, right) );
1099             } else {                            /* fractional power */
1100                 SETn( NV_NAN );
1101             }
1102         } else {
1103             SETn( Perl_pow( left, right) );
1104         }
1105 #else
1106         SETn( Perl_pow( left, right) );
1107 #endif  /* HAS_AIX_POWL_NEG_BASE_BUG */
1108
1109 #ifdef PERL_PRESERVE_IVUV
1110         if (is_int)
1111             SvIV_please_nomg(svr);
1112 #endif
1113         RETURN;
1114     }
1115 }
1116
1117 PP(pp_multiply)
1118 {
1119     dVAR; dSP; dATARGET; SV *svl, *svr;
1120     tryAMAGICbin_MG(mult_amg, AMGf_assign|AMGf_numeric);
1121     svr = TOPs;
1122     svl = TOPm1s;
1123 #ifdef PERL_PRESERVE_IVUV
1124     SvIV_please_nomg(svr);
1125     if (SvIOK(svr)) {
1126         /* Unless the left argument is integer in range we are going to have to
1127            use NV maths. Hence only attempt to coerce the right argument if
1128            we know the left is integer.  */
1129         /* Left operand is defined, so is it IV? */
1130         SvIV_please_nomg(svl);
1131         if (SvIOK(svl)) {
1132             bool auvok = SvUOK(svl);
1133             bool buvok = SvUOK(svr);
1134             const UV topmask = (~ (UV)0) << (4 * sizeof (UV));
1135             const UV botmask = ~((~ (UV)0) << (4 * sizeof (UV)));
1136             UV alow;
1137             UV ahigh;
1138             UV blow;
1139             UV bhigh;
1140
1141             if (auvok) {
1142                 alow = SvUVX(svl);
1143             } else {
1144                 const IV aiv = SvIVX(svl);
1145                 if (aiv >= 0) {
1146                     alow = aiv;
1147                     auvok = TRUE; /* effectively it's a UV now */
1148                 } else {
1149                     alow = -aiv; /* abs, auvok == false records sign */
1150                 }
1151             }
1152             if (buvok) {
1153                 blow = SvUVX(svr);
1154             } else {
1155                 const IV biv = SvIVX(svr);
1156                 if (biv >= 0) {
1157                     blow = biv;
1158                     buvok = TRUE; /* effectively it's a UV now */
1159                 } else {
1160                     blow = -biv; /* abs, buvok == false records sign */
1161                 }
1162             }
1163
1164             /* If this does sign extension on unsigned it's time for plan B  */
1165             ahigh = alow >> (4 * sizeof (UV));
1166             alow &= botmask;
1167             bhigh = blow >> (4 * sizeof (UV));
1168             blow &= botmask;
1169             if (ahigh && bhigh) {
1170                 NOOP;
1171                 /* eg 32 bit is at least 0x10000 * 0x10000 == 0x100000000
1172                    which is overflow. Drop to NVs below.  */
1173             } else if (!ahigh && !bhigh) {
1174                 /* eg 32 bit is at most 0xFFFF * 0xFFFF == 0xFFFE0001
1175                    so the unsigned multiply cannot overflow.  */
1176                 const UV product = alow * blow;
1177                 if (auvok == buvok) {
1178                     /* -ve * -ve or +ve * +ve gives a +ve result.  */
1179                     SP--;
1180                     SETu( product );
1181                     RETURN;
1182                 } else if (product <= (UV)IV_MIN) {
1183                     /* 2s complement assumption that (UV)-IV_MIN is correct.  */
1184                     /* -ve result, which could overflow an IV  */
1185                     SP--;
1186                     SETi( -(IV)product );
1187                     RETURN;
1188                 } /* else drop to NVs below. */
1189             } else {
1190                 /* One operand is large, 1 small */
1191                 UV product_middle;
1192                 if (bhigh) {
1193                     /* swap the operands */
1194                     ahigh = bhigh;
1195                     bhigh = blow; /* bhigh now the temp var for the swap */
1196                     blow = alow;
1197                     alow = bhigh;
1198                 }
1199                 /* now, ((ahigh * blow) << half_UV_len) + (alow * blow)
1200                    multiplies can't overflow. shift can, add can, -ve can.  */
1201                 product_middle = ahigh * blow;
1202                 if (!(product_middle & topmask)) {
1203                     /* OK, (ahigh * blow) won't lose bits when we shift it.  */
1204                     UV product_low;
1205                     product_middle <<= (4 * sizeof (UV));
1206                     product_low = alow * blow;
1207
1208                     /* as for pp_add, UV + something mustn't get smaller.
1209                        IIRC ANSI mandates this wrapping *behaviour* for
1210                        unsigned whatever the actual representation*/
1211                     product_low += product_middle;
1212                     if (product_low >= product_middle) {
1213                         /* didn't overflow */
1214                         if (auvok == buvok) {
1215                             /* -ve * -ve or +ve * +ve gives a +ve result.  */
1216                             SP--;
1217                             SETu( product_low );
1218                             RETURN;
1219                         } else if (product_low <= (UV)IV_MIN) {
1220                             /* 2s complement assumption again  */
1221                             /* -ve result, which could overflow an IV  */
1222                             SP--;
1223                             SETi( -(IV)product_low );
1224                             RETURN;
1225                         } /* else drop to NVs below. */
1226                     }
1227                 } /* product_middle too large */
1228             } /* ahigh && bhigh */
1229         } /* SvIOK(svl) */
1230     } /* SvIOK(svr) */
1231 #endif
1232     {
1233       NV right = SvNV_nomg(svr);
1234       NV left  = SvNV_nomg(svl);
1235       (void)POPs;
1236       SETn( left * right );
1237       RETURN;
1238     }
1239 }
1240
1241 PP(pp_divide)
1242 {
1243     dVAR; dSP; dATARGET; SV *svl, *svr;
1244     tryAMAGICbin_MG(div_amg, AMGf_assign|AMGf_numeric);
1245     svr = TOPs;
1246     svl = TOPm1s;
1247     /* Only try to do UV divide first
1248        if ((SLOPPYDIVIDE is true) or
1249            (PERL_PRESERVE_IVUV is true and one or both SV is a UV too large
1250             to preserve))
1251        The assumption is that it is better to use floating point divide
1252        whenever possible, only doing integer divide first if we can't be sure.
1253        If NV_PRESERVES_UV is true then we know at compile time that no UV
1254        can be too large to preserve, so don't need to compile the code to
1255        test the size of UVs.  */
1256
1257 #ifdef SLOPPYDIVIDE
1258 #  define PERL_TRY_UV_DIVIDE
1259     /* ensure that 20./5. == 4. */
1260 #else
1261 #  ifdef PERL_PRESERVE_IVUV
1262 #    ifndef NV_PRESERVES_UV
1263 #      define PERL_TRY_UV_DIVIDE
1264 #    endif
1265 #  endif
1266 #endif
1267
1268 #ifdef PERL_TRY_UV_DIVIDE
1269     SvIV_please_nomg(svr);
1270     if (SvIOK(svr)) {
1271         SvIV_please_nomg(svl);
1272         if (SvIOK(svl)) {
1273             bool left_non_neg = SvUOK(svl);
1274             bool right_non_neg = SvUOK(svr);
1275             UV left;
1276             UV right;
1277
1278             if (right_non_neg) {
1279                 right = SvUVX(svr);
1280             }
1281             else {
1282                 const IV biv = SvIVX(svr);
1283                 if (biv >= 0) {
1284                     right = biv;
1285                     right_non_neg = TRUE; /* effectively it's a UV now */
1286                 }
1287                 else {
1288                     right = -biv;
1289                 }
1290             }
1291             /* historically undef()/0 gives a "Use of uninitialized value"
1292                warning before dieing, hence this test goes here.
1293                If it were immediately before the second SvIV_please, then
1294                DIE() would be invoked before left was even inspected, so
1295                no inpsection would give no warning.  */
1296             if (right == 0)
1297                 DIE(aTHX_ "Illegal division by zero");
1298
1299             if (left_non_neg) {
1300                 left = SvUVX(svl);
1301             }
1302             else {
1303                 const IV aiv = SvIVX(svl);
1304                 if (aiv >= 0) {
1305                     left = aiv;
1306                     left_non_neg = TRUE; /* effectively it's a UV now */
1307                 }
1308                 else {
1309                     left = -aiv;
1310                 }
1311             }
1312
1313             if (left >= right
1314 #ifdef SLOPPYDIVIDE
1315                 /* For sloppy divide we always attempt integer division.  */
1316 #else
1317                 /* Otherwise we only attempt it if either or both operands
1318                    would not be preserved by an NV.  If both fit in NVs
1319                    we fall through to the NV divide code below.  However,
1320                    as left >= right to ensure integer result here, we know that
1321                    we can skip the test on the right operand - right big
1322                    enough not to be preserved can't get here unless left is
1323                    also too big.  */
1324
1325                 && (left > ((UV)1 << NV_PRESERVES_UV_BITS))
1326 #endif
1327                 ) {
1328                 /* Integer division can't overflow, but it can be imprecise.  */
1329                 const UV result = left / right;
1330                 if (result * right == left) {
1331                     SP--; /* result is valid */
1332                     if (left_non_neg == right_non_neg) {
1333                         /* signs identical, result is positive.  */
1334                         SETu( result );
1335                         RETURN;
1336                     }
1337                     /* 2s complement assumption */
1338                     if (result <= (UV)IV_MIN)
1339                         SETi( -(IV)result );
1340                     else {
1341                         /* It's exact but too negative for IV. */
1342                         SETn( -(NV)result );
1343                     }
1344                     RETURN;
1345                 } /* tried integer divide but it was not an integer result */
1346             } /* else (PERL_ABS(result) < 1.0) or (both UVs in range for NV) */
1347         } /* left wasn't SvIOK */
1348     } /* right wasn't SvIOK */
1349 #endif /* PERL_TRY_UV_DIVIDE */
1350     {
1351         NV right = SvNV_nomg(svr);
1352         NV left  = SvNV_nomg(svl);
1353         (void)POPs;(void)POPs;
1354 #if defined(NAN_COMPARE_BROKEN) && defined(Perl_isnan)
1355         if (! Perl_isnan(right) && right == 0.0)
1356 #else
1357         if (right == 0.0)
1358 #endif
1359             DIE(aTHX_ "Illegal division by zero");
1360         PUSHn( left / right );
1361         RETURN;
1362     }
1363 }
1364
1365 PP(pp_modulo)
1366 {
1367     dVAR; dSP; dATARGET;
1368     tryAMAGICbin_MG(modulo_amg, AMGf_assign|AMGf_numeric);
1369     {
1370         UV left  = 0;
1371         UV right = 0;
1372         bool left_neg = FALSE;
1373         bool right_neg = FALSE;
1374         bool use_double = FALSE;
1375         bool dright_valid = FALSE;
1376         NV dright = 0.0;
1377         NV dleft  = 0.0;
1378         SV * const svr = TOPs;
1379         SV * const svl = TOPm1s;
1380         SvIV_please_nomg(svr);
1381         if (SvIOK(svr)) {
1382             right_neg = !SvUOK(svr);
1383             if (!right_neg) {
1384                 right = SvUVX(svr);
1385             } else {
1386                 const IV biv = SvIVX(svr);
1387                 if (biv >= 0) {
1388                     right = biv;
1389                     right_neg = FALSE; /* effectively it's a UV now */
1390                 } else {
1391                     right = -biv;
1392                 }
1393             }
1394         }
1395         else {
1396             dright = SvNV_nomg(svr);
1397             right_neg = dright < 0;
1398             if (right_neg)
1399                 dright = -dright;
1400             if (dright < UV_MAX_P1) {
1401                 right = U_V(dright);
1402                 dright_valid = TRUE; /* In case we need to use double below.  */
1403             } else {
1404                 use_double = TRUE;
1405             }
1406         }
1407
1408         /* At this point use_double is only true if right is out of range for
1409            a UV.  In range NV has been rounded down to nearest UV and
1410            use_double false.  */
1411         SvIV_please_nomg(svl);
1412         if (!use_double && SvIOK(svl)) {
1413             if (SvIOK(svl)) {
1414                 left_neg = !SvUOK(svl);
1415                 if (!left_neg) {
1416                     left = SvUVX(svl);
1417                 } else {
1418                     const IV aiv = SvIVX(svl);
1419                     if (aiv >= 0) {
1420                         left = aiv;
1421                         left_neg = FALSE; /* effectively it's a UV now */
1422                     } else {
1423                         left = -aiv;
1424                     }
1425                 }
1426             }
1427         }
1428         else {
1429             dleft = SvNV_nomg(svl);
1430             left_neg = dleft < 0;
1431             if (left_neg)
1432                 dleft = -dleft;
1433
1434             /* This should be exactly the 5.6 behaviour - if left and right are
1435                both in range for UV then use U_V() rather than floor.  */
1436             if (!use_double) {
1437                 if (dleft < UV_MAX_P1) {
1438                     /* right was in range, so is dleft, so use UVs not double.
1439                      */
1440                     left = U_V(dleft);
1441                 }
1442                 /* left is out of range for UV, right was in range, so promote
1443                    right (back) to double.  */
1444                 else {
1445                     /* The +0.5 is used in 5.6 even though it is not strictly
1446                        consistent with the implicit +0 floor in the U_V()
1447                        inside the #if 1. */
1448                     dleft = Perl_floor(dleft + 0.5);
1449                     use_double = TRUE;
1450                     if (dright_valid)
1451                         dright = Perl_floor(dright + 0.5);
1452                     else
1453                         dright = right;
1454                 }
1455             }
1456         }
1457         sp -= 2;
1458         if (use_double) {
1459             NV dans;
1460
1461             if (!dright)
1462                 DIE(aTHX_ "Illegal modulus zero");
1463
1464             dans = Perl_fmod(dleft, dright);
1465             if ((left_neg != right_neg) && dans)
1466                 dans = dright - dans;
1467             if (right_neg)
1468                 dans = -dans;
1469             sv_setnv(TARG, dans);
1470         }
1471         else {
1472             UV ans;
1473
1474             if (!right)
1475                 DIE(aTHX_ "Illegal modulus zero");
1476
1477             ans = left % right;
1478             if ((left_neg != right_neg) && ans)
1479                 ans = right - ans;
1480             if (right_neg) {
1481                 /* XXX may warn: unary minus operator applied to unsigned type */
1482                 /* could change -foo to be (~foo)+1 instead     */
1483                 if (ans <= ~((UV)IV_MAX)+1)
1484                     sv_setiv(TARG, ~ans+1);
1485                 else
1486                     sv_setnv(TARG, -(NV)ans);
1487             }
1488             else
1489                 sv_setuv(TARG, ans);
1490         }
1491         PUSHTARG;
1492         RETURN;
1493     }
1494 }
1495
1496 PP(pp_repeat)
1497 {
1498     dVAR; dSP; dATARGET;
1499     register IV count;
1500     SV *sv;
1501
1502     if (GIMME == G_ARRAY && PL_op->op_private & OPpREPEAT_DOLIST) {
1503         /* TODO: think of some way of doing list-repeat overloading ??? */
1504         sv = POPs;
1505         SvGETMAGIC(sv);
1506     }
1507     else {
1508         tryAMAGICbin_MG(repeat_amg, AMGf_assign);
1509         sv = POPs;
1510     }
1511
1512     if (SvIOKp(sv)) {
1513          if (SvUOK(sv)) {
1514               const UV uv = SvUV_nomg(sv);
1515               if (uv > IV_MAX)
1516                    count = IV_MAX; /* The best we can do? */
1517               else
1518                    count = uv;
1519          } else {
1520               const IV iv = SvIV_nomg(sv);
1521               if (iv < 0)
1522                    count = 0;
1523               else
1524                    count = iv;
1525          }
1526     }
1527     else if (SvNOKp(sv)) {
1528          const NV nv = SvNV_nomg(sv);
1529          if (nv < 0.0)
1530               count = 0;
1531          else
1532               count = (IV)nv;
1533     }
1534     else
1535          count = SvIV_nomg(sv);
1536
1537     if (GIMME == G_ARRAY && PL_op->op_private & OPpREPEAT_DOLIST) {
1538         dMARK;
1539         static const char oom_list_extend[] = "Out of memory during list extend";
1540         const I32 items = SP - MARK;
1541         const I32 max = items * count;
1542
1543         MEM_WRAP_CHECK_1(max, SV*, oom_list_extend);
1544         /* Did the max computation overflow? */
1545         if (items > 0 && max > 0 && (max < items || max < count))
1546            Perl_croak(aTHX_ oom_list_extend);
1547         MEXTEND(MARK, max);
1548         if (count > 1) {
1549             while (SP > MARK) {
1550 #if 0
1551               /* This code was intended to fix 20010809.028:
1552
1553                  $x = 'abcd';
1554                  for (($x =~ /./g) x 2) {
1555                      print chop; # "abcdabcd" expected as output.
1556                  }
1557
1558                * but that change (#11635) broke this code:
1559
1560                $x = [("foo")x2]; # only one "foo" ended up in the anonlist.
1561
1562                * I can't think of a better fix that doesn't introduce
1563                * an efficiency hit by copying the SVs. The stack isn't
1564                * refcounted, and mortalisation obviously doesn't
1565                * Do The Right Thing when the stack has more than
1566                * one pointer to the same mortal value.
1567                * .robin.
1568                */
1569                 if (*SP) {
1570                     *SP = sv_2mortal(newSVsv(*SP));
1571                     SvREADONLY_on(*SP);
1572                 }
1573 #else
1574                if (*SP)
1575                    SvTEMP_off((*SP));
1576 #endif
1577                 SP--;
1578             }
1579             MARK++;
1580             repeatcpy((char*)(MARK + items), (char*)MARK,
1581                 items * sizeof(const SV *), count - 1);
1582             SP += max;
1583         }
1584         else if (count <= 0)
1585             SP -= items;
1586     }
1587     else {      /* Note: mark already snarfed by pp_list */
1588         SV * const tmpstr = POPs;
1589         STRLEN len;
1590         bool isutf;
1591         static const char oom_string_extend[] =
1592           "Out of memory during string extend";
1593
1594         if (TARG != tmpstr)
1595             sv_setsv_nomg(TARG, tmpstr);
1596         SvPV_force_nomg(TARG, len);
1597         isutf = DO_UTF8(TARG);
1598         if (count != 1) {
1599             if (count < 1)
1600                 SvCUR_set(TARG, 0);
1601             else {
1602                 const STRLEN max = (UV)count * len;
1603                 if (len > MEM_SIZE_MAX / count)
1604                      Perl_croak(aTHX_ oom_string_extend);
1605                 MEM_WRAP_CHECK_1(max, char, oom_string_extend);
1606                 SvGROW(TARG, max + 1);
1607                 repeatcpy(SvPVX(TARG) + len, SvPVX(TARG), len, count - 1);
1608                 SvCUR_set(TARG, SvCUR(TARG) * count);
1609             }
1610             *SvEND(TARG) = '\0';
1611         }
1612         if (isutf)
1613             (void)SvPOK_only_UTF8(TARG);
1614         else
1615             (void)SvPOK_only(TARG);
1616
1617         if (PL_op->op_private & OPpREPEAT_DOLIST) {
1618             /* The parser saw this as a list repeat, and there
1619                are probably several items on the stack. But we're
1620                in scalar context, and there's no pp_list to save us
1621                now. So drop the rest of the items -- robin@kitsite.com
1622              */
1623             dMARK;
1624             SP = MARK;
1625         }
1626         PUSHTARG;
1627     }
1628     RETURN;
1629 }
1630
1631 PP(pp_subtract)
1632 {
1633     dVAR; dSP; dATARGET; bool useleft; SV *svl, *svr;
1634     tryAMAGICbin_MG(subtr_amg, AMGf_assign|AMGf_numeric);
1635     svr = TOPs;
1636     svl = TOPm1s;
1637     useleft = USE_LEFT(svl);
1638 #ifdef PERL_PRESERVE_IVUV
1639     /* See comments in pp_add (in pp_hot.c) about Overflow, and how
1640        "bad things" happen if you rely on signed integers wrapping.  */
1641     SvIV_please_nomg(svr);
1642     if (SvIOK(svr)) {
1643         /* Unless the left argument is integer in range we are going to have to
1644            use NV maths. Hence only attempt to coerce the right argument if
1645            we know the left is integer.  */
1646         register UV auv = 0;
1647         bool auvok = FALSE;
1648         bool a_valid = 0;
1649
1650         if (!useleft) {
1651             auv = 0;
1652             a_valid = auvok = 1;
1653             /* left operand is undef, treat as zero.  */
1654         } else {
1655             /* Left operand is defined, so is it IV? */
1656             SvIV_please_nomg(svl);
1657             if (SvIOK(svl)) {
1658                 if ((auvok = SvUOK(svl)))
1659                     auv = SvUVX(svl);
1660                 else {
1661                     register const IV aiv = SvIVX(svl);
1662                     if (aiv >= 0) {
1663                         auv = aiv;
1664                         auvok = 1;      /* Now acting as a sign flag.  */
1665                     } else { /* 2s complement assumption for IV_MIN */
1666                         auv = (UV)-aiv;
1667                     }
1668                 }
1669                 a_valid = 1;
1670             }
1671         }
1672         if (a_valid) {
1673             bool result_good = 0;
1674             UV result;
1675             register UV buv;
1676             bool buvok = SvUOK(svr);
1677         
1678             if (buvok)
1679                 buv = SvUVX(svr);
1680             else {
1681                 register const IV biv = SvIVX(svr);
1682                 if (biv >= 0) {
1683                     buv = biv;
1684                     buvok = 1;
1685                 } else
1686                     buv = (UV)-biv;
1687             }
1688             /* ?uvok if value is >= 0. basically, flagged as UV if it's +ve,
1689                else "IV" now, independent of how it came in.
1690                if a, b represents positive, A, B negative, a maps to -A etc
1691                a - b =>  (a - b)
1692                A - b => -(a + b)
1693                a - B =>  (a + b)
1694                A - B => -(a - b)
1695                all UV maths. negate result if A negative.
1696                subtract if signs same, add if signs differ. */
1697
1698             if (auvok ^ buvok) {
1699                 /* Signs differ.  */
1700                 result = auv + buv;
1701                 if (result >= auv)
1702                     result_good = 1;
1703             } else {
1704                 /* Signs same */
1705                 if (auv >= buv) {
1706                     result = auv - buv;
1707                     /* Must get smaller */
1708                     if (result <= auv)
1709                         result_good = 1;
1710                 } else {
1711                     result = buv - auv;
1712                     if (result <= buv) {
1713                         /* result really should be -(auv-buv). as its negation
1714                            of true value, need to swap our result flag  */
1715                         auvok = !auvok;
1716                         result_good = 1;
1717                     }
1718                 }
1719             }
1720             if (result_good) {
1721                 SP--;
1722                 if (auvok)
1723                     SETu( result );
1724                 else {
1725                     /* Negate result */
1726                     if (result <= (UV)IV_MIN)
1727                         SETi( -(IV)result );
1728                     else {
1729                         /* result valid, but out of range for IV.  */
1730                         SETn( -(NV)result );
1731                     }
1732                 }
1733                 RETURN;
1734             } /* Overflow, drop through to NVs.  */
1735         }
1736     }
1737 #endif
1738     {
1739         NV value = SvNV_nomg(svr);
1740         (void)POPs;
1741
1742         if (!useleft) {
1743             /* left operand is undef, treat as zero - value */
1744             SETn(-value);
1745             RETURN;
1746         }
1747         SETn( SvNV_nomg(svl) - value );
1748         RETURN;
1749     }
1750 }
1751
1752 PP(pp_left_shift)
1753 {
1754     dVAR; dSP; dATARGET; SV *svl, *svr;
1755     tryAMAGICbin_MG(lshift_amg, AMGf_assign);
1756     svr = POPs;
1757     svl = TOPs;
1758     {
1759       const IV shift = SvIV_nomg(svr);
1760       if (PL_op->op_private & HINT_INTEGER) {
1761         const IV i = SvIV_nomg(svl);
1762         SETi(i << shift);
1763       }
1764       else {
1765         const UV u = SvUV_nomg(svl);
1766         SETu(u << shift);
1767       }
1768       RETURN;
1769     }
1770 }
1771
1772 PP(pp_right_shift)
1773 {
1774     dVAR; dSP; dATARGET; SV *svl, *svr;
1775     tryAMAGICbin_MG(rshift_amg, AMGf_assign);
1776     svr = POPs;
1777     svl = TOPs;
1778     {
1779       const IV shift = SvIV_nomg(svr);
1780       if (PL_op->op_private & HINT_INTEGER) {
1781         const IV i = SvIV_nomg(svl);
1782         SETi(i >> shift);
1783       }
1784       else {
1785         const UV u = SvUV_nomg(svl);
1786         SETu(u >> shift);
1787       }
1788       RETURN;
1789     }
1790 }
1791
1792 PP(pp_lt)
1793 {
1794     dVAR; dSP;
1795     tryAMAGICbin_MG(lt_amg, AMGf_set);
1796 #ifdef PERL_PRESERVE_IVUV
1797     SvIV_please_nomg(TOPs);
1798     if (SvIOK(TOPs)) {
1799         SvIV_please_nomg(TOPm1s);
1800         if (SvIOK(TOPm1s)) {
1801             bool auvok = SvUOK(TOPm1s);
1802             bool buvok = SvUOK(TOPs);
1803         
1804             if (!auvok && !buvok) { /* ## IV < IV ## */
1805                 const IV aiv = SvIVX(TOPm1s);
1806                 const IV biv = SvIVX(TOPs);
1807                 
1808                 SP--;
1809                 SETs(boolSV(aiv < biv));
1810                 RETURN;
1811             }
1812             if (auvok && buvok) { /* ## UV < UV ## */
1813                 const UV auv = SvUVX(TOPm1s);
1814                 const UV buv = SvUVX(TOPs);
1815                 
1816                 SP--;
1817                 SETs(boolSV(auv < buv));
1818                 RETURN;
1819             }
1820             if (auvok) { /* ## UV < IV ## */
1821                 UV auv;
1822                 const IV biv = SvIVX(TOPs);
1823                 SP--;
1824                 if (biv < 0) {
1825                     /* As (a) is a UV, it's >=0, so it cannot be < */
1826                     SETs(&PL_sv_no);
1827                     RETURN;
1828                 }
1829                 auv = SvUVX(TOPs);
1830                 SETs(boolSV(auv < (UV)biv));
1831                 RETURN;
1832             }
1833             { /* ## IV < UV ## */
1834                 const IV aiv = SvIVX(TOPm1s);
1835                 UV buv;
1836                 
1837                 if (aiv < 0) {
1838                     /* As (b) is a UV, it's >=0, so it must be < */
1839                     SP--;
1840                     SETs(&PL_sv_yes);
1841                     RETURN;
1842                 }
1843                 buv = SvUVX(TOPs);
1844                 SP--;
1845                 SETs(boolSV((UV)aiv < buv));
1846                 RETURN;
1847             }
1848         }
1849     }
1850 #endif
1851 #ifndef NV_PRESERVES_UV
1852 #ifdef PERL_PRESERVE_IVUV
1853     else
1854 #endif
1855     if (SvROK(TOPs) && !SvAMAGIC(TOPs) && SvROK(TOPm1s) && !SvAMAGIC(TOPm1s)) {
1856         SP--;
1857         SETs(boolSV(SvRV(TOPs) < SvRV(TOPp1s)));
1858         RETURN;
1859     }
1860 #endif
1861     {
1862 #if defined(NAN_COMPARE_BROKEN) && defined(Perl_isnan)
1863       dPOPTOPnnrl_nomg;
1864       if (Perl_isnan(left) || Perl_isnan(right))
1865           RETSETNO;
1866       SETs(boolSV(left < right));
1867 #else
1868       dPOPnv_nomg;
1869       SETs(boolSV(SvNV_nomg(TOPs) < value));
1870 #endif
1871       RETURN;
1872     }
1873 }
1874
1875 PP(pp_gt)
1876 {
1877     dVAR; dSP;
1878     tryAMAGICbin_MG(gt_amg, AMGf_set);
1879 #ifdef PERL_PRESERVE_IVUV
1880     SvIV_please_nomg(TOPs);
1881     if (SvIOK(TOPs)) {
1882         SvIV_please_nomg(TOPm1s);
1883         if (SvIOK(TOPm1s)) {
1884             bool auvok = SvUOK(TOPm1s);
1885             bool buvok = SvUOK(TOPs);
1886         
1887             if (!auvok && !buvok) { /* ## IV > IV ## */
1888                 const IV aiv = SvIVX(TOPm1s);
1889                 const IV biv = SvIVX(TOPs);
1890
1891                 SP--;
1892                 SETs(boolSV(aiv > biv));
1893                 RETURN;
1894             }
1895             if (auvok && buvok) { /* ## UV > UV ## */
1896                 const UV auv = SvUVX(TOPm1s);
1897                 const UV buv = SvUVX(TOPs);
1898                 
1899                 SP--;
1900                 SETs(boolSV(auv > buv));
1901                 RETURN;
1902             }
1903             if (auvok) { /* ## UV > IV ## */
1904                 UV auv;
1905                 const IV biv = SvIVX(TOPs);
1906
1907                 SP--;
1908                 if (biv < 0) {
1909                     /* As (a) is a UV, it's >=0, so it must be > */
1910                     SETs(&PL_sv_yes);
1911                     RETURN;
1912                 }
1913                 auv = SvUVX(TOPs);
1914                 SETs(boolSV(auv > (UV)biv));
1915                 RETURN;
1916             }
1917             { /* ## IV > UV ## */
1918                 const IV aiv = SvIVX(TOPm1s);
1919                 UV buv;
1920                 
1921                 if (aiv < 0) {
1922                     /* As (b) is a UV, it's >=0, so it cannot be > */
1923                     SP--;
1924                     SETs(&PL_sv_no);
1925                     RETURN;
1926                 }
1927                 buv = SvUVX(TOPs);
1928                 SP--;
1929                 SETs(boolSV((UV)aiv > buv));
1930                 RETURN;
1931             }
1932         }
1933     }
1934 #endif
1935 #ifndef NV_PRESERVES_UV
1936 #ifdef PERL_PRESERVE_IVUV
1937     else
1938 #endif
1939     if (SvROK(TOPs) && !SvAMAGIC(TOPs) && SvROK(TOPm1s) && !SvAMAGIC(TOPm1s)) {
1940         SP--;
1941         SETs(boolSV(SvRV(TOPs) > SvRV(TOPp1s)));
1942         RETURN;
1943     }
1944 #endif
1945     {
1946 #if defined(NAN_COMPARE_BROKEN) && defined(Perl_isnan)
1947       dPOPTOPnnrl_nomg;
1948       if (Perl_isnan(left) || Perl_isnan(right))
1949           RETSETNO;
1950       SETs(boolSV(left > right));
1951 #else
1952       dPOPnv_nomg;
1953       SETs(boolSV(SvNV_nomg(TOPs) > value));
1954 #endif
1955       RETURN;
1956     }
1957 }
1958
1959 PP(pp_le)
1960 {
1961     dVAR; dSP;
1962     tryAMAGICbin_MG(le_amg, AMGf_set);
1963 #ifdef PERL_PRESERVE_IVUV
1964     SvIV_please_nomg(TOPs);
1965     if (SvIOK(TOPs)) {
1966         SvIV_please_nomg(TOPm1s);
1967         if (SvIOK(TOPm1s)) {
1968             bool auvok = SvUOK(TOPm1s);
1969             bool buvok = SvUOK(TOPs);
1970         
1971             if (!auvok && !buvok) { /* ## IV <= IV ## */
1972                 const IV aiv = SvIVX(TOPm1s);
1973                 const IV biv = SvIVX(TOPs);
1974                 
1975                 SP--;
1976                 SETs(boolSV(aiv <= biv));
1977                 RETURN;
1978             }
1979             if (auvok && buvok) { /* ## UV <= UV ## */
1980                 UV auv = SvUVX(TOPm1s);
1981                 UV buv = SvUVX(TOPs);
1982                 
1983                 SP--;
1984                 SETs(boolSV(auv <= buv));
1985                 RETURN;
1986             }
1987             if (auvok) { /* ## UV <= IV ## */
1988                 UV auv;
1989                 const IV biv = SvIVX(TOPs);
1990
1991                 SP--;
1992                 if (biv < 0) {
1993                     /* As (a) is a UV, it's >=0, so a cannot be <= */
1994                     SETs(&PL_sv_no);
1995                     RETURN;
1996                 }
1997                 auv = SvUVX(TOPs);
1998                 SETs(boolSV(auv <= (UV)biv));
1999                 RETURN;
2000             }
2001             { /* ## IV <= UV ## */
2002                 const IV aiv = SvIVX(TOPm1s);
2003                 UV buv;
2004
2005                 if (aiv < 0) {
2006                     /* As (b) is a UV, it's >=0, so a must be <= */
2007                     SP--;
2008                     SETs(&PL_sv_yes);
2009                     RETURN;
2010                 }
2011                 buv = SvUVX(TOPs);
2012                 SP--;
2013                 SETs(boolSV((UV)aiv <= buv));
2014                 RETURN;
2015             }
2016         }
2017     }
2018 #endif
2019 #ifndef NV_PRESERVES_UV
2020 #ifdef PERL_PRESERVE_IVUV
2021     else
2022 #endif
2023     if (SvROK(TOPs) && !SvAMAGIC(TOPs) && SvROK(TOPm1s) && !SvAMAGIC(TOPm1s)) {
2024         SP--;
2025         SETs(boolSV(SvRV(TOPs) <= SvRV(TOPp1s)));
2026         RETURN;
2027     }
2028 #endif
2029     {
2030 #if defined(NAN_COMPARE_BROKEN) && defined(Perl_isnan)
2031       dPOPTOPnnrl_nomg;
2032       if (Perl_isnan(left) || Perl_isnan(right))
2033           RETSETNO;
2034       SETs(boolSV(left <= right));
2035 #else
2036       dPOPnv_nomg;
2037       SETs(boolSV(SvNV_nomg(TOPs) <= value));
2038 #endif
2039       RETURN;
2040     }
2041 }
2042
2043 PP(pp_ge)
2044 {
2045     dVAR; dSP;
2046     tryAMAGICbin_MG(ge_amg,AMGf_set);
2047 #ifdef PERL_PRESERVE_IVUV
2048     SvIV_please_nomg(TOPs);
2049     if (SvIOK(TOPs)) {
2050         SvIV_please_nomg(TOPm1s);
2051         if (SvIOK(TOPm1s)) {
2052             bool auvok = SvUOK(TOPm1s);
2053             bool buvok = SvUOK(TOPs);
2054         
2055             if (!auvok && !buvok) { /* ## IV >= IV ## */
2056                 const IV aiv = SvIVX(TOPm1s);
2057                 const IV biv = SvIVX(TOPs);
2058
2059                 SP--;
2060                 SETs(boolSV(aiv >= biv));
2061                 RETURN;
2062             }
2063             if (auvok && buvok) { /* ## UV >= UV ## */
2064                 const UV auv = SvUVX(TOPm1s);
2065                 const UV buv = SvUVX(TOPs);
2066
2067                 SP--;
2068                 SETs(boolSV(auv >= buv));
2069                 RETURN;
2070             }
2071             if (auvok) { /* ## UV >= IV ## */
2072                 UV auv;
2073                 const IV biv = SvIVX(TOPs);
2074
2075                 SP--;
2076                 if (biv < 0) {
2077                     /* As (a) is a UV, it's >=0, so it must be >= */
2078                     SETs(&PL_sv_yes);
2079                     RETURN;
2080                 }
2081                 auv = SvUVX(TOPs);
2082                 SETs(boolSV(auv >= (UV)biv));
2083                 RETURN;
2084             }
2085             { /* ## IV >= UV ## */
2086                 const IV aiv = SvIVX(TOPm1s);
2087                 UV buv;
2088
2089                 if (aiv < 0) {
2090                     /* As (b) is a UV, it's >=0, so a cannot be >= */
2091                     SP--;
2092                     SETs(&PL_sv_no);
2093                     RETURN;
2094                 }
2095                 buv = SvUVX(TOPs);
2096                 SP--;
2097                 SETs(boolSV((UV)aiv >= buv));
2098                 RETURN;
2099             }
2100         }
2101     }
2102 #endif
2103 #ifndef NV_PRESERVES_UV
2104 #ifdef PERL_PRESERVE_IVUV
2105     else
2106 #endif
2107     if (SvROK(TOPs) && !SvAMAGIC(TOPs) && SvROK(TOPm1s) && !SvAMAGIC(TOPm1s)) {
2108         SP--;
2109         SETs(boolSV(SvRV(TOPs) >= SvRV(TOPp1s)));
2110         RETURN;
2111     }
2112 #endif
2113     {
2114 #if defined(NAN_COMPARE_BROKEN) && defined(Perl_isnan)
2115       dPOPTOPnnrl_nomg;
2116       if (Perl_isnan(left) || Perl_isnan(right))
2117           RETSETNO;
2118       SETs(boolSV(left >= right));
2119 #else
2120       dPOPnv_nomg;
2121       SETs(boolSV(SvNV_nomg(TOPs) >= value));
2122 #endif
2123       RETURN;
2124     }
2125 }
2126
2127 PP(pp_ne)
2128 {
2129     dVAR; dSP;
2130     tryAMAGICbin_MG(ne_amg,AMGf_set);
2131 #ifndef NV_PRESERVES_UV
2132     if (SvROK(TOPs) && !SvAMAGIC(TOPs) && SvROK(TOPm1s) && !SvAMAGIC(TOPm1s)) {
2133         SP--;
2134         SETs(boolSV(SvRV(TOPs) != SvRV(TOPp1s)));
2135         RETURN;
2136     }
2137 #endif
2138 #ifdef PERL_PRESERVE_IVUV
2139     SvIV_please_nomg(TOPs);
2140     if (SvIOK(TOPs)) {
2141         SvIV_please_nomg(TOPm1s);
2142         if (SvIOK(TOPm1s)) {
2143             const bool auvok = SvUOK(TOPm1s);
2144             const bool buvok = SvUOK(TOPs);
2145         
2146             if (auvok == buvok) { /* ## IV == IV or UV == UV ## */
2147                 /* Casting IV to UV before comparison isn't going to matter
2148                    on 2s complement. On 1s complement or sign&magnitude
2149                    (if we have any of them) it could make negative zero
2150                    differ from normal zero. As I understand it. (Need to
2151                    check - is negative zero implementation defined behaviour
2152                    anyway?). NWC  */
2153                 const UV buv = SvUVX(POPs);
2154                 const UV auv = SvUVX(TOPs);
2155
2156                 SETs(boolSV(auv != buv));
2157                 RETURN;
2158             }
2159             {                   /* ## Mixed IV,UV ## */
2160                 IV iv;
2161                 UV uv;
2162                 
2163                 /* != is commutative so swap if needed (save code) */
2164                 if (auvok) {
2165                     /* swap. top of stack (b) is the iv */
2166                     iv = SvIVX(TOPs);
2167                     SP--;
2168                     if (iv < 0) {
2169                         /* As (a) is a UV, it's >0, so it cannot be == */
2170                         SETs(&PL_sv_yes);
2171                         RETURN;
2172                     }
2173                     uv = SvUVX(TOPs);
2174                 } else {
2175                     iv = SvIVX(TOPm1s);
2176                     SP--;
2177                     if (iv < 0) {
2178                         /* As (b) is a UV, it's >0, so it cannot be == */
2179                         SETs(&PL_sv_yes);
2180                         RETURN;
2181                     }
2182                     uv = SvUVX(*(SP+1)); /* Do I want TOPp1s() ? */
2183                 }
2184                 SETs(boolSV((UV)iv != uv));
2185                 RETURN;
2186             }
2187         }
2188     }
2189 #endif
2190     {
2191 #if defined(NAN_COMPARE_BROKEN) && defined(Perl_isnan)
2192       dPOPTOPnnrl_nomg;
2193       if (Perl_isnan(left) || Perl_isnan(right))
2194           RETSETYES;
2195       SETs(boolSV(left != right));
2196 #else
2197       dPOPnv_nomg;
2198       SETs(boolSV(SvNV_nomg(TOPs) != value));
2199 #endif
2200       RETURN;
2201     }
2202 }
2203
2204 PP(pp_ncmp)
2205 {
2206     dVAR; dSP; dTARGET;
2207     tryAMAGICbin_MG(ncmp_amg, 0);
2208 #ifndef NV_PRESERVES_UV
2209     if (SvROK(TOPs) && !SvAMAGIC(TOPs) && SvROK(TOPm1s) && !SvAMAGIC(TOPm1s)) {
2210         const UV right = PTR2UV(SvRV(POPs));
2211         const UV left = PTR2UV(SvRV(TOPs));
2212         SETi((left > right) - (left < right));
2213         RETURN;
2214     }
2215 #endif
2216 #ifdef PERL_PRESERVE_IVUV
2217     /* Fortunately it seems NaN isn't IOK */
2218     SvIV_please_nomg(TOPs);
2219     if (SvIOK(TOPs)) {
2220         SvIV_please_nomg(TOPm1s);
2221         if (SvIOK(TOPm1s)) {
2222             const bool leftuvok = SvUOK(TOPm1s);
2223             const bool rightuvok = SvUOK(TOPs);
2224             I32 value;
2225             if (!leftuvok && !rightuvok) { /* ## IV <=> IV ## */
2226                 const IV leftiv = SvIVX(TOPm1s);
2227                 const IV rightiv = SvIVX(TOPs);
2228                 
2229                 if (leftiv > rightiv)
2230                     value = 1;
2231                 else if (leftiv < rightiv)
2232                     value = -1;
2233                 else
2234                     value = 0;
2235             } else if (leftuvok && rightuvok) { /* ## UV <=> UV ## */
2236                 const UV leftuv = SvUVX(TOPm1s);
2237                 const UV rightuv = SvUVX(TOPs);
2238                 
2239                 if (leftuv > rightuv)
2240                     value = 1;
2241                 else if (leftuv < rightuv)
2242                     value = -1;
2243                 else
2244                     value = 0;
2245             } else if (leftuvok) { /* ## UV <=> IV ## */
2246                 const IV rightiv = SvIVX(TOPs);
2247                 if (rightiv < 0) {
2248                     /* As (a) is a UV, it's >=0, so it cannot be < */
2249                     value = 1;
2250                 } else {
2251                     const UV leftuv = SvUVX(TOPm1s);
2252                     if (leftuv > (UV)rightiv) {
2253                         value = 1;
2254                     } else if (leftuv < (UV)rightiv) {
2255                         value = -1;
2256                     } else {
2257                         value = 0;
2258                     }
2259                 }
2260             } else { /* ## IV <=> UV ## */
2261                 const IV leftiv = SvIVX(TOPm1s);
2262                 if (leftiv < 0) {
2263                     /* As (b) is a UV, it's >=0, so it must be < */
2264                     value = -1;
2265                 } else {
2266                     const UV rightuv = SvUVX(TOPs);
2267                     if ((UV)leftiv > rightuv) {
2268                         value = 1;
2269                     } else if ((UV)leftiv < rightuv) {
2270                         value = -1;
2271                     } else {
2272                         value = 0;
2273                     }
2274                 }
2275             }
2276             SP--;
2277             SETi(value);
2278             RETURN;
2279         }
2280     }
2281 #endif
2282     {
2283       dPOPTOPnnrl_nomg;
2284       I32 value;
2285
2286 #ifdef Perl_isnan
2287       if (Perl_isnan(left) || Perl_isnan(right)) {
2288           SETs(&PL_sv_undef);
2289           RETURN;
2290        }
2291       value = (left > right) - (left < right);
2292 #else
2293       if (left == right)
2294         value = 0;
2295       else if (left < right)
2296         value = -1;
2297       else if (left > right)
2298         value = 1;
2299       else {
2300         SETs(&PL_sv_undef);
2301         RETURN;
2302       }
2303 #endif
2304       SETi(value);
2305       RETURN;
2306     }
2307 }
2308
2309 PP(pp_sle)
2310 {
2311     dVAR; dSP;
2312
2313     int amg_type = sle_amg;
2314     int multiplier = 1;
2315     int rhs = 1;
2316
2317     switch (PL_op->op_type) {
2318     case OP_SLT:
2319         amg_type = slt_amg;
2320         /* cmp < 0 */
2321         rhs = 0;
2322         break;
2323     case OP_SGT:
2324         amg_type = sgt_amg;
2325         /* cmp > 0 */
2326         multiplier = -1;
2327         rhs = 0;
2328         break;
2329     case OP_SGE:
2330         amg_type = sge_amg;
2331         /* cmp >= 0 */
2332         multiplier = -1;
2333         break;
2334     }
2335
2336     tryAMAGICbin_MG(amg_type, AMGf_set);
2337     {
2338       dPOPTOPssrl;
2339       const int cmp = (IN_LOCALE_RUNTIME
2340                  ? sv_cmp_locale(left, right)
2341                  : sv_cmp(left, right));
2342       SETs(boolSV(cmp * multiplier < rhs));
2343       RETURN;
2344     }
2345 }
2346
2347 PP(pp_seq)
2348 {
2349     dVAR; dSP;
2350     tryAMAGICbin_MG(seq_amg, AMGf_set);
2351     {
2352       dPOPTOPssrl;
2353       SETs(boolSV(sv_eq(left, right)));
2354       RETURN;
2355     }
2356 }
2357
2358 PP(pp_sne)
2359 {
2360     dVAR; dSP;
2361     tryAMAGICbin_MG(sne_amg, AMGf_set);
2362     {
2363       dPOPTOPssrl;
2364       SETs(boolSV(!sv_eq(left, right)));
2365       RETURN;
2366     }
2367 }
2368
2369 PP(pp_scmp)
2370 {
2371     dVAR; dSP; dTARGET;
2372     tryAMAGICbin_MG(scmp_amg, 0);
2373     {
2374       dPOPTOPssrl;
2375       const int cmp = (IN_LOCALE_RUNTIME
2376                  ? sv_cmp_locale(left, right)
2377                  : sv_cmp(left, right));
2378       SETi( cmp );
2379       RETURN;
2380     }
2381 }
2382
2383 PP(pp_bit_and)
2384 {
2385     dVAR; dSP; dATARGET;
2386     tryAMAGICbin_MG(band_amg, AMGf_assign);
2387     {
2388       dPOPTOPssrl;
2389       if (SvNIOKp(left) || SvNIOKp(right)) {
2390         if (PL_op->op_private & HINT_INTEGER) {
2391           const IV i = SvIV_nomg(left) & SvIV_nomg(right);
2392           SETi(i);
2393         }
2394         else {
2395           const UV u = SvUV_nomg(left) & SvUV_nomg(right);
2396           SETu(u);
2397         }
2398       }
2399       else {
2400         do_vop(PL_op->op_type, TARG, left, right);
2401         SETTARG;
2402       }
2403       RETURN;
2404     }
2405 }
2406
2407 PP(pp_bit_or)
2408 {
2409     dVAR; dSP; dATARGET;
2410     const int op_type = PL_op->op_type;
2411
2412     tryAMAGICbin_MG((op_type == OP_BIT_OR ? bor_amg : bxor_amg), AMGf_assign);
2413     {
2414       dPOPTOPssrl;
2415       if (SvNIOKp(left) || SvNIOKp(right)) {
2416         if (PL_op->op_private & HINT_INTEGER) {
2417           const IV l = (USE_LEFT(left) ? SvIV_nomg(left) : 0);
2418           const IV r = SvIV_nomg(right);
2419           const IV result = op_type == OP_BIT_OR ? (l | r) : (l ^ r);
2420           SETi(result);
2421         }
2422         else {
2423           const UV l = (USE_LEFT(left) ? SvUV_nomg(left) : 0);
2424           const UV r = SvUV_nomg(right);
2425           const UV result = op_type == OP_BIT_OR ? (l | r) : (l ^ r);
2426           SETu(result);
2427         }
2428       }
2429       else {
2430         do_vop(op_type, TARG, left, right);
2431         SETTARG;
2432       }
2433       RETURN;
2434     }
2435 }
2436
2437 PP(pp_negate)
2438 {
2439     dVAR; dSP; dTARGET;
2440     tryAMAGICun_MG(neg_amg, AMGf_numeric);
2441     {
2442         SV * const sv = TOPs;
2443         const int flags = SvFLAGS(sv);
2444         if ((flags & SVf_IOK) || ((flags & (SVp_IOK | SVp_NOK)) == SVp_IOK)) {
2445             /* It's publicly an integer, or privately an integer-not-float */
2446         oops_its_an_int:
2447             if (SvIsUV(sv)) {
2448                 if (SvIVX(sv) == IV_MIN) {
2449                     /* 2s complement assumption. */
2450                     SETi(SvIVX(sv));    /* special case: -((UV)IV_MAX+1) == IV_MIN */
2451                     RETURN;
2452                 }
2453                 else if (SvUVX(sv) <= IV_MAX) {
2454                     SETi(-SvIVX(sv));
2455                     RETURN;
2456                 }
2457             }
2458             else if (SvIVX(sv) != IV_MIN) {
2459                 SETi(-SvIVX(sv));
2460                 RETURN;
2461             }
2462 #ifdef PERL_PRESERVE_IVUV
2463             else {
2464                 SETu((UV)IV_MIN);
2465                 RETURN;
2466             }
2467 #endif
2468         }
2469         if (SvNIOKp(sv))
2470             SETn(-SvNV_nomg(sv));
2471         else if (SvPOKp(sv)) {
2472             STRLEN len;
2473             const char * const s = SvPV_nomg_const(sv, len);
2474             if (isIDFIRST(*s)) {
2475                 sv_setpvs(TARG, "-");
2476                 sv_catsv(TARG, sv);
2477             }
2478             else if (*s == '+' || *s == '-') {
2479                 sv_setsv_nomg(TARG, sv);
2480                 *SvPV_force_nomg(TARG, len) = *s == '-' ? '+' : '-';
2481             }
2482             else if (DO_UTF8(sv)) {
2483                 SvIV_please_nomg(sv);
2484                 if (SvIOK(sv))
2485                     goto oops_its_an_int;
2486                 if (SvNOK(sv))
2487                     sv_setnv(TARG, -SvNV_nomg(sv));
2488                 else {
2489                     sv_setpvs(TARG, "-");
2490                     sv_catsv(TARG, sv);
2491                 }
2492             }
2493             else {
2494                 SvIV_please_nomg(sv);
2495                 if (SvIOK(sv))
2496                   goto oops_its_an_int;
2497                 sv_setnv(TARG, -SvNV_nomg(sv));
2498             }
2499             SETTARG;
2500         }
2501         else
2502             SETn(-SvNV_nomg(sv));
2503     }
2504     RETURN;
2505 }
2506
2507 PP(pp_not)
2508 {
2509     dVAR; dSP;
2510     tryAMAGICun_MG(not_amg, AMGf_set);
2511     *PL_stack_sp = boolSV(!SvTRUE(*PL_stack_sp));
2512     return NORMAL;
2513 }
2514
2515 PP(pp_complement)
2516 {
2517     dVAR; dSP; dTARGET;
2518     tryAMAGICun_MG(compl_amg, 0);
2519     {
2520       dTOPss;
2521       if (SvNIOKp(sv)) {
2522         if (PL_op->op_private & HINT_INTEGER) {
2523           const IV i = ~SvIV_nomg(sv);
2524           SETi(i);
2525         }
2526         else {
2527           const UV u = ~SvUV_nomg(sv);
2528           SETu(u);
2529         }
2530       }
2531       else {
2532         register U8 *tmps;
2533         register I32 anum;
2534         STRLEN len;
2535
2536         (void)SvPV_nomg_const(sv,len); /* force check for uninit var */
2537         sv_setsv_nomg(TARG, sv);
2538         tmps = (U8*)SvPV_force_nomg(TARG, len);
2539         anum = len;
2540         if (SvUTF8(TARG)) {
2541           /* Calculate exact length, let's not estimate. */
2542           STRLEN targlen = 0;
2543           STRLEN l;
2544           UV nchar = 0;
2545           UV nwide = 0;
2546           U8 * const send = tmps + len;
2547           U8 * const origtmps = tmps;
2548           const UV utf8flags = UTF8_ALLOW_ANYUV;
2549
2550           while (tmps < send) {
2551             const UV c = utf8n_to_uvchr(tmps, send-tmps, &l, utf8flags);
2552             tmps += l;
2553             targlen += UNISKIP(~c);
2554             nchar++;
2555             if (c > 0xff)
2556                 nwide++;
2557           }
2558
2559           /* Now rewind strings and write them. */
2560           tmps = origtmps;
2561
2562           if (nwide) {
2563               U8 *result;
2564               U8 *p;
2565
2566               Newx(result, targlen + 1, U8);
2567               p = result;
2568               while (tmps < send) {
2569                   const UV c = utf8n_to_uvchr(tmps, send-tmps, &l, utf8flags);
2570                   tmps += l;
2571                   p = uvchr_to_utf8_flags(p, ~c, UNICODE_ALLOW_ANY);
2572               }
2573               *p = '\0';
2574               sv_usepvn_flags(TARG, (char*)result, targlen,
2575                               SV_HAS_TRAILING_NUL);
2576               SvUTF8_on(TARG);
2577           }
2578           else {
2579               U8 *result;
2580               U8 *p;
2581
2582               Newx(result, nchar + 1, U8);
2583               p = result;
2584               while (tmps < send) {
2585                   const U8 c = (U8)utf8n_to_uvchr(tmps, send-tmps, &l, utf8flags);
2586                   tmps += l;
2587                   *p++ = ~c;
2588               }
2589               *p = '\0';
2590               sv_usepvn_flags(TARG, (char*)result, nchar, SV_HAS_TRAILING_NUL);
2591               SvUTF8_off(TARG);
2592           }
2593           SETTARG;
2594           RETURN;
2595         }
2596 #ifdef LIBERAL
2597         {
2598             register long *tmpl;
2599             for ( ; anum && (unsigned long)tmps % sizeof(long); anum--, tmps++)
2600                 *tmps = ~*tmps;
2601             tmpl = (long*)tmps;
2602             for ( ; anum >= (I32)sizeof(long); anum -= (I32)sizeof(long), tmpl++)
2603                 *tmpl = ~*tmpl;
2604             tmps = (U8*)tmpl;
2605         }
2606 #endif
2607         for ( ; anum > 0; anum--, tmps++)
2608             *tmps = ~*tmps;
2609         SETTARG;
2610       }
2611       RETURN;
2612     }
2613 }
2614
2615 /* integer versions of some of the above */
2616
2617 PP(pp_i_multiply)
2618 {
2619     dVAR; dSP; dATARGET;
2620     tryAMAGICbin_MG(mult_amg, AMGf_assign);
2621     {
2622       dPOPTOPiirl_nomg;
2623       SETi( left * right );
2624       RETURN;
2625     }
2626 }
2627
2628 PP(pp_i_divide)
2629 {
2630     IV num;
2631     dVAR; dSP; dATARGET;
2632     tryAMAGICbin_MG(div_amg, AMGf_assign);
2633     {
2634       dPOPTOPssrl;
2635       IV value = SvIV_nomg(right);
2636       if (value == 0)
2637           DIE(aTHX_ "Illegal division by zero");
2638       num = SvIV_nomg(left);
2639
2640       /* avoid FPE_INTOVF on some platforms when num is IV_MIN */
2641       if (value == -1)
2642           value = - num;
2643       else
2644           value = num / value;
2645       SETi(value);
2646       RETURN;
2647     }
2648 }
2649
2650 #if defined(__GLIBC__) && IVSIZE == 8
2651 STATIC
2652 PP(pp_i_modulo_0)
2653 #else
2654 PP(pp_i_modulo)
2655 #endif
2656 {
2657      /* This is the vanilla old i_modulo. */
2658      dVAR; dSP; dATARGET;
2659      tryAMAGICbin_MG(modulo_amg, AMGf_assign);
2660      {
2661           dPOPTOPiirl_nomg;
2662           if (!right)
2663                DIE(aTHX_ "Illegal modulus zero");
2664           /* avoid FPE_INTOVF on some platforms when left is IV_MIN */
2665           if (right == -1)
2666               SETi( 0 );
2667           else
2668               SETi( left % right );
2669           RETURN;
2670      }
2671 }
2672
2673 #if defined(__GLIBC__) && IVSIZE == 8
2674 STATIC
2675 PP(pp_i_modulo_1)
2676
2677 {
2678      /* This is the i_modulo with the workaround for the _moddi3 bug
2679       * in (at least) glibc 2.2.5 (the PERL_ABS() the workaround).
2680       * See below for pp_i_modulo. */
2681      dVAR; dSP; dATARGET;
2682      tryAMAGICbin_MG(modulo_amg, AMGf_assign);
2683      {
2684           dPOPTOPiirl_nomg;
2685           if (!right)
2686                DIE(aTHX_ "Illegal modulus zero");
2687           /* avoid FPE_INTOVF on some platforms when left is IV_MIN */
2688           if (right == -1)
2689               SETi( 0 );
2690           else
2691               SETi( left % PERL_ABS(right) );
2692           RETURN;
2693      }
2694 }
2695
2696 PP(pp_i_modulo)
2697 {
2698      dVAR; dSP; dATARGET;
2699      tryAMAGICbin_MG(modulo_amg, AMGf_assign);
2700      {
2701           dPOPTOPiirl_nomg;
2702           if (!right)
2703                DIE(aTHX_ "Illegal modulus zero");
2704           /* The assumption is to use hereafter the old vanilla version... */
2705           PL_op->op_ppaddr =
2706                PL_ppaddr[OP_I_MODULO] =
2707                    Perl_pp_i_modulo_0;
2708           /* .. but if we have glibc, we might have a buggy _moddi3
2709            * (at least glicb 2.2.5 is known to have this bug), in other
2710            * words our integer modulus with negative quad as the second
2711            * argument might be broken.  Test for this and re-patch the
2712            * opcode dispatch table if that is the case, remembering to
2713            * also apply the workaround so that this first round works
2714            * right, too.  See [perl #9402] for more information. */
2715           {
2716                IV l =   3;
2717                IV r = -10;
2718                /* Cannot do this check with inlined IV constants since
2719                 * that seems to work correctly even with the buggy glibc. */
2720                if (l % r == -3) {
2721                     /* Yikes, we have the bug.
2722                      * Patch in the workaround version. */
2723                     PL_op->op_ppaddr =
2724                          PL_ppaddr[OP_I_MODULO] =
2725                              &Perl_pp_i_modulo_1;
2726                     /* Make certain we work right this time, too. */
2727                     right = PERL_ABS(right);
2728                }
2729           }
2730           /* avoid FPE_INTOVF on some platforms when left is IV_MIN */
2731           if (right == -1)
2732               SETi( 0 );
2733           else
2734               SETi( left % right );
2735           RETURN;
2736      }
2737 }
2738 #endif
2739
2740 PP(pp_i_add)
2741 {
2742     dVAR; dSP; dATARGET;
2743     tryAMAGICbin_MG(add_amg, AMGf_assign);
2744     {
2745       dPOPTOPiirl_ul_nomg;
2746       SETi( left + right );
2747       RETURN;
2748     }
2749 }
2750
2751 PP(pp_i_subtract)
2752 {
2753     dVAR; dSP; dATARGET;
2754     tryAMAGICbin_MG(subtr_amg, AMGf_assign);
2755     {
2756       dPOPTOPiirl_ul_nomg;
2757       SETi( left - right );
2758       RETURN;
2759     }
2760 }
2761
2762 PP(pp_i_lt)
2763 {
2764     dVAR; dSP;
2765     tryAMAGICbin_MG(lt_amg, AMGf_set);
2766     {
2767       dPOPTOPiirl_nomg;
2768       SETs(boolSV(left < right));
2769       RETURN;
2770     }
2771 }
2772
2773 PP(pp_i_gt)
2774 {
2775     dVAR; dSP;
2776     tryAMAGICbin_MG(gt_amg, AMGf_set);
2777     {
2778       dPOPTOPiirl_nomg;
2779       SETs(boolSV(left > right));
2780       RETURN;
2781     }
2782 }
2783
2784 PP(pp_i_le)
2785 {
2786     dVAR; dSP;
2787     tryAMAGICbin_MG(le_amg, AMGf_set);
2788     {
2789       dPOPTOPiirl_nomg;
2790       SETs(boolSV(left <= right));
2791       RETURN;
2792     }
2793 }
2794
2795 PP(pp_i_ge)
2796 {
2797     dVAR; dSP;
2798     tryAMAGICbin_MG(ge_amg, AMGf_set);
2799     {
2800       dPOPTOPiirl_nomg;
2801       SETs(boolSV(left >= right));
2802       RETURN;
2803     }
2804 }
2805
2806 PP(pp_i_eq)
2807 {
2808     dVAR; dSP;
2809     tryAMAGICbin_MG(eq_amg, AMGf_set);
2810     {
2811       dPOPTOPiirl_nomg;
2812       SETs(boolSV(left == right));
2813       RETURN;
2814     }
2815 }
2816
2817 PP(pp_i_ne)
2818 {
2819     dVAR; dSP;
2820     tryAMAGICbin_MG(ne_amg, AMGf_set);
2821     {
2822       dPOPTOPiirl_nomg;
2823       SETs(boolSV(left != right));
2824       RETURN;
2825     }
2826 }
2827
2828 PP(pp_i_ncmp)
2829 {
2830     dVAR; dSP; dTARGET;
2831     tryAMAGICbin_MG(ncmp_amg, 0);
2832     {
2833       dPOPTOPiirl_nomg;
2834       I32 value;
2835
2836       if (left > right)
2837         value = 1;
2838       else if (left < right)
2839         value = -1;
2840       else
2841         value = 0;
2842       SETi(value);
2843       RETURN;
2844     }
2845 }
2846
2847 PP(pp_i_negate)
2848 {
2849     dVAR; dSP; dTARGET;
2850     tryAMAGICun_MG(neg_amg, 0);
2851     {
2852         SV * const sv = TOPs;
2853         IV const i = SvIV_nomg(sv);
2854         SETi(-i);
2855         RETURN;
2856     }
2857 }
2858
2859 /* High falutin' math. */
2860
2861 PP(pp_atan2)
2862 {
2863     dVAR; dSP; dTARGET;
2864     tryAMAGICbin_MG(atan2_amg, 0);
2865     {
2866       dPOPTOPnnrl_nomg;
2867       SETn(Perl_atan2(left, right));
2868       RETURN;
2869     }
2870 }
2871
2872 PP(pp_sin)
2873 {
2874     dVAR; dSP; dTARGET;
2875     int amg_type = sin_amg;
2876     const char *neg_report = NULL;
2877     NV (*func)(NV) = Perl_sin;
2878     const int op_type = PL_op->op_type;
2879
2880     switch (op_type) {
2881     case OP_COS:
2882         amg_type = cos_amg;
2883         func = Perl_cos;
2884         break;
2885     case OP_EXP:
2886         amg_type = exp_amg;
2887         func = Perl_exp;
2888         break;
2889     case OP_LOG:
2890         amg_type = log_amg;
2891         func = Perl_log;
2892         neg_report = "log";
2893         break;
2894     case OP_SQRT:
2895         amg_type = sqrt_amg;
2896         func = Perl_sqrt;
2897         neg_report = "sqrt";
2898         break;
2899     }
2900
2901
2902     tryAMAGICun_MG(amg_type, 0);
2903     {
2904       SV * const arg = POPs;
2905       const NV value = SvNV_nomg(arg);
2906       if (neg_report) {
2907           if (op_type == OP_LOG ? (value <= 0.0) : (value < 0.0)) {
2908               SET_NUMERIC_STANDARD();
2909               DIE(aTHX_ "Can't take %s of %"NVgf, neg_report, value);
2910           }
2911       }
2912       XPUSHn(func(value));
2913       RETURN;
2914     }
2915 }
2916
2917 /* Support Configure command-line overrides for rand() functions.
2918    After 5.005, perhaps we should replace this by Configure support
2919    for drand48(), random(), or rand().  For 5.005, though, maintain
2920    compatibility by calling rand() but allow the user to override it.
2921    See INSTALL for details.  --Andy Dougherty  15 July 1998
2922 */
2923 /* Now it's after 5.005, and Configure supports drand48() and random(),
2924    in addition to rand().  So the overrides should not be needed any more.
2925    --Jarkko Hietaniemi  27 September 1998
2926  */
2927
2928 #ifndef HAS_DRAND48_PROTO
2929 extern double drand48 (void);
2930 #endif
2931
2932 PP(pp_rand)
2933 {
2934     dVAR; dSP; dTARGET;
2935     NV value;
2936     if (MAXARG < 1)
2937         value = 1.0;
2938     else
2939         value = POPn;
2940     if (value == 0.0)
2941         value = 1.0;
2942     if (!PL_srand_called) {
2943         (void)seedDrand01((Rand_seed_t)seed());
2944         PL_srand_called = TRUE;
2945     }
2946     value *= Drand01();
2947     XPUSHn(value);
2948     RETURN;
2949 }
2950
2951 PP(pp_srand)
2952 {
2953     dVAR; dSP;
2954     const UV anum = (MAXARG < 1) ? seed() : POPu;
2955     (void)seedDrand01((Rand_seed_t)anum);
2956     PL_srand_called = TRUE;
2957     EXTEND(SP, 1);
2958     RETPUSHYES;
2959 }
2960
2961 PP(pp_int)
2962 {
2963     dVAR; dSP; dTARGET;
2964     tryAMAGICun_MG(int_amg, AMGf_numeric);
2965     {
2966       SV * const sv = TOPs;
2967       const IV iv = SvIV_nomg(sv);
2968       /* XXX it's arguable that compiler casting to IV might be subtly
2969          different from modf (for numbers inside (IV_MIN,UV_MAX)) in which
2970          else preferring IV has introduced a subtle behaviour change bug. OTOH
2971          relying on floating point to be accurate is a bug.  */
2972
2973       if (!SvOK(sv)) {
2974         SETu(0);
2975       }
2976       else if (SvIOK(sv)) {
2977         if (SvIsUV(sv))
2978             SETu(SvUV_nomg(sv));
2979         else
2980             SETi(iv);
2981       }
2982       else {
2983           const NV value = SvNV_nomg(sv);
2984           if (value >= 0.0) {
2985               if (value < (NV)UV_MAX + 0.5) {
2986                   SETu(U_V(value));
2987               } else {
2988                   SETn(Perl_floor(value));
2989               }
2990           }
2991           else {
2992               if (value > (NV)IV_MIN - 0.5) {
2993                   SETi(I_V(value));
2994               } else {
2995                   SETn(Perl_ceil(value));
2996               }
2997           }
2998       }
2999     }
3000     RETURN;
3001 }
3002
3003 PP(pp_abs)
3004 {
3005     dVAR; dSP; dTARGET;
3006     tryAMAGICun_MG(abs_amg, AMGf_numeric);
3007     {
3008       SV * const sv = TOPs;
3009       /* This will cache the NV value if string isn't actually integer  */
3010       const IV iv = SvIV_nomg(sv);
3011
3012       if (!SvOK(sv)) {
3013         SETu(0);
3014       }
3015       else if (SvIOK(sv)) {
3016         /* IVX is precise  */
3017         if (SvIsUV(sv)) {
3018           SETu(SvUV_nomg(sv));  /* force it to be numeric only */
3019         } else {
3020           if (iv >= 0) {
3021             SETi(iv);
3022           } else {
3023             if (iv != IV_MIN) {
3024               SETi(-iv);
3025             } else {
3026               /* 2s complement assumption. Also, not really needed as
3027                  IV_MIN and -IV_MIN should both be %100...00 and NV-able  */
3028               SETu(IV_MIN);
3029             }
3030           }
3031         }
3032       } else{
3033         const NV value = SvNV_nomg(sv);
3034         if (value < 0.0)
3035           SETn(-value);
3036         else
3037           SETn(value);
3038       }
3039     }
3040     RETURN;
3041 }
3042
3043 PP(pp_oct)
3044 {
3045     dVAR; dSP; dTARGET;
3046     const char *tmps;
3047     I32 flags = PERL_SCAN_ALLOW_UNDERSCORES;
3048     STRLEN len;
3049     NV result_nv;
3050     UV result_uv;
3051     SV* const sv = POPs;
3052
3053     tmps = (SvPV_const(sv, len));
3054     if (DO_UTF8(sv)) {
3055          /* If Unicode, try to downgrade
3056           * If not possible, croak. */
3057          SV* const tsv = sv_2mortal(newSVsv(sv));
3058         
3059          SvUTF8_on(tsv);
3060          sv_utf8_downgrade(tsv, FALSE);
3061          tmps = SvPV_const(tsv, len);
3062     }
3063     if (PL_op->op_type == OP_HEX)
3064         goto hex;
3065
3066     while (*tmps && len && isSPACE(*tmps))
3067         tmps++, len--;
3068     if (*tmps == '0')
3069         tmps++, len--;
3070     if (*tmps == 'x') {
3071     hex:
3072         result_uv = grok_hex (tmps, &len, &flags, &result_nv);
3073     }
3074     else if (*tmps == 'b')
3075         result_uv = grok_bin (tmps, &len, &flags, &result_nv);
3076     else
3077         result_uv = grok_oct (tmps, &len, &flags, &result_nv);
3078
3079     if (flags & PERL_SCAN_GREATER_THAN_UV_MAX) {
3080         XPUSHn(result_nv);
3081     }
3082     else {
3083         XPUSHu(result_uv);
3084     }
3085     RETURN;
3086 }
3087
3088 /* String stuff. */
3089
3090 PP(pp_length)
3091 {
3092     dVAR; dSP; dTARGET;
3093     SV * const sv = TOPs;
3094
3095     if (SvGAMAGIC(sv)) {
3096         /* For an overloaded or magic scalar, we can't know in advance if
3097            it's going to be UTF-8 or not. Also, we can't call sv_len_utf8 as
3098            it likes to cache the length. Maybe that should be a documented
3099            feature of it.
3100         */
3101         STRLEN len;
3102         const char *const p
3103             = sv_2pv_flags(sv, &len,
3104                            SV_UNDEF_RETURNS_NULL|SV_CONST_RETURN|SV_GMAGIC);
3105
3106         if (!p)
3107             SETs(&PL_sv_undef);
3108         else if (DO_UTF8(sv)) {
3109             SETi(utf8_length((U8*)p, (U8*)p + len));
3110         }
3111         else
3112             SETi(len);
3113     } else if (SvOK(sv)) {
3114         /* Neither magic nor overloaded.  */
3115         if (DO_UTF8(sv))
3116             SETi(sv_len_utf8(sv));
3117         else
3118             SETi(sv_len(sv));
3119     } else {
3120         SETs(&PL_sv_undef);
3121     }
3122     RETURN;
3123 }
3124
3125 PP(pp_substr)
3126 {
3127     dVAR; dSP; dTARGET;
3128     SV *sv;
3129     STRLEN curlen;
3130     STRLEN utf8_curlen;
3131     SV *   pos_sv;
3132     IV     pos1_iv;
3133     int    pos1_is_uv;
3134     IV     pos2_iv;
3135     int    pos2_is_uv;
3136     SV *   len_sv;
3137     IV     len_iv = 0;
3138     int    len_is_uv = 1;
3139     const I32 lvalue = PL_op->op_flags & OPf_MOD || LVRET;
3140     const char *tmps;
3141     const IV arybase = CopARYBASE_get(PL_curcop);
3142     SV *repl_sv = NULL;
3143     const char *repl = NULL;
3144     STRLEN repl_len;
3145     const int num_args = PL_op->op_private & 7;
3146     bool repl_need_utf8_upgrade = FALSE;
3147     bool repl_is_utf8 = FALSE;
3148
3149     SvTAINTED_off(TARG);                        /* decontaminate */
3150     SvUTF8_off(TARG);                           /* decontaminate */
3151     if (num_args > 2) {
3152         if (num_args > 3) {
3153             repl_sv = POPs;
3154             repl = SvPV_const(repl_sv, repl_len);
3155             repl_is_utf8 = DO_UTF8(repl_sv) && SvCUR(repl_sv);
3156         }
3157         len_sv    = POPs;
3158         len_iv    = SvIV(len_sv);
3159         len_is_uv = SvIOK_UV(len_sv);
3160     }
3161     pos_sv     = POPs;
3162     pos1_iv    = SvIV(pos_sv);
3163     pos1_is_uv = SvIOK_UV(pos_sv);
3164     sv = POPs;
3165     PUTBACK;
3166     if (repl_sv) {
3167         if (repl_is_utf8) {
3168             if (!DO_UTF8(sv))
3169                 sv_utf8_upgrade(sv);
3170         }
3171         else if (DO_UTF8(sv))
3172             repl_need_utf8_upgrade = TRUE;
3173     }
3174     tmps = SvPV_const(sv, curlen);
3175     if (DO_UTF8(sv)) {
3176         utf8_curlen = sv_len_utf8(sv);
3177         if (utf8_curlen == curlen)
3178             utf8_curlen = 0;
3179         else
3180             curlen = utf8_curlen;
3181     }
3182     else
3183         utf8_curlen = 0;
3184
3185     if ( (pos1_is_uv && arybase < 0) || (pos1_iv >= arybase) ) { /* pos >= $[ */
3186         UV pos1_uv = pos1_iv-arybase;
3187         /* Overflow can occur when $[ < 0 */
3188         if (arybase < 0 && pos1_uv < (UV)pos1_iv)
3189             goto bound_fail;
3190         pos1_iv = pos1_uv;
3191         pos1_is_uv = 1;
3192     }
3193     else if (pos1_is_uv ? (UV)pos1_iv > 0 : pos1_iv > 0) {
3194         goto bound_fail;  /* $[=3; substr($_,2,...) */
3195     }
3196     else { /* pos < $[ */
3197         if (pos1_iv == 0) { /* $[=1; substr($_,0,...) */
3198             pos1_iv = curlen;
3199             pos1_is_uv = 1;
3200         } else {
3201             if (curlen) {
3202                 pos1_is_uv = curlen-1 > ~(UV)pos1_iv;
3203                 pos1_iv += curlen;
3204            }
3205         }
3206     }
3207     if (pos1_is_uv || pos1_iv > 0) {
3208         if ((UV)pos1_iv > curlen)
3209             goto bound_fail;
3210     }
3211
3212     if (num_args > 2) {
3213         if (!len_is_uv && len_iv < 0) {
3214             pos2_iv = curlen + len_iv;
3215             if (curlen)
3216                 pos2_is_uv = curlen-1 > ~(UV)len_iv;
3217             else
3218                 pos2_is_uv = 0;
3219         } else {  /* len_iv >= 0 */
3220             if (!pos1_is_uv && pos1_iv < 0) {
3221                 pos2_iv = pos1_iv + len_iv;
3222                 pos2_is_uv = (UV)len_iv > (UV)IV_MAX;
3223             } else {
3224                 if ((UV)len_iv > curlen-(UV)pos1_iv)
3225                     pos2_iv = curlen;
3226                 else
3227                     pos2_iv = pos1_iv+len_iv;
3228                 pos2_is_uv = 1;
3229             }
3230         }
3231     }
3232     else {
3233         pos2_iv = curlen;
3234         pos2_is_uv = 1;
3235     }
3236
3237     if (!pos2_is_uv && pos2_iv < 0) {
3238         if (!pos1_is_uv && pos1_iv < 0)
3239             goto bound_fail;
3240         pos2_iv = 0;
3241     }
3242     else if (!pos1_is_uv && pos1_iv < 0)
3243         pos1_iv = 0;
3244
3245     if ((UV)pos2_iv < (UV)pos1_iv)
3246         pos2_iv = pos1_iv;
3247     if ((UV)pos2_iv > curlen)
3248         pos2_iv = curlen;
3249
3250     {
3251         /* pos1_iv and pos2_iv both in 0..curlen, so the cast is safe */
3252         const STRLEN pos = (STRLEN)( (UV)pos1_iv );
3253         const STRLEN len = (STRLEN)( (UV)pos2_iv - (UV)pos1_iv );
3254         STRLEN byte_len = len;
3255         STRLEN byte_pos = utf8_curlen
3256             ? sv_pos_u2b_flags(sv, pos, &byte_len, SV_CONST_RETURN) : pos;
3257
3258         tmps += byte_pos;
3259         /* we either return a PV or an LV. If the TARG hasn't been used
3260          * before, or is of that type, reuse it; otherwise use a mortal
3261          * instead. Note that LVs can have an extended lifetime, so also
3262          * dont reuse if refcount > 1 (bug #20933) */
3263         if (SvTYPE(TARG) > SVt_NULL) {
3264             if ( (SvTYPE(TARG) == SVt_PVLV)
3265                     ? (!lvalue || SvREFCNT(TARG) > 1)
3266                     : lvalue)
3267             {
3268                 TARG = sv_newmortal();
3269             }
3270         }
3271
3272         sv_setpvn(TARG, tmps, byte_len);
3273 #ifdef USE_LOCALE_COLLATE
3274         sv_unmagic(TARG, PERL_MAGIC_collxfrm);
3275 #endif
3276         if (utf8_curlen)
3277             SvUTF8_on(TARG);
3278         if (repl) {
3279             SV* repl_sv_copy = NULL;
3280
3281             if (repl_need_utf8_upgrade) {
3282                 repl_sv_copy = newSVsv(repl_sv);
3283                 sv_utf8_upgrade(repl_sv_copy);
3284                 repl = SvPV_const(repl_sv_copy, repl_len);
3285                 repl_is_utf8 = DO_UTF8(repl_sv_copy) && SvCUR(sv);
3286             }
3287             if (!SvOK(sv))
3288                 sv_setpvs(sv, "");
3289             sv_insert_flags(sv, byte_pos, byte_len, repl, repl_len, 0);
3290             if (repl_is_utf8)
3291                 SvUTF8_on(sv);
3292             SvREFCNT_dec(repl_sv_copy);
3293         }
3294         else if (lvalue) {              /* it's an lvalue! */
3295             if (!SvGMAGICAL(sv)) {
3296                 if (SvROK(sv)) {
3297                     SvPV_force_nolen(sv);
3298                     Perl_ck_warner(aTHX_ packWARN(WARN_SUBSTR),
3299                                    "Attempt to use reference as lvalue in substr");
3300                 }
3301                 if (isGV_with_GP(sv))
3302                     SvPV_force_nolen(sv);
3303                 else if (SvOK(sv))      /* is it defined ? */
3304                     (void)SvPOK_only_UTF8(sv);
3305                 else
3306                     sv_setpvs(sv, ""); /* avoid lexical reincarnation */
3307             }
3308
3309             if (SvTYPE(TARG) < SVt_PVLV) {
3310                 sv_upgrade(TARG, SVt_PVLV);
3311                 sv_magic(TARG, NULL, PERL_MAGIC_substr, NULL, 0);
3312             }
3313
3314             LvTYPE(TARG) = 'x';
3315             if (LvTARG(TARG) != sv) {
3316                 SvREFCNT_dec(LvTARG(TARG));
3317                 LvTARG(TARG) = SvREFCNT_inc_simple(sv);
3318             }
3319             LvTARGOFF(TARG) = pos;
3320             LvTARGLEN(TARG) = len;
3321         }
3322     }
3323     SPAGAIN;
3324     PUSHs(TARG);                /* avoid SvSETMAGIC here */
3325     RETURN;
3326
3327 bound_fail:
3328     if (lvalue || repl)
3329         Perl_croak(aTHX_ "substr outside of string");
3330     Perl_ck_warner(aTHX_ packWARN(WARN_SUBSTR), "substr outside of string");
3331     RETPUSHUNDEF;
3332 }
3333
3334 PP(pp_vec)
3335 {
3336     dVAR; dSP; dTARGET;
3337     register const IV size   = POPi;
3338     register const IV offset = POPi;
3339     register SV * const src = POPs;
3340     const I32 lvalue = PL_op->op_flags & OPf_MOD || LVRET;
3341
3342     SvTAINTED_off(TARG);                /* decontaminate */
3343     if (lvalue) {                       /* it's an lvalue! */
3344         if (SvREFCNT(TARG) > 1) /* don't share the TARG (#20933) */
3345             TARG = sv_newmortal();
3346         if (SvTYPE(TARG) < SVt_PVLV) {
3347             sv_upgrade(TARG, SVt_PVLV);
3348             sv_magic(TARG, NULL, PERL_MAGIC_vec, NULL, 0);
3349         }
3350         LvTYPE(TARG) = 'v';
3351         if (LvTARG(TARG) != src) {
3352             SvREFCNT_dec(LvTARG(TARG));
3353             LvTARG(TARG) = SvREFCNT_inc_simple(src);
3354         }
3355         LvTARGOFF(TARG) = offset;
3356         LvTARGLEN(TARG) = size;
3357     }
3358
3359     sv_setuv(TARG, do_vecget(src, offset, size));
3360     PUSHs(TARG);
3361     RETURN;
3362 }
3363
3364 PP(pp_index)
3365 {
3366     dVAR; dSP; dTARGET;
3367     SV *big;
3368     SV *little;
3369     SV *temp = NULL;
3370     STRLEN biglen;
3371     STRLEN llen = 0;
3372     I32 offset;
3373     I32 retval;
3374     const char *big_p;
3375     const char *little_p;
3376     const I32 arybase = CopARYBASE_get(PL_curcop);
3377     bool big_utf8;
3378     bool little_utf8;
3379     const bool is_index = PL_op->op_type == OP_INDEX;
3380
3381     if (MAXARG >= 3) {
3382         /* arybase is in characters, like offset, so combine prior to the
3383            UTF-8 to bytes calculation.  */
3384         offset = POPi - arybase;
3385     }
3386     little = POPs;
3387     big = POPs;
3388     big_p = SvPV_const(big, biglen);
3389     little_p = SvPV_const(little, llen);
3390
3391     big_utf8 = DO_UTF8(big);
3392     little_utf8 = DO_UTF8(little);
3393     if (big_utf8 ^ little_utf8) {
3394         /* One needs to be upgraded.  */
3395         if (little_utf8 && !PL_encoding) {
3396             /* Well, maybe instead we might be able to downgrade the small
3397                string?  */
3398             char * const pv = (char*)bytes_from_utf8((U8 *)little_p, &llen,
3399                                                      &little_utf8);
3400             if (little_utf8) {
3401                 /* If the large string is ISO-8859-1, and it's not possible to
3402                    convert the small string to ISO-8859-1, then there is no
3403                    way that it could be found anywhere by index.  */
3404                 retval = -1;
3405                 goto fail;
3406             }
3407
3408             /* At this point, pv is a malloc()ed string. So donate it to temp
3409                to ensure it will get free()d  */
3410             little = temp = newSV(0);
3411             sv_usepvn(temp, pv, llen);
3412             little_p = SvPVX(little);
3413         } else {
3414             temp = little_utf8
3415                 ? newSVpvn(big_p, biglen) : newSVpvn(little_p, llen);
3416
3417             if (PL_encoding) {
3418                 sv_recode_to_utf8(temp, PL_encoding);
3419             } else {
3420                 sv_utf8_upgrade(temp);
3421             }
3422             if (little_utf8) {
3423                 big = temp;
3424                 big_utf8 = TRUE;
3425                 big_p = SvPV_const(big, biglen);
3426             } else {
3427                 little = temp;
3428                 little_p = SvPV_const(little, llen);
3429             }
3430         }
3431     }
3432     if (SvGAMAGIC(big)) {
3433         /* Life just becomes a lot easier if I use a temporary here.
3434            Otherwise I need to avoid calls to sv_pos_u2b(), which (dangerously)
3435            will trigger magic and overloading again, as will fbm_instr()
3436         */
3437         big = newSVpvn_flags(big_p, biglen,
3438                              SVs_TEMP | (big_utf8 ? SVf_UTF8 : 0));
3439         big_p = SvPVX(big);
3440     }
3441     if (SvGAMAGIC(little) || (is_index && !SvOK(little))) {
3442         /* index && SvOK() is a hack. fbm_instr() calls SvPV_const, which will
3443            warn on undef, and we've already triggered a warning with the
3444            SvPV_const some lines above. We can't remove that, as we need to
3445            call some SvPV to trigger overloading early and find out if the
3446            string is UTF-8.
3447            This is all getting to messy. The API isn't quite clean enough,
3448            because data access has side effects.
3449         */
3450         little = newSVpvn_flags(little_p, llen,
3451                                 SVs_TEMP | (little_utf8 ? SVf_UTF8 : 0));
3452         little_p = SvPVX(little);
3453     }
3454
3455     if (MAXARG < 3)
3456         offset = is_index ? 0 : biglen;
3457     else {
3458         if (big_utf8 && offset > 0)
3459             sv_pos_u2b(big, &offset, 0);
3460         if (!is_index)
3461             offset += llen;
3462     }
3463     if (offset < 0)
3464         offset = 0;
3465     else if (offset > (I32)biglen)
3466         offset = biglen;
3467     if (!(little_p = is_index
3468           ? fbm_instr((unsigned char*)big_p + offset,
3469                       (unsigned char*)big_p + biglen, little, 0)
3470           : rninstr(big_p,  big_p  + offset,
3471                     little_p, little_p + llen)))
3472         retval = -1;
3473     else {
3474         retval = little_p - big_p;
3475         if (retval > 0 && big_utf8)
3476             sv_pos_b2u(big, &retval);
3477     }
3478     SvREFCNT_dec(temp);
3479  fail:
3480     PUSHi(retval + arybase);
3481     RETURN;
3482 }
3483
3484 PP(pp_sprintf)
3485 {
3486     dVAR; dSP; dMARK; dORIGMARK; dTARGET;
3487     if (SvTAINTED(MARK[1]))
3488         TAINT_PROPER("sprintf");
3489     SvTAINTED_off(TARG);
3490     do_sprintf(TARG, SP-MARK, MARK+1);
3491     TAINT_IF(SvTAINTED(TARG));
3492     SP = ORIGMARK;
3493     PUSHTARG;
3494     RETURN;
3495 }
3496
3497 PP(pp_ord)
3498 {
3499     dVAR; dSP; dTARGET;
3500
3501     SV *argsv = POPs;
3502     STRLEN len;
3503     const U8 *s = (U8*)SvPV_const(argsv, len);
3504
3505     if (PL_encoding && SvPOK(argsv) && !DO_UTF8(argsv)) {
3506         SV * const tmpsv = sv_2mortal(newSVsv(argsv));
3507         s = (U8*)sv_recode_to_utf8(tmpsv, PL_encoding);
3508         argsv = tmpsv;
3509     }
3510
3511     XPUSHu(DO_UTF8(argsv) ?
3512            utf8n_to_uvchr(s, UTF8_MAXBYTES, 0, UTF8_ALLOW_ANYUV) :
3513            (UV)(*s & 0xff));
3514
3515     RETURN;
3516 }
3517
3518 PP(pp_chr)
3519 {
3520     dVAR; dSP; dTARGET;
3521     char *tmps;
3522     UV value;
3523
3524     if (((SvIOK_notUV(TOPs) && SvIV(TOPs) < 0)
3525          ||
3526          (SvNOK(TOPs) && SvNV(TOPs) < 0.0))) {
3527         if (IN_BYTES) {
3528             value = POPu; /* chr(-1) eq chr(0xff), etc. */
3529         } else {
3530             (void) POPs; /* Ignore the argument value. */
3531             value = UNICODE_REPLACEMENT;
3532         }
3533     } else {
3534         value = POPu;
3535     }
3536
3537     SvUPGRADE(TARG,SVt_PV);
3538
3539     if (value > 255 && !IN_BYTES) {
3540         SvGROW(TARG, (STRLEN)UNISKIP(value)+1);
3541         tmps = (char*)uvchr_to_utf8_flags((U8*)SvPVX(TARG), value, 0);
3542         SvCUR_set(TARG, tmps - SvPVX_const(TARG));
3543         *tmps = '\0';
3544         (void)SvPOK_only(TARG);
3545         SvUTF8_on(TARG);
3546         XPUSHs(TARG);
3547         RETURN;
3548     }
3549
3550     SvGROW(TARG,2);
3551     SvCUR_set(TARG, 1);
3552     tmps = SvPVX(TARG);
3553     *tmps++ = (char)value;
3554     *tmps = '\0';
3555     (void)SvPOK_only(TARG);
3556
3557     if (PL_encoding && !IN_BYTES) {
3558         sv_recode_to_utf8(TARG, PL_encoding);
3559         tmps = SvPVX(TARG);
3560         if (SvCUR(TARG) == 0 || !is_utf8_string((U8*)tmps, SvCUR(TARG)) ||
3561             UNICODE_IS_REPLACEMENT(utf8_to_uvchr((U8*)tmps, NULL))) {
3562             SvGROW(TARG, 2);
3563             tmps = SvPVX(TARG);
3564             SvCUR_set(TARG, 1);
3565             *tmps++ = (char)value;
3566             *tmps = '\0';
3567             SvUTF8_off(TARG);
3568         }
3569     }
3570
3571     XPUSHs(TARG);
3572     RETURN;
3573 }
3574
3575 PP(pp_crypt)
3576 {
3577 #ifdef HAS_CRYPT
3578     dVAR; dSP; dTARGET;
3579     dPOPTOPssrl;
3580     STRLEN len;
3581     const char *tmps = SvPV_const(left, len);
3582
3583     if (DO_UTF8(left)) {
3584          /* If Unicode, try to downgrade.
3585           * If not possible, croak.
3586           * Yes, we made this up.  */
3587          SV* const tsv = sv_2mortal(newSVsv(left));
3588
3589          SvUTF8_on(tsv);
3590          sv_utf8_downgrade(tsv, FALSE);
3591          tmps = SvPV_const(tsv, len);
3592     }
3593 #   ifdef USE_ITHREADS
3594 #     ifdef HAS_CRYPT_R
3595     if (!PL_reentrant_buffer->_crypt_struct_buffer) {
3596       /* This should be threadsafe because in ithreads there is only
3597        * one thread per interpreter.  If this would not be true,
3598        * we would need a mutex to protect this malloc. */
3599         PL_reentrant_buffer->_crypt_struct_buffer =
3600           (struct crypt_data *)safemalloc(sizeof(struct crypt_data));
3601 #if defined(__GLIBC__) || defined(__EMX__)
3602         if (PL_reentrant_buffer->_crypt_struct_buffer) {
3603             PL_reentrant_buffer->_crypt_struct_buffer->initialized = 0;
3604             /* work around glibc-2.2.5 bug */
3605             PL_reentrant_buffer->_crypt_struct_buffer->current_saltbits = 0;
3606         }
3607 #endif
3608     }
3609 #     endif /* HAS_CRYPT_R */
3610 #   endif /* USE_ITHREADS */
3611 #   ifdef FCRYPT
3612     sv_setpv(TARG, fcrypt(tmps, SvPV_nolen_const(right)));
3613 #   else
3614     sv_setpv(TARG, PerlProc_crypt(tmps, SvPV_nolen_const(right)));
3615 #   endif
3616     SETTARG;
3617     RETURN;
3618 #else
3619     DIE(aTHX_
3620       "The crypt() function is unimplemented due to excessive paranoia.");
3621     return NORMAL;
3622 #endif
3623 }
3624
3625 /* Generally UTF-8 and UTF-EBCDIC are indistinguishable at this level.  So 
3626  * most comments below say UTF-8, when in fact they mean UTF-EBCDIC as well */
3627
3628 /* Both the characters below can be stored in two UTF-8 bytes.  In UTF-8 the max
3629  * character that 2 bytes can hold is U+07FF, and in UTF-EBCDIC it is U+03FF.
3630  * See http://www.unicode.org/unicode/reports/tr16 */
3631 #define LATIN_CAPITAL_LETTER_Y_WITH_DIAERESIS 0x0178    /* Also is title case */
3632 #define GREEK_CAPITAL_LETTER_MU 0x039C  /* Upper and title case of MICRON */
3633
3634 /* Below are several macros that generate code */
3635 /* Generates code to store a unicode codepoint c that is known to occupy
3636  * exactly two UTF-8 and UTF-EBCDIC bytes; it is stored into p and p+1. */
3637 #define STORE_UNI_TO_UTF8_TWO_BYTE(p, c)                                    \
3638     STMT_START {                                                            \
3639         *(p) = UTF8_TWO_BYTE_HI(c);                                         \
3640         *((p)+1) = UTF8_TWO_BYTE_LO(c);                                     \
3641     } STMT_END
3642
3643 /* Like STORE_UNI_TO_UTF8_TWO_BYTE, but advances p to point to the next
3644  * available byte after the two bytes */
3645 #define CAT_UNI_TO_UTF8_TWO_BYTE(p, c)                                      \
3646     STMT_START {                                                            \
3647         *(p)++ = UTF8_TWO_BYTE_HI(c);                                       \
3648         *((p)++) = UTF8_TWO_BYTE_LO(c);                                     \
3649     } STMT_END
3650
3651 /* Generates code to store the upper case of latin1 character l which is known
3652  * to have its upper case be non-latin1 into the two bytes p and p+1.  There
3653  * are only two characters that fit this description, and this macro knows
3654  * about them, and that the upper case values fit into two UTF-8 or UTF-EBCDIC
3655  * bytes */
3656 #define STORE_NON_LATIN1_UC(p, l)                                           \
3657 STMT_START {                                                                \
3658     if ((l) == LATIN_SMALL_LETTER_Y_WITH_DIAERESIS) {                       \
3659         STORE_UNI_TO_UTF8_TWO_BYTE((p), LATIN_CAPITAL_LETTER_Y_WITH_DIAERESIS);  \
3660     } else { /* Must be the following letter */                                                             \
3661         STORE_UNI_TO_UTF8_TWO_BYTE((p), GREEK_CAPITAL_LETTER_MU);           \
3662     }                                                                       \
3663 } STMT_END
3664
3665 /* Like STORE_NON_LATIN1_UC, but advances p to point to the next available byte
3666  * after the character stored */
3667 #define CAT_NON_LATIN1_UC(p, l)                                             \
3668 STMT_START {                                                                \
3669     if ((l) == LATIN_SMALL_LETTER_Y_WITH_DIAERESIS) {                       \
3670         CAT_UNI_TO_UTF8_TWO_BYTE((p), LATIN_CAPITAL_LETTER_Y_WITH_DIAERESIS);    \
3671     } else {                                                                \
3672         CAT_UNI_TO_UTF8_TWO_BYTE((p), GREEK_CAPITAL_LETTER_MU);             \
3673     }                                                                       \
3674 } STMT_END
3675
3676 /* Generates code to add the two UTF-8 bytes (probably u) that are the upper
3677  * case of l into p and p+1.  u must be the result of toUPPER_LATIN1_MOD(l),
3678  * and must require two bytes to store it.  Advances p to point to the next
3679  * available position */
3680 #define CAT_TWO_BYTE_UNI_UPPER_MOD(p, l, u)                                 \
3681 STMT_START {                                                                \
3682     if ((u) != LATIN_SMALL_LETTER_Y_WITH_DIAERESIS) {                       \
3683         CAT_UNI_TO_UTF8_TWO_BYTE((p), (u)); /* not special, just save it */ \
3684     } else if (l == LATIN_SMALL_LETTER_SHARP_S) {                           \
3685         *(p)++ = 'S'; *(p)++ = 'S'; /* upper case is 'SS' */                \
3686     } else {/* else is one of the other two special cases */                \
3687         CAT_NON_LATIN1_UC((p), (l));                                        \
3688     }                                                                       \
3689 } STMT_END
3690
3691 PP(pp_ucfirst)
3692 {
3693     /* Actually is both lcfirst() and ucfirst().  Only the first character
3694      * changes.  This means that possibly we can change in-place, ie., just
3695      * take the source and change that one character and store it back, but not
3696      * if read-only etc, or if the length changes */
3697
3698     dVAR;
3699     dSP;
3700     SV *source = TOPs;
3701     STRLEN slen; /* slen is the byte length of the whole SV. */
3702     STRLEN need;
3703     SV *dest;
3704     bool inplace;   /* ? Convert first char only, in-place */
3705     bool doing_utf8 = FALSE;               /* ? using utf8 */
3706     bool convert_source_to_utf8 = FALSE;   /* ? need to convert */
3707     const int op_type = PL_op->op_type;
3708     const U8 *s;
3709     U8 *d;
3710     U8 tmpbuf[UTF8_MAXBYTES_CASE+1];
3711     STRLEN ulen;    /* ulen is the byte length of the original Unicode character
3712                      * stored as UTF-8 at s. */
3713     STRLEN tculen;  /* tculen is the byte length of the freshly titlecased (or
3714                      * lowercased) character stored in tmpbuf.  May be either
3715                      * UTF-8 or not, but in either case is the number of bytes */
3716
3717     SvGETMAGIC(source);
3718     if (SvOK(source)) {
3719         s = (const U8*)SvPV_nomg_const(source, slen);
3720     } else {
3721         if (ckWARN(WARN_UNINITIALIZED))
3722             report_uninit(source);
3723         s = (const U8*)"";
3724         slen = 0;
3725     }
3726
3727     /* We may be able to get away with changing only the first character, in
3728      * place, but not if read-only, etc.  Later we may discover more reasons to
3729      * not convert in-place. */
3730     inplace = SvPADTMP(source) && !SvREADONLY(source) && SvTEMP(source);
3731
3732     /* First calculate what the changed first character should be.  This affects
3733      * whether we can just swap it out, leaving the rest of the string unchanged,
3734      * or even if have to convert the dest to UTF-8 when the source isn't */
3735
3736     if (! slen) {   /* If empty */
3737         need = 1; /* still need a trailing NUL */
3738     }
3739     else if (DO_UTF8(source)) { /* Is the source utf8? */
3740         doing_utf8 = TRUE;
3741
3742 /* TODO: This is #ifdefd out because it has hard-coded the standard mappings,
3743  * and doesn't allow for the user to specify their own.  When code is added to
3744  * detect if there is a user-defined mapping in force here, and if so to use
3745  * that, then the code below can be compiled.  The detection would be a good
3746  * thing anyway, as currently the user-defined mappings only work on utf8
3747  * strings, and thus depend on the chosen internal storage method, which is a
3748  * bad thing */
3749 #ifdef GO_AHEAD_AND_BREAK_USER_DEFINED_CASE_MAPPINGS
3750         if (UTF8_IS_INVARIANT(*s)) {
3751
3752             /* An invariant source character is either ASCII or, in EBCDIC, an
3753              * ASCII equivalent or a caseless C1 control.  In both these cases,
3754              * the lower and upper cases of any character are also invariants
3755              * (and title case is the same as upper case).  So it is safe to
3756              * use the simple case change macros which avoid the overhead of
3757              * the general functions.  Note that if perl were to be extended to
3758              * do locale handling in UTF-8 strings, this wouldn't be true in,
3759              * for example, Lithuanian or Turkic.  */
3760             *tmpbuf = (op_type == OP_LCFIRST) ? toLOWER(*s) : toUPPER(*s);
3761             tculen = ulen = 1;
3762             need = slen + 1;
3763         }
3764         else if (UTF8_IS_DOWNGRADEABLE_START(*s)) {
3765             U8 chr;
3766
3767             /* Similarly, if the source character isn't invariant but is in the
3768              * latin1 range (or EBCDIC equivalent thereof), we have the case
3769              * changes compiled into perl, and can avoid the overhead of the
3770              * general functions.  In this range, the characters are stored as
3771              * two UTF-8 bytes, and it so happens that any changed-case version
3772              * is also two bytes (in both ASCIIish and EBCDIC machines). */
3773             tculen = ulen = 2;
3774             need = slen + 1;
3775
3776             /* Convert the two source bytes to a single Unicode code point
3777              * value, change case and save for below */
3778             chr = UTF8_ACCUMULATE(*s, *(s+1));
3779             if (op_type == OP_LCFIRST) {    /* lower casing is easy */
3780                 U8 lower = toLOWER_LATIN1(chr);
3781                 STORE_UNI_TO_UTF8_TWO_BYTE(tmpbuf, lower);
3782             }
3783             else {      /* ucfirst */
3784                 U8 upper = toUPPER_LATIN1_MOD(chr);
3785
3786                 /* Most of the latin1 range characters are well-behaved.  Their
3787                  * title and upper cases are the same, and are also in the
3788                  * latin1 range.  The macro above returns their upper (hence
3789                  * title) case, and all that need be done is to save the result
3790                  * for below.  However, several characters are problematic, and
3791                  * have to be handled specially.  The MOD in the macro name
3792                  * above means that these tricky characters all get mapped to
3793                  * the single character LATIN_SMALL_LETTER_Y_WITH_DIAERESIS.
3794                  * This mapping saves some tests for the majority of the
3795                  * characters */
3796
3797                 if (upper != LATIN_SMALL_LETTER_Y_WITH_DIAERESIS) {
3798
3799                     /* Not tricky.  Just save it. */
3800                     STORE_UNI_TO_UTF8_TWO_BYTE(tmpbuf, upper);
3801                 }
3802                 else if (chr == LATIN_SMALL_LETTER_SHARP_S) {
3803
3804                     /* This one is tricky because it is two characters long,
3805                      * though the UTF-8 is still two bytes, so the stored
3806                      * length doesn't change */
3807                     *tmpbuf = 'S';  /* The UTF-8 is 'Ss' */
3808                     *(tmpbuf + 1) = 's';
3809                 }
3810                 else {
3811
3812                     /* The other two have their title and upper cases the same,
3813                      * but are tricky because the changed-case characters
3814                      * aren't in the latin1 range.  They, however, do fit into
3815                      * two UTF-8 bytes */
3816                     STORE_NON_LATIN1_UC(tmpbuf, chr);    
3817                 }
3818             }
3819         }
3820         else {
3821 #endif  /* end of dont want to break user-defined casing */
3822
3823             /* Here, can't short-cut the general case */
3824
3825             utf8_to_uvchr(s, &ulen);
3826             if (op_type == OP_UCFIRST) toTITLE_utf8(s, tmpbuf, &tculen);
3827             else toLOWER_utf8(s, tmpbuf, &tculen);
3828
3829             /* we can't do in-place if the length changes.  */
3830             if (ulen != tculen) inplace = FALSE;
3831             need = slen + 1 - ulen + tculen;
3832 #ifdef GO_AHEAD_AND_BREAK_USER_DEFINED_CASE_MAPPINGS
3833         }
3834 #endif
3835     }
3836     else { /* Non-zero length, non-UTF-8,  Need to consider locale and if
3837             * latin1 is treated as caseless.  Note that a locale takes
3838             * precedence */ 
3839         tculen = 1;     /* Most characters will require one byte, but this will
3840                          * need to be overridden for the tricky ones */
3841         need = slen + 1;
3842
3843         if (op_type == OP_LCFIRST) {
3844
3845             /* lower case the first letter: no trickiness for any character */
3846             *tmpbuf = (IN_LOCALE_RUNTIME) ? toLOWER_LC(*s) :
3847                         ((IN_UNI_8_BIT) ? toLOWER_LATIN1(*s) : toLOWER(*s));
3848         }
3849         /* is ucfirst() */
3850         else if (IN_LOCALE_RUNTIME) {
3851             *tmpbuf = toUPPER_LC(*s);   /* This would be a bug if any locales
3852                                          * have upper and title case different
3853                                          */
3854         }
3855         else if (! IN_UNI_8_BIT) {
3856             *tmpbuf = toUPPER(*s);      /* Returns caseless for non-ascii, or
3857                                          * on EBCDIC machines whatever the
3858                                          * native function does */
3859         }
3860         else { /* is ucfirst non-UTF-8, not in locale, and cased latin1 */
3861             *tmpbuf = toUPPER_LATIN1_MOD(*s);
3862
3863             /* tmpbuf now has the correct title case for all latin1 characters
3864              * except for the several ones that have tricky handling.  All
3865              * of these are mapped by the MOD to the letter below. */
3866             if (*tmpbuf == LATIN_SMALL_LETTER_Y_WITH_DIAERESIS) {
3867
3868                 /* The length is going to change, with all three of these, so
3869                  * can't replace just the first character */
3870                 inplace = FALSE;
3871
3872                 /* We use the original to distinguish between these tricky
3873                  * cases */
3874                 if (*s == LATIN_SMALL_LETTER_SHARP_S) {
3875                     /* Two character title case 'Ss', but can remain non-UTF-8 */
3876                     need = slen + 2;
3877                     *tmpbuf = 'S';
3878                     *(tmpbuf + 1) = 's';   /* Assert: length(tmpbuf) >= 2 */
3879                     tculen = 2;
3880                 }
3881                 else {
3882
3883                     /* The other two tricky ones have their title case outside
3884                      * latin1.  It is the same as their upper case. */
3885                     doing_utf8 = TRUE;
3886                     STORE_NON_LATIN1_UC(tmpbuf, *s);
3887
3888                     /* The UTF-8 and UTF-EBCDIC lengths of both these characters
3889                      * and their upper cases is 2. */
3890                     tculen = ulen = 2;
3891
3892                     /* The entire result will have to be in UTF-8.  Assume worst
3893                      * case sizing in conversion. (all latin1 characters occupy
3894                      * at most two bytes in utf8) */
3895                     convert_source_to_utf8 = TRUE;
3896                     need = slen * 2 + 1;
3897                 }
3898             } /* End of is one of the three special chars */
3899         } /* End of use Unicode (Latin1) semantics */
3900     } /* End of changing the case of the first character */
3901
3902     /* Here, have the first character's changed case stored in tmpbuf.  Ready to
3903      * generate the result */
3904     if (inplace) {
3905
3906         /* We can convert in place.  This means we change just the first
3907          * character without disturbing the rest; no need to grow */
3908         dest = source;
3909         s = d = (U8*)SvPV_force_nomg(source, slen);
3910     } else {
3911         dTARGET;
3912
3913         dest = TARG;
3914
3915         /* Here, we can't convert in place; we earlier calculated how much
3916          * space we will need, so grow to accommodate that */
3917         SvUPGRADE(dest, SVt_PV);
3918         d = (U8*)SvGROW(dest, need);
3919         (void)SvPOK_only(dest);
3920
3921         SETs(dest);
3922     }
3923
3924     if (doing_utf8) {
3925         if (! inplace) {
3926             if (! convert_source_to_utf8) {
3927
3928                 /* Here  both source and dest are in UTF-8, but have to create
3929                  * the entire output.  We initialize the result to be the
3930                  * title/lower cased first character, and then append the rest
3931                  * of the string. */
3932                 sv_setpvn(dest, (char*)tmpbuf, tculen);
3933                 if (slen > ulen) {
3934                     sv_catpvn(dest, (char*)(s + ulen), slen - ulen);
3935                 }
3936             }
3937             else {
3938                 const U8 *const send = s + slen;
3939
3940                 /* Here the dest needs to be in UTF-8, but the source isn't,
3941                  * except we earlier UTF-8'd the first character of the source
3942                  * into tmpbuf.  First put that into dest, and then append the
3943                  * rest of the source, converting it to UTF-8 as we go. */
3944
3945                 /* Assert tculen is 2 here because the only two characters that
3946                  * get to this part of the code have 2-byte UTF-8 equivalents */
3947                 *d++ = *tmpbuf;
3948                 *d++ = *(tmpbuf + 1);
3949                 s++;    /* We have just processed the 1st char */
3950
3951                 for (; s < send; s++) {
3952                     d = uvchr_to_utf8(d, *s);
3953                 }
3954                 *d = '\0';
3955                 SvCUR_set(dest, d - (U8*)SvPVX_const(dest));
3956             }
3957             SvUTF8_on(dest);
3958         }
3959         else {   /* in-place UTF-8.  Just overwrite the first character */
3960             Copy(tmpbuf, d, tculen, U8);
3961             SvCUR_set(dest, need - 1);
3962         }
3963     }
3964     else {  /* Neither source nor dest are in or need to be UTF-8 */
3965         if (slen) {
3966             if (IN_LOCALE_RUNTIME) {
3967                 TAINT;
3968                 SvTAINTED_on(dest);
3969             }
3970             if (inplace) {  /* in-place, only need to change the 1st char */
3971                 *d = *tmpbuf;
3972             }
3973             else {      /* Not in-place */
3974
3975                 /* Copy the case-changed character(s) from tmpbuf */
3976                 Copy(tmpbuf, d, tculen, U8);
3977                 d += tculen - 1; /* Code below expects d to point to final
3978                                   * character stored */
3979             }
3980         }
3981         else {  /* empty source */
3982             /* See bug #39028: Don't taint if empty  */
3983             *d = *s;
3984         }
3985
3986         /* In a "use bytes" we don't treat the source as UTF-8, but, still want
3987          * the destination to retain that flag */
3988         if (SvUTF8(source))
3989             SvUTF8_on(dest);
3990
3991         if (!inplace) { /* Finish the rest of the string, unchanged */
3992             /* This will copy the trailing NUL  */
3993             Copy(s + 1, d + 1, slen, U8);
3994             SvCUR_set(dest, need - 1);
3995         }
3996     }
3997     SvSETMAGIC(dest);
3998     RETURN;
3999 }
4000
4001 /* There's so much setup/teardown code common between uc and lc, I wonder if
4002    it would be worth merging the two, and just having a switch outside each
4003    of the three tight loops.  There is less and less commonality though */
4004 PP(pp_uc)
4005 {
4006     dVAR;
4007     dSP;
4008     SV *source = TOPs;
4009     STRLEN len;
4010     STRLEN min;
4011     SV *dest;
4012     const U8 *s;
4013     U8 *d;
4014
4015     SvGETMAGIC(source);
4016
4017     if (SvPADTMP(source) && !SvREADONLY(source) && !SvAMAGIC(source)
4018         && SvTEMP(source) && !DO_UTF8(source)
4019         && (IN_LOCALE_RUNTIME || ! IN_UNI_8_BIT)) {
4020
4021         /* We can convert in place.  The reason we can't if in UNI_8_BIT is to
4022          * make the loop tight, so we overwrite the source with the dest before
4023          * looking at it, and we need to look at the original source
4024          * afterwards.  There would also need to be code added to handle
4025          * switching to not in-place in midstream if we run into characters
4026          * that change the length.
4027          */
4028         dest = source;
4029         s = d = (U8*)SvPV_force_nomg(source, len);
4030         min = len + 1;
4031     } else {
4032         dTARGET;
4033
4034         dest = TARG;
4035
4036         /* The old implementation would copy source into TARG at this point.
4037            This had the side effect that if source was undef, TARG was now
4038            an undefined SV with PADTMP set, and they don't warn inside
4039            sv_2pv_flags(). However, we're now getting the PV direct from
4040            source, which doesn't have PADTMP set, so it would warn. Hence the
4041            little games.  */
4042
4043         if (SvOK(source)) {
4044             s = (const U8*)SvPV_nomg_const(source, len);
4045         } else {
4046             if (ckWARN(WARN_UNINITIALIZED))
4047                 report_uninit(source);
4048             s = (const U8*)"";
4049             len = 0;
4050         }
4051         min = len + 1;
4052
4053         SvUPGRADE(dest, SVt_PV);
4054         d = (U8*)SvGROW(dest, min);
4055         (void)SvPOK_only(dest);
4056
4057         SETs(dest);
4058     }
4059
4060     /* Overloaded values may have toggled the UTF-8 flag on source, so we need
4061        to check DO_UTF8 again here.  */
4062
4063     if (DO_UTF8(source)) {
4064         const U8 *const send = s + len;
4065         U8 tmpbuf[UTF8_MAXBYTES+1];
4066
4067 /* This is ifdefd out because it needs more work and thought.  It isn't clear
4068  * that we should do it.  These are hard-coded rules from the Unicode standard,
4069  * and may change.  5.2 gives new guidance on the iota subscript, for example,
4070  * which has not been checked against this; and secondly it may be that we are
4071  * passed a subset of the context, via a \U...\E, for example, and its not
4072  * clear what the best approach is to that */
4073 #ifdef CONTEXT_DEPENDENT_CASING
4074         bool in_iota_subscript = FALSE;
4075 #endif
4076
4077         while (s < send) {
4078 #ifdef CONTEXT_DEPENDENT_CASING
4079             if (in_iota_subscript && ! is_utf8_mark(s)) {
4080                 /* A non-mark.  Time to output the iota subscript */
4081 #define GREEK_CAPITAL_LETTER_IOTA 0x0399
4082 #define COMBINING_GREEK_YPOGEGRAMMENI 0x0345
4083
4084                 CAT_UNI_TO_UTF8_TWO_BYTE(d, GREEK_CAPITAL_LETTER_IOTA);
4085                 in_iota_subscript = FALSE;
4086             }
4087 #endif
4088
4089
4090 /* See comments at the first instance in this file of this ifdef */
4091 #ifdef GO_AHEAD_AND_BREAK_USER_DEFINED_CASE_MAPPINGS
4092
4093             /* If the UTF-8 character is invariant, then it is in the range
4094              * known by the standard macro; result is only one byte long */
4095             if (UTF8_IS_INVARIANT(*s)) {
4096                 *d++ = toUPPER(*s);
4097                 s++;
4098             }
4099             else if (UTF8_IS_DOWNGRADEABLE_START(*s)) {
4100
4101                 /* Likewise, if it fits in a byte, its case change is in our
4102                  * table */
4103                 U8 orig = UTF8_ACCUMULATE(*s, *(s+1));
4104                 U8 upper = toUPPER_LATIN1_MOD(orig);
4105                 CAT_TWO_BYTE_UNI_UPPER_MOD(d, orig, upper);
4106                 s += 2;
4107             }
4108             else {
4109 #else
4110             {
4111 #endif
4112
4113                 /* Otherwise, need the general UTF-8 case.  Get the changed
4114                  * case value and copy it to the output buffer */
4115
4116                 const STRLEN u = UTF8SKIP(s);
4117                 STRLEN ulen;
4118
4119 #ifndef CONTEXT_DEPENDENT_CASING
4120                 toUPPER_utf8(s, tmpbuf, &ulen);
4121 #else
4122                 const UV uv = toUPPER_utf8(s, tmpbuf, &ulen);
4123                 if (uv == GREEK_CAPITAL_LETTER_IOTA && utf8_to_uvchr(s, 0) == COMBINING_GREEK_YPOGEGRAMMENI) {
4124                     in_iota_subscript = TRUE;
4125                 }
4126                 else {
4127 #endif
4128                     if (ulen > u && (SvLEN(dest) < (min += ulen - u))) {
4129                         /* If the eventually required minimum size outgrows
4130                          * the available space, we need to grow. */
4131                         const UV o = d - (U8*)SvPVX_const(dest);
4132
4133                         /* If someone uppercases one million U+03B0s we
4134                          * SvGROW() one million times.  Or we could try
4135                          * guessing how much to allocate without allocating too
4136                          * much.  Such is life.  See corresponding comment in lc code
4137                          * for another option */
4138                         SvGROW(dest, min);
4139                         d = (U8*)SvPVX(dest) + o;
4140                     }
4141                     Copy(tmpbuf, d, ulen, U8);
4142                     d += ulen;
4143 #ifdef CONTEXT_DEPENDENT_CASING
4144                 }
4145 #endif
4146                 s += u;
4147             }
4148         }
4149 #ifdef CONTEXT_DEPENDENT_CASING
4150         if (in_iota_subscript) CAT_UNI_TO_UTF8_TWO_BYTE(d, GREEK_CAPITAL_LETTER_IOTA);
4151 #endif
4152         SvUTF8_on(dest);
4153         *d = '\0';
4154         SvCUR_set(dest, d - (U8*)SvPVX_const(dest));
4155     } else {    /* Not UTF-8 */
4156         if (len) {
4157             const U8 *const send = s + len;
4158
4159             /* Use locale casing if in locale; regular style if not treating
4160              * latin1 as having case; otherwise the latin1 casing.  Do the
4161              * whole thing in a tight loop, for speed, */
4162             if (IN_LOCALE_RUNTIME) {
4163                 TAINT;
4164                 SvTAINTED_on(dest);
4165                 for (; s < send; d++, s++)
4166                     *d = toUPPER_LC(*s);
4167             }
4168             else if (! IN_UNI_8_BIT) {
4169                 for (; s < send; d++, s++) {
4170                     *d = toUPPER(*s);
4171                 }
4172             }
4173             else {
4174                 for (; s < send; d++, s++) {
4175                     *d = toUPPER_LATIN1_MOD(*s);
4176                     if (*d != LATIN_SMALL_LETTER_Y_WITH_DIAERESIS) continue;
4177
4178                     /* The mainstream case is the tight loop above.  To avoid
4179                      * extra tests in that, all three characters that require
4180                      * special handling are mapped by the MOD to the one tested
4181                      * just above.  
4182                      * Use the source to distinguish between the three cases */
4183
4184                     if (*s == LATIN_SMALL_LETTER_SHARP_S) {
4185
4186                         /* uc() of this requires 2 characters, but they are
4187                          * ASCII.  If not enough room, grow the string */
4188                         if (SvLEN(dest) < ++min) {      
4189                             const UV o = d - (U8*)SvPVX_const(dest);
4190                             SvGROW(dest, min);
4191                             d = (U8*)SvPVX(dest) + o;
4192                         }
4193                         *d++ = 'S'; *d = 'S'; /* upper case is 'SS' */
4194                         continue;   /* Back to the tight loop; still in ASCII */
4195                     }
4196
4197                     /* The other two special handling characters have their
4198                      * upper cases outside the latin1 range, hence need to be
4199                      * in UTF-8, so the whole result needs to be in UTF-8.  So,
4200                      * here we are somewhere in the middle of processing a
4201                      * non-UTF-8 string, and realize that we will have to convert
4202                      * the whole thing to UTF-8.  What to do?  There are
4203                      * several possibilities.  The simplest to code is to
4204                      * convert what we have so far, set a flag, and continue on
4205                      * in the loop.  The flag would be tested each time through
4206                      * the loop, and if set, the next character would be
4207                      * converted to UTF-8 and stored.  But, I (khw) didn't want
4208                      * to slow down the mainstream case at all for this fairly
4209                      * rare case, so I didn't want to add a test that didn't
4210                      * absolutely have to be there in the loop, besides the
4211                      * possibility that it would get too complicated for
4212                      * optimizers to deal with.  Another possibility is to just
4213                      * give up, convert the source to UTF-8, and restart the
4214                      * function that way.  Another possibility is to convert
4215                      * both what has already been processed and what is yet to
4216                      * come separately to UTF-8, then jump into the loop that
4217                      * handles UTF-8.  But the most efficient time-wise of the
4218                      * ones I could think of is what follows, and turned out to
4219                      * not require much extra code.  */
4220
4221                     /* Convert what we have so far into UTF-8, telling the
4222                      * function that we know it should be converted, and to
4223                      * allow extra space for what we haven't processed yet.
4224                      * Assume the worst case space requirements for converting
4225                      * what we haven't processed so far: that it will require
4226                      * two bytes for each remaining source character, plus the
4227                      * NUL at the end.  This may cause the string pointer to
4228                      * move, so re-find it. */
4229
4230                     len = d - (U8*)SvPVX_const(dest);
4231                     SvCUR_set(dest, len);
4232                     len = sv_utf8_upgrade_flags_grow(dest,
4233                                                 SV_GMAGIC|SV_FORCE_UTF8_UPGRADE,
4234                                                 (send -s) * 2 + 1);
4235                     d = (U8*)SvPVX(dest) + len;
4236
4237                     /* And append the current character's upper case in UTF-8 */
4238                     CAT_NON_LATIN1_UC(d, *s);
4239
4240                     /* Now process the remainder of the source, converting to
4241                      * upper and UTF-8.  If a resulting byte is invariant in
4242                      * UTF-8, output it as-is, otherwise convert to UTF-8 and
4243                      * append it to the output. */
4244
4245                     s++;
4246                     for (; s < send; s++) {
4247                         U8 upper = toUPPER_LATIN1_MOD(*s);
4248                         if UTF8_IS_INVARIANT(upper) {
4249                             *d++ = upper;
4250                         }
4251                         else {
4252                             CAT_TWO_BYTE_UNI_UPPER_MOD(d, *s, upper);
4253                         }
4254                     }
4255
4256                     /* Here have processed the whole source; no need to continue
4257                      * with the outer loop.  Each character has been converted
4258                      * to upper case and converted to UTF-8 */
4259
4260                     break;
4261                 } /* End of processing all latin1-style chars */
4262             } /* End of processing all chars */
4263         } /* End of source is not empty */
4264
4265         if (source != dest) {
4266             *d = '\0';  /* Here d points to 1 after last char, add NUL */
4267             SvCUR_set(dest, d - (U8*)SvPVX_const(dest));
4268         }
4269     } /* End of isn't utf8 */
4270     SvSETMAGIC(dest);
4271     RETURN;
4272 }
4273
4274 PP(pp_lc)
4275 {
4276     dVAR;
4277     dSP;
4278     SV *source = TOPs;
4279     STRLEN len;
4280     STRLEN min;
4281     SV *dest;
4282     const U8 *s;
4283     U8 *d;
4284
4285     SvGETMAGIC(source);
4286
4287     if (SvPADTMP(source) && !SvREADONLY(source) && !SvAMAGIC(source)
4288         && SvTEMP(source) && !DO_UTF8(source)) {
4289
4290         /* We can convert in place, as lowercasing anything in the latin1 range
4291          * (or else DO_UTF8 would have been on) doesn't lengthen it */
4292         dest = source;
4293         s = d = (U8*)SvPV_force_nomg(source, len);
4294         min = len + 1;
4295     } else {
4296         dTARGET;
4297
4298         dest = TARG;
4299
4300         /* The old implementation would copy source into TARG at this point.
4301            This had the side effect that if source was undef, TARG was now
4302            an undefined SV with PADTMP set, and they don't warn inside
4303            sv_2pv_flags(). However, we're now getting the PV direct from
4304            source, which doesn't have PADTMP set, so it would warn. Hence the
4305            little games.  */
4306
4307         if (SvOK(source)) {
4308             s = (const U8*)SvPV_nomg_const(source, len);
4309         } else {
4310             if (ckWARN(WARN_UNINITIALIZED))
4311                 report_uninit(source);
4312             s = (const U8*)"";
4313             len = 0;
4314         }
4315         min = len + 1;
4316
4317         SvUPGRADE(dest, SVt_PV);
4318         d = (U8*)SvGROW(dest, min);
4319         (void)SvPOK_only(dest);
4320
4321         SETs(dest);
4322     }
4323
4324     /* Overloaded values may have toggled the UTF-8 flag on source, so we need
4325        to check DO_UTF8 again here.  */
4326
4327     if (DO_UTF8(source)) {
4328         const U8 *const send = s + len;
4329         U8 tmpbuf[UTF8_MAXBYTES_CASE+1];
4330
4331         while (s < send) {
4332 /* See comments at the first instance in this file of this ifdef */
4333 #ifdef GO_AHEAD_AND_BREAK_USER_DEFINED_CASE_MAPPINGS
4334             if (UTF8_IS_INVARIANT(*s)) {
4335
4336                 /* Invariant characters use the standard mappings compiled in.
4337                  */
4338                 *d++ = toLOWER(*s);
4339                 s++;
4340             }
4341             else if (UTF8_IS_DOWNGRADEABLE_START(*s)) {
4342
4343                 /* As do the ones in the Latin1 range */
4344                 U8 lower = toLOWER_LATIN1(UTF8_ACCUMULATE(*s, *(s+1)));
4345                 CAT_UNI_TO_UTF8_TWO_BYTE(d, lower);
4346                 s += 2;
4347             }
4348             else {
4349 #endif
4350                 /* Here, is utf8 not in Latin-1 range, have to go out and get
4351                  * the mappings from the tables. */
4352
4353                 const STRLEN u = UTF8SKIP(s);
4354                 STRLEN ulen;
4355
4356 /* See comments at the first instance in this file of this ifdef */
4357 #ifndef CONTEXT_DEPENDENT_CASING
4358                 toLOWER_utf8(s, tmpbuf, &ulen);
4359 #else
4360                 /* Here is context dependent casing, not compiled in currently;
4361                  * needs more thought and work */
4362
4363                 const UV uv = toLOWER_utf8(s, tmpbuf, &ulen);
4364
4365                 /* If the lower case is a small sigma, it may be that we need
4366                  * to change it to a final sigma.  This happens at the end of 
4367                  * a word that contains more than just this character, and only
4368                  * when we started with a capital sigma. */
4369                 if (uv == UNICODE_GREEK_SMALL_LETTER_SIGMA &&
4370                     s > send - len &&   /* Makes sure not the first letter */
4371                     utf8_to_uvchr(s, 0) == UNICODE_GREEK_CAPITAL_LETTER_SIGMA
4372                 ) {
4373
4374                     /* We use the algorithm in:
4375                      * http://www.unicode.org/versions/Unicode5.0.0/ch03.pdf (C
4376                      * is a CAPITAL SIGMA): If C is preceded by a sequence
4377                      * consisting of a cased letter and a case-ignorable
4378                      * sequence, and C is not followed by a sequence consisting
4379                      * of a case ignorable sequence and then a cased letter,
4380                      * then when lowercasing C, C becomes a final sigma */
4381
4382                     /* To determine if this is the end of a word, need to peek
4383                      * ahead.  Look at the next character */
4384                     const U8 *peek = s + u;
4385
4386                     /* Skip any case ignorable characters */
4387                     while (peek < send && is_utf8_case_ignorable(peek)) {
4388                         peek += UTF8SKIP(peek);
4389                     }
4390
4391                     /* If we reached the end of the string without finding any
4392                      * non-case ignorable characters, or if the next such one
4393                      * is not-cased, then we have met the conditions for it
4394                      * being a final sigma with regards to peek ahead, and so
4395                      * must do peek behind for the remaining conditions. (We
4396                      * know there is stuff behind to look at since we tested
4397                      * above that this isn't the first letter) */
4398                     if (peek >= send || ! is_utf8_cased(peek)) {
4399                         peek = utf8_hop(s, -1);
4400
4401                         /* Here are at the beginning of the first character
4402                          * before the original upper case sigma.  Keep backing
4403                          * up, skipping any case ignorable characters */
4404                         while (is_utf8_case_ignorable(peek)) {
4405                             peek = utf8_hop(peek, -1);
4406                         }
4407
4408                         /* Here peek points to the first byte of the closest
4409                          * non-case-ignorable character before the capital
4410                          * sigma.  If it is cased, then by the Unicode
4411                          * algorithm, we should use a small final sigma instead
4412                          * of what we have */
4413                         if (is_utf8_cased(peek)) {
4414                             STORE_UNI_TO_UTF8_TWO_BYTE(tmpbuf,
4415                                         UNICODE_GREEK_SMALL_LETTER_FINAL_SIGMA);
4416                         }
4417                     }
4418                 }
4419                 else {  /* Not a context sensitive mapping */
4420 #endif  /* End of commented out context sensitive */
4421                     if (ulen > u && (SvLEN(dest) < (min += ulen - u))) {
4422
4423                         /* If the eventually required minimum size outgrows
4424                          * the available space, we need to grow. */
4425                         const UV o = d - (U8*)SvPVX_const(dest);
4426
4427                         /* If someone lowercases one million U+0130s we
4428                          * SvGROW() one million times.  Or we could try
4429                          * guessing how much to allocate without allocating too
4430                          * much.  Such is life.  Another option would be to
4431                          * grow an extra byte or two more each time we need to
4432                          * grow, which would cut down the million to 500K, with
4433                          * little waste */
4434                         SvGROW(dest, min);
4435                         d = (U8*)SvPVX(dest) + o;
4436                     }
4437 #ifdef CONTEXT_DEPENDENT_CASING
4438                 }
4439 #endif
4440                 /* Copy the newly lowercased letter to the output buffer we're
4441                  * building */
4442                 Copy(tmpbuf, d, ulen, U8);
4443                 d += ulen;
4444                 s += u;
4445 #ifdef GO_AHEAD_AND_BREAK_USER_DEFINED_CASE_MAPPINGS
4446             }
4447 #endif
4448         }   /* End of looping through the source string */
4449         SvUTF8_on(dest);
4450         *d = '\0';
4451         SvCUR_set(dest, d - (U8*)SvPVX_const(dest));
4452     } else {    /* Not utf8 */
4453         if (len) {
4454             const U8 *const send = s + len;
4455
4456             /* Use locale casing if in locale; regular style if not treating
4457              * latin1 as having case; otherwise the latin1 casing.  Do the
4458              * whole thing in a tight loop, for speed, */
4459             if (IN_LOCALE_RUNTIME) {
4460                 TAINT;
4461                 SvTAINTED_on(dest);
4462                 for (; s < send; d++, s++)
4463                     *d = toLOWER_LC(*s);
4464             }
4465             else if (! IN_UNI_8_BIT) {
4466                 for (; s < send; d++, s++) {
4467                     *d = toLOWER(*s);
4468                 }
4469             }
4470             else {
4471                 for (; s < send; d++, s++) {
4472                     *d = toLOWER_LATIN1(*s);
4473                 }
4474             }
4475         }
4476         if (source != dest) {
4477             *d = '\0';
4478             SvCUR_set(dest, d - (U8*)SvPVX_const(dest));
4479         }
4480     }
4481     SvSETMAGIC(dest);
4482     RETURN;
4483 }
4484
4485 PP(pp_quotemeta)
4486 {
4487     dVAR; dSP; dTARGET;
4488     SV * const sv = TOPs;
4489     STRLEN len;
4490     register const char *s = SvPV_const(sv,len);
4491
4492     SvUTF8_off(TARG);                           /* decontaminate */
4493     if (len) {
4494         register char *d;
4495         SvUPGRADE(TARG, SVt_PV);
4496         SvGROW(TARG, (len * 2) + 1);
4497         d = SvPVX(TARG);
4498         if (DO_UTF8(sv)) {
4499             while (len) {
4500                 if (UTF8_IS_CONTINUED(*s)) {
4501                     STRLEN ulen = UTF8SKIP(s);
4502                     if (ulen > len)
4503                         ulen = len;
4504                     len -= ulen;
4505                     while (ulen--)
4506                         *d++ = *s++;
4507                 }
4508                 else {
4509                     if (!isALNUM(*s))
4510                         *d++ = '\\';
4511                     *d++ = *s++;
4512                     len--;
4513                 }
4514             }
4515             SvUTF8_on(TARG);
4516         }
4517         else {
4518             while (len--) {
4519                 if (!isALNUM(*s))
4520                     *d++ = '\\';
4521                 *d++ = *s++;
4522             }
4523         }
4524         *d = '\0';
4525         SvCUR_set(TARG, d - SvPVX_const(TARG));
4526         (void)SvPOK_only_UTF8(TARG);
4527     }
4528     else
4529         sv_setpvn(TARG, s, len);
4530     SETTARG;
4531     RETURN;
4532 }
4533
4534 /* Arrays. */
4535
4536 PP(pp_aslice)
4537 {
4538     dVAR; dSP; dMARK; dORIGMARK;
4539     register AV *const av = MUTABLE_AV(POPs);
4540     register const I32 lval = (PL_op->op_flags & OPf_MOD || LVRET);
4541
4542     if (SvTYPE(av) == SVt_PVAV) {
4543         const I32 arybase = CopARYBASE_get(PL_curcop);
4544         const bool localizing = PL_op->op_private & OPpLVAL_INTRO;
4545         bool can_preserve = FALSE;
4546
4547         if (localizing) {
4548             MAGIC *mg;
4549             HV *stash;
4550
4551             can_preserve = SvCANEXISTDELETE(av);
4552         }
4553
4554         if (lval && localizing) {
4555             register SV **svp;
4556             I32 max = -1;
4557             for (svp = MARK + 1; svp <= SP; svp++) {
4558                 const I32 elem = SvIV(*svp);
4559                 if (elem > max)
4560                     max = elem;
4561             }
4562             if (max > AvMAX(av))
4563                 av_extend(av, max);
4564         }
4565
4566         while (++MARK <= SP) {
4567             register SV **svp;
4568             I32 elem = SvIV(*MARK);
4569             bool preeminent = TRUE;
4570
4571             if (elem > 0)
4572                 elem -= arybase;
4573             if (localizing && can_preserve) {
4574                 /* If we can determine whether the element exist,
4575                  * Try to preserve the existenceness of a tied array
4576                  * element by using EXISTS and DELETE if possible.
4577                  * Fallback to FETCH and STORE otherwise. */
4578                 preeminent = av_exists(av, elem);
4579             }
4580
4581             svp = av_fetch(av, elem, lval);
4582             if (lval) {
4583                 if (!svp || *svp == &PL_sv_undef)
4584                     DIE(aTHX_ PL_no_aelem, elem);
4585                 if (localizing) {
4586                     if (preeminent)
4587                         save_aelem(av, elem, svp);
4588                     else
4589                         SAVEADELETE(av, elem);
4590                 }
4591             }
4592             *MARK = svp ? *svp : &PL_sv_undef;
4593         }
4594     }
4595     if (GIMME != G_ARRAY) {
4596         MARK = ORIGMARK;
4597         *++MARK = SP > ORIGMARK ? *SP : &PL_sv_undef;
4598         SP = MARK;
4599     }
4600     RETURN;
4601 }
4602
4603 PP(pp_aeach)
4604 {
4605     dVAR;
4606     dSP;
4607     AV *array = MUTABLE_AV(POPs);
4608     const I32 gimme = GIMME_V;
4609     IV *iterp = Perl_av_iter_p(aTHX_ array);
4610     const IV current = (*iterp)++;
4611
4612     if (current > av_len(array)) {
4613         *iterp = 0;
4614         if (gimme == G_SCALAR)
4615             RETPUSHUNDEF;
4616         else
4617             RETURN;
4618     }
4619
4620     EXTEND(SP, 2);
4621     mPUSHi(CopARYBASE_get(PL_curcop) + current);
4622     if (gimme == G_ARRAY) {
4623         SV **const element = av_fetch(array, current, 0);
4624         PUSHs(element ? *element : &PL_sv_undef);
4625     }
4626     RETURN;
4627 }
4628
4629 PP(pp_akeys)
4630 {
4631     dVAR;
4632     dSP;
4633     AV *array = MUTABLE_AV(POPs);
4634     const I32 gimme = GIMME_V;
4635
4636     *Perl_av_iter_p(aTHX_ array) = 0;
4637
4638     if (gimme == G_SCALAR) {
4639         dTARGET;
4640         PUSHi(av_len(array) + 1);
4641     }
4642     else if (gimme == G_ARRAY) {
4643         IV n = Perl_av_len(aTHX_ array);
4644         IV i = CopARYBASE_get(PL_curcop);
4645
4646         EXTEND(SP, n + 1);
4647
4648         if (PL_op->op_type == OP_AKEYS) {
4649             n += i;
4650             for (;  i <= n;  i++) {
4651                 mPUSHi(i);
4652             }
4653         }
4654         else {
4655             for (i = 0;  i <= n;  i++) {
4656                 SV *const *const elem = Perl_av_fetch(aTHX_ array, i, 0);
4657                 PUSHs(elem ? *elem : &PL_sv_undef);
4658             }
4659         }
4660     }
4661     RETURN;
4662 }
4663
4664 /* Associative arrays. */
4665
4666 PP(pp_each)
4667 {
4668     dVAR;
4669     dSP;
4670     HV * hash = MUTABLE_HV(POPs);
4671     HE *entry;
4672     const I32 gimme = GIMME_V;
4673
4674     PUTBACK;
4675     /* might clobber stack_sp */
4676     entry = hv_iternext(hash);
4677     SPAGAIN;
4678
4679     EXTEND(SP, 2);
4680     if (entry) {
4681         SV* const sv = hv_iterkeysv(entry);
4682         PUSHs(sv);      /* won't clobber stack_sp */
4683         if (gimme == G_ARRAY) {
4684             SV *val;
4685             PUTBACK;
4686             /* might clobber stack_sp */
4687             val = hv_iterval(hash, entry);
4688             SPAGAIN;
4689             PUSHs(val);
4690         }
4691     }
4692     else if (gimme == G_SCALAR)
4693         RETPUSHUNDEF;
4694
4695     RETURN;
4696 }
4697
4698 STATIC OP *
4699 S_do_delete_local(pTHX)
4700 {
4701     dVAR;
4702     dSP;
4703     const I32 gimme = GIMME_V;
4704     const MAGIC *mg;
4705     HV *stash;
4706
4707     if (PL_op->op_private & OPpSLICE) {
4708         dMARK; dORIGMARK;
4709         SV * const osv = POPs;
4710         const bool tied = SvRMAGICAL(osv)
4711                             && mg_find((const SV *)osv, PERL_MAGIC_tied);
4712         const bool can_preserve = SvCANEXISTDELETE(osv)
4713                                     || mg_find((const SV *)osv, PERL_MAGIC_env);
4714         const U32 type = SvTYPE(osv);
4715         if (type == SVt_PVHV) {                 /* hash element */
4716             HV * const hv = MUTABLE_HV(osv);
4717             while (++MARK <= SP) {
4718                 SV * const keysv = *MARK;
4719                 SV *sv = NULL;
4720                 bool preeminent = TRUE;
4721                 if (can_preserve)
4722                     preeminent = hv_exists_ent(hv, keysv, 0);
4723                 if (tied) {
4724                     HE *he = hv_fetch_ent(hv, keysv, 1, 0);
4725                     if (he)
4726                         sv = HeVAL(he);
4727                     else
4728                         preeminent = FALSE;
4729                 }
4730                 else {
4731                     sv = hv_delete_ent(hv, keysv, 0, 0);
4732                     SvREFCNT_inc_simple_void(sv); /* De-mortalize */
4733                 }
4734                 if (preeminent) {
4735                     save_helem_flags(hv, keysv, &sv, SAVEf_KEEPOLDELEM);
4736                     if (tied) {
4737                         *MARK = sv_mortalcopy(sv);
4738                         mg_clear(sv);
4739                     } else
4740                         *MARK = sv;
4741                 }
4742                 else {
4743                     SAVEHDELETE(hv, keysv);
4744                     *MARK = &PL_sv_undef;
4745                 }
4746             }
4747         }
4748         else if (type == SVt_PVAV) {                  /* array element */
4749             if (PL_op->op_flags & OPf_SPECIAL) {
4750                 AV * const av = MUTABLE_AV(osv);
4751                 while (++MARK <= SP) {
4752                     I32 idx = SvIV(*MARK);
4753                     SV *sv = NULL;
4754                     bool preeminent = TRUE;
4755                     if (can_preserve)
4756                         preeminent = av_exists(av, idx);
4757                     if (tied) {
4758                         SV **svp = av_fetch(av, idx, 1);
4759                         if (svp)
4760                             sv = *svp;
4761                         else
4762                             preeminent = FALSE;
4763                     }
4764                     else {
4765                         sv = av_delete(av, idx, 0);
4766                         SvREFCNT_inc_simple_void(sv); /* De-mortalize */
4767                     }
4768                     if (preeminent) {
4769                         save_aelem_flags(av, idx, &sv, SAVEf_KEEPOLDELEM);
4770                         if (tied) {
4771                             *MARK = sv_mortalcopy(sv);
4772                             mg_clear(sv);
4773                         } else
4774                             *MARK = sv;
4775                     }
4776                     else {
4777                         SAVEADELETE(av, idx);
4778                         *MARK = &PL_sv_undef;
4779                     }
4780                 }
4781             }
4782         }
4783         else
4784             DIE(aTHX_ "Not a HASH reference");
4785         if (gimme == G_VOID)
4786             SP = ORIGMARK;
4787         else if (gimme == G_SCALAR) {
4788             MARK = ORIGMARK;
4789             if (SP > MARK)
4790                 *++MARK = *SP;
4791             else
4792                 *++MARK = &PL_sv_undef;
4793             SP = MARK;
4794         }
4795     }
4796     else {
4797         SV * const keysv = POPs;
4798         SV * const osv   = POPs;
4799         const bool tied = SvRMAGICAL(osv)
4800                             && mg_find((const SV *)osv, PERL_MAGIC_tied);
4801         const bool can_preserve = SvCANEXISTDELETE(osv)
4802                                     || mg_find((const SV *)osv, PERL_MAGIC_env);
4803         const U32 type = SvTYPE(osv);
4804         SV *sv = NULL;
4805         if (type == SVt_PVHV) {
4806             HV * const hv = MUTABLE_HV(osv);
4807             bool preeminent = TRUE;
4808             if (can_preserve)
4809                 preeminent = hv_exists_ent(hv, keysv, 0);
4810             if (tied) {
4811                 HE *he = hv_fetch_ent(hv, keysv, 1, 0);
4812                 if (he)
4813                     sv = HeVAL(he);
4814                 else
4815                     preeminent = FALSE;
4816             }
4817             else {
4818                 sv = hv_delete_ent(hv, keysv, 0, 0);
4819                 SvREFCNT_inc_simple_void(sv); /* De-mortalize */
4820             }
4821             if (preeminent) {
4822                 save_helem_flags(hv, keysv, &sv, SAVEf_KEEPOLDELEM);
4823                 if (tied) {
4824                     SV *nsv = sv_mortalcopy(sv);
4825                     mg_clear(sv);
4826                     sv = nsv;
4827                 }
4828             }
4829             else
4830                 SAVEHDELETE(hv, keysv);
4831         }
4832         else if (type == SVt_PVAV) {
4833             if (PL_op->op_flags & OPf_SPECIAL) {
4834                 AV * const av = MUTABLE_AV(osv);
4835                 I32 idx = SvIV(keysv);
4836                 bool preeminent = TRUE;
4837                 if (can_preserve)
4838                     preeminent = av_exists(av, idx);
4839                 if (tied) {
4840                     SV **svp = av_fetch(av, idx, 1);
4841                     if (svp)
4842                         sv = *svp;
4843                     else
4844                         preeminent = FALSE;
4845                 }
4846                 else {
4847                     sv = av_delete(av, idx, 0);
4848                     SvREFCNT_inc_simple_void(sv); /* De-mortalize */
4849                 }
4850                 if (preeminent) {
4851                     save_aelem_flags(av, idx, &sv, SAVEf_KEEPOLDELEM);
4852                     if (tied) {
4853                         SV *nsv = sv_mortalcopy(sv);
4854                         mg_clear(sv);
4855                         sv = nsv;
4856                     }
4857                 }
4858                 else
4859                     SAVEADELETE(av, idx);
4860             }
4861             else
4862                 DIE(aTHX_ "panic: avhv_delete no longer supported");
4863         }
4864         else
4865             DIE(aTHX_ "Not a HASH reference");
4866         if (!sv)
4867             sv = &PL_sv_undef;
4868         if (gimme != G_VOID)
4869             PUSHs(sv);
4870     }
4871
4872     RETURN;
4873 }
4874
4875 PP(pp_delete)
4876 {
4877     dVAR;
4878     dSP;
4879     I32 gimme;
4880     I32 discard;
4881
4882     if (PL_op->op_private & OPpLVAL_INTRO)
4883         return do_delete_local();
4884
4885     gimme = GIMME_V;
4886     discard = (gimme == G_VOID) ? G_DISCARD : 0;
4887
4888     if (PL_op->op_private & OPpSLICE) {
4889         dMARK; dORIGMARK;
4890         HV * const hv = MUTABLE_HV(POPs);
4891         const U32 hvtype = SvTYPE(hv);
4892         if (hvtype == SVt_PVHV) {                       /* hash element */
4893             while (++MARK <= SP) {
4894                 SV * const sv = hv_delete_ent(hv, *MARK, discard, 0);
4895                 *MARK = sv ? sv : &PL_sv_undef;
4896             }
4897         }
4898         else if (hvtype == SVt_PVAV) {                  /* array element */
4899             if (PL_op->op_flags & OPf_SPECIAL) {
4900                 while (++MARK <= SP) {
4901                     SV * const sv = av_delete(MUTABLE_AV(hv), SvIV(*MARK), discard);
4902                     *MARK = sv ? sv : &PL_sv_undef;
4903                 }
4904             }
4905         }
4906         else
4907             DIE(aTHX_ "Not a HASH reference");
4908         if (discard)
4909             SP = ORIGMARK;
4910         else if (gimme == G_SCALAR) {
4911             MARK = ORIGMARK;
4912             if (SP > MARK)
4913                 *++MARK = *SP;
4914             else
4915                 *++MARK = &PL_sv_undef;
4916             SP = MARK;
4917         }
4918     }
4919     else {
4920         SV *keysv = POPs;
4921         HV * const hv = MUTABLE_HV(POPs);
4922         SV *sv = NULL;
4923         if (SvTYPE(hv) == SVt_PVHV)
4924             sv = hv_delete_ent(hv, keysv, discard, 0);
4925         else if (SvTYPE(hv) == SVt_PVAV) {
4926             if (PL_op->op_flags & OPf_SPECIAL)
4927                 sv = av_delete(MUTABLE_AV(hv), SvIV(keysv), discard);
4928             else
4929                 DIE(aTHX_ "panic: avhv_delete no longer supported");
4930         }
4931         else
4932             DIE(aTHX_ "Not a HASH reference");
4933         if (!sv)
4934             sv = &PL_sv_undef;
4935         if (!discard)
4936             PUSHs(sv);
4937     }
4938     RETURN;
4939 }
4940
4941 PP(pp_exists)
4942 {
4943     dVAR;
4944     dSP;
4945     SV *tmpsv;
4946     HV *hv;
4947
4948     if (PL_op->op_private & OPpEXISTS_SUB) {
4949         GV *gv;
4950         SV * const sv = POPs;
4951         CV * const cv = sv_2cv(sv, &hv, &gv, 0);
4952         if (cv)
4953             RETPUSHYES;
4954         if (gv && isGV(gv) && GvCV(gv) && !GvCVGEN(gv))
4955             RETPUSHYES;
4956         RETPUSHNO;
4957     }
4958     tmpsv = POPs;
4959     hv = MUTABLE_HV(POPs);
4960     if (SvTYPE(hv) == SVt_PVHV) {
4961         if (hv_exists_ent(hv, tmpsv, 0))
4962             RETPUSHYES;
4963     }
4964     else if (SvTYPE(hv) == SVt_PVAV) {
4965         if (PL_op->op_flags & OPf_SPECIAL) {            /* array element */
4966             if (av_exists(MUTABLE_AV(hv), SvIV(tmpsv)))
4967                 RETPUSHYES;
4968         }
4969     }
4970     else {
4971         DIE(aTHX_ "Not a HASH reference");
4972     }
4973     RETPUSHNO;
4974 }
4975
4976 PP(pp_hslice)
4977 {
4978     dVAR; dSP; dMARK; dORIGMARK;
4979     register HV * const hv = MUTABLE_HV(POPs);
4980     register const I32 lval = (PL_op->op_flags & OPf_MOD || LVRET);
4981     const bool localizing = PL_op->op_private & OPpLVAL_INTRO;
4982     bool can_preserve = FALSE;
4983
4984     if (localizing) {
4985         MAGIC *mg;
4986         HV *stash;
4987
4988         if (SvCANEXISTDELETE(hv) || mg_find((const SV *)hv, PERL_MAGIC_env))
4989             can_preserve = TRUE;
4990     }
4991
4992     while (++MARK <= SP) {
4993         SV * const keysv = *MARK;
4994         SV **svp;
4995         HE *he;
4996         bool preeminent = TRUE;
4997
4998         if (localizing && can_preserve) {
4999             /* If we can determine whether the element exist,
5000              * try to preserve the existenceness of a tied hash
5001              * element by using EXISTS and DELETE if possible.
5002              * Fallback to FETCH and STORE otherwise. */
5003             preeminent = hv_exists_ent(hv, keysv, 0);
5004         }
5005
5006         he = hv_fetch_ent(hv, keysv, lval, 0);
5007         svp = he ? &HeVAL(he) : NULL;
5008
5009         if (lval) {
5010             if (!svp || *svp == &PL_sv_undef) {
5011                 DIE(aTHX_ PL_no_helem_sv, SVfARG(keysv));
5012             }
5013             if (localizing) {
5014                 if (HvNAME_get(hv) && isGV(*svp))
5015                     save_gp(MUTABLE_GV(*svp), !(PL_op->op_flags & OPf_SPECIAL));
5016                 else if (preeminent)
5017                     save_helem_flags(hv, keysv, svp,
5018                          (PL_op->op_flags & OPf_SPECIAL) ? 0 : SAVEf_SETMAGIC);
5019                 else
5020                     SAVEHDELETE(hv, keysv);
5021             }
5022         }
5023         *MARK = svp ? *svp : &PL_sv_undef;
5024     }
5025     if (GIMME != G_ARRAY) {
5026         MARK = ORIGMARK;
5027         *++MARK = SP > ORIGMARK ? *SP : &PL_sv_undef;
5028         SP = MARK;
5029     }
5030     RETURN;
5031 }
5032
5033 /* List operators. */
5034
5035 PP(pp_list)
5036 {
5037     dVAR; dSP; dMARK;
5038     if (GIMME != G_ARRAY) {
5039         if (++MARK <= SP)
5040             *MARK = *SP;                /* unwanted list, return last item */
5041         else
5042             *MARK = &PL_sv_undef;
5043         SP = MARK;
5044     }
5045     RETURN;
5046 }
5047
5048 PP(pp_lslice)
5049 {
5050     dVAR;
5051     dSP;
5052     SV ** const lastrelem = PL_stack_sp;
5053     SV ** const lastlelem = PL_stack_base + POPMARK;
5054     SV ** const firstlelem = PL_stack_base + POPMARK + 1;
5055     register SV ** const firstrelem = lastlelem + 1;
5056     const I32 arybase = CopARYBASE_get(PL_curcop);
5057     I32 is_something_there = FALSE;
5058
5059     register const I32 max = lastrelem - lastlelem;
5060     register SV **lelem;
5061
5062     if (GIMME != G_ARRAY) {
5063         I32 ix = SvIV(*lastlelem);
5064         if (ix < 0)
5065             ix += max;
5066         else
5067             ix -= arybase;
5068         if (ix < 0 || ix >= max)
5069             *firstlelem = &PL_sv_undef;
5070         else
5071             *firstlelem = firstrelem[ix];
5072         SP = firstlelem;
5073         RETURN;
5074     }
5075
5076     if (max == 0) {
5077         SP = firstlelem - 1;
5078         RETURN;
5079     }
5080
5081     for (lelem = firstlelem; lelem <= lastlelem; lelem++) {
5082         I32 ix = SvIV(*lelem);
5083         if (ix < 0)
5084             ix += max;
5085         else
5086             ix -= arybase;
5087         if (ix < 0 || ix >= max)
5088             *lelem = &PL_sv_undef;
5089         else {
5090             is_something_there = TRUE;
5091             if (!(*lelem = firstrelem[ix]))
5092                 *lelem = &PL_sv_undef;
5093         }
5094     }
5095     if (is_something_there)
5096         SP = lastlelem;
5097     else
5098         SP = firstlelem - 1;
5099     RETURN;
5100 }
5101
5102 PP(pp_anonlist)
5103 {
5104     dVAR; dSP; dMARK; dORIGMARK;
5105     const I32 items = SP - MARK;
5106     SV * const av = MUTABLE_SV(av_make(items, MARK+1));
5107     SP = ORIGMARK;              /* av_make() might realloc stack_sp */
5108     mXPUSHs((PL_op->op_flags & OPf_SPECIAL)
5109             ? newRV_noinc(av) : av);
5110     RETURN;
5111 }
5112
5113 PP(pp_anonhash)
5114 {
5115     dVAR; dSP; dMARK; dORIGMARK;
5116     HV* const hv = newHV();
5117
5118     while (MARK < SP) {
5119         SV * const key = *++MARK;
5120         SV * const val = newSV(0);
5121         if (MARK < SP)
5122             sv_setsv(val, *++MARK);
5123         else
5124             Perl_ck_warner(aTHX_ packWARN(WARN_MISC), "Odd number of elements in anonymous hash");
5125         (void)hv_store_ent(hv,key,val,0);
5126     }
5127     SP = ORIGMARK;
5128     mXPUSHs((PL_op->op_flags & OPf_SPECIAL)
5129             ? newRV_noinc(MUTABLE_SV(hv)) : MUTABLE_SV(hv));
5130     RETURN;
5131 }
5132
5133 PP(pp_splice)
5134 {
5135     dVAR; dSP; dMARK; dORIGMARK;
5136     register AV *ary = MUTABLE_AV(*++MARK);
5137     register SV **src;
5138     register SV **dst;
5139     register I32 i;
5140     register I32 offset;
5141     register I32 length;
5142     I32 newlen;
5143     I32 after;
5144     I32 diff;
5145     const MAGIC * const mg = SvTIED_mg((const SV *)ary, PERL_MAGIC_tied);
5146
5147     if (mg) {
5148         *MARK-- = SvTIED_obj(MUTABLE_SV(ary), mg);
5149         PUSHMARK(MARK);
5150         PUTBACK;
5151         ENTER_with_name("call_SPLICE");
5152         call_method("SPLICE",GIMME_V);
5153         LEAVE_with_name("call_SPLICE");
5154         SPAGAIN;
5155         RETURN;
5156     }
5157
5158     SP++;
5159
5160     if (++MARK < SP) {
5161         offset = i = SvIV(*MARK);
5162         if (offset < 0)
5163             offset += AvFILLp(ary) + 1;
5164         else
5165             offset -= CopARYBASE_get(PL_curcop);
5166         if (offset < 0)
5167             DIE(aTHX_ PL_no_aelem, i);
5168         if (++MARK < SP) {
5169             length = SvIVx(*MARK++);
5170             if (length < 0) {
5171                 length += AvFILLp(ary) - offset + 1;
5172                 if (length < 0)
5173                     length = 0;
5174             }
5175         }
5176         else
5177             length = AvMAX(ary) + 1;            /* close enough to infinity */
5178     }
5179     else {
5180         offset = 0;
5181         length = AvMAX(ary) + 1;
5182     }
5183     if (offset > AvFILLp(ary) + 1) {
5184         Perl_ck_warner(aTHX_ packWARN(WARN_MISC), "splice() offset past end of array" );
5185         offset = AvFILLp(ary) + 1;
5186     }
5187     after = AvFILLp(ary) + 1 - (offset + length);
5188     if (after < 0) {                            /* not that much array */
5189         length += after;                        /* offset+length now in array */
5190         after = 0;
5191         if (!AvALLOC(ary))
5192             av_extend(ary, 0);
5193     }
5194
5195     /* At this point, MARK .. SP-1 is our new LIST */
5196
5197     newlen = SP - MARK;
5198     diff = newlen - length;
5199     if (newlen && !AvREAL(ary) && AvREIFY(ary))
5200         av_reify(ary);
5201
5202     /* make new elements SVs now: avoid problems if they're from the array */
5203     for (dst = MARK, i = newlen; i; i--) {
5204         SV * const h = *dst;
5205         *dst++ = newSVsv(h);
5206     }
5207
5208     if (diff < 0) {                             /* shrinking the area */
5209         SV **tmparyval = NULL;
5210         if (newlen) {
5211             Newx(tmparyval, newlen, SV*);       /* so remember insertion */
5212             Copy(MARK, tmparyval, newlen, SV*);
5213         }
5214
5215         MARK = ORIGMARK + 1;
5216         if (GIMME == G_ARRAY) {                 /* copy return vals to stack */
5217             MEXTEND(MARK, length);
5218             Copy(AvARRAY(ary)+offset, MARK, length, SV*);
5219             if (AvREAL(ary)) {
5220                 EXTEND_MORTAL(length);
5221                 for (i = length, dst = MARK; i; i--) {
5222                     sv_2mortal(*dst);   /* free them eventualy */
5223                     dst++;
5224                 }
5225             }
5226             MARK += length - 1;
5227         }
5228         else {
5229             *MARK = AvARRAY(ary)[offset+length-1];
5230             if (AvREAL(ary)) {
5231                 sv_2mortal(*MARK);
5232                 for (i = length - 1, dst = &AvARRAY(ary)[offset]; i > 0; i--)
5233                     SvREFCNT_dec(*dst++);       /* free them now */
5234             }
5235         }
5236         AvFILLp(ary) += diff;
5237
5238         /* pull up or down? */
5239
5240         if (offset < after) {                   /* easier to pull up */
5241             if (offset) {                       /* esp. if nothing to pull */
5242                 src = &AvARRAY(ary)[offset-1];
5243                 dst = src - diff;               /* diff is negative */
5244                 for (i = offset; i > 0; i--)    /* can't trust Copy */
5245                     *dst-- = *src--;
5246             }
5247             dst = AvARRAY(ary);
5248             AvARRAY(ary) = AvARRAY(ary) - diff; /* diff is negative */
5249             AvMAX(ary) += diff;
5250         }
5251         else {
5252             if (after) {                        /* anything to pull down? */
5253                 src = AvARRAY(ary) + offset + length;
5254                 dst = src + diff;               /* diff is negative */
5255                 Move(src, dst, after, SV*);
5256             }
5257             dst = &AvARRAY(ary)[AvFILLp(ary)+1];
5258                                                 /* avoid later double free */
5259         }
5260         i = -diff;
5261         while (i)
5262             dst[--i] = &PL_sv_undef;
5263         
5264         if (newlen) {
5265             Copy( tmparyval, AvARRAY(ary) + offset, newlen, SV* );
5266             Safefree(tmparyval);
5267         }
5268     }
5269     else {                                      /* no, expanding (or same) */
5270         SV** tmparyval = NULL;
5271         if (length) {
5272             Newx(tmparyval, length, SV*);       /* so remember deletion */
5273             Copy(AvARRAY(ary)+offset, tmparyval, length, SV*);
5274         }
5275
5276         if (diff > 0) {                         /* expanding */
5277             /* push up or down? */
5278             if (offset < after && diff <= AvARRAY(ary) - AvALLOC(ary)) {
5279                 if (offset) {
5280                     src = AvARRAY(ary);
5281                     dst = src - diff;
5282                     Move(src, dst, offset, SV*);
5283                 }
5284                 AvARRAY(ary) = AvARRAY(ary) - diff;/* diff is positive */
5285                 AvMAX(ary) += diff;
5286                 AvFILLp(ary) += diff;
5287             }
5288             else {
5289                 if (AvFILLp(ary) + diff >= AvMAX(ary))  /* oh, well */
5290                     av_extend(ary, AvFILLp(ary) + diff);
5291                 AvFILLp(ary) += diff;
5292
5293                 if (after) {
5294                     dst = AvARRAY(ary) + AvFILLp(ary);
5295                     src = dst - diff;
5296                     for (i = after; i; i--) {
5297                         *dst-- = *src--;
5298                     }
5299                 }
5300             }
5301         }
5302
5303         if (newlen) {
5304             Copy( MARK, AvARRAY(ary) + offset, newlen, SV* );
5305         }
5306
5307         MARK = ORIGMARK + 1;
5308         if (GIMME == G_ARRAY) {                 /* copy return vals to stack */
5309             if (length) {
5310                 Copy(tmparyval, MARK, length, SV*);
5311                 if (AvREAL(ary)) {
5312                     EXTEND_MORTAL(length);
5313                     for (i = length, dst = MARK; i; i--) {
5314                         sv_2mortal(*dst);       /* free them eventualy */
5315                         dst++;
5316                     }
5317                 }
5318             }
5319             MARK += length - 1;
5320         }
5321         else if (length--) {
5322             *MARK = tmparyval[length];
5323             if (AvREAL(ary)) {
5324                 sv_2mortal(*MARK);
5325                 while (length-- > 0)
5326                     SvREFCNT_dec(tmparyval[length]);
5327             }
5328         }
5329         else
5330             *MARK = &PL_sv_undef;
5331         Safefree(tmparyval);
5332     }
5333     SP = MARK;
5334     RETURN;
5335 }
5336
5337 PP(pp_push)
5338 {
5339     dVAR; dSP; dMARK; dORIGMARK; dTARGET;
5340     register AV * const ary = MUTABLE_AV(*++MARK);
5341     const MAGIC * const mg = SvTIED_mg((const SV *)ary, PERL_MAGIC_tied);
5342
5343     if (mg) {
5344         *MARK-- = SvTIED_obj(MUTABLE_SV(ary), mg);
5345         PUSHMARK(MARK);
5346         PUTBACK;
5347         ENTER_with_name("call_PUSH");
5348         call_method("PUSH",G_SCALAR|G_DISCARD);
5349         LEAVE_with_name("call_PUSH");
5350         SPAGAIN;
5351     }
5352     else {
5353         PL_delaymagic = DM_DELAY;
5354         for (++MARK; MARK <= SP; MARK++) {
5355             SV * const sv = newSV(0);
5356             if (*MARK)
5357                 sv_setsv(sv, *MARK);
5358             av_store(ary, AvFILLp(ary)+1, sv);
5359         }
5360         if (PL_delaymagic & DM_ARRAY)
5361             mg_set(MUTABLE_SV(ary));
5362
5363         PL_delaymagic = 0;
5364     }
5365     SP = ORIGMARK;
5366     if (OP_GIMME(PL_op, 0) != G_VOID) {
5367         PUSHi( AvFILL(ary) + 1 );
5368     }
5369     RETURN;
5370 }
5371
5372 PP(pp_shift)
5373 {
5374     dVAR;
5375     dSP;
5376     AV * const av = PL_op->op_flags & OPf_SPECIAL
5377         ? MUTABLE_AV(GvAV(PL_defgv)) : MUTABLE_AV(POPs);
5378     SV * const sv = PL_op->op_type == OP_SHIFT ? av_shift(av) : av_pop(av);
5379     EXTEND(SP, 1);
5380     assert (sv);
5381     if (AvREAL(av))
5382         (void)sv_2mortal(sv);
5383     PUSHs(sv);
5384     RETURN;
5385 }
5386
5387 PP(pp_unshift)
5388 {
5389     dVAR; dSP; dMARK; dORIGMARK; dTARGET;
5390     register AV *ary = MUTABLE_AV(*++MARK);
5391     const MAGIC * const mg = SvTIED_mg((const SV *)ary, PERL_MAGIC_tied);
5392
5393     if (mg) {
5394         *MARK-- = SvTIED_obj(MUTABLE_SV(ary), mg);
5395         PUSHMARK(MARK);
5396         PUTBACK;
5397         ENTER_with_name("call_UNSHIFT");
5398         call_method("UNSHIFT",G_SCALAR|G_DISCARD);
5399         LEAVE_with_name("call_UNSHIFT");
5400         SPAGAIN;
5401     }
5402     else {
5403         register I32 i = 0;
5404         av_unshift(ary, SP - MARK);
5405         while (MARK < SP) {
5406             SV * const sv = newSVsv(*++MARK);
5407             (void)av_store(ary, i++, sv);
5408         }
5409     }
5410     SP = ORIGMARK;
5411     if (OP_GIMME(PL_op, 0) != G_VOID) {
5412         PUSHi( AvFILL(ary) + 1 );
5413     }
5414     RETURN;
5415 }
5416
5417 PP(pp_reverse)
5418 {
5419     dVAR; dSP; dMARK;
5420
5421     if (GIMME == G_ARRAY) {
5422         if (PL_op->op_private & OPpREVERSE_INPLACE) {
5423             AV *av;
5424
5425             /* See pp_sort() */
5426             assert( MARK+1 == SP && *SP && SvTYPE(*SP) == SVt_PVAV);
5427             (void)POPMARK; /* remove mark associated with ex-OP_AASSIGN */
5428             av = MUTABLE_AV((*SP));
5429             /* In-place reversing only happens in void context for the array
5430              * assignment. We don't need to push anything on the stack. */
5431             SP = MARK;
5432
5433             if (SvMAGICAL(av)) {
5434                 I32 i, j;
5435                 register SV *tmp = sv_newmortal();
5436                 /* For SvCANEXISTDELETE */
5437                 HV *stash;
5438                 const MAGIC *mg;
5439                 bool can_preserve = SvCANEXISTDELETE(av);
5440
5441                 for (i = 0, j = av_len(av); i < j; ++i, --j) {
5442                     register SV *begin, *end;
5443
5444                     if (can_preserve) {
5445                         if (!av_exists(av, i)) {
5446                             if (av_exists(av, j)) {
5447                                 register SV *sv = av_delete(av, j, 0);
5448                                 begin = *av_fetch(av, i, TRUE);
5449                                 sv_setsv_mg(begin, sv);
5450                             }
5451                             continue;
5452                         }
5453                         else if (!av_exists(av, j)) {
5454                             register SV *sv = av_delete(av, i, 0);
5455                             end = *av_fetch(av, j, TRUE);
5456                             sv_setsv_mg(end, sv);
5457                             continue;
5458                         }
5459                     }
5460
5461                     begin = *av_fetch(av, i, TRUE);
5462                     end   = *av_fetch(av, j, TRUE);
5463                     sv_setsv(tmp,      begin);
5464                     sv_setsv_mg(begin, end);
5465                     sv_setsv_mg(end,   tmp);
5466                 }
5467             }
5468             else {
5469                 SV **begin = AvARRAY(av);
5470
5471                 if (begin) {
5472                     SV **end   = begin + AvFILLp(av);
5473
5474                     while (begin < end) {
5475                         register SV * const tmp = *begin;
5476                         *begin++ = *end;
5477                         *end--   = tmp;
5478                     }
5479                 }
5480             }
5481         }
5482         else {
5483             SV **oldsp = SP;
5484             MARK++;
5485             while (MARK < SP) {
5486                 register SV * const tmp = *MARK;
5487                 *MARK++ = *SP;
5488                 *SP--   = tmp;
5489             }
5490             /* safe as long as stack cannot get extended in the above */
5491             SP = oldsp;
5492         }
5493     }
5494     else {
5495         register char *up;
5496         register char *down;
5497         register I32 tmp;
5498         dTARGET;
5499         STRLEN len;
5500         PADOFFSET padoff_du;
5501
5502         SvUTF8_off(TARG);                               /* decontaminate */
5503         if (SP - MARK > 1)
5504             do_join(TARG, &PL_sv_no, MARK, SP);
5505         else {
5506             sv_setsv(TARG, (SP > MARK)
5507                     ? *SP
5508                     : (padoff_du = find_rundefsvoffset(),
5509                         (padoff_du == NOT_IN_PAD
5510                          || PAD_COMPNAME_FLAGS_isOUR(padoff_du))
5511                         ? DEFSV : PAD_SVl(padoff_du)));
5512
5513             if (! SvOK(TARG) && ckWARN(WARN_UNINITIALIZED))
5514                 report_uninit(TARG);
5515         }
5516
5517         up = SvPV_force(TARG, len);
5518         if (len > 1) {
5519             if (DO_UTF8(TARG)) {        /* first reverse each character */
5520                 U8* s = (U8*)SvPVX(TARG);
5521                 const U8* send = (U8*)(s + len);
5522                 while (s < send) {
5523                     if (UTF8_IS_INVARIANT(*s)) {
5524                         s++;
5525                         continue;
5526                     }
5527                     else {
5528                         if (!utf8_to_uvchr(s, 0))
5529                             break;
5530                         up = (char*)s;
5531                         s += UTF8SKIP(s);
5532                         down = (char*)(s - 1);
5533                         /* reverse this character */
5534                         while (down > up) {
5535                             tmp = *up;
5536                             *up++ = *down;
5537                             *down-- = (char)tmp;
5538                         }
5539                     }
5540                 }
5541                 up = SvPVX(TARG);
5542             }
5543             down = SvPVX(TARG) + len - 1;
5544             while (down > up) {
5545                 tmp = *up;
5546                 *up++ = *down;
5547                 *down-- = (char)tmp;
5548             }
5549             (void)SvPOK_only_UTF8(TARG);
5550         }
5551         SP = MARK + 1;
5552         SETTARG;
5553     }
5554     RETURN;
5555 }
5556
5557 PP(pp_split)
5558 {
5559     dVAR; dSP; dTARG;
5560     AV *ary;
5561     register IV limit = POPi;                   /* note, negative is forever */
5562     SV * const sv = POPs;
5563     STRLEN len;
5564     register const char *s = SvPV_const(sv, len);
5565     const bool do_utf8 = DO_UTF8(sv);
5566     const char *strend = s + len;
5567     register PMOP *pm;
5568     register REGEXP *rx;
5569     register SV *dstr;
5570     register const char *m;
5571     I32 iters = 0;
5572     const STRLEN slen = do_utf8 ? utf8_length((U8*)s, (U8*)strend) : (STRLEN)(strend - s);
5573     I32 maxiters = slen + 10;
5574     I32 trailing_empty = 0;
5575     const char *orig;
5576     const I32 origlimit = limit;
5577     I32 realarray = 0;
5578     I32 base;
5579     const I32 gimme = GIMME_V;
5580     bool gimme_scalar;
5581     const I32 oldsave = PL_savestack_ix;
5582     U32 make_mortal = SVs_TEMP;
5583     bool multiline = 0;
5584     MAGIC *mg = NULL;
5585
5586 #ifdef DEBUGGING
5587     Copy(&LvTARGOFF(POPs), &pm, 1, PMOP*);
5588 #else
5589     pm = (PMOP*)POPs;
5590 #endif
5591     if (!pm || !s)
5592         DIE(aTHX_ "panic: pp_split");
5593     rx = PM_GETRE(pm);
5594
5595     TAINT_IF((RX_EXTFLAGS(rx) & RXf_PMf_LOCALE) &&
5596              (RX_EXTFLAGS(rx) & (RXf_WHITE | RXf_SKIPWHITE)));
5597
5598     RX_MATCH_UTF8_set(rx, do_utf8);
5599
5600 #ifdef USE_ITHREADS
5601     if (pm->op_pmreplrootu.op_pmtargetoff) {
5602         ary = GvAVn(MUTABLE_GV(PAD_SVl(pm->op_pmreplrootu.op_pmtargetoff)));
5603     }
5604 #else
5605     if (pm->op_pmreplrootu.op_pmtargetgv) {
5606         ary = GvAVn(pm->op_pmreplrootu.op_pmtargetgv);
5607     }
5608 #endif
5609     else
5610         ary = NULL;
5611     if (ary && (gimme != G_ARRAY || (pm->op_pmflags & PMf_ONCE))) {
5612         realarray = 1;
5613         PUTBACK;
5614         av_extend(ary,0);
5615         av_clear(ary);
5616         SPAGAIN;
5617         if ((mg = SvTIED_mg((const SV *)ary, PERL_MAGIC_tied))) {
5618             PUSHMARK(SP);
5619             XPUSHs(SvTIED_obj(MUTABLE_SV(ary), mg));
5620         }
5621         else {
5622             if (!AvREAL(ary)) {
5623                 I32 i;
5624                 AvREAL_on(ary);
5625                 AvREIFY_off(ary);
5626                 for (i = AvFILLp(ary); i >= 0; i--)
5627                     AvARRAY(ary)[i] = &PL_sv_undef;     /* don't free mere refs */
5628             }
5629             /* temporarily switch stacks */
5630             SAVESWITCHSTACK(PL_curstack, ary);
5631             make_mortal = 0;
5632         }
5633     }
5634     base = SP - PL_stack_base;
5635     orig = s;
5636     if (RX_EXTFLAGS(rx) & RXf_SKIPWHITE) {
5637         if (do_utf8) {
5638             while (*s == ' ' || is_utf8_space((U8*)s))
5639                 s += UTF8SKIP(s);
5640         }
5641         else if (RX_EXTFLAGS(rx) & RXf_PMf_LOCALE) {
5642             while (isSPACE_LC(*s))
5643                 s++;
5644         }
5645         else {
5646             while (isSPACE(*s))
5647                 s++;
5648         }
5649     }
5650     if (RX_EXTFLAGS(rx) & PMf_MULTILINE) {
5651         multiline = 1;
5652     }
5653
5654     gimme_scalar = gimme == G_SCALAR && !ary;
5655
5656     if (!limit)
5657         limit = maxiters + 2;
5658     if (RX_EXTFLAGS(rx) & RXf_WHITE) {
5659         while (--limit) {
5660             m = s;
5661             /* this one uses 'm' and is a negative test */
5662             if (do_utf8) {
5663                 while (m < strend && !( *m == ' ' || is_utf8_space((U8*)m) )) {
5664                     const int t = UTF8SKIP(m);
5665                     /* is_utf8_space returns FALSE for malform utf8 */
5666                     if (strend - m < t)
5667                         m = strend;
5668                     else
5669                         m += t;
5670                 }
5671             } else if (RX_EXTFLAGS(rx) & RXf_PMf_LOCALE) {
5672                 while (m < strend && !isSPACE_LC(*m))
5673                     ++m;
5674             } else {
5675                 while (m < strend && !isSPACE(*m))
5676                     ++m;
5677             }  
5678             if (m >= strend)
5679                 break;
5680
5681             if (gimme_scalar) {
5682                 iters++;
5683                 if (m-s == 0)
5684                     trailing_empty++;
5685                 else
5686                     trailing_empty = 0;
5687             } else {
5688                 dstr = newSVpvn_flags(s, m-s,
5689                                       (do_utf8 ? SVf_UTF8 : 0) | make_mortal);
5690                 XPUSHs(dstr);
5691             }
5692
5693             /* skip the whitespace found last */
5694             if (do_utf8)
5695                 s = m + UTF8SKIP(m);
5696             else
5697                 s = m + 1;
5698
5699             /* this one uses 's' and is a positive test */
5700             if (do_utf8) {
5701                 while (s < strend && ( *s == ' ' || is_utf8_space((U8*)s) ))
5702                     s +=  UTF8SKIP(s);
5703             } else if (RX_EXTFLAGS(rx) & RXf_PMf_LOCALE) {
5704                 while (s < strend && isSPACE_LC(*s))
5705                     ++s;
5706             } else {
5707                 while (s < strend && isSPACE(*s))
5708                     ++s;
5709             }       
5710         }
5711     }
5712     else if (RX_EXTFLAGS(rx) & RXf_START_ONLY) {
5713         while (--limit) {
5714             for (m = s; m < strend && *m != '\n'; m++)
5715                 ;
5716             m++;
5717             if (m >= strend)
5718                 break;
5719
5720             if (gimme_scalar) {
5721                 iters++;
5722                 if (m-s == 0)
5723                     trailing_empty++;
5724                 else
5725                     trailing_empty = 0;
5726             } else {
5727                 dstr = newSVpvn_flags(s, m-s,
5728                                       (do_utf8 ? SVf_UTF8 : 0) | make_mortal);
5729                 XPUSHs(dstr);
5730             }
5731             s = m;
5732         }
5733     }
5734     else if (RX_EXTFLAGS(rx) & RXf_NULL && !(s >= strend)) {
5735         /*
5736           Pre-extend the stack, either the number of bytes or
5737           characters in the string or a limited amount, triggered by:
5738
5739           my ($x, $y) = split //, $str;
5740             or
5741           split //, $str, $i;
5742         */
5743         if (!gimme_scalar) {
5744             const U32 items = limit - 1;
5745             if (items < slen)
5746                 EXTEND(SP, items);
5747             else
5748                 EXTEND(SP, slen);
5749         }
5750
5751         if (do_utf8) {
5752             while (--limit) {
5753                 /* keep track of how many bytes we skip over */
5754                 m = s;
5755                 s += UTF8SKIP(s);
5756                 if (gimme_scalar) {
5757                     iters++;
5758                     if (s-m == 0)
5759                         trailing_empty++;
5760                     else
5761                         trailing_empty = 0;
5762                 } else {
5763                     dstr = newSVpvn_flags(m, s-m, SVf_UTF8 | make_mortal);
5764
5765                     PUSHs(dstr);
5766                 }
5767
5768                 if (s >= strend)
5769                     break;
5770             }
5771         } else {
5772             while (--limit) {
5773                 if (gimme_scalar) {
5774                     iters++;
5775                 } else {
5776                     dstr = newSVpvn(s, 1);
5777
5778
5779                     if (make_mortal)
5780                         sv_2mortal(dstr);
5781
5782                     PUSHs(dstr);
5783                 }
5784
5785                 s++;
5786
5787                 if (s >= strend)
5788                     break;
5789             }
5790         }
5791     }
5792     else if (do_utf8 == (RX_UTF8(rx) != 0) &&
5793              (RX_EXTFLAGS(rx) & RXf_USE_INTUIT) && !RX_NPARENS(rx)
5794              && (RX_EXTFLAGS(rx) & RXf_CHECK_ALL)
5795              && !(RX_EXTFLAGS(rx) & RXf_ANCH)) {
5796         const int tail = (RX_EXTFLAGS(rx) & RXf_INTUIT_TAIL);
5797         SV * const csv = CALLREG_INTUIT_STRING(rx);
5798
5799         len = RX_MINLENRET(rx);
5800         if (len == 1 && !RX_UTF8(rx) && !tail) {
5801             const char c = *SvPV_nolen_const(csv);
5802             while (--limit) {
5803                 for (m = s; m < strend && *m != c; m++)
5804                     ;
5805                 if (m >= strend)
5806                     break;
5807                 if (gimme_scalar) {
5808                     iters++;
5809                     if (m-s == 0)
5810                         trailing_empty++;
5811                     else
5812                         trailing_empty = 0;
5813                 } else {
5814                     dstr = newSVpvn_flags(s, m-s,
5815                                           (do_utf8 ? SVf_UTF8 : 0) | make_mortal);
5816                     XPUSHs(dstr);
5817                 }
5818                 /* The rx->minlen is in characters but we want to step
5819                  * s ahead by bytes. */
5820                 if (do_utf8)
5821                     s = (char*)utf8_hop((U8*)m, len);
5822                 else
5823                     s = m + len; /* Fake \n at the end */
5824             }
5825         }
5826         else {
5827             while (s < strend && --limit &&
5828               (m = fbm_instr((unsigned char*)s, (unsigned char*)strend,
5829                              csv, multiline ? FBMrf_MULTILINE : 0)) )
5830             {
5831                 if (gimme_scalar) {
5832                     iters++;
5833                     if (m-s == 0)
5834                         trailing_empty++;
5835                     else
5836                         trailing_empty = 0;
5837                 } else {
5838                     dstr = newSVpvn_flags(s, m-s,
5839                                           (do_utf8 ? SVf_UTF8 : 0) | make_mortal);
5840                     XPUSHs(dstr);
5841                 }
5842                 /* The rx->minlen is in characters but we want to step
5843                  * s ahead by bytes. */
5844                 if (do_utf8)
5845                     s = (char*)utf8_hop((U8*)m, len);
5846                 else
5847                     s = m + len; /* Fake \n at the end */
5848             }
5849         }
5850     }
5851     else {
5852         maxiters += slen * RX_NPARENS(rx);
5853         while (s < strend && --limit)
5854         {
5855             I32 rex_return;
5856             PUTBACK;
5857             rex_return = CALLREGEXEC(rx, (char*)s, (char*)strend, (char*)orig, 1 ,
5858                             sv, NULL, 0);
5859             SPAGAIN;
5860             if (rex_return == 0)
5861                 break;
5862             TAINT_IF(RX_MATCH_TAINTED(rx));
5863             if (RX_MATCH_COPIED(rx) && RX_SUBBEG(rx) != orig) {
5864                 m = s;
5865                 s = orig;
5866                 orig = RX_SUBBEG(rx);
5867                 s = orig + (m - s);
5868                 strend = s + (strend - m);
5869             }
5870             m = RX_OFFS(rx)[0].start + orig;
5871
5872             if (gimme_scalar) {
5873                 iters++;
5874                 if (m-s == 0)
5875                     trailing_empty++;
5876                 else
5877                     trailing_empty = 0;
5878             } else {
5879                 dstr = newSVpvn_flags(s, m-s,
5880                                       (do_utf8 ? SVf_UTF8 : 0) | make_mortal);
5881                 XPUSHs(dstr);
5882             }
5883             if (RX_NPARENS(rx)) {
5884                 I32 i;
5885                 for (i = 1; i <= (I32)RX_NPARENS(rx); i++) {
5886                     s = RX_OFFS(rx)[i].start + orig;
5887                     m = RX_OFFS(rx)[i].end + orig;
5888
5889                     /* japhy (07/27/01) -- the (m && s) test doesn't catch
5890                        parens that didn't match -- they should be set to
5891                        undef, not the empty string */
5892                     if (gimme_scalar) {
5893                         iters++;
5894                         if (m-s == 0)
5895                             trailing_empty++;
5896                         else
5897                             trailing_empty = 0;
5898                     } else {
5899                         if (m >= orig && s >= orig) {
5900                             dstr = newSVpvn_flags(s, m-s,
5901                                                  (do_utf8 ? SVf_UTF8 : 0)
5902                                                   | make_mortal);
5903                         }
5904                         else
5905                             dstr = &PL_sv_undef;  /* undef, not "" */
5906                         XPUSHs(dstr);
5907                     }
5908
5909                 }
5910             }
5911             s = RX_OFFS(rx)[0].end + orig;
5912         }
5913     }
5914
5915     if (!gimme_scalar) {
5916         iters = (SP - PL_stack_base) - base;
5917     }
5918     if (iters > maxiters)
5919         DIE(aTHX_ "Split loop");
5920
5921     /* keep field after final delim? */
5922     if (s < strend || (iters && origlimit)) {
5923         if (!gimme_scalar) {
5924             const STRLEN l = strend - s;
5925             dstr = newSVpvn_flags(s, l, (do_utf8 ? SVf_UTF8 : 0) | make_mortal);
5926             XPUSHs(dstr);
5927         }
5928         iters++;
5929     }
5930     else if (!origlimit) {
5931         if (gimme_scalar) {
5932             iters -= trailing_empty;
5933         } else {
5934             while (iters > 0 && (!TOPs || !SvANY(TOPs) || SvCUR(TOPs) == 0)) {
5935                 if (TOPs && !make_mortal)
5936                     sv_2mortal(TOPs);
5937                 *SP-- = &PL_sv_undef;
5938                 iters--;
5939             }
5940         }
5941     }
5942
5943     PUTBACK;
5944     LEAVE_SCOPE(oldsave); /* may undo an earlier SWITCHSTACK */
5945     SPAGAIN;
5946     if (realarray) {
5947         if (!mg) {
5948             if (SvSMAGICAL(ary)) {
5949                 PUTBACK;
5950                 mg_set(MUTABLE_SV(ary));
5951                 SPAGAIN;
5952             }
5953             if (gimme == G_ARRAY) {
5954                 EXTEND(SP, iters);
5955                 Copy(AvARRAY(ary), SP + 1, iters, SV*);
5956                 SP += iters;
5957                 RETURN;
5958             }
5959         }
5960         else {
5961             PUTBACK;
5962             ENTER_with_name("call_PUSH");
5963             call_method("PUSH",G_SCALAR|G_DISCARD);
5964             LEAVE_with_name("call_PUSH");
5965             SPAGAIN;
5966             if (gimme == G_ARRAY) {
5967                 I32 i;
5968                 /* EXTEND should not be needed - we just popped them */
5969                 EXTEND(SP, iters);
5970                 for (i=0; i < iters; i++) {
5971                     SV **svp = av_fetch(ary, i, FALSE);
5972                     PUSHs((svp) ? *svp : &PL_sv_undef);
5973                 }
5974                 RETURN;
5975             }
5976         }
5977     }
5978     else {
5979         if (gimme == G_ARRAY)
5980             RETURN;
5981     }
5982
5983     GETTARGET;
5984     PUSHi(iters);
5985     RETURN;
5986 }
5987
5988 PP(pp_once)
5989 {
5990     dSP;
5991     SV *const sv = PAD_SVl(PL_op->op_targ);
5992
5993     if (SvPADSTALE(sv)) {
5994         /* First time. */
5995         SvPADSTALE_off(sv);
5996         RETURNOP(cLOGOP->op_other);
5997     }
5998     RETURNOP(cLOGOP->op_next);
5999 }
6000
6001 PP(pp_lock)
6002 {
6003     dVAR;
6004     dSP;
6005     dTOPss;
6006     SV *retsv = sv;
6007     assert(SvTYPE(retsv) != SVt_PVCV);
6008     SvLOCK(sv);
6009     if (SvTYPE(retsv) == SVt_PVAV || SvTYPE(retsv) == SVt_PVHV) {
6010         retsv = refto(retsv);
6011     }
6012     SETs(retsv);
6013     RETURN;
6014 }
6015
6016
6017 PP(unimplemented_op)
6018 {
6019     dVAR;
6020     DIE(aTHX_ "panic: unimplemented op %s (#%d) called", OP_NAME(PL_op),
6021         PL_op->op_type);
6022     return NORMAL;
6023 }
6024
6025 PP(pp_boolkeys)
6026 {
6027     dVAR;
6028     dSP;
6029     HV * const hv = (HV*)POPs;
6030     
6031     if (SvRMAGICAL(hv)) {
6032         MAGIC * const mg = mg_find((SV*)hv, PERL_MAGIC_tied);
6033         if (mg) {
6034             XPUSHs(magic_scalarpack(hv, mg));
6035             RETURN;
6036         }           
6037     }
6038
6039     XPUSHs(boolSV(HvKEYS(hv) != 0));
6040     RETURN;
6041 }
6042
6043 /*
6044  * Local variables:
6045  * c-indentation-style: bsd
6046  * c-basic-offset: 4
6047  * indent-tabs-mode: t
6048  * End:
6049  *
6050  * ex: set ts=8 sts=4 sw=4 noet:
6051  */