This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Use <sys/poll.h> if available before going select().
[perl5.git] / op.c
1 #line 2 "op.c"
2 /*    op.c
3  *
4  *    Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
5  *    2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008 by Larry Wall and others
6  *
7  *    You may distribute under the terms of either the GNU General Public
8  *    License or the Artistic License, as specified in the README file.
9  *
10  */
11
12 /*
13  * 'You see: Mr. Drogo, he married poor Miss Primula Brandybuck.  She was
14  *  our Mr. Bilbo's first cousin on the mother's side (her mother being the
15  *  youngest of the Old Took's daughters); and Mr. Drogo was his second
16  *  cousin.  So Mr. Frodo is his first *and* second cousin, once removed
17  *  either way, as the saying is, if you follow me.'       --the Gaffer
18  *
19  *     [p.23 of _The Lord of the Rings_, I/i: "A Long-Expected Party"]
20  */
21
22 /* This file contains the functions that create, manipulate and optimize
23  * the OP structures that hold a compiled perl program.
24  *
25  * A Perl program is compiled into a tree of OPs. Each op contains
26  * structural pointers (eg to its siblings and the next op in the
27  * execution sequence), a pointer to the function that would execute the
28  * op, plus any data specific to that op. For example, an OP_CONST op
29  * points to the pp_const() function and to an SV containing the constant
30  * value. When pp_const() is executed, its job is to push that SV onto the
31  * stack.
32  *
33  * OPs are mainly created by the newFOO() functions, which are mainly
34  * called from the parser (in perly.y) as the code is parsed. For example
35  * the Perl code $a + $b * $c would cause the equivalent of the following
36  * to be called (oversimplifying a bit):
37  *
38  *  newBINOP(OP_ADD, flags,
39  *      newSVREF($a),
40  *      newBINOP(OP_MULTIPLY, flags, newSVREF($b), newSVREF($c))
41  *  )
42  *
43  * Note that during the build of miniperl, a temporary copy of this file
44  * is made, called opmini.c.
45  */
46
47 /*
48 Perl's compiler is essentially a 3-pass compiler with interleaved phases:
49
50     A bottom-up pass
51     A top-down pass
52     An execution-order pass
53
54 The bottom-up pass is represented by all the "newOP" routines and
55 the ck_ routines.  The bottom-upness is actually driven by yacc.
56 So at the point that a ck_ routine fires, we have no idea what the
57 context is, either upward in the syntax tree, or either forward or
58 backward in the execution order.  (The bottom-up parser builds that
59 part of the execution order it knows about, but if you follow the "next"
60 links around, you'll find it's actually a closed loop through the
61 top level node.)
62
63 Whenever the bottom-up parser gets to a node that supplies context to
64 its components, it invokes that portion of the top-down pass that applies
65 to that part of the subtree (and marks the top node as processed, so
66 if a node further up supplies context, it doesn't have to take the
67 plunge again).  As a particular subcase of this, as the new node is
68 built, it takes all the closed execution loops of its subcomponents
69 and links them into a new closed loop for the higher level node.  But
70 it's still not the real execution order.
71
72 The actual execution order is not known till we get a grammar reduction
73 to a top-level unit like a subroutine or file that will be called by
74 "name" rather than via a "next" pointer.  At that point, we can call
75 into peep() to do that code's portion of the 3rd pass.  It has to be
76 recursive, but it's recursive on basic blocks, not on tree nodes.
77 */
78
79 /* To implement user lexical pragmas, there needs to be a way at run time to
80    get the compile time state of %^H for that block.  Storing %^H in every
81    block (or even COP) would be very expensive, so a different approach is
82    taken.  The (running) state of %^H is serialised into a tree of HE-like
83    structs.  Stores into %^H are chained onto the current leaf as a struct
84    refcounted_he * with the key and the value.  Deletes from %^H are saved
85    with a value of PL_sv_placeholder.  The state of %^H at any point can be
86    turned back into a regular HV by walking back up the tree from that point's
87    leaf, ignoring any key you've already seen (placeholder or not), storing
88    the rest into the HV structure, then removing the placeholders. Hence
89    memory is only used to store the %^H deltas from the enclosing COP, rather
90    than the entire %^H on each COP.
91
92    To cause actions on %^H to write out the serialisation records, it has
93    magic type 'H'. This magic (itself) does nothing, but its presence causes
94    the values to gain magic type 'h', which has entries for set and clear.
95    C<Perl_magic_sethint> updates C<PL_compiling.cop_hints_hash> with a store
96    record, with deletes written by C<Perl_magic_clearhint>. C<SAVEHINTS>
97    saves the current C<PL_compiling.cop_hints_hash> on the save stack, so that
98    it will be correctly restored when any inner compiling scope is exited.
99 */
100
101 #include "EXTERN.h"
102 #define PERL_IN_OP_C
103 #include "perl.h"
104 #include "keywords.h"
105 #include "feature.h"
106 #include "regcomp.h"
107
108 #define CALL_PEEP(o) PL_peepp(aTHX_ o)
109 #define CALL_RPEEP(o) PL_rpeepp(aTHX_ o)
110 #define CALL_OPFREEHOOK(o) if (PL_opfreehook) PL_opfreehook(aTHX_ o)
111
112 /* Used to avoid recursion through the op tree in scalarvoid() and
113    op_free()
114 */
115
116 #define DEFERRED_OP_STEP 100
117 #define DEFER_OP(o) \
118   STMT_START { \
119     if (UNLIKELY(defer_ix == (defer_stack_alloc-1))) {    \
120         defer_stack_alloc += DEFERRED_OP_STEP; \
121         assert(defer_stack_alloc > 0); \
122         Renew(defer_stack, defer_stack_alloc, OP *); \
123     } \
124     defer_stack[++defer_ix] = o; \
125   } STMT_END
126
127 #define POP_DEFERRED_OP() (defer_ix >= 0 ? defer_stack[defer_ix--] : (OP *)NULL)
128
129 /* remove any leading "empty" ops from the op_next chain whose first
130  * node's address is stored in op_p. Store the updated address of the
131  * first node in op_p.
132  */
133
134 STATIC void
135 S_prune_chain_head(OP** op_p)
136 {
137     while (*op_p
138         && (   (*op_p)->op_type == OP_NULL
139             || (*op_p)->op_type == OP_SCOPE
140             || (*op_p)->op_type == OP_SCALAR
141             || (*op_p)->op_type == OP_LINESEQ)
142     )
143         *op_p = (*op_p)->op_next;
144 }
145
146
147 /* See the explanatory comments above struct opslab in op.h. */
148
149 #ifdef PERL_DEBUG_READONLY_OPS
150 #  define PERL_SLAB_SIZE 128
151 #  define PERL_MAX_SLAB_SIZE 4096
152 #  include <sys/mman.h>
153 #endif
154
155 #ifndef PERL_SLAB_SIZE
156 #  define PERL_SLAB_SIZE 64
157 #endif
158 #ifndef PERL_MAX_SLAB_SIZE
159 #  define PERL_MAX_SLAB_SIZE 2048
160 #endif
161
162 /* rounds up to nearest pointer */
163 #define SIZE_TO_PSIZE(x)        (((x) + sizeof(I32 *) - 1)/sizeof(I32 *))
164 #define DIFF(o,p)               ((size_t)((I32 **)(p) - (I32**)(o)))
165
166 static OPSLAB *
167 S_new_slab(pTHX_ size_t sz)
168 {
169 #ifdef PERL_DEBUG_READONLY_OPS
170     OPSLAB *slab = (OPSLAB *) mmap(0, sz * sizeof(I32 *),
171                                    PROT_READ|PROT_WRITE,
172                                    MAP_ANON|MAP_PRIVATE, -1, 0);
173     DEBUG_m(PerlIO_printf(Perl_debug_log, "mapped %lu at %p\n",
174                           (unsigned long) sz, slab));
175     if (slab == MAP_FAILED) {
176         perror("mmap failed");
177         abort();
178     }
179     slab->opslab_size = (U16)sz;
180 #else
181     OPSLAB *slab = (OPSLAB *)PerlMemShared_calloc(sz, sizeof(I32 *));
182 #endif
183 #ifndef WIN32
184     /* The context is unused in non-Windows */
185     PERL_UNUSED_CONTEXT;
186 #endif
187     slab->opslab_first = (OPSLOT *)((I32 **)slab + sz - 1);
188     return slab;
189 }
190
191 /* requires double parens and aTHX_ */
192 #define DEBUG_S_warn(args)                                             \
193     DEBUG_S(                                                            \
194         PerlIO_printf(Perl_debug_log, "%s", SvPVx_nolen(Perl_mess args)) \
195     )
196
197 void *
198 Perl_Slab_Alloc(pTHX_ size_t sz)
199 {
200     OPSLAB *slab;
201     OPSLAB *slab2;
202     OPSLOT *slot;
203     OP *o;
204     size_t opsz, space;
205
206     /* We only allocate ops from the slab during subroutine compilation.
207        We find the slab via PL_compcv, hence that must be non-NULL. It could
208        also be pointing to a subroutine which is now fully set up (CvROOT()
209        pointing to the top of the optree for that sub), or a subroutine
210        which isn't using the slab allocator. If our sanity checks aren't met,
211        don't use a slab, but allocate the OP directly from the heap.  */
212     if (!PL_compcv || CvROOT(PL_compcv)
213      || (CvSTART(PL_compcv) && !CvSLABBED(PL_compcv)))
214     {
215         o = (OP*)PerlMemShared_calloc(1, sz);
216         goto gotit;
217     }
218
219     /* While the subroutine is under construction, the slabs are accessed via
220        CvSTART(), to avoid needing to expand PVCV by one pointer for something
221        unneeded at runtime. Once a subroutine is constructed, the slabs are
222        accessed via CvROOT(). So if CvSTART() is NULL, no slab has been
223        allocated yet.  See the commit message for 8be227ab5eaa23f2 for more
224        details.  */
225     if (!CvSTART(PL_compcv)) {
226         CvSTART(PL_compcv) =
227             (OP *)(slab = S_new_slab(aTHX_ PERL_SLAB_SIZE));
228         CvSLABBED_on(PL_compcv);
229         slab->opslab_refcnt = 2; /* one for the CV; one for the new OP */
230     }
231     else ++(slab = (OPSLAB *)CvSTART(PL_compcv))->opslab_refcnt;
232
233     opsz = SIZE_TO_PSIZE(sz);
234     sz = opsz + OPSLOT_HEADER_P;
235
236     /* The slabs maintain a free list of OPs. In particular, constant folding
237        will free up OPs, so it makes sense to re-use them where possible. A
238        freed up slot is used in preference to a new allocation.  */
239     if (slab->opslab_freed) {
240         OP **too = &slab->opslab_freed;
241         o = *too;
242         DEBUG_S_warn((aTHX_ "found free op at %p, slab %p", (void*)o, (void*)slab));
243         while (o && DIFF(OpSLOT(o), OpSLOT(o)->opslot_next) < sz) {
244             DEBUG_S_warn((aTHX_ "Alas! too small"));
245             o = *(too = &o->op_next);
246             if (o) { DEBUG_S_warn((aTHX_ "found another free op at %p", (void*)o)); }
247         }
248         if (o) {
249             *too = o->op_next;
250             Zero(o, opsz, I32 *);
251             o->op_slabbed = 1;
252             goto gotit;
253         }
254     }
255
256 #define INIT_OPSLOT \
257             slot->opslot_slab = slab;                   \
258             slot->opslot_next = slab2->opslab_first;    \
259             slab2->opslab_first = slot;                 \
260             o = &slot->opslot_op;                       \
261             o->op_slabbed = 1
262
263     /* The partially-filled slab is next in the chain. */
264     slab2 = slab->opslab_next ? slab->opslab_next : slab;
265     if ((space = DIFF(&slab2->opslab_slots, slab2->opslab_first)) < sz) {
266         /* Remaining space is too small. */
267
268         /* If we can fit a BASEOP, add it to the free chain, so as not
269            to waste it. */
270         if (space >= SIZE_TO_PSIZE(sizeof(OP)) + OPSLOT_HEADER_P) {
271             slot = &slab2->opslab_slots;
272             INIT_OPSLOT;
273             o->op_type = OP_FREED;
274             o->op_next = slab->opslab_freed;
275             slab->opslab_freed = o;
276         }
277
278         /* Create a new slab.  Make this one twice as big. */
279         slot = slab2->opslab_first;
280         while (slot->opslot_next) slot = slot->opslot_next;
281         slab2 = S_new_slab(aTHX_
282                             (DIFF(slab2, slot)+1)*2 > PERL_MAX_SLAB_SIZE
283                                         ? PERL_MAX_SLAB_SIZE
284                                         : (DIFF(slab2, slot)+1)*2);
285         slab2->opslab_next = slab->opslab_next;
286         slab->opslab_next = slab2;
287     }
288     assert(DIFF(&slab2->opslab_slots, slab2->opslab_first) >= sz);
289
290     /* Create a new op slot */
291     slot = (OPSLOT *)((I32 **)slab2->opslab_first - sz);
292     assert(slot >= &slab2->opslab_slots);
293     if (DIFF(&slab2->opslab_slots, slot)
294          < SIZE_TO_PSIZE(sizeof(OP)) + OPSLOT_HEADER_P)
295         slot = &slab2->opslab_slots;
296     INIT_OPSLOT;
297     DEBUG_S_warn((aTHX_ "allocating op at %p, slab %p", (void*)o, (void*)slab));
298
299   gotit:
300 #ifdef PERL_OP_PARENT
301     /* moresib == 0, op_sibling == 0 implies a solitary unattached op */
302     assert(!o->op_moresib);
303     assert(!o->op_sibparent);
304 #endif
305
306     return (void *)o;
307 }
308
309 #undef INIT_OPSLOT
310
311 #ifdef PERL_DEBUG_READONLY_OPS
312 void
313 Perl_Slab_to_ro(pTHX_ OPSLAB *slab)
314 {
315     PERL_ARGS_ASSERT_SLAB_TO_RO;
316
317     if (slab->opslab_readonly) return;
318     slab->opslab_readonly = 1;
319     for (; slab; slab = slab->opslab_next) {
320         /*DEBUG_U(PerlIO_printf(Perl_debug_log,"mprotect ->ro %lu at %p\n",
321                               (unsigned long) slab->opslab_size, slab));*/
322         if (mprotect(slab, slab->opslab_size * sizeof(I32 *), PROT_READ))
323             Perl_warn(aTHX_ "mprotect for %p %lu failed with %d", slab,
324                              (unsigned long)slab->opslab_size, errno);
325     }
326 }
327
328 void
329 Perl_Slab_to_rw(pTHX_ OPSLAB *const slab)
330 {
331     OPSLAB *slab2;
332
333     PERL_ARGS_ASSERT_SLAB_TO_RW;
334
335     if (!slab->opslab_readonly) return;
336     slab2 = slab;
337     for (; slab2; slab2 = slab2->opslab_next) {
338         /*DEBUG_U(PerlIO_printf(Perl_debug_log,"mprotect ->rw %lu at %p\n",
339                               (unsigned long) size, slab2));*/
340         if (mprotect((void *)slab2, slab2->opslab_size * sizeof(I32 *),
341                      PROT_READ|PROT_WRITE)) {
342             Perl_warn(aTHX_ "mprotect RW for %p %lu failed with %d", slab,
343                              (unsigned long)slab2->opslab_size, errno);
344         }
345     }
346     slab->opslab_readonly = 0;
347 }
348
349 #else
350 #  define Slab_to_rw(op)    NOOP
351 #endif
352
353 /* This cannot possibly be right, but it was copied from the old slab
354    allocator, to which it was originally added, without explanation, in
355    commit 083fcd5. */
356 #ifdef NETWARE
357 #    define PerlMemShared PerlMem
358 #endif
359
360 void
361 Perl_Slab_Free(pTHX_ void *op)
362 {
363     OP * const o = (OP *)op;
364     OPSLAB *slab;
365
366     PERL_ARGS_ASSERT_SLAB_FREE;
367
368     if (!o->op_slabbed) {
369         if (!o->op_static)
370             PerlMemShared_free(op);
371         return;
372     }
373
374     slab = OpSLAB(o);
375     /* If this op is already freed, our refcount will get screwy. */
376     assert(o->op_type != OP_FREED);
377     o->op_type = OP_FREED;
378     o->op_next = slab->opslab_freed;
379     slab->opslab_freed = o;
380     DEBUG_S_warn((aTHX_ "free op at %p, recorded in slab %p", (void*)o, (void*)slab));
381     OpslabREFCNT_dec_padok(slab);
382 }
383
384 void
385 Perl_opslab_free_nopad(pTHX_ OPSLAB *slab)
386 {
387     const bool havepad = !!PL_comppad;
388     PERL_ARGS_ASSERT_OPSLAB_FREE_NOPAD;
389     if (havepad) {
390         ENTER;
391         PAD_SAVE_SETNULLPAD();
392     }
393     opslab_free(slab);
394     if (havepad) LEAVE;
395 }
396
397 void
398 Perl_opslab_free(pTHX_ OPSLAB *slab)
399 {
400     OPSLAB *slab2;
401     PERL_ARGS_ASSERT_OPSLAB_FREE;
402     PERL_UNUSED_CONTEXT;
403     DEBUG_S_warn((aTHX_ "freeing slab %p", (void*)slab));
404     assert(slab->opslab_refcnt == 1);
405     do {
406         slab2 = slab->opslab_next;
407 #ifdef DEBUGGING
408         slab->opslab_refcnt = ~(size_t)0;
409 #endif
410 #ifdef PERL_DEBUG_READONLY_OPS
411         DEBUG_m(PerlIO_printf(Perl_debug_log, "Deallocate slab at %p\n",
412                                                (void*)slab));
413         if (munmap(slab, slab->opslab_size * sizeof(I32 *))) {
414             perror("munmap failed");
415             abort();
416         }
417 #else
418         PerlMemShared_free(slab);
419 #endif
420         slab = slab2;
421     } while (slab);
422 }
423
424 void
425 Perl_opslab_force_free(pTHX_ OPSLAB *slab)
426 {
427     OPSLAB *slab2;
428     OPSLOT *slot;
429 #ifdef DEBUGGING
430     size_t savestack_count = 0;
431 #endif
432     PERL_ARGS_ASSERT_OPSLAB_FORCE_FREE;
433     slab2 = slab;
434     do {
435         for (slot = slab2->opslab_first;
436              slot->opslot_next;
437              slot = slot->opslot_next) {
438             if (slot->opslot_op.op_type != OP_FREED
439              && !(slot->opslot_op.op_savefree
440 #ifdef DEBUGGING
441                   && ++savestack_count
442 #endif
443                  )
444             ) {
445                 assert(slot->opslot_op.op_slabbed);
446                 op_free(&slot->opslot_op);
447                 if (slab->opslab_refcnt == 1) goto free;
448             }
449         }
450     } while ((slab2 = slab2->opslab_next));
451     /* > 1 because the CV still holds a reference count. */
452     if (slab->opslab_refcnt > 1) { /* still referenced by the savestack */
453 #ifdef DEBUGGING
454         assert(savestack_count == slab->opslab_refcnt-1);
455 #endif
456         /* Remove the CV’s reference count. */
457         slab->opslab_refcnt--;
458         return;
459     }
460    free:
461     opslab_free(slab);
462 }
463
464 #ifdef PERL_DEBUG_READONLY_OPS
465 OP *
466 Perl_op_refcnt_inc(pTHX_ OP *o)
467 {
468     if(o) {
469         OPSLAB *const slab = o->op_slabbed ? OpSLAB(o) : NULL;
470         if (slab && slab->opslab_readonly) {
471             Slab_to_rw(slab);
472             ++o->op_targ;
473             Slab_to_ro(slab);
474         } else {
475             ++o->op_targ;
476         }
477     }
478     return o;
479
480 }
481
482 PADOFFSET
483 Perl_op_refcnt_dec(pTHX_ OP *o)
484 {
485     PADOFFSET result;
486     OPSLAB *const slab = o->op_slabbed ? OpSLAB(o) : NULL;
487
488     PERL_ARGS_ASSERT_OP_REFCNT_DEC;
489
490     if (slab && slab->opslab_readonly) {
491         Slab_to_rw(slab);
492         result = --o->op_targ;
493         Slab_to_ro(slab);
494     } else {
495         result = --o->op_targ;
496     }
497     return result;
498 }
499 #endif
500 /*
501  * In the following definition, the ", (OP*)0" is just to make the compiler
502  * think the expression is of the right type: croak actually does a Siglongjmp.
503  */
504 #define CHECKOP(type,o) \
505     ((PL_op_mask && PL_op_mask[type])                           \
506      ? ( op_free((OP*)o),                                       \
507          Perl_croak(aTHX_ "'%s' trapped by operation mask", PL_op_desc[type]),  \
508          (OP*)0 )                                               \
509      : PL_check[type](aTHX_ (OP*)o))
510
511 #define RETURN_UNLIMITED_NUMBER (PERL_INT_MAX / 2)
512
513 #define OpTYPE_set(o,type) \
514     STMT_START {                                \
515         o->op_type = (OPCODE)type;              \
516         o->op_ppaddr = PL_ppaddr[type];         \
517     } STMT_END
518
519 STATIC OP *
520 S_no_fh_allowed(pTHX_ OP *o)
521 {
522     PERL_ARGS_ASSERT_NO_FH_ALLOWED;
523
524     yyerror(Perl_form(aTHX_ "Missing comma after first argument to %s function",
525                  OP_DESC(o)));
526     return o;
527 }
528
529 STATIC OP *
530 S_too_few_arguments_pv(pTHX_ OP *o, const char* name, U32 flags)
531 {
532     PERL_ARGS_ASSERT_TOO_FEW_ARGUMENTS_PV;
533     yyerror_pv(Perl_form(aTHX_ "Not enough arguments for %s", name), flags);
534     return o;
535 }
536  
537 STATIC OP *
538 S_too_many_arguments_pv(pTHX_ OP *o, const char *name, U32 flags)
539 {
540     PERL_ARGS_ASSERT_TOO_MANY_ARGUMENTS_PV;
541
542     yyerror_pv(Perl_form(aTHX_ "Too many arguments for %s", name), flags);
543     return o;
544 }
545
546 STATIC void
547 S_bad_type_pv(pTHX_ I32 n, const char *t, const OP *o, const OP *kid)
548 {
549     PERL_ARGS_ASSERT_BAD_TYPE_PV;
550
551     yyerror_pv(Perl_form(aTHX_ "Type of arg %d to %s must be %s (not %s)",
552                  (int)n, PL_op_desc[(o)->op_type], t, OP_DESC(kid)), 0);
553 }
554
555 /* remove flags var, its unused in all callers, move to to right end since gv
556   and kid are always the same */
557 STATIC void
558 S_bad_type_gv(pTHX_ I32 n, GV *gv, const OP *kid, const char *t)
559 {
560     SV * const namesv = cv_name((CV *)gv, NULL, 0);
561     PERL_ARGS_ASSERT_BAD_TYPE_GV;
562  
563     yyerror_pv(Perl_form(aTHX_ "Type of arg %d to %"SVf" must be %s (not %s)",
564                  (int)n, SVfARG(namesv), t, OP_DESC(kid)), SvUTF8(namesv));
565 }
566
567 STATIC void
568 S_no_bareword_allowed(pTHX_ OP *o)
569 {
570     PERL_ARGS_ASSERT_NO_BAREWORD_ALLOWED;
571
572     qerror(Perl_mess(aTHX_
573                      "Bareword \"%"SVf"\" not allowed while \"strict subs\" in use",
574                      SVfARG(cSVOPo_sv)));
575     o->op_private &= ~OPpCONST_STRICT; /* prevent warning twice about the same OP */
576 }
577
578 /* "register" allocation */
579
580 PADOFFSET
581 Perl_allocmy(pTHX_ const char *const name, const STRLEN len, const U32 flags)
582 {
583     PADOFFSET off;
584     const bool is_our = (PL_parser->in_my == KEY_our);
585
586     PERL_ARGS_ASSERT_ALLOCMY;
587
588     if (flags & ~SVf_UTF8)
589         Perl_croak(aTHX_ "panic: allocmy illegal flag bits 0x%" UVxf,
590                    (UV)flags);
591
592     /* complain about "my $<special_var>" etc etc */
593     if (len &&
594         !(is_our ||
595           isALPHA(name[1]) ||
596           ((flags & SVf_UTF8) && isIDFIRST_utf8((U8 *)name+1)) ||
597           (name[1] == '_' && len > 2)))
598     {
599         if (!(flags & SVf_UTF8 && UTF8_IS_START(name[1]))
600          && isASCII(name[1])
601          && (!isPRINT(name[1]) || strchr("\t\n\r\f", name[1]))) {
602             yyerror(Perl_form(aTHX_ "Can't use global %c^%c%.*s in \"%s\"",
603                               name[0], toCTRL(name[1]), (int)(len - 2), name + 2,
604                               PL_parser->in_my == KEY_state ? "state" : "my"));
605         } else {
606             yyerror_pv(Perl_form(aTHX_ "Can't use global %.*s in \"%s\"", (int) len, name,
607                               PL_parser->in_my == KEY_state ? "state" : "my"), flags & SVf_UTF8);
608         }
609     }
610
611     /* allocate a spare slot and store the name in that slot */
612
613     off = pad_add_name_pvn(name, len,
614                        (is_our ? padadd_OUR :
615                         PL_parser->in_my == KEY_state ? padadd_STATE : 0),
616                     PL_parser->in_my_stash,
617                     (is_our
618                         /* $_ is always in main::, even with our */
619                         ? (PL_curstash && !memEQs(name,len,"$_")
620                             ? PL_curstash
621                             : PL_defstash)
622                         : NULL
623                     )
624     );
625     /* anon sub prototypes contains state vars should always be cloned,
626      * otherwise the state var would be shared between anon subs */
627
628     if (PL_parser->in_my == KEY_state && CvANON(PL_compcv))
629         CvCLONE_on(PL_compcv);
630
631     return off;
632 }
633
634 /*
635 =head1 Optree Manipulation Functions
636
637 =for apidoc alloccopstash
638
639 Available only under threaded builds, this function allocates an entry in
640 C<PL_stashpad> for the stash passed to it.
641
642 =cut
643 */
644
645 #ifdef USE_ITHREADS
646 PADOFFSET
647 Perl_alloccopstash(pTHX_ HV *hv)
648 {
649     PADOFFSET off = 0, o = 1;
650     bool found_slot = FALSE;
651
652     PERL_ARGS_ASSERT_ALLOCCOPSTASH;
653
654     if (PL_stashpad[PL_stashpadix] == hv) return PL_stashpadix;
655
656     for (; o < PL_stashpadmax; ++o) {
657         if (PL_stashpad[o] == hv) return PL_stashpadix = o;
658         if (!PL_stashpad[o] || SvTYPE(PL_stashpad[o]) != SVt_PVHV)
659             found_slot = TRUE, off = o;
660     }
661     if (!found_slot) {
662         Renew(PL_stashpad, PL_stashpadmax + 10, HV *);
663         Zero(PL_stashpad + PL_stashpadmax, 10, HV *);
664         off = PL_stashpadmax;
665         PL_stashpadmax += 10;
666     }
667
668     PL_stashpad[PL_stashpadix = off] = hv;
669     return off;
670 }
671 #endif
672
673 /* free the body of an op without examining its contents.
674  * Always use this rather than FreeOp directly */
675
676 static void
677 S_op_destroy(pTHX_ OP *o)
678 {
679     FreeOp(o);
680 }
681
682 /* Destructor */
683
684 /*
685 =for apidoc Am|void|op_free|OP *o
686
687 Free an op.  Only use this when an op is no longer linked to from any
688 optree.
689
690 =cut
691 */
692
693 void
694 Perl_op_free(pTHX_ OP *o)
695 {
696     dVAR;
697     OPCODE type;
698     SSize_t defer_ix = -1;
699     SSize_t defer_stack_alloc = 0;
700     OP **defer_stack = NULL;
701
702     do {
703
704         /* Though ops may be freed twice, freeing the op after its slab is a
705            big no-no. */
706         assert(!o || !o->op_slabbed || OpSLAB(o)->opslab_refcnt != ~(size_t)0);
707         /* During the forced freeing of ops after compilation failure, kidops
708            may be freed before their parents. */
709         if (!o || o->op_type == OP_FREED)
710             continue;
711
712         type = o->op_type;
713
714         /* an op should only ever acquire op_private flags that we know about.
715          * If this fails, you may need to fix something in regen/op_private */
716         if (o->op_ppaddr == PL_ppaddr[o->op_type]) {
717             assert(!(o->op_private & ~PL_op_private_valid[type]));
718         }
719
720         if (o->op_private & OPpREFCOUNTED) {
721             switch (type) {
722             case OP_LEAVESUB:
723             case OP_LEAVESUBLV:
724             case OP_LEAVEEVAL:
725             case OP_LEAVE:
726             case OP_SCOPE:
727             case OP_LEAVEWRITE:
728                 {
729                 PADOFFSET refcnt;
730                 OP_REFCNT_LOCK;
731                 refcnt = OpREFCNT_dec(o);
732                 OP_REFCNT_UNLOCK;
733                 if (refcnt) {
734                     /* Need to find and remove any pattern match ops from the list
735                        we maintain for reset().  */
736                     find_and_forget_pmops(o);
737                     continue;
738                 }
739                 }
740                 break;
741             default:
742                 break;
743             }
744         }
745
746         /* Call the op_free hook if it has been set. Do it now so that it's called
747          * at the right time for refcounted ops, but still before all of the kids
748          * are freed. */
749         CALL_OPFREEHOOK(o);
750
751         if (o->op_flags & OPf_KIDS) {
752             OP *kid, *nextkid;
753             for (kid = cUNOPo->op_first; kid; kid = nextkid) {
754                 nextkid = OpSIBLING(kid); /* Get before next freeing kid */
755                 if (!kid || kid->op_type == OP_FREED)
756                     /* During the forced freeing of ops after
757                        compilation failure, kidops may be freed before
758                        their parents. */
759                     continue;
760                 if (!(kid->op_flags & OPf_KIDS))
761                     /* If it has no kids, just free it now */
762                     op_free(kid);
763                 else
764                     DEFER_OP(kid);
765             }
766         }
767         if (type == OP_NULL)
768             type = (OPCODE)o->op_targ;
769
770         if (o->op_slabbed)
771             Slab_to_rw(OpSLAB(o));
772
773         /* COP* is not cleared by op_clear() so that we may track line
774          * numbers etc even after null() */
775         if (type == OP_NEXTSTATE || type == OP_DBSTATE) {
776             cop_free((COP*)o);
777         }
778
779         op_clear(o);
780         FreeOp(o);
781 #ifdef DEBUG_LEAKING_SCALARS
782         if (PL_op == o)
783             PL_op = NULL;
784 #endif
785     } while ( (o = POP_DEFERRED_OP()) );
786
787     Safefree(defer_stack);
788 }
789
790 /* S_op_clear_gv(): free a GV attached to an OP */
791
792 #ifdef USE_ITHREADS
793 void S_op_clear_gv(pTHX_ OP *o, PADOFFSET *ixp)
794 #else
795 void S_op_clear_gv(pTHX_ OP *o, SV**svp)
796 #endif
797 {
798
799     GV *gv = (o->op_type == OP_GV || o->op_type == OP_GVSV
800             || o->op_type == OP_MULTIDEREF)
801 #ifdef USE_ITHREADS
802                 && PL_curpad
803                 ? ((GV*)PAD_SVl(*ixp)) : NULL;
804 #else
805                 ? (GV*)(*svp) : NULL;
806 #endif
807     /* It's possible during global destruction that the GV is freed
808        before the optree. Whilst the SvREFCNT_inc is happy to bump from
809        0 to 1 on a freed SV, the corresponding SvREFCNT_dec from 1 to 0
810        will trigger an assertion failure, because the entry to sv_clear
811        checks that the scalar is not already freed.  A check of for
812        !SvIS_FREED(gv) turns out to be invalid, because during global
813        destruction the reference count can be forced down to zero
814        (with SVf_BREAK set).  In which case raising to 1 and then
815        dropping to 0 triggers cleanup before it should happen.  I
816        *think* that this might actually be a general, systematic,
817        weakness of the whole idea of SVf_BREAK, in that code *is*
818        allowed to raise and lower references during global destruction,
819        so any *valid* code that happens to do this during global
820        destruction might well trigger premature cleanup.  */
821     bool still_valid = gv && SvREFCNT(gv);
822
823     if (still_valid)
824         SvREFCNT_inc_simple_void(gv);
825 #ifdef USE_ITHREADS
826     if (*ixp > 0) {
827         pad_swipe(*ixp, TRUE);
828         *ixp = 0;
829     }
830 #else
831     SvREFCNT_dec(*svp);
832     *svp = NULL;
833 #endif
834     if (still_valid) {
835         int try_downgrade = SvREFCNT(gv) == 2;
836         SvREFCNT_dec_NN(gv);
837         if (try_downgrade)
838             gv_try_downgrade(gv);
839     }
840 }
841
842
843 void
844 Perl_op_clear(pTHX_ OP *o)
845 {
846
847     dVAR;
848
849     PERL_ARGS_ASSERT_OP_CLEAR;
850
851     switch (o->op_type) {
852     case OP_NULL:       /* Was holding old type, if any. */
853         /* FALLTHROUGH */
854     case OP_ENTERTRY:
855     case OP_ENTEREVAL:  /* Was holding hints. */
856         o->op_targ = 0;
857         break;
858     default:
859         if (!(o->op_flags & OPf_REF)
860             || (PL_check[o->op_type] != Perl_ck_ftst))
861             break;
862         /* FALLTHROUGH */
863     case OP_GVSV:
864     case OP_GV:
865     case OP_AELEMFAST:
866 #ifdef USE_ITHREADS
867             S_op_clear_gv(aTHX_ o, &(cPADOPx(o)->op_padix));
868 #else
869             S_op_clear_gv(aTHX_ o, &(cSVOPx(o)->op_sv));
870 #endif
871         break;
872     case OP_METHOD_REDIR:
873     case OP_METHOD_REDIR_SUPER:
874 #ifdef USE_ITHREADS
875         if (cMETHOPx(o)->op_rclass_targ) {
876             pad_swipe(cMETHOPx(o)->op_rclass_targ, 1);
877             cMETHOPx(o)->op_rclass_targ = 0;
878         }
879 #else
880         SvREFCNT_dec(cMETHOPx(o)->op_rclass_sv);
881         cMETHOPx(o)->op_rclass_sv = NULL;
882 #endif
883     case OP_METHOD_NAMED:
884     case OP_METHOD_SUPER:
885         SvREFCNT_dec(cMETHOPx(o)->op_u.op_meth_sv);
886         cMETHOPx(o)->op_u.op_meth_sv = NULL;
887 #ifdef USE_ITHREADS
888         if (o->op_targ) {
889             pad_swipe(o->op_targ, 1);
890             o->op_targ = 0;
891         }
892 #endif
893         break;
894     case OP_CONST:
895     case OP_HINTSEVAL:
896         SvREFCNT_dec(cSVOPo->op_sv);
897         cSVOPo->op_sv = NULL;
898 #ifdef USE_ITHREADS
899         /** Bug #15654
900           Even if op_clear does a pad_free for the target of the op,
901           pad_free doesn't actually remove the sv that exists in the pad;
902           instead it lives on. This results in that it could be reused as 
903           a target later on when the pad was reallocated.
904         **/
905         if(o->op_targ) {
906           pad_swipe(o->op_targ,1);
907           o->op_targ = 0;
908         }
909 #endif
910         break;
911     case OP_DUMP:
912     case OP_GOTO:
913     case OP_NEXT:
914     case OP_LAST:
915     case OP_REDO:
916         if (o->op_flags & (OPf_SPECIAL|OPf_STACKED|OPf_KIDS))
917             break;
918         /* FALLTHROUGH */
919     case OP_TRANS:
920     case OP_TRANSR:
921         if (o->op_private & (OPpTRANS_FROM_UTF|OPpTRANS_TO_UTF)) {
922             assert(o->op_type == OP_TRANS || o->op_type == OP_TRANSR);
923 #ifdef USE_ITHREADS
924             if (cPADOPo->op_padix > 0) {
925                 pad_swipe(cPADOPo->op_padix, TRUE);
926                 cPADOPo->op_padix = 0;
927             }
928 #else
929             SvREFCNT_dec(cSVOPo->op_sv);
930             cSVOPo->op_sv = NULL;
931 #endif
932         }
933         else {
934             PerlMemShared_free(cPVOPo->op_pv);
935             cPVOPo->op_pv = NULL;
936         }
937         break;
938     case OP_SUBST:
939         op_free(cPMOPo->op_pmreplrootu.op_pmreplroot);
940         goto clear_pmop;
941     case OP_PUSHRE:
942 #ifdef USE_ITHREADS
943         if (cPMOPo->op_pmreplrootu.op_pmtargetoff) {
944             pad_swipe(cPMOPo->op_pmreplrootu.op_pmtargetoff, TRUE);
945         }
946 #else
947         SvREFCNT_dec(MUTABLE_SV(cPMOPo->op_pmreplrootu.op_pmtargetgv));
948 #endif
949         /* FALLTHROUGH */
950     case OP_MATCH:
951     case OP_QR:
952     clear_pmop:
953         if (!(cPMOPo->op_pmflags & PMf_CODELIST_PRIVATE))
954             op_free(cPMOPo->op_code_list);
955         cPMOPo->op_code_list = NULL;
956         forget_pmop(cPMOPo);
957         cPMOPo->op_pmreplrootu.op_pmreplroot = NULL;
958         /* we use the same protection as the "SAFE" version of the PM_ macros
959          * here since sv_clean_all might release some PMOPs
960          * after PL_regex_padav has been cleared
961          * and the clearing of PL_regex_padav needs to
962          * happen before sv_clean_all
963          */
964 #ifdef USE_ITHREADS
965         if(PL_regex_pad) {        /* We could be in destruction */
966             const IV offset = (cPMOPo)->op_pmoffset;
967             ReREFCNT_dec(PM_GETRE(cPMOPo));
968             PL_regex_pad[offset] = &PL_sv_undef;
969             sv_catpvn_nomg(PL_regex_pad[0], (const char *)&offset,
970                            sizeof(offset));
971         }
972 #else
973         ReREFCNT_dec(PM_GETRE(cPMOPo));
974         PM_SETRE(cPMOPo, NULL);
975 #endif
976
977         break;
978
979     case OP_MULTIDEREF:
980         {
981             UNOP_AUX_item *items = cUNOP_AUXo->op_aux;
982             UV actions = items->uv;
983             bool last = 0;
984             bool is_hash = FALSE;
985
986             while (!last) {
987                 switch (actions & MDEREF_ACTION_MASK) {
988
989                 case MDEREF_reload:
990                     actions = (++items)->uv;
991                     continue;
992
993                 case MDEREF_HV_padhv_helem:
994                     is_hash = TRUE;
995                 case MDEREF_AV_padav_aelem:
996                     pad_free((++items)->pad_offset);
997                     goto do_elem;
998
999                 case MDEREF_HV_gvhv_helem:
1000                     is_hash = TRUE;
1001                 case MDEREF_AV_gvav_aelem:
1002 #ifdef USE_ITHREADS
1003                     S_op_clear_gv(aTHX_ o, &((++items)->pad_offset));
1004 #else
1005                     S_op_clear_gv(aTHX_ o, &((++items)->sv));
1006 #endif
1007                     goto do_elem;
1008
1009                 case MDEREF_HV_gvsv_vivify_rv2hv_helem:
1010                     is_hash = TRUE;
1011                 case MDEREF_AV_gvsv_vivify_rv2av_aelem:
1012 #ifdef USE_ITHREADS
1013                     S_op_clear_gv(aTHX_ o, &((++items)->pad_offset));
1014 #else
1015                     S_op_clear_gv(aTHX_ o, &((++items)->sv));
1016 #endif
1017                     goto do_vivify_rv2xv_elem;
1018
1019                 case MDEREF_HV_padsv_vivify_rv2hv_helem:
1020                     is_hash = TRUE;
1021                 case MDEREF_AV_padsv_vivify_rv2av_aelem:
1022                     pad_free((++items)->pad_offset);
1023                     goto do_vivify_rv2xv_elem;
1024
1025                 case MDEREF_HV_pop_rv2hv_helem:
1026                 case MDEREF_HV_vivify_rv2hv_helem:
1027                     is_hash = TRUE;
1028                 do_vivify_rv2xv_elem:
1029                 case MDEREF_AV_pop_rv2av_aelem:
1030                 case MDEREF_AV_vivify_rv2av_aelem:
1031                 do_elem:
1032                     switch (actions & MDEREF_INDEX_MASK) {
1033                     case MDEREF_INDEX_none:
1034                         last = 1;
1035                         break;
1036                     case MDEREF_INDEX_const:
1037                         if (is_hash) {
1038 #ifdef USE_ITHREADS
1039                             /* see RT #15654 */
1040                             pad_swipe((++items)->pad_offset, 1);
1041 #else
1042                             SvREFCNT_dec((++items)->sv);
1043 #endif
1044                         }
1045                         else
1046                             items++;
1047                         break;
1048                     case MDEREF_INDEX_padsv:
1049                         pad_free((++items)->pad_offset);
1050                         break;
1051                     case MDEREF_INDEX_gvsv:
1052 #ifdef USE_ITHREADS
1053                         S_op_clear_gv(aTHX_ o, &((++items)->pad_offset));
1054 #else
1055                         S_op_clear_gv(aTHX_ o, &((++items)->sv));
1056 #endif
1057                         break;
1058                     }
1059
1060                     if (actions & MDEREF_FLAG_last)
1061                         last = 1;
1062                     is_hash = FALSE;
1063
1064                     break;
1065
1066                 default:
1067                     assert(0);
1068                     last = 1;
1069                     break;
1070
1071                 } /* switch */
1072
1073                 actions >>= MDEREF_SHIFT;
1074             } /* while */
1075
1076             /* start of malloc is at op_aux[-1], where the length is
1077              * stored */
1078             PerlMemShared_free(cUNOP_AUXo->op_aux - 1);
1079         }
1080         break;
1081     }
1082
1083     if (o->op_targ > 0) {
1084         pad_free(o->op_targ);
1085         o->op_targ = 0;
1086     }
1087 }
1088
1089 STATIC void
1090 S_cop_free(pTHX_ COP* cop)
1091 {
1092     PERL_ARGS_ASSERT_COP_FREE;
1093
1094     CopFILE_free(cop);
1095     if (! specialWARN(cop->cop_warnings))
1096         PerlMemShared_free(cop->cop_warnings);
1097     cophh_free(CopHINTHASH_get(cop));
1098     if (PL_curcop == cop)
1099        PL_curcop = NULL;
1100 }
1101
1102 STATIC void
1103 S_forget_pmop(pTHX_ PMOP *const o
1104               )
1105 {
1106     HV * const pmstash = PmopSTASH(o);
1107
1108     PERL_ARGS_ASSERT_FORGET_PMOP;
1109
1110     if (pmstash && !SvIS_FREED(pmstash) && SvMAGICAL(pmstash)) {
1111         MAGIC * const mg = mg_find((const SV *)pmstash, PERL_MAGIC_symtab);
1112         if (mg) {
1113             PMOP **const array = (PMOP**) mg->mg_ptr;
1114             U32 count = mg->mg_len / sizeof(PMOP**);
1115             U32 i = count;
1116
1117             while (i--) {
1118                 if (array[i] == o) {
1119                     /* Found it. Move the entry at the end to overwrite it.  */
1120                     array[i] = array[--count];
1121                     mg->mg_len = count * sizeof(PMOP**);
1122                     /* Could realloc smaller at this point always, but probably
1123                        not worth it. Probably worth free()ing if we're the
1124                        last.  */
1125                     if(!count) {
1126                         Safefree(mg->mg_ptr);
1127                         mg->mg_ptr = NULL;
1128                     }
1129                     break;
1130                 }
1131             }
1132         }
1133     }
1134     if (PL_curpm == o) 
1135         PL_curpm = NULL;
1136 }
1137
1138 STATIC void
1139 S_find_and_forget_pmops(pTHX_ OP *o)
1140 {
1141     PERL_ARGS_ASSERT_FIND_AND_FORGET_PMOPS;
1142
1143     if (o->op_flags & OPf_KIDS) {
1144         OP *kid = cUNOPo->op_first;
1145         while (kid) {
1146             switch (kid->op_type) {
1147             case OP_SUBST:
1148             case OP_PUSHRE:
1149             case OP_MATCH:
1150             case OP_QR:
1151                 forget_pmop((PMOP*)kid);
1152             }
1153             find_and_forget_pmops(kid);
1154             kid = OpSIBLING(kid);
1155         }
1156     }
1157 }
1158
1159 /*
1160 =for apidoc Am|void|op_null|OP *o
1161
1162 Neutralizes an op when it is no longer needed, but is still linked to from
1163 other ops.
1164
1165 =cut
1166 */
1167
1168 void
1169 Perl_op_null(pTHX_ OP *o)
1170 {
1171     dVAR;
1172
1173     PERL_ARGS_ASSERT_OP_NULL;
1174
1175     if (o->op_type == OP_NULL)
1176         return;
1177     op_clear(o);
1178     o->op_targ = o->op_type;
1179     OpTYPE_set(o, OP_NULL);
1180 }
1181
1182 void
1183 Perl_op_refcnt_lock(pTHX)
1184 {
1185 #ifdef USE_ITHREADS
1186     dVAR;
1187 #endif
1188     PERL_UNUSED_CONTEXT;
1189     OP_REFCNT_LOCK;
1190 }
1191
1192 void
1193 Perl_op_refcnt_unlock(pTHX)
1194 {
1195 #ifdef USE_ITHREADS
1196     dVAR;
1197 #endif
1198     PERL_UNUSED_CONTEXT;
1199     OP_REFCNT_UNLOCK;
1200 }
1201
1202
1203 /*
1204 =for apidoc op_sibling_splice
1205
1206 A general function for editing the structure of an existing chain of
1207 op_sibling nodes.  By analogy with the perl-level C<splice()> function, allows
1208 you to delete zero or more sequential nodes, replacing them with zero or
1209 more different nodes.  Performs the necessary op_first/op_last
1210 housekeeping on the parent node and op_sibling manipulation on the
1211 children.  The last deleted node will be marked as as the last node by
1212 updating the op_sibling/op_sibparent or op_moresib field as appropriate.
1213
1214 Note that op_next is not manipulated, and nodes are not freed; that is the
1215 responsibility of the caller.  It also won't create a new list op for an
1216 empty list etc; use higher-level functions like op_append_elem() for that.
1217
1218 C<parent> is the parent node of the sibling chain. It may passed as C<NULL> if
1219 the splicing doesn't affect the first or last op in the chain.
1220
1221 C<start> is the node preceding the first node to be spliced.  Node(s)
1222 following it will be deleted, and ops will be inserted after it.  If it is
1223 C<NULL>, the first node onwards is deleted, and nodes are inserted at the
1224 beginning.
1225
1226 C<del_count> is the number of nodes to delete.  If zero, no nodes are deleted.
1227 If -1 or greater than or equal to the number of remaining kids, all
1228 remaining kids are deleted.
1229
1230 C<insert> is the first of a chain of nodes to be inserted in place of the nodes.
1231 If C<NULL>, no nodes are inserted.
1232
1233 The head of the chain of deleted ops is returned, or C<NULL> if no ops were
1234 deleted.
1235
1236 For example:
1237
1238     action                    before      after         returns
1239     ------                    -----       -----         -------
1240
1241                               P           P
1242     splice(P, A, 2, X-Y-Z)    |           |             B-C
1243                               A-B-C-D     A-X-Y-Z-D
1244
1245                               P           P
1246     splice(P, NULL, 1, X-Y)   |           |             A
1247                               A-B-C-D     X-Y-B-C-D
1248
1249                               P           P
1250     splice(P, NULL, 3, NULL)  |           |             A-B-C
1251                               A-B-C-D     D
1252
1253                               P           P
1254     splice(P, B, 0, X-Y)      |           |             NULL
1255                               A-B-C-D     A-B-X-Y-C-D
1256
1257
1258 For lower-level direct manipulation of C<op_sibparent> and C<op_moresib>,
1259 see C<L</OpMORESIB_set>>, C<L</OpLASTSIB_set>>, C<L</OpMAYBESIB_set>>.
1260
1261 =cut
1262 */
1263
1264 OP *
1265 Perl_op_sibling_splice(OP *parent, OP *start, int del_count, OP* insert)
1266 {
1267     OP *first;
1268     OP *rest;
1269     OP *last_del = NULL;
1270     OP *last_ins = NULL;
1271
1272     if (start)
1273         first = OpSIBLING(start);
1274     else if (!parent)
1275         goto no_parent;
1276     else
1277         first = cLISTOPx(parent)->op_first;
1278
1279     assert(del_count >= -1);
1280
1281     if (del_count && first) {
1282         last_del = first;
1283         while (--del_count && OpHAS_SIBLING(last_del))
1284             last_del = OpSIBLING(last_del);
1285         rest = OpSIBLING(last_del);
1286         OpLASTSIB_set(last_del, NULL);
1287     }
1288     else
1289         rest = first;
1290
1291     if (insert) {
1292         last_ins = insert;
1293         while (OpHAS_SIBLING(last_ins))
1294             last_ins = OpSIBLING(last_ins);
1295         OpMAYBESIB_set(last_ins, rest, NULL);
1296     }
1297     else
1298         insert = rest;
1299
1300     if (start) {
1301         OpMAYBESIB_set(start, insert, NULL);
1302     }
1303     else {
1304         if (!parent)
1305             goto no_parent;
1306         cLISTOPx(parent)->op_first = insert;
1307         if (insert)
1308             parent->op_flags |= OPf_KIDS;
1309         else
1310             parent->op_flags &= ~OPf_KIDS;
1311     }
1312
1313     if (!rest) {
1314         /* update op_last etc */
1315         U32 type;
1316         OP *lastop;
1317
1318         if (!parent)
1319             goto no_parent;
1320
1321         /* ought to use OP_CLASS(parent) here, but that can't handle
1322          * ex-foo OP_NULL ops. Also note that XopENTRYCUSTOM() can't
1323          * either */
1324         type = parent->op_type;
1325         if (type == OP_CUSTOM) {
1326             dTHX;
1327             type = XopENTRYCUSTOM(parent, xop_class);
1328         }
1329         else {
1330             if (type == OP_NULL)
1331                 type = parent->op_targ;
1332             type = PL_opargs[type] & OA_CLASS_MASK;
1333         }
1334
1335         lastop = last_ins ? last_ins : start ? start : NULL;
1336         if (   type == OA_BINOP
1337             || type == OA_LISTOP
1338             || type == OA_PMOP
1339             || type == OA_LOOP
1340         )
1341             cLISTOPx(parent)->op_last = lastop;
1342
1343         if (lastop)
1344             OpLASTSIB_set(lastop, parent);
1345     }
1346     return last_del ? first : NULL;
1347
1348   no_parent:
1349     Perl_croak_nocontext("panic: op_sibling_splice(): NULL parent");
1350 }
1351
1352
1353 #ifdef PERL_OP_PARENT
1354
1355 /*
1356 =for apidoc op_parent
1357
1358 Returns the parent OP of C<o>, if it has a parent. Returns C<NULL> otherwise.
1359 This function is only available on perls built with C<-DPERL_OP_PARENT>.
1360
1361 =cut
1362 */
1363
1364 OP *
1365 Perl_op_parent(OP *o)
1366 {
1367     PERL_ARGS_ASSERT_OP_PARENT;
1368     while (OpHAS_SIBLING(o))
1369         o = OpSIBLING(o);
1370     return o->op_sibparent;
1371 }
1372
1373 #endif
1374
1375
1376 /* replace the sibling following start with a new UNOP, which becomes
1377  * the parent of the original sibling; e.g.
1378  *
1379  *  op_sibling_newUNOP(P, A, unop-args...)
1380  *
1381  *  P              P
1382  *  |      becomes |
1383  *  A-B-C          A-U-C
1384  *                   |
1385  *                   B
1386  *
1387  * where U is the new UNOP.
1388  *
1389  * parent and start args are the same as for op_sibling_splice();
1390  * type and flags args are as newUNOP().
1391  *
1392  * Returns the new UNOP.
1393  */
1394
1395 OP *
1396 S_op_sibling_newUNOP(pTHX_ OP *parent, OP *start, I32 type, I32 flags)
1397 {
1398     OP *kid, *newop;
1399
1400     kid = op_sibling_splice(parent, start, 1, NULL);
1401     newop = newUNOP(type, flags, kid);
1402     op_sibling_splice(parent, start, 0, newop);
1403     return newop;
1404 }
1405
1406
1407 /* lowest-level newLOGOP-style function - just allocates and populates
1408  * the struct. Higher-level stuff should be done by S_new_logop() /
1409  * newLOGOP(). This function exists mainly to avoid op_first assignment
1410  * being spread throughout this file.
1411  */
1412
1413 LOGOP *
1414 S_alloc_LOGOP(pTHX_ I32 type, OP *first, OP* other)
1415 {
1416     dVAR;
1417     LOGOP *logop;
1418     OP *kid = first;
1419     NewOp(1101, logop, 1, LOGOP);
1420     OpTYPE_set(logop, type);
1421     logop->op_first = first;
1422     logop->op_other = other;
1423     logop->op_flags = OPf_KIDS;
1424     while (kid && OpHAS_SIBLING(kid))
1425         kid = OpSIBLING(kid);
1426     if (kid)
1427         OpLASTSIB_set(kid, (OP*)logop);
1428     return logop;
1429 }
1430
1431
1432 /* Contextualizers */
1433
1434 /*
1435 =for apidoc Am|OP *|op_contextualize|OP *o|I32 context
1436
1437 Applies a syntactic context to an op tree representing an expression.
1438 C<o> is the op tree, and C<context> must be C<G_SCALAR>, C<G_ARRAY>,
1439 or C<G_VOID> to specify the context to apply.  The modified op tree
1440 is returned.
1441
1442 =cut
1443 */
1444
1445 OP *
1446 Perl_op_contextualize(pTHX_ OP *o, I32 context)
1447 {
1448     PERL_ARGS_ASSERT_OP_CONTEXTUALIZE;
1449     switch (context) {
1450         case G_SCALAR: return scalar(o);
1451         case G_ARRAY:  return list(o);
1452         case G_VOID:   return scalarvoid(o);
1453         default:
1454             Perl_croak(aTHX_ "panic: op_contextualize bad context %ld",
1455                        (long) context);
1456     }
1457 }
1458
1459 /*
1460
1461 =for apidoc Am|OP*|op_linklist|OP *o
1462 This function is the implementation of the L</LINKLIST> macro.  It should
1463 not be called directly.
1464
1465 =cut
1466 */
1467
1468 OP *
1469 Perl_op_linklist(pTHX_ OP *o)
1470 {
1471     OP *first;
1472
1473     PERL_ARGS_ASSERT_OP_LINKLIST;
1474
1475     if (o->op_next)
1476         return o->op_next;
1477
1478     /* establish postfix order */
1479     first = cUNOPo->op_first;
1480     if (first) {
1481         OP *kid;
1482         o->op_next = LINKLIST(first);
1483         kid = first;
1484         for (;;) {
1485             OP *sibl = OpSIBLING(kid);
1486             if (sibl) {
1487                 kid->op_next = LINKLIST(sibl);
1488                 kid = sibl;
1489             } else {
1490                 kid->op_next = o;
1491                 break;
1492             }
1493         }
1494     }
1495     else
1496         o->op_next = o;
1497
1498     return o->op_next;
1499 }
1500
1501 static OP *
1502 S_scalarkids(pTHX_ OP *o)
1503 {
1504     if (o && o->op_flags & OPf_KIDS) {
1505         OP *kid;
1506         for (kid = cLISTOPo->op_first; kid; kid = OpSIBLING(kid))
1507             scalar(kid);
1508     }
1509     return o;
1510 }
1511
1512 STATIC OP *
1513 S_scalarboolean(pTHX_ OP *o)
1514 {
1515     PERL_ARGS_ASSERT_SCALARBOOLEAN;
1516
1517     if (o->op_type == OP_SASSIGN && cBINOPo->op_first->op_type == OP_CONST
1518      && !(cBINOPo->op_first->op_flags & OPf_SPECIAL)) {
1519         if (ckWARN(WARN_SYNTAX)) {
1520             const line_t oldline = CopLINE(PL_curcop);
1521
1522             if (PL_parser && PL_parser->copline != NOLINE) {
1523                 /* This ensures that warnings are reported at the first line
1524                    of the conditional, not the last.  */
1525                 CopLINE_set(PL_curcop, PL_parser->copline);
1526             }
1527             Perl_warner(aTHX_ packWARN(WARN_SYNTAX), "Found = in conditional, should be ==");
1528             CopLINE_set(PL_curcop, oldline);
1529         }
1530     }
1531     return scalar(o);
1532 }
1533
1534 static SV *
1535 S_op_varname(pTHX_ const OP *o)
1536 {
1537     assert(o);
1538     assert(o->op_type == OP_PADAV || o->op_type == OP_RV2AV ||
1539            o->op_type == OP_PADHV || o->op_type == OP_RV2HV);
1540     {
1541         const char funny  = o->op_type == OP_PADAV
1542                          || o->op_type == OP_RV2AV ? '@' : '%';
1543         if (o->op_type == OP_RV2AV || o->op_type == OP_RV2HV) {
1544             GV *gv;
1545             if (cUNOPo->op_first->op_type != OP_GV
1546              || !(gv = cGVOPx_gv(cUNOPo->op_first)))
1547                 return NULL;
1548             return varname(gv, funny, 0, NULL, 0, 1);
1549         }
1550         return
1551             varname(MUTABLE_GV(PL_compcv), funny, o->op_targ, NULL, 0, 1);
1552     }
1553 }
1554
1555 static void
1556 S_op_pretty(pTHX_ const OP *o, SV **retsv, const char **retpv)
1557 { /* or not so pretty :-) */
1558     if (o->op_type == OP_CONST) {
1559         *retsv = cSVOPo_sv;
1560         if (SvPOK(*retsv)) {
1561             SV *sv = *retsv;
1562             *retsv = sv_newmortal();
1563             pv_pretty(*retsv, SvPVX_const(sv), SvCUR(sv), 32, NULL, NULL,
1564                       PERL_PV_PRETTY_DUMP |PERL_PV_ESCAPE_UNI_DETECT);
1565         }
1566         else if (!SvOK(*retsv))
1567             *retpv = "undef";
1568     }
1569     else *retpv = "...";
1570 }
1571
1572 static void
1573 S_scalar_slice_warning(pTHX_ const OP *o)
1574 {
1575     OP *kid;
1576     const char lbrack =
1577         o->op_type == OP_HSLICE ? '{' : '[';
1578     const char rbrack =
1579         o->op_type == OP_HSLICE ? '}' : ']';
1580     SV *name;
1581     SV *keysv = NULL; /* just to silence compiler warnings */
1582     const char *key = NULL;
1583
1584     if (!(o->op_private & OPpSLICEWARNING))
1585         return;
1586     if (PL_parser && PL_parser->error_count)
1587         /* This warning can be nonsensical when there is a syntax error. */
1588         return;
1589
1590     kid = cLISTOPo->op_first;
1591     kid = OpSIBLING(kid); /* get past pushmark */
1592     /* weed out false positives: any ops that can return lists */
1593     switch (kid->op_type) {
1594     case OP_BACKTICK:
1595     case OP_GLOB:
1596     case OP_READLINE:
1597     case OP_MATCH:
1598     case OP_RV2AV:
1599     case OP_EACH:
1600     case OP_VALUES:
1601     case OP_KEYS:
1602     case OP_SPLIT:
1603     case OP_LIST:
1604     case OP_SORT:
1605     case OP_REVERSE:
1606     case OP_ENTERSUB:
1607     case OP_CALLER:
1608     case OP_LSTAT:
1609     case OP_STAT:
1610     case OP_READDIR:
1611     case OP_SYSTEM:
1612     case OP_TMS:
1613     case OP_LOCALTIME:
1614     case OP_GMTIME:
1615     case OP_ENTEREVAL:
1616         return;
1617     }
1618
1619     /* Don't warn if we have a nulled list either. */
1620     if (kid->op_type == OP_NULL && kid->op_targ == OP_LIST)
1621         return;
1622
1623     assert(OpSIBLING(kid));
1624     name = S_op_varname(aTHX_ OpSIBLING(kid));
1625     if (!name) /* XS module fiddling with the op tree */
1626         return;
1627     S_op_pretty(aTHX_ kid, &keysv, &key);
1628     assert(SvPOK(name));
1629     sv_chop(name,SvPVX(name)+1);
1630     if (key)
1631        /* diag_listed_as: Scalar value @%s[%s] better written as $%s[%s] */
1632         Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
1633                    "Scalar value @%"SVf"%c%s%c better written as $%"SVf
1634                    "%c%s%c",
1635                     SVfARG(name), lbrack, key, rbrack, SVfARG(name),
1636                     lbrack, key, rbrack);
1637     else
1638        /* diag_listed_as: Scalar value @%s[%s] better written as $%s[%s] */
1639         Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
1640                    "Scalar value @%"SVf"%c%"SVf"%c better written as $%"
1641                     SVf"%c%"SVf"%c",
1642                     SVfARG(name), lbrack, SVfARG(keysv), rbrack,
1643                     SVfARG(name), lbrack, SVfARG(keysv), rbrack);
1644 }
1645
1646 OP *
1647 Perl_scalar(pTHX_ OP *o)
1648 {
1649     OP *kid;
1650
1651     /* assumes no premature commitment */
1652     if (!o || (PL_parser && PL_parser->error_count)
1653          || (o->op_flags & OPf_WANT)
1654          || o->op_type == OP_RETURN)
1655     {
1656         return o;
1657     }
1658
1659     o->op_flags = (o->op_flags & ~OPf_WANT) | OPf_WANT_SCALAR;
1660
1661     switch (o->op_type) {
1662     case OP_REPEAT:
1663         scalar(cBINOPo->op_first);
1664         if (o->op_private & OPpREPEAT_DOLIST) {
1665             kid = cLISTOPx(cUNOPo->op_first)->op_first;
1666             assert(kid->op_type == OP_PUSHMARK);
1667             if (OpHAS_SIBLING(kid) && !OpHAS_SIBLING(OpSIBLING(kid))) {
1668                 op_null(cLISTOPx(cUNOPo->op_first)->op_first);
1669                 o->op_private &=~ OPpREPEAT_DOLIST;
1670             }
1671         }
1672         break;
1673     case OP_OR:
1674     case OP_AND:
1675     case OP_COND_EXPR:
1676         for (kid = OpSIBLING(cUNOPo->op_first); kid; kid = OpSIBLING(kid))
1677             scalar(kid);
1678         break;
1679         /* FALLTHROUGH */
1680     case OP_SPLIT:
1681     case OP_MATCH:
1682     case OP_QR:
1683     case OP_SUBST:
1684     case OP_NULL:
1685     default:
1686         if (o->op_flags & OPf_KIDS) {
1687             for (kid = cUNOPo->op_first; kid; kid = OpSIBLING(kid))
1688                 scalar(kid);
1689         }
1690         break;
1691     case OP_LEAVE:
1692     case OP_LEAVETRY:
1693         kid = cLISTOPo->op_first;
1694         scalar(kid);
1695         kid = OpSIBLING(kid);
1696     do_kids:
1697         while (kid) {
1698             OP *sib = OpSIBLING(kid);
1699             if (sib && kid->op_type != OP_LEAVEWHEN
1700              && (  OpHAS_SIBLING(sib) || sib->op_type != OP_NULL
1701                 || (  sib->op_targ != OP_NEXTSTATE
1702                    && sib->op_targ != OP_DBSTATE  )))
1703                 scalarvoid(kid);
1704             else
1705                 scalar(kid);
1706             kid = sib;
1707         }
1708         PL_curcop = &PL_compiling;
1709         break;
1710     case OP_SCOPE:
1711     case OP_LINESEQ:
1712     case OP_LIST:
1713         kid = cLISTOPo->op_first;
1714         goto do_kids;
1715     case OP_SORT:
1716         Perl_ck_warner(aTHX_ packWARN(WARN_VOID), "Useless use of sort in scalar context");
1717         break;
1718     case OP_KVHSLICE:
1719     case OP_KVASLICE:
1720     {
1721         /* Warn about scalar context */
1722         const char lbrack = o->op_type == OP_KVHSLICE ? '{' : '[';
1723         const char rbrack = o->op_type == OP_KVHSLICE ? '}' : ']';
1724         SV *name;
1725         SV *keysv;
1726         const char *key = NULL;
1727
1728         /* This warning can be nonsensical when there is a syntax error. */
1729         if (PL_parser && PL_parser->error_count)
1730             break;
1731
1732         if (!ckWARN(WARN_SYNTAX)) break;
1733
1734         kid = cLISTOPo->op_first;
1735         kid = OpSIBLING(kid); /* get past pushmark */
1736         assert(OpSIBLING(kid));
1737         name = S_op_varname(aTHX_ OpSIBLING(kid));
1738         if (!name) /* XS module fiddling with the op tree */
1739             break;
1740         S_op_pretty(aTHX_ kid, &keysv, &key);
1741         assert(SvPOK(name));
1742         sv_chop(name,SvPVX(name)+1);
1743         if (key)
1744   /* diag_listed_as: %%s[%s] in scalar context better written as $%s[%s] */
1745             Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
1746                        "%%%"SVf"%c%s%c in scalar context better written "
1747                        "as $%"SVf"%c%s%c",
1748                         SVfARG(name), lbrack, key, rbrack, SVfARG(name),
1749                         lbrack, key, rbrack);
1750         else
1751   /* diag_listed_as: %%s[%s] in scalar context better written as $%s[%s] */
1752             Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
1753                        "%%%"SVf"%c%"SVf"%c in scalar context better "
1754                        "written as $%"SVf"%c%"SVf"%c",
1755                         SVfARG(name), lbrack, SVfARG(keysv), rbrack,
1756                         SVfARG(name), lbrack, SVfARG(keysv), rbrack);
1757     }
1758     }
1759     return o;
1760 }
1761
1762 OP *
1763 Perl_scalarvoid(pTHX_ OP *arg)
1764 {
1765     dVAR;
1766     OP *kid;
1767     SV* sv;
1768     U8 want;
1769     SSize_t defer_stack_alloc = 0;
1770     SSize_t defer_ix = -1;
1771     OP **defer_stack = NULL;
1772     OP *o = arg;
1773
1774     PERL_ARGS_ASSERT_SCALARVOID;
1775
1776     do {
1777         SV *useless_sv = NULL;
1778         const char* useless = NULL;
1779
1780         if (o->op_type == OP_NEXTSTATE
1781             || o->op_type == OP_DBSTATE
1782             || (o->op_type == OP_NULL && (o->op_targ == OP_NEXTSTATE
1783                                           || o->op_targ == OP_DBSTATE)))
1784             PL_curcop = (COP*)o;                /* for warning below */
1785
1786         /* assumes no premature commitment */
1787         want = o->op_flags & OPf_WANT;
1788         if ((want && want != OPf_WANT_SCALAR)
1789             || (PL_parser && PL_parser->error_count)
1790             || o->op_type == OP_RETURN || o->op_type == OP_REQUIRE || o->op_type == OP_LEAVEWHEN)
1791         {
1792             continue;
1793         }
1794
1795         if ((o->op_private & OPpTARGET_MY)
1796             && (PL_opargs[o->op_type] & OA_TARGLEX))/* OPp share the meaning */
1797         {
1798             /* newASSIGNOP has already applied scalar context, which we
1799                leave, as if this op is inside SASSIGN.  */
1800             continue;
1801         }
1802
1803         o->op_flags = (o->op_flags & ~OPf_WANT) | OPf_WANT_VOID;
1804
1805         switch (o->op_type) {
1806         default:
1807             if (!(PL_opargs[o->op_type] & OA_FOLDCONST))
1808                 break;
1809             /* FALLTHROUGH */
1810         case OP_REPEAT:
1811             if (o->op_flags & OPf_STACKED)
1812                 break;
1813             if (o->op_type == OP_REPEAT)
1814                 scalar(cBINOPo->op_first);
1815             goto func_ops;
1816         case OP_SUBSTR:
1817             if (o->op_private == 4)
1818                 break;
1819             /* FALLTHROUGH */
1820         case OP_WANTARRAY:
1821         case OP_GV:
1822         case OP_SMARTMATCH:
1823         case OP_AV2ARYLEN:
1824         case OP_REF:
1825         case OP_REFGEN:
1826         case OP_SREFGEN:
1827         case OP_DEFINED:
1828         case OP_HEX:
1829         case OP_OCT:
1830         case OP_LENGTH:
1831         case OP_VEC:
1832         case OP_INDEX:
1833         case OP_RINDEX:
1834         case OP_SPRINTF:
1835         case OP_KVASLICE:
1836         case OP_KVHSLICE:
1837         case OP_UNPACK:
1838         case OP_PACK:
1839         case OP_JOIN:
1840         case OP_LSLICE:
1841         case OP_ANONLIST:
1842         case OP_ANONHASH:
1843         case OP_SORT:
1844         case OP_REVERSE:
1845         case OP_RANGE:
1846         case OP_FLIP:
1847         case OP_FLOP:
1848         case OP_CALLER:
1849         case OP_FILENO:
1850         case OP_EOF:
1851         case OP_TELL:
1852         case OP_GETSOCKNAME:
1853         case OP_GETPEERNAME:
1854         case OP_READLINK:
1855         case OP_TELLDIR:
1856         case OP_GETPPID:
1857         case OP_GETPGRP:
1858         case OP_GETPRIORITY:
1859         case OP_TIME:
1860         case OP_TMS:
1861         case OP_LOCALTIME:
1862         case OP_GMTIME:
1863         case OP_GHBYNAME:
1864         case OP_GHBYADDR:
1865         case OP_GHOSTENT:
1866         case OP_GNBYNAME:
1867         case OP_GNBYADDR:
1868         case OP_GNETENT:
1869         case OP_GPBYNAME:
1870         case OP_GPBYNUMBER:
1871         case OP_GPROTOENT:
1872         case OP_GSBYNAME:
1873         case OP_GSBYPORT:
1874         case OP_GSERVENT:
1875         case OP_GPWNAM:
1876         case OP_GPWUID:
1877         case OP_GGRNAM:
1878         case OP_GGRGID:
1879         case OP_GETLOGIN:
1880         case OP_PROTOTYPE:
1881         case OP_RUNCV:
1882         func_ops:
1883             useless = OP_DESC(o);
1884             break;
1885
1886         case OP_GVSV:
1887         case OP_PADSV:
1888         case OP_PADAV:
1889         case OP_PADHV:
1890         case OP_PADANY:
1891         case OP_AELEM:
1892         case OP_AELEMFAST:
1893         case OP_AELEMFAST_LEX:
1894         case OP_ASLICE:
1895         case OP_HELEM:
1896         case OP_HSLICE:
1897             if (!(o->op_private & (OPpLVAL_INTRO|OPpOUR_INTRO)))
1898                 /* Otherwise it's "Useless use of grep iterator" */
1899                 useless = OP_DESC(o);
1900             break;
1901
1902         case OP_SPLIT:
1903             kid = cLISTOPo->op_first;
1904             if (kid && kid->op_type == OP_PUSHRE
1905                 && !kid->op_targ
1906                 && !(o->op_flags & OPf_STACKED)
1907 #ifdef USE_ITHREADS
1908                 && !((PMOP*)kid)->op_pmreplrootu.op_pmtargetoff
1909 #else
1910                 && !((PMOP*)kid)->op_pmreplrootu.op_pmtargetgv
1911 #endif
1912                 )
1913                 useless = OP_DESC(o);
1914             break;
1915
1916         case OP_NOT:
1917             kid = cUNOPo->op_first;
1918             if (kid->op_type != OP_MATCH && kid->op_type != OP_SUBST &&
1919                 kid->op_type != OP_TRANS && kid->op_type != OP_TRANSR) {
1920                 goto func_ops;
1921             }
1922             useless = "negative pattern binding (!~)";
1923             break;
1924
1925         case OP_SUBST:
1926             if (cPMOPo->op_pmflags & PMf_NONDESTRUCT)
1927                 useless = "non-destructive substitution (s///r)";
1928             break;
1929
1930         case OP_TRANSR:
1931             useless = "non-destructive transliteration (tr///r)";
1932             break;
1933
1934         case OP_RV2GV:
1935         case OP_RV2SV:
1936         case OP_RV2AV:
1937         case OP_RV2HV:
1938             if (!(o->op_private & (OPpLVAL_INTRO|OPpOUR_INTRO)) &&
1939                 (!OpHAS_SIBLING(o) || OpSIBLING(o)->op_type != OP_READLINE))
1940                 useless = "a variable";
1941             break;
1942
1943         case OP_CONST:
1944             sv = cSVOPo_sv;
1945             if (cSVOPo->op_private & OPpCONST_STRICT)
1946                 no_bareword_allowed(o);
1947             else {
1948                 if (ckWARN(WARN_VOID)) {
1949                     NV nv;
1950                     /* don't warn on optimised away booleans, eg
1951                      * use constant Foo, 5; Foo || print; */
1952                     if (cSVOPo->op_private & OPpCONST_SHORTCIRCUIT)
1953                         useless = NULL;
1954                     /* the constants 0 and 1 are permitted as they are
1955                        conventionally used as dummies in constructs like
1956                        1 while some_condition_with_side_effects;  */
1957                     else if (SvNIOK(sv) && ((nv = SvNV(sv)) == 0.0 || nv == 1.0))
1958                         useless = NULL;
1959                     else if (SvPOK(sv)) {
1960                         SV * const dsv = newSVpvs("");
1961                         useless_sv
1962                             = Perl_newSVpvf(aTHX_
1963                                             "a constant (%s)",
1964                                             pv_pretty(dsv, SvPVX_const(sv),
1965                                                       SvCUR(sv), 32, NULL, NULL,
1966                                                       PERL_PV_PRETTY_DUMP
1967                                                       | PERL_PV_ESCAPE_NOCLEAR
1968                                                       | PERL_PV_ESCAPE_UNI_DETECT));
1969                         SvREFCNT_dec_NN(dsv);
1970                     }
1971                     else if (SvOK(sv)) {
1972                         useless_sv = Perl_newSVpvf(aTHX_ "a constant (%"SVf")", SVfARG(sv));
1973                     }
1974                     else
1975                         useless = "a constant (undef)";
1976                 }
1977             }
1978             op_null(o);         /* don't execute or even remember it */
1979             break;
1980
1981         case OP_POSTINC:
1982             OpTYPE_set(o, OP_PREINC);  /* pre-increment is faster */
1983             break;
1984
1985         case OP_POSTDEC:
1986             OpTYPE_set(o, OP_PREDEC);  /* pre-decrement is faster */
1987             break;
1988
1989         case OP_I_POSTINC:
1990             OpTYPE_set(o, OP_I_PREINC);        /* pre-increment is faster */
1991             break;
1992
1993         case OP_I_POSTDEC:
1994             OpTYPE_set(o, OP_I_PREDEC);        /* pre-decrement is faster */
1995             break;
1996
1997         case OP_SASSIGN: {
1998             OP *rv2gv;
1999             UNOP *refgen, *rv2cv;
2000             LISTOP *exlist;
2001
2002             if ((o->op_private & ~OPpASSIGN_BACKWARDS) != 2)
2003                 break;
2004
2005             rv2gv = ((BINOP *)o)->op_last;
2006             if (!rv2gv || rv2gv->op_type != OP_RV2GV)
2007                 break;
2008
2009             refgen = (UNOP *)((BINOP *)o)->op_first;
2010
2011             if (!refgen || (refgen->op_type != OP_REFGEN
2012                             && refgen->op_type != OP_SREFGEN))
2013                 break;
2014
2015             exlist = (LISTOP *)refgen->op_first;
2016             if (!exlist || exlist->op_type != OP_NULL
2017                 || exlist->op_targ != OP_LIST)
2018                 break;
2019
2020             if (exlist->op_first->op_type != OP_PUSHMARK
2021                 && exlist->op_first != exlist->op_last)
2022                 break;
2023
2024             rv2cv = (UNOP*)exlist->op_last;
2025
2026             if (rv2cv->op_type != OP_RV2CV)
2027                 break;
2028
2029             assert ((rv2gv->op_private & OPpDONT_INIT_GV) == 0);
2030             assert ((o->op_private & OPpASSIGN_CV_TO_GV) == 0);
2031             assert ((rv2cv->op_private & OPpMAY_RETURN_CONSTANT) == 0);
2032
2033             o->op_private |= OPpASSIGN_CV_TO_GV;
2034             rv2gv->op_private |= OPpDONT_INIT_GV;
2035             rv2cv->op_private |= OPpMAY_RETURN_CONSTANT;
2036
2037             break;
2038         }
2039
2040         case OP_AASSIGN: {
2041             inplace_aassign(o);
2042             break;
2043         }
2044
2045         case OP_OR:
2046         case OP_AND:
2047             kid = cLOGOPo->op_first;
2048             if (kid->op_type == OP_NOT
2049                 && (kid->op_flags & OPf_KIDS)) {
2050                 if (o->op_type == OP_AND) {
2051                     OpTYPE_set(o, OP_OR);
2052                 } else {
2053                     OpTYPE_set(o, OP_AND);
2054                 }
2055                 op_null(kid);
2056             }
2057             /* FALLTHROUGH */
2058
2059         case OP_DOR:
2060         case OP_COND_EXPR:
2061         case OP_ENTERGIVEN:
2062         case OP_ENTERWHEN:
2063             for (kid = OpSIBLING(cUNOPo->op_first); kid; kid = OpSIBLING(kid))
2064                 if (!(kid->op_flags & OPf_KIDS))
2065                     scalarvoid(kid);
2066                 else
2067                     DEFER_OP(kid);
2068         break;
2069
2070         case OP_NULL:
2071             if (o->op_flags & OPf_STACKED)
2072                 break;
2073             /* FALLTHROUGH */
2074         case OP_NEXTSTATE:
2075         case OP_DBSTATE:
2076         case OP_ENTERTRY:
2077         case OP_ENTER:
2078             if (!(o->op_flags & OPf_KIDS))
2079                 break;
2080             /* FALLTHROUGH */
2081         case OP_SCOPE:
2082         case OP_LEAVE:
2083         case OP_LEAVETRY:
2084         case OP_LEAVELOOP:
2085         case OP_LINESEQ:
2086         case OP_LEAVEGIVEN:
2087         case OP_LEAVEWHEN:
2088         kids:
2089             for (kid = cLISTOPo->op_first; kid; kid = OpSIBLING(kid))
2090                 if (!(kid->op_flags & OPf_KIDS))
2091                     scalarvoid(kid);
2092                 else
2093                     DEFER_OP(kid);
2094             break;
2095         case OP_LIST:
2096             /* If the first kid after pushmark is something that the padrange
2097                optimisation would reject, then null the list and the pushmark.
2098             */
2099             if ((kid = cLISTOPo->op_first)->op_type == OP_PUSHMARK
2100                 && (  !(kid = OpSIBLING(kid))
2101                       || (  kid->op_type != OP_PADSV
2102                             && kid->op_type != OP_PADAV
2103                             && kid->op_type != OP_PADHV)
2104                       || kid->op_private & ~OPpLVAL_INTRO
2105                       || !(kid = OpSIBLING(kid))
2106                       || (  kid->op_type != OP_PADSV
2107                             && kid->op_type != OP_PADAV
2108                             && kid->op_type != OP_PADHV)
2109                       || kid->op_private & ~OPpLVAL_INTRO)
2110             ) {
2111                 op_null(cUNOPo->op_first); /* NULL the pushmark */
2112                 op_null(o); /* NULL the list */
2113             }
2114             goto kids;
2115         case OP_ENTEREVAL:
2116             scalarkids(o);
2117             break;
2118         case OP_SCALAR:
2119             scalar(o);
2120             break;
2121         }
2122
2123         if (useless_sv) {
2124             /* mortalise it, in case warnings are fatal.  */
2125             Perl_ck_warner(aTHX_ packWARN(WARN_VOID),
2126                            "Useless use of %"SVf" in void context",
2127                            SVfARG(sv_2mortal(useless_sv)));
2128         }
2129         else if (useless) {
2130             Perl_ck_warner(aTHX_ packWARN(WARN_VOID),
2131                            "Useless use of %s in void context",
2132                            useless);
2133         }
2134     } while ( (o = POP_DEFERRED_OP()) );
2135
2136     Safefree(defer_stack);
2137
2138     return arg;
2139 }
2140
2141 static OP *
2142 S_listkids(pTHX_ OP *o)
2143 {
2144     if (o && o->op_flags & OPf_KIDS) {
2145         OP *kid;
2146         for (kid = cLISTOPo->op_first; kid; kid = OpSIBLING(kid))
2147             list(kid);
2148     }
2149     return o;
2150 }
2151
2152 OP *
2153 Perl_list(pTHX_ OP *o)
2154 {
2155     OP *kid;
2156
2157     /* assumes no premature commitment */
2158     if (!o || (o->op_flags & OPf_WANT)
2159          || (PL_parser && PL_parser->error_count)
2160          || o->op_type == OP_RETURN)
2161     {
2162         return o;
2163     }
2164
2165     if ((o->op_private & OPpTARGET_MY)
2166         && (PL_opargs[o->op_type] & OA_TARGLEX))/* OPp share the meaning */
2167     {
2168         return o;                               /* As if inside SASSIGN */
2169     }
2170
2171     o->op_flags = (o->op_flags & ~OPf_WANT) | OPf_WANT_LIST;
2172
2173     switch (o->op_type) {
2174     case OP_FLOP:
2175         list(cBINOPo->op_first);
2176         break;
2177     case OP_REPEAT:
2178         if (o->op_private & OPpREPEAT_DOLIST
2179          && !(o->op_flags & OPf_STACKED))
2180         {
2181             list(cBINOPo->op_first);
2182             kid = cBINOPo->op_last;
2183             if (kid->op_type == OP_CONST && SvIOK(kSVOP_sv)
2184              && SvIVX(kSVOP_sv) == 1)
2185             {
2186                 op_null(o); /* repeat */
2187                 op_null(cUNOPx(cBINOPo->op_first)->op_first);/* pushmark */
2188                 /* const (rhs): */
2189                 op_free(op_sibling_splice(o, cBINOPo->op_first, 1, NULL));
2190             }
2191         }
2192         break;
2193     case OP_OR:
2194     case OP_AND:
2195     case OP_COND_EXPR:
2196         for (kid = OpSIBLING(cUNOPo->op_first); kid; kid = OpSIBLING(kid))
2197             list(kid);
2198         break;
2199     default:
2200     case OP_MATCH:
2201     case OP_QR:
2202     case OP_SUBST:
2203     case OP_NULL:
2204         if (!(o->op_flags & OPf_KIDS))
2205             break;
2206         if (!o->op_next && cUNOPo->op_first->op_type == OP_FLOP) {
2207             list(cBINOPo->op_first);
2208             return gen_constant_list(o);
2209         }
2210         listkids(o);
2211         break;
2212     case OP_LIST:
2213         listkids(o);
2214         if (cLISTOPo->op_first->op_type == OP_PUSHMARK) {
2215             op_null(cUNOPo->op_first); /* NULL the pushmark */
2216             op_null(o); /* NULL the list */
2217         }
2218         break;
2219     case OP_LEAVE:
2220     case OP_LEAVETRY:
2221         kid = cLISTOPo->op_first;
2222         list(kid);
2223         kid = OpSIBLING(kid);
2224     do_kids:
2225         while (kid) {
2226             OP *sib = OpSIBLING(kid);
2227             if (sib && kid->op_type != OP_LEAVEWHEN)
2228                 scalarvoid(kid);
2229             else
2230                 list(kid);
2231             kid = sib;
2232         }
2233         PL_curcop = &PL_compiling;
2234         break;
2235     case OP_SCOPE:
2236     case OP_LINESEQ:
2237         kid = cLISTOPo->op_first;
2238         goto do_kids;
2239     }
2240     return o;
2241 }
2242
2243 static OP *
2244 S_scalarseq(pTHX_ OP *o)
2245 {
2246     if (o) {
2247         const OPCODE type = o->op_type;
2248
2249         if (type == OP_LINESEQ || type == OP_SCOPE ||
2250             type == OP_LEAVE || type == OP_LEAVETRY)
2251         {
2252             OP *kid, *sib;
2253             for (kid = cLISTOPo->op_first; kid; kid = sib) {
2254                 if ((sib = OpSIBLING(kid))
2255                  && (  OpHAS_SIBLING(sib) || sib->op_type != OP_NULL
2256                     || (  sib->op_targ != OP_NEXTSTATE
2257                        && sib->op_targ != OP_DBSTATE  )))
2258                 {
2259                     scalarvoid(kid);
2260                 }
2261             }
2262             PL_curcop = &PL_compiling;
2263         }
2264         o->op_flags &= ~OPf_PARENS;
2265         if (PL_hints & HINT_BLOCK_SCOPE)
2266             o->op_flags |= OPf_PARENS;
2267     }
2268     else
2269         o = newOP(OP_STUB, 0);
2270     return o;
2271 }
2272
2273 STATIC OP *
2274 S_modkids(pTHX_ OP *o, I32 type)
2275 {
2276     if (o && o->op_flags & OPf_KIDS) {
2277         OP *kid;
2278         for (kid = cLISTOPo->op_first; kid; kid = OpSIBLING(kid))
2279             op_lvalue(kid, type);
2280     }
2281     return o;
2282 }
2283
2284
2285 /* for a helem/hslice/kvslice, if its a fixed hash, croak on invalid
2286  * const fields. Also, convert CONST keys to HEK-in-SVs.
2287  * rop is the op that retrieves the hash;
2288  * key_op is the first key
2289  */
2290
2291 void
2292 S_check_hash_fields_and_hekify(pTHX_ UNOP *rop, SVOP *key_op)
2293 {
2294     PADNAME *lexname;
2295     GV **fields;
2296     bool check_fields;
2297
2298     /* find the padsv corresponding to $lex->{} or @{$lex}{} */
2299     if (rop) {
2300         if (rop->op_first->op_type == OP_PADSV)
2301             /* @$hash{qw(keys here)} */
2302             rop = (UNOP*)rop->op_first;
2303         else {
2304             /* @{$hash}{qw(keys here)} */
2305             if (rop->op_first->op_type == OP_SCOPE
2306                 && cLISTOPx(rop->op_first)->op_last->op_type == OP_PADSV)
2307                 {
2308                     rop = (UNOP*)cLISTOPx(rop->op_first)->op_last;
2309                 }
2310             else
2311                 rop = NULL;
2312         }
2313     }
2314
2315     lexname = NULL; /* just to silence compiler warnings */
2316     fields  = NULL; /* just to silence compiler warnings */
2317
2318     check_fields =
2319             rop
2320          && (lexname = padnamelist_fetch(PL_comppad_name, rop->op_targ),
2321              SvPAD_TYPED(lexname))
2322          && (fields = (GV**)hv_fetchs(PadnameTYPE(lexname), "FIELDS", FALSE))
2323          && isGV(*fields) && GvHV(*fields);
2324
2325     for (; key_op; key_op = (SVOP*)OpSIBLING(key_op)) {
2326         SV **svp, *sv;
2327         if (key_op->op_type != OP_CONST)
2328             continue;
2329         svp = cSVOPx_svp(key_op);
2330
2331         /* Make the CONST have a shared SV */
2332         if (   !SvIsCOW_shared_hash(sv = *svp)
2333             && SvTYPE(sv) < SVt_PVMG
2334             && SvOK(sv)
2335             && !SvROK(sv))
2336         {
2337             SSize_t keylen;
2338             const char * const key = SvPV_const(sv, *(STRLEN*)&keylen);
2339             SV *nsv = newSVpvn_share(key, SvUTF8(sv) ? -keylen : keylen, 0);
2340             SvREFCNT_dec_NN(sv);
2341             *svp = nsv;
2342         }
2343
2344         if (   check_fields
2345             && !hv_fetch_ent(GvHV(*fields), *svp, FALSE, 0))
2346         {
2347             Perl_croak(aTHX_ "No such class field \"%"SVf"\" "
2348                         "in variable %"PNf" of type %"HEKf,
2349                         SVfARG(*svp), PNfARG(lexname),
2350                         HEKfARG(HvNAME_HEK(PadnameTYPE(lexname))));
2351         }
2352     }
2353 }
2354
2355
2356 /*
2357 =for apidoc finalize_optree
2358
2359 This function finalizes the optree.  Should be called directly after
2360 the complete optree is built.  It does some additional
2361 checking which can't be done in the normal C<ck_>xxx functions and makes
2362 the tree thread-safe.
2363
2364 =cut
2365 */
2366 void
2367 Perl_finalize_optree(pTHX_ OP* o)
2368 {
2369     PERL_ARGS_ASSERT_FINALIZE_OPTREE;
2370
2371     ENTER;
2372     SAVEVPTR(PL_curcop);
2373
2374     finalize_op(o);
2375
2376     LEAVE;
2377 }
2378
2379 #ifdef USE_ITHREADS
2380 /* Relocate sv to the pad for thread safety.
2381  * Despite being a "constant", the SV is written to,
2382  * for reference counts, sv_upgrade() etc. */
2383 PERL_STATIC_INLINE void
2384 S_op_relocate_sv(pTHX_ SV** svp, PADOFFSET* targp)
2385 {
2386     PADOFFSET ix;
2387     PERL_ARGS_ASSERT_OP_RELOCATE_SV;
2388     if (!*svp) return;
2389     ix = pad_alloc(OP_CONST, SVf_READONLY);
2390     SvREFCNT_dec(PAD_SVl(ix));
2391     PAD_SETSV(ix, *svp);
2392     /* XXX I don't know how this isn't readonly already. */
2393     if (!SvIsCOW(PAD_SVl(ix))) SvREADONLY_on(PAD_SVl(ix));
2394     *svp = NULL;
2395     *targp = ix;
2396 }
2397 #endif
2398
2399
2400 STATIC void
2401 S_finalize_op(pTHX_ OP* o)
2402 {
2403     PERL_ARGS_ASSERT_FINALIZE_OP;
2404
2405
2406     switch (o->op_type) {
2407     case OP_NEXTSTATE:
2408     case OP_DBSTATE:
2409         PL_curcop = ((COP*)o);          /* for warnings */
2410         break;
2411     case OP_EXEC:
2412         if (OpHAS_SIBLING(o)) {
2413             OP *sib = OpSIBLING(o);
2414             if ((  sib->op_type == OP_NEXTSTATE || sib->op_type == OP_DBSTATE)
2415                 && ckWARN(WARN_EXEC)
2416                 && OpHAS_SIBLING(sib))
2417             {
2418                     const OPCODE type = OpSIBLING(sib)->op_type;
2419                     if (type != OP_EXIT && type != OP_WARN && type != OP_DIE) {
2420                         const line_t oldline = CopLINE(PL_curcop);
2421                         CopLINE_set(PL_curcop, CopLINE((COP*)sib));
2422                         Perl_warner(aTHX_ packWARN(WARN_EXEC),
2423                             "Statement unlikely to be reached");
2424                         Perl_warner(aTHX_ packWARN(WARN_EXEC),
2425                             "\t(Maybe you meant system() when you said exec()?)\n");
2426                         CopLINE_set(PL_curcop, oldline);
2427                     }
2428             }
2429         }
2430         break;
2431
2432     case OP_GV:
2433         if ((o->op_private & OPpEARLY_CV) && ckWARN(WARN_PROTOTYPE)) {
2434             GV * const gv = cGVOPo_gv;
2435             if (SvTYPE(gv) == SVt_PVGV && GvCV(gv) && SvPVX_const(GvCV(gv))) {
2436                 /* XXX could check prototype here instead of just carping */
2437                 SV * const sv = sv_newmortal();
2438                 gv_efullname3(sv, gv, NULL);
2439                 Perl_warner(aTHX_ packWARN(WARN_PROTOTYPE),
2440                     "%"SVf"() called too early to check prototype",
2441                     SVfARG(sv));
2442             }
2443         }
2444         break;
2445
2446     case OP_CONST:
2447         if (cSVOPo->op_private & OPpCONST_STRICT)
2448             no_bareword_allowed(o);
2449         /* FALLTHROUGH */
2450 #ifdef USE_ITHREADS
2451     case OP_HINTSEVAL:
2452         op_relocate_sv(&cSVOPo->op_sv, &o->op_targ);
2453 #endif
2454         break;
2455
2456 #ifdef USE_ITHREADS
2457     /* Relocate all the METHOP's SVs to the pad for thread safety. */
2458     case OP_METHOD_NAMED:
2459     case OP_METHOD_SUPER:
2460     case OP_METHOD_REDIR:
2461     case OP_METHOD_REDIR_SUPER:
2462         op_relocate_sv(&cMETHOPx(o)->op_u.op_meth_sv, &o->op_targ);
2463         break;
2464 #endif
2465
2466     case OP_HELEM: {
2467         UNOP *rop;
2468         SVOP *key_op;
2469         OP *kid;
2470
2471         if ((key_op = cSVOPx(((BINOP*)o)->op_last))->op_type != OP_CONST)
2472             break;
2473
2474         rop = (UNOP*)((BINOP*)o)->op_first;
2475
2476         goto check_keys;
2477
2478     case OP_HSLICE:
2479         S_scalar_slice_warning(aTHX_ o);
2480         /* FALLTHROUGH */
2481
2482     case OP_KVHSLICE:
2483         kid = OpSIBLING(cLISTOPo->op_first);
2484         if (/* I bet there's always a pushmark... */
2485             OP_TYPE_ISNT_AND_WASNT_NN(kid, OP_LIST)
2486             && OP_TYPE_ISNT_NN(kid, OP_CONST))
2487         {
2488             break;
2489         }
2490
2491         key_op = (SVOP*)(kid->op_type == OP_CONST
2492                                 ? kid
2493                                 : OpSIBLING(kLISTOP->op_first));
2494
2495         rop = (UNOP*)((LISTOP*)o)->op_last;
2496
2497       check_keys:       
2498         if (o->op_private & OPpLVAL_INTRO || rop->op_type != OP_RV2HV)
2499             rop = NULL;
2500         S_check_hash_fields_and_hekify(aTHX_ rop, key_op);
2501         break;
2502     }
2503     case OP_ASLICE:
2504         S_scalar_slice_warning(aTHX_ o);
2505         break;
2506
2507     case OP_SUBST: {
2508         if (cPMOPo->op_pmreplrootu.op_pmreplroot)
2509             finalize_op(cPMOPo->op_pmreplrootu.op_pmreplroot);
2510         break;
2511     }
2512     default:
2513         break;
2514     }
2515
2516     if (o->op_flags & OPf_KIDS) {
2517         OP *kid;
2518
2519 #ifdef DEBUGGING
2520         /* check that op_last points to the last sibling, and that
2521          * the last op_sibling/op_sibparent field points back to the
2522          * parent, and that the only ops with KIDS are those which are
2523          * entitled to them */
2524         U32 type = o->op_type;
2525         U32 family;
2526         bool has_last;
2527
2528         if (type == OP_NULL) {
2529             type = o->op_targ;
2530             /* ck_glob creates a null UNOP with ex-type GLOB
2531              * (which is a list op. So pretend it wasn't a listop */
2532             if (type == OP_GLOB)
2533                 type = OP_NULL;
2534         }
2535         family = PL_opargs[type] & OA_CLASS_MASK;
2536
2537         has_last = (   family == OA_BINOP
2538                     || family == OA_LISTOP
2539                     || family == OA_PMOP
2540                     || family == OA_LOOP
2541                    );
2542         assert(  has_last /* has op_first and op_last, or ...
2543               ... has (or may have) op_first: */
2544               || family == OA_UNOP
2545               || family == OA_UNOP_AUX
2546               || family == OA_LOGOP
2547               || family == OA_BASEOP_OR_UNOP
2548               || family == OA_FILESTATOP
2549               || family == OA_LOOPEXOP
2550               || family == OA_METHOP
2551               /* I don't know why SASSIGN is tagged as OA_BASEOP - DAPM */
2552               || type == OP_SASSIGN
2553               || type == OP_CUSTOM
2554               || type == OP_NULL /* new_logop does this */
2555               );
2556
2557         for (kid = cUNOPo->op_first; kid; kid = OpSIBLING(kid)) {
2558 #  ifdef PERL_OP_PARENT
2559             if (!OpHAS_SIBLING(kid)) {
2560                 if (has_last)
2561                     assert(kid == cLISTOPo->op_last);
2562                 assert(kid->op_sibparent == o);
2563             }
2564 #  else
2565             if (has_last && !OpHAS_SIBLING(kid))
2566                 assert(kid == cLISTOPo->op_last);
2567 #  endif
2568         }
2569 #endif
2570
2571         for (kid = cUNOPo->op_first; kid; kid = OpSIBLING(kid))
2572             finalize_op(kid);
2573     }
2574 }
2575
2576 /*
2577 =for apidoc Amx|OP *|op_lvalue|OP *o|I32 type
2578
2579 Propagate lvalue ("modifiable") context to an op and its children.
2580 C<type> represents the context type, roughly based on the type of op that
2581 would do the modifying, although C<local()> is represented by C<OP_NULL>,
2582 because it has no op type of its own (it is signalled by a flag on
2583 the lvalue op).
2584
2585 This function detects things that can't be modified, such as C<$x+1>, and
2586 generates errors for them.  For example, C<$x+1 = 2> would cause it to be
2587 called with an op of type C<OP_ADD> and a C<type> argument of C<OP_SASSIGN>.
2588
2589 It also flags things that need to behave specially in an lvalue context,
2590 such as C<$$x = 5> which might have to vivify a reference in C<$x>.
2591
2592 =cut
2593 */
2594
2595 static void
2596 S_mark_padname_lvalue(pTHX_ PADNAME *pn)
2597 {
2598     CV *cv = PL_compcv;
2599     PadnameLVALUE_on(pn);
2600     while (PadnameOUTER(pn) && PARENT_PAD_INDEX(pn)) {
2601         cv = CvOUTSIDE(cv);
2602         assert(cv);
2603         assert(CvPADLIST(cv));
2604         pn =
2605            PadlistNAMESARRAY(CvPADLIST(cv))[PARENT_PAD_INDEX(pn)];
2606         assert(PadnameLEN(pn));
2607         PadnameLVALUE_on(pn);
2608     }
2609 }
2610
2611 static bool
2612 S_vivifies(const OPCODE type)
2613 {
2614     switch(type) {
2615     case OP_RV2AV:     case   OP_ASLICE:
2616     case OP_RV2HV:     case OP_KVASLICE:
2617     case OP_RV2SV:     case   OP_HSLICE:
2618     case OP_AELEMFAST: case OP_KVHSLICE:
2619     case OP_HELEM:
2620     case OP_AELEM:
2621         return 1;
2622     }
2623     return 0;
2624 }
2625
2626 static void
2627 S_lvref(pTHX_ OP *o, I32 type)
2628 {
2629     dVAR;
2630     OP *kid;
2631     switch (o->op_type) {
2632     case OP_COND_EXPR:
2633         for (kid = OpSIBLING(cUNOPo->op_first); kid;
2634              kid = OpSIBLING(kid))
2635             S_lvref(aTHX_ kid, type);
2636         /* FALLTHROUGH */
2637     case OP_PUSHMARK:
2638         return;
2639     case OP_RV2AV:
2640         if (cUNOPo->op_first->op_type != OP_GV) goto badref;
2641         o->op_flags |= OPf_STACKED;
2642         if (o->op_flags & OPf_PARENS) {
2643             if (o->op_private & OPpLVAL_INTRO) {
2644                  yyerror(Perl_form(aTHX_ "Can't modify reference to "
2645                       "localized parenthesized array in list assignment"));
2646                 return;
2647             }
2648           slurpy:
2649             OpTYPE_set(o, OP_LVAVREF);
2650             o->op_private &= OPpLVAL_INTRO|OPpPAD_STATE;
2651             o->op_flags |= OPf_MOD|OPf_REF;
2652             return;
2653         }
2654         o->op_private |= OPpLVREF_AV;
2655         goto checkgv;
2656     case OP_RV2CV:
2657         kid = cUNOPo->op_first;
2658         if (kid->op_type == OP_NULL)
2659             kid = cUNOPx(OpSIBLING(kUNOP->op_first))
2660                 ->op_first;
2661         o->op_private = OPpLVREF_CV;
2662         if (kid->op_type == OP_GV)
2663             o->op_flags |= OPf_STACKED;
2664         else if (kid->op_type == OP_PADCV) {
2665             o->op_targ = kid->op_targ;
2666             kid->op_targ = 0;
2667             op_free(cUNOPo->op_first);
2668             cUNOPo->op_first = NULL;
2669             o->op_flags &=~ OPf_KIDS;
2670         }
2671         else goto badref;
2672         break;
2673     case OP_RV2HV:
2674         if (o->op_flags & OPf_PARENS) {
2675           parenhash:
2676             yyerror(Perl_form(aTHX_ "Can't modify reference to "
2677                                  "parenthesized hash in list assignment"));
2678                 return;
2679         }
2680         o->op_private |= OPpLVREF_HV;
2681         /* FALLTHROUGH */
2682     case OP_RV2SV:
2683       checkgv:
2684         if (cUNOPo->op_first->op_type != OP_GV) goto badref;
2685         o->op_flags |= OPf_STACKED;
2686         break;
2687     case OP_PADHV:
2688         if (o->op_flags & OPf_PARENS) goto parenhash;
2689         o->op_private |= OPpLVREF_HV;
2690         /* FALLTHROUGH */
2691     case OP_PADSV:
2692         PAD_COMPNAME_GEN_set(o->op_targ, PERL_INT_MAX);
2693         break;
2694     case OP_PADAV:
2695         PAD_COMPNAME_GEN_set(o->op_targ, PERL_INT_MAX);
2696         if (o->op_flags & OPf_PARENS) goto slurpy;
2697         o->op_private |= OPpLVREF_AV;
2698         break;
2699     case OP_AELEM:
2700     case OP_HELEM:
2701         o->op_private |= OPpLVREF_ELEM;
2702         o->op_flags   |= OPf_STACKED;
2703         break;
2704     case OP_ASLICE:
2705     case OP_HSLICE:
2706         OpTYPE_set(o, OP_LVREFSLICE);
2707         o->op_private &= OPpLVAL_INTRO|OPpLVREF_ELEM;
2708         return;
2709     case OP_NULL:
2710         if (o->op_flags & OPf_SPECIAL)          /* do BLOCK */
2711             goto badref;
2712         else if (!(o->op_flags & OPf_KIDS))
2713             return;
2714         if (o->op_targ != OP_LIST) {
2715             S_lvref(aTHX_ cBINOPo->op_first, type);
2716             return;
2717         }
2718         /* FALLTHROUGH */
2719     case OP_LIST:
2720         for (kid = cLISTOPo->op_first; kid; kid = OpSIBLING(kid)) {
2721             assert((kid->op_flags & OPf_WANT) != OPf_WANT_VOID);
2722             S_lvref(aTHX_ kid, type);
2723         }
2724         return;
2725     case OP_STUB:
2726         if (o->op_flags & OPf_PARENS)
2727             return;
2728         /* FALLTHROUGH */
2729     default:
2730       badref:
2731         /* diag_listed_as: Can't modify reference to %s in %s assignment */
2732         yyerror(Perl_form(aTHX_ "Can't modify reference to %s in %s",
2733                      o->op_type == OP_NULL && o->op_flags & OPf_SPECIAL
2734                       ? "do block"
2735                       : OP_DESC(o),
2736                      PL_op_desc[type]));
2737     }
2738     OpTYPE_set(o, OP_LVREF);
2739     o->op_private &=
2740         OPpLVAL_INTRO|OPpLVREF_ELEM|OPpLVREF_TYPE|OPpPAD_STATE;
2741     if (type == OP_ENTERLOOP)
2742         o->op_private |= OPpLVREF_ITER;
2743 }
2744
2745 OP *
2746 Perl_op_lvalue_flags(pTHX_ OP *o, I32 type, U32 flags)
2747 {
2748     dVAR;
2749     OP *kid;
2750     /* -1 = error on localize, 0 = ignore localize, 1 = ok to localize */
2751     int localize = -1;
2752
2753     if (!o || (PL_parser && PL_parser->error_count))
2754         return o;
2755
2756     if ((o->op_private & OPpTARGET_MY)
2757         && (PL_opargs[o->op_type] & OA_TARGLEX))/* OPp share the meaning */
2758     {
2759         return o;
2760     }
2761
2762     assert( (o->op_flags & OPf_WANT) != OPf_WANT_VOID );
2763
2764     if (type == OP_PRTF || type == OP_SPRINTF) type = OP_ENTERSUB;
2765
2766     switch (o->op_type) {
2767     case OP_UNDEF:
2768         PL_modcount++;
2769         return o;
2770     case OP_STUB:
2771         if ((o->op_flags & OPf_PARENS))
2772             break;
2773         goto nomod;
2774     case OP_ENTERSUB:
2775         if ((type == OP_UNDEF || type == OP_REFGEN || type == OP_LOCK) &&
2776             !(o->op_flags & OPf_STACKED)) {
2777             OpTYPE_set(o, OP_RV2CV);            /* entersub => rv2cv */
2778             assert(cUNOPo->op_first->op_type == OP_NULL);
2779             op_null(((LISTOP*)cUNOPo->op_first)->op_first);/* disable pushmark */
2780             break;
2781         }
2782         else {                          /* lvalue subroutine call */
2783             o->op_private |= OPpLVAL_INTRO;
2784             PL_modcount = RETURN_UNLIMITED_NUMBER;
2785             if (type == OP_GREPSTART || type == OP_ENTERSUB
2786              || type == OP_REFGEN    || type == OP_LEAVESUBLV) {
2787                 /* Potential lvalue context: */
2788                 o->op_private |= OPpENTERSUB_INARGS;
2789                 break;
2790             }
2791             else {                      /* Compile-time error message: */
2792                 OP *kid = cUNOPo->op_first;
2793                 CV *cv;
2794                 GV *gv;
2795
2796                 if (kid->op_type != OP_PUSHMARK) {
2797                     if (kid->op_type != OP_NULL || kid->op_targ != OP_LIST)
2798                         Perl_croak(aTHX_
2799                                 "panic: unexpected lvalue entersub "
2800                                 "args: type/targ %ld:%"UVuf,
2801                                 (long)kid->op_type, (UV)kid->op_targ);
2802                     kid = kLISTOP->op_first;
2803                 }
2804                 while (OpHAS_SIBLING(kid))
2805                     kid = OpSIBLING(kid);
2806                 if (!(kid->op_type == OP_NULL && kid->op_targ == OP_RV2CV)) {
2807                     break;      /* Postpone until runtime */
2808                 }
2809
2810                 kid = kUNOP->op_first;
2811                 if (kid->op_type == OP_NULL && kid->op_targ == OP_RV2SV)
2812                     kid = kUNOP->op_first;
2813                 if (kid->op_type == OP_NULL)
2814                     Perl_croak(aTHX_
2815                                "Unexpected constant lvalue entersub "
2816                                "entry via type/targ %ld:%"UVuf,
2817                                (long)kid->op_type, (UV)kid->op_targ);
2818                 if (kid->op_type != OP_GV) {
2819                     break;
2820                 }
2821
2822                 gv = kGVOP_gv;
2823                 cv = isGV(gv)
2824                     ? GvCV(gv)
2825                     : SvROK(gv) && SvTYPE(SvRV(gv)) == SVt_PVCV
2826                         ? MUTABLE_CV(SvRV(gv))
2827                         : NULL;
2828                 if (!cv)
2829                     break;
2830                 if (CvLVALUE(cv))
2831                     break;
2832             }
2833         }
2834         /* FALLTHROUGH */
2835     default:
2836       nomod:
2837         if (flags & OP_LVALUE_NO_CROAK) return NULL;
2838         /* grep, foreach, subcalls, refgen */
2839         if (type == OP_GREPSTART || type == OP_ENTERSUB
2840          || type == OP_REFGEN    || type == OP_LEAVESUBLV)
2841             break;
2842         yyerror(Perl_form(aTHX_ "Can't modify %s in %s",
2843                      (o->op_type == OP_NULL && (o->op_flags & OPf_SPECIAL)
2844                       ? "do block"
2845                       : (o->op_type == OP_ENTERSUB
2846                         ? "non-lvalue subroutine call"
2847                         : OP_DESC(o))),
2848                      type ? PL_op_desc[type] : "local"));
2849         return o;
2850
2851     case OP_PREINC:
2852     case OP_PREDEC:
2853     case OP_POW:
2854     case OP_MULTIPLY:
2855     case OP_DIVIDE:
2856     case OP_MODULO:
2857     case OP_ADD:
2858     case OP_SUBTRACT:
2859     case OP_CONCAT:
2860     case OP_LEFT_SHIFT:
2861     case OP_RIGHT_SHIFT:
2862     case OP_BIT_AND:
2863     case OP_BIT_XOR:
2864     case OP_BIT_OR:
2865     case OP_I_MULTIPLY:
2866     case OP_I_DIVIDE:
2867     case OP_I_MODULO:
2868     case OP_I_ADD:
2869     case OP_I_SUBTRACT:
2870         if (!(o->op_flags & OPf_STACKED))
2871             goto nomod;
2872         PL_modcount++;
2873         break;
2874
2875     case OP_REPEAT:
2876         if (o->op_flags & OPf_STACKED) {
2877             PL_modcount++;
2878             break;
2879         }
2880         if (!(o->op_private & OPpREPEAT_DOLIST))
2881             goto nomod;
2882         else {
2883             const I32 mods = PL_modcount;
2884             modkids(cBINOPo->op_first, type);
2885             if (type != OP_AASSIGN)
2886                 goto nomod;
2887             kid = cBINOPo->op_last;
2888             if (kid->op_type == OP_CONST && SvIOK(kSVOP_sv)) {
2889                 const IV iv = SvIV(kSVOP_sv);
2890                 if (PL_modcount != RETURN_UNLIMITED_NUMBER)
2891                     PL_modcount =
2892                         mods + (PL_modcount - mods) * (iv < 0 ? 0 : iv);
2893             }
2894             else
2895                 PL_modcount = RETURN_UNLIMITED_NUMBER;
2896         }
2897         break;
2898
2899     case OP_COND_EXPR:
2900         localize = 1;
2901         for (kid = OpSIBLING(cUNOPo->op_first); kid; kid = OpSIBLING(kid))
2902             op_lvalue(kid, type);
2903         break;
2904
2905     case OP_RV2AV:
2906     case OP_RV2HV:
2907         if (type == OP_REFGEN && o->op_flags & OPf_PARENS) {
2908            PL_modcount = RETURN_UNLIMITED_NUMBER;
2909             return o;           /* Treat \(@foo) like ordinary list. */
2910         }
2911         /* FALLTHROUGH */
2912     case OP_RV2GV:
2913         if (scalar_mod_type(o, type))
2914             goto nomod;
2915         ref(cUNOPo->op_first, o->op_type);
2916         /* FALLTHROUGH */
2917     case OP_ASLICE:
2918     case OP_HSLICE:
2919         localize = 1;
2920         /* FALLTHROUGH */
2921     case OP_AASSIGN:
2922         /* Do not apply the lvsub flag for rv2[ah]v in scalar context.  */
2923         if (type == OP_LEAVESUBLV && (
2924                 (o->op_type != OP_RV2AV && o->op_type != OP_RV2HV)
2925              || (o->op_flags & OPf_WANT) != OPf_WANT_SCALAR
2926            ))
2927             o->op_private |= OPpMAYBE_LVSUB;
2928         /* FALLTHROUGH */
2929     case OP_NEXTSTATE:
2930     case OP_DBSTATE:
2931        PL_modcount = RETURN_UNLIMITED_NUMBER;
2932         break;
2933     case OP_KVHSLICE:
2934     case OP_KVASLICE:
2935         if (type == OP_LEAVESUBLV)
2936             o->op_private |= OPpMAYBE_LVSUB;
2937         goto nomod;
2938     case OP_AV2ARYLEN:
2939         PL_hints |= HINT_BLOCK_SCOPE;
2940         if (type == OP_LEAVESUBLV)
2941             o->op_private |= OPpMAYBE_LVSUB;
2942         PL_modcount++;
2943         break;
2944     case OP_RV2SV:
2945         ref(cUNOPo->op_first, o->op_type);
2946         localize = 1;
2947         /* FALLTHROUGH */
2948     case OP_GV:
2949         PL_hints |= HINT_BLOCK_SCOPE;
2950         /* FALLTHROUGH */
2951     case OP_SASSIGN:
2952     case OP_ANDASSIGN:
2953     case OP_ORASSIGN:
2954     case OP_DORASSIGN:
2955         PL_modcount++;
2956         break;
2957
2958     case OP_AELEMFAST:
2959     case OP_AELEMFAST_LEX:
2960         localize = -1;
2961         PL_modcount++;
2962         break;
2963
2964     case OP_PADAV:
2965     case OP_PADHV:
2966        PL_modcount = RETURN_UNLIMITED_NUMBER;
2967         if (type == OP_REFGEN && o->op_flags & OPf_PARENS)
2968             return o;           /* Treat \(@foo) like ordinary list. */
2969         if (scalar_mod_type(o, type))
2970             goto nomod;
2971         if ((o->op_flags & OPf_WANT) != OPf_WANT_SCALAR
2972           && type == OP_LEAVESUBLV)
2973             o->op_private |= OPpMAYBE_LVSUB;
2974         /* FALLTHROUGH */
2975     case OP_PADSV:
2976         PL_modcount++;
2977         if (!type) /* local() */
2978             Perl_croak(aTHX_ "Can't localize lexical variable %"PNf,
2979                               PNfARG(PAD_COMPNAME(o->op_targ)));
2980         if (!(o->op_private & OPpLVAL_INTRO)
2981          || (  type != OP_SASSIGN && type != OP_AASSIGN
2982             && PadnameIsSTATE(PAD_COMPNAME_SV(o->op_targ))  ))
2983             S_mark_padname_lvalue(aTHX_ PAD_COMPNAME_SV(o->op_targ));
2984         break;
2985
2986     case OP_PUSHMARK:
2987         localize = 0;
2988         break;
2989
2990     case OP_KEYS:
2991         if (type != OP_SASSIGN && type != OP_LEAVESUBLV)
2992             goto nomod;
2993         goto lvalue_func;
2994     case OP_SUBSTR:
2995         if (o->op_private == 4) /* don't allow 4 arg substr as lvalue */
2996             goto nomod;
2997         /* FALLTHROUGH */
2998     case OP_POS:
2999     case OP_VEC:
3000       lvalue_func:
3001         if (type == OP_LEAVESUBLV)
3002             o->op_private |= OPpMAYBE_LVSUB;
3003         if (o->op_flags & OPf_KIDS)
3004             op_lvalue(OpSIBLING(cBINOPo->op_first), type);
3005         break;
3006
3007     case OP_AELEM:
3008     case OP_HELEM:
3009         ref(cBINOPo->op_first, o->op_type);
3010         if (type == OP_ENTERSUB &&
3011              !(o->op_private & (OPpLVAL_INTRO | OPpDEREF)))
3012             o->op_private |= OPpLVAL_DEFER;
3013         if (type == OP_LEAVESUBLV)
3014             o->op_private |= OPpMAYBE_LVSUB;
3015         localize = 1;
3016         PL_modcount++;
3017         break;
3018
3019     case OP_LEAVE:
3020     case OP_LEAVELOOP:
3021         o->op_private |= OPpLVALUE;
3022         /* FALLTHROUGH */
3023     case OP_SCOPE:
3024     case OP_ENTER:
3025     case OP_LINESEQ:
3026         localize = 0;
3027         if (o->op_flags & OPf_KIDS)
3028             op_lvalue(cLISTOPo->op_last, type);
3029         break;
3030
3031     case OP_NULL:
3032         localize = 0;
3033         if (o->op_flags & OPf_SPECIAL)          /* do BLOCK */
3034             goto nomod;
3035         else if (!(o->op_flags & OPf_KIDS))
3036             break;
3037         if (o->op_targ != OP_LIST) {
3038             op_lvalue(cBINOPo->op_first, type);
3039             break;
3040         }
3041         /* FALLTHROUGH */
3042     case OP_LIST:
3043         localize = 0;
3044         for (kid = cLISTOPo->op_first; kid; kid = OpSIBLING(kid))
3045             /* elements might be in void context because the list is
3046                in scalar context or because they are attribute sub calls */
3047             if ( (kid->op_flags & OPf_WANT) != OPf_WANT_VOID )
3048                 op_lvalue(kid, type);
3049         break;
3050
3051     case OP_COREARGS:
3052         return o;
3053
3054     case OP_AND:
3055     case OP_OR:
3056         if (type == OP_LEAVESUBLV
3057          || !S_vivifies(cLOGOPo->op_first->op_type))
3058             op_lvalue(cLOGOPo->op_first, type);
3059         if (type == OP_LEAVESUBLV
3060          || !S_vivifies(OpSIBLING(cLOGOPo->op_first)->op_type))
3061             op_lvalue(OpSIBLING(cLOGOPo->op_first), type);
3062         goto nomod;
3063
3064     case OP_SREFGEN:
3065         if (type != OP_AASSIGN && type != OP_SASSIGN
3066          && type != OP_ENTERLOOP)
3067             goto nomod;
3068         /* Don’t bother applying lvalue context to the ex-list.  */
3069         kid = cUNOPx(cUNOPo->op_first)->op_first;
3070         assert (!OpHAS_SIBLING(kid));
3071         goto kid_2lvref;
3072     case OP_REFGEN:
3073         if (type != OP_AASSIGN) goto nomod;
3074         kid = cUNOPo->op_first;
3075       kid_2lvref:
3076         {
3077             const U8 ec = PL_parser ? PL_parser->error_count : 0;
3078             S_lvref(aTHX_ kid, type);
3079             if (!PL_parser || PL_parser->error_count == ec) {
3080                 if (!FEATURE_REFALIASING_IS_ENABLED)
3081                     Perl_croak(aTHX_
3082                        "Experimental aliasing via reference not enabled");
3083                 Perl_ck_warner_d(aTHX_
3084                                  packWARN(WARN_EXPERIMENTAL__REFALIASING),
3085                                 "Aliasing via reference is experimental");
3086             }
3087         }
3088         if (o->op_type == OP_REFGEN)
3089             op_null(cUNOPx(cUNOPo->op_first)->op_first); /* pushmark */
3090         op_null(o);
3091         return o;
3092
3093     case OP_SPLIT:
3094         kid = cLISTOPo->op_first;
3095         if (kid && kid->op_type == OP_PUSHRE &&
3096                 (  kid->op_targ
3097                 || o->op_flags & OPf_STACKED
3098 #ifdef USE_ITHREADS
3099                 || ((PMOP*)kid)->op_pmreplrootu.op_pmtargetoff
3100 #else
3101                 || ((PMOP*)kid)->op_pmreplrootu.op_pmtargetgv
3102 #endif
3103         )) {
3104             /* This is actually @array = split.  */
3105             PL_modcount = RETURN_UNLIMITED_NUMBER;
3106             break;
3107         }
3108         goto nomod;
3109
3110     case OP_SCALAR:
3111         op_lvalue(cUNOPo->op_first, OP_ENTERSUB);
3112         goto nomod;
3113     }
3114
3115     /* [20011101.069] File test operators interpret OPf_REF to mean that
3116        their argument is a filehandle; thus \stat(".") should not set
3117        it. AMS 20011102 */
3118     if (type == OP_REFGEN &&
3119         PL_check[o->op_type] == Perl_ck_ftst)
3120         return o;
3121
3122     if (type != OP_LEAVESUBLV)
3123         o->op_flags |= OPf_MOD;
3124
3125     if (type == OP_AASSIGN || type == OP_SASSIGN)
3126         o->op_flags |= OPf_SPECIAL|OPf_REF;
3127     else if (!type) { /* local() */
3128         switch (localize) {
3129         case 1:
3130             o->op_private |= OPpLVAL_INTRO;
3131             o->op_flags &= ~OPf_SPECIAL;
3132             PL_hints |= HINT_BLOCK_SCOPE;
3133             break;
3134         case 0:
3135             break;
3136         case -1:
3137             Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX),
3138                            "Useless localization of %s", OP_DESC(o));
3139         }
3140     }
3141     else if (type != OP_GREPSTART && type != OP_ENTERSUB
3142              && type != OP_LEAVESUBLV)
3143         o->op_flags |= OPf_REF;
3144     return o;
3145 }
3146
3147 STATIC bool
3148 S_scalar_mod_type(const OP *o, I32 type)
3149 {
3150     switch (type) {
3151     case OP_POS:
3152     case OP_SASSIGN:
3153         if (o && o->op_type == OP_RV2GV)
3154             return FALSE;
3155         /* FALLTHROUGH */
3156     case OP_PREINC:
3157     case OP_PREDEC:
3158     case OP_POSTINC:
3159     case OP_POSTDEC:
3160     case OP_I_PREINC:
3161     case OP_I_PREDEC:
3162     case OP_I_POSTINC:
3163     case OP_I_POSTDEC:
3164     case OP_POW:
3165     case OP_MULTIPLY:
3166     case OP_DIVIDE:
3167     case OP_MODULO:
3168     case OP_REPEAT:
3169     case OP_ADD:
3170     case OP_SUBTRACT:
3171     case OP_I_MULTIPLY:
3172     case OP_I_DIVIDE:
3173     case OP_I_MODULO:
3174     case OP_I_ADD:
3175     case OP_I_SUBTRACT:
3176     case OP_LEFT_SHIFT:
3177     case OP_RIGHT_SHIFT:
3178     case OP_BIT_AND:
3179     case OP_BIT_XOR:
3180     case OP_BIT_OR:
3181     case OP_CONCAT:
3182     case OP_SUBST:
3183     case OP_TRANS:
3184     case OP_TRANSR:
3185     case OP_READ:
3186     case OP_SYSREAD:
3187     case OP_RECV:
3188     case OP_ANDASSIGN:
3189     case OP_ORASSIGN:
3190     case OP_DORASSIGN:
3191         return TRUE;
3192     default:
3193         return FALSE;
3194     }
3195 }
3196
3197 STATIC bool
3198 S_is_handle_constructor(const OP *o, I32 numargs)
3199 {
3200     PERL_ARGS_ASSERT_IS_HANDLE_CONSTRUCTOR;
3201
3202     switch (o->op_type) {
3203     case OP_PIPE_OP:
3204     case OP_SOCKPAIR:
3205         if (numargs == 2)
3206             return TRUE;
3207         /* FALLTHROUGH */
3208     case OP_SYSOPEN:
3209     case OP_OPEN:
3210     case OP_SELECT:             /* XXX c.f. SelectSaver.pm */
3211     case OP_SOCKET:
3212     case OP_OPEN_DIR:
3213     case OP_ACCEPT:
3214         if (numargs == 1)
3215             return TRUE;
3216         /* FALLTHROUGH */
3217     default:
3218         return FALSE;
3219     }
3220 }
3221
3222 static OP *
3223 S_refkids(pTHX_ OP *o, I32 type)
3224 {
3225     if (o && o->op_flags & OPf_KIDS) {
3226         OP *kid;
3227         for (kid = cLISTOPo->op_first; kid; kid = OpSIBLING(kid))
3228             ref(kid, type);
3229     }
3230     return o;
3231 }
3232
3233 OP *
3234 Perl_doref(pTHX_ OP *o, I32 type, bool set_op_ref)
3235 {
3236     dVAR;
3237     OP *kid;
3238
3239     PERL_ARGS_ASSERT_DOREF;
3240
3241     if (PL_parser && PL_parser->error_count)
3242         return o;
3243
3244     switch (o->op_type) {
3245     case OP_ENTERSUB:
3246         if ((type == OP_EXISTS || type == OP_DEFINED) &&
3247             !(o->op_flags & OPf_STACKED)) {
3248             OpTYPE_set(o, OP_RV2CV);             /* entersub => rv2cv */
3249             assert(cUNOPo->op_first->op_type == OP_NULL);
3250             op_null(((LISTOP*)cUNOPo->op_first)->op_first);     /* disable pushmark */
3251             o->op_flags |= OPf_SPECIAL;
3252         }
3253         else if (type == OP_RV2SV || type == OP_RV2AV || type == OP_RV2HV){
3254             o->op_private |= (type == OP_RV2AV ? OPpDEREF_AV
3255                               : type == OP_RV2HV ? OPpDEREF_HV
3256                               : OPpDEREF_SV);
3257             o->op_flags |= OPf_MOD;
3258         }
3259
3260         break;
3261
3262     case OP_COND_EXPR:
3263         for (kid = OpSIBLING(cUNOPo->op_first); kid; kid = OpSIBLING(kid))
3264             doref(kid, type, set_op_ref);
3265         break;
3266     case OP_RV2SV:
3267         if (type == OP_DEFINED)
3268             o->op_flags |= OPf_SPECIAL;         /* don't create GV */
3269         doref(cUNOPo->op_first, o->op_type, set_op_ref);
3270         /* FALLTHROUGH */
3271     case OP_PADSV:
3272         if (type == OP_RV2SV || type == OP_RV2AV || type == OP_RV2HV) {
3273             o->op_private |= (type == OP_RV2AV ? OPpDEREF_AV
3274                               : type == OP_RV2HV ? OPpDEREF_HV
3275                               : OPpDEREF_SV);
3276             o->op_flags |= OPf_MOD;
3277         }
3278         break;
3279
3280     case OP_RV2AV:
3281     case OP_RV2HV:
3282         if (set_op_ref)
3283             o->op_flags |= OPf_REF;
3284         /* FALLTHROUGH */
3285     case OP_RV2GV:
3286         if (type == OP_DEFINED)
3287             o->op_flags |= OPf_SPECIAL;         /* don't create GV */
3288         doref(cUNOPo->op_first, o->op_type, set_op_ref);
3289         break;
3290
3291     case OP_PADAV:
3292     case OP_PADHV:
3293         if (set_op_ref)
3294             o->op_flags |= OPf_REF;
3295         break;
3296
3297     case OP_SCALAR:
3298     case OP_NULL:
3299         if (!(o->op_flags & OPf_KIDS) || type == OP_DEFINED)
3300             break;
3301         doref(cBINOPo->op_first, type, set_op_ref);
3302         break;
3303     case OP_AELEM:
3304     case OP_HELEM:
3305         doref(cBINOPo->op_first, o->op_type, set_op_ref);
3306         if (type == OP_RV2SV || type == OP_RV2AV || type == OP_RV2HV) {
3307             o->op_private |= (type == OP_RV2AV ? OPpDEREF_AV
3308                               : type == OP_RV2HV ? OPpDEREF_HV
3309                               : OPpDEREF_SV);
3310             o->op_flags |= OPf_MOD;
3311         }
3312         break;
3313
3314     case OP_SCOPE:
3315     case OP_LEAVE:
3316         set_op_ref = FALSE;
3317         /* FALLTHROUGH */
3318     case OP_ENTER:
3319     case OP_LIST:
3320         if (!(o->op_flags & OPf_KIDS))
3321             break;
3322         doref(cLISTOPo->op_last, type, set_op_ref);
3323         break;
3324     default:
3325         break;
3326     }
3327     return scalar(o);
3328
3329 }
3330
3331 STATIC OP *
3332 S_dup_attrlist(pTHX_ OP *o)
3333 {
3334     OP *rop;
3335
3336     PERL_ARGS_ASSERT_DUP_ATTRLIST;
3337
3338     /* An attrlist is either a simple OP_CONST or an OP_LIST with kids,
3339      * where the first kid is OP_PUSHMARK and the remaining ones
3340      * are OP_CONST.  We need to push the OP_CONST values.
3341      */
3342     if (o->op_type == OP_CONST)
3343         rop = newSVOP(OP_CONST, o->op_flags, SvREFCNT_inc_NN(cSVOPo->op_sv));
3344     else {
3345         assert((o->op_type == OP_LIST) && (o->op_flags & OPf_KIDS));
3346         rop = NULL;
3347         for (o = cLISTOPo->op_first; o; o = OpSIBLING(o)) {
3348             if (o->op_type == OP_CONST)
3349                 rop = op_append_elem(OP_LIST, rop,
3350                                   newSVOP(OP_CONST, o->op_flags,
3351                                           SvREFCNT_inc_NN(cSVOPo->op_sv)));
3352         }
3353     }
3354     return rop;
3355 }
3356
3357 STATIC void
3358 S_apply_attrs(pTHX_ HV *stash, SV *target, OP *attrs)
3359 {
3360     PERL_ARGS_ASSERT_APPLY_ATTRS;
3361     {
3362         SV * const stashsv = newSVhek(HvNAME_HEK(stash));
3363
3364         /* fake up C<use attributes $pkg,$rv,@attrs> */
3365
3366 #define ATTRSMODULE "attributes"
3367 #define ATTRSMODULE_PM "attributes.pm"
3368
3369         Perl_load_module(
3370           aTHX_ PERL_LOADMOD_IMPORT_OPS,
3371           newSVpvs(ATTRSMODULE),
3372           NULL,
3373           op_prepend_elem(OP_LIST,
3374                           newSVOP(OP_CONST, 0, stashsv),
3375                           op_prepend_elem(OP_LIST,
3376                                           newSVOP(OP_CONST, 0,
3377                                                   newRV(target)),
3378                                           dup_attrlist(attrs))));
3379     }
3380 }
3381
3382 STATIC void
3383 S_apply_attrs_my(pTHX_ HV *stash, OP *target, OP *attrs, OP **imopsp)
3384 {
3385     OP *pack, *imop, *arg;
3386     SV *meth, *stashsv, **svp;
3387
3388     PERL_ARGS_ASSERT_APPLY_ATTRS_MY;
3389
3390     if (!attrs)
3391         return;
3392
3393     assert(target->op_type == OP_PADSV ||
3394            target->op_type == OP_PADHV ||
3395            target->op_type == OP_PADAV);
3396
3397     /* Ensure that attributes.pm is loaded. */
3398     /* Don't force the C<use> if we don't need it. */
3399     svp = hv_fetchs(GvHVn(PL_incgv), ATTRSMODULE_PM, FALSE);
3400     if (svp && *svp != &PL_sv_undef)
3401         NOOP;   /* already in %INC */
3402     else
3403         Perl_load_module(aTHX_ PERL_LOADMOD_NOIMPORT,
3404                                newSVpvs(ATTRSMODULE), NULL);
3405
3406     /* Need package name for method call. */
3407     pack = newSVOP(OP_CONST, 0, newSVpvs(ATTRSMODULE));
3408
3409     /* Build up the real arg-list. */
3410     stashsv = newSVhek(HvNAME_HEK(stash));
3411
3412     arg = newOP(OP_PADSV, 0);
3413     arg->op_targ = target->op_targ;
3414     arg = op_prepend_elem(OP_LIST,
3415                        newSVOP(OP_CONST, 0, stashsv),
3416                        op_prepend_elem(OP_LIST,
3417                                     newUNOP(OP_REFGEN, 0,
3418                                             arg),
3419                                     dup_attrlist(attrs)));
3420
3421     /* Fake up a method call to import */
3422     meth = newSVpvs_share("import");
3423     imop = op_convert_list(OP_ENTERSUB, OPf_STACKED|OPf_SPECIAL|OPf_WANT_VOID,
3424                    op_append_elem(OP_LIST,
3425                                op_prepend_elem(OP_LIST, pack, arg),
3426                                newMETHOP_named(OP_METHOD_NAMED, 0, meth)));
3427
3428     /* Combine the ops. */
3429     *imopsp = op_append_elem(OP_LIST, *imopsp, imop);
3430 }
3431
3432 /*
3433 =notfor apidoc apply_attrs_string
3434
3435 Attempts to apply a list of attributes specified by the C<attrstr> and
3436 C<len> arguments to the subroutine identified by the C<cv> argument which
3437 is expected to be associated with the package identified by the C<stashpv>
3438 argument (see L<attributes>).  It gets this wrong, though, in that it
3439 does not correctly identify the boundaries of the individual attribute
3440 specifications within C<attrstr>.  This is not really intended for the
3441 public API, but has to be listed here for systems such as AIX which
3442 need an explicit export list for symbols.  (It's called from XS code
3443 in support of the C<ATTRS:> keyword from F<xsubpp>.)  Patches to fix it
3444 to respect attribute syntax properly would be welcome.
3445
3446 =cut
3447 */
3448
3449 void
3450 Perl_apply_attrs_string(pTHX_ const char *stashpv, CV *cv,
3451                         const char *attrstr, STRLEN len)
3452 {
3453     OP *attrs = NULL;
3454
3455     PERL_ARGS_ASSERT_APPLY_ATTRS_STRING;
3456
3457     if (!len) {
3458         len = strlen(attrstr);
3459     }
3460
3461     while (len) {
3462         for (; isSPACE(*attrstr) && len; --len, ++attrstr) ;
3463         if (len) {
3464             const char * const sstr = attrstr;
3465             for (; !isSPACE(*attrstr) && len; --len, ++attrstr) ;
3466             attrs = op_append_elem(OP_LIST, attrs,
3467                                 newSVOP(OP_CONST, 0,
3468                                         newSVpvn(sstr, attrstr-sstr)));
3469         }
3470     }
3471
3472     Perl_load_module(aTHX_ PERL_LOADMOD_IMPORT_OPS,
3473                      newSVpvs(ATTRSMODULE),
3474                      NULL, op_prepend_elem(OP_LIST,
3475                                   newSVOP(OP_CONST, 0, newSVpv(stashpv,0)),
3476                                   op_prepend_elem(OP_LIST,
3477                                                newSVOP(OP_CONST, 0,
3478                                                        newRV(MUTABLE_SV(cv))),
3479                                                attrs)));
3480 }
3481
3482 STATIC void
3483 S_move_proto_attr(pTHX_ OP **proto, OP **attrs, const GV * name)
3484 {
3485     OP *new_proto = NULL;
3486     STRLEN pvlen;
3487     char *pv;
3488     OP *o;
3489
3490     PERL_ARGS_ASSERT_MOVE_PROTO_ATTR;
3491
3492     if (!*attrs)
3493         return;
3494
3495     o = *attrs;
3496     if (o->op_type == OP_CONST) {
3497         pv = SvPV(cSVOPo_sv, pvlen);
3498         if (pvlen >= 10 && memEQ(pv, "prototype(", 10)) {
3499             SV * const tmpsv = newSVpvn_flags(pv + 10, pvlen - 11, SvUTF8(cSVOPo_sv));
3500             SV ** const tmpo = cSVOPx_svp(o);
3501             SvREFCNT_dec(cSVOPo_sv);
3502             *tmpo = tmpsv;
3503             new_proto = o;
3504             *attrs = NULL;
3505         }
3506     } else if (o->op_type == OP_LIST) {
3507         OP * lasto;
3508         assert(o->op_flags & OPf_KIDS);
3509         lasto = cLISTOPo->op_first;
3510         assert(lasto->op_type == OP_PUSHMARK);
3511         for (o = OpSIBLING(lasto); o; o = OpSIBLING(o)) {
3512             if (o->op_type == OP_CONST) {
3513                 pv = SvPV(cSVOPo_sv, pvlen);
3514                 if (pvlen >= 10 && memEQ(pv, "prototype(", 10)) {
3515                     SV * const tmpsv = newSVpvn_flags(pv + 10, pvlen - 11, SvUTF8(cSVOPo_sv));
3516                     SV ** const tmpo = cSVOPx_svp(o);
3517                     SvREFCNT_dec(cSVOPo_sv);
3518                     *tmpo = tmpsv;
3519                     if (new_proto && ckWARN(WARN_MISC)) {
3520                         STRLEN new_len;
3521                         const char * newp = SvPV(cSVOPo_sv, new_len);
3522                         Perl_warner(aTHX_ packWARN(WARN_MISC),
3523                             "Attribute prototype(%"UTF8f") discards earlier prototype attribute in same sub",
3524                             UTF8fARG(SvUTF8(cSVOPo_sv), new_len, newp));
3525                         op_free(new_proto);
3526                     }
3527                     else if (new_proto)
3528                         op_free(new_proto);
3529                     new_proto = o;
3530                     /* excise new_proto from the list */
3531                     op_sibling_splice(*attrs, lasto, 1, NULL);
3532                     o = lasto;
3533                     continue;
3534                 }
3535             }
3536             lasto = o;
3537         }
3538         /* If the list is now just the PUSHMARK, scrap the whole thing; otherwise attributes.xs
3539            would get pulled in with no real need */
3540         if (!OpHAS_SIBLING(cLISTOPx(*attrs)->op_first)) {
3541             op_free(*attrs);
3542             *attrs = NULL;
3543         }
3544     }
3545
3546     if (new_proto) {
3547         SV *svname;
3548         if (isGV(name)) {
3549             svname = sv_newmortal();
3550             gv_efullname3(svname, name, NULL);
3551         }
3552         else if (SvPOK(name) && *SvPVX((SV *)name) == '&')
3553             svname = newSVpvn_flags(SvPVX((SV *)name)+1, SvCUR(name)-1, SvUTF8(name)|SVs_TEMP);
3554         else
3555             svname = (SV *)name;
3556         if (ckWARN(WARN_ILLEGALPROTO))
3557             (void)validate_proto(svname, cSVOPx_sv(new_proto), TRUE);
3558         if (*proto && ckWARN(WARN_PROTOTYPE)) {
3559             STRLEN old_len, new_len;
3560             const char * oldp = SvPV(cSVOPx_sv(*proto), old_len);
3561             const char * newp = SvPV(cSVOPx_sv(new_proto), new_len);
3562
3563             Perl_warner(aTHX_ packWARN(WARN_PROTOTYPE),
3564                 "Prototype '%"UTF8f"' overridden by attribute 'prototype(%"UTF8f")'"
3565                 " in %"SVf,
3566                 UTF8fARG(SvUTF8(cSVOPx_sv(*proto)), old_len, oldp),
3567                 UTF8fARG(SvUTF8(cSVOPx_sv(new_proto)), new_len, newp),
3568                 SVfARG(svname));
3569         }
3570         if (*proto)
3571             op_free(*proto);
3572         *proto = new_proto;
3573     }
3574 }
3575
3576 static void
3577 S_cant_declare(pTHX_ OP *o)
3578 {
3579     if (o->op_type == OP_NULL
3580      && (o->op_flags & (OPf_SPECIAL|OPf_KIDS)) == OPf_KIDS)
3581         o = cUNOPo->op_first;
3582     yyerror(Perl_form(aTHX_ "Can't declare %s in \"%s\"",
3583                              o->op_type == OP_NULL
3584                                && o->op_flags & OPf_SPECIAL
3585                                  ? "do block"
3586                                  : OP_DESC(o),
3587                              PL_parser->in_my == KEY_our   ? "our"   :
3588                              PL_parser->in_my == KEY_state ? "state" :
3589                                                              "my"));
3590 }
3591
3592 STATIC OP *
3593 S_my_kid(pTHX_ OP *o, OP *attrs, OP **imopsp)
3594 {
3595     I32 type;
3596     const bool stately = PL_parser && PL_parser->in_my == KEY_state;
3597
3598     PERL_ARGS_ASSERT_MY_KID;
3599
3600     if (!o || (PL_parser && PL_parser->error_count))
3601         return o;
3602
3603     type = o->op_type;
3604
3605     if (type == OP_LIST) {
3606         OP *kid;
3607         for (kid = cLISTOPo->op_first; kid; kid = OpSIBLING(kid))
3608             my_kid(kid, attrs, imopsp);
3609         return o;
3610     } else if (type == OP_UNDEF || type == OP_STUB) {
3611         return o;
3612     } else if (type == OP_RV2SV ||      /* "our" declaration */
3613                type == OP_RV2AV ||
3614                type == OP_RV2HV) { /* XXX does this let anything illegal in? */
3615         if (cUNOPo->op_first->op_type != OP_GV) { /* MJD 20011224 */
3616             S_cant_declare(aTHX_ o);
3617         } else if (attrs) {
3618             GV * const gv = cGVOPx_gv(cUNOPo->op_first);
3619             assert(PL_parser);
3620             PL_parser->in_my = FALSE;
3621             PL_parser->in_my_stash = NULL;
3622             apply_attrs(GvSTASH(gv),
3623                         (type == OP_RV2SV ? GvSV(gv) :
3624                          type == OP_RV2AV ? MUTABLE_SV(GvAV(gv)) :
3625                          type == OP_RV2HV ? MUTABLE_SV(GvHV(gv)) : MUTABLE_SV(gv)),
3626                         attrs);
3627         }
3628         o->op_private |= OPpOUR_INTRO;
3629         return o;
3630     }
3631     else if (type != OP_PADSV &&
3632              type != OP_PADAV &&
3633              type != OP_PADHV &&
3634              type != OP_PUSHMARK)
3635     {
3636         S_cant_declare(aTHX_ o);
3637         return o;
3638     }
3639     else if (attrs && type != OP_PUSHMARK) {
3640         HV *stash;
3641
3642         assert(PL_parser);
3643         PL_parser->in_my = FALSE;
3644         PL_parser->in_my_stash = NULL;
3645
3646         /* check for C<my Dog $spot> when deciding package */
3647         stash = PAD_COMPNAME_TYPE(o->op_targ);
3648         if (!stash)
3649             stash = PL_curstash;
3650         apply_attrs_my(stash, o, attrs, imopsp);
3651     }
3652     o->op_flags |= OPf_MOD;
3653     o->op_private |= OPpLVAL_INTRO;
3654     if (stately)
3655         o->op_private |= OPpPAD_STATE;
3656     return o;
3657 }
3658
3659 OP *
3660 Perl_my_attrs(pTHX_ OP *o, OP *attrs)
3661 {
3662     OP *rops;
3663     int maybe_scalar = 0;
3664
3665     PERL_ARGS_ASSERT_MY_ATTRS;
3666
3667 /* [perl #17376]: this appears to be premature, and results in code such as
3668    C< our(%x); > executing in list mode rather than void mode */
3669 #if 0
3670     if (o->op_flags & OPf_PARENS)
3671         list(o);
3672     else
3673         maybe_scalar = 1;
3674 #else
3675     maybe_scalar = 1;
3676 #endif
3677     if (attrs)
3678         SAVEFREEOP(attrs);
3679     rops = NULL;
3680     o = my_kid(o, attrs, &rops);
3681     if (rops) {
3682         if (maybe_scalar && o->op_type == OP_PADSV) {
3683             o = scalar(op_append_list(OP_LIST, rops, o));
3684             o->op_private |= OPpLVAL_INTRO;
3685         }
3686         else {
3687             /* The listop in rops might have a pushmark at the beginning,
3688                which will mess up list assignment. */
3689             LISTOP * const lrops = (LISTOP *)rops; /* for brevity */
3690             if (rops->op_type == OP_LIST && 
3691                 lrops->op_first && lrops->op_first->op_type == OP_PUSHMARK)
3692             {
3693                 OP * const pushmark = lrops->op_first;
3694                 /* excise pushmark */
3695                 op_sibling_splice(rops, NULL, 1, NULL);
3696                 op_free(pushmark);
3697             }
3698             o = op_append_list(OP_LIST, o, rops);
3699         }
3700     }
3701     PL_parser->in_my = FALSE;
3702     PL_parser->in_my_stash = NULL;
3703     return o;
3704 }
3705
3706 OP *
3707 Perl_sawparens(pTHX_ OP *o)
3708 {
3709     PERL_UNUSED_CONTEXT;
3710     if (o)
3711         o->op_flags |= OPf_PARENS;
3712     return o;
3713 }
3714
3715 OP *
3716 Perl_bind_match(pTHX_ I32 type, OP *left, OP *right)
3717 {
3718     OP *o;
3719     bool ismatchop = 0;
3720     const OPCODE ltype = left->op_type;
3721     const OPCODE rtype = right->op_type;
3722
3723     PERL_ARGS_ASSERT_BIND_MATCH;
3724
3725     if ( (ltype == OP_RV2AV || ltype == OP_RV2HV || ltype == OP_PADAV
3726           || ltype == OP_PADHV) && ckWARN(WARN_MISC))
3727     {
3728       const char * const desc
3729           = PL_op_desc[(
3730                           rtype == OP_SUBST || rtype == OP_TRANS
3731                        || rtype == OP_TRANSR
3732                        )
3733                        ? (int)rtype : OP_MATCH];
3734       const bool isary = ltype == OP_RV2AV || ltype == OP_PADAV;
3735       SV * const name =
3736         S_op_varname(aTHX_ left);
3737       if (name)
3738         Perl_warner(aTHX_ packWARN(WARN_MISC),
3739              "Applying %s to %"SVf" will act on scalar(%"SVf")",
3740              desc, SVfARG(name), SVfARG(name));
3741       else {
3742         const char * const sample = (isary
3743              ? "@array" : "%hash");
3744         Perl_warner(aTHX_ packWARN(WARN_MISC),
3745              "Applying %s to %s will act on scalar(%s)",
3746              desc, sample, sample);
3747       }
3748     }
3749
3750     if (rtype == OP_CONST &&
3751         cSVOPx(right)->op_private & OPpCONST_BARE &&
3752         cSVOPx(right)->op_private & OPpCONST_STRICT)
3753     {
3754         no_bareword_allowed(right);
3755     }
3756
3757     /* !~ doesn't make sense with /r, so error on it for now */
3758     if (rtype == OP_SUBST && (cPMOPx(right)->op_pmflags & PMf_NONDESTRUCT) &&
3759         type == OP_NOT)
3760         /* diag_listed_as: Using !~ with %s doesn't make sense */
3761         yyerror("Using !~ with s///r doesn't make sense");
3762     if (rtype == OP_TRANSR && type == OP_NOT)
3763         /* diag_listed_as: Using !~ with %s doesn't make sense */
3764         yyerror("Using !~ with tr///r doesn't make sense");
3765
3766     ismatchop = (rtype == OP_MATCH ||
3767                  rtype == OP_SUBST ||
3768                  rtype == OP_TRANS || rtype == OP_TRANSR)
3769              && !(right->op_flags & OPf_SPECIAL);
3770     if (ismatchop && right->op_private & OPpTARGET_MY) {
3771         right->op_targ = 0;
3772         right->op_private &= ~OPpTARGET_MY;
3773     }
3774     if (!(right->op_flags & OPf_STACKED) && !right->op_targ && ismatchop) {
3775         if (left->op_type == OP_PADSV
3776          && !(left->op_private & OPpLVAL_INTRO))
3777         {
3778             right->op_targ = left->op_targ;
3779             op_free(left);
3780             o = right;
3781         }
3782         else {
3783             right->op_flags |= OPf_STACKED;
3784             if (rtype != OP_MATCH && rtype != OP_TRANSR &&
3785             ! (rtype == OP_TRANS &&
3786                right->op_private & OPpTRANS_IDENTICAL) &&
3787             ! (rtype == OP_SUBST &&
3788                (cPMOPx(right)->op_pmflags & PMf_NONDESTRUCT)))
3789                 left = op_lvalue(left, rtype);
3790             if (right->op_type == OP_TRANS || right->op_type == OP_TRANSR)
3791                 o = newBINOP(OP_NULL, OPf_STACKED, scalar(left), right);
3792             else
3793                 o = op_prepend_elem(rtype, scalar(left), right);
3794         }
3795         if (type == OP_NOT)
3796             return newUNOP(OP_NOT, 0, scalar(o));
3797         return o;
3798     }
3799     else
3800         return bind_match(type, left,
3801                 pmruntime(newPMOP(OP_MATCH, 0), right, NULL, 0, 0));
3802 }
3803
3804 OP *
3805 Perl_invert(pTHX_ OP *o)
3806 {
3807     if (!o)
3808         return NULL;
3809     return newUNOP(OP_NOT, OPf_SPECIAL, scalar(o));
3810 }
3811
3812 /*
3813 =for apidoc Amx|OP *|op_scope|OP *o
3814
3815 Wraps up an op tree with some additional ops so that at runtime a dynamic
3816 scope will be created.  The original ops run in the new dynamic scope,
3817 and then, provided that they exit normally, the scope will be unwound.
3818 The additional ops used to create and unwind the dynamic scope will
3819 normally be an C<enter>/C<leave> pair, but a C<scope> op may be used
3820 instead if the ops are simple enough to not need the full dynamic scope
3821 structure.
3822
3823 =cut
3824 */
3825
3826 OP *
3827 Perl_op_scope(pTHX_ OP *o)
3828 {
3829     dVAR;
3830     if (o) {
3831         if (o->op_flags & OPf_PARENS || PERLDB_NOOPT || TAINTING_get) {
3832             o = op_prepend_elem(OP_LINESEQ, newOP(OP_ENTER, 0), o);
3833             OpTYPE_set(o, OP_LEAVE);
3834         }
3835         else if (o->op_type == OP_LINESEQ) {
3836             OP *kid;
3837             OpTYPE_set(o, OP_SCOPE);
3838             kid = ((LISTOP*)o)->op_first;
3839             if (kid->op_type == OP_NEXTSTATE || kid->op_type == OP_DBSTATE) {
3840                 op_null(kid);
3841
3842                 /* The following deals with things like 'do {1 for 1}' */
3843                 kid = OpSIBLING(kid);
3844                 if (kid &&
3845                     (kid->op_type == OP_NEXTSTATE || kid->op_type == OP_DBSTATE))
3846                     op_null(kid);
3847             }
3848         }
3849         else
3850             o = newLISTOP(OP_SCOPE, 0, o, NULL);
3851     }
3852     return o;
3853 }
3854
3855 OP *
3856 Perl_op_unscope(pTHX_ OP *o)
3857 {
3858     if (o && o->op_type == OP_LINESEQ) {
3859         OP *kid = cLISTOPo->op_first;
3860         for(; kid; kid = OpSIBLING(kid))
3861             if (kid->op_type == OP_NEXTSTATE || kid->op_type == OP_DBSTATE)
3862                 op_null(kid);
3863     }
3864     return o;
3865 }
3866
3867 /*
3868 =for apidoc Am|int|block_start|int full
3869
3870 Handles compile-time scope entry.
3871 Arranges for hints to be restored on block
3872 exit and also handles pad sequence numbers to make lexical variables scope
3873 right.  Returns a savestack index for use with C<block_end>.
3874
3875 =cut
3876 */
3877
3878 int
3879 Perl_block_start(pTHX_ int full)
3880 {
3881     const int retval = PL_savestack_ix;
3882
3883     PL_compiling.cop_seq = PL_cop_seqmax;
3884     COP_SEQMAX_INC;
3885     pad_block_start(full);
3886     SAVEHINTS();
3887     PL_hints &= ~HINT_BLOCK_SCOPE;
3888     SAVECOMPILEWARNINGS();
3889     PL_compiling.cop_warnings = DUP_WARNINGS(PL_compiling.cop_warnings);
3890     SAVEI32(PL_compiling.cop_seq);
3891     PL_compiling.cop_seq = 0;
3892
3893     CALL_BLOCK_HOOKS(bhk_start, full);
3894
3895     return retval;
3896 }
3897
3898 /*
3899 =for apidoc Am|OP *|block_end|I32 floor|OP *seq
3900
3901 Handles compile-time scope exit.  C<floor>
3902 is the savestack index returned by
3903 C<block_start>, and C<seq> is the body of the block.  Returns the block,
3904 possibly modified.
3905
3906 =cut
3907 */
3908
3909 OP*
3910 Perl_block_end(pTHX_ I32 floor, OP *seq)
3911 {
3912     const int needblockscope = PL_hints & HINT_BLOCK_SCOPE;
3913     OP* retval = scalarseq(seq);
3914     OP *o;
3915
3916     /* XXX Is the null PL_parser check necessary here? */
3917     assert(PL_parser); /* Let’s find out under debugging builds.  */
3918     if (PL_parser && PL_parser->parsed_sub) {
3919         o = newSTATEOP(0, NULL, NULL);
3920         op_null(o);
3921         retval = op_append_elem(OP_LINESEQ, retval, o);
3922     }
3923
3924     CALL_BLOCK_HOOKS(bhk_pre_end, &retval);
3925
3926     LEAVE_SCOPE(floor);
3927     if (needblockscope)
3928         PL_hints |= HINT_BLOCK_SCOPE; /* propagate out */
3929     o = pad_leavemy();
3930
3931     if (o) {
3932         /* pad_leavemy has created a sequence of introcv ops for all my
3933            subs declared in the block.  We have to replicate that list with
3934            clonecv ops, to deal with this situation:
3935
3936                sub {
3937                    my sub s1;
3938                    my sub s2;
3939                    sub s1 { state sub foo { \&s2 } }
3940                }->()
3941
3942            Originally, I was going to have introcv clone the CV and turn
3943            off the stale flag.  Since &s1 is declared before &s2, the
3944            introcv op for &s1 is executed (on sub entry) before the one for
3945            &s2.  But the &foo sub inside &s1 (which is cloned when &s1 is
3946            cloned, since it is a state sub) closes over &s2 and expects
3947            to see it in its outer CV’s pad.  If the introcv op clones &s1,
3948            then &s2 is still marked stale.  Since &s1 is not active, and
3949            &foo closes over &s1’s implicit entry for &s2, we get a â€˜Varia-
3950            ble will not stay shared’ warning.  Because it is the same stub
3951            that will be used when the introcv op for &s2 is executed, clos-
3952            ing over it is safe.  Hence, we have to turn off the stale flag
3953            on all lexical subs in the block before we clone any of them.
3954            Hence, having introcv clone the sub cannot work.  So we create a
3955            list of ops like this:
3956
3957                lineseq
3958                   |
3959                   +-- introcv
3960                   |
3961                   +-- introcv
3962                   |
3963                   +-- introcv
3964                   |
3965                   .
3966                   .
3967                   .
3968                   |
3969                   +-- clonecv
3970                   |
3971                   +-- clonecv
3972                   |
3973                   +-- clonecv
3974                   |
3975                   .
3976                   .
3977                   .
3978          */
3979         OP *kid = o->op_flags & OPf_KIDS ? cLISTOPo->op_first : o;
3980         OP * const last = o->op_flags & OPf_KIDS ? cLISTOPo->op_last : o;
3981         for (;; kid = OpSIBLING(kid)) {
3982             OP *newkid = newOP(OP_CLONECV, 0);
3983             newkid->op_targ = kid->op_targ;
3984             o = op_append_elem(OP_LINESEQ, o, newkid);
3985             if (kid == last) break;
3986         }
3987         retval = op_prepend_elem(OP_LINESEQ, o, retval);
3988     }
3989
3990     CALL_BLOCK_HOOKS(bhk_post_end, &retval);
3991
3992     return retval;
3993 }
3994
3995 /*
3996 =head1 Compile-time scope hooks
3997
3998 =for apidoc Aox||blockhook_register
3999
4000 Register a set of hooks to be called when the Perl lexical scope changes
4001 at compile time.  See L<perlguts/"Compile-time scope hooks">.
4002
4003 =cut
4004 */
4005
4006 void
4007 Perl_blockhook_register(pTHX_ BHK *hk)
4008 {
4009     PERL_ARGS_ASSERT_BLOCKHOOK_REGISTER;
4010
4011     Perl_av_create_and_push(aTHX_ &PL_blockhooks, newSViv(PTR2IV(hk)));
4012 }
4013
4014 void
4015 Perl_newPROG(pTHX_ OP *o)
4016 {
4017     PERL_ARGS_ASSERT_NEWPROG;
4018
4019     if (PL_in_eval) {
4020         PERL_CONTEXT *cx;
4021         I32 i;
4022         if (PL_eval_root)
4023                 return;
4024         PL_eval_root = newUNOP(OP_LEAVEEVAL,
4025                                ((PL_in_eval & EVAL_KEEPERR)
4026                                 ? OPf_SPECIAL : 0), o);
4027
4028         cx = &cxstack[cxstack_ix];
4029         assert(CxTYPE(cx) == CXt_EVAL);
4030
4031         if ((cx->blk_gimme & G_WANT) == G_VOID)
4032             scalarvoid(PL_eval_root);
4033         else if ((cx->blk_gimme & G_WANT) == G_ARRAY)
4034             list(PL_eval_root);
4035         else
4036             scalar(PL_eval_root);
4037
4038         PL_eval_start = op_linklist(PL_eval_root);
4039         PL_eval_root->op_private |= OPpREFCOUNTED;
4040         OpREFCNT_set(PL_eval_root, 1);
4041         PL_eval_root->op_next = 0;
4042         i = PL_savestack_ix;
4043         SAVEFREEOP(o);
4044         ENTER;
4045         CALL_PEEP(PL_eval_start);
4046         finalize_optree(PL_eval_root);
4047         S_prune_chain_head(&PL_eval_start);
4048         LEAVE;
4049         PL_savestack_ix = i;
4050     }
4051     else {
4052         if (o->op_type == OP_STUB) {
4053             /* This block is entered if nothing is compiled for the main
4054                program. This will be the case for an genuinely empty main
4055                program, or one which only has BEGIN blocks etc, so already
4056                run and freed.
4057
4058                Historically (5.000) the guard above was !o. However, commit
4059                f8a08f7b8bd67b28 (Jun 2001), integrated to blead as
4060                c71fccf11fde0068, changed perly.y so that newPROG() is now
4061                called with the output of block_end(), which returns a new
4062                OP_STUB for the case of an empty optree. ByteLoader (and
4063                maybe other things) also take this path, because they set up
4064                PL_main_start and PL_main_root directly, without generating an
4065                optree.
4066
4067                If the parsing the main program aborts (due to parse errors,
4068                or due to BEGIN or similar calling exit), then newPROG()
4069                isn't even called, and hence this code path and its cleanups
4070                are skipped. This shouldn't make a make a difference:
4071                * a non-zero return from perl_parse is a failure, and
4072                  perl_destruct() should be called immediately.
4073                * however, if exit(0) is called during the parse, then
4074                  perl_parse() returns 0, and perl_run() is called. As
4075                  PL_main_start will be NULL, perl_run() will return
4076                  promptly, and the exit code will remain 0.
4077             */
4078
4079             PL_comppad_name = 0;
4080             PL_compcv = 0;
4081             S_op_destroy(aTHX_ o);
4082             return;
4083         }
4084         PL_main_root = op_scope(sawparens(scalarvoid(o)));
4085         PL_curcop = &PL_compiling;
4086         PL_main_start = LINKLIST(PL_main_root);
4087         PL_main_root->op_private |= OPpREFCOUNTED;
4088         OpREFCNT_set(PL_main_root, 1);
4089         PL_main_root->op_next = 0;
4090         CALL_PEEP(PL_main_start);
4091         finalize_optree(PL_main_root);
4092         S_prune_chain_head(&PL_main_start);
4093         cv_forget_slab(PL_compcv);
4094         PL_compcv = 0;
4095
4096         /* Register with debugger */
4097         if (PERLDB_INTER) {
4098             CV * const cv = get_cvs("DB::postponed", 0);
4099             if (cv) {
4100                 dSP;
4101                 PUSHMARK(SP);
4102                 XPUSHs(MUTABLE_SV(CopFILEGV(&PL_compiling)));
4103                 PUTBACK;
4104                 call_sv(MUTABLE_SV(cv), G_DISCARD);
4105             }
4106         }
4107     }
4108 }
4109
4110 OP *
4111 Perl_localize(pTHX_ OP *o, I32 lex)
4112 {
4113     PERL_ARGS_ASSERT_LOCALIZE;
4114
4115     if (o->op_flags & OPf_PARENS)
4116 /* [perl #17376]: this appears to be premature, and results in code such as
4117    C< our(%x); > executing in list mode rather than void mode */
4118 #if 0
4119         list(o);
4120 #else
4121         NOOP;
4122 #endif
4123     else {
4124         if ( PL_parser->bufptr > PL_parser->oldbufptr
4125             && PL_parser->bufptr[-1] == ','
4126             && ckWARN(WARN_PARENTHESIS))
4127         {
4128             char *s = PL_parser->bufptr;
4129             bool sigil = FALSE;
4130
4131             /* some heuristics to detect a potential error */
4132             while (*s && (strchr(", \t\n", *s)))
4133                 s++;
4134
4135             while (1) {
4136                 if (*s && strchr("@$%*", *s) && *++s
4137                        && (isWORDCHAR(*s) || UTF8_IS_CONTINUED(*s))) {
4138                     s++;
4139                     sigil = TRUE;
4140                     while (*s && (isWORDCHAR(*s) || UTF8_IS_CONTINUED(*s)))
4141                         s++;
4142                     while (*s && (strchr(", \t\n", *s)))
4143                         s++;
4144                 }
4145                 else
4146                     break;
4147             }
4148             if (sigil && (*s == ';' || *s == '=')) {
4149                 Perl_warner(aTHX_ packWARN(WARN_PARENTHESIS),
4150                                 "Parentheses missing around \"%s\" list",
4151                                 lex
4152                                     ? (PL_parser->in_my == KEY_our
4153                                         ? "our"
4154                                         : PL_parser->in_my == KEY_state
4155                                             ? "state"
4156                                             : "my")
4157                                     : "local");
4158             }
4159         }
4160     }
4161     if (lex)
4162         o = my(o);
4163     else
4164         o = op_lvalue(o, OP_NULL);              /* a bit kludgey */
4165     PL_parser->in_my = FALSE;
4166     PL_parser->in_my_stash = NULL;
4167     return o;
4168 }
4169
4170 OP *
4171 Perl_jmaybe(pTHX_ OP *o)
4172 {
4173     PERL_ARGS_ASSERT_JMAYBE;
4174
4175     if (o->op_type == OP_LIST) {
4176         OP * const o2
4177             = newSVREF(newGVOP(OP_GV, 0, gv_fetchpvs(";", GV_ADD|GV_NOTQUAL, SVt_PV)));
4178         o = op_convert_list(OP_JOIN, 0, op_prepend_elem(OP_LIST, o2, o));
4179     }
4180     return o;
4181 }
4182
4183 PERL_STATIC_INLINE OP *
4184 S_op_std_init(pTHX_ OP *o)
4185 {
4186     I32 type = o->op_type;
4187
4188     PERL_ARGS_ASSERT_OP_STD_INIT;
4189
4190     if (PL_opargs[type] & OA_RETSCALAR)
4191         scalar(o);
4192     if (PL_opargs[type] & OA_TARGET && !o->op_targ)
4193         o->op_targ = pad_alloc(type, SVs_PADTMP);
4194
4195     return o;
4196 }
4197
4198 PERL_STATIC_INLINE OP *
4199 S_op_integerize(pTHX_ OP *o)
4200 {
4201     I32 type = o->op_type;
4202
4203     PERL_ARGS_ASSERT_OP_INTEGERIZE;
4204
4205     /* integerize op. */
4206     if ((PL_opargs[type] & OA_OTHERINT) && (PL_hints & HINT_INTEGER))
4207     {
4208         dVAR;
4209         o->op_ppaddr = PL_ppaddr[++(o->op_type)];
4210     }
4211
4212     if (type == OP_NEGATE)
4213         /* XXX might want a ck_negate() for this */
4214         cUNOPo->op_first->op_private &= ~OPpCONST_STRICT;
4215
4216     return o;
4217 }
4218
4219 static OP *
4220 S_fold_constants(pTHX_ OP *o)
4221 {
4222     dVAR;
4223     OP * VOL curop;
4224     OP *newop;
4225     VOL I32 type = o->op_type;
4226     bool is_stringify;
4227     SV * VOL sv = NULL;
4228     int ret = 0;
4229     I32 oldscope;
4230     OP *old_next;
4231     SV * const oldwarnhook = PL_warnhook;
4232     SV * const olddiehook  = PL_diehook;
4233     COP not_compiling;
4234     U8 oldwarn = PL_dowarn;
4235     dJMPENV;
4236
4237     PERL_ARGS_ASSERT_FOLD_CONSTANTS;
4238
4239     if (!(PL_opargs[type] & OA_FOLDCONST))
4240         goto nope;
4241
4242     switch (type) {
4243     case OP_UCFIRST:
4244     case OP_LCFIRST:
4245     case OP_UC:
4246     case OP_LC:
4247     case OP_FC:
4248 #ifdef USE_LOCALE_CTYPE
4249         if (IN_LC_COMPILETIME(LC_CTYPE))
4250             goto nope;
4251 #endif
4252         break;
4253     case OP_SLT:
4254     case OP_SGT:
4255     case OP_SLE:
4256     case OP_SGE:
4257     case OP_SCMP:
4258 #ifdef USE_LOCALE_COLLATE
4259         if (IN_LC_COMPILETIME(LC_COLLATE))
4260             goto nope;
4261 #endif
4262         break;
4263     case OP_SPRINTF:
4264         /* XXX what about the numeric ops? */
4265 #ifdef USE_LOCALE_NUMERIC
4266         if (IN_LC_COMPILETIME(LC_NUMERIC))
4267             goto nope;
4268 #endif
4269         break;
4270     case OP_PACK:
4271         if (!OpHAS_SIBLING(cLISTOPo->op_first)
4272           || OpSIBLING(cLISTOPo->op_first)->op_type != OP_CONST)
4273             goto nope;
4274         {
4275             SV * const sv = cSVOPx_sv(OpSIBLING(cLISTOPo->op_first));
4276             if (!SvPOK(sv) || SvGMAGICAL(sv)) goto nope;
4277             {
4278                 const char *s = SvPVX_const(sv);
4279                 while (s < SvEND(sv)) {
4280                     if (isALPHA_FOLD_EQ(*s, 'p')) goto nope;
4281                     s++;
4282                 }
4283             }
4284         }
4285         break;
4286     case OP_REPEAT:
4287         if (o->op_private & OPpREPEAT_DOLIST) goto nope;
4288         break;
4289     case OP_SREFGEN:
4290         if (cUNOPx(cUNOPo->op_first)->op_first->op_type != OP_CONST
4291          || SvPADTMP(cSVOPx_sv(cUNOPx(cUNOPo->op_first)->op_first)))
4292             goto nope;
4293     }
4294
4295     if (PL_parser && PL_parser->error_count)
4296         goto nope;              /* Don't try to run w/ errors */
4297
4298     for (curop = LINKLIST(o); curop != o; curop = LINKLIST(curop)) {
4299         const OPCODE type = curop->op_type;
4300         if ((type != OP_CONST || (curop->op_private & OPpCONST_BARE)) &&
4301             type != OP_LIST &&
4302             type != OP_SCALAR &&
4303             type != OP_NULL &&
4304             type != OP_PUSHMARK)
4305         {
4306             goto nope;
4307         }
4308     }
4309
4310     curop = LINKLIST(o);
4311     old_next = o->op_next;
4312     o->op_next = 0;
4313     PL_op = curop;
4314
4315     oldscope = PL_scopestack_ix;
4316     create_eval_scope(G_FAKINGEVAL);
4317
4318     /* Verify that we don't need to save it:  */
4319     assert(PL_curcop == &PL_compiling);
4320     StructCopy(&PL_compiling, &not_compiling, COP);
4321     PL_curcop = &not_compiling;
4322     /* The above ensures that we run with all the correct hints of the
4323        currently compiling COP, but that IN_PERL_RUNTIME is true. */
4324     assert(IN_PERL_RUNTIME);
4325     PL_warnhook = PERL_WARNHOOK_FATAL;
4326     PL_diehook  = NULL;
4327     JMPENV_PUSH(ret);
4328
4329     /* Effective $^W=1.  */
4330     if ( ! (PL_dowarn & G_WARN_ALL_MASK))
4331         PL_dowarn |= G_WARN_ON;
4332
4333     switch (ret) {
4334     case 0:
4335         CALLRUNOPS(aTHX);
4336         sv = *(PL_stack_sp--);
4337         if (o->op_targ && sv == PAD_SV(o->op_targ)) {   /* grab pad temp? */
4338             pad_swipe(o->op_targ,  FALSE);
4339         }
4340         else if (SvTEMP(sv)) {                  /* grab mortal temp? */
4341             SvREFCNT_inc_simple_void(sv);
4342             SvTEMP_off(sv);
4343         }
4344         else { assert(SvIMMORTAL(sv)); }
4345         break;
4346     case 3:
4347         /* Something tried to die.  Abandon constant folding.  */
4348         /* Pretend the error never happened.  */
4349         CLEAR_ERRSV();
4350         o->op_next = old_next;
4351         break;
4352     default:
4353         JMPENV_POP;
4354         /* Don't expect 1 (setjmp failed) or 2 (something called my_exit)  */
4355         PL_warnhook = oldwarnhook;
4356         PL_diehook  = olddiehook;
4357         /* XXX note that this croak may fail as we've already blown away
4358          * the stack - eg any nested evals */
4359         Perl_croak(aTHX_ "panic: fold_constants JMPENV_PUSH returned %d", ret);
4360     }
4361     JMPENV_POP;
4362     PL_dowarn   = oldwarn;
4363     PL_warnhook = oldwarnhook;
4364     PL_diehook  = olddiehook;
4365     PL_curcop = &PL_compiling;
4366
4367     if (PL_scopestack_ix > oldscope)
4368         delete_eval_scope();
4369
4370     if (ret)
4371         goto nope;
4372
4373     /* OP_STRINGIFY and constant folding are used to implement qq.
4374        Here the constant folding is an implementation detail that we
4375        want to hide.  If the stringify op is itself already marked
4376        folded, however, then it is actually a folded join.  */
4377     is_stringify = type == OP_STRINGIFY && !o->op_folded;
4378     op_free(o);
4379     assert(sv);
4380     if (is_stringify)
4381         SvPADTMP_off(sv);
4382     else if (!SvIMMORTAL(sv)) {
4383         SvPADTMP_on(sv);
4384         SvREADONLY_on(sv);
4385     }
4386     newop = newSVOP(OP_CONST, 0, MUTABLE_SV(sv));
4387     if (!is_stringify) newop->op_folded = 1;
4388     return newop;
4389
4390  nope:
4391     return o;
4392 }
4393
4394 static OP *
4395 S_gen_constant_list(pTHX_ OP *o)
4396 {
4397     dVAR;
4398     OP *curop;
4399     const SSize_t oldtmps_floor = PL_tmps_floor;
4400     SV **svp;
4401     AV *av;
4402
4403     list(o);
4404     if (PL_parser && PL_parser->error_count)
4405         return o;               /* Don't attempt to run with errors */
4406
4407     curop = LINKLIST(o);
4408     o->op_next = 0;
4409     CALL_PEEP(curop);
4410     S_prune_chain_head(&curop);
4411     PL_op = curop;
4412     Perl_pp_pushmark(aTHX);
4413     CALLRUNOPS(aTHX);
4414     PL_op = curop;
4415     assert (!(curop->op_flags & OPf_SPECIAL));
4416     assert(curop->op_type == OP_RANGE);
4417     Perl_pp_anonlist(aTHX);
4418     PL_tmps_floor = oldtmps_floor;
4419
4420     OpTYPE_set(o, OP_RV2AV);
4421     o->op_flags &= ~OPf_REF;    /* treat \(1..2) like an ordinary list */
4422     o->op_flags |= OPf_PARENS;  /* and flatten \(1..2,3) */
4423     o->op_opt = 0;              /* needs to be revisited in rpeep() */
4424     av = (AV *)SvREFCNT_inc_NN(*PL_stack_sp--);
4425
4426     /* replace subtree with an OP_CONST */
4427     curop = ((UNOP*)o)->op_first;
4428     op_sibling_splice(o, NULL, -1, newSVOP(OP_CONST, 0, (SV *)av));
4429     op_free(curop);
4430
4431     if (AvFILLp(av) != -1)
4432         for (svp = AvARRAY(av) + AvFILLp(av); svp >= AvARRAY(av); --svp)
4433         {
4434             SvPADTMP_on(*svp);
4435             SvREADONLY_on(*svp);
4436         }
4437     LINKLIST(o);
4438     return list(o);
4439 }
4440
4441 /*
4442 =head1 Optree Manipulation Functions
4443 */
4444
4445 /* List constructors */
4446
4447 /*
4448 =for apidoc Am|OP *|op_append_elem|I32 optype|OP *first|OP *last
4449
4450 Append an item to the list of ops contained directly within a list-type
4451 op, returning the lengthened list.  C<first> is the list-type op,
4452 and C<last> is the op to append to the list.  C<optype> specifies the
4453 intended opcode for the list.  If C<first> is not already a list of the
4454 right type, it will be upgraded into one.  If either C<first> or C<last>
4455 is null, the other is returned unchanged.
4456
4457 =cut
4458 */
4459
4460 OP *
4461 Perl_op_append_elem(pTHX_ I32 type, OP *first, OP *last)
4462 {
4463     if (!first)
4464         return last;
4465
4466     if (!last)
4467         return first;
4468
4469     if (first->op_type != (unsigned)type
4470         || (type == OP_LIST && (first->op_flags & OPf_PARENS)))
4471     {
4472         return newLISTOP(type, 0, first, last);
4473     }
4474
4475     op_sibling_splice(first, ((LISTOP*)first)->op_last, 0, last);
4476     first->op_flags |= OPf_KIDS;
4477     return first;
4478 }
4479
4480 /*
4481 =for apidoc Am|OP *|op_append_list|I32 optype|OP *first|OP *last
4482
4483 Concatenate the lists of ops contained directly within two list-type ops,
4484 returning the combined list.  C<first> and C<last> are the list-type ops
4485 to concatenate.  C<optype> specifies the intended opcode for the list.
4486 If either C<first> or C<last> is not already a list of the right type,
4487 it will be upgraded into one.  If either C<first> or C<last> is null,
4488 the other is returned unchanged.
4489
4490 =cut
4491 */
4492
4493 OP *
4494 Perl_op_append_list(pTHX_ I32 type, OP *first, OP *last)
4495 {
4496     if (!first)
4497         return last;
4498
4499     if (!last)
4500         return first;
4501
4502     if (first->op_type != (unsigned)type)
4503         return op_prepend_elem(type, first, last);
4504
4505     if (last->op_type != (unsigned)type)
4506         return op_append_elem(type, first, last);
4507
4508     OpMORESIB_set(((LISTOP*)first)->op_last, ((LISTOP*)last)->op_first);
4509     ((LISTOP*)first)->op_last = ((LISTOP*)last)->op_last;
4510     OpLASTSIB_set(((LISTOP*)first)->op_last, first);
4511     first->op_flags |= (last->op_flags & OPf_KIDS);
4512
4513     S_op_destroy(aTHX_ last);
4514
4515     return first;
4516 }
4517
4518 /*
4519 =for apidoc Am|OP *|op_prepend_elem|I32 optype|OP *first|OP *last
4520
4521 Prepend an item to the list of ops contained directly within a list-type
4522 op, returning the lengthened list.  C<first> is the op to prepend to the
4523 list, and C<last> is the list-type op.  C<optype> specifies the intended
4524 opcode for the list.  If C<last> is not already a list of the right type,
4525 it will be upgraded into one.  If either C<first> or C<last> is null,
4526 the other is returned unchanged.
4527
4528 =cut
4529 */
4530
4531 OP *
4532 Perl_op_prepend_elem(pTHX_ I32 type, OP *first, OP *last)
4533 {
4534     if (!first)
4535         return last;
4536
4537     if (!last)
4538         return first;
4539
4540     if (last->op_type == (unsigned)type) {
4541         if (type == OP_LIST) {  /* already a PUSHMARK there */
4542             /* insert 'first' after pushmark */
4543             op_sibling_splice(last, cLISTOPx(last)->op_first, 0, first);
4544             if (!(first->op_flags & OPf_PARENS))
4545                 last->op_flags &= ~OPf_PARENS;
4546         }
4547         else
4548             op_sibling_splice(last, NULL, 0, first);
4549         last->op_flags |= OPf_KIDS;
4550         return last;
4551     }
4552
4553     return newLISTOP(type, 0, first, last);
4554 }
4555
4556 /*
4557 =for apidoc Am|OP *|op_convert_list|I32 type|I32 flags|OP *o
4558
4559 Converts C<o> into a list op if it is not one already, and then converts it
4560 into the specified C<type>, calling its check function, allocating a target if
4561 it needs one, and folding constants.
4562
4563 A list-type op is usually constructed one kid at a time via C<newLISTOP>,
4564 C<op_prepend_elem> and C<op_append_elem>.  Then finally it is passed to
4565 C<op_convert_list> to make it the right type.
4566
4567 =cut
4568 */
4569
4570 OP *
4571 Perl_op_convert_list(pTHX_ I32 type, I32 flags, OP *o)
4572 {
4573     dVAR;
4574     if (type < 0) type = -type, flags |= OPf_SPECIAL;
4575     if (!o || o->op_type != OP_LIST)
4576         o = force_list(o, 0);
4577     else
4578     {
4579         o->op_flags &= ~OPf_WANT;
4580         o->op_private &= ~OPpLVAL_INTRO;
4581     }
4582
4583     if (!(PL_opargs[type] & OA_MARK))
4584         op_null(cLISTOPo->op_first);
4585     else {
4586         OP * const kid2 = OpSIBLING(cLISTOPo->op_first);
4587         if (kid2 && kid2->op_type == OP_COREARGS) {
4588             op_null(cLISTOPo->op_first);
4589             kid2->op_private |= OPpCOREARGS_PUSHMARK;
4590         }
4591     }
4592
4593     OpTYPE_set(o, type);
4594     o->op_flags |= flags;
4595     if (flags & OPf_FOLDED)
4596         o->op_folded = 1;
4597
4598     o = CHECKOP(type, o);
4599     if (o->op_type != (unsigned)type)
4600         return o;
4601
4602     return fold_constants(op_integerize(op_std_init(o)));
4603 }
4604
4605 /* Constructors */
4606
4607
4608 /*
4609 =head1 Optree construction
4610
4611 =for apidoc Am|OP *|newNULLLIST
4612
4613 Constructs, checks, and returns a new C<stub> op, which represents an
4614 empty list expression.
4615
4616 =cut
4617 */
4618
4619 OP *
4620 Perl_newNULLLIST(pTHX)
4621 {
4622     return newOP(OP_STUB, 0);
4623 }
4624
4625 /* promote o and any siblings to be a list if its not already; i.e.
4626  *
4627  *  o - A - B
4628  *
4629  * becomes
4630  *
4631  *  list
4632  *    |
4633  *  pushmark - o - A - B
4634  *
4635  * If nullit it true, the list op is nulled.
4636  */
4637
4638 static OP *
4639 S_force_list(pTHX_ OP *o, bool nullit)
4640 {
4641     if (!o || o->op_type != OP_LIST) {
4642         OP *rest = NULL;
4643         if (o) {
4644             /* manually detach any siblings then add them back later */
4645             rest = OpSIBLING(o);
4646             OpLASTSIB_set(o, NULL);
4647         }
4648         o = newLISTOP(OP_LIST, 0, o, NULL);
4649         if (rest)
4650             op_sibling_splice(o, cLISTOPo->op_last, 0, rest);
4651     }
4652     if (nullit)
4653         op_null(o);
4654     return o;
4655 }
4656
4657 /*
4658 =for apidoc Am|OP *|newLISTOP|I32 type|I32 flags|OP *first|OP *last
4659
4660 Constructs, checks, and returns an op of any list type.  C<type> is
4661 the opcode.  C<flags> gives the eight bits of C<op_flags>, except that
4662 C<OPf_KIDS> will be set automatically if required.  C<first> and C<last>
4663 supply up to two ops to be direct children of the list op; they are
4664 consumed by this function and become part of the constructed op tree.
4665
4666 For most list operators, the check function expects all the kid ops to be
4667 present already, so calling C<newLISTOP(OP_JOIN, ...)> (e.g.) is not
4668 appropriate.  What you want to do in that case is create an op of type
4669 C<OP_LIST>, append more children to it, and then call L</op_convert_list>.
4670 See L</op_convert_list> for more information.
4671
4672
4673 =cut
4674 */
4675
4676 OP *
4677 Perl_newLISTOP(pTHX_ I32 type, I32 flags, OP *first, OP *last)
4678 {
4679     dVAR;
4680     LISTOP *listop;
4681
4682     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_LISTOP
4683         || type == OP_CUSTOM);
4684
4685     NewOp(1101, listop, 1, LISTOP);
4686
4687     OpTYPE_set(listop, type);
4688     if (first || last)
4689         flags |= OPf_KIDS;
4690     listop->op_flags = (U8)flags;
4691
4692     if (!last && first)
4693         last = first;
4694     else if (!first && last)
4695         first = last;
4696     else if (first)
4697         OpMORESIB_set(first, last);
4698     listop->op_first = first;
4699     listop->op_last = last;
4700     if (type == OP_LIST) {
4701         OP* const pushop = newOP(OP_PUSHMARK, 0);
4702         OpMORESIB_set(pushop, first);
4703         listop->op_first = pushop;
4704         listop->op_flags |= OPf_KIDS;
4705         if (!last)
4706             listop->op_last = pushop;
4707     }
4708     if (listop->op_last)
4709         OpLASTSIB_set(listop->op_last, (OP*)listop);
4710
4711     return CHECKOP(type, listop);
4712 }
4713
4714 /*
4715 =for apidoc Am|OP *|newOP|I32 type|I32 flags
4716
4717 Constructs, checks, and returns an op of any base type (any type that
4718 has no extra fields).  C<type> is the opcode.  C<flags> gives the
4719 eight bits of C<op_flags>, and, shifted up eight bits, the eight bits
4720 of C<op_private>.
4721
4722 =cut
4723 */
4724
4725 OP *
4726 Perl_newOP(pTHX_ I32 type, I32 flags)
4727 {
4728     dVAR;
4729     OP *o;
4730
4731     if (type == -OP_ENTEREVAL) {
4732         type = OP_ENTEREVAL;
4733         flags |= OPpEVAL_BYTES<<8;
4734     }
4735
4736     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_BASEOP
4737         || (PL_opargs[type] & OA_CLASS_MASK) == OA_BASEOP_OR_UNOP
4738         || (PL_opargs[type] & OA_CLASS_MASK) == OA_FILESTATOP
4739         || (PL_opargs[type] & OA_CLASS_MASK) == OA_LOOPEXOP);
4740
4741     NewOp(1101, o, 1, OP);
4742     OpTYPE_set(o, type);
4743     o->op_flags = (U8)flags;
4744
4745     o->op_next = o;
4746     o->op_private = (U8)(0 | (flags >> 8));
4747     if (PL_opargs[type] & OA_RETSCALAR)
4748         scalar(o);
4749     if (PL_opargs[type] & OA_TARGET)
4750         o->op_targ = pad_alloc(type, SVs_PADTMP);
4751     return CHECKOP(type, o);
4752 }
4753
4754 /*
4755 =for apidoc Am|OP *|newUNOP|I32 type|I32 flags|OP *first
4756
4757 Constructs, checks, and returns an op of any unary type.  C<type> is
4758 the opcode.  C<flags> gives the eight bits of C<op_flags>, except that
4759 C<OPf_KIDS> will be set automatically if required, and, shifted up eight
4760 bits, the eight bits of C<op_private>, except that the bit with value 1
4761 is automatically set.  C<first> supplies an optional op to be the direct
4762 child of the unary op; it is consumed by this function and become part
4763 of the constructed op tree.
4764
4765 =cut
4766 */
4767
4768 OP *
4769 Perl_newUNOP(pTHX_ I32 type, I32 flags, OP *first)
4770 {
4771     dVAR;
4772     UNOP *unop;
4773
4774     if (type == -OP_ENTEREVAL) {
4775         type = OP_ENTEREVAL;
4776         flags |= OPpEVAL_BYTES<<8;
4777     }
4778
4779     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_UNOP
4780         || (PL_opargs[type] & OA_CLASS_MASK) == OA_BASEOP_OR_UNOP
4781         || (PL_opargs[type] & OA_CLASS_MASK) == OA_FILESTATOP
4782         || (PL_opargs[type] & OA_CLASS_MASK) == OA_LOOPEXOP
4783         || type == OP_SASSIGN
4784         || type == OP_ENTERTRY
4785         || type == OP_CUSTOM
4786         || type == OP_NULL );
4787
4788     if (!first)
4789         first = newOP(OP_STUB, 0);
4790     if (PL_opargs[type] & OA_MARK)
4791         first = force_list(first, 1);
4792
4793     NewOp(1101, unop, 1, UNOP);
4794     OpTYPE_set(unop, type);
4795     unop->op_first = first;
4796     unop->op_flags = (U8)(flags | OPf_KIDS);
4797     unop->op_private = (U8)(1 | (flags >> 8));
4798
4799     if (!OpHAS_SIBLING(first)) /* true unless weird syntax error */
4800         OpLASTSIB_set(first, (OP*)unop);
4801
4802     unop = (UNOP*) CHECKOP(type, unop);
4803     if (unop->op_next)
4804         return (OP*)unop;
4805
4806     return fold_constants(op_integerize(op_std_init((OP *) unop)));
4807 }
4808
4809 /*
4810 =for apidoc newUNOP_AUX
4811
4812 Similar to C<newUNOP>, but creates an C<UNOP_AUX> struct instead, with C<op_aux>
4813 initialised to C<aux>
4814
4815 =cut
4816 */
4817
4818 OP *
4819 Perl_newUNOP_AUX(pTHX_ I32 type, I32 flags, OP *first, UNOP_AUX_item *aux)
4820 {
4821     dVAR;
4822     UNOP_AUX *unop;
4823
4824     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_UNOP_AUX
4825         || type == OP_CUSTOM);
4826
4827     NewOp(1101, unop, 1, UNOP_AUX);
4828     unop->op_type = (OPCODE)type;
4829     unop->op_ppaddr = PL_ppaddr[type];
4830     unop->op_first = first;
4831     unop->op_flags = (U8)(flags | (first ? OPf_KIDS : 0));
4832     unop->op_private = (U8)((first ? 1 : 0) | (flags >> 8));
4833     unop->op_aux = aux;
4834
4835     if (first && !OpHAS_SIBLING(first)) /* true unless weird syntax error */
4836         OpLASTSIB_set(first, (OP*)unop);
4837
4838     unop = (UNOP_AUX*) CHECKOP(type, unop);
4839
4840     return op_std_init((OP *) unop);
4841 }
4842
4843 /*
4844 =for apidoc Am|OP *|newMETHOP|I32 type|I32 flags|OP *first
4845
4846 Constructs, checks, and returns an op of method type with a method name
4847 evaluated at runtime.  C<type> is the opcode.  C<flags> gives the eight
4848 bits of C<op_flags>, except that C<OPf_KIDS> will be set automatically,
4849 and, shifted up eight bits, the eight bits of C<op_private>, except that
4850 the bit with value 1 is automatically set.  C<dynamic_meth> supplies an
4851 op which evaluates method name; it is consumed by this function and
4852 become part of the constructed op tree.
4853 Supported optypes: C<OP_METHOD>.
4854
4855 =cut
4856 */
4857
4858 static OP*
4859 S_newMETHOP_internal(pTHX_ I32 type, I32 flags, OP* dynamic_meth, SV* const_meth) {
4860     dVAR;
4861     METHOP *methop;
4862
4863     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_METHOP
4864         || type == OP_CUSTOM);
4865
4866     NewOp(1101, methop, 1, METHOP);
4867     if (dynamic_meth) {
4868         if (PL_opargs[type] & OA_MARK) dynamic_meth = force_list(dynamic_meth, 1);
4869         methop->op_flags = (U8)(flags | OPf_KIDS);
4870         methop->op_u.op_first = dynamic_meth;
4871         methop->op_private = (U8)(1 | (flags >> 8));
4872
4873         if (!OpHAS_SIBLING(dynamic_meth))
4874             OpLASTSIB_set(dynamic_meth, (OP*)methop);
4875     }
4876     else {
4877         assert(const_meth);
4878         methop->op_flags = (U8)(flags & ~OPf_KIDS);
4879         methop->op_u.op_meth_sv = const_meth;
4880         methop->op_private = (U8)(0 | (flags >> 8));
4881         methop->op_next = (OP*)methop;
4882     }
4883
4884 #ifdef USE_ITHREADS
4885     methop->op_rclass_targ = 0;
4886 #else
4887     methop->op_rclass_sv = NULL;
4888 #endif
4889
4890     OpTYPE_set(methop, type);
4891     return CHECKOP(type, methop);
4892 }
4893
4894 OP *
4895 Perl_newMETHOP (pTHX_ I32 type, I32 flags, OP* dynamic_meth) {
4896     PERL_ARGS_ASSERT_NEWMETHOP;
4897     return newMETHOP_internal(type, flags, dynamic_meth, NULL);
4898 }
4899
4900 /*
4901 =for apidoc Am|OP *|newMETHOP_named|I32 type|I32 flags|SV *const_meth
4902
4903 Constructs, checks, and returns an op of method type with a constant
4904 method name.  C<type> is the opcode.  C<flags> gives the eight bits of
4905 C<op_flags>, and, shifted up eight bits, the eight bits of
4906 C<op_private>.  C<const_meth> supplies a constant method name;
4907 it must be a shared COW string.
4908 Supported optypes: C<OP_METHOD_NAMED>.
4909
4910 =cut
4911 */
4912
4913 OP *
4914 Perl_newMETHOP_named (pTHX_ I32 type, I32 flags, SV* const_meth) {
4915     PERL_ARGS_ASSERT_NEWMETHOP_NAMED;
4916     return newMETHOP_internal(type, flags, NULL, const_meth);
4917 }
4918
4919 /*
4920 =for apidoc Am|OP *|newBINOP|I32 type|I32 flags|OP *first|OP *last
4921
4922 Constructs, checks, and returns an op of any binary type.  C<type>
4923 is the opcode.  C<flags> gives the eight bits of C<op_flags>, except
4924 that C<OPf_KIDS> will be set automatically, and, shifted up eight bits,
4925 the eight bits of C<op_private>, except that the bit with value 1 or
4926 2 is automatically set as required.  C<first> and C<last> supply up to
4927 two ops to be the direct children of the binary op; they are consumed
4928 by this function and become part of the constructed op tree.
4929
4930 =cut
4931 */
4932
4933 OP *
4934 Perl_newBINOP(pTHX_ I32 type, I32 flags, OP *first, OP *last)
4935 {
4936     dVAR;
4937     BINOP *binop;
4938
4939     ASSUME((PL_opargs[type] & OA_CLASS_MASK) == OA_BINOP
4940         || type == OP_SASSIGN || type == OP_NULL || type == OP_CUSTOM);
4941
4942     NewOp(1101, binop, 1, BINOP);
4943
4944     if (!first)
4945         first = newOP(OP_NULL, 0);
4946
4947     OpTYPE_set(binop, type);
4948     binop->op_first = first;
4949     binop->op_flags = (U8)(flags | OPf_KIDS);
4950     if (!last) {
4951         last = first;
4952         binop->op_private = (U8)(1 | (flags >> 8));
4953     }
4954     else {
4955         binop->op_private = (U8)(2 | (flags >> 8));
4956         OpMORESIB_set(first, last);
4957     }
4958
4959     if (!OpHAS_SIBLING(last)) /* true unless weird syntax error */
4960         OpLASTSIB_set(last, (OP*)binop);
4961
4962     binop->op_last = OpSIBLING(binop->op_first);
4963     if (binop->op_last)
4964         OpLASTSIB_set(binop->op_last, (OP*)binop);
4965
4966     binop = (BINOP*)CHECKOP(type, binop);
4967     if (binop->op_next || binop->op_type != (OPCODE)type)
4968         return (OP*)binop;
4969
4970     return fold_constants(op_integerize(op_std_init((OP *)binop)));
4971 }
4972
4973 static int uvcompare(const void *a, const void *b)
4974     __attribute__nonnull__(1)
4975     __attribute__nonnull__(2)
4976     __attribute__pure__;
4977 static int uvcompare(const void *a, const void *b)
4978 {
4979     if (*((const UV *)a) < (*(const UV *)b))
4980         return -1;
4981     if (*((const UV *)a) > (*(const UV *)b))
4982         return 1;
4983     if (*((const UV *)a+1) < (*(const UV *)b+1))
4984         return -1;
4985     if (*((const UV *)a+1) > (*(const UV *)b+1))
4986         return 1;
4987     return 0;
4988 }
4989
4990 static OP *
4991 S_pmtrans(pTHX_ OP *o, OP *expr, OP *repl)
4992 {
4993     SV * const tstr = ((SVOP*)expr)->op_sv;
4994     SV * const rstr =
4995                               ((SVOP*)repl)->op_sv;
4996     STRLEN tlen;
4997     STRLEN rlen;
4998     const U8 *t = (U8*)SvPV_const(tstr, tlen);
4999     const U8 *r = (U8*)SvPV_const(rstr, rlen);
5000     I32 i;
5001     I32 j;
5002     I32 grows = 0;
5003     short *tbl;
5004
5005     const I32 complement = o->op_private & OPpTRANS_COMPLEMENT;
5006     const I32 squash     = o->op_private & OPpTRANS_SQUASH;
5007     I32 del              = o->op_private & OPpTRANS_DELETE;
5008     SV* swash;
5009
5010     PERL_ARGS_ASSERT_PMTRANS;
5011
5012     PL_hints |= HINT_BLOCK_SCOPE;
5013
5014     if (SvUTF8(tstr))
5015         o->op_private |= OPpTRANS_FROM_UTF;
5016
5017     if (SvUTF8(rstr))
5018         o->op_private |= OPpTRANS_TO_UTF;
5019
5020     if (o->op_private & (OPpTRANS_FROM_UTF|OPpTRANS_TO_UTF)) {
5021         SV* const listsv = newSVpvs("# comment\n");
5022         SV* transv = NULL;
5023         const U8* tend = t + tlen;
5024         const U8* rend = r + rlen;
5025         STRLEN ulen;
5026         UV tfirst = 1;
5027         UV tlast = 0;
5028         IV tdiff;
5029         STRLEN tcount = 0;
5030         UV rfirst = 1;
5031         UV rlast = 0;
5032         IV rdiff;
5033         STRLEN rcount = 0;
5034         IV diff;
5035         I32 none = 0;
5036         U32 max = 0;
5037         I32 bits;
5038         I32 havefinal = 0;
5039         U32 final = 0;
5040         const I32 from_utf  = o->op_private & OPpTRANS_FROM_UTF;
5041         const I32 to_utf    = o->op_private & OPpTRANS_TO_UTF;
5042         U8* tsave = NULL;
5043         U8* rsave = NULL;
5044         const U32 flags = UTF8_ALLOW_DEFAULT;
5045
5046         if (!from_utf) {
5047             STRLEN len = tlen;
5048             t = tsave = bytes_to_utf8(t, &len);
5049             tend = t + len;
5050         }
5051         if (!to_utf && rlen) {
5052             STRLEN len = rlen;
5053             r = rsave = bytes_to_utf8(r, &len);
5054             rend = r + len;
5055         }
5056
5057 /* There is a snag with this code on EBCDIC: scan_const() in toke.c has
5058  * encoded chars in native encoding which makes ranges in the EBCDIC 0..255
5059  * odd.  */
5060
5061         if (complement) {
5062             U8 tmpbuf[UTF8_MAXBYTES+1];
5063             UV *cp;
5064             UV nextmin = 0;
5065             Newx(cp, 2*tlen, UV);
5066             i = 0;
5067             transv = newSVpvs("");
5068             while (t < tend) {
5069                 cp[2*i] = utf8n_to_uvchr(t, tend-t, &ulen, flags);
5070                 t += ulen;
5071                 if (t < tend && *t == ILLEGAL_UTF8_BYTE) {
5072                     t++;
5073                     cp[2*i+1] = utf8n_to_uvchr(t, tend-t, &ulen, flags);
5074                     t += ulen;
5075                 }
5076                 else {
5077                  cp[2*i+1] = cp[2*i];
5078                 }
5079                 i++;
5080             }
5081             qsort(cp, i, 2*sizeof(UV), uvcompare);
5082             for (j = 0; j < i; j++) {
5083                 UV  val = cp[2*j];
5084                 diff = val - nextmin;
5085                 if (diff > 0) {
5086                     t = uvchr_to_utf8(tmpbuf,nextmin);
5087                     sv_catpvn(transv, (char*)tmpbuf, t - tmpbuf);
5088                     if (diff > 1) {
5089                         U8  range_mark = ILLEGAL_UTF8_BYTE;
5090                         t = uvchr_to_utf8(tmpbuf, val - 1);
5091                         sv_catpvn(transv, (char *)&range_mark, 1);
5092                         sv_catpvn(transv, (char*)tmpbuf, t - tmpbuf);
5093                     }
5094                 }
5095                 val = cp[2*j+1];
5096                 if (val >= nextmin)
5097                     nextmin = val + 1;
5098             }
5099             t = uvchr_to_utf8(tmpbuf,nextmin);
5100             sv_catpvn(transv, (char*)tmpbuf, t - tmpbuf);
5101             {
5102                 U8 range_mark = ILLEGAL_UTF8_BYTE;
5103                 sv_catpvn(transv, (char *)&range_mark, 1);
5104             }
5105             t = uvchr_to_utf8(tmpbuf, 0x7fffffff);
5106             sv_catpvn(transv, (char*)tmpbuf, t - tmpbuf);
5107             t = (const U8*)SvPVX_const(transv);
5108             tlen = SvCUR(transv);
5109             tend = t + tlen;
5110             Safefree(cp);
5111         }
5112         else if (!rlen && !del) {
5113             r = t; rlen = tlen; rend = tend;
5114         }
5115         if (!squash) {
5116                 if ((!rlen && !del) || t == r ||
5117                     (tlen == rlen && memEQ((char *)t, (char *)r, tlen)))
5118                 {
5119                     o->op_private |= OPpTRANS_IDENTICAL;
5120                 }
5121         }
5122
5123         while (t < tend || tfirst <= tlast) {
5124             /* see if we need more "t" chars */
5125             if (tfirst > tlast) {
5126                 tfirst = (I32)utf8n_to_uvchr(t, tend - t, &ulen, flags);
5127                 t += ulen;
5128                 if (t < tend && *t == ILLEGAL_UTF8_BYTE) {      /* illegal utf8 val indicates range */
5129                     t++;
5130                     tlast = (I32)utf8n_to_uvchr(t, tend - t, &ulen, flags);
5131                     t += ulen;
5132                 }
5133                 else
5134                     tlast = tfirst;
5135             }
5136
5137             /* now see if we need more "r" chars */
5138             if (rfirst > rlast) {
5139                 if (r < rend) {
5140                     rfirst = (I32)utf8n_to_uvchr(r, rend - r, &ulen, flags);
5141                     r += ulen;
5142                     if (r < rend && *r == ILLEGAL_UTF8_BYTE) {  /* illegal utf8 val indicates range */
5143                         r++;
5144                         rlast = (I32)utf8n_to_uvchr(r, rend - r, &ulen, flags);
5145                         r += ulen;
5146                     }
5147                     else
5148                         rlast = rfirst;
5149                 }
5150                 else {
5151                     if (!havefinal++)
5152                         final = rlast;
5153                     rfirst = rlast = 0xffffffff;
5154                 }
5155             }
5156
5157             /* now see which range will peter out first, if either. */
5158             tdiff = tlast - tfirst;
5159             rdiff = rlast - rfirst;
5160             tcount += tdiff + 1;
5161             rcount += rdiff + 1;
5162
5163             if (tdiff <= rdiff)
5164                 diff = tdiff;
5165             else
5166                 diff = rdiff;
5167
5168             if (rfirst == 0xffffffff) {
5169                 diff = tdiff;   /* oops, pretend rdiff is infinite */
5170                 if (diff > 0)
5171                     Perl_sv_catpvf(aTHX_ listsv, "%04lx\t%04lx\tXXXX\n",
5172                                    (long)tfirst, (long)tlast);
5173                 else
5174                     Perl_sv_catpvf(aTHX_ listsv, "%04lx\t\tXXXX\n", (long)tfirst);
5175             }
5176             else {
5177                 if (diff > 0)
5178                     Perl_sv_catpvf(aTHX_ listsv, "%04lx\t%04lx\t%04lx\n",
5179                                    (long)tfirst, (long)(tfirst + diff),
5180                                    (long)rfirst);
5181                 else
5182                     Perl_sv_catpvf(aTHX_ listsv, "%04lx\t\t%04lx\n",
5183                                    (long)tfirst, (long)rfirst);
5184
5185                 if (rfirst + diff > max)
5186                     max = rfirst + diff;
5187                 if (!grows)
5188                     grows = (tfirst < rfirst &&
5189                              UVCHR_SKIP(tfirst) < UVCHR_SKIP(rfirst + diff));
5190                 rfirst += diff + 1;
5191             }
5192             tfirst += diff + 1;
5193         }
5194
5195         none = ++max;
5196         if (del)
5197             del = ++max;
5198
5199         if (max > 0xffff)
5200             bits = 32;
5201         else if (max > 0xff)
5202             bits = 16;
5203         else
5204             bits = 8;
5205
5206         swash = MUTABLE_SV(swash_init("utf8", "", listsv, bits, none));
5207 #ifdef USE_ITHREADS
5208         cPADOPo->op_padix = pad_alloc(OP_TRANS, SVf_READONLY);
5209         SvREFCNT_dec(PAD_SVl(cPADOPo->op_padix));
5210         PAD_SETSV(cPADOPo->op_padix, swash);
5211         SvPADTMP_on(swash);
5212         SvREADONLY_on(swash);
5213 #else
5214         cSVOPo->op_sv = swash;
5215 #endif
5216         SvREFCNT_dec(listsv);
5217         SvREFCNT_dec(transv);
5218
5219         if (!del && havefinal && rlen)
5220             (void)hv_store(MUTABLE_HV(SvRV(swash)), "FINAL", 5,
5221                            newSVuv((UV)final), 0);
5222
5223         Safefree(tsave);
5224         Safefree(rsave);
5225
5226         tlen = tcount;
5227         rlen = rcount;
5228         if (r < rend)
5229             rlen++;
5230         else if (rlast == 0xffffffff)
5231             rlen = 0;
5232
5233         goto warnins;
5234     }
5235
5236     tbl = (short*)PerlMemShared_calloc(
5237         (o->op_private & OPpTRANS_COMPLEMENT) &&
5238             !(o->op_private & OPpTRANS_DELETE) ? 258 : 256,
5239         sizeof(short));
5240     cPVOPo->op_pv = (char*)tbl;
5241     if (complement) {
5242         for (i = 0; i < (I32)tlen; i++)
5243             tbl[t[i]] = -1;
5244         for (i = 0, j = 0; i < 256; i++) {
5245             if (!tbl[i]) {
5246                 if (j >= (I32)rlen) {
5247                     if (del)
5248                         tbl[i] = -2;
5249                     else if (rlen)
5250                         tbl[i] = r[j-1];
5251                     else
5252                         tbl[i] = (short)i;
5253                 }
5254                 else {
5255                     if (i < 128 && r[j] >= 128)
5256                         grows = 1;
5257                     tbl[i] = r[j++];
5258                 }
5259             }
5260         }
5261         if (!del) {
5262             if (!rlen) {
5263                 j = rlen;
5264                 if (!squash)
5265                     o->op_private |= OPpTRANS_IDENTICAL;
5266             }
5267             else if (j >= (I32)rlen)
5268                 j = rlen - 1;
5269             else {
5270                 tbl = 
5271                     (short *)
5272                     PerlMemShared_realloc(tbl,
5273                                           (0x101+rlen-j) * sizeof(short));
5274                 cPVOPo->op_pv = (char*)tbl;
5275             }
5276             tbl[0x100] = (short)(rlen - j);
5277             for (i=0; i < (I32)rlen - j; i++)
5278                 tbl[0x101+i] = r[j+i];
5279         }
5280     }
5281     else {
5282         if (!rlen && !del) {
5283             r = t; rlen = tlen;
5284             if (!squash)
5285                 o->op_private |= OPpTRANS_IDENTICAL;
5286         }
5287         else if (!squash && rlen == tlen && memEQ((char*)t, (char*)r, tlen)) {
5288             o->op_private |= OPpTRANS_IDENTICAL;
5289         }
5290         for (i = 0; i < 256; i++)
5291             tbl[i] = -1;
5292         for (i = 0, j = 0; i < (I32)tlen; i++,j++) {
5293             if (j >= (I32)rlen) {
5294                 if (del) {
5295                     if (tbl[t[i]] == -1)
5296                         tbl[t[i]] = -2;
5297                     continue;
5298                 }
5299                 --j;
5300             }
5301             if (tbl[t[i]] == -1) {
5302                 if (t[i] < 128 && r[j] >= 128)
5303                     grows = 1;
5304                 tbl[t[i]] = r[j];
5305             }
5306         }
5307     }
5308
5309   warnins:
5310     if(del && rlen == tlen) {
5311         Perl_ck_warner(aTHX_ packWARN(WARN_MISC), "Useless use of /d modifier in transliteration operator"); 
5312     } else if(rlen > tlen && !complement) {
5313         Perl_ck_warner(aTHX_ packWARN(WARN_MISC), "Replacement list is longer than search list");
5314     }
5315
5316     if (grows)
5317         o->op_private |= OPpTRANS_GROWS;
5318     op_free(expr);
5319     op_free(repl);
5320
5321     return o;
5322 }
5323
5324 /*
5325 =for apidoc Am|OP *|newPMOP|I32 type|I32 flags
5326
5327 Constructs, checks, and returns an op of any pattern matching type.
5328 C<type> is the opcode.  C<flags> gives the eight bits of C<op_flags>
5329 and, shifted up eight bits, the eight bits of C<op_private>.
5330
5331 =cut
5332 */
5333
5334 OP *
5335 Perl_newPMOP(pTHX_ I32 type, I32 flags)
5336 {
5337     dVAR;
5338     PMOP *pmop;
5339
5340     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_PMOP
5341         || type == OP_CUSTOM);
5342
5343     NewOp(1101, pmop, 1, PMOP);
5344     OpTYPE_set(pmop, type);
5345     pmop->op_flags = (U8)flags;
5346     pmop->op_private = (U8)(0 | (flags >> 8));
5347     if (PL_opargs[type] & OA_RETSCALAR)
5348         scalar((OP *)pmop);
5349
5350     if (PL_hints & HINT_RE_TAINT)
5351         pmop->op_pmflags |= PMf_RETAINT;
5352 #ifdef USE_LOCALE_CTYPE
5353     if (IN_LC_COMPILETIME(LC_CTYPE)) {
5354         set_regex_charset(&(pmop->op_pmflags), REGEX_LOCALE_CHARSET);
5355     }
5356     else
5357 #endif
5358          if (IN_UNI_8_BIT) {
5359         set_regex_charset(&(pmop->op_pmflags), REGEX_UNICODE_CHARSET);
5360     }
5361     if (PL_hints & HINT_RE_FLAGS) {
5362         SV *reflags = Perl_refcounted_he_fetch_pvn(aTHX_
5363          PL_compiling.cop_hints_hash, STR_WITH_LEN("reflags"), 0, 0
5364         );
5365         if (reflags && SvOK(reflags)) pmop->op_pmflags |= SvIV(reflags);
5366         reflags = Perl_refcounted_he_fetch_pvn(aTHX_
5367          PL_compiling.cop_hints_hash, STR_WITH_LEN("reflags_charset"), 0, 0
5368         );
5369         if (reflags && SvOK(reflags)) {
5370             set_regex_charset(&(pmop->op_pmflags), (regex_charset)SvIV(reflags));
5371         }
5372     }
5373
5374
5375 #ifdef USE_ITHREADS
5376     assert(SvPOK(PL_regex_pad[0]));
5377     if (SvCUR(PL_regex_pad[0])) {
5378         /* Pop off the "packed" IV from the end.  */
5379         SV *const repointer_list = PL_regex_pad[0];
5380         const char *p = SvEND(repointer_list) - sizeof(IV);
5381         const IV offset = *((IV*)p);
5382
5383         assert(SvCUR(repointer_list) % sizeof(IV) == 0);
5384
5385         SvEND_set(repointer_list, p);
5386
5387         pmop->op_pmoffset = offset;
5388         /* This slot should be free, so assert this:  */
5389         assert(PL_regex_pad[offset] == &PL_sv_undef);
5390     } else {
5391         SV * const repointer = &PL_sv_undef;
5392         av_push(PL_regex_padav, repointer);
5393         pmop->op_pmoffset = av_tindex(PL_regex_padav);
5394         PL_regex_pad = AvARRAY(PL_regex_padav);
5395     }
5396 #endif
5397
5398     return CHECKOP(type, pmop);
5399 }
5400
5401 static void
5402 S_set_haseval(pTHX)
5403 {
5404     PADOFFSET i = 1;
5405     PL_cv_has_eval = 1;
5406     /* Any pad names in scope are potentially lvalues.  */
5407     for (; i < PadnamelistMAXNAMED(PL_comppad_name); i++) {
5408         PADNAME *pn = PAD_COMPNAME_SV(i);
5409         if (!pn || !PadnameLEN(pn))
5410             continue;
5411         if (PadnameOUTER(pn) || PadnameIN_SCOPE(pn, PL_cop_seqmax))
5412             S_mark_padname_lvalue(aTHX_ pn);
5413     }
5414 }
5415
5416 /* Given some sort of match op o, and an expression expr containing a
5417  * pattern, either compile expr into a regex and attach it to o (if it's
5418  * constant), or convert expr into a runtime regcomp op sequence (if it's
5419  * not)
5420  *
5421  * isreg indicates that the pattern is part of a regex construct, eg
5422  * $x =~ /pattern/ or split /pattern/, as opposed to $x =~ $pattern or
5423  * split "pattern", which aren't. In the former case, expr will be a list
5424  * if the pattern contains more than one term (eg /a$b/).
5425  *
5426  * When the pattern has been compiled within a new anon CV (for
5427  * qr/(?{...})/ ), then floor indicates the savestack level just before
5428  * the new sub was created
5429  */
5430
5431 OP *
5432 Perl_pmruntime(pTHX_ OP *o, OP *expr, OP *repl, bool isreg, I32 floor)
5433 {
5434     PMOP *pm;
5435     LOGOP *rcop;
5436     I32 repl_has_vars = 0;
5437     bool is_trans = (o->op_type == OP_TRANS || o->op_type == OP_TRANSR);
5438     bool is_compiletime;
5439     bool has_code;
5440
5441     PERL_ARGS_ASSERT_PMRUNTIME;
5442
5443     if (is_trans) {
5444         return pmtrans(o, expr, repl);
5445     }
5446
5447     /* find whether we have any runtime or code elements;
5448      * at the same time, temporarily set the op_next of each DO block;
5449      * then when we LINKLIST, this will cause the DO blocks to be excluded
5450      * from the op_next chain (and from having LINKLIST recursively
5451      * applied to them). We fix up the DOs specially later */
5452
5453     is_compiletime = 1;
5454     has_code = 0;
5455     if (expr->op_type == OP_LIST) {
5456         OP *o;
5457         for (o = cLISTOPx(expr)->op_first; o; o = OpSIBLING(o)) {
5458             if (o->op_type == OP_NULL && (o->op_flags & OPf_SPECIAL)) {
5459                 has_code = 1;
5460                 assert(!o->op_next);
5461                 if (UNLIKELY(!OpHAS_SIBLING(o))) {
5462                     assert(PL_parser && PL_parser->error_count);
5463                     /* This can happen with qr/ (?{(^{})/.  Just fake up
5464                        the op we were expecting to see, to avoid crashing
5465                        elsewhere.  */
5466                     op_sibling_splice(expr, o, 0,
5467                                       newSVOP(OP_CONST, 0, &PL_sv_no));
5468                 }
5469                 o->op_next = OpSIBLING(o);
5470             }
5471             else if (o->op_type != OP_CONST && o->op_type != OP_PUSHMARK)
5472                 is_compiletime = 0;
5473         }
5474     }
5475     else if (expr->op_type != OP_CONST)
5476         is_compiletime = 0;
5477
5478     LINKLIST(expr);
5479
5480     /* fix up DO blocks; treat each one as a separate little sub;
5481      * also, mark any arrays as LIST/REF */
5482
5483     if (expr->op_type == OP_LIST) {
5484         OP *o;
5485         for (o = cLISTOPx(expr)->op_first; o; o = OpSIBLING(o)) {
5486
5487             if (o->op_type == OP_PADAV || o->op_type == OP_RV2AV) {
5488                 assert( !(o->op_flags  & OPf_WANT));
5489                 /* push the array rather than its contents. The regex
5490                  * engine will retrieve and join the elements later */
5491                 o->op_flags |= (OPf_WANT_LIST | OPf_REF);
5492                 continue;
5493             }
5494
5495             if (!(o->op_type == OP_NULL && (o->op_flags & OPf_SPECIAL)))
5496                 continue;
5497             o->op_next = NULL; /* undo temporary hack from above */
5498             scalar(o);
5499             LINKLIST(o);
5500             if (cLISTOPo->op_first->op_type == OP_LEAVE) {
5501                 LISTOP *leaveop = cLISTOPx(cLISTOPo->op_first);
5502                 /* skip ENTER */
5503                 assert(leaveop->op_first->op_type == OP_ENTER);
5504                 assert(OpHAS_SIBLING(leaveop->op_first));
5505                 o->op_next = OpSIBLING(leaveop->op_first);
5506                 /* skip leave */
5507                 assert(leaveop->op_flags & OPf_KIDS);
5508                 assert(leaveop->op_last->op_next == (OP*)leaveop);
5509                 leaveop->op_next = NULL; /* stop on last op */
5510                 op_null((OP*)leaveop);
5511             }
5512             else {
5513                 /* skip SCOPE */
5514                 OP *scope = cLISTOPo->op_first;
5515                 assert(scope->op_type == OP_SCOPE);
5516                 assert(scope->op_flags & OPf_KIDS);
5517                 scope->op_next = NULL; /* stop on last op */
5518                 op_null(scope);
5519             }
5520             /* have to peep the DOs individually as we've removed it from
5521              * the op_next chain */
5522             CALL_PEEP(o);
5523             S_prune_chain_head(&(o->op_next));
5524             if (is_compiletime)
5525                 /* runtime finalizes as part of finalizing whole tree */
5526                 finalize_optree(o);
5527         }
5528     }
5529     else if (expr->op_type == OP_PADAV || expr->op_type == OP_RV2AV) {
5530         assert( !(expr->op_flags  & OPf_WANT));
5531         /* push the array rather than its contents. The regex
5532          * engine will retrieve and join the elements later */
5533         expr->op_flags |= (OPf_WANT_LIST | OPf_REF);
5534     }
5535
5536     PL_hints |= HINT_BLOCK_SCOPE;
5537     pm = (PMOP*)o;
5538     assert(floor==0 || (pm->op_pmflags & PMf_HAS_CV));
5539
5540     if (is_compiletime) {
5541         U32 rx_flags = pm->op_pmflags & RXf_PMf_COMPILETIME;
5542         regexp_engine const *eng = current_re_engine();
5543
5544         if (o->op_flags & OPf_SPECIAL)
5545             rx_flags |= RXf_SPLIT;
5546
5547         if (!has_code || !eng->op_comp) {
5548             /* compile-time simple constant pattern */
5549
5550             if ((pm->op_pmflags & PMf_HAS_CV) && !has_code) {
5551                 /* whoops! we guessed that a qr// had a code block, but we
5552                  * were wrong (e.g. /[(?{}]/ ). Throw away the PL_compcv
5553                  * that isn't required now. Note that we have to be pretty
5554                  * confident that nothing used that CV's pad while the
5555                  * regex was parsed, except maybe op targets for \Q etc.
5556                  * If there were any op targets, though, they should have
5557                  * been stolen by constant folding.
5558                  */
5559 #ifdef DEBUGGING
5560                 SSize_t i = 0;
5561                 assert(PadnamelistMAXNAMED(PL_comppad_name) == 0);
5562                 while (++i <= AvFILLp(PL_comppad)) {
5563                     assert(!PL_curpad[i]);
5564                 }
5565 #endif
5566                 /* But we know that one op is using this CV's slab. */
5567                 cv_forget_slab(PL_compcv);
5568                 LEAVE_SCOPE(floor);
5569                 pm->op_pmflags &= ~PMf_HAS_CV;
5570             }
5571
5572             PM_SETRE(pm,
5573                 eng->op_comp
5574                     ? eng->op_comp(aTHX_ NULL, 0, expr, eng, NULL, NULL,
5575                                         rx_flags, pm->op_pmflags)
5576                     : Perl_re_op_compile(aTHX_ NULL, 0, expr, eng, NULL, NULL,
5577                                         rx_flags, pm->op_pmflags)
5578             );
5579             op_free(expr);
5580         }
5581         else {
5582             /* compile-time pattern that includes literal code blocks */
5583             REGEXP* re = eng->op_comp(aTHX_ NULL, 0, expr, eng, NULL, NULL,
5584                         rx_flags,
5585                         (pm->op_pmflags |
5586                             ((PL_hints & HINT_RE_EVAL) ? PMf_USE_RE_EVAL : 0))
5587                     );
5588             PM_SETRE(pm, re);
5589             if (pm->op_pmflags & PMf_HAS_CV) {
5590                 CV *cv;
5591                 /* this QR op (and the anon sub we embed it in) is never
5592                  * actually executed. It's just a placeholder where we can
5593                  * squirrel away expr in op_code_list without the peephole
5594                  * optimiser etc processing it for a second time */
5595                 OP *qr = newPMOP(OP_QR, 0);
5596                 ((PMOP*)qr)->op_code_list = expr;
5597
5598                 /* handle the implicit sub{} wrapped round the qr/(?{..})/ */
5599                 SvREFCNT_inc_simple_void(PL_compcv);
5600                 cv = newATTRSUB(floor, 0, NULL, NULL, qr);
5601                 ReANY(re)->qr_anoncv = cv;
5602
5603                 /* attach the anon CV to the pad so that
5604                  * pad_fixup_inner_anons() can find it */
5605                 (void)pad_add_anon(cv, o->op_type);
5606                 SvREFCNT_inc_simple_void(cv);
5607             }
5608             else {
5609                 pm->op_code_list = expr;
5610             }
5611         }
5612     }
5613     else {
5614         /* runtime pattern: build chain of regcomp etc ops */
5615         bool reglist;
5616         PADOFFSET cv_targ = 0;
5617
5618         reglist = isreg && expr->op_type == OP_LIST;
5619         if (reglist)
5620             op_null(expr);
5621
5622         if (has_code) {
5623             pm->op_code_list = expr;
5624             /* don't free op_code_list; its ops are embedded elsewhere too */
5625             pm->op_pmflags |= PMf_CODELIST_PRIVATE;
5626         }
5627
5628         if (o->op_flags & OPf_SPECIAL)
5629             pm->op_pmflags |= PMf_SPLIT;
5630
5631         /* the OP_REGCMAYBE is a placeholder in the non-threaded case
5632          * to allow its op_next to be pointed past the regcomp and
5633          * preceding stacking ops;
5634          * OP_REGCRESET is there to reset taint before executing the
5635          * stacking ops */
5636         if (pm->op_pmflags & PMf_KEEP || TAINTING_get)
5637             expr = newUNOP((TAINTING_get ? OP_REGCRESET : OP_REGCMAYBE),0,expr);
5638
5639         if (pm->op_pmflags & PMf_HAS_CV) {
5640             /* we have a runtime qr with literal code. This means
5641              * that the qr// has been wrapped in a new CV, which
5642              * means that runtime consts, vars etc will have been compiled
5643              * against a new pad. So... we need to execute those ops
5644              * within the environment of the new CV. So wrap them in a call
5645              * to a new anon sub. i.e. for
5646              *
5647              *     qr/a$b(?{...})/,
5648              *
5649              * we build an anon sub that looks like
5650              *
5651              *     sub { "a", $b, '(?{...})' }
5652              *
5653              * and call it, passing the returned list to regcomp.
5654              * Or to put it another way, the list of ops that get executed
5655              * are:
5656              *
5657              *     normal              PMf_HAS_CV
5658              *     ------              -------------------
5659              *                         pushmark (for regcomp)
5660              *                         pushmark (for entersub)
5661              *                         anoncode
5662              *                         srefgen
5663              *                         entersub
5664              *     regcreset                  regcreset
5665              *     pushmark                   pushmark
5666              *     const("a")                 const("a")
5667              *     gvsv(b)                    gvsv(b)
5668              *     const("(?{...})")          const("(?{...})")
5669              *                                leavesub
5670              *     regcomp             regcomp
5671              */
5672
5673             SvREFCNT_inc_simple_void(PL_compcv);
5674             CvLVALUE_on(PL_compcv);
5675             /* these lines are just an unrolled newANONATTRSUB */
5676             expr = newSVOP(OP_ANONCODE, 0,
5677                     MUTABLE_SV(newATTRSUB(floor, 0, NULL, NULL, expr)));
5678             cv_targ = expr->op_targ;
5679             expr = newUNOP(OP_REFGEN, 0, expr);
5680
5681             expr = list(force_list(newUNOP(OP_ENTERSUB, 0, scalar(expr)), 1));
5682         }
5683
5684         rcop = S_alloc_LOGOP(aTHX_ OP_REGCOMP, scalar(expr), o);
5685         rcop->op_flags |=  ((PL_hints & HINT_RE_EVAL) ? OPf_SPECIAL : 0)
5686                            | (reglist ? OPf_STACKED : 0);
5687         rcop->op_targ = cv_targ;
5688
5689         /* /$x/ may cause an eval, since $x might be qr/(?{..})/  */
5690         if (PL_hints & HINT_RE_EVAL)
5691             S_set_haseval(aTHX);
5692
5693         /* establish postfix order */
5694         if (expr->op_type == OP_REGCRESET || expr->op_type == OP_REGCMAYBE) {
5695             LINKLIST(expr);
5696             rcop->op_next = expr;
5697             ((UNOP*)expr)->op_first->op_next = (OP*)rcop;
5698         }
5699         else {
5700             rcop->op_next = LINKLIST(expr);
5701             expr->op_next = (OP*)rcop;
5702         }
5703
5704         op_prepend_elem(o->op_type, scalar((OP*)rcop), o);
5705     }
5706
5707     if (repl) {
5708         OP *curop = repl;
5709         bool konst;
5710         /* If we are looking at s//.../e with a single statement, get past
5711            the implicit do{}. */
5712         if (curop->op_type == OP_NULL && curop->op_flags & OPf_KIDS
5713              && cUNOPx(curop)->op_first->op_type == OP_SCOPE
5714              && cUNOPx(curop)->op_first->op_flags & OPf_KIDS)
5715          {
5716             OP *sib;
5717             OP *kid = cUNOPx(cUNOPx(curop)->op_first)->op_first;
5718             if (kid->op_type == OP_NULL && (sib = OpSIBLING(kid))
5719              && !OpHAS_SIBLING(sib))
5720                 curop = sib;
5721         }
5722         if (curop->op_type == OP_CONST)
5723             konst = TRUE;
5724         else if (( (curop->op_type == OP_RV2SV ||
5725                     curop->op_type == OP_RV2AV ||
5726                     curop->op_type == OP_RV2HV ||
5727                     curop->op_type == OP_RV2GV)
5728                    && cUNOPx(curop)->op_first
5729                    && cUNOPx(curop)->op_first->op_type == OP_GV )
5730                 || curop->op_type == OP_PADSV
5731                 || curop->op_type == OP_PADAV
5732                 || curop->op_type == OP_PADHV
5733                 || curop->op_type == OP_PADANY) {
5734             repl_has_vars = 1;
5735             konst = TRUE;
5736         }
5737         else konst = FALSE;
5738         if (konst
5739             && !(repl_has_vars
5740                  && (!PM_GETRE(pm)
5741                      || !RX_PRELEN(PM_GETRE(pm))
5742                      || RX_EXTFLAGS(PM_GETRE(pm)) & RXf_EVAL_SEEN)))
5743         {
5744             pm->op_pmflags |= PMf_CONST;        /* const for long enough */
5745             op_prepend_elem(o->op_type, scalar(repl), o);
5746         }
5747         else {
5748             rcop = S_alloc_LOGOP(aTHX_ OP_SUBSTCONT, scalar(repl), o);
5749             rcop->op_private = 1;
5750
5751             /* establish postfix order */
5752             rcop->op_next = LINKLIST(repl);
5753             repl->op_next = (OP*)rcop;
5754
5755             pm->op_pmreplrootu.op_pmreplroot = scalar((OP*)rcop);
5756             assert(!(pm->op_pmflags & PMf_ONCE));
5757             pm->op_pmstashstartu.op_pmreplstart = LINKLIST(rcop);
5758             rcop->op_next = 0;
5759         }
5760     }
5761
5762     return (OP*)pm;
5763 }
5764
5765 /*
5766 =for apidoc Am|OP *|newSVOP|I32 type|I32 flags|SV *sv
5767
5768 Constructs, checks, and returns an op of any type that involves an
5769 embedded SV.  C<type> is the opcode.  C<flags> gives the eight bits
5770 of C<op_flags>.  C<sv> gives the SV to embed in the op; this function
5771 takes ownership of one reference to it.
5772
5773 =cut
5774 */
5775
5776 OP *
5777 Perl_newSVOP(pTHX_ I32 type, I32 flags, SV *sv)
5778 {
5779     dVAR;
5780     SVOP *svop;
5781
5782     PERL_ARGS_ASSERT_NEWSVOP;
5783
5784     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_SVOP
5785         || (PL_opargs[type] & OA_CLASS_MASK) == OA_PVOP_OR_SVOP
5786         || (PL_opargs[type] & OA_CLASS_MASK) == OA_FILESTATOP
5787         || type == OP_CUSTOM);
5788
5789     NewOp(1101, svop, 1, SVOP);
5790     OpTYPE_set(svop, type);
5791     svop->op_sv = sv;
5792     svop->op_next = (OP*)svop;
5793     svop->op_flags = (U8)flags;
5794     svop->op_private = (U8)(0 | (flags >> 8));
5795     if (PL_opargs[type] & OA_RETSCALAR)
5796         scalar((OP*)svop);
5797     if (PL_opargs[type] & OA_TARGET)
5798         svop->op_targ = pad_alloc(type, SVs_PADTMP);
5799     return CHECKOP(type, svop);
5800 }
5801
5802 /*
5803 =for apidoc Am|OP *|newDEFSVOP|
5804
5805 Constructs and returns an op to access C<$_>.
5806
5807 =cut
5808 */
5809
5810 OP *
5811 Perl_newDEFSVOP(pTHX)
5812 {
5813         return newSVREF(newGVOP(OP_GV, 0, PL_defgv));
5814 }
5815
5816 #ifdef USE_ITHREADS
5817
5818 /*
5819 =for apidoc Am|OP *|newPADOP|I32 type|I32 flags|SV *sv
5820
5821 Constructs, checks, and returns an op of any type that involves a
5822 reference to a pad element.  C<type> is the opcode.  C<flags> gives the
5823 eight bits of C<op_flags>.  A pad slot is automatically allocated, and
5824 is populated with C<sv>; this function takes ownership of one reference
5825 to it.
5826
5827 This function only exists if Perl has been compiled to use ithreads.
5828
5829 =cut
5830 */
5831
5832 OP *
5833 Perl_newPADOP(pTHX_ I32 type, I32 flags, SV *sv)
5834 {
5835     dVAR;
5836     PADOP *padop;
5837
5838     PERL_ARGS_ASSERT_NEWPADOP;
5839
5840     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_SVOP
5841         || (PL_opargs[type] & OA_CLASS_MASK) == OA_PVOP_OR_SVOP
5842         || (PL_opargs[type] & OA_CLASS_MASK) == OA_FILESTATOP
5843         || type == OP_CUSTOM);
5844
5845     NewOp(1101, padop, 1, PADOP);
5846     OpTYPE_set(padop, type);
5847     padop->op_padix =
5848         pad_alloc(type, isGV(sv) ? SVf_READONLY : SVs_PADTMP);
5849     SvREFCNT_dec(PAD_SVl(padop->op_padix));
5850     PAD_SETSV(padop->op_padix, sv);
5851     assert(sv);
5852     padop->op_next = (OP*)padop;
5853     padop->op_flags = (U8)flags;
5854     if (PL_opargs[type] & OA_RETSCALAR)
5855         scalar((OP*)padop);
5856     if (PL_opargs[type] & OA_TARGET)
5857         padop->op_targ = pad_alloc(type, SVs_PADTMP);
5858     return CHECKOP(type, padop);
5859 }
5860
5861 #endif /* USE_ITHREADS */
5862
5863 /*
5864 =for apidoc Am|OP *|newGVOP|I32 type|I32 flags|GV *gv
5865
5866 Constructs, checks, and returns an op of any type that involves an
5867 embedded reference to a GV.  C<type> is the opcode.  C<flags> gives the
5868 eight bits of C<op_flags>.  C<gv> identifies the GV that the op should
5869 reference; calling this function does not transfer ownership of any
5870 reference to it.
5871
5872 =cut
5873 */
5874
5875 OP *
5876 Perl_newGVOP(pTHX_ I32 type, I32 flags, GV *gv)
5877 {
5878     PERL_ARGS_ASSERT_NEWGVOP;
5879
5880 #ifdef USE_ITHREADS
5881     return newPADOP(type, flags, SvREFCNT_inc_simple_NN(gv));
5882 #else
5883     return newSVOP(type, flags, SvREFCNT_inc_simple_NN(gv));
5884 #endif
5885 }
5886
5887 /*
5888 =for apidoc Am|OP *|newPVOP|I32 type|I32 flags|char *pv
5889
5890 Constructs, checks, and returns an op of any type that involves an
5891 embedded C-level pointer (PV).  C<type> is the opcode.  C<flags> gives
5892 the eight bits of C<op_flags>.  C<pv> supplies the C-level pointer, which
5893 must have been allocated using C<PerlMemShared_malloc>; the memory will
5894 be freed when the op is destroyed.
5895
5896 =cut
5897 */
5898
5899 OP *
5900 Perl_newPVOP(pTHX_ I32 type, I32 flags, char *pv)
5901 {
5902     dVAR;
5903     const bool utf8 = cBOOL(flags & SVf_UTF8);
5904     PVOP *pvop;
5905
5906     flags &= ~SVf_UTF8;
5907
5908     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_PVOP_OR_SVOP
5909         || type == OP_RUNCV || type == OP_CUSTOM
5910         || (PL_opargs[type] & OA_CLASS_MASK) == OA_LOOPEXOP);
5911
5912     NewOp(1101, pvop, 1, PVOP);
5913     OpTYPE_set(pvop, type);
5914     pvop->op_pv = pv;
5915     pvop->op_next = (OP*)pvop;
5916     pvop->op_flags = (U8)flags;
5917     pvop->op_private = utf8 ? OPpPV_IS_UTF8 : 0;
5918     if (PL_opargs[type] & OA_RETSCALAR)
5919         scalar((OP*)pvop);
5920     if (PL_opargs[type] & OA_TARGET)
5921         pvop->op_targ = pad_alloc(type, SVs_PADTMP);
5922     return CHECKOP(type, pvop);
5923 }
5924
5925 void
5926 Perl_package(pTHX_ OP *o)
5927 {
5928     SV *const sv = cSVOPo->op_sv;
5929
5930     PERL_ARGS_ASSERT_PACKAGE;
5931
5932     SAVEGENERICSV(PL_curstash);
5933     save_item(PL_curstname);
5934
5935     PL_curstash = (HV *)SvREFCNT_inc(gv_stashsv(sv, GV_ADD));
5936
5937     sv_setsv(PL_curstname, sv);
5938
5939     PL_hints |= HINT_BLOCK_SCOPE;
5940     PL_parser->copline = NOLINE;
5941
5942     op_free(o);
5943 }
5944
5945 void
5946 Perl_package_version( pTHX_ OP *v )
5947 {
5948     U32 savehints = PL_hints;
5949     PERL_ARGS_ASSERT_PACKAGE_VERSION;
5950     PL_hints &= ~HINT_STRICT_VARS;
5951     sv_setsv( GvSV(gv_fetchpvs("VERSION", GV_ADDMULTI, SVt_PV)), cSVOPx(v)->op_sv );
5952     PL_hints = savehints;
5953     op_free(v);
5954 }
5955
5956 void
5957 Perl_utilize(pTHX_ int aver, I32 floor, OP *version, OP *idop, OP *arg)
5958 {
5959     OP *pack;
5960     OP *imop;
5961     OP *veop;
5962     SV *use_version = NULL;
5963
5964     PERL_ARGS_ASSERT_UTILIZE;
5965
5966     if (idop->op_type != OP_CONST)
5967         Perl_croak(aTHX_ "Module name must be constant");
5968
5969     veop = NULL;
5970
5971     if (version) {
5972         SV * const vesv = ((SVOP*)version)->op_sv;
5973
5974         if (!arg && !SvNIOKp(vesv)) {
5975             arg = version;
5976         }
5977         else {
5978             OP *pack;
5979             SV *meth;
5980
5981             if (version->op_type != OP_CONST || !SvNIOKp(vesv))
5982                 Perl_croak(aTHX_ "Version number must be a constant number");
5983
5984             /* Make copy of idop so we don't free it twice */
5985             pack = newSVOP(OP_CONST, 0, newSVsv(((SVOP*)idop)->op_sv));
5986
5987             /* Fake up a method call to VERSION */
5988             meth = newSVpvs_share("VERSION");
5989             veop = op_convert_list(OP_ENTERSUB, OPf_STACKED|OPf_SPECIAL,
5990                             op_append_elem(OP_LIST,
5991                                         op_prepend_elem(OP_LIST, pack, version),
5992                                         newMETHOP_named(OP_METHOD_NAMED, 0, meth)));
5993         }
5994     }
5995
5996     /* Fake up an import/unimport */
5997     if (arg && arg->op_type == OP_STUB) {
5998         imop = arg;             /* no import on explicit () */
5999     }
6000     else if (SvNIOKp(((SVOP*)idop)->op_sv)) {
6001         imop = NULL;            /* use 5.0; */
6002         if (aver)
6003             use_version = ((SVOP*)idop)->op_sv;
6004         else
6005             idop->op_private |= OPpCONST_NOVER;
6006     }
6007     else {
6008         SV *meth;
6009
6010         /* Make copy of idop so we don't free it twice */
6011         pack = newSVOP(OP_CONST, 0, newSVsv(((SVOP*)idop)->op_sv));
6012
6013         /* Fake up a method call to import/unimport */
6014         meth = aver
6015             ? newSVpvs_share("import") : newSVpvs_share("unimport");
6016         imop = op_convert_list(OP_ENTERSUB, OPf_STACKED|OPf_SPECIAL,
6017                        op_append_elem(OP_LIST,
6018                                    op_prepend_elem(OP_LIST, pack, arg),
6019                                    newMETHOP_named(OP_METHOD_NAMED, 0, meth)
6020                        ));
6021     }
6022
6023     /* Fake up the BEGIN {}, which does its thing immediately. */
6024     newATTRSUB(floor,
6025         newSVOP(OP_CONST, 0, newSVpvs_share("BEGIN")),
6026         NULL,
6027         NULL,
6028         op_append_elem(OP_LINESEQ,
6029             op_append_elem(OP_LINESEQ,
6030                 newSTATEOP(0, NULL, newUNOP(OP_REQUIRE, 0, idop)),
6031                 newSTATEOP(0, NULL, veop)),
6032             newSTATEOP(0, NULL, imop) ));
6033
6034     if (use_version) {
6035         /* Enable the
6036          * feature bundle that corresponds to the required version. */
6037         use_version = sv_2mortal(new_version(use_version));
6038         S_enable_feature_bundle(aTHX_ use_version);
6039
6040         /* If a version >= 5.11.0 is requested, strictures are on by default! */
6041         if (vcmp(use_version,
6042                  sv_2mortal(upg_version(newSVnv(5.011000), FALSE))) >= 0) {
6043             if (!(PL_hints & HINT_EXPLICIT_STRICT_REFS))
6044                 PL_hints |= HINT_STRICT_REFS;
6045             if (!(PL_hints & HINT_EXPLICIT_STRICT_SUBS))
6046                 PL_hints |= HINT_STRICT_SUBS;
6047             if (!(PL_hints & HINT_EXPLICIT_STRICT_VARS))
6048                 PL_hints |= HINT_STRICT_VARS;
6049         }
6050         /* otherwise they are off */
6051         else {
6052             if (!(PL_hints & HINT_EXPLICIT_STRICT_REFS))
6053                 PL_hints &= ~HINT_STRICT_REFS;
6054             if (!(PL_hints & HINT_EXPLICIT_STRICT_SUBS))
6055                 PL_hints &= ~HINT_STRICT_SUBS;
6056             if (!(PL_hints & HINT_EXPLICIT_STRICT_VARS))
6057                 PL_hints &= ~HINT_STRICT_VARS;
6058         }
6059     }
6060
6061     /* The "did you use incorrect case?" warning used to be here.
6062      * The problem is that on case-insensitive filesystems one
6063      * might get false positives for "use" (and "require"):
6064      * "use Strict" or "require CARP" will work.  This causes
6065      * portability problems for the script: in case-strict
6066      * filesystems the script will stop working.
6067      *
6068      * The "incorrect case" warning checked whether "use Foo"
6069      * imported "Foo" to your namespace, but that is wrong, too:
6070      * there is no requirement nor promise in the language that
6071      * a Foo.pm should or would contain anything in package "Foo".
6072      *
6073      * There is very little Configure-wise that can be done, either:
6074      * the case-sensitivity of the build filesystem of Perl does not
6075      * help in guessing the case-sensitivity of the runtime environment.
6076      */
6077
6078     PL_hints |= HINT_BLOCK_SCOPE;
6079     PL_parser->copline = NOLINE;
6080     COP_SEQMAX_INC; /* Purely for B::*'s benefit */
6081 }
6082
6083 /*
6084 =head1 Embedding Functions
6085
6086 =for apidoc load_module
6087
6088 Loads the module whose name is pointed to by the string part of name.
6089 Note that the actual module name, not its filename, should be given.
6090 Eg, "Foo::Bar" instead of "Foo/Bar.pm".  flags can be any of
6091 C<PERL_LOADMOD_DENY>, C<PERL_LOADMOD_NOIMPORT>, or C<PERL_LOADMOD_IMPORT_OPS>
6092 (or 0 for no flags).  ver, if specified
6093 and not NULL, provides version semantics
6094 similar to C<use Foo::Bar VERSION>.  The optional trailing SV*
6095 arguments can be used to specify arguments to the module's C<import()>
6096 method, similar to C<use Foo::Bar VERSION LIST>.  They must be
6097 terminated with a final C<NULL> pointer.  Note that this list can only
6098 be omitted when the C<PERL_LOADMOD_NOIMPORT> flag has been used.
6099 Otherwise at least a single C<NULL> pointer to designate the default
6100 import list is required.
6101
6102 The reference count for each specified C<SV*> parameter is decremented.
6103
6104 =cut */
6105
6106 void
6107 Perl_load_module(pTHX_ U32 flags, SV *name, SV *ver, ...)
6108 {
6109     va_list args;
6110
6111     PERL_ARGS_ASSERT_LOAD_MODULE;
6112
6113     va_start(args, ver);
6114     vload_module(flags, name, ver, &args);
6115     va_end(args);
6116 }
6117
6118 #ifdef PERL_IMPLICIT_CONTEXT
6119 void
6120 Perl_load_module_nocontext(U32 flags, SV *name, SV *ver, ...)
6121 {
6122     dTHX;
6123     va_list args;
6124     PERL_ARGS_ASSERT_LOAD_MODULE_NOCONTEXT;
6125     va_start(args, ver);
6126     vload_module(flags, name, ver, &args);
6127     va_end(args);
6128 }
6129 #endif
6130
6131 void
6132 Perl_vload_module(pTHX_ U32 flags, SV *name, SV *ver, va_list *args)
6133 {
6134     OP *veop, *imop;
6135     OP * const modname = newSVOP(OP_CONST, 0, name);
6136
6137     PERL_ARGS_ASSERT_VLOAD_MODULE;
6138
6139     modname->op_private |= OPpCONST_BARE;
6140     if (ver) {
6141         veop = newSVOP(OP_CONST, 0, ver);
6142     }
6143     else
6144         veop = NULL;
6145     if (flags & PERL_LOADMOD_NOIMPORT) {
6146         imop = sawparens(newNULLLIST());
6147     }
6148     else if (flags & PERL_LOADMOD_IMPORT_OPS) {
6149         imop = va_arg(*args, OP*);
6150     }
6151     else {
6152         SV *sv;
6153         imop = NULL;
6154         sv = va_arg(*args, SV*);
6155         while (sv) {
6156             imop = op_append_elem(OP_LIST, imop, newSVOP(OP_CONST, 0, sv));
6157             sv = va_arg(*args, SV*);
6158         }
6159     }
6160
6161     /* utilize() fakes up a BEGIN { require ..; import ... }, so make sure
6162      * that it has a PL_parser to play with while doing that, and also
6163      * that it doesn't mess with any existing parser, by creating a tmp
6164      * new parser with lex_start(). This won't actually be used for much,
6165      * since pp_require() will create another parser for the real work.
6166      * The ENTER/LEAVE pair protect callers from any side effects of use.  */
6167
6168     ENTER;
6169     SAVEVPTR(PL_curcop);
6170     lex_start(NULL, NULL, LEX_START_SAME_FILTER);
6171     utilize(!(flags & PERL_LOADMOD_DENY), start_subparse(FALSE, 0),
6172             veop, modname, imop);
6173     LEAVE;
6174 }
6175
6176 PERL_STATIC_INLINE OP *
6177 S_new_entersubop(pTHX_ GV *gv, OP *arg)
6178 {
6179     return newUNOP(OP_ENTERSUB, OPf_STACKED,
6180                    newLISTOP(OP_LIST, 0, arg,
6181                              newUNOP(OP_RV2CV, 0,
6182                                      newGVOP(OP_GV, 0, gv))));
6183 }
6184
6185 OP *
6186 Perl_dofile(pTHX_ OP *term, I32 force_builtin)
6187 {
6188     OP *doop;
6189     GV *gv;
6190
6191     PERL_ARGS_ASSERT_DOFILE;
6192
6193     if (!force_builtin && (gv = gv_override("do", 2))) {
6194         doop = S_new_entersubop(aTHX_ gv, term);
6195     }
6196     else {
6197         doop = newUNOP(OP_DOFILE, 0, scalar(term));
6198     }
6199     return doop;
6200 }
6201
6202 /*
6203 =head1 Optree construction
6204
6205 =for apidoc Am|OP *|newSLICEOP|I32 flags|OP *subscript|OP *listval
6206
6207 Constructs, checks, and returns an C<lslice> (list slice) op.  C<flags>
6208 gives the eight bits of C<op_flags>, except that C<OPf_KIDS> will
6209 be set automatically, and, shifted up eight bits, the eight bits of
6210 C<op_private>, except that the bit with value 1 or 2 is automatically
6211 set as required.  C<listval> and C<subscript> supply the parameters of
6212 the slice; they are consumed by this function and become part of the
6213 constructed op tree.
6214
6215 =cut
6216 */
6217
6218 OP *
6219 Perl_newSLICEOP(pTHX_ I32 flags, OP *subscript, OP *listval)
6220 {
6221     return newBINOP(OP_LSLICE, flags,
6222             list(force_list(subscript, 1)),
6223             list(force_list(listval,   1)) );
6224 }
6225
6226 #define ASSIGN_LIST   1
6227 #define ASSIGN_REF    2
6228
6229 STATIC I32
6230 S_assignment_type(pTHX_ const OP *o)
6231 {
6232     unsigned type;
6233     U8 flags;
6234     U8 ret;
6235
6236     if (!o)
6237         return TRUE;
6238
6239     if ((o->op_type == OP_NULL) && (o->op_flags & OPf_KIDS))
6240         o = cUNOPo->op_first;
6241
6242     flags = o->op_flags;
6243     type = o->op_type;
6244     if (type == OP_COND_EXPR) {
6245         OP * const sib = OpSIBLING(cLOGOPo->op_first);
6246         const I32 t = assignment_type(sib);
6247         const I32 f = assignment_type(OpSIBLING(sib));
6248
6249         if (t == ASSIGN_LIST && f == ASSIGN_LIST)
6250             return ASSIGN_LIST;
6251         if ((t == ASSIGN_LIST) ^ (f == ASSIGN_LIST))
6252             yyerror("Assignment to both a list and a scalar");
6253         return FALSE;
6254     }
6255
6256     if (type == OP_SREFGEN)
6257     {
6258         OP * const kid = cUNOPx(cUNOPo->op_first)->op_first;
6259         type = kid->op_type;
6260         flags |= kid->op_flags;
6261         if (!(flags & OPf_PARENS)
6262           && (kid->op_type == OP_RV2AV || kid->op_type == OP_PADAV ||
6263               kid->op_type == OP_RV2HV || kid->op_type == OP_PADHV ))
6264             return ASSIGN_REF;
6265         ret = ASSIGN_REF;
6266     }
6267     else ret = 0;
6268
6269     if (type == OP_LIST &&
6270         (flags & OPf_WANT) == OPf_WANT_SCALAR &&
6271         o->op_private & OPpLVAL_INTRO)
6272         return ret;
6273
6274     if (type == OP_LIST || flags & OPf_PARENS ||
6275         type == OP_RV2AV || type == OP_RV2HV ||
6276         type == OP_ASLICE || type == OP_HSLICE ||
6277         type == OP_KVASLICE || type == OP_KVHSLICE || type == OP_REFGEN)
6278         return TRUE;
6279
6280     if (type == OP_PADAV || type == OP_PADHV)
6281         return TRUE;
6282
6283     if (type == OP_RV2SV)
6284         return ret;
6285
6286     return ret;
6287 }
6288
6289
6290 /*
6291 =for apidoc Am|OP *|newASSIGNOP|I32 flags|OP *left|I32 optype|OP *right
6292
6293 Constructs, checks, and returns an assignment op.  C<left> and C<right>
6294 supply the parameters of the assignment; they are consumed by this
6295 function and become part of the constructed op tree.
6296
6297 If C<optype> is C<OP_ANDASSIGN>, C<OP_ORASSIGN>, or C<OP_DORASSIGN>, then
6298 a suitable conditional optree is constructed.  If C<optype> is the opcode
6299 of a binary operator, such as C<OP_BIT_OR>, then an op is constructed that
6300 performs the binary operation and assigns the result to the left argument.
6301 Either way, if C<optype> is non-zero then C<flags> has no effect.
6302
6303 If C<optype> is zero, then a plain scalar or list assignment is
6304 constructed.  Which type of assignment it is is automatically determined.
6305 C<flags> gives the eight bits of C<op_flags>, except that C<OPf_KIDS>
6306 will be set automatically, and, shifted up eight bits, the eight bits
6307 of C<op_private>, except that the bit with value 1 or 2 is automatically
6308 set as required.
6309
6310 =cut
6311 */
6312
6313 OP *
6314 Perl_newASSIGNOP(pTHX_ I32 flags, OP *left, I32 optype, OP *right)
6315 {
6316     OP *o;
6317     I32 assign_type;
6318
6319     if (optype) {
6320         if (optype == OP_ANDASSIGN || optype == OP_ORASSIGN || optype == OP_DORASSIGN) {
6321             return newLOGOP(optype, 0,
6322                 op_lvalue(scalar(left), optype),
6323                 newUNOP(OP_SASSIGN, 0, scalar(right)));
6324         }
6325         else {
6326             return newBINOP(optype, OPf_STACKED,
6327                 op_lvalue(scalar(left), optype), scalar(right));
6328         }
6329     }
6330
6331     if ((assign_type = assignment_type(left)) == ASSIGN_LIST) {
6332         static const char no_list_state[] = "Initialization of state variables"
6333             " in list context currently forbidden";
6334         OP *curop;
6335
6336         if (left->op_type == OP_ASLICE || left->op_type == OP_HSLICE)
6337             left->op_private &= ~ OPpSLICEWARNING;
6338
6339         PL_modcount = 0;
6340         left = op_lvalue(left, OP_AASSIGN);
6341         curop = list(force_list(left, 1));
6342         o = newBINOP(OP_AASSIGN, flags, list(force_list(right, 1)), curop);
6343         o->op_private = (U8)(0 | (flags >> 8));
6344
6345         if (OP_TYPE_IS_OR_WAS(left, OP_LIST))
6346         {
6347             OP* lop = ((LISTOP*)left)->op_first;
6348             while (lop) {
6349                 if ((lop->op_type == OP_PADSV ||
6350                      lop->op_type == OP_PADAV ||
6351                      lop->op_type == OP_PADHV ||
6352                      lop->op_type == OP_PADANY)
6353                   && (lop->op_private & OPpPAD_STATE)
6354                 )
6355                     yyerror(no_list_state);
6356                 lop = OpSIBLING(lop);
6357             }
6358         }
6359         else if (  (left->op_private & OPpLVAL_INTRO)
6360                 && (left->op_private & OPpPAD_STATE)
6361                 && (   left->op_type == OP_PADSV
6362                     || left->op_type == OP_PADAV
6363                     || left->op_type == OP_PADHV
6364                     || left->op_type == OP_PADANY)
6365         ) {
6366                 /* All single variable list context state assignments, hence
6367                    state ($a) = ...
6368                    (state $a) = ...
6369                    state @a = ...
6370                    state (@a) = ...
6371                    (state @a) = ...
6372                    state %a = ...
6373                    state (%a) = ...
6374                    (state %a) = ...
6375                 */
6376                 yyerror(no_list_state);
6377         }
6378
6379         if (right && right->op_type == OP_SPLIT
6380          && !(right->op_flags & OPf_STACKED)) {
6381             OP* tmpop = ((LISTOP*)right)->op_first;
6382             PMOP * const pm = (PMOP*)tmpop;
6383             assert (tmpop && (tmpop->op_type == OP_PUSHRE));
6384             if (
6385 #ifdef USE_ITHREADS
6386                     !pm->op_pmreplrootu.op_pmtargetoff
6387 #else
6388                     !pm->op_pmreplrootu.op_pmtargetgv
6389 #endif
6390                  && !pm->op_targ
6391                 ) {
6392                     if (!(left->op_private & OPpLVAL_INTRO) &&
6393                         ( (left->op_type == OP_RV2AV &&
6394                           (tmpop=((UNOP*)left)->op_first)->op_type==OP_GV)
6395                         || left->op_type == OP_PADAV )
6396                         ) {
6397                         if (tmpop != (OP *)pm) {
6398 #ifdef USE_ITHREADS
6399                           pm->op_pmreplrootu.op_pmtargetoff
6400                             = cPADOPx(tmpop)->op_padix;
6401                           cPADOPx(tmpop)->op_padix = 0; /* steal it */
6402 #else
6403                           pm->op_pmreplrootu.op_pmtargetgv
6404                             = MUTABLE_GV(cSVOPx(tmpop)->op_sv);
6405                           cSVOPx(tmpop)->op_sv = NULL;  /* steal it */
6406 #endif
6407                           right->op_private |=
6408                             left->op_private & OPpOUR_INTRO;
6409                         }
6410                         else {
6411                             pm->op_targ = left->op_targ;
6412                             left->op_targ = 0; /* filch it */
6413                         }
6414                       detach_split:
6415                         tmpop = cUNOPo->op_first;       /* to list (nulled) */
6416                         tmpop = ((UNOP*)tmpop)->op_first; /* to pushmark */
6417                         /* detach rest of siblings from o subtree,
6418                          * and free subtree */
6419                         op_sibling_splice(cUNOPo->op_first, tmpop, -1, NULL);
6420                         op_free(o);                     /* blow off assign */
6421                         right->op_flags &= ~OPf_WANT;
6422                                 /* "I don't know and I don't care." */
6423                         return right;
6424                     }
6425                     else if (left->op_type == OP_RV2AV
6426                           || left->op_type == OP_PADAV)
6427                     {
6428                         /* Detach the array.  */
6429 #ifdef DEBUGGING
6430                         OP * const ary =
6431 #endif
6432                         op_sibling_splice(cBINOPo->op_last,
6433                                           cUNOPx(cBINOPo->op_last)
6434                                                 ->op_first, 1, NULL);
6435                         assert(ary == left);
6436                         /* Attach it to the split.  */
6437                         op_sibling_splice(right, cLISTOPx(right)->op_last,
6438                                           0, left);
6439                         right->op_flags |= OPf_STACKED;
6440                         /* Detach split and expunge aassign as above.  */
6441                         goto detach_split;
6442                     }
6443                     else if (PL_modcount < RETURN_UNLIMITED_NUMBER &&
6444                             ((LISTOP*)right)->op_last->op_type == OP_CONST)
6445                     {
6446                         SV ** const svp =
6447                             &((SVOP*)((LISTOP*)right)->op_last)->op_sv;
6448                         SV * const sv = *svp;
6449                         if (SvIOK(sv) && SvIVX(sv) == 0)
6450                         {
6451                           if (right->op_private & OPpSPLIT_IMPLIM) {
6452                             /* our own SV, created in ck_split */
6453                             SvREADONLY_off(sv);
6454                             sv_setiv(sv, PL_modcount+1);
6455                           }
6456                           else {
6457                             /* SV may belong to someone else */
6458                             SvREFCNT_dec(sv);
6459                             *svp = newSViv(PL_modcount+1);
6460                           }
6461                         }
6462                     }
6463             }
6464         }
6465         return o;
6466     }
6467     if (assign_type == ASSIGN_REF)
6468         return newBINOP(OP_REFASSIGN, flags, scalar(right), left);
6469     if (!right)
6470         right = newOP(OP_UNDEF, 0);
6471     if (right->op_type == OP_READLINE) {
6472         right->op_flags |= OPf_STACKED;
6473         return newBINOP(OP_NULL, flags, op_lvalue(scalar(left), OP_SASSIGN),
6474                 scalar(right));
6475     }
6476     else {
6477         o = newBINOP(OP_SASSIGN, flags,
6478             scalar(right), op_lvalue(scalar(left), OP_SASSIGN) );
6479     }
6480     return o;
6481 }
6482
6483 /*
6484 =for apidoc Am|OP *|newSTATEOP|I32 flags|char *label|OP *o
6485
6486 Constructs a state op (COP).  The state op is normally a C<nextstate> op,
6487 but will be a C<dbstate> op if debugging is enabled for currently-compiled
6488 code.  The state op is populated from C<PL_curcop> (or C<PL_compiling>).
6489 If C<label> is non-null, it supplies the name of a label to attach to
6490 the state op; this function takes ownership of the memory pointed at by
6491 C<label>, and will free it.  C<flags> gives the eight bits of C<op_flags>
6492 for the state op.
6493
6494 If C<o> is null, the state op is returned.  Otherwise the state op is
6495 combined with C<o> into a C<lineseq> list op, which is returned.  C<o>
6496 is consumed by this function and becomes part of the returned op tree.
6497
6498 =cut
6499 */
6500
6501 OP *
6502 Perl_newSTATEOP(pTHX_ I32 flags, char *label, OP *o)
6503 {
6504     dVAR;
6505     const U32 seq = intro_my();
6506     const U32 utf8 = flags & SVf_UTF8;
6507     COP *cop;
6508
6509     PL_parser->parsed_sub = 0;
6510
6511     flags &= ~SVf_UTF8;
6512
6513     NewOp(1101, cop, 1, COP);
6514     if (PERLDB_LINE && CopLINE(PL_curcop) && PL_curstash != PL_debstash) {
6515         OpTYPE_set(cop, OP_DBSTATE);
6516     }
6517     else {
6518         OpTYPE_set(cop, OP_NEXTSTATE);
6519     }
6520     cop->op_flags = (U8)flags;
6521     CopHINTS_set(cop, PL_hints);
6522 #ifdef VMS
6523     if (VMSISH_HUSHED) cop->op_private |= OPpHUSH_VMSISH;
6524 #endif
6525     cop->op_next = (OP*)cop;
6526
6527     cop->cop_seq = seq;
6528     cop->cop_warnings = DUP_WARNINGS(PL_curcop->cop_warnings);
6529     CopHINTHASH_set(cop, cophh_copy(CopHINTHASH_get(PL_curcop)));
6530     if (label) {
6531         Perl_cop_store_label(aTHX_ cop, label, strlen(label), utf8);
6532
6533         PL_hints |= HINT_BLOCK_SCOPE;
6534         /* It seems that we need to defer freeing this pointer, as other parts
6535            of the grammar end up wanting to copy it after this op has been
6536            created. */
6537         SAVEFREEPV(label);
6538     }
6539
6540     if (PL_parser->preambling != NOLINE) {
6541         CopLINE_set(cop, PL_parser->preambling);
6542         PL_parser->copline = NOLINE;
6543     }
6544     else if (PL_parser->copline == NOLINE)
6545         CopLINE_set(cop, CopLINE(PL_curcop));
6546     else {
6547         CopLINE_set(cop, PL_parser->copline);
6548         PL_parser->copline = NOLINE;
6549     }
6550 #ifdef USE_ITHREADS
6551     CopFILE_set(cop, CopFILE(PL_curcop));       /* XXX share in a pvtable? */
6552 #else
6553     CopFILEGV_set(cop, CopFILEGV(PL_curcop));
6554 #endif
6555     CopSTASH_set(cop, PL_curstash);
6556
6557     if (cop->op_type == OP_DBSTATE) {
6558         /* this line can have a breakpoint - store the cop in IV */
6559         AV *av = CopFILEAVx(PL_curcop);
6560         if (av) {
6561             SV * const * const svp = av_fetch(av, CopLINE(cop), FALSE);
6562             if (svp && *svp != &PL_sv_undef ) {
6563                 (void)SvIOK_on(*svp);
6564                 SvIV_set(*svp, PTR2IV(cop));
6565             }
6566         }
6567     }
6568
6569     if (flags & OPf_SPECIAL)
6570         op_null((OP*)cop);
6571     return op_prepend_elem(OP_LINESEQ, (OP*)cop, o);
6572 }
6573
6574 /*
6575 =for apidoc Am|OP *|newLOGOP|I32 type|I32 flags|OP *first|OP *other
6576
6577 Constructs, checks, and returns a logical (flow control) op.  C<type>
6578 is the opcode.  C<flags> gives the eight bits of C<op_flags>, except
6579 that C<OPf_KIDS> will be set automatically, and, shifted up eight bits,
6580 the eight bits of C<op_private>, except that the bit with value 1 is
6581 automatically set.  C<first> supplies the expression controlling the
6582 flow, and C<other> supplies the side (alternate) chain of ops; they are
6583 consumed by this function and become part of the constructed op tree.
6584
6585 =cut
6586 */
6587
6588 OP *
6589 Perl_newLOGOP(pTHX_ I32 type, I32 flags, OP *first, OP *other)
6590 {
6591     PERL_ARGS_ASSERT_NEWLOGOP;
6592
6593     return new_logop(type, flags, &first, &other);
6594 }
6595
6596 STATIC OP *
6597 S_search_const(pTHX_ OP *o)
6598 {
6599     PERL_ARGS_ASSERT_SEARCH_CONST;
6600
6601     switch (o->op_type) {
6602         case OP_CONST:
6603             return o;
6604         case OP_NULL:
6605             if (o->op_flags & OPf_KIDS)
6606                 return search_const(cUNOPo->op_first);
6607             break;
6608         case OP_LEAVE:
6609         case OP_SCOPE:
6610         case OP_LINESEQ:
6611         {
6612             OP *kid;
6613             if (!(o->op_flags & OPf_KIDS))
6614                 return NULL;
6615             kid = cLISTOPo->op_first;
6616             do {
6617                 switch (kid->op_type) {
6618                     case OP_ENTER:
6619                     case OP_NULL:
6620                     case OP_NEXTSTATE:
6621                         kid = OpSIBLING(kid);
6622                         break;
6623                     default:
6624                         if (kid != cLISTOPo->op_last)
6625                             return NULL;
6626                         goto last;
6627                 }
6628             } while (kid);
6629             if (!kid)
6630                 kid = cLISTOPo->op_last;
6631           last:
6632             return search_const(kid);
6633         }
6634     }
6635
6636     return NULL;
6637 }
6638
6639 STATIC OP *
6640 S_new_logop(pTHX_ I32 type, I32 flags, OP** firstp, OP** otherp)
6641 {
6642     dVAR;
6643     LOGOP *logop;
6644     OP *o;
6645     OP *first;
6646     OP *other;
6647     OP *cstop = NULL;
6648     int prepend_not = 0;
6649
6650     PERL_ARGS_ASSERT_NEW_LOGOP;
6651
6652     first = *firstp;
6653     other = *otherp;
6654
6655     /* [perl #59802]: Warn about things like "return $a or $b", which
6656        is parsed as "(return $a) or $b" rather than "return ($a or
6657        $b)".  NB: This also applies to xor, which is why we do it
6658        here.
6659      */
6660     switch (first->op_type) {
6661     case OP_NEXT:
6662     case OP_LAST:
6663     case OP_REDO:
6664         /* XXX: Perhaps we should emit a stronger warning for these.
6665            Even with the high-precedence operator they don't seem to do
6666            anything sensible.
6667
6668            But until we do, fall through here.
6669          */
6670     case OP_RETURN:
6671     case OP_EXIT:
6672     case OP_DIE:
6673     case OP_GOTO:
6674         /* XXX: Currently we allow people to "shoot themselves in the
6675            foot" by explicitly writing "(return $a) or $b".
6676
6677            Warn unless we are looking at the result from folding or if
6678            the programmer explicitly grouped the operators like this.
6679            The former can occur with e.g.
6680
6681                 use constant FEATURE => ( $] >= ... );
6682                 sub { not FEATURE and return or do_stuff(); }
6683          */
6684         if (!first->op_folded && !(first->op_flags & OPf_PARENS))
6685             Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX),
6686                            "Possible precedence issue with control flow operator");
6687         /* XXX: Should we optimze this to "return $a;" (i.e. remove
6688            the "or $b" part)?
6689         */
6690         break;
6691     }
6692
6693     if (type == OP_XOR)         /* Not short circuit, but here by precedence. */
6694         return newBINOP(type, flags, scalar(first), scalar(other));
6695
6696     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_LOGOP
6697         || type == OP_CUSTOM);
6698
6699     scalarboolean(first);
6700     /* optimize AND and OR ops that have NOTs as children */
6701     if (first->op_type == OP_NOT
6702         && (first->op_flags & OPf_KIDS)
6703         && ((first->op_flags & OPf_SPECIAL) /* unless ($x) { } */
6704             || (other->op_type == OP_NOT))  /* if (!$x && !$y) { } */
6705         ) {
6706         if (type == OP_AND || type == OP_OR) {
6707             if (type == OP_AND)
6708                 type = OP_OR;
6709             else
6710                 type = OP_AND;
6711             op_null(first);
6712             if (other->op_type == OP_NOT) { /* !a AND|OR !b => !(a OR|AND b) */
6713                 op_null(other);
6714                 prepend_not = 1; /* prepend a NOT op later */
6715             }
6716         }
6717     }
6718     /* search for a constant op that could let us fold the test */
6719     if ((cstop = search_const(first))) {
6720         if (cstop->op_private & OPpCONST_STRICT)
6721             no_bareword_allowed(cstop);
6722         else if ((cstop->op_private & OPpCONST_BARE))
6723                 Perl_ck_warner(aTHX_ packWARN(WARN_BAREWORD), "Bareword found in conditional");
6724         if ((type == OP_AND &&  SvTRUE(((SVOP*)cstop)->op_sv)) ||
6725             (type == OP_OR  && !SvTRUE(((SVOP*)cstop)->op_sv)) ||
6726             (type == OP_DOR && !SvOK(((SVOP*)cstop)->op_sv))) {
6727             *firstp = NULL;
6728             if (other->op_type == OP_CONST)
6729                 other->op_private |= OPpCONST_SHORTCIRCUIT;
6730             op_free(first);
6731             if (other->op_type == OP_LEAVE)
6732                 other = newUNOP(OP_NULL, OPf_SPECIAL, other);
6733             else if (other->op_type == OP_MATCH
6734                   || other->op_type == OP_SUBST
6735                   || other->op_type == OP_TRANSR
6736                   || other->op_type == OP_TRANS)
6737                 /* Mark the op as being unbindable with =~ */
6738                 other->op_flags |= OPf_SPECIAL;
6739
6740             other->op_folded = 1;
6741             return other;
6742         }
6743         else {
6744             /* check for C<my $x if 0>, or C<my($x,$y) if 0> */
6745             const OP *o2 = other;
6746             if ( ! (o2->op_type == OP_LIST
6747                     && (( o2 = cUNOPx(o2)->op_first))
6748                     && o2->op_type == OP_PUSHMARK
6749                     && (( o2 = OpSIBLING(o2))) )
6750             )
6751                 o2 = other;
6752             if ((o2->op_type == OP_PADSV || o2->op_type == OP_PADAV
6753                         || o2->op_type == OP_PADHV)
6754                 && o2->op_private & OPpLVAL_INTRO
6755                 && !(o2->op_private & OPpPAD_STATE))
6756             {
6757                 Perl_ck_warner_d(aTHX_ packWARN(WARN_DEPRECATED),
6758                                  "Deprecated use of my() in false conditional");
6759             }
6760
6761             *otherp = NULL;
6762             if (cstop->op_type == OP_CONST)
6763                 cstop->op_private |= OPpCONST_SHORTCIRCUIT;
6764                 op_free(other);
6765             return first;
6766         }
6767     }
6768     else if ((first->op_flags & OPf_KIDS) && type != OP_DOR
6769         && ckWARN(WARN_MISC)) /* [#24076] Don't warn for <FH> err FOO. */
6770     {
6771         const OP * const k1 = ((UNOP*)first)->op_first;
6772         const OP * const k2 = OpSIBLING(k1);
6773         OPCODE warnop = 0;
6774         switch (first->op_type)
6775         {
6776         case OP_NULL:
6777             if (k2 && k2->op_type == OP_READLINE
6778                   && (k2->op_flags & OPf_STACKED)
6779                   && ((k1->op_flags & OPf_WANT) == OPf_WANT_SCALAR))
6780             {
6781                 warnop = k2->op_type;
6782             }
6783             break;
6784
6785         case OP_SASSIGN:
6786             if (k1->op_type == OP_READDIR
6787                   || k1->op_type == OP_GLOB
6788                   || (k1->op_type == OP_NULL && k1->op_targ == OP_GLOB)
6789                  || k1->op_type == OP_EACH
6790                  || k1->op_type == OP_AEACH)
6791             {
6792                 warnop = ((k1->op_type == OP_NULL)
6793                           ? (OPCODE)k1->op_targ : k1->op_type);
6794             }
6795             break;
6796         }
6797         if (warnop) {
6798             const line_t oldline = CopLINE(PL_curcop);
6799             /* This ensures that warnings are reported at the first line
6800                of the construction, not the last.  */
6801             CopLINE_set(PL_curcop, PL_parser->copline);
6802             Perl_warner(aTHX_ packWARN(WARN_MISC),
6803                  "Value of %s%s can be \"0\"; test with defined()",
6804                  PL_op_desc[warnop],
6805                  ((warnop == OP_READLINE || warnop == OP_GLOB)
6806                   ? " construct" : "() operator"));
6807             CopLINE_set(PL_curcop, oldline);
6808         }
6809     }
6810
6811     if (!other)
6812         return first;
6813
6814     if (type == OP_ANDASSIGN || type == OP_ORASSIGN || type == OP_DORASSIGN)
6815         other->op_private |= OPpASSIGN_BACKWARDS;  /* other is an OP_SASSIGN */
6816
6817     logop = S_alloc_LOGOP(aTHX_ type, first, LINKLIST(other));
6818     logop->op_flags |= (U8)flags;
6819     logop->op_private = (U8)(1 | (flags >> 8));
6820
6821     /* establish postfix order */
6822     logop->op_next = LINKLIST(first);
6823     first->op_next = (OP*)logop;
6824     assert(!OpHAS_SIBLING(first));
6825     op_sibling_splice((OP*)logop, first, 0, other);
6826
6827     CHECKOP(type,logop);
6828
6829     o = newUNOP(prepend_not ? OP_NOT : OP_NULL,
6830                 PL_opargs[type] & OA_RETSCALAR ? OPf_WANT_SCALAR : 0,
6831                 (OP*)logop);
6832     other->op_next = o;
6833
6834     return o;
6835 }
6836
6837 /*
6838 =for apidoc Am|OP *|newCONDOP|I32 flags|OP *first|OP *trueop|OP *falseop
6839
6840 Constructs, checks, and returns a conditional-expression (C<cond_expr>)
6841 op.  C<flags> gives the eight bits of C<op_flags>, except that C<OPf_KIDS>
6842 will be set automatically, and, shifted up eight bits, the eight bits of
6843 C<op_private>, except that the bit with value 1 is automatically set.
6844 C<first> supplies the expression selecting between the two branches,
6845 and C<trueop> and C<falseop> supply the branches; they are consumed by
6846 this function and become part of the constructed op tree.
6847
6848 =cut
6849 */
6850
6851 OP *
6852 Perl_newCONDOP(pTHX_ I32 flags, OP *first, OP *trueop, OP *falseop)
6853 {
6854     dVAR;
6855     LOGOP *logop;
6856     OP *start;
6857     OP *o;
6858     OP *cstop;
6859
6860     PERL_ARGS_ASSERT_NEWCONDOP;
6861
6862     if (!falseop)
6863         return newLOGOP(OP_AND, 0, first, trueop);
6864     if (!trueop)
6865         return newLOGOP(OP_OR, 0, first, falseop);
6866
6867     scalarboolean(first);
6868     if ((cstop = search_const(first))) {
6869         /* Left or right arm of the conditional?  */
6870         const bool left = SvTRUE(((SVOP*)cstop)->op_sv);
6871         OP *live = left ? trueop : falseop;
6872         OP *const dead = left ? falseop : trueop;
6873         if (cstop->op_private & OPpCONST_BARE &&
6874             cstop->op_private & OPpCONST_STRICT) {
6875             no_bareword_allowed(cstop);
6876         }
6877         op_free(first);
6878         op_free(dead);
6879         if (live->op_type == OP_LEAVE)
6880             live = newUNOP(OP_NULL, OPf_SPECIAL, live);
6881         else if (live->op_type == OP_MATCH || live->op_type == OP_SUBST
6882               || live->op_type == OP_TRANS || live->op_type == OP_TRANSR)
6883             /* Mark the op as being unbindable with =~ */
6884             live->op_flags |= OPf_SPECIAL;
6885         live->op_folded = 1;
6886         return live;
6887     }
6888     logop = S_alloc_LOGOP(aTHX_ OP_COND_EXPR, first, LINKLIST(trueop));
6889     logop->op_flags |= (U8)flags;
6890     logop->op_private = (U8)(1 | (flags >> 8));
6891     logop->op_next = LINKLIST(falseop);
6892
6893     CHECKOP(OP_COND_EXPR, /* that's logop->op_type */
6894             logop);
6895
6896     /* establish postfix order */
6897     start = LINKLIST(first);
6898     first->op_next = (OP*)logop;
6899
6900     /* make first, trueop, falseop siblings */
6901     op_sibling_splice((OP*)logop, first,  0, trueop);
6902     op_sibling_splice((OP*)logop, trueop, 0, falseop);
6903
6904     o = newUNOP(OP_NULL, 0, (OP*)logop);
6905
6906     trueop->op_next = falseop->op_next = o;
6907
6908     o->op_next = start;
6909     return o;
6910 }
6911
6912 /*
6913 =for apidoc Am|OP *|newRANGE|I32 flags|OP *left|OP *right
6914
6915 Constructs and returns a C<range> op, with subordinate C<flip> and
6916 C<flop> ops.  C<flags> gives the eight bits of C<op_flags> for the
6917 C<flip> op and, shifted up eight bits, the eight bits of C<op_private>
6918 for both the C<flip> and C<range> ops, except that the bit with value
6919 1 is automatically set.  C<left> and C<right> supply the expressions
6920 controlling the endpoints of the range; they are consumed by this function
6921 and become part of the constructed op tree.
6922
6923 =cut
6924 */
6925
6926 OP *
6927 Perl_newRANGE(pTHX_ I32 flags, OP *left, OP *right)
6928 {
6929     LOGOP *range;
6930     OP *flip;
6931     OP *flop;
6932     OP *leftstart;
6933     OP *o;
6934
6935     PERL_ARGS_ASSERT_NEWRANGE;
6936
6937     range = S_alloc_LOGOP(aTHX_ OP_RANGE, left, LINKLIST(right));
6938     range->op_flags = OPf_KIDS;
6939     leftstart = LINKLIST(left);
6940     range->op_private = (U8)(1 | (flags >> 8));
6941
6942     /* make left and right siblings */
6943     op_sibling_splice((OP*)range, left, 0, right);
6944
6945     range->op_next = (OP*)range;
6946     flip = newUNOP(OP_FLIP, flags, (OP*)range);
6947     flop = newUNOP(OP_FLOP, 0, flip);
6948     o = newUNOP(OP_NULL, 0, flop);
6949     LINKLIST(flop);
6950     range->op_next = leftstart;
6951
6952     left->op_next = flip;
6953     right->op_next = flop;
6954
6955     range->op_targ =
6956         pad_add_name_pvn("$", 1, padadd_NO_DUP_CHECK|padadd_STATE, 0, 0);
6957     sv_upgrade(PAD_SV(range->op_targ), SVt_PVNV);
6958     flip->op_targ =
6959         pad_add_name_pvn("$", 1, padadd_NO_DUP_CHECK|padadd_STATE, 0, 0);;
6960     sv_upgrade(PAD_SV(flip->op_targ), SVt_PVNV);
6961     SvPADTMP_on(PAD_SV(flip->op_targ));
6962
6963     flip->op_private =  left->op_type == OP_CONST ? OPpFLIP_LINENUM : 0;
6964     flop->op_private = right->op_type == OP_CONST ? OPpFLIP_LINENUM : 0;
6965
6966     /* check barewords before they might be optimized aways */
6967     if (flip->op_private && cSVOPx(left)->op_private & OPpCONST_STRICT)
6968         no_bareword_allowed(left);
6969     if (flop->op_private && cSVOPx(right)->op_private & OPpCONST_STRICT)
6970         no_bareword_allowed(right);
6971
6972     flip->op_next = o;
6973     if (!flip->op_private || !flop->op_private)
6974         LINKLIST(o);            /* blow off optimizer unless constant */
6975
6976     return o;
6977 }
6978
6979 /*
6980 =for apidoc Am|OP *|newLOOPOP|I32 flags|I32 debuggable|OP *expr|OP *block
6981
6982 Constructs, checks, and returns an op tree expressing a loop.  This is
6983 only a loop in the control flow through the op tree; it does not have
6984 the heavyweight loop structure that allows exiting the loop by C<last>
6985 and suchlike.  C<flags> gives the eight bits of C<op_flags> for the
6986 top-level op, except that some bits will be set automatically as required.
6987 C<expr> supplies the expression controlling loop iteration, and C<block>
6988 supplies the body of the loop; they are consumed by this function and
6989 become part of the constructed op tree.  C<debuggable> is currently
6990 unused and should always be 1.
6991
6992 =cut
6993 */
6994
6995 OP *
6996 Perl_newLOOPOP(pTHX_ I32 flags, I32 debuggable, OP *expr, OP *block)
6997 {
6998     OP* listop;
6999     OP* o;
7000     const bool once = block && block->op_flags & OPf_SPECIAL &&
7001                       block->op_type == OP_NULL;
7002
7003     PERL_UNUSED_ARG(debuggable);
7004
7005     if (expr) {
7006         if (once && (
7007               (expr->op_type == OP_CONST && !SvTRUE(((SVOP*)expr)->op_sv))
7008            || (  expr->op_type == OP_NOT
7009               && cUNOPx(expr)->op_first->op_type == OP_CONST
7010               && SvTRUE(cSVOPx_sv(cUNOPx(expr)->op_first))
7011               )
7012            ))
7013             /* Return the block now, so that S_new_logop does not try to
7014                fold it away. */
7015             return block;       /* do {} while 0 does once */
7016         if (expr->op_type == OP_READLINE
7017             || expr->op_type == OP_READDIR
7018             || expr->op_type == OP_GLOB
7019             || expr->op_type == OP_EACH || expr->op_type == OP_AEACH
7020             || (expr->op_type == OP_NULL && expr->op_targ == OP_GLOB)) {
7021             expr = newUNOP(OP_DEFINED, 0,
7022                 newASSIGNOP(0, newDEFSVOP(), 0, expr) );
7023         } else if (expr->op_flags & OPf_KIDS) {
7024             const OP * const k1 = ((UNOP*)expr)->op_first;
7025             const OP * const k2 = k1 ? OpSIBLING(k1) : NULL;
7026             switch (expr->op_type) {
7027               case OP_NULL:
7028                 if (k2 && (k2->op_type == OP_READLINE || k2->op_type == OP_READDIR)
7029                       && (k2->op_flags & OPf_STACKED)
7030                       && ((k1->op_flags & OPf_WANT) == OPf_WANT_SCALAR))
7031                     expr = newUNOP(OP_DEFINED, 0, expr);
7032                 break;
7033
7034               case OP_SASSIGN:
7035                 if (k1 && (k1->op_type == OP_READDIR
7036                       || k1->op_type == OP_GLOB
7037                       || (k1->op_type == OP_NULL && k1->op_targ == OP_GLOB)
7038                      || k1->op_type == OP_EACH
7039                      || k1->op_type == OP_AEACH))
7040                     expr = newUNOP(OP_DEFINED, 0, expr);
7041                 break;
7042             }
7043         }
7044     }
7045
7046     /* if block is null, the next op_append_elem() would put UNSTACK, a scalar
7047      * op, in listop. This is wrong. [perl #27024] */
7048     if (!block)
7049         block = newOP(OP_NULL, 0);
7050     listop = op_append_elem(OP_LINESEQ, block, newOP(OP_UNSTACK, 0));
7051     o = new_logop(OP_AND, 0, &expr, &listop);
7052
7053     if (once) {
7054         ASSUME(listop);
7055     }
7056
7057     if (listop)
7058         ((LISTOP*)listop)->op_last->op_next = LINKLIST(o);
7059
7060     if (once && o != listop)
7061     {
7062         assert(cUNOPo->op_first->op_type == OP_AND
7063             || cUNOPo->op_first->op_type == OP_OR);
7064         o->op_next = ((LOGOP*)cUNOPo->op_first)->op_other;
7065     }
7066
7067     if (o == listop)
7068         o = newUNOP(OP_NULL, 0, o);     /* or do {} while 1 loses outer block */
7069
7070     o->op_flags |= flags;
7071     o = op_scope(o);
7072     o->op_flags |= OPf_SPECIAL; /* suppress POPBLOCK curpm restoration*/
7073     return o;
7074 }
7075
7076 /*
7077 =for apidoc Am|OP *|newWHILEOP|I32 flags|I32 debuggable|LOOP *loop|OP *expr|OP *block|OP *cont|I32 has_my
7078
7079 Constructs, checks, and returns an op tree expressing a C<while> loop.
7080 This is a heavyweight loop, with structure that allows exiting the loop
7081 by C<last> and suchlike.
7082
7083 C<loop> is an optional preconstructed C<enterloop> op to use in the
7084 loop; if it is null then a suitable op will be constructed automatically.
7085 C<expr> supplies the loop's controlling expression.  C<block> supplies the
7086 main body of the loop, and C<cont> optionally supplies a C<continue> block
7087 that operates as a second half of the body.  All of these optree inputs
7088 are consumed by this function and become part of the constructed op tree.
7089
7090 C<flags> gives the eight bits of C<op_flags> for the C<leaveloop>
7091 op and, shifted up eight bits, the eight bits of C<op_private> for
7092 the C<leaveloop> op, except that (in both cases) some bits will be set
7093 automatically.  C<debuggable> is currently unused and should always be 1.
7094 C<has_my> can be supplied as true to force the
7095 loop body to be enclosed in its own scope.
7096
7097 =cut
7098 */
7099
7100 OP *
7101 Perl_newWHILEOP(pTHX_ I32 flags, I32 debuggable, LOOP *loop,
7102         OP *expr, OP *block, OP *cont, I32 has_my)
7103 {
7104     dVAR;
7105     OP *redo;
7106     OP *next = NULL;
7107     OP *listop;
7108     OP *o;
7109     U8 loopflags = 0;
7110
7111     PERL_UNUSED_ARG(debuggable);
7112
7113     if (expr) {
7114         if (expr->op_type == OP_READLINE
7115          || expr->op_type == OP_READDIR
7116          || expr->op_type == OP_GLOB
7117          || expr->op_type == OP_EACH || expr->op_type == OP_AEACH
7118                      || (expr->op_type == OP_NULL && expr->op_targ == OP_GLOB)) {
7119             expr = newUNOP(OP_DEFINED, 0,
7120                 newASSIGNOP(0, newDEFSVOP(), 0, expr) );
7121         } else if (expr->op_flags & OPf_KIDS) {
7122             const OP * const k1 = ((UNOP*)expr)->op_first;
7123             const OP * const k2 = (k1) ? OpSIBLING(k1) : NULL;
7124             switch (expr->op_type) {
7125               case OP_NULL:
7126                 if (k2 && (k2->op_type == OP_READLINE || k2->op_type == OP_READDIR)
7127                       && (k2->op_flags & OPf_STACKED)
7128                       && ((k1->op_flags & OPf_WANT) == OPf_WANT_SCALAR))
7129                     expr = newUNOP(OP_DEFINED, 0, expr);
7130                 break;
7131
7132               case OP_SASSIGN:
7133                 if (k1 && (k1->op_type == OP_READDIR
7134                       || k1->op_type == OP_GLOB
7135                       || (k1->op_type == OP_NULL && k1->op_targ == OP_GLOB)
7136                      || k1->op_type == OP_EACH
7137                      || k1->op_type == OP_AEACH))
7138                     expr = newUNOP(OP_DEFINED, 0, expr);
7139                 break;
7140             }
7141         }
7142     }
7143
7144     if (!block)
7145         block = newOP(OP_NULL, 0);
7146     else if (cont || has_my) {
7147         block = op_scope(block);
7148     }
7149
7150     if (cont) {
7151         next = LINKLIST(cont);
7152     }
7153     if (expr) {
7154         OP * const unstack = newOP(OP_UNSTACK, 0);
7155         if (!next)
7156             next = unstack;
7157         cont = op_append_elem(OP_LINESEQ, cont, unstack);
7158     }
7159
7160     assert(block);
7161     listop = op_append_list(OP_LINESEQ, block, cont);
7162     assert(listop);
7163     redo = LINKLIST(listop);
7164
7165     if (expr) {
7166         scalar(listop);
7167         o = new_logop(OP_AND, 0, &expr, &listop);
7168         if (o == expr && o->op_type == OP_CONST && !SvTRUE(cSVOPo->op_sv)) {
7169             op_free((OP*)loop);
7170             return expr;                /* listop already freed by new_logop */
7171         }
7172         if (listop)
7173             ((LISTOP*)listop)->op_last->op_next =
7174                 (o == listop ? redo : LINKLIST(o));
7175     }
7176     else
7177         o = listop;
7178
7179     if (!loop) {
7180         NewOp(1101,loop,1,LOOP);
7181         OpTYPE_set(loop, OP_ENTERLOOP);
7182         loop->op_private = 0;
7183         loop->op_next = (OP*)loop;
7184     }
7185
7186     o = newBINOP(OP_LEAVELOOP, 0, (OP*)loop, o);
7187
7188     loop->op_redoop = redo;
7189     loop->op_lastop = o;
7190     o->op_private |= loopflags;
7191
7192     if (next)
7193         loop->op_nextop = next;
7194     else
7195         loop->op_nextop = o;
7196
7197     o->op_flags |= flags;
7198     o->op_private |= (flags >> 8);
7199     return o;
7200 }
7201
7202 /*
7203 =for apidoc Am|OP *|newFOROP|I32 flags|OP *sv|OP *expr|OP *block|OP *cont
7204
7205 Constructs, checks, and returns an op tree expressing a C<foreach>
7206 loop (iteration through a list of values).  This is a heavyweight loop,
7207 with structure that allows exiting the loop by C<last> and suchlike.
7208
7209 C<sv> optionally supplies the variable that will be aliased to each
7210 item in turn; if null, it defaults to C<$_>.
7211 C<expr> supplies the list of values to iterate over.  C<block> supplies
7212 the main body of the loop, and C<cont> optionally supplies a C<continue>
7213 block that operates as a second half of the body.  All of these optree
7214 inputs are consumed by this function and become part of the constructed
7215 op tree.
7216
7217 C<flags> gives the eight bits of C<op_flags> for the C<leaveloop>
7218 op and, shifted up eight bits, the eight bits of C<op_private> for
7219 the C<leaveloop> op, except that (in both cases) some bits will be set
7220 automatically.
7221
7222 =cut
7223 */
7224
7225 OP *
7226 Perl_newFOROP(pTHX_ I32 flags, OP *sv, OP *expr, OP *block, OP *cont)
7227 {
7228     dVAR;
7229     LOOP *loop;
7230     OP *wop;
7231     PADOFFSET padoff = 0;
7232     I32 iterflags = 0;
7233     I32 iterpflags = 0;
7234
7235     PERL_ARGS_ASSERT_NEWFOROP;
7236
7237     if (sv) {
7238         if (sv->op_type == OP_RV2SV) {  /* symbol table variable */
7239             iterpflags = sv->op_private & OPpOUR_INTRO; /* for our $x () */
7240             OpTYPE_set(sv, OP_RV2GV);
7241
7242             /* The op_type check is needed to prevent a possible segfault
7243              * if the loop variable is undeclared and 'strict vars' is in
7244              * effect. This is illegal but is nonetheless parsed, so we
7245              * may reach this point with an OP_CONST where we're expecting
7246              * an OP_GV.
7247              */
7248             if (cUNOPx(sv)->op_first->op_type == OP_GV
7249              && cGVOPx_gv(cUNOPx(sv)->op_first) == PL_defgv)
7250                 iterpflags |= OPpITER_DEF;
7251         }
7252         else if (sv->op_type == OP_PADSV) { /* private variable */
7253             iterpflags = sv->op_private & OPpLVAL_INTRO; /* for my $x () */
7254             padoff = sv->op_targ;
7255             sv->op_targ = 0;
7256             op_free(sv);
7257             sv = NULL;
7258             PAD_COMPNAME_GEN_set(padoff, PERL_INT_MAX);
7259         }
7260         else if (sv->op_type == OP_NULL && sv->op_targ == OP_SREFGEN)
7261             NOOP;
7262         else
7263             Perl_croak(aTHX_ "Can't use %s for loop variable", PL_op_desc[sv->op_type]);
7264         if (padoff) {
7265             PADNAME * const pn = PAD_COMPNAME(padoff);
7266             const char * const name = PadnamePV(pn);
7267
7268             if (PadnameLEN(pn) == 2 && name[0] == '$' && name[1] == '_')
7269                 iterpflags |= OPpITER_DEF;
7270         }
7271     }
7272     else {
7273         sv = newGVOP(OP_GV, 0, PL_defgv);
7274         iterpflags |= OPpITER_DEF;
7275     }
7276
7277     if (expr->op_type == OP_RV2AV || expr->op_type == OP_PADAV) {
7278         expr = op_lvalue(force_list(scalar(ref(expr, OP_ITER)), 1), OP_GREPSTART);
7279         iterflags |= OPf_STACKED;
7280     }
7281     else if (expr->op_type == OP_NULL &&
7282              (expr->op_flags & OPf_KIDS) &&
7283              ((BINOP*)expr)->op_first->op_type == OP_FLOP)
7284     {
7285         /* Basically turn for($x..$y) into the same as for($x,$y), but we
7286          * set the STACKED flag to indicate that these values are to be
7287          * treated as min/max values by 'pp_enteriter'.
7288          */
7289         const UNOP* const flip = (UNOP*)((UNOP*)((BINOP*)expr)->op_first)->op_first;
7290         LOGOP* const range = (LOGOP*) flip->op_first;
7291         OP* const left  = range->op_first;
7292         OP* const right = OpSIBLING(left);
7293         LISTOP* listop;
7294
7295         range->op_flags &= ~OPf_KIDS;
7296         /* detach range's children */
7297         op_sibling_splice((OP*)range, NULL, -1, NULL);
7298
7299         listop = (LISTOP*)newLISTOP(OP_LIST, 0, left, right);
7300         listop->op_first->op_next = range->op_next;
7301         left->op_next = range->op_other;
7302         right->op_next = (OP*)listop;
7303         listop->op_next = listop->op_first;
7304
7305         op_free(expr);
7306         expr = (OP*)(listop);
7307         op_null(expr);
7308         iterflags |= OPf_STACKED;
7309     }
7310     else {
7311         expr = op_lvalue(force_list(expr, 1), OP_GREPSTART);
7312     }
7313
7314     loop = (LOOP*)op_convert_list(OP_ENTERITER, iterflags,
7315                                   op_append_elem(OP_LIST, list(expr),
7316                                                  scalar(sv)));
7317     assert(!loop->op_next);
7318     /* for my  $x () sets OPpLVAL_INTRO;
7319      * for our $x () sets OPpOUR_INTRO */
7320     loop->op_private = (U8)iterpflags;
7321     if (loop->op_slabbed
7322      && DIFF(loop, OpSLOT(loop)->opslot_next)
7323          < SIZE_TO_PSIZE(sizeof(LOOP)))
7324     {
7325         LOOP *tmp;
7326         NewOp(1234,tmp,1,LOOP);
7327         Copy(loop,tmp,1,LISTOP);
7328 #ifdef PERL_OP_PARENT
7329         assert(loop->op_last->op_sibparent == (OP*)loop);
7330         OpLASTSIB_set(loop->op_last, (OP*)tmp); /*point back to new parent */
7331 #endif
7332         S_op_destroy(aTHX_ (OP*)loop);
7333         loop = tmp;
7334     }
7335     else if (!loop->op_slabbed)
7336     {
7337         loop = (LOOP*)PerlMemShared_realloc(loop, sizeof(LOOP));
7338 #ifdef PERL_OP_PARENT
7339         OpLASTSIB_set(loop->op_last, (OP*)loop);
7340 #endif
7341     }
7342     loop->op_targ = padoff;
7343     wop = newWHILEOP(flags, 1, loop, newOP(OP_ITER, 0), block, cont, 0);
7344     return wop;
7345 }
7346
7347 /*
7348 =for apidoc Am|OP *|newLOOPEX|I32 type|OP *label
7349
7350 Constructs, checks, and returns a loop-exiting op (such as C<goto>
7351 or C<last>).  C<type> is the opcode.  C<label> supplies the parameter
7352 determining the target of the op; it is consumed by this function and
7353 becomes part of the constructed op tree.
7354
7355 =cut
7356 */
7357
7358 OP*
7359 Perl_newLOOPEX(pTHX_ I32 type, OP *label)
7360 {
7361     OP *o = NULL;
7362
7363     PERL_ARGS_ASSERT_NEWLOOPEX;
7364
7365     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_LOOPEXOP
7366         || type == OP_CUSTOM);
7367
7368     if (type != OP_GOTO) {
7369         /* "last()" means "last" */
7370         if (label->op_type == OP_STUB && (label->op_flags & OPf_PARENS)) {
7371             o = newOP(type, OPf_SPECIAL);
7372         }
7373     }
7374     else {
7375         /* Check whether it's going to be a goto &function */
7376         if (label->op_type == OP_ENTERSUB
7377                 && !(label->op_flags & OPf_STACKED))
7378             label = newUNOP(OP_REFGEN, 0, op_lvalue(label, OP_REFGEN));
7379     }
7380
7381     /* Check for a constant argument */
7382     if (label->op_type == OP_CONST) {
7383             SV * const sv = ((SVOP *)label)->op_sv;
7384             STRLEN l;
7385             const char *s = SvPV_const(sv,l);
7386             if (l == strlen(s)) {
7387                 o = newPVOP(type,
7388                             SvUTF8(((SVOP*)label)->op_sv),
7389                             savesharedpv(
7390                                 SvPV_nolen_const(((SVOP*)label)->op_sv)));
7391             }
7392     }
7393     
7394     /* If we have already created an op, we do not need the label. */
7395     if (o)
7396                 op_free(label);
7397     else o = newUNOP(type, OPf_STACKED, label);
7398
7399     PL_hints |= HINT_BLOCK_SCOPE;
7400     return o;
7401 }
7402
7403 /* if the condition is a literal array or hash
7404    (or @{ ... } etc), make a reference to it.
7405  */
7406 STATIC OP *
7407 S_ref_array_or_hash(pTHX_ OP *cond)
7408 {
7409     if (cond
7410     && (cond->op_type == OP_RV2AV
7411     ||  cond->op_type == OP_PADAV
7412     ||  cond->op_type == OP_RV2HV
7413     ||  cond->op_type == OP_PADHV))
7414
7415         return newUNOP(OP_REFGEN, 0, op_lvalue(cond, OP_REFGEN));
7416
7417     else if(cond
7418     && (cond->op_type == OP_ASLICE
7419     ||  cond->op_type == OP_KVASLICE
7420     ||  cond->op_type == OP_HSLICE
7421     ||  cond->op_type == OP_KVHSLICE)) {
7422
7423         /* anonlist now needs a list from this op, was previously used in
7424          * scalar context */
7425         cond->op_flags &= ~(OPf_WANT_SCALAR | OPf_REF);
7426         cond->op_flags |= OPf_WANT_LIST;
7427
7428         return newANONLIST(op_lvalue(cond, OP_ANONLIST));
7429     }
7430
7431     else
7432         return cond;
7433 }
7434
7435 /* These construct the optree fragments representing given()
7436    and when() blocks.
7437
7438    entergiven and enterwhen are LOGOPs; the op_other pointer
7439    points up to the associated leave op. We need this so we
7440    can put it in the context and make break/continue work.
7441    (Also, of course, pp_enterwhen will jump straight to
7442    op_other if the match fails.)
7443  */
7444
7445 STATIC OP *
7446 S_newGIVWHENOP(pTHX_ OP *cond, OP *block,
7447                    I32 enter_opcode, I32 leave_opcode,
7448                    PADOFFSET entertarg)
7449 {
7450     dVAR;
7451     LOGOP *enterop;
7452     OP *o;
7453
7454     PERL_ARGS_ASSERT_NEWGIVWHENOP;
7455     PERL_UNUSED_ARG(entertarg); /* used to indicate targ of lexical $_ */
7456
7457     enterop = S_alloc_LOGOP(aTHX_ enter_opcode, block, NULL);
7458     enterop->op_targ = 0;
7459     enterop->op_private = 0;
7460
7461     o = newUNOP(leave_opcode, 0, (OP *) enterop);
7462
7463     if (cond) {
7464         /* prepend cond if we have one */
7465         op_sibling_splice((OP*)enterop, NULL, 0, scalar(cond));
7466
7467         o->op_next = LINKLIST(cond);
7468         cond->op_next = (OP *) enterop;
7469     }
7470     else {
7471         /* This is a default {} block */
7472         enterop->op_flags |= OPf_SPECIAL;
7473         o      ->op_flags |= OPf_SPECIAL;
7474
7475         o->op_next = (OP *) enterop;
7476     }
7477
7478     CHECKOP(enter_opcode, enterop); /* Currently does nothing, since
7479                                        entergiven and enterwhen both
7480                                        use ck_null() */
7481
7482     enterop->op_next = LINKLIST(block);
7483     block->op_next = enterop->op_other = o;
7484
7485     return o;
7486 }
7487
7488 /* Does this look like a boolean operation? For these purposes
7489    a boolean operation is:
7490      - a subroutine call [*]
7491      - a logical connective
7492      - a comparison operator
7493      - a filetest operator, with the exception of -s -M -A -C
7494      - defined(), exists() or eof()
7495      - /$re/ or $foo =~ /$re/
7496    
7497    [*] possibly surprising
7498  */
7499 STATIC bool
7500 S_looks_like_bool(pTHX_ const OP *o)
7501 {
7502     PERL_ARGS_ASSERT_LOOKS_LIKE_BOOL;
7503
7504     switch(o->op_type) {
7505         case OP_OR:
7506         case OP_DOR:
7507             return looks_like_bool(cLOGOPo->op_first);
7508
7509         case OP_AND:
7510         {
7511             OP* sibl = OpSIBLING(cLOGOPo->op_first);
7512             ASSUME(sibl);
7513             return (
7514                 looks_like_bool(cLOGOPo->op_first)
7515              && looks_like_bool(sibl));
7516         }
7517
7518         case OP_NULL:
7519         case OP_SCALAR:
7520             return (
7521                 o->op_flags & OPf_KIDS
7522             && looks_like_bool(cUNOPo->op_first));
7523
7524         case OP_ENTERSUB:
7525
7526         case OP_NOT:    case OP_XOR:
7527
7528         case OP_EQ:     case OP_NE:     case OP_LT:
7529         case OP_GT:     case OP_LE:     case OP_GE:
7530
7531         case OP_I_EQ:   case OP_I_NE:   case OP_I_LT:
7532         case OP_I_GT:   case OP_I_LE:   case OP_I_GE:
7533
7534         case OP_SEQ:    case OP_SNE:    case OP_SLT:
7535         case OP_SGT:    case OP_SLE:    case OP_SGE:
7536         
7537         case OP_SMARTMATCH:
7538         
7539         case OP_FTRREAD:  case OP_FTRWRITE: case OP_FTREXEC:
7540         case OP_FTEREAD:  case OP_FTEWRITE: case OP_FTEEXEC:
7541         case OP_FTIS:     case OP_FTEOWNED: case OP_FTROWNED:
7542         case OP_FTZERO:   case OP_FTSOCK:   case OP_FTCHR:
7543         case OP_FTBLK:    case OP_FTFILE:   case OP_FTDIR:
7544         case OP_FTPIPE:   case OP_FTLINK:   case OP_FTSUID:
7545         case OP_FTSGID:   case OP_FTSVTX:   case OP_FTTTY:
7546         case OP_FTTEXT:   case OP_FTBINARY:
7547         
7548         case OP_DEFINED: case OP_EXISTS:
7549         case OP_MATCH:   case OP_EOF:
7550
7551         case OP_FLOP:
7552
7553             return TRUE;
7554         
7555         case OP_CONST:
7556             /* Detect comparisons that have been optimized away */
7557             if (cSVOPo->op_sv == &PL_sv_yes
7558             ||  cSVOPo->op_sv == &PL_sv_no)
7559             
7560                 return TRUE;
7561             else
7562                 return FALSE;
7563
7564         /* FALLTHROUGH */
7565         default:
7566             return FALSE;
7567     }
7568 }
7569
7570 /*
7571 =for apidoc Am|OP *|newGIVENOP|OP *cond|OP *block|PADOFFSET defsv_off
7572
7573 Constructs, checks, and returns an op tree expressing a C<given> block.
7574 C<cond> supplies the expression that will be locally assigned to a lexical
7575 variable, and C<block> supplies the body of the C<given> construct; they
7576 are consumed by this function and become part of the constructed op tree.
7577 C<defsv_off> must be zero (it used to identity the pad slot of lexical $_).
7578
7579 =cut
7580 */
7581
7582 OP *
7583 Perl_newGIVENOP(pTHX_ OP *cond, OP *block, PADOFFSET defsv_off)
7584 {
7585     PERL_ARGS_ASSERT_NEWGIVENOP;
7586     PERL_UNUSED_ARG(defsv_off);
7587
7588     assert(!defsv_off);
7589     return newGIVWHENOP(
7590         ref_array_or_hash(cond),
7591         block,
7592         OP_ENTERGIVEN, OP_LEAVEGIVEN,
7593         0);
7594 }
7595
7596 /*
7597 =for apidoc Am|OP *|newWHENOP|OP *cond|OP *block
7598
7599 Constructs, checks, and returns an op tree expressing a C<when> block.
7600 C<cond> supplies the test expression, and C<block> supplies the block
7601 that will be executed if the test evaluates to true; they are consumed
7602 by this function and become part of the constructed op tree.  C<cond>
7603 will be interpreted DWIMically, often as a comparison against C<$_>,
7604 and may be null to generate a C<default> block.
7605
7606 =cut
7607 */
7608
7609 OP *
7610 Perl_newWHENOP(pTHX_ OP *cond, OP *block)
7611 {
7612     const bool cond_llb = (!cond || looks_like_bool(cond));
7613     OP *cond_op;
7614
7615     PERL_ARGS_ASSERT_NEWWHENOP;
7616
7617     if (cond_llb)
7618         cond_op = cond;
7619     else {
7620         cond_op = newBINOP(OP_SMARTMATCH, OPf_SPECIAL,
7621                 newDEFSVOP(),
7622                 scalar(ref_array_or_hash(cond)));
7623     }
7624     
7625     return newGIVWHENOP(cond_op, block, OP_ENTERWHEN, OP_LEAVEWHEN, 0);
7626 }
7627
7628 /* must not conflict with SVf_UTF8 */
7629 #define CV_CKPROTO_CURSTASH     0x1
7630
7631 void
7632 Perl_cv_ckproto_len_flags(pTHX_ const CV *cv, const GV *gv, const char *p,
7633                     const STRLEN len, const U32 flags)
7634 {
7635     SV *name = NULL, *msg;
7636     const char * cvp = SvROK(cv)
7637                         ? SvTYPE(SvRV_const(cv)) == SVt_PVCV
7638                            ? (cv = (const CV *)SvRV_const(cv), CvPROTO(cv))
7639                            : ""
7640                         : CvPROTO(cv);
7641     STRLEN clen = CvPROTOLEN(cv), plen = len;
7642
7643     PERL_ARGS_ASSERT_CV_CKPROTO_LEN_FLAGS;
7644
7645     if (p == NULL && cvp == NULL)
7646         return;
7647
7648     if (!ckWARN_d(WARN_PROTOTYPE))
7649         return;
7650
7651     if (p && cvp) {
7652         p = S_strip_spaces(aTHX_ p, &plen);
7653         cvp = S_strip_spaces(aTHX_ cvp, &clen);
7654         if ((flags & SVf_UTF8) == SvUTF8(cv)) {
7655             if (plen == clen && memEQ(cvp, p, plen))
7656                 return;
7657         } else {
7658             if (flags & SVf_UTF8) {
7659                 if (bytes_cmp_utf8((const U8 *)cvp, clen, (const U8 *)p, plen) == 0)
7660                     return;
7661             }
7662             else {
7663                 if (bytes_cmp_utf8((const U8 *)p, plen, (const U8 *)cvp, clen) == 0)
7664                     return;
7665             }
7666         }
7667     }
7668
7669     msg = sv_newmortal();
7670
7671     if (gv)
7672     {
7673         if (isGV(gv))
7674             gv_efullname3(name = sv_newmortal(), gv, NULL);
7675         else if (SvPOK(gv) && *SvPVX((SV *)gv) == '&')
7676             name = newSVpvn_flags(SvPVX((SV *)gv)+1, SvCUR(gv)-1, SvUTF8(gv)|SVs_TEMP);
7677         else if (flags & CV_CKPROTO_CURSTASH || SvROK(gv)) {
7678             name = sv_2mortal(newSVhek(HvNAME_HEK(PL_curstash)));
7679             sv_catpvs(name, "::");
7680             if (SvROK(gv)) {
7681                 assert (SvTYPE(SvRV_const(gv)) == SVt_PVCV);
7682                 assert (CvNAMED(SvRV_const(gv)));
7683                 sv_cathek(name, CvNAME_HEK(MUTABLE_CV(SvRV_const(gv))));
7684             }
7685             else sv_catsv(name, (SV *)gv);
7686         }
7687         else name = (SV *)gv;
7688     }
7689     sv_setpvs(msg, "Prototype mismatch:");
7690     if (name)
7691         Perl_sv_catpvf(aTHX_ msg, " sub %"SVf, SVfARG(name));
7692     if (cvp)
7693         Perl_sv_catpvf(aTHX_ msg, " (%"UTF8f")", 
7694             UTF8fARG(SvUTF8(cv),clen,cvp)
7695         );
7696     else
7697         sv_catpvs(msg, ": none");
7698     sv_catpvs(msg, " vs ");
7699     if (p)
7700         Perl_sv_catpvf(aTHX_ msg, "(%"UTF8f")", UTF8fARG(flags & SVf_UTF8,len,p));
7701     else
7702         sv_catpvs(msg, "none");
7703     Perl_warner(aTHX_ packWARN(WARN_PROTOTYPE), "%"SVf, SVfARG(msg));
7704 }
7705
7706 static void const_sv_xsub(pTHX_ CV* cv);
7707 static void const_av_xsub(pTHX_ CV* cv);
7708
7709 /*
7710
7711 =head1 Optree Manipulation Functions
7712
7713 =for apidoc cv_const_sv
7714
7715 If C<cv> is a constant sub eligible for inlining, returns the constant
7716 value returned by the sub.  Otherwise, returns C<NULL>.
7717
7718 Constant subs can be created with C<newCONSTSUB> or as described in
7719 L<perlsub/"Constant Functions">.
7720
7721 =cut
7722 */
7723 SV *
7724 Perl_cv_const_sv(const CV *const cv)
7725 {
7726     SV *sv;
7727     if (!cv)
7728         return NULL;
7729     if (!(SvTYPE(cv) == SVt_PVCV || SvTYPE(cv) == SVt_PVFM))
7730         return NULL;
7731     sv = CvCONST(cv) ? MUTABLE_SV(CvXSUBANY(cv).any_ptr) : NULL;
7732     if (sv && SvTYPE(sv) == SVt_PVAV) return NULL;
7733     return sv;
7734 }
7735
7736 SV *
7737 Perl_cv_const_sv_or_av(const CV * const cv)
7738 {
7739     if (!cv)
7740         return NULL;
7741     if (SvROK(cv)) return SvRV((SV *)cv);
7742     assert (SvTYPE(cv) == SVt_PVCV || SvTYPE(cv) == SVt_PVFM);
7743     return CvCONST(cv) ? MUTABLE_SV(CvXSUBANY(cv).any_ptr) : NULL;
7744 }
7745
7746 /* op_const_sv:  examine an optree to determine whether it's in-lineable.
7747  * Can be called in 2 ways:
7748  *
7749  * !allow_lex
7750  *      look for a single OP_CONST with attached value: return the value
7751  *
7752  * allow_lex && !CvCONST(cv);
7753  *
7754  *      examine the clone prototype, and if contains only a single
7755  *      OP_CONST, return the value; or if it contains a single PADSV ref-
7756  *      erencing an outer lexical, turn on CvCONST to indicate the CV is
7757  *      a candidate for "constizing" at clone time, and return NULL.
7758  */
7759
7760 static SV *
7761 S_op_const_sv(pTHX_ const OP *o, CV *cv, bool allow_lex)
7762 {
7763     SV *sv = NULL;
7764     bool padsv = FALSE;
7765
7766     assert(o);
7767     assert(cv);
7768
7769     for (; o; o = o->op_next) {
7770         const OPCODE type = o->op_type;
7771
7772         if (type == OP_NEXTSTATE || type == OP_LINESEQ
7773              || type == OP_NULL
7774              || type == OP_PUSHMARK)
7775                 continue;
7776         if (type == OP_DBSTATE)
7777                 continue;
7778         if (type == OP_LEAVESUB)
7779             break;
7780         if (sv)
7781             return NULL;
7782         if (type == OP_CONST && cSVOPo->op_sv)
7783             sv = cSVOPo->op_sv;
7784         else if (type == OP_UNDEF && !o->op_private) {
7785             sv = newSV(0);
7786             SAVEFREESV(sv);
7787         }
7788         else if (allow_lex && type == OP_PADSV) {
7789                 if (PAD_COMPNAME_FLAGS(o->op_targ) & PADNAMEt_OUTER)
7790                 {
7791                     sv = &PL_sv_undef; /* an arbitrary non-null value */
7792                     padsv = TRUE;
7793                 }
7794                 else
7795                     return NULL;
7796         }
7797         else {
7798             return NULL;
7799         }
7800     }
7801     if (padsv) {
7802         CvCONST_on(cv);
7803         return NULL;
7804     }
7805     return sv;
7806 }
7807
7808 static bool
7809 S_already_defined(pTHX_ CV *const cv, OP * const block, OP * const o,
7810                         PADNAME * const name, SV ** const const_svp)
7811 {
7812     assert (cv);
7813     assert (o || name);
7814     assert (const_svp);
7815     if ((!block
7816          )) {
7817         if (CvFLAGS(PL_compcv)) {
7818             /* might have had built-in attrs applied */
7819             const bool pureperl = !CvISXSUB(cv) && CvROOT(cv);
7820             if (CvLVALUE(PL_compcv) && ! CvLVALUE(cv) && pureperl
7821              && ckWARN(WARN_MISC))
7822             {
7823                 /* protect against fatal warnings leaking compcv */
7824                 SAVEFREESV(PL_compcv);
7825                 Perl_warner(aTHX_ packWARN(WARN_MISC), "lvalue attribute ignored after the subroutine has been defined");
7826                 SvREFCNT_inc_simple_void_NN(PL_compcv);
7827             }
7828             CvFLAGS(cv) |=
7829                 (CvFLAGS(PL_compcv) & CVf_BUILTIN_ATTRS
7830                   & ~(CVf_LVALUE * pureperl));
7831         }
7832         return FALSE;
7833     }
7834
7835     /* redundant check for speed: */
7836     if (CvCONST(cv) || ckWARN(WARN_REDEFINE)) {
7837         const line_t oldline = CopLINE(PL_curcop);
7838         SV *namesv = o
7839             ? cSVOPo->op_sv
7840             : sv_2mortal(newSVpvn_utf8(
7841                 PadnamePV(name)+1,PadnameLEN(name)-1, PadnameUTF8(name)
7842               ));
7843         if (PL_parser && PL_parser->copline != NOLINE)
7844             /* This ensures that warnings are reported at the first
7845                line of a redefinition, not the last.  */
7846             CopLINE_set(PL_curcop, PL_parser->copline);
7847         /* protect against fatal warnings leaking compcv */
7848         SAVEFREESV(PL_compcv);
7849         report_redefined_cv(namesv, cv, const_svp);
7850         SvREFCNT_inc_simple_void_NN(PL_compcv);
7851         CopLINE_set(PL_curcop, oldline);
7852     }
7853     SAVEFREESV(cv);
7854     return TRUE;
7855 }
7856
7857 CV *
7858 Perl_newMYSUB(pTHX_ I32 floor, OP *o, OP *proto, OP *attrs, OP *block)
7859 {
7860     CV **spot;
7861     SV **svspot;
7862     const char *ps;
7863     STRLEN ps_len = 0; /* init it to avoid false uninit warning from icc */
7864     U32 ps_utf8 = 0;
7865     CV *cv = NULL;
7866     CV *compcv = PL_compcv;
7867     SV *const_sv;
7868     PADNAME *name;
7869     PADOFFSET pax = o->op_targ;
7870     CV *outcv = CvOUTSIDE(PL_compcv);
7871     CV *clonee = NULL;
7872     HEK *hek = NULL;
7873     bool reusable = FALSE;
7874     OP *start = NULL;
7875 #ifdef PERL_DEBUG_READONLY_OPS
7876     OPSLAB *slab = NULL;
7877 #endif
7878
7879     PERL_ARGS_ASSERT_NEWMYSUB;
7880
7881     /* Find the pad slot for storing the new sub.
7882        We cannot use PL_comppad, as it is the pad owned by the new sub.  We
7883        need to look in CvOUTSIDE and find the pad belonging to the enclos-
7884        ing sub.  And then we need to dig deeper if this is a lexical from
7885        outside, as in:
7886            my sub foo; sub { sub foo { } }
7887      */
7888    redo:
7889     name = PadlistNAMESARRAY(CvPADLIST(outcv))[pax];
7890     if (PadnameOUTER(name) && PARENT_PAD_INDEX(name)) {
7891         pax = PARENT_PAD_INDEX(name);
7892         outcv = CvOUTSIDE(outcv);
7893         assert(outcv);
7894         goto redo;
7895     }
7896     svspot =
7897         &PadARRAY(PadlistARRAY(CvPADLIST(outcv))
7898                         [CvDEPTH(outcv) ? CvDEPTH(outcv) : 1])[pax];
7899     spot = (CV **)svspot;
7900
7901     if (!(PL_parser && PL_parser->error_count))
7902         move_proto_attr(&proto, &attrs, (GV *)PadnameSV(name));
7903
7904     if (proto) {
7905         assert(proto->op_type == OP_CONST);
7906         ps = SvPV_const(((SVOP*)proto)->op_sv, ps_len);
7907         ps_utf8 = SvUTF8(((SVOP*)proto)->op_sv);
7908     }
7909     else
7910         ps = NULL;
7911
7912     if (proto)
7913         SAVEFREEOP(proto);
7914     if (attrs)
7915         SAVEFREEOP(attrs);
7916
7917     if (PL_parser && PL_parser->error_count) {
7918         op_free(block);
7919         SvREFCNT_dec(PL_compcv);
7920         PL_compcv = 0;
7921         goto done;
7922     }
7923
7924     if (CvDEPTH(outcv) && CvCLONE(compcv)) {
7925         cv = *spot;
7926         svspot = (SV **)(spot = &clonee);
7927     }
7928     else if (PadnameIsSTATE(name) || CvDEPTH(outcv))
7929         cv = *spot;
7930     else {
7931         assert (SvTYPE(*spot) == SVt_PVCV);
7932         if (CvNAMED(*spot))
7933             hek = CvNAME_HEK(*spot);
7934         else {
7935             dVAR;
7936             U32 hash;
7937             PERL_HASH(hash, PadnamePV(name)+1, PadnameLEN(name)-1);
7938             CvNAME_HEK_set(*spot, hek =
7939                 share_hek(
7940                     PadnamePV(name)+1,
7941                     (PadnameLEN(name)-1) * (PadnameUTF8(name) ? -1 : 1),
7942                     hash
7943                 )
7944             );
7945             CvLEXICAL_on(*spot);
7946         }
7947         cv = PadnamePROTOCV(name);
7948         svspot = (SV **)(spot = &PadnamePROTOCV(name));
7949     }
7950
7951     if (block) {
7952         /* This makes sub {}; work as expected.  */
7953         if (block->op_type == OP_STUB) {
7954             const line_t l = PL_parser->copline;
7955             op_free(block);
7956             block = newSTATEOP(0, NULL, 0);
7957             PL_parser->copline = l;
7958         }
7959         block = CvLVALUE(compcv)
7960              || (cv && CvLVALUE(cv) && !CvROOT(cv) && !CvXSUB(cv))
7961                    ? newUNOP(OP_LEAVESUBLV, 0,
7962                              op_lvalue(scalarseq(block), OP_LEAVESUBLV))
7963                    : newUNOP(OP_LEAVESUB, 0, scalarseq(block));
7964         start = LINKLIST(block);
7965         block->op_next = 0;
7966         if (ps && !*ps && !attrs && !CvLVALUE(compcv))
7967             const_sv = S_op_const_sv(aTHX_ start, compcv, FALSE);
7968         else
7969             const_sv = NULL;
7970     }
7971     else
7972         const_sv = NULL;
7973
7974     if (cv) {
7975         const bool exists = CvROOT(cv) || CvXSUB(cv);
7976
7977         /* if the subroutine doesn't exist and wasn't pre-declared
7978          * with a prototype, assume it will be AUTOLOADed,
7979          * skipping the prototype check
7980          */
7981         if (exists || SvPOK(cv))
7982             cv_ckproto_len_flags(cv, (GV *)PadnameSV(name), ps, ps_len,
7983                                  ps_utf8);
7984         /* already defined? */
7985         if (exists) {
7986             if (S_already_defined(aTHX_ cv,block,NULL,name,&const_sv))
7987                 cv = NULL;
7988             else {
7989                 if (attrs) goto attrs;
7990                 /* just a "sub foo;" when &foo is already defined */
7991                 SAVEFREESV(compcv);
7992                 goto done;
7993             }
7994         }
7995         else if (CvDEPTH(outcv) && CvCLONE(compcv)) {
7996             cv = NULL;
7997             reusable = TRUE;
7998         }
7999     }
8000     if (const_sv) {
8001         SvREFCNT_inc_simple_void_NN(const_sv);
8002         SvFLAGS(const_sv) |= SVs_PADTMP;
8003         if (cv) {
8004             assert(!CvROOT(cv) && !CvCONST(cv));
8005             cv_forget_slab(cv);
8006         }
8007         else {
8008             cv = MUTABLE_CV(newSV_type(SVt_PVCV));
8009             CvFILE_set_from_cop(cv, PL_curcop);
8010             CvSTASH_set(cv, PL_curstash);
8011             *spot = cv;
8012         }
8013         sv_setpvs(MUTABLE_SV(cv), "");  /* prototype is "" */
8014         CvXSUBANY(cv).any_ptr = const_sv;
8015         CvXSUB(cv) = const_sv_xsub;
8016         CvCONST_on(cv);
8017         CvISXSUB_on(cv);
8018         PoisonPADLIST(cv);
8019         CvFLAGS(cv) |= CvMETHOD(compcv);
8020         op_free(block);
8021         SvREFCNT_dec(compcv);
8022         PL_compcv = NULL;
8023         goto setname;
8024     }
8025     /* Checking whether outcv is CvOUTSIDE(compcv) is not sufficient to
8026        determine whether this sub definition is in the same scope as its
8027        declaration.  If this sub definition is inside an inner named pack-
8028        age sub (my sub foo; sub bar { sub foo { ... } }), outcv points to
8029        the package sub.  So check PadnameOUTER(name) too.
8030      */
8031     if (outcv == CvOUTSIDE(compcv) && !PadnameOUTER(name)) { 
8032         assert(!CvWEAKOUTSIDE(compcv));
8033         SvREFCNT_dec(CvOUTSIDE(compcv));
8034         CvWEAKOUTSIDE_on(compcv);
8035     }
8036     /* XXX else do we have a circular reference? */
8037     if (cv) {   /* must reuse cv in case stub is referenced elsewhere */
8038         /* transfer PL_compcv to cv */
8039         if (block
8040         ) {
8041             cv_flags_t preserved_flags =
8042                 CvFLAGS(cv) & (CVf_BUILTIN_ATTRS|CVf_NAMED);
8043             PADLIST *const temp_padl = CvPADLIST(cv);
8044             CV *const temp_cv = CvOUTSIDE(cv);
8045             const cv_flags_t other_flags =
8046                 CvFLAGS(cv) & (CVf_SLABBED|CVf_WEAKOUTSIDE);
8047             OP * const cvstart = CvSTART(cv);
8048
8049             SvPOK_off(cv);
8050             CvFLAGS(cv) =
8051                 CvFLAGS(compcv) | preserved_flags;
8052             CvOUTSIDE(cv) = CvOUTSIDE(compcv);
8053             CvOUTSIDE_SEQ(cv) = CvOUTSIDE_SEQ(compcv);
8054             CvPADLIST_set(cv, CvPADLIST(compcv));
8055             CvOUTSIDE(compcv) = temp_cv;
8056             CvPADLIST_set(compcv, temp_padl);
8057             CvSTART(cv) = CvSTART(compcv);
8058             CvSTART(compcv) = cvstart;
8059             CvFLAGS(compcv) &= ~(CVf_SLABBED|CVf_WEAKOUTSIDE);
8060             CvFLAGS(compcv) |= other_flags;
8061
8062             if (CvFILE(cv) && CvDYNFILE(cv)) {
8063                 Safefree(CvFILE(cv));
8064             }
8065
8066             /* inner references to compcv must be fixed up ... */
8067             pad_fixup_inner_anons(CvPADLIST(cv), compcv, cv);
8068             if (PERLDB_INTER)/* Advice debugger on the new sub. */
8069               ++PL_sub_generation;
8070         }
8071         else {
8072             /* Might have had built-in attributes applied -- propagate them. */
8073             CvFLAGS(cv) |= (CvFLAGS(compcv) & CVf_BUILTIN_ATTRS);
8074         }
8075         /* ... before we throw it away */
8076         SvREFCNT_dec(compcv);
8077         PL_compcv = compcv = cv;
8078     }
8079     else {
8080         cv = compcv;
8081         *spot = cv;
8082     }
8083    setname:
8084     CvLEXICAL_on(cv);
8085     if (!CvNAME_HEK(cv)) {
8086         if (hek) (void)share_hek_hek(hek);
8087         else {
8088             dVAR;
8089             U32 hash;
8090             PERL_HASH(hash, PadnamePV(name)+1, PadnameLEN(name)-1);
8091             hek = share_hek(PadnamePV(name)+1,
8092                       (PadnameLEN(name)-1) * (PadnameUTF8(name) ? -1 : 1),
8093                       hash);
8094         }
8095         CvNAME_HEK_set(cv, hek);
8096     }
8097     if (const_sv) goto clone;
8098
8099     CvFILE_set_from_cop(cv, PL_curcop);
8100     CvSTASH_set(cv, PL_curstash);
8101
8102     if (ps) {
8103         sv_setpvn(MUTABLE_SV(cv), ps, ps_len);
8104         if ( ps_utf8 ) SvUTF8_on(MUTABLE_SV(cv));
8105     }
8106
8107     if (!block)
8108         goto attrs;
8109
8110     /* If we assign an optree to a PVCV, then we've defined a subroutine that
8111        the debugger could be able to set a breakpoint in, so signal to
8112        pp_entereval that it should not throw away any saved lines at scope
8113        exit.  */
8114        
8115     PL_breakable_sub_gen++;
8116     CvROOT(cv) = block;
8117     CvROOT(cv)->op_private |= OPpREFCOUNTED;
8118     OpREFCNT_set(CvROOT(cv), 1);
8119     /* The cv no longer needs to hold a refcount on the slab, as CvROOT
8120        itself has a refcount. */
8121     CvSLABBED_off(cv);
8122     OpslabREFCNT_dec_padok((OPSLAB *)CvSTART(cv));
8123 #ifdef PERL_DEBUG_READONLY_OPS
8124     slab = (OPSLAB *)CvSTART(cv);
8125 #endif
8126     CvSTART(cv) = start;
8127     CALL_PEEP(start);
8128     finalize_optree(CvROOT(cv));
8129     S_prune_chain_head(&CvSTART(cv));
8130
8131     /* now that optimizer has done its work, adjust pad values */
8132
8133     pad_tidy(CvCLONE(cv) ? padtidy_SUBCLONE : padtidy_SUB);
8134
8135   attrs:
8136     if (attrs) {
8137         /* Need to do a C<use attributes $stash_of_cv,\&cv,@attrs>. */
8138         apply_attrs(PL_curstash, MUTABLE_SV(cv), attrs);
8139     }
8140
8141     if (block) {
8142         if (PERLDB_SUBLINE && PL_curstash != PL_debstash) {
8143             SV * const tmpstr = sv_newmortal();
8144             GV * const db_postponed = gv_fetchpvs("DB::postponed",
8145                                                   GV_ADDMULTI, SVt_PVHV);
8146             HV *hv;
8147             SV * const sv = Perl_newSVpvf(aTHX_ "%s:%ld-%ld",
8148                                           CopFILE(PL_curcop),
8149                                           (long)PL_subline,
8150                                           (long)CopLINE(PL_curcop));
8151             if (HvNAME_HEK(PL_curstash)) {
8152                 sv_sethek(tmpstr, HvNAME_HEK(PL_curstash));
8153                 sv_catpvs(tmpstr, "::");
8154             }
8155             else sv_setpvs(tmpstr, "__ANON__::");
8156             sv_catpvn_flags(tmpstr, PadnamePV(name)+1, PadnameLEN(name)-1,
8157                             PadnameUTF8(name) ? SV_CATUTF8 : SV_CATBYTES);
8158             (void)hv_store(GvHV(PL_DBsub), SvPVX_const(tmpstr),
8159                     SvUTF8(tmpstr) ? -(I32)SvCUR(tmpstr) : (I32)SvCUR(tmpstr), sv, 0);
8160             hv = GvHVn(db_postponed);
8161             if (HvTOTALKEYS(hv) > 0 && hv_exists(hv, SvPVX_const(tmpstr), SvUTF8(tmpstr) ? -(I32)SvCUR(tmpstr) : (I32)SvCUR(tmpstr))) {
8162                 CV * const pcv = GvCV(db_postponed);
8163                 if (pcv) {
8164                     dSP;
8165                     PUSHMARK(SP);
8166                     XPUSHs(tmpstr);
8167                     PUTBACK;
8168                     call_sv(MUTABLE_SV(pcv), G_DISCARD);
8169                 }
8170             }
8171         }
8172     }
8173
8174   clone:
8175     if (clonee) {
8176         assert(CvDEPTH(outcv));
8177         spot = (CV **)
8178             &PadARRAY(PadlistARRAY(CvPADLIST(outcv))[CvDEPTH(outcv)])[pax];
8179         if (reusable) cv_clone_into(clonee, *spot);
8180         else *spot = cv_clone(clonee);
8181         SvREFCNT_dec_NN(clonee);
8182         cv = *spot;
8183     }
8184     if (CvDEPTH(outcv) && !reusable && PadnameIsSTATE(name)) {
8185         PADOFFSET depth = CvDEPTH(outcv);
8186         while (--depth) {
8187             SV *oldcv;
8188             svspot = &PadARRAY(PadlistARRAY(CvPADLIST(outcv))[depth])[pax];
8189             oldcv = *svspot;
8190             *svspot = SvREFCNT_inc_simple_NN(cv);
8191             SvREFCNT_dec(oldcv);
8192         }
8193     }
8194
8195   done:
8196     if (PL_parser)
8197         PL_parser->copline = NOLINE;
8198     LEAVE_SCOPE(floor);
8199 #ifdef PERL_DEBUG_READONLY_OPS
8200     if (slab)
8201         Slab_to_ro(slab);
8202 #endif
8203     op_free(o);
8204     return cv;
8205 }
8206
8207 /* _x = extended */
8208 CV *
8209 Perl_newATTRSUB_x(pTHX_ I32 floor, OP *o, OP *proto, OP *attrs,
8210                             OP *block, bool o_is_gv)
8211 {
8212     GV *gv;
8213     const char *ps;
8214     STRLEN ps_len = 0; /* init it to avoid false uninit warning from icc */
8215     U32 ps_utf8 = 0;
8216     CV *cv = NULL;
8217     SV *const_sv;
8218     const bool ec = PL_parser && PL_parser->error_count;
8219     /* If the subroutine has no body, no attributes, and no builtin attributes
8220        then it's just a sub declaration, and we may be able to get away with
8221        storing with a placeholder scalar in the symbol table, rather than a
8222        full CV.  If anything is present then it will take a full CV to
8223        store it.  */
8224     const I32 gv_fetch_flags
8225         = ec ? GV_NOADD_NOINIT :
8226         (block || attrs || (CvFLAGS(PL_compcv) & CVf_BUILTIN_ATTRS))
8227         ? GV_ADDMULTI : GV_ADDMULTI | GV_NOINIT;
8228     STRLEN namlen = 0;
8229     const char * const name =
8230          o ? SvPV_const(o_is_gv ? (SV *)o : cSVOPo->op_sv, namlen) : NULL;
8231     bool has_name;
8232     bool name_is_utf8 = o && !o_is_gv && SvUTF8(cSVOPo->op_sv);
8233     bool evanescent = FALSE;
8234     OP *start = NULL;
8235 #ifdef PERL_DEBUG_READONLY_OPS
8236     OPSLAB *slab = NULL;
8237 #endif
8238
8239     if (o_is_gv) {
8240         gv = (GV*)o;
8241         o = NULL;
8242         has_name = TRUE;
8243     } else if (name) {
8244         /* Try to optimise and avoid creating a GV.  Instead, the CV’s name
8245            hek and CvSTASH pointer together can imply the GV.  If the name
8246            contains a package name, then GvSTASH(CvGV(cv)) may differ from
8247            CvSTASH, so forego the optimisation if we find any.
8248            Also, we may be called from load_module at run time, so
8249            PL_curstash (which sets CvSTASH) may not point to the stash the
8250            sub is stored in.  */
8251         const I32 flags =
8252            ec ? GV_NOADD_NOINIT
8253               :   PL_curstash != CopSTASH(PL_curcop)
8254                || memchr(name, ':', namlen) || memchr(name, '\'', namlen)
8255                     ? gv_fetch_flags
8256                     : GV_ADDMULTI | GV_NOINIT | GV_NOTQUAL;
8257         gv = gv_fetchsv(cSVOPo->op_sv, flags, SVt_PVCV);
8258         has_name = TRUE;
8259     } else if (PERLDB_NAMEANON && CopLINE(PL_curcop)) {
8260         SV * const sv = sv_newmortal();
8261         Perl_sv_setpvf(aTHX_ sv, "%s[%s:%"IVdf"]",
8262                        PL_curstash ? "__ANON__" : "__ANON__::__ANON__",
8263                        CopFILE(PL_curcop), (IV)CopLINE(PL_curcop));
8264         gv = gv_fetchsv(sv, gv_fetch_flags, SVt_PVCV);
8265         has_name = TRUE;
8266     } else if (PL_curstash) {
8267         gv = gv_fetchpvs("__ANON__", gv_fetch_flags, SVt_PVCV);
8268         has_name = FALSE;
8269     } else {
8270         gv = gv_fetchpvs("__ANON__::__ANON__", gv_fetch_flags, SVt_PVCV);
8271         has_name = FALSE;
8272     }
8273     if (!ec) {
8274         if (isGV(gv)) {
8275             move_proto_attr(&proto, &attrs, gv);
8276         } else {
8277             assert(cSVOPo);
8278             move_proto_attr(&proto, &attrs, (GV *)cSVOPo->op_sv);
8279         }
8280     }
8281
8282     if (proto) {
8283         assert(proto->op_type == OP_CONST);
8284         ps = SvPV_const(((SVOP*)proto)->op_sv, ps_len);
8285         ps_utf8 = SvUTF8(((SVOP*)proto)->op_sv);
8286     }
8287     else
8288         ps = NULL;
8289
8290     if (o)
8291         SAVEFREEOP(o);
8292     if (proto)
8293         SAVEFREEOP(proto);
8294     if (attrs)
8295         SAVEFREEOP(attrs);
8296
8297     if (ec) {
8298         op_free(block);
8299         if (name) SvREFCNT_dec(PL_compcv);
8300         else cv = PL_compcv;
8301         PL_compcv = 0;
8302         if (name && block) {
8303             const char *s = strrchr(name, ':');
8304             s = s ? s+1 : name;
8305             if (strEQ(s, "BEGIN")) {
8306                 if (PL_in_eval & EVAL_KEEPERR)
8307                     Perl_croak_nocontext("BEGIN not safe after errors--compilation aborted");
8308                 else {
8309                     SV * const errsv = ERRSV;
8310                     /* force display of errors found but not reported */
8311                     sv_catpvs(errsv, "BEGIN not safe after errors--compilation aborted");
8312                     Perl_croak_nocontext("%"SVf, SVfARG(errsv));
8313                 }
8314             }
8315         }
8316         goto done;
8317     }
8318
8319     if (!block && SvTYPE(gv) != SVt_PVGV) {
8320       /* If we are not defining a new sub and the existing one is not a
8321          full GV + CV... */
8322       if (attrs || (CvFLAGS(PL_compcv) & CVf_BUILTIN_ATTRS)) {
8323         /* We are applying attributes to an existing sub, so we need it
8324            upgraded if it is a constant.  */
8325         if (SvROK(gv) && SvTYPE(SvRV(gv)) != SVt_PVCV)
8326             gv_init_pvn(gv, PL_curstash, name, namlen,
8327                         SVf_UTF8 * name_is_utf8);
8328       }
8329       else {                    /* Maybe prototype now, and had at maximum
8330                                    a prototype or const/sub ref before.  */
8331         if (SvTYPE(gv) > SVt_NULL) {
8332             cv_ckproto_len_flags((const CV *)gv,
8333                                  o ? (const GV *)cSVOPo->op_sv : NULL, ps,
8334                                  ps_len, ps_utf8);
8335         }
8336         if (!SvROK(gv)) {
8337           if (ps) {
8338             sv_setpvn(MUTABLE_SV(gv), ps, ps_len);
8339             if ( ps_utf8 ) SvUTF8_on(MUTABLE_SV(gv));
8340           }
8341           else
8342             sv_setiv(MUTABLE_SV(gv), -1);
8343         }
8344
8345         SvREFCNT_dec(PL_compcv);
8346         cv = PL_compcv = NULL;
8347         goto done;
8348       }
8349     }
8350
8351     cv = (!name || (isGV(gv) && GvCVGEN(gv)))
8352         ? NULL
8353         : isGV(gv)
8354             ? GvCV(gv)
8355             : SvROK(gv) && SvTYPE(SvRV(gv)) == SVt_PVCV
8356                 ? (CV *)SvRV(gv)
8357                 : NULL;
8358
8359     if (block) {
8360         /* This makes sub {}; work as expected.  */
8361         if (block->op_type == OP_STUB) {
8362             const line_t l = PL_parser->copline;
8363             op_free(block);
8364             block = newSTATEOP(0, NULL, 0);
8365             PL_parser->copline = l;
8366         }
8367         block = CvLVALUE(PL_compcv)
8368              || (cv && CvLVALUE(cv) && !CvROOT(cv) && !CvXSUB(cv)
8369                     && (!isGV(gv) || !GvASSUMECV(gv)))
8370                    ? newUNOP(OP_LEAVESUBLV, 0,
8371                              op_lvalue(scalarseq(block), OP_LEAVESUBLV))
8372                    : newUNOP(OP_LEAVESUB, 0, scalarseq(block));
8373         start = LINKLIST(block);
8374         block->op_next = 0;
8375         if (ps && !*ps && !attrs && !CvLVALUE(PL_compcv))
8376             const_sv =
8377                 S_op_const_sv(aTHX_ start, PL_compcv, CvCLONE(PL_compcv));
8378         else
8379             const_sv = NULL;
8380     }
8381     else
8382         const_sv = NULL;
8383
8384     if (SvPOK(gv) || (SvROK(gv) && SvTYPE(SvRV(gv)) != SVt_PVCV)) {
8385         assert (block);
8386         cv_ckproto_len_flags((const CV *)gv,
8387                              o ? (const GV *)cSVOPo->op_sv : NULL, ps,
8388                              ps_len, ps_utf8|CV_CKPROTO_CURSTASH);
8389         if (SvROK(gv)) {
8390             /* All the other code for sub redefinition warnings expects the
8391                clobbered sub to be a CV.  Instead of making all those code
8392                paths more complex, just inline the RV version here.  */
8393             const line_t oldline = CopLINE(PL_curcop);
8394             assert(IN_PERL_COMPILETIME);
8395             if (PL_parser && PL_parser->copline != NOLINE)
8396                 /* This ensures that warnings are reported at the first
8397                    line of a redefinition, not the last.  */
8398                 CopLINE_set(PL_curcop, PL_parser->copline);
8399             /* protect against fatal warnings leaking compcv */
8400             SAVEFREESV(PL_compcv);
8401
8402             if (ckWARN(WARN_REDEFINE)
8403              || (  ckWARN_d(WARN_REDEFINE)
8404                 && (  !const_sv || SvRV(gv) == const_sv
8405                    || sv_cmp(SvRV(gv), const_sv)  )))
8406                 Perl_warner(aTHX_ packWARN(WARN_REDEFINE),
8407                           "Constant subroutine %"SVf" redefined",
8408                           SVfARG(cSVOPo->op_sv));
8409
8410             SvREFCNT_inc_simple_void_NN(PL_compcv);
8411             CopLINE_set(PL_curcop, oldline);
8412             SvREFCNT_dec(SvRV(gv));
8413         }
8414     }
8415
8416     if (cv) {
8417         const bool exists = CvROOT(cv) || CvXSUB(cv);
8418
8419         /* if the subroutine doesn't exist and wasn't pre-declared
8420          * with a prototype, assume it will be AUTOLOADed,
8421          * skipping the prototype check
8422          */
8423         if (exists || SvPOK(cv))
8424             cv_ckproto_len_flags(cv, gv, ps, ps_len, ps_utf8);
8425         /* already defined (or promised)? */
8426         if (exists || (isGV(gv) && GvASSUMECV(gv))) {
8427             if (S_already_defined(aTHX_ cv, block, o, NULL, &const_sv))
8428                 cv = NULL;
8429             else {
8430                 if (attrs) goto attrs;
8431                 /* just a "sub foo;" when &foo is already defined */
8432                 SAVEFREESV(PL_compcv);
8433                 goto done;
8434             }
8435         }
8436     }
8437     if (const_sv) {
8438         SvREFCNT_inc_simple_void_NN(const_sv);
8439         SvFLAGS(const_sv) |= SVs_PADTMP;
8440         if (cv) {
8441             assert(!CvROOT(cv) && !CvCONST(cv));
8442             cv_forget_slab(cv);
8443             sv_setpvs(MUTABLE_SV(cv), "");  /* prototype is "" */
8444             CvXSUBANY(cv).any_ptr = const_sv;
8445             CvXSUB(cv) = const_sv_xsub;
8446             CvCONST_on(cv);
8447             CvISXSUB_on(cv);
8448             PoisonPADLIST(cv);
8449             CvFLAGS(cv) |= CvMETHOD(PL_compcv);
8450         }
8451         else {
8452             if (isGV(gv) || CvMETHOD(PL_compcv)) {
8453                 if (name && isGV(gv))
8454                     GvCV_set(gv, NULL);
8455                 cv = newCONSTSUB_flags(
8456                     NULL, name, namlen, name_is_utf8 ? SVf_UTF8 : 0,
8457                     const_sv
8458                 );
8459                 CvFLAGS(cv) |= CvMETHOD(PL_compcv);
8460             }
8461             else {
8462                 if (!SvROK(gv)) {
8463                     SV_CHECK_THINKFIRST_COW_DROP((SV *)gv);
8464                     prepare_SV_for_RV((SV *)gv);
8465                     SvOK_off((SV *)gv);
8466                     SvROK_on(gv);
8467                 }
8468                 SvRV_set(gv, const_sv);
8469             }
8470         }
8471         op_free(block);
8472         SvREFCNT_dec(PL_compcv);
8473         PL_compcv = NULL;
8474         goto done;
8475     }
8476     if (cv) {                           /* must reuse cv if autoloaded */
8477         /* transfer PL_compcv to cv */
8478         if (block
8479         ) {
8480             cv_flags_t existing_builtin_attrs = CvFLAGS(cv) & CVf_BUILTIN_ATTRS;
8481             PADLIST *const temp_av = CvPADLIST(cv);
8482             CV *const temp_cv = CvOUTSIDE(cv);
8483             const cv_flags_t other_flags =
8484                 CvFLAGS(cv) & (CVf_SLABBED|CVf_WEAKOUTSIDE);
8485             OP * const cvstart = CvSTART(cv);
8486
8487             if (isGV(gv)) {
8488                 CvGV_set(cv,gv);
8489                 assert(!CvCVGV_RC(cv));
8490                 assert(CvGV(cv) == gv);
8491             }
8492             else {
8493                 dVAR;
8494                 U32 hash;
8495                 PERL_HASH(hash, name, namlen);
8496                 CvNAME_HEK_set(cv,
8497                                share_hek(name,
8498                                          name_is_utf8
8499                                             ? -(SSize_t)namlen
8500                                             :  (SSize_t)namlen,
8501                                          hash));
8502             }
8503
8504             SvPOK_off(cv);
8505             CvFLAGS(cv) = CvFLAGS(PL_compcv) | existing_builtin_attrs
8506                                              | CvNAMED(cv);
8507             CvOUTSIDE(cv) = CvOUTSIDE(PL_compcv);
8508             CvOUTSIDE_SEQ(cv) = CvOUTSIDE_SEQ(PL_compcv);
8509             CvPADLIST_set(cv,CvPADLIST(PL_compcv));
8510             CvOUTSIDE(PL_compcv) = temp_cv;
8511             CvPADLIST_set(PL_compcv, temp_av);
8512             CvSTART(cv) = CvSTART(PL_compcv);
8513             CvSTART(PL_compcv) = cvstart;
8514             CvFLAGS(PL_compcv) &= ~(CVf_SLABBED|CVf_WEAKOUTSIDE);
8515             CvFLAGS(PL_compcv) |= other_flags;
8516
8517             if (CvFILE(cv) && CvDYNFILE(cv)) {
8518                 Safefree(CvFILE(cv));
8519     }
8520             CvFILE_set_from_cop(cv, PL_curcop);
8521             CvSTASH_set(cv, PL_curstash);
8522
8523             /* inner references to PL_compcv must be fixed up ... */
8524             pad_fixup_inner_anons(CvPADLIST(cv), PL_compcv, cv);
8525             if (PERLDB_INTER)/* Advice debugger on the new sub. */
8526               ++PL_sub_generation;
8527         }
8528         else {
8529             /* Might have had built-in attributes applied -- propagate them. */
8530             CvFLAGS(cv) |= (CvFLAGS(PL_compcv) & CVf_BUILTIN_ATTRS);
8531         }
8532         /* ... before we throw it away */
8533         SvREFCNT_dec(PL_compcv);
8534         PL_compcv = cv;
8535     }
8536     else {
8537         cv = PL_compcv;
8538         if (name && isGV(gv)) {
8539             GvCV_set(gv, cv);
8540             GvCVGEN(gv) = 0;
8541             if (HvENAME_HEK(GvSTASH(gv)))
8542                 /* sub Foo::bar { (shift)+1 } */
8543                 gv_method_changed(gv);
8544         }
8545         else if (name) {
8546             if (!SvROK(gv)) {
8547                 SV_CHECK_THINKFIRST_COW_DROP((SV *)gv);
8548                 prepare_SV_for_RV((SV *)gv);
8549                 SvOK_off((SV *)gv);
8550                 SvROK_on(gv);
8551             }
8552             SvRV_set(gv, (SV *)cv);
8553         }
8554     }
8555     if (!CvHASGV(cv)) {
8556         if (isGV(gv)) CvGV_set(cv, gv);
8557         else {
8558             dVAR;
8559             U32 hash;
8560             PERL_HASH(hash, name, namlen);
8561             CvNAME_HEK_set(cv, share_hek(name,
8562                                          name_is_utf8
8563                                             ? -(SSize_t)namlen
8564                                             :  (SSize_t)namlen,
8565                                          hash));
8566         }
8567         CvFILE_set_from_cop(cv, PL_curcop);
8568         CvSTASH_set(cv, PL_curstash);
8569     }
8570
8571     if (ps) {
8572         sv_setpvn(MUTABLE_SV(cv), ps, ps_len);
8573         if ( ps_utf8 ) SvUTF8_on(MUTABLE_SV(cv));
8574     }
8575
8576     if (!block)
8577         goto attrs;
8578
8579     /* If we assign an optree to a PVCV, then we've defined a subroutine that
8580        the debugger could be able to set a breakpoint in, so signal to
8581        pp_entereval that it should not throw away any saved lines at scope
8582        exit.  */
8583        
8584     PL_breakable_sub_gen++;
8585     CvROOT(cv) = block;
8586     CvROOT(cv)->op_private |= OPpREFCOUNTED;
8587     OpREFCNT_set(CvROOT(cv), 1);
8588     /* The cv no longer needs to hold a refcount on the slab, as CvROOT
8589        itself has a refcount. */
8590     CvSLABBED_off(cv);
8591     OpslabREFCNT_dec_padok((OPSLAB *)CvSTART(cv));
8592 #ifdef PERL_DEBUG_READONLY_OPS
8593     slab = (OPSLAB *)CvSTART(cv);
8594 #endif
8595     CvSTART(cv) = start;
8596     CALL_PEEP(start);
8597     finalize_optree(CvROOT(cv));
8598     S_prune_chain_head(&CvSTART(cv));
8599
8600     /* now that optimizer has done its work, adjust pad values */
8601
8602     pad_tidy(CvCLONE(cv) ? padtidy_SUBCLONE : padtidy_SUB);
8603
8604   attrs:
8605     if (attrs) {
8606         /* Need to do a C<use attributes $stash_of_cv,\&cv,@attrs>. */
8607         HV *stash = name && !CvNAMED(cv) && GvSTASH(CvGV(cv))
8608                         ? GvSTASH(CvGV(cv))
8609                         : PL_curstash;
8610         if (!name) SAVEFREESV(cv);
8611         apply_attrs(stash, MUTABLE_SV(cv), attrs);
8612         if (!name) SvREFCNT_inc_simple_void_NN(cv);
8613     }
8614
8615     if (block && has_name) {
8616         if (PERLDB_SUBLINE && PL_curstash != PL_debstash) {
8617             SV * const tmpstr = cv_name(cv,NULL,0);
8618             GV * const db_postponed = gv_fetchpvs("DB::postponed",
8619                                                   GV_ADDMULTI, SVt_PVHV);
8620             HV *hv;
8621             SV * const sv = Perl_newSVpvf(aTHX_ "%s:%ld-%ld",
8622                                           CopFILE(PL_curcop),
8623                                           (long)PL_subline,
8624                                           (long)CopLINE(PL_curcop));
8625             (void)hv_store(GvHV(PL_DBsub), SvPVX_const(tmpstr),
8626                     SvUTF8(tmpstr) ? -(I32)SvCUR(tmpstr) : (I32)SvCUR(tmpstr), sv, 0);
8627             hv = GvHVn(db_postponed);
8628             if (HvTOTALKEYS(hv) > 0 && hv_exists(hv, SvPVX_const(tmpstr), SvUTF8(tmpstr) ? -(I32)SvCUR(tmpstr) : (I32)SvCUR(tmpstr))) {
8629                 CV * const pcv = GvCV(db_postponed);
8630                 if (pcv) {
8631                     dSP;
8632                     PUSHMARK(SP);
8633                     XPUSHs(tmpstr);
8634                     PUTBACK;
8635                     call_sv(MUTABLE_SV(pcv), G_DISCARD);
8636                 }
8637             }
8638         }
8639
8640         if (name) {
8641             if (PL_parser && PL_parser->error_count)
8642                 clear_special_blocks(name, gv, cv);
8643             else
8644                 evanescent =
8645                     process_special_blocks(floor, name, gv, cv);
8646         }
8647     }
8648
8649   done:
8650     if (PL_parser)
8651         PL_parser->copline = NOLINE;
8652     LEAVE_SCOPE(floor);
8653     if (!evanescent) {
8654 #ifdef PERL_DEBUG_READONLY_OPS
8655       if (slab)
8656         Slab_to_ro(slab);
8657 #endif
8658       if (cv && name && CvOUTSIDE(cv) && !CvEVAL(CvOUTSIDE(cv)))
8659         pad_add_weakref(cv);
8660     }
8661     return cv;
8662 }
8663
8664 STATIC void
8665 S_clear_special_blocks(pTHX_ const char *const fullname,
8666                        GV *const gv, CV *const cv) {
8667     const char *colon;
8668     const char *name;
8669
8670     PERL_ARGS_ASSERT_CLEAR_SPECIAL_BLOCKS;
8671
8672     colon = strrchr(fullname,':');
8673     name = colon ? colon + 1 : fullname;
8674
8675     if ((*name == 'B' && strEQ(name, "BEGIN"))
8676         || (*name == 'E' && strEQ(name, "END"))
8677         || (*name == 'U' && strEQ(name, "UNITCHECK"))
8678         || (*name == 'C' && strEQ(name, "CHECK"))
8679         || (*name == 'I' && strEQ(name, "INIT"))) {
8680         if (!isGV(gv)) {
8681             (void)CvGV(cv);
8682             assert(isGV(gv));
8683         }
8684         GvCV_set(gv, NULL);
8685         SvREFCNT_dec_NN(MUTABLE_SV(cv));
8686     }
8687 }
8688
8689 /* Returns true if the sub has been freed.  */
8690 STATIC bool
8691 S_process_special_blocks(pTHX_ I32 floor, const char *const fullname,
8692                          GV *const gv,
8693                          CV *const cv)
8694 {
8695     const char *const colon = strrchr(fullname,':');
8696     const char *const name = colon ? colon + 1 : fullname;
8697
8698     PERL_ARGS_ASSERT_PROCESS_SPECIAL_BLOCKS;
8699
8700     if (*name == 'B') {
8701         if (strEQ(name, "BEGIN")) {
8702             const I32 oldscope = PL_scopestack_ix;
8703             dSP;
8704             (void)CvGV(cv);
8705             if (floor) LEAVE_SCOPE(floor);
8706             ENTER;
8707             PUSHSTACKi(PERLSI_REQUIRE);
8708             SAVECOPFILE(&PL_compiling);
8709             SAVECOPLINE(&PL_compiling);
8710             SAVEVPTR(PL_curcop);
8711
8712             DEBUG_x( dump_sub(gv) );
8713             Perl_av_create_and_push(aTHX_ &PL_beginav, MUTABLE_SV(cv));
8714             GvCV_set(gv,0);             /* cv has been hijacked */
8715             call_list(oldscope, PL_beginav);
8716
8717             POPSTACK;
8718             LEAVE;
8719             return !PL_savebegin;
8720         }
8721         else
8722             return FALSE;
8723     } else {
8724         if (*name == 'E') {
8725             if strEQ(name, "END") {
8726                 DEBUG_x( dump_sub(gv) );
8727                 Perl_av_create_and_unshift_one(aTHX_ &PL_endav, MUTABLE_SV(cv));
8728             } else
8729                 return FALSE;
8730         } else if (*name == 'U') {
8731             if (strEQ(name, "UNITCHECK")) {
8732                 /* It's never too late to run a unitcheck block */
8733                 Perl_av_create_and_unshift_one(aTHX_ &PL_unitcheckav, MUTABLE_SV(cv));
8734             }
8735             else
8736                 return FALSE;
8737         } else if (*name == 'C') {
8738             if (strEQ(name, "CHECK")) {
8739                 if (PL_main_start)
8740                     /* diag_listed_as: Too late to run %s block */
8741                     Perl_ck_warner(aTHX_ packWARN(WARN_VOID),
8742                                    "Too late to run CHECK block");
8743                 Perl_av_create_and_unshift_one(aTHX_ &PL_checkav, MUTABLE_SV(cv));
8744             }
8745             else
8746                 return FALSE;
8747         } else if (*name == 'I') {
8748             if (strEQ(name, "INIT")) {
8749                 if (PL_main_start)
8750                     /* diag_listed_as: Too late to run %s block */
8751                     Perl_ck_warner(aTHX_ packWARN(WARN_VOID),
8752                                    "Too late to run INIT block");
8753                 Perl_av_create_and_push(aTHX_ &PL_initav, MUTABLE_SV(cv));
8754             }
8755             else
8756                 return FALSE;
8757         } else
8758             return FALSE;
8759         DEBUG_x( dump_sub(gv) );
8760         (void)CvGV(cv);
8761         GvCV_set(gv,0);         /* cv has been hijacked */
8762         return FALSE;
8763     }
8764 }
8765
8766 /*
8767 =for apidoc newCONSTSUB
8768
8769 See L</newCONSTSUB_flags>.
8770
8771 =cut
8772 */
8773
8774 CV *
8775 Perl_newCONSTSUB(pTHX_ HV *stash, const char *name, SV *sv)
8776 {
8777     return newCONSTSUB_flags(stash, name, name ? strlen(name) : 0, 0, sv);
8778 }
8779
8780 /*
8781 =for apidoc newCONSTSUB_flags
8782
8783 Creates a constant sub equivalent to Perl S<C<sub FOO () { 123 }>> which is
8784 eligible for inlining at compile-time.
8785
8786 Currently, the only useful value for C<flags> is C<SVf_UTF8>.
8787
8788 The newly created subroutine takes ownership of a reference to the passed in
8789 SV.
8790
8791 Passing C<NULL> for SV creates a constant sub equivalent to S<C<sub BAR () {}>>,
8792 which won't be called if used as a destructor, but will suppress the overhead
8793 of a call to C<AUTOLOAD>.  (This form, however, isn't eligible for inlining at
8794 compile time.)
8795
8796 =cut
8797 */
8798
8799 CV *
8800 Perl_newCONSTSUB_flags(pTHX_ HV *stash, const char *name, STRLEN len,
8801                              U32 flags, SV *sv)
8802 {
8803     CV* cv;
8804     const char *const file = CopFILE(PL_curcop);
8805
8806     ENTER;
8807
8808     if (IN_PERL_RUNTIME) {
8809         /* at runtime, it's not safe to manipulate PL_curcop: it may be
8810          * an op shared between threads. Use a non-shared COP for our
8811          * dirty work */
8812          SAVEVPTR(PL_curcop);
8813          SAVECOMPILEWARNINGS();
8814          PL_compiling.cop_warnings = DUP_WARNINGS(PL_curcop->cop_warnings);
8815          PL_curcop = &PL_compiling;
8816     }
8817     SAVECOPLINE(PL_curcop);
8818     CopLINE_set(PL_curcop, PL_parser ? PL_parser->copline : NOLINE);
8819
8820     SAVEHINTS();
8821     PL_hints &= ~HINT_BLOCK_SCOPE;
8822
8823     if (stash) {
8824         SAVEGENERICSV(PL_curstash);
8825         PL_curstash = (HV *)SvREFCNT_inc_simple_NN(stash);
8826     }
8827
8828     /* Protect sv against leakage caused by fatal warnings. */
8829     if (sv) SAVEFREESV(sv);
8830
8831     /* file becomes the CvFILE. For an XS, it's usually static storage,
8832        and so doesn't get free()d.  (It's expected to be from the C pre-
8833        processor __FILE__ directive). But we need a dynamically allocated one,
8834        and we need it to get freed.  */
8835     cv = newXS_len_flags(name, len,
8836                          sv && SvTYPE(sv) == SVt_PVAV
8837                              ? const_av_xsub
8838                              : const_sv_xsub,
8839                          file ? file : "", "",
8840                          &sv, XS_DYNAMIC_FILENAME | flags);
8841     CvXSUBANY(cv).any_ptr = SvREFCNT_inc_simple(sv);
8842     CvCONST_on(cv);
8843
8844     LEAVE;
8845
8846     return cv;
8847 }
8848
8849 /*
8850 =for apidoc U||newXS
8851
8852 Used by C<xsubpp> to hook up XSUBs as Perl subs.  C<filename> needs to be
8853 static storage, as it is used directly as CvFILE(), without a copy being made.
8854
8855 =cut
8856 */
8857
8858 CV *
8859 Perl_newXS(pTHX_ const char *name, XSUBADDR_t subaddr, const char *filename)
8860 {
8861     PERL_ARGS_ASSERT_NEWXS;
8862     return newXS_len_flags(
8863         name, name ? strlen(name) : 0, subaddr, filename, NULL, NULL, 0
8864     );
8865 }
8866
8867 CV *
8868 Perl_newXS_flags(pTHX_ const char *name, XSUBADDR_t subaddr,
8869                  const char *const filename, const char *const proto,
8870                  U32 flags)
8871 {
8872     PERL_ARGS_ASSERT_NEWXS_FLAGS;
8873     return newXS_len_flags(
8874        name, name ? strlen(name) : 0, subaddr, filename, proto, NULL, flags
8875     );
8876 }
8877
8878 CV *
8879 Perl_newXS_deffile(pTHX_ const char *name, XSUBADDR_t subaddr)
8880 {
8881     PERL_ARGS_ASSERT_NEWXS_DEFFILE;
8882     return newXS_len_flags(
8883         name, strlen(name), subaddr, NULL, NULL, NULL, 0
8884     );
8885 }
8886
8887 CV *
8888 Perl_newXS_len_flags(pTHX_ const char *name, STRLEN len,
8889                            XSUBADDR_t subaddr, const char *const filename,
8890                            const char *const proto, SV **const_svp,
8891                            U32 flags)
8892 {
8893     CV *cv;
8894     bool interleave = FALSE;
8895
8896     PERL_ARGS_ASSERT_NEWXS_LEN_FLAGS;
8897
8898     {
8899         GV * const gv = gv_fetchpvn(
8900                             name ? name : PL_curstash ? "__ANON__" : "__ANON__::__ANON__",
8901                             name ? len : PL_curstash ? sizeof("__ANON__") - 1:
8902                                 sizeof("__ANON__::__ANON__") - 1,
8903                             GV_ADDMULTI | flags, SVt_PVCV);
8904
8905         if ((cv = (name ? GvCV(gv) : NULL))) {
8906             if (GvCVGEN(gv)) {
8907                 /* just a cached method */
8908                 SvREFCNT_dec(cv);
8909                 cv = NULL;
8910             }
8911             else if (CvROOT(cv) || CvXSUB(cv) || GvASSUMECV(gv)) {
8912                 /* already defined (or promised) */
8913                 /* Redundant check that allows us to avoid creating an SV
8914                    most of the time: */
8915                 if (CvCONST(cv) || ckWARN(WARN_REDEFINE)) {
8916                     report_redefined_cv(newSVpvn_flags(
8917                                          name,len,(flags&SVf_UTF8)|SVs_TEMP
8918                                         ),
8919                                         cv, const_svp);
8920                 }
8921                 interleave = TRUE;
8922                 ENTER;
8923                 SAVEFREESV(cv);
8924                 cv = NULL;
8925             }
8926         }
8927     
8928         if (cv)                         /* must reuse cv if autoloaded */
8929             cv_undef(cv);
8930         else {
8931             cv = MUTABLE_CV(newSV_type(SVt_PVCV));
8932             if (name) {
8933                 GvCV_set(gv,cv);
8934                 GvCVGEN(gv) = 0;
8935                 if (HvENAME_HEK(GvSTASH(gv)))
8936                     gv_method_changed(gv); /* newXS */
8937             }
8938         }
8939
8940         CvGV_set(cv, gv);
8941         if(filename) {
8942             /* XSUBs can't be perl lang/perl5db.pl debugged
8943             if (PERLDB_LINE_OR_SAVESRC)
8944                 (void)gv_fetchfile(filename); */
8945             assert(!CvDYNFILE(cv)); /* cv_undef should have turned it off */
8946             if (flags & XS_DYNAMIC_FILENAME) {
8947                 CvDYNFILE_on(cv);
8948                 CvFILE(cv) = savepv(filename);
8949             } else {
8950             /* NOTE: not copied, as it is expected to be an external constant string */
8951                 CvFILE(cv) = (char *)filename;
8952             }
8953         } else {
8954             assert((flags & XS_DYNAMIC_FILENAME) == 0 && PL_xsubfilename);
8955             CvFILE(cv) = (char*)PL_xsubfilename;
8956         }
8957         CvISXSUB_on(cv);
8958         CvXSUB(cv) = subaddr;
8959 #ifndef PERL_IMPLICIT_CONTEXT
8960         CvHSCXT(cv) = &PL_stack_sp;
8961 #else
8962         PoisonPADLIST(cv);
8963 #endif
8964
8965         if (name)
8966             process_special_blocks(0, name, gv, cv);
8967         else
8968             CvANON_on(cv);
8969     } /* <- not a conditional branch */
8970
8971
8972     sv_setpv(MUTABLE_SV(cv), proto);
8973     if (interleave) LEAVE;
8974     return cv;
8975 }
8976
8977 CV *
8978 Perl_newSTUB(pTHX_ GV *gv, bool fake)
8979 {
8980     CV *cv = MUTABLE_CV(newSV_type(SVt_PVCV));
8981     GV *cvgv;
8982     PERL_ARGS_ASSERT_NEWSTUB;
8983     assert(!GvCVu(gv));
8984     GvCV_set(gv, cv);
8985     GvCVGEN(gv) = 0;
8986     if (!fake && HvENAME_HEK(GvSTASH(gv)))
8987         gv_method_changed(gv);
8988     if (SvFAKE(gv)) {
8989         cvgv = gv_fetchsv((SV *)gv, GV_ADDMULTI, SVt_PVCV);
8990         SvFAKE_off(cvgv);
8991     }
8992     else cvgv = gv;
8993     CvGV_set(cv, cvgv);
8994     CvFILE_set_from_cop(cv, PL_curcop);
8995     CvSTASH_set(cv, PL_curstash);
8996     GvMULTI_on(gv);
8997     return cv;
8998 }
8999
9000 void
9001 Perl_newFORM(pTHX_ I32 floor, OP *o, OP *block)
9002 {
9003     CV *cv;
9004
9005     GV *gv;
9006
9007     if (PL_parser && PL_parser->error_count) {
9008         op_free(block);
9009         goto finish;
9010     }
9011
9012     gv = o
9013         ? gv_fetchsv(cSVOPo->op_sv, GV_ADD, SVt_PVFM)
9014         : gv_fetchpvs("STDOUT", GV_ADD|GV_NOTQUAL, SVt_PVFM);
9015
9016     GvMULTI_on(gv);
9017     if ((cv = GvFORM(gv))) {
9018         if (ckWARN(WARN_REDEFINE)) {
9019             const line_t oldline = CopLINE(PL_curcop);
9020             if (PL_parser && PL_parser->copline != NOLINE)
9021                 CopLINE_set(PL_curcop, PL_parser->copline);
9022             if (o) {
9023                 Perl_warner(aTHX_ packWARN(WARN_REDEFINE),
9024                             "Format %"SVf" redefined", SVfARG(cSVOPo->op_sv));
9025             } else {
9026                 /* diag_listed_as: Format %s redefined */
9027                 Perl_warner(aTHX_ packWARN(WARN_REDEFINE),
9028                             "Format STDOUT redefined");
9029             }
9030             CopLINE_set(PL_curcop, oldline);
9031         }
9032         SvREFCNT_dec(cv);
9033     }
9034     cv = PL_compcv;
9035     GvFORM(gv) = (CV *)SvREFCNT_inc_simple_NN(cv);
9036     CvGV_set(cv, gv);
9037     CvFILE_set_from_cop(cv, PL_curcop);
9038
9039
9040     pad_tidy(padtidy_FORMAT);
9041     CvROOT(cv) = newUNOP(OP_LEAVEWRITE, 0, scalarseq(block));
9042     CvROOT(cv)->op_private |= OPpREFCOUNTED;
9043     OpREFCNT_set(CvROOT(cv), 1);
9044     CvSTART(cv) = LINKLIST(CvROOT(cv));
9045     CvROOT(cv)->op_next = 0;
9046     CALL_PEEP(CvSTART(cv));
9047     finalize_optree(CvROOT(cv));
9048     S_prune_chain_head(&CvSTART(cv));
9049     cv_forget_slab(cv);
9050
9051   finish:
9052     op_free(o);
9053     if (PL_parser)
9054         PL_parser->copline = NOLINE;
9055     LEAVE_SCOPE(floor);
9056     PL_compiling.cop_seq = 0;
9057 }
9058
9059 OP *
9060 Perl_newANONLIST(pTHX_ OP *o)
9061 {
9062     return op_convert_list(OP_ANONLIST, OPf_SPECIAL, o);
9063 }
9064
9065 OP *
9066 Perl_newANONHASH(pTHX_ OP *o)
9067 {
9068     return op_convert_list(OP_ANONHASH, OPf_SPECIAL, o);
9069 }
9070
9071 OP *
9072 Perl_newANONSUB(pTHX_ I32 floor, OP *proto, OP *block)
9073 {
9074     return newANONATTRSUB(floor, proto, NULL, block);
9075 }
9076
9077 OP *
9078 Perl_newANONATTRSUB(pTHX_ I32 floor, OP *proto, OP *attrs, OP *block)
9079 {
9080     SV * const cv = MUTABLE_SV(newATTRSUB(floor, 0, proto, attrs, block));
9081     OP * anoncode = 
9082         newSVOP(OP_ANONCODE, 0,
9083                 cv);
9084     if (CvANONCONST(cv))
9085         anoncode = newUNOP(OP_ANONCONST, 0,
9086                            op_convert_list(OP_ENTERSUB,
9087                                            OPf_STACKED|OPf_WANT_SCALAR,
9088                                            anoncode));
9089     return newUNOP(OP_REFGEN, 0, anoncode);
9090 }
9091
9092 OP *
9093 Perl_oopsAV(pTHX_ OP *o)
9094 {
9095     dVAR;
9096
9097     PERL_ARGS_ASSERT_OOPSAV;
9098
9099     switch (o->op_type) {
9100     case OP_PADSV:
9101     case OP_PADHV:
9102         OpTYPE_set(o, OP_PADAV);
9103         return ref(o, OP_RV2AV);
9104
9105     case OP_RV2SV:
9106     case OP_RV2HV:
9107         OpTYPE_set(o, OP_RV2AV);
9108         ref(o, OP_RV2AV);
9109         break;
9110
9111     default:
9112         Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL), "oops: oopsAV");
9113         break;
9114     }
9115     return o;
9116 }
9117
9118 OP *
9119 Perl_oopsHV(pTHX_ OP *o)
9120 {
9121     dVAR;
9122
9123     PERL_ARGS_ASSERT_OOPSHV;
9124
9125     switch (o->op_type) {
9126     case OP_PADSV:
9127     case OP_PADAV:
9128         OpTYPE_set(o, OP_PADHV);
9129         return ref(o, OP_RV2HV);
9130
9131     case OP_RV2SV:
9132     case OP_RV2AV:
9133         OpTYPE_set(o, OP_RV2HV);
9134         ref(o, OP_RV2HV);
9135         break;
9136
9137     default:
9138         Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL), "oops: oopsHV");
9139         break;
9140     }
9141     return o;
9142 }
9143
9144 OP *
9145 Perl_newAVREF(pTHX_ OP *o)
9146 {
9147     dVAR;
9148
9149     PERL_ARGS_ASSERT_NEWAVREF;
9150
9151     if (o->op_type == OP_PADANY) {
9152         OpTYPE_set(o, OP_PADAV);
9153         return o;
9154     }
9155     else if ((o->op_type == OP_RV2AV || o->op_type == OP_PADAV)) {
9156         Perl_croak(aTHX_ "Can't use an array as a reference");
9157     }
9158     return newUNOP(OP_RV2AV, 0, scalar(o));
9159 }
9160
9161 OP *
9162 Perl_newGVREF(pTHX_ I32 type, OP *o)
9163 {
9164     if (type == OP_MAPSTART || type == OP_GREPSTART || type == OP_SORT)
9165         return newUNOP(OP_NULL, 0, o);
9166     return ref(newUNOP(OP_RV2GV, OPf_REF, o), type);
9167 }
9168
9169 OP *
9170 Perl_newHVREF(pTHX_ OP *o)
9171 {
9172     dVAR;
9173
9174     PERL_ARGS_ASSERT_NEWHVREF;
9175
9176     if (o->op_type == OP_PADANY) {
9177         OpTYPE_set(o, OP_PADHV);
9178         return o;
9179     }
9180     else if ((o->op_type == OP_RV2HV || o->op_type == OP_PADHV)) {
9181         Perl_croak(aTHX_ "Can't use a hash as a reference");
9182     }
9183     return newUNOP(OP_RV2HV, 0, scalar(o));
9184 }
9185
9186 OP *
9187 Perl_newCVREF(pTHX_ I32 flags, OP *o)
9188 {
9189     if (o->op_type == OP_PADANY) {
9190         dVAR;
9191         OpTYPE_set(o, OP_PADCV);
9192     }
9193     return newUNOP(OP_RV2CV, flags, scalar(o));
9194 }
9195
9196 OP *
9197 Perl_newSVREF(pTHX_ OP *o)
9198 {
9199     dVAR;
9200
9201     PERL_ARGS_ASSERT_NEWSVREF;
9202
9203     if (o->op_type == OP_PADANY) {
9204         OpTYPE_set(o, OP_PADSV);
9205         scalar(o);
9206         return o;
9207     }
9208     return newUNOP(OP_RV2SV, 0, scalar(o));
9209 }
9210
9211 /* Check routines. See the comments at the top of this file for details
9212  * on when these are called */
9213
9214 OP *
9215 Perl_ck_anoncode(pTHX_ OP *o)
9216 {
9217     PERL_ARGS_ASSERT_CK_ANONCODE;
9218
9219     cSVOPo->op_targ = pad_add_anon((CV*)cSVOPo->op_sv, o->op_type);
9220     cSVOPo->op_sv = NULL;
9221     return o;
9222 }
9223
9224 static void
9225 S_io_hints(pTHX_ OP *o)
9226 {
9227 #if O_BINARY != 0 || O_TEXT != 0
9228     HV * const table =
9229         PL_hints & HINT_LOCALIZE_HH ? GvHV(PL_hintgv) : NULL;;
9230     if (table) {
9231         SV **svp = hv_fetchs(table, "open_IN", FALSE);
9232         if (svp && *svp) {
9233             STRLEN len = 0;
9234             const char *d = SvPV_const(*svp, len);
9235             const I32 mode = mode_from_discipline(d, len);
9236             /* bit-and:ing with zero O_BINARY or O_TEXT would be useless. */
9237 #  if O_BINARY != 0
9238             if (mode & O_BINARY)
9239                 o->op_private |= OPpOPEN_IN_RAW;
9240 #  endif
9241 #  if O_TEXT != 0
9242             if (mode & O_TEXT)
9243                 o->op_private |= OPpOPEN_IN_CRLF;
9244 #  endif
9245         }
9246
9247         svp = hv_fetchs(table, "open_OUT", FALSE);
9248         if (svp && *svp) {
9249             STRLEN len = 0;
9250             const char *d = SvPV_const(*svp, len);
9251             const I32 mode = mode_from_discipline(d, len);
9252             /* bit-and:ing with zero O_BINARY or O_TEXT would be useless. */
9253 #  if O_BINARY != 0
9254             if (mode & O_BINARY)
9255                 o->op_private |= OPpOPEN_OUT_RAW;
9256 #  endif
9257 #  if O_TEXT != 0
9258             if (mode & O_TEXT)
9259                 o->op_private |= OPpOPEN_OUT_CRLF;
9260 #  endif
9261         }
9262     }
9263 #else
9264     PERL_UNUSED_CONTEXT;
9265     PERL_UNUSED_ARG(o);
9266 #endif
9267 }
9268
9269 OP *
9270 Perl_ck_backtick(pTHX_ OP *o)
9271 {
9272     GV *gv;
9273     OP *newop = NULL;
9274     OP *sibl;
9275     PERL_ARGS_ASSERT_CK_BACKTICK;
9276     /* qx and `` have a null pushmark; CORE::readpipe has only one kid. */
9277     if (o->op_flags & OPf_KIDS && (sibl = OpSIBLING(cUNOPo->op_first))
9278      && (gv = gv_override("readpipe",8)))
9279     {
9280         /* detach rest of siblings from o and its first child */
9281         op_sibling_splice(o, cUNOPo->op_first, -1, NULL);
9282         newop = S_new_entersubop(aTHX_ gv, sibl);
9283     }
9284     else if (!(o->op_flags & OPf_KIDS))
9285         newop = newUNOP(OP_BACKTICK, 0, newDEFSVOP());
9286     if (newop) {
9287         op_free(o);
9288         return newop;
9289     }
9290     S_io_hints(aTHX_ o);
9291     return o;
9292 }
9293
9294 OP *
9295 Perl_ck_bitop(pTHX_ OP *o)
9296 {
9297     PERL_ARGS_ASSERT_CK_BITOP;
9298
9299     o->op_private = (U8)(PL_hints & HINT_INTEGER);
9300
9301     if (o->op_type == OP_NBIT_OR     || o->op_type == OP_SBIT_OR
9302      || o->op_type == OP_NBIT_XOR    || o->op_type == OP_SBIT_XOR
9303      || o->op_type == OP_NBIT_AND    || o->op_type == OP_SBIT_AND
9304      || o->op_type == OP_NCOMPLEMENT || o->op_type == OP_SCOMPLEMENT)
9305         Perl_ck_warner_d(aTHX_ packWARN(WARN_EXPERIMENTAL__BITWISE),
9306                               "The bitwise feature is experimental");
9307     if (!(o->op_flags & OPf_STACKED) /* Not an assignment */
9308             && OP_IS_INFIX_BIT(o->op_type))
9309     {
9310         const OP * const left = cBINOPo->op_first;
9311         const OP * const right = OpSIBLING(left);
9312         if ((OP_IS_NUMCOMPARE(left->op_type) &&
9313                 (left->op_flags & OPf_PARENS) == 0) ||
9314             (OP_IS_NUMCOMPARE(right->op_type) &&
9315                 (right->op_flags & OPf_PARENS) == 0))
9316             Perl_ck_warner(aTHX_ packWARN(WARN_PRECEDENCE),
9317                           "Possible precedence problem on bitwise %s operator",
9318                            o->op_type ==  OP_BIT_OR
9319                          ||o->op_type == OP_NBIT_OR  ? "|"
9320                         :  o->op_type ==  OP_BIT_AND
9321                          ||o->op_type == OP_NBIT_AND ? "&"
9322                         :  o->op_type ==  OP_BIT_XOR
9323                          ||o->op_type == OP_NBIT_XOR ? "^"
9324                         :  o->op_type == OP_SBIT_OR  ? "|."
9325                         :  o->op_type == OP_SBIT_AND ? "&." : "^."
9326                            );
9327     }
9328     return o;
9329 }
9330
9331 PERL_STATIC_INLINE bool
9332 is_dollar_bracket(pTHX_ const OP * const o)
9333 {
9334     const OP *kid;
9335     PERL_UNUSED_CONTEXT;
9336     return o->op_type == OP_RV2SV && o->op_flags & OPf_KIDS
9337         && (kid = cUNOPx(o)->op_first)
9338         && kid->op_type == OP_GV
9339         && strEQ(GvNAME(cGVOPx_gv(kid)), "[");
9340 }
9341
9342 OP *
9343 Perl_ck_cmp(pTHX_ OP *o)
9344 {
9345     PERL_ARGS_ASSERT_CK_CMP;
9346     if (ckWARN(WARN_SYNTAX)) {
9347         const OP *kid = cUNOPo->op_first;
9348         if (kid &&
9349             (
9350                 (   is_dollar_bracket(aTHX_ kid)
9351                  && OpSIBLING(kid) && OpSIBLING(kid)->op_type == OP_CONST
9352                 )
9353              || (   kid->op_type == OP_CONST
9354                  && (kid = OpSIBLING(kid)) && is_dollar_bracket(aTHX_ kid)
9355                 )
9356            )
9357         )
9358             Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
9359                         "$[ used in %s (did you mean $] ?)", OP_DESC(o));
9360     }
9361     return o;
9362 }
9363
9364 OP *
9365 Perl_ck_concat(pTHX_ OP *o)
9366 {
9367     const OP * const kid = cUNOPo->op_first;
9368
9369     PERL_ARGS_ASSERT_CK_CONCAT;
9370     PERL_UNUSED_CONTEXT;
9371
9372     if (kid->op_type == OP_CONCAT && !(kid->op_private & OPpTARGET_MY) &&
9373             !(kUNOP->op_first->op_flags & OPf_MOD))
9374         o->op_flags |= OPf_STACKED;
9375     return o;
9376 }
9377
9378 OP *
9379 Perl_ck_spair(pTHX_ OP *o)
9380 {
9381     dVAR;
9382
9383     PERL_ARGS_ASSERT_CK_SPAIR;
9384
9385     if (o->op_flags & OPf_KIDS) {
9386         OP* newop;
9387         OP* kid;
9388         OP* kidkid;
9389         const OPCODE type = o->op_type;
9390         o = modkids(ck_fun(o), type);
9391         kid    = cUNOPo->op_first;
9392         kidkid = kUNOP->op_first;
9393         newop = OpSIBLING(kidkid);
9394         if (newop) {
9395             const OPCODE type = newop->op_type;
9396             if (OpHAS_SIBLING(newop))
9397                 return o;
9398             if (o->op_type == OP_REFGEN
9399              && (  type == OP_RV2CV
9400                 || (  !(newop->op_flags & OPf_PARENS)
9401                    && (  type == OP_RV2AV || type == OP_PADAV
9402                       || type == OP_RV2HV || type == OP_PADHV))))
9403                 NOOP; /* OK (allow srefgen for \@a and \%h) */
9404             else if (OP_GIMME(newop,0) != G_SCALAR)
9405                 return o;
9406         }
9407         /* excise first sibling */
9408         op_sibling_splice(kid, NULL, 1, NULL);
9409         op_free(kidkid);
9410     }
9411     /* transforms OP_REFGEN into OP_SREFGEN, OP_CHOP into OP_SCHOP,
9412      * and OP_CHOMP into OP_SCHOMP */
9413     o->op_ppaddr = PL_ppaddr[++o->op_type];
9414     return ck_fun(o);
9415 }
9416
9417 OP *
9418 Perl_ck_delete(pTHX_ OP *o)
9419 {
9420     PERL_ARGS_ASSERT_CK_DELETE;
9421
9422     o = ck_fun(o);
9423     o->op_private = 0;
9424     if (o->op_flags & OPf_KIDS) {
9425         OP * const kid = cUNOPo->op_first;
9426         switch (kid->op_type) {
9427         case OP_ASLICE:
9428             o->op_flags |= OPf_SPECIAL;
9429             /* FALLTHROUGH */
9430         case OP_HSLICE:
9431             o->op_private |= OPpSLICE;
9432             break;
9433         case OP_AELEM:
9434             o->op_flags |= OPf_SPECIAL;
9435             /* FALLTHROUGH */
9436         case OP_HELEM:
9437             break;
9438         case OP_KVASLICE:
9439             Perl_croak(aTHX_ "delete argument is index/value array slice,"
9440                              " use array slice");
9441         case OP_KVHSLICE:
9442             Perl_croak(aTHX_ "delete argument is key/value hash slice, use"
9443                              " hash slice");
9444         default:
9445             Perl_croak(aTHX_ "delete argument is not a HASH or ARRAY "
9446                              "element or slice");
9447         }
9448         if (kid->op_private & OPpLVAL_INTRO)
9449             o->op_private |= OPpLVAL_INTRO;
9450         op_null(kid);
9451     }
9452     return o;
9453 }
9454
9455 OP *
9456 Perl_ck_eof(pTHX_ OP *o)
9457 {
9458     PERL_ARGS_ASSERT_CK_EOF;
9459
9460     if (o->op_flags & OPf_KIDS) {
9461         OP *kid;
9462         if (cLISTOPo->op_first->op_type == OP_STUB) {
9463             OP * const newop
9464                 = newUNOP(o->op_type, OPf_SPECIAL, newGVOP(OP_GV, 0, PL_argvgv));
9465             op_free(o);
9466             o = newop;
9467         }
9468         o = ck_fun(o);
9469         kid = cLISTOPo->op_first;
9470         if (kid->op_type == OP_RV2GV)
9471             kid->op_private |= OPpALLOW_FAKE;
9472     }
9473     return o;
9474 }
9475
9476 OP *
9477 Perl_ck_eval(pTHX_ OP *o)
9478 {
9479     dVAR;
9480
9481     PERL_ARGS_ASSERT_CK_EVAL;
9482
9483     PL_hints |= HINT_BLOCK_SCOPE;
9484     if (o->op_flags & OPf_KIDS) {
9485         SVOP * const kid = (SVOP*)cUNOPo->op_first;
9486         assert(kid);
9487
9488         if (o->op_type == OP_ENTERTRY) {
9489             LOGOP *enter;
9490
9491             /* cut whole sibling chain free from o */
9492             op_sibling_splice(o, NULL, -1, NULL);
9493             op_free(o);
9494
9495             enter = S_alloc_LOGOP(aTHX_ OP_ENTERTRY, NULL, NULL);
9496
9497             /* establish postfix order */
9498             enter->op_next = (OP*)enter;
9499
9500             o = op_prepend_elem(OP_LINESEQ, (OP*)enter, (OP*)kid);
9501             OpTYPE_set(o, OP_LEAVETRY);
9502             enter->op_other = o;
9503             return o;
9504         }
9505         else {
9506             scalar((OP*)kid);
9507             S_set_haseval(aTHX);
9508         }
9509     }
9510     else {
9511         const U8 priv = o->op_private;
9512         op_free(o);
9513         /* the newUNOP will recursively call ck_eval(), which will handle
9514          * all the stuff at the end of this function, like adding
9515          * OP_HINTSEVAL
9516          */
9517         return newUNOP(OP_ENTEREVAL, priv <<8, newDEFSVOP());
9518     }
9519     o->op_targ = (PADOFFSET)PL_hints;
9520     if (o->op_private & OPpEVAL_BYTES) o->op_targ &= ~HINT_UTF8;
9521     if ((PL_hints & HINT_LOCALIZE_HH) != 0
9522      && !(o->op_private & OPpEVAL_COPHH) && GvHV(PL_hintgv)) {
9523         /* Store a copy of %^H that pp_entereval can pick up. */
9524         OP *hhop = newSVOP(OP_HINTSEVAL, 0,
9525                            MUTABLE_SV(hv_copy_hints_hv(GvHV(PL_hintgv))));
9526         /* append hhop to only child  */
9527         op_sibling_splice(o, cUNOPo->op_first, 0, hhop);
9528
9529         o->op_private |= OPpEVAL_HAS_HH;
9530     }
9531     if (!(o->op_private & OPpEVAL_BYTES)
9532          && FEATURE_UNIEVAL_IS_ENABLED)
9533             o->op_private |= OPpEVAL_UNICODE;
9534     return o;
9535 }
9536
9537 OP *
9538 Perl_ck_exec(pTHX_ OP *o)
9539 {
9540     PERL_ARGS_ASSERT_CK_EXEC;
9541
9542     if (o->op_flags & OPf_STACKED) {
9543         OP *kid;
9544         o = ck_fun(o);
9545         kid = OpSIBLING(cUNOPo->op_first);
9546         if (kid->op_type == OP_RV2GV)
9547             op_null(kid);
9548     }
9549     else
9550         o = listkids(o);
9551     return o;
9552 }
9553
9554 OP *
9555 Perl_ck_exists(pTHX_ OP *o)
9556 {
9557     PERL_ARGS_ASSERT_CK_EXISTS;
9558
9559     o = ck_fun(o);
9560     if (o->op_flags & OPf_KIDS) {
9561         OP * const kid = cUNOPo->op_first;
9562         if (kid->op_type == OP_ENTERSUB) {
9563             (void) ref(kid, o->op_type);
9564             if (kid->op_type != OP_RV2CV
9565                         && !(PL_parser && PL_parser->error_count))
9566                 Perl_croak(aTHX_
9567                           "exists argument is not a subroutine name");
9568             o->op_private |= OPpEXISTS_SUB;
9569         }
9570         else if (kid->op_type == OP_AELEM)
9571             o->op_flags |= OPf_SPECIAL;
9572         else if (kid->op_type != OP_HELEM)
9573             Perl_croak(aTHX_ "exists argument is not a HASH or ARRAY "
9574                              "element or a subroutine");
9575         op_null(kid);
9576     }
9577     return o;
9578 }
9579
9580 OP *
9581 Perl_ck_rvconst(pTHX_ OP *o)
9582 {
9583     dVAR;
9584     SVOP * const kid = (SVOP*)cUNOPo->op_first;
9585
9586     PERL_ARGS_ASSERT_CK_RVCONST;
9587
9588     o->op_private |= (PL_hints & HINT_STRICT_REFS);
9589
9590     if (kid->op_type == OP_CONST) {
9591         int iscv;
9592         GV *gv;
9593         SV * const kidsv = kid->op_sv;
9594
9595         /* Is it a constant from cv_const_sv()? */
9596         if ((SvROK(kidsv) || isGV_with_GP(kidsv)) && SvREADONLY(kidsv)) {
9597             return o;
9598         }
9599         if (SvTYPE(kidsv) == SVt_PVAV) return o;
9600         if ((o->op_private & HINT_STRICT_REFS) && (kid->op_private & OPpCONST_BARE)) {
9601             const char *badthing;
9602             switch (o->op_type) {
9603             case OP_RV2SV:
9604                 badthing = "a SCALAR";
9605                 break;
9606             case OP_RV2AV:
9607                 badthing = "an ARRAY";
9608                 break;
9609             case OP_RV2HV:
9610                 badthing = "a HASH";
9611                 break;
9612             default:
9613                 badthing = NULL;
9614                 break;
9615             }
9616             if (badthing)
9617                 Perl_croak(aTHX_
9618                            "Can't use bareword (\"%"SVf"\") as %s ref while \"strict refs\" in use",
9619                            SVfARG(kidsv), badthing);
9620         }
9621         /*
9622          * This is a little tricky.  We only want to add the symbol if we
9623          * didn't add it in the lexer.  Otherwise we get duplicate strict
9624          * warnings.  But if we didn't add it in the lexer, we must at
9625          * least pretend like we wanted to add it even if it existed before,
9626          * or we get possible typo warnings.  OPpCONST_ENTERED says
9627          * whether the lexer already added THIS instance of this symbol.
9628          */
9629         iscv = o->op_type == OP_RV2CV ? GV_NOEXPAND|GV_ADDMULTI : 0;
9630         gv = gv_fetchsv(kidsv,
9631                 o->op_type == OP_RV2CV
9632                         && o->op_private & OPpMAY_RETURN_CONSTANT
9633                     ? GV_NOEXPAND
9634                     : iscv | !(kid->op_private & OPpCONST_ENTERED),
9635                 iscv
9636                     ? SVt_PVCV
9637                     : o->op_type == OP_RV2SV
9638                         ? SVt_PV
9639                         : o->op_type == OP_RV2AV
9640                             ? SVt_PVAV
9641                             : o->op_type == OP_RV2HV
9642                                 ? SVt_PVHV
9643                                 : SVt_PVGV);
9644         if (gv) {
9645             if (!isGV(gv)) {
9646                 assert(iscv);
9647                 assert(SvROK(gv));
9648                 if (!(o->op_private & OPpMAY_RETURN_CONSTANT)
9649                   && SvTYPE(SvRV(gv)) != SVt_PVCV)
9650                     gv_fetchsv(kidsv, GV_ADDMULTI, SVt_PVCV);
9651             }
9652             OpTYPE_set(kid, OP_GV);
9653             SvREFCNT_dec(kid->op_sv);
9654 #ifdef USE_ITHREADS
9655             /* XXX hack: dependence on sizeof(PADOP) <= sizeof(SVOP) */
9656             STATIC_ASSERT_STMT(sizeof(PADOP) <= sizeof(SVOP));
9657             kPADOP->op_padix = pad_alloc(OP_GV, SVf_READONLY);
9658             SvREFCNT_dec(PAD_SVl(kPADOP->op_padix));
9659             PAD_SETSV(kPADOP->op_padix, MUTABLE_SV(SvREFCNT_inc_simple_NN(gv)));
9660 #else
9661             kid->op_sv = SvREFCNT_inc_simple_NN(gv);
9662 #endif
9663             kid->op_private = 0;
9664             /* FAKE globs in the symbol table cause weird bugs (#77810) */
9665             SvFAKE_off(gv);
9666         }
9667     }
9668     return o;
9669 }
9670
9671 OP *
9672 Perl_ck_ftst(pTHX_ OP *o)
9673 {
9674     dVAR;
9675     const I32 type = o->op_type;
9676
9677     PERL_ARGS_ASSERT_CK_FTST;
9678
9679     if (o->op_flags & OPf_REF) {
9680         NOOP;
9681     }
9682     else if (o->op_flags & OPf_KIDS && cUNOPo->op_first->op_type != OP_STUB) {
9683         SVOP * const kid = (SVOP*)cUNOPo->op_first;
9684         const OPCODE kidtype = kid->op_type;
9685
9686         if (kidtype == OP_CONST && (kid->op_private & OPpCONST_BARE)
9687          && !kid->op_folded) {
9688             OP * const newop = newGVOP(type, OPf_REF,
9689                 gv_fetchsv(kid->op_sv, GV_ADD, SVt_PVIO));
9690             op_free(o);
9691             return newop;
9692         }
9693         scalar((OP *) kid);
9694         if ((PL_hints & HINT_FILETEST_ACCESS) && OP_IS_FILETEST_ACCESS(o->op_type))
9695             o->op_private |= OPpFT_ACCESS;
9696         if (type != OP_STAT && type != OP_LSTAT
9697             && PL_check[kidtype] == Perl_ck_ftst
9698             && kidtype != OP_STAT && kidtype != OP_LSTAT
9699         ) {
9700             o->op_private |= OPpFT_STACKED;
9701             kid->op_private |= OPpFT_STACKING;
9702             if (kidtype == OP_FTTTY && (
9703                    !(kid->op_private & OPpFT_STACKED)
9704                 || kid->op_private & OPpFT_AFTER_t
9705                ))
9706                 o->op_private |= OPpFT_AFTER_t;
9707         }
9708     }
9709     else {
9710         op_free(o);
9711         if (type == OP_FTTTY)
9712             o = newGVOP(type, OPf_REF, PL_stdingv);
9713         else
9714             o = newUNOP(type, 0, newDEFSVOP());
9715     }
9716     return o;
9717 }
9718
9719 OP *
9720 Perl_ck_fun(pTHX_ OP *o)
9721 {
9722     const int type = o->op_type;
9723     I32 oa = PL_opargs[type] >> OASHIFT;
9724
9725     PERL_ARGS_ASSERT_CK_FUN;
9726
9727     if (o->op_flags & OPf_STACKED) {
9728         if ((oa & OA_OPTIONAL) && (oa >> 4) && !((oa >> 4) & OA_OPTIONAL))
9729             oa &= ~OA_OPTIONAL;
9730         else
9731             return no_fh_allowed(o);
9732     }
9733
9734     if (o->op_flags & OPf_KIDS) {
9735         OP *prev_kid = NULL;
9736         OP *kid = cLISTOPo->op_first;
9737         I32 numargs = 0;
9738         bool seen_optional = FALSE;
9739
9740         if (kid->op_type == OP_PUSHMARK ||
9741             (kid->op_type == OP_NULL && kid->op_targ == OP_PUSHMARK))
9742         {
9743             prev_kid = kid;
9744             kid = OpSIBLING(kid);
9745         }
9746         if (kid && kid->op_type == OP_COREARGS) {
9747             bool optional = FALSE;
9748             while (oa) {
9749                 numargs++;
9750                 if (oa & OA_OPTIONAL) optional = TRUE;
9751                 oa = oa >> 4;
9752             }
9753             if (optional) o->op_private |= numargs;
9754             return o;
9755         }
9756
9757         while (oa) {
9758             if (oa & OA_OPTIONAL || (oa & 7) == OA_LIST) {
9759                 if (!kid && !seen_optional && PL_opargs[type] & OA_DEFGV) {
9760                     kid = newDEFSVOP();
9761                     /* append kid to chain */
9762                     op_sibling_splice(o, prev_kid, 0, kid);
9763                 }
9764                 seen_optional = TRUE;
9765             }
9766             if (!kid) break;
9767
9768             numargs++;
9769             switch (oa & 7) {
9770             case OA_SCALAR:
9771                 /* list seen where single (scalar) arg expected? */
9772                 if (numargs == 1 && !(oa >> 4)
9773                     && kid->op_type == OP_LIST && type != OP_SCALAR)
9774                 {
9775                     return too_many_arguments_pv(o,PL_op_desc[type], 0);
9776                 }
9777                 if (type != OP_DELETE) scalar(kid);
9778                 break;
9779             case OA_LIST:
9780                 if (oa < 16) {
9781                     kid = 0;
9782                     continue;
9783                 }
9784                 else
9785                     list(kid);
9786                 break;
9787             case OA_AVREF:
9788                 if ((type == OP_PUSH || type == OP_UNSHIFT)
9789                     && !OpHAS_SIBLING(kid))
9790                     Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX),
9791                                    "Useless use of %s with no values",
9792                                    PL_op_desc[type]);
9793
9794                 if (kid->op_type == OP_CONST
9795                       && (  !SvROK(cSVOPx_sv(kid)) 
9796                          || SvTYPE(SvRV(cSVOPx_sv(kid))) != SVt_PVAV  )
9797                         )
9798                     bad_type_pv(numargs, "array", o, kid);
9799                 else if (kid->op_type != OP_RV2AV && kid->op_type != OP_PADAV) {
9800                     yyerror_pv(Perl_form(aTHX_ "Experimental %s on scalar is now forbidden",
9801                                          PL_op_desc[type]), 0);
9802                 }
9803                 else {
9804                     op_lvalue(kid, type);
9805                 }
9806                 break;
9807             case OA_HVREF:
9808                 if (kid->op_type != OP_RV2HV && kid->op_type != OP_PADHV)
9809                     bad_type_pv(numargs, "hash", o, kid);
9810                 op_lvalue(kid, type);
9811                 break;
9812             case OA_CVREF:
9813                 {
9814                     /* replace kid with newop in chain */
9815                     OP * const newop =
9816                         S_op_sibling_newUNOP(aTHX_ o, prev_kid, OP_NULL, 0);
9817                     newop->op_next = newop;
9818                     kid = newop;
9819                 }
9820                 break;
9821             case OA_FILEREF:
9822                 if (kid->op_type != OP_GV && kid->op_type != OP_RV2GV) {
9823                     if (kid->op_type == OP_CONST &&
9824                         (kid->op_private & OPpCONST_BARE))
9825                     {
9826                         OP * const newop = newGVOP(OP_GV, 0,
9827                             gv_fetchsv(((SVOP*)kid)->op_sv, GV_ADD, SVt_PVIO));
9828                         /* replace kid with newop in chain */
9829                         op_sibling_splice(o, prev_kid, 1, newop);
9830                         op_free(kid);
9831                         kid = newop;
9832                     }
9833                     else if (kid->op_type == OP_READLINE) {
9834                         /* neophyte patrol: open(<FH>), close(<FH>) etc. */
9835                         bad_type_pv(numargs, "HANDLE", o, kid);
9836                     }
9837                     else {
9838                         I32 flags = OPf_SPECIAL;
9839                         I32 priv = 0;
9840                         PADOFFSET targ = 0;
9841
9842                         /* is this op a FH constructor? */
9843                         if (is_handle_constructor(o,numargs)) {
9844                             const char *name = NULL;
9845                             STRLEN len = 0;
9846                             U32 name_utf8 = 0;
9847                             bool want_dollar = TRUE;
9848
9849                             flags = 0;
9850                             /* Set a flag to tell rv2gv to vivify
9851                              * need to "prove" flag does not mean something
9852                              * else already - NI-S 1999/05/07
9853                              */
9854                             priv = OPpDEREF;
9855                             if (kid->op_type == OP_PADSV) {
9856                                 PADNAME * const pn
9857                                     = PAD_COMPNAME_SV(kid->op_targ);
9858                                 name = PadnamePV (pn);
9859                                 len  = PadnameLEN(pn);
9860                                 name_utf8 = PadnameUTF8(pn);
9861                             }
9862                             else if (kid->op_type == OP_RV2SV
9863                                      && kUNOP->op_first->op_type == OP_GV)
9864                             {
9865                                 GV * const gv = cGVOPx_gv(kUNOP->op_first);
9866                                 name = GvNAME(gv);
9867                                 len = GvNAMELEN(gv);
9868                                 name_utf8 = GvNAMEUTF8(gv) ? SVf_UTF8 : 0;
9869                             }
9870                             else if (kid->op_type == OP_AELEM
9871                                      || kid->op_type == OP_HELEM)
9872                             {
9873                                  OP *firstop;
9874                                  OP *op = ((BINOP*)kid)->op_first;
9875                                  name = NULL;
9876                                  if (op) {
9877                                       SV *tmpstr = NULL;
9878                                       const char * const a =
9879                                            kid->op_type == OP_AELEM ?
9880                                            "[]" : "{}";
9881                                       if (((op->op_type == OP_RV2AV) ||
9882                                            (op->op_type == OP_RV2HV)) &&
9883                                           (firstop = ((UNOP*)op)->op_first) &&
9884                                           (firstop->op_type == OP_GV)) {
9885                                            /* packagevar $a[] or $h{} */
9886                                            GV * const gv = cGVOPx_gv(firstop);
9887                                            if (gv)
9888                                                 tmpstr =
9889                                                      Perl_newSVpvf(aTHX_
9890                                                                    "%s%c...%c",
9891                                                                    GvNAME(gv),
9892                                                                    a[0], a[1]);
9893                                       }
9894                                       else if (op->op_type == OP_PADAV
9895                                                || op->op_type == OP_PADHV) {
9896                                            /* lexicalvar $a[] or $h{} */
9897                                            const char * const padname =
9898                                                 PAD_COMPNAME_PV(op->op_targ);
9899                                            if (padname)
9900                                                 tmpstr =
9901                                                      Perl_newSVpvf(aTHX_
9902                                                                    "%s%c...%c",
9903                                                                    padname + 1,
9904                                                                    a[0], a[1]);
9905                                       }
9906                                       if (tmpstr) {
9907                                            name = SvPV_const(tmpstr, len);
9908                                            name_utf8 = SvUTF8(tmpstr);
9909                                            sv_2mortal(tmpstr);
9910                                       }
9911                                  }
9912                                  if (!name) {
9913                                       name = "__ANONIO__";
9914                                       len = 10;
9915                                       want_dollar = FALSE;
9916                                  }
9917                                  op_lvalue(kid, type);
9918                             }
9919                             if (name) {
9920                                 SV *namesv;
9921                                 targ = pad_alloc(OP_RV2GV, SVf_READONLY);
9922                                 namesv = PAD_SVl(targ);
9923                                 if (want_dollar && *name != '$')
9924                                     sv_setpvs(namesv, "$");
9925                                 else
9926                                     sv_setpvs(namesv, "");
9927                                 sv_catpvn(namesv, name, len);
9928                                 if ( name_utf8 ) SvUTF8_on(namesv);
9929                             }
9930                         }
9931                         scalar(kid);
9932                         kid = S_op_sibling_newUNOP(aTHX_ o, prev_kid,
9933                                     OP_RV2GV, flags);
9934                         kid->op_targ = targ;
9935                         kid->op_private |= priv;
9936                     }
9937                 }
9938                 scalar(kid);
9939                 break;
9940             case OA_SCALARREF:
9941                 if ((type == OP_UNDEF || type == OP_POS)
9942                     && numargs == 1 && !(oa >> 4)
9943                     && kid->op_type == OP_LIST)
9944                     return too_many_arguments_pv(o,PL_op_desc[type], 0);
9945                 op_lvalue(scalar(kid), type);
9946                 break;
9947             }
9948             oa >>= 4;
9949             prev_kid = kid;
9950             kid = OpSIBLING(kid);
9951         }
9952         /* FIXME - should the numargs or-ing move after the too many
9953          * arguments check? */
9954         o->op_private |= numargs;
9955         if (kid)
9956             return too_many_arguments_pv(o,OP_DESC(o), 0);
9957         listkids(o);
9958     }
9959     else if (PL_opargs[type] & OA_DEFGV) {
9960         /* Ordering of these two is important to keep f_map.t passing.  */
9961         op_free(o);
9962         return newUNOP(type, 0, newDEFSVOP());
9963     }
9964
9965     if (oa) {
9966         while (oa & OA_OPTIONAL)
9967             oa >>= 4;
9968         if (oa && oa != OA_LIST)
9969             return too_few_arguments_pv(o,OP_DESC(o), 0);
9970     }
9971     return o;
9972 }
9973
9974 OP *
9975 Perl_ck_glob(pTHX_ OP *o)
9976 {
9977     GV *gv;
9978
9979     PERL_ARGS_ASSERT_CK_GLOB;
9980
9981     o = ck_fun(o);
9982     if ((o->op_flags & OPf_KIDS) && !OpHAS_SIBLING(cLISTOPo->op_first))
9983         op_append_elem(OP_GLOB, o, newDEFSVOP()); /* glob() => glob($_) */
9984
9985     if (!(o->op_flags & OPf_SPECIAL) && (gv = gv_override("glob", 4)))
9986     {
9987         /* convert
9988          *     glob
9989          *       \ null - const(wildcard)
9990          * into
9991          *     null
9992          *       \ enter
9993          *            \ list
9994          *                 \ mark - glob - rv2cv
9995          *                             |        \ gv(CORE::GLOBAL::glob)
9996          *                             |
9997          *                              \ null - const(wildcard)
9998          */
9999         o->op_flags |= OPf_SPECIAL;
10000         o->op_targ = pad_alloc(OP_GLOB, SVs_PADTMP);
10001         o = S_new_entersubop(aTHX_ gv, o);
10002         o = newUNOP(OP_NULL, 0, o);
10003         o->op_targ = OP_GLOB; /* hint at what it used to be: eg in newWHILEOP */
10004         return o;
10005     }
10006     else o->op_flags &= ~OPf_SPECIAL;
10007 #if !defined(PERL_EXTERNAL_GLOB)
10008     if (!PL_globhook) {
10009         ENTER;
10010         Perl_load_module(aTHX_ PERL_LOADMOD_NOIMPORT,
10011                                newSVpvs("File::Glob"), NULL, NULL, NULL);
10012         LEAVE;
10013     }
10014 #endif /* !PERL_EXTERNAL_GLOB */
10015     gv = (GV *)newSV(0);
10016     gv_init(gv, 0, "", 0, 0);
10017     gv_IOadd(gv);
10018     op_append_elem(OP_GLOB, o, newGVOP(OP_GV, 0, gv));
10019     SvREFCNT_dec_NN(gv); /* newGVOP increased it */
10020     scalarkids(o);
10021     return o;
10022 }
10023
10024 OP *
10025 Perl_ck_grep(pTHX_ OP *o)
10026 {
10027     LOGOP *gwop;
10028     OP *kid;
10029     const OPCODE type = o->op_type == OP_GREPSTART ? OP_GREPWHILE : OP_MAPWHILE;
10030
10031     PERL_ARGS_ASSERT_CK_GREP;
10032
10033     /* don't allocate gwop here, as we may leak it if PL_parser->error_count > 0 */
10034
10035     if (o->op_flags & OPf_STACKED) {
10036         kid = cUNOPx(OpSIBLING(cLISTOPo->op_first))->op_first;
10037         if (kid->op_type != OP_SCOPE && kid->op_type != OP_LEAVE)
10038             return no_fh_allowed(o);
10039         o->op_flags &= ~OPf_STACKED;
10040     }
10041     kid = OpSIBLING(cLISTOPo->op_first);
10042     if (type == OP_MAPWHILE)
10043         list(kid);
10044     else
10045         scalar(kid);
10046     o = ck_fun(o);
10047     if (PL_parser && PL_parser->error_count)
10048         return o;
10049     kid = OpSIBLING(cLISTOPo->op_first);
10050     if (kid->op_type != OP_NULL)
10051         Perl_croak(aTHX_ "panic: ck_grep, type=%u", (unsigned) kid->op_type);
10052     kid = kUNOP->op_first;
10053
10054     gwop = S_alloc_LOGOP(aTHX_ type, o, LINKLIST(kid));
10055     kid->op_next = (OP*)gwop;
10056     o->op_private = gwop->op_private = 0;
10057     gwop->op_targ = pad_alloc(type, SVs_PADTMP);
10058
10059     kid = OpSIBLING(cLISTOPo->op_first);
10060     for (kid = OpSIBLING(kid); kid; kid = OpSIBLING(kid))
10061         op_lvalue(kid, OP_GREPSTART);
10062
10063     return (OP*)gwop;
10064 }
10065
10066 OP *
10067 Perl_ck_index(pTHX_ OP *o)
10068 {
10069     PERL_ARGS_ASSERT_CK_INDEX;
10070
10071     if (o->op_flags & OPf_KIDS) {
10072         OP *kid = OpSIBLING(cLISTOPo->op_first);        /* get past pushmark */
10073         if (kid)
10074             kid = OpSIBLING(kid);                       /* get past "big" */
10075         if (kid && kid->op_type == OP_CONST) {
10076             const bool save_taint = TAINT_get;
10077             SV *sv = kSVOP->op_sv;
10078             if ((!SvPOK(sv) || SvNIOKp(sv)) && SvOK(sv) && !SvROK(sv)) {
10079                 sv = newSV(0);
10080                 sv_copypv(sv, kSVOP->op_sv);
10081                 SvREFCNT_dec_NN(kSVOP->op_sv);
10082                 kSVOP->op_sv = sv;
10083             }
10084             if (SvOK(sv)) fbm_compile(sv, 0);
10085             TAINT_set(save_taint);
10086 #ifdef NO_TAINT_SUPPORT
10087             PERL_UNUSED_VAR(save_taint);
10088 #endif
10089         }
10090     }
10091     return ck_fun(o);
10092 }
10093
10094 OP *
10095 Perl_ck_lfun(pTHX_ OP *o)
10096 {
10097     const OPCODE type = o->op_type;
10098
10099     PERL_ARGS_ASSERT_CK_LFUN;
10100
10101     return modkids(ck_fun(o), type);
10102 }
10103
10104 OP *
10105 Perl_ck_defined(pTHX_ OP *o)            /* 19990527 MJD */
10106 {
10107     PERL_ARGS_ASSERT_CK_DEFINED;
10108
10109     if ((o->op_flags & OPf_KIDS)) {
10110         switch (cUNOPo->op_first->op_type) {
10111         case OP_RV2AV:
10112         case OP_PADAV:
10113             Perl_croak(aTHX_ "Can't use 'defined(@array)'"
10114                              " (Maybe you should just omit the defined()?)");
10115         break;
10116         case OP_RV2HV:
10117         case OP_PADHV:
10118             Perl_croak(aTHX_ "Can't use 'defined(%%hash)'"
10119                              " (Maybe you should just omit the defined()?)");
10120             break;
10121         default:
10122             /* no warning */
10123             break;
10124         }
10125     }
10126     return ck_rfun(o);
10127 }
10128
10129 OP *
10130 Perl_ck_readline(pTHX_ OP *o)
10131 {
10132     PERL_ARGS_ASSERT_CK_READLINE;
10133
10134     if (o->op_flags & OPf_KIDS) {
10135          OP *kid = cLISTOPo->op_first;
10136          if (kid->op_type == OP_RV2GV) kid->op_private |= OPpALLOW_FAKE;
10137     }
10138     else {
10139         OP * const newop
10140             = newUNOP(OP_READLINE, 0, newGVOP(OP_GV, 0, PL_argvgv));
10141         op_free(o);
10142         return newop;
10143     }
10144     return o;
10145 }
10146
10147 OP *
10148 Perl_ck_rfun(pTHX_ OP *o)
10149 {
10150     const OPCODE type = o->op_type;
10151
10152     PERL_ARGS_ASSERT_CK_RFUN;
10153
10154     return refkids(ck_fun(o), type);
10155 }
10156
10157 OP *
10158 Perl_ck_listiob(pTHX_ OP *o)
10159 {
10160     OP *kid;
10161
10162     PERL_ARGS_ASSERT_CK_LISTIOB;
10163
10164     kid = cLISTOPo->op_first;
10165     if (!kid) {
10166         o = force_list(o, 1);
10167         kid = cLISTOPo->op_first;
10168     }
10169     if (kid->op_type == OP_PUSHMARK)
10170         kid = OpSIBLING(kid);
10171     if (kid && o->op_flags & OPf_STACKED)
10172         kid = OpSIBLING(kid);
10173     else if (kid && !OpHAS_SIBLING(kid)) {              /* print HANDLE; */
10174         if (kid->op_type == OP_CONST && kid->op_private & OPpCONST_BARE
10175          && !kid->op_folded) {
10176             o->op_flags |= OPf_STACKED; /* make it a filehandle */
10177             scalar(kid);
10178             /* replace old const op with new OP_RV2GV parent */
10179             kid = S_op_sibling_newUNOP(aTHX_ o, cLISTOPo->op_first,
10180                                         OP_RV2GV, OPf_REF);
10181             kid = OpSIBLING(kid);
10182         }
10183     }
10184
10185     if (!kid)
10186         op_append_elem(o->op_type, o, newDEFSVOP());
10187
10188     if (o->op_type == OP_PRTF) return modkids(listkids(o), OP_PRTF);
10189     return listkids(o);
10190 }
10191
10192 OP *
10193 Perl_ck_smartmatch(pTHX_ OP *o)
10194 {
10195     dVAR;
10196     PERL_ARGS_ASSERT_CK_SMARTMATCH;
10197     if (0 == (o->op_flags & OPf_SPECIAL)) {
10198         OP *first  = cBINOPo->op_first;
10199         OP *second = OpSIBLING(first);
10200         
10201         /* Implicitly take a reference to an array or hash */
10202
10203         /* remove the original two siblings, then add back the
10204          * (possibly different) first and second sibs.
10205          */
10206         op_sibling_splice(o, NULL, 1, NULL);
10207         op_sibling_splice(o, NULL, 1, NULL);
10208         first  = ref_array_or_hash(first);
10209         second = ref_array_or_hash(second);
10210         op_sibling_splice(o, NULL, 0, second);
10211         op_sibling_splice(o, NULL, 0, first);
10212         
10213         /* Implicitly take a reference to a regular expression */
10214         if (first->op_type == OP_MATCH) {
10215             OpTYPE_set(first, OP_QR);
10216         }
10217         if (second->op_type == OP_MATCH) {
10218             OpTYPE_set(second, OP_QR);
10219         }
10220     }
10221     
10222     return o;
10223 }
10224
10225
10226 static OP *
10227 S_maybe_targlex(pTHX_ OP *o)
10228 {
10229     OP * const kid = cLISTOPo->op_first;
10230     /* has a disposable target? */
10231     if ((PL_opargs[kid->op_type] & OA_TARGLEX)
10232         && !(kid->op_flags & OPf_STACKED)
10233         /* Cannot steal the second time! */
10234         && !(kid->op_private & OPpTARGET_MY)
10235         )
10236     {
10237         OP * const kkid = OpSIBLING(kid);
10238
10239         /* Can just relocate the target. */
10240         if (kkid && kkid->op_type == OP_PADSV
10241             && (!(kkid->op_private & OPpLVAL_INTRO)
10242                || kkid->op_private & OPpPAD_STATE))
10243         {
10244             kid->op_targ = kkid->op_targ;
10245             kkid->op_targ = 0;
10246             /* Now we do not need PADSV and SASSIGN.
10247              * Detach kid and free the rest. */
10248             op_sibling_splice(o, NULL, 1, NULL);
10249             op_free(o);
10250             kid->op_private |= OPpTARGET_MY;    /* Used for context settings */
10251             return kid;
10252         }
10253     }
10254     return o;
10255 }
10256
10257 OP *
10258 Perl_ck_sassign(pTHX_ OP *o)
10259 {
10260     dVAR;
10261     OP * const kid = cLISTOPo->op_first;
10262
10263     PERL_ARGS_ASSERT_CK_SASSIGN;
10264
10265     if (OpHAS_SIBLING(kid)) {
10266         OP *kkid = OpSIBLING(kid);
10267         /* For state variable assignment with attributes, kkid is a list op
10268            whose op_last is a padsv. */
10269         if ((kkid->op_type == OP_PADSV ||
10270              (OP_TYPE_IS_OR_WAS(kkid, OP_LIST) &&
10271               (kkid = cLISTOPx(kkid)->op_last)->op_type == OP_PADSV
10272              )
10273             )
10274                 && (kkid->op_private & (OPpLVAL_INTRO|OPpPAD_STATE))
10275                     == (OPpLVAL_INTRO|OPpPAD_STATE)) {
10276             const PADOFFSET target = kkid->op_targ;
10277             OP *const other = newOP(OP_PADSV,
10278                                     kkid->op_flags
10279                                     | ((kkid->op_private & ~OPpLVAL_INTRO) << 8));
10280             OP *const first = newOP(OP_NULL, 0);
10281             OP *const nullop =
10282                 newCONDOP(0, first, o, other);
10283             /* XXX targlex disabled for now; see ticket #124160
10284                 newCONDOP(0, first, S_maybe_targlex(aTHX_ o), other);
10285              */
10286             OP *const condop = first->op_next;
10287
10288             OpTYPE_set(condop, OP_ONCE);
10289             other->op_targ = target;
10290             nullop->op_flags |= OPf_WANT_SCALAR;
10291
10292             /* Store the initializedness of state vars in a separate
10293                pad entry.  */
10294             condop->op_targ =
10295               pad_add_name_pvn("$",1,padadd_NO_DUP_CHECK|padadd_STATE,0,0);
10296             /* hijacking PADSTALE for uninitialized state variables */
10297             SvPADSTALE_on(PAD_SVl(condop->op_targ));
10298
10299             return nullop;
10300         }
10301     }
10302     return S_maybe_targlex(aTHX_ o);
10303 }
10304
10305 OP *
10306 Perl_ck_match(pTHX_ OP *o)
10307 {
10308     PERL_UNUSED_CONTEXT;
10309     PERL_ARGS_ASSERT_CK_MATCH;
10310
10311     if (o->op_type == OP_MATCH || o->op_type == OP_QR)
10312         o->op_private |= OPpRUNTIME;
10313     return o;
10314 }
10315
10316 OP *
10317 Perl_ck_method(pTHX_ OP *o)
10318 {
10319     SV *sv, *methsv, *rclass;
10320     const char* method;
10321     char* compatptr;
10322     int utf8;
10323     STRLEN len, nsplit = 0, i;
10324     OP* new_op;
10325     OP * const kid = cUNOPo->op_first;
10326
10327     PERL_ARGS_ASSERT_CK_METHOD;
10328     if (kid->op_type != OP_CONST) return o;
10329
10330     sv = kSVOP->op_sv;
10331
10332     /* replace ' with :: */
10333     while ((compatptr = strchr(SvPVX(sv), '\''))) {
10334         *compatptr = ':';
10335         sv_insert(sv, compatptr - SvPVX_const(sv), 0, ":", 1);
10336     }
10337
10338     method = SvPVX_const(sv);
10339     len = SvCUR(sv);
10340     utf8 = SvUTF8(sv) ? -1 : 1;
10341
10342     for (i = len - 1; i > 0; --i) if (method[i] == ':') {
10343         nsplit = i+1;
10344         break;
10345     }
10346
10347     methsv = newSVpvn_share(method+nsplit, utf8*(len - nsplit), 0);
10348
10349     if (!nsplit) { /* $proto->method() */
10350         op_free(o);
10351         return newMETHOP_named(OP_METHOD_NAMED, 0, methsv);
10352     }
10353
10354     if (nsplit == 7 && memEQ(method, "SUPER::", nsplit)) { /* $proto->SUPER::method() */
10355         op_free(o);
10356         return newMETHOP_named(OP_METHOD_SUPER, 0, methsv);
10357     }
10358
10359     /* $proto->MyClass::method() and $proto->MyClass::SUPER::method() */
10360     if (nsplit >= 9 && strnEQ(method+nsplit-9, "::SUPER::", 9)) {
10361         rclass = newSVpvn_share(method, utf8*(nsplit-9), 0);
10362         new_op = newMETHOP_named(OP_METHOD_REDIR_SUPER, 0, methsv);
10363     } else {
10364         rclass = newSVpvn_share(method, utf8*(nsplit-2), 0);
10365         new_op = newMETHOP_named(OP_METHOD_REDIR, 0, methsv);
10366     }
10367 #ifdef USE_ITHREADS
10368     op_relocate_sv(&rclass, &cMETHOPx(new_op)->op_rclass_targ);
10369 #else
10370     cMETHOPx(new_op)->op_rclass_sv = rclass;
10371 #endif
10372     op_free(o);
10373     return new_op;
10374 }
10375
10376 OP *
10377 Perl_ck_null(pTHX_ OP *o)
10378 {
10379     PERL_ARGS_ASSERT_CK_NULL;
10380     PERL_UNUSED_CONTEXT;
10381     return o;
10382 }
10383
10384 OP *
10385 Perl_ck_open(pTHX_ OP *o)
10386 {
10387     PERL_ARGS_ASSERT_CK_OPEN;
10388
10389     S_io_hints(aTHX_ o);
10390     {
10391          /* In case of three-arg dup open remove strictness
10392           * from the last arg if it is a bareword. */
10393          OP * const first = cLISTOPx(o)->op_first; /* The pushmark. */
10394          OP * const last  = cLISTOPx(o)->op_last;  /* The bareword. */
10395          OP *oa;
10396          const char *mode;
10397
10398          if ((last->op_type == OP_CONST) &&             /* The bareword. */
10399              (last->op_private & OPpCONST_BARE) &&
10400              (last->op_private & OPpCONST_STRICT) &&
10401              (oa = OpSIBLING(first)) &&         /* The fh. */
10402              (oa = OpSIBLING(oa)) &&                    /* The mode. */
10403              (oa->op_type == OP_CONST) &&
10404              SvPOK(((SVOP*)oa)->op_sv) &&
10405              (mode = SvPVX_const(((SVOP*)oa)->op_sv)) &&
10406              mode[0] == '>' && mode[1] == '&' &&        /* A dup open. */
10407              (last == OpSIBLING(oa)))                   /* The bareword. */
10408               last->op_private &= ~OPpCONST_STRICT;
10409     }
10410     return ck_fun(o);
10411 }
10412
10413 OP *
10414 Perl_ck_prototype(pTHX_ OP *o)
10415 {
10416     PERL_ARGS_ASSERT_CK_PROTOTYPE;
10417     if (!(o->op_flags & OPf_KIDS)) {
10418         op_free(o);
10419         return newUNOP(OP_PROTOTYPE, 0, newDEFSVOP());
10420     }
10421     return o;
10422 }
10423
10424 OP *
10425 Perl_ck_refassign(pTHX_ OP *o)
10426 {
10427     OP * const right = cLISTOPo->op_first;
10428     OP * const left = OpSIBLING(right);
10429     OP *varop = cUNOPx(cUNOPx(left)->op_first)->op_first;
10430     bool stacked = 0;
10431
10432     PERL_ARGS_ASSERT_CK_REFASSIGN;
10433     assert (left);
10434     assert (left->op_type == OP_SREFGEN);
10435
10436     o->op_private = 0;
10437     /* we use OPpPAD_STATE in refassign to mean either of those things,
10438      * and the code assumes the two flags occupy the same bit position
10439      * in the various ops below */
10440     assert(OPpPAD_STATE == OPpOUR_INTRO);
10441
10442     switch (varop->op_type) {
10443     case OP_PADAV:
10444         o->op_private |= OPpLVREF_AV;
10445         goto settarg;
10446     case OP_PADHV:
10447         o->op_private |= OPpLVREF_HV;
10448         /* FALLTHROUGH */
10449     case OP_PADSV:
10450       settarg:
10451         o->op_private |= (varop->op_private & (OPpLVAL_INTRO|OPpPAD_STATE));
10452         o->op_targ = varop->op_targ;
10453         varop->op_targ = 0;
10454         PAD_COMPNAME_GEN_set(o->op_targ, PERL_INT_MAX);
10455         break;
10456
10457     case OP_RV2AV:
10458         o->op_private |= OPpLVREF_AV;
10459         goto checkgv;
10460         NOT_REACHED; /* NOTREACHED */
10461     case OP_RV2HV:
10462         o->op_private |= OPpLVREF_HV;
10463         /* FALLTHROUGH */
10464     case OP_RV2SV:
10465       checkgv:
10466         o->op_private |= (varop->op_private & (OPpLVAL_INTRO|OPpOUR_INTRO));
10467         if (cUNOPx(varop)->op_first->op_type != OP_GV) goto bad;
10468       detach_and_stack:
10469         /* Point varop to its GV kid, detached.  */
10470         varop = op_sibling_splice(varop, NULL, -1, NULL);
10471         stacked = TRUE;
10472         break;
10473     case OP_RV2CV: {
10474         OP * const kidparent =
10475             OpSIBLING(cUNOPx(cUNOPx(varop)->op_first)->op_first);
10476         OP * const kid = cUNOPx(kidparent)->op_first;
10477         o->op_private |= OPpLVREF_CV;
10478         if (kid->op_type == OP_GV) {
10479             varop = kidparent;
10480             goto detach_and_stack;
10481         }
10482         if (kid->op_type != OP_PADCV)   goto bad;
10483         o->op_targ = kid->op_targ;
10484         kid->op_targ = 0;
10485         break;
10486     }
10487     case OP_AELEM:
10488     case OP_HELEM:
10489         o->op_private |= (varop->op_private & OPpLVAL_INTRO);
10490         o->op_private |= OPpLVREF_ELEM;
10491         op_null(varop);
10492         stacked = TRUE;
10493         /* Detach varop.  */
10494         op_sibling_splice(cUNOPx(left)->op_first, NULL, -1, NULL);
10495         break;
10496     default:
10497       bad:
10498         /* diag_listed_as: Can't modify reference to %s in %s assignment */
10499         yyerror(Perl_form(aTHX_ "Can't modify reference to %s in scalar "
10500                                 "assignment",
10501                                  OP_DESC(varop)));
10502         return o;
10503     }
10504     if (!FEATURE_REFALIASING_IS_ENABLED)
10505         Perl_croak(aTHX_
10506                   "Experimental aliasing via reference not enabled");
10507     Perl_ck_warner_d(aTHX_
10508                      packWARN(WARN_EXPERIMENTAL__REFALIASING),
10509                     "Aliasing via reference is experimental");
10510     if (stacked) {
10511         o->op_flags |= OPf_STACKED;
10512         op_sibling_splice(o, right, 1, varop);
10513     }
10514     else {
10515         o->op_flags &=~ OPf_STACKED;
10516         op_sibling_splice(o, right, 1, NULL);
10517     }
10518     op_free(left);
10519     return o;
10520 }
10521
10522 OP *
10523 Perl_ck_repeat(pTHX_ OP *o)
10524 {
10525     PERL_ARGS_ASSERT_CK_REPEAT;
10526
10527     if (cBINOPo->op_first->op_flags & OPf_PARENS) {
10528         OP* kids;
10529         o->op_private |= OPpREPEAT_DOLIST;
10530         kids = op_sibling_splice(o, NULL, 1, NULL); /* detach first kid */
10531         kids = force_list(kids, 1); /* promote it to a list */
10532         op_sibling_splice(o, NULL, 0, kids); /* and add back */
10533     }
10534     else
10535         scalar(o);
10536     return o;
10537 }
10538
10539 OP *
10540 Perl_ck_require(pTHX_ OP *o)
10541 {
10542     GV* gv;
10543
10544     PERL_ARGS_ASSERT_CK_REQUIRE;
10545
10546     if (o->op_flags & OPf_KIDS) {       /* Shall we supply missing .pm? */
10547         SVOP * const kid = (SVOP*)cUNOPo->op_first;
10548         HEK *hek;
10549         U32 hash;
10550         char *s;
10551         STRLEN len;
10552         if (kid->op_type == OP_CONST) {
10553           SV * const sv = kid->op_sv;
10554           U32 const was_readonly = SvREADONLY(sv);
10555           if (kid->op_private & OPpCONST_BARE) {
10556             dVAR;
10557             const char *end;
10558
10559             if (was_readonly) {
10560                     SvREADONLY_off(sv);
10561             }   
10562             if (SvIsCOW(sv)) sv_force_normal_flags(sv, 0);
10563
10564             s = SvPVX(sv);
10565             len = SvCUR(sv);
10566             end = s + len;
10567             for (; s < end; s++) {
10568                 if (*s == ':' && s[1] == ':') {
10569                     *s = '/';
10570                     Move(s+2, s+1, end - s - 1, char);
10571                     --end;
10572                 }
10573             }
10574             SvEND_set(sv, end);
10575             sv_catpvs(sv, ".pm");
10576             PERL_HASH(hash, SvPVX(sv), SvCUR(sv));
10577             hek = share_hek(SvPVX(sv),
10578                             (SSize_t)SvCUR(sv) * (SvUTF8(sv) ? -1 : 1),
10579                             hash);
10580             sv_sethek(sv, hek);
10581             unshare_hek(hek);
10582             SvFLAGS(sv) |= was_readonly;
10583           }
10584           else if (SvPOK(sv) && !SvNIOK(sv) && !SvGMAGICAL(sv)
10585                 && !SvVOK(sv)) {
10586             s = SvPV(sv, len);
10587             if (SvREFCNT(sv) > 1) {
10588                 kid->op_sv = newSVpvn_share(
10589                     s, SvUTF8(sv) ? -(SSize_t)len : (SSize_t)len, 0);
10590                 SvREFCNT_dec_NN(sv);
10591             }
10592             else {
10593                 dVAR;
10594                 if (was_readonly) SvREADONLY_off(sv);
10595                 PERL_HASH(hash, s, len);
10596                 hek = share_hek(s,
10597                                 SvUTF8(sv) ? -(SSize_t)len : (SSize_t)len,
10598                                 hash);
10599                 sv_sethek(sv, hek);
10600                 unshare_hek(hek);
10601                 SvFLAGS(sv) |= was_readonly;
10602             }
10603           }
10604         }
10605     }
10606
10607     if (!(o->op_flags & OPf_SPECIAL) /* Wasn't written as CORE::require */
10608         /* handle override, if any */
10609      && (gv = gv_override("require", 7))) {
10610         OP *kid, *newop;
10611         if (o->op_flags & OPf_KIDS) {
10612             kid = cUNOPo->op_first;
10613             op_sibling_splice(o, NULL, -1, NULL);
10614         }
10615         else {
10616             kid = newDEFSVOP();
10617         }
10618         op_free(o);
10619         newop = S_new_entersubop(aTHX_ gv, kid);
10620         return newop;
10621     }
10622
10623     return ck_fun(o);
10624 }
10625
10626 OP *
10627 Perl_ck_return(pTHX_ OP *o)
10628 {
10629     OP *kid;
10630
10631     PERL_ARGS_ASSERT_CK_RETURN;
10632
10633     kid = OpSIBLING(cLISTOPo->op_first);
10634     if (CvLVALUE(PL_compcv)) {
10635         for (; kid; kid = OpSIBLING(kid))
10636             op_lvalue(kid, OP_LEAVESUBLV);
10637     }
10638
10639     return o;
10640 }
10641
10642 OP *
10643 Perl_ck_select(pTHX_ OP *o)
10644 {
10645     dVAR;
10646     OP* kid;
10647
10648     PERL_ARGS_ASSERT_CK_SELECT;
10649
10650     if (o->op_flags & OPf_KIDS) {
10651         kid = OpSIBLING(cLISTOPo->op_first);     /* get past pushmark */
10652         if (kid && OpHAS_SIBLING(kid)) {
10653             OpTYPE_set(o, OP_SSELECT);
10654             o = ck_fun(o);
10655             return fold_constants(op_integerize(op_std_init(o)));
10656         }
10657     }
10658     o = ck_fun(o);
10659     kid = OpSIBLING(cLISTOPo->op_first);    /* get past pushmark */
10660     if (kid && kid->op_type == OP_RV2GV)
10661         kid->op_private &= ~HINT_STRICT_REFS;
10662     return o;
10663 }
10664
10665 OP *
10666 Perl_ck_shift(pTHX_ OP *o)
10667 {
10668     const I32 type = o->op_type;
10669
10670     PERL_ARGS_ASSERT_CK_SHIFT;
10671
10672     if (!(o->op_flags & OPf_KIDS)) {
10673         OP *argop;
10674
10675         if (!CvUNIQUE(PL_compcv)) {
10676             o->op_flags |= OPf_SPECIAL;
10677             return o;
10678         }
10679
10680         argop = newUNOP(OP_RV2AV, 0, scalar(newGVOP(OP_GV, 0, PL_argvgv)));
10681         op_free(o);
10682         return newUNOP(type, 0, scalar(argop));
10683     }
10684     return scalar(ck_fun(o));
10685 }
10686
10687 OP *
10688 Perl_ck_sort(pTHX_ OP *o)
10689 {
10690     OP *firstkid;
10691     OP *kid;
10692     HV * const hinthv =
10693         PL_hints & HINT_LOCALIZE_HH ? GvHV(PL_hintgv) : NULL;
10694     U8 stacked;
10695
10696     PERL_ARGS_ASSERT_CK_SORT;
10697
10698     if (hinthv) {
10699             SV ** const svp = hv_fetchs(hinthv, "sort", FALSE);
10700             if (svp) {
10701                 const I32 sorthints = (I32)SvIV(*svp);
10702                 if ((sorthints & HINT_SORT_QUICKSORT) != 0)
10703                     o->op_private |= OPpSORT_QSORT;
10704                 if ((sorthints & HINT_SORT_STABLE) != 0)
10705                     o->op_private |= OPpSORT_STABLE;
10706             }
10707     }
10708
10709     if (o->op_flags & OPf_STACKED)
10710         simplify_sort(o);
10711     firstkid = OpSIBLING(cLISTOPo->op_first);           /* get past pushmark */
10712
10713     if ((stacked = o->op_flags & OPf_STACKED)) {        /* may have been cleared */
10714         OP *kid = cUNOPx(firstkid)->op_first;           /* get past null */
10715
10716         /* if the first arg is a code block, process it and mark sort as
10717          * OPf_SPECIAL */
10718         if (kid->op_type == OP_SCOPE || kid->op_type == OP_LEAVE) {
10719             LINKLIST(kid);
10720             if (kid->op_type == OP_LEAVE)
10721                     op_null(kid);                       /* wipe out leave */
10722             /* Prevent execution from escaping out of the sort block. */
10723             kid->op_next = 0;
10724
10725             /* provide scalar context for comparison function/block */
10726             kid = scalar(firstkid);
10727             kid->op_next = kid;
10728             o->op_flags |= OPf_SPECIAL;
10729         }
10730         else if (kid->op_type == OP_CONST
10731               && kid->op_private & OPpCONST_BARE) {
10732             char tmpbuf[256];
10733             STRLEN len;
10734             PADOFFSET off;
10735             const char * const name = SvPV(kSVOP_sv, len);
10736             *tmpbuf = '&';
10737             assert (len < 256);
10738             Copy(name, tmpbuf+1, len, char);
10739             off = pad_findmy_pvn(tmpbuf, len+1, SvUTF8(kSVOP_sv));
10740             if (off != NOT_IN_PAD) {
10741                 if (PAD_COMPNAME_FLAGS_isOUR(off)) {
10742                     SV * const fq =
10743                         newSVhek(HvNAME_HEK(PAD_COMPNAME_OURSTASH(off)));
10744                     sv_catpvs(fq, "::");
10745                     sv_catsv(fq, kSVOP_sv);
10746                     SvREFCNT_dec_NN(kSVOP_sv);
10747                     kSVOP->op_sv = fq;
10748                 }
10749                 else {
10750                     OP * const padop = newOP(OP_PADCV, 0);
10751                     padop->op_targ = off;
10752                     /* replace the const op with the pad op */
10753                     op_sibling_splice(firstkid, NULL, 1, padop);
10754                     op_free(kid);
10755                 }
10756             }
10757         }
10758
10759         firstkid = OpSIBLING(firstkid);
10760     }
10761
10762     for (kid = firstkid; kid; kid = OpSIBLING(kid)) {
10763         /* provide list context for arguments */
10764         list(kid);
10765         if (stacked)
10766             op_lvalue(kid, OP_GREPSTART);
10767     }
10768
10769     return o;
10770 }
10771
10772 /* for sort { X } ..., where X is one of
10773  *   $a <=> $b, $b <= $a, $a cmp $b, $b cmp $a
10774  * elide the second child of the sort (the one containing X),
10775  * and set these flags as appropriate
10776         OPpSORT_NUMERIC;
10777         OPpSORT_INTEGER;
10778         OPpSORT_DESCEND;
10779  * Also, check and warn on lexical $a, $b.
10780  */
10781
10782 STATIC void
10783 S_simplify_sort(pTHX_ OP *o)
10784 {
10785     OP *kid = OpSIBLING(cLISTOPo->op_first);    /* get past pushmark */
10786     OP *k;
10787     int descending;
10788     GV *gv;
10789     const char *gvname;
10790     bool have_scopeop;
10791
10792     PERL_ARGS_ASSERT_SIMPLIFY_SORT;
10793
10794     kid = kUNOP->op_first;                              /* get past null */
10795     if (!(have_scopeop = kid->op_type == OP_SCOPE)
10796      && kid->op_type != OP_LEAVE)
10797         return;
10798     kid = kLISTOP->op_last;                             /* get past scope */
10799     switch(kid->op_type) {
10800         case OP_NCMP:
10801         case OP_I_NCMP:
10802         case OP_SCMP:
10803             if (!have_scopeop) goto padkids;
10804             break;
10805         default:
10806             return;
10807     }
10808     k = kid;                                            /* remember this node*/
10809     if (kBINOP->op_first->op_type != OP_RV2SV
10810      || kBINOP->op_last ->op_type != OP_RV2SV)
10811     {
10812         /*
10813            Warn about my($a) or my($b) in a sort block, *if* $a or $b is
10814            then used in a comparison.  This catches most, but not
10815            all cases.  For instance, it catches
10816                sort { my($a); $a <=> $b }
10817            but not
10818                sort { my($a); $a < $b ? -1 : $a == $b ? 0 : 1; }
10819            (although why you'd do that is anyone's guess).
10820         */
10821
10822        padkids:
10823         if (!ckWARN(WARN_SYNTAX)) return;
10824         kid = kBINOP->op_first;
10825         do {
10826             if (kid->op_type == OP_PADSV) {
10827                 PADNAME * const name = PAD_COMPNAME(kid->op_targ);
10828                 if (PadnameLEN(name) == 2 && *PadnamePV(name) == '$'
10829                  && (  PadnamePV(name)[1] == 'a'
10830                     || PadnamePV(name)[1] == 'b'  ))
10831                     /* diag_listed_as: "my %s" used in sort comparison */
10832                     Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
10833                                      "\"%s %s\" used in sort comparison",
10834                                       PadnameIsSTATE(name)
10835                                         ? "state"
10836                                         : "my",
10837                                       PadnamePV(name));
10838             }
10839         } while ((kid = OpSIBLING(kid)));
10840         return;
10841     }
10842     kid = kBINOP->op_first;                             /* get past cmp */
10843     if (kUNOP->op_first->op_type != OP_GV)
10844         return;
10845     kid = kUNOP->op_first;                              /* get past rv2sv */
10846     gv = kGVOP_gv;
10847     if (GvSTASH(gv) != PL_curstash)
10848         return;
10849     gvname = GvNAME(gv);
10850     if (*gvname == 'a' && gvname[1] == '\0')
10851         descending = 0;
10852     else if (*gvname == 'b' && gvname[1] == '\0')
10853         descending = 1;
10854     else
10855         return;
10856
10857     kid = k;                                            /* back to cmp */
10858     /* already checked above that it is rv2sv */
10859     kid = kBINOP->op_last;                              /* down to 2nd arg */
10860     if (kUNOP->op_first->op_type != OP_GV)
10861         return;
10862     kid = kUNOP->op_first;                              /* get past rv2sv */
10863     gv = kGVOP_gv;
10864     if (GvSTASH(gv) != PL_curstash)
10865         return;
10866     gvname = GvNAME(gv);
10867     if ( descending
10868          ? !(*gvname == 'a' && gvname[1] == '\0')
10869          : !(*gvname == 'b' && gvname[1] == '\0'))
10870         return;
10871     o->op_flags &= ~(OPf_STACKED | OPf_SPECIAL);
10872     if (descending)
10873         o->op_private |= OPpSORT_DESCEND;
10874     if (k->op_type == OP_NCMP)
10875         o->op_private |= OPpSORT_NUMERIC;
10876     if (k->op_type == OP_I_NCMP)
10877         o->op_private |= OPpSORT_NUMERIC | OPpSORT_INTEGER;
10878     kid = OpSIBLING(cLISTOPo->op_first);
10879     /* cut out and delete old block (second sibling) */
10880     op_sibling_splice(o, cLISTOPo->op_first, 1, NULL);
10881     op_free(kid);
10882 }
10883
10884 OP *
10885 Perl_ck_split(pTHX_ OP *o)
10886 {
10887     dVAR;
10888     OP *kid;
10889
10890     PERL_ARGS_ASSERT_CK_SPLIT;
10891
10892     if (o->op_flags & OPf_STACKED)
10893         return no_fh_allowed(o);
10894
10895     kid = cLISTOPo->op_first;
10896     if (kid->op_type != OP_NULL)
10897         Perl_croak(aTHX_ "panic: ck_split, type=%u", (unsigned) kid->op_type);
10898     /* delete leading NULL node, then add a CONST if no other nodes */
10899     op_sibling_splice(o, NULL, 1,
10900         OpHAS_SIBLING(kid) ? NULL : newSVOP(OP_CONST, 0, newSVpvs(" ")));
10901     op_free(kid);
10902     kid = cLISTOPo->op_first;
10903
10904     if (kid->op_type != OP_MATCH || kid->op_flags & OPf_STACKED) {
10905         /* remove kid, and replace with new optree */
10906         op_sibling_splice(o, NULL, 1, NULL);
10907         /* OPf_SPECIAL is used to trigger split " " behavior */
10908         kid = pmruntime( newPMOP(OP_MATCH, OPf_SPECIAL), kid, NULL, 0, 0);
10909         op_sibling_splice(o, NULL, 0, kid);
10910     }
10911     OpTYPE_set(kid, OP_PUSHRE);
10912     /* target implies @ary=..., so wipe it */
10913     kid->op_targ = 0;
10914     scalar(kid);
10915     if (((PMOP *)kid)->op_pmflags & PMf_GLOBAL) {
10916       Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP),
10917                      "Use of /g modifier is meaningless in split");
10918     }
10919
10920     if (!OpHAS_SIBLING(kid))
10921         op_append_elem(OP_SPLIT, o, newDEFSVOP());
10922
10923     kid = OpSIBLING(kid);
10924     assert(kid);
10925     scalar(kid);
10926
10927     if (!OpHAS_SIBLING(kid))
10928     {
10929         op_append_elem(OP_SPLIT, o, newSVOP(OP_CONST, 0, newSViv(0)));
10930         o->op_private |= OPpSPLIT_IMPLIM;
10931     }
10932     assert(OpHAS_SIBLING(kid));
10933
10934     kid = OpSIBLING(kid);
10935     scalar(kid);
10936
10937     if (OpHAS_SIBLING(kid))
10938         return too_many_arguments_pv(o,OP_DESC(o), 0);
10939
10940     return o;
10941 }
10942
10943 OP *
10944 Perl_ck_stringify(pTHX_ OP *o)
10945 {
10946     OP * const kid = OpSIBLING(cUNOPo->op_first);
10947     PERL_ARGS_ASSERT_CK_STRINGIFY;
10948     if ((   kid->op_type == OP_JOIN || kid->op_type == OP_QUOTEMETA
10949          || kid->op_type == OP_LC   || kid->op_type == OP_LCFIRST
10950          || kid->op_type == OP_UC   || kid->op_type == OP_UCFIRST)
10951         && !OpHAS_SIBLING(kid)) /* syntax errs can leave extra children */
10952     {
10953         op_sibling_splice(o, cUNOPo->op_first, -1, NULL);
10954         op_free(o);
10955         return kid;
10956     }
10957     return ck_fun(o);
10958 }
10959         
10960 OP *
10961 Perl_ck_join(pTHX_ OP *o)
10962 {
10963     OP * const kid = OpSIBLING(cLISTOPo->op_first);
10964
10965     PERL_ARGS_ASSERT_CK_JOIN;
10966
10967     if (kid && kid->op_type == OP_MATCH) {
10968         if (ckWARN(WARN_SYNTAX)) {
10969             const REGEXP *re = PM_GETRE(kPMOP);
10970             const SV *msg = re
10971                     ? newSVpvn_flags( RX_PRECOMP_const(re), RX_PRELEN(re),
10972                                             SVs_TEMP | ( RX_UTF8(re) ? SVf_UTF8 : 0 ) )
10973                     : newSVpvs_flags( "STRING", SVs_TEMP );
10974             Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
10975                         "/%"SVf"/ should probably be written as \"%"SVf"\"",
10976                         SVfARG(msg), SVfARG(msg));
10977         }
10978     }
10979     if (kid
10980      && (kid->op_type == OP_CONST /* an innocent, unsuspicious separator */
10981         || (kid->op_type == OP_PADSV && !(kid->op_private & OPpLVAL_INTRO))
10982         || (  kid->op_type==OP_RV2SV && kUNOP->op_first->op_type == OP_GV
10983            && !(kid->op_private & (OPpLVAL_INTRO|OPpOUR_INTRO)))))
10984     {
10985         const OP * const bairn = OpSIBLING(kid); /* the list */
10986         if (bairn && !OpHAS_SIBLING(bairn) /* single-item list */
10987          && OP_GIMME(bairn,0) == G_SCALAR)
10988         {
10989             OP * const ret = op_convert_list(OP_STRINGIFY, OPf_FOLDED,
10990                                      op_sibling_splice(o, kid, 1, NULL));
10991             op_free(o);
10992             return ret;
10993         }
10994     }
10995
10996     return ck_fun(o);
10997 }
10998
10999 /*
11000 =for apidoc Am|CV *|rv2cv_op_cv|OP *cvop|U32 flags
11001
11002 Examines an op, which is expected to identify a subroutine at runtime,
11003 and attempts to determine at compile time which subroutine it identifies.
11004 This is normally used during Perl compilation to determine whether
11005 a prototype can be applied to a function call.  C<cvop> is the op
11006 being considered, normally an C<rv2cv> op.  A pointer to the identified
11007 subroutine is returned, if it could be determined statically, and a null
11008 pointer is returned if it was not possible to determine statically.
11009
11010 Currently, the subroutine can be identified statically if the RV that the
11011 C<rv2cv> is to operate on is provided by a suitable C<gv> or C<const> op.
11012 A C<gv> op is suitable if the GV's CV slot is populated.  A C<const> op is
11013 suitable if the constant value must be an RV pointing to a CV.  Details of
11014 this process may change in future versions of Perl.  If the C<rv2cv> op
11015 has the C<OPpENTERSUB_AMPER> flag set then no attempt is made to identify
11016 the subroutine statically: this flag is used to suppress compile-time
11017 magic on a subroutine call, forcing it to use default runtime behaviour.
11018
11019 If C<flags> has the bit C<RV2CVOPCV_MARK_EARLY> set, then the handling
11020 of a GV reference is modified.  If a GV was examined and its CV slot was
11021 found to be empty, then the C<gv> op has the C<OPpEARLY_CV> flag set.
11022 If the op is not optimised away, and the CV slot is later populated with
11023 a subroutine having a prototype, that flag eventually triggers the warning
11024 "called too early to check prototype".
11025
11026 If C<flags> has the bit C<RV2CVOPCV_RETURN_NAME_GV> set, then instead
11027 of returning a pointer to the subroutine it returns a pointer to the
11028 GV giving the most appropriate name for the subroutine in this context.
11029 Normally this is just the C<CvGV> of the subroutine, but for an anonymous
11030 (C<CvANON>) subroutine that is referenced through a GV it will be the
11031 referencing GV.  The resulting C<GV*> is cast to C<CV*> to be returned.
11032 A null pointer is returned as usual if there is no statically-determinable
11033 subroutine.
11034
11035 =cut
11036 */
11037
11038 /* shared by toke.c:yylex */
11039 CV *
11040 Perl_find_lexical_cv(pTHX_ PADOFFSET off)
11041 {
11042     PADNAME *name = PAD_COMPNAME(off);
11043     CV *compcv = PL_compcv;
11044     while (PadnameOUTER(name)) {
11045         assert(PARENT_PAD_INDEX(name));
11046         compcv = CvOUTSIDE(compcv);
11047         name = PadlistNAMESARRAY(CvPADLIST(compcv))
11048                 [off = PARENT_PAD_INDEX(name)];
11049     }
11050     assert(!PadnameIsOUR(name));
11051     if (!PadnameIsSTATE(name) && PadnamePROTOCV(name)) {
11052         return PadnamePROTOCV(name);
11053     }
11054     return (CV *)AvARRAY(PadlistARRAY(CvPADLIST(compcv))[1])[off];
11055 }
11056
11057 CV *
11058 Perl_rv2cv_op_cv(pTHX_ OP *cvop, U32 flags)
11059 {
11060     OP *rvop;
11061     CV *cv;
11062     GV *gv;
11063     PERL_ARGS_ASSERT_RV2CV_OP_CV;
11064     if (flags & ~RV2CVOPCV_FLAG_MASK)
11065         Perl_croak(aTHX_ "panic: rv2cv_op_cv bad flags %x", (unsigned)flags);
11066     if (cvop->op_type != OP_RV2CV)
11067         return NULL;
11068     if (cvop->op_private & OPpENTERSUB_AMPER)
11069         return NULL;
11070     if (!(cvop->op_flags & OPf_KIDS))
11071         return NULL;
11072     rvop = cUNOPx(cvop)->op_first;
11073     switch (rvop->op_type) {
11074         case OP_GV: {
11075             gv = cGVOPx_gv(rvop);
11076             if (!isGV(gv)) {
11077                 if (SvROK(gv) && SvTYPE(SvRV(gv)) == SVt_PVCV) {
11078                     cv = MUTABLE_CV(SvRV(gv));
11079                     gv = NULL;
11080                     break;
11081                 }
11082                 if (flags & RV2CVOPCV_RETURN_STUB)
11083                     return (CV *)gv;
11084                 else return NULL;
11085             }
11086             cv = GvCVu(gv);
11087             if (!cv) {
11088                 if (flags & RV2CVOPCV_MARK_EARLY)
11089                     rvop->op_private |= OPpEARLY_CV;
11090                 return NULL;
11091             }
11092         } break;
11093         case OP_CONST: {
11094             SV *rv = cSVOPx_sv(rvop);
11095             if (!SvROK(rv))
11096                 return NULL;
11097             cv = (CV*)SvRV(rv);
11098             gv = NULL;
11099         } break;
11100         case OP_PADCV: {
11101             cv = find_lexical_cv(rvop->op_targ);
11102             gv = NULL;
11103         } break;
11104         default: {
11105             return NULL;
11106         } NOT_REACHED; /* NOTREACHED */
11107     }
11108     if (SvTYPE((SV*)cv) != SVt_PVCV)
11109         return NULL;
11110     if (flags & (RV2CVOPCV_RETURN_NAME_GV|RV2CVOPCV_MAYBE_NAME_GV)) {
11111         if ((!CvANON(cv) || !gv) && !CvLEXICAL(cv)
11112          && ((flags & RV2CVOPCV_RETURN_NAME_GV) || !CvNAMED(cv)))
11113             gv = CvGV(cv);
11114         return (CV*)gv;
11115     } else {
11116         return cv;
11117     }
11118 }
11119
11120 /*
11121 =for apidoc Am|OP *|ck_entersub_args_list|OP *entersubop
11122
11123 Performs the default fixup of the arguments part of an C<entersub>
11124 op tree.  This consists of applying list context to each of the
11125 argument ops.  This is the standard treatment used on a call marked
11126 with C<&>, or a method call, or a call through a subroutine reference,
11127 or any other call where the callee can't be identified at compile time,
11128 or a call where the callee has no prototype.
11129
11130 =cut
11131 */
11132
11133 OP *
11134 Perl_ck_entersub_args_list(pTHX_ OP *entersubop)
11135 {
11136     OP *aop;
11137     PERL_ARGS_ASSERT_CK_ENTERSUB_ARGS_LIST;
11138     aop = cUNOPx(entersubop)->op_first;
11139     if (!OpHAS_SIBLING(aop))
11140         aop = cUNOPx(aop)->op_first;
11141     for (aop = OpSIBLING(aop); OpHAS_SIBLING(aop); aop = OpSIBLING(aop)) {
11142         list(aop);
11143         op_lvalue(aop, OP_ENTERSUB);
11144     }
11145     return entersubop;
11146 }
11147
11148 /*
11149 =for apidoc Am|OP *|ck_entersub_args_proto|OP *entersubop|GV *namegv|SV *protosv
11150
11151 Performs the fixup of the arguments part of an C<entersub> op tree
11152 based on a subroutine prototype.  This makes various modifications to
11153 the argument ops, from applying context up to inserting C<refgen> ops,
11154 and checking the number and syntactic types of arguments, as directed by
11155 the prototype.  This is the standard treatment used on a subroutine call,
11156 not marked with C<&>, where the callee can be identified at compile time
11157 and has a prototype.
11158
11159 C<protosv> supplies the subroutine prototype to be applied to the call.
11160 It may be a normal defined scalar, of which the string value will be used.
11161 Alternatively, for convenience, it may be a subroutine object (a C<CV*>
11162 that has been cast to C<SV*>) which has a prototype.  The prototype
11163 supplied, in whichever form, does not need to match the actual callee
11164 referenced by the op tree.
11165
11166 If the argument ops disagree with the prototype, for example by having
11167 an unacceptable number of arguments, a valid op tree is returned anyway.
11168 The error is reflected in the parser state, normally resulting in a single
11169 exception at the top level of parsing which covers all the compilation
11170 errors that occurred.  In the error message, the callee is referred to
11171 by the name defined by the C<namegv> parameter.
11172
11173 =cut
11174 */
11175
11176 OP *
11177 Perl_ck_entersub_args_proto(pTHX_ OP *entersubop, GV *namegv, SV *protosv)
11178 {
11179     STRLEN proto_len;
11180     const char *proto, *proto_end;
11181     OP *aop, *prev, *cvop, *parent;
11182     int optional = 0;
11183     I32 arg = 0;
11184     I32 contextclass = 0;
11185     const char *e = NULL;
11186     PERL_ARGS_ASSERT_CK_ENTERSUB_ARGS_PROTO;
11187     if (SvTYPE(protosv) == SVt_PVCV ? !SvPOK(protosv) : !SvOK(protosv))
11188         Perl_croak(aTHX_ "panic: ck_entersub_args_proto CV with no proto, "
11189                    "flags=%lx", (unsigned long) SvFLAGS(protosv));
11190     if (SvTYPE(protosv) == SVt_PVCV)
11191          proto = CvPROTO(protosv), proto_len = CvPROTOLEN(protosv);
11192     else proto = SvPV(protosv, proto_len);
11193     proto = S_strip_spaces(aTHX_ proto, &proto_len);
11194     proto_end = proto + proto_len;
11195     parent = entersubop;
11196     aop = cUNOPx(entersubop)->op_first;
11197     if (!OpHAS_SIBLING(aop)) {
11198         parent = aop;
11199         aop = cUNOPx(aop)->op_first;
11200     }
11201     prev = aop;
11202     aop = OpSIBLING(aop);
11203     for (cvop = aop; OpHAS_SIBLING(cvop); cvop = OpSIBLING(cvop)) ;
11204     while (aop != cvop) {
11205         OP* o3 = aop;
11206
11207         if (proto >= proto_end)
11208         {
11209             SV * const namesv = cv_name((CV *)namegv, NULL, 0);
11210             yyerror_pv(Perl_form(aTHX_ "Too many arguments for %"SVf,
11211                                         SVfARG(namesv)), SvUTF8(namesv));
11212             return entersubop;
11213         }
11214
11215         switch (*proto) {
11216             case ';':
11217                 optional = 1;
11218                 proto++;
11219                 continue;
11220             case '_':
11221                 /* _ must be at the end */
11222                 if (proto[1] && !strchr(";@%", proto[1]))
11223                     goto oops;
11224                 /* FALLTHROUGH */
11225             case '$':
11226                 proto++;
11227                 arg++;
11228                 scalar(aop);
11229                 break;
11230             case '%':
11231             case '@':
11232                 list(aop);
11233                 arg++;
11234                 break;
11235             case '&':
11236                 proto++;
11237                 arg++;
11238                 if (    o3->op_type != OP_UNDEF
11239                     && (o3->op_type != OP_SREFGEN
11240                         || (  cUNOPx(cUNOPx(o3)->op_first)->op_first->op_type
11241                                 != OP_ANONCODE
11242                             && cUNOPx(cUNOPx(o3)->op_first)->op_first->op_type
11243                                 != OP_RV2CV)))
11244                     bad_type_gv(arg, namegv, o3,
11245                             arg == 1 ? "block or sub {}" : "sub {}");
11246                 break;
11247             case '*':
11248                 /* '*' allows any scalar type, including bareword */
11249                 proto++;
11250                 arg++;
11251                 if (o3->op_type == OP_RV2GV)
11252                     goto wrapref;       /* autoconvert GLOB -> GLOBref */
11253                 else if (o3->op_type == OP_CONST)
11254                     o3->op_private &= ~OPpCONST_STRICT;
11255                 scalar(aop);
11256                 break;
11257             case '+':
11258                 proto++;
11259                 arg++;
11260                 if (o3->op_type == OP_RV2AV ||
11261                     o3->op_type == OP_PADAV ||
11262                     o3->op_type == OP_RV2HV ||
11263                     o3->op_type == OP_PADHV
11264                 ) {
11265                     goto wrapref;
11266                 }
11267                 scalar(aop);
11268                 break;
11269             case '[': case ']':
11270                 goto oops;
11271
11272             case '\\':
11273                 proto++;
11274                 arg++;
11275             again:
11276                 switch (*proto++) {
11277                     case '[':
11278                         if (contextclass++ == 0) {
11279                             e = strchr(proto, ']');
11280                             if (!e || e == proto)
11281                                 goto oops;
11282                         }
11283                         else
11284                             goto oops;
11285                         goto again;
11286
11287                     case ']':
11288                         if (contextclass) {
11289                             const char *p = proto;
11290                             const char *const end = proto;
11291                             contextclass = 0;
11292                             while (*--p != '[')
11293                                 /* \[$] accepts any scalar lvalue */
11294                                 if (*p == '$'
11295                                  && Perl_op_lvalue_flags(aTHX_
11296                                      scalar(o3),
11297                                      OP_READ, /* not entersub */
11298                                      OP_LVALUE_NO_CROAK
11299                                     )) goto wrapref;
11300                             bad_type_gv(arg, namegv, o3,
11301                                     Perl_form(aTHX_ "one of %.*s",(int)(end - p), p));
11302                         } else
11303                             goto oops;
11304                         break;
11305                     case '*':
11306                         if (o3->op_type == OP_RV2GV)
11307                             goto wrapref;
11308                         if (!contextclass)
11309                             bad_type_gv(arg, namegv, o3, "symbol");
11310                         break;
11311                     case '&':
11312                         if (o3->op_type == OP_ENTERSUB
11313                          && !(o3->op_flags & OPf_STACKED))
11314                             goto wrapref;
11315                         if (!contextclass)
11316                             bad_type_gv(arg, namegv, o3, "subroutine");
11317                         break;
11318                     case '$':
11319                         if (o3->op_type == OP_RV2SV ||
11320                                 o3->op_type == OP_PADSV ||
11321                                 o3->op_type == OP_HELEM ||
11322                                 o3->op_type == OP_AELEM)
11323                             goto wrapref;
11324                         if (!contextclass) {
11325                             /* \$ accepts any scalar lvalue */
11326                             if (Perl_op_lvalue_flags(aTHX_
11327                                     scalar(o3),
11328                                     OP_READ,  /* not entersub */
11329                                     OP_LVALUE_NO_CROAK
11330                                )) goto wrapref;
11331                             bad_type_gv(arg, namegv, o3, "scalar");
11332                         }
11333                         break;
11334                     case '@':
11335                         if (o3->op_type == OP_RV2AV ||
11336                                 o3->op_type == OP_PADAV)
11337                         {
11338                             o3->op_flags &=~ OPf_PARENS;
11339                             goto wrapref;
11340                         }
11341                         if (!contextclass)
11342                             bad_type_gv(arg, namegv, o3, "array");
11343                         break;
11344                     case '%':
11345                         if (o3->op_type == OP_RV2HV ||
11346                                 o3->op_type == OP_PADHV)
11347                         {
11348                             o3->op_flags &=~ OPf_PARENS;
11349                             goto wrapref;
11350                         }
11351                         if (!contextclass)
11352                             bad_type_gv(arg, namegv, o3, "hash");
11353                         break;
11354                     wrapref:
11355                             aop = S_op_sibling_newUNOP(aTHX_ parent, prev,
11356                                                 OP_REFGEN, 0);
11357                         if (contextclass && e) {
11358                             proto = e + 1;
11359                             contextclass = 0;
11360                         }
11361                         break;
11362                     default: goto oops;
11363                 }
11364                 if (contextclass)
11365                     goto again;
11366                 break;
11367             case ' ':
11368                 proto++;
11369                 continue;
11370             default:
11371             oops: {
11372                 Perl_croak(aTHX_ "Malformed prototype for %"SVf": %"SVf,
11373                                   SVfARG(cv_name((CV *)namegv, NULL, 0)),
11374                                   SVfARG(protosv));
11375             }
11376         }
11377
11378         op_lvalue(aop, OP_ENTERSUB);
11379         prev = aop;
11380         aop = OpSIBLING(aop);
11381     }
11382     if (aop == cvop && *proto == '_') {
11383         /* generate an access to $_ */
11384         op_sibling_splice(parent, prev, 0, newDEFSVOP());
11385     }
11386     if (!optional && proto_end > proto &&
11387         (*proto != '@' && *proto != '%' && *proto != ';' && *proto != '_'))
11388     {
11389         SV * const namesv = cv_name((CV *)namegv, NULL, 0);
11390         yyerror_pv(Perl_form(aTHX_ "Not enough arguments for %"SVf,
11391                                     SVfARG(namesv)), SvUTF8(namesv));
11392     }
11393     return entersubop;
11394 }
11395
11396 /*
11397 =for apidoc Am|OP *|ck_entersub_args_proto_or_list|OP *entersubop|GV *namegv|SV *protosv
11398
11399 Performs the fixup of the arguments part of an C<entersub> op tree either
11400 based on a subroutine prototype or using default list-context processing.
11401 This is the standard treatment used on a subroutine call, not marked
11402 with C<&>, where the callee can be identified at compile time.
11403
11404 C<protosv> supplies the subroutine prototype to be applied to the call,
11405 or indicates that there is no prototype.  It may be a normal scalar,
11406 in which case if it is defined then the string value will be used
11407 as a prototype, and if it is undefined then there is no prototype.
11408 Alternatively, for convenience, it may be a subroutine object (a C<CV*>
11409 that has been cast to C<SV*>), of which the prototype will be used if it
11410 has one.  The prototype (or lack thereof) supplied, in whichever form,
11411 does not need to match the actual callee referenced by the op tree.
11412
11413 If the argument ops disagree with the prototype, for example by having
11414 an unacceptable number of arguments, a valid op tree is returned anyway.
11415 The error is reflected in the parser state, normally resulting in a single
11416 exception at the top level of parsing which covers all the compilation
11417 errors that occurred.  In the error message, the callee is referred to
11418 by the name defined by the C<namegv> parameter.
11419
11420 =cut
11421 */
11422
11423 OP *
11424 Perl_ck_entersub_args_proto_or_list(pTHX_ OP *entersubop,
11425         GV *namegv, SV *protosv)
11426 {
11427     PERL_ARGS_ASSERT_CK_ENTERSUB_ARGS_PROTO_OR_LIST;
11428     if (SvTYPE(protosv) == SVt_PVCV ? SvPOK(protosv) : SvOK(protosv))
11429         return ck_entersub_args_proto(entersubop, namegv, protosv);
11430     else
11431         return ck_entersub_args_list(entersubop);
11432 }
11433
11434 OP *
11435 Perl_ck_entersub_args_core(pTHX_ OP *entersubop, GV *namegv, SV *protosv)
11436 {
11437     int opnum = SvTYPE(protosv) == SVt_PVCV ? 0 : (int)SvUV(protosv);
11438     OP *aop = cUNOPx(entersubop)->op_first;
11439
11440     PERL_ARGS_ASSERT_CK_ENTERSUB_ARGS_CORE;
11441
11442     if (!opnum) {
11443         OP *cvop;
11444         if (!OpHAS_SIBLING(aop))
11445             aop = cUNOPx(aop)->op_first;
11446         aop = OpSIBLING(aop);
11447         for (cvop = aop; OpSIBLING(cvop); cvop = OpSIBLING(cvop)) ;
11448         if (aop != cvop)
11449             (void)too_many_arguments_pv(entersubop, GvNAME(namegv), 0);
11450         
11451         op_free(entersubop);
11452         switch(GvNAME(namegv)[2]) {
11453         case 'F': return newSVOP(OP_CONST, 0,
11454                                         newSVpv(CopFILE(PL_curcop),0));
11455         case 'L': return newSVOP(
11456                            OP_CONST, 0,
11457                            Perl_newSVpvf(aTHX_
11458                              "%"IVdf, (IV)CopLINE(PL_curcop)
11459                            )
11460                          );
11461         case 'P': return newSVOP(OP_CONST, 0,
11462                                    (PL_curstash
11463                                      ? newSVhek(HvNAME_HEK(PL_curstash))
11464                                      : &PL_sv_undef
11465                                    )
11466                                 );
11467         }
11468         NOT_REACHED; /* NOTREACHED */
11469     }
11470     else {
11471         OP *prev, *cvop, *first, *parent;
11472         U32 flags = 0;
11473
11474         parent = entersubop;
11475         if (!OpHAS_SIBLING(aop)) {
11476             parent = aop;
11477             aop = cUNOPx(aop)->op_first;
11478         }
11479         
11480         first = prev = aop;
11481         aop = OpSIBLING(aop);
11482         /* find last sibling */
11483         for (cvop = aop;
11484              OpHAS_SIBLING(cvop);
11485              prev = cvop, cvop = OpSIBLING(cvop))
11486             ;
11487         if (!(cvop->op_private & OPpENTERSUB_NOPAREN)
11488             /* Usually, OPf_SPECIAL on an op with no args means that it had
11489              * parens, but these have their own meaning for that flag: */
11490             && opnum != OP_VALUES && opnum != OP_KEYS && opnum != OP_EACH
11491             && opnum != OP_DELETE && opnum != OP_EXISTS)
11492                 flags |= OPf_SPECIAL;
11493         /* excise cvop from end of sibling chain */
11494         op_sibling_splice(parent, prev, 1, NULL);
11495         op_free(cvop);
11496         if (aop == cvop) aop = NULL;
11497
11498         /* detach remaining siblings from the first sibling, then
11499          * dispose of original optree */
11500
11501         if (aop)
11502             op_sibling_splice(parent, first, -1, NULL);
11503         op_free(entersubop);
11504
11505         if (opnum == OP_ENTEREVAL
11506          && GvNAMELEN(namegv)==9 && strnEQ(GvNAME(namegv), "evalbytes", 9))
11507             flags |= OPpEVAL_BYTES <<8;
11508         
11509         switch (PL_opargs[opnum] & OA_CLASS_MASK) {
11510         case OA_UNOP:
11511         case OA_BASEOP_OR_UNOP:
11512         case OA_FILESTATOP:
11513             return aop ? newUNOP(opnum,flags,aop) : newOP(opnum,flags);
11514         case OA_BASEOP:
11515             if (aop) {
11516                     (void)too_many_arguments_pv(aop, GvNAME(namegv), 0);
11517                 op_free(aop);
11518             }
11519             return opnum == OP_RUNCV
11520                 ? newPVOP(OP_RUNCV,0,NULL)
11521                 : newOP(opnum,0);
11522         default:
11523             return op_convert_list(opnum,0,aop);
11524         }
11525     }
11526     NOT_REACHED; /* NOTREACHED */
11527     return entersubop;
11528 }
11529
11530 /*
11531 =for apidoc Am|void|cv_get_call_checker|CV *cv|Perl_call_checker *ckfun_p|SV **ckobj_p
11532
11533 Retrieves the function that will be used to fix up a call to C<cv>.
11534 Specifically, the function is applied to an C<entersub> op tree for a
11535 subroutine call, not marked with C<&>, where the callee can be identified
11536 at compile time as C<cv>.
11537
11538 The C-level function pointer is returned in C<*ckfun_p>, and an SV
11539 argument for it is returned in C<*ckobj_p>.  The function is intended
11540 to be called in this manner:
11541
11542  entersubop = (*ckfun_p)(aTHX_ entersubop, namegv, (*ckobj_p));
11543
11544 In this call, C<entersubop> is a pointer to the C<entersub> op,
11545 which may be replaced by the check function, and C<namegv> is a GV
11546 supplying the name that should be used by the check function to refer
11547 to the callee of the C<entersub> op if it needs to emit any diagnostics.
11548 It is permitted to apply the check function in non-standard situations,
11549 such as to a call to a different subroutine or to a method call.
11550
11551 By default, the function is
11552 L<Perl_ck_entersub_args_proto_or_list|/ck_entersub_args_proto_or_list>,
11553 and the SV parameter is C<cv> itself.  This implements standard
11554 prototype processing.  It can be changed, for a particular subroutine,
11555 by L</cv_set_call_checker>.
11556
11557 =cut
11558 */
11559
11560 static void
11561 S_cv_get_call_checker(CV *cv, Perl_call_checker *ckfun_p, SV **ckobj_p,
11562                       U8 *flagsp)
11563 {
11564     MAGIC *callmg;
11565     callmg = SvMAGICAL((SV*)cv) ? mg_find((SV*)cv, PERL_MAGIC_checkcall) : NULL;
11566     if (callmg) {
11567         *ckfun_p = DPTR2FPTR(Perl_call_checker, callmg->mg_ptr);
11568         *ckobj_p = callmg->mg_obj;
11569         if (flagsp) *flagsp = callmg->mg_flags;
11570     } else {
11571         *ckfun_p = Perl_ck_entersub_args_proto_or_list;
11572         *ckobj_p = (SV*)cv;
11573         if (flagsp) *flagsp = 0;
11574     }
11575 }
11576
11577 void
11578 Perl_cv_get_call_checker(pTHX_ CV *cv, Perl_call_checker *ckfun_p, SV **ckobj_p)
11579 {
11580     PERL_ARGS_ASSERT_CV_GET_CALL_CHECKER;
11581     PERL_UNUSED_CONTEXT;
11582     S_cv_get_call_checker(cv, ckfun_p, ckobj_p, NULL);
11583 }
11584
11585 /*
11586 =for apidoc Am|void|cv_set_call_checker_flags|CV *cv|Perl_call_checker ckfun|SV *ckobj|U32 flags
11587
11588 Sets the function that will be used to fix up a call to C<cv>.
11589 Specifically, the function is applied to an C<entersub> op tree for a
11590 subroutine call, not marked with C<&>, where the callee can be identified
11591 at compile time as C<cv>.
11592
11593 The C-level function pointer is supplied in C<ckfun>, and an SV argument
11594 for it is supplied in C<ckobj>.  The function should be defined like this:
11595
11596     STATIC OP * ckfun(pTHX_ OP *op, GV *namegv, SV *ckobj)
11597
11598 It is intended to be called in this manner:
11599
11600     entersubop = ckfun(aTHX_ entersubop, namegv, ckobj);
11601
11602 In this call, C<entersubop> is a pointer to the C<entersub> op,
11603 which may be replaced by the check function, and C<namegv> supplies
11604 the name that should be used by the check function to refer
11605 to the callee of the C<entersub> op if it needs to emit any diagnostics.
11606 It is permitted to apply the check function in non-standard situations,
11607 such as to a call to a different subroutine or to a method call.
11608
11609 C<namegv> may not actually be a GV.  For efficiency, perl may pass a
11610 CV or other SV instead.  Whatever is passed can be used as the first
11611 argument to L</cv_name>.  You can force perl to pass a GV by including
11612 C<CALL_CHECKER_REQUIRE_GV> in the C<flags>.
11613
11614 The current setting for a particular CV can be retrieved by
11615 L</cv_get_call_checker>.
11616
11617 =for apidoc Am|void|cv_set_call_checker|CV *cv|Perl_call_checker ckfun|SV *ckobj
11618
11619 The original form of L</cv_set_call_checker_flags>, which passes it the
11620 C<CALL_CHECKER_REQUIRE_GV> flag for backward-compatibility.
11621
11622 =cut
11623 */
11624
11625 void
11626 Perl_cv_set_call_checker(pTHX_ CV *cv, Perl_call_checker ckfun, SV *ckobj)
11627 {
11628     PERL_ARGS_ASSERT_CV_SET_CALL_CHECKER;
11629     cv_set_call_checker_flags(cv, ckfun, ckobj, CALL_CHECKER_REQUIRE_GV);
11630 }
11631
11632 void
11633 Perl_cv_set_call_checker_flags(pTHX_ CV *cv, Perl_call_checker ckfun,
11634                                      SV *ckobj, U32 flags)
11635 {
11636     PERL_ARGS_ASSERT_CV_SET_CALL_CHECKER_FLAGS;
11637     if (ckfun == Perl_ck_entersub_args_proto_or_list && ckobj == (SV*)cv) {
11638         if (SvMAGICAL((SV*)cv))
11639             mg_free_type((SV*)cv, PERL_MAGIC_checkcall);
11640     } else {
11641         MAGIC *callmg;
11642         sv_magic((SV*)cv, &PL_sv_undef, PERL_MAGIC_checkcall, NULL, 0);
11643         callmg = mg_find((SV*)cv, PERL_MAGIC_checkcall);
11644         assert(callmg);
11645         if (callmg->mg_flags & MGf_REFCOUNTED) {
11646             SvREFCNT_dec(callmg->mg_obj);
11647             callmg->mg_flags &= ~MGf_REFCOUNTED;
11648         }
11649         callmg->mg_ptr = FPTR2DPTR(char *, ckfun);
11650         callmg->mg_obj = ckobj;
11651         if (ckobj != (SV*)cv) {
11652             SvREFCNT_inc_simple_void_NN(ckobj);
11653             callmg->mg_flags |= MGf_REFCOUNTED;
11654         }
11655         callmg->mg_flags = (callmg->mg_flags &~ MGf_REQUIRE_GV)
11656                          | (U8)(flags & MGf_REQUIRE_GV) | MGf_COPY;
11657     }
11658 }
11659
11660 static void
11661 S_entersub_alloc_targ(pTHX_ OP * const o)
11662 {
11663     o->op_targ = pad_alloc(OP_ENTERSUB, SVs_PADTMP);
11664     o->op_private |= OPpENTERSUB_HASTARG;
11665 }
11666
11667 OP *
11668 Perl_ck_subr(pTHX_ OP *o)
11669 {
11670     OP *aop, *cvop;
11671     CV *cv;
11672     GV *namegv;
11673     SV **const_class = NULL;
11674
11675     PERL_ARGS_ASSERT_CK_SUBR;
11676
11677     aop = cUNOPx(o)->op_first;
11678     if (!OpHAS_SIBLING(aop))
11679         aop = cUNOPx(aop)->op_first;
11680     aop = OpSIBLING(aop);
11681     for (cvop = aop; OpHAS_SIBLING(cvop); cvop = OpSIBLING(cvop)) ;
11682     cv = rv2cv_op_cv(cvop, RV2CVOPCV_MARK_EARLY);
11683     namegv = cv ? (GV*)rv2cv_op_cv(cvop, RV2CVOPCV_MAYBE_NAME_GV) : NULL;
11684
11685     o->op_private &= ~1;
11686     o->op_private |= (PL_hints & HINT_STRICT_REFS);
11687     if (PERLDB_SUB && PL_curstash != PL_debstash)
11688         o->op_private |= OPpENTERSUB_DB;
11689     switch (cvop->op_type) {
11690         case OP_RV2CV:
11691             o->op_private |= (cvop->op_private & OPpENTERSUB_AMPER);
11692             op_null(cvop);
11693             break;
11694         case OP_METHOD:
11695         case OP_METHOD_NAMED:
11696         case OP_METHOD_SUPER:
11697         case OP_METHOD_REDIR:
11698         case OP_METHOD_REDIR_SUPER:
11699             if (aop->op_type == OP_CONST) {
11700                 aop->op_private &= ~OPpCONST_STRICT;
11701                 const_class = &cSVOPx(aop)->op_sv;
11702             }
11703             else if (aop->op_type == OP_LIST) {
11704                 OP * const sib = OpSIBLING(((UNOP*)aop)->op_first);
11705                 if (sib && sib->op_type == OP_CONST) {
11706                     sib->op_private &= ~OPpCONST_STRICT;
11707                     const_class = &cSVOPx(sib)->op_sv;
11708                 }
11709             }
11710             /* make class name a shared cow string to speedup method calls */
11711             /* constant string might be replaced with object, f.e. bigint */
11712             if (const_class && SvPOK(*const_class)) {
11713                 STRLEN len;
11714                 const char* str = SvPV(*const_class, len);
11715                 if (len) {
11716                     SV* const shared = newSVpvn_share(
11717                         str, SvUTF8(*const_class)
11718                                     ? -(SSize_t)len : (SSize_t)len,
11719                         0
11720                     );
11721                     if (SvREADONLY(*const_class))
11722                         SvREADONLY_on(shared);
11723                     SvREFCNT_dec(*const_class);
11724                     *const_class = shared;
11725                 }
11726             }
11727             break;
11728     }
11729
11730     if (!cv) {
11731         S_entersub_alloc_targ(aTHX_ o);
11732         return ck_entersub_args_list(o);
11733     } else {
11734         Perl_call_checker ckfun;
11735         SV *ckobj;
11736         U8 flags;
11737         S_cv_get_call_checker(cv, &ckfun, &ckobj, &flags);
11738         if (CvISXSUB(cv) || !CvROOT(cv))
11739             S_entersub_alloc_targ(aTHX_ o);
11740         if (!namegv) {
11741             /* The original call checker API guarantees that a GV will be
11742                be provided with the right name.  So, if the old API was
11743                used (or the REQUIRE_GV flag was passed), we have to reify
11744                the CV’s GV, unless this is an anonymous sub.  This is not
11745                ideal for lexical subs, as its stringification will include
11746                the package.  But it is the best we can do.  */
11747             if (flags & MGf_REQUIRE_GV) {
11748                 if (!CvANON(cv) && (!CvNAMED(cv) || CvNAME_HEK(cv)))
11749                     namegv = CvGV(cv);
11750             }
11751             else namegv = MUTABLE_GV(cv);
11752             /* After a syntax error in a lexical sub, the cv that
11753                rv2cv_op_cv returns may be a nameless stub. */
11754             if (!namegv) return ck_entersub_args_list(o);
11755
11756         }
11757         return ckfun(aTHX_ o, namegv, ckobj);
11758     }
11759 }
11760
11761 OP *
11762 Perl_ck_svconst(pTHX_ OP *o)
11763 {
11764     SV * const sv = cSVOPo->op_sv;
11765     PERL_ARGS_ASSERT_CK_SVCONST;
11766     PERL_UNUSED_CONTEXT;
11767 #ifdef PERL_COPY_ON_WRITE
11768     /* Since the read-only flag may be used to protect a string buffer, we
11769        cannot do copy-on-write with existing read-only scalars that are not
11770        already copy-on-write scalars.  To allow $_ = "hello" to do COW with
11771        that constant, mark the constant as COWable here, if it is not
11772        already read-only. */
11773     if (!SvREADONLY(sv) && !SvIsCOW(sv) && SvCANCOW(sv)) {
11774         SvIsCOW_on(sv);
11775         CowREFCNT(sv) = 0;
11776 # ifdef PERL_DEBUG_READONLY_COW
11777         sv_buf_to_ro(sv);
11778 # endif
11779     }
11780 #endif
11781     SvREADONLY_on(sv);
11782     return o;
11783 }
11784
11785 OP *
11786 Perl_ck_trunc(pTHX_ OP *o)
11787 {
11788     PERL_ARGS_ASSERT_CK_TRUNC;
11789
11790     if (o->op_flags & OPf_KIDS) {
11791         SVOP *kid = (SVOP*)cUNOPo->op_first;
11792
11793         if (kid->op_type == OP_NULL)
11794             kid = (SVOP*)OpSIBLING(kid);
11795         if (kid && kid->op_type == OP_CONST &&
11796             (kid->op_private & OPpCONST_BARE) &&
11797             !kid->op_folded)
11798         {
11799             o->op_flags |= OPf_SPECIAL;
11800             kid->op_private &= ~OPpCONST_STRICT;
11801         }
11802     }
11803     return ck_fun(o);
11804 }
11805
11806 OP *
11807 Perl_ck_substr(pTHX_ OP *o)
11808 {
11809     PERL_ARGS_ASSERT_CK_SUBSTR;
11810
11811     o = ck_fun(o);
11812     if ((o->op_flags & OPf_KIDS) && (o->op_private == 4)) {
11813         OP *kid = cLISTOPo->op_first;
11814
11815         if (kid->op_type == OP_NULL)
11816             kid = OpSIBLING(kid);
11817         if (kid)
11818             kid->op_flags |= OPf_MOD;
11819
11820     }
11821     return o;
11822 }
11823
11824 OP *
11825 Perl_ck_tell(pTHX_ OP *o)
11826 {
11827     PERL_ARGS_ASSERT_CK_TELL;
11828     o = ck_fun(o);
11829     if (o->op_flags & OPf_KIDS) {
11830      OP *kid = cLISTOPo->op_first;
11831      if (kid->op_type == OP_NULL && OpHAS_SIBLING(kid)) kid = OpSIBLING(kid);
11832      if (kid->op_type == OP_RV2GV) kid->op_private |= OPpALLOW_FAKE;
11833     }
11834     return o;
11835 }
11836
11837 OP *
11838 Perl_ck_each(pTHX_ OP *o)
11839 {
11840     dVAR;
11841     OP *kid = o->op_flags & OPf_KIDS ? cUNOPo->op_first : NULL;
11842     const unsigned orig_type  = o->op_type;
11843
11844     PERL_ARGS_ASSERT_CK_EACH;
11845
11846     if (kid) {
11847         switch (kid->op_type) {
11848             case OP_PADHV:
11849             case OP_RV2HV:
11850                 break;
11851             case OP_PADAV:
11852             case OP_RV2AV:
11853                 OpTYPE_set(o, orig_type == OP_EACH ? OP_AEACH
11854                             : orig_type == OP_KEYS ? OP_AKEYS
11855                             :                        OP_AVALUES);
11856                 break;
11857             case OP_CONST:
11858                 if (kid->op_private == OPpCONST_BARE
11859                  || !SvROK(cSVOPx_sv(kid))
11860                  || (  SvTYPE(SvRV(cSVOPx_sv(kid))) != SVt_PVAV
11861                     && SvTYPE(SvRV(cSVOPx_sv(kid))) != SVt_PVHV  )
11862                    )
11863                     /* we let ck_fun handle it */
11864                     break;
11865             default:
11866                 Perl_croak_nocontext(
11867                     "Experimental %s on scalar is now forbidden",
11868                     PL_op_desc[orig_type]);
11869                 break;
11870         }
11871     }
11872     return ck_fun(o);
11873 }
11874
11875 OP *
11876 Perl_ck_length(pTHX_ OP *o)
11877 {
11878     PERL_ARGS_ASSERT_CK_LENGTH;
11879
11880     o = ck_fun(o);
11881
11882     if (ckWARN(WARN_SYNTAX)) {
11883         const OP *kid = o->op_flags & OPf_KIDS ? cLISTOPo->op_first : NULL;
11884
11885         if (kid) {
11886             SV *name = NULL;
11887             const bool hash = kid->op_type == OP_PADHV
11888                            || kid->op_type == OP_RV2HV;
11889             switch (kid->op_type) {
11890                 case OP_PADHV:
11891                 case OP_PADAV:
11892                 case OP_RV2HV:
11893                 case OP_RV2AV:
11894                     name = S_op_varname(aTHX_ kid);
11895                     break;
11896                 default:
11897                     return o;
11898             }
11899             if (name)
11900                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
11901                     "length() used on %"SVf" (did you mean \"scalar(%s%"SVf
11902                     ")\"?)",
11903                     SVfARG(name), hash ? "keys " : "", SVfARG(name)
11904                 );
11905             else if (hash)
11906      /* diag_listed_as: length() used on %s (did you mean "scalar(%s)"?) */
11907                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
11908                     "length() used on %%hash (did you mean \"scalar(keys %%hash)\"?)");
11909             else
11910      /* diag_listed_as: length() used on %s (did you mean "scalar(%s)"?) */
11911                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
11912                     "length() used on @array (did you mean \"scalar(@array)\"?)");
11913         }
11914     }
11915
11916     return o;
11917 }
11918
11919
11920
11921 /* 
11922    ---------------------------------------------------------
11923  
11924    Common vars in list assignment
11925
11926    There now follows some enums and static functions for detecting
11927    common variables in list assignments. Here is a little essay I wrote
11928    for myself when trying to get my head around this. DAPM.
11929
11930    ----
11931
11932    First some random observations:
11933    
11934    * If a lexical var is an alias of something else, e.g.
11935        for my $x ($lex, $pkg, $a[0]) {...}
11936      then the act of aliasing will increase the reference count of the SV
11937    
11938    * If a package var is an alias of something else, it may still have a
11939      reference count of 1, depending on how the alias was created, e.g.
11940      in *a = *b, $a may have a refcount of 1 since the GP is shared
11941      with a single GvSV pointer to the SV. So If it's an alias of another
11942      package var, then RC may be 1; if it's an alias of another scalar, e.g.
11943      a lexical var or an array element, then it will have RC > 1.
11944    
11945    * There are many ways to create a package alias; ultimately, XS code
11946      may quite legally do GvSV(gv) = SvREFCNT_inc(sv) for example, so
11947      run-time tracing mechanisms are unlikely to be able to catch all cases.
11948    
11949    * When the LHS is all my declarations, the same vars can't appear directly
11950      on the RHS, but they can indirectly via closures, aliasing and lvalue
11951      subs. But those techniques all involve an increase in the lexical
11952      scalar's ref count.
11953    
11954    * When the LHS is all lexical vars (but not necessarily my declarations),
11955      it is possible for the same lexicals to appear directly on the RHS, and
11956      without an increased ref count, since the stack isn't refcounted.
11957      This case can be detected at compile time by scanning for common lex
11958      vars with PL_generation.
11959    
11960    * lvalue subs defeat common var detection, but they do at least
11961      return vars with a temporary ref count increment. Also, you can't
11962      tell at compile time whether a sub call is lvalue.
11963    
11964     
11965    So...
11966          
11967    A: There are a few circumstances where there definitely can't be any
11968      commonality:
11969    
11970        LHS empty:  () = (...);
11971        RHS empty:  (....) = ();
11972        RHS contains only constants or other 'can't possibly be shared'
11973            elements (e.g. ops that return PADTMPs):  (...) = (1,2, length)
11974            i.e. they only contain ops not marked as dangerous, whose children
11975            are also not dangerous;
11976        LHS ditto;
11977        LHS contains a single scalar element: e.g. ($x) = (....); because
11978            after $x has been modified, it won't be used again on the RHS;
11979        RHS contains a single element with no aggregate on LHS: e.g.
11980            ($a,$b,$c)  = ($x); again, once $a has been modified, its value
11981            won't be used again.
11982    
11983    B: If LHS are all 'my' lexical var declarations (or safe ops, which
11984      we can ignore):
11985    
11986        my ($a, $b, @c) = ...;
11987    
11988        Due to closure and goto tricks, these vars may already have content.
11989        For the same reason, an element on the RHS may be a lexical or package
11990        alias of one of the vars on the left, or share common elements, for
11991        example:
11992    
11993            my ($x,$y) = f(); # $x and $y on both sides
11994            sub f : lvalue { ($x,$y) = (1,2); $y, $x }
11995    
11996        and
11997    
11998            my $ra = f();
11999            my @a = @$ra;  # elements of @a on both sides
12000            sub f { @a = 1..4; \@a }
12001    
12002    
12003        First, just consider scalar vars on LHS:
12004    
12005            RHS is safe only if (A), or in addition,
12006                * contains only lexical *scalar* vars, where neither side's
12007                  lexicals have been flagged as aliases 
12008    
12009            If RHS is not safe, then it's always legal to check LHS vars for
12010            RC==1, since the only RHS aliases will always be associated
12011            with an RC bump.
12012    
12013            Note that in particular, RHS is not safe if:
12014    
12015                * it contains package scalar vars; e.g.:
12016    
12017                    f();
12018                    my ($x, $y) = (2, $x_alias);
12019                    sub f { $x = 1; *x_alias = \$x; }
12020    
12021                * It contains other general elements, such as flattened or
12022                * spliced or single array or hash elements, e.g.
12023    
12024                    f();
12025                    my ($x,$y) = @a; # or $a[0] or @a{@b} etc 
12026    
12027                    sub f {
12028                        ($x, $y) = (1,2);
12029                        use feature 'refaliasing';
12030                        \($a[0], $a[1]) = \($y,$x);
12031                    }
12032    
12033                  It doesn't matter if the array/hash is lexical or package.
12034    
12035                * it contains a function call that happens to be an lvalue
12036                  sub which returns one or more of the above, e.g.
12037    
12038                    f();
12039                    my ($x,$y) = f();
12040    
12041                    sub f : lvalue {
12042                        ($x, $y) = (1,2);
12043                        *x1 = \$x;
12044                        $y, $x1;
12045                    }
12046    
12047                    (so a sub call on the RHS should be treated the same
12048                    as having a package var on the RHS).
12049    
12050                * any other "dangerous" thing, such an op or built-in that
12051                  returns one of the above, e.g. pp_preinc
12052    
12053    
12054            If RHS is not safe, what we can do however is at compile time flag
12055            that the LHS are all my declarations, and at run time check whether
12056            all the LHS have RC == 1, and if so skip the full scan.
12057    
12058        Now consider array and hash vars on LHS: e.g. my (...,@a) = ...;
12059    
12060            Here the issue is whether there can be elements of @a on the RHS
12061            which will get prematurely freed when @a is cleared prior to
12062            assignment. This is only a problem if the aliasing mechanism
12063            is one which doesn't increase the refcount - only if RC == 1
12064            will the RHS element be prematurely freed.
12065    
12066            Because the array/hash is being INTROed, it or its elements
12067            can't directly appear on the RHS:
12068    
12069                my (@a) = ($a[0], @a, etc) # NOT POSSIBLE
12070    
12071            but can indirectly, e.g.:
12072    
12073                my $r = f();
12074                my (@a) = @$r;
12075                sub f { @a = 1..3; \@a }
12076    
12077            So if the RHS isn't safe as defined by (A), we must always
12078            mortalise and bump the ref count of any remaining RHS elements
12079            when assigning to a non-empty LHS aggregate.
12080    
12081            Lexical scalars on the RHS aren't safe if they've been involved in
12082            aliasing, e.g.
12083    
12084                use feature 'refaliasing';
12085    
12086                f();
12087                \(my $lex) = \$pkg;
12088                my @a = ($lex,3); # equivalent to ($a[0],3)
12089    
12090                sub f {
12091                    @a = (1,2);
12092                    \$pkg = \$a[0];
12093                }
12094    
12095            Similarly with lexical arrays and hashes on the RHS:
12096    
12097                f();
12098                my @b;
12099                my @a = (@b);
12100    
12101                sub f {
12102                    @a = (1,2);
12103                    \$b[0] = \$a[1];
12104                    \$b[1] = \$a[0];
12105                }
12106    
12107    
12108    
12109    C: As (B), but in addition the LHS may contain non-intro lexicals, e.g.
12110        my $a; ($a, my $b) = (....);
12111    
12112        The difference between (B) and (C) is that it is now physically
12113        possible for the LHS vars to appear on the RHS too, where they
12114        are not reference counted; but in this case, the compile-time
12115        PL_generation sweep will detect such common vars.
12116    
12117        So the rules for (C) differ from (B) in that if common vars are
12118        detected, the runtime "test RC==1" optimisation can no longer be used,
12119        and a full mark and sweep is required
12120    
12121    D: As (C), but in addition the LHS may contain package vars.
12122    
12123        Since package vars can be aliased without a corresponding refcount
12124        increase, all bets are off. It's only safe if (A). E.g.
12125    
12126            my ($x, $y) = (1,2);
12127    
12128            for $x_alias ($x) {
12129                ($x_alias, $y) = (3, $x); # whoops
12130            }
12131    
12132        Ditto for LHS aggregate package vars.
12133    
12134    E: Any other dangerous ops on LHS, e.g.
12135            (f(), $a[0], @$r) = (...);
12136    
12137        this is similar to (E) in that all bets are off. In addition, it's
12138        impossible to determine at compile time whether the LHS
12139        contains a scalar or an aggregate, e.g.
12140    
12141            sub f : lvalue { @a }
12142            (f()) = 1..3;
12143
12144 * ---------------------------------------------------------
12145 */
12146
12147
12148 /* A set of bit flags returned by S_aassign_scan(). Each flag indicates
12149  * that at least one of the things flagged was seen.
12150  */
12151
12152 enum {
12153     AAS_MY_SCALAR       = 0x001, /* my $scalar */
12154     AAS_MY_AGG          = 0x002, /* aggregate: my @array or my %hash */
12155     AAS_LEX_SCALAR      = 0x004, /* $lexical */
12156     AAS_LEX_AGG         = 0x008, /* @lexical or %lexical aggregate */
12157     AAS_LEX_SCALAR_COMM = 0x010, /* $lexical seen on both sides */
12158     AAS_PKG_SCALAR      = 0x020, /* $scalar (where $scalar is pkg var) */
12159     AAS_PKG_AGG         = 0x040, /* package @array or %hash aggregate */
12160     AAS_DANGEROUS       = 0x080, /* an op (other than the above)
12161                                          that's flagged OA_DANGEROUS */
12162     AAS_SAFE_SCALAR     = 0x100, /* produces at least one scalar SV that's
12163                                         not in any of the categories above */
12164     AAS_DEFAV           = 0x200, /* contains just a single '@_' on RHS */
12165 };
12166
12167
12168
12169 /* helper function for S_aassign_scan().
12170  * check a PAD-related op for commonality and/or set its generation number.
12171  * Returns a boolean indicating whether its shared */
12172
12173 static bool
12174 S_aassign_padcheck(pTHX_ OP* o, bool rhs)
12175 {
12176     if (PAD_COMPNAME_GEN(o->op_targ) == PERL_INT_MAX)
12177         /* lexical used in aliasing */
12178         return TRUE;
12179
12180     if (rhs)
12181         return cBOOL(PAD_COMPNAME_GEN(o->op_targ) == (STRLEN)PL_generation);
12182     else
12183         PAD_COMPNAME_GEN_set(o->op_targ, PL_generation);
12184
12185     return FALSE;
12186 }
12187
12188
12189 /*
12190   Helper function for OPpASSIGN_COMMON* detection in rpeep().
12191   It scans the left or right hand subtree of the aassign op, and returns a
12192   set of flags indicating what sorts of things it found there.
12193   'rhs' indicates whether we're scanning the LHS or RHS. If the former, we
12194   set PL_generation on lexical vars; if the latter, we see if
12195   PL_generation matches.
12196   'top' indicates whether we're recursing or at the top level.
12197   'scalars_p' is a pointer to a counter of the number of scalar SVs seen.
12198   This fn will increment it by the number seen. It's not intended to
12199   be an accurate count (especially as many ops can push a variable
12200   number of SVs onto the stack); rather it's used as to test whether there
12201   can be at most 1 SV pushed; so it's only meanings are "0, 1, many".
12202 */
12203
12204 static int
12205 S_aassign_scan(pTHX_ OP* o, bool rhs, bool top, int *scalars_p)
12206 {
12207     int flags = 0;
12208     bool kid_top = FALSE;
12209
12210     /* first, look for a solitary @_ on the RHS */
12211     if (   rhs
12212         && top
12213         && (o->op_flags & OPf_KIDS)
12214         && OP_TYPE_IS_OR_WAS(o, OP_LIST)
12215     ) {
12216         OP *kid = cUNOPo->op_first;
12217         if (   (   kid->op_type == OP_PUSHMARK
12218                 || kid->op_type == OP_PADRANGE) /* ex-pushmark */
12219             && ((kid = OpSIBLING(kid)))
12220             && !OpHAS_SIBLING(kid)
12221             && kid->op_type == OP_RV2AV
12222             && !(kid->op_flags & OPf_REF)
12223             && !(kid->op_private & (OPpLVAL_INTRO|OPpMAYBE_LVSUB))
12224             && ((kid->op_flags & OPf_WANT) == OPf_WANT_LIST)
12225             && ((kid = cUNOPx(kid)->op_first))
12226             && kid->op_type == OP_GV
12227             && cGVOPx_gv(kid) == PL_defgv
12228         )
12229             flags |= AAS_DEFAV;
12230     }
12231
12232     switch (o->op_type) {
12233     case OP_GVSV:
12234         (*scalars_p)++;
12235         return AAS_PKG_SCALAR;
12236
12237     case OP_PADAV:
12238     case OP_PADHV:
12239         (*scalars_p) += 2;
12240         if (top && (o->op_flags & OPf_REF))
12241             return (o->op_private & OPpLVAL_INTRO)
12242                 ? AAS_MY_AGG : AAS_LEX_AGG;
12243         return AAS_DANGEROUS;
12244
12245     case OP_PADSV:
12246         {
12247             int comm = S_aassign_padcheck(aTHX_ o, rhs)
12248                         ?  AAS_LEX_SCALAR_COMM : 0;
12249             (*scalars_p)++;
12250             return (o->op_private & OPpLVAL_INTRO)
12251                 ? (AAS_MY_SCALAR|comm) : (AAS_LEX_SCALAR|comm);
12252         }
12253
12254     case OP_RV2AV:
12255     case OP_RV2HV:
12256         (*scalars_p) += 2;
12257         if (cUNOPx(o)->op_first->op_type != OP_GV)
12258             return AAS_DANGEROUS; /* @{expr}, %{expr} */
12259         /* @pkg, %pkg */
12260         if (top && (o->op_flags & OPf_REF))
12261             return AAS_PKG_AGG;
12262         return AAS_DANGEROUS;
12263
12264     case OP_RV2SV:
12265         (*scalars_p)++;
12266         if (cUNOPx(o)->op_first->op_type != OP_GV) {
12267             (*scalars_p) += 2;
12268             return AAS_DANGEROUS; /* ${expr} */
12269         }
12270         return AAS_PKG_SCALAR; /* $pkg */
12271
12272     case OP_SPLIT:
12273         if (cLISTOPo->op_first->op_type == OP_PUSHRE) {
12274             /* "@foo = split... " optimises away the aassign and stores its
12275              * destination array in the OP_PUSHRE that precedes it.
12276              * A flattened array is always dangerous.
12277              */
12278             (*scalars_p) += 2;
12279             return AAS_DANGEROUS;
12280         }
12281         break;
12282
12283     case OP_UNDEF:
12284         /* undef counts as a scalar on the RHS:
12285          *   (undef, $x) = ...;         # only 1 scalar on LHS: always safe
12286          *   ($x, $y)    = (undef, $x); # 2 scalars on RHS: unsafe
12287          */
12288         if (rhs)
12289             (*scalars_p)++;
12290         flags = AAS_SAFE_SCALAR;
12291         break;
12292
12293     case OP_PUSHMARK:
12294     case OP_STUB:
12295         /* these are all no-ops; they don't push a potentially common SV
12296          * onto the stack, so they are neither AAS_DANGEROUS nor
12297          * AAS_SAFE_SCALAR */
12298         return 0;
12299
12300     case OP_PADRANGE: /* Ignore padrange; checking its siblings is enough */
12301         break;
12302
12303     case OP_NULL:
12304     case OP_LIST:
12305         /* these do nothing but may have children; but their children
12306          * should also be treated as top-level */
12307         kid_top = top;
12308         break;
12309
12310     default:
12311         if (PL_opargs[o->op_type] & OA_DANGEROUS) {
12312             (*scalars_p) += 2;
12313             return AAS_DANGEROUS;
12314         }
12315
12316         if (   (PL_opargs[o->op_type] & OA_TARGLEX)
12317             && (o->op_private & OPpTARGET_MY))
12318         {
12319             (*scalars_p)++;
12320             return S_aassign_padcheck(aTHX_ o, rhs)
12321                 ? AAS_LEX_SCALAR_COMM : AAS_LEX_SCALAR;
12322         }
12323
12324         /* if its an unrecognised, non-dangerous op, assume that it
12325          * it the cause of at least one safe scalar */
12326         (*scalars_p)++;
12327         flags = AAS_SAFE_SCALAR;
12328         break;
12329     }
12330
12331     if (o->op_flags & OPf_KIDS) {
12332         OP *kid;
12333         for (kid = cUNOPo->op_first; kid; kid = OpSIBLING(kid))
12334             flags |= S_aassign_scan(aTHX_ kid, rhs, kid_top, scalars_p);
12335     }
12336     return flags;
12337 }
12338
12339
12340 /* Check for in place reverse and sort assignments like "@a = reverse @a"
12341    and modify the optree to make them work inplace */
12342
12343 STATIC void
12344 S_inplace_aassign(pTHX_ OP *o) {
12345
12346     OP *modop, *modop_pushmark;
12347     OP *oright;
12348     OP *oleft, *oleft_pushmark;
12349
12350     PERL_ARGS_ASSERT_INPLACE_AASSIGN;
12351
12352     assert((o->op_flags & OPf_WANT) == OPf_WANT_VOID);
12353
12354     assert(cUNOPo->op_first->op_type == OP_NULL);
12355     modop_pushmark = cUNOPx(cUNOPo->op_first)->op_first;
12356     assert(modop_pushmark->op_type == OP_PUSHMARK);
12357     modop = OpSIBLING(modop_pushmark);
12358
12359     if (modop->op_type != OP_SORT && modop->op_type != OP_REVERSE)
12360         return;
12361
12362     /* no other operation except sort/reverse */
12363     if (OpHAS_SIBLING(modop))
12364         return;
12365
12366     assert(cUNOPx(modop)->op_first->op_type == OP_PUSHMARK);
12367     if (!(oright = OpSIBLING(cUNOPx(modop)->op_first))) return;
12368
12369     if (modop->op_flags & OPf_STACKED) {
12370         /* skip sort subroutine/block */
12371         assert(oright->op_type == OP_NULL);
12372         oright = OpSIBLING(oright);
12373     }
12374
12375     assert(OpSIBLING(cUNOPo->op_first)->op_type == OP_NULL);
12376     oleft_pushmark = cUNOPx(OpSIBLING(cUNOPo->op_first))->op_first;
12377     assert(oleft_pushmark->op_type == OP_PUSHMARK);
12378     oleft = OpSIBLING(oleft_pushmark);
12379
12380     /* Check the lhs is an array */
12381     if (!oleft ||
12382         (oleft->op_type != OP_RV2AV && oleft->op_type != OP_PADAV)
12383         || OpHAS_SIBLING(oleft)
12384         || (oleft->op_private & OPpLVAL_INTRO)
12385     )
12386         return;
12387
12388     /* Only one thing on the rhs */
12389     if (OpHAS_SIBLING(oright))
12390         return;
12391
12392     /* check the array is the same on both sides */
12393     if (oleft->op_type == OP_RV2AV) {
12394         if (oright->op_type != OP_RV2AV
12395             || !cUNOPx(oright)->op_first
12396             || cUNOPx(oright)->op_first->op_type != OP_GV
12397             || cUNOPx(oleft )->op_first->op_type != OP_GV
12398             || cGVOPx_gv(cUNOPx(oleft)->op_first) !=
12399                cGVOPx_gv(cUNOPx(oright)->op_first)
12400         )
12401             return;
12402     }
12403     else if (oright->op_type != OP_PADAV
12404         || oright->op_targ != oleft->op_targ
12405     )
12406         return;
12407
12408     /* This actually is an inplace assignment */
12409
12410     modop->op_private |= OPpSORT_INPLACE;
12411
12412     /* transfer MODishness etc from LHS arg to RHS arg */
12413     oright->op_flags = oleft->op_flags;
12414
12415     /* remove the aassign op and the lhs */
12416     op_null(o);
12417     op_null(oleft_pushmark);
12418     if (oleft->op_type == OP_RV2AV && cUNOPx(oleft)->op_first)
12419         op_null(cUNOPx(oleft)->op_first);
12420     op_null(oleft);
12421 }
12422
12423
12424
12425 /* S_maybe_multideref(): given an op_next chain of ops beginning at 'start'
12426  * that potentially represent a series of one or more aggregate derefs
12427  * (such as $a->[1]{$key}), examine the chain, and if appropriate, convert
12428  * the whole chain to a single OP_MULTIDEREF op (maybe with a few
12429  * additional ops left in too).
12430  *
12431  * The caller will have already verified that the first few ops in the
12432  * chain following 'start' indicate a multideref candidate, and will have
12433  * set 'orig_o' to the point further on in the chain where the first index
12434  * expression (if any) begins.  'orig_action' specifies what type of
12435  * beginning has already been determined by the ops between start..orig_o
12436  * (e.g.  $lex_ary[], $pkg_ary->{}, expr->[], etc).
12437  *
12438  * 'hints' contains any hints flags that need adding (currently just
12439  * OPpHINT_STRICT_REFS) as found in any rv2av/hv skipped by the caller.
12440  */
12441
12442 void
12443 S_maybe_multideref(pTHX_ OP *start, OP *orig_o, UV orig_action, U8 hints)
12444 {
12445     dVAR;
12446     int pass;
12447     UNOP_AUX_item *arg_buf = NULL;
12448     bool reset_start_targ  = FALSE; /* start->op_targ needs zeroing */
12449     int index_skip         = -1;    /* don't output index arg on this action */
12450
12451     /* similar to regex compiling, do two passes; the first pass
12452      * determines whether the op chain is convertible and calculates the
12453      * buffer size; the second pass populates the buffer and makes any
12454      * changes necessary to ops (such as moving consts to the pad on
12455      * threaded builds).
12456      *
12457      * NB: for things like Coverity, note that both passes take the same
12458      * path through the logic tree (except for 'if (pass)' bits), since
12459      * both passes are following the same op_next chain; and in
12460      * particular, if it would return early on the second pass, it would
12461      * already have returned early on the first pass.
12462      */
12463     for (pass = 0; pass < 2; pass++) {
12464         OP *o                = orig_o;
12465         UV action            = orig_action;
12466         OP *first_elem_op    = NULL;  /* first seen aelem/helem */
12467         OP *top_op           = NULL;  /* highest [ah]elem/exists/del/rv2[ah]v */
12468         int action_count     = 0;     /* number of actions seen so far */
12469         int action_ix        = 0;     /* action_count % (actions per IV) */
12470         bool next_is_hash    = FALSE; /* is the next lookup to be a hash? */
12471         bool is_last         = FALSE; /* no more derefs to follow */
12472         bool maybe_aelemfast = FALSE; /* we can replace with aelemfast? */
12473         UNOP_AUX_item *arg     = arg_buf;
12474         UNOP_AUX_item *action_ptr = arg_buf;
12475
12476         if (pass)
12477             action_ptr->uv = 0;
12478         arg++;
12479
12480         switch (action) {
12481         case MDEREF_HV_gvsv_vivify_rv2hv_helem:
12482         case MDEREF_HV_gvhv_helem:
12483             next_is_hash = TRUE;
12484             /* FALLTHROUGH */
12485         case MDEREF_AV_gvsv_vivify_rv2av_aelem:
12486         case MDEREF_AV_gvav_aelem:
12487             if (pass) {
12488 #ifdef USE_ITHREADS
12489                 arg->pad_offset = cPADOPx(start)->op_padix;
12490                 /* stop it being swiped when nulled */
12491                 cPADOPx(start)->op_padix = 0;
12492 #else
12493                 arg->sv = cSVOPx(start)->op_sv;
12494                 cSVOPx(start)->op_sv = NULL;
12495 #endif
12496             }
12497             arg++;
12498             break;
12499
12500         case MDEREF_HV_padhv_helem:
12501         case MDEREF_HV_padsv_vivify_rv2hv_helem:
12502             next_is_hash = TRUE;
12503             /* FALLTHROUGH */
12504         case MDEREF_AV_padav_aelem:
12505         case MDEREF_AV_padsv_vivify_rv2av_aelem:
12506             if (pass) {
12507                 arg->pad_offset = start->op_targ;
12508                 /* we skip setting op_targ = 0 for now, since the intact
12509                  * OP_PADXV is needed by S_check_hash_fields_and_hekify */
12510                 reset_start_targ = TRUE;
12511             }
12512             arg++;
12513             break;
12514
12515         case MDEREF_HV_pop_rv2hv_helem:
12516             next_is_hash = TRUE;
12517             /* FALLTHROUGH */
12518         case MDEREF_AV_pop_rv2av_aelem:
12519             break;
12520
12521         default:
12522             NOT_REACHED; /* NOTREACHED */
12523             return;
12524         }
12525
12526         while (!is_last) {
12527             /* look for another (rv2av/hv; get index;
12528              * aelem/helem/exists/delele) sequence */
12529
12530             OP *kid;
12531             bool is_deref;
12532             bool ok;
12533             UV index_type = MDEREF_INDEX_none;
12534
12535             if (action_count) {
12536                 /* if this is not the first lookup, consume the rv2av/hv  */
12537
12538                 /* for N levels of aggregate lookup, we normally expect
12539                  * that the first N-1 [ah]elem ops will be flagged as
12540                  * /DEREF (so they autovivifiy if necessary), and the last
12541                  * lookup op not to be.
12542                  * For other things (like @{$h{k1}{k2}}) extra scope or
12543                  * leave ops can appear, so abandon the effort in that
12544                  * case */
12545                 if (o->op_type != OP_RV2AV && o->op_type != OP_RV2HV)
12546                     return;
12547
12548                 /* rv2av or rv2hv sKR/1 */
12549
12550                 ASSUME(!(o->op_flags & ~(OPf_WANT|OPf_KIDS|OPf_PARENS
12551                                             |OPf_REF|OPf_MOD|OPf_SPECIAL)));
12552                 if (o->op_flags != (OPf_WANT_SCALAR|OPf_KIDS|OPf_REF))
12553                     return;
12554
12555                 /* at this point, we wouldn't expect any of these
12556                  * possible private flags:
12557                  * OPpMAYBE_LVSUB, OPpOUR_INTRO, OPpLVAL_INTRO
12558                  * OPpTRUEBOOL, OPpMAYBE_TRUEBOOL (rv2hv only)
12559                  */
12560                 ASSUME(!(o->op_private &
12561                     ~(OPpHINT_STRICT_REFS|OPpARG1_MASK|OPpSLICEWARNING)));
12562
12563                 hints = (o->op_private & OPpHINT_STRICT_REFS);
12564
12565                 /* make sure the type of the previous /DEREF matches the
12566                  * type of the next lookup */
12567                 ASSUME(o->op_type == (next_is_hash ? OP_RV2HV : OP_RV2AV));
12568                 top_op = o;
12569
12570                 action = next_is_hash
12571                             ? MDEREF_HV_vivify_rv2hv_helem
12572                             : MDEREF_AV_vivify_rv2av_aelem;
12573                 o = o->op_next;
12574             }
12575
12576             /* if this is the second pass, and we're at the depth where
12577              * previously we encountered a non-simple index expression,
12578              * stop processing the index at this point */
12579             if (action_count != index_skip) {
12580
12581                 /* look for one or more simple ops that return an array
12582                  * index or hash key */
12583
12584                 switch (o->op_type) {
12585                 case OP_PADSV:
12586                     /* it may be a lexical var index */
12587                     ASSUME(!(o->op_flags & ~(OPf_WANT|OPf_PARENS
12588                                             |OPf_REF|OPf_MOD|OPf_SPECIAL)));
12589                     ASSUME(!(o->op_private &
12590                             ~(OPpPAD_STATE|OPpDEREF|OPpLVAL_INTRO)));
12591
12592                     if (   OP_GIMME(o,0) == G_SCALAR
12593                         && !(o->op_flags & (OPf_REF|OPf_MOD))
12594                         && o->op_private == 0)
12595                     {
12596                         if (pass)
12597                             arg->pad_offset = o->op_targ;
12598                         arg++;
12599                         index_type = MDEREF_INDEX_padsv;
12600                         o = o->op_next;
12601                     }
12602                     break;
12603
12604                 case OP_CONST:
12605                     if (next_is_hash) {
12606                         /* it's a constant hash index */
12607                         if (!(SvFLAGS(cSVOPo_sv) & (SVf_IOK|SVf_NOK|SVf_POK)))
12608                             /* "use constant foo => FOO; $h{+foo}" for
12609                              * some weird FOO, can leave you with constants
12610                              * that aren't simple strings. It's not worth
12611                              * the extra hassle for those edge cases */
12612                             break;
12613
12614                         if (pass) {
12615                             UNOP *rop = NULL;
12616                             OP * helem_op = o->op_next;
12617
12618                             ASSUME(   helem_op->op_type == OP_HELEM
12619                                    || helem_op->op_type == OP_NULL);
12620                             if (helem_op->op_type == OP_HELEM) {
12621                                 rop = (UNOP*)(((BINOP*)helem_op)->op_first);
12622                                 if (   helem_op->op_private & OPpLVAL_INTRO
12623                                     || rop->op_type != OP_RV2HV
12624                                 )
12625                                     rop = NULL;
12626                             }
12627                             S_check_hash_fields_and_hekify(aTHX_ rop, cSVOPo);
12628
12629 #ifdef USE_ITHREADS
12630                             /* Relocate sv to the pad for thread safety */
12631                             op_relocate_sv(&cSVOPo->op_sv, &o->op_targ);
12632                             arg->pad_offset = o->op_targ;
12633                             o->op_targ = 0;
12634 #else
12635                             arg->sv = cSVOPx_sv(o);
12636 #endif
12637                         }
12638                     }
12639                     else {
12640                         /* it's a constant array index */
12641                         IV iv;
12642                         SV *ix_sv = cSVOPo->op_sv;
12643                         if (!SvIOK(ix_sv))
12644                             break;
12645                         iv = SvIV(ix_sv);
12646
12647                         if (   action_count == 0
12648                             && iv >= -128
12649                             && iv <= 127
12650                             && (   action == MDEREF_AV_padav_aelem
12651                                 || action == MDEREF_AV_gvav_aelem)
12652                         )
12653                             maybe_aelemfast = TRUE;
12654
12655                         if (pass) {
12656                             arg->iv = iv;
12657                             SvREFCNT_dec_NN(cSVOPo->op_sv);
12658                         }
12659                     }
12660                     if (pass)
12661                         /* we've taken ownership of the SV */
12662                         cSVOPo->op_sv = NULL;
12663                     arg++;
12664                     index_type = MDEREF_INDEX_const;
12665                     o = o->op_next;
12666                     break;
12667
12668                 case OP_GV:
12669                     /* it may be a package var index */
12670
12671                     ASSUME(!(o->op_flags & ~(OPf_WANT|OPf_SPECIAL)));
12672                     ASSUME(!(o->op_private & ~(OPpEARLY_CV)));
12673                     if (  (o->op_flags &~ OPf_SPECIAL) != OPf_WANT_SCALAR
12674                         || o->op_private != 0
12675                     )
12676                         break;
12677
12678                     kid = o->op_next;
12679                     if (kid->op_type != OP_RV2SV)
12680                         break;
12681
12682                     ASSUME(!(kid->op_flags &
12683                             ~(OPf_WANT|OPf_KIDS|OPf_MOD|OPf_REF
12684                              |OPf_SPECIAL|OPf_PARENS)));
12685                     ASSUME(!(kid->op_private &
12686                                     ~(OPpARG1_MASK
12687                                      |OPpHINT_STRICT_REFS|OPpOUR_INTRO
12688                                      |OPpDEREF|OPpLVAL_INTRO)));
12689                     if(   (kid->op_flags &~ OPf_PARENS)
12690                             != (OPf_WANT_SCALAR|OPf_KIDS)
12691                        || (kid->op_private & ~(OPpARG1_MASK|HINT_STRICT_REFS))
12692                     )
12693                         break;
12694
12695                     if (pass) {
12696 #ifdef USE_ITHREADS
12697                         arg->pad_offset = cPADOPx(o)->op_padix;
12698                         /* stop it being swiped when nulled */
12699                         cPADOPx(o)->op_padix = 0;
12700 #else
12701                         arg->sv = cSVOPx(o)->op_sv;
12702                         cSVOPo->op_sv = NULL;
12703 #endif
12704                     }
12705                     arg++;
12706                     index_type = MDEREF_INDEX_gvsv;
12707                     o = kid->op_next;
12708                     break;
12709
12710                 } /* switch */
12711             } /* action_count != index_skip */
12712
12713             action |= index_type;
12714
12715
12716             /* at this point we have either:
12717              *   * detected what looks like a simple index expression,
12718              *     and expect the next op to be an [ah]elem, or
12719              *     an nulled  [ah]elem followed by a delete or exists;
12720              *  * found a more complex expression, so something other
12721              *    than the above follows.
12722              */
12723
12724             /* possibly an optimised away [ah]elem (where op_next is
12725              * exists or delete) */
12726             if (o->op_type == OP_NULL)
12727                 o = o->op_next;
12728
12729             /* at this point we're looking for an OP_AELEM, OP_HELEM,
12730              * OP_EXISTS or OP_DELETE */
12731
12732             /* if something like arybase (a.k.a $[ ) is in scope,
12733              * abandon optimisation attempt */
12734             if (  (o->op_type == OP_AELEM || o->op_type == OP_HELEM)
12735                && PL_check[o->op_type] != Perl_ck_null)
12736                 return;
12737
12738             if (   o->op_type != OP_AELEM
12739                 || (o->op_private &
12740                       (OPpLVAL_INTRO|OPpLVAL_DEFER|OPpDEREF|OPpMAYBE_LVSUB))
12741                 )
12742                 maybe_aelemfast = FALSE;
12743
12744             /* look for aelem/helem/exists/delete. If it's not the last elem
12745              * lookup, it *must* have OPpDEREF_AV/HV, but not many other
12746              * flags; if it's the last, then it mustn't have
12747              * OPpDEREF_AV/HV, but may have lots of other flags, like
12748              * OPpLVAL_INTRO etc
12749              */
12750
12751             if (   index_type == MDEREF_INDEX_none
12752                 || (   o->op_type != OP_AELEM  && o->op_type != OP_HELEM
12753                     && o->op_type != OP_EXISTS && o->op_type != OP_DELETE)
12754             )
12755                 ok = FALSE;
12756             else {
12757                 /* we have aelem/helem/exists/delete with valid simple index */
12758
12759                 is_deref =    (o->op_type == OP_AELEM || o->op_type == OP_HELEM)
12760                            && (   (o->op_private & OPpDEREF) == OPpDEREF_AV
12761                                || (o->op_private & OPpDEREF) == OPpDEREF_HV);
12762
12763                 if (is_deref) {
12764                     ASSUME(!(o->op_flags &
12765                                  ~(OPf_WANT|OPf_KIDS|OPf_MOD|OPf_PARENS)));
12766                     ASSUME(!(o->op_private & ~(OPpARG2_MASK|OPpDEREF)));
12767
12768                     ok =    (o->op_flags &~ OPf_PARENS)
12769                                == (OPf_WANT_SCALAR|OPf_KIDS|OPf_MOD)
12770                          && !(o->op_private & ~(OPpDEREF|OPpARG2_MASK));
12771                 }
12772                 else if (o->op_type == OP_EXISTS) {
12773                     ASSUME(!(o->op_flags & ~(OPf_WANT|OPf_KIDS|OPf_PARENS
12774                                 |OPf_REF|OPf_MOD|OPf_SPECIAL)));
12775                     ASSUME(!(o->op_private & ~(OPpARG1_MASK|OPpEXISTS_SUB)));
12776                     ok =  !(o->op_private & ~OPpARG1_MASK);
12777                 }
12778                 else if (o->op_type == OP_DELETE) {
12779                     ASSUME(!(o->op_flags & ~(OPf_WANT|OPf_KIDS|OPf_PARENS
12780                                 |OPf_REF|OPf_MOD|OPf_SPECIAL)));
12781                     ASSUME(!(o->op_private &
12782                                     ~(OPpARG1_MASK|OPpSLICE|OPpLVAL_INTRO)));
12783                     /* don't handle slices or 'local delete'; the latter
12784                      * is fairly rare, and has a complex runtime */
12785                     ok =  !(o->op_private & ~OPpARG1_MASK);
12786                     if (OP_TYPE_IS_OR_WAS(cUNOPo->op_first, OP_AELEM))
12787                         /* skip handling run-tome error */
12788                         ok = (ok && cBOOL(o->op_flags & OPf_SPECIAL));
12789                 }
12790                 else {
12791                     ASSUME(o->op_type == OP_AELEM || o->op_type == OP_HELEM);
12792                     ASSUME(!(o->op_flags & ~(OPf_WANT|OPf_KIDS|OPf_MOD
12793                                             |OPf_PARENS|OPf_REF|OPf_SPECIAL)));
12794                     ASSUME(!(o->op_private & ~(OPpARG2_MASK|OPpMAYBE_LVSUB
12795                                     |OPpLVAL_DEFER|OPpDEREF|OPpLVAL_INTRO)));
12796                     ok = (o->op_private & OPpDEREF) != OPpDEREF_SV;
12797                 }
12798             }
12799
12800             if (ok) {
12801                 if (!first_elem_op)
12802                     first_elem_op = o;
12803                 top_op = o;
12804                 if (is_deref) {
12805                     next_is_hash = cBOOL((o->op_private & OPpDEREF) == OPpDEREF_HV);
12806                     o = o->op_next;
12807                 }
12808                 else {
12809                     is_last = TRUE;
12810                     action |= MDEREF_FLAG_last;
12811                 }
12812             }
12813             else {
12814                 /* at this point we have something that started
12815                  * promisingly enough (with rv2av or whatever), but failed
12816                  * to find a simple index followed by an
12817                  * aelem/helem/exists/delete. If this is the first action,
12818                  * give up; but if we've already seen at least one
12819                  * aelem/helem, then keep them and add a new action with
12820                  * MDEREF_INDEX_none, which causes it to do the vivify
12821                  * from the end of the previous lookup, and do the deref,
12822                  * but stop at that point. So $a[0][expr] will do one
12823                  * av_fetch, vivify and deref, then continue executing at
12824                  * expr */
12825                 if (!action_count)
12826                     return;
12827                 is_last = TRUE;
12828                 index_skip = action_count;
12829                 action |= MDEREF_FLAG_last;
12830             }
12831
12832             if (pass)
12833                 action_ptr->uv |= (action << (action_ix * MDEREF_SHIFT));
12834             action_ix++;
12835             action_count++;
12836             /* if there's no space for the next action, create a new slot
12837              * for it *before* we start adding args for that action */
12838             if ((action_ix + 1) * MDEREF_SHIFT > UVSIZE*8) {
12839                 action_ptr = arg;
12840                 if (pass)
12841                     arg->uv = 0;
12842                 arg++;
12843                 action_ix = 0;
12844             }
12845         } /* while !is_last */
12846
12847         /* success! */
12848
12849         if (pass) {
12850             OP *mderef;
12851             OP *p, *q;
12852
12853             mderef = newUNOP_AUX(OP_MULTIDEREF, 0, NULL, arg_buf);
12854             if (index_skip == -1) {
12855                 mderef->op_flags = o->op_flags
12856                         & (OPf_WANT|OPf_MOD|(next_is_hash ? OPf_SPECIAL : 0));
12857                 if (o->op_type == OP_EXISTS)
12858                     mderef->op_private = OPpMULTIDEREF_EXISTS;
12859                 else if (o->op_type == OP_DELETE)
12860                     mderef->op_private = OPpMULTIDEREF_DELETE;
12861                 else
12862                     mderef->op_private = o->op_private
12863                         & (OPpMAYBE_LVSUB|OPpLVAL_DEFER|OPpLVAL_INTRO);
12864             }
12865             /* accumulate strictness from every level (although I don't think
12866              * they can actually vary) */
12867             mderef->op_private |= hints;
12868
12869             /* integrate the new multideref op into the optree and the
12870              * op_next chain.
12871              *
12872              * In general an op like aelem or helem has two child
12873              * sub-trees: the aggregate expression (a_expr) and the
12874              * index expression (i_expr):
12875              *
12876              *     aelem
12877              *       |
12878              *     a_expr - i_expr
12879              *
12880              * The a_expr returns an AV or HV, while the i-expr returns an
12881              * index. In general a multideref replaces most or all of a
12882              * multi-level tree, e.g.
12883              *
12884              *     exists
12885              *       |
12886              *     ex-aelem
12887              *       |
12888              *     rv2av  - i_expr1
12889              *       |
12890              *     helem
12891              *       |
12892              *     rv2hv  - i_expr2
12893              *       |
12894              *     aelem
12895              *       |
12896              *     a_expr - i_expr3
12897              *
12898              * With multideref, all the i_exprs will be simple vars or
12899              * constants, except that i_expr1 may be arbitrary in the case
12900              * of MDEREF_INDEX_none.
12901              *
12902              * The bottom-most a_expr will be either:
12903              *   1) a simple var (so padXv or gv+rv2Xv);
12904              *   2) a simple scalar var dereferenced (e.g. $r->[0]):
12905              *      so a simple var with an extra rv2Xv;
12906              *   3) or an arbitrary expression.
12907              *
12908              * 'start', the first op in the execution chain, will point to
12909              *   1),2): the padXv or gv op;
12910              *   3):    the rv2Xv which forms the last op in the a_expr
12911              *          execution chain, and the top-most op in the a_expr
12912              *          subtree.
12913              *
12914              * For all cases, the 'start' node is no longer required,
12915              * but we can't free it since one or more external nodes
12916              * may point to it. E.g. consider
12917              *     $h{foo} = $a ? $b : $c
12918              * Here, both the op_next and op_other branches of the
12919              * cond_expr point to the gv[*h] of the hash expression, so
12920              * we can't free the 'start' op.
12921              *
12922              * For expr->[...], we need to save the subtree containing the
12923              * expression; for the other cases, we just need to save the
12924              * start node.
12925              * So in all cases, we null the start op and keep it around by
12926              * making it the child of the multideref op; for the expr->
12927              * case, the expr will be a subtree of the start node.
12928              *
12929              * So in the simple 1,2 case the  optree above changes to
12930              *
12931              *     ex-exists
12932              *       |
12933              *     multideref
12934              *       |
12935              *     ex-gv (or ex-padxv)
12936              *
12937              *  with the op_next chain being
12938              *
12939              *  -> ex-gv -> multideref -> op-following-ex-exists ->
12940              *
12941              *  In the 3 case, we have
12942              *
12943              *     ex-exists
12944              *       |
12945              *     multideref
12946              *       |
12947              *     ex-rv2xv
12948              *       |
12949              *    rest-of-a_expr
12950              *      subtree
12951              *
12952              *  and
12953              *
12954              *  -> rest-of-a_expr subtree ->
12955              *    ex-rv2xv -> multideref -> op-following-ex-exists ->
12956              *
12957              *
12958              * Where the last i_expr is non-simple (i.e. MDEREF_INDEX_none,
12959              * e.g. $a[0]{foo}[$x+1], the next rv2xv is nulled and the
12960              * multideref attached as the child, e.g.
12961              *
12962              *     exists
12963              *       |
12964              *     ex-aelem
12965              *       |
12966              *     ex-rv2av  - i_expr1
12967              *       |
12968              *     multideref
12969              *       |
12970              *     ex-whatever
12971              *
12972              */
12973
12974             /* if we free this op, don't free the pad entry */
12975             if (reset_start_targ)
12976                 start->op_targ = 0;
12977
12978
12979             /* Cut the bit we need to save out of the tree and attach to
12980              * the multideref op, then free the rest of the tree */
12981
12982             /* find parent of node to be detached (for use by splice) */
12983             p = first_elem_op;
12984             if (   orig_action == MDEREF_AV_pop_rv2av_aelem
12985                 || orig_action == MDEREF_HV_pop_rv2hv_helem)
12986             {
12987                 /* there is an arbitrary expression preceding us, e.g.
12988                  * expr->[..]? so we need to save the 'expr' subtree */
12989                 if (p->op_type == OP_EXISTS || p->op_type == OP_DELETE)
12990                     p = cUNOPx(p)->op_first;
12991                 ASSUME(   start->op_type == OP_RV2AV
12992                        || start->op_type == OP_RV2HV);
12993             }
12994             else {
12995                 /* either a padXv or rv2Xv+gv, maybe with an ex-Xelem
12996                  * above for exists/delete. */
12997                 while (   (p->op_flags & OPf_KIDS)
12998                        && cUNOPx(p)->op_first != start
12999                 )
13000                     p = cUNOPx(p)->op_first;
13001             }
13002             ASSUME(cUNOPx(p)->op_first == start);
13003
13004             /* detach from main tree, and re-attach under the multideref */
13005             op_sibling_splice(mderef, NULL, 0,
13006                     op_sibling_splice(p, NULL, 1, NULL));
13007             op_null(start);
13008
13009             start->op_next = mderef;
13010
13011             mderef->op_next = index_skip == -1 ? o->op_next : o;
13012
13013             /* excise and free the original tree, and replace with
13014              * the multideref op */
13015             p = op_sibling_splice(top_op, NULL, -1, mderef);
13016             while (p) {
13017                 q = OpSIBLING(p);
13018                 op_free(p);
13019                 p = q;
13020             }
13021             op_null(top_op);
13022         }
13023         else {
13024             Size_t size = arg - arg_buf;
13025
13026             if (maybe_aelemfast && action_count == 1)
13027                 return;
13028
13029             arg_buf = (UNOP_AUX_item*)PerlMemShared_malloc(
13030                                 sizeof(UNOP_AUX_item) * (size + 1));
13031             /* for dumping etc: store the length in a hidden first slot;
13032              * we set the op_aux pointer to the second slot */
13033             arg_buf->uv = size;
13034             arg_buf++;
13035         }
13036     } /* for (pass = ...) */
13037 }
13038
13039
13040
13041 /* mechanism for deferring recursion in rpeep() */
13042
13043 #define MAX_DEFERRED 4
13044
13045 #define DEFER(o) \
13046   STMT_START { \
13047     if (defer_ix == (MAX_DEFERRED-1)) { \
13048         OP **defer = defer_queue[defer_base]; \
13049         CALL_RPEEP(*defer); \
13050         S_prune_chain_head(defer); \
13051         defer_base = (defer_base + 1) % MAX_DEFERRED; \
13052         defer_ix--; \
13053     } \
13054     defer_queue[(defer_base + ++defer_ix) % MAX_DEFERRED] = &(o); \
13055   } STMT_END
13056
13057 #define IS_AND_OP(o)   (o->op_type == OP_AND)
13058 #define IS_OR_OP(o)    (o->op_type == OP_OR)
13059
13060
13061 /* A peephole optimizer.  We visit the ops in the order they're to execute.
13062  * See the comments at the top of this file for more details about when
13063  * peep() is called */
13064
13065 void
13066 Perl_rpeep(pTHX_ OP *o)
13067 {
13068     dVAR;
13069     OP* oldop = NULL;
13070     OP* oldoldop = NULL;
13071     OP** defer_queue[MAX_DEFERRED]; /* small queue of deferred branches */
13072     int defer_base = 0;
13073     int defer_ix = -1;
13074     OP *fop;
13075     OP *sop;
13076
13077     if (!o || o->op_opt)
13078         return;
13079     ENTER;
13080     SAVEOP();
13081     SAVEVPTR(PL_curcop);
13082     for (;; o = o->op_next) {
13083         if (o && o->op_opt)
13084             o = NULL;
13085         if (!o) {
13086             while (defer_ix >= 0) {
13087                 OP **defer =
13088                         defer_queue[(defer_base + defer_ix--) % MAX_DEFERRED];
13089                 CALL_RPEEP(*defer);
13090                 S_prune_chain_head(defer);
13091             }
13092             break;
13093         }
13094
13095       redo:
13096         /* By default, this op has now been optimised. A couple of cases below
13097            clear this again.  */
13098         o->op_opt = 1;
13099         PL_op = o;
13100
13101         /* look for a series of 1 or more aggregate derefs, e.g.
13102          *   $a[1]{foo}[$i]{$k}
13103          * and replace with a single OP_MULTIDEREF op.
13104          * Each index must be either a const, or a simple variable,
13105          *
13106          * First, look for likely combinations of starting ops,
13107          * corresponding to (global and lexical variants of)
13108          *     $a[...]   $h{...}
13109          *     $r->[...] $r->{...}
13110          *     (preceding expression)->[...]
13111          *     (preceding expression)->{...}
13112          * and if so, call maybe_multideref() to do a full inspection
13113          * of the op chain and if appropriate, replace with an
13114          * OP_MULTIDEREF
13115          */
13116         {
13117             UV action;
13118             OP *o2 = o;
13119             U8 hints = 0;
13120
13121             switch (o2->op_type) {
13122             case OP_GV:
13123                 /* $pkg[..]   :   gv[*pkg]
13124                  * $pkg->[...]:   gv[*pkg]; rv2sv sKM/DREFAV */
13125
13126                 /* Fail if there are new op flag combinations that we're
13127                  * not aware of, rather than:
13128                  *  * silently failing to optimise, or
13129                  *  * silently optimising the flag away.
13130                  * If this ASSUME starts failing, examine what new flag
13131                  * has been added to the op, and decide whether the
13132                  * optimisation should still occur with that flag, then
13133                  * update the code accordingly. This applies to all the
13134                  * other ASSUMEs in the block of code too.
13135                  */
13136                 ASSUME(!(o2->op_flags &
13137                             ~(OPf_WANT|OPf_MOD|OPf_PARENS|OPf_SPECIAL)));
13138                 ASSUME(!(o2->op_private & ~OPpEARLY_CV));
13139
13140                 o2 = o2->op_next;
13141
13142                 if (o2->op_type == OP_RV2AV) {
13143                     action = MDEREF_AV_gvav_aelem;
13144                     goto do_deref;
13145                 }
13146
13147                 if (o2->op_type == OP_RV2HV) {
13148                     action = MDEREF_HV_gvhv_helem;
13149                     goto do_deref;
13150                 }
13151
13152                 if (o2->op_type != OP_RV2SV)
13153                     break;
13154
13155                 /* at this point we've seen gv,rv2sv, so the only valid
13156                  * construct left is $pkg->[] or $pkg->{} */
13157
13158                 ASSUME(!(o2->op_flags & OPf_STACKED));
13159                 if ((o2->op_flags & (OPf_WANT|OPf_REF|OPf_MOD|OPf_SPECIAL))
13160                             != (OPf_WANT_SCALAR|OPf_MOD))
13161                     break;
13162
13163                 ASSUME(!(o2->op_private & ~(OPpARG1_MASK|HINT_STRICT_REFS
13164                                     |OPpOUR_INTRO|OPpDEREF|OPpLVAL_INTRO)));
13165                 if (o2->op_private & (OPpOUR_INTRO|OPpLVAL_INTRO))
13166                     break;
13167                 if (   (o2->op_private & OPpDEREF) != OPpDEREF_AV
13168                     && (o2->op_private & OPpDEREF) != OPpDEREF_HV)
13169                     break;
13170
13171                 o2 = o2->op_next;
13172                 if (o2->op_type == OP_RV2AV) {
13173                     action = MDEREF_AV_gvsv_vivify_rv2av_aelem;
13174                     goto do_deref;
13175                 }
13176                 if (o2->op_type == OP_RV2HV) {
13177                     action = MDEREF_HV_gvsv_vivify_rv2hv_helem;
13178                     goto do_deref;
13179                 }
13180                 break;
13181
13182             case OP_PADSV:
13183                 /* $lex->[...]: padsv[$lex] sM/DREFAV */
13184
13185                 ASSUME(!(o2->op_flags &
13186                     ~(OPf_WANT|OPf_PARENS|OPf_REF|OPf_MOD|OPf_SPECIAL)));
13187                 if ((o2->op_flags &
13188                         (OPf_WANT|OPf_REF|OPf_MOD|OPf_SPECIAL))
13189                      != (OPf_WANT_SCALAR|OPf_MOD))
13190                     break;
13191
13192                 ASSUME(!(o2->op_private &
13193                                 ~(OPpPAD_STATE|OPpDEREF|OPpLVAL_INTRO)));
13194                 /* skip if state or intro, or not a deref */
13195                 if (      o2->op_private != OPpDEREF_AV
13196                        && o2->op_private != OPpDEREF_HV)
13197                     break;
13198
13199                 o2 = o2->op_next;
13200                 if (o2->op_type == OP_RV2AV) {
13201                     action = MDEREF_AV_padsv_vivify_rv2av_aelem;
13202                     goto do_deref;
13203                 }
13204                 if (o2->op_type == OP_RV2HV) {
13205                     action = MDEREF_HV_padsv_vivify_rv2hv_helem;
13206                     goto do_deref;
13207                 }
13208                 break;
13209
13210             case OP_PADAV:
13211             case OP_PADHV:
13212                 /*    $lex[..]:  padav[@lex:1,2] sR *
13213                  * or $lex{..}:  padhv[%lex:1,2] sR */
13214                 ASSUME(!(o2->op_flags & ~(OPf_WANT|OPf_MOD|OPf_PARENS|
13215                                             OPf_REF|OPf_SPECIAL)));
13216                 if ((o2->op_flags &
13217                         (OPf_WANT|OPf_REF|OPf_MOD|OPf_SPECIAL))
13218                      != (OPf_WANT_SCALAR|OPf_REF))
13219                     break;
13220                 if (o2->op_flags != (OPf_WANT_SCALAR|OPf_REF))
13221                     break;
13222                 /* OPf_PARENS isn't currently used in this case;
13223                  * if that changes, let us know! */
13224                 ASSUME(!(o2->op_flags & OPf_PARENS));
13225
13226                 /* at this point, we wouldn't expect any of the remaining
13227                  * possible private flags:
13228                  * OPpPAD_STATE, OPpLVAL_INTRO, OPpTRUEBOOL,
13229                  * OPpMAYBE_TRUEBOOL, OPpMAYBE_LVSUB
13230                  *
13231                  * OPpSLICEWARNING shouldn't affect runtime
13232                  */
13233                 ASSUME(!(o2->op_private & ~(OPpSLICEWARNING)));
13234
13235                 action = o2->op_type == OP_PADAV
13236                             ? MDEREF_AV_padav_aelem
13237                             : MDEREF_HV_padhv_helem;
13238                 o2 = o2->op_next;
13239                 S_maybe_multideref(aTHX_ o, o2, action, 0);
13240                 break;
13241
13242
13243             case OP_RV2AV:
13244             case OP_RV2HV:
13245                 action = o2->op_type == OP_RV2AV
13246                             ? MDEREF_AV_pop_rv2av_aelem
13247                             : MDEREF_HV_pop_rv2hv_helem;
13248                 /* FALLTHROUGH */
13249             do_deref:
13250                 /* (expr)->[...]:  rv2av sKR/1;
13251                  * (expr)->{...}:  rv2hv sKR/1; */
13252
13253                 ASSUME(o2->op_type == OP_RV2AV || o2->op_type == OP_RV2HV);
13254
13255                 ASSUME(!(o2->op_flags & ~(OPf_WANT|OPf_KIDS|OPf_PARENS
13256                                 |OPf_REF|OPf_MOD|OPf_STACKED|OPf_SPECIAL)));
13257                 if (o2->op_flags != (OPf_WANT_SCALAR|OPf_KIDS|OPf_REF))
13258                     break;
13259
13260                 /* at this point, we wouldn't expect any of these
13261                  * possible private flags:
13262                  * OPpMAYBE_LVSUB, OPpLVAL_INTRO
13263                  * OPpTRUEBOOL, OPpMAYBE_TRUEBOOL, (rv2hv only)
13264                  */
13265                 ASSUME(!(o2->op_private &
13266                     ~(OPpHINT_STRICT_REFS|OPpARG1_MASK|OPpSLICEWARNING
13267                      |OPpOUR_INTRO)));
13268                 hints |= (o2->op_private & OPpHINT_STRICT_REFS);
13269
13270                 o2 = o2->op_next;
13271
13272                 S_maybe_multideref(aTHX_ o, o2, action, hints);
13273                 break;
13274
13275             default:
13276                 break;
13277             }
13278         }
13279
13280
13281         switch (o->op_type) {
13282         case OP_DBSTATE:
13283             PL_curcop = ((COP*)o);              /* for warnings */
13284             break;
13285         case OP_NEXTSTATE:
13286             PL_curcop = ((COP*)o);              /* for warnings */
13287
13288             /* Optimise a "return ..." at the end of a sub to just be "...".
13289              * This saves 2 ops. Before:
13290              * 1  <;> nextstate(main 1 -e:1) v ->2
13291              * 4  <@> return K ->5
13292              * 2    <0> pushmark s ->3
13293              * -    <1> ex-rv2sv sK/1 ->4
13294              * 3      <#> gvsv[*cat] s ->4
13295              *
13296              * After:
13297              * -  <@> return K ->-
13298              * -    <0> pushmark s ->2
13299              * -    <1> ex-rv2sv sK/1 ->-
13300              * 2      <$> gvsv(*cat) s ->3
13301              */
13302             {
13303                 OP *next = o->op_next;
13304                 OP *sibling = OpSIBLING(o);
13305                 if (   OP_TYPE_IS(next, OP_PUSHMARK)
13306                     && OP_TYPE_IS(sibling, OP_RETURN)
13307                     && OP_TYPE_IS(sibling->op_next, OP_LINESEQ)
13308                     && ( OP_TYPE_IS(sibling->op_next->op_next, OP_LEAVESUB)
13309                        ||OP_TYPE_IS(sibling->op_next->op_next,
13310                                     OP_LEAVESUBLV))
13311                     && cUNOPx(sibling)->op_first == next
13312                     && OpHAS_SIBLING(next) && OpSIBLING(next)->op_next
13313                     && next->op_next
13314                 ) {
13315                     /* Look through the PUSHMARK's siblings for one that
13316                      * points to the RETURN */
13317                     OP *top = OpSIBLING(next);
13318                     while (top && top->op_next) {
13319                         if (top->op_next == sibling) {
13320                             top->op_next = sibling->op_next;
13321                             o->op_next = next->op_next;
13322                             break;
13323                         }
13324                         top = OpSIBLING(top);
13325                     }
13326                 }
13327             }
13328
13329             /* Optimise 'my $x; my $y;' into 'my ($x, $y);'
13330              *
13331              * This latter form is then suitable for conversion into padrange
13332              * later on. Convert:
13333              *
13334              *   nextstate1 -> padop1 -> nextstate2 -> padop2 -> nextstate3
13335              *
13336              * into:
13337              *
13338              *   nextstate1 ->     listop     -> nextstate3
13339              *                 /            \
13340              *         pushmark -> padop1 -> padop2
13341              */
13342             if (o->op_next && (
13343                     o->op_next->op_type == OP_PADSV
13344                  || o->op_next->op_type == OP_PADAV
13345                  || o->op_next->op_type == OP_PADHV
13346                 )
13347                 && !(o->op_next->op_private & ~OPpLVAL_INTRO)
13348                 && o->op_next->op_next && o->op_next->op_next->op_type == OP_NEXTSTATE
13349                 && o->op_next->op_next->op_next && (
13350                     o->op_next->op_next->op_next->op_type == OP_PADSV
13351                  || o->op_next->op_next->op_next->op_type == OP_PADAV
13352                  || o->op_next->op_next->op_next->op_type == OP_PADHV
13353                 )
13354                 && !(o->op_next->op_next->op_next->op_private & ~OPpLVAL_INTRO)
13355                 && o->op_next->op_next->op_next->op_next && o->op_next->op_next->op_next->op_next->op_type == OP_NEXTSTATE
13356                 && (!CopLABEL((COP*)o)) /* Don't mess with labels */
13357                 && (!CopLABEL((COP*)o->op_next->op_next)) /* ... */
13358             ) {
13359                 OP *pad1, *ns2, *pad2, *ns3, *newop, *newpm;
13360
13361                 pad1 =    o->op_next;
13362                 ns2  = pad1->op_next;
13363                 pad2 =  ns2->op_next;
13364                 ns3  = pad2->op_next;
13365
13366                 /* we assume here that the op_next chain is the same as
13367                  * the op_sibling chain */
13368                 assert(OpSIBLING(o)    == pad1);
13369                 assert(OpSIBLING(pad1) == ns2);
13370                 assert(OpSIBLING(ns2)  == pad2);
13371                 assert(OpSIBLING(pad2) == ns3);
13372
13373                 /* excise and delete ns2 */
13374                 op_sibling_splice(NULL, pad1, 1, NULL);
13375                 op_free(ns2);
13376
13377                 /* excise pad1 and pad2 */
13378                 op_sibling_splice(NULL, o, 2, NULL);
13379
13380                 /* create new listop, with children consisting of:
13381                  * a new pushmark, pad1, pad2. */
13382                 newop = newLISTOP(OP_LIST, 0, pad1, pad2);
13383                 newop->op_flags |= OPf_PARENS;
13384                 newop->op_flags = (newop->op_flags & ~OPf_WANT) | OPf_WANT_VOID;
13385
13386                 /* insert newop between o and ns3 */
13387                 op_sibling_splice(NULL, o, 0, newop);
13388
13389                 /*fixup op_next chain */
13390                 newpm = cUNOPx(newop)->op_first; /* pushmark */
13391                 o    ->op_next = newpm;
13392                 newpm->op_next = pad1;
13393                 pad1 ->op_next = pad2;
13394                 pad2 ->op_next = newop; /* listop */
13395                 newop->op_next = ns3;
13396
13397                 /* Ensure pushmark has this flag if padops do */
13398                 if (pad1->op_flags & OPf_MOD && pad2->op_flags & OPf_MOD) {
13399                     newpm->op_flags |= OPf_MOD;
13400                 }
13401
13402                 break;
13403             }
13404
13405             /* Two NEXTSTATEs in a row serve no purpose. Except if they happen
13406                to carry two labels. For now, take the easier option, and skip
13407                this optimisation if the first NEXTSTATE has a label.  */
13408             if (!CopLABEL((COP*)o) && !PERLDB_NOOPT) {
13409                 OP *nextop = o->op_next;
13410                 while (nextop && nextop->op_type == OP_NULL)
13411                     nextop = nextop->op_next;
13412
13413                 if (nextop && (nextop->op_type == OP_NEXTSTATE)) {
13414                     op_null(o);
13415                     if (oldop)
13416                         oldop->op_next = nextop;
13417                     /* Skip (old)oldop assignment since the current oldop's
13418                        op_next already points to the next op.  */
13419                     continue;
13420                 }
13421             }
13422             break;
13423
13424         case OP_CONCAT:
13425             if (o->op_next && o->op_next->op_type == OP_STRINGIFY) {
13426                 if (o->op_next->op_private & OPpTARGET_MY) {
13427                     if (o->op_flags & OPf_STACKED) /* chained concats */
13428                         break; /* ignore_optimization */
13429                     else {
13430                         /* assert(PL_opargs[o->op_type] & OA_TARGLEX); */
13431                         o->op_targ = o->op_next->op_targ;
13432                         o->op_next->op_targ = 0;
13433                         o->op_private |= OPpTARGET_MY;
13434                     }
13435                 }
13436                 op_null(o->op_next);
13437             }
13438             break;
13439         case OP_STUB:
13440             if ((o->op_flags & OPf_WANT) != OPf_WANT_LIST) {
13441                 break; /* Scalar stub must produce undef.  List stub is noop */
13442             }
13443             goto nothin;
13444         case OP_NULL:
13445             if (o->op_targ == OP_NEXTSTATE
13446                 || o->op_targ == OP_DBSTATE)
13447             {
13448                 PL_curcop = ((COP*)o);
13449             }
13450             /* XXX: We avoid setting op_seq here to prevent later calls
13451                to rpeep() from mistakenly concluding that optimisation
13452                has already occurred. This doesn't fix the real problem,
13453                though (See 20010220.007). AMS 20010719 */
13454             /* op_seq functionality is now replaced by op_opt */
13455             o->op_opt = 0;
13456             /* FALLTHROUGH */
13457         case OP_SCALAR:
13458         case OP_LINESEQ:
13459         case OP_SCOPE:
13460         nothin:
13461             if (oldop) {
13462                 oldop->op_next = o->op_next;
13463                 o->op_opt = 0;
13464                 continue;
13465             }
13466             break;
13467
13468         case OP_PUSHMARK:
13469
13470             /* Given
13471                  5 repeat/DOLIST
13472                  3   ex-list
13473                  1     pushmark
13474                  2     scalar or const
13475                  4   const[0]
13476                convert repeat into a stub with no kids.
13477              */
13478             if (o->op_next->op_type == OP_CONST
13479              || (  o->op_next->op_type == OP_PADSV
13480                 && !(o->op_next->op_private & OPpLVAL_INTRO))
13481              || (  o->op_next->op_type == OP_GV
13482                 && o->op_next->op_next->op_type == OP_RV2SV
13483                 && !(o->op_next->op_next->op_private
13484                         & (OPpLVAL_INTRO|OPpOUR_INTRO))))
13485             {
13486                 const OP *kid = o->op_next->op_next;
13487                 if (o->op_next->op_type == OP_GV)
13488                    kid = kid->op_next;
13489                 /* kid is now the ex-list.  */
13490                 if (kid->op_type == OP_NULL
13491                  && (kid = kid->op_next)->op_type == OP_CONST
13492                     /* kid is now the repeat count.  */
13493                  && kid->op_next->op_type == OP_REPEAT
13494                  && kid->op_next->op_private & OPpREPEAT_DOLIST
13495                  && (kid->op_next->op_flags & OPf_WANT) == OPf_WANT_LIST
13496                  && SvIOK(kSVOP_sv) && SvIVX(kSVOP_sv) == 0)
13497                 {
13498                     o = kid->op_next; /* repeat */
13499                     assert(oldop);
13500                     oldop->op_next = o;
13501                     op_free(cBINOPo->op_first);
13502                     op_free(cBINOPo->op_last );
13503                     o->op_flags &=~ OPf_KIDS;
13504                     /* stub is a baseop; repeat is a binop */
13505                     STATIC_ASSERT_STMT(sizeof(OP) <= sizeof(BINOP));
13506                     OpTYPE_set(o, OP_STUB);
13507                     o->op_private = 0;
13508                     break;
13509                 }
13510             }
13511
13512             /* Convert a series of PAD ops for my vars plus support into a
13513              * single padrange op. Basically
13514              *
13515              *    pushmark -> pad[ahs]v -> pad[ahs]?v -> ... -> (list) -> rest
13516              *
13517              * becomes, depending on circumstances, one of
13518              *
13519              *    padrange  ----------------------------------> (list) -> rest
13520              *    padrange  --------------------------------------------> rest
13521              *
13522              * where all the pad indexes are sequential and of the same type
13523              * (INTRO or not).
13524              * We convert the pushmark into a padrange op, then skip
13525              * any other pad ops, and possibly some trailing ops.
13526              * Note that we don't null() the skipped ops, to make it
13527              * easier for Deparse to undo this optimisation (and none of
13528              * the skipped ops are holding any resourses). It also makes
13529              * it easier for find_uninit_var(), as it can just ignore
13530              * padrange, and examine the original pad ops.
13531              */
13532         {
13533             OP *p;
13534             OP *followop = NULL; /* the op that will follow the padrange op */
13535             U8 count = 0;
13536             U8 intro = 0;
13537             PADOFFSET base = 0; /* init only to stop compiler whining */
13538             bool gvoid = 0;     /* init only to stop compiler whining */
13539             bool defav = 0;  /* seen (...) = @_ */
13540             bool reuse = 0;  /* reuse an existing padrange op */
13541
13542             /* look for a pushmark -> gv[_] -> rv2av */
13543
13544             {
13545                 OP *rv2av, *q;
13546                 p = o->op_next;
13547                 if (   p->op_type == OP_GV
13548                     && cGVOPx_gv(p) == PL_defgv
13549                     && (rv2av = p->op_next)
13550                     && rv2av->op_type == OP_RV2AV
13551                     && !(rv2av->op_flags & OPf_REF)
13552                     && !(rv2av->op_private & (OPpLVAL_INTRO|OPpMAYBE_LVSUB))
13553                     && ((rv2av->op_flags & OPf_WANT) == OPf_WANT_LIST)
13554                 ) {
13555                     q = rv2av->op_next;
13556                     if (q->op_type == OP_NULL)
13557                         q = q->op_next;
13558                     if (q->op_type == OP_PUSHMARK) {
13559                         defav = 1;
13560                         p = q;
13561                     }
13562                 }
13563             }
13564             if (!defav) {
13565                 p = o;
13566             }
13567
13568             /* scan for PAD ops */
13569
13570             for (p = p->op_next; p; p = p->op_next) {
13571                 if (p->op_type == OP_NULL)
13572                     continue;
13573
13574                 if ((     p->op_type != OP_PADSV
13575                        && p->op_type != OP_PADAV
13576                        && p->op_type != OP_PADHV
13577                     )
13578                       /* any private flag other than INTRO? e.g. STATE */
13579                    || (p->op_private & ~OPpLVAL_INTRO)
13580                 )
13581                     break;
13582
13583                 /* let $a[N] potentially be optimised into AELEMFAST_LEX
13584                  * instead */
13585                 if (   p->op_type == OP_PADAV
13586                     && p->op_next
13587                     && p->op_next->op_type == OP_CONST
13588                     && p->op_next->op_next
13589                     && p->op_next->op_next->op_type == OP_AELEM
13590                 )
13591                     break;
13592
13593                 /* for 1st padop, note what type it is and the range
13594                  * start; for the others, check that it's the same type
13595                  * and that the targs are contiguous */
13596                 if (count == 0) {
13597                     intro = (p->op_private & OPpLVAL_INTRO);
13598                     base = p->op_targ;
13599                     gvoid = OP_GIMME(p,0) == G_VOID;
13600                 }
13601                 else {
13602                     if ((p->op_private & OPpLVAL_INTRO) != intro)
13603                         break;
13604                     /* Note that you'd normally  expect targs to be
13605                      * contiguous in my($a,$b,$c), but that's not the case
13606                      * when external modules start doing things, e.g.
13607                      i* Function::Parameters */
13608                     if (p->op_targ != base + count)
13609                         break;
13610                     assert(p->op_targ == base + count);
13611                     /* Either all the padops or none of the padops should
13612                        be in void context.  Since we only do the optimisa-
13613                        tion for av/hv when the aggregate itself is pushed
13614                        on to the stack (one item), there is no need to dis-
13615                        tinguish list from scalar context.  */
13616                     if (gvoid != (OP_GIMME(p,0) == G_VOID))
13617                         break;
13618                 }
13619
13620                 /* for AV, HV, only when we're not flattening */
13621                 if (   p->op_type != OP_PADSV
13622                     && !gvoid
13623                     && !(p->op_flags & OPf_REF)
13624                 )
13625                     break;
13626
13627                 if (count >= OPpPADRANGE_COUNTMASK)
13628                     break;
13629
13630                 /* there's a biggest base we can fit into a
13631                  * SAVEt_CLEARPADRANGE in pp_padrange */
13632                 if (intro && base >
13633                         (UV_MAX >> (OPpPADRANGE_COUNTSHIFT+SAVE_TIGHT_SHIFT)))
13634                     break;
13635
13636                 /* Success! We've got another valid pad op to optimise away */
13637                 count++;
13638                 followop = p->op_next;
13639             }
13640
13641             if (count < 1 || (count == 1 && !defav))
13642                 break;
13643
13644             /* pp_padrange in specifically compile-time void context
13645              * skips pushing a mark and lexicals; in all other contexts
13646              * (including unknown till runtime) it pushes a mark and the
13647              * lexicals. We must be very careful then, that the ops we
13648              * optimise away would have exactly the same effect as the
13649              * padrange.
13650              * In particular in void context, we can only optimise to
13651              * a padrange if see see the complete sequence
13652              *     pushmark, pad*v, ...., list
13653              * which has the net effect of of leaving the markstack as it
13654              * was.  Not pushing on to the stack (whereas padsv does touch
13655              * the stack) makes no difference in void context.
13656              */
13657             assert(followop);
13658             if (gvoid) {
13659                 if (followop->op_type == OP_LIST
13660                         && OP_GIMME(followop,0) == G_VOID
13661                    )
13662                 {
13663                     followop = followop->op_next; /* skip OP_LIST */
13664
13665                     /* consolidate two successive my(...);'s */
13666
13667                     if (   oldoldop
13668                         && oldoldop->op_type == OP_PADRANGE
13669                         && (oldoldop->op_flags & OPf_WANT) == OPf_WANT_VOID
13670                         && (oldoldop->op_private & OPpLVAL_INTRO) == intro
13671                         && !(oldoldop->op_flags & OPf_SPECIAL)
13672                     ) {
13673                         U8 old_count;
13674                         assert(oldoldop->op_next == oldop);
13675                         assert(   oldop->op_type == OP_NEXTSTATE
13676                                || oldop->op_type == OP_DBSTATE);
13677                         assert(oldop->op_next == o);
13678
13679                         old_count
13680                             = (oldoldop->op_private & OPpPADRANGE_COUNTMASK);
13681
13682                        /* Do not assume pad offsets for $c and $d are con-
13683                           tiguous in
13684                             my ($a,$b,$c);
13685                             my ($d,$e,$f);
13686                         */
13687                         if (  oldoldop->op_targ + old_count == base
13688                            && old_count < OPpPADRANGE_COUNTMASK - count) {
13689                             base = oldoldop->op_targ;
13690                             count += old_count;
13691                             reuse = 1;
13692                         }
13693                     }
13694
13695                     /* if there's any immediately following singleton
13696                      * my var's; then swallow them and the associated
13697                      * nextstates; i.e.
13698                      *    my ($a,$b); my $c; my $d;
13699                      * is treated as
13700                      *    my ($a,$b,$c,$d);
13701                      */
13702
13703                     while (    ((p = followop->op_next))
13704                             && (  p->op_type == OP_PADSV
13705                                || p->op_type == OP_PADAV
13706                                || p->op_type == OP_PADHV)
13707                             && (p->op_flags & OPf_WANT) == OPf_WANT_VOID
13708                             && (p->op_private & OPpLVAL_INTRO) == intro
13709                             && !(p->op_private & ~OPpLVAL_INTRO)
13710                             && p->op_next
13711                             && (   p->op_next->op_type == OP_NEXTSTATE
13712                                 || p->op_next->op_type == OP_DBSTATE)
13713                             && count < OPpPADRANGE_COUNTMASK
13714                             && base + count == p->op_targ
13715                     ) {
13716                         count++;
13717                         followop = p->op_next;
13718                     }
13719                 }
13720                 else
13721                     break;
13722             }
13723
13724             if (reuse) {
13725                 assert(oldoldop->op_type == OP_PADRANGE);
13726                 oldoldop->op_next = followop;
13727                 oldoldop->op_private = (intro | count);
13728                 o = oldoldop;
13729                 oldop = NULL;
13730                 oldoldop = NULL;
13731             }
13732             else {
13733                 /* Convert the pushmark into a padrange.
13734                  * To make Deparse easier, we guarantee that a padrange was
13735                  * *always* formerly a pushmark */
13736                 assert(o->op_type == OP_PUSHMARK);
13737                 o->op_next = followop;
13738                 OpTYPE_set(o, OP_PADRANGE);
13739                 o->op_targ = base;
13740                 /* bit 7: INTRO; bit 6..0: count */
13741                 o->op_private = (intro | count);
13742                 o->op_flags = ((o->op_flags & ~(OPf_WANT|OPf_SPECIAL))
13743                               | gvoid * OPf_WANT_VOID
13744                               | (defav ? OPf_SPECIAL : 0));
13745             }
13746             break;
13747         }
13748
13749         case OP_PADAV:
13750         case OP_PADSV:
13751         case OP_PADHV:
13752         /* Skip over state($x) in void context.  */
13753         if (oldop && o->op_private == (OPpPAD_STATE|OPpLVAL_INTRO)
13754          && (o->op_flags & OPf_WANT) == OPf_WANT_VOID)
13755         {
13756             oldop->op_next = o->op_next;
13757             goto redo_nextstate;
13758         }
13759         if (o->op_type != OP_PADAV)
13760             break;
13761         /* FALLTHROUGH */
13762         case OP_GV:
13763             if (o->op_type == OP_PADAV || o->op_next->op_type == OP_RV2AV) {
13764                 OP* const pop = (o->op_type == OP_PADAV) ?
13765                             o->op_next : o->op_next->op_next;
13766                 IV i;
13767                 if (pop && pop->op_type == OP_CONST &&
13768                     ((PL_op = pop->op_next)) &&
13769                     pop->op_next->op_type == OP_AELEM &&
13770                     !(pop->op_next->op_private &
13771                       (OPpLVAL_INTRO|OPpLVAL_DEFER|OPpDEREF|OPpMAYBE_LVSUB)) &&
13772                     (i = SvIV(((SVOP*)pop)->op_sv)) >= -128 && i <= 127)
13773                 {
13774                     GV *gv;
13775                     if (cSVOPx(pop)->op_private & OPpCONST_STRICT)
13776                         no_bareword_allowed(pop);
13777                     if (o->op_type == OP_GV)
13778                         op_null(o->op_next);
13779                     op_null(pop->op_next);
13780                     op_null(pop);
13781                     o->op_flags |= pop->op_next->op_flags & OPf_MOD;
13782                     o->op_next = pop->op_next->op_next;
13783                     o->op_ppaddr = PL_ppaddr[OP_AELEMFAST];
13784                     o->op_private = (U8)i;
13785                     if (o->op_type == OP_GV) {
13786                         gv = cGVOPo_gv;
13787                         GvAVn(gv);
13788                         o->op_type = OP_AELEMFAST;
13789                     }
13790                     else
13791                         o->op_type = OP_AELEMFAST_LEX;
13792                 }
13793                 if (o->op_type != OP_GV)
13794                     break;
13795             }
13796
13797             /* Remove $foo from the op_next chain in void context.  */
13798             if (oldop
13799              && (  o->op_next->op_type == OP_RV2SV
13800                 || o->op_next->op_type == OP_RV2AV
13801                 || o->op_next->op_type == OP_RV2HV  )
13802              && (o->op_next->op_flags & OPf_WANT) == OPf_WANT_VOID
13803              && !(o->op_next->op_private & OPpLVAL_INTRO))
13804             {
13805                 oldop->op_next = o->op_next->op_next;
13806                 /* Reprocess the previous op if it is a nextstate, to
13807                    allow double-nextstate optimisation.  */
13808               redo_nextstate:
13809                 if (oldop->op_type == OP_NEXTSTATE) {
13810                     oldop->op_opt = 0;
13811                     o = oldop;
13812                     oldop = oldoldop;
13813                     oldoldop = NULL;
13814                     goto redo;
13815                 }
13816                 o = oldop;
13817             }
13818             else if (o->op_next->op_type == OP_RV2SV) {
13819                 if (!(o->op_next->op_private & OPpDEREF)) {
13820                     op_null(o->op_next);
13821                     o->op_private |= o->op_next->op_private & (OPpLVAL_INTRO
13822                                                                | OPpOUR_INTRO);
13823                     o->op_next = o->op_next->op_next;
13824                     OpTYPE_set(o, OP_GVSV);
13825                 }
13826             }
13827             else if (o->op_next->op_type == OP_READLINE
13828                     && o->op_next->op_next->op_type == OP_CONCAT
13829                     && (o->op_next->op_next->op_flags & OPf_STACKED))
13830             {
13831                 /* Turn "$a .= <FH>" into an OP_RCATLINE. AMS 20010917 */
13832                 OpTYPE_set(o, OP_RCATLINE);
13833                 o->op_flags |= OPf_STACKED;
13834                 op_null(o->op_next->op_next);
13835                 op_null(o->op_next);
13836             }
13837
13838             break;
13839         
13840 #define HV_OR_SCALARHV(op)                                   \
13841     (  (op)->op_type == OP_PADHV || (op)->op_type == OP_RV2HV \
13842        ? (op)                                                  \
13843        : (op)->op_type == OP_SCALAR && (op)->op_flags & OPf_KIDS \
13844        && (  cUNOPx(op)->op_first->op_type == OP_PADHV          \
13845           || cUNOPx(op)->op_first->op_type == OP_RV2HV)          \
13846          ? cUNOPx(op)->op_first                                   \
13847          : NULL)
13848
13849         case OP_NOT:
13850             if ((fop = HV_OR_SCALARHV(cUNOP->op_first)))
13851                 fop->op_private |= OPpTRUEBOOL;
13852             break;
13853
13854         case OP_AND:
13855         case OP_OR:
13856         case OP_DOR:
13857             fop = cLOGOP->op_first;
13858             sop = OpSIBLING(fop);
13859             while (cLOGOP->op_other->op_type == OP_NULL)
13860                 cLOGOP->op_other = cLOGOP->op_other->op_next;
13861             while (o->op_next && (   o->op_type == o->op_next->op_type
13862                                   || o->op_next->op_type == OP_NULL))
13863                 o->op_next = o->op_next->op_next;
13864
13865             /* if we're an OR and our next is a AND in void context, we'll
13866                follow it's op_other on short circuit, same for reverse.
13867                We can't do this with OP_DOR since if it's true, its return
13868                value is the underlying value which must be evaluated
13869                by the next op */
13870             if (o->op_next &&
13871                 (
13872                     (IS_AND_OP(o) && IS_OR_OP(o->op_next))
13873                  || (IS_OR_OP(o) && IS_AND_OP(o->op_next))
13874                 )
13875                 && (o->op_next->op_flags & OPf_WANT) == OPf_WANT_VOID
13876             ) {
13877                 o->op_next = ((LOGOP*)o->op_next)->op_other;
13878             }
13879             DEFER(cLOGOP->op_other);
13880           
13881             o->op_opt = 1;
13882             fop = HV_OR_SCALARHV(fop);
13883             if (sop) sop = HV_OR_SCALARHV(sop);
13884             if (fop || sop
13885             ){  
13886                 OP * nop = o;
13887                 OP * lop = o;
13888                 if (!((nop->op_flags & OPf_WANT) == OPf_WANT_VOID)) {
13889                     while (nop && nop->op_next) {
13890                         switch (nop->op_next->op_type) {
13891                             case OP_NOT:
13892                             case OP_AND:
13893                             case OP_OR:
13894                             case OP_DOR:
13895                                 lop = nop = nop->op_next;
13896                                 break;
13897                             case OP_NULL:
13898                                 nop = nop->op_next;
13899                                 break;
13900                             default:
13901                                 nop = NULL;
13902                                 break;
13903                         }
13904                     }            
13905                 }
13906                 if (fop) {
13907                     if (  (lop->op_flags & OPf_WANT) == OPf_WANT_VOID
13908                       || o->op_type == OP_AND  )
13909                         fop->op_private |= OPpTRUEBOOL;
13910                     else if (!(lop->op_flags & OPf_WANT))
13911                         fop->op_private |= OPpMAYBE_TRUEBOOL;
13912                 }
13913                 if (  (lop->op_flags & OPf_WANT) == OPf_WANT_VOID
13914                    && sop)
13915                     sop->op_private |= OPpTRUEBOOL;
13916             }                  
13917             
13918             
13919             break;
13920         
13921         case OP_COND_EXPR:
13922             if ((fop = HV_OR_SCALARHV(cLOGOP->op_first)))
13923                 fop->op_private |= OPpTRUEBOOL;
13924 #undef HV_OR_SCALARHV
13925             /* GERONIMO! */ /* FALLTHROUGH */
13926
13927         case OP_MAPWHILE:
13928         case OP_GREPWHILE:
13929         case OP_ANDASSIGN:
13930         case OP_ORASSIGN:
13931         case OP_DORASSIGN:
13932         case OP_RANGE:
13933         case OP_ONCE:
13934             while (cLOGOP->op_other->op_type == OP_NULL)
13935                 cLOGOP->op_other = cLOGOP->op_other->op_next;
13936             DEFER(cLOGOP->op_other);
13937             break;
13938
13939         case OP_ENTERLOOP:
13940         case OP_ENTERITER:
13941             while (cLOOP->op_redoop->op_type == OP_NULL)
13942                 cLOOP->op_redoop = cLOOP->op_redoop->op_next;
13943             while (cLOOP->op_nextop->op_type == OP_NULL)
13944                 cLOOP->op_nextop = cLOOP->op_nextop->op_next;
13945             while (cLOOP->op_lastop->op_type == OP_NULL)
13946                 cLOOP->op_lastop = cLOOP->op_lastop->op_next;
13947             /* a while(1) loop doesn't have an op_next that escapes the
13948              * loop, so we have to explicitly follow the op_lastop to
13949              * process the rest of the code */
13950             DEFER(cLOOP->op_lastop);
13951             break;
13952
13953         case OP_ENTERTRY:
13954             assert(cLOGOPo->op_other->op_type == OP_LEAVETRY);
13955             DEFER(cLOGOPo->op_other);
13956             break;
13957
13958         case OP_SUBST:
13959             assert(!(cPMOP->op_pmflags & PMf_ONCE));
13960             while (cPMOP->op_pmstashstartu.op_pmreplstart &&
13961                    cPMOP->op_pmstashstartu.op_pmreplstart->op_type == OP_NULL)
13962                 cPMOP->op_pmstashstartu.op_pmreplstart
13963                     = cPMOP->op_pmstashstartu.op_pmreplstart->op_next;
13964             DEFER(cPMOP->op_pmstashstartu.op_pmreplstart);
13965             break;
13966
13967         case OP_SORT: {
13968             OP *oright;
13969
13970             if (o->op_flags & OPf_SPECIAL) {
13971                 /* first arg is a code block */
13972                 OP * const nullop = OpSIBLING(cLISTOP->op_first);
13973                 OP * kid          = cUNOPx(nullop)->op_first;
13974
13975                 assert(nullop->op_type == OP_NULL);
13976                 assert(kid->op_type == OP_SCOPE
13977                  || (kid->op_type == OP_NULL && kid->op_targ == OP_LEAVE));
13978                 /* since OP_SORT doesn't have a handy op_other-style
13979                  * field that can point directly to the start of the code
13980                  * block, store it in the otherwise-unused op_next field
13981                  * of the top-level OP_NULL. This will be quicker at
13982                  * run-time, and it will also allow us to remove leading
13983                  * OP_NULLs by just messing with op_nexts without
13984                  * altering the basic op_first/op_sibling layout. */
13985                 kid = kLISTOP->op_first;
13986                 assert(
13987                       (kid->op_type == OP_NULL
13988                       && (  kid->op_targ == OP_NEXTSTATE
13989                          || kid->op_targ == OP_DBSTATE  ))
13990                     || kid->op_type == OP_STUB
13991                     || kid->op_type == OP_ENTER);
13992                 nullop->op_next = kLISTOP->op_next;
13993                 DEFER(nullop->op_next);
13994             }
13995
13996             /* check that RHS of sort is a single plain array */
13997             oright = cUNOPo->op_first;
13998             if (!oright || oright->op_type != OP_PUSHMARK)
13999                 break;
14000
14001             if (o->op_private & OPpSORT_INPLACE)
14002                 break;
14003
14004             /* reverse sort ... can be optimised.  */
14005             if (!OpHAS_SIBLING(cUNOPo)) {
14006                 /* Nothing follows us on the list. */
14007                 OP * const reverse = o->op_next;
14008
14009                 if (reverse->op_type == OP_REVERSE &&
14010                     (reverse->op_flags & OPf_WANT) == OPf_WANT_LIST) {
14011                     OP * const pushmark = cUNOPx(reverse)->op_first;
14012                     if (pushmark && (pushmark->op_type == OP_PUSHMARK)
14013                         && (OpSIBLING(cUNOPx(pushmark)) == o)) {
14014                         /* reverse -> pushmark -> sort */
14015                         o->op_private |= OPpSORT_REVERSE;
14016                         op_null(reverse);
14017                         pushmark->op_next = oright->op_next;
14018                         op_null(oright);
14019                     }
14020                 }
14021             }
14022
14023             break;
14024         }
14025
14026         case OP_REVERSE: {
14027             OP *ourmark, *theirmark, *ourlast, *iter, *expushmark, *rv2av;
14028             OP *gvop = NULL;
14029             LISTOP *enter, *exlist;
14030
14031             if (o->op_private & OPpSORT_INPLACE)
14032                 break;
14033
14034             enter = (LISTOP *) o->op_next;
14035             if (!enter)
14036                 break;
14037             if (enter->op_type == OP_NULL) {
14038                 enter = (LISTOP *) enter->op_next;
14039                 if (!enter)
14040                     break;
14041             }
14042             /* for $a (...) will have OP_GV then OP_RV2GV here.
14043                for (...) just has an OP_GV.  */
14044             if (enter->op_type == OP_GV) {
14045                 gvop = (OP *) enter;
14046                 enter = (LISTOP *) enter->op_next;
14047                 if (!enter)
14048                     break;
14049                 if (enter->op_type == OP_RV2GV) {
14050                   enter = (LISTOP *) enter->op_next;
14051                   if (!enter)
14052                     break;
14053                 }
14054             }
14055
14056             if (enter->op_type != OP_ENTERITER)
14057                 break;
14058
14059             iter = enter->op_next;
14060             if (!iter || iter->op_type != OP_ITER)
14061                 break;
14062             
14063             expushmark = enter->op_first;
14064             if (!expushmark || expushmark->op_type != OP_NULL
14065                 || expushmark->op_targ != OP_PUSHMARK)
14066                 break;
14067
14068             exlist = (LISTOP *) OpSIBLING(expushmark);
14069             if (!exlist || exlist->op_type != OP_NULL
14070                 || exlist->op_targ != OP_LIST)
14071                 break;
14072
14073             if (exlist->op_last != o) {
14074                 /* Mmm. Was expecting to point back to this op.  */
14075                 break;
14076             }
14077             theirmark = exlist->op_first;
14078             if (!theirmark || theirmark->op_type != OP_PUSHMARK)
14079                 break;
14080
14081             if (OpSIBLING(theirmark) != o) {
14082                 /* There's something between the mark and the reverse, eg
14083                    for (1, reverse (...))
14084                    so no go.  */
14085                 break;
14086             }
14087
14088             ourmark = ((LISTOP *)o)->op_first;
14089             if (!ourmark || ourmark->op_type != OP_PUSHMARK)
14090                 break;
14091
14092             ourlast = ((LISTOP *)o)->op_last;
14093             if (!ourlast || ourlast->op_next != o)
14094                 break;
14095
14096             rv2av = OpSIBLING(ourmark);
14097             if (rv2av && rv2av->op_type == OP_RV2AV && !OpHAS_SIBLING(rv2av)
14098                 && rv2av->op_flags == (OPf_WANT_LIST | OPf_KIDS)) {
14099                 /* We're just reversing a single array.  */
14100                 rv2av->op_flags = OPf_WANT_SCALAR | OPf_KIDS | OPf_REF;
14101                 enter->op_flags |= OPf_STACKED;
14102             }
14103
14104             /* We don't have control over who points to theirmark, so sacrifice
14105                ours.  */
14106             theirmark->op_next = ourmark->op_next;
14107             theirmark->op_flags = ourmark->op_flags;
14108             ourlast->op_next = gvop ? gvop : (OP *) enter;
14109             op_null(ourmark);
14110             op_null(o);
14111             enter->op_private |= OPpITER_REVERSED;
14112             iter->op_private |= OPpITER_REVERSED;
14113             
14114             break;
14115         }
14116
14117         case OP_QR:
14118         case OP_MATCH:
14119             if (!(cPMOP->op_pmflags & PMf_ONCE)) {
14120                 assert (!cPMOP->op_pmstashstartu.op_pmreplstart);
14121             }
14122             break;
14123
14124         case OP_RUNCV:
14125             if (!(o->op_private & OPpOFFBYONE) && !CvCLONE(PL_compcv)
14126              && (!CvANON(PL_compcv) || (!PL_cv_has_eval && !PL_perldb)))
14127             {
14128                 SV *sv;
14129                 if (CvEVAL(PL_compcv)) sv = &PL_sv_undef;
14130                 else {
14131                     sv = newRV((SV *)PL_compcv);
14132                     sv_rvweaken(sv);
14133                     SvREADONLY_on(sv);
14134                 }
14135                 OpTYPE_set(o, OP_CONST);
14136                 o->op_flags |= OPf_SPECIAL;
14137                 cSVOPo->op_sv = sv;
14138             }
14139             break;
14140
14141         case OP_SASSIGN:
14142             if (OP_GIMME(o,0) == G_VOID
14143              || (  o->op_next->op_type == OP_LINESEQ
14144                 && (  o->op_next->op_next->op_type == OP_LEAVESUB
14145                    || (  o->op_next->op_next->op_type == OP_RETURN
14146                       && !CvLVALUE(PL_compcv)))))
14147             {
14148                 OP *right = cBINOP->op_first;
14149                 if (right) {
14150                     /*   sassign
14151                     *      RIGHT
14152                     *      substr
14153                     *         pushmark
14154                     *         arg1
14155                     *         arg2
14156                     *         ...
14157                     * becomes
14158                     *
14159                     *  ex-sassign
14160                     *     substr
14161                     *        pushmark
14162                     *        RIGHT
14163                     *        arg1
14164                     *        arg2
14165                     *        ...
14166                     */
14167                     OP *left = OpSIBLING(right);
14168                     if (left->op_type == OP_SUBSTR
14169                          && (left->op_private & 7) < 4) {
14170                         op_null(o);
14171                         /* cut out right */
14172                         op_sibling_splice(o, NULL, 1, NULL);
14173                         /* and insert it as second child of OP_SUBSTR */
14174                         op_sibling_splice(left, cBINOPx(left)->op_first, 0,
14175                                     right);
14176                         left->op_private |= OPpSUBSTR_REPL_FIRST;
14177                         left->op_flags =
14178                             (o->op_flags & ~OPf_WANT) | OPf_WANT_VOID;
14179                     }
14180                 }
14181             }
14182             break;
14183
14184         case OP_AASSIGN: {
14185             int l, r, lr, lscalars, rscalars;
14186
14187             /* handle common vars detection, e.g. ($a,$b) = ($b,$a).
14188                Note that we do this now rather than in newASSIGNOP(),
14189                since only by now are aliased lexicals flagged as such
14190
14191                See the essay "Common vars in list assignment" above for
14192                the full details of the rationale behind all the conditions
14193                below.
14194
14195                PL_generation sorcery:
14196                To detect whether there are common vars, the global var
14197                PL_generation is incremented for each assign op we scan.
14198                Then we run through all the lexical variables on the LHS,
14199                of the assignment, setting a spare slot in each of them to
14200                PL_generation.  Then we scan the RHS, and if any lexicals
14201                already have that value, we know we've got commonality.
14202                Also, if the generation number is already set to
14203                PERL_INT_MAX, then the variable is involved in aliasing, so
14204                we also have potential commonality in that case.
14205              */
14206
14207             PL_generation++;
14208             /* scan LHS */
14209             lscalars = 0;
14210             l = S_aassign_scan(aTHX_ cLISTOPo->op_last,  FALSE, 1, &lscalars);
14211             /* scan RHS */
14212             rscalars = 0;
14213             r = S_aassign_scan(aTHX_ cLISTOPo->op_first, TRUE, 1, &rscalars);
14214             lr = (l|r);
14215
14216
14217             /* After looking for things which are *always* safe, this main
14218              * if/else chain selects primarily based on the type of the
14219              * LHS, gradually working its way down from the more dangerous
14220              * to the more restrictive and thus safer cases */
14221
14222             if (   !l                      /* () = ....; */
14223                 || !r                      /* .... = (); */
14224                 || !(l & ~AAS_SAFE_SCALAR) /* (undef, pos()) = ...; */
14225                 || !(r & ~AAS_SAFE_SCALAR) /* ... = (1,2,length,undef); */
14226                 || (lscalars < 2)          /* ($x, undef) = ... */
14227             ) {
14228                 NOOP; /* always safe */
14229             }
14230             else if (l & AAS_DANGEROUS) {
14231                 /* always dangerous */
14232                 o->op_private |= OPpASSIGN_COMMON_SCALAR;
14233                 o->op_private |= OPpASSIGN_COMMON_AGG;
14234             }
14235             else if (l & (AAS_PKG_SCALAR|AAS_PKG_AGG)) {
14236                 /* package vars are always dangerous - too many
14237                  * aliasing possibilities */
14238                 if (l & AAS_PKG_SCALAR)
14239                     o->op_private |= OPpASSIGN_COMMON_SCALAR;
14240                 if (l & AAS_PKG_AGG)
14241                     o->op_private |= OPpASSIGN_COMMON_AGG;
14242             }
14243             else if (l & ( AAS_MY_SCALAR|AAS_MY_AGG
14244                           |AAS_LEX_SCALAR|AAS_LEX_AGG))
14245             {
14246                 /* LHS contains only lexicals and safe ops */
14247
14248                 if (l & (AAS_MY_AGG|AAS_LEX_AGG))
14249                     o->op_private |= OPpASSIGN_COMMON_AGG;
14250
14251                 if (l & (AAS_MY_SCALAR|AAS_LEX_SCALAR)) {
14252                     if (lr & AAS_LEX_SCALAR_COMM)
14253                         o->op_private |= OPpASSIGN_COMMON_SCALAR;
14254                     else if (   !(l & AAS_LEX_SCALAR)
14255                              && (r & AAS_DEFAV))
14256                     {
14257                         /* falsely mark
14258                          *    my (...) = @_
14259                          * as scalar-safe for performance reasons.
14260                          * (it will still have been marked _AGG if necessary */
14261                         NOOP;
14262                     }
14263                     else if (r  & (AAS_PKG_SCALAR|AAS_PKG_AGG|AAS_DANGEROUS))
14264                         o->op_private |= OPpASSIGN_COMMON_RC1;
14265                 }
14266             }
14267
14268             /* ... = ($x)
14269              * may have to handle aggregate on LHS, but we can't
14270              * have common scalars. */
14271             if (rscalars < 2)
14272                 o->op_private &=
14273                         ~(OPpASSIGN_COMMON_SCALAR|OPpASSIGN_COMMON_RC1);
14274
14275             break;
14276         }
14277
14278         case OP_CUSTOM: {
14279             Perl_cpeep_t cpeep = 
14280                 XopENTRYCUSTOM(o, xop_peep);
14281             if (cpeep)
14282                 cpeep(aTHX_ o, oldop);
14283             break;
14284         }
14285             
14286         }
14287         /* did we just null the current op? If so, re-process it to handle
14288          * eliding "empty" ops from the chain */
14289         if (o->op_type == OP_NULL && oldop && oldop->op_next == o) {
14290             o->op_opt = 0;
14291             o = oldop;
14292         }
14293         else {
14294             oldoldop = oldop;
14295             oldop = o;
14296         }
14297     }
14298     LEAVE;
14299 }
14300
14301 void
14302 Perl_peep(pTHX_ OP *o)
14303 {
14304     CALL_RPEEP(o);
14305 }
14306
14307 /*
14308 =head1 Custom Operators
14309
14310 =for apidoc Ao||custom_op_xop
14311 Return the XOP structure for a given custom op.  This macro should be
14312 considered internal to C<OP_NAME> and the other access macros: use them instead.
14313 This macro does call a function.  Prior
14314 to 5.19.6, this was implemented as a
14315 function.
14316
14317 =cut
14318 */
14319
14320 XOPRETANY
14321 Perl_custom_op_get_field(pTHX_ const OP *o, const xop_flags_enum field)
14322 {
14323     SV *keysv;
14324     HE *he = NULL;
14325     XOP *xop;
14326
14327     static const XOP xop_null = { 0, 0, 0, 0, 0 };
14328
14329     PERL_ARGS_ASSERT_CUSTOM_OP_GET_FIELD;
14330     assert(o->op_type == OP_CUSTOM);
14331
14332     /* This is wrong. It assumes a function pointer can be cast to IV,
14333      * which isn't guaranteed, but this is what the old custom OP code
14334      * did. In principle it should be safer to Copy the bytes of the
14335      * pointer into a PV: since the new interface is hidden behind
14336      * functions, this can be changed later if necessary.  */
14337     /* Change custom_op_xop if this ever happens */
14338     keysv = sv_2mortal(newSViv(PTR2IV(o->op_ppaddr)));
14339
14340     if (PL_custom_ops)
14341         he = hv_fetch_ent(PL_custom_ops, keysv, 0, 0);
14342
14343     /* assume noone will have just registered a desc */
14344     if (!he && PL_custom_op_names &&
14345         (he = hv_fetch_ent(PL_custom_op_names, keysv, 0, 0))
14346     ) {
14347         const char *pv;
14348         STRLEN l;
14349
14350         /* XXX does all this need to be shared mem? */
14351         Newxz(xop, 1, XOP);
14352         pv = SvPV(HeVAL(he), l);
14353         XopENTRY_set(xop, xop_name, savepvn(pv, l));
14354         if (PL_custom_op_descs &&
14355             (he = hv_fetch_ent(PL_custom_op_descs, keysv, 0, 0))
14356         ) {
14357             pv = SvPV(HeVAL(he), l);
14358             XopENTRY_set(xop, xop_desc, savepvn(pv, l));
14359         }
14360         Perl_custom_op_register(aTHX_ o->op_ppaddr, xop);
14361     }
14362     else {
14363         if (!he)
14364             xop = (XOP *)&xop_null;
14365         else
14366             xop = INT2PTR(XOP *, SvIV(HeVAL(he)));
14367     }
14368     {
14369         XOPRETANY any;
14370         if(field == XOPe_xop_ptr) {
14371             any.xop_ptr = xop;
14372         } else {
14373             const U32 flags = XopFLAGS(xop);
14374             if(flags & field) {
14375                 switch(field) {
14376                 case XOPe_xop_name:
14377                     any.xop_name = xop->xop_name;
14378                     break;
14379                 case XOPe_xop_desc:
14380                     any.xop_desc = xop->xop_desc;
14381                     break;
14382                 case XOPe_xop_class:
14383                     any.xop_class = xop->xop_class;
14384                     break;
14385                 case XOPe_xop_peep:
14386                     any.xop_peep = xop->xop_peep;
14387                     break;
14388                 default:
14389                     NOT_REACHED; /* NOTREACHED */
14390                     break;
14391                 }
14392             } else {
14393                 switch(field) {
14394                 case XOPe_xop_name:
14395                     any.xop_name = XOPd_xop_name;
14396                     break;
14397                 case XOPe_xop_desc:
14398                     any.xop_desc = XOPd_xop_desc;
14399                     break;
14400                 case XOPe_xop_class:
14401                     any.xop_class = XOPd_xop_class;
14402                     break;
14403                 case XOPe_xop_peep:
14404                     any.xop_peep = XOPd_xop_peep;
14405                     break;
14406                 default:
14407                     NOT_REACHED; /* NOTREACHED */
14408                     break;
14409                 }
14410             }
14411         }
14412         /* Some gcc releases emit a warning for this function:
14413          * op.c: In function 'Perl_custom_op_get_field':
14414          * op.c:...: warning: 'any.xop_name' may be used uninitialized in this function [-Wmaybe-uninitialized]
14415          * Whether this is true, is currently unknown. */
14416         return any;
14417     }
14418 }
14419
14420 /*
14421 =for apidoc Ao||custom_op_register
14422 Register a custom op.  See L<perlguts/"Custom Operators">.
14423
14424 =cut
14425 */
14426
14427 void
14428 Perl_custom_op_register(pTHX_ Perl_ppaddr_t ppaddr, const XOP *xop)
14429 {
14430     SV *keysv;
14431
14432     PERL_ARGS_ASSERT_CUSTOM_OP_REGISTER;
14433
14434     /* see the comment in custom_op_xop */
14435     keysv = sv_2mortal(newSViv(PTR2IV(ppaddr)));
14436
14437     if (!PL_custom_ops)
14438         PL_custom_ops = newHV();
14439
14440     if (!hv_store_ent(PL_custom_ops, keysv, newSViv(PTR2IV(xop)), 0))
14441         Perl_croak(aTHX_ "panic: can't register custom OP %s", xop->xop_name);
14442 }
14443
14444 /*
14445
14446 =for apidoc core_prototype
14447
14448 This function assigns the prototype of the named core function to C<sv>, or
14449 to a new mortal SV if C<sv> is C<NULL>.  It returns the modified C<sv>, or
14450 C<NULL> if the core function has no prototype.  C<code> is a code as returned
14451 by C<keyword()>.  It must not be equal to 0.
14452
14453 =cut
14454 */
14455
14456 SV *
14457 Perl_core_prototype(pTHX_ SV *sv, const char *name, const int code,
14458                           int * const opnum)
14459 {
14460     int i = 0, n = 0, seen_question = 0, defgv = 0;
14461     I32 oa;
14462 #define MAX_ARGS_OP ((sizeof(I32) - 1) * 2)
14463     char str[ MAX_ARGS_OP * 2 + 2 ]; /* One ';', one '\0' */
14464     bool nullret = FALSE;
14465
14466     PERL_ARGS_ASSERT_CORE_PROTOTYPE;
14467
14468     assert (code);
14469
14470     if (!sv) sv = sv_newmortal();
14471
14472 #define retsetpvs(x,y) sv_setpvs(sv, x); if(opnum) *opnum=(y); return sv
14473
14474     switch (code < 0 ? -code : code) {
14475     case KEY_and   : case KEY_chop: case KEY_chomp:
14476     case KEY_cmp   : case KEY_defined: case KEY_delete: case KEY_exec  :
14477     case KEY_exists: case KEY_eq     : case KEY_ge    : case KEY_goto  :
14478     case KEY_grep  : case KEY_gt     : case KEY_last  : case KEY_le    :
14479     case KEY_lt    : case KEY_map    : case KEY_ne    : case KEY_next  :
14480     case KEY_or    : case KEY_print  : case KEY_printf: case KEY_qr    :
14481     case KEY_redo  : case KEY_require: case KEY_return: case KEY_say   :
14482     case KEY_select: case KEY_sort   : case KEY_split : case KEY_system:
14483     case KEY_x     : case KEY_xor    :
14484         if (!opnum) return NULL; nullret = TRUE; goto findopnum;
14485     case KEY_glob:    retsetpvs("_;", OP_GLOB);
14486     case KEY_keys:    retsetpvs("\\[%@]", OP_KEYS);
14487     case KEY_values:  retsetpvs("\\[%@]", OP_VALUES);
14488     case KEY_each:    retsetpvs("\\[%@]", OP_EACH);
14489     case KEY_push:    retsetpvs("\\@@", OP_PUSH);
14490     case KEY_unshift: retsetpvs("\\@@", OP_UNSHIFT);
14491     case KEY_pop:     retsetpvs(";\\@", OP_POP);
14492     case KEY_shift:   retsetpvs(";\\@", OP_SHIFT);
14493     case KEY_pos:     retsetpvs(";\\[$*]", OP_POS);
14494     case KEY_splice:
14495         retsetpvs("\\@;$$@", OP_SPLICE);
14496     case KEY___FILE__: case KEY___LINE__: case KEY___PACKAGE__:
14497         retsetpvs("", 0);
14498     case KEY_evalbytes:
14499         name = "entereval"; break;
14500     case KEY_readpipe:
14501         name = "backtick";
14502     }
14503
14504 #undef retsetpvs
14505
14506   findopnum:
14507     while (i < MAXO) {  /* The slow way. */
14508         if (strEQ(name, PL_op_name[i])
14509             || strEQ(name, PL_op_desc[i]))
14510         {
14511             if (nullret) { assert(opnum); *opnum = i; return NULL; }
14512             goto found;
14513         }
14514         i++;
14515     }
14516     return NULL;
14517   found:
14518     defgv = PL_opargs[i] & OA_DEFGV;
14519     oa = PL_opargs[i] >> OASHIFT;
14520     while (oa) {
14521         if (oa & OA_OPTIONAL && !seen_question && (
14522               !defgv || (oa & (OA_OPTIONAL - 1)) == OA_FILEREF
14523         )) {
14524             seen_question = 1;
14525             str[n++] = ';';
14526         }
14527         if ((oa & (OA_OPTIONAL - 1)) >= OA_AVREF
14528             && (oa & (OA_OPTIONAL - 1)) <= OA_SCALARREF
14529             /* But globs are already references (kinda) */
14530             && (oa & (OA_OPTIONAL - 1)) != OA_FILEREF
14531         ) {
14532             str[n++] = '\\';
14533         }
14534         if ((oa & (OA_OPTIONAL - 1)) == OA_SCALARREF
14535          && !scalar_mod_type(NULL, i)) {
14536             str[n++] = '[';
14537             str[n++] = '$';
14538             str[n++] = '@';
14539             str[n++] = '%';
14540             if (i == OP_LOCK || i == OP_UNDEF) str[n++] = '&';
14541             str[n++] = '*';
14542             str[n++] = ']';
14543         }
14544         else str[n++] = ("?$@@%&*$")[oa & (OA_OPTIONAL - 1)];
14545         if (oa & OA_OPTIONAL && defgv && str[n-1] == '$') {
14546             str[n-1] = '_'; defgv = 0;
14547         }
14548         oa = oa >> 4;
14549     }
14550     if (code == -KEY_not || code == -KEY_getprotobynumber) str[n++] = ';';
14551     str[n++] = '\0';
14552     sv_setpvn(sv, str, n - 1);
14553     if (opnum) *opnum = i;
14554     return sv;
14555 }
14556
14557 OP *
14558 Perl_coresub_op(pTHX_ SV * const coreargssv, const int code,
14559                       const int opnum)
14560 {
14561     OP * const argop = newSVOP(OP_COREARGS,0,coreargssv);
14562     OP *o;
14563
14564     PERL_ARGS_ASSERT_CORESUB_OP;
14565
14566     switch(opnum) {
14567     case 0:
14568         return op_append_elem(OP_LINESEQ,
14569                        argop,
14570                        newSLICEOP(0,
14571                                   newSVOP(OP_CONST, 0, newSViv(-code % 3)),
14572                                   newOP(OP_CALLER,0)
14573                        )
14574                );
14575     case OP_SELECT: /* which represents OP_SSELECT as well */
14576         if (code)
14577             return newCONDOP(
14578                          0,
14579                          newBINOP(OP_GT, 0,
14580                                   newAVREF(newGVOP(OP_GV, 0, PL_defgv)),
14581                                   newSVOP(OP_CONST, 0, newSVuv(1))
14582                                  ),
14583                          coresub_op(newSVuv((UV)OP_SSELECT), 0,
14584                                     OP_SSELECT),
14585                          coresub_op(coreargssv, 0, OP_SELECT)
14586                    );
14587         /* FALLTHROUGH */
14588     default:
14589         switch (PL_opargs[opnum] & OA_CLASS_MASK) {
14590         case OA_BASEOP:
14591             return op_append_elem(
14592                         OP_LINESEQ, argop,
14593                         newOP(opnum,
14594                               opnum == OP_WANTARRAY || opnum == OP_RUNCV
14595                                 ? OPpOFFBYONE << 8 : 0)
14596                    );
14597         case OA_BASEOP_OR_UNOP:
14598             if (opnum == OP_ENTEREVAL) {
14599                 o = newUNOP(OP_ENTEREVAL,OPpEVAL_COPHH<<8,argop);
14600                 if (code == -KEY_evalbytes) o->op_private |= OPpEVAL_BYTES;
14601             }
14602             else o = newUNOP(opnum,0,argop);
14603             if (opnum == OP_CALLER) o->op_private |= OPpOFFBYONE;
14604             else {
14605           onearg:
14606               if (is_handle_constructor(o, 1))
14607                 argop->op_private |= OPpCOREARGS_DEREF1;
14608               if (scalar_mod_type(NULL, opnum))
14609                 argop->op_private |= OPpCOREARGS_SCALARMOD;
14610             }
14611             return o;
14612         default:
14613             o = op_convert_list(opnum,OPf_SPECIAL*(opnum == OP_GLOB),argop);
14614             if (is_handle_constructor(o, 2))
14615                 argop->op_private |= OPpCOREARGS_DEREF2;
14616             if (opnum == OP_SUBSTR) {
14617                 o->op_private |= OPpMAYBE_LVSUB;
14618                 return o;
14619             }
14620             else goto onearg;
14621         }
14622     }
14623 }
14624
14625 void
14626 Perl_report_redefined_cv(pTHX_ const SV *name, const CV *old_cv,
14627                                SV * const *new_const_svp)
14628 {
14629     const char *hvname;
14630     bool is_const = !!CvCONST(old_cv);
14631     SV *old_const_sv = is_const ? cv_const_sv(old_cv) : NULL;
14632
14633     PERL_ARGS_ASSERT_REPORT_REDEFINED_CV;
14634
14635     if (is_const && new_const_svp && old_const_sv == *new_const_svp)
14636         return;
14637         /* They are 2 constant subroutines generated from
14638            the same constant. This probably means that
14639            they are really the "same" proxy subroutine
14640            instantiated in 2 places. Most likely this is
14641            when a constant is exported twice.  Don't warn.
14642         */
14643     if (
14644         (ckWARN(WARN_REDEFINE)
14645          && !(
14646                 CvGV(old_cv) && GvSTASH(CvGV(old_cv))
14647              && HvNAMELEN(GvSTASH(CvGV(old_cv))) == 7
14648              && (hvname = HvNAME(GvSTASH(CvGV(old_cv))),
14649                  strEQ(hvname, "autouse"))
14650              )
14651         )
14652      || (is_const
14653          && ckWARN_d(WARN_REDEFINE)
14654          && (!new_const_svp || sv_cmp(old_const_sv, *new_const_svp))
14655         )
14656     )
14657         Perl_warner(aTHX_ packWARN(WARN_REDEFINE),
14658                           is_const
14659                             ? "Constant subroutine %"SVf" redefined"
14660                             : "Subroutine %"SVf" redefined",
14661                           SVfARG(name));
14662 }
14663
14664 /*
14665 =head1 Hook manipulation
14666
14667 These functions provide convenient and thread-safe means of manipulating
14668 hook variables.
14669
14670 =cut
14671 */
14672
14673 /*
14674 =for apidoc Am|void|wrap_op_checker|Optype opcode|Perl_check_t new_checker|Perl_check_t *old_checker_p
14675
14676 Puts a C function into the chain of check functions for a specified op
14677 type.  This is the preferred way to manipulate the L</PL_check> array.
14678 C<opcode> specifies which type of op is to be affected.  C<new_checker>
14679 is a pointer to the C function that is to be added to that opcode's
14680 check chain, and C<old_checker_p> points to the storage location where a
14681 pointer to the next function in the chain will be stored.  The value of
14682 C<new_pointer> is written into the L</PL_check> array, while the value
14683 previously stored there is written to C<*old_checker_p>.
14684
14685 The function should be defined like this:
14686
14687     static OP *new_checker(pTHX_ OP *op) { ... }
14688
14689 It is intended to be called in this manner:
14690
14691     new_checker(aTHX_ op)
14692
14693 C<old_checker_p> should be defined like this:
14694
14695     static Perl_check_t old_checker_p;
14696
14697 L</PL_check> is global to an entire process, and a module wishing to
14698 hook op checking may find itself invoked more than once per process,
14699 typically in different threads.  To handle that situation, this function
14700 is idempotent.  The location C<*old_checker_p> must initially (once
14701 per process) contain a null pointer.  A C variable of static duration
14702 (declared at file scope, typically also marked C<static> to give
14703 it internal linkage) will be implicitly initialised appropriately,
14704 if it does not have an explicit initialiser.  This function will only
14705 actually modify the check chain if it finds C<*old_checker_p> to be null.
14706 This function is also thread safe on the small scale.  It uses appropriate
14707 locking to avoid race conditions in accessing L</PL_check>.
14708
14709 When this function is called, the function referenced by C<new_checker>
14710 must be ready to be called, except for C<*old_checker_p> being unfilled.
14711 In a threading situation, C<new_checker> may be called immediately,
14712 even before this function has returned.  C<*old_checker_p> will always
14713 be appropriately set before C<new_checker> is called.  If C<new_checker>
14714 decides not to do anything special with an op that it is given (which
14715 is the usual case for most uses of op check hooking), it must chain the
14716 check function referenced by C<*old_checker_p>.
14717
14718 If you want to influence compilation of calls to a specific subroutine,
14719 then use L</cv_set_call_checker> rather than hooking checking of all
14720 C<entersub> ops.
14721
14722 =cut
14723 */
14724
14725 void
14726 Perl_wrap_op_checker(pTHX_ Optype opcode,
14727     Perl_check_t new_checker, Perl_check_t *old_checker_p)
14728 {
14729     dVAR;
14730
14731     PERL_UNUSED_CONTEXT;
14732     PERL_ARGS_ASSERT_WRAP_OP_CHECKER;
14733     if (*old_checker_p) return;
14734     OP_CHECK_MUTEX_LOCK;
14735     if (!*old_checker_p) {
14736         *old_checker_p = PL_check[opcode];
14737         PL_check[opcode] = new_checker;
14738     }
14739     OP_CHECK_MUTEX_UNLOCK;
14740 }
14741
14742 #include "XSUB.h"
14743
14744 /* Efficient sub that returns a constant scalar value. */
14745 static void
14746 const_sv_xsub(pTHX_ CV* cv)
14747 {
14748     dXSARGS;
14749     SV *const sv = MUTABLE_SV(XSANY.any_ptr);
14750     PERL_UNUSED_ARG(items);
14751     if (!sv) {
14752         XSRETURN(0);
14753     }
14754     EXTEND(sp, 1);
14755     ST(0) = sv;
14756     XSRETURN(1);
14757 }
14758
14759 static void
14760 const_av_xsub(pTHX_ CV* cv)
14761 {
14762     dXSARGS;
14763     AV * const av = MUTABLE_AV(XSANY.any_ptr);
14764     SP -= items;
14765     assert(av);
14766 #ifndef DEBUGGING
14767     if (!av) {
14768         XSRETURN(0);
14769     }
14770 #endif
14771     if (SvRMAGICAL(av))
14772         Perl_croak(aTHX_ "Magical list constants are not supported");
14773     if (GIMME_V != G_ARRAY) {
14774         EXTEND(SP, 1);
14775         ST(0) = sv_2mortal(newSViv((IV)AvFILLp(av)+1));
14776         XSRETURN(1);
14777     }
14778     EXTEND(SP, AvFILLp(av)+1);
14779     Copy(AvARRAY(av), &ST(0), AvFILLp(av)+1, SV *);
14780     XSRETURN(AvFILLp(av)+1);
14781 }
14782
14783 /*
14784  * ex: set ts=8 sts=4 sw=4 et:
14785  */