This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
autodoc.pl: Extract code into a function
[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  * Note that during the build of miniperl, a temporary copy of this file
26  * is made, called opmini.c.
27  *
28  * A Perl program is compiled into a tree of OP nodes. Each op contains:
29  *  * structural OP pointers to its children and siblings (op_sibling,
30  *    op_first etc) that define the tree structure;
31  *  * execution order OP pointers (op_next, plus sometimes op_other,
32  *    op_lastop  etc) that define the execution sequence plus variants;
33  *  * a pointer to the C "pp" function that would execute the op;
34  *  * any data specific to that op.
35  * For example, an OP_CONST op points to the pp_const() function and to an
36  * SV containing the constant value. When pp_const() is executed, its job
37  * is to push that SV onto the stack.
38  *
39  * OPs are mainly created by the newFOO() functions, which are mainly
40  * called from the parser (in perly.y) as the code is parsed. For example
41  * the Perl code $a + $b * $c would cause the equivalent of the following
42  * to be called (oversimplifying a bit):
43  *
44  *  newBINOP(OP_ADD, flags,
45  *      newSVREF($a),
46  *      newBINOP(OP_MULTIPLY, flags, newSVREF($b), newSVREF($c))
47  *  )
48  *
49  * As the parser reduces low-level rules, it creates little op subtrees;
50  * as higher-level rules are resolved, these subtrees get joined together
51  * as branches on a bigger subtree, until eventually a top-level rule like
52  * a subroutine definition is reduced, at which point there is one large
53  * parse tree left.
54  *
55  * The execution order pointers (op_next) are generated as the subtrees
56  * are joined together. Consider this sub-expression: A*B + C/D: at the
57  * point when it's just been parsed, the op tree looks like:
58  *
59  *   [+]
60  *    |
61  *   [*]------[/]
62  *    |        |
63  *    A---B    C---D
64  *
65  * with the intended execution order being:
66  *
67  *   [PREV] => A => B => [*] => C => D => [/] =>  [+] => [NEXT]
68  *
69  * At this point all the nodes' op_next pointers will have been set,
70  * except that:
71  *    * we don't know what the [NEXT] node will be yet;
72  *    * we don't know what the [PREV] node will be yet, but when it gets
73  *      created and needs its op_next set, it needs to be set to point to
74  *      A, which is non-obvious.
75  * To handle both those cases, we temporarily set the top node's
76  * op_next to point to the first node to be executed in this subtree (A in
77  * this case). This means that initially a subtree's op_next chain,
78  * starting from the top node, will visit each node in execution sequence
79  * then point back at the top node.
80  * When we embed this subtree in a larger tree, its top op_next is used
81  * to get the start node, then is set to point to its new neighbour.
82  * For example the two separate [*],A,B and [/],C,D subtrees would
83  * initially have had:
84  *   [*] => A;  A => B;  B => [*]
85  * and
86  *   [/] => C;  C => D;  D => [/]
87  * When these two subtrees were joined together to make the [+] subtree,
88  * [+]'s op_next was set to [*]'s op_next, i.e. A; then [*]'s op_next was
89  * set to point to [/]'s op_next, i.e. C.
90  *
91  * This op_next linking is done by the LINKLIST() macro and its underlying
92  * op_linklist() function. Given a top-level op, if its op_next is
93  * non-null, it's already been linked, so leave it. Otherwise link it with
94  * its children as described above, possibly recursively if any of the
95  * children have a null op_next.
96  *
97  * In summary: given a subtree, its top-level node's op_next will either
98  * be:
99  *   NULL: the subtree hasn't been LINKLIST()ed yet;
100  *   fake: points to the start op for this subtree;
101  *   real: once the subtree has been embedded into a larger tree
102  */
103
104 /*
105
106 Here's an older description from Larry.
107
108 Perl's compiler is essentially a 3-pass compiler with interleaved phases:
109
110     A bottom-up pass
111     A top-down pass
112     An execution-order pass
113
114 The bottom-up pass is represented by all the "newOP" routines and
115 the ck_ routines.  The bottom-upness is actually driven by yacc.
116 So at the point that a ck_ routine fires, we have no idea what the
117 context is, either upward in the syntax tree, or either forward or
118 backward in the execution order.  (The bottom-up parser builds that
119 part of the execution order it knows about, but if you follow the "next"
120 links around, you'll find it's actually a closed loop through the
121 top level node.)
122
123 Whenever the bottom-up parser gets to a node that supplies context to
124 its components, it invokes that portion of the top-down pass that applies
125 to that part of the subtree (and marks the top node as processed, so
126 if a node further up supplies context, it doesn't have to take the
127 plunge again).  As a particular subcase of this, as the new node is
128 built, it takes all the closed execution loops of its subcomponents
129 and links them into a new closed loop for the higher level node.  But
130 it's still not the real execution order.
131
132 The actual execution order is not known till we get a grammar reduction
133 to a top-level unit like a subroutine or file that will be called by
134 "name" rather than via a "next" pointer.  At that point, we can call
135 into peep() to do that code's portion of the 3rd pass.  It has to be
136 recursive, but it's recursive on basic blocks, not on tree nodes.
137 */
138
139 /* To implement user lexical pragmas, there needs to be a way at run time to
140    get the compile time state of %^H for that block.  Storing %^H in every
141    block (or even COP) would be very expensive, so a different approach is
142    taken.  The (running) state of %^H is serialised into a tree of HE-like
143    structs.  Stores into %^H are chained onto the current leaf as a struct
144    refcounted_he * with the key and the value.  Deletes from %^H are saved
145    with a value of PL_sv_placeholder.  The state of %^H at any point can be
146    turned back into a regular HV by walking back up the tree from that point's
147    leaf, ignoring any key you've already seen (placeholder or not), storing
148    the rest into the HV structure, then removing the placeholders. Hence
149    memory is only used to store the %^H deltas from the enclosing COP, rather
150    than the entire %^H on each COP.
151
152    To cause actions on %^H to write out the serialisation records, it has
153    magic type 'H'. This magic (itself) does nothing, but its presence causes
154    the values to gain magic type 'h', which has entries for set and clear.
155    C<Perl_magic_sethint> updates C<PL_compiling.cop_hints_hash> with a store
156    record, with deletes written by C<Perl_magic_clearhint>. C<SAVEHINTS>
157    saves the current C<PL_compiling.cop_hints_hash> on the save stack, so that
158    it will be correctly restored when any inner compiling scope is exited.
159 */
160
161 #include "EXTERN.h"
162 #define PERL_IN_OP_C
163 #include "perl.h"
164 #include "keywords.h"
165 #include "feature.h"
166 #include "regcomp.h"
167 #include "invlist_inline.h"
168
169 #define CALL_PEEP(o) PL_peepp(aTHX_ o)
170 #define CALL_RPEEP(o) PL_rpeepp(aTHX_ o)
171 #define CALL_OPFREEHOOK(o) if (PL_opfreehook) PL_opfreehook(aTHX_ o)
172
173 static const char array_passed_to_stat[] = "Array passed to stat will be coerced to a scalar";
174
175 /* remove any leading "empty" ops from the op_next chain whose first
176  * node's address is stored in op_p. Store the updated address of the
177  * first node in op_p.
178  */
179
180 STATIC void
181 S_prune_chain_head(OP** op_p)
182 {
183     while (*op_p
184         && (   (*op_p)->op_type == OP_NULL
185             || (*op_p)->op_type == OP_SCOPE
186             || (*op_p)->op_type == OP_SCALAR
187             || (*op_p)->op_type == OP_LINESEQ)
188     )
189         *op_p = (*op_p)->op_next;
190 }
191
192
193 /* See the explanatory comments above struct opslab in op.h. */
194
195 #ifdef PERL_DEBUG_READONLY_OPS
196 #  define PERL_SLAB_SIZE 128
197 #  define PERL_MAX_SLAB_SIZE 4096
198 #  include <sys/mman.h>
199 #endif
200
201 #ifndef PERL_SLAB_SIZE
202 #  define PERL_SLAB_SIZE 64
203 #endif
204 #ifndef PERL_MAX_SLAB_SIZE
205 #  define PERL_MAX_SLAB_SIZE 2048
206 #endif
207
208 /* rounds up to nearest pointer */
209 #define SIZE_TO_PSIZE(x)        (((x) + sizeof(I32 *) - 1)/sizeof(I32 *))
210
211 #define DIFF(o,p)       \
212     (assert(((char *)(p) - (char *)(o)) % sizeof(I32**) == 0), \
213       ((size_t)((I32 **)(p) - (I32**)(o))))
214
215 /* requires double parens and aTHX_ */
216 #define DEBUG_S_warn(args)                                             \
217     DEBUG_S(                                                            \
218         PerlIO_printf(Perl_debug_log, "%s", SvPVx_nolen(Perl_mess args)) \
219     )
220
221 /* opslot_size includes the size of the slot header, and an op can't be smaller than BASEOP */
222 #define OPSLOT_SIZE_BASE (SIZE_TO_PSIZE(sizeof(OPSLOT)))
223
224 /* the number of bytes to allocate for a slab with sz * sizeof(I32 **) space for op */
225 #define OpSLABSizeBytes(sz) \
226     ((sz) * sizeof(I32 *) + STRUCT_OFFSET(OPSLAB, opslab_slots))
227
228 /* malloc a new op slab (suitable for attaching to PL_compcv).
229  * sz is in units of pointers from the beginning of opslab_opslots */
230
231 static OPSLAB *
232 S_new_slab(pTHX_ OPSLAB *head, size_t sz)
233 {
234     OPSLAB *slab;
235     size_t sz_bytes = OpSLABSizeBytes(sz);
236
237     /* opslot_offset is only U16 */
238     assert(sz < U16_MAX);
239     /* room for at least one op */
240     assert(sz >= OPSLOT_SIZE_BASE);
241
242 #ifdef PERL_DEBUG_READONLY_OPS
243     slab = (OPSLAB *) mmap(0, sz_bytes,
244                                    PROT_READ|PROT_WRITE,
245                                    MAP_ANON|MAP_PRIVATE, -1, 0);
246     DEBUG_m(PerlIO_printf(Perl_debug_log, "mapped %lu at %p\n",
247                           (unsigned long) sz, slab));
248     if (slab == MAP_FAILED) {
249         perror("mmap failed");
250         abort();
251     }
252 #else
253     slab = (OPSLAB *)PerlMemShared_malloc(sz_bytes);
254     Zero(slab, sz_bytes, char);
255 #endif
256     slab->opslab_size = (U16)sz;
257
258 #ifndef WIN32
259     /* The context is unused in non-Windows */
260     PERL_UNUSED_CONTEXT;
261 #endif
262     slab->opslab_free_space = sz;
263     slab->opslab_head = head ? head : slab;
264     DEBUG_S_warn((aTHX_ "allocated new op slab sz 0x%x, %p, head slab %p",
265         (unsigned int)slab->opslab_size, (void*)slab,
266         (void*)(slab->opslab_head)));
267     return slab;
268 }
269
270 #define OPSLOT_SIZE_TO_INDEX(sz) ((sz) - OPSLOT_SIZE_BASE)
271
272 #define link_freed_op(slab, o) S_link_freed_op(aTHX_ slab, o)
273 static void
274 S_link_freed_op(pTHX_ OPSLAB *slab, OP *o) {
275     U16 sz = OpSLOT(o)->opslot_size;
276     U16 index = OPSLOT_SIZE_TO_INDEX(sz);
277
278     assert(sz >= OPSLOT_SIZE_BASE);
279     /* make sure the array is large enough to include ops this large */
280     if (!slab->opslab_freed) {
281         /* we don't have a free list array yet, make a new one */
282         slab->opslab_freed_size = index+1;
283         slab->opslab_freed = (OP**)PerlMemShared_calloc((slab->opslab_freed_size), sizeof(OP*));
284
285         if (!slab->opslab_freed)
286             croak_no_mem();
287     }
288     else if (index >= slab->opslab_freed_size) {
289         /* It's probably not worth doing exponential expansion here, the number of op sizes
290            is small.
291         */
292         /* We already have a list that isn't large enough, expand it */
293         size_t newsize = index+1;
294         OP **p = (OP **)PerlMemShared_realloc(slab->opslab_freed, newsize * sizeof(OP*));
295
296         if (!p)
297             croak_no_mem();
298
299         Zero(p+slab->opslab_freed_size, newsize - slab->opslab_freed_size, OP *);
300
301         slab->opslab_freed = p;
302         slab->opslab_freed_size = newsize;
303     }
304
305     o->op_next = slab->opslab_freed[index];
306     slab->opslab_freed[index] = o;
307 }
308
309 /* Returns a sz-sized block of memory (suitable for holding an op) from
310  * a free slot in the chain of op slabs attached to PL_compcv.
311  * Allocates a new slab if necessary.
312  * if PL_compcv isn't compiling, malloc() instead.
313  */
314
315 void *
316 Perl_Slab_Alloc(pTHX_ size_t sz)
317 {
318     OPSLAB *head_slab; /* first slab in the chain */
319     OPSLAB *slab2;
320     OPSLOT *slot;
321     OP *o;
322     size_t sz_in_p; /* size in pointer units, including the OPSLOT header */
323
324     /* We only allocate ops from the slab during subroutine compilation.
325        We find the slab via PL_compcv, hence that must be non-NULL. It could
326        also be pointing to a subroutine which is now fully set up (CvROOT()
327        pointing to the top of the optree for that sub), or a subroutine
328        which isn't using the slab allocator. If our sanity checks aren't met,
329        don't use a slab, but allocate the OP directly from the heap.  */
330     if (!PL_compcv || CvROOT(PL_compcv)
331      || (CvSTART(PL_compcv) && !CvSLABBED(PL_compcv)))
332     {
333         o = (OP*)PerlMemShared_calloc(1, sz);
334         goto gotit;
335     }
336
337     /* While the subroutine is under construction, the slabs are accessed via
338        CvSTART(), to avoid needing to expand PVCV by one pointer for something
339        unneeded at runtime. Once a subroutine is constructed, the slabs are
340        accessed via CvROOT(). So if CvSTART() is NULL, no slab has been
341        allocated yet.  See the commit message for 8be227ab5eaa23f2 for more
342        details.  */
343     if (!CvSTART(PL_compcv)) {
344         CvSTART(PL_compcv) =
345             (OP *)(head_slab = S_new_slab(aTHX_ NULL, PERL_SLAB_SIZE));
346         CvSLABBED_on(PL_compcv);
347         head_slab->opslab_refcnt = 2; /* one for the CV; one for the new OP */
348     }
349     else ++(head_slab = (OPSLAB *)CvSTART(PL_compcv))->opslab_refcnt;
350
351     sz_in_p = SIZE_TO_PSIZE(sz + OPSLOT_HEADER);
352
353     /* The head slab for each CV maintains a free list of OPs. In particular, constant folding
354        will free up OPs, so it makes sense to re-use them where possible. A
355        freed up slot is used in preference to a new allocation.  */
356     if (head_slab->opslab_freed &&
357         OPSLOT_SIZE_TO_INDEX(sz_in_p) < head_slab->opslab_freed_size) {
358         U16 base_index;
359
360         /* look for a large enough size with any freed ops */
361         for (base_index = OPSLOT_SIZE_TO_INDEX(sz_in_p);
362              base_index < head_slab->opslab_freed_size && !head_slab->opslab_freed[base_index];
363              ++base_index) {
364         }
365
366         if (base_index < head_slab->opslab_freed_size) {
367             /* found a freed op */
368             o = head_slab->opslab_freed[base_index];
369
370             DEBUG_S_warn((aTHX_ "realloced  op at %p, slab %p, head slab %p",
371                           (void *)o, (void *)OpMySLAB(o), (void *)head_slab));
372             head_slab->opslab_freed[base_index] = o->op_next;
373             Zero(o, sz, char);
374             o->op_slabbed = 1;
375             goto gotit;
376         }
377     }
378
379 #define INIT_OPSLOT(s) \
380             slot->opslot_offset = DIFF(&slab2->opslab_slots, slot) ;    \
381             slot->opslot_size = s;                      \
382             slab2->opslab_free_space -= s;              \
383             o = &slot->opslot_op;                       \
384             o->op_slabbed = 1
385
386     /* The partially-filled slab is next in the chain. */
387     slab2 = head_slab->opslab_next ? head_slab->opslab_next : head_slab;
388     if (slab2->opslab_free_space < sz_in_p) {
389         /* Remaining space is too small. */
390         /* If we can fit a BASEOP, add it to the free chain, so as not
391            to waste it. */
392         if (slab2->opslab_free_space >= OPSLOT_SIZE_BASE) {
393             slot = &slab2->opslab_slots;
394             INIT_OPSLOT(slab2->opslab_free_space);
395             o->op_type = OP_FREED;
396             DEBUG_S_warn((aTHX_ "linked unused op space at %p, slab %p, head slab %p",
397                           (void *)o, (void *)slab2, (void *)head_slab));
398             link_freed_op(head_slab, o);
399         }
400
401         /* Create a new slab.  Make this one twice as big. */
402         slab2 = S_new_slab(aTHX_ head_slab,
403                             slab2->opslab_size  > PERL_MAX_SLAB_SIZE / 2
404                                 ? PERL_MAX_SLAB_SIZE
405                                 : slab2->opslab_size * 2);
406         slab2->opslab_next = head_slab->opslab_next;
407         head_slab->opslab_next = slab2;
408     }
409     assert(slab2->opslab_size >= sz_in_p);
410
411     /* Create a new op slot */
412     slot = OpSLOToff(slab2, slab2->opslab_free_space - sz_in_p);
413     assert(slot >= &slab2->opslab_slots);
414     INIT_OPSLOT(sz_in_p);
415     DEBUG_S_warn((aTHX_ "allocating op at %p, slab %p, head slab %p",
416         (void*)o, (void*)slab2, (void*)head_slab));
417
418   gotit:
419     /* moresib == 0, op_sibling == 0 implies a solitary unattached op */
420     assert(!o->op_moresib);
421     assert(!o->op_sibparent);
422
423     return (void *)o;
424 }
425
426 #undef INIT_OPSLOT
427
428 #ifdef PERL_DEBUG_READONLY_OPS
429 void
430 Perl_Slab_to_ro(pTHX_ OPSLAB *slab)
431 {
432     PERL_ARGS_ASSERT_SLAB_TO_RO;
433
434     if (slab->opslab_readonly) return;
435     slab->opslab_readonly = 1;
436     for (; slab; slab = slab->opslab_next) {
437         /*DEBUG_U(PerlIO_printf(Perl_debug_log,"mprotect ->ro %lu at %p\n",
438                               (unsigned long) slab->opslab_size, (void *)slab));*/
439         if (mprotect(slab, OpSLABSizeBytes(slab->opslab_size), PROT_READ))
440             Perl_warn(aTHX_ "mprotect for %p %lu failed with %d", (void *)slab,
441                              (unsigned long)slab->opslab_size, errno);
442     }
443 }
444
445 void
446 Perl_Slab_to_rw(pTHX_ OPSLAB *const slab)
447 {
448     OPSLAB *slab2;
449
450     PERL_ARGS_ASSERT_SLAB_TO_RW;
451
452     if (!slab->opslab_readonly) return;
453     slab2 = slab;
454     for (; slab2; slab2 = slab2->opslab_next) {
455         /*DEBUG_U(PerlIO_printf(Perl_debug_log,"mprotect ->rw %lu at %p\n",
456                               (unsigned long) size, (void *)slab2));*/
457         if (mprotect((void *)slab2, OpSLABSizeBytes(slab2->opslab_size),
458                      PROT_READ|PROT_WRITE)) {
459             Perl_warn(aTHX_ "mprotect RW for %p %lu failed with %d", (void *)slab,
460                              (unsigned long)slab2->opslab_size, errno);
461         }
462     }
463     slab->opslab_readonly = 0;
464 }
465
466 #else
467 #  define Slab_to_rw(op)    NOOP
468 #endif
469
470 /* This cannot possibly be right, but it was copied from the old slab
471    allocator, to which it was originally added, without explanation, in
472    commit 083fcd5. */
473 #ifdef NETWARE
474 #    define PerlMemShared PerlMem
475 #endif
476
477 /* make freed ops die if they're inadvertently executed */
478 #ifdef DEBUGGING
479 static OP *
480 S_pp_freed(pTHX)
481 {
482     DIE(aTHX_ "panic: freed op 0x%p called\n", PL_op);
483 }
484 #endif
485
486
487 /* Return the block of memory used by an op to the free list of
488  * the OP slab associated with that op.
489  */
490
491 void
492 Perl_Slab_Free(pTHX_ void *op)
493 {
494     OP * const o = (OP *)op;
495     OPSLAB *slab;
496
497     PERL_ARGS_ASSERT_SLAB_FREE;
498
499 #ifdef DEBUGGING
500     o->op_ppaddr = S_pp_freed;
501 #endif
502
503     if (!o->op_slabbed) {
504         if (!o->op_static)
505             PerlMemShared_free(op);
506         return;
507     }
508
509     slab = OpSLAB(o);
510     /* If this op is already freed, our refcount will get screwy. */
511     assert(o->op_type != OP_FREED);
512     o->op_type = OP_FREED;
513     link_freed_op(slab, o);
514     DEBUG_S_warn((aTHX_ "freeing    op at %p, slab %p, head slab %p",
515         (void*)o, (void *)OpMySLAB(o), (void*)slab));
516     OpslabREFCNT_dec_padok(slab);
517 }
518
519 void
520 Perl_opslab_free_nopad(pTHX_ OPSLAB *slab)
521 {
522     const bool havepad = !!PL_comppad;
523     PERL_ARGS_ASSERT_OPSLAB_FREE_NOPAD;
524     if (havepad) {
525         ENTER;
526         PAD_SAVE_SETNULLPAD();
527     }
528     opslab_free(slab);
529     if (havepad) LEAVE;
530 }
531
532 /* Free a chain of OP slabs. Should only be called after all ops contained
533  * in it have been freed. At this point, its reference count should be 1,
534  * because OpslabREFCNT_dec() skips doing rc-- when it detects that rc == 1,
535  * and just directly calls opslab_free().
536  * (Note that the reference count which PL_compcv held on the slab should
537  * have been removed once compilation of the sub was complete).
538  *
539  *
540  */
541
542 void
543 Perl_opslab_free(pTHX_ OPSLAB *slab)
544 {
545     OPSLAB *slab2;
546     PERL_ARGS_ASSERT_OPSLAB_FREE;
547     PERL_UNUSED_CONTEXT;
548     DEBUG_S_warn((aTHX_ "freeing slab %p", (void*)slab));
549     assert(slab->opslab_refcnt == 1);
550     PerlMemShared_free(slab->opslab_freed);
551     do {
552         slab2 = slab->opslab_next;
553 #ifdef DEBUGGING
554         slab->opslab_refcnt = ~(size_t)0;
555 #endif
556 #ifdef PERL_DEBUG_READONLY_OPS
557         DEBUG_m(PerlIO_printf(Perl_debug_log, "Deallocate slab at %p\n",
558                                                (void*)slab));
559         if (munmap(slab, OpSLABSizeBytes(slab->opslab_size))) {
560             perror("munmap failed");
561             abort();
562         }
563 #else
564         PerlMemShared_free(slab);
565 #endif
566         slab = slab2;
567     } while (slab);
568 }
569
570 /* like opslab_free(), but first calls op_free() on any ops in the slab
571  * not marked as OP_FREED
572  */
573
574 void
575 Perl_opslab_force_free(pTHX_ OPSLAB *slab)
576 {
577     OPSLAB *slab2;
578 #ifdef DEBUGGING
579     size_t savestack_count = 0;
580 #endif
581     PERL_ARGS_ASSERT_OPSLAB_FORCE_FREE;
582     slab2 = slab;
583     do {
584         OPSLOT *slot = OpSLOToff(slab2, slab2->opslab_free_space);
585         OPSLOT *end  = OpSLOToff(slab2, slab2->opslab_size);
586         for (; slot < end;
587                 slot = (OPSLOT*) ((I32**)slot + slot->opslot_size) )
588         {
589             if (slot->opslot_op.op_type != OP_FREED
590              && !(slot->opslot_op.op_savefree
591 #ifdef DEBUGGING
592                   && ++savestack_count
593 #endif
594                  )
595             ) {
596                 assert(slot->opslot_op.op_slabbed);
597                 op_free(&slot->opslot_op);
598                 if (slab->opslab_refcnt == 1) goto free;
599             }
600         }
601     } while ((slab2 = slab2->opslab_next));
602     /* > 1 because the CV still holds a reference count. */
603     if (slab->opslab_refcnt > 1) { /* still referenced by the savestack */
604 #ifdef DEBUGGING
605         assert(savestack_count == slab->opslab_refcnt-1);
606 #endif
607         /* Remove the CV’s reference count. */
608         slab->opslab_refcnt--;
609         return;
610     }
611    free:
612     opslab_free(slab);
613 }
614
615 #ifdef PERL_DEBUG_READONLY_OPS
616 OP *
617 Perl_op_refcnt_inc(pTHX_ OP *o)
618 {
619     if(o) {
620         OPSLAB *const slab = o->op_slabbed ? OpSLAB(o) : NULL;
621         if (slab && slab->opslab_readonly) {
622             Slab_to_rw(slab);
623             ++o->op_targ;
624             Slab_to_ro(slab);
625         } else {
626             ++o->op_targ;
627         }
628     }
629     return o;
630
631 }
632
633 PADOFFSET
634 Perl_op_refcnt_dec(pTHX_ OP *o)
635 {
636     PADOFFSET result;
637     OPSLAB *const slab = o->op_slabbed ? OpSLAB(o) : NULL;
638
639     PERL_ARGS_ASSERT_OP_REFCNT_DEC;
640
641     if (slab && slab->opslab_readonly) {
642         Slab_to_rw(slab);
643         result = --o->op_targ;
644         Slab_to_ro(slab);
645     } else {
646         result = --o->op_targ;
647     }
648     return result;
649 }
650 #endif
651 /*
652  * In the following definition, the ", (OP*)0" is just to make the compiler
653  * think the expression is of the right type: croak actually does a Siglongjmp.
654  */
655 #define CHECKOP(type,o) \
656     ((PL_op_mask && PL_op_mask[type])                           \
657      ? ( op_free((OP*)o),                                       \
658          Perl_croak(aTHX_ "'%s' trapped by operation mask", PL_op_desc[type]),  \
659          (OP*)0 )                                               \
660      : PL_check[type](aTHX_ (OP*)o))
661
662 #define RETURN_UNLIMITED_NUMBER (PERL_INT_MAX / 2)
663
664 #define OpTYPE_set(o,type) \
665     STMT_START {                                \
666         o->op_type = (OPCODE)type;              \
667         o->op_ppaddr = PL_ppaddr[type];         \
668     } STMT_END
669
670 STATIC OP *
671 S_no_fh_allowed(pTHX_ OP *o)
672 {
673     PERL_ARGS_ASSERT_NO_FH_ALLOWED;
674
675     yyerror(Perl_form(aTHX_ "Missing comma after first argument to %s function",
676                  OP_DESC(o)));
677     return o;
678 }
679
680 STATIC OP *
681 S_too_few_arguments_pv(pTHX_ OP *o, const char* name, U32 flags)
682 {
683     PERL_ARGS_ASSERT_TOO_FEW_ARGUMENTS_PV;
684     yyerror_pv(Perl_form(aTHX_ "Not enough arguments for %s", name), flags);
685     return o;
686 }
687
688 STATIC OP *
689 S_too_many_arguments_pv(pTHX_ OP *o, const char *name, U32 flags)
690 {
691     PERL_ARGS_ASSERT_TOO_MANY_ARGUMENTS_PV;
692
693     yyerror_pv(Perl_form(aTHX_ "Too many arguments for %s", name), flags);
694     return o;
695 }
696
697 STATIC void
698 S_bad_type_pv(pTHX_ I32 n, const char *t, const OP *o, const OP *kid)
699 {
700     PERL_ARGS_ASSERT_BAD_TYPE_PV;
701
702     yyerror_pv(Perl_form(aTHX_ "Type of arg %d to %s must be %s (not %s)",
703                  (int)n, PL_op_desc[(o)->op_type], t, OP_DESC(kid)), 0);
704 }
705
706 STATIC void
707 S_bad_type_gv(pTHX_ I32 n, GV *gv, const OP *kid, const char *t)
708 {
709     SV * const namesv = cv_name((CV *)gv, NULL, 0);
710     PERL_ARGS_ASSERT_BAD_TYPE_GV;
711
712     yyerror_pv(Perl_form(aTHX_ "Type of arg %d to %" SVf " must be %s (not %s)",
713                  (int)n, SVfARG(namesv), t, OP_DESC(kid)), SvUTF8(namesv));
714 }
715
716 STATIC void
717 S_no_bareword_allowed(pTHX_ OP *o)
718 {
719     PERL_ARGS_ASSERT_NO_BAREWORD_ALLOWED;
720
721     qerror(Perl_mess(aTHX_
722                      "Bareword \"%" SVf "\" not allowed while \"strict subs\" in use",
723                      SVfARG(cSVOPo_sv)));
724     o->op_private &= ~OPpCONST_STRICT; /* prevent warning twice about the same OP */
725 }
726
727 /* "register" allocation */
728
729 PADOFFSET
730 Perl_allocmy(pTHX_ const char *const name, const STRLEN len, const U32 flags)
731 {
732     PADOFFSET off;
733     const bool is_our = (PL_parser->in_my == KEY_our);
734
735     PERL_ARGS_ASSERT_ALLOCMY;
736
737     if (flags & ~SVf_UTF8)
738         Perl_croak(aTHX_ "panic: allocmy illegal flag bits 0x%" UVxf,
739                    (UV)flags);
740
741     /* complain about "my $<special_var>" etc etc */
742     if (   len
743         && !(  is_our
744             || isALPHA(name[1])
745             || (   (flags & SVf_UTF8)
746                 && isIDFIRST_utf8_safe((U8 *)name+1, name + len))
747             || (name[1] == '_' && len > 2)))
748     {
749         const char * const type =
750               PL_parser->in_my == KEY_sigvar ? "subroutine signature" :
751               PL_parser->in_my == KEY_state  ? "\"state\""     : "\"my\"";
752
753         if (!(flags & SVf_UTF8 && UTF8_IS_START(name[1]))
754          && isASCII(name[1])
755          && (!isPRINT(name[1]) || memCHRs("\t\n\r\f", name[1]))) {
756             /* diag_listed_as: Can't use global %s in %s */
757             yyerror(Perl_form(aTHX_ "Can't use global %c^%c%.*s in %s",
758                               name[0], toCTRL(name[1]),
759                               (int)(len - 2), name + 2,
760                               type));
761         } else {
762             yyerror_pv(Perl_form(aTHX_ "Can't use global %.*s in %s",
763                               (int) len, name,
764                               type), flags & SVf_UTF8);
765         }
766     }
767
768     /* allocate a spare slot and store the name in that slot */
769
770     off = pad_add_name_pvn(name, len,
771                        (is_our ? padadd_OUR :
772                         PL_parser->in_my == KEY_state ? padadd_STATE : 0),
773                     PL_parser->in_my_stash,
774                     (is_our
775                         /* $_ is always in main::, even with our */
776                         ? (PL_curstash && !memEQs(name,len,"$_")
777                             ? PL_curstash
778                             : PL_defstash)
779                         : NULL
780                     )
781     );
782     /* anon sub prototypes contains state vars should always be cloned,
783      * otherwise the state var would be shared between anon subs */
784
785     if (PL_parser->in_my == KEY_state && CvANON(PL_compcv))
786         CvCLONE_on(PL_compcv);
787
788     return off;
789 }
790
791 /*
792 =for apidoc_section Optree Manipulation Functions
793
794 =for apidoc alloccopstash
795
796 Available only under threaded builds, this function allocates an entry in
797 C<PL_stashpad> for the stash passed to it.
798
799 =cut
800 */
801
802 #ifdef USE_ITHREADS
803 PADOFFSET
804 Perl_alloccopstash(pTHX_ HV *hv)
805 {
806     PADOFFSET off = 0, o = 1;
807     bool found_slot = FALSE;
808
809     PERL_ARGS_ASSERT_ALLOCCOPSTASH;
810
811     if (PL_stashpad[PL_stashpadix] == hv) return PL_stashpadix;
812
813     for (; o < PL_stashpadmax; ++o) {
814         if (PL_stashpad[o] == hv) return PL_stashpadix = o;
815         if (!PL_stashpad[o] || SvTYPE(PL_stashpad[o]) != SVt_PVHV)
816             found_slot = TRUE, off = o;
817     }
818     if (!found_slot) {
819         Renew(PL_stashpad, PL_stashpadmax + 10, HV *);
820         Zero(PL_stashpad + PL_stashpadmax, 10, HV *);
821         off = PL_stashpadmax;
822         PL_stashpadmax += 10;
823     }
824
825     PL_stashpad[PL_stashpadix = off] = hv;
826     return off;
827 }
828 #endif
829
830 /* free the body of an op without examining its contents.
831  * Always use this rather than FreeOp directly */
832
833 static void
834 S_op_destroy(pTHX_ OP *o)
835 {
836     FreeOp(o);
837 }
838
839 /* Destructor */
840
841 /*
842 =for apidoc op_free
843
844 Free an op and its children. Only use this when an op is no longer linked
845 to from any optree.
846
847 =cut
848 */
849
850 void
851 Perl_op_free(pTHX_ OP *o)
852 {
853     OPCODE type;
854     OP *top_op = o;
855     OP *next_op = o;
856     bool went_up = FALSE; /* whether we reached the current node by
857                             following the parent pointer from a child, and
858                             so have already seen this node */
859
860     if (!o || o->op_type == OP_FREED)
861         return;
862
863     if (o->op_private & OPpREFCOUNTED) {
864         /* if base of tree is refcounted, just decrement */
865         switch (o->op_type) {
866         case OP_LEAVESUB:
867         case OP_LEAVESUBLV:
868         case OP_LEAVEEVAL:
869         case OP_LEAVE:
870         case OP_SCOPE:
871         case OP_LEAVEWRITE:
872             {
873                 PADOFFSET refcnt;
874                 OP_REFCNT_LOCK;
875                 refcnt = OpREFCNT_dec(o);
876                 OP_REFCNT_UNLOCK;
877                 if (refcnt) {
878                     /* Need to find and remove any pattern match ops from
879                      * the list we maintain for reset().  */
880                     find_and_forget_pmops(o);
881                     return;
882                 }
883             }
884             break;
885         default:
886             break;
887         }
888     }
889
890     while (next_op) {
891         o = next_op;
892
893         /* free child ops before ourself, (then free ourself "on the
894          * way back up") */
895
896         if (!went_up && o->op_flags & OPf_KIDS) {
897             next_op = cUNOPo->op_first;
898             continue;
899         }
900
901         /* find the next node to visit, *then* free the current node
902          * (can't rely on o->op_* fields being valid after o has been
903          * freed) */
904
905         /* The next node to visit will be either the sibling, or the
906          * parent if no siblings left, or NULL if we've worked our way
907          * back up to the top node in the tree */
908         next_op = (o == top_op) ? NULL : o->op_sibparent;
909         went_up = cBOOL(!OpHAS_SIBLING(o)); /* parents are already visited */
910
911         /* Now process the current node */
912
913         /* Though ops may be freed twice, freeing the op after its slab is a
914            big no-no. */
915         assert(!o->op_slabbed || OpSLAB(o)->opslab_refcnt != ~(size_t)0);
916         /* During the forced freeing of ops after compilation failure, kidops
917            may be freed before their parents. */
918         if (!o || o->op_type == OP_FREED)
919             continue;
920
921         type = o->op_type;
922
923         /* an op should only ever acquire op_private flags that we know about.
924          * If this fails, you may need to fix something in regen/op_private.
925          * Don't bother testing if:
926          *   * the op_ppaddr doesn't match the op; someone may have
927          *     overridden the op and be doing strange things with it;
928          *   * we've errored, as op flags are often left in an
929          *     inconsistent state then. Note that an error when
930          *     compiling the main program leaves PL_parser NULL, so
931          *     we can't spot faults in the main code, only
932          *     evaled/required code */
933 #ifdef DEBUGGING
934         if (   o->op_ppaddr == PL_ppaddr[type]
935             && PL_parser
936             && !PL_parser->error_count)
937         {
938             assert(!(o->op_private & ~PL_op_private_valid[type]));
939         }
940 #endif
941
942
943         /* Call the op_free hook if it has been set. Do it now so that it's called
944          * at the right time for refcounted ops, but still before all of the kids
945          * are freed. */
946         CALL_OPFREEHOOK(o);
947
948         if (type == OP_NULL)
949             type = (OPCODE)o->op_targ;
950
951         if (o->op_slabbed)
952             Slab_to_rw(OpSLAB(o));
953
954         /* COP* is not cleared by op_clear() so that we may track line
955          * numbers etc even after null() */
956         if (type == OP_NEXTSTATE || type == OP_DBSTATE) {
957             cop_free((COP*)o);
958         }
959
960         op_clear(o);
961         FreeOp(o);
962         if (PL_op == o)
963             PL_op = NULL;
964     }
965 }
966
967
968 /* S_op_clear_gv(): free a GV attached to an OP */
969
970 STATIC
971 #ifdef USE_ITHREADS
972 void S_op_clear_gv(pTHX_ OP *o, PADOFFSET *ixp)
973 #else
974 void S_op_clear_gv(pTHX_ OP *o, SV**svp)
975 #endif
976 {
977
978     GV *gv = (o->op_type == OP_GV || o->op_type == OP_GVSV
979             || o->op_type == OP_MULTIDEREF)
980 #ifdef USE_ITHREADS
981                 && PL_curpad
982                 ? ((GV*)PAD_SVl(*ixp)) : NULL;
983 #else
984                 ? (GV*)(*svp) : NULL;
985 #endif
986     /* It's possible during global destruction that the GV is freed
987        before the optree. Whilst the SvREFCNT_inc is happy to bump from
988        0 to 1 on a freed SV, the corresponding SvREFCNT_dec from 1 to 0
989        will trigger an assertion failure, because the entry to sv_clear
990        checks that the scalar is not already freed.  A check of for
991        !SvIS_FREED(gv) turns out to be invalid, because during global
992        destruction the reference count can be forced down to zero
993        (with SVf_BREAK set).  In which case raising to 1 and then
994        dropping to 0 triggers cleanup before it should happen.  I
995        *think* that this might actually be a general, systematic,
996        weakness of the whole idea of SVf_BREAK, in that code *is*
997        allowed to raise and lower references during global destruction,
998        so any *valid* code that happens to do this during global
999        destruction might well trigger premature cleanup.  */
1000     bool still_valid = gv && SvREFCNT(gv);
1001
1002     if (still_valid)
1003         SvREFCNT_inc_simple_void(gv);
1004 #ifdef USE_ITHREADS
1005     if (*ixp > 0) {
1006         pad_swipe(*ixp, TRUE);
1007         *ixp = 0;
1008     }
1009 #else
1010     SvREFCNT_dec(*svp);
1011     *svp = NULL;
1012 #endif
1013     if (still_valid) {
1014         int try_downgrade = SvREFCNT(gv) == 2;
1015         SvREFCNT_dec_NN(gv);
1016         if (try_downgrade)
1017             gv_try_downgrade(gv);
1018     }
1019 }
1020
1021
1022 void
1023 Perl_op_clear(pTHX_ OP *o)
1024 {
1025
1026
1027     PERL_ARGS_ASSERT_OP_CLEAR;
1028
1029     switch (o->op_type) {
1030     case OP_NULL:       /* Was holding old type, if any. */
1031         /* FALLTHROUGH */
1032     case OP_ENTERTRY:
1033     case OP_ENTEREVAL:  /* Was holding hints. */
1034     case OP_ARGDEFELEM: /* Was holding signature index. */
1035         o->op_targ = 0;
1036         break;
1037     default:
1038         if (!(o->op_flags & OPf_REF) || !OP_IS_STAT(o->op_type))
1039             break;
1040         /* FALLTHROUGH */
1041     case OP_GVSV:
1042     case OP_GV:
1043     case OP_AELEMFAST:
1044 #ifdef USE_ITHREADS
1045             S_op_clear_gv(aTHX_ o, &(cPADOPx(o)->op_padix));
1046 #else
1047             S_op_clear_gv(aTHX_ o, &(cSVOPx(o)->op_sv));
1048 #endif
1049         break;
1050     case OP_METHOD_REDIR:
1051     case OP_METHOD_REDIR_SUPER:
1052 #ifdef USE_ITHREADS
1053         if (cMETHOPx(o)->op_rclass_targ) {
1054             pad_swipe(cMETHOPx(o)->op_rclass_targ, 1);
1055             cMETHOPx(o)->op_rclass_targ = 0;
1056         }
1057 #else
1058         SvREFCNT_dec(cMETHOPx(o)->op_rclass_sv);
1059         cMETHOPx(o)->op_rclass_sv = NULL;
1060 #endif
1061         /* FALLTHROUGH */
1062     case OP_METHOD_NAMED:
1063     case OP_METHOD_SUPER:
1064         SvREFCNT_dec(cMETHOPx(o)->op_u.op_meth_sv);
1065         cMETHOPx(o)->op_u.op_meth_sv = NULL;
1066 #ifdef USE_ITHREADS
1067         if (o->op_targ) {
1068             pad_swipe(o->op_targ, 1);
1069             o->op_targ = 0;
1070         }
1071 #endif
1072         break;
1073     case OP_CONST:
1074     case OP_HINTSEVAL:
1075         SvREFCNT_dec(cSVOPo->op_sv);
1076         cSVOPo->op_sv = NULL;
1077 #ifdef USE_ITHREADS
1078         /** Bug #15654
1079           Even if op_clear does a pad_free for the target of the op,
1080           pad_free doesn't actually remove the sv that exists in the pad;
1081           instead it lives on. This results in that it could be reused as
1082           a target later on when the pad was reallocated.
1083         **/
1084         if(o->op_targ) {
1085           pad_swipe(o->op_targ,1);
1086           o->op_targ = 0;
1087         }
1088 #endif
1089         break;
1090     case OP_DUMP:
1091     case OP_GOTO:
1092     case OP_NEXT:
1093     case OP_LAST:
1094     case OP_REDO:
1095         if (o->op_flags & (OPf_SPECIAL|OPf_STACKED|OPf_KIDS))
1096             break;
1097         /* FALLTHROUGH */
1098     case OP_TRANS:
1099     case OP_TRANSR:
1100         if (   (o->op_type == OP_TRANS || o->op_type == OP_TRANSR)
1101             && (o->op_private & OPpTRANS_USE_SVOP))
1102         {
1103 #ifdef USE_ITHREADS
1104             if (cPADOPo->op_padix > 0) {
1105                 pad_swipe(cPADOPo->op_padix, TRUE);
1106                 cPADOPo->op_padix = 0;
1107             }
1108 #else
1109             SvREFCNT_dec(cSVOPo->op_sv);
1110             cSVOPo->op_sv = NULL;
1111 #endif
1112         }
1113         else {
1114             PerlMemShared_free(cPVOPo->op_pv);
1115             cPVOPo->op_pv = NULL;
1116         }
1117         break;
1118     case OP_SUBST:
1119         op_free(cPMOPo->op_pmreplrootu.op_pmreplroot);
1120         goto clear_pmop;
1121
1122     case OP_SPLIT:
1123         if (     (o->op_private & OPpSPLIT_ASSIGN) /* @array  = split */
1124             && !(o->op_flags & OPf_STACKED))       /* @{expr} = split */
1125         {
1126             if (o->op_private & OPpSPLIT_LEX)
1127                 pad_free(cPMOPo->op_pmreplrootu.op_pmtargetoff);
1128             else
1129 #ifdef USE_ITHREADS
1130                 pad_swipe(cPMOPo->op_pmreplrootu.op_pmtargetoff, TRUE);
1131 #else
1132                 SvREFCNT_dec(MUTABLE_SV(cPMOPo->op_pmreplrootu.op_pmtargetgv));
1133 #endif
1134         }
1135         /* FALLTHROUGH */
1136     case OP_MATCH:
1137     case OP_QR:
1138     clear_pmop:
1139         if (!(cPMOPo->op_pmflags & PMf_CODELIST_PRIVATE))
1140             op_free(cPMOPo->op_code_list);
1141         cPMOPo->op_code_list = NULL;
1142         forget_pmop(cPMOPo);
1143         cPMOPo->op_pmreplrootu.op_pmreplroot = NULL;
1144         /* we use the same protection as the "SAFE" version of the PM_ macros
1145          * here since sv_clean_all might release some PMOPs
1146          * after PL_regex_padav has been cleared
1147          * and the clearing of PL_regex_padav needs to
1148          * happen before sv_clean_all
1149          */
1150 #ifdef USE_ITHREADS
1151         if(PL_regex_pad) {        /* We could be in destruction */
1152             const IV offset = (cPMOPo)->op_pmoffset;
1153             ReREFCNT_dec(PM_GETRE(cPMOPo));
1154             PL_regex_pad[offset] = &PL_sv_undef;
1155             sv_catpvn_nomg(PL_regex_pad[0], (const char *)&offset,
1156                            sizeof(offset));
1157         }
1158 #else
1159         ReREFCNT_dec(PM_GETRE(cPMOPo));
1160         PM_SETRE(cPMOPo, NULL);
1161 #endif
1162
1163         break;
1164
1165     case OP_ARGCHECK:
1166         PerlMemShared_free(cUNOP_AUXo->op_aux);
1167         break;
1168
1169     case OP_MULTICONCAT:
1170         {
1171             UNOP_AUX_item *aux = cUNOP_AUXo->op_aux;
1172             /* aux[PERL_MULTICONCAT_IX_PLAIN_PV] and/or
1173              * aux[PERL_MULTICONCAT_IX_UTF8_PV] point to plain and/or
1174              * utf8 shared strings */
1175             char *p1 = aux[PERL_MULTICONCAT_IX_PLAIN_PV].pv;
1176             char *p2 = aux[PERL_MULTICONCAT_IX_UTF8_PV].pv;
1177             if (p1)
1178                 PerlMemShared_free(p1);
1179             if (p2 && p1 != p2)
1180                 PerlMemShared_free(p2);
1181             PerlMemShared_free(aux);
1182         }
1183         break;
1184
1185     case OP_MULTIDEREF:
1186         {
1187             UNOP_AUX_item *items = cUNOP_AUXo->op_aux;
1188             UV actions = items->uv;
1189             bool last = 0;
1190             bool is_hash = FALSE;
1191
1192             while (!last) {
1193                 switch (actions & MDEREF_ACTION_MASK) {
1194
1195                 case MDEREF_reload:
1196                     actions = (++items)->uv;
1197                     continue;
1198
1199                 case MDEREF_HV_padhv_helem:
1200                     is_hash = TRUE;
1201                     /* FALLTHROUGH */
1202                 case MDEREF_AV_padav_aelem:
1203                     pad_free((++items)->pad_offset);
1204                     goto do_elem;
1205
1206                 case MDEREF_HV_gvhv_helem:
1207                     is_hash = TRUE;
1208                     /* FALLTHROUGH */
1209                 case MDEREF_AV_gvav_aelem:
1210 #ifdef USE_ITHREADS
1211                     S_op_clear_gv(aTHX_ o, &((++items)->pad_offset));
1212 #else
1213                     S_op_clear_gv(aTHX_ o, &((++items)->sv));
1214 #endif
1215                     goto do_elem;
1216
1217                 case MDEREF_HV_gvsv_vivify_rv2hv_helem:
1218                     is_hash = TRUE;
1219                     /* FALLTHROUGH */
1220                 case MDEREF_AV_gvsv_vivify_rv2av_aelem:
1221 #ifdef USE_ITHREADS
1222                     S_op_clear_gv(aTHX_ o, &((++items)->pad_offset));
1223 #else
1224                     S_op_clear_gv(aTHX_ o, &((++items)->sv));
1225 #endif
1226                     goto do_vivify_rv2xv_elem;
1227
1228                 case MDEREF_HV_padsv_vivify_rv2hv_helem:
1229                     is_hash = TRUE;
1230                     /* FALLTHROUGH */
1231                 case MDEREF_AV_padsv_vivify_rv2av_aelem:
1232                     pad_free((++items)->pad_offset);
1233                     goto do_vivify_rv2xv_elem;
1234
1235                 case MDEREF_HV_pop_rv2hv_helem:
1236                 case MDEREF_HV_vivify_rv2hv_helem:
1237                     is_hash = TRUE;
1238                     /* FALLTHROUGH */
1239                 do_vivify_rv2xv_elem:
1240                 case MDEREF_AV_pop_rv2av_aelem:
1241                 case MDEREF_AV_vivify_rv2av_aelem:
1242                 do_elem:
1243                     switch (actions & MDEREF_INDEX_MASK) {
1244                     case MDEREF_INDEX_none:
1245                         last = 1;
1246                         break;
1247                     case MDEREF_INDEX_const:
1248                         if (is_hash) {
1249 #ifdef USE_ITHREADS
1250                             /* see RT #15654 */
1251                             pad_swipe((++items)->pad_offset, 1);
1252 #else
1253                             SvREFCNT_dec((++items)->sv);
1254 #endif
1255                         }
1256                         else
1257                             items++;
1258                         break;
1259                     case MDEREF_INDEX_padsv:
1260                         pad_free((++items)->pad_offset);
1261                         break;
1262                     case MDEREF_INDEX_gvsv:
1263 #ifdef USE_ITHREADS
1264                         S_op_clear_gv(aTHX_ o, &((++items)->pad_offset));
1265 #else
1266                         S_op_clear_gv(aTHX_ o, &((++items)->sv));
1267 #endif
1268                         break;
1269                     }
1270
1271                     if (actions & MDEREF_FLAG_last)
1272                         last = 1;
1273                     is_hash = FALSE;
1274
1275                     break;
1276
1277                 default:
1278                     assert(0);
1279                     last = 1;
1280                     break;
1281
1282                 } /* switch */
1283
1284                 actions >>= MDEREF_SHIFT;
1285             } /* while */
1286
1287             /* start of malloc is at op_aux[-1], where the length is
1288              * stored */
1289             PerlMemShared_free(cUNOP_AUXo->op_aux - 1);
1290         }
1291         break;
1292     }
1293
1294     if (o->op_targ > 0) {
1295         pad_free(o->op_targ);
1296         o->op_targ = 0;
1297     }
1298 }
1299
1300 STATIC void
1301 S_cop_free(pTHX_ COP* cop)
1302 {
1303     PERL_ARGS_ASSERT_COP_FREE;
1304
1305     CopFILE_free(cop);
1306     if (! specialWARN(cop->cop_warnings))
1307         PerlMemShared_free(cop->cop_warnings);
1308     cophh_free(CopHINTHASH_get(cop));
1309     if (PL_curcop == cop)
1310        PL_curcop = NULL;
1311 }
1312
1313 STATIC void
1314 S_forget_pmop(pTHX_ PMOP *const o)
1315 {
1316     HV * const pmstash = PmopSTASH(o);
1317
1318     PERL_ARGS_ASSERT_FORGET_PMOP;
1319
1320     if (pmstash && !SvIS_FREED(pmstash) && SvMAGICAL(pmstash)) {
1321         MAGIC * const mg = mg_find((const SV *)pmstash, PERL_MAGIC_symtab);
1322         if (mg) {
1323             PMOP **const array = (PMOP**) mg->mg_ptr;
1324             U32 count = mg->mg_len / sizeof(PMOP**);
1325             U32 i = count;
1326
1327             while (i--) {
1328                 if (array[i] == o) {
1329                     /* Found it. Move the entry at the end to overwrite it.  */
1330                     array[i] = array[--count];
1331                     mg->mg_len = count * sizeof(PMOP**);
1332                     /* Could realloc smaller at this point always, but probably
1333                        not worth it. Probably worth free()ing if we're the
1334                        last.  */
1335                     if(!count) {
1336                         Safefree(mg->mg_ptr);
1337                         mg->mg_ptr = NULL;
1338                     }
1339                     break;
1340                 }
1341             }
1342         }
1343     }
1344     if (PL_curpm == o)
1345         PL_curpm = NULL;
1346 }
1347
1348
1349 STATIC void
1350 S_find_and_forget_pmops(pTHX_ OP *o)
1351 {
1352     OP* top_op = o;
1353
1354     PERL_ARGS_ASSERT_FIND_AND_FORGET_PMOPS;
1355
1356     while (1) {
1357         switch (o->op_type) {
1358         case OP_SUBST:
1359         case OP_SPLIT:
1360         case OP_MATCH:
1361         case OP_QR:
1362             forget_pmop((PMOP*)o);
1363         }
1364
1365         if (o->op_flags & OPf_KIDS) {
1366             o = cUNOPo->op_first;
1367             continue;
1368         }
1369
1370         while (1) {
1371             if (o == top_op)
1372                 return; /* at top; no parents/siblings to try */
1373             if (OpHAS_SIBLING(o)) {
1374                 o = o->op_sibparent; /* process next sibling */
1375                 break;
1376             }
1377             o = o->op_sibparent; /*try parent's next sibling */
1378         }
1379     }
1380 }
1381
1382
1383 /*
1384 =for apidoc op_null
1385
1386 Neutralizes an op when it is no longer needed, but is still linked to from
1387 other ops.
1388
1389 =cut
1390 */
1391
1392 void
1393 Perl_op_null(pTHX_ OP *o)
1394 {
1395
1396     PERL_ARGS_ASSERT_OP_NULL;
1397
1398     if (o->op_type == OP_NULL)
1399         return;
1400     op_clear(o);
1401     o->op_targ = o->op_type;
1402     OpTYPE_set(o, OP_NULL);
1403 }
1404
1405 void
1406 Perl_op_refcnt_lock(pTHX)
1407   PERL_TSA_ACQUIRE(PL_op_mutex)
1408 {
1409 #ifdef USE_ITHREADS
1410 #endif
1411     PERL_UNUSED_CONTEXT;
1412     OP_REFCNT_LOCK;
1413 }
1414
1415 void
1416 Perl_op_refcnt_unlock(pTHX)
1417   PERL_TSA_RELEASE(PL_op_mutex)
1418 {
1419 #ifdef USE_ITHREADS
1420 #endif
1421     PERL_UNUSED_CONTEXT;
1422     OP_REFCNT_UNLOCK;
1423 }
1424
1425
1426 /*
1427 =for apidoc op_sibling_splice
1428
1429 A general function for editing the structure of an existing chain of
1430 op_sibling nodes.  By analogy with the perl-level C<splice()> function, allows
1431 you to delete zero or more sequential nodes, replacing them with zero or
1432 more different nodes.  Performs the necessary op_first/op_last
1433 housekeeping on the parent node and op_sibling manipulation on the
1434 children.  The last deleted node will be marked as the last node by
1435 updating the op_sibling/op_sibparent or op_moresib field as appropriate.
1436
1437 Note that op_next is not manipulated, and nodes are not freed; that is the
1438 responsibility of the caller.  It also won't create a new list op for an
1439 empty list etc; use higher-level functions like op_append_elem() for that.
1440
1441 C<parent> is the parent node of the sibling chain. It may passed as C<NULL> if
1442 the splicing doesn't affect the first or last op in the chain.
1443
1444 C<start> is the node preceding the first node to be spliced.  Node(s)
1445 following it will be deleted, and ops will be inserted after it.  If it is
1446 C<NULL>, the first node onwards is deleted, and nodes are inserted at the
1447 beginning.
1448
1449 C<del_count> is the number of nodes to delete.  If zero, no nodes are deleted.
1450 If -1 or greater than or equal to the number of remaining kids, all
1451 remaining kids are deleted.
1452
1453 C<insert> is the first of a chain of nodes to be inserted in place of the nodes.
1454 If C<NULL>, no nodes are inserted.
1455
1456 The head of the chain of deleted ops is returned, or C<NULL> if no ops were
1457 deleted.
1458
1459 For example:
1460
1461     action                    before      after         returns
1462     ------                    -----       -----         -------
1463
1464                               P           P
1465     splice(P, A, 2, X-Y-Z)    |           |             B-C
1466                               A-B-C-D     A-X-Y-Z-D
1467
1468                               P           P
1469     splice(P, NULL, 1, X-Y)   |           |             A
1470                               A-B-C-D     X-Y-B-C-D
1471
1472                               P           P
1473     splice(P, NULL, 3, NULL)  |           |             A-B-C
1474                               A-B-C-D     D
1475
1476                               P           P
1477     splice(P, B, 0, X-Y)      |           |             NULL
1478                               A-B-C-D     A-B-X-Y-C-D
1479
1480
1481 For lower-level direct manipulation of C<op_sibparent> and C<op_moresib>,
1482 see C<L</OpMORESIB_set>>, C<L</OpLASTSIB_set>>, C<L</OpMAYBESIB_set>>.
1483
1484 =cut
1485 */
1486
1487 OP *
1488 Perl_op_sibling_splice(OP *parent, OP *start, int del_count, OP* insert)
1489 {
1490     OP *first;
1491     OP *rest;
1492     OP *last_del = NULL;
1493     OP *last_ins = NULL;
1494
1495     if (start)
1496         first = OpSIBLING(start);
1497     else if (!parent)
1498         goto no_parent;
1499     else
1500         first = cLISTOPx(parent)->op_first;
1501
1502     assert(del_count >= -1);
1503
1504     if (del_count && first) {
1505         last_del = first;
1506         while (--del_count && OpHAS_SIBLING(last_del))
1507             last_del = OpSIBLING(last_del);
1508         rest = OpSIBLING(last_del);
1509         OpLASTSIB_set(last_del, NULL);
1510     }
1511     else
1512         rest = first;
1513
1514     if (insert) {
1515         last_ins = insert;
1516         while (OpHAS_SIBLING(last_ins))
1517             last_ins = OpSIBLING(last_ins);
1518         OpMAYBESIB_set(last_ins, rest, NULL);
1519     }
1520     else
1521         insert = rest;
1522
1523     if (start) {
1524         OpMAYBESIB_set(start, insert, NULL);
1525     }
1526     else {
1527         assert(parent);
1528         cLISTOPx(parent)->op_first = insert;
1529         if (insert)
1530             parent->op_flags |= OPf_KIDS;
1531         else
1532             parent->op_flags &= ~OPf_KIDS;
1533     }
1534
1535     if (!rest) {
1536         /* update op_last etc */
1537         U32 type;
1538         OP *lastop;
1539
1540         if (!parent)
1541             goto no_parent;
1542
1543         /* ought to use OP_CLASS(parent) here, but that can't handle
1544          * ex-foo OP_NULL ops. Also note that XopENTRYCUSTOM() can't
1545          * either */
1546         type = parent->op_type;
1547         if (type == OP_CUSTOM) {
1548             dTHX;
1549             type = XopENTRYCUSTOM(parent, xop_class);
1550         }
1551         else {
1552             if (type == OP_NULL)
1553                 type = parent->op_targ;
1554             type = PL_opargs[type] & OA_CLASS_MASK;
1555         }
1556
1557         lastop = last_ins ? last_ins : start ? start : NULL;
1558         if (   type == OA_BINOP
1559             || type == OA_LISTOP
1560             || type == OA_PMOP
1561             || type == OA_LOOP
1562         )
1563             cLISTOPx(parent)->op_last = lastop;
1564
1565         if (lastop)
1566             OpLASTSIB_set(lastop, parent);
1567     }
1568     return last_del ? first : NULL;
1569
1570   no_parent:
1571     Perl_croak_nocontext("panic: op_sibling_splice(): NULL parent");
1572 }
1573
1574 /*
1575 =for apidoc op_parent
1576
1577 Returns the parent OP of C<o>, if it has a parent. Returns C<NULL> otherwise.
1578
1579 =cut
1580 */
1581
1582 OP *
1583 Perl_op_parent(OP *o)
1584 {
1585     PERL_ARGS_ASSERT_OP_PARENT;
1586     while (OpHAS_SIBLING(o))
1587         o = OpSIBLING(o);
1588     return o->op_sibparent;
1589 }
1590
1591 /* replace the sibling following start with a new UNOP, which becomes
1592  * the parent of the original sibling; e.g.
1593  *
1594  *  op_sibling_newUNOP(P, A, unop-args...)
1595  *
1596  *  P              P
1597  *  |      becomes |
1598  *  A-B-C          A-U-C
1599  *                   |
1600  *                   B
1601  *
1602  * where U is the new UNOP.
1603  *
1604  * parent and start args are the same as for op_sibling_splice();
1605  * type and flags args are as newUNOP().
1606  *
1607  * Returns the new UNOP.
1608  */
1609
1610 STATIC OP *
1611 S_op_sibling_newUNOP(pTHX_ OP *parent, OP *start, I32 type, I32 flags)
1612 {
1613     OP *kid, *newop;
1614
1615     kid = op_sibling_splice(parent, start, 1, NULL);
1616     newop = newUNOP(type, flags, kid);
1617     op_sibling_splice(parent, start, 0, newop);
1618     return newop;
1619 }
1620
1621
1622 /* lowest-level newLOGOP-style function - just allocates and populates
1623  * the struct. Higher-level stuff should be done by S_new_logop() /
1624  * newLOGOP(). This function exists mainly to avoid op_first assignment
1625  * being spread throughout this file.
1626  */
1627
1628 LOGOP *
1629 Perl_alloc_LOGOP(pTHX_ I32 type, OP *first, OP* other)
1630 {
1631     LOGOP *logop;
1632     OP *kid = first;
1633     NewOp(1101, logop, 1, LOGOP);
1634     OpTYPE_set(logop, type);
1635     logop->op_first = first;
1636     logop->op_other = other;
1637     if (first)
1638         logop->op_flags = OPf_KIDS;
1639     while (kid && OpHAS_SIBLING(kid))
1640         kid = OpSIBLING(kid);
1641     if (kid)
1642         OpLASTSIB_set(kid, (OP*)logop);
1643     return logop;
1644 }
1645
1646
1647 /* Contextualizers */
1648
1649 /*
1650 =for apidoc op_contextualize
1651
1652 Applies a syntactic context to an op tree representing an expression.
1653 C<o> is the op tree, and C<context> must be C<G_SCALAR>, C<G_ARRAY>,
1654 or C<G_VOID> to specify the context to apply.  The modified op tree
1655 is returned.
1656
1657 =cut
1658 */
1659
1660 OP *
1661 Perl_op_contextualize(pTHX_ OP *o, I32 context)
1662 {
1663     PERL_ARGS_ASSERT_OP_CONTEXTUALIZE;
1664     switch (context) {
1665         case G_SCALAR: return scalar(o);
1666         case G_ARRAY:  return list(o);
1667         case G_VOID:   return scalarvoid(o);
1668         default:
1669             Perl_croak(aTHX_ "panic: op_contextualize bad context %ld",
1670                        (long) context);
1671     }
1672 }
1673
1674 /*
1675
1676 =for apidoc op_linklist
1677 This function is the implementation of the L</LINKLIST> macro.  It should
1678 not be called directly.
1679
1680 =cut
1681 */
1682
1683
1684 OP *
1685 Perl_op_linklist(pTHX_ OP *o)
1686 {
1687
1688     OP **prevp;
1689     OP *kid;
1690     OP * top_op = o;
1691
1692     PERL_ARGS_ASSERT_OP_LINKLIST;
1693
1694     while (1) {
1695         /* Descend down the tree looking for any unprocessed subtrees to
1696          * do first */
1697         if (!o->op_next) {
1698             if (o->op_flags & OPf_KIDS) {
1699                 o = cUNOPo->op_first;
1700                 continue;
1701             }
1702             o->op_next = o; /* leaf node; link to self initially */
1703         }
1704
1705         /* if we're at the top level, there either weren't any children
1706          * to process, or we've worked our way back to the top. */
1707         if (o == top_op)
1708             return o->op_next;
1709
1710         /* o is now processed. Next, process any sibling subtrees */
1711
1712         if (OpHAS_SIBLING(o)) {
1713             o = OpSIBLING(o);
1714             continue;
1715         }
1716
1717         /* Done all the subtrees at this level. Go back up a level and
1718          * link the parent in with all its (processed) children.
1719          */
1720
1721         o = o->op_sibparent;
1722         assert(!o->op_next);
1723         prevp = &(o->op_next);
1724         kid   = (o->op_flags & OPf_KIDS) ? cUNOPo->op_first : NULL;
1725         while (kid) {
1726             *prevp = kid->op_next;
1727             prevp = &(kid->op_next);
1728             kid = OpSIBLING(kid);
1729         }
1730         *prevp = o;
1731     }
1732 }
1733
1734
1735 static OP *
1736 S_scalarkids(pTHX_ OP *o)
1737 {
1738     if (o && o->op_flags & OPf_KIDS) {
1739         OP *kid;
1740         for (kid = cLISTOPo->op_first; kid; kid = OpSIBLING(kid))
1741             scalar(kid);
1742     }
1743     return o;
1744 }
1745
1746 STATIC OP *
1747 S_scalarboolean(pTHX_ OP *o)
1748 {
1749     PERL_ARGS_ASSERT_SCALARBOOLEAN;
1750
1751     if ((o->op_type == OP_SASSIGN && cBINOPo->op_first->op_type == OP_CONST &&
1752          !(cBINOPo->op_first->op_flags & OPf_SPECIAL)) ||
1753         (o->op_type == OP_NOT     && cUNOPo->op_first->op_type == OP_SASSIGN &&
1754          cBINOPx(cUNOPo->op_first)->op_first->op_type == OP_CONST &&
1755          !(cBINOPx(cUNOPo->op_first)->op_first->op_flags & OPf_SPECIAL))) {
1756         if (ckWARN(WARN_SYNTAX)) {
1757             const line_t oldline = CopLINE(PL_curcop);
1758
1759             if (PL_parser && PL_parser->copline != NOLINE) {
1760                 /* This ensures that warnings are reported at the first line
1761                    of the conditional, not the last.  */
1762                 CopLINE_set(PL_curcop, PL_parser->copline);
1763             }
1764             Perl_warner(aTHX_ packWARN(WARN_SYNTAX), "Found = in conditional, should be ==");
1765             CopLINE_set(PL_curcop, oldline);
1766         }
1767     }
1768     return scalar(o);
1769 }
1770
1771 static SV *
1772 S_op_varname_subscript(pTHX_ const OP *o, int subscript_type)
1773 {
1774     assert(o);
1775     assert(o->op_type == OP_PADAV || o->op_type == OP_RV2AV ||
1776            o->op_type == OP_PADHV || o->op_type == OP_RV2HV);
1777     {
1778         const char funny  = o->op_type == OP_PADAV
1779                          || o->op_type == OP_RV2AV ? '@' : '%';
1780         if (o->op_type == OP_RV2AV || o->op_type == OP_RV2HV) {
1781             GV *gv;
1782             if (cUNOPo->op_first->op_type != OP_GV
1783              || !(gv = cGVOPx_gv(cUNOPo->op_first)))
1784                 return NULL;
1785             return varname(gv, funny, 0, NULL, 0, subscript_type);
1786         }
1787         return
1788             varname(MUTABLE_GV(PL_compcv), funny, o->op_targ, NULL, 0, subscript_type);
1789     }
1790 }
1791
1792 static SV *
1793 S_op_varname(pTHX_ const OP *o)
1794 {
1795     return S_op_varname_subscript(aTHX_ o, 1);
1796 }
1797
1798 static void
1799 S_op_pretty(pTHX_ const OP *o, SV **retsv, const char **retpv)
1800 { /* or not so pretty :-) */
1801     if (o->op_type == OP_CONST) {
1802         *retsv = cSVOPo_sv;
1803         if (SvPOK(*retsv)) {
1804             SV *sv = *retsv;
1805             *retsv = sv_newmortal();
1806             pv_pretty(*retsv, SvPVX_const(sv), SvCUR(sv), 32, NULL, NULL,
1807                       PERL_PV_PRETTY_DUMP |PERL_PV_ESCAPE_UNI_DETECT);
1808         }
1809         else if (!SvOK(*retsv))
1810             *retpv = "undef";
1811     }
1812     else *retpv = "...";
1813 }
1814
1815 static void
1816 S_scalar_slice_warning(pTHX_ const OP *o)
1817 {
1818     OP *kid;
1819     const bool h = o->op_type == OP_HSLICE
1820                 || (o->op_type == OP_NULL && o->op_targ == OP_HSLICE);
1821     const char lbrack =
1822         h ? '{' : '[';
1823     const char rbrack =
1824         h ? '}' : ']';
1825     SV *name;
1826     SV *keysv = NULL; /* just to silence compiler warnings */
1827     const char *key = NULL;
1828
1829     if (!(o->op_private & OPpSLICEWARNING))
1830         return;
1831     if (PL_parser && PL_parser->error_count)
1832         /* This warning can be nonsensical when there is a syntax error. */
1833         return;
1834
1835     kid = cLISTOPo->op_first;
1836     kid = OpSIBLING(kid); /* get past pushmark */
1837     /* weed out false positives: any ops that can return lists */
1838     switch (kid->op_type) {
1839     case OP_BACKTICK:
1840     case OP_GLOB:
1841     case OP_READLINE:
1842     case OP_MATCH:
1843     case OP_RV2AV:
1844     case OP_EACH:
1845     case OP_VALUES:
1846     case OP_KEYS:
1847     case OP_SPLIT:
1848     case OP_LIST:
1849     case OP_SORT:
1850     case OP_REVERSE:
1851     case OP_ENTERSUB:
1852     case OP_CALLER:
1853     case OP_LSTAT:
1854     case OP_STAT:
1855     case OP_READDIR:
1856     case OP_SYSTEM:
1857     case OP_TMS:
1858     case OP_LOCALTIME:
1859     case OP_GMTIME:
1860     case OP_ENTEREVAL:
1861         return;
1862     }
1863
1864     /* Don't warn if we have a nulled list either. */
1865     if (kid->op_type == OP_NULL && kid->op_targ == OP_LIST)
1866         return;
1867
1868     assert(OpSIBLING(kid));
1869     name = S_op_varname(aTHX_ OpSIBLING(kid));
1870     if (!name) /* XS module fiddling with the op tree */
1871         return;
1872     S_op_pretty(aTHX_ kid, &keysv, &key);
1873     assert(SvPOK(name));
1874     sv_chop(name,SvPVX(name)+1);
1875     if (key)
1876        /* diag_listed_as: Scalar value @%s[%s] better written as $%s[%s] */
1877         Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
1878                    "Scalar value @%" SVf "%c%s%c better written as $%" SVf
1879                    "%c%s%c",
1880                     SVfARG(name), lbrack, key, rbrack, SVfARG(name),
1881                     lbrack, key, rbrack);
1882     else
1883        /* diag_listed_as: Scalar value @%s[%s] better written as $%s[%s] */
1884         Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
1885                    "Scalar value @%" SVf "%c%" SVf "%c better written as $%"
1886                     SVf "%c%" SVf "%c",
1887                     SVfARG(name), lbrack, SVfARG(keysv), rbrack,
1888                     SVfARG(name), lbrack, SVfARG(keysv), rbrack);
1889 }
1890
1891
1892
1893 /* apply scalar context to the o subtree */
1894
1895 OP *
1896 Perl_scalar(pTHX_ OP *o)
1897 {
1898     OP * top_op = o;
1899
1900     while (1) {
1901         OP *next_kid = NULL; /* what op (if any) to process next */
1902         OP *kid;
1903
1904         /* assumes no premature commitment */
1905         if (!o || (PL_parser && PL_parser->error_count)
1906              || (o->op_flags & OPf_WANT)
1907              || o->op_type == OP_RETURN)
1908         {
1909             goto do_next;
1910         }
1911
1912         o->op_flags = (o->op_flags & ~OPf_WANT) | OPf_WANT_SCALAR;
1913
1914         switch (o->op_type) {
1915         case OP_REPEAT:
1916             scalar(cBINOPo->op_first);
1917             /* convert what initially looked like a list repeat into a
1918              * scalar repeat, e.g. $s = (1) x $n
1919              */
1920             if (o->op_private & OPpREPEAT_DOLIST) {
1921                 kid = cLISTOPx(cUNOPo->op_first)->op_first;
1922                 assert(kid->op_type == OP_PUSHMARK);
1923                 if (OpHAS_SIBLING(kid) && !OpHAS_SIBLING(OpSIBLING(kid))) {
1924                     op_null(cLISTOPx(cUNOPo->op_first)->op_first);
1925                     o->op_private &=~ OPpREPEAT_DOLIST;
1926                 }
1927             }
1928             break;
1929
1930         case OP_OR:
1931         case OP_AND:
1932         case OP_COND_EXPR:
1933             /* impose scalar context on everything except the condition */
1934             next_kid = OpSIBLING(cUNOPo->op_first);
1935             break;
1936
1937         default:
1938             if (o->op_flags & OPf_KIDS)
1939                 next_kid = cUNOPo->op_first; /* do all kids */
1940             break;
1941
1942         /* the children of these ops are usually a list of statements,
1943          * except the leaves, whose first child is a corresponding enter
1944          */
1945         case OP_SCOPE:
1946         case OP_LINESEQ:
1947         case OP_LIST:
1948             kid = cLISTOPo->op_first;
1949             goto do_kids;
1950         case OP_LEAVE:
1951         case OP_LEAVETRY:
1952             kid = cLISTOPo->op_first;
1953             scalar(kid);
1954             kid = OpSIBLING(kid);
1955         do_kids:
1956             while (kid) {
1957                 OP *sib = OpSIBLING(kid);
1958                 /* Apply void context to all kids except the last, which
1959                  * is scalar (ignoring a trailing ex-nextstate in determining
1960                  * if it's the last kid). E.g.
1961                  *      $scalar = do { void; void; scalar }
1962                  * Except that 'when's are always scalar, e.g.
1963                  *      $scalar = do { given(..) {
1964                     *                 when (..) { scalar }
1965                     *                 when (..) { scalar }
1966                     *                 ...
1967                     *                }}
1968                     */
1969                 if (!sib
1970                      || (  !OpHAS_SIBLING(sib)
1971                          && sib->op_type == OP_NULL
1972                          && (   sib->op_targ == OP_NEXTSTATE
1973                              || sib->op_targ == OP_DBSTATE  )
1974                         )
1975                 )
1976                 {
1977                     /* tail call optimise calling scalar() on the last kid */
1978                     next_kid = kid;
1979                     goto do_next;
1980                 }
1981                 else if (kid->op_type == OP_LEAVEWHEN)
1982                     scalar(kid);
1983                 else
1984                     scalarvoid(kid);
1985                 kid = sib;
1986             }
1987             NOT_REACHED; /* NOTREACHED */
1988             break;
1989
1990         case OP_SORT:
1991             Perl_ck_warner(aTHX_ packWARN(WARN_VOID), "Useless use of sort in scalar context");
1992             break;
1993
1994         case OP_KVHSLICE:
1995         case OP_KVASLICE:
1996         {
1997             /* Warn about scalar context */
1998             const char lbrack = o->op_type == OP_KVHSLICE ? '{' : '[';
1999             const char rbrack = o->op_type == OP_KVHSLICE ? '}' : ']';
2000             SV *name;
2001             SV *keysv;
2002             const char *key = NULL;
2003
2004             /* This warning can be nonsensical when there is a syntax error. */
2005             if (PL_parser && PL_parser->error_count)
2006                 break;
2007
2008             if (!ckWARN(WARN_SYNTAX)) break;
2009
2010             kid = cLISTOPo->op_first;
2011             kid = OpSIBLING(kid); /* get past pushmark */
2012             assert(OpSIBLING(kid));
2013             name = S_op_varname(aTHX_ OpSIBLING(kid));
2014             if (!name) /* XS module fiddling with the op tree */
2015                 break;
2016             S_op_pretty(aTHX_ kid, &keysv, &key);
2017             assert(SvPOK(name));
2018             sv_chop(name,SvPVX(name)+1);
2019             if (key)
2020       /* diag_listed_as: %%s[%s] in scalar context better written as $%s[%s] */
2021                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
2022                            "%%%" SVf "%c%s%c in scalar context better written "
2023                            "as $%" SVf "%c%s%c",
2024                             SVfARG(name), lbrack, key, rbrack, SVfARG(name),
2025                             lbrack, key, rbrack);
2026             else
2027       /* diag_listed_as: %%s[%s] in scalar context better written as $%s[%s] */
2028                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
2029                            "%%%" SVf "%c%" SVf "%c in scalar context better "
2030                            "written as $%" SVf "%c%" SVf "%c",
2031                             SVfARG(name), lbrack, SVfARG(keysv), rbrack,
2032                             SVfARG(name), lbrack, SVfARG(keysv), rbrack);
2033         }
2034         } /* switch */
2035
2036         /* If next_kid is set, someone in the code above wanted us to process
2037          * that kid and all its remaining siblings.  Otherwise, work our way
2038          * back up the tree */
2039       do_next:
2040         while (!next_kid) {
2041             if (o == top_op)
2042                 return top_op; /* at top; no parents/siblings to try */
2043             if (OpHAS_SIBLING(o))
2044                 next_kid = o->op_sibparent;
2045             else {
2046                 o = o->op_sibparent; /*try parent's next sibling */
2047                 switch (o->op_type) {
2048                 case OP_SCOPE:
2049                 case OP_LINESEQ:
2050                 case OP_LIST:
2051                 case OP_LEAVE:
2052                 case OP_LEAVETRY:
2053                     /* should really restore PL_curcop to its old value, but
2054                      * setting it to PL_compiling is better than do nothing */
2055                     PL_curcop = &PL_compiling;
2056                 }
2057             }
2058         }
2059         o = next_kid;
2060     } /* while */
2061 }
2062
2063
2064 /* apply void context to the optree arg */
2065
2066 OP *
2067 Perl_scalarvoid(pTHX_ OP *arg)
2068 {
2069     OP *kid;
2070     SV* sv;
2071     OP *o = arg;
2072
2073     PERL_ARGS_ASSERT_SCALARVOID;
2074
2075     while (1) {
2076         U8 want;
2077         SV *useless_sv = NULL;
2078         const char* useless = NULL;
2079         OP * next_kid = NULL;
2080
2081         if (o->op_type == OP_NEXTSTATE
2082             || o->op_type == OP_DBSTATE
2083             || (o->op_type == OP_NULL && (o->op_targ == OP_NEXTSTATE
2084                                           || o->op_targ == OP_DBSTATE)))
2085             PL_curcop = (COP*)o;                /* for warning below */
2086
2087         /* assumes no premature commitment */
2088         want = o->op_flags & OPf_WANT;
2089         if ((want && want != OPf_WANT_SCALAR)
2090             || (PL_parser && PL_parser->error_count)
2091             || o->op_type == OP_RETURN || o->op_type == OP_REQUIRE || o->op_type == OP_LEAVEWHEN)
2092         {
2093             goto get_next_op;
2094         }
2095
2096         if ((o->op_private & OPpTARGET_MY)
2097             && (PL_opargs[o->op_type] & OA_TARGLEX))/* OPp share the meaning */
2098         {
2099             /* newASSIGNOP has already applied scalar context, which we
2100                leave, as if this op is inside SASSIGN.  */
2101             goto get_next_op;
2102         }
2103
2104         o->op_flags = (o->op_flags & ~OPf_WANT) | OPf_WANT_VOID;
2105
2106         switch (o->op_type) {
2107         default:
2108             if (!(PL_opargs[o->op_type] & OA_FOLDCONST))
2109                 break;
2110             /* FALLTHROUGH */
2111         case OP_REPEAT:
2112             if (o->op_flags & OPf_STACKED)
2113                 break;
2114             if (o->op_type == OP_REPEAT)
2115                 scalar(cBINOPo->op_first);
2116             goto func_ops;
2117         case OP_CONCAT:
2118             if ((o->op_flags & OPf_STACKED) &&
2119                     !(o->op_private & OPpCONCAT_NESTED))
2120                 break;
2121             goto func_ops;
2122         case OP_SUBSTR:
2123             if (o->op_private == 4)
2124                 break;
2125             /* FALLTHROUGH */
2126         case OP_WANTARRAY:
2127         case OP_GV:
2128         case OP_SMARTMATCH:
2129         case OP_AV2ARYLEN:
2130         case OP_REF:
2131         case OP_REFGEN:
2132         case OP_SREFGEN:
2133         case OP_DEFINED:
2134         case OP_HEX:
2135         case OP_OCT:
2136         case OP_LENGTH:
2137         case OP_VEC:
2138         case OP_INDEX:
2139         case OP_RINDEX:
2140         case OP_SPRINTF:
2141         case OP_KVASLICE:
2142         case OP_KVHSLICE:
2143         case OP_UNPACK:
2144         case OP_PACK:
2145         case OP_JOIN:
2146         case OP_LSLICE:
2147         case OP_ANONLIST:
2148         case OP_ANONHASH:
2149         case OP_SORT:
2150         case OP_REVERSE:
2151         case OP_RANGE:
2152         case OP_FLIP:
2153         case OP_FLOP:
2154         case OP_CALLER:
2155         case OP_FILENO:
2156         case OP_EOF:
2157         case OP_TELL:
2158         case OP_GETSOCKNAME:
2159         case OP_GETPEERNAME:
2160         case OP_READLINK:
2161         case OP_TELLDIR:
2162         case OP_GETPPID:
2163         case OP_GETPGRP:
2164         case OP_GETPRIORITY:
2165         case OP_TIME:
2166         case OP_TMS:
2167         case OP_LOCALTIME:
2168         case OP_GMTIME:
2169         case OP_GHBYNAME:
2170         case OP_GHBYADDR:
2171         case OP_GHOSTENT:
2172         case OP_GNBYNAME:
2173         case OP_GNBYADDR:
2174         case OP_GNETENT:
2175         case OP_GPBYNAME:
2176         case OP_GPBYNUMBER:
2177         case OP_GPROTOENT:
2178         case OP_GSBYNAME:
2179         case OP_GSBYPORT:
2180         case OP_GSERVENT:
2181         case OP_GPWNAM:
2182         case OP_GPWUID:
2183         case OP_GGRNAM:
2184         case OP_GGRGID:
2185         case OP_GETLOGIN:
2186         case OP_PROTOTYPE:
2187         case OP_RUNCV:
2188         func_ops:
2189             useless = OP_DESC(o);
2190             break;
2191
2192         case OP_GVSV:
2193         case OP_PADSV:
2194         case OP_PADAV:
2195         case OP_PADHV:
2196         case OP_PADANY:
2197         case OP_AELEM:
2198         case OP_AELEMFAST:
2199         case OP_AELEMFAST_LEX:
2200         case OP_ASLICE:
2201         case OP_HELEM:
2202         case OP_HSLICE:
2203             if (!(o->op_private & (OPpLVAL_INTRO|OPpOUR_INTRO)))
2204                 /* Otherwise it's "Useless use of grep iterator" */
2205                 useless = OP_DESC(o);
2206             break;
2207
2208         case OP_SPLIT:
2209             if (!(o->op_private & OPpSPLIT_ASSIGN))
2210                 useless = OP_DESC(o);
2211             break;
2212
2213         case OP_NOT:
2214             kid = cUNOPo->op_first;
2215             if (kid->op_type != OP_MATCH && kid->op_type != OP_SUBST &&
2216                 kid->op_type != OP_TRANS && kid->op_type != OP_TRANSR) {
2217                 goto func_ops;
2218             }
2219             useless = "negative pattern binding (!~)";
2220             break;
2221
2222         case OP_SUBST:
2223             if (cPMOPo->op_pmflags & PMf_NONDESTRUCT)
2224                 useless = "non-destructive substitution (s///r)";
2225             break;
2226
2227         case OP_TRANSR:
2228             useless = "non-destructive transliteration (tr///r)";
2229             break;
2230
2231         case OP_RV2GV:
2232         case OP_RV2SV:
2233         case OP_RV2AV:
2234         case OP_RV2HV:
2235             if (!(o->op_private & (OPpLVAL_INTRO|OPpOUR_INTRO)) &&
2236                 (!OpHAS_SIBLING(o) || OpSIBLING(o)->op_type != OP_READLINE))
2237                 useless = "a variable";
2238             break;
2239
2240         case OP_CONST:
2241             sv = cSVOPo_sv;
2242             if (cSVOPo->op_private & OPpCONST_STRICT)
2243                 no_bareword_allowed(o);
2244             else {
2245                 if (ckWARN(WARN_VOID)) {
2246                     NV nv;
2247                     /* don't warn on optimised away booleans, eg
2248                      * use constant Foo, 5; Foo || print; */
2249                     if (cSVOPo->op_private & OPpCONST_SHORTCIRCUIT)
2250                         useless = NULL;
2251                     /* the constants 0 and 1 are permitted as they are
2252                        conventionally used as dummies in constructs like
2253                        1 while some_condition_with_side_effects;  */
2254                     else if (SvNIOK(sv) && ((nv = SvNV(sv)) == 0.0 || nv == 1.0))
2255                         useless = NULL;
2256                     else if (SvPOK(sv)) {
2257                         SV * const dsv = newSVpvs("");
2258                         useless_sv
2259                             = Perl_newSVpvf(aTHX_
2260                                             "a constant (%s)",
2261                                             pv_pretty(dsv, SvPVX_const(sv),
2262                                                       SvCUR(sv), 32, NULL, NULL,
2263                                                       PERL_PV_PRETTY_DUMP
2264                                                       | PERL_PV_ESCAPE_NOCLEAR
2265                                                       | PERL_PV_ESCAPE_UNI_DETECT));
2266                         SvREFCNT_dec_NN(dsv);
2267                     }
2268                     else if (SvOK(sv)) {
2269                         useless_sv = Perl_newSVpvf(aTHX_ "a constant (%" SVf ")", SVfARG(sv));
2270                     }
2271                     else
2272                         useless = "a constant (undef)";
2273                 }
2274             }
2275             op_null(o);         /* don't execute or even remember it */
2276             break;
2277
2278         case OP_POSTINC:
2279             OpTYPE_set(o, OP_PREINC);  /* pre-increment is faster */
2280             break;
2281
2282         case OP_POSTDEC:
2283             OpTYPE_set(o, OP_PREDEC);  /* pre-decrement is faster */
2284             break;
2285
2286         case OP_I_POSTINC:
2287             OpTYPE_set(o, OP_I_PREINC);        /* pre-increment is faster */
2288             break;
2289
2290         case OP_I_POSTDEC:
2291             OpTYPE_set(o, OP_I_PREDEC);        /* pre-decrement is faster */
2292             break;
2293
2294         case OP_SASSIGN: {
2295             OP *rv2gv;
2296             UNOP *refgen, *rv2cv;
2297             LISTOP *exlist;
2298
2299             if ((o->op_private & ~OPpASSIGN_BACKWARDS) != 2)
2300                 break;
2301
2302             rv2gv = ((BINOP *)o)->op_last;
2303             if (!rv2gv || rv2gv->op_type != OP_RV2GV)
2304                 break;
2305
2306             refgen = (UNOP *)((BINOP *)o)->op_first;
2307
2308             if (!refgen || (refgen->op_type != OP_REFGEN
2309                             && refgen->op_type != OP_SREFGEN))
2310                 break;
2311
2312             exlist = (LISTOP *)refgen->op_first;
2313             if (!exlist || exlist->op_type != OP_NULL
2314                 || exlist->op_targ != OP_LIST)
2315                 break;
2316
2317             if (exlist->op_first->op_type != OP_PUSHMARK
2318                 && exlist->op_first != exlist->op_last)
2319                 break;
2320
2321             rv2cv = (UNOP*)exlist->op_last;
2322
2323             if (rv2cv->op_type != OP_RV2CV)
2324                 break;
2325
2326             assert ((rv2gv->op_private & OPpDONT_INIT_GV) == 0);
2327             assert ((o->op_private & OPpASSIGN_CV_TO_GV) == 0);
2328             assert ((rv2cv->op_private & OPpMAY_RETURN_CONSTANT) == 0);
2329
2330             o->op_private |= OPpASSIGN_CV_TO_GV;
2331             rv2gv->op_private |= OPpDONT_INIT_GV;
2332             rv2cv->op_private |= OPpMAY_RETURN_CONSTANT;
2333
2334             break;
2335         }
2336
2337         case OP_AASSIGN: {
2338             inplace_aassign(o);
2339             break;
2340         }
2341
2342         case OP_OR:
2343         case OP_AND:
2344             kid = cLOGOPo->op_first;
2345             if (kid->op_type == OP_NOT
2346                 && (kid->op_flags & OPf_KIDS)) {
2347                 if (o->op_type == OP_AND) {
2348                     OpTYPE_set(o, OP_OR);
2349                 } else {
2350                     OpTYPE_set(o, OP_AND);
2351                 }
2352                 op_null(kid);
2353             }
2354             /* FALLTHROUGH */
2355
2356         case OP_DOR:
2357         case OP_COND_EXPR:
2358         case OP_ENTERGIVEN:
2359         case OP_ENTERWHEN:
2360             next_kid = OpSIBLING(cUNOPo->op_first);
2361         break;
2362
2363         case OP_NULL:
2364             if (o->op_flags & OPf_STACKED)
2365                 break;
2366             /* FALLTHROUGH */
2367         case OP_NEXTSTATE:
2368         case OP_DBSTATE:
2369         case OP_ENTERTRY:
2370         case OP_ENTER:
2371             if (!(o->op_flags & OPf_KIDS))
2372                 break;
2373             /* FALLTHROUGH */
2374         case OP_SCOPE:
2375         case OP_LEAVE:
2376         case OP_LEAVETRY:
2377         case OP_LEAVELOOP:
2378         case OP_LINESEQ:
2379         case OP_LEAVEGIVEN:
2380         case OP_LEAVEWHEN:
2381         kids:
2382             next_kid = cLISTOPo->op_first;
2383             break;
2384         case OP_LIST:
2385             /* If the first kid after pushmark is something that the padrange
2386                optimisation would reject, then null the list and the pushmark.
2387             */
2388             if ((kid = cLISTOPo->op_first)->op_type == OP_PUSHMARK
2389                 && (  !(kid = OpSIBLING(kid))
2390                       || (  kid->op_type != OP_PADSV
2391                             && kid->op_type != OP_PADAV
2392                             && kid->op_type != OP_PADHV)
2393                       || kid->op_private & ~OPpLVAL_INTRO
2394                       || !(kid = OpSIBLING(kid))
2395                       || (  kid->op_type != OP_PADSV
2396                             && kid->op_type != OP_PADAV
2397                             && kid->op_type != OP_PADHV)
2398                       || kid->op_private & ~OPpLVAL_INTRO)
2399             ) {
2400                 op_null(cUNOPo->op_first); /* NULL the pushmark */
2401                 op_null(o); /* NULL the list */
2402             }
2403             goto kids;
2404         case OP_ENTEREVAL:
2405             scalarkids(o);
2406             break;
2407         case OP_SCALAR:
2408             scalar(o);
2409             break;
2410         }
2411
2412         if (useless_sv) {
2413             /* mortalise it, in case warnings are fatal.  */
2414             Perl_ck_warner(aTHX_ packWARN(WARN_VOID),
2415                            "Useless use of %" SVf " in void context",
2416                            SVfARG(sv_2mortal(useless_sv)));
2417         }
2418         else if (useless) {
2419             Perl_ck_warner(aTHX_ packWARN(WARN_VOID),
2420                            "Useless use of %s in void context",
2421                            useless);
2422         }
2423
2424       get_next_op:
2425         /* if a kid hasn't been nominated to process, continue with the
2426          * next sibling, or if no siblings left, go back to the parent's
2427          * siblings and so on
2428          */
2429         while (!next_kid) {
2430             if (o == arg)
2431                 return arg; /* at top; no parents/siblings to try */
2432             if (OpHAS_SIBLING(o))
2433                 next_kid = o->op_sibparent;
2434             else
2435                 o = o->op_sibparent; /*try parent's next sibling */
2436         }
2437         o = next_kid;
2438     }
2439
2440     return arg;
2441 }
2442
2443
2444 static OP *
2445 S_listkids(pTHX_ OP *o)
2446 {
2447     if (o && o->op_flags & OPf_KIDS) {
2448         OP *kid;
2449         for (kid = cLISTOPo->op_first; kid; kid = OpSIBLING(kid))
2450             list(kid);
2451     }
2452     return o;
2453 }
2454
2455
2456 /* apply list context to the o subtree */
2457
2458 OP *
2459 Perl_list(pTHX_ OP *o)
2460 {
2461     OP * top_op = o;
2462
2463     while (1) {
2464         OP *next_kid = NULL; /* what op (if any) to process next */
2465
2466         OP *kid;
2467
2468         /* assumes no premature commitment */
2469         if (!o || (o->op_flags & OPf_WANT)
2470              || (PL_parser && PL_parser->error_count)
2471              || o->op_type == OP_RETURN)
2472         {
2473             goto do_next;
2474         }
2475
2476         if ((o->op_private & OPpTARGET_MY)
2477             && (PL_opargs[o->op_type] & OA_TARGLEX))/* OPp share the meaning */
2478         {
2479             goto do_next;                               /* As if inside SASSIGN */
2480         }
2481
2482         o->op_flags = (o->op_flags & ~OPf_WANT) | OPf_WANT_LIST;
2483
2484         switch (o->op_type) {
2485         case OP_REPEAT:
2486             if (o->op_private & OPpREPEAT_DOLIST
2487              && !(o->op_flags & OPf_STACKED))
2488             {
2489                 list(cBINOPo->op_first);
2490                 kid = cBINOPo->op_last;
2491                 /* optimise away (.....) x 1 */
2492                 if (kid->op_type == OP_CONST && SvIOK(kSVOP_sv)
2493                  && SvIVX(kSVOP_sv) == 1)
2494                 {
2495                     op_null(o); /* repeat */
2496                     op_null(cUNOPx(cBINOPo->op_first)->op_first);/* pushmark */
2497                     /* const (rhs): */
2498                     op_free(op_sibling_splice(o, cBINOPo->op_first, 1, NULL));
2499                 }
2500             }
2501             break;
2502
2503         case OP_OR:
2504         case OP_AND:
2505         case OP_COND_EXPR:
2506             /* impose list context on everything except the condition */
2507             next_kid = OpSIBLING(cUNOPo->op_first);
2508             break;
2509
2510         default:
2511             if (!(o->op_flags & OPf_KIDS))
2512                 break;
2513             /* possibly flatten 1..10 into a constant array */
2514             if (!o->op_next && cUNOPo->op_first->op_type == OP_FLOP) {
2515                 list(cBINOPo->op_first);
2516                 gen_constant_list(o);
2517                 goto do_next;
2518             }
2519             next_kid = cUNOPo->op_first; /* do all kids */
2520             break;
2521
2522         case OP_LIST:
2523             if (cLISTOPo->op_first->op_type == OP_PUSHMARK) {
2524                 op_null(cUNOPo->op_first); /* NULL the pushmark */
2525                 op_null(o); /* NULL the list */
2526             }
2527             if (o->op_flags & OPf_KIDS)
2528                 next_kid = cUNOPo->op_first; /* do all kids */
2529             break;
2530
2531         /* the children of these ops are usually a list of statements,
2532          * except the leaves, whose first child is a corresponding enter
2533          */
2534         case OP_SCOPE:
2535         case OP_LINESEQ:
2536             kid = cLISTOPo->op_first;
2537             goto do_kids;
2538         case OP_LEAVE:
2539         case OP_LEAVETRY:
2540             kid = cLISTOPo->op_first;
2541             list(kid);
2542             kid = OpSIBLING(kid);
2543         do_kids:
2544             while (kid) {
2545                 OP *sib = OpSIBLING(kid);
2546                 /* Apply void context to all kids except the last, which
2547                  * is list. E.g.
2548                  *      @a = do { void; void; list }
2549                  * Except that 'when's are always list context, e.g.
2550                  *      @a = do { given(..) {
2551                     *                 when (..) { list }
2552                     *                 when (..) { list }
2553                     *                 ...
2554                     *                }}
2555                     */
2556                 if (!sib) {
2557                     /* tail call optimise calling list() on the last kid */
2558                     next_kid = kid;
2559                     goto do_next;
2560                 }
2561                 else if (kid->op_type == OP_LEAVEWHEN)
2562                     list(kid);
2563                 else
2564                     scalarvoid(kid);
2565                 kid = sib;
2566             }
2567             NOT_REACHED; /* NOTREACHED */
2568             break;
2569
2570         }
2571
2572         /* If next_kid is set, someone in the code above wanted us to process
2573          * that kid and all its remaining siblings.  Otherwise, work our way
2574          * back up the tree */
2575       do_next:
2576         while (!next_kid) {
2577             if (o == top_op)
2578                 return top_op; /* at top; no parents/siblings to try */
2579             if (OpHAS_SIBLING(o))
2580                 next_kid = o->op_sibparent;
2581             else {
2582                 o = o->op_sibparent; /*try parent's next sibling */
2583                 switch (o->op_type) {
2584                 case OP_SCOPE:
2585                 case OP_LINESEQ:
2586                 case OP_LIST:
2587                 case OP_LEAVE:
2588                 case OP_LEAVETRY:
2589                     /* should really restore PL_curcop to its old value, but
2590                      * setting it to PL_compiling is better than do nothing */
2591                     PL_curcop = &PL_compiling;
2592                 }
2593             }
2594
2595
2596         }
2597         o = next_kid;
2598     } /* while */
2599 }
2600
2601
2602 static OP *
2603 S_scalarseq(pTHX_ OP *o)
2604 {
2605     if (o) {
2606         const OPCODE type = o->op_type;
2607
2608         if (type == OP_LINESEQ || type == OP_SCOPE ||
2609             type == OP_LEAVE || type == OP_LEAVETRY)
2610         {
2611             OP *kid, *sib;
2612             for (kid = cLISTOPo->op_first; kid; kid = sib) {
2613                 if ((sib = OpSIBLING(kid))
2614                  && (  OpHAS_SIBLING(sib) || sib->op_type != OP_NULL
2615                     || (  sib->op_targ != OP_NEXTSTATE
2616                        && sib->op_targ != OP_DBSTATE  )))
2617                 {
2618                     scalarvoid(kid);
2619                 }
2620             }
2621             PL_curcop = &PL_compiling;
2622         }
2623         o->op_flags &= ~OPf_PARENS;
2624         if (PL_hints & HINT_BLOCK_SCOPE)
2625             o->op_flags |= OPf_PARENS;
2626     }
2627     else
2628         o = newOP(OP_STUB, 0);
2629     return o;
2630 }
2631
2632 STATIC OP *
2633 S_modkids(pTHX_ OP *o, I32 type)
2634 {
2635     if (o && o->op_flags & OPf_KIDS) {
2636         OP *kid;
2637         for (kid = cLISTOPo->op_first; kid; kid = OpSIBLING(kid))
2638             op_lvalue(kid, type);
2639     }
2640     return o;
2641 }
2642
2643
2644 /* for a helem/hslice/kvslice, if its a fixed hash, croak on invalid
2645  * const fields. Also, convert CONST keys to HEK-in-SVs.
2646  * rop    is the op that retrieves the hash;
2647  * key_op is the first key
2648  * real   if false, only check (and possibly croak); don't update op
2649  */
2650
2651 STATIC void
2652 S_check_hash_fields_and_hekify(pTHX_ UNOP *rop, SVOP *key_op, int real)
2653 {
2654     PADNAME *lexname;
2655     GV **fields;
2656     bool check_fields;
2657
2658     /* find the padsv corresponding to $lex->{} or @{$lex}{} */
2659     if (rop) {
2660         if (rop->op_first->op_type == OP_PADSV)
2661             /* @$hash{qw(keys here)} */
2662             rop = (UNOP*)rop->op_first;
2663         else {
2664             /* @{$hash}{qw(keys here)} */
2665             if (rop->op_first->op_type == OP_SCOPE
2666                 && cLISTOPx(rop->op_first)->op_last->op_type == OP_PADSV)
2667                 {
2668                     rop = (UNOP*)cLISTOPx(rop->op_first)->op_last;
2669                 }
2670             else
2671                 rop = NULL;
2672         }
2673     }
2674
2675     lexname = NULL; /* just to silence compiler warnings */
2676     fields  = NULL; /* just to silence compiler warnings */
2677
2678     check_fields =
2679             rop
2680          && (lexname = padnamelist_fetch(PL_comppad_name, rop->op_targ),
2681              SvPAD_TYPED(lexname))
2682          && (fields = (GV**)hv_fetchs(PadnameTYPE(lexname), "FIELDS", FALSE))
2683          && isGV(*fields) && GvHV(*fields);
2684
2685     for (; key_op; key_op = (SVOP*)OpSIBLING(key_op)) {
2686         SV **svp, *sv;
2687         if (key_op->op_type != OP_CONST)
2688             continue;
2689         svp = cSVOPx_svp(key_op);
2690
2691         /* make sure it's not a bareword under strict subs */
2692         if (key_op->op_private & OPpCONST_BARE &&
2693             key_op->op_private & OPpCONST_STRICT)
2694         {
2695             no_bareword_allowed((OP*)key_op);
2696         }
2697
2698         /* Make the CONST have a shared SV */
2699         if (   !SvIsCOW_shared_hash(sv = *svp)
2700             && SvTYPE(sv) < SVt_PVMG
2701             && SvOK(sv)
2702             && !SvROK(sv)
2703             && real)
2704         {
2705             SSize_t keylen;
2706             const char * const key = SvPV_const(sv, *(STRLEN*)&keylen);
2707             SV *nsv = newSVpvn_share(key, SvUTF8(sv) ? -keylen : keylen, 0);
2708             SvREFCNT_dec_NN(sv);
2709             *svp = nsv;
2710         }
2711
2712         if (   check_fields
2713             && !hv_fetch_ent(GvHV(*fields), *svp, FALSE, 0))
2714         {
2715             Perl_croak(aTHX_ "No such class field \"%" SVf "\" "
2716                         "in variable %" PNf " of type %" HEKf,
2717                         SVfARG(*svp), PNfARG(lexname),
2718                         HEKfARG(HvNAME_HEK(PadnameTYPE(lexname))));
2719         }
2720     }
2721 }
2722
2723 /* info returned by S_sprintf_is_multiconcatable() */
2724
2725 struct sprintf_ismc_info {
2726     SSize_t nargs;    /* num of args to sprintf (not including the format) */
2727     char  *start;     /* start of raw format string */
2728     char  *end;       /* bytes after end of raw format string */
2729     STRLEN total_len; /* total length (in bytes) of format string, not
2730                          including '%s' and  half of '%%' */
2731     STRLEN variant;   /* number of bytes by which total_len_p would grow
2732                          if upgraded to utf8 */
2733     bool   utf8;      /* whether the format is utf8 */
2734 };
2735
2736
2737 /* is the OP_SPRINTF o suitable for converting into a multiconcat op?
2738  * i.e. its format argument is a const string with only '%s' and '%%'
2739  * formats, and the number of args is known, e.g.
2740  *    sprintf "a=%s f=%s", $a[0], scalar(f());
2741  * but not
2742  *    sprintf "i=%d a=%s f=%s", $i, @a, f();
2743  *
2744  * If successful, the sprintf_ismc_info struct pointed to by info will be
2745  * populated.
2746  */
2747
2748 STATIC bool
2749 S_sprintf_is_multiconcatable(pTHX_ OP *o,struct sprintf_ismc_info *info)
2750 {
2751     OP    *pm, *constop, *kid;
2752     SV    *sv;
2753     char  *s, *e, *p;
2754     SSize_t nargs, nformats;
2755     STRLEN cur, total_len, variant;
2756     bool   utf8;
2757
2758     /* if sprintf's behaviour changes, die here so that someone
2759      * can decide whether to enhance this function or skip optimising
2760      * under those new circumstances */
2761     assert(!(o->op_flags & OPf_STACKED));
2762     assert(!(PL_opargs[OP_SPRINTF] & OA_TARGLEX));
2763     assert(!(o->op_private & ~OPpARG4_MASK));
2764
2765     pm = cUNOPo->op_first;
2766     if (pm->op_type != OP_PUSHMARK) /* weird coreargs stuff */
2767         return FALSE;
2768     constop = OpSIBLING(pm);
2769     if (!constop || constop->op_type != OP_CONST)
2770         return FALSE;
2771     sv = cSVOPx_sv(constop);
2772     if (SvMAGICAL(sv) || !SvPOK(sv))
2773         return FALSE;
2774
2775     s = SvPV(sv, cur);
2776     e = s + cur;
2777
2778     /* Scan format for %% and %s and work out how many %s there are.
2779      * Abandon if other format types are found.
2780      */
2781
2782     nformats  = 0;
2783     total_len = 0;
2784     variant   = 0;
2785
2786     for (p = s; p < e; p++) {
2787         if (*p != '%') {
2788             total_len++;
2789             if (!UTF8_IS_INVARIANT(*p))
2790                 variant++;
2791             continue;
2792         }
2793         p++;
2794         if (p >= e)
2795             return FALSE; /* lone % at end gives "Invalid conversion" */
2796         if (*p == '%')
2797             total_len++;
2798         else if (*p == 's')
2799             nformats++;
2800         else
2801             return FALSE;
2802     }
2803
2804     if (!nformats || nformats > PERL_MULTICONCAT_MAXARG)
2805         return FALSE;
2806
2807     utf8 = cBOOL(SvUTF8(sv));
2808     if (utf8)
2809         variant = 0;
2810
2811     /* scan args; they must all be in scalar cxt */
2812
2813     nargs = 0;
2814     kid = OpSIBLING(constop);
2815
2816     while (kid) {
2817         if ((kid->op_flags & OPf_WANT) != OPf_WANT_SCALAR)
2818             return FALSE;
2819         nargs++;
2820         kid = OpSIBLING(kid);
2821     }
2822
2823     if (nargs != nformats)
2824         return FALSE; /* e.g. sprintf("%s%s", $a); */
2825
2826
2827     info->nargs      = nargs;
2828     info->start      = s;
2829     info->end        = e;
2830     info->total_len  = total_len;
2831     info->variant    = variant;
2832     info->utf8       = utf8;
2833
2834     return TRUE;
2835 }
2836
2837
2838
2839 /* S_maybe_multiconcat():
2840  *
2841  * given an OP_STRINGIFY, OP_SASSIGN, OP_CONCAT or OP_SPRINTF op, possibly
2842  * convert it (and its children) into an OP_MULTICONCAT. See the code
2843  * comments just before pp_multiconcat() for the full details of what
2844  * OP_MULTICONCAT supports.
2845  *
2846  * Basically we're looking for an optree with a chain of OP_CONCATS down
2847  * the LHS (or an OP_SPRINTF), with possibly an OP_SASSIGN, and/or
2848  * OP_STRINGIFY, and/or OP_CONCAT acting as '.=' at its head, e.g.
2849  *
2850  *      $x = "$a$b-$c"
2851  *
2852  *  looks like
2853  *
2854  *      SASSIGN
2855  *         |
2856  *      STRINGIFY   -- PADSV[$x]
2857  *         |
2858  *         |
2859  *      ex-PUSHMARK -- CONCAT/S
2860  *                        |
2861  *                     CONCAT/S  -- PADSV[$d]
2862  *                        |
2863  *                     CONCAT    -- CONST["-"]
2864  *                        |
2865  *                     PADSV[$a] -- PADSV[$b]
2866  *
2867  * Note that at this stage the OP_SASSIGN may have already been optimised
2868  * away with OPpTARGET_MY set on the OP_STRINGIFY or OP_CONCAT.
2869  */
2870
2871 STATIC void
2872 S_maybe_multiconcat(pTHX_ OP *o)
2873 {
2874     OP *lastkidop;   /* the right-most of any kids unshifted onto o */
2875     OP *topop;       /* the top-most op in the concat tree (often equals o,
2876                         unless there are assign/stringify ops above it */
2877     OP *parentop;    /* the parent op of topop (or itself if no parent) */
2878     OP *targmyop;    /* the op (if any) with the OPpTARGET_MY flag */
2879     OP *targetop;    /* the op corresponding to target=... or target.=... */
2880     OP *stringop;    /* the OP_STRINGIFY op, if any */
2881     OP *nextop;      /* used for recreating the op_next chain without consts */
2882     OP *kid;         /* general-purpose op pointer */
2883     UNOP_AUX_item *aux;
2884     UNOP_AUX_item *lenp;
2885     char *const_str, *p;
2886     struct sprintf_ismc_info sprintf_info;
2887
2888                      /* store info about each arg in args[];
2889                       * toparg is the highest used slot; argp is a general
2890                       * pointer to args[] slots */
2891     struct {
2892         void *p;      /* initially points to const sv (or null for op);
2893                          later, set to SvPV(constsv), with ... */
2894         STRLEN len;   /* ... len set to SvPV(..., len) */
2895     } *argp, *toparg, args[PERL_MULTICONCAT_MAXARG*2 + 1];
2896
2897     SSize_t nargs  = 0;
2898     SSize_t nconst = 0;
2899     SSize_t nadjconst  = 0; /* adjacent consts - may be demoted to args */
2900     STRLEN variant;
2901     bool utf8 = FALSE;
2902     bool kid_is_last = FALSE; /* most args will be the RHS kid of a concat op;
2903                                  the last-processed arg will the LHS of one,
2904                                  as args are processed in reverse order */
2905     U8   stacked_last = 0;   /* whether the last seen concat op was STACKED */
2906     STRLEN total_len  = 0;   /* sum of the lengths of the const segments */
2907     U8 flags          = 0;   /* what will become the op_flags and ... */
2908     U8 private_flags  = 0;   /* ... op_private of the multiconcat op */
2909     bool is_sprintf = FALSE; /* we're optimising an sprintf */
2910     bool is_targable  = FALSE; /* targetop is an OPpTARGET_MY candidate */
2911     bool prev_was_const = FALSE; /* previous arg was a const */
2912
2913     /* -----------------------------------------------------------------
2914      * Phase 1:
2915      *
2916      * Examine the optree non-destructively to determine whether it's
2917      * suitable to be converted into an OP_MULTICONCAT. Accumulate
2918      * information about the optree in args[].
2919      */
2920
2921     argp     = args;
2922     targmyop = NULL;
2923     targetop = NULL;
2924     stringop = NULL;
2925     topop    = o;
2926     parentop = o;
2927
2928     assert(   o->op_type == OP_SASSIGN
2929            || o->op_type == OP_CONCAT
2930            || o->op_type == OP_SPRINTF
2931            || o->op_type == OP_STRINGIFY);
2932
2933     Zero(&sprintf_info, 1, struct sprintf_ismc_info);
2934
2935     /* first see if, at the top of the tree, there is an assign,
2936      * append and/or stringify */
2937
2938     if (topop->op_type == OP_SASSIGN) {
2939         /* expr = ..... */
2940         if (o->op_ppaddr != PL_ppaddr[OP_SASSIGN])
2941             return;
2942         if (o->op_private & (OPpASSIGN_BACKWARDS|OPpASSIGN_CV_TO_GV))
2943             return;
2944         assert(!(o->op_private & ~OPpARG2_MASK)); /* barf on unknown flags */
2945
2946         parentop = topop;
2947         topop = cBINOPo->op_first;
2948         targetop = OpSIBLING(topop);
2949         if (!targetop) /* probably some sort of syntax error */
2950             return;
2951
2952         /* don't optimise away assign in 'local $foo = ....' */
2953         if (   (targetop->op_private & OPpLVAL_INTRO)
2954             /* these are the common ops which do 'local', but
2955              * not all */
2956             && (   targetop->op_type == OP_GVSV
2957                 || targetop->op_type == OP_RV2SV
2958                 || targetop->op_type == OP_AELEM
2959                 || targetop->op_type == OP_HELEM
2960                 )
2961         )
2962             return;
2963     }
2964     else if (   topop->op_type == OP_CONCAT
2965              && (topop->op_flags & OPf_STACKED)
2966              && (!(topop->op_private & OPpCONCAT_NESTED))
2967             )
2968     {
2969         /* expr .= ..... */
2970
2971         /* OPpTARGET_MY shouldn't be able to be set here. If it is,
2972          * decide what to do about it */
2973         assert(!(o->op_private & OPpTARGET_MY));
2974
2975         /* barf on unknown flags */
2976         assert(!(o->op_private & ~(OPpARG2_MASK|OPpTARGET_MY)));
2977         private_flags |= OPpMULTICONCAT_APPEND;
2978         targetop = cBINOPo->op_first;
2979         parentop = topop;
2980         topop    = OpSIBLING(targetop);
2981
2982         /* $x .= <FOO> gets optimised to rcatline instead */
2983         if (topop->op_type == OP_READLINE)
2984             return;
2985     }
2986
2987     if (targetop) {
2988         /* Can targetop (the LHS) if it's a padsv, be optimised
2989          * away and use OPpTARGET_MY instead?
2990          */
2991         if (    (targetop->op_type == OP_PADSV)
2992             && !(targetop->op_private & OPpDEREF)
2993             && !(targetop->op_private & OPpPAD_STATE)
2994                /* we don't support 'my $x .= ...' */
2995             && (   o->op_type == OP_SASSIGN
2996                 || !(targetop->op_private & OPpLVAL_INTRO))
2997         )
2998             is_targable = TRUE;
2999     }
3000
3001     if (topop->op_type == OP_STRINGIFY) {
3002         if (topop->op_ppaddr != PL_ppaddr[OP_STRINGIFY])
3003             return;
3004         stringop = topop;
3005
3006         /* barf on unknown flags */
3007         assert(!(o->op_private & ~(OPpARG4_MASK|OPpTARGET_MY)));
3008
3009         if ((topop->op_private & OPpTARGET_MY)) {
3010             if (o->op_type == OP_SASSIGN)
3011                 return; /* can't have two assigns */
3012             targmyop = topop;
3013         }
3014
3015         private_flags |= OPpMULTICONCAT_STRINGIFY;
3016         parentop = topop;
3017         topop = cBINOPx(topop)->op_first;
3018         assert(OP_TYPE_IS_OR_WAS_NN(topop, OP_PUSHMARK));
3019         topop = OpSIBLING(topop);
3020     }
3021
3022     if (topop->op_type == OP_SPRINTF) {
3023         if (topop->op_ppaddr != PL_ppaddr[OP_SPRINTF])
3024             return;
3025         if (S_sprintf_is_multiconcatable(aTHX_ topop, &sprintf_info)) {
3026             nargs     = sprintf_info.nargs;
3027             total_len = sprintf_info.total_len;
3028             variant   = sprintf_info.variant;
3029             utf8      = sprintf_info.utf8;
3030             is_sprintf = TRUE;
3031             private_flags |= OPpMULTICONCAT_FAKE;
3032             toparg = argp;
3033             /* we have an sprintf op rather than a concat optree.
3034              * Skip most of the code below which is associated with
3035              * processing that optree. We also skip phase 2, determining
3036              * whether its cost effective to optimise, since for sprintf,
3037              * multiconcat is *always* faster */
3038             goto create_aux;
3039         }
3040         /* note that even if the sprintf itself isn't multiconcatable,
3041          * the expression as a whole may be, e.g. in
3042          *    $x .= sprintf("%d",...)
3043          * the sprintf op will be left as-is, but the concat/S op may
3044          * be upgraded to multiconcat
3045          */
3046     }
3047     else if (topop->op_type == OP_CONCAT) {
3048         if (topop->op_ppaddr != PL_ppaddr[OP_CONCAT])
3049             return;
3050
3051         if ((topop->op_private & OPpTARGET_MY)) {
3052             if (o->op_type == OP_SASSIGN || targmyop)
3053                 return; /* can't have two assigns */
3054             targmyop = topop;
3055         }
3056     }
3057
3058     /* Is it safe to convert a sassign/stringify/concat op into
3059      * a multiconcat? */
3060     assert((PL_opargs[OP_SASSIGN]   & OA_CLASS_MASK) == OA_BINOP);
3061     assert((PL_opargs[OP_CONCAT]    & OA_CLASS_MASK) == OA_BINOP);
3062     assert((PL_opargs[OP_STRINGIFY] & OA_CLASS_MASK) == OA_LISTOP);
3063     assert((PL_opargs[OP_SPRINTF]   & OA_CLASS_MASK) == OA_LISTOP);
3064     STATIC_ASSERT_STMT(   STRUCT_OFFSET(BINOP,    op_last)
3065                        == STRUCT_OFFSET(UNOP_AUX, op_aux));
3066     STATIC_ASSERT_STMT(   STRUCT_OFFSET(LISTOP,   op_last)
3067                        == STRUCT_OFFSET(UNOP_AUX, op_aux));
3068
3069     /* Now scan the down the tree looking for a series of
3070      * CONCAT/OPf_STACKED ops on the LHS (with the last one not
3071      * stacked). For example this tree:
3072      *
3073      *     |
3074      *   CONCAT/STACKED
3075      *     |
3076      *   CONCAT/STACKED -- EXPR5
3077      *     |
3078      *   CONCAT/STACKED -- EXPR4
3079      *     |
3080      *   CONCAT -- EXPR3
3081      *     |
3082      *   EXPR1  -- EXPR2
3083      *
3084      * corresponds to an expression like
3085      *
3086      *   (EXPR1 . EXPR2 . EXPR3 . EXPR4 . EXPR5)
3087      *
3088      * Record info about each EXPR in args[]: in particular, whether it is
3089      * a stringifiable OP_CONST and if so what the const sv is.
3090      *
3091      * The reason why the last concat can't be STACKED is the difference
3092      * between
3093      *
3094      *    ((($a .= $a) .= $a) .= $a) .= $a
3095      *
3096      * and
3097      *    $a . $a . $a . $a . $a
3098      *
3099      * The main difference between the optrees for those two constructs
3100      * is the presence of the last STACKED. As well as modifying $a,
3101      * the former sees the changed $a between each concat, so if $s is
3102      * initially 'a', the first returns 'a' x 16, while the latter returns
3103      * 'a' x 5. And pp_multiconcat can't handle that kind of thing.
3104      */
3105
3106     kid = topop;
3107
3108     for (;;) {
3109         OP *argop;
3110         SV *sv;
3111         bool last = FALSE;
3112
3113         if (    kid->op_type == OP_CONCAT
3114             && !kid_is_last
3115         ) {
3116             OP *k1, *k2;
3117             k1 = cUNOPx(kid)->op_first;
3118             k2 = OpSIBLING(k1);
3119             /* shouldn't happen except maybe after compile err? */
3120             if (!k2)
3121                 return;
3122
3123             /* avoid turning (A . B . ($lex = C) ...)  into  (A . B . C ...) */
3124             if (kid->op_private & OPpTARGET_MY)
3125                 kid_is_last = TRUE;
3126
3127             stacked_last = (kid->op_flags & OPf_STACKED);
3128             if (!stacked_last)
3129                 kid_is_last = TRUE;
3130
3131             kid   = k1;
3132             argop = k2;
3133         }
3134         else {
3135             argop = kid;
3136             last = TRUE;
3137         }
3138
3139         if (   nargs + nadjconst  >  PERL_MULTICONCAT_MAXARG        - 2
3140             || (argp - args + 1)  > (PERL_MULTICONCAT_MAXARG*2 + 1) - 2)
3141         {
3142             /* At least two spare slots are needed to decompose both
3143              * concat args. If there are no slots left, continue to
3144              * examine the rest of the optree, but don't push new values
3145              * on args[]. If the optree as a whole is legal for conversion
3146              * (in particular that the last concat isn't STACKED), then
3147              * the first PERL_MULTICONCAT_MAXARG elements of the optree
3148              * can be converted into an OP_MULTICONCAT now, with the first
3149              * child of that op being the remainder of the optree -
3150              * which may itself later be converted to a multiconcat op
3151              * too.
3152              */
3153             if (last) {
3154                 /* the last arg is the rest of the optree */
3155                 argp++->p = NULL;
3156                 nargs++;
3157             }
3158         }
3159         else if (   argop->op_type == OP_CONST
3160             && ((sv = cSVOPx_sv(argop)))
3161             /* defer stringification until runtime of 'constant'
3162              * things that might stringify variantly, e.g. the radix
3163              * point of NVs, or overloaded RVs */
3164             && (SvPOK(sv) || SvIOK(sv))
3165             && (!SvGMAGICAL(sv))
3166         ) {
3167             if (argop->op_private & OPpCONST_STRICT)
3168                 no_bareword_allowed(argop);
3169             argp++->p = sv;
3170             utf8   |= cBOOL(SvUTF8(sv));
3171             nconst++;
3172             if (prev_was_const)
3173                 /* this const may be demoted back to a plain arg later;
3174                  * make sure we have enough arg slots left */
3175                 nadjconst++;
3176             prev_was_const = !prev_was_const;
3177         }
3178         else {
3179             argp++->p = NULL;
3180             nargs++;
3181             prev_was_const = FALSE;
3182         }
3183
3184         if (last)
3185             break;
3186     }
3187
3188     toparg = argp - 1;
3189
3190     if (stacked_last)
3191         return; /* we don't support ((A.=B).=C)...) */
3192
3193     /* look for two adjacent consts and don't fold them together:
3194      *     $o . "a" . "b"
3195      * should do
3196      *     $o->concat("a")->concat("b")
3197      * rather than
3198      *     $o->concat("ab")
3199      * (but $o .=  "a" . "b" should still fold)
3200      */
3201     {
3202         bool seen_nonconst = FALSE;
3203         for (argp = toparg; argp >= args; argp--) {
3204             if (argp->p == NULL) {
3205                 seen_nonconst = TRUE;
3206                 continue;
3207             }
3208             if (!seen_nonconst)
3209                 continue;
3210             if (argp[1].p) {
3211                 /* both previous and current arg were constants;
3212                  * leave the current OP_CONST as-is */
3213                 argp->p = NULL;
3214                 nconst--;
3215                 nargs++;
3216             }
3217         }
3218     }
3219
3220     /* -----------------------------------------------------------------
3221      * Phase 2:
3222      *
3223      * At this point we have determined that the optree *can* be converted
3224      * into a multiconcat. Having gathered all the evidence, we now decide
3225      * whether it *should*.
3226      */
3227
3228
3229     /* we need at least one concat action, e.g.:
3230      *
3231      *  Y . Z
3232      *  X = Y . Z
3233      *  X .= Y
3234      *
3235      * otherwise we could be doing something like $x = "foo", which
3236      * if treated as a concat, would fail to COW.
3237      */
3238     if (nargs + nconst + cBOOL(private_flags & OPpMULTICONCAT_APPEND) < 2)
3239         return;
3240
3241     /* Benchmarking seems to indicate that we gain if:
3242      * * we optimise at least two actions into a single multiconcat
3243      *    (e.g concat+concat, sassign+concat);
3244      * * or if we can eliminate at least 1 OP_CONST;
3245      * * or if we can eliminate a padsv via OPpTARGET_MY
3246      */
3247
3248     if (
3249            /* eliminated at least one OP_CONST */
3250            nconst >= 1
3251            /* eliminated an OP_SASSIGN */
3252         || o->op_type == OP_SASSIGN
3253            /* eliminated an OP_PADSV */
3254         || (!targmyop && is_targable)
3255     )
3256         /* definitely a net gain to optimise */
3257         goto optimise;
3258
3259     /* ... if not, what else? */
3260
3261     /* special-case '$lex1 = expr . $lex1' (where expr isn't lex1):
3262      * multiconcat is faster (due to not creating a temporary copy of
3263      * $lex1), whereas for a general $lex1 = $lex2 . $lex3, concat is
3264      * faster.
3265      */
3266     if (   nconst == 0
3267          && nargs == 2
3268          && targmyop
3269          && topop->op_type == OP_CONCAT
3270     ) {
3271         PADOFFSET t = targmyop->op_targ;
3272         OP *k1 = cBINOPx(topop)->op_first;
3273         OP *k2 = cBINOPx(topop)->op_last;
3274         if (   k2->op_type == OP_PADSV
3275             && k2->op_targ == t
3276             && (   k1->op_type != OP_PADSV
3277                 || k1->op_targ != t)
3278         )
3279             goto optimise;
3280     }
3281
3282     /* need at least two concats */
3283     if (nargs + nconst + cBOOL(private_flags & OPpMULTICONCAT_APPEND) < 3)
3284         return;
3285
3286
3287
3288     /* -----------------------------------------------------------------
3289      * Phase 3:
3290      *
3291      * At this point the optree has been verified as ok to be optimised
3292      * into an OP_MULTICONCAT. Now start changing things.
3293      */
3294
3295    optimise:
3296
3297     /* stringify all const args and determine utf8ness */
3298
3299     variant = 0;
3300     for (argp = args; argp <= toparg; argp++) {
3301         SV *sv = (SV*)argp->p;
3302         if (!sv)
3303             continue; /* not a const op */
3304         if (utf8 && !SvUTF8(sv))
3305             sv_utf8_upgrade_nomg(sv);
3306         argp->p = SvPV_nomg(sv, argp->len);
3307         total_len += argp->len;
3308
3309         /* see if any strings would grow if converted to utf8 */
3310         if (!utf8) {
3311             variant += variant_under_utf8_count((U8 *) argp->p,
3312                                                 (U8 *) argp->p + argp->len);
3313         }
3314     }
3315
3316     /* create and populate aux struct */
3317
3318   create_aux:
3319
3320     aux = (UNOP_AUX_item*)PerlMemShared_malloc(
3321                     sizeof(UNOP_AUX_item)
3322                     *  (
3323                            PERL_MULTICONCAT_HEADER_SIZE
3324                          + ((nargs + 1) * (variant ? 2 : 1))
3325                         )
3326                     );
3327     const_str = (char *)PerlMemShared_malloc(total_len ? total_len : 1);
3328
3329     /* Extract all the non-const expressions from the concat tree then
3330      * dispose of the old tree, e.g. convert the tree from this:
3331      *
3332      *  o => SASSIGN
3333      *         |
3334      *       STRINGIFY   -- TARGET
3335      *         |
3336      *       ex-PUSHMARK -- CONCAT
3337      *                        |
3338      *                      CONCAT -- EXPR5
3339      *                        |
3340      *                      CONCAT -- EXPR4
3341      *                        |
3342      *                      CONCAT -- EXPR3
3343      *                        |
3344      *                      EXPR1  -- EXPR2
3345      *
3346      *
3347      * to:
3348      *
3349      *  o => MULTICONCAT
3350      *         |
3351      *       ex-PUSHMARK -- EXPR1 -- EXPR2 -- EXPR3 -- EXPR4 -- EXPR5 -- TARGET
3352      *
3353      * except that if EXPRi is an OP_CONST, it's discarded.
3354      *
3355      * During the conversion process, EXPR ops are stripped from the tree
3356      * and unshifted onto o. Finally, any of o's remaining original
3357      * childen are discarded and o is converted into an OP_MULTICONCAT.
3358      *
3359      * In this middle of this, o may contain both: unshifted args on the
3360      * left, and some remaining original args on the right. lastkidop
3361      * is set to point to the right-most unshifted arg to delineate
3362      * between the two sets.
3363      */
3364
3365
3366     if (is_sprintf) {
3367         /* create a copy of the format with the %'s removed, and record
3368          * the sizes of the const string segments in the aux struct */
3369         char *q, *oldq;
3370         lenp = aux + PERL_MULTICONCAT_IX_LENGTHS;
3371
3372         p    = sprintf_info.start;
3373         q    = const_str;
3374         oldq = q;
3375         for (; p < sprintf_info.end; p++) {
3376             if (*p == '%') {
3377                 p++;
3378                 if (*p != '%') {
3379                     (lenp++)->ssize = q - oldq;
3380                     oldq = q;
3381                     continue;
3382                 }
3383             }
3384             *q++ = *p;
3385         }
3386         lenp->ssize = q - oldq;
3387         assert((STRLEN)(q - const_str) == total_len);
3388
3389         /* Attach all the args (i.e. the kids of the sprintf) to o (which
3390          * may or may not be topop) The pushmark and const ops need to be
3391          * kept in case they're an op_next entry point.
3392          */
3393         lastkidop = cLISTOPx(topop)->op_last;
3394         kid = cUNOPx(topop)->op_first; /* pushmark */
3395         op_null(kid);
3396         op_null(OpSIBLING(kid));       /* const */
3397         if (o != topop) {
3398             kid = op_sibling_splice(topop, NULL, -1, NULL); /* cut all args */
3399             op_sibling_splice(o, NULL, 0, kid); /* and attach to o */
3400             lastkidop->op_next = o;
3401         }
3402     }
3403     else {
3404         p = const_str;
3405         lenp = aux + PERL_MULTICONCAT_IX_LENGTHS;
3406
3407         lenp->ssize = -1;
3408
3409         /* Concatenate all const strings into const_str.
3410          * Note that args[] contains the RHS args in reverse order, so
3411          * we scan args[] from top to bottom to get constant strings
3412          * in L-R order
3413          */
3414         for (argp = toparg; argp >= args; argp--) {
3415             if (!argp->p)
3416                 /* not a const op */
3417                 (++lenp)->ssize = -1;
3418             else {
3419                 STRLEN l = argp->len;
3420                 Copy(argp->p, p, l, char);
3421                 p += l;
3422                 if (lenp->ssize == -1)
3423                     lenp->ssize = l;
3424                 else
3425                     lenp->ssize += l;
3426             }
3427         }
3428
3429         kid = topop;
3430         nextop = o;
3431         lastkidop = NULL;
3432
3433         for (argp = args; argp <= toparg; argp++) {
3434             /* only keep non-const args, except keep the first-in-next-chain
3435              * arg no matter what it is (but nulled if OP_CONST), because it
3436              * may be the entry point to this subtree from the previous
3437              * op_next.
3438              */
3439             bool last = (argp == toparg);
3440             OP *prev;
3441
3442             /* set prev to the sibling *before* the arg to be cut out,
3443              * e.g. when cutting EXPR:
3444              *
3445              *         |
3446              * kid=  CONCAT
3447              *         |
3448              * prev= CONCAT -- EXPR
3449              *         |
3450              */
3451             if (argp == args && kid->op_type != OP_CONCAT) {
3452                 /* in e.g. '$x .= f(1)' there's no RHS concat tree
3453                  * so the expression to be cut isn't kid->op_last but
3454                  * kid itself */
3455                 OP *o1, *o2;
3456                 /* find the op before kid */
3457                 o1 = NULL;
3458                 o2 = cUNOPx(parentop)->op_first;
3459                 while (o2 && o2 != kid) {
3460                     o1 = o2;
3461                     o2 = OpSIBLING(o2);
3462                 }
3463                 assert(o2 == kid);
3464                 prev = o1;
3465                 kid  = parentop;
3466             }
3467             else if (kid == o && lastkidop)
3468                 prev = last ? lastkidop : OpSIBLING(lastkidop);
3469             else
3470                 prev = last ? NULL : cUNOPx(kid)->op_first;
3471
3472             if (!argp->p || last) {
3473                 /* cut RH op */
3474                 OP *aop = op_sibling_splice(kid, prev, 1, NULL);
3475                 /* and unshift to front of o */
3476                 op_sibling_splice(o, NULL, 0, aop);
3477                 /* record the right-most op added to o: later we will
3478                  * free anything to the right of it */
3479                 if (!lastkidop)
3480                     lastkidop = aop;
3481                 aop->op_next = nextop;
3482                 if (last) {
3483                     if (argp->p)
3484                         /* null the const at start of op_next chain */
3485                         op_null(aop);
3486                 }
3487                 else if (prev)
3488                     nextop = prev->op_next;
3489             }
3490
3491             /* the last two arguments are both attached to the same concat op */
3492             if (argp < toparg - 1)
3493                 kid = prev;
3494         }
3495     }
3496
3497     /* Populate the aux struct */
3498
3499     aux[PERL_MULTICONCAT_IX_NARGS].ssize     = nargs;
3500     aux[PERL_MULTICONCAT_IX_PLAIN_PV].pv    = utf8 ? NULL : const_str;
3501     aux[PERL_MULTICONCAT_IX_PLAIN_LEN].ssize = utf8 ?    0 : total_len;
3502     aux[PERL_MULTICONCAT_IX_UTF8_PV].pv     = const_str;
3503     aux[PERL_MULTICONCAT_IX_UTF8_LEN].ssize  = total_len;
3504
3505     /* if variant > 0, calculate a variant const string and lengths where
3506      * the utf8 version of the string will take 'variant' more bytes than
3507      * the plain one. */
3508
3509     if (variant) {
3510         char              *p = const_str;
3511         STRLEN          ulen = total_len + variant;
3512         UNOP_AUX_item  *lens = aux + PERL_MULTICONCAT_IX_LENGTHS;
3513         UNOP_AUX_item *ulens = lens + (nargs + 1);
3514         char             *up = (char*)PerlMemShared_malloc(ulen);
3515         SSize_t            n;
3516
3517         aux[PERL_MULTICONCAT_IX_UTF8_PV].pv    = up;
3518         aux[PERL_MULTICONCAT_IX_UTF8_LEN].ssize = ulen;
3519
3520         for (n = 0; n < (nargs + 1); n++) {
3521             SSize_t i;
3522             char * orig_up = up;
3523             for (i = (lens++)->ssize; i > 0; i--) {
3524                 U8 c = *p++;
3525                 append_utf8_from_native_byte(c, (U8**)&up);
3526             }
3527             (ulens++)->ssize = (i < 0) ? i : up - orig_up;
3528         }
3529     }
3530
3531     if (stringop) {
3532         /* if there was a top(ish)-level OP_STRINGIFY, we need to keep
3533          * that op's first child - an ex-PUSHMARK - because the op_next of
3534          * the previous op may point to it (i.e. it's the entry point for
3535          * the o optree)
3536          */
3537         OP *pmop =
3538             (stringop == o)
3539                 ? op_sibling_splice(o, lastkidop, 1, NULL)
3540                 : op_sibling_splice(stringop, NULL, 1, NULL);
3541         assert(OP_TYPE_IS_OR_WAS_NN(pmop, OP_PUSHMARK));
3542         op_sibling_splice(o, NULL, 0, pmop);
3543         if (!lastkidop)
3544             lastkidop = pmop;
3545     }
3546
3547     /* Optimise
3548      *    target  = A.B.C...
3549      *    target .= A.B.C...
3550      */
3551
3552     if (targetop) {
3553         assert(!targmyop);
3554
3555         if (o->op_type == OP_SASSIGN) {
3556             /* Move the target subtree from being the last of o's children
3557              * to being the last of o's preserved children.
3558              * Note the difference between 'target = ...' and 'target .= ...':
3559              * for the former, target is executed last; for the latter,
3560              * first.
3561              */
3562             kid = OpSIBLING(lastkidop);
3563             op_sibling_splice(o, kid, 1, NULL); /* cut target op */
3564             op_sibling_splice(o, lastkidop, 0, targetop); /* and paste */
3565             lastkidop->op_next = kid->op_next;
3566             lastkidop = targetop;
3567         }
3568         else {
3569             /* Move the target subtree from being the first of o's
3570              * original children to being the first of *all* o's children.
3571              */
3572             if (lastkidop) {
3573                 op_sibling_splice(o, lastkidop, 1, NULL); /* cut target op */
3574                 op_sibling_splice(o, NULL, 0, targetop);  /* and paste*/
3575             }
3576             else {
3577                 /* if the RHS of .= doesn't contain a concat (e.g.
3578                  * $x .= "foo"), it gets missed by the "strip ops from the
3579                  * tree and add to o" loop earlier */
3580                 assert(topop->op_type != OP_CONCAT);
3581                 if (stringop) {
3582                     /* in e.g. $x .= "$y", move the $y expression
3583                      * from being a child of OP_STRINGIFY to being the
3584                      * second child of the OP_CONCAT
3585                      */
3586                     assert(cUNOPx(stringop)->op_first == topop);
3587                     op_sibling_splice(stringop, NULL, 1, NULL);
3588                     op_sibling_splice(o, cUNOPo->op_first, 0, topop);
3589                 }
3590                 assert(topop == OpSIBLING(cBINOPo->op_first));
3591                 if (toparg->p)
3592                     op_null(topop);
3593                 lastkidop = topop;
3594             }
3595         }
3596
3597         if (is_targable) {
3598             /* optimise
3599              *  my $lex  = A.B.C...
3600              *     $lex  = A.B.C...
3601              *     $lex .= A.B.C...
3602              * The original padsv op is kept but nulled in case it's the
3603              * entry point for the optree (which it will be for
3604              * '$lex .=  ... '
3605              */
3606             private_flags |= OPpTARGET_MY;
3607             private_flags |= (targetop->op_private & OPpLVAL_INTRO);
3608             o->op_targ = targetop->op_targ;
3609             targetop->op_targ = 0;
3610             op_null(targetop);
3611         }
3612         else
3613             flags |= OPf_STACKED;
3614     }
3615     else if (targmyop) {
3616         private_flags |= OPpTARGET_MY;
3617         if (o != targmyop) {
3618             o->op_targ = targmyop->op_targ;
3619             targmyop->op_targ = 0;
3620         }
3621     }
3622
3623     /* detach the emaciated husk of the sprintf/concat optree and free it */
3624     for (;;) {
3625         kid = op_sibling_splice(o, lastkidop, 1, NULL);
3626         if (!kid)
3627             break;
3628         op_free(kid);
3629     }
3630
3631     /* and convert o into a multiconcat */
3632
3633     o->op_flags        = (flags|OPf_KIDS|stacked_last
3634                          |(o->op_flags & (OPf_WANT|OPf_PARENS)));
3635     o->op_private      = private_flags;
3636     o->op_type         = OP_MULTICONCAT;
3637     o->op_ppaddr       = PL_ppaddr[OP_MULTICONCAT];
3638     cUNOP_AUXo->op_aux = aux;
3639 }
3640
3641
3642 /* do all the final processing on an optree (e.g. running the peephole
3643  * optimiser on it), then attach it to cv (if cv is non-null)
3644  */
3645
3646 static void
3647 S_process_optree(pTHX_ CV *cv, OP *optree, OP* start)
3648 {
3649     OP **startp;
3650
3651     /* XXX for some reason, evals, require and main optrees are
3652      * never attached to their CV; instead they just hang off
3653      * PL_main_root + PL_main_start or PL_eval_root + PL_eval_start
3654      * and get manually freed when appropriate */
3655     if (cv)
3656         startp = &CvSTART(cv);
3657     else
3658         startp = PL_in_eval? &PL_eval_start : &PL_main_start;
3659
3660     *startp = start;
3661     optree->op_private |= OPpREFCOUNTED;
3662     OpREFCNT_set(optree, 1);
3663     optimize_optree(optree);
3664     CALL_PEEP(*startp);
3665     finalize_optree(optree);
3666     S_prune_chain_head(startp);
3667
3668     if (cv) {
3669         /* now that optimizer has done its work, adjust pad values */
3670         pad_tidy(optree->op_type == OP_LEAVEWRITE ? padtidy_FORMAT
3671                  : CvCLONE(cv) ? padtidy_SUBCLONE : padtidy_SUB);
3672     }
3673 }
3674
3675
3676 /*
3677 =for apidoc optimize_optree
3678
3679 This function applies some optimisations to the optree in top-down order.
3680 It is called before the peephole optimizer, which processes ops in
3681 execution order. Note that finalize_optree() also does a top-down scan,
3682 but is called *after* the peephole optimizer.
3683
3684 =cut
3685 */
3686
3687 void
3688 Perl_optimize_optree(pTHX_ OP* o)
3689 {
3690     PERL_ARGS_ASSERT_OPTIMIZE_OPTREE;
3691
3692     ENTER;
3693     SAVEVPTR(PL_curcop);
3694
3695     optimize_op(o);
3696
3697     LEAVE;
3698 }
3699
3700
3701 /* helper for optimize_optree() which optimises one op then recurses
3702  * to optimise any children.
3703  */
3704
3705 STATIC void
3706 S_optimize_op(pTHX_ OP* o)
3707 {
3708     OP *top_op = o;
3709
3710     PERL_ARGS_ASSERT_OPTIMIZE_OP;
3711
3712     while (1) {
3713         OP * next_kid = NULL;
3714
3715         assert(o->op_type != OP_FREED);
3716
3717         switch (o->op_type) {
3718         case OP_NEXTSTATE:
3719         case OP_DBSTATE:
3720             PL_curcop = ((COP*)o);              /* for warnings */
3721             break;
3722
3723
3724         case OP_CONCAT:
3725         case OP_SASSIGN:
3726         case OP_STRINGIFY:
3727         case OP_SPRINTF:
3728             S_maybe_multiconcat(aTHX_ o);
3729             break;
3730
3731         case OP_SUBST:
3732             if (cPMOPo->op_pmreplrootu.op_pmreplroot) {
3733                 /* we can't assume that op_pmreplroot->op_sibparent == o
3734                  * and that it is thus possible to walk back up the tree
3735                  * past op_pmreplroot. So, although we try to avoid
3736                  * recursing through op trees, do it here. After all,
3737                  * there are unlikely to be many nested s///e's within
3738                  * the replacement part of a s///e.
3739                  */
3740                 optimize_op(cPMOPo->op_pmreplrootu.op_pmreplroot);
3741             }
3742             break;
3743
3744         default:
3745             break;
3746         }
3747
3748         if (o->op_flags & OPf_KIDS)
3749             next_kid = cUNOPo->op_first;
3750
3751         /* if a kid hasn't been nominated to process, continue with the
3752          * next sibling, or if no siblings left, go back to the parent's
3753          * siblings and so on
3754          */
3755         while (!next_kid) {
3756             if (o == top_op)
3757                 return; /* at top; no parents/siblings to try */
3758             if (OpHAS_SIBLING(o))
3759                 next_kid = o->op_sibparent;
3760             else
3761                 o = o->op_sibparent; /*try parent's next sibling */
3762         }
3763
3764       /* this label not yet used. Goto here if any code above sets
3765        * next-kid
3766        get_next_op:
3767        */
3768         o = next_kid;
3769     }
3770 }
3771
3772
3773 /*
3774 =for apidoc finalize_optree
3775
3776 This function finalizes the optree.  Should be called directly after
3777 the complete optree is built.  It does some additional
3778 checking which can't be done in the normal C<ck_>xxx functions and makes
3779 the tree thread-safe.
3780
3781 =cut
3782 */
3783 void
3784 Perl_finalize_optree(pTHX_ OP* o)
3785 {
3786     PERL_ARGS_ASSERT_FINALIZE_OPTREE;
3787
3788     ENTER;
3789     SAVEVPTR(PL_curcop);
3790
3791     finalize_op(o);
3792
3793     LEAVE;
3794 }
3795
3796 #ifdef USE_ITHREADS
3797 /* Relocate sv to the pad for thread safety.
3798  * Despite being a "constant", the SV is written to,
3799  * for reference counts, sv_upgrade() etc. */
3800 PERL_STATIC_INLINE void
3801 S_op_relocate_sv(pTHX_ SV** svp, PADOFFSET* targp)
3802 {
3803     PADOFFSET ix;
3804     PERL_ARGS_ASSERT_OP_RELOCATE_SV;
3805     if (!*svp) return;
3806     ix = pad_alloc(OP_CONST, SVf_READONLY);
3807     SvREFCNT_dec(PAD_SVl(ix));
3808     PAD_SETSV(ix, *svp);
3809     /* XXX I don't know how this isn't readonly already. */
3810     if (!SvIsCOW(PAD_SVl(ix))) SvREADONLY_on(PAD_SVl(ix));
3811     *svp = NULL;
3812     *targp = ix;
3813 }
3814 #endif
3815
3816 /*
3817 =for apidoc traverse_op_tree
3818
3819 Return the next op in a depth-first traversal of the op tree,
3820 returning NULL when the traversal is complete.
3821
3822 The initial call must supply the root of the tree as both top and o.
3823
3824 For now it's static, but it may be exposed to the API in the future.
3825
3826 =cut
3827 */
3828
3829 STATIC OP*
3830 S_traverse_op_tree(pTHX_ OP *top, OP *o) {
3831     OP *sib;
3832
3833     PERL_ARGS_ASSERT_TRAVERSE_OP_TREE;
3834
3835     if ((o->op_flags & OPf_KIDS) && cUNOPo->op_first) {
3836         return cUNOPo->op_first;
3837     }
3838     else if ((sib = OpSIBLING(o))) {
3839         return sib;
3840     }
3841     else {
3842         OP *parent = o->op_sibparent;
3843         assert(!(o->op_moresib));
3844         while (parent && parent != top) {
3845             OP *sib = OpSIBLING(parent);
3846             if (sib)
3847                 return sib;
3848             parent = parent->op_sibparent;
3849         }
3850
3851         return NULL;
3852     }
3853 }
3854
3855 STATIC void
3856 S_finalize_op(pTHX_ OP* o)
3857 {
3858     OP * const top = o;
3859     PERL_ARGS_ASSERT_FINALIZE_OP;
3860
3861     do {
3862         assert(o->op_type != OP_FREED);
3863
3864         switch (o->op_type) {
3865         case OP_NEXTSTATE:
3866         case OP_DBSTATE:
3867             PL_curcop = ((COP*)o);              /* for warnings */
3868             break;
3869         case OP_EXEC:
3870             if (OpHAS_SIBLING(o)) {
3871                 OP *sib = OpSIBLING(o);
3872                 if ((  sib->op_type == OP_NEXTSTATE || sib->op_type == OP_DBSTATE)
3873                     && ckWARN(WARN_EXEC)
3874                     && OpHAS_SIBLING(sib))
3875                 {
3876                     const OPCODE type = OpSIBLING(sib)->op_type;
3877                     if (type != OP_EXIT && type != OP_WARN && type != OP_DIE) {
3878                         const line_t oldline = CopLINE(PL_curcop);
3879                         CopLINE_set(PL_curcop, CopLINE((COP*)sib));
3880                         Perl_warner(aTHX_ packWARN(WARN_EXEC),
3881                             "Statement unlikely to be reached");
3882                         Perl_warner(aTHX_ packWARN(WARN_EXEC),
3883                             "\t(Maybe you meant system() when you said exec()?)\n");
3884                         CopLINE_set(PL_curcop, oldline);
3885                     }
3886                 }
3887             }
3888             break;
3889
3890         case OP_GV:
3891             if ((o->op_private & OPpEARLY_CV) && ckWARN(WARN_PROTOTYPE)) {
3892                 GV * const gv = cGVOPo_gv;
3893                 if (SvTYPE(gv) == SVt_PVGV && GvCV(gv) && SvPVX_const(GvCV(gv))) {
3894                     /* XXX could check prototype here instead of just carping */
3895                     SV * const sv = sv_newmortal();
3896                     gv_efullname3(sv, gv, NULL);
3897                     Perl_warner(aTHX_ packWARN(WARN_PROTOTYPE),
3898                                 "%" SVf "() called too early to check prototype",
3899                                 SVfARG(sv));
3900                 }
3901             }
3902             break;
3903
3904         case OP_CONST:
3905             if (cSVOPo->op_private & OPpCONST_STRICT)
3906                 no_bareword_allowed(o);
3907 #ifdef USE_ITHREADS
3908             /* FALLTHROUGH */
3909         case OP_HINTSEVAL:
3910             op_relocate_sv(&cSVOPo->op_sv, &o->op_targ);
3911 #endif
3912             break;
3913
3914 #ifdef USE_ITHREADS
3915             /* Relocate all the METHOP's SVs to the pad for thread safety. */
3916         case OP_METHOD_NAMED:
3917         case OP_METHOD_SUPER:
3918         case OP_METHOD_REDIR:
3919         case OP_METHOD_REDIR_SUPER:
3920             op_relocate_sv(&cMETHOPx(o)->op_u.op_meth_sv, &o->op_targ);
3921             break;
3922 #endif
3923
3924         case OP_HELEM: {
3925             UNOP *rop;
3926             SVOP *key_op;
3927             OP *kid;
3928
3929             if ((key_op = cSVOPx(((BINOP*)o)->op_last))->op_type != OP_CONST)
3930                 break;
3931
3932             rop = (UNOP*)((BINOP*)o)->op_first;
3933
3934             goto check_keys;
3935
3936             case OP_HSLICE:
3937                 S_scalar_slice_warning(aTHX_ o);
3938                 /* FALLTHROUGH */
3939
3940             case OP_KVHSLICE:
3941                 kid = OpSIBLING(cLISTOPo->op_first);
3942             if (/* I bet there's always a pushmark... */
3943                 OP_TYPE_ISNT_AND_WASNT_NN(kid, OP_LIST)
3944                 && OP_TYPE_ISNT_NN(kid, OP_CONST))
3945             {
3946                 break;
3947             }
3948
3949             key_op = (SVOP*)(kid->op_type == OP_CONST
3950                              ? kid
3951                              : OpSIBLING(kLISTOP->op_first));
3952
3953             rop = (UNOP*)((LISTOP*)o)->op_last;
3954
3955         check_keys:
3956             if (o->op_private & OPpLVAL_INTRO || rop->op_type != OP_RV2HV)
3957                 rop = NULL;
3958             S_check_hash_fields_and_hekify(aTHX_ rop, key_op, 1);
3959             break;
3960         }
3961         case OP_NULL:
3962             if (o->op_targ != OP_HSLICE && o->op_targ != OP_ASLICE)
3963                 break;
3964             /* FALLTHROUGH */
3965         case OP_ASLICE:
3966             S_scalar_slice_warning(aTHX_ o);
3967             break;
3968
3969         case OP_SUBST: {
3970             if (cPMOPo->op_pmreplrootu.op_pmreplroot)
3971                 finalize_op(cPMOPo->op_pmreplrootu.op_pmreplroot);
3972             break;
3973         }
3974         default:
3975             break;
3976         }
3977
3978 #ifdef DEBUGGING
3979         if (o->op_flags & OPf_KIDS) {
3980             OP *kid;
3981
3982             /* check that op_last points to the last sibling, and that
3983              * the last op_sibling/op_sibparent field points back to the
3984              * parent, and that the only ops with KIDS are those which are
3985              * entitled to them */
3986             U32 type = o->op_type;
3987             U32 family;
3988             bool has_last;
3989
3990             if (type == OP_NULL) {
3991                 type = o->op_targ;
3992                 /* ck_glob creates a null UNOP with ex-type GLOB
3993                  * (which is a list op. So pretend it wasn't a listop */
3994                 if (type == OP_GLOB)
3995                     type = OP_NULL;
3996             }
3997             family = PL_opargs[type] & OA_CLASS_MASK;
3998
3999             has_last = (   family == OA_BINOP
4000                         || family == OA_LISTOP
4001                         || family == OA_PMOP
4002                         || family == OA_LOOP
4003                        );
4004             assert(  has_last /* has op_first and op_last, or ...
4005                   ... has (or may have) op_first: */
4006                   || family == OA_UNOP
4007                   || family == OA_UNOP_AUX
4008                   || family == OA_LOGOP
4009                   || family == OA_BASEOP_OR_UNOP
4010                   || family == OA_FILESTATOP
4011                   || family == OA_LOOPEXOP
4012                   || family == OA_METHOP
4013                   || type == OP_CUSTOM
4014                   || type == OP_NULL /* new_logop does this */
4015                   );
4016
4017             for (kid = cUNOPo->op_first; kid; kid = OpSIBLING(kid)) {
4018                 if (!OpHAS_SIBLING(kid)) {
4019                     if (has_last)
4020                         assert(kid == cLISTOPo->op_last);
4021                     assert(kid->op_sibparent == o);
4022                 }
4023             }
4024         }
4025 #endif
4026     } while (( o = traverse_op_tree(top, o)) != NULL);
4027 }
4028
4029 static void
4030 S_mark_padname_lvalue(pTHX_ PADNAME *pn)
4031 {
4032     CV *cv = PL_compcv;
4033     PadnameLVALUE_on(pn);
4034     while (PadnameOUTER(pn) && PARENT_PAD_INDEX(pn)) {
4035         cv = CvOUTSIDE(cv);
4036         /* RT #127786: cv can be NULL due to an eval within the DB package
4037          * called from an anon sub - anon subs don't have CvOUTSIDE() set
4038          * unless they contain an eval, but calling eval within DB
4039          * pretends the eval was done in the caller's scope.
4040          */
4041         if (!cv)
4042             break;
4043         assert(CvPADLIST(cv));
4044         pn =
4045            PadlistNAMESARRAY(CvPADLIST(cv))[PARENT_PAD_INDEX(pn)];
4046         assert(PadnameLEN(pn));
4047         PadnameLVALUE_on(pn);
4048     }
4049 }
4050
4051 static bool
4052 S_vivifies(const OPCODE type)
4053 {
4054     switch(type) {
4055     case OP_RV2AV:     case   OP_ASLICE:
4056     case OP_RV2HV:     case OP_KVASLICE:
4057     case OP_RV2SV:     case   OP_HSLICE:
4058     case OP_AELEMFAST: case OP_KVHSLICE:
4059     case OP_HELEM:
4060     case OP_AELEM:
4061         return 1;
4062     }
4063     return 0;
4064 }
4065
4066
4067 /* apply lvalue reference (aliasing) context to the optree o.
4068  * E.g. in
4069  *     \($x,$y) = (...)
4070  * o would be the list ($x,$y) and type would be OP_AASSIGN.
4071  * It may descend and apply this to children too, for example in
4072  * \( $cond ? $x, $y) = (...)
4073  */
4074
4075 static void
4076 S_lvref(pTHX_ OP *o, I32 type)
4077 {
4078     OP *kid;
4079     OP * top_op = o;
4080
4081     while (1) {
4082         switch (o->op_type) {
4083         case OP_COND_EXPR:
4084             o = OpSIBLING(cUNOPo->op_first);
4085             continue;
4086
4087         case OP_PUSHMARK:
4088             goto do_next;
4089
4090         case OP_RV2AV:
4091             if (cUNOPo->op_first->op_type != OP_GV) goto badref;
4092             o->op_flags |= OPf_STACKED;
4093             if (o->op_flags & OPf_PARENS) {
4094                 if (o->op_private & OPpLVAL_INTRO) {
4095                      yyerror(Perl_form(aTHX_ "Can't modify reference to "
4096                           "localized parenthesized array in list assignment"));
4097                     goto do_next;
4098                 }
4099               slurpy:
4100                 OpTYPE_set(o, OP_LVAVREF);
4101                 o->op_private &= OPpLVAL_INTRO|OPpPAD_STATE;
4102                 o->op_flags |= OPf_MOD|OPf_REF;
4103                 goto do_next;
4104             }
4105             o->op_private |= OPpLVREF_AV;
4106             goto checkgv;
4107
4108         case OP_RV2CV:
4109             kid = cUNOPo->op_first;
4110             if (kid->op_type == OP_NULL)
4111                 kid = cUNOPx(OpSIBLING(kUNOP->op_first))
4112                     ->op_first;
4113             o->op_private = OPpLVREF_CV;
4114             if (kid->op_type == OP_GV)
4115                 o->op_flags |= OPf_STACKED;
4116             else if (kid->op_type == OP_PADCV) {
4117                 o->op_targ = kid->op_targ;
4118                 kid->op_targ = 0;
4119                 op_free(cUNOPo->op_first);
4120                 cUNOPo->op_first = NULL;
4121                 o->op_flags &=~ OPf_KIDS;
4122             }
4123             else goto badref;
4124             break;
4125
4126         case OP_RV2HV:
4127             if (o->op_flags & OPf_PARENS) {
4128               parenhash:
4129                 yyerror(Perl_form(aTHX_ "Can't modify reference to "
4130                                      "parenthesized hash in list assignment"));
4131                     goto do_next;
4132             }
4133             o->op_private |= OPpLVREF_HV;
4134             /* FALLTHROUGH */
4135         case OP_RV2SV:
4136           checkgv:
4137             if (cUNOPo->op_first->op_type != OP_GV) goto badref;
4138             o->op_flags |= OPf_STACKED;
4139             break;
4140
4141         case OP_PADHV:
4142             if (o->op_flags & OPf_PARENS) goto parenhash;
4143             o->op_private |= OPpLVREF_HV;
4144             /* FALLTHROUGH */
4145         case OP_PADSV:
4146             PAD_COMPNAME_GEN_set(o->op_targ, PERL_INT_MAX);
4147             break;
4148
4149         case OP_PADAV:
4150             PAD_COMPNAME_GEN_set(o->op_targ, PERL_INT_MAX);
4151             if (o->op_flags & OPf_PARENS) goto slurpy;
4152             o->op_private |= OPpLVREF_AV;
4153             break;
4154
4155         case OP_AELEM:
4156         case OP_HELEM:
4157             o->op_private |= OPpLVREF_ELEM;
4158             o->op_flags   |= OPf_STACKED;
4159             break;
4160
4161         case OP_ASLICE:
4162         case OP_HSLICE:
4163             OpTYPE_set(o, OP_LVREFSLICE);
4164             o->op_private &= OPpLVAL_INTRO;
4165             goto do_next;
4166
4167         case OP_NULL:
4168             if (o->op_flags & OPf_SPECIAL)              /* do BLOCK */
4169                 goto badref;
4170             else if (!(o->op_flags & OPf_KIDS))
4171                 goto do_next;
4172
4173             /* the code formerly only recursed into the first child of
4174              * a non ex-list OP_NULL. if we ever encounter such a null op with
4175              * more than one child, need to decide whether its ok to process
4176              * *all* its kids or not */
4177             assert(o->op_targ == OP_LIST
4178                     || !(OpHAS_SIBLING(cBINOPo->op_first)));
4179             /* FALLTHROUGH */
4180         case OP_LIST:
4181             o = cLISTOPo->op_first;
4182             continue;
4183
4184         case OP_STUB:
4185             if (o->op_flags & OPf_PARENS)
4186                 goto do_next;
4187             /* FALLTHROUGH */
4188         default:
4189           badref:
4190             /* diag_listed_as: Can't modify reference to %s in %s assignment */
4191             yyerror(Perl_form(aTHX_ "Can't modify reference to %s in %s",
4192                          o->op_type == OP_NULL && o->op_flags & OPf_SPECIAL
4193                           ? "do block"
4194                           : OP_DESC(o),
4195                          PL_op_desc[type]));
4196             goto do_next;
4197         }
4198
4199         OpTYPE_set(o, OP_LVREF);
4200         o->op_private &=
4201             OPpLVAL_INTRO|OPpLVREF_ELEM|OPpLVREF_TYPE|OPpPAD_STATE;
4202         if (type == OP_ENTERLOOP)
4203             o->op_private |= OPpLVREF_ITER;
4204
4205       do_next:
4206         while (1) {
4207             if (o == top_op)
4208                 return; /* at top; no parents/siblings to try */
4209             if (OpHAS_SIBLING(o)) {
4210                 o = o->op_sibparent;
4211                 break;
4212             }
4213             o = o->op_sibparent; /*try parent's next sibling */
4214         }
4215     } /* while */
4216 }
4217
4218
4219 PERL_STATIC_INLINE bool
4220 S_potential_mod_type(I32 type)
4221 {
4222     /* Types that only potentially result in modification.  */
4223     return type == OP_GREPSTART || type == OP_ENTERSUB
4224         || type == OP_REFGEN    || type == OP_LEAVESUBLV;
4225 }
4226
4227
4228 /*
4229 =for apidoc op_lvalue
4230
4231 Propagate lvalue ("modifiable") context to an op and its children.
4232 C<type> represents the context type, roughly based on the type of op that
4233 would do the modifying, although C<local()> is represented by C<OP_NULL>,
4234 because it has no op type of its own (it is signalled by a flag on
4235 the lvalue op).
4236
4237 This function detects things that can't be modified, such as C<$x+1>, and
4238 generates errors for them.  For example, C<$x+1 = 2> would cause it to be
4239 called with an op of type C<OP_ADD> and a C<type> argument of C<OP_SASSIGN>.
4240
4241 It also flags things that need to behave specially in an lvalue context,
4242 such as C<$$x = 5> which might have to vivify a reference in C<$x>.
4243
4244 =cut
4245
4246 Perl_op_lvalue_flags() is a non-API lower-level interface to
4247 op_lvalue().  The flags param has these bits:
4248     OP_LVALUE_NO_CROAK:  return rather than croaking on error
4249
4250 */
4251
4252 OP *
4253 Perl_op_lvalue_flags(pTHX_ OP *o, I32 type, U32 flags)
4254 {
4255     OP *top_op = o;
4256
4257     if (!o || (PL_parser && PL_parser->error_count))
4258         return o;
4259
4260     while (1) {
4261     OP *kid;
4262     /* -1 = error on localize, 0 = ignore localize, 1 = ok to localize */
4263     int localize = -1;
4264     OP *next_kid = NULL;
4265
4266     if ((o->op_private & OPpTARGET_MY)
4267         && (PL_opargs[o->op_type] & OA_TARGLEX))/* OPp share the meaning */
4268     {
4269         goto do_next;
4270     }
4271
4272     /* elements of a list might be in void context because the list is
4273        in scalar context or because they are attribute sub calls */
4274     if ((o->op_flags & OPf_WANT) == OPf_WANT_VOID)
4275         goto do_next;
4276
4277     if (type == OP_PRTF || type == OP_SPRINTF) type = OP_ENTERSUB;
4278
4279     switch (o->op_type) {
4280     case OP_UNDEF:
4281         PL_modcount++;
4282         goto do_next;
4283
4284     case OP_STUB:
4285         if ((o->op_flags & OPf_PARENS))
4286             break;
4287         goto nomod;
4288
4289     case OP_ENTERSUB:
4290         if ((type == OP_UNDEF || type == OP_REFGEN || type == OP_LOCK) &&
4291             !(o->op_flags & OPf_STACKED)) {
4292             OpTYPE_set(o, OP_RV2CV);            /* entersub => rv2cv */
4293             assert(cUNOPo->op_first->op_type == OP_NULL);
4294             op_null(((LISTOP*)cUNOPo->op_first)->op_first);/* disable pushmark */
4295             break;
4296         }
4297         else {                          /* lvalue subroutine call */
4298             o->op_private |= OPpLVAL_INTRO;
4299             PL_modcount = RETURN_UNLIMITED_NUMBER;
4300             if (S_potential_mod_type(type)) {
4301                 o->op_private |= OPpENTERSUB_INARGS;
4302                 break;
4303             }
4304             else {                      /* Compile-time error message: */
4305                 OP *kid = cUNOPo->op_first;
4306                 CV *cv;
4307                 GV *gv;
4308                 SV *namesv;
4309
4310                 if (kid->op_type != OP_PUSHMARK) {
4311                     if (kid->op_type != OP_NULL || kid->op_targ != OP_LIST)
4312                         Perl_croak(aTHX_
4313                                 "panic: unexpected lvalue entersub "
4314                                 "args: type/targ %ld:%" UVuf,
4315                                 (long)kid->op_type, (UV)kid->op_targ);
4316                     kid = kLISTOP->op_first;
4317                 }
4318                 while (OpHAS_SIBLING(kid))
4319                     kid = OpSIBLING(kid);
4320                 if (!(kid->op_type == OP_NULL && kid->op_targ == OP_RV2CV)) {
4321                     break;      /* Postpone until runtime */
4322                 }
4323
4324                 kid = kUNOP->op_first;
4325                 if (kid->op_type == OP_NULL && kid->op_targ == OP_RV2SV)
4326                     kid = kUNOP->op_first;
4327                 if (kid->op_type == OP_NULL)
4328                     Perl_croak(aTHX_
4329                                "Unexpected constant lvalue entersub "
4330                                "entry via type/targ %ld:%" UVuf,
4331                                (long)kid->op_type, (UV)kid->op_targ);
4332                 if (kid->op_type != OP_GV) {
4333                     break;
4334                 }
4335
4336                 gv = kGVOP_gv;
4337                 cv = isGV(gv)
4338                     ? GvCV(gv)
4339                     : SvROK(gv) && SvTYPE(SvRV(gv)) == SVt_PVCV
4340                         ? MUTABLE_CV(SvRV(gv))
4341                         : NULL;
4342                 if (!cv)
4343                     break;
4344                 if (CvLVALUE(cv))
4345                     break;
4346                 if (flags & OP_LVALUE_NO_CROAK)
4347                     return NULL;
4348
4349                 namesv = cv_name(cv, NULL, 0);
4350                 yyerror_pv(Perl_form(aTHX_ "Can't modify non-lvalue "
4351                                      "subroutine call of &%" SVf " in %s",
4352                                      SVfARG(namesv), PL_op_desc[type]),
4353                            SvUTF8(namesv));
4354                 goto do_next;
4355             }
4356         }
4357         /* FALLTHROUGH */
4358     default:
4359       nomod:
4360         if (flags & OP_LVALUE_NO_CROAK) return NULL;
4361         /* grep, foreach, subcalls, refgen */
4362         if (S_potential_mod_type(type))
4363             break;
4364         yyerror(Perl_form(aTHX_ "Can't modify %s in %s",
4365                      (o->op_type == OP_NULL && (o->op_flags & OPf_SPECIAL)
4366                       ? "do block"
4367                       : OP_DESC(o)),
4368                      type ? PL_op_desc[type] : "local"));
4369         goto do_next;
4370
4371     case OP_PREINC:
4372     case OP_PREDEC:
4373     case OP_POW:
4374     case OP_MULTIPLY:
4375     case OP_DIVIDE:
4376     case OP_MODULO:
4377     case OP_ADD:
4378     case OP_SUBTRACT:
4379     case OP_CONCAT:
4380     case OP_LEFT_SHIFT:
4381     case OP_RIGHT_SHIFT:
4382     case OP_BIT_AND:
4383     case OP_BIT_XOR:
4384     case OP_BIT_OR:
4385     case OP_I_MULTIPLY:
4386     case OP_I_DIVIDE:
4387     case OP_I_MODULO:
4388     case OP_I_ADD:
4389     case OP_I_SUBTRACT:
4390         if (!(o->op_flags & OPf_STACKED))
4391             goto nomod;
4392         PL_modcount++;
4393         break;
4394
4395     case OP_REPEAT:
4396         if (o->op_flags & OPf_STACKED) {
4397             PL_modcount++;
4398             break;
4399         }
4400         if (!(o->op_private & OPpREPEAT_DOLIST))
4401             goto nomod;
4402         else {
4403             const I32 mods = PL_modcount;
4404             /* we recurse rather than iterate here because we need to
4405              * calculate and use the delta applied to PL_modcount by the
4406              * first child. So in something like
4407              *     ($x, ($y) x 3) = split;
4408              * split knows that 4 elements are wanted
4409              */
4410             modkids(cBINOPo->op_first, type);
4411             if (type != OP_AASSIGN)
4412                 goto nomod;
4413             kid = cBINOPo->op_last;
4414             if (kid->op_type == OP_CONST && SvIOK(kSVOP_sv)) {
4415                 const IV iv = SvIV(kSVOP_sv);
4416                 if (PL_modcount != RETURN_UNLIMITED_NUMBER)
4417                     PL_modcount =
4418                         mods + (PL_modcount - mods) * (iv < 0 ? 0 : iv);
4419             }
4420             else
4421                 PL_modcount = RETURN_UNLIMITED_NUMBER;
4422         }
4423         break;
4424
4425     case OP_COND_EXPR:
4426         localize = 1;
4427         next_kid = OpSIBLING(cUNOPo->op_first);
4428         break;
4429
4430     case OP_RV2AV:
4431     case OP_RV2HV:
4432         if (type == OP_REFGEN && o->op_flags & OPf_PARENS) {
4433            PL_modcount = RETURN_UNLIMITED_NUMBER;
4434            /* Treat \(@foo) like ordinary list, but still mark it as modi-
4435               fiable since some contexts need to know.  */
4436            o->op_flags |= OPf_MOD;
4437            goto do_next;
4438         }
4439         /* FALLTHROUGH */
4440     case OP_RV2GV:
4441         if (scalar_mod_type(o, type))
4442             goto nomod;
4443         ref(cUNOPo->op_first, o->op_type);
4444         /* FALLTHROUGH */
4445     case OP_ASLICE:
4446     case OP_HSLICE:
4447         localize = 1;
4448         /* FALLTHROUGH */
4449     case OP_AASSIGN:
4450         /* Do not apply the lvsub flag for rv2[ah]v in scalar context.  */
4451         if (type == OP_LEAVESUBLV && (
4452                 (o->op_type != OP_RV2AV && o->op_type != OP_RV2HV)
4453              || (o->op_flags & OPf_WANT) != OPf_WANT_SCALAR
4454            ))
4455             o->op_private |= OPpMAYBE_LVSUB;
4456         /* FALLTHROUGH */
4457     case OP_NEXTSTATE:
4458     case OP_DBSTATE:
4459        PL_modcount = RETURN_UNLIMITED_NUMBER;
4460         break;
4461
4462     case OP_KVHSLICE:
4463     case OP_KVASLICE:
4464     case OP_AKEYS:
4465         if (type == OP_LEAVESUBLV)
4466             o->op_private |= OPpMAYBE_LVSUB;
4467         goto nomod;
4468
4469     case OP_AVHVSWITCH:
4470         if (type == OP_LEAVESUBLV
4471          && (o->op_private & OPpAVHVSWITCH_MASK) + OP_EACH == OP_KEYS)
4472             o->op_private |= OPpMAYBE_LVSUB;
4473         goto nomod;
4474
4475     case OP_AV2ARYLEN:
4476         PL_hints |= HINT_BLOCK_SCOPE;
4477         if (type == OP_LEAVESUBLV)
4478             o->op_private |= OPpMAYBE_LVSUB;
4479         PL_modcount++;
4480         break;
4481
4482     case OP_RV2SV:
4483         ref(cUNOPo->op_first, o->op_type);
4484         localize = 1;
4485         /* FALLTHROUGH */
4486     case OP_GV:
4487         PL_hints |= HINT_BLOCK_SCOPE;
4488         /* FALLTHROUGH */
4489     case OP_SASSIGN:
4490     case OP_ANDASSIGN:
4491     case OP_ORASSIGN:
4492     case OP_DORASSIGN:
4493         PL_modcount++;
4494         break;
4495
4496     case OP_AELEMFAST:
4497     case OP_AELEMFAST_LEX:
4498         localize = -1;
4499         PL_modcount++;
4500         break;
4501
4502     case OP_PADAV:
4503     case OP_PADHV:
4504        PL_modcount = RETURN_UNLIMITED_NUMBER;
4505         if (type == OP_REFGEN && o->op_flags & OPf_PARENS)
4506         {
4507            /* Treat \(@foo) like ordinary list, but still mark it as modi-
4508               fiable since some contexts need to know.  */
4509             o->op_flags |= OPf_MOD;
4510             goto do_next;
4511         }
4512         if (scalar_mod_type(o, type))
4513             goto nomod;
4514         if ((o->op_flags & OPf_WANT) != OPf_WANT_SCALAR
4515           && type == OP_LEAVESUBLV)
4516             o->op_private |= OPpMAYBE_LVSUB;
4517         /* FALLTHROUGH */
4518     case OP_PADSV:
4519         PL_modcount++;
4520         if (!type) /* local() */
4521             Perl_croak(aTHX_ "Can't localize lexical variable %" PNf,
4522                               PNfARG(PAD_COMPNAME(o->op_targ)));
4523         if (!(o->op_private & OPpLVAL_INTRO)
4524          || (  type != OP_SASSIGN && type != OP_AASSIGN
4525             && PadnameIsSTATE(PAD_COMPNAME_SV(o->op_targ))  ))
4526             S_mark_padname_lvalue(aTHX_ PAD_COMPNAME_SV(o->op_targ));
4527         break;
4528
4529     case OP_PUSHMARK:
4530         localize = 0;
4531         break;
4532
4533     case OP_KEYS:
4534         if (type != OP_LEAVESUBLV && !scalar_mod_type(NULL, type))
4535             goto nomod;
4536         goto lvalue_func;
4537     case OP_SUBSTR:
4538         if (o->op_private == 4) /* don't allow 4 arg substr as lvalue */
4539             goto nomod;
4540         /* FALLTHROUGH */
4541     case OP_POS:
4542     case OP_VEC:
4543       lvalue_func:
4544         if (type == OP_LEAVESUBLV)
4545             o->op_private |= OPpMAYBE_LVSUB;
4546         if (o->op_flags & OPf_KIDS && OpHAS_SIBLING(cBINOPo->op_first)) {
4547             /* we recurse rather than iterate here because the child
4548              * needs to be processed with a different 'type' parameter */
4549
4550             /* substr and vec */
4551             /* If this op is in merely potential (non-fatal) modifiable
4552                context, then apply OP_ENTERSUB context to
4553                the kid op (to avoid croaking).  Other-
4554                wise pass this op’s own type so the correct op is mentioned
4555                in error messages.  */
4556             op_lvalue(OpSIBLING(cBINOPo->op_first),
4557                       S_potential_mod_type(type)
4558                         ? (I32)OP_ENTERSUB
4559                         : o->op_type);
4560         }
4561         break;
4562
4563     case OP_AELEM:
4564     case OP_HELEM:
4565         ref(cBINOPo->op_first, o->op_type);
4566         if (type == OP_ENTERSUB &&
4567              !(o->op_private & (OPpLVAL_INTRO | OPpDEREF)))
4568             o->op_private |= OPpLVAL_DEFER;
4569         if (type == OP_LEAVESUBLV)
4570             o->op_private |= OPpMAYBE_LVSUB;
4571         localize = 1;
4572         PL_modcount++;
4573         break;
4574
4575     case OP_LEAVE:
4576     case OP_LEAVELOOP:
4577         o->op_private |= OPpLVALUE;
4578         /* FALLTHROUGH */
4579     case OP_SCOPE:
4580     case OP_ENTER:
4581     case OP_LINESEQ:
4582         localize = 0;
4583         if (o->op_flags & OPf_KIDS)
4584             next_kid = cLISTOPo->op_last;
4585         break;
4586
4587     case OP_NULL:
4588         localize = 0;
4589         if (o->op_flags & OPf_SPECIAL)          /* do BLOCK */
4590             goto nomod;
4591         else if (!(o->op_flags & OPf_KIDS))
4592             break;
4593
4594         if (o->op_targ != OP_LIST) {
4595             OP *sib = OpSIBLING(cLISTOPo->op_first);
4596             /* OP_TRANS and OP_TRANSR with argument have a weird optree
4597              * that looks like
4598              *
4599              *   null
4600              *      arg
4601              *      trans
4602              *
4603              * compared with things like OP_MATCH which have the argument
4604              * as a child:
4605              *
4606              *   match
4607              *      arg
4608              *
4609              * so handle specially to correctly get "Can't modify" croaks etc
4610              */
4611
4612             if (sib && (sib->op_type == OP_TRANS || sib->op_type == OP_TRANSR))
4613             {
4614                 /* this should trigger a "Can't modify transliteration" err */
4615                 op_lvalue(sib, type);
4616             }
4617             next_kid = cBINOPo->op_first;
4618             /* we assume OP_NULLs which aren't ex-list have no more than 2
4619              * children. If this assumption is wrong, increase the scan
4620              * limit below */
4621             assert(   !OpHAS_SIBLING(next_kid)
4622                    || !OpHAS_SIBLING(OpSIBLING(next_kid)));
4623             break;
4624         }
4625         /* FALLTHROUGH */
4626     case OP_LIST:
4627         localize = 0;
4628         next_kid = cLISTOPo->op_first;
4629         break;
4630
4631     case OP_COREARGS:
4632         goto do_next;
4633
4634     case OP_AND:
4635     case OP_OR:
4636         if (type == OP_LEAVESUBLV
4637          || !S_vivifies(cLOGOPo->op_first->op_type))
4638             next_kid = cLOGOPo->op_first;
4639         else if (type == OP_LEAVESUBLV
4640          || !S_vivifies(OpSIBLING(cLOGOPo->op_first)->op_type))
4641             next_kid = OpSIBLING(cLOGOPo->op_first);
4642         goto nomod;
4643
4644     case OP_SREFGEN:
4645         if (type == OP_NULL) { /* local */
4646           local_refgen:
4647             if (!FEATURE_MYREF_IS_ENABLED)
4648                 Perl_croak(aTHX_ "The experimental declared_refs "
4649                                  "feature is not enabled");
4650             Perl_ck_warner_d(aTHX_
4651                      packWARN(WARN_EXPERIMENTAL__DECLARED_REFS),
4652                     "Declaring references is experimental");
4653             next_kid = cUNOPo->op_first;
4654             goto do_next;
4655         }
4656         if (type != OP_AASSIGN && type != OP_SASSIGN
4657          && type != OP_ENTERLOOP)
4658             goto nomod;
4659         /* Don’t bother applying lvalue context to the ex-list.  */
4660         kid = cUNOPx(cUNOPo->op_first)->op_first;
4661         assert (!OpHAS_SIBLING(kid));
4662         goto kid_2lvref;
4663     case OP_REFGEN:
4664         if (type == OP_NULL) /* local */
4665             goto local_refgen;
4666         if (type != OP_AASSIGN) goto nomod;
4667         kid = cUNOPo->op_first;
4668       kid_2lvref:
4669         {
4670             const U8 ec = PL_parser ? PL_parser->error_count : 0;
4671             S_lvref(aTHX_ kid, type);
4672             if (!PL_parser || PL_parser->error_count == ec) {
4673                 if (!FEATURE_REFALIASING_IS_ENABLED)
4674                     Perl_croak(aTHX_
4675                        "Experimental aliasing via reference not enabled");
4676                 Perl_ck_warner_d(aTHX_
4677                                  packWARN(WARN_EXPERIMENTAL__REFALIASING),
4678                                 "Aliasing via reference is experimental");
4679             }
4680         }
4681         if (o->op_type == OP_REFGEN)
4682             op_null(cUNOPx(cUNOPo->op_first)->op_first); /* pushmark */
4683         op_null(o);
4684         goto do_next;
4685
4686     case OP_SPLIT:
4687         if ((o->op_private & OPpSPLIT_ASSIGN)) {
4688             /* This is actually @array = split.  */
4689             PL_modcount = RETURN_UNLIMITED_NUMBER;
4690             break;
4691         }
4692         goto nomod;
4693
4694     case OP_SCALAR:
4695         op_lvalue(cUNOPo->op_first, OP_ENTERSUB);
4696         goto nomod;
4697     }
4698
4699     /* [20011101.069 (#7861)] File test operators interpret OPf_REF to mean that
4700        their argument is a filehandle; thus \stat(".") should not set
4701        it. AMS 20011102 */
4702     if (type == OP_REFGEN && OP_IS_STAT(o->op_type))
4703         goto do_next;
4704
4705     if (type != OP_LEAVESUBLV)
4706         o->op_flags |= OPf_MOD;
4707
4708     if (type == OP_AASSIGN || type == OP_SASSIGN)
4709         o->op_flags |= OPf_SPECIAL
4710                       |(o->op_type == OP_ENTERSUB ? 0 : OPf_REF);
4711     else if (!type) { /* local() */
4712         switch (localize) {
4713         case 1:
4714             o->op_private |= OPpLVAL_INTRO;
4715             o->op_flags &= ~OPf_SPECIAL;
4716             PL_hints |= HINT_BLOCK_SCOPE;
4717             break;
4718         case 0:
4719             break;
4720         case -1:
4721             Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX),
4722                            "Useless localization of %s", OP_DESC(o));
4723         }
4724     }
4725     else if (type != OP_GREPSTART && type != OP_ENTERSUB
4726              && type != OP_LEAVESUBLV && o->op_type != OP_ENTERSUB)
4727         o->op_flags |= OPf_REF;
4728
4729   do_next:
4730     while (!next_kid) {
4731         if (o == top_op)
4732             return top_op; /* at top; no parents/siblings to try */
4733         if (OpHAS_SIBLING(o)) {
4734             next_kid = o->op_sibparent;
4735             if (!OpHAS_SIBLING(next_kid)) {
4736                 /* a few node types don't recurse into their second child */
4737                 OP *parent = next_kid->op_sibparent;
4738                 I32 ptype  = parent->op_type;
4739                 if (   (ptype == OP_NULL && parent->op_targ != OP_LIST)
4740                     || (   (ptype == OP_AND || ptype == OP_OR)
4741                         && (type != OP_LEAVESUBLV 
4742                             && S_vivifies(next_kid->op_type))
4743                        )
4744                 )  {
4745                     /*try parent's next sibling */
4746                     o = parent;
4747                     next_kid =  NULL;
4748                 }
4749             }
4750         }
4751         else
4752             o = o->op_sibparent; /*try parent's next sibling */
4753
4754     }
4755     o = next_kid;
4756
4757     } /* while */
4758
4759 }
4760
4761
4762 STATIC bool
4763 S_scalar_mod_type(const OP *o, I32 type)
4764 {
4765     switch (type) {
4766     case OP_POS:
4767     case OP_SASSIGN:
4768         if (o && o->op_type == OP_RV2GV)
4769             return FALSE;
4770         /* FALLTHROUGH */
4771     case OP_PREINC:
4772     case OP_PREDEC:
4773     case OP_POSTINC:
4774     case OP_POSTDEC:
4775     case OP_I_PREINC:
4776     case OP_I_PREDEC:
4777     case OP_I_POSTINC:
4778     case OP_I_POSTDEC:
4779     case OP_POW:
4780     case OP_MULTIPLY:
4781     case OP_DIVIDE:
4782     case OP_MODULO:
4783     case OP_REPEAT:
4784     case OP_ADD:
4785     case OP_SUBTRACT:
4786     case OP_I_MULTIPLY:
4787     case OP_I_DIVIDE:
4788     case OP_I_MODULO:
4789     case OP_I_ADD:
4790     case OP_I_SUBTRACT:
4791     case OP_LEFT_SHIFT:
4792     case OP_RIGHT_SHIFT:
4793     case OP_BIT_AND:
4794     case OP_BIT_XOR:
4795     case OP_BIT_OR:
4796     case OP_NBIT_AND:
4797     case OP_NBIT_XOR:
4798     case OP_NBIT_OR:
4799     case OP_SBIT_AND:
4800     case OP_SBIT_XOR:
4801     case OP_SBIT_OR:
4802     case OP_CONCAT:
4803     case OP_SUBST:
4804     case OP_TRANS:
4805     case OP_TRANSR:
4806     case OP_READ:
4807     case OP_SYSREAD:
4808     case OP_RECV:
4809     case OP_ANDASSIGN:
4810     case OP_ORASSIGN:
4811     case OP_DORASSIGN:
4812     case OP_VEC:
4813     case OP_SUBSTR:
4814         return TRUE;
4815     default:
4816         return FALSE;
4817     }
4818 }
4819
4820 STATIC bool
4821 S_is_handle_constructor(const OP *o, I32 numargs)
4822 {
4823     PERL_ARGS_ASSERT_IS_HANDLE_CONSTRUCTOR;
4824
4825     switch (o->op_type) {
4826     case OP_PIPE_OP:
4827     case OP_SOCKPAIR:
4828         if (numargs == 2)
4829             return TRUE;
4830         /* FALLTHROUGH */
4831     case OP_SYSOPEN:
4832     case OP_OPEN:
4833     case OP_SELECT:             /* XXX c.f. SelectSaver.pm */
4834     case OP_SOCKET:
4835     case OP_OPEN_DIR:
4836     case OP_ACCEPT:
4837         if (numargs == 1)
4838             return TRUE;
4839         /* FALLTHROUGH */
4840     default:
4841         return FALSE;
4842     }
4843 }
4844
4845 static OP *
4846 S_refkids(pTHX_ OP *o, I32 type)
4847 {
4848     if (o && o->op_flags & OPf_KIDS) {
4849         OP *kid;
4850         for (kid = cLISTOPo->op_first; kid; kid = OpSIBLING(kid))
4851             ref(kid, type);
4852     }
4853     return o;
4854 }
4855
4856
4857 /* Apply reference (autovivification) context to the subtree at o.
4858  * For example in
4859  *     push @{expression}, ....;
4860  * o will be the head of 'expression' and type will be OP_RV2AV.
4861  * It marks the op o (or a suitable child) as autovivifying, e.g. by
4862  * setting  OPf_MOD.
4863  * For OP_RV2AV/OP_PADAV and OP_RV2HV/OP_PADHV sets OPf_REF too if
4864  * set_op_ref is true.
4865  *
4866  * Also calls scalar(o).
4867  */
4868
4869 OP *
4870 Perl_doref(pTHX_ OP *o, I32 type, bool set_op_ref)
4871 {
4872     OP * top_op = o;
4873
4874     PERL_ARGS_ASSERT_DOREF;
4875
4876     if (PL_parser && PL_parser->error_count)
4877         return o;
4878
4879     while (1) {
4880         switch (o->op_type) {
4881         case OP_ENTERSUB:
4882             if ((type == OP_EXISTS || type == OP_DEFINED) &&
4883                 !(o->op_flags & OPf_STACKED)) {
4884                 OpTYPE_set(o, OP_RV2CV);             /* entersub => rv2cv */
4885                 assert(cUNOPo->op_first->op_type == OP_NULL);
4886                 /* disable pushmark */
4887                 op_null(((LISTOP*)cUNOPo->op_first)->op_first);
4888                 o->op_flags |= OPf_SPECIAL;
4889             }
4890             else if (type == OP_RV2SV || type == OP_RV2AV || type == OP_RV2HV){
4891                 o->op_private |= (type == OP_RV2AV ? OPpDEREF_AV
4892                                   : type == OP_RV2HV ? OPpDEREF_HV
4893                                   : OPpDEREF_SV);
4894                 o->op_flags |= OPf_MOD;
4895             }
4896
4897             break;
4898
4899         case OP_COND_EXPR:
4900             o = OpSIBLING(cUNOPo->op_first);
4901             continue;
4902
4903         case OP_RV2SV:
4904             if (type == OP_DEFINED)
4905                 o->op_flags |= OPf_SPECIAL;             /* don't create GV */
4906             /* FALLTHROUGH */
4907         case OP_PADSV:
4908             if (type == OP_RV2SV || type == OP_RV2AV || type == OP_RV2HV) {
4909                 o->op_private |= (type == OP_RV2AV ? OPpDEREF_AV
4910                                   : type == OP_RV2HV ? OPpDEREF_HV
4911                                   : OPpDEREF_SV);
4912                 o->op_flags |= OPf_MOD;
4913             }
4914             if (o->op_flags & OPf_KIDS) {
4915                 type = o->op_type;
4916                 o = cUNOPo->op_first;
4917                 continue;
4918             }
4919             break;
4920
4921         case OP_RV2AV:
4922         case OP_RV2HV:
4923             if (set_op_ref)
4924                 o->op_flags |= OPf_REF;
4925             /* FALLTHROUGH */
4926         case OP_RV2GV:
4927             if (type == OP_DEFINED)
4928                 o->op_flags |= OPf_SPECIAL;             /* don't create GV */
4929             type = o->op_type;
4930             o = cUNOPo->op_first;
4931             continue;
4932
4933         case OP_PADAV:
4934         case OP_PADHV:
4935             if (set_op_ref)
4936                 o->op_flags |= OPf_REF;
4937             break;
4938
4939         case OP_SCALAR:
4940         case OP_NULL:
4941             if (!(o->op_flags & OPf_KIDS) || type == OP_DEFINED)
4942                 break;
4943              o = cBINOPo->op_first;
4944             continue;
4945
4946         case OP_AELEM:
4947         case OP_HELEM:
4948             if (type == OP_RV2SV || type == OP_RV2AV || type == OP_RV2HV) {
4949                 o->op_private |= (type == OP_RV2AV ? OPpDEREF_AV
4950                                   : type == OP_RV2HV ? OPpDEREF_HV
4951                                   : OPpDEREF_SV);
4952                 o->op_flags |= OPf_MOD;
4953             }
4954             type = o->op_type;
4955             o = cBINOPo->op_first;
4956             continue;;
4957
4958         case OP_SCOPE:
4959         case OP_LEAVE:
4960             set_op_ref = FALSE;
4961             /* FALLTHROUGH */
4962         case OP_ENTER:
4963         case OP_LIST:
4964             if (!(o->op_flags & OPf_KIDS))
4965                 break;
4966             o = cLISTOPo->op_last;
4967             continue;
4968
4969         default:
4970             break;
4971         } /* switch */
4972
4973         while (1) {
4974             if (o == top_op)
4975                 return scalar(top_op); /* at top; no parents/siblings to try */
4976             if (OpHAS_SIBLING(o)) {
4977                 o = o->op_sibparent;
4978                 /* Normally skip all siblings and go straight to the parent;
4979                  * the only op that requires two children to be processed
4980                  * is OP_COND_EXPR */
4981                 if (!OpHAS_SIBLING(o)
4982                         && o->op_sibparent->op_type == OP_COND_EXPR)
4983                     break;
4984                 continue;
4985             }
4986             o = o->op_sibparent; /*try parent's next sibling */
4987         }
4988     } /* while */
4989 }
4990
4991
4992 STATIC OP *
4993 S_dup_attrlist(pTHX_ OP *o)
4994 {
4995     OP *rop;
4996
4997     PERL_ARGS_ASSERT_DUP_ATTRLIST;
4998
4999     /* An attrlist is either a simple OP_CONST or an OP_LIST with kids,
5000      * where the first kid is OP_PUSHMARK and the remaining ones
5001      * are OP_CONST.  We need to push the OP_CONST values.
5002      */
5003     if (o->op_type == OP_CONST)
5004         rop = newSVOP(OP_CONST, o->op_flags, SvREFCNT_inc_NN(cSVOPo->op_sv));
5005     else {
5006         assert((o->op_type == OP_LIST) && (o->op_flags & OPf_KIDS));
5007         rop = NULL;
5008         for (o = cLISTOPo->op_first; o; o = OpSIBLING(o)) {
5009             if (o->op_type == OP_CONST)
5010                 rop = op_append_elem(OP_LIST, rop,
5011                                   newSVOP(OP_CONST, o->op_flags,
5012                                           SvREFCNT_inc_NN(cSVOPo->op_sv)));
5013         }
5014     }
5015     return rop;
5016 }
5017
5018 STATIC void
5019 S_apply_attrs(pTHX_ HV *stash, SV *target, OP *attrs)
5020 {
5021     PERL_ARGS_ASSERT_APPLY_ATTRS;
5022     {
5023         SV * const stashsv = newSVhek(HvNAME_HEK(stash));
5024
5025         /* fake up C<use attributes $pkg,$rv,@attrs> */
5026
5027 #define ATTRSMODULE "attributes"
5028 #define ATTRSMODULE_PM "attributes.pm"
5029
5030         Perl_load_module(
5031           aTHX_ PERL_LOADMOD_IMPORT_OPS,
5032           newSVpvs(ATTRSMODULE),
5033           NULL,
5034           op_prepend_elem(OP_LIST,
5035                           newSVOP(OP_CONST, 0, stashsv),
5036                           op_prepend_elem(OP_LIST,
5037                                           newSVOP(OP_CONST, 0,
5038                                                   newRV(target)),
5039                                           dup_attrlist(attrs))));
5040     }
5041 }
5042
5043 STATIC void
5044 S_apply_attrs_my(pTHX_ HV *stash, OP *target, OP *attrs, OP **imopsp)
5045 {
5046     OP *pack, *imop, *arg;
5047     SV *meth, *stashsv, **svp;
5048
5049     PERL_ARGS_ASSERT_APPLY_ATTRS_MY;
5050
5051     if (!attrs)
5052         return;
5053
5054     assert(target->op_type == OP_PADSV ||
5055            target->op_type == OP_PADHV ||
5056            target->op_type == OP_PADAV);
5057
5058     /* Ensure that attributes.pm is loaded. */
5059     /* Don't force the C<use> if we don't need it. */
5060     svp = hv_fetchs(GvHVn(PL_incgv), ATTRSMODULE_PM, FALSE);
5061     if (svp && *svp != &PL_sv_undef)
5062         NOOP;   /* already in %INC */
5063     else
5064         Perl_load_module(aTHX_ PERL_LOADMOD_NOIMPORT,
5065                                newSVpvs(ATTRSMODULE), NULL);
5066
5067     /* Need package name for method call. */
5068     pack = newSVOP(OP_CONST, 0, newSVpvs(ATTRSMODULE));
5069
5070     /* Build up the real arg-list. */
5071     stashsv = newSVhek(HvNAME_HEK(stash));
5072
5073     arg = newOP(OP_PADSV, 0);
5074     arg->op_targ = target->op_targ;
5075     arg = op_prepend_elem(OP_LIST,
5076                        newSVOP(OP_CONST, 0, stashsv),
5077                        op_prepend_elem(OP_LIST,
5078                                     newUNOP(OP_REFGEN, 0,
5079                                             arg),
5080                                     dup_attrlist(attrs)));
5081
5082     /* Fake up a method call to import */
5083     meth = newSVpvs_share("import");
5084     imop = op_convert_list(OP_ENTERSUB, OPf_STACKED|OPf_SPECIAL|OPf_WANT_VOID,
5085                    op_append_elem(OP_LIST,
5086                                op_prepend_elem(OP_LIST, pack, arg),
5087                                newMETHOP_named(OP_METHOD_NAMED, 0, meth)));
5088
5089     /* Combine the ops. */
5090     *imopsp = op_append_elem(OP_LIST, *imopsp, imop);
5091 }
5092
5093 /*
5094 =notfor apidoc apply_attrs_string
5095
5096 Attempts to apply a list of attributes specified by the C<attrstr> and
5097 C<len> arguments to the subroutine identified by the C<cv> argument which
5098 is expected to be associated with the package identified by the C<stashpv>
5099 argument (see L<attributes>).  It gets this wrong, though, in that it
5100 does not correctly identify the boundaries of the individual attribute
5101 specifications within C<attrstr>.  This is not really intended for the
5102 public API, but has to be listed here for systems such as AIX which
5103 need an explicit export list for symbols.  (It's called from XS code
5104 in support of the C<ATTRS:> keyword from F<xsubpp>.)  Patches to fix it
5105 to respect attribute syntax properly would be welcome.
5106
5107 =cut
5108 */
5109
5110 void
5111 Perl_apply_attrs_string(pTHX_ const char *stashpv, CV *cv,
5112                         const char *attrstr, STRLEN len)
5113 {
5114     OP *attrs = NULL;
5115
5116     PERL_ARGS_ASSERT_APPLY_ATTRS_STRING;
5117
5118     if (!len) {
5119         len = strlen(attrstr);
5120     }
5121
5122     while (len) {
5123         for (; isSPACE(*attrstr) && len; --len, ++attrstr) ;
5124         if (len) {
5125             const char * const sstr = attrstr;
5126             for (; !isSPACE(*attrstr) && len; --len, ++attrstr) ;
5127             attrs = op_append_elem(OP_LIST, attrs,
5128                                 newSVOP(OP_CONST, 0,
5129                                         newSVpvn(sstr, attrstr-sstr)));
5130         }
5131     }
5132
5133     Perl_load_module(aTHX_ PERL_LOADMOD_IMPORT_OPS,
5134                      newSVpvs(ATTRSMODULE),
5135                      NULL, op_prepend_elem(OP_LIST,
5136                                   newSVOP(OP_CONST, 0, newSVpv(stashpv,0)),
5137                                   op_prepend_elem(OP_LIST,
5138                                                newSVOP(OP_CONST, 0,
5139                                                        newRV(MUTABLE_SV(cv))),
5140                                                attrs)));
5141 }
5142
5143 STATIC void
5144 S_move_proto_attr(pTHX_ OP **proto, OP **attrs, const GV * name,
5145                         bool curstash)
5146 {
5147     OP *new_proto = NULL;
5148     STRLEN pvlen;
5149     char *pv;
5150     OP *o;
5151
5152     PERL_ARGS_ASSERT_MOVE_PROTO_ATTR;
5153
5154     if (!*attrs)
5155         return;
5156
5157     o = *attrs;
5158     if (o->op_type == OP_CONST) {
5159         pv = SvPV(cSVOPo_sv, pvlen);
5160         if (memBEGINs(pv, pvlen, "prototype(")) {
5161             SV * const tmpsv = newSVpvn_flags(pv + 10, pvlen - 11, SvUTF8(cSVOPo_sv));
5162             SV ** const tmpo = cSVOPx_svp(o);
5163             SvREFCNT_dec(cSVOPo_sv);
5164             *tmpo = tmpsv;
5165             new_proto = o;
5166             *attrs = NULL;
5167         }
5168     } else if (o->op_type == OP_LIST) {
5169         OP * lasto;
5170         assert(o->op_flags & OPf_KIDS);
5171         lasto = cLISTOPo->op_first;
5172         assert(lasto->op_type == OP_PUSHMARK);
5173         for (o = OpSIBLING(lasto); o; o = OpSIBLING(o)) {
5174             if (o->op_type == OP_CONST) {
5175                 pv = SvPV(cSVOPo_sv, pvlen);
5176                 if (memBEGINs(pv, pvlen, "prototype(")) {
5177                     SV * const tmpsv = newSVpvn_flags(pv + 10, pvlen - 11, SvUTF8(cSVOPo_sv));
5178                     SV ** const tmpo = cSVOPx_svp(o);
5179                     SvREFCNT_dec(cSVOPo_sv);
5180                     *tmpo = tmpsv;
5181                     if (new_proto && ckWARN(WARN_MISC)) {
5182                         STRLEN new_len;
5183                         const char * newp = SvPV(cSVOPo_sv, new_len);
5184                         Perl_warner(aTHX_ packWARN(WARN_MISC),
5185                             "Attribute prototype(%" UTF8f ") discards earlier prototype attribute in same sub",
5186                             UTF8fARG(SvUTF8(cSVOPo_sv), new_len, newp));
5187                         op_free(new_proto);
5188                     }
5189                     else if (new_proto)
5190                         op_free(new_proto);
5191                     new_proto = o;
5192                     /* excise new_proto from the list */
5193                     op_sibling_splice(*attrs, lasto, 1, NULL);
5194                     o = lasto;
5195                     continue;
5196                 }
5197             }
5198             lasto = o;
5199         }
5200         /* If the list is now just the PUSHMARK, scrap the whole thing; otherwise attributes.xs
5201            would get pulled in with no real need */
5202         if (!OpHAS_SIBLING(cLISTOPx(*attrs)->op_first)) {
5203             op_free(*attrs);
5204             *attrs = NULL;
5205         }
5206     }
5207
5208     if (new_proto) {
5209         SV *svname;
5210         if (isGV(name)) {
5211             svname = sv_newmortal();
5212             gv_efullname3(svname, name, NULL);
5213         }
5214         else if (SvPOK(name) && *SvPVX((SV *)name) == '&')
5215             svname = newSVpvn_flags(SvPVX((SV *)name)+1, SvCUR(name)-1, SvUTF8(name)|SVs_TEMP);
5216         else
5217             svname = (SV *)name;
5218         if (ckWARN(WARN_ILLEGALPROTO))
5219             (void)validate_proto(svname, cSVOPx_sv(new_proto), TRUE,
5220                                  curstash);
5221         if (*proto && ckWARN(WARN_PROTOTYPE)) {
5222             STRLEN old_len, new_len;
5223             const char * oldp = SvPV(cSVOPx_sv(*proto), old_len);
5224             const char * newp = SvPV(cSVOPx_sv(new_proto), new_len);
5225
5226             if (curstash && svname == (SV *)name
5227              && !memchr(SvPVX(svname), ':', SvCUR(svname))) {
5228                 svname = sv_2mortal(newSVsv(PL_curstname));
5229                 sv_catpvs(svname, "::");
5230                 sv_catsv(svname, (SV *)name);
5231             }
5232
5233             Perl_warner(aTHX_ packWARN(WARN_PROTOTYPE),
5234                 "Prototype '%" UTF8f "' overridden by attribute 'prototype(%" UTF8f ")'"
5235                 " in %" SVf,
5236                 UTF8fARG(SvUTF8(cSVOPx_sv(*proto)), old_len, oldp),
5237                 UTF8fARG(SvUTF8(cSVOPx_sv(new_proto)), new_len, newp),
5238                 SVfARG(svname));
5239         }
5240         if (*proto)
5241             op_free(*proto);
5242         *proto = new_proto;
5243     }
5244 }
5245
5246 static void
5247 S_cant_declare(pTHX_ OP *o)
5248 {
5249     if (o->op_type == OP_NULL
5250      && (o->op_flags & (OPf_SPECIAL|OPf_KIDS)) == OPf_KIDS)
5251         o = cUNOPo->op_first;
5252     yyerror(Perl_form(aTHX_ "Can't declare %s in \"%s\"",
5253                              o->op_type == OP_NULL
5254                                && o->op_flags & OPf_SPECIAL
5255                                  ? "do block"
5256                                  : OP_DESC(o),
5257                              PL_parser->in_my == KEY_our   ? "our"   :
5258                              PL_parser->in_my == KEY_state ? "state" :
5259                                                              "my"));
5260 }
5261
5262 STATIC OP *
5263 S_my_kid(pTHX_ OP *o, OP *attrs, OP **imopsp)
5264 {
5265     I32 type;
5266     const bool stately = PL_parser && PL_parser->in_my == KEY_state;
5267
5268     PERL_ARGS_ASSERT_MY_KID;
5269
5270     if (!o || (PL_parser && PL_parser->error_count))
5271         return o;
5272
5273     type = o->op_type;
5274
5275     if (OP_TYPE_IS_OR_WAS(o, OP_LIST)) {
5276         OP *kid;
5277         for (kid = cLISTOPo->op_first; kid; kid = OpSIBLING(kid))
5278             my_kid(kid, attrs, imopsp);
5279         return o;
5280     } else if (type == OP_UNDEF || type == OP_STUB) {
5281         return o;
5282     } else if (type == OP_RV2SV ||      /* "our" declaration */
5283                type == OP_RV2AV ||
5284                type == OP_RV2HV) {
5285         if (cUNOPo->op_first->op_type != OP_GV) { /* MJD 20011224 */
5286             S_cant_declare(aTHX_ o);
5287         } else if (attrs) {
5288             GV * const gv = cGVOPx_gv(cUNOPo->op_first);
5289             assert(PL_parser);
5290             PL_parser->in_my = FALSE;
5291             PL_parser->in_my_stash = NULL;
5292             apply_attrs(GvSTASH(gv),
5293                         (type == OP_RV2SV ? GvSVn(gv) :
5294                          type == OP_RV2AV ? MUTABLE_SV(GvAVn(gv)) :
5295                          type == OP_RV2HV ? MUTABLE_SV(GvHVn(gv)) : MUTABLE_SV(gv)),
5296                         attrs);
5297         }
5298         o->op_private |= OPpOUR_INTRO;
5299         return o;
5300     }
5301     else if (type == OP_REFGEN || type == OP_SREFGEN) {
5302         if (!FEATURE_MYREF_IS_ENABLED)
5303             Perl_croak(aTHX_ "The experimental declared_refs "
5304                              "feature is not enabled");
5305         Perl_ck_warner_d(aTHX_
5306              packWARN(WARN_EXPERIMENTAL__DECLARED_REFS),
5307             "Declaring references is experimental");
5308         /* Kid is a nulled OP_LIST, handled above.  */
5309         my_kid(cUNOPo->op_first, attrs, imopsp);
5310         return o;
5311     }
5312     else if (type != OP_PADSV &&
5313              type != OP_PADAV &&
5314              type != OP_PADHV &&
5315              type != OP_PUSHMARK)
5316     {
5317         S_cant_declare(aTHX_ o);
5318         return o;
5319     }
5320     else if (attrs && type != OP_PUSHMARK) {
5321         HV *stash;
5322
5323         assert(PL_parser);
5324         PL_parser->in_my = FALSE;
5325         PL_parser->in_my_stash = NULL;
5326
5327         /* check for C<my Dog $spot> when deciding package */
5328         stash = PAD_COMPNAME_TYPE(o->op_targ);
5329         if (!stash)
5330             stash = PL_curstash;
5331         apply_attrs_my(stash, o, attrs, imopsp);
5332     }
5333     o->op_flags |= OPf_MOD;
5334     o->op_private |= OPpLVAL_INTRO;
5335     if (stately)
5336         o->op_private |= OPpPAD_STATE;
5337     return o;
5338 }
5339
5340 OP *
5341 Perl_my_attrs(pTHX_ OP *o, OP *attrs)
5342 {
5343     OP *rops;
5344     int maybe_scalar = 0;
5345
5346     PERL_ARGS_ASSERT_MY_ATTRS;
5347
5348 /* [perl #17376]: this appears to be premature, and results in code such as
5349    C< our(%x); > executing in list mode rather than void mode */
5350 #if 0
5351     if (o->op_flags & OPf_PARENS)
5352         list(o);
5353     else
5354         maybe_scalar = 1;
5355 #else
5356     maybe_scalar = 1;
5357 #endif
5358     if (attrs)
5359         SAVEFREEOP(attrs);
5360     rops = NULL;
5361     o = my_kid(o, attrs, &rops);
5362     if (rops) {
5363         if (maybe_scalar && o->op_type == OP_PADSV) {
5364             o = scalar(op_append_list(OP_LIST, rops, o));
5365             o->op_private |= OPpLVAL_INTRO;
5366         }
5367         else {
5368             /* The listop in rops might have a pushmark at the beginning,
5369                which will mess up list assignment. */
5370             LISTOP * const lrops = (LISTOP *)rops; /* for brevity */
5371             if (rops->op_type == OP_LIST &&
5372                 lrops->op_first && lrops->op_first->op_type == OP_PUSHMARK)
5373             {
5374                 OP * const pushmark = lrops->op_first;
5375                 /* excise pushmark */
5376                 op_sibling_splice(rops, NULL, 1, NULL);
5377                 op_free(pushmark);
5378             }
5379             o = op_append_list(OP_LIST, o, rops);
5380         }
5381     }
5382     PL_parser->in_my = FALSE;
5383     PL_parser->in_my_stash = NULL;
5384     return o;
5385 }
5386
5387 OP *
5388 Perl_sawparens(pTHX_ OP *o)
5389 {
5390     PERL_UNUSED_CONTEXT;
5391     if (o)
5392         o->op_flags |= OPf_PARENS;
5393     return o;
5394 }
5395
5396 OP *
5397 Perl_bind_match(pTHX_ I32 type, OP *left, OP *right)
5398 {
5399     OP *o;
5400     bool ismatchop = 0;
5401     const OPCODE ltype = left->op_type;
5402     const OPCODE rtype = right->op_type;
5403
5404     PERL_ARGS_ASSERT_BIND_MATCH;
5405
5406     if ( (ltype == OP_RV2AV || ltype == OP_RV2HV || ltype == OP_PADAV
5407           || ltype == OP_PADHV) && ckWARN(WARN_MISC))
5408     {
5409       const char * const desc
5410           = PL_op_desc[(
5411                           rtype == OP_SUBST || rtype == OP_TRANS
5412                        || rtype == OP_TRANSR
5413                        )
5414                        ? (int)rtype : OP_MATCH];
5415       const bool isary = ltype == OP_RV2AV || ltype == OP_PADAV;
5416       SV * const name =
5417         S_op_varname(aTHX_ left);
5418       if (name)
5419         Perl_warner(aTHX_ packWARN(WARN_MISC),
5420              "Applying %s to %" SVf " will act on scalar(%" SVf ")",
5421              desc, SVfARG(name), SVfARG(name));
5422       else {
5423         const char * const sample = (isary
5424              ? "@array" : "%hash");
5425         Perl_warner(aTHX_ packWARN(WARN_MISC),
5426              "Applying %s to %s will act on scalar(%s)",
5427              desc, sample, sample);
5428       }
5429     }
5430
5431     if (rtype == OP_CONST &&
5432         cSVOPx(right)->op_private & OPpCONST_BARE &&
5433         cSVOPx(right)->op_private & OPpCONST_STRICT)
5434     {
5435         no_bareword_allowed(right);
5436     }
5437
5438     /* !~ doesn't make sense with /r, so error on it for now */
5439     if (rtype == OP_SUBST && (cPMOPx(right)->op_pmflags & PMf_NONDESTRUCT) &&
5440         type == OP_NOT)
5441         /* diag_listed_as: Using !~ with %s doesn't make sense */
5442         yyerror("Using !~ with s///r doesn't make sense");
5443     if (rtype == OP_TRANSR && type == OP_NOT)
5444         /* diag_listed_as: Using !~ with %s doesn't make sense */
5445         yyerror("Using !~ with tr///r doesn't make sense");
5446
5447     ismatchop = (rtype == OP_MATCH ||
5448                  rtype == OP_SUBST ||
5449                  rtype == OP_TRANS || rtype == OP_TRANSR)
5450              && !(right->op_flags & OPf_SPECIAL);
5451     if (ismatchop && right->op_private & OPpTARGET_MY) {
5452         right->op_targ = 0;
5453         right->op_private &= ~OPpTARGET_MY;
5454     }
5455     if (!(right->op_flags & OPf_STACKED) && !right->op_targ && ismatchop) {
5456         if (left->op_type == OP_PADSV
5457          && !(left->op_private & OPpLVAL_INTRO))
5458         {
5459             right->op_targ = left->op_targ;
5460             op_free(left);
5461             o = right;
5462         }
5463         else {
5464             right->op_flags |= OPf_STACKED;
5465             if (rtype != OP_MATCH && rtype != OP_TRANSR &&
5466             ! (rtype == OP_TRANS &&
5467                right->op_private & OPpTRANS_IDENTICAL) &&
5468             ! (rtype == OP_SUBST &&
5469                (cPMOPx(right)->op_pmflags & PMf_NONDESTRUCT)))
5470                 left = op_lvalue(left, rtype);
5471             if (right->op_type == OP_TRANS || right->op_type == OP_TRANSR)
5472                 o = newBINOP(OP_NULL, OPf_STACKED, scalar(left), right);
5473             else
5474                 o = op_prepend_elem(rtype, scalar(left), right);
5475         }
5476         if (type == OP_NOT)
5477             return newUNOP(OP_NOT, 0, scalar(o));
5478         return o;
5479     }
5480     else
5481         return bind_match(type, left,
5482                 pmruntime(newPMOP(OP_MATCH, 0), right, NULL, 0, 0));
5483 }
5484
5485 OP *
5486 Perl_invert(pTHX_ OP *o)
5487 {
5488     if (!o)
5489         return NULL;
5490     return newUNOP(OP_NOT, OPf_SPECIAL, scalar(o));
5491 }
5492
5493 OP *
5494 Perl_cmpchain_start(pTHX_ I32 type, OP *left, OP *right)
5495 {
5496     BINOP *bop;
5497     OP *op;
5498
5499     if (!left)
5500         left = newOP(OP_NULL, 0);
5501     if (!right)
5502         right = newOP(OP_NULL, 0);
5503     scalar(left);
5504     scalar(right);
5505     NewOp(0, bop, 1, BINOP);
5506     op = (OP*)bop;
5507     ASSUME((PL_opargs[type] & OA_CLASS_MASK) == OA_BINOP);
5508     OpTYPE_set(op, type);
5509     cBINOPx(op)->op_flags = OPf_KIDS;
5510     cBINOPx(op)->op_private = 2;
5511     cBINOPx(op)->op_first = left;
5512     cBINOPx(op)->op_last = right;
5513     OpMORESIB_set(left, right);
5514     OpLASTSIB_set(right, op);
5515     return op;
5516 }
5517
5518 OP *
5519 Perl_cmpchain_extend(pTHX_ I32 type, OP *ch, OP *right)
5520 {
5521     BINOP *bop;
5522     OP *op;
5523
5524     PERL_ARGS_ASSERT_CMPCHAIN_EXTEND;
5525     if (!right)
5526         right = newOP(OP_NULL, 0);
5527     scalar(right);
5528     NewOp(0, bop, 1, BINOP);
5529     op = (OP*)bop;
5530     ASSUME((PL_opargs[type] & OA_CLASS_MASK) == OA_BINOP);
5531     OpTYPE_set(op, type);
5532     if (ch->op_type != OP_NULL) {
5533         UNOP *lch;
5534         OP *nch, *cleft, *cright;
5535         NewOp(0, lch, 1, UNOP);
5536         nch = (OP*)lch;
5537         OpTYPE_set(nch, OP_NULL);
5538         nch->op_flags = OPf_KIDS;
5539         cleft = cBINOPx(ch)->op_first;
5540         cright = cBINOPx(ch)->op_last;
5541         cBINOPx(ch)->op_first = NULL;
5542         cBINOPx(ch)->op_last = NULL;
5543         cBINOPx(ch)->op_private = 0;
5544         cBINOPx(ch)->op_flags = 0;
5545         cUNOPx(nch)->op_first = cright;
5546         OpMORESIB_set(cright, ch);
5547         OpMORESIB_set(ch, cleft);
5548         OpLASTSIB_set(cleft, nch);
5549         ch = nch;
5550     }
5551     OpMORESIB_set(right, op);
5552     OpMORESIB_set(op, cUNOPx(ch)->op_first);
5553     cUNOPx(ch)->op_first = right;
5554     return ch;
5555 }
5556
5557 OP *
5558 Perl_cmpchain_finish(pTHX_ OP *ch)
5559 {
5560
5561     PERL_ARGS_ASSERT_CMPCHAIN_FINISH;
5562     if (ch->op_type != OP_NULL) {
5563         OPCODE cmpoptype = ch->op_type;
5564         ch = CHECKOP(cmpoptype, ch);
5565         if(!ch->op_next && ch->op_type == cmpoptype)
5566             ch = fold_constants(op_integerize(op_std_init(ch)));
5567         return ch;
5568     } else {
5569         OP *condop = NULL;
5570         OP *rightarg = cUNOPx(ch)->op_first;
5571         cUNOPx(ch)->op_first = OpSIBLING(rightarg);
5572         OpLASTSIB_set(rightarg, NULL);
5573         while (1) {
5574             OP *cmpop = cUNOPx(ch)->op_first;
5575             OP *leftarg = OpSIBLING(cmpop);
5576             OPCODE cmpoptype = cmpop->op_type;
5577             OP *nextrightarg;
5578             bool is_last;
5579             is_last = !(cUNOPx(ch)->op_first = OpSIBLING(leftarg));
5580             OpLASTSIB_set(cmpop, NULL);
5581             OpLASTSIB_set(leftarg, NULL);
5582             if (is_last) {
5583                 ch->op_flags = 0;
5584                 op_free(ch);
5585                 nextrightarg = NULL;
5586             } else {
5587                 nextrightarg = newUNOP(OP_CMPCHAIN_DUP, 0, leftarg);
5588                 leftarg = newOP(OP_NULL, 0);
5589             }
5590             cBINOPx(cmpop)->op_first = leftarg;
5591             cBINOPx(cmpop)->op_last = rightarg;
5592             OpMORESIB_set(leftarg, rightarg);
5593             OpLASTSIB_set(rightarg, cmpop);
5594             cmpop->op_flags = OPf_KIDS;
5595             cmpop->op_private = 2;
5596             cmpop = CHECKOP(cmpoptype, cmpop);
5597             if(!cmpop->op_next && cmpop->op_type == cmpoptype)
5598                 cmpop = fold_constants(op_integerize(op_std_init(cmpop)));
5599             condop = condop ? newLOGOP(OP_CMPCHAIN_AND, 0, cmpop, condop) :
5600                         cmpop;
5601             if (!nextrightarg)
5602                 return condop;
5603             rightarg = nextrightarg;
5604         }
5605     }
5606 }
5607
5608 /*
5609 =for apidoc op_scope
5610
5611 Wraps up an op tree with some additional ops so that at runtime a dynamic
5612 scope will be created.  The original ops run in the new dynamic scope,
5613 and then, provided that they exit normally, the scope will be unwound.
5614 The additional ops used to create and unwind the dynamic scope will
5615 normally be an C<enter>/C<leave> pair, but a C<scope> op may be used
5616 instead if the ops are simple enough to not need the full dynamic scope
5617 structure.
5618
5619 =cut
5620 */
5621
5622 OP *
5623 Perl_op_scope(pTHX_ OP *o)
5624 {
5625     if (o) {
5626         if (o->op_flags & OPf_PARENS || PERLDB_NOOPT || TAINTING_get) {
5627             o = op_prepend_elem(OP_LINESEQ,
5628                     newOP(OP_ENTER, (o->op_flags & OPf_WANT)), o);
5629             OpTYPE_set(o, OP_LEAVE);
5630         }
5631         else if (o->op_type == OP_LINESEQ) {
5632             OP *kid;
5633             OpTYPE_set(o, OP_SCOPE);
5634             kid = ((LISTOP*)o)->op_first;
5635             if (kid->op_type == OP_NEXTSTATE || kid->op_type == OP_DBSTATE) {
5636                 op_null(kid);
5637
5638                 /* The following deals with things like 'do {1 for 1}' */
5639                 kid = OpSIBLING(kid);
5640                 if (kid &&
5641                     (kid->op_type == OP_NEXTSTATE || kid->op_type == OP_DBSTATE))
5642                     op_null(kid);
5643             }
5644         }
5645         else
5646             o = newLISTOP(OP_SCOPE, 0, o, NULL);
5647     }
5648     return o;
5649 }
5650
5651 OP *
5652 Perl_op_unscope(pTHX_ OP *o)
5653 {
5654     if (o && o->op_type == OP_LINESEQ) {
5655         OP *kid = cLISTOPo->op_first;
5656         for(; kid; kid = OpSIBLING(kid))
5657             if (kid->op_type == OP_NEXTSTATE || kid->op_type == OP_DBSTATE)
5658                 op_null(kid);
5659     }
5660     return o;
5661 }
5662
5663 /*
5664 =for apidoc block_start
5665
5666 Handles compile-time scope entry.
5667 Arranges for hints to be restored on block
5668 exit and also handles pad sequence numbers to make lexical variables scope
5669 right.  Returns a savestack index for use with C<block_end>.
5670
5671 =cut
5672 */
5673
5674 int
5675 Perl_block_start(pTHX_ int full)
5676 {
5677     const int retval = PL_savestack_ix;
5678
5679     PL_compiling.cop_seq = PL_cop_seqmax;
5680     COP_SEQMAX_INC;
5681     pad_block_start(full);
5682     SAVEHINTS();
5683     PL_hints &= ~HINT_BLOCK_SCOPE;
5684     SAVECOMPILEWARNINGS();
5685     PL_compiling.cop_warnings = DUP_WARNINGS(PL_compiling.cop_warnings);
5686     SAVEI32(PL_compiling.cop_seq);
5687     PL_compiling.cop_seq = 0;
5688
5689     CALL_BLOCK_HOOKS(bhk_start, full);
5690
5691     return retval;
5692 }
5693
5694 /*
5695 =for apidoc block_end
5696
5697 Handles compile-time scope exit.  C<floor>
5698 is the savestack index returned by
5699 C<block_start>, and C<seq> is the body of the block.  Returns the block,
5700 possibly modified.
5701
5702 =cut
5703 */
5704
5705 OP*
5706 Perl_block_end(pTHX_ I32 floor, OP *seq)
5707 {
5708     const int needblockscope = PL_hints & HINT_BLOCK_SCOPE;
5709     OP* retval = scalarseq(seq);
5710     OP *o;
5711
5712     /* XXX Is the null PL_parser check necessary here? */
5713     assert(PL_parser); /* Let’s find out under debugging builds.  */
5714     if (PL_parser && PL_parser->parsed_sub) {
5715         o = newSTATEOP(0, NULL, NULL);
5716         op_null(o);
5717         retval = op_append_elem(OP_LINESEQ, retval, o);
5718     }
5719
5720     CALL_BLOCK_HOOKS(bhk_pre_end, &retval);
5721
5722     LEAVE_SCOPE(floor);
5723     if (needblockscope)
5724         PL_hints |= HINT_BLOCK_SCOPE; /* propagate out */
5725     o = pad_leavemy();
5726
5727     if (o) {
5728         /* pad_leavemy has created a sequence of introcv ops for all my
5729            subs declared in the block.  We have to replicate that list with
5730            clonecv ops, to deal with this situation:
5731
5732                sub {
5733                    my sub s1;
5734                    my sub s2;
5735                    sub s1 { state sub foo { \&s2 } }
5736                }->()
5737
5738            Originally, I was going to have introcv clone the CV and turn
5739            off the stale flag.  Since &s1 is declared before &s2, the
5740            introcv op for &s1 is executed (on sub entry) before the one for
5741            &s2.  But the &foo sub inside &s1 (which is cloned when &s1 is
5742            cloned, since it is a state sub) closes over &s2 and expects
5743            to see it in its outer CV’s pad.  If the introcv op clones &s1,
5744            then &s2 is still marked stale.  Since &s1 is not active, and
5745            &foo closes over &s1’s implicit entry for &s2, we get a â€˜Varia-
5746            ble will not stay shared’ warning.  Because it is the same stub
5747            that will be used when the introcv op for &s2 is executed, clos-
5748            ing over it is safe.  Hence, we have to turn off the stale flag
5749            on all lexical subs in the block before we clone any of them.
5750            Hence, having introcv clone the sub cannot work.  So we create a
5751            list of ops like this:
5752
5753                lineseq
5754                   |
5755                   +-- introcv
5756                   |
5757                   +-- introcv
5758                   |
5759                   +-- introcv
5760                   |
5761                   .
5762                   .
5763                   .
5764                   |
5765                   +-- clonecv
5766                   |
5767                   +-- clonecv
5768                   |
5769                   +-- clonecv
5770                   |
5771                   .
5772                   .
5773                   .
5774          */
5775         OP *kid = o->op_flags & OPf_KIDS ? cLISTOPo->op_first : o;
5776         OP * const last = o->op_flags & OPf_KIDS ? cLISTOPo->op_last : o;
5777         for (;; kid = OpSIBLING(kid)) {
5778             OP *newkid = newOP(OP_CLONECV, 0);
5779             newkid->op_targ = kid->op_targ;
5780             o = op_append_elem(OP_LINESEQ, o, newkid);
5781             if (kid == last) break;
5782         }
5783         retval = op_prepend_elem(OP_LINESEQ, o, retval);
5784     }
5785
5786     CALL_BLOCK_HOOKS(bhk_post_end, &retval);
5787
5788     return retval;
5789 }
5790
5791 /*
5792 =for apidoc_section Compile-time scope hooks
5793
5794 =for apidoc blockhook_register
5795
5796 Register a set of hooks to be called when the Perl lexical scope changes
5797 at compile time.  See L<perlguts/"Compile-time scope hooks">.
5798
5799 =cut
5800 */
5801
5802 void
5803 Perl_blockhook_register(pTHX_ BHK *hk)
5804 {
5805     PERL_ARGS_ASSERT_BLOCKHOOK_REGISTER;
5806
5807     Perl_av_create_and_push(aTHX_ &PL_blockhooks, newSViv(PTR2IV(hk)));
5808 }
5809
5810 void
5811 Perl_newPROG(pTHX_ OP *o)
5812 {
5813     OP *start;
5814
5815     PERL_ARGS_ASSERT_NEWPROG;
5816
5817     if (PL_in_eval) {
5818         PERL_CONTEXT *cx;
5819         I32 i;
5820         if (PL_eval_root)
5821                 return;
5822         PL_eval_root = newUNOP(OP_LEAVEEVAL,
5823                                ((PL_in_eval & EVAL_KEEPERR)
5824                                 ? OPf_SPECIAL : 0), o);
5825
5826         cx = CX_CUR();
5827         assert(CxTYPE(cx) == CXt_EVAL);
5828
5829         if ((cx->blk_gimme & G_WANT) == G_VOID)
5830             scalarvoid(PL_eval_root);
5831         else if ((cx->blk_gimme & G_WANT) == G_ARRAY)
5832             list(PL_eval_root);
5833         else
5834             scalar(PL_eval_root);
5835
5836         start = op_linklist(PL_eval_root);
5837         PL_eval_root->op_next = 0;
5838         i = PL_savestack_ix;
5839         SAVEFREEOP(o);
5840         ENTER;
5841         S_process_optree(aTHX_ NULL, PL_eval_root, start);
5842         LEAVE;
5843         PL_savestack_ix = i;
5844     }
5845     else {
5846         if (o->op_type == OP_STUB) {
5847             /* This block is entered if nothing is compiled for the main
5848                program. This will be the case for an genuinely empty main
5849                program, or one which only has BEGIN blocks etc, so already
5850                run and freed.
5851
5852                Historically (5.000) the guard above was !o. However, commit
5853                f8a08f7b8bd67b28 (Jun 2001), integrated to blead as
5854                c71fccf11fde0068, changed perly.y so that newPROG() is now
5855                called with the output of block_end(), which returns a new
5856                OP_STUB for the case of an empty optree. ByteLoader (and
5857                maybe other things) also take this path, because they set up
5858                PL_main_start and PL_main_root directly, without generating an
5859                optree.
5860
5861                If the parsing the main program aborts (due to parse errors,
5862                or due to BEGIN or similar calling exit), then newPROG()
5863                isn't even called, and hence this code path and its cleanups
5864                are skipped. This shouldn't make a make a difference:
5865                * a non-zero return from perl_parse is a failure, and
5866                  perl_destruct() should be called immediately.
5867                * however, if exit(0) is called during the parse, then
5868                  perl_parse() returns 0, and perl_run() is called. As
5869                  PL_main_start will be NULL, perl_run() will return
5870                  promptly, and the exit code will remain 0.
5871             */
5872
5873             PL_comppad_name = 0;
5874             PL_compcv = 0;
5875             S_op_destroy(aTHX_ o);
5876             return;
5877         }
5878         PL_main_root = op_scope(sawparens(scalarvoid(o)));
5879         PL_curcop = &PL_compiling;
5880         start = LINKLIST(PL_main_root);
5881         PL_main_root->op_next = 0;
5882         S_process_optree(aTHX_ NULL, PL_main_root, start);
5883         if (!PL_parser->error_count)
5884             /* on error, leave CV slabbed so that ops left lying around
5885              * will eb cleaned up. Else unslab */
5886             cv_forget_slab(PL_compcv);
5887         PL_compcv = 0;
5888
5889         /* Register with debugger */
5890         if (PERLDB_INTER) {
5891             CV * const cv = get_cvs("DB::postponed", 0);
5892             if (cv) {
5893                 dSP;
5894                 PUSHMARK(SP);
5895                 XPUSHs(MUTABLE_SV(CopFILEGV(&PL_compiling)));
5896                 PUTBACK;
5897                 call_sv(MUTABLE_SV(cv), G_DISCARD);
5898             }
5899         }
5900     }
5901 }
5902
5903 OP *
5904 Perl_localize(pTHX_ OP *o, I32 lex)
5905 {
5906     PERL_ARGS_ASSERT_LOCALIZE;
5907
5908     if (o->op_flags & OPf_PARENS)
5909 /* [perl #17376]: this appears to be premature, and results in code such as
5910    C< our(%x); > executing in list mode rather than void mode */
5911 #if 0
5912         list(o);
5913 #else
5914         NOOP;
5915 #endif
5916     else {
5917         if ( PL_parser->bufptr > PL_parser->oldbufptr
5918             && PL_parser->bufptr[-1] == ','
5919             && ckWARN(WARN_PARENTHESIS))
5920         {
5921             char *s = PL_parser->bufptr;
5922             bool sigil = FALSE;
5923
5924             /* some heuristics to detect a potential error */
5925             while (*s && (memCHRs(", \t\n", *s)))
5926                 s++;
5927
5928             while (1) {
5929                 if (*s && (memCHRs("@$%", *s) || (!lex && *s == '*'))
5930                        && *++s
5931                        && (isWORDCHAR(*s) || UTF8_IS_CONTINUED(*s))) {
5932                     s++;
5933                     sigil = TRUE;
5934                     while (*s && (isWORDCHAR(*s) || UTF8_IS_CONTINUED(*s)))
5935                         s++;
5936                     while (*s && (memCHRs(", \t\n", *s)))
5937                         s++;
5938                 }
5939                 else
5940                     break;
5941             }
5942             if (sigil && (*s == ';' || *s == '=')) {
5943                 Perl_warner(aTHX_ packWARN(WARN_PARENTHESIS),
5944                                 "Parentheses missing around \"%s\" list",
5945                                 lex
5946                                     ? (PL_parser->in_my == KEY_our
5947                                         ? "our"
5948                                         : PL_parser->in_my == KEY_state
5949                                             ? "state"
5950                                             : "my")
5951                                     : "local");
5952             }
5953         }
5954     }
5955     if (lex)
5956         o = my(o);
5957     else
5958         o = op_lvalue(o, OP_NULL);              /* a bit kludgey */
5959     PL_parser->in_my = FALSE;
5960     PL_parser->in_my_stash = NULL;
5961     return o;
5962 }
5963
5964 OP *
5965 Perl_jmaybe(pTHX_ OP *o)
5966 {
5967     PERL_ARGS_ASSERT_JMAYBE;
5968
5969     if (o->op_type == OP_LIST) {
5970         if (FEATURE_MULTIDIMENSIONAL_IS_ENABLED) {
5971             OP * const o2
5972                 = newSVREF(newGVOP(OP_GV, 0, gv_fetchpvs(";", GV_ADD|GV_NOTQUAL, SVt_PV)));
5973             o = op_convert_list(OP_JOIN, 0, op_prepend_elem(OP_LIST, o2, o));
5974         }
5975         else {
5976             /* If the user disables this, then a warning might not be enough to alert
5977                them to a possible change of behaviour here, so throw an exception.
5978             */
5979             yyerror("Multidimensional hash lookup is disabled");
5980         }
5981     }
5982     return o;
5983 }
5984
5985 PERL_STATIC_INLINE OP *
5986 S_op_std_init(pTHX_ OP *o)
5987 {
5988     I32 type = o->op_type;
5989
5990     PERL_ARGS_ASSERT_OP_STD_INIT;
5991
5992     if (PL_opargs[type] & OA_RETSCALAR)
5993         scalar(o);
5994     if (PL_opargs[type] & OA_TARGET && !o->op_targ)
5995         o->op_targ = pad_alloc(type, SVs_PADTMP);
5996
5997     return o;
5998 }
5999
6000 PERL_STATIC_INLINE OP *
6001 S_op_integerize(pTHX_ OP *o)
6002 {
6003     I32 type = o->op_type;
6004
6005     PERL_ARGS_ASSERT_OP_INTEGERIZE;
6006
6007     /* integerize op. */
6008     if ((PL_opargs[type] & OA_OTHERINT) && (PL_hints & HINT_INTEGER))
6009     {
6010         o->op_ppaddr = PL_ppaddr[++(o->op_type)];
6011     }
6012
6013     if (type == OP_NEGATE)
6014         /* XXX might want a ck_negate() for this */
6015         cUNOPo->op_first->op_private &= ~OPpCONST_STRICT;
6016
6017     return o;
6018 }
6019
6020 /* This function exists solely to provide a scope to limit
6021    setjmp/longjmp() messing with auto variables.  It cannot be inlined because
6022    it uses setjmp
6023  */
6024 STATIC int
6025 S_fold_constants_eval(pTHX) {
6026     int ret = 0;
6027     dJMPENV;
6028
6029     JMPENV_PUSH(ret);
6030
6031     if (ret == 0) {
6032         CALLRUNOPS(aTHX);
6033     }
6034
6035     JMPENV_POP;
6036
6037     return ret;
6038 }
6039
6040 static OP *
6041 S_fold_constants(pTHX_ OP *const o)
6042 {
6043     OP *curop;
6044     OP *newop;
6045     I32 type = o->op_type;
6046     bool is_stringify;
6047     SV *sv = NULL;
6048     int ret = 0;
6049     OP *old_next;
6050     SV * const oldwarnhook = PL_warnhook;
6051     SV * const olddiehook  = PL_diehook;
6052     COP not_compiling;
6053     U8 oldwarn = PL_dowarn;
6054     I32 old_cxix;
6055
6056     PERL_ARGS_ASSERT_FOLD_CONSTANTS;
6057
6058     if (!(PL_opargs[type] & OA_FOLDCONST))
6059         goto nope;
6060
6061     switch (type) {
6062     case OP_UCFIRST:
6063     case OP_LCFIRST:
6064     case OP_UC:
6065     case OP_LC:
6066     case OP_FC:
6067 #ifdef USE_LOCALE_CTYPE
6068         if (IN_LC_COMPILETIME(LC_CTYPE))
6069             goto nope;
6070 #endif
6071         break;
6072     case OP_SLT:
6073     case OP_SGT:
6074     case OP_SLE:
6075     case OP_SGE:
6076     case OP_SCMP:
6077 #ifdef USE_LOCALE_COLLATE
6078         if (IN_LC_COMPILETIME(LC_COLLATE))
6079             goto nope;
6080 #endif
6081         break;
6082     case OP_SPRINTF:
6083         /* XXX what about the numeric ops? */
6084 #ifdef USE_LOCALE_NUMERIC
6085         if (IN_LC_COMPILETIME(LC_NUMERIC))
6086             goto nope;
6087 #endif
6088         break;
6089     case OP_PACK:
6090         if (!OpHAS_SIBLING(cLISTOPo->op_first)
6091           || OpSIBLING(cLISTOPo->op_first)->op_type != OP_CONST)
6092             goto nope;
6093         {
6094             SV * const sv = cSVOPx_sv(OpSIBLING(cLISTOPo->op_first));
6095             if (!SvPOK(sv) || SvGMAGICAL(sv)) goto nope;
6096             {
6097                 const char *s = SvPVX_const(sv);
6098                 while (s < SvEND(sv)) {
6099                     if (isALPHA_FOLD_EQ(*s, 'p')) goto nope;
6100                     s++;
6101                 }
6102             }
6103         }
6104         break;
6105     case OP_REPEAT:
6106         if (o->op_private & OPpREPEAT_DOLIST) goto nope;
6107         break;
6108     case OP_SREFGEN:
6109         if (cUNOPx(cUNOPo->op_first)->op_first->op_type != OP_CONST
6110          || SvPADTMP(cSVOPx_sv(cUNOPx(cUNOPo->op_first)->op_first)))
6111             goto nope;
6112     }
6113
6114     if (PL_parser && PL_parser->error_count)
6115         goto nope;              /* Don't try to run w/ errors */
6116
6117     for (curop = LINKLIST(o); curop != o; curop = LINKLIST(curop)) {
6118         switch (curop->op_type) {
6119         case OP_CONST:
6120             if (   (curop->op_private & OPpCONST_BARE)
6121                 && (curop->op_private & OPpCONST_STRICT)) {
6122                 no_bareword_allowed(curop);
6123                 goto nope;
6124             }
6125             /* FALLTHROUGH */
6126         case OP_LIST:
6127         case OP_SCALAR:
6128         case OP_NULL:
6129         case OP_PUSHMARK:
6130             /* Foldable; move to next op in list */
6131             break;
6132
6133         default:
6134             /* No other op types are considered foldable */
6135             goto nope;
6136         }
6137     }
6138
6139     curop = LINKLIST(o);
6140     old_next = o->op_next;
6141     o->op_next = 0;
6142     PL_op = curop;
6143
6144     old_cxix = cxstack_ix;
6145     create_eval_scope(NULL, G_FAKINGEVAL);
6146
6147     /* Verify that we don't need to save it:  */
6148     assert(PL_curcop == &PL_compiling);
6149     StructCopy(&PL_compiling, &not_compiling, COP);
6150     PL_curcop = &not_compiling;
6151     /* The above ensures that we run with all the correct hints of the
6152        currently compiling COP, but that IN_PERL_RUNTIME is true. */
6153     assert(IN_PERL_RUNTIME);
6154     PL_warnhook = PERL_WARNHOOK_FATAL;
6155     PL_diehook  = NULL;
6156
6157     /* Effective $^W=1.  */
6158     if ( ! (PL_dowarn & G_WARN_ALL_MASK))
6159         PL_dowarn |= G_WARN_ON;
6160
6161     ret = S_fold_constants_eval(aTHX);
6162
6163     switch (ret) {
6164     case 0:
6165         sv = *(PL_stack_sp--);
6166         if (o->op_targ && sv == PAD_SV(o->op_targ)) {   /* grab pad temp? */
6167             pad_swipe(o->op_targ,  FALSE);
6168         }
6169         else if (SvTEMP(sv)) {                  /* grab mortal temp? */
6170             SvREFCNT_inc_simple_void(sv);
6171             SvTEMP_off(sv);
6172         }
6173         else { assert(SvIMMORTAL(sv)); }
6174         break;
6175     case 3:
6176         /* Something tried to die.  Abandon constant folding.  */
6177         /* Pretend the error never happened.  */
6178         CLEAR_ERRSV();
6179         o->op_next = old_next;
6180         break;
6181     default:
6182         /* Don't expect 1 (setjmp failed) or 2 (something called my_exit)  */
6183         PL_warnhook = oldwarnhook;
6184         PL_diehook  = olddiehook;
6185         /* XXX note that this croak may fail as we've already blown away
6186          * the stack - eg any nested evals */
6187         Perl_croak(aTHX_ "panic: fold_constants JMPENV_PUSH returned %d", ret);
6188     }
6189     PL_dowarn   = oldwarn;
6190     PL_warnhook = oldwarnhook;
6191     PL_diehook  = olddiehook;
6192     PL_curcop = &PL_compiling;
6193
6194     /* if we croaked, depending on how we croaked the eval scope
6195      * may or may not have already been popped */
6196     if (cxstack_ix > old_cxix) {
6197         assert(cxstack_ix == old_cxix + 1);
6198         assert(CxTYPE(CX_CUR()) == CXt_EVAL);
6199         delete_eval_scope();
6200     }
6201     if (ret)
6202         goto nope;
6203
6204     /* OP_STRINGIFY and constant folding are used to implement qq.
6205        Here the constant folding is an implementation detail that we
6206        want to hide.  If the stringify op is itself already marked
6207        folded, however, then it is actually a folded join.  */
6208     is_stringify = type == OP_STRINGIFY && !o->op_folded;
6209     op_free(o);
6210     assert(sv);
6211     if (is_stringify)
6212         SvPADTMP_off(sv);
6213     else if (!SvIMMORTAL(sv)) {
6214         SvPADTMP_on(sv);
6215         SvREADONLY_on(sv);
6216     }
6217     newop = newSVOP(OP_CONST, 0, MUTABLE_SV(sv));
6218     if (!is_stringify) newop->op_folded = 1;
6219     return newop;
6220
6221  nope:
6222     return o;
6223 }
6224
6225 /* convert a constant range in list context into an OP_RV2AV, OP_CONST pair;
6226  * the constant value being an AV holding the flattened range.
6227  */
6228
6229 static void
6230 S_gen_constant_list(pTHX_ OP *o)
6231 {
6232     OP *curop, *old_next;
6233     SV * const oldwarnhook = PL_warnhook;
6234     SV * const olddiehook  = PL_diehook;
6235     COP *old_curcop;
6236     U8 oldwarn = PL_dowarn;
6237     SV **svp;
6238     AV *av;
6239     I32 old_cxix;
6240     COP not_compiling;
6241     int ret = 0;
6242     dJMPENV;
6243     bool op_was_null;
6244
6245     list(o);
6246     if (PL_parser && PL_parser->error_count)
6247         return;         /* Don't attempt to run with errors */
6248
6249     curop = LINKLIST(o);
6250     old_next = o->op_next;
6251     o->op_next = 0;
6252     op_was_null = o->op_type == OP_NULL;
6253     if (op_was_null) /* b3698342565fb462291fba4b432cfcd05b6eb4e1 */
6254         o->op_type = OP_CUSTOM;
6255     CALL_PEEP(curop);
6256     if (op_was_null)
6257         o->op_type = OP_NULL;
6258     S_prune_chain_head(&curop);
6259     PL_op = curop;
6260
6261     old_cxix = cxstack_ix;
6262     create_eval_scope(NULL, G_FAKINGEVAL);
6263
6264     old_curcop = PL_curcop;
6265     StructCopy(old_curcop, &not_compiling, COP);
6266     PL_curcop = &not_compiling;
6267     /* The above ensures that we run with all the correct hints of the
6268        current COP, but that IN_PERL_RUNTIME is true. */
6269     assert(IN_PERL_RUNTIME);
6270     PL_warnhook = PERL_WARNHOOK_FATAL;
6271     PL_diehook  = NULL;
6272     JMPENV_PUSH(ret);
6273
6274     /* Effective $^W=1.  */
6275     if ( ! (PL_dowarn & G_WARN_ALL_MASK))
6276         PL_dowarn |= G_WARN_ON;
6277
6278     switch (ret) {
6279     case 0:
6280 #if defined DEBUGGING && !defined DEBUGGING_RE_ONLY
6281         PL_curstackinfo->si_stack_hwm = 0; /* stop valgrind complaining */
6282 #endif
6283         Perl_pp_pushmark(aTHX);
6284         CALLRUNOPS(aTHX);
6285         PL_op = curop;
6286         assert (!(curop->op_flags & OPf_SPECIAL));
6287         assert(curop->op_type == OP_RANGE);
6288         Perl_pp_anonlist(aTHX);
6289         break;
6290     case 3:
6291         CLEAR_ERRSV();
6292         o->op_next = old_next;
6293         break;
6294     default:
6295         JMPENV_POP;
6296         PL_warnhook = oldwarnhook;
6297         PL_diehook = olddiehook;
6298         Perl_croak(aTHX_ "panic: gen_constant_list JMPENV_PUSH returned %d",
6299             ret);
6300     }
6301
6302     JMPENV_POP;
6303     PL_dowarn = oldwarn;
6304     PL_warnhook = oldwarnhook;
6305     PL_diehook = olddiehook;
6306     PL_curcop = old_curcop;
6307
6308     if (cxstack_ix > old_cxix) {
6309         assert(cxstack_ix == old_cxix + 1);
6310         assert(CxTYPE(CX_CUR()) == CXt_EVAL);
6311         delete_eval_scope();
6312     }
6313     if (ret)
6314         return;
6315
6316     OpTYPE_set(o, OP_RV2AV);
6317     o->op_flags &= ~OPf_REF;    /* treat \(1..2) like an ordinary list */
6318     o->op_flags |= OPf_PARENS;  /* and flatten \(1..2,3) */
6319     o->op_opt = 0;              /* needs to be revisited in rpeep() */
6320     av = (AV *)SvREFCNT_inc_NN(*PL_stack_sp--);
6321
6322     /* replace subtree with an OP_CONST */
6323     curop = ((UNOP*)o)->op_first;
6324     op_sibling_splice(o, NULL, -1, newSVOP(OP_CONST, 0, (SV *)av));
6325     op_free(curop);
6326
6327     if (AvFILLp(av) != -1)
6328         for (svp = AvARRAY(av) + AvFILLp(av); svp >= AvARRAY(av); --svp)
6329         {
6330             SvPADTMP_on(*svp);
6331             SvREADONLY_on(*svp);
6332         }
6333     LINKLIST(o);
6334     list(o);
6335     return;
6336 }
6337
6338 /*
6339 =for apidoc_section Optree Manipulation Functions
6340 */
6341
6342 /* List constructors */
6343
6344 /*
6345 =for apidoc op_append_elem
6346
6347 Append an item to the list of ops contained directly within a list-type
6348 op, returning the lengthened list.  C<first> is the list-type op,
6349 and C<last> is the op to append to the list.  C<optype> specifies the
6350 intended opcode for the list.  If C<first> is not already a list of the
6351 right type, it will be upgraded into one.  If either C<first> or C<last>
6352 is null, the other is returned unchanged.
6353
6354 =cut
6355 */
6356
6357 OP *
6358 Perl_op_append_elem(pTHX_ I32 type, OP *first, OP *last)
6359 {
6360     if (!first)
6361         return last;
6362
6363     if (!last)
6364         return first;
6365
6366     if (first->op_type != (unsigned)type
6367         || (type == OP_LIST && (first->op_flags & OPf_PARENS)))
6368     {
6369         return newLISTOP(type, 0, first, last);
6370     }
6371
6372     op_sibling_splice(first, ((LISTOP*)first)->op_last, 0, last);
6373     first->op_flags |= OPf_KIDS;
6374     return first;
6375 }
6376
6377 /*
6378 =for apidoc op_append_list
6379
6380 Concatenate the lists of ops contained directly within two list-type ops,
6381 returning the combined list.  C<first> and C<last> are the list-type ops
6382 to concatenate.  C<optype> specifies the intended opcode for the list.
6383 If either C<first> or C<last> is not already a list of the right type,
6384 it will be upgraded into one.  If either C<first> or C<last> is null,
6385 the other is returned unchanged.
6386
6387 =cut
6388 */
6389
6390 OP *
6391 Perl_op_append_list(pTHX_ I32 type, OP *first, OP *last)
6392 {
6393     if (!first)
6394         return last;
6395
6396     if (!last)
6397         return first;
6398
6399     if (first->op_type != (unsigned)type)
6400         return op_prepend_elem(type, first, last);
6401
6402     if (last->op_type != (unsigned)type)
6403         return op_append_elem(type, first, last);
6404
6405     OpMORESIB_set(((LISTOP*)first)->op_last, ((LISTOP*)last)->op_first);
6406     ((LISTOP*)first)->op_last = ((LISTOP*)last)->op_last;
6407     OpLASTSIB_set(((LISTOP*)first)->op_last, first);
6408     first->op_flags |= (last->op_flags & OPf_KIDS);
6409
6410     S_op_destroy(aTHX_ last);
6411
6412     return first;
6413 }
6414
6415 /*
6416 =for apidoc op_prepend_elem
6417
6418 Prepend an item to the list of ops contained directly within a list-type
6419 op, returning the lengthened list.  C<first> is the op to prepend to the
6420 list, and C<last> is the list-type op.  C<optype> specifies the intended
6421 opcode for the list.  If C<last> is not already a list of the right type,
6422 it will be upgraded into one.  If either C<first> or C<last> is null,
6423 the other is returned unchanged.
6424
6425 =cut
6426 */
6427
6428 OP *
6429 Perl_op_prepend_elem(pTHX_ I32 type, OP *first, OP *last)
6430 {
6431     if (!first)
6432         return last;
6433
6434     if (!last)
6435         return first;
6436
6437     if (last->op_type == (unsigned)type) {
6438         if (type == OP_LIST) {  /* already a PUSHMARK there */
6439             /* insert 'first' after pushmark */
6440             op_sibling_splice(last, cLISTOPx(last)->op_first, 0, first);
6441             if (!(first->op_flags & OPf_PARENS))
6442                 last->op_flags &= ~OPf_PARENS;
6443         }
6444         else
6445             op_sibling_splice(last, NULL, 0, first);
6446         last->op_flags |= OPf_KIDS;
6447         return last;
6448     }
6449
6450     return newLISTOP(type, 0, first, last);
6451 }
6452
6453 /*
6454 =for apidoc op_convert_list
6455
6456 Converts C<o> into a list op if it is not one already, and then converts it
6457 into the specified C<type>, calling its check function, allocating a target if
6458 it needs one, and folding constants.
6459
6460 A list-type op is usually constructed one kid at a time via C<newLISTOP>,
6461 C<op_prepend_elem> and C<op_append_elem>.  Then finally it is passed to
6462 C<op_convert_list> to make it the right type.
6463
6464 =cut
6465 */
6466
6467 OP *
6468 Perl_op_convert_list(pTHX_ I32 type, I32 flags, OP *o)
6469 {
6470     if (type < 0) type = -type, flags |= OPf_SPECIAL;
6471     if (!o || o->op_type != OP_LIST)
6472         o = force_list(o, 0);
6473     else
6474     {
6475         o->op_flags &= ~OPf_WANT;
6476         o->op_private &= ~OPpLVAL_INTRO;
6477     }
6478
6479     if (!(PL_opargs[type] & OA_MARK))
6480         op_null(cLISTOPo->op_first);
6481     else {
6482         OP * const kid2 = OpSIBLING(cLISTOPo->op_first);
6483         if (kid2 && kid2->op_type == OP_COREARGS) {
6484             op_null(cLISTOPo->op_first);
6485             kid2->op_private |= OPpCOREARGS_PUSHMARK;
6486         }
6487     }
6488
6489     if (type != OP_SPLIT)
6490         /* At this point o is a LISTOP, but OP_SPLIT is a PMOP; let
6491          * ck_split() create a real PMOP and leave the op's type as listop
6492          * for now. Otherwise op_free() etc will crash.
6493          */
6494         OpTYPE_set(o, type);
6495
6496     o->op_flags |= flags;
6497     if (flags & OPf_FOLDED)
6498         o->op_folded = 1;
6499
6500     o = CHECKOP(type, o);
6501     if (o->op_type != (unsigned)type)
6502         return o;
6503
6504     return fold_constants(op_integerize(op_std_init(o)));
6505 }
6506
6507 /* Constructors */
6508
6509
6510 /*
6511 =for apidoc_section Optree construction
6512
6513 =for apidoc newNULLLIST
6514
6515 Constructs, checks, and returns a new C<stub> op, which represents an
6516 empty list expression.
6517
6518 =cut
6519 */
6520
6521 OP *
6522 Perl_newNULLLIST(pTHX)
6523 {
6524     return newOP(OP_STUB, 0);
6525 }
6526
6527 /* promote o and any siblings to be a list if its not already; i.e.
6528  *
6529  *  o - A - B
6530  *
6531  * becomes
6532  *
6533  *  list
6534  *    |
6535  *  pushmark - o - A - B
6536  *
6537  * If nullit it true, the list op is nulled.
6538  */
6539
6540 static OP *
6541 S_force_list(pTHX_ OP *o, bool nullit)
6542 {
6543     if (!o || o->op_type != OP_LIST) {
6544         OP *rest = NULL;
6545         if (o) {
6546             /* manually detach any siblings then add them back later */
6547             rest = OpSIBLING(o);
6548             OpLASTSIB_set(o, NULL);
6549         }
6550         o = newLISTOP(OP_LIST, 0, o, NULL);
6551         if (rest)
6552             op_sibling_splice(o, cLISTOPo->op_last, 0, rest);
6553     }
6554     if (nullit)
6555         op_null(o);
6556     return o;
6557 }
6558
6559 /*
6560 =for apidoc newLISTOP
6561
6562 Constructs, checks, and returns an op of any list type.  C<type> is
6563 the opcode.  C<flags> gives the eight bits of C<op_flags>, except that
6564 C<OPf_KIDS> will be set automatically if required.  C<first> and C<last>
6565 supply up to two ops to be direct children of the list op; they are
6566 consumed by this function and become part of the constructed op tree.
6567
6568 For most list operators, the check function expects all the kid ops to be
6569 present already, so calling C<newLISTOP(OP_JOIN, ...)> (e.g.) is not
6570 appropriate.  What you want to do in that case is create an op of type
6571 C<OP_LIST>, append more children to it, and then call L</op_convert_list>.
6572 See L</op_convert_list> for more information.
6573
6574
6575 =cut
6576 */
6577
6578 OP *
6579 Perl_newLISTOP(pTHX_ I32 type, I32 flags, OP *first, OP *last)
6580 {
6581     LISTOP *listop;
6582     /* Note that allocating an OP_PUSHMARK can die under Safe.pm if
6583      * pushmark is banned. So do it now while existing ops are in a
6584      * consistent state, in case they suddenly get freed */
6585     OP* const pushop = type == OP_LIST ? newOP(OP_PUSHMARK, 0) : NULL;
6586
6587     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_LISTOP
6588         || type == OP_CUSTOM);
6589
6590     NewOp(1101, listop, 1, LISTOP);
6591     OpTYPE_set(listop, type);
6592     if (first || last)
6593         flags |= OPf_KIDS;
6594     listop->op_flags = (U8)flags;
6595
6596     if (!last && first)
6597         last = first;
6598     else if (!first && last)
6599         first = last;
6600     else if (first)
6601         OpMORESIB_set(first, last);
6602     listop->op_first = first;
6603     listop->op_last = last;
6604
6605     if (pushop) {
6606         OpMORESIB_set(pushop, first);
6607         listop->op_first = pushop;
6608         listop->op_flags |= OPf_KIDS;
6609         if (!last)
6610             listop->op_last = pushop;
6611     }
6612     if (listop->op_last)
6613         OpLASTSIB_set(listop->op_last, (OP*)listop);
6614
6615     return CHECKOP(type, listop);
6616 }
6617
6618 /*
6619 =for apidoc newOP
6620
6621 Constructs, checks, and returns an op of any base type (any type that
6622 has no extra fields).  C<type> is the opcode.  C<flags> gives the
6623 eight bits of C<op_flags>, and, shifted up eight bits, the eight bits
6624 of C<op_private>.
6625
6626 =cut
6627 */
6628
6629 OP *
6630 Perl_newOP(pTHX_ I32 type, I32 flags)
6631 {
6632     OP *o;
6633
6634     if (type == -OP_ENTEREVAL) {
6635         type = OP_ENTEREVAL;
6636         flags |= OPpEVAL_BYTES<<8;
6637     }
6638
6639     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_BASEOP
6640         || (PL_opargs[type] & OA_CLASS_MASK) == OA_BASEOP_OR_UNOP
6641         || (PL_opargs[type] & OA_CLASS_MASK) == OA_FILESTATOP
6642         || (PL_opargs[type] & OA_CLASS_MASK) == OA_LOOPEXOP);
6643
6644     NewOp(1101, o, 1, OP);
6645     OpTYPE_set(o, type);
6646     o->op_flags = (U8)flags;
6647
6648     o->op_next = o;
6649     o->op_private = (U8)(0 | (flags >> 8));
6650     if (PL_opargs[type] & OA_RETSCALAR)
6651         scalar(o);
6652     if (PL_opargs[type] & OA_TARGET)
6653         o->op_targ = pad_alloc(type, SVs_PADTMP);
6654     return CHECKOP(type, o);
6655 }
6656
6657 /*
6658 =for apidoc newUNOP
6659
6660 Constructs, checks, and returns an op of any unary type.  C<type> is
6661 the opcode.  C<flags> gives the eight bits of C<op_flags>, except that
6662 C<OPf_KIDS> will be set automatically if required, and, shifted up eight
6663 bits, the eight bits of C<op_private>, except that the bit with value 1
6664 is automatically set.  C<first> supplies an optional op to be the direct
6665 child of the unary op; it is consumed by this function and become part
6666 of the constructed op tree.
6667
6668 =for apidoc Amnh||OPf_KIDS
6669
6670 =cut
6671 */
6672
6673 OP *
6674 Perl_newUNOP(pTHX_ I32 type, I32 flags, OP *first)
6675 {
6676     UNOP *unop;
6677
6678     if (type == -OP_ENTEREVAL) {
6679         type = OP_ENTEREVAL;
6680         flags |= OPpEVAL_BYTES<<8;
6681     }
6682
6683     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_UNOP
6684         || (PL_opargs[type] & OA_CLASS_MASK) == OA_BASEOP_OR_UNOP
6685         || (PL_opargs[type] & OA_CLASS_MASK) == OA_FILESTATOP
6686         || (PL_opargs[type] & OA_CLASS_MASK) == OA_LOOPEXOP
6687         || type == OP_SASSIGN
6688         || type == OP_ENTERTRY
6689         || type == OP_CUSTOM
6690         || type == OP_NULL );
6691
6692     if (!first)
6693         first = newOP(OP_STUB, 0);
6694     if (PL_opargs[type] & OA_MARK)
6695         first = force_list(first, 1);
6696
6697     NewOp(1101, unop, 1, UNOP);
6698     OpTYPE_set(unop, type);
6699     unop->op_first = first;
6700     unop->op_flags = (U8)(flags | OPf_KIDS);
6701     unop->op_private = (U8)(1 | (flags >> 8));
6702
6703     if (!OpHAS_SIBLING(first)) /* true unless weird syntax error */
6704         OpLASTSIB_set(first, (OP*)unop);
6705
6706     unop = (UNOP*) CHECKOP(type, unop);
6707     if (unop->op_next)
6708         return (OP*)unop;
6709
6710     return fold_constants(op_integerize(op_std_init((OP *) unop)));
6711 }
6712
6713 /*
6714 =for apidoc newUNOP_AUX
6715
6716 Similar to C<newUNOP>, but creates an C<UNOP_AUX> struct instead, with C<op_aux>
6717 initialised to C<aux>
6718
6719 =cut
6720 */
6721
6722 OP *
6723 Perl_newUNOP_AUX(pTHX_ I32 type, I32 flags, OP *first, UNOP_AUX_item *aux)
6724 {
6725     UNOP_AUX *unop;
6726
6727     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_UNOP_AUX
6728         || type == OP_CUSTOM);
6729
6730     NewOp(1101, unop, 1, UNOP_AUX);
6731     unop->op_type = (OPCODE)type;
6732     unop->op_ppaddr = PL_ppaddr[type];
6733     unop->op_first = first;
6734     unop->op_flags = (U8)(flags | (first ? OPf_KIDS : 0));
6735     unop->op_private = (U8)((first ? 1 : 0) | (flags >> 8));
6736     unop->op_aux = aux;
6737
6738     if (first && !OpHAS_SIBLING(first)) /* true unless weird syntax error */
6739         OpLASTSIB_set(first, (OP*)unop);
6740
6741     unop = (UNOP_AUX*) CHECKOP(type, unop);
6742
6743     return op_std_init((OP *) unop);
6744 }
6745
6746 /*
6747 =for apidoc newMETHOP
6748
6749 Constructs, checks, and returns an op of method type with a method name
6750 evaluated at runtime.  C<type> is the opcode.  C<flags> gives the eight
6751 bits of C<op_flags>, except that C<OPf_KIDS> will be set automatically,
6752 and, shifted up eight bits, the eight bits of C<op_private>, except that
6753 the bit with value 1 is automatically set.  C<dynamic_meth> supplies an
6754 op which evaluates method name; it is consumed by this function and
6755 become part of the constructed op tree.
6756 Supported optypes: C<OP_METHOD>.
6757
6758 =cut
6759 */
6760
6761 static OP*
6762 S_newMETHOP_internal(pTHX_ I32 type, I32 flags, OP* dynamic_meth, SV* const_meth) {
6763     METHOP *methop;
6764
6765     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_METHOP
6766         || type == OP_CUSTOM);
6767
6768     NewOp(1101, methop, 1, METHOP);
6769     if (dynamic_meth) {
6770         if (PL_opargs[type] & OA_MARK) dynamic_meth = force_list(dynamic_meth, 1);
6771         methop->op_flags = (U8)(flags | OPf_KIDS);
6772         methop->op_u.op_first = dynamic_meth;
6773         methop->op_private = (U8)(1 | (flags >> 8));
6774
6775         if (!OpHAS_SIBLING(dynamic_meth))
6776             OpLASTSIB_set(dynamic_meth, (OP*)methop);
6777     }
6778     else {
6779         assert(const_meth);
6780         methop->op_flags = (U8)(flags & ~OPf_KIDS);
6781         methop->op_u.op_meth_sv = const_meth;
6782         methop->op_private = (U8)(0 | (flags >> 8));
6783         methop->op_next = (OP*)methop;
6784     }
6785
6786 #ifdef USE_ITHREADS
6787     methop->op_rclass_targ = 0;
6788 #else
6789     methop->op_rclass_sv = NULL;
6790 #endif
6791
6792     OpTYPE_set(methop, type);
6793     return CHECKOP(type, methop);
6794 }
6795
6796 OP *
6797 Perl_newMETHOP (pTHX_ I32 type, I32 flags, OP* dynamic_meth) {
6798     PERL_ARGS_ASSERT_NEWMETHOP;
6799     return newMETHOP_internal(type, flags, dynamic_meth, NULL);
6800 }
6801
6802 /*
6803 =for apidoc newMETHOP_named
6804
6805 Constructs, checks, and returns an op of method type with a constant
6806 method name.  C<type> is the opcode.  C<flags> gives the eight bits of
6807 C<op_flags>, and, shifted up eight bits, the eight bits of
6808 C<op_private>.  C<const_meth> supplies a constant method name;
6809 it must be a shared COW string.
6810 Supported optypes: C<OP_METHOD_NAMED>.
6811
6812 =cut
6813 */
6814
6815 OP *
6816 Perl_newMETHOP_named (pTHX_ I32 type, I32 flags, SV* const_meth) {
6817     PERL_ARGS_ASSERT_NEWMETHOP_NAMED;
6818     return newMETHOP_internal(type, flags, NULL, const_meth);
6819 }
6820
6821 /*
6822 =for apidoc newBINOP
6823
6824 Constructs, checks, and returns an op of any binary type.  C<type>
6825 is the opcode.  C<flags> gives the eight bits of C<op_flags>, except
6826 that C<OPf_KIDS> will be set automatically, and, shifted up eight bits,
6827 the eight bits of C<op_private>, except that the bit with value 1 or
6828 2 is automatically set as required.  C<first> and C<last> supply up to
6829 two ops to be the direct children of the binary op; they are consumed
6830 by this function and become part of the constructed op tree.
6831
6832 =cut
6833 */
6834
6835 OP *
6836 Perl_newBINOP(pTHX_ I32 type, I32 flags, OP *first, OP *last)
6837 {
6838     BINOP *binop;
6839
6840     ASSUME((PL_opargs[type] & OA_CLASS_MASK) == OA_BINOP
6841         || type == OP_NULL || type == OP_CUSTOM);
6842
6843     NewOp(1101, binop, 1, BINOP);
6844
6845     if (!first)
6846         first = newOP(OP_NULL, 0);
6847
6848     OpTYPE_set(binop, type);
6849     binop->op_first = first;
6850     binop->op_flags = (U8)(flags | OPf_KIDS);
6851     if (!last) {
6852         last = first;
6853         binop->op_private = (U8)(1 | (flags >> 8));
6854     }
6855     else {
6856         binop->op_private = (U8)(2 | (flags >> 8));
6857         OpMORESIB_set(first, last);
6858     }
6859
6860     if (!OpHAS_SIBLING(last)) /* true unless weird syntax error */
6861         OpLASTSIB_set(last, (OP*)binop);
6862
6863     binop->op_last = OpSIBLING(binop->op_first);
6864     if (binop->op_last)
6865         OpLASTSIB_set(binop->op_last, (OP*)binop);
6866
6867     binop = (BINOP*)CHECKOP(type, binop);
6868     if (binop->op_next || binop->op_type != (OPCODE)type)
6869         return (OP*)binop;
6870
6871     return fold_constants(op_integerize(op_std_init((OP *)binop)));
6872 }
6873
6874 void
6875 Perl_invmap_dump(pTHX_ SV* invlist, UV *map)
6876 {
6877     const char indent[] = "    ";
6878
6879     UV len = _invlist_len(invlist);
6880     UV * array = invlist_array(invlist);
6881     UV i;
6882
6883     PERL_ARGS_ASSERT_INVMAP_DUMP;
6884
6885     for (i = 0; i < len; i++) {
6886         UV start = array[i];
6887         UV end   = (i + 1 < len) ? array[i+1] - 1 : IV_MAX;
6888
6889         PerlIO_printf(Perl_debug_log, "%s[%" UVuf "] 0x%04" UVXf, indent, i, start);
6890         if (end == IV_MAX) {
6891             PerlIO_printf(Perl_debug_log, " .. INFTY");
6892         }
6893         else if (end != start) {
6894             PerlIO_printf(Perl_debug_log, " .. 0x%04" UVXf, end);
6895         }
6896         else {
6897             PerlIO_printf(Perl_debug_log, "            ");
6898         }
6899
6900         PerlIO_printf(Perl_debug_log, "\t");
6901
6902         if (map[i] == TR_UNLISTED) {
6903             PerlIO_printf(Perl_debug_log, "TR_UNLISTED\n");
6904         }
6905         else if (map[i] == TR_SPECIAL_HANDLING) {
6906             PerlIO_printf(Perl_debug_log, "TR_SPECIAL_HANDLING\n");
6907         }
6908         else {
6909             PerlIO_printf(Perl_debug_log, "0x%04" UVXf "\n", map[i]);
6910         }
6911     }
6912 }
6913
6914 /* Given an OP_TRANS / OP_TRANSR op o, plus OP_CONST ops expr and repl
6915  * containing the search and replacement strings, assemble into
6916  * a translation table attached as o->op_pv.
6917  * Free expr and repl.
6918  * It expects the toker to have already set the
6919  *   OPpTRANS_COMPLEMENT
6920  *   OPpTRANS_SQUASH
6921  *   OPpTRANS_DELETE
6922  * flags as appropriate; this function may add
6923  *   OPpTRANS_USE_SVOP
6924  *   OPpTRANS_CAN_FORCE_UTF8
6925  *   OPpTRANS_IDENTICAL
6926  *   OPpTRANS_GROWS
6927  * flags
6928  */
6929
6930 static OP *
6931 S_pmtrans(pTHX_ OP *o, OP *expr, OP *repl)
6932 {
6933     /* This function compiles a tr///, from data gathered from toke.c, into a
6934      * form suitable for use by do_trans() in doop.c at runtime.
6935      *
6936      * It first normalizes the data, while discarding extraneous inputs; then
6937      * writes out the compiled data.  The normalization allows for complete
6938      * analysis, and avoids some false negatives and positives earlier versions
6939      * of this code had.
6940      *
6941      * The normalization form is an inversion map (described below in detail).
6942      * This is essentially the compiled form for tr///'s that require UTF-8,
6943      * and its easy to use it to write the 257-byte table for tr///'s that
6944      * don't need UTF-8.  That table is identical to what's been in use for
6945      * many perl versions, except that it doesn't handle some edge cases that
6946      * it used to, involving code points above 255.  The UTF-8 form now handles
6947      * these.  (This could be changed with extra coding should it shown to be
6948      * desirable.)
6949      *
6950      * If the complement (/c) option is specified, the lhs string (tstr) is
6951      * parsed into an inversion list.  Complementing these is trivial.  Then a
6952      * complemented tstr is built from that, and used thenceforth.  This hides
6953      * the fact that it was complemented from almost all successive code.
6954      *
6955      * One of the important characteristics to know about the input is whether
6956      * the transliteration may be done in place, or does a temporary need to be
6957      * allocated, then copied.  If the replacement for every character in every
6958      * possible string takes up no more bytes than the character it
6959      * replaces, then it can be edited in place.  Otherwise the replacement
6960      * could overwrite a byte we are about to read, depending on the strings
6961      * being processed.  The comments and variable names here refer to this as
6962      * "growing".  Some inputs won't grow, and might even shrink under /d, but
6963      * some inputs could grow, so we have to assume any given one might grow.
6964      * On very long inputs, the temporary could eat up a lot of memory, so we
6965      * want to avoid it if possible.  For non-UTF-8 inputs, everything is
6966      * single-byte, so can be edited in place, unless there is something in the
6967      * pattern that could force it into UTF-8.  The inversion map makes it
6968      * feasible to determine this.  Previous versions of this code pretty much
6969      * punted on determining if UTF-8 could be edited in place.  Now, this code
6970      * is rigorous in making that determination.
6971      *
6972      * Another characteristic we need to know is whether the lhs and rhs are
6973      * identical.  If so, and no other flags are present, the only effect of
6974      * the tr/// is to count the characters present in the input that are
6975      * mentioned in the lhs string.  The implementation of that is easier and
6976      * runs faster than the more general case.  Normalizing here allows for
6977      * accurate determination of this.  Previously there were false negatives
6978      * possible.
6979      *
6980      * Instead of 'transliterated', the comments here use 'unmapped' for the
6981      * characters that are left unchanged by the operation; otherwise they are
6982      * 'mapped'
6983      *
6984      * The lhs of the tr/// is here referred to as the t side.
6985      * The rhs of the tr/// is here referred to as the r side.
6986      */
6987
6988     SV * const tstr = ((SVOP*)expr)->op_sv;
6989     SV * const rstr = ((SVOP*)repl)->op_sv;
6990     STRLEN tlen;
6991     STRLEN rlen;
6992     const U8 * t0 = (U8*)SvPV_const(tstr, tlen);
6993     const U8 * r0 = (U8*)SvPV_const(rstr, rlen);
6994     const U8 * t = t0;
6995     const U8 * r = r0;
6996     UV t_count = 0, r_count = 0;  /* Number of characters in search and
6997                                          replacement lists */
6998
6999     /* khw thinks some of the private flags for this op are quaintly named.
7000      * OPpTRANS_GROWS for example is TRUE if the replacement for some lhs
7001      * character when represented in UTF-8 is longer than the original
7002      * character's UTF-8 representation */
7003     const bool complement = cBOOL(o->op_private & OPpTRANS_COMPLEMENT);
7004     const bool squash     = cBOOL(o->op_private & OPpTRANS_SQUASH);
7005     const bool del        = cBOOL(o->op_private & OPpTRANS_DELETE);
7006
7007     /* Set to true if there is some character < 256 in the lhs that maps to
7008      * above 255.  If so, a non-UTF-8 match string can be forced into being in
7009      * UTF-8 by a tr/// operation. */
7010     bool can_force_utf8 = FALSE;
7011
7012     /* What is the maximum expansion factor in UTF-8 transliterations.  If a
7013      * 2-byte UTF-8 encoded character is to be replaced by a 3-byte one, its
7014      * expansion factor is 1.5.  This number is used at runtime to calculate
7015      * how much space to allocate for non-inplace transliterations.  Without
7016      * this number, the worst case is 14, which is extremely unlikely to happen
7017      * in real life, and could require significant memory overhead. */
7018     NV max_expansion = 1.;
7019
7020     UV t_range_count, r_range_count, min_range_count;
7021     UV* t_array;
7022     SV* t_invlist;
7023     UV* r_map;
7024     UV r_cp, t_cp;
7025     UV t_cp_end = (UV) -1;
7026     UV r_cp_end;
7027     Size_t len;
7028     AV* invmap;
7029     UV final_map = TR_UNLISTED;    /* The final character in the replacement
7030                                       list, updated as we go along.  Initialize
7031                                       to something illegal */
7032
7033     bool rstr_utf8 = cBOOL(SvUTF8(rstr));
7034     bool tstr_utf8 = cBOOL(SvUTF8(tstr));
7035
7036     const U8* tend = t + tlen;
7037     const U8* rend = r + rlen;
7038
7039     SV * inverted_tstr = NULL;
7040
7041     Size_t i;
7042     unsigned int pass2;
7043
7044     /* This routine implements detection of a transliteration having a longer
7045      * UTF-8 representation than its source, by partitioning all the possible
7046      * code points of the platform into equivalence classes of the same UTF-8
7047      * byte length in the first pass.  As it constructs the mappings, it carves
7048      * these up into smaller chunks, but doesn't merge any together.  This
7049      * makes it easy to find the instances it's looking for.  A second pass is
7050      * done after this has been determined which merges things together to
7051      * shrink the table for runtime.  The table below is used for both ASCII
7052      * and EBCDIC platforms.  On EBCDIC, the byte length is not monotonically
7053      * increasing for code points below 256.  To correct for that, the macro
7054      * CP_ADJUST defined below converts those code points to ASCII in the first
7055      * pass, and we use the ASCII partition values.  That works because the
7056      * growth factor will be unaffected, which is all that is calculated during
7057      * the first pass. */
7058     UV PL_partition_by_byte_length[] = {
7059         0,
7060         0x80,   /* Below this is 1 byte representations */
7061         (32 * (1UL << (    UTF_ACCUMULATION_SHIFT))),   /* 2 bytes below this */
7062         (16 * (1UL << (2 * UTF_ACCUMULATION_SHIFT))),   /* 3 bytes below this */
7063         ( 8 * (1UL << (3 * UTF_ACCUMULATION_SHIFT))),   /* 4 bytes below this */
7064         ( 4 * (1UL << (4 * UTF_ACCUMULATION_SHIFT))),   /* 5 bytes below this */
7065         ( 2 * (1UL << (5 * UTF_ACCUMULATION_SHIFT)))    /* 6 bytes below this */
7066
7067 #  ifdef UV_IS_QUAD
7068                                                     ,
7069         ( ((UV) 1U << (6 * UTF_ACCUMULATION_SHIFT)))    /* 7 bytes below this */
7070 #  endif
7071
7072     };
7073
7074     PERL_ARGS_ASSERT_PMTRANS;
7075
7076     PL_hints |= HINT_BLOCK_SCOPE;
7077
7078     /* If /c, the search list is sorted and complemented.  This is now done by
7079      * creating an inversion list from it, and then trivially inverting that.
7080      * The previous implementation used qsort, but creating the list
7081      * automatically keeps it sorted as we go along */
7082     if (complement) {
7083         UV start, end;
7084         SV * inverted_tlist = _new_invlist(tlen);
7085         Size_t temp_len;
7086
7087         DEBUG_y(PerlIO_printf(Perl_debug_log,
7088                     "%s: %d: tstr before inversion=\n%s\n",
7089                     __FILE__, __LINE__, _byte_dump_string(t, tend - t, 0)));
7090
7091         while (t < tend) {
7092
7093             /* Non-utf8 strings don't have ranges, so each character is listed
7094              * out */
7095             if (! tstr_utf8) {
7096                 inverted_tlist = add_cp_to_invlist(inverted_tlist, *t);
7097                 t++;
7098             }
7099             else {  /* But UTF-8 strings have been parsed in toke.c to have
7100                  * ranges if appropriate. */
7101                 UV t_cp;
7102                 Size_t t_char_len;
7103
7104                 /* Get the first character */
7105                 t_cp = valid_utf8_to_uvchr(t, &t_char_len);
7106                 t += t_char_len;
7107
7108                 /* If the next byte indicates that this wasn't the first
7109                  * element of a range, the range is just this one */
7110                 if (t >= tend || *t != RANGE_INDICATOR) {
7111                     inverted_tlist = add_cp_to_invlist(inverted_tlist, t_cp);
7112                 }
7113                 else { /* Otherwise, ignore the indicator byte, and get the
7114                           final element, and add the whole range */
7115                     t++;
7116                     t_cp_end = valid_utf8_to_uvchr(t, &t_char_len);
7117                     t += t_char_len;
7118
7119                     inverted_tlist = _add_range_to_invlist(inverted_tlist,
7120                                                       t_cp, t_cp_end);
7121                 }
7122             }
7123         } /* End of parse through tstr */
7124
7125         /* The inversion list is done; now invert it */
7126         _invlist_invert(inverted_tlist);
7127
7128         /* Now go through the inverted list and create a new tstr for the rest
7129          * of the routine to use.  Since the UTF-8 version can have ranges, and
7130          * can be much more compact than the non-UTF-8 version, we create the
7131          * string in UTF-8 even if not necessary.  (This is just an intermediate
7132          * value that gets thrown away anyway.) */
7133         invlist_iterinit(inverted_tlist);
7134         inverted_tstr = newSVpvs("");
7135         while (invlist_iternext(inverted_tlist, &start, &end)) {
7136             U8 temp[UTF8_MAXBYTES];
7137             U8 * temp_end_pos;
7138
7139             /* IV_MAX keeps things from going out of bounds */
7140             start = MIN(IV_MAX, start);
7141             end   = MIN(IV_MAX, end);
7142
7143             temp_end_pos = uvchr_to_utf8(temp, start);
7144             sv_catpvn(inverted_tstr, (char *) temp, temp_end_pos - temp);
7145
7146             if (start != end) {
7147                 Perl_sv_catpvf(aTHX_ inverted_tstr, "%c", RANGE_INDICATOR);
7148                 temp_end_pos = uvchr_to_utf8(temp, end);
7149                 sv_catpvn(inverted_tstr, (char *) temp, temp_end_pos - temp);
7150             }
7151         }
7152
7153         /* Set up so the remainder of the routine uses this complement, instead
7154          * of the actual input */
7155         t0 = t = (U8*)SvPV_const(inverted_tstr, temp_len);
7156         tend = t0 + temp_len;
7157         tstr_utf8 = TRUE;
7158
7159         SvREFCNT_dec_NN(inverted_tlist);
7160     }
7161
7162     /* For non-/d, an empty rhs means to use the lhs */
7163     if (rlen == 0 && ! del) {
7164         r0 = t0;
7165         rend = tend;
7166         rstr_utf8  = tstr_utf8;
7167     }
7168
7169     t_invlist = _new_invlist(1);
7170
7171     /* Initialize to a single range */
7172     t_invlist = _add_range_to_invlist(t_invlist, 0, UV_MAX);
7173
7174     /* For the first pass, the lhs is partitioned such that the
7175      * number of UTF-8 bytes required to represent a code point in each
7176      * partition is the same as the number for any other code point in
7177      * that partion.  We copy the pre-compiled partion. */
7178     len = C_ARRAY_LENGTH(PL_partition_by_byte_length);
7179     invlist_extend(t_invlist, len);
7180     t_array = invlist_array(t_invlist);
7181     Copy(PL_partition_by_byte_length, t_array, len, UV);
7182     invlist_set_len(t_invlist, len, *(get_invlist_offset_addr(t_invlist)));
7183     Newx(r_map, len + 1, UV);
7184
7185     /* Parse the (potentially adjusted) input, creating the inversion map.
7186      * This is done in two passes.  The first pass is to determine if the
7187      * transliteration can be done in place.  The inversion map it creates
7188      * could be used, but generally would be larger and slower to run than the
7189      * output of the second pass, which starts with a more compact table and
7190      * allows more ranges to be merged */
7191     for (pass2 = 0; pass2 < 2; pass2++) {
7192         if (pass2) {
7193             /* Initialize to a single range */
7194             t_invlist = _add_range_to_invlist(t_invlist, 0, UV_MAX);
7195
7196             /* In the second pass, we just have the single range */
7197             len = 1;
7198             t_array = invlist_array(t_invlist);
7199         }
7200
7201 /* As noted earlier, we convert EBCDIC code points to Unicode in the first pass
7202  * so as to get the well-behaved length 1 vs length 2 boundary.  Only code
7203  * points below 256 differ between the two character sets in this regard.  For
7204  * these, we also can't have any ranges, as they have to be individually
7205  * converted. */
7206 #ifdef EBCDIC
7207 #  define CP_ADJUST(x)          ((pass2) ? (x) : NATIVE_TO_UNI(x))
7208 #  define FORCE_RANGE_LEN_1(x)  ((pass2) ? 0 : ((x) < 256))
7209 #  define CP_SKIP(x)            ((pass2) ? UVCHR_SKIP(x) : OFFUNISKIP(x))
7210 #else
7211 #  define CP_ADJUST(x)          (x)
7212 #  define FORCE_RANGE_LEN_1(x)  0
7213 #  define CP_SKIP(x)            UVCHR_SKIP(x)
7214 #endif
7215
7216         /* And the mapping of each of the ranges is initialized.  Initially,
7217          * everything is TR_UNLISTED. */
7218         for (i = 0; i < len; i++) {
7219             r_map[i] = TR_UNLISTED;
7220         }
7221
7222         t = t0;
7223         t_count = 0;
7224         r = r0;
7225         r_count = 0;
7226         t_range_count = r_range_count = 0;
7227
7228         DEBUG_y(PerlIO_printf(Perl_debug_log, "%s: %d:\ntstr=%s\n",
7229                     __FILE__, __LINE__, _byte_dump_string(t, tend - t, 0)));
7230         DEBUG_y(PerlIO_printf(Perl_debug_log, "rstr=%s\n",
7231                                         _byte_dump_string(r, rend - r, 0)));
7232         DEBUG_y(PerlIO_printf(Perl_debug_log, "/c=%d; /s=%d; /d=%d\n",
7233                                                   complement, squash, del));
7234         DEBUG_y(invmap_dump(t_invlist, r_map));
7235
7236         /* Now go through the search list constructing an inversion map.  The
7237          * input is not necessarily in any particular order.  Making it an
7238          * inversion map orders it, potentially simplifying, and makes it easy
7239          * to deal with at run time.  This is the only place in core that
7240          * generates an inversion map; if others were introduced, it might be
7241          * better to create general purpose routines to handle them.
7242          * (Inversion maps are created in perl in other places.)
7243          *
7244          * An inversion map consists of two parallel arrays.  One is
7245          * essentially an inversion list: an ordered list of code points such
7246          * that each element gives the first code point of a range of
7247          * consecutive code points that map to the element in the other array
7248          * that has the same index as this one (in other words, the
7249          * corresponding element).  Thus the range extends up to (but not
7250          * including) the code point given by the next higher element.  In a
7251          * true inversion map, the corresponding element in the other array
7252          * gives the mapping of the first code point in the range, with the
7253          * understanding that the next higher code point in the inversion
7254          * list's range will map to the next higher code point in the map.
7255          *
7256          * So if at element [i], let's say we have:
7257          *
7258          *     t_invlist  r_map
7259          * [i]    A         a
7260          *
7261          * This means that A => a, B => b, C => c....  Let's say that the
7262          * situation is such that:
7263          *
7264          * [i+1]  L        -1
7265          *
7266          * This means the sequence that started at [i] stops at K => k.  This
7267          * illustrates that you need to look at the next element to find where
7268          * a sequence stops.  Except, the highest element in the inversion list
7269          * begins a range that is understood to extend to the platform's
7270          * infinity.
7271          *
7272          * This routine modifies traditional inversion maps to reserve two
7273          * mappings:
7274          *
7275          *  TR_UNLISTED (or -1) indicates that no code point in the range
7276          *      is listed in the tr/// searchlist.  At runtime, these are
7277          *      always passed through unchanged.  In the inversion map, all
7278          *      points in the range are mapped to -1, instead of increasing,
7279          *      like the 'L' in the example above.
7280          *
7281          *      We start the parse with every code point mapped to this, and as
7282          *      we parse and find ones that are listed in the search list, we
7283          *      carve out ranges as we go along that override that.
7284          *
7285          *  TR_SPECIAL_HANDLING (or -2) indicates that every code point in the
7286          *      range needs special handling.  Again, all code points in the
7287          *      range are mapped to -2, instead of increasing.
7288          *
7289          *      Under /d this value means the code point should be deleted from
7290          *      the transliteration when encountered.
7291          *
7292          *      Otherwise, it marks that every code point in the range is to
7293          *      map to the final character in the replacement list.  This
7294          *      happens only when the replacement list is shorter than the
7295          *      search one, so there are things in the search list that have no
7296          *      correspondence in the replacement list.  For example, in
7297          *      tr/a-z/A/, 'A' is the final value, and the inversion map
7298          *      generated for this would be like this:
7299          *          \0  =>  -1
7300          *          a   =>   A
7301          *          b-z =>  -2
7302          *          z+1 =>  -1
7303          *      'A' appears once, then the remainder of the range maps to -2.
7304          *      The use of -2 isn't strictly necessary, as an inversion map is
7305          *      capable of representing this situation, but not nearly so
7306          *      compactly, and this is actually quite commonly encountered.
7307          *      Indeed, the original design of this code used a full inversion
7308          *      map for this.  But things like
7309          *          tr/\0-\x{FFFF}/A/
7310          *      generated huge data structures, slowly, and the execution was
7311          *      also slow.  So the current scheme was implemented.
7312          *
7313          *  So, if the next element in our example is:
7314          *
7315          * [i+2]  Q        q
7316          *
7317          * Then all of L, M, N, O, and P map to TR_UNLISTED.  If the next
7318          * elements are
7319          *
7320          * [i+3]  R        z
7321          * [i+4]  S       TR_UNLISTED
7322          *
7323          * Then Q => q; R => z; and S => TR_UNLISTED.  If [i+4] (the 'S') is
7324          * the final element in the arrays, every code point from S to infinity
7325          * maps to TR_UNLISTED.
7326          *
7327          */
7328                            /* Finish up range started in what otherwise would
7329                             * have been the final iteration */
7330         while (t < tend || t_range_count > 0) {
7331             bool adjacent_to_range_above = FALSE;
7332             bool adjacent_to_range_below = FALSE;
7333
7334             bool merge_with_range_above = FALSE;
7335             bool merge_with_range_below = FALSE;
7336
7337             UV span, invmap_range_length_remaining;
7338             SSize_t j;
7339             Size_t i;
7340
7341             /* If we are in the middle of processing a range in the 'target'
7342              * side, the previous iteration has set us up.  Otherwise, look at
7343              * the next character in the search list */
7344             if (t_range_count <= 0) {
7345                 if (! tstr_utf8) {
7346
7347                     /* Here, not in the middle of a range, and not UTF-8.  The
7348                      * next code point is the single byte where we're at */
7349                     t_cp = CP_ADJUST(*t);
7350                     t_range_count = 1;
7351                     t++;
7352                 }
7353                 else {
7354                     Size_t t_char_len;
7355
7356                     /* Here, not in the middle of a range, and is UTF-8.  The
7357                      * next code point is the next UTF-8 char in the input.  We
7358                      * know the input is valid, because the toker constructed
7359                      * it */
7360                     t_cp = CP_ADJUST(valid_utf8_to_uvchr(t, &t_char_len));
7361                     t += t_char_len;
7362
7363                     /* UTF-8 strings (only) have been parsed in toke.c to have
7364                      * ranges.  See if the next byte indicates that this was
7365                      * the first element of a range.  If so, get the final
7366                      * element and calculate the range size.  If not, the range
7367                      * size is 1 */
7368                     if (   t < tend && *t == RANGE_INDICATOR
7369                         && ! FORCE_RANGE_LEN_1(t_cp))
7370                     {
7371                         t++;
7372                         t_range_count = valid_utf8_to_uvchr(t, &t_char_len)
7373                                       - t_cp + 1;
7374                         t += t_char_len;
7375                     }
7376                     else {
7377                         t_range_count = 1;
7378                     }
7379                 }
7380
7381                 /* Count the total number of listed code points * */
7382                 t_count += t_range_count;
7383             }
7384
7385             /* Similarly, get the next character in the replacement list */
7386             if (r_range_count <= 0) {
7387                 if (r >= rend) {
7388
7389                     /* But if we've exhausted the rhs, there is nothing to map
7390                      * to, except the special handling one, and we make the
7391                      * range the same size as the lhs one. */
7392                     r_cp = TR_SPECIAL_HANDLING;
7393                     r_range_count = t_range_count;
7394
7395                     if (! del) {
7396                         DEBUG_yv(PerlIO_printf(Perl_debug_log,
7397                                         "final_map =%" UVXf "\n", final_map));
7398                     }
7399                 }
7400                 else {
7401                     if (! rstr_utf8) {
7402                         r_cp = CP_ADJUST(*r);
7403                         r_range_count = 1;
7404                         r++;
7405                     }
7406                     else {
7407                         Size_t r_char_len;
7408
7409                         r_cp = CP_ADJUST(valid_utf8_to_uvchr(r, &r_char_len));
7410                         r += r_char_len;
7411                         if (   r < rend && *r == RANGE_INDICATOR
7412                             && ! FORCE_RANGE_LEN_1(r_cp))
7413                         {
7414                             r++;
7415                             r_range_count = valid_utf8_to_uvchr(r,
7416                                                     &r_char_len) - r_cp + 1;
7417                             r += r_char_len;
7418                         }
7419                         else {
7420                             r_range_count = 1;
7421                         }
7422                     }
7423
7424                     if (r_cp == TR_SPECIAL_HANDLING) {
7425                         r_range_count = t_range_count;
7426                     }
7427
7428                     /* This is the final character so far */
7429                     final_map = r_cp + r_range_count - 1;
7430
7431                     r_count += r_range_count;
7432                 }
7433             }
7434
7435             /* Here, we have the next things ready in both sides.  They are
7436              * potentially ranges.  We try to process as big a chunk as
7437              * possible at once, but the lhs and rhs must be synchronized, so
7438              * things like tr/A-Z/a-ij-z/ will need to be processed in 2 chunks
7439              * */
7440             min_range_count = MIN(t_range_count, r_range_count);
7441
7442             /* Search the inversion list for the entry that contains the input
7443              * code point <cp>.  The inversion map was initialized to cover the
7444              * entire range of possible inputs, so this should not fail.  So
7445              * the return value is the index into the list's array of the range
7446              * that contains <cp>, that is, 'i' such that array[i] <= cp <
7447              * array[i+1] */
7448             j = _invlist_search(t_invlist, t_cp);
7449             assert(j >= 0);
7450             i = j;
7451
7452             /* Here, the data structure might look like:
7453              *
7454              * index    t   r     Meaning
7455              * [i-1]    J   j   # J-L => j-l
7456              * [i]      M  -1   # M => default; as do N, O, P, Q
7457              * [i+1]    R   x   # R => x, S => x+1, T => x+2
7458              * [i+2]    U   y   # U => y, V => y+1, ...
7459              * ...
7460              * [-1]     Z  -1   # Z => default; as do Z+1, ... infinity
7461              *
7462              * where 'x' and 'y' above are not to be taken literally.
7463              *
7464              * The maximum chunk we can handle in this loop iteration, is the
7465              * smallest of the three components: the lhs 't_', the rhs 'r_',
7466              * and the remainder of the range in element [i].  (In pass 1, that
7467              * range will have everything in it be of the same class; we can't
7468              * cross into another class.)  'min_range_count' already contains
7469              * the smallest of the first two values.  The final one is
7470              * irrelevant if the map is to the special indicator */
7471
7472             invmap_range_length_remaining = (i + 1 < len)
7473                                             ? t_array[i+1] - t_cp
7474                                             : IV_MAX - t_cp;
7475             span = MAX(1, MIN(min_range_count, invmap_range_length_remaining));
7476
7477             /* The end point of this chunk is where we are, plus the span, but
7478              * never larger than the platform's infinity */
7479             t_cp_end = MIN(IV_MAX, t_cp + span - 1);
7480
7481             if (r_cp == TR_SPECIAL_HANDLING) {
7482
7483                 /* If unmatched lhs code points map to the final map, use that
7484                  * value.  This being set to TR_SPECIAL_HANDLING indicates that
7485                  * we don't have a final map: unmatched lhs code points are
7486                  * simply deleted */
7487                 r_cp_end = (del) ? TR_SPECIAL_HANDLING : final_map;
7488             }
7489             else {
7490                 r_cp_end = MIN(IV_MAX, r_cp + span - 1);
7491
7492                 /* If something on the lhs is below 256, and something on the
7493                  * rhs is above, there is a potential mapping here across that
7494                  * boundary.  Indeed the only way there isn't is if both sides
7495                  * start at the same point.  That means they both cross at the
7496                  * same time.  But otherwise one crosses before the other */
7497                 if (t_cp < 256 && r_cp_end > 255 && r_cp != t_cp) {
7498                     can_force_utf8 = TRUE;
7499                 }
7500             }
7501
7502             /* If a character appears in the search list more than once, the
7503              * 2nd and succeeding occurrences are ignored, so only do this
7504              * range if haven't already processed this character.  (The range
7505              * has been set up so that all members in it will be of the same
7506              * ilk) */
7507             if (r_map[i] == TR_UNLISTED) {
7508                 DEBUG_yv(PerlIO_printf(Perl_debug_log,
7509                     "Processing %" UVxf "-%" UVxf " => %" UVxf "-%" UVxf "\n",
7510                     t_cp, t_cp_end, r_cp, r_cp_end));
7511
7512                 /* This is the first definition for this chunk, hence is valid
7513                  * and needs to be processed.  Here and in the comments below,
7514                  * we use the above sample data.  The t_cp chunk must be any
7515                  * contiguous subset of M, N, O, P, and/or Q.
7516                  *
7517                  * In the first pass, calculate if there is any possible input
7518                  * string that has a character whose transliteration will be
7519                  * longer than it.  If none, the transliteration may be done
7520                  * in-place, as it can't write over a so-far unread byte.
7521                  * Otherwise, a copy must first be made.  This could be
7522                  * expensive for long inputs.
7523                  *
7524                  * In the first pass, the t_invlist has been partitioned so
7525                  * that all elements in any single range have the same number
7526                  * of bytes in their UTF-8 representations.  And the r space is
7527                  * either a single byte, or a range of strictly monotonically
7528                  * increasing code points.  So the final element in the range
7529                  * will be represented by no fewer bytes than the initial one.
7530                  * That means that if the final code point in the t range has
7531                  * at least as many bytes as the final code point in the r,
7532                  * then all code points in the t range have at least as many
7533                  * bytes as their corresponding r range element.  But if that's
7534                  * not true, the transliteration of at least the final code
7535                  * point grows in length.  As an example, suppose we had
7536                  *      tr/\x{fff0}-\x{fff1}/\x{ffff}-\x{10000}/
7537                  * The UTF-8 for all but 10000 occupies 3 bytes on ASCII
7538                  * platforms.  We have deliberately set up the data structure
7539                  * so that any range in the lhs gets split into chunks for
7540                  * processing, such that every code point in a chunk has the
7541                  * same number of UTF-8 bytes.  We only have to check the final
7542                  * code point in the rhs against any code point in the lhs. */
7543                 if ( ! pass2
7544                     && r_cp_end != TR_SPECIAL_HANDLING
7545                     && CP_SKIP(t_cp_end) < CP_SKIP(r_cp_end))
7546                 {
7547                     /* Here, we will need to make a copy of the input string
7548                      * before doing the transliteration.  The worst possible
7549                      * case is an expansion ratio of 14:1. This is rare, and
7550                      * we'd rather allocate only the necessary amount of extra
7551                      * memory for that copy.  We can calculate the worst case
7552                      * for this particular transliteration is by keeping track
7553                      * of the expansion factor for each range.
7554                      *
7555                      * Consider tr/\xCB/\X{E000}/.  The maximum expansion
7556                      * factor is 1 byte going to 3 if the target string is not
7557                      * UTF-8, but 2 bytes going to 3 if it is in UTF-8.  We
7558                      * could pass two different values so doop could choose
7559                      * based on the UTF-8ness of the target.  But khw thinks
7560                      * (perhaps wrongly) that is overkill.  It is used only to
7561                      * make sure we malloc enough space.
7562                      *
7563                      * If no target string can force the result to be UTF-8,
7564                      * then we don't have to worry about the case of the target
7565                      * string not being UTF-8 */
7566                     NV t_size = (can_force_utf8 && t_cp < 256)
7567                                 ? 1
7568                                 : CP_SKIP(t_cp_end);
7569                     NV ratio = CP_SKIP(r_cp_end) / t_size;
7570
7571                     o->op_private |= OPpTRANS_GROWS;
7572
7573                     /* Now that we know it grows, we can keep track of the
7574                      * largest ratio */
7575                     if (ratio > max_expansion) {
7576                         max_expansion = ratio;
7577                         DEBUG_y(PerlIO_printf(Perl_debug_log,
7578                                         "New expansion factor: %" NVgf "\n",
7579                                         max_expansion));
7580                     }
7581                 }
7582
7583                 /* The very first range is marked as adjacent to the
7584                  * non-existent range below it, as it causes things to "just
7585                  * work" (TradeMark)
7586                  *
7587                  * If the lowest code point in this chunk is M, it adjoins the
7588                  * J-L range */
7589                 if (t_cp == t_array[i]) {
7590                     adjacent_to_range_below = TRUE;
7591
7592                     /* And if the map has the same offset from the beginning of
7593                      * the range as does this new code point (or both are for
7594                      * TR_SPECIAL_HANDLING), this chunk can be completely
7595                      * merged with the range below.  EXCEPT, in the first pass,
7596                      * we don't merge ranges whose UTF-8 byte representations
7597                      * have different lengths, so that we can more easily
7598                      * detect if a replacement is longer than the source, that
7599                      * is if it 'grows'.  But in the 2nd pass, there's no
7600                      * reason to not merge */
7601                     if (   (i > 0 && (   pass2
7602                                       || CP_SKIP(t_array[i-1])
7603                                                             == CP_SKIP(t_cp)))
7604                         && (   (   r_cp == TR_SPECIAL_HANDLING
7605                                 && r_map[i-1] == TR_SPECIAL_HANDLING)
7606                             || (   r_cp != TR_SPECIAL_HANDLING
7607                                 && r_cp - r_map[i-1] == t_cp - t_array[i-1])))
7608                     {
7609                         merge_with_range_below = TRUE;
7610                     }
7611                 }
7612
7613                 /* Similarly, if the highest code point in this chunk is 'Q',
7614                  * it adjoins the range above, and if the map is suitable, can
7615                  * be merged with it */
7616                 if (    t_cp_end >= IV_MAX - 1
7617                     || (   i + 1 < len
7618                         && t_cp_end + 1 == t_array[i+1]))
7619                 {
7620                     adjacent_to_range_above = TRUE;
7621                     if (i + 1 < len)
7622                     if (    (   pass2
7623                              || CP_SKIP(t_cp) == CP_SKIP(t_array[i+1]))
7624                         && (   (   r_cp == TR_SPECIAL_HANDLING
7625                                 && r_map[i+1] == (UV) TR_SPECIAL_HANDLING)
7626                             || (   r_cp != TR_SPECIAL_HANDLING
7627                                 && r_cp_end == r_map[i+1] - 1)))
7628                     {
7629                         merge_with_range_above = TRUE;
7630                     }
7631                 }
7632
7633                 if (merge_with_range_below && merge_with_range_above) {
7634
7635                     /* Here the new chunk looks like M => m, ... Q => q; and
7636                      * the range above is like R => r, ....  Thus, the [i-1]
7637                      * and [i+1] ranges should be seamlessly melded so the
7638                      * result looks like
7639                      *
7640                      * [i-1]    J   j   # J-T => j-t
7641                      * [i]      U   y   # U => y, V => y+1, ...
7642                      * ...
7643                      * [-1]     Z  -1   # Z => default; as do Z+1, ... infinity
7644                      */
7645                     Move(t_array + i + 2, t_array + i, len - i - 2, UV);
7646                     Move(r_map   + i + 2, r_map   + i, len - i - 2, UV);
7647                     len -= 2;
7648                     invlist_set_len(t_invlist,
7649                                     len,
7650                                     *(get_invlist_offset_addr(t_invlist)));
7651                 }
7652                 else if (merge_with_range_below) {
7653
7654                     /* Here the new chunk looks like M => m, .... But either
7655                      * (or both) it doesn't extend all the way up through Q; or
7656                      * the range above doesn't start with R => r. */
7657                     if (! adjacent_to_range_above) {
7658
7659                         /* In the first case, let's say the new chunk extends
7660                          * through O.  We then want:
7661                          *
7662                          * [i-1]    J   j   # J-O => j-o
7663                          * [i]      P  -1   # P => -1, Q => -1
7664                          * [i+1]    R   x   # R => x, S => x+1, T => x+2
7665                          * [i+2]    U   y   # U => y, V => y+1, ...
7666                          * ...
7667                          * [-1]     Z  -1   # Z => default; as do Z+1, ...
7668                          *                                            infinity
7669                          */
7670                         t_array[i] = t_cp_end + 1;
7671                         r_map[i] = TR_UNLISTED;
7672                     }
7673                     else { /* Adjoins the range above, but can't merge with it
7674                               (because 'x' is not the next map after q) */
7675                         /*
7676                          * [i-1]    J   j   # J-Q => j-q
7677                          * [i]      R   x   # R => x, S => x+1, T => x+2
7678                          * [i+1]    U   y   # U => y, V => y+1, ...
7679                          * ...
7680                          * [-1]     Z  -1   # Z => default; as do Z+1, ...
7681                          *                                          infinity
7682                          */
7683
7684                         Move(t_array + i + 1, t_array + i, len - i - 1, UV);
7685                         Move(r_map + i + 1, r_map + i, len - i - 1, UV);
7686                         len--;
7687                         invlist_set_len(t_invlist, len,
7688                                         *(get_invlist_offset_addr(t_invlist)));
7689                     }
7690                 }
7691                 else if (merge_with_range_above) {
7692
7693                     /* Here the new chunk ends with Q => q, and the range above
7694                      * must start with R => r, so the two can be merged. But
7695                      * either (or both) the new chunk doesn't extend all the
7696                      * way down to M; or the mapping of the final code point
7697                      * range below isn't m */
7698                     if (! adjacent_to_range_below) {
7699
7700                         /* In the first case, let's assume the new chunk starts
7701                          * with P => p.  Then, because it's merge-able with the
7702                          * range above, that range must be R => r.  We want:
7703                          *
7704                          * [i-1]    J   j   # J-L => j-l
7705                          * [i]      M  -1   # M => -1, N => -1
7706                          * [i+1]    P   p   # P-T => p-t
7707                          * [i+2]    U   y   # U => y, V => y+1, ...
7708                          * ...
7709                          * [-1]     Z  -1   # Z => default; as do Z+1, ...
7710                          *                                          infinity
7711                          */
7712                         t_array[i+1] = t_cp;
7713                         r_map[i+1] = r_cp;
7714                     }
7715                     else { /* Adjoins the range below, but can't merge with it
7716                             */
7717                         /*
7718                          * [i-1]    J   j   # J-L => j-l
7719                          * [i]      M   x   # M-T => x-5 .. x+2
7720                          * [i+1]    U   y   # U => y, V => y+1, ...
7721                          * ...
7722                          * [-1]     Z  -1   # Z => default; as do Z+1, ...
7723                          *                                          infinity
7724                          */
7725                         Move(t_array + i + 1, t_array + i, len - i - 1, UV);
7726                         Move(r_map   + i + 1, r_map   + i, len - i - 1, UV);
7727                         len--;
7728                         t_array[i] = t_cp;
7729                         r_map[i] = r_cp;
7730                         invlist_set_len(t_invlist, len,
7731                                         *(get_invlist_offset_addr(t_invlist)));
7732                     }
7733                 }
7734                 else if (adjacent_to_range_below && adjacent_to_range_above) {
7735                     /* The new chunk completely fills the gap between the
7736                      * ranges on either side, but can't merge with either of
7737                      * them.
7738                      *
7739                      * [i-1]    J   j   # J-L => j-l
7740                      * [i]      M   z   # M => z, N => z+1 ... Q => z+4
7741                      * [i+1]    R   x   # R => x, S => x+1, T => x+2
7742                      * [i+2]    U   y   # U => y, V => y+1, ...
7743                      * ...
7744                      * [-1]     Z  -1   # Z => default; as do Z+1, ... infinity
7745                      */
7746                     r_map[i] = r_cp;
7747                 }
7748                 else if (adjacent_to_range_below) {
7749                     /* The new chunk adjoins the range below, but not the range
7750                      * above, and can't merge.  Let's assume the chunk ends at
7751                      * O.
7752                      *
7753                      * [i-1]    J   j   # J-L => j-l
7754                      * [i]      M   z   # M => z, N => z+1, O => z+2
7755                      * [i+1]    P   -1  # P => -1, Q => -1
7756                      * [i+2]    R   x   # R => x, S => x+1, T => x+2
7757                      * [i+3]    U   y   # U => y, V => y+1, ...
7758                      * ...
7759                      * [-w]     Z  -1   # Z => default; as do Z+1, ... infinity
7760                      */
7761                     invlist_extend(t_invlist, len + 1);
7762                     t_array = invlist_array(t_invlist);
7763                     Renew(r_map, len + 1, UV);
7764
7765                     Move(t_array + i + 1, t_array + i + 2, len - i - 1, UV);
7766                     Move(r_map + i + 1,   r_map   + i + 2, len - i - 1, UV);
7767                     r_map[i] = r_cp;
7768                     t_array[i+1] = t_cp_end + 1;
7769                     r_map[i+1] = TR_UNLISTED;
7770                     len++;
7771                     invlist_set_len(t_invlist, len,
7772                                     *(get_invlist_offset_addr(t_invlist)));
7773                 }
7774                 else if (adjacent_to_range_above) {
7775                     /* The new chunk adjoins the range above, but not the range
7776                      * below, and can't merge.  Let's assume the new chunk
7777                      * starts at O
7778                      *
7779                      * [i-1]    J   j   # J-L => j-l
7780                      * [i]      M  -1   # M => default, N => default
7781                      * [i+1]    O   z   # O => z, P => z+1, Q => z+2
7782                      * [i+2]    R   x   # R => x, S => x+1, T => x+2
7783                      * [i+3]    U   y   # U => y, V => y+1, ...
7784                      * ...
7785                      * [-1]     Z  -1   # Z => default; as do Z+1, ... infinity
7786                      */
7787                     invlist_extend(t_invlist, len + 1);
7788                     t_array = invlist_array(t_invlist);
7789                     Renew(r_map, len + 1, UV);
7790
7791                     Move(t_array + i + 1, t_array + i + 2, len - i - 1, UV);
7792                     Move(r_map   + i + 1, r_map   + i + 2, len - i - 1, UV);
7793                     t_array[i+1] = t_cp;
7794                     r_map[i+1] = r_cp;
7795                     len++;
7796                     invlist_set_len(t_invlist, len,
7797                                     *(get_invlist_offset_addr(t_invlist)));
7798                 }
7799                 else {
7800                     /* The new chunk adjoins neither the range above, nor the
7801                      * range below.  Lets assume it is N..P => n..p
7802                      *
7803                      * [i-1]    J   j   # J-L => j-l
7804                      * [i]      M  -1   # M => default
7805                      * [i+1]    N   n   # N..P => n..p
7806                      * [i+2]    Q  -1   # Q => default
7807                      * [i+3]    R   x   # R => x, S => x+1, T => x+2
7808                      * [i+4]    U   y   # U => y, V => y+1, ...
7809                      * ...
7810                      * [-1]     Z  -1   # Z => default; as do Z+1, ... infinity
7811                      */
7812
7813                     DEBUG_yv(PerlIO_printf(Perl_debug_log,
7814                                         "Before fixing up: len=%d, i=%d\n",
7815                                         (int) len, (int) i));
7816                     DEBUG_yv(invmap_dump(t_invlist, r_map));
7817
7818                     invlist_extend(t_invlist, len + 2);
7819                     t_array = invlist_array(t_invlist);
7820                     Renew(r_map, len + 2, UV);
7821
7822                     Move(t_array + i + 1,
7823                          t_array + i + 2 + 1, len - i - (2 - 1), UV);
7824                     Move(r_map   + i + 1,
7825                          r_map   + i + 2 + 1, len - i - (2 - 1), UV);
7826
7827                     len += 2;
7828                     invlist_set_len(t_invlist, len,
7829                                     *(get_invlist_offset_addr(t_invlist)));
7830
7831                     t_array[i+1] = t_cp;
7832                     r_map[i+1] = r_cp;
7833
7834                     t_array[i+2] = t_cp_end + 1;
7835                     r_map[i+2] = TR_UNLISTED;
7836                 }
7837                 DEBUG_yv(PerlIO_printf(Perl_debug_log,
7838                           "After iteration: span=%" UVuf ", t_range_count=%"
7839                           UVuf " r_range_count=%" UVuf "\n",
7840                           span, t_range_count, r_range_count));
7841                 DEBUG_yv(invmap_dump(t_invlist, r_map));
7842             } /* End of this chunk needs to be processed */
7843
7844             /* Done with this chunk. */
7845             t_cp += span;
7846             if (t_cp >= IV_MAX) {
7847                 break;
7848             }
7849             t_range_count -= span;
7850             if (r_cp != TR_SPECIAL_HANDLING) {
7851                 r_cp += span;
7852                 r_range_count -= span;
7853             }
7854             else {
7855                 r_range_count = 0;
7856             }
7857
7858         } /* End of loop through the search list */
7859
7860         /* We don't need an exact count, but we do need to know if there is
7861          * anything left over in the replacement list.  So, just assume it's
7862          * one byte per character */
7863         if (rend > r) {
7864             r_count++;
7865         }
7866     } /* End of passes */
7867
7868     SvREFCNT_dec(inverted_tstr);
7869
7870     DEBUG_y(PerlIO_printf(Perl_debug_log, "After everything: \n"));
7871     DEBUG_y(invmap_dump(t_invlist, r_map));
7872
7873     /* We now have normalized the input into an inversion map.
7874      *
7875      * See if the lhs and rhs are equivalent.  If so, this tr/// is a no-op
7876      * except for the count, and streamlined runtime code can be used */
7877     if (!del && !squash) {
7878
7879         /* They are identical if they point to same address, or if everything
7880          * maps to UNLISTED or to itself.  This catches things that not looking
7881          * at the normalized inversion map doesn't catch, like tr/aa/ab/ or
7882          * tr/\x{100}-\x{104}/\x{100}-\x{102}\x{103}-\x{104}  */
7883         if (r0 != t0) {
7884             for (i = 0; i < len; i++) {
7885                 if (r_map[i] != TR_UNLISTED && r_map[i] != t_array[i]) {
7886                     goto done_identical_check;
7887                 }
7888             }
7889         }
7890
7891         /* Here have gone through entire list, and didn't find any
7892          * non-identical mappings */
7893         o->op_private |= OPpTRANS_IDENTICAL;
7894
7895       done_identical_check: ;
7896     }
7897
7898     t_array = invlist_array(t_invlist);
7899
7900     /* If has components above 255, we generally need to use the inversion map
7901      * implementation */
7902     if (   can_force_utf8
7903         || (   len > 0
7904             && t_array[len-1] > 255
7905                  /* If the final range is 0x100-INFINITY and is a special
7906                   * mapping, the table implementation can handle it */
7907             && ! (   t_array[len-1] == 256
7908                   && (   r_map[len-1] == TR_UNLISTED
7909                       || r_map[len-1] == TR_SPECIAL_HANDLING))))
7910     {
7911         SV* r_map_sv;
7912
7913         /* A UTF-8 op is generated, indicated by this flag.  This op is an
7914          * sv_op */
7915         o->op_private |= OPpTRANS_USE_SVOP;
7916
7917         if (can_force_utf8) {
7918             o->op_private |= OPpTRANS_CAN_FORCE_UTF8;
7919         }
7920
7921         /* The inversion map is pushed; first the list. */
7922         invmap = MUTABLE_AV(newAV());
7923         av_push(invmap, t_invlist);
7924
7925         /* 2nd is the mapping */
7926         r_map_sv = newSVpvn((char *) r_map, len * sizeof(UV));
7927         av_push(invmap, r_map_sv);
7928
7929         /* 3rd is the max possible expansion factor */
7930         av_push(invmap, newSVnv(max_expansion));
7931
7932         /* Characters that are in the search list, but not in the replacement
7933          * list are mapped to the final character in the replacement list */
7934         if (! del && r_count < t_count) {
7935             av_push(invmap, newSVuv(final_map));
7936         }
7937
7938 #ifdef USE_ITHREADS
7939         cPADOPo->op_padix = pad_alloc(OP_TRANS, SVf_READONLY);
7940         SvREFCNT_dec(PAD_SVl(cPADOPo->op_padix));
7941         PAD_SETSV(cPADOPo->op_padix, (SV *) invmap);
7942         SvPADTMP_on(invmap);
7943         SvREADONLY_on(invmap);
7944 #else
7945         cSVOPo->op_sv = (SV *) invmap;
7946 #endif
7947
7948     }
7949     else {
7950         OPtrans_map *tbl;
7951         unsigned short i;
7952
7953         /* The OPtrans_map struct already contains one slot; hence the -1. */
7954         SSize_t struct_size = sizeof(OPtrans_map)
7955                             + (256 - 1 + 1)*sizeof(short);
7956
7957         /* Non-utf8 case: set o->op_pv to point to a simple 256+ entry lookup
7958         * table. Entries with the value TR_UNMAPPED indicate chars not to be
7959         * translated, while TR_DELETE indicates a search char without a
7960         * corresponding replacement char under /d.
7961         *
7962         * In addition, an extra slot at the end is used to store the final
7963         * repeating char, or TR_R_EMPTY under an empty replacement list, or
7964         * TR_DELETE under /d; which makes the runtime code easier.
7965         */
7966
7967         /* Indicate this is an op_pv */
7968         o->op_private &= ~OPpTRANS_USE_SVOP;
7969
7970         tbl = (OPtrans_map*)PerlMemShared_calloc(struct_size, 1);
7971         tbl->size = 256;
7972         cPVOPo->op_pv = (char*)tbl;
7973
7974         for (i = 0; i < len; i++) {
7975             STATIC_ASSERT_DECL(TR_SPECIAL_HANDLING == TR_DELETE);
7976             short upper = i >= len - 1 ? 256 : (short) t_array[i+1];
7977             short to = (short) r_map[i];
7978             short j;
7979             bool do_increment = TRUE;
7980
7981             /* Any code points above our limit should be irrelevant */
7982             if (t_array[i] >= tbl->size) break;
7983
7984             /* Set up the map */
7985             if (to == (short) TR_SPECIAL_HANDLING && ! del) {
7986                 to = (short) final_map;
7987                 do_increment = FALSE;
7988             }
7989             else if (to < 0) {
7990                 do_increment = FALSE;
7991             }
7992
7993             /* Create a map for everything in this range.  The value increases
7994              * except for the special cases */
7995             for (j = (short) t_array[i]; j < upper; j++) {
7996                 tbl->map[j] = to;
7997                 if (do_increment) to++;
7998             }
7999         }
8000
8001         tbl->map[tbl->size] = del
8002                               ? (short) TR_DELETE
8003                               : (short) rlen
8004                                 ? (short) final_map
8005                                 : (short) TR_R_EMPTY;
8006         DEBUG_y(PerlIO_printf(Perl_debug_log,"%s: %d\n", __FILE__, __LINE__));
8007         for (i = 0; i < tbl->size; i++) {
8008             if (tbl->map[i] < 0) {
8009                 DEBUG_y(PerlIO_printf(Perl_debug_log," %02x=>%d",
8010                                                 (unsigned) i, tbl->map[i]));
8011             }
8012             else {
8013                 DEBUG_y(PerlIO_printf(Perl_debug_log," %02x=>%02x",
8014                                                 (unsigned) i, tbl->map[i]));
8015             }
8016             if ((i+1) % 8 == 0 || i + 1 == (short) tbl->size) {
8017                 DEBUG_y(PerlIO_printf(Perl_debug_log,"\n"));
8018             }
8019         }
8020         DEBUG_y(PerlIO_printf(Perl_debug_log,"Final map 0x%x=>%02x\n",
8021                                 (unsigned) tbl->size, tbl->map[tbl->size]));
8022
8023         SvREFCNT_dec(t_invlist);
8024
8025 #if 0   /* code that added excess above-255 chars at the end of the table, in
8026            case we ever want to not use the inversion map implementation for
8027            this */
8028
8029         ASSUME(j <= rlen);
8030         excess = rlen - j;
8031
8032         if (excess) {
8033             /* More replacement chars than search chars:
8034              * store excess replacement chars at end of main table.
8035              */
8036
8037             struct_size += excess;
8038             tbl = (OPtrans_map*)PerlMemShared_realloc(tbl,
8039                         struct_size + excess * sizeof(short));
8040             tbl->size += excess;
8041             cPVOPo->op_pv = (char*)tbl;
8042
8043             for (i = 0; i < excess; i++)
8044                 tbl->map[i + 256] = r[j+i];
8045         }
8046         else {
8047             /* no more replacement chars than search chars */
8048         }
8049 #endif
8050
8051     }
8052
8053     DEBUG_y(PerlIO_printf(Perl_debug_log,
8054             "/d=%d, /s=%d, /c=%d, identical=%d, grows=%d,"
8055             " use_svop=%d, can_force_utf8=%d,\nexpansion=%" NVgf "\n",
8056             del, squash, complement,
8057             cBOOL(o->op_private & OPpTRANS_IDENTICAL),
8058             cBOOL(o->op_private & OPpTRANS_USE_SVOP),
8059             cBOOL(o->op_private & OPpTRANS_GROWS),
8060             cBOOL(o->op_private & OPpTRANS_CAN_FORCE_UTF8),
8061             max_expansion));
8062
8063     Safefree(r_map);
8064
8065     if(del && rlen != 0 && r_count == t_count) {
8066         Perl_ck_warner(aTHX_ packWARN(WARN_MISC), "Useless use of /d modifier in transliteration operator");
8067     } else if(r_count > t_count) {
8068         Perl_ck_warner(aTHX_ packWARN(WARN_MISC), "Replacement list is longer than search list");
8069     }
8070
8071     op_free(expr);
8072     op_free(repl);
8073
8074     return o;
8075 }
8076
8077
8078 /*
8079 =for apidoc newPMOP
8080
8081 Constructs, checks, and returns an op of any pattern matching type.
8082 C<type> is the opcode.  C<flags> gives the eight bits of C<op_flags>
8083 and, shifted up eight bits, the eight bits of C<op_private>.
8084
8085 =cut
8086 */
8087
8088 OP *
8089 Perl_newPMOP(pTHX_ I32 type, I32 flags)
8090 {
8091     PMOP *pmop;
8092
8093     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_PMOP
8094         || type == OP_CUSTOM);
8095
8096     NewOp(1101, pmop, 1, PMOP);
8097     OpTYPE_set(pmop, type);
8098     pmop->op_flags = (U8)flags;
8099     pmop->op_private = (U8)(0 | (flags >> 8));
8100     if (PL_opargs[type] & OA_RETSCALAR)
8101         scalar((OP *)pmop);
8102
8103     if (PL_hints & HINT_RE_TAINT)
8104         pmop->op_pmflags |= PMf_RETAINT;
8105 #ifdef USE_LOCALE_CTYPE
8106     if (IN_LC_COMPILETIME(LC_CTYPE)) {
8107         set_regex_charset(&(pmop->op_pmflags), REGEX_LOCALE_CHARSET);
8108     }
8109     else
8110 #endif
8111          if (IN_UNI_8_BIT) {
8112         set_regex_charset(&(pmop->op_pmflags), REGEX_UNICODE_CHARSET);
8113     }
8114     if (PL_hints & HINT_RE_FLAGS) {
8115         SV *reflags = Perl_refcounted_he_fetch_pvn(aTHX_
8116          PL_compiling.cop_hints_hash, STR_WITH_LEN("reflags"), 0, 0
8117         );
8118         if (reflags && SvOK(reflags)) pmop->op_pmflags |= SvIV(reflags);
8119         reflags = Perl_refcounted_he_fetch_pvn(aTHX_
8120          PL_compiling.cop_hints_hash, STR_WITH_LEN("reflags_charset"), 0, 0
8121         );
8122         if (reflags && SvOK(reflags)) {
8123             set_regex_charset(&(pmop->op_pmflags), (regex_charset)SvIV(reflags));
8124         }
8125     }
8126
8127
8128 #ifdef USE_ITHREADS
8129     assert(SvPOK(PL_regex_pad[0]));
8130     if (SvCUR(PL_regex_pad[0])) {
8131         /* Pop off the "packed" IV from the end.  */
8132         SV *const repointer_list = PL_regex_pad[0];
8133         const char *p = SvEND(repointer_list) - sizeof(IV);
8134         const IV offset = *((IV*)p);
8135
8136         assert(SvCUR(repointer_list) % sizeof(IV) == 0);
8137
8138         SvEND_set(repointer_list, p);
8139
8140         pmop->op_pmoffset = offset;
8141         /* This slot should be free, so assert this:  */
8142         assert(PL_regex_pad[offset] == &PL_sv_undef);
8143     } else {
8144         SV * const repointer = &PL_sv_undef;
8145         av_push(PL_regex_padav, repointer);
8146         pmop->op_pmoffset = av_top_index(PL_regex_padav);
8147         PL_regex_pad = AvARRAY(PL_regex_padav);
8148     }
8149 #endif
8150
8151     return CHECKOP(type, pmop);
8152 }
8153
8154 static void
8155 S_set_haseval(pTHX)
8156 {
8157     PADOFFSET i = 1;
8158     PL_cv_has_eval = 1;
8159     /* Any pad names in scope are potentially lvalues.  */
8160     for (; i < PadnamelistMAXNAMED(PL_comppad_name); i++) {
8161         PADNAME *pn = PAD_COMPNAME_SV(i);
8162         if (!pn || !PadnameLEN(pn))
8163             continue;
8164         if (PadnameOUTER(pn) || PadnameIN_SCOPE(pn, PL_cop_seqmax))
8165             S_mark_padname_lvalue(aTHX_ pn);
8166     }
8167 }
8168
8169 /* Given some sort of match op o, and an expression expr containing a
8170  * pattern, either compile expr into a regex and attach it to o (if it's
8171  * constant), or convert expr into a runtime regcomp op sequence (if it's
8172  * not)
8173  *
8174  * Flags currently has 2 bits of meaning:
8175  * 1: isreg indicates that the pattern is part of a regex construct, eg
8176  *      $x =~ /pattern/ or split /pattern/, as opposed to $x =~ $pattern or
8177  *      split "pattern", which aren't. In the former case, expr will be a list
8178  *      if the pattern contains more than one term (eg /a$b/).
8179  * 2: The pattern is for a split.
8180  *
8181  * When the pattern has been compiled within a new anon CV (for
8182  * qr/(?{...})/ ), then floor indicates the savestack level just before
8183  * the new sub was created
8184  *
8185  * tr/// is also handled.
8186  */
8187
8188 OP *
8189 Perl_pmruntime(pTHX_ OP *o, OP *expr, OP *repl, UV flags, I32 floor)
8190 {
8191     PMOP *pm;
8192     LOGOP *rcop;
8193     I32 repl_has_vars = 0;
8194     bool is_trans = (o->op_type == OP_TRANS || o->op_type == OP_TRANSR);
8195     bool is_compiletime;
8196     bool has_code;
8197     bool isreg    = cBOOL(flags & 1);
8198     bool is_split = cBOOL(flags & 2);
8199
8200     PERL_ARGS_ASSERT_PMRUNTIME;
8201
8202     if (is_trans) {
8203         return pmtrans(o, expr, repl);
8204     }
8205
8206     /* find whether we have any runtime or code elements;
8207      * at the same time, temporarily set the op_next of each DO block;
8208      * then when we LINKLIST, this will cause the DO blocks to be excluded
8209      * from the op_next chain (and from having LINKLIST recursively
8210      * applied to them). We fix up the DOs specially later */
8211
8212     is_compiletime = 1;
8213     has_code = 0;
8214     if (expr->op_type == OP_LIST) {
8215         OP *child;
8216         for (child = cLISTOPx(expr)->op_first; child; child = OpSIBLING(child)) {
8217             if (child->op_type == OP_NULL && (child->op_flags & OPf_SPECIAL)) {
8218                 has_code = 1;
8219                 assert(!child->op_next);
8220                 if (UNLIKELY(!OpHAS_SIBLING(child))) {
8221                     assert(PL_parser && PL_parser->error_count);
8222                     /* This can happen with qr/ (?{(^{})/.  Just fake up
8223                        the op we were expecting to see, to avoid crashing
8224                        elsewhere.  */
8225                     op_sibling_splice(expr, child, 0,
8226                               newSVOP(OP_CONST, 0, &PL_sv_no));
8227                 }
8228                 child->op_next = OpSIBLING(child);
8229             }
8230             else if (child->op_type != OP_CONST && child->op_type != OP_PUSHMARK)
8231             is_compiletime = 0;
8232         }
8233     }
8234     else if (expr->op_type != OP_CONST)
8235         is_compiletime = 0;
8236
8237     LINKLIST(expr);
8238
8239     /* fix up DO blocks; treat each one as a separate little sub;
8240      * also, mark any arrays as LIST/REF */
8241
8242     if (expr->op_type == OP_LIST) {
8243         OP *child;
8244         for (child = cLISTOPx(expr)->op_first; child; child = OpSIBLING(child)) {
8245
8246             if (child->op_type == OP_PADAV || child->op_type == OP_RV2AV) {
8247                 assert( !(child->op_flags  & OPf_WANT));
8248                 /* push the array rather than its contents. The regex
8249                  * engine will retrieve and join the elements later */
8250                 child->op_flags |= (OPf_WANT_LIST | OPf_REF);
8251                 continue;
8252             }
8253
8254             if (!(child->op_type == OP_NULL && (child->op_flags & OPf_SPECIAL)))
8255                 continue;
8256             child->op_next = NULL; /* undo temporary hack from above */
8257             scalar(child);
8258             LINKLIST(child);
8259             if (cLISTOPx(child)->op_first->op_type == OP_LEAVE) {
8260                 LISTOP *leaveop = cLISTOPx(cLISTOPx(child)->op_first);
8261                 /* skip ENTER */
8262                 assert(leaveop->op_first->op_type == OP_ENTER);
8263                 assert(OpHAS_SIBLING(leaveop->op_first));
8264                 child->op_next = OpSIBLING(leaveop->op_first);
8265                 /* skip leave */
8266                 assert(leaveop->op_flags & OPf_KIDS);
8267                 assert(leaveop->op_last->op_next == (OP*)leaveop);
8268                 leaveop->op_next = NULL; /* stop on last op */
8269                 op_null((OP*)leaveop);
8270             }
8271             else {
8272                 /* skip SCOPE */
8273                 OP *scope = cLISTOPx(child)->op_first;
8274                 assert(scope->op_type == OP_SCOPE);
8275                 assert(scope->op_flags & OPf_KIDS);
8276                 scope->op_next = NULL; /* stop on last op */
8277                 op_null(scope);
8278             }
8279
8280             /* XXX optimize_optree() must be called on o before
8281              * CALL_PEEP(), as currently S_maybe_multiconcat() can't
8282              * currently cope with a peephole-optimised optree.
8283              * Calling optimize_optree() here ensures that condition
8284              * is met, but may mean optimize_optree() is applied
8285              * to the same optree later (where hopefully it won't do any
8286              * harm as it can't convert an op to multiconcat if it's
8287              * already been converted */
8288             optimize_optree(child);
8289
8290             /* have to peep the DOs individually as we've removed it from
8291              * the op_next chain */
8292             CALL_PEEP(child);
8293             S_prune_chain_head(&(child->op_next));
8294             if (is_compiletime)
8295                 /* runtime finalizes as part of finalizing whole tree */
8296                 finalize_optree(child);
8297         }
8298     }
8299     else if (expr->op_type == OP_PADAV || expr->op_type == OP_RV2AV) {
8300         assert( !(expr->op_flags  & OPf_WANT));
8301         /* push the array rather than its contents. The regex
8302          * engine will retrieve and join the elements later */
8303         expr->op_flags |= (OPf_WANT_LIST | OPf_REF);
8304     }
8305
8306     PL_hints |= HINT_BLOCK_SCOPE;
8307     pm = (PMOP*)o;
8308     assert(floor==0 || (pm->op_pmflags & PMf_HAS_CV));
8309
8310     if (is_compiletime) {
8311         U32 rx_flags = pm->op_pmflags & RXf_PMf_COMPILETIME;
8312         regexp_engine const *eng = current_re_engine();
8313
8314         if (is_split) {
8315             /* make engine handle split ' ' specially */
8316             pm->op_pmflags |= PMf_SPLIT;
8317             rx_flags |= RXf_SPLIT;
8318         }
8319
8320         if (!has_code || !eng->op_comp) {
8321             /* compile-time simple constant pattern */
8322
8323             if ((pm->op_pmflags & PMf_HAS_CV) && !has_code) {
8324                 /* whoops! we guessed that a qr// had a code block, but we
8325                  * were wrong (e.g. /[(?{}]/ ). Throw away the PL_compcv
8326                  * that isn't required now. Note that we have to be pretty
8327                  * confident that nothing used that CV's pad while the
8328                  * regex was parsed, except maybe op targets for \Q etc.
8329                  * If there were any op targets, though, they should have
8330                  * been stolen by constant folding.
8331                  */
8332 #ifdef DEBUGGING
8333                 SSize_t i = 0;
8334                 assert(PadnamelistMAXNAMED(PL_comppad_name) == 0);
8335                 while (++i <= AvFILLp(PL_comppad)) {
8336 #  ifdef USE_PAD_RESET
8337                     /* under USE_PAD_RESET, pad swipe replaces a swiped
8338                      * folded constant with a fresh padtmp */
8339                     assert(!PL_curpad[i] || SvPADTMP(PL_curpad[i]));
8340 #  else
8341                     assert(!PL_curpad[i]);
8342 #  endif
8343                 }
8344 #endif
8345                 /* This LEAVE_SCOPE will restore PL_compcv to point to the
8346                  * outer CV (the one whose slab holds the pm op). The
8347                  * inner CV (which holds expr) will be freed later, once
8348                  * all the entries on the parse stack have been popped on
8349                  * return from this function. Which is why its safe to
8350                  * call op_free(expr) below.
8351                  */
8352                 LEAVE_SCOPE(floor);
8353                 pm->op_pmflags &= ~PMf_HAS_CV;
8354             }
8355
8356             /* Skip compiling if parser found an error for this pattern */
8357             if (pm->op_pmflags & PMf_HAS_ERROR) {
8358                 return o;
8359             }
8360
8361             PM_SETRE(pm,
8362                 eng->op_comp
8363                     ? eng->op_comp(aTHX_ NULL, 0, expr, eng, NULL, NULL,
8364                                         rx_flags, pm->op_pmflags)
8365                     : Perl_re_op_compile(aTHX_ NULL, 0, expr, eng, NULL, NULL,
8366                                         rx_flags, pm->op_pmflags)
8367             );
8368             op_free(expr);
8369         }
8370         else {
8371             /* compile-time pattern that includes literal code blocks */
8372
8373             REGEXP* re;
8374
8375             /* Skip compiling if parser found an error for this pattern */
8376             if (pm->op_pmflags & PMf_HAS_ERROR) {
8377                 return o;
8378             }
8379
8380             re = eng->op_comp(aTHX_ NULL, 0, expr, eng, NULL, NULL,
8381                         rx_flags,
8382                         (pm->op_pmflags |
8383                             ((PL_hints & HINT_RE_EVAL) ? PMf_USE_RE_EVAL : 0))
8384                     );
8385             PM_SETRE(pm, re);
8386             if (pm->op_pmflags & PMf_HAS_CV) {
8387                 CV *cv;
8388                 /* this QR op (and the anon sub we embed it in) is never
8389                  * actually executed. It's just a placeholder where we can
8390                  * squirrel away expr in op_code_list without the peephole
8391                  * optimiser etc processing it for a second time */
8392                 OP *qr = newPMOP(OP_QR, 0);
8393                 ((PMOP*)qr)->op_code_list = expr;
8394
8395                 /* handle the implicit sub{} wrapped round the qr/(?{..})/ */
8396                 SvREFCNT_inc_simple_void(PL_compcv);
8397                 cv = newATTRSUB(floor, 0, NULL, NULL, qr);
8398                 ReANY(re)->qr_anoncv = cv;
8399
8400                 /* attach the anon CV to the pad so that
8401                  * pad_fixup_inner_anons() can find it */
8402                 (void)pad_add_anon(cv, o->op_type);
8403                 SvREFCNT_inc_simple_void(cv);
8404             }
8405             else {
8406                 pm->op_code_list = expr;
8407             }
8408         }
8409     }
8410     else {
8411         /* runtime pattern: build chain of regcomp etc ops */
8412         bool reglist;
8413         PADOFFSET cv_targ = 0;
8414
8415         reglist = isreg && expr->op_type == OP_LIST;
8416         if (reglist)
8417             op_null(expr);
8418
8419         if (has_code) {
8420             pm->op_code_list = expr;
8421             /* don't free op_code_list; its ops are embedded elsewhere too */
8422             pm->op_pmflags |= PMf_CODELIST_PRIVATE;
8423         }
8424
8425         if (is_split)
8426             /* make engine handle split ' ' specially */
8427             pm->op_pmflags |= PMf_SPLIT;
8428
8429         /* the OP_REGCMAYBE is a placeholder in the non-threaded case
8430          * to allow its op_next to be pointed past the regcomp and
8431          * preceding stacking ops;
8432          * OP_REGCRESET is there to reset taint before executing the
8433          * stacking ops */
8434         if (pm->op_pmflags & PMf_KEEP || TAINTING_get)
8435             expr = newUNOP((TAINTING_get ? OP_REGCRESET : OP_REGCMAYBE),0,expr);
8436
8437         if (pm->op_pmflags & PMf_HAS_CV) {
8438             /* we have a runtime qr with literal code. This means
8439              * that the qr// has been wrapped in a new CV, which
8440              * means that runtime consts, vars etc will have been compiled
8441              * against a new pad. So... we need to execute those ops
8442              * within the environment of the new CV. So wrap them in a call
8443              * to a new anon sub. i.e. for
8444              *
8445              *     qr/a$b(?{...})/,
8446              *
8447              * we build an anon sub that looks like
8448              *
8449              *     sub { "a", $b, '(?{...})' }
8450              *
8451              * and call it, passing the returned list to regcomp.
8452              * Or to put it another way, the list of ops that get executed
8453              * are:
8454              *
8455              *     normal              PMf_HAS_CV
8456              *     ------              -------------------
8457              *                         pushmark (for regcomp)
8458              *                         pushmark (for entersub)
8459              *                         anoncode
8460              *                         srefgen
8461              *                         entersub
8462              *     regcreset                  regcreset
8463              *     pushmark                   pushmark
8464              *     const("a")                 const("a")
8465              *     gvsv(b)                    gvsv(b)
8466              *     const("(?{...})")          const("(?{...})")
8467              *                                leavesub
8468              *     regcomp             regcomp
8469              */
8470
8471             SvREFCNT_inc_simple_void(PL_compcv);
8472             CvLVALUE_on(PL_compcv);
8473             /* these lines are just an unrolled newANONATTRSUB */
8474             expr = newSVOP(OP_ANONCODE, 0,
8475                     MUTABLE_SV(newATTRSUB(floor, 0, NULL, NULL, expr)));
8476             cv_targ = expr->op_targ;
8477             expr = newUNOP(OP_REFGEN, 0, expr);
8478
8479             expr = list(force_list(newUNOP(OP_ENTERSUB, 0, scalar(expr)), 1));
8480         }
8481
8482         rcop = alloc_LOGOP(OP_REGCOMP, scalar(expr), o);
8483         rcop->op_flags |=  ((PL_hints & HINT_RE_EVAL) ? OPf_SPECIAL : 0)
8484                            | (reglist ? OPf_STACKED : 0);
8485         rcop->op_targ = cv_targ;
8486
8487         /* /$x/ may cause an eval, since $x might be qr/(?{..})/  */
8488         if (PL_hints & HINT_RE_EVAL)
8489             S_set_haseval(aTHX);
8490
8491         /* establish postfix order */
8492         if (expr->op_type == OP_REGCRESET || expr->op_type == OP_REGCMAYBE) {
8493             LINKLIST(expr);
8494             rcop->op_next = expr;
8495             ((UNOP*)expr)->op_first->op_next = (OP*)rcop;
8496         }
8497         else {
8498             rcop->op_next = LINKLIST(expr);
8499             expr->op_next = (OP*)rcop;
8500         }
8501
8502         op_prepend_elem(o->op_type, scalar((OP*)rcop), o);
8503     }
8504
8505     if (repl) {
8506         OP *curop = repl;
8507         bool konst;
8508         /* If we are looking at s//.../e with a single statement, get past
8509            the implicit do{}. */
8510         if (curop->op_type == OP_NULL && curop->op_flags & OPf_KIDS
8511              && cUNOPx(curop)->op_first->op_type == OP_SCOPE
8512              && cUNOPx(curop)->op_first->op_flags & OPf_KIDS)
8513          {
8514             OP *sib;
8515             OP *kid = cUNOPx(cUNOPx(curop)->op_first)->op_first;
8516             if (kid->op_type == OP_NULL && (sib = OpSIBLING(kid))
8517              && !OpHAS_SIBLING(sib))
8518                 curop = sib;
8519         }
8520         if (curop->op_type == OP_CONST)
8521             konst = TRUE;
8522         else if (( (curop->op_type == OP_RV2SV ||
8523                     curop->op_type == OP_RV2AV ||
8524                     curop->op_type == OP_RV2HV ||
8525                     curop->op_type == OP_RV2GV)
8526                    && cUNOPx(curop)->op_first
8527                    && cUNOPx(curop)->op_first->op_type == OP_GV )
8528                 || curop->op_type == OP_PADSV
8529                 || curop->op_type == OP_PADAV
8530                 || curop->op_type == OP_PADHV
8531                 || curop->op_type == OP_PADANY) {
8532             repl_has_vars = 1;
8533             konst = TRUE;
8534         }
8535         else konst = FALSE;
8536         if (konst
8537             && !(repl_has_vars
8538                  && (!PM_GETRE(pm)
8539                      || !RX_PRELEN(PM_GETRE(pm))
8540                      || RX_EXTFLAGS(PM_GETRE(pm)) & RXf_EVAL_SEEN)))
8541         {
8542             pm->op_pmflags |= PMf_CONST;        /* const for long enough */
8543             op_prepend_elem(o->op_type, scalar(repl), o);
8544         }
8545         else {
8546             rcop = alloc_LOGOP(OP_SUBSTCONT, scalar(repl), o);
8547             rcop->op_private = 1;
8548
8549             /* establish postfix order */
8550             rcop->op_next = LINKLIST(repl);
8551             repl->op_next = (OP*)rcop;
8552
8553             pm->op_pmreplrootu.op_pmreplroot = scalar((OP*)rcop);
8554             assert(!(pm->op_pmflags & PMf_ONCE));
8555             pm->op_pmstashstartu.op_pmreplstart = LINKLIST(rcop);
8556             rcop->op_next = 0;
8557         }
8558     }
8559
8560     return (OP*)pm;
8561 }
8562
8563 /*
8564 =for apidoc newSVOP
8565
8566 Constructs, checks, and returns an op of any type that involves an
8567 embedded SV.  C<type> is the opcode.  C<flags> gives the eight bits
8568 of C<op_flags>.  C<sv> gives the SV to embed in the op; this function
8569 takes ownership of one reference to it.
8570
8571 =cut
8572 */
8573
8574 OP *
8575 Perl_newSVOP(pTHX_ I32 type, I32 flags, SV *sv)
8576 {
8577     SVOP *svop;
8578
8579     PERL_ARGS_ASSERT_NEWSVOP;
8580
8581     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_SVOP
8582         || (PL_opargs[type] & OA_CLASS_MASK) == OA_PVOP_OR_SVOP
8583         || (PL_opargs[type] & OA_CLASS_MASK) == OA_FILESTATOP
8584         || type == OP_CUSTOM);
8585
8586     NewOp(1101, svop, 1, SVOP);
8587     OpTYPE_set(svop, type);
8588     svop->op_sv = sv;
8589     svop->op_next = (OP*)svop;
8590     svop->op_flags = (U8)flags;
8591     svop->op_private = (U8)(0 | (flags >> 8));
8592     if (PL_opargs[type] & OA_RETSCALAR)
8593         scalar((OP*)svop);
8594     if (PL_opargs[type] & OA_TARGET)
8595         svop->op_targ = pad_alloc(type, SVs_PADTMP);
8596     return CHECKOP(type, svop);
8597 }
8598
8599 /*
8600 =for apidoc newDEFSVOP
8601
8602 Constructs and returns an op to access C<$_>.
8603
8604 =cut
8605 */
8606
8607 OP *
8608 Perl_newDEFSVOP(pTHX)
8609 {
8610         return newSVREF(newGVOP(OP_GV, 0, PL_defgv));
8611 }
8612
8613 #ifdef USE_ITHREADS
8614
8615 /*
8616 =for apidoc newPADOP
8617
8618 Constructs, checks, and returns an op of any type that involves a
8619 reference to a pad element.  C<type> is the opcode.  C<flags> gives the
8620 eight bits of C<op_flags>.  A pad slot is automatically allocated, and
8621 is populated with C<sv>; this function takes ownership of one reference
8622 to it.
8623
8624 This function only exists if Perl has been compiled to use ithreads.
8625
8626 =cut
8627 */
8628
8629 OP *
8630 Perl_newPADOP(pTHX_ I32 type, I32 flags, SV *sv)
8631 {
8632     PADOP *padop;
8633
8634     PERL_ARGS_ASSERT_NEWPADOP;
8635
8636     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_SVOP
8637         || (PL_opargs[type] & OA_CLASS_MASK) == OA_PVOP_OR_SVOP
8638         || (PL_opargs[type] & OA_CLASS_MASK) == OA_FILESTATOP
8639         || type == OP_CUSTOM);
8640
8641     NewOp(1101, padop, 1, PADOP);
8642     OpTYPE_set(padop, type);
8643     padop->op_padix =
8644         pad_alloc(type, isGV(sv) ? SVf_READONLY : SVs_PADTMP);
8645     SvREFCNT_dec(PAD_SVl(padop->op_padix));
8646     PAD_SETSV(padop->op_padix, sv);
8647     assert(sv);
8648     padop->op_next = (OP*)padop;
8649     padop->op_flags = (U8)flags;
8650     if (PL_opargs[type] & OA_RETSCALAR)
8651         scalar((OP*)padop);
8652     if (PL_opargs[type] & OA_TARGET)
8653         padop->op_targ = pad_alloc(type, SVs_PADTMP);
8654     return CHECKOP(type, padop);
8655 }
8656
8657 #endif /* USE_ITHREADS */
8658
8659 /*
8660 =for apidoc newGVOP
8661
8662 Constructs, checks, and returns an op of any type that involves an
8663 embedded reference to a GV.  C<type> is the opcode.  C<flags> gives the
8664 eight bits of C<op_flags>.  C<gv> identifies the GV that the op should
8665 reference; calling this function does not transfer ownership of any
8666 reference to it.
8667
8668 =cut
8669 */
8670
8671 OP *
8672 Perl_newGVOP(pTHX_ I32 type, I32 flags, GV *gv)
8673 {
8674     PERL_ARGS_ASSERT_NEWGVOP;
8675
8676 #ifdef USE_ITHREADS
8677     return newPADOP(type, flags, SvREFCNT_inc_simple_NN(gv));
8678 #else
8679     return newSVOP(type, flags, SvREFCNT_inc_simple_NN(gv));
8680 #endif
8681 }
8682
8683 /*
8684 =for apidoc newPVOP
8685
8686 Constructs, checks, and returns an op of any type that involves an
8687 embedded C-level pointer (PV).  C<type> is the opcode.  C<flags> gives
8688 the eight bits of C<op_flags>.  C<pv> supplies the C-level pointer.
8689 Depending on the op type, the memory referenced by C<pv> may be freed
8690 when the op is destroyed.  If the op is of a freeing type, C<pv> must
8691 have been allocated using C<PerlMemShared_malloc>.
8692
8693 =cut
8694 */
8695
8696 OP *
8697 Perl_newPVOP(pTHX_ I32 type, I32 flags, char *pv)
8698 {
8699     const bool utf8 = cBOOL(flags & SVf_UTF8);
8700     PVOP *pvop;
8701
8702     flags &= ~SVf_UTF8;
8703
8704     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_PVOP_OR_SVOP
8705         || type == OP_RUNCV || type == OP_CUSTOM
8706         || (PL_opargs[type] & OA_CLASS_MASK) == OA_LOOPEXOP);
8707
8708     NewOp(1101, pvop, 1, PVOP);
8709     OpTYPE_set(pvop, type);
8710     pvop->op_pv = pv;
8711     pvop->op_next = (OP*)pvop;
8712     pvop->op_flags = (U8)flags;
8713     pvop->op_private = utf8 ? OPpPV_IS_UTF8 : 0;
8714     if (PL_opargs[type] & OA_RETSCALAR)
8715         scalar((OP*)pvop);
8716     if (PL_opargs[type] & OA_TARGET)
8717         pvop->op_targ = pad_alloc(type, SVs_PADTMP);
8718     return CHECKOP(type, pvop);
8719 }
8720
8721 void
8722 Perl_package(pTHX_ OP *o)
8723 {
8724     SV *const sv = cSVOPo->op_sv;
8725
8726     PERL_ARGS_ASSERT_PACKAGE;
8727
8728     SAVEGENERICSV(PL_curstash);
8729     save_item(PL_curstname);
8730
8731     PL_curstash = (HV *)SvREFCNT_inc(gv_stashsv(sv, GV_ADD));
8732
8733     sv_setsv(PL_curstname, sv);
8734
8735     PL_hints |= HINT_BLOCK_SCOPE;
8736     PL_parser->copline = NOLINE;
8737
8738     op_free(o);
8739 }
8740
8741 void
8742 Perl_package_version( pTHX_ OP *v )
8743 {
8744     U32 savehints = PL_hints;
8745     PERL_ARGS_ASSERT_PACKAGE_VERSION;
8746     PL_hints &= ~HINT_STRICT_VARS;
8747     sv_setsv( GvSV(gv_fetchpvs("VERSION", GV_ADDMULTI, SVt_PV)), cSVOPx(v)->op_sv );
8748     PL_hints = savehints;
8749     op_free(v);
8750 }
8751
8752 void
8753 Perl_utilize(pTHX_ int aver, I32 floor, OP *version, OP *idop, OP *arg)
8754 {
8755     OP *pack;
8756     OP *imop;
8757     OP *veop;
8758     SV *use_version = NULL;
8759
8760     PERL_ARGS_ASSERT_UTILIZE;
8761
8762     if (idop->op_type != OP_CONST)
8763         Perl_croak(aTHX_ "Module name must be constant");
8764
8765     veop = NULL;
8766
8767     if (version) {
8768         SV * const vesv = ((SVOP*)version)->op_sv;
8769
8770         if (!arg && !SvNIOKp(vesv)) {
8771             arg = version;
8772         }
8773         else {
8774             OP *pack;
8775             SV *meth;
8776
8777             if (version->op_type != OP_CONST || !SvNIOKp(vesv))
8778                 Perl_croak(aTHX_ "Version number must be a constant number");
8779
8780             /* Make copy of idop so we don't free it twice */
8781             pack = newSVOP(OP_CONST, 0, newSVsv(((SVOP*)idop)->op_sv));
8782
8783             /* Fake up a method call to VERSION */
8784             meth = newSVpvs_share("VERSION");
8785             veop = op_convert_list(OP_ENTERSUB, OPf_STACKED|OPf_SPECIAL,
8786                             op_append_elem(OP_LIST,
8787                                         op_prepend_elem(OP_LIST, pack, version),
8788                                         newMETHOP_named(OP_METHOD_NAMED, 0, meth)));
8789         }
8790     }
8791
8792     /* Fake up an import/unimport */
8793     if (arg && arg->op_type == OP_STUB) {
8794         imop = arg;             /* no import on explicit () */
8795     }
8796     else if (SvNIOKp(((SVOP*)idop)->op_sv)) {
8797         imop = NULL;            /* use 5.0; */
8798         if (aver)
8799             use_version = ((SVOP*)idop)->op_sv;
8800         else
8801             idop->op_private |= OPpCONST_NOVER;
8802     }
8803     else {
8804         SV *meth;
8805
8806         /* Make copy of idop so we don't free it twice */
8807         pack = newSVOP(OP_CONST, 0, newSVsv(((SVOP*)idop)->op_sv));
8808
8809         /* Fake up a method call to import/unimport */
8810         meth = aver
8811             ? newSVpvs_share("import") : newSVpvs_share("unimport");
8812         imop = op_convert_list(OP_ENTERSUB, OPf_STACKED|OPf_SPECIAL,
8813                        op_append_elem(OP_LIST,
8814                                    op_prepend_elem(OP_LIST, pack, arg),
8815                                    newMETHOP_named(OP_METHOD_NAMED, 0, meth)
8816                        ));
8817     }
8818
8819     /* Fake up the BEGIN {}, which does its thing immediately. */
8820     newATTRSUB(floor,
8821         newSVOP(OP_CONST, 0, newSVpvs_share("BEGIN")),
8822         NULL,
8823         NULL,
8824         op_append_elem(OP_LINESEQ,
8825             op_append_elem(OP_LINESEQ,
8826                 newSTATEOP(0, NULL, newUNOP(OP_REQUIRE, 0, idop)),
8827                 newSTATEOP(0, NULL, veop)),
8828             newSTATEOP(0, NULL, imop) ));
8829
8830     if (use_version) {
8831         /* Enable the
8832          * feature bundle that corresponds to the required version. */
8833         use_version = sv_2mortal(new_version(use_version));
8834         S_enable_feature_bundle(aTHX_ use_version);
8835
8836         /* If a version >= 5.11.0 is requested, strictures are on by default! */
8837         if (vcmp(use_version,
8838                  sv_2mortal(upg_version(newSVnv(5.011000), FALSE))) >= 0) {
8839             if (!(PL_hints & HINT_EXPLICIT_STRICT_REFS))
8840                 PL_hints |= HINT_STRICT_REFS;
8841             if (!(PL_hints & HINT_EXPLICIT_STRICT_SUBS))
8842                 PL_hints |= HINT_STRICT_SUBS;
8843             if (!(PL_hints & HINT_EXPLICIT_STRICT_VARS))
8844                 PL_hints |= HINT_STRICT_VARS;
8845         }
8846         /* otherwise they are off */
8847         else {
8848             if (!(PL_hints & HINT_EXPLICIT_STRICT_REFS))
8849                 PL_hints &= ~HINT_STRICT_REFS;
8850             if (!(PL_hints & HINT_EXPLICIT_STRICT_SUBS))
8851                 PL_hints &= ~HINT_STRICT_SUBS;
8852             if (!(PL_hints & HINT_EXPLICIT_STRICT_VARS))
8853                 PL_hints &= ~HINT_STRICT_VARS;
8854         }
8855     }
8856
8857     /* The "did you use incorrect case?" warning used to be here.
8858      * The problem is that on case-insensitive filesystems one
8859      * might get false positives for "use" (and "require"):
8860      * "use Strict" or "require CARP" will work.  This causes
8861      * portability problems for the script: in case-strict
8862      * filesystems the script will stop working.
8863      *
8864      * The "incorrect case" warning checked whether "use Foo"
8865      * imported "Foo" to your namespace, but that is wrong, too:
8866      * there is no requirement nor promise in the language that
8867      * a Foo.pm should or would contain anything in package "Foo".
8868      *
8869      * There is very little Configure-wise that can be done, either:
8870      * the case-sensitivity of the build filesystem of Perl does not
8871      * help in guessing the case-sensitivity of the runtime environment.
8872      */
8873
8874     PL_hints |= HINT_BLOCK_SCOPE;
8875     PL_parser->copline = NOLINE;
8876     COP_SEQMAX_INC; /* Purely for B::*'s benefit */
8877 }
8878
8879 /*
8880 =for apidoc_section Embedding and Interpreter Cloning
8881
8882 =for apidoc load_module
8883
8884 Loads the module whose name is pointed to by the string part of C<name>.
8885 Note that the actual module name, not its filename, should be given.
8886 Eg, "Foo::Bar" instead of "Foo/Bar.pm". ver, if specified and not NULL,
8887 provides version semantics similar to C<use Foo::Bar VERSION>. The optional
8888 trailing arguments can be used to specify arguments to the module's C<import()>
8889 method, similar to C<use Foo::Bar VERSION LIST>; their precise handling depends
8890 on the flags. The flags argument is a bitwise-ORed collection of any of
8891 C<PERL_LOADMOD_DENY>, C<PERL_LOADMOD_NOIMPORT>, or C<PERL_LOADMOD_IMPORT_OPS>
8892 (or 0 for no flags).
8893
8894 If C<PERL_LOADMOD_NOIMPORT> is set, the module is loaded as if with an empty
8895 import list, as in C<use Foo::Bar ()>; this is the only circumstance in which
8896 the trailing optional arguments may be omitted entirely. Otherwise, if
8897 C<PERL_LOADMOD_IMPORT_OPS> is set, the trailing arguments must consist of
8898 exactly one C<OP*>, containing the op tree that produces the relevant import
8899 arguments. Otherwise, the trailing arguments must all be C<SV*> values that
8900 will be used as import arguments; and the list must be terminated with C<(SV*)
8901 NULL>. If neither C<PERL_LOADMOD_NOIMPORT> nor C<PERL_LOADMOD_IMPORT_OPS> is
8902 set, the trailing C<NULL> pointer is needed even if no import arguments are
8903 desired. The reference count for each specified C<SV*> argument is
8904 decremented. In addition, the C<name> argument is modified.
8905
8906 If C<PERL_LOADMOD_DENY> is set, the module is loaded as if with C<no> rather
8907 than C<use>.
8908
8909 =for apidoc Amnh||PERL_LOADMOD_DENY
8910 =for apidoc Amnh||PERL_LOADMOD_NOIMPORT
8911 =for apidoc Amnh||PERL_LOADMOD_IMPORT_OPS
8912
8913 =for apidoc vload_module
8914 Like C<L</load_module>> but the arguments are an encapsulated argument list.
8915
8916 =for apidoc load_module_nocontext
8917 Like C<L</load_module>> but does not take a thread context (C<aTHX>) parameter,
8918 so is used in situations where the caller doesn't already have the thread
8919 context.
8920
8921 =cut */
8922
8923 void
8924 Perl_load_module(pTHX_ U32 flags, SV *name, SV *ver, ...)
8925 {
8926     va_list args;
8927
8928     PERL_ARGS_ASSERT_LOAD_MODULE;
8929
8930     va_start(args, ver);
8931     vload_module(flags, name, ver, &args);
8932     va_end(args);
8933 }
8934
8935 #ifdef PERL_IMPLICIT_CONTEXT
8936 void
8937 Perl_load_module_nocontext(U32 flags, SV *name, SV *ver, ...)
8938 {
8939     dTHX;
8940     va_list args;
8941     PERL_ARGS_ASSERT_LOAD_MODULE_NOCONTEXT;
8942     va_start(args, ver);
8943     vload_module(flags, name, ver, &args);
8944     va_end(args);
8945 }
8946 #endif
8947
8948 void
8949 Perl_vload_module(pTHX_ U32 flags, SV *name, SV *ver, va_list *args)
8950 {
8951     OP *veop, *imop;
8952     OP * modname;
8953     I32 floor;
8954
8955     PERL_ARGS_ASSERT_VLOAD_MODULE;
8956
8957     /* utilize() fakes up a BEGIN { require ..; import ... }, so make sure
8958      * that it has a PL_parser to play with while doing that, and also
8959      * that it doesn't mess with any existing parser, by creating a tmp
8960      * new parser with lex_start(). This won't actually be used for much,
8961      * since pp_require() will create another parser for the real work.
8962      * The ENTER/LEAVE pair protect callers from any side effects of use.
8963      *
8964      * start_subparse() creates a new PL_compcv. This means that any ops
8965      * allocated below will be allocated from that CV's op slab, and so
8966      * will be automatically freed if the utilise() fails
8967      */
8968
8969     ENTER;
8970     SAVEVPTR(PL_curcop);
8971     lex_start(NULL, NULL, LEX_START_SAME_FILTER);
8972     floor = start_subparse(FALSE, 0);
8973
8974     modname = newSVOP(OP_CONST, 0, name);
8975     modname->op_private |= OPpCONST_BARE;
8976     if (ver) {
8977         veop = newSVOP(OP_CONST, 0, ver);
8978     }
8979     else
8980         veop = NULL;
8981     if (flags & PERL_LOADMOD_NOIMPORT) {
8982         imop = sawparens(newNULLLIST());
8983     }
8984     else if (flags & PERL_LOADMOD_IMPORT_OPS) {
8985         imop = va_arg(*args, OP*);
8986     }
8987     else {
8988         SV *sv;
8989         imop = NULL;
8990         sv = va_arg(*args, SV*);
8991         while (sv) {
8992             imop = op_append_elem(OP_LIST, imop, newSVOP(OP_CONST, 0, sv));
8993             sv = va_arg(*args, SV*);
8994         }
8995     }
8996
8997     utilize(!(flags & PERL_LOADMOD_DENY), floor, veop, modname, imop);
8998     LEAVE;
8999 }
9000
9001 PERL_STATIC_INLINE OP *
9002 S_new_entersubop(pTHX_ GV *gv, OP *arg)
9003 {
9004     return newUNOP(OP_ENTERSUB, OPf_STACKED,
9005                    newLISTOP(OP_LIST, 0, arg,
9006                              newUNOP(OP_RV2CV, 0,
9007                                      newGVOP(OP_GV, 0, gv))));
9008 }
9009
9010 OP *
9011 Perl_dofile(pTHX_ OP *term, I32 force_builtin)
9012 {
9013     OP *doop;
9014     GV *gv;
9015
9016     PERL_ARGS_ASSERT_DOFILE;
9017
9018     if (!force_builtin && (gv = gv_override("do", 2))) {
9019         doop = S_new_entersubop(aTHX_ gv, term);
9020     }
9021     else {
9022         doop = newUNOP(OP_DOFILE, 0, scalar(term));
9023     }
9024     return doop;
9025 }
9026
9027 /*
9028 =for apidoc_section Optree construction
9029
9030 =for apidoc newSLICEOP
9031
9032 Constructs, checks, and returns an C<lslice> (list slice) op.  C<flags>
9033 gives the eight bits of C<op_flags>, except that C<OPf_KIDS> will
9034 be set automatically, and, shifted up eight bits, the eight bits of
9035 C<op_private>, except that the bit with value 1 or 2 is automatically
9036 set as required.  C<listval> and C<subscript> supply the parameters of
9037 the slice; they are consumed by this function and become part of the
9038 constructed op tree.
9039
9040 =cut
9041 */
9042
9043 OP *
9044 Perl_newSLICEOP(pTHX_ I32 flags, OP *subscript, OP *listval)
9045 {
9046     return newBINOP(OP_LSLICE, flags,
9047             list(force_list(subscript, 1)),
9048             list(force_list(listval,   1)) );
9049 }
9050
9051 #define ASSIGN_SCALAR 0
9052 #define ASSIGN_LIST   1
9053 #define ASSIGN_REF    2
9054
9055 /* given the optree o on the LHS of an assignment, determine whether its:
9056  *  ASSIGN_SCALAR   $x  = ...
9057  *  ASSIGN_LIST    ($x) = ...
9058  *  ASSIGN_REF     \$x  = ...
9059  */
9060
9061 STATIC I32
9062 S_assignment_type(pTHX_ const OP *o)
9063 {
9064     unsigned type;
9065     U8 flags;
9066     U8 ret;
9067
9068     if (!o)
9069         return ASSIGN_LIST;
9070
9071     if (o->op_type == OP_SREFGEN)
9072     {
9073         OP * const kid = cUNOPx(cUNOPo->op_first)->op_first;
9074         type = kid->op_type;
9075         flags = o->op_flags | kid->op_flags;
9076         if (!(flags & OPf_PARENS)
9077           && (kid->op_type == OP_RV2AV || kid->op_type == OP_PADAV ||
9078               kid->op_type == OP_RV2HV || kid->op_type == OP_PADHV ))
9079             return ASSIGN_REF;
9080         ret = ASSIGN_REF;
9081     } else {
9082         if ((o->op_type == OP_NULL) && (o->op_flags & OPf_KIDS))
9083             o = cUNOPo->op_first;
9084         flags = o->op_flags;
9085         type = o->op_type;
9086         ret = ASSIGN_SCALAR;
9087     }
9088
9089     if (type == OP_COND_EXPR) {
9090         OP * const sib = OpSIBLING(cLOGOPo->op_first);
9091         const I32 t = assignment_type(sib);
9092         const I32 f = assignment_type(OpSIBLING(sib));
9093
9094         if (t == ASSIGN_LIST && f == ASSIGN_LIST)
9095             return ASSIGN_LIST;
9096         if ((t == ASSIGN_LIST) ^ (f == ASSIGN_LIST))
9097             yyerror("Assignment to both a list and a scalar");
9098         return ASSIGN_SCALAR;
9099     }
9100
9101     if (type == OP_LIST &&
9102         (flags & OPf_WANT) == OPf_WANT_SCALAR &&
9103         o->op_private & OPpLVAL_INTRO)
9104         return ret;
9105
9106     if (type == OP_LIST || flags & OPf_PARENS ||
9107         type == OP_RV2AV || type == OP_RV2HV ||
9108         type == OP_ASLICE || type == OP_HSLICE ||
9109         type == OP_KVASLICE || type == OP_KVHSLICE || type == OP_REFGEN)
9110         return ASSIGN_LIST;
9111
9112     if (type == OP_PADAV || type == OP_PADHV)
9113         return ASSIGN_LIST;
9114
9115     if (type == OP_RV2SV)
9116         return ret;
9117
9118     return ret;
9119 }
9120
9121 static OP *
9122 S_newONCEOP(pTHX_ OP *initop, OP *padop)
9123 {
9124     const PADOFFSET target = padop->op_targ;
9125     OP *const other = newOP(OP_PADSV,
9126                             padop->op_flags
9127                             | ((padop->op_private & ~OPpLVAL_INTRO) << 8));
9128     OP *const first = newOP(OP_NULL, 0);
9129     OP *const nullop = newCONDOP(0, first, initop, other);
9130     /* XXX targlex disabled for now; see ticket #124160
9131         newCONDOP(0, first, S_maybe_targlex(aTHX_ initop), other);
9132      */
9133     OP *const condop = first->op_next;
9134
9135     OpTYPE_set(condop, OP_ONCE);
9136     other->op_targ = target;
9137     nullop->op_flags |= OPf_WANT_SCALAR;
9138
9139     /* Store the initializedness of state vars in a separate
9140        pad entry.  */
9141     condop->op_targ =
9142       pad_add_name_pvn("$",1,padadd_NO_DUP_CHECK|padadd_STATE,0,0);
9143     /* hijacking PADSTALE for uninitialized state variables */
9144     SvPADSTALE_on(PAD_SVl(condop->op_targ));
9145
9146     return nullop;
9147 }
9148
9149 /*
9150 =for apidoc newASSIGNOP
9151
9152 Constructs, checks, and returns an assignment op.  C<left> and C<right>
9153 supply the parameters of the assignment; they are consumed by this
9154 function and become part of the constructed op tree.
9155
9156 If C<optype> is C<OP_ANDASSIGN>, C<OP_ORASSIGN>, or C<OP_DORASSIGN>, then
9157 a suitable conditional optree is constructed.  If C<optype> is the opcode
9158 of a binary operator, such as C<OP_BIT_OR>, then an op is constructed that
9159 performs the binary operation and assigns the result to the left argument.
9160 Either way, if C<optype> is non-zero then C<flags> has no effect.
9161
9162 If C<optype> is zero, then a plain scalar or list assignment is
9163 constructed.  Which type of assignment it is is automatically determined.
9164 C<flags> gives the eight bits of C<op_flags>, except that C<OPf_KIDS>
9165 will be set automatically, and, shifted up eight bits, the eight bits
9166 of C<op_private>, except that the bit with value 1 or 2 is automatically
9167 set as required.
9168
9169 =cut
9170 */
9171
9172 OP *
9173 Perl_newASSIGNOP(pTHX_ I32 flags, OP *left, I32 optype, OP *right)
9174 {
9175     OP *o;
9176     I32 assign_type;
9177
9178     if (optype) {
9179         if (optype == OP_ANDASSIGN || optype == OP_ORASSIGN || optype == OP_DORASSIGN) {
9180             right = scalar(right);
9181             return newLOGOP(optype, 0,
9182                 op_lvalue(scalar(left), optype),
9183                 newBINOP(OP_SASSIGN, OPpASSIGN_BACKWARDS<<8, right, right));
9184         }
9185         else {
9186             return newBINOP(optype, OPf_STACKED,
9187                 op_lvalue(scalar(left), optype), scalar(right));
9188         }
9189     }
9190
9191     if ((assign_type = assignment_type(left)) == ASSIGN_LIST) {
9192         OP *state_var_op = NULL;
9193         static const char no_list_state[] = "Initialization of state variables"
9194             " in list currently forbidden";
9195         OP *curop;
9196
9197         if (left->op_type == OP_ASLICE || left->op_type == OP_HSLICE)
9198             left->op_private &= ~ OPpSLICEWARNING;
9199
9200         PL_modcount = 0;
9201         left = op_lvalue(left, OP_AASSIGN);
9202         curop = list(force_list(left, 1));
9203         o = newBINOP(OP_AASSIGN, flags, list(force_list(right, 1)), curop);
9204         o->op_private = (U8)(0 | (flags >> 8));
9205
9206         if (OP_TYPE_IS_OR_WAS(left, OP_LIST))
9207         {
9208             OP *lop = ((LISTOP*)left)->op_first, *vop, *eop;
9209             if (!(left->op_flags & OPf_PARENS) &&
9210                     lop->op_type == OP_PUSHMARK &&
9211                     (vop = OpSIBLING(lop)) &&
9212                     (vop->op_type == OP_PADAV || vop->op_type == OP_PADHV) &&
9213                     !(vop->op_flags & OPf_PARENS) &&
9214                     (vop->op_private & (OPpLVAL_INTRO|OPpPAD_STATE)) ==
9215                         (OPpLVAL_INTRO|OPpPAD_STATE) &&
9216                     (eop = OpSIBLING(vop)) &&
9217                     eop->op_type == OP_ENTERSUB &&
9218                     !OpHAS_SIBLING(eop)) {
9219                 state_var_op = vop;
9220             } else {
9221                 while (lop) {
9222                     if ((lop->op_type == OP_PADSV ||
9223                          lop->op_type == OP_PADAV ||
9224                          lop->op_type == OP_PADHV ||
9225                          lop->op_type == OP_PADANY)
9226                       && (lop->op_private & OPpPAD_STATE)
9227                     )
9228                         yyerror(no_list_state);
9229                     lop = OpSIBLING(lop);
9230                 }
9231             }
9232         }
9233         else if (  (left->op_private & OPpLVAL_INTRO)
9234                 && (left->op_private & OPpPAD_STATE)
9235                 && (   left->op_type == OP_PADSV
9236                     || left->op_type == OP_PADAV
9237                     || left->op_type == OP_PADHV
9238                     || left->op_type == OP_PADANY)
9239         ) {
9240                 /* All single variable list context state assignments, hence
9241                    state ($a) = ...
9242                    (state $a) = ...
9243                    state @a = ...
9244                    state (@a) = ...
9245                    (state @a) = ...
9246                    state %a = ...
9247                    state (%a) = ...
9248                    (state %a) = ...
9249                 */
9250                 if (left->op_flags & OPf_PARENS)
9251                     yyerror(no_list_state);
9252                 else
9253                     state_var_op = left;
9254         }
9255
9256         /* optimise @a = split(...) into:
9257         * @{expr}:              split(..., @{expr}) (where @a is not flattened)
9258         * @a, my @a, local @a:  split(...)          (where @a is attached to
9259         *                                            the split op itself)
9260         */
9261
9262         if (   right
9263             && right->op_type == OP_SPLIT
9264             /* don't do twice, e.g. @b = (@a = split) */
9265             && !(right->op_private & OPpSPLIT_ASSIGN))
9266         {
9267             OP *gvop = NULL;
9268
9269             if (   (  left->op_type == OP_RV2AV
9270                    && (gvop=((UNOP*)left)->op_first)->op_type==OP_GV)
9271                 || left->op_type == OP_PADAV)
9272             {
9273                 /* @pkg or @lex or local @pkg' or 'my @lex' */
9274                 OP *tmpop;
9275                 if (gvop) {
9276 #ifdef USE_ITHREADS
9277                     ((PMOP*)right)->op_pmreplrootu.op_pmtargetoff
9278                         = cPADOPx(gvop)->op_padix;
9279                     cPADOPx(gvop)->op_padix = 0;        /* steal it */
9280 #else
9281                     ((PMOP*)right)->op_pmreplrootu.op_pmtargetgv
9282                         = MUTABLE_GV(cSVOPx(gvop)->op_sv);
9283                     cSVOPx(gvop)->op_sv = NULL; /* steal it */
9284 #endif
9285                     right->op_private |=
9286                         left->op_private & OPpOUR_INTRO;
9287                 }
9288                 else {
9289                     ((PMOP*)right)->op_pmreplrootu.op_pmtargetoff = left->op_targ;
9290                     left->op_targ = 0;  /* steal it */
9291                     right->op_private |= OPpSPLIT_LEX;
9292                 }
9293                 right->op_private |= left->op_private & OPpLVAL_INTRO;
9294
9295               detach_split:
9296                 tmpop = cUNOPo->op_first;       /* to list (nulled) */
9297                 tmpop = ((UNOP*)tmpop)->op_first; /* to pushmark */
9298                 assert(OpSIBLING(tmpop) == right);
9299                 assert(!OpHAS_SIBLING(right));
9300                 /* detach the split subtreee from the o tree,
9301                  * then free the residual o tree */
9302                 op_sibling_splice(cUNOPo->op_first, tmpop, 1, NULL);
9303                 op_free(o);                     /* blow off assign */
9304                 right->op_private |= OPpSPLIT_ASSIGN;
9305                 right->op_flags &= ~OPf_WANT;
9306                         /* "I don't know and I don't care." */
9307                 return right;
9308             }
9309             else if (left->op_type == OP_RV2AV) {
9310                 /* @{expr} */
9311
9312                 OP *pushop = cUNOPx(cBINOPo->op_last)->op_first;
9313                 assert(OpSIBLING(pushop) == left);
9314                 /* Detach the array ...  */
9315                 op_sibling_splice(cBINOPo->op_last, pushop, 1, NULL);
9316                 /* ... and attach it to the split.  */
9317                 op_sibling_splice(right, cLISTOPx(right)->op_last,
9318                                   0, left);
9319                 right->op_flags |= OPf_STACKED;
9320                 /* Detach split and expunge aassign as above.  */
9321                 goto detach_split;
9322             }
9323             else if (PL_modcount < RETURN_UNLIMITED_NUMBER &&
9324                     ((LISTOP*)right)->op_last->op_type == OP_CONST)
9325             {
9326                 /* convert split(...,0) to split(..., PL_modcount+1) */
9327                 SV ** const svp =
9328                     &((SVOP*)((LISTOP*)right)->op_last)->op_sv;
9329                 SV * const sv = *svp;
9330                 if (SvIOK(sv) && SvIVX(sv) == 0)
9331                 {
9332                   if (right->op_private & OPpSPLIT_IMPLIM) {
9333                     /* our own SV, created in ck_split */
9334                     SvREADONLY_off(sv);
9335                     sv_setiv(sv, PL_modcount+1);
9336                   }
9337                   else {
9338                     /* SV may belong to someone else */
9339                     SvREFCNT_dec(sv);
9340                     *svp = newSViv(PL_modcount+1);
9341                   }
9342                 }
9343             }
9344         }
9345
9346         if (state_var_op)
9347             o = S_newONCEOP(aTHX_ o, state_var_op);
9348         return o;
9349     }
9350     if (assign_type == ASSIGN_REF)
9351         return newBINOP(OP_REFASSIGN, flags, scalar(right), left);
9352     if (!right)
9353         right = newOP(OP_UNDEF, 0);
9354     if (right->op_type == OP_READLINE) {
9355         right->op_flags |= OPf_STACKED;
9356         return newBINOP(OP_NULL, flags, op_lvalue(scalar(left), OP_SASSIGN),
9357                 scalar(right));
9358     }
9359     else {
9360         o = newBINOP(OP_SASSIGN, flags,
9361             scalar(right), op_lvalue(scalar(left), OP_SASSIGN) );
9362     }
9363     return o;
9364 }
9365
9366 /*
9367 =for apidoc newSTATEOP
9368
9369 Constructs a state op (COP).  The state op is normally a C<nextstate> op,
9370 but will be a C<dbstate> op if debugging is enabled for currently-compiled
9371 code.  The state op is populated from C<PL_curcop> (or C<PL_compiling>).
9372 If C<label> is non-null, it supplies the name of a label to attach to
9373 the state op; this function takes ownership of the memory pointed at by
9374 C<label>, and will free it.  C<flags> gives the eight bits of C<op_flags>
9375 for the state op.
9376
9377 If C<o> is null, the state op is returned.  Otherwise the state op is
9378 combined with C<o> into a C<lineseq> list op, which is returned.  C<o>
9379 is consumed by this function and becomes part of the returned op tree.
9380
9381 =cut
9382 */
9383
9384 OP *
9385 Perl_newSTATEOP(pTHX_ I32 flags, char *label, OP *o)
9386 {
9387     const U32 seq = intro_my();
9388     const U32 utf8 = flags & SVf_UTF8;
9389     COP *cop;
9390
9391     PL_parser->parsed_sub = 0;
9392
9393     flags &= ~SVf_UTF8;
9394
9395     NewOp(1101, cop, 1, COP);
9396     if (PERLDB_LINE && CopLINE(PL_curcop) && PL_curstash != PL_debstash) {
9397         OpTYPE_set(cop, OP_DBSTATE);
9398     }
9399     else {
9400         OpTYPE_set(cop, OP_NEXTSTATE);
9401     }
9402     cop->op_flags = (U8)flags;
9403     CopHINTS_set(cop, PL_hints);
9404 #ifdef VMS
9405     if (VMSISH_HUSHED) cop->op_private |= OPpHUSH_VMSISH;
9406 #endif
9407     cop->op_next = (OP*)cop;
9408
9409     cop->cop_seq = seq;
9410     cop->cop_warnings = DUP_WARNINGS(PL_curcop->cop_warnings);
9411     CopHINTHASH_set(cop, cophh_copy(CopHINTHASH_get(PL_curcop)));
9412     if (label) {
9413         Perl_cop_store_label(aTHX_ cop, label, strlen(label), utf8);
9414
9415         PL_hints |= HINT_BLOCK_SCOPE;
9416         /* It seems that we need to defer freeing this pointer, as other parts
9417            of the grammar end up wanting to copy it after this op has been
9418            created. */
9419         SAVEFREEPV(label);
9420     }
9421
9422     if (PL_parser->preambling != NOLINE) {
9423         CopLINE_set(cop, PL_parser->preambling);
9424         PL_parser->copline = NOLINE;
9425     }
9426     else if (PL_parser->copline == NOLINE)
9427         CopLINE_set(cop, CopLINE(PL_curcop));
9428     else {
9429         CopLINE_set(cop, PL_parser->copline);
9430         PL_parser->copline = NOLINE;
9431     }
9432 #ifdef USE_ITHREADS
9433     CopFILE_set(cop, CopFILE(PL_curcop));       /* XXX share in a pvtable? */
9434 #else
9435     CopFILEGV_set(cop, CopFILEGV(PL_curcop));
9436 #endif
9437     CopSTASH_set(cop, PL_curstash);
9438
9439     if (cop->op_type == OP_DBSTATE) {
9440         /* this line can have a breakpoint - store the cop in IV */
9441         AV *av = CopFILEAVx(PL_curcop);
9442         if (av) {
9443             SV * const * const svp = av_fetch(av, CopLINE(cop), FALSE);
9444             if (svp && *svp != &PL_sv_undef ) {
9445                 (void)SvIOK_on(*svp);
9446                 SvIV_set(*svp, PTR2IV(cop));
9447             }
9448         }
9449     }
9450
9451     if (flags & OPf_SPECIAL)
9452         op_null((OP*)cop);
9453     return op_prepend_elem(OP_LINESEQ, (OP*)cop, o);
9454 }
9455
9456 /*
9457 =for apidoc newLOGOP
9458
9459 Constructs, checks, and returns a logical (flow control) op.  C<type>
9460 is the opcode.  C<flags> gives the eight bits of C<op_flags>, except
9461 that C<OPf_KIDS> will be set automatically, and, shifted up eight bits,
9462 the eight bits of C<op_private>, except that the bit with value 1 is
9463 automatically set.  C<first> supplies the expression controlling the
9464 flow, and C<other> supplies the side (alternate) chain of ops; they are
9465 consumed by this function and become part of the constructed op tree.
9466
9467 =cut
9468 */
9469
9470 OP *
9471 Perl_newLOGOP(pTHX_ I32 type, I32 flags, OP *first, OP *other)
9472 {
9473     PERL_ARGS_ASSERT_NEWLOGOP;
9474
9475     return new_logop(type, flags, &first, &other);
9476 }
9477
9478
9479 /* See if the optree o contains a single OP_CONST (plus possibly
9480  * surrounding enter/nextstate/null etc). If so, return it, else return
9481  * NULL.
9482  */
9483
9484 STATIC OP *
9485 S_search_const(pTHX_ OP *o)
9486 {
9487     PERL_ARGS_ASSERT_SEARCH_CONST;
9488
9489   redo:
9490     switch (o->op_type) {
9491         case OP_CONST:
9492             return o;
9493         case OP_NULL:
9494             if (o->op_flags & OPf_KIDS) {
9495                 o = cUNOPo->op_first;
9496                 goto redo;
9497             }
9498             break;
9499         case OP_LEAVE:
9500         case OP_SCOPE:
9501         case OP_LINESEQ:
9502         {
9503             OP *kid;
9504             if (!(o->op_flags & OPf_KIDS))
9505                 return NULL;
9506             kid = cLISTOPo->op_first;
9507
9508             do {
9509                 switch (kid->op_type) {
9510                     case OP_ENTER:
9511                     case OP_NULL:
9512                     case OP_NEXTSTATE:
9513                         kid = OpSIBLING(kid);
9514                         break;
9515                     default:
9516                         if (kid != cLISTOPo->op_last)
9517                             return NULL;
9518                         goto last;
9519                 }
9520             } while (kid);
9521
9522             if (!kid)
9523                 kid = cLISTOPo->op_last;
9524           last:
9525              o = kid;
9526              goto redo;
9527         }
9528     }
9529
9530     return NULL;
9531 }
9532
9533
9534 STATIC OP *
9535 S_new_logop(pTHX_ I32 type, I32 flags, OP** firstp, OP** otherp)
9536 {
9537     LOGOP *logop;
9538     OP *o;
9539     OP *first;
9540     OP *other;
9541     OP *cstop = NULL;
9542     int prepend_not = 0;
9543
9544     PERL_ARGS_ASSERT_NEW_LOGOP;
9545
9546     first = *firstp;
9547     other = *otherp;
9548
9549     /* [perl #59802]: Warn about things like "return $a or $b", which
9550        is parsed as "(return $a) or $b" rather than "return ($a or
9551        $b)".  NB: This also applies to xor, which is why we do it
9552        here.
9553      */
9554     switch (first->op_type) {
9555     case OP_NEXT:
9556     case OP_LAST:
9557     case OP_REDO:
9558         /* XXX: Perhaps we should emit a stronger warning for these.
9559            Even with the high-precedence operator they don't seem to do
9560            anything sensible.
9561
9562            But until we do, fall through here.
9563          */
9564     case OP_RETURN:
9565     case OP_EXIT:
9566     case OP_DIE:
9567     case OP_GOTO:
9568         /* XXX: Currently we allow people to "shoot themselves in the
9569            foot" by explicitly writing "(return $a) or $b".
9570
9571            Warn unless we are looking at the result from folding or if
9572            the programmer explicitly grouped the operators like this.
9573            The former can occur with e.g.
9574
9575                 use constant FEATURE => ( $] >= ... );
9576                 sub { not FEATURE and return or do_stuff(); }
9577          */
9578         if (!first->op_folded && !(first->op_flags & OPf_PARENS))
9579             Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX),
9580                            "Possible precedence issue with control flow operator");
9581         /* XXX: Should we optimze this to "return $a;" (i.e. remove
9582            the "or $b" part)?
9583         */
9584         break;
9585     }
9586
9587     if (type == OP_XOR)         /* Not short circuit, but here by precedence. */
9588         return newBINOP(type, flags, scalar(first), scalar(other));
9589
9590     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_LOGOP
9591         || type == OP_CUSTOM);
9592
9593     scalarboolean(first);
9594
9595     /* search for a constant op that could let us fold the test */
9596     if ((cstop = search_const(first))) {
9597         if (cstop->op_private & OPpCONST_STRICT)
9598             no_bareword_allowed(cstop);
9599         else if ((cstop->op_private & OPpCONST_BARE))
9600                 Perl_ck_warner(aTHX_ packWARN(WARN_BAREWORD), "Bareword found in conditional");
9601         if ((type == OP_AND &&  SvTRUE(((SVOP*)cstop)->op_sv)) ||
9602             (type == OP_OR  && !SvTRUE(((SVOP*)cstop)->op_sv)) ||
9603             (type == OP_DOR && !SvOK(((SVOP*)cstop)->op_sv))) {
9604             /* Elide the (constant) lhs, since it can't affect the outcome */
9605             *firstp = NULL;
9606             if (other->op_type == OP_CONST)
9607                 other->op_private |= OPpCONST_SHORTCIRCUIT;
9608             op_free(first);
9609             if (other->op_type == OP_LEAVE)
9610                 other = newUNOP(OP_NULL, OPf_SPECIAL, other);
9611             else if (other->op_type == OP_MATCH
9612                   || other->op_type == OP_SUBST
9613                   || other->op_type == OP_TRANSR
9614                   || other->op_type == OP_TRANS)
9615                 /* Mark the op as being unbindable with =~ */
9616                 other->op_flags |= OPf_SPECIAL;
9617
9618             other->op_folded = 1;
9619             return other;
9620         }
9621         else {
9622             /* Elide the rhs, since the outcome is entirely determined by
9623              * the (constant) lhs */
9624
9625             /* check for C<my $x if 0>, or C<my($x,$y) if 0> */
9626             const OP *o2 = other;
9627             if ( ! (o2->op_type == OP_LIST
9628                     && (( o2 = cUNOPx(o2)->op_first))
9629                     && o2->op_type == OP_PUSHMARK
9630                     && (( o2 = OpSIBLING(o2))) )
9631             )
9632                 o2 = other;
9633             if ((o2->op_type == OP_PADSV || o2->op_type == OP_PADAV
9634                         || o2->op_type == OP_PADHV)
9635                 && o2->op_private & OPpLVAL_INTRO
9636                 && !(o2->op_private & OPpPAD_STATE))
9637             {
9638         Perl_croak(aTHX_ "This use of my() in false conditional is "
9639                           "no longer allowed");
9640             }
9641
9642             *otherp = NULL;
9643             if (cstop->op_type == OP_CONST)
9644                 cstop->op_private |= OPpCONST_SHORTCIRCUIT;
9645             op_free(other);
9646             return first;
9647         }
9648     }
9649     else if ((first->op_flags & OPf_KIDS) && type != OP_DOR
9650         && ckWARN(WARN_MISC)) /* [#24076] Don't warn for <FH> err FOO. */
9651     {
9652         const OP * const k1 = ((UNOP*)first)->op_first;
9653         const OP * const k2 = OpSIBLING(k1);
9654         OPCODE warnop = 0;
9655         switch (first->op_type)
9656         {
9657         case OP_NULL:
9658             if (k2 && k2->op_type == OP_READLINE
9659                   && (k2->op_flags & OPf_STACKED)
9660                   && ((k1->op_flags & OPf_WANT) == OPf_WANT_SCALAR))
9661             {
9662                 warnop = k2->op_type;
9663             }
9664             break;
9665
9666         case OP_SASSIGN:
9667             if (k1->op_type == OP_READDIR
9668                   || k1->op_type == OP_GLOB
9669                   || (k1->op_type == OP_NULL && k1->op_targ == OP_GLOB)
9670                  || k1->op_type == OP_EACH
9671                  || k1->op_type == OP_AEACH)
9672             {
9673                 warnop = ((k1->op_type == OP_NULL)
9674                           ? (OPCODE)k1->op_targ : k1->op_type);
9675             }
9676             break;
9677         }
9678         if (warnop) {
9679             const line_t oldline = CopLINE(PL_curcop);
9680             /* This ensures that warnings are reported at the first line
9681                of the construction, not the last.  */
9682             CopLINE_set(PL_curcop, PL_parser->copline);
9683             Perl_warner(aTHX_ packWARN(WARN_MISC),
9684                  "Value of %s%s can be \"0\"; test with defined()",
9685                  PL_op_desc[warnop],
9686                  ((warnop == OP_READLINE || warnop == OP_GLOB)
9687                   ? " construct" : "() operator"));
9688             CopLINE_set(PL_curcop, oldline);
9689         }
9690     }
9691
9692     /* optimize AND and OR ops that have NOTs as children */
9693     if (first->op_type == OP_NOT
9694         && (first->op_flags & OPf_KIDS)
9695         && ((first->op_flags & OPf_SPECIAL) /* unless ($x) { } */
9696             || (other->op_type == OP_NOT))  /* if (!$x && !$y) { } */
9697         ) {
9698         if (type == OP_AND || type == OP_OR) {
9699             if (type == OP_AND)
9700                 type = OP_OR;
9701             else
9702                 type = OP_AND;
9703             op_null(first);
9704             if (other->op_type == OP_NOT) { /* !a AND|OR !b => !(a OR|AND b) */
9705                 op_null(other);
9706                 prepend_not = 1; /* prepend a NOT op later */
9707             }
9708         }
9709     }
9710
9711     logop = alloc_LOGOP(type, first, LINKLIST(other));
9712     logop->op_flags |= (U8)flags;
9713     logop->op_private = (U8)(1 | (flags >> 8));
9714
9715     /* establish postfix order */
9716     logop->op_next = LINKLIST(first);
9717     first->op_next = (OP*)logop;
9718     assert(!OpHAS_SIBLING(first));
9719     op_sibling_splice((OP*)logop, first, 0, other);
9720
9721     CHECKOP(type,logop);
9722
9723     o = newUNOP(prepend_not ? OP_NOT : OP_NULL,
9724                 PL_opargs[type] & OA_RETSCALAR ? OPf_WANT_SCALAR : 0,
9725                 (OP*)logop);
9726     other->op_next = o;
9727
9728     return o;
9729 }
9730
9731 /*
9732 =for apidoc newCONDOP
9733
9734 Constructs, checks, and returns a conditional-expression (C<cond_expr>)
9735 op.  C<flags> gives the eight bits of C<op_flags>, except that C<OPf_KIDS>
9736 will be set automatically, and, shifted up eight bits, the eight bits of
9737 C<op_private>, except that the bit with value 1 is automatically set.
9738 C<first> supplies the expression selecting between the two branches,
9739 and C<trueop> and C<falseop> supply the branches; they are consumed by
9740 this function and become part of the constructed op tree.
9741
9742 =cut
9743 */
9744
9745 OP *
9746 Perl_newCONDOP(pTHX_ I32 flags, OP *first, OP *trueop, OP *falseop)
9747 {
9748     LOGOP *logop;
9749     OP *start;
9750     OP *o;
9751     OP *cstop;
9752
9753     PERL_ARGS_ASSERT_NEWCONDOP;
9754
9755     if (!falseop)
9756         return newLOGOP(OP_AND, 0, first, trueop);
9757     if (!trueop)
9758         return newLOGOP(OP_OR, 0, first, falseop);
9759
9760     scalarboolean(first);
9761     if ((cstop = search_const(first))) {
9762         /* Left or right arm of the conditional?  */
9763         const bool left = SvTRUE(((SVOP*)cstop)->op_sv);
9764         OP *live = left ? trueop : falseop;
9765         OP *const dead = left ? falseop : trueop;
9766         if (cstop->op_private & OPpCONST_BARE &&
9767             cstop->op_private & OPpCONST_STRICT) {
9768             no_bareword_allowed(cstop);
9769         }
9770         op_free(first);
9771         op_free(dead);
9772         if (live->op_type == OP_LEAVE)
9773             live = newUNOP(OP_NULL, OPf_SPECIAL, live);
9774         else if (live->op_type == OP_MATCH || live->op_type == OP_SUBST
9775               || live->op_type == OP_TRANS || live->op_type == OP_TRANSR)
9776             /* Mark the op as being unbindable with =~ */
9777             live->op_flags |= OPf_SPECIAL;
9778         live->op_folded = 1;
9779         return live;
9780     }
9781     logop = alloc_LOGOP(OP_COND_EXPR, first, LINKLIST(trueop));
9782     logop->op_flags |= (U8)flags;
9783     logop->op_private = (U8)(1 | (flags >> 8));
9784     logop->op_next = LINKLIST(falseop);
9785
9786     CHECKOP(OP_COND_EXPR, /* that's logop->op_type */
9787             logop);
9788
9789     /* establish postfix order */
9790     start = LINKLIST(first);
9791     first->op_next = (OP*)logop;
9792
9793     /* make first, trueop, falseop siblings */
9794     op_sibling_splice((OP*)logop, first,  0, trueop);
9795     op_sibling_splice((OP*)logop, trueop, 0, falseop);
9796
9797     o = newUNOP(OP_NULL, 0, (OP*)logop);
9798
9799     trueop->op_next = falseop->op_next = o;
9800
9801     o->op_next = start;
9802     return o;
9803 }
9804
9805 /*
9806 =for apidoc newRANGE
9807
9808 Constructs and returns a C<range> op, with subordinate C<flip> and
9809 C<flop> ops.  C<flags> gives the eight bits of C<op_flags> for the
9810 C<flip> op and, shifted up eight bits, the eight bits of C<op_private>
9811 for both the C<flip> and C<range> ops, except that the bit with value
9812 1 is automatically set.  C<left> and C<right> supply the expressions
9813 controlling the endpoints of the range; they are consumed by this function
9814 and become part of the constructed op tree.
9815
9816 =cut
9817 */
9818
9819 OP *
9820 Perl_newRANGE(pTHX_ I32 flags, OP *left, OP *right)
9821 {
9822     LOGOP *range;
9823     OP *flip;
9824     OP *flop;
9825     OP *leftstart;
9826     OP *o;
9827
9828     PERL_ARGS_ASSERT_NEWRANGE;
9829
9830     range = alloc_LOGOP(OP_RANGE, left, LINKLIST(right));
9831     range->op_flags = OPf_KIDS;
9832     leftstart = LINKLIST(left);
9833     range->op_private = (U8)(1 | (flags >> 8));
9834
9835     /* make left and right siblings */
9836     op_sibling_splice((OP*)range, left, 0, right);
9837
9838     range->op_next = (OP*)range;
9839     flip = newUNOP(OP_FLIP, flags, (OP*)range);
9840     flop = newUNOP(OP_FLOP, 0, flip);
9841     o = newUNOP(OP_NULL, 0, flop);
9842     LINKLIST(flop);
9843     range->op_next = leftstart;
9844
9845     left->op_next = flip;
9846     right->op_next = flop;
9847
9848     range->op_targ =
9849         pad_add_name_pvn("$", 1, padadd_NO_DUP_CHECK|padadd_STATE, 0, 0);
9850     sv_upgrade(PAD_SV(range->op_targ), SVt_PVNV);
9851     flip->op_targ =
9852         pad_add_name_pvn("$", 1, padadd_NO_DUP_CHECK|padadd_STATE, 0, 0);;
9853     sv_upgrade(PAD_SV(flip->op_targ), SVt_PVNV);
9854     SvPADTMP_on(PAD_SV(flip->op_targ));
9855
9856     flip->op_private =  left->op_type == OP_CONST ? OPpFLIP_LINENUM : 0;
9857     flop->op_private = right->op_type == OP_CONST ? OPpFLIP_LINENUM : 0;
9858
9859     /* check barewords before they might be optimized aways */
9860     if (flip->op_private && cSVOPx(left)->op_private & OPpCONST_STRICT)
9861         no_bareword_allowed(left);
9862     if (flop->op_private && cSVOPx(right)->op_private & OPpCONST_STRICT)
9863         no_bareword_allowed(right);
9864
9865     flip->op_next = o;
9866     if (!flip->op_private || !flop->op_private)
9867         LINKLIST(o);            /* blow off optimizer unless constant */
9868
9869     return o;
9870 }
9871
9872 /*
9873 =for apidoc newLOOPOP
9874
9875 Constructs, checks, and returns an op tree expressing a loop.  This is
9876 only a loop in the control flow through the op tree; it does not have
9877 the heavyweight loop structure that allows exiting the loop by C<last>
9878 and suchlike.  C<flags> gives the eight bits of C<op_flags> for the
9879 top-level op, except that some bits will be set automatically as required.
9880 C<expr> supplies the expression controlling loop iteration, and C<block>
9881 supplies the body of the loop; they are consumed by this function and
9882 become part of the constructed op tree.  C<debuggable> is currently
9883 unused and should always be 1.
9884
9885 =cut
9886 */
9887
9888 OP *
9889 Perl_newLOOPOP(pTHX_ I32 flags, I32 debuggable, OP *expr, OP *block)
9890 {
9891     OP* listop;
9892     OP* o;
9893     const bool once = block && block->op_flags & OPf_SPECIAL &&
9894                       block->op_type == OP_NULL;
9895
9896     PERL_UNUSED_ARG(debuggable);
9897
9898     if (expr) {
9899         if (once && (
9900               (expr->op_type == OP_CONST && !SvTRUE(((SVOP*)expr)->op_sv))
9901            || (  expr->op_type == OP_NOT
9902               && cUNOPx(expr)->op_first->op_type == OP_CONST
9903               && SvTRUE(cSVOPx_sv(cUNOPx(expr)->op_first))
9904               )
9905            ))
9906             /* Return the block now, so that S_new_logop does not try to
9907                fold it away. */
9908         {
9909             op_free(expr);
9910             return block;       /* do {} while 0 does once */
9911         }
9912
9913         if (expr->op_type == OP_READLINE
9914             || expr->op_type == OP_READDIR
9915             || expr->op_type == OP_GLOB
9916             || expr->op_type == OP_EACH || expr->op_type == OP_AEACH
9917             || (expr->op_type == OP_NULL && expr->op_targ == OP_GLOB)) {
9918             expr = newUNOP(OP_DEFINED, 0,
9919                 newASSIGNOP(0, newDEFSVOP(), 0, expr) );
9920         } else if (expr->op_flags & OPf_KIDS) {
9921             const OP * const k1 = ((UNOP*)expr)->op_first;
9922             const OP * const k2 = k1 ? OpSIBLING(k1) : NULL;
9923             switch (expr->op_type) {
9924               case OP_NULL:
9925                 if (k2 && (k2->op_type == OP_READLINE || k2->op_type == OP_READDIR)
9926                       && (k2->op_flags & OPf_STACKED)
9927                       && ((k1->op_flags & OPf_WANT) == OPf_WANT_SCALAR))
9928                     expr = newUNOP(OP_DEFINED, 0, expr);
9929                 break;
9930
9931               case OP_SASSIGN:
9932                 if (k1 && (k1->op_type == OP_READDIR
9933                       || k1->op_type == OP_GLOB
9934                       || (k1->op_type == OP_NULL && k1->op_targ == OP_GLOB)
9935                      || k1->op_type == OP_EACH
9936                      || k1->op_type == OP_AEACH))
9937                     expr = newUNOP(OP_DEFINED, 0, expr);
9938                 break;
9939             }
9940         }
9941     }
9942
9943     /* if block is null, the next op_append_elem() would put UNSTACK, a scalar
9944      * op, in listop. This is wrong. [perl #27024] */
9945     if (!block)
9946         block = newOP(OP_NULL, 0);
9947     listop = op_append_elem(OP_LINESEQ, block, newOP(OP_UNSTACK, 0));
9948     o = new_logop(OP_AND, 0, &expr, &listop);
9949
9950     if (once) {
9951         ASSUME(listop);
9952     }
9953
9954     if (listop)
9955         ((LISTOP*)listop)->op_last->op_next = LINKLIST(o);
9956
9957     if (once && o != listop)
9958     {
9959         assert(cUNOPo->op_first->op_type == OP_AND
9960             || cUNOPo->op_first->op_type == OP_OR);
9961         o->op_next = ((LOGOP*)cUNOPo->op_first)->op_other;
9962     }
9963
9964     if (o == listop)
9965         o = newUNOP(OP_NULL, 0, o);     /* or do {} while 1 loses outer block */
9966
9967     o->op_flags |= flags;
9968     o = op_scope(o);
9969     o->op_flags |= OPf_SPECIAL; /* suppress cx_popblock() curpm restoration*/
9970     return o;
9971 }
9972
9973 /*
9974 =for apidoc newWHILEOP
9975
9976 Constructs, checks, and returns an op tree expressing a C<while> loop.
9977 This is a heavyweight loop, with structure that allows exiting the loop
9978 by C<last> and suchlike.
9979
9980 C<loop> is an optional preconstructed C<enterloop> op to use in the
9981 loop; if it is null then a suitable op will be constructed automatically.
9982 C<expr> supplies the loop's controlling expression.  C<block> supplies the
9983 main body of the loop, and C<cont> optionally supplies a C<continue> block
9984 that operates as a second half of the body.  All of these optree inputs
9985 are consumed by this function and become part of the constructed op tree.
9986
9987 C<flags> gives the eight bits of C<op_flags> for the C<leaveloop>
9988 op and, shifted up eight bits, the eight bits of C<op_private> for
9989 the C<leaveloop> op, except that (in both cases) some bits will be set
9990 automatically.  C<debuggable> is currently unused and should always be 1.
9991 C<has_my> can be supplied as true to force the
9992 loop body to be enclosed in its own scope.
9993
9994 =cut
9995 */
9996
9997 OP *
9998 Perl_newWHILEOP(pTHX_ I32 flags, I32 debuggable, LOOP *loop,
9999         OP *expr, OP *block, OP *cont, I32 has_my)
10000 {
10001     OP *redo;
10002     OP *next = NULL;
10003     OP *listop;
10004     OP *o;
10005     U8 loopflags = 0;
10006
10007     PERL_UNUSED_ARG(debuggable);
10008
10009     if (expr) {
10010         if (expr->op_type == OP_READLINE
10011          || expr->op_type == OP_READDIR
10012          || expr->op_type == OP_GLOB
10013          || expr->op_type == OP_EACH || expr->op_type == OP_AEACH
10014                      || (expr->op_type == OP_NULL && expr->op_targ == OP_GLOB)) {
10015             expr = newUNOP(OP_DEFINED, 0,
10016                 newASSIGNOP(0, newDEFSVOP(), 0, expr) );
10017         } else if (expr->op_flags & OPf_KIDS) {
10018             const OP * const k1 = ((UNOP*)expr)->op_first;
10019             const OP * const k2 = (k1) ? OpSIBLING(k1) : NULL;
10020             switch (expr->op_type) {
10021               case OP_NULL:
10022                 if (k2 && (k2->op_type == OP_READLINE || k2->op_type == OP_READDIR)
10023                       && (k2->op_flags & OPf_STACKED)
10024                       && ((k1->op_flags & OPf_WANT) == OPf_WANT_SCALAR))
10025                     expr = newUNOP(OP_DEFINED, 0, expr);
10026                 break;
10027
10028               case OP_SASSIGN:
10029                 if (k1 && (k1->op_type == OP_READDIR
10030                       || k1->op_type == OP_GLOB
10031                       || (k1->op_type == OP_NULL && k1->op_targ == OP_GLOB)
10032                      || k1->op_type == OP_EACH
10033                      || k1->op_type == OP_AEACH))
10034                     expr = newUNOP(OP_DEFINED, 0, expr);
10035                 break;
10036             }
10037         }
10038     }
10039
10040     if (!block)
10041         block = newOP(OP_NULL, 0);
10042     else if (cont || has_my) {
10043         block = op_scope(block);
10044     }
10045
10046     if (cont) {
10047         next = LINKLIST(cont);
10048     }
10049     if (expr) {
10050         OP * const unstack = newOP(OP_UNSTACK, 0);
10051         if (!next)
10052             next = unstack;
10053         cont = op_append_elem(OP_LINESEQ, cont, unstack);
10054     }
10055
10056     assert(block);
10057     listop = op_append_list(OP_LINESEQ, block, cont);
10058     assert(listop);
10059     redo = LINKLIST(listop);
10060
10061     if (expr) {
10062         scalar(listop);
10063         o = new_logop(OP_AND, 0, &expr, &listop);
10064         if (o == expr && o->op_type == OP_CONST && !SvTRUE(cSVOPo->op_sv)) {
10065             op_free((OP*)loop);
10066             return expr;                /* listop already freed by new_logop */
10067         }
10068         if (listop)
10069             ((LISTOP*)listop)->op_last->op_next =
10070                 (o == listop ? redo : LINKLIST(o));
10071     }
10072     else
10073         o = listop;
10074
10075     if (!loop) {
10076         NewOp(1101,loop,1,LOOP);
10077         OpTYPE_set(loop, OP_ENTERLOOP);
10078         loop->op_private = 0;
10079         loop->op_next = (OP*)loop;
10080     }
10081
10082     o = newBINOP(OP_LEAVELOOP, 0, (OP*)loop, o);
10083
10084     loop->op_redoop = redo;
10085     loop->op_lastop = o;
10086     o->op_private |= loopflags;
10087
10088     if (next)
10089         loop->op_nextop = next;
10090     else
10091         loop->op_nextop = o;
10092
10093     o->op_flags |= flags;
10094     o->op_private |= (flags >> 8);
10095     return o;
10096 }
10097
10098 /*
10099 =for apidoc newFOROP
10100
10101 Constructs, checks, and returns an op tree expressing a C<foreach>
10102 loop (iteration through a list of values).  This is a heavyweight loop,
10103 with structure that allows exiting the loop by C<last> and suchlike.
10104
10105 C<sv> optionally supplies the variable that will be aliased to each
10106 item in turn; if null, it defaults to C<$_>.
10107 C<expr> supplies the list of values to iterate over.  C<block> supplies
10108 the main body of the loop, and C<cont> optionally supplies a C<continue>
10109 block that operates as a second half of the body.  All of these optree
10110 inputs are consumed by this function and become part of the constructed
10111 op tree.
10112
10113 C<flags> gives the eight bits of C<op_flags> for the C<leaveloop>
10114 op and, shifted up eight bits, the eight bits of C<op_private> for
10115 the C<leaveloop> op, except that (in both cases) some bits will be set
10116 automatically.
10117
10118 =cut
10119 */
10120
10121 OP *
10122 Perl_newFOROP(pTHX_ I32 flags, OP *sv, OP *expr, OP *block, OP *cont)
10123 {
10124     LOOP *loop;
10125     OP *wop;
10126     PADOFFSET padoff = 0;
10127     I32 iterflags = 0;
10128     I32 iterpflags = 0;
10129
10130     PERL_ARGS_ASSERT_NEWFOROP;
10131
10132     if (sv) {
10133         if (sv->op_type == OP_RV2SV) {  /* symbol table variable */
10134             iterpflags = sv->op_private & OPpOUR_INTRO; /* for our $x () */
10135             OpTYPE_set(sv, OP_RV2GV);
10136
10137             /* The op_type check is needed to prevent a possible segfault
10138              * if the loop variable is undeclared and 'strict vars' is in
10139              * effect. This is illegal but is nonetheless parsed, so we
10140              * may reach this point with an OP_CONST where we're expecting
10141              * an OP_GV.
10142              */
10143             if (cUNOPx(sv)->op_first->op_type == OP_GV
10144              && cGVOPx_gv(cUNOPx(sv)->op_first) == PL_defgv)
10145                 iterpflags |= OPpITER_DEF;
10146         }
10147         else if (sv->op_type == OP_PADSV) { /* private variable */
10148             iterpflags = sv->op_private & OPpLVAL_INTRO; /* for my $x () */
10149             padoff = sv->op_targ;
10150             sv->op_targ = 0;
10151             op_free(sv);
10152             sv = NULL;
10153             PAD_COMPNAME_GEN_set(padoff, PERL_INT_MAX);
10154         }
10155         else if (sv->op_type == OP_NULL && sv->op_targ == OP_SREFGEN)
10156             NOOP;
10157         else
10158             Perl_croak(aTHX_ "Can't use %s for loop variable", PL_op_desc[sv->op_type]);
10159         if (padoff) {
10160             PADNAME * const pn = PAD_COMPNAME(padoff);
10161             const char * const name = PadnamePV(pn);
10162
10163             if (PadnameLEN(pn) == 2 && name[0] == '$' && name[1] == '_')
10164                 iterpflags |= OPpITER_DEF;
10165         }
10166     }
10167     else {
10168         sv = newGVOP(OP_GV, 0, PL_defgv);
10169         iterpflags |= OPpITER_DEF;
10170     }
10171
10172     if (expr->op_type == OP_RV2AV || expr->op_type == OP_PADAV) {
10173         expr = op_lvalue(force_list(scalar(ref(expr, OP_ITER)), 1), OP_GREPSTART);
10174         iterflags |= OPf_STACKED;
10175     }
10176     else if (expr->op_type == OP_NULL &&
10177              (expr->op_flags & OPf_KIDS) &&
10178              ((BINOP*)expr)->op_first->op_type == OP_FLOP)
10179     {
10180         /* Basically turn for($x..$y) into the same as for($x,$y), but we
10181          * set the STACKED flag to indicate that these values are to be
10182          * treated as min/max values by 'pp_enteriter'.
10183          */
10184         const UNOP* const flip = (UNOP*)((UNOP*)((BINOP*)expr)->op_first)->op_first;
10185         LOGOP* const range = (LOGOP*) flip->op_first;
10186         OP* const left  = range->op_first;
10187         OP* const right = OpSIBLING(left);
10188         LISTOP* listop;
10189
10190         range->op_flags &= ~OPf_KIDS;
10191         /* detach range's children */
10192         op_sibling_splice((OP*)range, NULL, -1, NULL);
10193
10194         listop = (LISTOP*)newLISTOP(OP_LIST, 0, left, right);
10195         listop->op_first->op_next = range->op_next;
10196         left->op_next = range->op_other;
10197         right->op_next = (OP*)listop;
10198         listop->op_next = listop->op_first;
10199
10200         op_free(expr);
10201         expr = (OP*)(listop);
10202         op_null(expr);
10203         iterflags |= OPf_STACKED;
10204     }
10205     else {
10206         expr = op_lvalue(force_list(expr, 1), OP_GREPSTART);
10207     }
10208
10209     loop = (LOOP*)op_convert_list(OP_ENTERITER, iterflags,
10210                                   op_append_elem(OP_LIST, list(expr),
10211                                                  scalar(sv)));
10212     assert(!loop->op_next);
10213     /* for my  $x () sets OPpLVAL_INTRO;
10214      * for our $x () sets OPpOUR_INTRO */
10215     loop->op_private = (U8)iterpflags;
10216
10217     /* upgrade loop from a LISTOP to a LOOPOP;
10218      * keep it in-place if there's space */
10219     if (loop->op_slabbed
10220         &&    OpSLOT(loop)->opslot_size
10221             < SIZE_TO_PSIZE(sizeof(LOOP) + OPSLOT_HEADER))
10222     {
10223         /* no space; allocate new op */
10224         LOOP *tmp;
10225         NewOp(1234,tmp,1,LOOP);
10226         Copy(loop,tmp,1,LISTOP);
10227         assert(loop->op_last->op_sibparent == (OP*)loop);
10228         OpLASTSIB_set(loop->op_last, (OP*)tmp); /*point back to new parent */
10229         S_op_destroy(aTHX_ (OP*)loop);
10230         loop = tmp;
10231     }
10232     else if (!loop->op_slabbed)
10233     {
10234         /* loop was malloc()ed */
10235         loop = (LOOP*)PerlMemShared_realloc(loop, sizeof(LOOP));
10236         OpLASTSIB_set(loop->op_last, (OP*)loop);
10237     }
10238     loop->op_targ = padoff;
10239     wop = newWHILEOP(flags, 1, loop, newOP(OP_ITER, 0), block, cont, 0);
10240     return wop;
10241 }
10242
10243 /*
10244 =for apidoc newLOOPEX
10245
10246 Constructs, checks, and returns a loop-exiting op (such as C<goto>
10247 or C<last>).  C<type> is the opcode.  C<label> supplies the parameter
10248 determining the target of the op; it is consumed by this function and
10249 becomes part of the constructed op tree.
10250
10251 =cut
10252 */
10253
10254 OP*
10255 Perl_newLOOPEX(pTHX_ I32 type, OP *label)
10256 {
10257     OP *o = NULL;
10258
10259     PERL_ARGS_ASSERT_NEWLOOPEX;
10260
10261     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_LOOPEXOP
10262         || type == OP_CUSTOM);
10263
10264     if (type != OP_GOTO) {
10265         /* "last()" means "last" */
10266         if (label->op_type == OP_STUB && (label->op_flags & OPf_PARENS)) {
10267             o = newOP(type, OPf_SPECIAL);
10268         }
10269     }
10270     else {
10271         /* Check whether it's going to be a goto &function */
10272         if (label->op_type == OP_ENTERSUB
10273                 && !(label->op_flags & OPf_STACKED))
10274             label = newUNOP(OP_REFGEN, 0, op_lvalue(label, OP_REFGEN));
10275     }
10276
10277     /* Check for a constant argument */
10278     if (label->op_type == OP_CONST) {
10279             SV * const sv = ((SVOP *)label)->op_sv;
10280             STRLEN l;
10281             const char *s = SvPV_const(sv,l);
10282             if (l == strlen(s)) {
10283                 o = newPVOP(type,
10284                             SvUTF8(((SVOP*)label)->op_sv),
10285                             savesharedpv(
10286                                 SvPV_nolen_const(((SVOP*)label)->op_sv)));
10287             }
10288     }
10289
10290     /* If we have already created an op, we do not need the label. */
10291     if (o)
10292                 op_free(label);
10293     else o = newUNOP(type, OPf_STACKED, label);
10294
10295     PL_hints |= HINT_BLOCK_SCOPE;
10296     return o;
10297 }
10298
10299 /* if the condition is a literal array or hash
10300    (or @{ ... } etc), make a reference to it.
10301  */
10302 STATIC OP *
10303 S_ref_array_or_hash(pTHX_ OP *cond)
10304 {
10305     if (cond
10306     && (cond->op_type == OP_RV2AV
10307     ||  cond->op_type == OP_PADAV
10308     ||  cond->op_type == OP_RV2HV
10309     ||  cond->op_type == OP_PADHV))
10310
10311         return newUNOP(OP_REFGEN, 0, op_lvalue(cond, OP_REFGEN));
10312
10313     else if(cond
10314     && (cond->op_type == OP_ASLICE
10315     ||  cond->op_type == OP_KVASLICE
10316     ||  cond->op_type == OP_HSLICE
10317     ||  cond->op_type == OP_KVHSLICE)) {
10318
10319         /* anonlist now needs a list from this op, was previously used in
10320          * scalar context */
10321         cond->op_flags &= ~(OPf_WANT_SCALAR | OPf_REF);
10322         cond->op_flags |= OPf_WANT_LIST;
10323
10324         return newANONLIST(op_lvalue(cond, OP_ANONLIST));
10325     }
10326
10327     else
10328         return cond;
10329 }
10330
10331 /* These construct the optree fragments representing given()
10332    and when() blocks.
10333
10334    entergiven and enterwhen are LOGOPs; the op_other pointer
10335    points up to the associated leave op. We need this so we
10336    can put it in the context and make break/continue work.
10337    (Also, of course, pp_enterwhen will jump straight to
10338    op_other if the match fails.)
10339  */
10340
10341 STATIC OP *
10342 S_newGIVWHENOP(pTHX_ OP *cond, OP *block,
10343                    I32 enter_opcode, I32 leave_opcode,
10344                    PADOFFSET entertarg)
10345 {
10346     LOGOP *enterop;
10347     OP *o;
10348
10349     PERL_ARGS_ASSERT_NEWGIVWHENOP;
10350     PERL_UNUSED_ARG(entertarg); /* used to indicate targ of lexical $_ */
10351
10352     enterop = alloc_LOGOP(enter_opcode, block, NULL);
10353     enterop->op_targ = 0;
10354     enterop->op_private = 0;
10355
10356     o = newUNOP(leave_opcode, 0, (OP *) enterop);
10357
10358     if (cond) {
10359         /* prepend cond if we have one */
10360         op_sibling_splice((OP*)enterop, NULL, 0, scalar(cond));
10361
10362         o->op_next = LINKLIST(cond);
10363         cond->op_next = (OP *) enterop;
10364     }
10365     else {
10366         /* This is a default {} block */
10367         enterop->op_flags |= OPf_SPECIAL;
10368         o      ->op_flags |= OPf_SPECIAL;
10369
10370         o->op_next = (OP *) enterop;
10371     }
10372
10373     CHECKOP(enter_opcode, enterop); /* Currently does nothing, since
10374                                        entergiven and enterwhen both
10375                                        use ck_null() */
10376
10377     enterop->op_next = LINKLIST(block);
10378     block->op_next = enterop->op_other = o;
10379
10380     return o;
10381 }
10382
10383
10384 /* For the purposes of 'when(implied_smartmatch)'
10385  *              versus 'when(boolean_expression)',
10386  * does this look like a boolean operation? For these purposes
10387    a boolean operation is:
10388      - a subroutine call [*]
10389      - a logical connective
10390      - a comparison operator
10391      - a filetest operator, with the exception of -s -M -A -C
10392      - defined(), exists() or eof()
10393      - /$re/ or $foo =~ /$re/
10394
10395    [*] possibly surprising
10396  */
10397 STATIC bool
10398 S_looks_like_bool(pTHX_ const OP *o)
10399 {
10400     PERL_ARGS_ASSERT_LOOKS_LIKE_BOOL;
10401
10402     switch(o->op_type) {
10403         case OP_OR:
10404         case OP_DOR:
10405             return looks_like_bool(cLOGOPo->op_first);
10406
10407         case OP_AND:
10408         {
10409             OP* sibl = OpSIBLING(cLOGOPo->op_first);
10410             ASSUME(sibl);
10411             return (
10412                 looks_like_bool(cLOGOPo->op_first)
10413              && looks_like_bool(sibl));
10414         }
10415
10416         case OP_NULL:
10417         case OP_SCALAR:
10418             return (
10419                 o->op_flags & OPf_KIDS
10420             && looks_like_bool(cUNOPo->op_first));
10421
10422         case OP_ENTERSUB:
10423
10424         case OP_NOT:    case OP_XOR:
10425
10426         case OP_EQ:     case OP_NE:     case OP_LT:
10427         case OP_GT:     case OP_LE:     case OP_GE:
10428
10429         case OP_I_EQ:   case OP_I_NE:   case OP_I_LT:
10430         case OP_I_GT:   case OP_I_LE:   case OP_I_GE:
10431
10432         case OP_SEQ:    case OP_SNE:    case OP_SLT:
10433         case OP_SGT:    case OP_SLE:    case OP_SGE:
10434
10435         case OP_SMARTMATCH:
10436
10437         case OP_FTRREAD:  case OP_FTRWRITE: case OP_FTREXEC:
10438         case OP_FTEREAD:  case OP_FTEWRITE: case OP_FTEEXEC:
10439         case OP_FTIS:     case OP_FTEOWNED: case OP_FTROWNED:
10440         case OP_FTZERO:   case OP_FTSOCK:   case OP_FTCHR:
10441         case OP_FTBLK:    case OP_FTFILE:   case OP_FTDIR:
10442         case OP_FTPIPE:   case OP_FTLINK:   case OP_FTSUID:
10443         case OP_FTSGID:   case OP_FTSVTX:   case OP_FTTTY:
10444         case OP_FTTEXT:   case OP_FTBINARY:
10445
10446         case OP_DEFINED: case OP_EXISTS:
10447         case OP_MATCH:   case OP_EOF:
10448
10449         case OP_FLOP:
10450
10451             return TRUE;
10452
10453         case OP_INDEX:
10454         case OP_RINDEX:
10455             /* optimised-away (index() != -1) or similar comparison */
10456             if (o->op_private & OPpTRUEBOOL)
10457                 return TRUE;
10458             return FALSE;
10459
10460         case OP_CONST:
10461             /* Detect comparisons that have been optimized away */
10462             if (cSVOPo->op_sv == &PL_sv_yes
10463             ||  cSVOPo->op_sv == &PL_sv_no)
10464
10465                 return TRUE;
10466             else
10467                 return FALSE;
10468         /* FALLTHROUGH */
10469         default:
10470             return FALSE;
10471     }
10472 }
10473
10474
10475 /*
10476 =for apidoc newGIVENOP
10477
10478 Constructs, checks, and returns an op tree expressing a C<given> block.
10479 C<cond> supplies the expression to whose value C<$_> will be locally
10480 aliased, and C<block> supplies the body of the C<given> construct; they
10481 are consumed by this function and become part of the constructed op tree.
10482 C<defsv_off> must be zero (it used to identity the pad slot of lexical $_).
10483
10484 =cut
10485 */
10486
10487 OP *
10488 Perl_newGIVENOP(pTHX_ OP *cond, OP *block, PADOFFSET defsv_off)
10489 {
10490     PERL_ARGS_ASSERT_NEWGIVENOP;
10491     PERL_UNUSED_ARG(defsv_off);
10492
10493     assert(!defsv_off);
10494     return newGIVWHENOP(
10495         ref_array_or_hash(cond),
10496         block,
10497         OP_ENTERGIVEN, OP_LEAVEGIVEN,
10498         0);
10499 }
10500
10501 /*
10502 =for apidoc newWHENOP
10503
10504 Constructs, checks, and returns an op tree expressing a C<when> block.
10505 C<cond> supplies the test expression, and C<block> supplies the block
10506 that will be executed if the test evaluates to true; they are consumed
10507 by this function and become part of the constructed op tree.  C<cond>
10508 will be interpreted DWIMically, often as a comparison against C<$_>,
10509 and may be null to generate a C<default> block.
10510
10511 =cut
10512 */
10513
10514 OP *
10515 Perl_newWHENOP(pTHX_ OP *cond, OP *block)
10516 {
10517     const bool cond_llb = (!cond || looks_like_bool(cond));
10518     OP *cond_op;
10519
10520     PERL_ARGS_ASSERT_NEWWHENOP;
10521
10522     if (cond_llb)
10523         cond_op = cond;
10524     else {
10525         cond_op = newBINOP(OP_SMARTMATCH, OPf_SPECIAL,
10526                 newDEFSVOP(),
10527                 scalar(ref_array_or_hash(cond)));
10528     }
10529
10530     return newGIVWHENOP(cond_op, block, OP_ENTERWHEN, OP_LEAVEWHEN, 0);
10531 }
10532
10533 /* must not conflict with SVf_UTF8 */
10534 #define CV_CKPROTO_CURSTASH     0x1
10535
10536 void
10537 Perl_cv_ckproto_len_flags(pTHX_ const CV *cv, const GV *gv, const char *p,
10538                     const STRLEN len, const U32 flags)
10539 {
10540     SV *name = NULL, *msg;
10541     const char * cvp = SvROK(cv)
10542                         ? SvTYPE(SvRV_const(cv)) == SVt_PVCV
10543                            ? (cv = (const CV *)SvRV_const(cv), CvPROTO(cv))
10544                            : ""
10545                         : CvPROTO(cv);
10546     STRLEN clen = CvPROTOLEN(cv), plen = len;
10547
10548     PERL_ARGS_ASSERT_CV_CKPROTO_LEN_FLAGS;
10549
10550     if (p == NULL && cvp == NULL)
10551         return;
10552
10553     if (!ckWARN_d(WARN_PROTOTYPE))
10554         return;
10555
10556     if (p && cvp) {
10557         p = S_strip_spaces(aTHX_ p, &plen);
10558         cvp = S_strip_spaces(aTHX_ cvp, &clen);
10559         if ((flags & SVf_UTF8) == SvUTF8(cv)) {
10560             if (plen == clen && memEQ(cvp, p, plen))
10561                 return;
10562         } else {
10563             if (flags & SVf_UTF8) {
10564                 if (bytes_cmp_utf8((const U8 *)cvp, clen, (const U8 *)p, plen) == 0)
10565                     return;
10566             }
10567             else {
10568                 if (bytes_cmp_utf8((const U8 *)p, plen, (const U8 *)cvp, clen) == 0)
10569                     return;
10570             }
10571         }
10572     }
10573
10574     msg = sv_newmortal();
10575
10576     if (gv)
10577     {
10578         if (isGV(gv))
10579             gv_efullname3(name = sv_newmortal(), gv, NULL);
10580         else if (SvPOK(gv) && *SvPVX((SV *)gv) == '&')
10581             name = newSVpvn_flags(SvPVX((SV *)gv)+1, SvCUR(gv)-1, SvUTF8(gv)|SVs_TEMP);
10582         else if (flags & CV_CKPROTO_CURSTASH || SvROK(gv)) {
10583             name = sv_2mortal(newSVhek(HvNAME_HEK(PL_curstash)));
10584             sv_catpvs(name, "::");
10585             if (SvROK(gv)) {
10586                 assert (SvTYPE(SvRV_const(gv)) == SVt_PVCV);
10587                 assert (CvNAMED(SvRV_const(gv)));
10588                 sv_cathek(name, CvNAME_HEK(MUTABLE_CV(SvRV_const(gv))));
10589             }
10590             else sv_catsv(name, (SV *)gv);
10591         }
10592         else name = (SV *)gv;
10593     }
10594     sv_setpvs(msg, "Prototype mismatch:");
10595     if (name)
10596         Perl_sv_catpvf(aTHX_ msg, " sub %" SVf, SVfARG(name));
10597     if (cvp)
10598         Perl_sv_catpvf(aTHX_ msg, " (%" UTF8f ")",
10599             UTF8fARG(SvUTF8(cv),clen,cvp)
10600         );
10601     else
10602         sv_catpvs(msg, ": none");
10603     sv_catpvs(msg, " vs ");
10604     if (p)
10605         Perl_sv_catpvf(aTHX_ msg, "(%" UTF8f ")", UTF8fARG(flags & SVf_UTF8,len,p));
10606     else
10607         sv_catpvs(msg, "none");
10608     Perl_warner(aTHX_ packWARN(WARN_PROTOTYPE), "%" SVf, SVfARG(msg));
10609 }
10610
10611 static void const_sv_xsub(pTHX_ CV* cv);
10612 static void const_av_xsub(pTHX_ CV* cv);
10613
10614 /*
10615
10616 =for apidoc_section Optree Manipulation Functions
10617
10618 =for apidoc cv_const_sv
10619
10620 If C<cv> is a constant sub eligible for inlining, returns the constant
10621 value returned by the sub.  Otherwise, returns C<NULL>.
10622
10623 Constant subs can be created with C<newCONSTSUB> or as described in
10624 L<perlsub/"Constant Functions">.
10625
10626 =cut
10627 */
10628 SV *
10629 Perl_cv_const_sv(const CV *const cv)
10630 {
10631     SV *sv;
10632     if (!cv)
10633         return NULL;
10634     if (!(SvTYPE(cv) == SVt_PVCV || SvTYPE(cv) == SVt_PVFM))
10635         return NULL;
10636     sv = CvCONST(cv) ? MUTABLE_SV(CvXSUBANY(cv).any_ptr) : NULL;
10637     if (sv && SvTYPE(sv) == SVt_PVAV) return NULL;
10638     return sv;
10639 }
10640
10641 SV *
10642 Perl_cv_const_sv_or_av(const CV * const cv)
10643 {
10644     if (!cv)
10645         return NULL;
10646     if (SvROK(cv)) return SvRV((SV *)cv);
10647     assert (SvTYPE(cv) == SVt_PVCV || SvTYPE(cv) == SVt_PVFM);
10648     return CvCONST(cv) ? MUTABLE_SV(CvXSUBANY(cv).any_ptr) : NULL;
10649 }
10650
10651 /* op_const_sv:  examine an optree to determine whether it's in-lineable.
10652  * Can be called in 2 ways:
10653  *
10654  * !allow_lex
10655  *      look for a single OP_CONST with attached value: return the value
10656  *
10657  * allow_lex && !CvCONST(cv);
10658  *
10659  *      examine the clone prototype, and if contains only a single
10660  *      OP_CONST, return the value; or if it contains a single PADSV ref-
10661  *      erencing an outer lexical, turn on CvCONST to indicate the CV is
10662  *      a candidate for "constizing" at clone time, and return NULL.
10663  */
10664
10665 static SV *
10666 S_op_const_sv(pTHX_ const OP *o, CV *cv, bool allow_lex)
10667 {
10668     SV *sv = NULL;
10669     bool padsv = FALSE;
10670
10671     assert(o);
10672     assert(cv);
10673
10674     for (; o; o = o->op_next) {
10675         const OPCODE type = o->op_type;
10676
10677         if (type == OP_NEXTSTATE || type == OP_LINESEQ
10678              || type == OP_NULL
10679              || type == OP_PUSHMARK)
10680                 continue;
10681         if (type == OP_DBSTATE)
10682                 continue;
10683         if (type == OP_LEAVESUB)
10684             break;
10685         if (sv)
10686             return NULL;
10687         if (type == OP_CONST && cSVOPo->op_sv)
10688             sv = cSVOPo->op_sv;
10689         else if (type == OP_UNDEF && !o->op_private) {
10690             sv = newSV(0);
10691             SAVEFREESV(sv);
10692         }
10693         else if (allow_lex && type == OP_PADSV) {
10694                 if (PAD_COMPNAME_FLAGS(o->op_targ) & PADNAMEt_OUTER)
10695                 {
10696                     sv = &PL_sv_undef; /* an arbitrary non-null value */
10697                     padsv = TRUE;
10698                 }
10699                 else
10700                     return NULL;
10701         }
10702         else {
10703             return NULL;
10704         }
10705     }
10706     if (padsv) {
10707         CvCONST_on(cv);
10708         return NULL;
10709     }
10710     return sv;
10711 }
10712
10713 static void
10714 S_already_defined(pTHX_ CV *const cv, OP * const block, OP * const o,
10715                         PADNAME * const name, SV ** const const_svp)
10716 {
10717     assert (cv);
10718     assert (o || name);
10719     assert (const_svp);
10720     if (!block) {
10721         if (CvFLAGS(PL_compcv)) {
10722             /* might have had built-in attrs applied */
10723             const bool pureperl = !CvISXSUB(cv) && CvROOT(cv);
10724             if (CvLVALUE(PL_compcv) && ! CvLVALUE(cv) && pureperl
10725              && ckWARN(WARN_MISC))
10726             {
10727                 /* protect against fatal warnings leaking compcv */
10728                 SAVEFREESV(PL_compcv);
10729                 Perl_warner(aTHX_ packWARN(WARN_MISC), "lvalue attribute ignored after the subroutine has been defined");
10730                 SvREFCNT_inc_simple_void_NN(PL_compcv);
10731             }
10732             CvFLAGS(cv) |=
10733                 (CvFLAGS(PL_compcv) & CVf_BUILTIN_ATTRS
10734                   & ~(CVf_LVALUE * pureperl));
10735         }
10736         return;
10737     }
10738
10739     /* redundant check for speed: */
10740     if (CvCONST(cv) || ckWARN(WARN_REDEFINE)) {
10741         const line_t oldline = CopLINE(PL_curcop);
10742         SV *namesv = o
10743             ? cSVOPo->op_sv
10744             : sv_2mortal(newSVpvn_utf8(
10745                 PadnamePV(name)+1,PadnameLEN(name)-1, PadnameUTF8(name)
10746               ));
10747         if (PL_parser && PL_parser->copline != NOLINE)
10748             /* This ensures that warnings are reported at the first
10749                line of a redefinition, not the last.  */
10750             CopLINE_set(PL_curcop, PL_parser->copline);
10751         /* protect against fatal warnings leaking compcv */
10752         SAVEFREESV(PL_compcv);
10753         report_redefined_cv(namesv, cv, const_svp);
10754         SvREFCNT_inc_simple_void_NN(PL_compcv);
10755         CopLINE_set(PL_curcop, oldline);
10756     }
10757     SAVEFREESV(cv);
10758     return;
10759 }
10760
10761 CV *
10762 Perl_newMYSUB(pTHX_ I32 floor, OP *o, OP *proto, OP *attrs, OP *block)
10763 {
10764     CV **spot;
10765     SV **svspot;
10766     const char *ps;
10767     STRLEN ps_len = 0; /* init it to avoid false uninit warning from icc */
10768     U32 ps_utf8 = 0;
10769     CV *cv = NULL;
10770     CV *compcv = PL_compcv;
10771     SV *const_sv;
10772     PADNAME *name;
10773     PADOFFSET pax = o->op_targ;
10774     CV *outcv = CvOUTSIDE(PL_compcv);
10775     CV *clonee = NULL;
10776     HEK *hek = NULL;
10777     bool reusable = FALSE;
10778     OP *start = NULL;
10779 #ifdef PERL_DEBUG_READONLY_OPS
10780     OPSLAB *slab = NULL;
10781 #endif
10782
10783     PERL_ARGS_ASSERT_NEWMYSUB;
10784
10785     PL_hints |= HINT_BLOCK_SCOPE;
10786
10787     /* Find the pad slot for storing the new sub.
10788        We cannot use PL_comppad, as it is the pad owned by the new sub.  We
10789        need to look in CvOUTSIDE and find the pad belonging to the enclos-
10790        ing sub.  And then we need to dig deeper if this is a lexical from
10791        outside, as in:
10792            my sub foo; sub { sub foo { } }
10793      */
10794   redo:
10795     name = PadlistNAMESARRAY(CvPADLIST(outcv))[pax];
10796     if (PadnameOUTER(name) && PARENT_PAD_INDEX(name)) {
10797         pax = PARENT_PAD_INDEX(name);
10798         outcv = CvOUTSIDE(outcv);
10799         assert(outcv);
10800         goto redo;
10801     }
10802     svspot =
10803         &PadARRAY(PadlistARRAY(CvPADLIST(outcv))
10804                         [CvDEPTH(outcv) ? CvDEPTH(outcv) : 1])[pax];
10805     spot = (CV **)svspot;
10806
10807     if (!(PL_parser && PL_parser->error_count))
10808         move_proto_attr(&proto, &attrs, (GV *)PadnameSV(name), 0);
10809
10810     if (proto) {
10811         assert(proto->op_type == OP_CONST);
10812         ps = SvPV_const(((SVOP*)proto)->op_sv, ps_len);
10813         ps_utf8 = SvUTF8(((SVOP*)proto)->op_sv);
10814     }
10815     else
10816         ps = NULL;
10817
10818     if (proto)
10819         SAVEFREEOP(proto);
10820     if (attrs)
10821         SAVEFREEOP(attrs);
10822
10823     if (PL_parser && PL_parser->error_count) {
10824         op_free(block);
10825         SvREFCNT_dec(PL_compcv);
10826         PL_compcv = 0;
10827         goto done;
10828     }
10829
10830     if (CvDEPTH(outcv) && CvCLONE(compcv)) {
10831         cv = *spot;
10832         svspot = (SV **)(spot = &clonee);
10833     }
10834     else if (PadnameIsSTATE(name) || CvDEPTH(outcv))
10835         cv = *spot;
10836     else {
10837         assert (SvTYPE(*spot) == SVt_PVCV);
10838         if (CvNAMED(*spot))
10839             hek = CvNAME_HEK(*spot);
10840         else {
10841             U32 hash;
10842             PERL_HASH(hash, PadnamePV(name)+1, PadnameLEN(name)-1);
10843             CvNAME_HEK_set(*spot, hek =
10844                 share_hek(
10845                     PadnamePV(name)+1,
10846                     (PadnameLEN(name)-1) * (PadnameUTF8(name) ? -1 : 1),
10847                     hash
10848                 )
10849             );
10850             CvLEXICAL_on(*spot);
10851         }
10852         cv = PadnamePROTOCV(name);
10853         svspot = (SV **)(spot = &PadnamePROTOCV(name));
10854     }
10855
10856     if (block) {
10857         /* This makes sub {}; work as expected.  */
10858         if (block->op_type == OP_STUB) {
10859             const line_t l = PL_parser->copline;
10860             op_free(block);
10861             block = newSTATEOP(0, NULL, 0);
10862             PL_parser->copline = l;
10863         }
10864         block = CvLVALUE(compcv)
10865              || (cv && CvLVALUE(cv) && !CvROOT(cv) && !CvXSUB(cv))
10866                    ? newUNOP(OP_LEAVESUBLV, 0,
10867                              op_lvalue(scalarseq(block), OP_LEAVESUBLV))
10868                    : newUNOP(OP_LEAVESUB, 0, scalarseq(block));
10869         start = LINKLIST(block);
10870         block->op_next = 0;
10871         if (ps && !*ps && !attrs && !CvLVALUE(compcv))
10872             const_sv = S_op_const_sv(aTHX_ start, compcv, FALSE);
10873         else
10874             const_sv = NULL;
10875     }
10876     else
10877         const_sv = NULL;
10878
10879     if (cv) {
10880         const bool exists = CvROOT(cv) || CvXSUB(cv);
10881
10882         /* if the subroutine doesn't exist and wasn't pre-declared
10883          * with a prototype, assume it will be AUTOLOADed,
10884          * skipping the prototype check
10885          */
10886         if (exists || SvPOK(cv))
10887             cv_ckproto_len_flags(cv, (GV *)PadnameSV(name), ps, ps_len,
10888                                  ps_utf8);
10889         /* already defined? */
10890         if (exists) {
10891             S_already_defined(aTHX_ cv, block, NULL, name, &const_sv);
10892             if (block)
10893                 cv = NULL;
10894             else {
10895                 if (attrs)
10896                     goto attrs;
10897                 /* just a "sub foo;" when &foo is already defined */
10898                 SAVEFREESV(compcv);
10899                 goto done;
10900             }
10901         }
10902         else if (CvDEPTH(outcv) && CvCLONE(compcv)) {
10903             cv = NULL;
10904             reusable = TRUE;
10905         }
10906     }
10907
10908     if (const_sv) {
10909         SvREFCNT_inc_simple_void_NN(const_sv);
10910         SvFLAGS(const_sv) |= SVs_PADTMP;
10911         if (cv) {
10912             assert(!CvROOT(cv) && !CvCONST(cv));
10913             cv_forget_slab(cv);
10914         }
10915         else {
10916             cv = MUTABLE_CV(newSV_type(SVt_PVCV));
10917             CvFILE_set_from_cop(cv, PL_curcop);
10918             CvSTASH_set(cv, PL_curstash);
10919             *spot = cv;
10920         }
10921         SvPVCLEAR(MUTABLE_SV(cv));  /* prototype is "" */
10922         CvXSUBANY(cv).any_ptr = const_sv;
10923         CvXSUB(cv) = const_sv_xsub;
10924         CvCONST_on(cv);
10925         CvISXSUB_on(cv);
10926         PoisonPADLIST(cv);
10927         CvFLAGS(cv) |= CvMETHOD(compcv);
10928         op_free(block);
10929         SvREFCNT_dec(compcv);
10930         PL_compcv = NULL;
10931         goto setname;
10932     }
10933
10934     /* Checking whether outcv is CvOUTSIDE(compcv) is not sufficient to
10935        determine whether this sub definition is in the same scope as its
10936        declaration.  If this sub definition is inside an inner named pack-
10937        age sub (my sub foo; sub bar { sub foo { ... } }), outcv points to
10938        the package sub.  So check PadnameOUTER(name) too.
10939      */
10940     if (outcv == CvOUTSIDE(compcv) && !PadnameOUTER(name)) {
10941         assert(!CvWEAKOUTSIDE(compcv));
10942         SvREFCNT_dec(CvOUTSIDE(compcv));
10943         CvWEAKOUTSIDE_on(compcv);
10944     }
10945     /* XXX else do we have a circular reference? */
10946
10947     if (cv) {   /* must reuse cv in case stub is referenced elsewhere */
10948         /* transfer PL_compcv to cv */
10949         if (block) {
10950             bool free_file = CvFILE(cv) && CvDYNFILE(cv);
10951             cv_flags_t preserved_flags =
10952                 CvFLAGS(cv) & (CVf_BUILTIN_ATTRS|CVf_NAMED);
10953             PADLIST *const temp_padl = CvPADLIST(cv);
10954             CV *const temp_cv = CvOUTSIDE(cv);
10955             const cv_flags_t other_flags =
10956                 CvFLAGS(cv) & (CVf_SLABBED|CVf_WEAKOUTSIDE);
10957             OP * const cvstart = CvSTART(cv);
10958
10959             SvPOK_off(cv);
10960             CvFLAGS(cv) =
10961                 CvFLAGS(compcv) | preserved_flags;
10962             CvOUTSIDE(cv) = CvOUTSIDE(compcv);
10963             CvOUTSIDE_SEQ(cv) = CvOUTSIDE_SEQ(compcv);
10964             CvPADLIST_set(cv, CvPADLIST(compcv));
10965             CvOUTSIDE(compcv) = temp_cv;
10966             CvPADLIST_set(compcv, temp_padl);
10967             CvSTART(cv) = CvSTART(compcv);
10968             CvSTART(compcv) = cvstart;
10969             CvFLAGS(compcv) &= ~(CVf_SLABBED|CVf_WEAKOUTSIDE);
10970             CvFLAGS(compcv) |= other_flags;
10971
10972             if (free_file) {
10973                 Safefree(CvFILE(cv));
10974                 CvFILE(cv) = NULL;
10975             }
10976
10977             /* inner references to compcv must be fixed up ... */
10978             pad_fixup_inner_anons(CvPADLIST(cv), compcv, cv);
10979             if (PERLDB_INTER)/* Advice debugger on the new sub. */
10980                 ++PL_sub_generation;
10981         }
10982         else {
10983             /* Might have had built-in attributes applied -- propagate them. */
10984             CvFLAGS(cv) |= (CvFLAGS(compcv) & CVf_BUILTIN_ATTRS);
10985         }
10986         /* ... before we throw it away */
10987         SvREFCNT_dec(compcv);
10988         PL_compcv = compcv = cv;
10989     }
10990     else {
10991         cv = compcv;
10992         *spot = cv;
10993     }
10994
10995   setname:
10996     CvLEXICAL_on(cv);
10997     if (!CvNAME_HEK(cv)) {
10998         if (hek) (void)share_hek_hek(hek);
10999         else {
11000             U32 hash;
11001             PERL_HASH(hash, PadnamePV(name)+1, PadnameLEN(name)-1);
11002             hek = share_hek(PadnamePV(name)+1,
11003                       (PadnameLEN(name)-1) * (PadnameUTF8(name) ? -1 : 1),
11004                       hash);
11005         }
11006         CvNAME_HEK_set(cv, hek);
11007     }
11008
11009     if (const_sv)
11010         goto clone;
11011
11012     if (CvFILE(cv) && CvDYNFILE(cv))
11013         Safefree(CvFILE(cv));
11014     CvFILE_set_from_cop(cv, PL_curcop);
11015     CvSTASH_set(cv, PL_curstash);
11016
11017     if (ps) {
11018         sv_setpvn(MUTABLE_SV(cv), ps, ps_len);
11019         if (ps_utf8)
11020             SvUTF8_on(MUTABLE_SV(cv));
11021     }
11022
11023     if (block) {
11024         /* If we assign an optree to a PVCV, then we've defined a
11025          * subroutine that the debugger could be able to set a breakpoint
11026          * in, so signal to pp_entereval that it should not throw away any
11027          * saved lines at scope exit.  */
11028
11029         PL_breakable_sub_gen++;
11030         CvROOT(cv) = block;
11031         /* The cv no longer needs to hold a refcount on the slab, as CvROOT
11032            itself has a refcount. */
11033         CvSLABBED_off(cv);
11034         OpslabREFCNT_dec_padok((OPSLAB *)CvSTART(cv));
11035 #ifdef PERL_DEBUG_READONLY_OPS
11036         slab = (OPSLAB *)CvSTART(cv);
11037 #endif
11038         S_process_optree(aTHX_ cv, block, start);
11039     }
11040
11041   attrs:
11042     if (attrs) {
11043         /* Need to do a C<use attributes $stash_of_cv,\&cv,@attrs>. */
11044         apply_attrs(PL_curstash, MUTABLE_SV(cv), attrs);
11045     }
11046
11047     if (block) {
11048         if (PERLDB_SUBLINE && PL_curstash != PL_debstash) {
11049             SV * const tmpstr = sv_newmortal();
11050             GV * const db_postponed = gv_fetchpvs("DB::postponed",
11051                                                   GV_ADDMULTI, SVt_PVHV);
11052             HV *hv;
11053             SV * const sv = Perl_newSVpvf(aTHX_ "%s:%ld-%ld",
11054                                           CopFILE(PL_curcop),
11055                                           (long)PL_subline,
11056                                           (long)CopLINE(PL_curcop));
11057             if (HvNAME_HEK(PL_curstash)) {
11058                 sv_sethek(tmpstr, HvNAME_HEK(PL_curstash));
11059                 sv_catpvs(tmpstr, "::");
11060             }
11061             else
11062                 sv_setpvs(tmpstr, "__ANON__::");
11063
11064             sv_catpvn_flags(tmpstr, PadnamePV(name)+1, PadnameLEN(name)-1,
11065                             PadnameUTF8(name) ? SV_CATUTF8 : SV_CATBYTES);
11066             (void)hv_store(GvHV(PL_DBsub), SvPVX_const(tmpstr),
11067                     SvUTF8(tmpstr) ? -(I32)SvCUR(tmpstr) : (I32)SvCUR(tmpstr), sv, 0);
11068             hv = GvHVn(db_postponed);
11069             if (HvTOTALKEYS(hv) > 0 && hv_exists(hv, SvPVX_const(tmpstr), SvUTF8(tmpstr) ? -(I32)SvCUR(tmpstr) : (I32)SvCUR(tmpstr))) {
11070                 CV * const pcv = GvCV(db_postponed);
11071                 if (pcv) {
11072                     dSP;
11073                     PUSHMARK(SP);
11074                     XPUSHs(tmpstr);
11075                     PUTBACK;
11076                     call_sv(MUTABLE_SV(pcv), G_DISCARD);
11077                 }
11078             }
11079         }
11080     }
11081
11082   clone:
11083     if (clonee) {
11084         assert(CvDEPTH(outcv));
11085         spot = (CV **)
11086             &PadARRAY(PadlistARRAY(CvPADLIST(outcv))[CvDEPTH(outcv)])[pax];
11087         if (reusable)
11088             cv_clone_into(clonee, *spot);
11089         else *spot = cv_clone(clonee);
11090         SvREFCNT_dec_NN(clonee);
11091         cv = *spot;
11092     }
11093
11094     if (CvDEPTH(outcv) && !reusable && PadnameIsSTATE(name)) {
11095         PADOFFSET depth = CvDEPTH(outcv);
11096         while (--depth) {
11097             SV *oldcv;
11098             svspot = &PadARRAY(PadlistARRAY(CvPADLIST(outcv))[depth])[pax];
11099             oldcv = *svspot;
11100             *svspot = SvREFCNT_inc_simple_NN(cv);
11101             SvREFCNT_dec(oldcv);
11102         }
11103     }
11104
11105   done:
11106     if (PL_parser)
11107         PL_parser->copline = NOLINE;
11108     LEAVE_SCOPE(floor);
11109 #ifdef PERL_DEBUG_READONLY_OPS
11110     if (slab)
11111         Slab_to_ro(slab);
11112 #endif
11113     op_free(o);
11114     return cv;
11115 }
11116
11117 /*
11118 =for apidoc newATTRSUB_x
11119
11120 Construct a Perl subroutine, also performing some surrounding jobs.
11121
11122 This function is expected to be called in a Perl compilation context,
11123 and some aspects of the subroutine are taken from global variables
11124 associated with compilation.  In particular, C<PL_compcv> represents
11125 the subroutine that is currently being compiled.  It must be non-null
11126 when this function is called, and some aspects of the subroutine being
11127 constructed are taken from it.  The constructed subroutine may actually
11128 be a reuse of the C<PL_compcv> object, but will not necessarily be so.
11129
11130 If C<block> is null then the subroutine will have no body, and for the
11131 time being it will be an error to call it.  This represents a forward
11132 subroutine declaration such as S<C<sub foo ($$);>>.  If C<block> is
11133 non-null then it provides the Perl code of the subroutine body, which
11134 will be executed when the subroutine is called.  This body includes
11135 any argument unwrapping code resulting from a subroutine signature or
11136 similar.  The pad use of the code must correspond to the pad attached
11137 to C<PL_compcv>.  The code is not expected to include a C<leavesub> or
11138 C<leavesublv> op; this function will add such an op.  C<block> is consumed
11139 by this function and will become part of the constructed subroutine.
11140
11141 C<proto> specifies the subroutine's prototype, unless one is supplied
11142 as an attribute (see below).  If C<proto> is null, then the subroutine
11143 will not have a prototype.  If C<proto> is non-null, it must point to a
11144 C<const> op whose value is a string, and the subroutine will have that
11145 string as its prototype.  If a prototype is supplied as an attribute, the
11146 attribute takes precedence over C<proto>, but in that case C<proto> should
11147 preferably be null.  In any case, C<proto> is consumed by this function.
11148
11149 C<attrs> supplies attributes to be applied the subroutine.  A handful of
11150 attributes take effect by built-in means, being applied to C<PL_compcv>
11151 immediately when seen.  Other attributes are collected up and attached
11152 to the subroutine by this route.  C<attrs> may be null to supply no
11153 attributes, or point to a C<const> op for a single attribute, or point
11154 to a C<list> op whose children apart from the C<pushmark> are C<const>
11155 ops for one or more attributes.  Each C<const> op must be a string,
11156 giving the attribute name optionally followed by parenthesised arguments,
11157 in the manner in which attributes appear in Perl source.  The attributes
11158 will be applied to the sub by this function.  C<attrs> is consumed by
11159 this function.
11160
11161 If C<o_is_gv> is false and C<o> is null, then the subroutine will
11162 be anonymous.  If C<o_is_gv> is false and C<o> is non-null, then C<o>
11163 must point to a C<const> OP, which will be consumed by this function,
11164 and its string value supplies a name for the subroutine.  The name may
11165 be qualified or unqualified, and if it is unqualified then a default
11166 stash will be selected in some manner.  If C<o_is_gv> is true, then C<o>
11167 doesn't point to an C<OP> at all, but is instead a cast pointer to a C<GV>
11168 by which the subroutine will be named.
11169
11170 If there is already a subroutine of the specified name, then the new
11171 sub will either replace the existing one in the glob or be merged with
11172 the existing one.  A warning may be generated about redefinition.
11173
11174 If the subroutine has one of a few special names, such as C<BEGIN> or
11175 C<END>, then it will be claimed by the appropriate queue for automatic
11176 running of phase-related subroutines.  In this case the relevant glob will
11177 be left not containing any subroutine, even if it did contain one before.
11178 In the case of C<BEGIN>, the subroutine will be executed and the reference
11179 to it disposed of before this function returns.
11180
11181 The function returns a pointer to the constructed subroutine.  If the sub
11182 is anonymous then ownership of one counted reference to the subroutine
11183 is transferred to the caller.  If the sub is named then the caller does
11184 not get ownership of a reference.  In most such cases, where the sub
11185 has a non-phase name, the sub will be alive at the point it is returned
11186 by virtue of being contained in the glob that names it.  A phase-named
11187 subroutine will usually be alive by virtue of the reference owned by the
11188 phase's automatic run queue.  But a C<BEGIN> subroutine, having already
11189 been executed, will quite likely have been destroyed already by the
11190 time this function returns, making it erroneous for the caller to make
11191 any use of the returned pointer.  It is the caller's responsibility to
11192 ensure that it knows which of these situations applies.
11193
11194 =for apidoc newATTRSUB
11195 Construct a Perl subroutine, also performing some surrounding jobs.
11196
11197 This is the same as L<perlintern/C<newATTRSUB_x>> with its C<o_is_gv> parameter set to
11198 FALSE.  This means that if C<o> is null, the new sub will be anonymous; otherwise
11199 the name will be derived from C<o> in the way described (as with all other
11200 details) in L<perlintern/C<newATTRSUB_x>>.
11201
11202 =for apidoc newSUB
11203 Like C<L</newATTRSUB>>, but without attributes.
11204
11205 =cut
11206 */
11207
11208 /* _x = extended */
11209 CV *
11210 Perl_newATTRSUB_x(pTHX_ I32 floor, OP *o, OP *proto, OP *attrs,
11211                             OP *block, bool o_is_gv)
11212 {
11213     GV *gv;
11214     const char *ps;
11215     STRLEN ps_len = 0; /* init it to avoid false uninit warning from icc */
11216     U32 ps_utf8 = 0;
11217     CV *cv = NULL;     /* the previous CV with this name, if any */
11218     SV *const_sv;
11219     const bool ec = PL_parser && PL_parser->error_count;
11220     /* If the subroutine has no body, no attributes, and no builtin attributes
11221        then it's just a sub declaration, and we may be able to get away with
11222        storing with a placeholder scalar in the symbol table, rather than a
11223        full CV.  If anything is present then it will take a full CV to
11224        store it.  */
11225     const I32 gv_fetch_flags
11226         = ec ? GV_NOADD_NOINIT :
11227         (block || attrs || (CvFLAGS(PL_compcv) & CVf_BUILTIN_ATTRS))
11228         ? GV_ADDMULTI : GV_ADDMULTI | GV_NOINIT;
11229     STRLEN namlen = 0;
11230     const char * const name =
11231          o ? SvPV_const(o_is_gv ? (SV *)o : cSVOPo->op_sv, namlen) : NULL;
11232     bool has_name;
11233     bool name_is_utf8 = o && !o_is_gv && SvUTF8(cSVOPo->op_sv);
11234     bool evanescent = FALSE;
11235     OP *start = NULL;
11236 #ifdef PERL_DEBUG_READONLY_OPS
11237     OPSLAB *slab = NULL;
11238 #endif
11239
11240     if (o_is_gv) {
11241         gv = (GV*)o;
11242         o = NULL;
11243         has_name = TRUE;
11244     } else if (name) {
11245         /* Try to optimise and avoid creating a GV.  Instead, the CV’s name
11246            hek and CvSTASH pointer together can imply the GV.  If the name
11247            contains a package name, then GvSTASH(CvGV(cv)) may differ from
11248            CvSTASH, so forego the optimisation if we find any.
11249            Also, we may be called from load_module at run time, so
11250            PL_curstash (which sets CvSTASH) may not point to the stash the
11251            sub is stored in.  */
11252         /* XXX This optimization is currently disabled for packages other
11253                than main, since there was too much CPAN breakage.  */
11254         const I32 flags =
11255            ec ? GV_NOADD_NOINIT
11256               :   (IN_PERL_RUNTIME && PL_curstash != CopSTASH(PL_curcop))
11257                || PL_curstash != PL_defstash
11258                || memchr(name, ':', namlen) || memchr(name, '\'', namlen)
11259                     ? gv_fetch_flags
11260                     : GV_ADDMULTI | GV_NOINIT | GV_NOTQUAL;
11261         gv = gv_fetchsv(cSVOPo->op_sv, flags, SVt_PVCV);
11262         has_name = TRUE;
11263     } else if (PERLDB_NAMEANON && CopLINE(PL_curcop)) {
11264         SV * const sv = sv_newmortal();
11265         Perl_sv_setpvf(aTHX_ sv, "%s[%s:%" IVdf "]",
11266                        PL_curstash ? "__ANON__" : "__ANON__::__ANON__",
11267                        CopFILE(PL_curcop), (IV)CopLINE(PL_curcop));
11268         gv = gv_fetchsv(sv, gv_fetch_flags, SVt_PVCV);
11269         has_name = TRUE;
11270     } else if (PL_curstash) {
11271         gv = gv_fetchpvs("__ANON__", gv_fetch_flags, SVt_PVCV);
11272         has_name = FALSE;
11273     } else {
11274         gv = gv_fetchpvs("__ANON__::__ANON__", gv_fetch_flags, SVt_PVCV);
11275         has_name = FALSE;
11276     }
11277
11278     if (!ec) {
11279         if (isGV(gv)) {
11280             move_proto_attr(&proto, &attrs, gv, 0);
11281         } else {
11282             assert(cSVOPo);
11283             move_proto_attr(&proto, &attrs, (GV *)cSVOPo->op_sv, 1);
11284         }
11285     }
11286
11287     if (proto) {
11288         assert(proto->op_type == OP_CONST);
11289         ps = SvPV_const(((SVOP*)proto)->op_sv, ps_len);
11290         ps_utf8 = SvUTF8(((SVOP*)proto)->op_sv);
11291     }
11292     else
11293         ps = NULL;
11294
11295     if (o)
11296         SAVEFREEOP(o);
11297     if (proto)
11298         SAVEFREEOP(proto);
11299     if (attrs)
11300         SAVEFREEOP(attrs);
11301
11302     if (ec) {
11303         op_free(block);
11304
11305         if (name)
11306             SvREFCNT_dec(PL_compcv);
11307         else
11308             cv = PL_compcv;
11309
11310         PL_compcv = 0;
11311         if (name && block) {
11312             const char *s = (char *) my_memrchr(name, ':', namlen);
11313             s = s ? s+1 : name;
11314             if (strEQ(s, "BEGIN")) {
11315                 if (PL_in_eval & EVAL_KEEPERR)
11316                     Perl_croak_nocontext("BEGIN not safe after errors--compilation aborted");
11317                 else {
11318                     SV * const errsv = ERRSV;
11319                     /* force display of errors found but not reported */
11320                     sv_catpvs(errsv, "BEGIN not safe after errors--compilation aborted");
11321                     Perl_croak_nocontext("%" SVf, SVfARG(errsv));
11322                 }
11323             }
11324         }
11325         goto done;
11326     }
11327
11328     if (!block && SvTYPE(gv) != SVt_PVGV) {
11329         /* If we are not defining a new sub and the existing one is not a
11330            full GV + CV... */
11331         if (attrs || (CvFLAGS(PL_compcv) & CVf_BUILTIN_ATTRS)) {
11332             /* We are applying attributes to an existing sub, so we need it
11333                upgraded if it is a constant.  */
11334             if (SvROK(gv) && SvTYPE(SvRV(gv)) != SVt_PVCV)
11335                 gv_init_pvn(gv, PL_curstash, name, namlen,
11336                             SVf_UTF8 * name_is_utf8);
11337         }
11338         else {                  /* Maybe prototype now, and had at maximum
11339                                    a prototype or const/sub ref before.  */
11340             if (SvTYPE(gv) > SVt_NULL) {
11341                 cv_ckproto_len_flags((const CV *)gv,
11342                                     o ? (const GV *)cSVOPo->op_sv : NULL, ps,
11343                                     ps_len, ps_utf8);
11344             }
11345
11346             if (!SvROK(gv)) {
11347                 if (ps) {
11348                     sv_setpvn(MUTABLE_SV(gv), ps, ps_len);
11349                     if (ps_utf8)
11350                         SvUTF8_on(MUTABLE_SV(gv));
11351                 }
11352                 else
11353                     sv_setiv(MUTABLE_SV(gv), -1);
11354             }
11355
11356             SvREFCNT_dec(PL_compcv);
11357             cv = PL_compcv = NULL;
11358             goto done;
11359         }
11360     }
11361
11362     cv = (!name || (isGV(gv) && GvCVGEN(gv)))
11363         ? NULL
11364         : isGV(gv)
11365             ? GvCV(gv)
11366             : SvROK(gv) && SvTYPE(SvRV(gv)) == SVt_PVCV
11367                 ? (CV *)SvRV(gv)
11368                 : NULL;
11369
11370     if (block) {
11371         assert(PL_parser);
11372         /* This makes sub {}; work as expected.  */
11373         if (block->op_type == OP_STUB) {
11374             const line_t l = PL_parser->copline;
11375             op_free(block);
11376             block = newSTATEOP(0, NULL, 0);
11377             PL_parser->copline = l;
11378         }
11379         block = CvLVALUE(PL_compcv)
11380              || (cv && CvLVALUE(cv) && !CvROOT(cv) && !CvXSUB(cv)
11381                     && (!isGV(gv) || !GvASSUMECV(gv)))
11382                    ? newUNOP(OP_LEAVESUBLV, 0,
11383                              op_lvalue(scalarseq(block), OP_LEAVESUBLV))
11384                    : newUNOP(OP_LEAVESUB, 0, scalarseq(block));
11385         start = LINKLIST(block);
11386         block->op_next = 0;
11387         if (ps && !*ps && !attrs && !CvLVALUE(PL_compcv))
11388             const_sv =
11389                 S_op_const_sv(aTHX_ start, PL_compcv,
11390                                         cBOOL(CvCLONE(PL_compcv)));
11391         else
11392             const_sv = NULL;
11393     }
11394     else
11395         const_sv = NULL;
11396
11397     if (SvPOK(gv) || (SvROK(gv) && SvTYPE(SvRV(gv)) != SVt_PVCV)) {
11398         cv_ckproto_len_flags((const CV *)gv,
11399                              o ? (const GV *)cSVOPo->op_sv : NULL, ps,
11400                              ps_len, ps_utf8|CV_CKPROTO_CURSTASH);
11401         if (SvROK(gv)) {
11402             /* All the other code for sub redefinition warnings expects the
11403                clobbered sub to be a CV.  Instead of making all those code
11404                paths more complex, just inline the RV version here.  */
11405             const line_t oldline = CopLINE(PL_curcop);
11406             assert(IN_PERL_COMPILETIME);
11407             if (PL_parser && PL_parser->copline != NOLINE)
11408                 /* This ensures that warnings are reported at the first
11409                    line of a redefinition, not the last.  */
11410                 CopLINE_set(PL_curcop, PL_parser->copline);
11411             /* protect against fatal warnings leaking compcv */
11412             SAVEFREESV(PL_compcv);
11413
11414             if (ckWARN(WARN_REDEFINE)
11415              || (  ckWARN_d(WARN_REDEFINE)
11416                 && (  !const_sv || SvRV(gv) == const_sv
11417                    || sv_cmp(SvRV(gv), const_sv)  ))) {
11418                 assert(cSVOPo);
11419                 Perl_warner(aTHX_ packWARN(WARN_REDEFINE),
11420                           "Constant subroutine %" SVf " redefined",
11421                           SVfARG(cSVOPo->op_sv));
11422             }
11423
11424             SvREFCNT_inc_simple_void_NN(PL_compcv);
11425             CopLINE_set(PL_curcop, oldline);
11426             SvREFCNT_dec(SvRV(gv));
11427         }
11428     }
11429
11430     if (cv) {
11431         const bool exists = CvROOT(cv) || CvXSUB(cv);
11432
11433         /* if the subroutine doesn't exist and wasn't pre-declared
11434          * with a prototype, assume it will be AUTOLOADed,
11435          * skipping the prototype check
11436          */
11437         if (exists || SvPOK(cv))
11438             cv_ckproto_len_flags(cv, gv, ps, ps_len, ps_utf8);
11439         /* already defined (or promised)? */
11440         if (exists || (isGV(gv) && GvASSUMECV(gv))) {
11441             S_already_defined(aTHX_ cv, block, o, NULL, &const_sv);
11442             if (block)
11443                 cv = NULL;
11444             else {
11445                 if (attrs)
11446                     goto attrs;
11447                 /* just a "sub foo;" when &foo is already defined */
11448                 SAVEFREESV(PL_compcv);
11449                 goto done;
11450             }
11451         }
11452     }
11453
11454     if (const_sv) {
11455         SvREFCNT_inc_simple_void_NN(const_sv);
11456         SvFLAGS(const_sv) |= SVs_PADTMP;
11457         if (cv) {
11458             assert(!CvROOT(cv) && !CvCONST(cv));
11459             cv_forget_slab(cv);
11460             SvPVCLEAR(MUTABLE_SV(cv));  /* prototype is "" */
11461             CvXSUBANY(cv).any_ptr = const_sv;
11462             CvXSUB(cv) = const_sv_xsub;
11463             CvCONST_on(cv);
11464             CvISXSUB_on(cv);
11465             PoisonPADLIST(cv);
11466             CvFLAGS(cv) |= CvMETHOD(PL_compcv);
11467         }
11468         else {
11469             if (isGV(gv) || CvMETHOD(PL_compcv)) {
11470                 if (name && isGV(gv))
11471                     GvCV_set(gv, NULL);
11472                 cv = newCONSTSUB_flags(
11473                     NULL, name, namlen, name_is_utf8 ? SVf_UTF8 : 0,
11474                     const_sv
11475                 );
11476                 assert(cv);
11477                 assert(SvREFCNT((SV*)cv) != 0);
11478                 CvFLAGS(cv) |= CvMETHOD(PL_compcv);
11479             }
11480             else {
11481                 if (!SvROK(gv)) {
11482                     SV_CHECK_THINKFIRST_COW_DROP((SV *)gv);
11483                     prepare_SV_for_RV((SV *)gv);
11484                     SvOK_off((SV *)gv);
11485                     SvROK_on(gv);
11486                 }
11487                 SvRV_set(gv, const_sv);
11488             }
11489         }
11490         op_free(block);
11491         SvREFCNT_dec(PL_compcv);
11492         PL_compcv = NULL;
11493         goto done;
11494     }
11495
11496     /* don't copy new BEGIN CV to old BEGIN CV - RT #129099 */
11497     if (name && cv && *name == 'B' && strEQ(name, "BEGIN"))
11498         cv = NULL;
11499
11500     if (cv) {                           /* must reuse cv if autoloaded */
11501         /* transfer PL_compcv to cv */
11502         if (block) {
11503             bool free_file = CvFILE(cv) && CvDYNFILE(cv);
11504             cv_flags_t existing_builtin_attrs = CvFLAGS(cv) & CVf_BUILTIN_ATTRS;
11505             PADLIST *const temp_av = CvPADLIST(cv);
11506             CV *const temp_cv = CvOUTSIDE(cv);
11507             const cv_flags_t other_flags =
11508                 CvFLAGS(cv) & (CVf_SLABBED|CVf_WEAKOUTSIDE);
11509             OP * const cvstart = CvSTART(cv);
11510
11511             if (isGV(gv)) {
11512                 CvGV_set(cv,gv);
11513                 assert(!CvCVGV_RC(cv));
11514                 assert(CvGV(cv) == gv);
11515             }
11516             else {
11517                 U32 hash;
11518                 PERL_HASH(hash, name, namlen);
11519                 CvNAME_HEK_set(cv,
11520                                share_hek(name,
11521                                          name_is_utf8
11522                                             ? -(SSize_t)namlen
11523                                             :  (SSize_t)namlen,
11524                                          hash));
11525             }
11526
11527             SvPOK_off(cv);
11528             CvFLAGS(cv) = CvFLAGS(PL_compcv) | existing_builtin_attrs
11529                                              | CvNAMED(cv);
11530             CvOUTSIDE(cv) = CvOUTSIDE(PL_compcv);
11531             CvOUTSIDE_SEQ(cv) = CvOUTSIDE_SEQ(PL_compcv);
11532             CvPADLIST_set(cv,CvPADLIST(PL_compcv));
11533             CvOUTSIDE(PL_compcv) = temp_cv;
11534             CvPADLIST_set(PL_compcv, temp_av);
11535             CvSTART(cv) = CvSTART(PL_compcv);
11536             CvSTART(PL_compcv) = cvstart;
11537             CvFLAGS(PL_compcv) &= ~(CVf_SLABBED|CVf_WEAKOUTSIDE);
11538             CvFLAGS(PL_compcv) |= other_flags;
11539
11540             if (free_file) {
11541                 Safefree(CvFILE(cv));
11542             }
11543             CvFILE_set_from_cop(cv, PL_curcop);
11544             CvSTASH_set(cv, PL_curstash);
11545
11546             /* inner references to PL_compcv must be fixed up ... */
11547             pad_fixup_inner_anons(CvPADLIST(cv), PL_compcv, cv);
11548             if (PERLDB_INTER)/* Advice debugger on the new sub. */
11549                 ++PL_sub_generation;
11550         }
11551         else {
11552             /* Might have had built-in attributes applied -- propagate them. */
11553             CvFLAGS(cv) |= (CvFLAGS(PL_compcv) & CVf_BUILTIN_ATTRS);
11554         }
11555         /* ... before we throw it away */
11556         SvREFCNT_dec(PL_compcv);
11557         PL_compcv = cv;
11558     }
11559     else {
11560         cv = PL_compcv;
11561         if (name && isGV(gv)) {
11562             GvCV_set(gv, cv);
11563             GvCVGEN(gv) = 0;
11564             if (HvENAME_HEK(GvSTASH(gv)))
11565                 /* sub Foo::bar { (shift)+1 } */
11566                 gv_method_changed(gv);
11567         }
11568         else if (name) {
11569             if (!SvROK(gv)) {
11570                 SV_CHECK_THINKFIRST_COW_DROP((SV *)gv);
11571                 prepare_SV_for_RV((SV *)gv);
11572                 SvOK_off((SV *)gv);
11573                 SvROK_on(gv);
11574             }
11575             SvRV_set(gv, (SV *)cv);
11576             if (HvENAME_HEK(PL_curstash))
11577                 mro_method_changed_in(PL_curstash);
11578         }
11579     }
11580     assert(cv);
11581     assert(SvREFCNT((SV*)cv) != 0);
11582
11583     if (!CvHASGV(cv)) {
11584         if (isGV(gv))
11585             CvGV_set(cv, gv);
11586         else {
11587             U32 hash;
11588             PERL_HASH(hash, name, namlen);
11589             CvNAME_HEK_set(cv, share_hek(name,
11590                                          name_is_utf8
11591                                             ? -(SSize_t)namlen
11592                                             :  (SSize_t)namlen,
11593                                          hash));
11594         }
11595         CvFILE_set_from_cop(cv, PL_curcop);
11596         CvSTASH_set(cv, PL_curstash);
11597     }
11598
11599     if (ps) {
11600         sv_setpvn(MUTABLE_SV(cv), ps, ps_len);
11601         if ( ps_utf8 )
11602             SvUTF8_on(MUTABLE_SV(cv));
11603     }
11604
11605     if (block) {
11606         /* If we assign an optree to a PVCV, then we've defined a
11607          * subroutine that the debugger could be able to set a breakpoint
11608          * in, so signal to pp_entereval that it should not throw away any
11609          * saved lines at scope exit.  */
11610
11611         PL_breakable_sub_gen++;
11612         CvROOT(cv) = block;
11613         /* The cv no longer needs to hold a refcount on the slab, as CvROOT
11614            itself has a refcount. */
11615         CvSLABBED_off(cv);
11616         OpslabREFCNT_dec_padok((OPSLAB *)CvSTART(cv));
11617 #ifdef PERL_DEBUG_READONLY_OPS
11618         slab = (OPSLAB *)CvSTART(cv);
11619 #endif
11620         S_process_optree(aTHX_ cv, block, start);
11621     }
11622
11623   attrs:
11624     if (attrs) {
11625         /* Need to do a C<use attributes $stash_of_cv,\&cv,@attrs>. */
11626         HV *stash = name && !CvNAMED(cv) && GvSTASH(CvGV(cv))
11627                         ? GvSTASH(CvGV(cv))
11628                         : PL_curstash;
11629         if (!name)
11630             SAVEFREESV(cv);
11631         apply_attrs(stash, MUTABLE_SV(cv), attrs);
11632         if (!name)
11633             SvREFCNT_inc_simple_void_NN(cv);
11634     }
11635
11636     if (block && has_name) {
11637         if (PERLDB_SUBLINE && PL_curstash != PL_debstash) {
11638             SV * const tmpstr = cv_name(cv,NULL,0);
11639             GV * const db_postponed = gv_fetchpvs("DB::postponed",
11640                                                   GV_ADDMULTI, SVt_PVHV);
11641             HV *hv;
11642             SV * const sv = Perl_newSVpvf(aTHX_ "%s:%ld-%ld",
11643                                           CopFILE(PL_curcop),
11644                                           (long)PL_subline,
11645                                           (long)CopLINE(PL_curcop));
11646             (void)hv_store(GvHV(PL_DBsub), SvPVX_const(tmpstr),
11647                     SvUTF8(tmpstr) ? -(I32)SvCUR(tmpstr) : (I32)SvCUR(tmpstr), sv, 0);
11648             hv = GvHVn(db_postponed);
11649             if (HvTOTALKEYS(hv) > 0 && hv_exists(hv, SvPVX_const(tmpstr), SvUTF8(tmpstr) ? -(I32)SvCUR(tmpstr) : (I32)SvCUR(tmpstr))) {
11650                 CV * const pcv = GvCV(db_postponed);
11651                 if (pcv) {
11652                     dSP;
11653                     PUSHMARK(SP);
11654                     XPUSHs(tmpstr);
11655                     PUTBACK;
11656                     call_sv(MUTABLE_SV(pcv), G_DISCARD);
11657                 }
11658             }
11659         }
11660
11661         if (name) {
11662             if (PL_parser && PL_parser->error_count)
11663                 clear_special_blocks(name, gv, cv);
11664             else
11665                 evanescent =
11666                     process_special_blocks(floor, name, gv, cv);
11667         }
11668     }
11669     assert(cv);
11670
11671   done:
11672     assert(!cv || evanescent || SvREFCNT((SV*)cv) != 0);
11673     if (PL_parser)
11674         PL_parser->copline = NOLINE;
11675     LEAVE_SCOPE(floor);
11676
11677     assert(!cv || evanescent || SvREFCNT((SV*)cv) != 0);
11678     if (!evanescent) {
11679 #ifdef PERL_DEBUG_READONLY_OPS
11680     if (slab)
11681         Slab_to_ro(slab);
11682 #endif
11683     if (cv && name && block && CvOUTSIDE(cv) && !CvEVAL(CvOUTSIDE(cv)))
11684         pad_add_weakref(cv);
11685     }
11686     return cv;
11687 }
11688
11689 STATIC void
11690 S_clear_special_blocks(pTHX_ const char *const fullname,
11691                        GV *const gv, CV *const cv) {
11692     const char *colon;
11693     const char *name;
11694
11695     PERL_ARGS_ASSERT_CLEAR_SPECIAL_BLOCKS;
11696
11697     colon = strrchr(fullname,':');
11698     name = colon ? colon + 1 : fullname;
11699
11700     if ((*name == 'B' && strEQ(name, "BEGIN"))
11701         || (*name == 'E' && strEQ(name, "END"))
11702         || (*name == 'U' && strEQ(name, "UNITCHECK"))
11703         || (*name == 'C' && strEQ(name, "CHECK"))
11704         || (*name == 'I' && strEQ(name, "INIT"))) {
11705         if (!isGV(gv)) {
11706             (void)CvGV(cv);
11707             assert(isGV(gv));
11708         }
11709         GvCV_set(gv, NULL);
11710         SvREFCNT_dec_NN(MUTABLE_SV(cv));
11711     }
11712 }
11713
11714 /* Returns true if the sub has been freed.  */
11715 STATIC bool
11716 S_process_special_blocks(pTHX_ I32 floor, const char *const fullname,
11717                          GV *const gv,
11718                          CV *const cv)
11719 {
11720     const char *const colon = strrchr(fullname,':');
11721     const char *const name = colon ? colon + 1 : fullname;
11722
11723     PERL_ARGS_ASSERT_PROCESS_SPECIAL_BLOCKS;
11724
11725     if (*name == 'B') {
11726         if (strEQ(name, "BEGIN")) {
11727             const I32 oldscope = PL_scopestack_ix;
11728             dSP;
11729             (void)CvGV(cv);
11730             if (floor) LEAVE_SCOPE(floor);
11731             ENTER;
11732             PUSHSTACKi(PERLSI_REQUIRE);
11733             SAVECOPFILE(&PL_compiling);
11734             SAVECOPLINE(&PL_compiling);
11735             SAVEVPTR(PL_curcop);
11736
11737             DEBUG_x( dump_sub(gv) );
11738             Perl_av_create_and_push(aTHX_ &PL_beginav, MUTABLE_SV(cv));
11739             GvCV_set(gv,0);             /* cv has been hijacked */
11740             call_list(oldscope, PL_beginav);
11741
11742             POPSTACK;
11743             LEAVE;
11744             return !PL_savebegin;
11745         }
11746         else
11747             return FALSE;
11748     } else {
11749         if (*name == 'E') {
11750             if (strEQ(name, "END")) {
11751                 DEBUG_x( dump_sub(gv) );
11752                 Perl_av_create_and_unshift_one(aTHX_ &PL_endav, MUTABLE_SV(cv));
11753             } else
11754                 return FALSE;
11755         } else if (*name == 'U') {
11756             if (strEQ(name, "UNITCHECK")) {
11757                 /* It's never too late to run a unitcheck block */
11758                 Perl_av_create_and_unshift_one(aTHX_ &PL_unitcheckav, MUTABLE_SV(cv));
11759             }
11760             else
11761                 return FALSE;
11762         } else if (*name == 'C') {
11763             if (strEQ(name, "CHECK")) {
11764                 if (PL_main_start)
11765                     /* diag_listed_as: Too late to run %s block */
11766                     Perl_ck_warner(aTHX_ packWARN(WARN_VOID),
11767                                    "Too late to run CHECK block");
11768                 Perl_av_create_and_unshift_one(aTHX_ &PL_checkav, MUTABLE_SV(cv));
11769             }
11770             else
11771                 return FALSE;
11772         } else if (*name == 'I') {
11773             if (strEQ(name, "INIT")) {
11774                 if (PL_main_start)
11775                     /* diag_listed_as: Too late to run %s block */
11776                     Perl_ck_warner(aTHX_ packWARN(WARN_VOID),
11777                                    "Too late to run INIT block");
11778                 Perl_av_create_and_push(aTHX_ &PL_initav, MUTABLE_SV(cv));
11779             }
11780             else
11781                 return FALSE;
11782         } else
11783             return FALSE;
11784         DEBUG_x( dump_sub(gv) );
11785         (void)CvGV(cv);
11786         GvCV_set(gv,0);         /* cv has been hijacked */
11787         return FALSE;
11788     }
11789 }
11790
11791 /*
11792 =for apidoc newCONSTSUB
11793
11794 Behaves like L</newCONSTSUB_flags>, except that C<name> is nul-terminated
11795 rather than of counted length, and no flags are set.  (This means that
11796 C<name> is always interpreted as Latin-1.)
11797
11798 =cut
11799 */
11800
11801 CV *
11802 Perl_newCONSTSUB(pTHX_ HV *stash, const char *name, SV *sv)
11803 {
11804     return newCONSTSUB_flags(stash, name, name ? strlen(name) : 0, 0, sv);
11805 }
11806
11807 /*
11808 =for apidoc newCONSTSUB_flags
11809
11810 Construct a constant subroutine, also performing some surrounding
11811 jobs.  A scalar constant-valued subroutine is eligible for inlining
11812 at compile-time, and in Perl code can be created by S<C<sub FOO () {
11813 123 }>>.  Other kinds of constant subroutine have other treatment.
11814
11815 The subroutine will have an empty prototype and will ignore any arguments
11816 when called.  Its constant behaviour is determined by C<sv>.  If C<sv>
11817 is null, the subroutine will yield an empty list.  If C<sv> points to a
11818 scalar, the subroutine will always yield that scalar.  If C<sv> points
11819 to an array, the subroutine will always yield a list of the elements of
11820 that array in list context, or the number of elements in the array in
11821 scalar context.  This function takes ownership of one counted reference
11822 to the scalar or array, and will arrange for the object to live as long
11823 as the subroutine does.  If C<sv> points to a scalar then the inlining
11824 assumes that the value of the scalar will never change, so the caller
11825 must ensure that the scalar is not subsequently written to.  If C<sv>
11826 points to an array then no such assumption is made, so it is ostensibly
11827 safe to mutate the array or its elements, but whether this is really
11828 supported has not been determined.
11829
11830 The subroutine will have C<CvFILE> set according to C<PL_curcop>.
11831 Other aspects of the subroutine will be left in their default state.
11832 The caller is free to mutate the subroutine beyond its initial state
11833 after this function has returned.
11834
11835 If C<name> is null then the subroutine will be anonymous, with its
11836 C<CvGV> referring to an C<__ANON__> glob.  If C<name> is non-null then the
11837 subroutine will be named accordingly, referenced by the appropriate glob.
11838 C<name> is a string of length C<len> bytes giving a sigilless symbol
11839 name, in UTF-8 if C<flags> has the C<SVf_UTF8> bit set and in Latin-1
11840 otherwise.  The name may be either qualified or unqualified.  If the
11841 name is unqualified then it defaults to being in the stash specified by
11842 C<stash> if that is non-null, or to C<PL_curstash> if C<stash> is null.
11843 The symbol is always added to the stash if necessary, with C<GV_ADDMULTI>
11844 semantics.
11845
11846 C<flags> should not have bits set other than C<SVf_UTF8>.
11847
11848 If there is already a subroutine of the specified name, then the new sub
11849 will replace the existing one in the glob.  A warning may be generated
11850 about the redefinition.
11851
11852 If the subroutine has one of a few special names, such as C<BEGIN> or
11853 C<END>, then it will be claimed by the appropriate queue for automatic
11854 running of phase-related subroutines.  In this case the relevant glob will
11855 be left not containing any subroutine, even if it did contain one before.
11856 Execution of the subroutine will likely be a no-op, unless C<sv> was
11857 a tied array or the caller modified the subroutine in some interesting
11858 way before it was executed.  In the case of C<BEGIN>, the treatment is
11859 buggy: the sub will be executed when only half built, and may be deleted
11860 prematurely, possibly causing a crash.
11861
11862 The function returns a pointer to the constructed subroutine.  If the sub
11863 is anonymous then ownership of one counted reference to the subroutine
11864 is transferred to the caller.  If the sub is named then the caller does
11865 not get ownership of a reference.  In most such cases, where the sub
11866 has a non-phase name, the sub will be alive at the point it is returned
11867 by virtue of being contained in the glob that names it.  A phase-named
11868 subroutine will usually be alive by virtue of the reference owned by
11869 the phase's automatic run queue.  A C<BEGIN> subroutine may have been
11870 destroyed already by the time this function returns, but currently bugs
11871 occur in that case before the caller gets control.  It is the caller's
11872 responsibility to ensure that it knows which of these situations applies.
11873
11874 =cut
11875 */
11876
11877 CV *
11878 Perl_newCONSTSUB_flags(pTHX_ HV *stash, const char *name, STRLEN len,
11879                              U32 flags, SV *sv)
11880 {
11881     CV* cv;
11882     const char *const file = CopFILE(PL_curcop);
11883
11884     ENTER;
11885
11886     if (IN_PERL_RUNTIME) {
11887         /* at runtime, it's not safe to manipulate PL_curcop: it may be
11888          * an op shared between threads. Use a non-shared COP for our
11889          * dirty work */
11890          SAVEVPTR(PL_curcop);
11891          SAVECOMPILEWARNINGS();
11892          PL_compiling.cop_warnings = DUP_WARNINGS(PL_curcop->cop_warnings);
11893          PL_curcop = &PL_compiling;
11894     }
11895     SAVECOPLINE(PL_curcop);
11896     CopLINE_set(PL_curcop, PL_parser ? PL_parser->copline : NOLINE);
11897
11898     SAVEHINTS();
11899     PL_hints &= ~HINT_BLOCK_SCOPE;
11900
11901     if (stash) {
11902         SAVEGENERICSV(PL_curstash);
11903         PL_curstash = (HV *)SvREFCNT_inc_simple_NN(stash);
11904     }
11905
11906     /* Protect sv against leakage caused by fatal warnings. */
11907     if (sv) SAVEFREESV(sv);
11908
11909     /* file becomes the CvFILE. For an XS, it's usually static storage,
11910        and so doesn't get free()d.  (It's expected to be from the C pre-
11911        processor __FILE__ directive). But we need a dynamically allocated one,
11912        and we need it to get freed.  */
11913     cv = newXS_len_flags(name, len,
11914                          sv && SvTYPE(sv) == SVt_PVAV
11915                              ? const_av_xsub
11916                              : const_sv_xsub,
11917                          file ? file : "", "",
11918                          &sv, XS_DYNAMIC_FILENAME | flags);
11919     assert(cv);
11920     assert(SvREFCNT((SV*)cv) != 0);
11921     CvXSUBANY(cv).any_ptr = SvREFCNT_inc_simple(sv);
11922     CvCONST_on(cv);
11923
11924     LEAVE;
11925
11926     return cv;
11927 }
11928
11929 /*
11930 =for apidoc newXS
11931
11932 Used by C<xsubpp> to hook up XSUBs as Perl subs.  C<filename> needs to be
11933 static storage, as it is used directly as CvFILE(), without a copy being made.
11934
11935 =cut
11936 */
11937
11938 CV *
11939 Perl_newXS(pTHX_ const char *name, XSUBADDR_t subaddr, const char *filename)
11940 {
11941     PERL_ARGS_ASSERT_NEWXS;
11942     return newXS_len_flags(
11943         name, name ? strlen(name) : 0, subaddr, filename, NULL, NULL, 0
11944     );
11945 }
11946
11947 CV *
11948 Perl_newXS_flags(pTHX_ const char *name, XSUBADDR_t subaddr,
11949                  const char *const filename, const char *const proto,
11950                  U32 flags)
11951 {
11952     PERL_ARGS_ASSERT_NEWXS_FLAGS;
11953     return newXS_len_flags(
11954        name, name ? strlen(name) : 0, subaddr, filename, proto, NULL, flags
11955     );
11956 }
11957
11958 CV *
11959 Perl_newXS_deffile(pTHX_ const char *name, XSUBADDR_t subaddr)
11960 {
11961     PERL_ARGS_ASSERT_NEWXS_DEFFILE;
11962     return newXS_len_flags(
11963         name, strlen(name), subaddr, NULL, NULL, NULL, 0
11964     );
11965 }
11966
11967 /*
11968 =for apidoc newXS_len_flags
11969
11970 Construct an XS subroutine, also performing some surrounding jobs.
11971
11972 The subroutine will have the entry point C<subaddr>.  It will have
11973 the prototype specified by the nul-terminated string C<proto>, or
11974 no prototype if C<proto> is null.  The prototype string is copied;
11975 the caller can mutate the supplied string afterwards.  If C<filename>
11976 is non-null, it must be a nul-terminated filename, and the subroutine
11977 will have its C<CvFILE> set accordingly.  By default C<CvFILE> is set to
11978 point directly to the supplied string, which must be static.  If C<flags>
11979 has the C<XS_DYNAMIC_FILENAME> bit set, then a copy of the string will
11980 be taken instead.
11981
11982 Other aspects of the subroutine will be left in their default state.
11983 If anything else needs to be done to the subroutine for it to function
11984 correctly, it is the caller's responsibility to do that after this
11985 function has constructed it.  However, beware of the subroutine
11986 potentially being destroyed before this function returns, as described
11987 below.
11988
11989 If C<name> is null then the subroutine will be anonymous, with its
11990 C<CvGV> referring to an C<__ANON__> glob.  If C<name> is non-null then the
11991 subroutine will be named accordingly, referenced by the appropriate glob.
11992 C<name> is a string of length C<len> bytes giving a sigilless symbol name,
11993 in UTF-8 if C<flags> has the C<SVf_UTF8> bit set and in Latin-1 otherwise.
11994 The name may be either qualified or unqualified, with the stash defaulting
11995 in the same manner as for C<gv_fetchpvn_flags>.  C<flags> may contain
11996 flag bits understood by C<gv_fetchpvn_flags> with the same meaning as
11997 they have there, such as C<GV_ADDWARN>.  The symbol is always added to
11998 the stash if necessary, with C<GV_ADDMULTI> semantics.
11999
12000 If there is already a subroutine of the specified name, then the new sub
12001 will replace the existing one in the glob.  A warning may be generated
12002 about the redefinition.  If the old subroutine was C<CvCONST> then the
12003 decision about whether to warn is influenced by an expectation about
12004 whether the new subroutine will become a constant of similar value.
12005 That expectation is determined by C<const_svp>.  (Note that the call to
12006 this function doesn't make the new subroutine C<CvCONST> in any case;
12007 that is left to the caller.)  If C<const_svp> is null then it indicates
12008 that the new subroutine will not become a constant.  If C<const_svp>
12009 is non-null then it indicates that the new subroutine will become a
12010 constant, and it points to an C<SV*> that provides the constant value
12011 that the subroutine will have.
12012
12013 If the subroutine has one of a few special names, such as C<BEGIN> or
12014 C<END>, then it will be claimed by the appropriate queue for automatic
12015 running of phase-related subroutines.  In this case the relevant glob will
12016 be left not containing any subroutine, even if it did contain one before.
12017 In the case of C<BEGIN>, the subroutine will be executed and the reference
12018 to it disposed of before this function returns, and also before its
12019 prototype is set.  If a C<BEGIN> subroutine would not be sufficiently
12020 constructed by this function to be ready for execution then the caller
12021 must prevent this happening by giving the subroutine a different name.
12022
12023 The function returns a pointer to the constructed subroutine.  If the sub
12024 is anonymous then ownership of one counted reference to the subroutine
12025 is transferred to the caller.  If the sub is named then the caller does
12026 not get ownership of a reference.  In most such cases, where the sub
12027 has a non-phase name, the sub will be alive at the point it is returned
12028 by virtue of being contained in the glob that names it.  A phase-named
12029 subroutine will usually be alive by virtue of the reference owned by the
12030 phase's automatic run queue.  But a C<BEGIN> subroutine, having already
12031 been executed, will quite likely have been destroyed already by the
12032 time this function returns, making it erroneous for the caller to make
12033 any use of the returned pointer.  It is the caller's responsibility to
12034 ensure that it knows which of these situations applies.
12035
12036 =cut
12037 */
12038
12039 CV *
12040 Perl_newXS_len_flags(pTHX_ const char *name, STRLEN len,
12041                            XSUBADDR_t subaddr, const char *const filename,
12042                            const char *const proto, SV **const_svp,
12043                            U32 flags)
12044 {
12045     CV *cv;
12046     bool interleave = FALSE;
12047     bool evanescent = FALSE;
12048
12049     PERL_ARGS_ASSERT_NEWXS_LEN_FLAGS;
12050
12051     {
12052         GV * const gv = gv_fetchpvn(
12053                             name ? name : PL_curstash ? "__ANON__" : "__ANON__::__ANON__",
12054                             name ? len : PL_curstash ? sizeof("__ANON__") - 1:
12055                                 sizeof("__ANON__::__ANON__") - 1,
12056                             GV_ADDMULTI | flags, SVt_PVCV);
12057
12058         if ((cv = (name ? GvCV(gv) : NULL))) {
12059             if (GvCVGEN(gv)) {
12060                 /* just a cached method */
12061                 SvREFCNT_dec(cv);
12062                 cv = NULL;
12063             }
12064             else if (CvROOT(cv) || CvXSUB(cv) || GvASSUMECV(gv)) {
12065                 /* already defined (or promised) */
12066                 /* Redundant check that allows us to avoid creating an SV
12067                    most of the time: */
12068                 if (CvCONST(cv) || ckWARN(WARN_REDEFINE)) {
12069                     report_redefined_cv(newSVpvn_flags(
12070                                          name,len,(flags&SVf_UTF8)|SVs_TEMP
12071                                         ),
12072                                         cv, const_svp);
12073                 }
12074                 interleave = TRUE;
12075                 ENTER;
12076                 SAVEFREESV(cv);
12077                 cv = NULL;
12078             }
12079         }
12080
12081         if (cv)                         /* must reuse cv if autoloaded */
12082             cv_undef(cv);
12083         else {
12084             cv = MUTABLE_CV(newSV_type(SVt_PVCV));
12085             if (name) {
12086                 GvCV_set(gv,cv);
12087                 GvCVGEN(gv) = 0;
12088                 if (HvENAME_HEK(GvSTASH(gv)))
12089                     gv_method_changed(gv); /* newXS */
12090             }
12091         }
12092         assert(cv);
12093         assert(SvREFCNT((SV*)cv) != 0);
12094
12095         CvGV_set(cv, gv);
12096         if(filename) {
12097             /* XSUBs can't be perl lang/perl5db.pl debugged
12098             if (PERLDB_LINE_OR_SAVESRC)
12099                 (void)gv_fetchfile(filename); */
12100             assert(!CvDYNFILE(cv)); /* cv_undef should have turned it off */
12101             if (flags & XS_DYNAMIC_FILENAME) {
12102                 CvDYNFILE_on(cv);
12103                 CvFILE(cv) = savepv(filename);
12104             } else {
12105             /* NOTE: not copied, as it is expected to be an external constant string */
12106                 CvFILE(cv) = (char *)filename;
12107             }
12108         } else {
12109             assert((flags & XS_DYNAMIC_FILENAME) == 0 && PL_xsubfilename);
12110             CvFILE(cv) = (char*)PL_xsubfilename;
12111         }
12112         CvISXSUB_on(cv);
12113         CvXSUB(cv) = subaddr;
12114 #ifndef PERL_IMPLICIT_CONTEXT
12115         CvHSCXT(cv) = &PL_stack_sp;
12116 #else
12117         PoisonPADLIST(cv);
12118 #endif
12119
12120         if (name)
12121             evanescent = process_special_blocks(0, name, gv, cv);
12122         else
12123             CvANON_on(cv);
12124     } /* <- not a conditional branch */
12125
12126     assert(cv);
12127     assert(evanescent || SvREFCNT((SV*)cv) != 0);
12128
12129     if (!evanescent) sv_setpv(MUTABLE_SV(cv), proto);
12130     if (interleave) LEAVE;
12131     assert(evanescent || SvREFCNT((SV*)cv) != 0);
12132     return cv;
12133 }
12134
12135 /* Add a stub CV to a typeglob.
12136  * This is the implementation of a forward declaration, 'sub foo';'
12137  */
12138
12139 CV *
12140 Perl_newSTUB(pTHX_ GV *gv, bool fake)
12141 {
12142     CV *cv = MUTABLE_CV(newSV_type(SVt_PVCV));
12143     GV *cvgv;
12144     PERL_ARGS_ASSERT_NEWSTUB;
12145     assert(!GvCVu(gv));
12146     GvCV_set(gv, cv);
12147     GvCVGEN(gv) = 0;
12148     if (!fake && GvSTASH(gv) && HvENAME_HEK(GvSTASH(gv)))
12149         gv_method_changed(gv);
12150     if (SvFAKE(gv)) {
12151         cvgv = gv_fetchsv((SV *)gv, GV_ADDMULTI, SVt_PVCV);
12152         SvFAKE_off(cvgv);
12153     }
12154     else cvgv = gv;
12155     CvGV_set(cv, cvgv);
12156     CvFILE_set_from_cop(cv, PL_curcop);
12157     CvSTASH_set(cv, PL_curstash);
12158     GvMULTI_on(gv);
12159     return cv;
12160 }
12161
12162 void
12163 Perl_newFORM(pTHX_ I32 floor, OP *o, OP *block)
12164 {
12165     CV *cv;
12166     GV *gv;
12167     OP *root;
12168     OP *start;
12169
12170     if (PL_parser && PL_parser->error_count) {
12171         op_free(block);
12172         goto finish;
12173     }
12174
12175     gv = o
12176         ? gv_fetchsv(cSVOPo->op_sv, GV_ADD, SVt_PVFM)
12177         : gv_fetchpvs("STDOUT", GV_ADD|GV_NOTQUAL, SVt_PVFM);
12178
12179     GvMULTI_on(gv);
12180     if ((cv = GvFORM(gv))) {
12181         if (ckWARN(WARN_REDEFINE)) {
12182             const line_t oldline = CopLINE(PL_curcop);
12183             if (PL_parser && PL_parser->copline != NOLINE)
12184                 CopLINE_set(PL_curcop, PL_parser->copline);
12185             if (o) {
12186                 Perl_warner(aTHX_ packWARN(WARN_REDEFINE),
12187                             "Format %" SVf " redefined", SVfARG(cSVOPo->op_sv));
12188             } else {
12189                 /* diag_listed_as: Format %s redefined */
12190                 Perl_warner(aTHX_ packWARN(WARN_REDEFINE),
12191                             "Format STDOUT redefined");
12192             }
12193             CopLINE_set(PL_curcop, oldline);
12194         }
12195         SvREFCNT_dec(cv);
12196     }
12197     cv = PL_compcv;
12198     GvFORM(gv) = (CV *)SvREFCNT_inc_simple_NN(cv);
12199     CvGV_set(cv, gv);
12200     CvFILE_set_from_cop(cv, PL_curcop);
12201
12202
12203     root = newUNOP(OP_LEAVEWRITE, 0, scalarseq(block));
12204     CvROOT(cv) = root;
12205     start = LINKLIST(root);
12206     root->op_next = 0;
12207     S_process_optree(aTHX_ cv, root, start);
12208     cv_forget_slab(cv);
12209
12210   finish:
12211     op_free(o);
12212     if (PL_parser)
12213         PL_parser->copline = NOLINE;
12214     LEAVE_SCOPE(floor);
12215     PL_compiling.cop_seq = 0;
12216 }
12217
12218 OP *
12219 Perl_newANONLIST(pTHX_ OP *o)
12220 {
12221     return op_convert_list(OP_ANONLIST, OPf_SPECIAL, o);
12222 }
12223
12224 OP *
12225 Perl_newANONHASH(pTHX_ OP *o)
12226 {
12227     return op_convert_list(OP_ANONHASH, OPf_SPECIAL, o);
12228 }
12229
12230 OP *
12231 Perl_newANONSUB(pTHX_ I32 floor, OP *proto, OP *block)
12232 {
12233     return newANONATTRSUB(floor, proto, NULL, block);
12234 }
12235
12236 OP *
12237 Perl_newANONATTRSUB(pTHX_ I32 floor, OP *proto, OP *attrs, OP *block)
12238 {
12239     SV * const cv = MUTABLE_SV(newATTRSUB(floor, 0, proto, attrs, block));
12240     OP * anoncode =
12241         newSVOP(OP_ANONCODE, 0,
12242                 cv);
12243     if (CvANONCONST(cv))
12244         anoncode = newUNOP(OP_ANONCONST, 0,
12245                            op_convert_list(OP_ENTERSUB,
12246                                            OPf_STACKED|OPf_WANT_SCALAR,
12247                                            anoncode));
12248     return newUNOP(OP_REFGEN, 0, anoncode);
12249 }
12250
12251 OP *
12252 Perl_oopsAV(pTHX_ OP *o)
12253 {
12254
12255     PERL_ARGS_ASSERT_OOPSAV;
12256
12257     switch (o->op_type) {
12258     case OP_PADSV:
12259     case OP_PADHV:
12260         OpTYPE_set(o, OP_PADAV);
12261         return ref(o, OP_RV2AV);
12262
12263     case OP_RV2SV:
12264     case OP_RV2HV:
12265         OpTYPE_set(o, OP_RV2AV);
12266         ref(o, OP_RV2AV);
12267         break;
12268
12269     default:
12270         Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL), "oops: oopsAV");
12271         break;
12272     }
12273     return o;
12274 }
12275
12276 OP *
12277 Perl_oopsHV(pTHX_ OP *o)
12278 {
12279
12280     PERL_ARGS_ASSERT_OOPSHV;
12281
12282     switch (o->op_type) {
12283     case OP_PADSV:
12284     case OP_PADAV:
12285         OpTYPE_set(o, OP_PADHV);
12286         return ref(o, OP_RV2HV);
12287
12288     case OP_RV2SV:
12289     case OP_RV2AV:
12290         OpTYPE_set(o, OP_RV2HV);
12291         /* rv2hv steals the bottom bit for its own uses */
12292         o->op_private &= ~OPpARG1_MASK;
12293         ref(o, OP_RV2HV);
12294         break;
12295
12296     default:
12297         Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL), "oops: oopsHV");
12298         break;
12299     }
12300     return o;
12301 }
12302
12303 OP *
12304 Perl_newAVREF(pTHX_ OP *o)
12305 {
12306
12307     PERL_ARGS_ASSERT_NEWAVREF;
12308
12309     if (o->op_type == OP_PADANY) {
12310         OpTYPE_set(o, OP_PADAV);
12311         return o;
12312     }
12313     else if ((o->op_type == OP_RV2AV || o->op_type == OP_PADAV)) {
12314         Perl_croak(aTHX_ "Can't use an array as a reference");
12315     }
12316     return newUNOP(OP_RV2AV, 0, scalar(o));
12317 }
12318
12319 OP *
12320 Perl_newGVREF(pTHX_ I32 type, OP *o)
12321 {
12322     if (type == OP_MAPSTART || type == OP_GREPSTART || type == OP_SORT)
12323         return newUNOP(OP_NULL, 0, o);
12324     return ref(newUNOP(OP_RV2GV, OPf_REF, o), type);
12325 }
12326
12327 OP *
12328 Perl_newHVREF(pTHX_ OP *o)
12329 {
12330
12331     PERL_ARGS_ASSERT_NEWHVREF;
12332
12333     if (o->op_type == OP_PADANY) {
12334         OpTYPE_set(o, OP_PADHV);
12335         return o;
12336     }
12337     else if ((o->op_type == OP_RV2HV || o->op_type == OP_PADHV)) {
12338         Perl_croak(aTHX_ "Can't use a hash as a reference");
12339     }
12340     return newUNOP(OP_RV2HV, 0, scalar(o));
12341 }
12342
12343 OP *
12344 Perl_newCVREF(pTHX_ I32 flags, OP *o)
12345 {
12346     if (o->op_type == OP_PADANY) {
12347         OpTYPE_set(o, OP_PADCV);
12348     }
12349     return newUNOP(OP_RV2CV, flags, scalar(o));
12350 }
12351
12352 OP *
12353 Perl_newSVREF(pTHX_ OP *o)
12354 {
12355
12356     PERL_ARGS_ASSERT_NEWSVREF;
12357
12358     if (o->op_type == OP_PADANY) {
12359         OpTYPE_set(o, OP_PADSV);
12360         scalar(o);
12361         return o;
12362     }
12363     return newUNOP(OP_RV2SV, 0, scalar(o));
12364 }
12365
12366 /* Check routines. See the comments at the top of this file for details
12367  * on when these are called */
12368
12369 OP *
12370 Perl_ck_anoncode(pTHX_ OP *o)
12371 {
12372     PERL_ARGS_ASSERT_CK_ANONCODE;
12373
12374     cSVOPo->op_targ = pad_add_anon((CV*)cSVOPo->op_sv, o->op_type);
12375     cSVOPo->op_sv = NULL;
12376     return o;
12377 }
12378
12379 static void
12380 S_io_hints(pTHX_ OP *o)
12381 {
12382 #if O_BINARY != 0 || O_TEXT != 0
12383     HV * const table =
12384         PL_hints & HINT_LOCALIZE_HH ? GvHV(PL_hintgv) : NULL;;
12385     if (table) {
12386         SV **svp = hv_fetchs(table, "open_IN", FALSE);
12387         if (svp && *svp) {
12388             STRLEN len = 0;
12389             const char *d = SvPV_const(*svp, len);
12390             const I32 mode = mode_from_discipline(d, len);
12391             /* bit-and:ing with zero O_BINARY or O_TEXT would be useless. */
12392 #  if O_BINARY != 0
12393             if (mode & O_BINARY)
12394                 o->op_private |= OPpOPEN_IN_RAW;
12395 #  endif
12396 #  if O_TEXT != 0
12397             if (mode & O_TEXT)
12398                 o->op_private |= OPpOPEN_IN_CRLF;
12399 #  endif
12400         }
12401
12402         svp = hv_fetchs(table, "open_OUT", FALSE);
12403         if (svp && *svp) {
12404             STRLEN len = 0;
12405             const char *d = SvPV_const(*svp, len);
12406             const I32 mode = mode_from_discipline(d, len);
12407             /* bit-and:ing with zero O_BINARY or O_TEXT would be useless. */
12408 #  if O_BINARY != 0
12409             if (mode & O_BINARY)
12410                 o->op_private |= OPpOPEN_OUT_RAW;
12411 #  endif
12412 #  if O_TEXT != 0
12413             if (mode & O_TEXT)
12414                 o->op_private |= OPpOPEN_OUT_CRLF;
12415 #  endif
12416         }
12417     }
12418 #else
12419     PERL_UNUSED_CONTEXT;
12420     PERL_UNUSED_ARG(o);
12421 #endif
12422 }
12423
12424 OP *
12425 Perl_ck_backtick(pTHX_ OP *o)
12426 {
12427     GV *gv;
12428     OP *newop = NULL;
12429     OP *sibl;
12430     PERL_ARGS_ASSERT_CK_BACKTICK;
12431     o = ck_fun(o);
12432     /* qx and `` have a null pushmark; CORE::readpipe has only one kid. */
12433     if (o->op_flags & OPf_KIDS && (sibl = OpSIBLING(cUNOPo->op_first))
12434      && (gv = gv_override("readpipe",8)))
12435     {
12436         /* detach rest of siblings from o and its first child */
12437         op_sibling_splice(o, cUNOPo->op_first, -1, NULL);
12438         newop = S_new_entersubop(aTHX_ gv, sibl);
12439     }
12440     else if (!(o->op_flags & OPf_KIDS))
12441         newop = newUNOP(OP_BACKTICK, 0, newDEFSVOP());
12442     if (newop) {
12443         op_free(o);
12444         return newop;
12445     }
12446     S_io_hints(aTHX_ o);
12447     return o;
12448 }
12449
12450 OP *
12451 Perl_ck_bitop(pTHX_ OP *o)
12452 {
12453     PERL_ARGS_ASSERT_CK_BITOP;
12454
12455     o->op_private = (U8)(PL_hints & HINT_INTEGER);
12456
12457     if (!(o->op_flags & OPf_STACKED) /* Not an assignment */
12458             && OP_IS_INFIX_BIT(o->op_type))
12459     {
12460         const OP * const left = cBINOPo->op_first;
12461         const OP * const right = OpSIBLING(left);
12462         if ((OP_IS_NUMCOMPARE(left->op_type) &&
12463                 (left->op_flags & OPf_PARENS) == 0) ||
12464             (OP_IS_NUMCOMPARE(right->op_type) &&
12465                 (right->op_flags & OPf_PARENS) == 0))
12466             Perl_ck_warner(aTHX_ packWARN(WARN_PRECEDENCE),
12467                           "Possible precedence problem on bitwise %s operator",
12468                            o->op_type ==  OP_BIT_OR
12469                          ||o->op_type == OP_NBIT_OR  ? "|"
12470                         :  o->op_type ==  OP_BIT_AND
12471                          ||o->op_type == OP_NBIT_AND ? "&"
12472                         :  o->op_type ==  OP_BIT_XOR
12473                          ||o->op_type == OP_NBIT_XOR ? "^"
12474                         :  o->op_type == OP_SBIT_OR  ? "|."
12475                         :  o->op_type == OP_SBIT_AND ? "&." : "^."
12476                            );
12477     }
12478     return o;
12479 }
12480
12481 PERL_STATIC_INLINE bool
12482 is_dollar_bracket(pTHX_ const OP * const o)
12483 {
12484     const OP *kid;
12485     PERL_UNUSED_CONTEXT;
12486     return o->op_type == OP_RV2SV && o->op_flags & OPf_KIDS
12487         && (kid = cUNOPx(o)->op_first)
12488         && kid->op_type == OP_GV
12489         && strEQ(GvNAME(cGVOPx_gv(kid)), "[");
12490 }
12491
12492 /* for lt, gt, le, ge, eq, ne and their i_ variants */
12493
12494 OP *
12495 Perl_ck_cmp(pTHX_ OP *o)
12496 {
12497     bool is_eq;
12498     bool neg;
12499     bool reverse;
12500     bool iv0;
12501     OP *indexop, *constop, *start;
12502     SV *sv;
12503     IV iv;
12504
12505     PERL_ARGS_ASSERT_CK_CMP;
12506
12507     is_eq = (   o->op_type == OP_EQ
12508              || o->op_type == OP_NE
12509              || o->op_type == OP_I_EQ
12510              || o->op_type == OP_I_NE);
12511
12512     if (!is_eq && ckWARN(WARN_SYNTAX)) {
12513         const OP *kid = cUNOPo->op_first;
12514         if (kid &&
12515             (
12516                 (   is_dollar_bracket(aTHX_ kid)
12517                  && OpSIBLING(kid) && OpSIBLING(kid)->op_type == OP_CONST
12518                 )
12519              || (   kid->op_type == OP_CONST
12520                  && (kid = OpSIBLING(kid)) && is_dollar_bracket(aTHX_ kid)
12521                 )
12522            )
12523         )
12524             Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
12525                         "$[ used in %s (did you mean $] ?)", OP_DESC(o));
12526     }
12527
12528     /* convert (index(...) == -1) and variations into
12529      *   (r)index/BOOL(,NEG)
12530      */
12531
12532     reverse = FALSE;
12533
12534     indexop = cUNOPo->op_first;
12535     constop = OpSIBLING(indexop);
12536     start = NULL;
12537     if (indexop->op_type == OP_CONST) {
12538         constop = indexop;
12539         indexop = OpSIBLING(constop);
12540         start = constop;
12541         reverse = TRUE;
12542     }
12543
12544     if (indexop->op_type != OP_INDEX && indexop->op_type != OP_RINDEX)
12545         return o;
12546
12547     /* ($lex = index(....)) == -1 */
12548     if (indexop->op_private & OPpTARGET_MY)
12549         return o;
12550
12551     if (constop->op_type != OP_CONST)
12552         return o;
12553
12554     sv = cSVOPx_sv(constop);
12555     if (!(sv && SvIOK_notUV(sv)))
12556         return o;
12557
12558     iv = SvIVX(sv);
12559     if (iv != -1 && iv != 0)
12560         return o;
12561     iv0 = (iv == 0);
12562
12563     if (o->op_type == OP_LT || o->op_type == OP_I_LT) {
12564         if (!(iv0 ^ reverse))
12565             return o;
12566         neg = iv0;
12567     }
12568     else if (o->op_type == OP_LE || o->op_type == OP_I_LE) {
12569         if (iv0 ^ reverse)
12570             return o;
12571         neg = !iv0;
12572     }
12573     else if (o->op_type == OP_GE || o->op_type == OP_I_GE) {
12574         if (!(iv0 ^ reverse))
12575             return o;
12576         neg = !iv0;
12577     }
12578     else if (o->op_type == OP_GT || o->op_type == OP_I_GT) {
12579         if (iv0 ^ reverse)
12580             return o;
12581         neg = iv0;
12582     }
12583     else if (o->op_type == OP_EQ || o->op_type == OP_I_EQ) {
12584         if (iv0)
12585             return o;
12586         neg = TRUE;
12587     }
12588     else {
12589         assert(o->op_type == OP_NE || o->op_type == OP_I_NE);
12590         if (iv0)
12591             return o;
12592         neg = FALSE;
12593     }
12594
12595     indexop->op_flags &= ~OPf_PARENS;
12596     indexop->op_flags |= (o->op_flags & OPf_PARENS);
12597     indexop->op_private |= OPpTRUEBOOL;
12598     if (neg)
12599         indexop->op_private |= OPpINDEX_BOOLNEG;
12600     /* cut out the index op and free the eq,const ops */
12601     (void)op_sibling_splice(o, start, 1, NULL);
12602     op_free(o);
12603
12604     return indexop;
12605 }
12606
12607
12608 OP *
12609 Perl_ck_concat(pTHX_ OP *o)
12610 {
12611     const OP * const kid = cUNOPo->op_first;
12612
12613     PERL_ARGS_ASSERT_CK_CONCAT;
12614     PERL_UNUSED_CONTEXT;
12615
12616     /* reuse the padtmp returned by the concat child */
12617     if (kid->op_type == OP_CONCAT && !(kid->op_private & OPpTARGET_MY) &&
12618             !(kUNOP->op_first->op_flags & OPf_MOD))
12619     {
12620         o->op_flags |= OPf_STACKED;
12621         o->op_private |= OPpCONCAT_NESTED;
12622     }
12623     return o;
12624 }
12625
12626 OP *
12627 Perl_ck_spair(pTHX_ OP *o)
12628 {
12629
12630     PERL_ARGS_ASSERT_CK_SPAIR;
12631
12632     if (o->op_flags & OPf_KIDS) {
12633         OP* newop;
12634         OP* kid;
12635         OP* kidkid;
12636         const OPCODE type = o->op_type;
12637         o = modkids(ck_fun(o), type);
12638         kid    = cUNOPo->op_first;
12639         kidkid = kUNOP->op_first;
12640         newop = OpSIBLING(kidkid);
12641         if (newop) {
12642             const OPCODE type = newop->op_type;
12643             if (OpHAS_SIBLING(newop))
12644                 return o;
12645             if (o->op_type == OP_REFGEN
12646              && (  type == OP_RV2CV
12647                 || (  !(newop->op_flags & OPf_PARENS)
12648                    && (  type == OP_RV2AV || type == OP_PADAV
12649                       || type == OP_RV2HV || type == OP_PADHV))))
12650                 NOOP; /* OK (allow srefgen for \@a and \%h) */
12651             else if (OP_GIMME(newop,0) != G_SCALAR)
12652                 return o;
12653         }
12654         /* excise first sibling */
12655         op_sibling_splice(kid, NULL, 1, NULL);
12656         op_free(kidkid);
12657     }
12658     /* transforms OP_REFGEN into OP_SREFGEN, OP_CHOP into OP_SCHOP,
12659      * and OP_CHOMP into OP_SCHOMP */
12660     o->op_ppaddr = PL_ppaddr[++o->op_type];
12661     return ck_fun(o);
12662 }
12663
12664 OP *
12665 Perl_ck_delete(pTHX_ OP *o)
12666 {
12667     PERL_ARGS_ASSERT_CK_DELETE;
12668
12669     o = ck_fun(o);
12670     o->op_private = 0;
12671     if (o->op_flags & OPf_KIDS) {
12672         OP * const kid = cUNOPo->op_first;
12673         switch (kid->op_type) {
12674         case OP_ASLICE:
12675             o->op_flags |= OPf_SPECIAL;
12676             /* FALLTHROUGH */
12677         case OP_HSLICE:
12678             o->op_private |= OPpSLICE;
12679             break;
12680         case OP_AELEM:
12681             o->op_flags |= OPf_SPECIAL;
12682             /* FALLTHROUGH */
12683         case OP_HELEM:
12684             break;
12685         case OP_KVASLICE:
12686             o->op_flags |= OPf_SPECIAL;
12687             /* FALLTHROUGH */
12688         case OP_KVHSLICE:
12689             o->op_private |= OPpKVSLICE;
12690             break;
12691         default:
12692             Perl_croak(aTHX_ "delete argument is not a HASH or ARRAY "
12693                              "element or slice");
12694         }
12695         if (kid->op_private & OPpLVAL_INTRO)
12696             o->op_private |= OPpLVAL_INTRO;
12697         op_null(kid);
12698     }
12699     return o;
12700 }
12701
12702 OP *
12703 Perl_ck_eof(pTHX_ OP *o)
12704 {
12705     PERL_ARGS_ASSERT_CK_EOF;
12706
12707     if (o->op_flags & OPf_KIDS) {
12708         OP *kid;
12709         if (cLISTOPo->op_first->op_type == OP_STUB) {
12710             OP * const newop
12711                 = newUNOP(o->op_type, OPf_SPECIAL, newGVOP(OP_GV, 0, PL_argvgv));
12712             op_free(o);
12713             o = newop;
12714         }
12715         o = ck_fun(o);
12716         kid = cLISTOPo->op_first;
12717         if (kid->op_type == OP_RV2GV)
12718             kid->op_private |= OPpALLOW_FAKE;
12719     }
12720     return o;
12721 }
12722
12723
12724 OP *
12725 Perl_ck_eval(pTHX_ OP *o)
12726 {
12727
12728     PERL_ARGS_ASSERT_CK_EVAL;
12729
12730     PL_hints |= HINT_BLOCK_SCOPE;
12731     if (o->op_flags & OPf_KIDS) {
12732         SVOP * const kid = (SVOP*)cUNOPo->op_first;
12733         assert(kid);
12734
12735         if (o->op_type == OP_ENTERTRY) {
12736             LOGOP *enter;
12737
12738             /* cut whole sibling chain free from o */
12739             op_sibling_splice(o, NULL, -1, NULL);
12740             op_free(o);
12741
12742             enter = alloc_LOGOP(OP_ENTERTRY, NULL, NULL);
12743
12744             /* establish postfix order */
12745             enter->op_next = (OP*)enter;
12746
12747             o = op_prepend_elem(OP_LINESEQ, (OP*)enter, (OP*)kid);
12748             OpTYPE_set(o, OP_LEAVETRY);
12749             enter->op_other = o;
12750             return o;
12751         }
12752         else {
12753             scalar((OP*)kid);
12754             S_set_haseval(aTHX);
12755         }
12756     }
12757     else {
12758         const U8 priv = o->op_private;
12759         op_free(o);
12760         /* the newUNOP will recursively call ck_eval(), which will handle
12761          * all the stuff at the end of this function, like adding
12762          * OP_HINTSEVAL
12763          */
12764         return newUNOP(OP_ENTEREVAL, priv <<8, newDEFSVOP());
12765     }
12766     o->op_targ = (PADOFFSET)PL_hints;
12767     if (o->op_private & OPpEVAL_BYTES) o->op_targ &= ~HINT_UTF8;
12768     if ((PL_hints & HINT_LOCALIZE_HH) != 0
12769      && !(o->op_private & OPpEVAL_COPHH) && GvHV(PL_hintgv)) {
12770         /* Store a copy of %^H that pp_entereval can pick up. */
12771         HV *hh = hv_copy_hints_hv(GvHV(PL_hintgv));
12772         OP *hhop;
12773         STOREFEATUREBITSHH(hh);
12774         hhop = newSVOP(OP_HINTSEVAL, 0, MUTABLE_SV(hh));
12775         /* append hhop to only child  */
12776         op_sibling_splice(o, cUNOPo->op_first, 0, hhop);
12777
12778         o->op_private |= OPpEVAL_HAS_HH;
12779     }
12780     if (!(o->op_private & OPpEVAL_BYTES)
12781          && FEATURE_UNIEVAL_IS_ENABLED)
12782             o->op_private |= OPpEVAL_UNICODE;
12783     return o;
12784 }
12785
12786 OP *
12787 Perl_ck_exec(pTHX_ OP *o)
12788 {
12789     PERL_ARGS_ASSERT_CK_EXEC;
12790
12791     if (o->op_flags & OPf_STACKED) {
12792         OP *kid;
12793         o = ck_fun(o);
12794         kid = OpSIBLING(cUNOPo->op_first);
12795         if (kid->op_type == OP_RV2GV)
12796             op_null(kid);
12797     }
12798     else
12799         o = listkids(o);
12800     return o;
12801 }
12802
12803 OP *
12804 Perl_ck_exists(pTHX_ OP *o)
12805 {
12806     PERL_ARGS_ASSERT_CK_EXISTS;
12807
12808     o = ck_fun(o);
12809     if (o->op_flags & OPf_KIDS) {
12810         OP * const kid = cUNOPo->op_first;
12811         if (kid->op_type == OP_ENTERSUB) {
12812             (void) ref(kid, o->op_type);
12813             if (kid->op_type != OP_RV2CV
12814                         && !(PL_parser && PL_parser->error_count))
12815                 Perl_croak(aTHX_
12816                           "exists argument is not a subroutine name");
12817             o->op_private |= OPpEXISTS_SUB;
12818         }
12819         else if (kid->op_type == OP_AELEM)
12820             o->op_flags |= OPf_SPECIAL;
12821         else if (kid->op_type != OP_HELEM)
12822             Perl_croak(aTHX_ "exists argument is not a HASH or ARRAY "
12823                              "element or a subroutine");
12824         op_null(kid);
12825     }
12826     return o;
12827 }
12828
12829 OP *
12830 Perl_ck_rvconst(pTHX_ OP *o)
12831 {
12832     SVOP * const kid = (SVOP*)cUNOPo->op_first;
12833
12834     PERL_ARGS_ASSERT_CK_RVCONST;
12835
12836     if (o->op_type == OP_RV2HV)
12837         /* rv2hv steals the bottom bit for its own uses */
12838         o->op_private &= ~OPpARG1_MASK;
12839
12840     o->op_private |= (PL_hints & HINT_STRICT_REFS);
12841
12842     if (kid->op_type == OP_CONST) {
12843         int iscv;
12844         GV *gv;
12845         SV * const kidsv = kid->op_sv;
12846
12847         /* Is it a constant from cv_const_sv()? */
12848         if ((SvROK(kidsv) || isGV_with_GP(kidsv)) && SvREADONLY(kidsv)) {
12849             return o;
12850         }
12851         if (SvTYPE(kidsv) == SVt_PVAV) return o;
12852         if ((o->op_private & HINT_STRICT_REFS) && (kid->op_private & OPpCONST_BARE)) {
12853             const char *badthing;
12854             switch (o->op_type) {
12855             case OP_RV2SV:
12856                 badthing = "a SCALAR";
12857                 break;
12858             case OP_RV2AV:
12859                 badthing = "an ARRAY";
12860                 break;
12861             case OP_RV2HV:
12862                 badthing = "a HASH";
12863                 break;
12864             default:
12865                 badthing = NULL;
12866                 break;
12867             }
12868             if (badthing)
12869                 Perl_croak(aTHX_
12870                            "Can't use bareword (\"%" SVf "\") as %s ref while \"strict refs\" in use",
12871                            SVfARG(kidsv), badthing);
12872         }
12873         /*
12874          * This is a little tricky.  We only want to add the symbol if we
12875          * didn't add it in the lexer.  Otherwise we get duplicate strict
12876          * warnings.  But if we didn't add it in the lexer, we must at
12877          * least pretend like we wanted to add it even if it existed before,
12878          * or we get possible typo warnings.  OPpCONST_ENTERED says
12879          * whether the lexer already added THIS instance of this symbol.
12880          */
12881         iscv = o->op_type == OP_RV2CV ? GV_NOEXPAND|GV_ADDMULTI : 0;
12882         gv = gv_fetchsv(kidsv,
12883                 o->op_type == OP_RV2CV
12884                         && o->op_private & OPpMAY_RETURN_CONSTANT
12885                     ? GV_NOEXPAND
12886                     : iscv | !(kid->op_private & OPpCONST_ENTERED),
12887                 iscv
12888                     ? SVt_PVCV
12889                     : o->op_type == OP_RV2SV
12890                         ? SVt_PV
12891                         : o->op_type == OP_RV2AV
12892                             ? SVt_PVAV
12893                             : o->op_type == OP_RV2HV
12894                                 ? SVt_PVHV
12895                                 : SVt_PVGV);
12896         if (gv) {
12897             if (!isGV(gv)) {
12898                 assert(iscv);
12899                 assert(SvROK(gv));
12900                 if (!(o->op_private & OPpMAY_RETURN_CONSTANT)
12901                   && SvTYPE(SvRV(gv)) != SVt_PVCV)
12902                     gv_fetchsv(kidsv, GV_ADDMULTI, SVt_PVCV);
12903             }
12904             OpTYPE_set(kid, OP_GV);
12905             SvREFCNT_dec(kid->op_sv);
12906 #ifdef USE_ITHREADS
12907             /* XXX hack: dependence on sizeof(PADOP) <= sizeof(SVOP) */
12908             STATIC_ASSERT_STMT(sizeof(PADOP) <= sizeof(SVOP));
12909             kPADOP->op_padix = pad_alloc(OP_GV, SVf_READONLY);
12910             SvREFCNT_dec(PAD_SVl(kPADOP->op_padix));
12911             PAD_SETSV(kPADOP->op_padix, MUTABLE_SV(SvREFCNT_inc_simple_NN(gv)));
12912 #else
12913             kid->op_sv = SvREFCNT_inc_simple_NN(gv);
12914 #endif
12915             kid->op_private = 0;
12916             /* FAKE globs in the symbol table cause weird bugs (#77810) */
12917             SvFAKE_off(gv);
12918         }
12919     }
12920     return o;
12921 }
12922
12923 OP *
12924 Perl_ck_ftst(pTHX_ OP *o)
12925 {
12926     const I32 type = o->op_type;
12927
12928     PERL_ARGS_ASSERT_CK_FTST;
12929
12930     if (o->op_flags & OPf_REF) {
12931         NOOP;
12932     }
12933     else if (o->op_flags & OPf_KIDS && cUNOPo->op_first->op_type != OP_STUB) {
12934         SVOP * const kid = (SVOP*)cUNOPo->op_first;
12935         const OPCODE kidtype = kid->op_type;
12936
12937         if (kidtype == OP_CONST && (kid->op_private & OPpCONST_BARE)
12938          && !kid->op_folded) {
12939             OP * const newop = newGVOP(type, OPf_REF,
12940                 gv_fetchsv(kid->op_sv, GV_ADD, SVt_PVIO));
12941             op_free(o);
12942             return newop;
12943         }
12944
12945         if ((kidtype == OP_RV2AV || kidtype == OP_PADAV) && ckWARN(WARN_SYNTAX)) {
12946             SV *name = S_op_varname_subscript(aTHX_ (OP*)kid, 2);
12947             if (name) {
12948                 /* diag_listed_as: Array passed to stat will be coerced to a scalar%s */
12949                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX), "%s (did you want stat %" SVf "?)",
12950                             array_passed_to_stat, name);
12951             }
12952             else {
12953                 /* diag_listed_as: Array passed to stat will be coerced to a scalar%s */
12954                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX), "%s", array_passed_to_stat);
12955             }
12956        }
12957         scalar((OP *) kid);
12958         if ((PL_hints & HINT_FILETEST_ACCESS) && OP_IS_FILETEST_ACCESS(o->op_type))
12959             o->op_private |= OPpFT_ACCESS;
12960         if (OP_IS_FILETEST(type)
12961             && OP_IS_FILETEST(kidtype)
12962         ) {
12963             o->op_private |= OPpFT_STACKED;
12964             kid->op_private |= OPpFT_STACKING;
12965             if (kidtype == OP_FTTTY && (
12966                    !(kid->op_private & OPpFT_STACKED)
12967                 || kid->op_private & OPpFT_AFTER_t
12968                ))
12969                 o->op_private |= OPpFT_AFTER_t;
12970         }
12971     }
12972     else {
12973         op_free(o);
12974         if (type == OP_FTTTY)
12975             o = newGVOP(type, OPf_REF, PL_stdingv);
12976         else
12977             o = newUNOP(type, 0, newDEFSVOP());
12978     }
12979     return o;
12980 }
12981
12982 OP *
12983 Perl_ck_fun(pTHX_ OP *o)
12984 {
12985     const int type = o->op_type;
12986     I32 oa = PL_opargs[type] >> OASHIFT;
12987
12988     PERL_ARGS_ASSERT_CK_FUN;
12989
12990     if (o->op_flags & OPf_STACKED) {
12991         if ((oa & OA_OPTIONAL) && (oa >> 4) && !((oa >> 4) & OA_OPTIONAL))
12992             oa &= ~OA_OPTIONAL;
12993         else
12994             return no_fh_allowed(o);
12995     }
12996
12997     if (o->op_flags & OPf_KIDS) {
12998         OP *prev_kid = NULL;
12999         OP *kid = cLISTOPo->op_first;
13000         I32 numargs = 0;
13001         bool seen_optional = FALSE;
13002
13003         if (kid->op_type == OP_PUSHMARK ||
13004             (kid->op_type == OP_NULL && kid->op_targ == OP_PUSHMARK))
13005         {
13006             prev_kid = kid;
13007             kid = OpSIBLING(kid);
13008         }
13009         if (kid && kid->op_type == OP_COREARGS) {
13010             bool optional = FALSE;
13011             while (oa) {
13012                 numargs++;
13013                 if (oa & OA_OPTIONAL) optional = TRUE;
13014                 oa = oa >> 4;
13015             }
13016             if (optional) o->op_private |= numargs;
13017             return o;
13018         }
13019
13020         while (oa) {
13021             if (oa & OA_OPTIONAL || (oa & 7) == OA_LIST) {
13022                 if (!kid && !seen_optional && PL_opargs[type] & OA_DEFGV) {
13023                     kid = newDEFSVOP();
13024                     /* append kid to chain */
13025                     op_sibling_splice(o, prev_kid, 0, kid);
13026                 }
13027                 seen_optional = TRUE;
13028             }
13029             if (!kid) break;
13030
13031             numargs++;
13032             switch (oa & 7) {
13033             case OA_SCALAR:
13034                 /* list seen where single (scalar) arg expected? */
13035                 if (numargs == 1 && !(oa >> 4)
13036                     && kid->op_type == OP_LIST && type != OP_SCALAR)
13037                 {
13038                     return too_many_arguments_pv(o,PL_op_desc[type], 0);
13039                 }
13040                 if (type != OP_DELETE) scalar(kid);
13041                 break;
13042             case OA_LIST:
13043                 if (oa < 16) {
13044                     kid = 0;
13045                     continue;
13046                 }
13047                 else
13048                     list(kid);
13049                 break;
13050             case OA_AVREF:
13051                 if ((type == OP_PUSH || type == OP_UNSHIFT)
13052                     && !OpHAS_SIBLING(kid))
13053                     Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX),
13054                                    "Useless use of %s with no values",
13055                                    PL_op_desc[type]);
13056
13057                 if (kid->op_type == OP_CONST
13058                       && (  !SvROK(cSVOPx_sv(kid))
13059                          || SvTYPE(SvRV(cSVOPx_sv(kid))) != SVt_PVAV  )
13060                         )
13061                     bad_type_pv(numargs, "array", o, kid);
13062                 else if (kid->op_type == OP_RV2HV || kid->op_type == OP_PADHV
13063                          || kid->op_type == OP_RV2GV) {
13064                     bad_type_pv(1, "array", o, kid);
13065                 }
13066                 else if (kid->op_type != OP_RV2AV && kid->op_type != OP_PADAV) {
13067                     yyerror_pv(Perl_form(aTHX_ "Experimental %s on scalar is now forbidden",
13068                                          PL_op_desc[type]), 0);
13069                 }
13070                 else {
13071                     op_lvalue(kid, type);
13072                 }
13073                 break;
13074             case OA_HVREF:
13075                 if (kid->op_type != OP_RV2HV && kid->op_type != OP_PADHV)
13076                     bad_type_pv(numargs, "hash", o, kid);
13077                 op_lvalue(kid, type);
13078                 break;
13079             case OA_CVREF:
13080                 {
13081                     /* replace kid with newop in chain */
13082                     OP * const newop =
13083                         S_op_sibling_newUNOP(aTHX_ o, prev_kid, OP_NULL, 0);
13084                     newop->op_next = newop;
13085                     kid = newop;
13086                 }
13087                 break;
13088             case OA_FILEREF:
13089                 if (kid->op_type != OP_GV && kid->op_type != OP_RV2GV) {
13090                     if (kid->op_type == OP_CONST &&
13091                         (kid->op_private & OPpCONST_BARE))
13092                     {
13093                         OP * const newop = newGVOP(OP_GV, 0,
13094                             gv_fetchsv(((SVOP*)kid)->op_sv, GV_ADD, SVt_PVIO));
13095                         /* replace kid with newop in chain */
13096                         op_sibling_splice(o, prev_kid, 1, newop);
13097                         op_free(kid);
13098                         kid = newop;
13099                     }
13100                     else if (kid->op_type == OP_READLINE) {
13101                         /* neophyte patrol: open(<FH>), close(<FH>) etc. */
13102                         bad_type_pv(numargs, "HANDLE", o, kid);
13103                     }
13104                     else {
13105                         I32 flags = OPf_SPECIAL;
13106                         I32 priv = 0;
13107                         PADOFFSET targ = 0;
13108
13109                         /* is this op a FH constructor? */
13110                         if (is_handle_constructor(o,numargs)) {
13111                             const char *name = NULL;
13112                             STRLEN len = 0;
13113                             U32 name_utf8 = 0;
13114                             bool want_dollar = TRUE;
13115
13116                             flags = 0;
13117                             /* Set a flag to tell rv2gv to vivify
13118                              * need to "prove" flag does not mean something
13119                              * else already - NI-S 1999/05/07
13120                              */
13121                             priv = OPpDEREF;
13122                             if (kid->op_type == OP_PADSV) {
13123                                 PADNAME * const pn
13124                                     = PAD_COMPNAME_SV(kid->op_targ);
13125                                 name = PadnamePV (pn);
13126                                 len  = PadnameLEN(pn);
13127                                 name_utf8 = PadnameUTF8(pn);
13128                             }
13129                             else if (kid->op_type == OP_RV2SV
13130                                      && kUNOP->op_first->op_type == OP_GV)
13131                             {
13132                                 GV * const gv = cGVOPx_gv(kUNOP->op_first);
13133                                 name = GvNAME(gv);
13134                                 len = GvNAMELEN(gv);
13135                                 name_utf8 = GvNAMEUTF8(gv) ? SVf_UTF8 : 0;
13136                             }
13137                             else if (kid->op_type == OP_AELEM
13138                                      || kid->op_type == OP_HELEM)
13139                             {
13140                                  OP *firstop;
13141                                  OP *op = ((BINOP*)kid)->op_first;
13142                                  name = NULL;
13143                                  if (op) {
13144                                       SV *tmpstr = NULL;
13145                                       const char * const a =
13146                                            kid->op_type == OP_AELEM ?
13147                                            "[]" : "{}";
13148                                       if (((op->op_type == OP_RV2AV) ||
13149                                            (op->op_type == OP_RV2HV)) &&
13150                                           (firstop = ((UNOP*)op)->op_first) &&
13151                                           (firstop->op_type == OP_GV)) {
13152                                            /* packagevar $a[] or $h{} */
13153                                            GV * const gv = cGVOPx_gv(firstop);
13154                                            if (gv)
13155                                                 tmpstr =
13156                                                      Perl_newSVpvf(aTHX_
13157                                                                    "%s%c...%c",
13158                                                                    GvNAME(gv),
13159                                                                    a[0], a[1]);
13160                                       }
13161                                       else if (op->op_type == OP_PADAV
13162                                                || op->op_type == OP_PADHV) {
13163                                            /* lexicalvar $a[] or $h{} */
13164                                            const char * const padname =
13165                                                 PAD_COMPNAME_PV(op->op_targ);
13166                                            if (padname)
13167                                                 tmpstr =
13168                                                      Perl_newSVpvf(aTHX_
13169                                                                    "%s%c...%c",
13170                                                                    padname + 1,
13171                                                                    a[0], a[1]);
13172                                       }
13173                                       if (tmpstr) {
13174                                            name = SvPV_const(tmpstr, len);
13175                                            name_utf8 = SvUTF8(tmpstr);
13176                                            sv_2mortal(tmpstr);
13177                                       }
13178                                  }
13179                                  if (!name) {
13180                                       name = "__ANONIO__";
13181                                       len = 10;
13182                                       want_dollar = FALSE;
13183                                  }
13184                                  op_lvalue(kid, type);
13185                             }
13186                             if (name) {
13187                                 SV *namesv;
13188                                 targ = pad_alloc(OP_RV2GV, SVf_READONLY);
13189                                 namesv = PAD_SVl(targ);
13190                                 if (want_dollar && *name != '$')
13191                                     sv_setpvs(namesv, "$");
13192                                 else
13193                                     SvPVCLEAR(namesv);
13194                                 sv_catpvn(namesv, name, len);
13195                                 if ( name_utf8 ) SvUTF8_on(namesv);
13196                             }
13197                         }
13198                         scalar(kid);
13199                         kid = S_op_sibling_newUNOP(aTHX_ o, prev_kid,
13200                                     OP_RV2GV, flags);
13201                         kid->op_targ = targ;
13202                         kid->op_private |= priv;
13203                     }
13204                 }
13205                 scalar(kid);
13206                 break;
13207             case OA_SCALARREF:
13208                 if ((type == OP_UNDEF || type == OP_POS)
13209                     && numargs == 1 && !(oa >> 4)
13210                     && kid->op_type == OP_LIST)
13211                     return too_many_arguments_pv(o,PL_op_desc[type], 0);
13212                 op_lvalue(scalar(kid), type);
13213                 break;
13214             }
13215             oa >>= 4;
13216             prev_kid = kid;
13217             kid = OpSIBLING(kid);
13218         }
13219         /* FIXME - should the numargs or-ing move after the too many
13220          * arguments check? */
13221         o->op_private |= numargs;
13222         if (kid)
13223             return too_many_arguments_pv(o,OP_DESC(o), 0);
13224         listkids(o);
13225     }
13226     else if (PL_opargs[type] & OA_DEFGV) {
13227         /* Ordering of these two is important to keep f_map.t passing.  */
13228         op_free(o);
13229         return newUNOP(type, 0, newDEFSVOP());
13230     }
13231
13232     if (oa) {
13233         while (oa & OA_OPTIONAL)
13234             oa >>= 4;
13235         if (oa && oa != OA_LIST)
13236             return too_few_arguments_pv(o,OP_DESC(o), 0);
13237     }
13238     return o;
13239 }
13240
13241 OP *
13242 Perl_ck_glob(pTHX_ OP *o)
13243 {
13244     GV *gv;
13245
13246     PERL_ARGS_ASSERT_CK_GLOB;
13247
13248     o = ck_fun(o);
13249     if ((o->op_flags & OPf_KIDS) && !OpHAS_SIBLING(cLISTOPo->op_first))
13250         op_append_elem(OP_GLOB, o, newDEFSVOP()); /* glob() => glob($_) */
13251
13252     if (!(o->op_flags & OPf_SPECIAL) && (gv = gv_override("glob", 4)))
13253     {
13254         /* convert
13255          *     glob
13256          *       \ null - const(wildcard)
13257          * into
13258          *     null
13259          *       \ enter
13260          *            \ list
13261          *                 \ mark - glob - rv2cv
13262          *                             |        \ gv(CORE::GLOBAL::glob)
13263          *                             |
13264          *                              \ null - const(wildcard)
13265          */
13266         o->op_flags |= OPf_SPECIAL;
13267         o->op_targ = pad_alloc(OP_GLOB, SVs_PADTMP);
13268         o = S_new_entersubop(aTHX_ gv, o);
13269         o = newUNOP(OP_NULL, 0, o);
13270         o->op_targ = OP_GLOB; /* hint at what it used to be: eg in newWHILEOP */
13271         return o;
13272     }
13273     else o->op_flags &= ~OPf_SPECIAL;
13274 #if !defined(PERL_EXTERNAL_GLOB)
13275     if (!PL_globhook) {
13276         ENTER;
13277         Perl_load_module(aTHX_ PERL_LOADMOD_NOIMPORT,
13278                                newSVpvs("File::Glob"), NULL, NULL, NULL);
13279         LEAVE;
13280     }
13281 #endif /* !PERL_EXTERNAL_GLOB */
13282     gv = (GV *)newSV(0);
13283     gv_init(gv, 0, "", 0, 0);
13284     gv_IOadd(gv);
13285     op_append_elem(OP_GLOB, o, newGVOP(OP_GV, 0, gv));
13286     SvREFCNT_dec_NN(gv); /* newGVOP increased it */
13287     scalarkids(o);
13288     return o;
13289 }
13290
13291 OP *
13292 Perl_ck_grep(pTHX_ OP *o)
13293 {
13294     LOGOP *gwop;
13295     OP *kid;
13296     const OPCODE type = o->op_type == OP_GREPSTART ? OP_GREPWHILE : OP_MAPWHILE;
13297
13298     PERL_ARGS_ASSERT_CK_GREP;
13299
13300     /* don't allocate gwop here, as we may leak it if PL_parser->error_count > 0 */
13301
13302     if (o->op_flags & OPf_STACKED) {
13303         kid = cUNOPx(OpSIBLING(cLISTOPo->op_first))->op_first;
13304         if (kid->op_type != OP_SCOPE && kid->op_type != OP_LEAVE)
13305             return no_fh_allowed(o);
13306         o->op_flags &= ~OPf_STACKED;
13307     }
13308     kid = OpSIBLING(cLISTOPo->op_first);
13309     if (type == OP_MAPWHILE)
13310         list(kid);
13311     else
13312         scalar(kid);
13313     o = ck_fun(o);
13314     if (PL_parser && PL_parser->error_count)
13315         return o;
13316     kid = OpSIBLING(cLISTOPo->op_first);
13317     if (kid->op_type != OP_NULL)
13318         Perl_croak(aTHX_ "panic: ck_grep, type=%u", (unsigned) kid->op_type);
13319     kid = kUNOP->op_first;
13320
13321     gwop = alloc_LOGOP(type, o, LINKLIST(kid));
13322     kid->op_next = (OP*)gwop;
13323     o->op_private = gwop->op_private = 0;
13324     gwop->op_targ = pad_alloc(type, SVs_PADTMP);
13325
13326     kid = OpSIBLING(cLISTOPo->op_first);
13327     for (kid = OpSIBLING(kid); kid; kid = OpSIBLING(kid))
13328         op_lvalue(kid, OP_GREPSTART);
13329
13330     return (OP*)gwop;
13331 }
13332
13333 OP *
13334 Perl_ck_index(pTHX_ OP *o)
13335 {
13336     PERL_ARGS_ASSERT_CK_INDEX;
13337
13338     if (o->op_flags & OPf_KIDS) {
13339         OP *kid = OpSIBLING(cLISTOPo->op_first);        /* get past pushmark */
13340         if (kid)
13341             kid = OpSIBLING(kid);                       /* get past "big" */
13342         if (kid && kid->op_type == OP_CONST) {
13343             const bool save_taint = TAINT_get;
13344             SV *sv = kSVOP->op_sv;
13345             if (   (!SvPOK(sv) || SvNIOKp(sv) || isREGEXP(sv))
13346                 && SvOK(sv) && !SvROK(sv))
13347             {
13348                 sv = newSV(0);
13349                 sv_copypv(sv, kSVOP->op_sv);
13350                 SvREFCNT_dec_NN(kSVOP->op_sv);
13351                 kSVOP->op_sv = sv;
13352             }
13353             if (SvOK(sv)) fbm_compile(sv, 0);
13354             TAINT_set(save_taint);
13355 #ifdef NO_TAINT_SUPPORT
13356             PERL_UNUSED_VAR(save_taint);
13357 #endif
13358         }
13359     }
13360     return ck_fun(o);
13361 }
13362
13363 OP *
13364 Perl_ck_lfun(pTHX_ OP *o)
13365 {
13366     const OPCODE type = o->op_type;
13367
13368     PERL_ARGS_ASSERT_CK_LFUN;
13369
13370     return modkids(ck_fun(o), type);
13371 }
13372
13373 OP *
13374 Perl_ck_defined(pTHX_ OP *o)            /* 19990527 MJD */
13375 {
13376     PERL_ARGS_ASSERT_CK_DEFINED;
13377
13378     if ((o->op_flags & OPf_KIDS)) {
13379         switch (cUNOPo->op_first->op_type) {
13380         case OP_RV2AV:
13381         case OP_PADAV:
13382             Perl_croak(aTHX_ "Can't use 'defined(@array)'"
13383                              " (Maybe you should just omit the defined()?)");
13384             NOT_REACHED; /* NOTREACHED */
13385             break;
13386         case OP_RV2HV:
13387         case OP_PADHV:
13388             Perl_croak(aTHX_ "Can't use 'defined(%%hash)'"
13389                              " (Maybe you should just omit the defined()?)");
13390             NOT_REACHED; /* NOTREACHED */
13391             break;
13392         default:
13393             /* no warning */
13394             break;
13395         }
13396     }
13397     return ck_rfun(o);
13398 }
13399
13400 OP *
13401 Perl_ck_readline(pTHX_ OP *o)
13402 {
13403     PERL_ARGS_ASSERT_CK_READLINE;
13404
13405     if (o->op_flags & OPf_KIDS) {
13406          OP *kid = cLISTOPo->op_first;
13407          if (kid->op_type == OP_RV2GV) kid->op_private |= OPpALLOW_FAKE;
13408          scalar(kid);
13409     }
13410     else {
13411         OP * const newop
13412             = newUNOP(OP_READLINE, 0, newGVOP(OP_GV, 0, PL_argvgv));
13413         op_free(o);
13414         return newop;
13415     }
13416     return o;
13417 }
13418
13419 OP *
13420 Perl_ck_rfun(pTHX_ OP *o)
13421 {
13422     const OPCODE type = o->op_type;
13423
13424     PERL_ARGS_ASSERT_CK_RFUN;
13425
13426     return refkids(ck_fun(o), type);
13427 }
13428
13429 OP *
13430 Perl_ck_listiob(pTHX_ OP *o)
13431 {
13432     OP *kid;
13433
13434     PERL_ARGS_ASSERT_CK_LISTIOB;
13435
13436     kid = cLISTOPo->op_first;
13437     if (!kid) {
13438         o = force_list(o, 1);
13439         kid = cLISTOPo->op_first;
13440     }
13441     if (kid->op_type == OP_PUSHMARK)
13442         kid = OpSIBLING(kid);
13443     if (kid && o->op_flags & OPf_STACKED)
13444         kid = OpSIBLING(kid);
13445     else if (kid && !OpHAS_SIBLING(kid)) {              /* print HANDLE; */
13446         if (kid->op_type == OP_CONST && kid->op_private & OPpCONST_BARE
13447          && !kid->op_folded) {
13448             o->op_flags |= OPf_STACKED; /* make it a filehandle */
13449             scalar(kid);
13450             /* replace old const op with new OP_RV2GV parent */
13451             kid = S_op_sibling_newUNOP(aTHX_ o, cLISTOPo->op_first,
13452                                         OP_RV2GV, OPf_REF);
13453             kid = OpSIBLING(kid);
13454         }
13455     }
13456
13457     if (!kid)
13458         op_append_elem(o->op_type, o, newDEFSVOP());
13459
13460     if (o->op_type == OP_PRTF) return modkids(listkids(o), OP_PRTF);
13461     return listkids(o);
13462 }
13463
13464 OP *
13465 Perl_ck_smartmatch(pTHX_ OP *o)
13466 {
13467     PERL_ARGS_ASSERT_CK_SMARTMATCH;
13468     if (0 == (o->op_flags & OPf_SPECIAL)) {
13469         OP *first  = cBINOPo->op_first;
13470         OP *second = OpSIBLING(first);
13471
13472         /* Implicitly take a reference to an array or hash */
13473
13474         /* remove the original two siblings, then add back the
13475          * (possibly different) first and second sibs.
13476          */
13477         op_sibling_splice(o, NULL, 1, NULL);
13478         op_sibling_splice(o, NULL, 1, NULL);
13479         first  = ref_array_or_hash(first);
13480         second = ref_array_or_hash(second);
13481         op_sibling_splice(o, NULL, 0, second);
13482         op_sibling_splice(o, NULL, 0, first);
13483
13484         /* Implicitly take a reference to a regular expression */
13485         if (first->op_type == OP_MATCH && !(first->op_flags & OPf_STACKED)) {
13486             OpTYPE_set(first, OP_QR);
13487         }
13488         if (second->op_type == OP_MATCH && !(second->op_flags & OPf_STACKED)) {
13489             OpTYPE_set(second, OP_QR);
13490         }
13491     }
13492
13493     return o;
13494 }
13495
13496
13497 static OP *
13498 S_maybe_targlex(pTHX_ OP *o)
13499 {
13500     OP * const kid = cLISTOPo->op_first;
13501     /* has a disposable target? */
13502     if ((PL_opargs[kid->op_type] & OA_TARGLEX)
13503         && !(kid->op_flags & OPf_STACKED)
13504         /* Cannot steal the second time! */
13505         && !(kid->op_private & OPpTARGET_MY)
13506         )
13507     {
13508         OP * const kkid = OpSIBLING(kid);
13509
13510         /* Can just relocate the target. */
13511         if (kkid && kkid->op_type == OP_PADSV
13512             && (!(kkid->op_private & OPpLVAL_INTRO)
13513                || kkid->op_private & OPpPAD_STATE))
13514         {
13515             kid->op_targ = kkid->op_targ;
13516             kkid->op_targ = 0;
13517             /* Now we do not need PADSV and SASSIGN.
13518              * Detach kid and free the rest. */
13519             op_sibling_splice(o, NULL, 1, NULL);
13520             op_free(o);
13521             kid->op_private |= OPpTARGET_MY;    /* Used for context settings */
13522             return kid;
13523         }
13524     }
13525     return o;
13526 }
13527
13528 OP *
13529 Perl_ck_sassign(pTHX_ OP *o)
13530 {
13531     OP * const kid = cBINOPo->op_first;
13532
13533     PERL_ARGS_ASSERT_CK_SASSIGN;
13534
13535     if (OpHAS_SIBLING(kid)) {
13536         OP *kkid = OpSIBLING(kid);
13537         /* For state variable assignment with attributes, kkid is a list op
13538            whose op_last is a padsv. */
13539         if ((kkid->op_type == OP_PADSV ||
13540              (OP_TYPE_IS_OR_WAS(kkid, OP_LIST) &&
13541               (kkid = cLISTOPx(kkid)->op_last)->op_type == OP_PADSV
13542              )
13543             )
13544                 && (kkid->op_private & (OPpLVAL_INTRO|OPpPAD_STATE))
13545                     == (OPpLVAL_INTRO|OPpPAD_STATE)) {
13546             return S_newONCEOP(aTHX_ o, kkid);
13547         }
13548     }
13549     return S_maybe_targlex(aTHX_ o);
13550 }
13551
13552
13553 OP *
13554 Perl_ck_match(pTHX_ OP *o)
13555 {
13556     PERL_UNUSED_CONTEXT;
13557     PERL_ARGS_ASSERT_CK_MATCH;
13558
13559     return o;
13560 }
13561
13562 OP *
13563 Perl_ck_method(pTHX_ OP *o)
13564 {
13565     SV *sv, *methsv, *rclass;
13566     const char* method;
13567     char* compatptr;
13568     int utf8;
13569     STRLEN len, nsplit = 0, i;
13570     OP* new_op;
13571     OP * const kid = cUNOPo->op_first;
13572
13573     PERL_ARGS_ASSERT_CK_METHOD;
13574     if (kid->op_type != OP_CONST) return o;
13575
13576     sv = kSVOP->op_sv;
13577
13578     /* replace ' with :: */
13579     while ((compatptr = (char *) memchr(SvPVX(sv), '\'',
13580                                         SvEND(sv) - SvPVX(sv) )))
13581     {
13582         *compatptr = ':';
13583         sv_insert(sv, compatptr - SvPVX_const(sv), 0, ":", 1);
13584     }
13585
13586     method = SvPVX_const(sv);
13587     len = SvCUR(sv);
13588     utf8 = SvUTF8(sv) ? -1 : 1;
13589
13590     for (i = len - 1; i > 0; --i) if (method[i] == ':') {
13591         nsplit = i+1;
13592         break;
13593     }
13594
13595     methsv = newSVpvn_share(method+nsplit, utf8*(len - nsplit), 0);
13596
13597     if (!nsplit) { /* $proto->method() */
13598         op_free(o);
13599         return newMETHOP_named(OP_METHOD_NAMED, 0, methsv);
13600     }
13601
13602     if (memEQs(method, nsplit, "SUPER::")) { /* $proto->SUPER::method() */
13603         op_free(o);
13604         return newMETHOP_named(OP_METHOD_SUPER, 0, methsv);
13605     }
13606
13607     /* $proto->MyClass::method() and $proto->MyClass::SUPER::method() */
13608     if (nsplit >= 9 && strBEGINs(method+nsplit-9, "::SUPER::")) {
13609         rclass = newSVpvn_share(method, utf8*(nsplit-9), 0);
13610         new_op = newMETHOP_named(OP_METHOD_REDIR_SUPER, 0, methsv);
13611     } else {
13612         rclass = newSVpvn_share(method, utf8*(nsplit-2), 0);
13613         new_op = newMETHOP_named(OP_METHOD_REDIR, 0, methsv);
13614     }
13615 #ifdef USE_ITHREADS
13616     op_relocate_sv(&rclass, &cMETHOPx(new_op)->op_rclass_targ);
13617 #else
13618     cMETHOPx(new_op)->op_rclass_sv = rclass;
13619 #endif
13620     op_free(o);
13621     return new_op;
13622 }
13623
13624 OP *
13625 Perl_ck_null(pTHX_ OP *o)
13626 {
13627     PERL_ARGS_ASSERT_CK_NULL;
13628     PERL_UNUSED_CONTEXT;
13629     return o;
13630 }
13631
13632 OP *
13633 Perl_ck_open(pTHX_ OP *o)
13634 {
13635     PERL_ARGS_ASSERT_CK_OPEN;
13636
13637     S_io_hints(aTHX_ o);
13638     {
13639          /* In case of three-arg dup open remove strictness
13640           * from the last arg if it is a bareword. */
13641          OP * const first = cLISTOPx(o)->op_first; /* The pushmark. */
13642          OP * const last  = cLISTOPx(o)->op_last;  /* The bareword. */
13643          OP *oa;
13644          const char *mode;
13645
13646          if ((last->op_type == OP_CONST) &&             /* The bareword. */
13647              (last->op_private & OPpCONST_BARE) &&
13648              (last->op_private & OPpCONST_STRICT) &&
13649              (oa = OpSIBLING(first)) &&         /* The fh. */
13650              (oa = OpSIBLING(oa)) &&                    /* The mode. */
13651              (oa->op_type == OP_CONST) &&
13652              SvPOK(((SVOP*)oa)->op_sv) &&
13653              (mode = SvPVX_const(((SVOP*)oa)->op_sv)) &&
13654              mode[0] == '>' && mode[1] == '&' &&        /* A dup open. */
13655              (last == OpSIBLING(oa)))                   /* The bareword. */
13656               last->op_private &= ~OPpCONST_STRICT;
13657     }
13658     return ck_fun(o);
13659 }
13660
13661 OP *
13662 Perl_ck_prototype(pTHX_ OP *o)
13663 {
13664     PERL_ARGS_ASSERT_CK_PROTOTYPE;
13665     if (!(o->op_flags & OPf_KIDS)) {
13666         op_free(o);
13667         return newUNOP(OP_PROTOTYPE, 0, newDEFSVOP());
13668     }
13669     return o;
13670 }
13671
13672 OP *
13673 Perl_ck_refassign(pTHX_ OP *o)
13674 {
13675     OP * const right = cLISTOPo->op_first;
13676     OP * const left = OpSIBLING(right);
13677     OP *varop = cUNOPx(cUNOPx(left)->op_first)->op_first;
13678     bool stacked = 0;
13679
13680     PERL_ARGS_ASSERT_CK_REFASSIGN;
13681     assert (left);
13682     assert (left->op_type == OP_SREFGEN);
13683
13684     o->op_private = 0;
13685     /* we use OPpPAD_STATE in refassign to mean either of those things,
13686      * and the code assumes the two flags occupy the same bit position
13687      * in the various ops below */
13688     assert(OPpPAD_STATE == OPpOUR_INTRO);
13689
13690     switch (varop->op_type) {
13691     case OP_PADAV:
13692         o->op_private |= OPpLVREF_AV;
13693         goto settarg;
13694     case OP_PADHV:
13695         o->op_private |= OPpLVREF_HV;
13696         /* FALLTHROUGH */
13697     case OP_PADSV:
13698       settarg:
13699         o->op_private |= (varop->op_private & (OPpLVAL_INTRO|OPpPAD_STATE));
13700         o->op_targ = varop->op_targ;
13701         varop->op_targ = 0;
13702         PAD_COMPNAME_GEN_set(o->op_targ, PERL_INT_MAX);
13703         break;
13704
13705     case OP_RV2AV:
13706         o->op_private |= OPpLVREF_AV;
13707         goto checkgv;
13708         NOT_REACHED; /* NOTREACHED */
13709     case OP_RV2HV:
13710         o->op_private |= OPpLVREF_HV;
13711         /* FALLTHROUGH */
13712     case OP_RV2SV:
13713       checkgv:
13714         o->op_private |= (varop->op_private & (OPpLVAL_INTRO|OPpOUR_INTRO));
13715         if (cUNOPx(varop)->op_first->op_type != OP_GV) goto bad;
13716       detach_and_stack:
13717         /* Point varop to its GV kid, detached.  */
13718         varop = op_sibling_splice(varop, NULL, -1, NULL);
13719         stacked = TRUE;
13720         break;
13721     case OP_RV2CV: {
13722         OP * const kidparent =
13723             OpSIBLING(cUNOPx(cUNOPx(varop)->op_first)->op_first);
13724         OP * const kid = cUNOPx(kidparent)->op_first;
13725         o->op_private |= OPpLVREF_CV;
13726         if (kid->op_type == OP_GV) {
13727             SV *sv = (SV*)cGVOPx_gv(kid);
13728             varop = kidparent;
13729             if (SvROK(sv) && SvTYPE(SvRV(sv)) == SVt_PVCV) {
13730                 /* a CVREF here confuses pp_refassign, so make sure
13731                    it gets a GV */
13732                 CV *const cv = (CV*)SvRV(sv);
13733                 SV *name_sv = sv_2mortal(newSVhek(CvNAME_HEK(cv)));
13734                 (void)gv_init_sv((GV*)sv, CvSTASH(cv), name_sv, 0);
13735                 assert(SvTYPE(sv) == SVt_PVGV);
13736             }
13737             goto detach_and_stack;
13738         }
13739         if (kid->op_type != OP_PADCV)   goto bad;
13740         o->op_targ = kid->op_targ;
13741         kid->op_targ = 0;
13742         break;
13743     }
13744     case OP_AELEM:
13745     case OP_HELEM:
13746         o->op_private |= (varop->op_private & OPpLVAL_INTRO);
13747         o->op_private |= OPpLVREF_ELEM;
13748         op_null(varop);
13749         stacked = TRUE;
13750         /* Detach varop.  */
13751         op_sibling_splice(cUNOPx(left)->op_first, NULL, -1, NULL);
13752         break;
13753     default:
13754       bad:
13755         /* diag_listed_as: Can't modify reference to %s in %s assignment */
13756         yyerror(Perl_form(aTHX_ "Can't modify reference to %s in scalar "
13757                                 "assignment",
13758                                  OP_DESC(varop)));
13759         return o;
13760     }
13761     if (!FEATURE_REFALIASING_IS_ENABLED)
13762         Perl_croak(aTHX_
13763                   "Experimental aliasing via reference not enabled");
13764     Perl_ck_warner_d(aTHX_
13765                      packWARN(WARN_EXPERIMENTAL__REFALIASING),
13766                     "Aliasing via reference is experimental");
13767     if (stacked) {
13768         o->op_flags |= OPf_STACKED;
13769         op_sibling_splice(o, right, 1, varop);
13770     }
13771     else {
13772         o->op_flags &=~ OPf_STACKED;
13773         op_sibling_splice(o, right, 1, NULL);
13774     }
13775     op_free(left);
13776     return o;
13777 }
13778
13779 OP *
13780 Perl_ck_repeat(pTHX_ OP *o)
13781 {
13782     PERL_ARGS_ASSERT_CK_REPEAT;
13783
13784     if (cBINOPo->op_first->op_flags & OPf_PARENS) {
13785         OP* kids;
13786         o->op_private |= OPpREPEAT_DOLIST;
13787         kids = op_sibling_splice(o, NULL, 1, NULL); /* detach first kid */
13788         kids = force_list(kids, 1); /* promote it to a list */
13789         op_sibling_splice(o, NULL, 0, kids); /* and add back */
13790     }
13791     else
13792         scalar(o);
13793     return o;
13794 }
13795
13796 OP *
13797 Perl_ck_require(pTHX_ OP *o)
13798 {
13799     GV* gv;
13800
13801     PERL_ARGS_ASSERT_CK_REQUIRE;
13802
13803     if (o->op_flags & OPf_KIDS) {       /* Shall we supply missing .pm? */
13804         SVOP * const kid = (SVOP*)cUNOPo->op_first;
13805         U32 hash;
13806         char *s;
13807         STRLEN len;
13808         if (kid->op_type == OP_CONST) {
13809           SV * const sv = kid->op_sv;
13810           U32 const was_readonly = SvREADONLY(sv);
13811           if (kid->op_private & OPpCONST_BARE) {
13812             const char *end;
13813             HEK *hek;
13814
13815             if (was_readonly) {
13816                 SvREADONLY_off(sv);
13817             }
13818
13819             if (SvIsCOW(sv)) sv_force_normal_flags(sv, 0);
13820
13821             s = SvPVX(sv);
13822             len = SvCUR(sv);
13823             end = s + len;
13824             /* treat ::foo::bar as foo::bar */
13825             if (len >= 2 && s[0] == ':' && s[1] == ':')
13826                 DIE(aTHX_ "Bareword in require must not start with a double-colon: \"%s\"\n", s);
13827             if (s == end)
13828                 DIE(aTHX_ "Bareword in require maps to empty filename");
13829
13830             for (; s < end; s++) {
13831                 if (*s == ':' && s[1] == ':') {
13832                     *s = '/';
13833                     Move(s+2, s+1, end - s - 1, char);
13834                     --end;
13835                 }
13836             }
13837             SvEND_set(sv, end);
13838             sv_catpvs(sv, ".pm");
13839             PERL_HASH(hash, SvPVX(sv), SvCUR(sv));
13840             hek = share_hek(SvPVX(sv),
13841                             (SSize_t)SvCUR(sv) * (SvUTF8(sv) ? -1 : 1),
13842                             hash);
13843             sv_sethek(sv, hek);
13844             unshare_hek(hek);
13845             SvFLAGS(sv) |= was_readonly;
13846           }
13847           else if (SvPOK(sv) && !SvNIOK(sv) && !SvGMAGICAL(sv)
13848                 && !SvVOK(sv)) {
13849             s = SvPV(sv, len);
13850             if (SvREFCNT(sv) > 1) {
13851                 kid->op_sv = newSVpvn_share(
13852                     s, SvUTF8(sv) ? -(SSize_t)len : (SSize_t)len, 0);
13853                 SvREFCNT_dec_NN(sv);
13854             }
13855             else {
13856                 HEK *hek;
13857                 if (was_readonly) SvREADONLY_off(sv);
13858                 PERL_HASH(hash, s, len);
13859                 hek = share_hek(s,
13860                                 SvUTF8(sv) ? -(SSize_t)len : (SSize_t)len,
13861                                 hash);
13862                 sv_sethek(sv, hek);
13863                 unshare_hek(hek);
13864                 SvFLAGS(sv) |= was_readonly;
13865             }
13866           }
13867         }
13868     }
13869
13870     if (!(o->op_flags & OPf_SPECIAL) /* Wasn't written as CORE::require */
13871         /* handle override, if any */
13872      && (gv = gv_override("require", 7))) {
13873         OP *kid, *newop;
13874         if (o->op_flags & OPf_KIDS) {
13875             kid = cUNOPo->op_first;
13876             op_sibling_splice(o, NULL, -1, NULL);
13877         }
13878         else {
13879             kid = newDEFSVOP();
13880         }
13881         op_free(o);
13882         newop = S_new_entersubop(aTHX_ gv, kid);
13883         return newop;
13884     }
13885
13886     return ck_fun(o);
13887 }
13888
13889 OP *
13890 Perl_ck_return(pTHX_ OP *o)
13891 {
13892     OP *kid;
13893
13894     PERL_ARGS_ASSERT_CK_RETURN;
13895
13896     kid = OpSIBLING(cLISTOPo->op_first);
13897     if (PL_compcv && CvLVALUE(PL_compcv)) {
13898         for (; kid; kid = OpSIBLING(kid))
13899             op_lvalue(kid, OP_LEAVESUBLV);
13900     }
13901
13902     return o;
13903 }
13904
13905 OP *
13906 Perl_ck_select(pTHX_ OP *o)
13907 {
13908     OP* kid;
13909
13910     PERL_ARGS_ASSERT_CK_SELECT;
13911
13912     if (o->op_flags & OPf_KIDS) {
13913         kid = OpSIBLING(cLISTOPo->op_first);     /* get past pushmark */
13914         if (kid && OpHAS_SIBLING(kid)) {
13915             OpTYPE_set(o, OP_SSELECT);
13916             o = ck_fun(o);
13917             return fold_constants(op_integerize(op_std_init(o)));
13918         }
13919     }
13920     o = ck_fun(o);
13921     kid = OpSIBLING(cLISTOPo->op_first);    /* get past pushmark */
13922     if (kid && kid->op_type == OP_RV2GV)
13923         kid->op_private &= ~HINT_STRICT_REFS;
13924     return o;
13925 }
13926
13927 OP *
13928 Perl_ck_shift(pTHX_ OP *o)
13929 {
13930     const I32 type = o->op_type;
13931
13932     PERL_ARGS_ASSERT_CK_SHIFT;
13933
13934     if (!(o->op_flags & OPf_KIDS)) {
13935         OP *argop;
13936
13937         if (!CvUNIQUE(PL_compcv)) {
13938             o->op_flags |= OPf_SPECIAL;
13939             return o;
13940         }
13941
13942         argop = newUNOP(OP_RV2AV, 0, scalar(newGVOP(OP_GV, 0, PL_argvgv)));
13943         op_free(o);
13944         return newUNOP(type, 0, scalar(argop));
13945     }
13946     return scalar(ck_fun(o));
13947 }
13948
13949 OP *
13950 Perl_ck_sort(pTHX_ OP *o)
13951 {
13952     OP *firstkid;
13953     OP *kid;
13954     HV * const hinthv =
13955         PL_hints & HINT_LOCALIZE_HH ? GvHV(PL_hintgv) : NULL;
13956     U8 stacked;
13957
13958     PERL_ARGS_ASSERT_CK_SORT;
13959
13960     if (hinthv) {
13961             SV ** const svp = hv_fetchs(hinthv, "sort", FALSE);
13962             if (svp) {
13963                 const I32 sorthints = (I32)SvIV(*svp);
13964                 if ((sorthints & HINT_SORT_STABLE) != 0)
13965                     o->op_private |= OPpSORT_STABLE;
13966                 if ((sorthints & HINT_SORT_UNSTABLE) != 0)
13967                     o->op_private |= OPpSORT_UNSTABLE;
13968             }
13969     }
13970
13971     if (o->op_flags & OPf_STACKED)
13972         simplify_sort(o);
13973     firstkid = OpSIBLING(cLISTOPo->op_first);           /* get past pushmark */
13974
13975     if ((stacked = o->op_flags & OPf_STACKED)) {        /* may have been cleared */
13976         OP *kid = cUNOPx(firstkid)->op_first;           /* get past null */
13977
13978         /* if the first arg is a code block, process it and mark sort as
13979          * OPf_SPECIAL */
13980         if (kid->op_type == OP_SCOPE || kid->op_type == OP_LEAVE) {
13981             LINKLIST(kid);
13982             if (kid->op_type == OP_LEAVE)
13983                     op_null(kid);                       /* wipe out leave */
13984             /* Prevent execution from escaping out of the sort block. */
13985             kid->op_next = 0;
13986
13987             /* provide scalar context for comparison function/block */
13988             kid = scalar(firstkid);
13989             kid->op_next = kid;
13990             o->op_flags |= OPf_SPECIAL;
13991         }
13992         else if (kid->op_type == OP_CONST
13993               && kid->op_private & OPpCONST_BARE) {
13994             char tmpbuf[256];
13995             STRLEN len;
13996             PADOFFSET off;
13997             const char * const name = SvPV(kSVOP_sv, len);
13998             *tmpbuf = '&';
13999             assert (len < 256);
14000             Copy(name, tmpbuf+1, len, char);
14001             off = pad_findmy_pvn(tmpbuf, len+1, 0);
14002             if (off != NOT_IN_PAD) {
14003                 if (PAD_COMPNAME_FLAGS_isOUR(off)) {
14004                     SV * const fq =
14005                         newSVhek(HvNAME_HEK(PAD_COMPNAME_OURSTASH(off)));
14006                     sv_catpvs(fq, "::");
14007                     sv_catsv(fq, kSVOP_sv);
14008                     SvREFCNT_dec_NN(kSVOP_sv);
14009                     kSVOP->op_sv = fq;
14010                 }
14011                 else {
14012                     OP * const padop = newOP(OP_PADCV, 0);
14013                     padop->op_targ = off;
14014                     /* replace the const op with the pad op */
14015                     op_sibling_splice(firstkid, NULL, 1, padop);
14016                     op_free(kid);
14017                 }
14018             }
14019         }
14020
14021         firstkid = OpSIBLING(firstkid);
14022     }
14023
14024     for (kid = firstkid; kid; kid = OpSIBLING(kid)) {
14025         /* provide list context for arguments */
14026         list(kid);
14027         if (stacked)
14028             op_lvalue(kid, OP_GREPSTART);
14029     }
14030
14031     return o;
14032 }
14033
14034 /* for sort { X } ..., where X is one of
14035  *   $a <=> $b, $b <=> $a, $a cmp $b, $b cmp $a
14036  * elide the second child of the sort (the one containing X),
14037  * and set these flags as appropriate
14038         OPpSORT_NUMERIC;
14039         OPpSORT_INTEGER;
14040         OPpSORT_DESCEND;
14041  * Also, check and warn on lexical $a, $b.
14042  */
14043
14044 STATIC void
14045 S_simplify_sort(pTHX_ OP *o)
14046 {
14047     OP *kid = OpSIBLING(cLISTOPo->op_first);    /* get past pushmark */
14048     OP *k;
14049     int descending;
14050     GV *gv;
14051     const char *gvname;
14052     bool have_scopeop;
14053
14054     PERL_ARGS_ASSERT_SIMPLIFY_SORT;
14055
14056     kid = kUNOP->op_first;                              /* get past null */
14057     if (!(have_scopeop = kid->op_type == OP_SCOPE)
14058      && kid->op_type != OP_LEAVE)
14059         return;
14060     kid = kLISTOP->op_last;                             /* get past scope */
14061     switch(kid->op_type) {
14062         case OP_NCMP:
14063         case OP_I_NCMP:
14064         case OP_SCMP:
14065             if (!have_scopeop) goto padkids;
14066             break;
14067         default:
14068             return;
14069     }
14070     k = kid;                                            /* remember this node*/
14071     if (kBINOP->op_first->op_type != OP_RV2SV
14072      || kBINOP->op_last ->op_type != OP_RV2SV)
14073     {
14074         /*
14075            Warn about my($a) or my($b) in a sort block, *if* $a or $b is
14076            then used in a comparison.  This catches most, but not
14077            all cases.  For instance, it catches
14078                sort { my($a); $a <=> $b }
14079            but not
14080                sort { my($a); $a < $b ? -1 : $a == $b ? 0 : 1; }
14081            (although why you'd do that is anyone's guess).
14082         */
14083
14084        padkids:
14085         if (!ckWARN(WARN_SYNTAX)) return;
14086         kid = kBINOP->op_first;
14087         do {
14088             if (kid->op_type == OP_PADSV) {
14089                 PADNAME * const name = PAD_COMPNAME(kid->op_targ);
14090                 if (PadnameLEN(name) == 2 && *PadnamePV(name) == '$'
14091                  && (  PadnamePV(name)[1] == 'a'
14092                     || PadnamePV(name)[1] == 'b'  ))
14093                     /* diag_listed_as: "my %s" used in sort comparison */
14094                     Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
14095                                      "\"%s %s\" used in sort comparison",
14096                                       PadnameIsSTATE(name)
14097                                         ? "state"
14098                                         : "my",
14099                                       PadnamePV(name));
14100             }
14101         } while ((kid = OpSIBLING(kid)));
14102         return;
14103     }
14104     kid = kBINOP->op_first;                             /* get past cmp */
14105     if (kUNOP->op_first->op_type != OP_GV)
14106         return;
14107     kid = kUNOP->op_first;                              /* get past rv2sv */
14108     gv = kGVOP_gv;
14109     if (GvSTASH(gv) != PL_curstash)
14110         return;
14111     gvname = GvNAME(gv);
14112     if (*gvname == 'a' && gvname[1] == '\0')
14113         descending = 0;
14114     else if (*gvname == 'b' && gvname[1] == '\0')
14115         descending = 1;
14116     else
14117         return;
14118
14119     kid = k;                                            /* back to cmp */
14120     /* already checked above that it is rv2sv */
14121     kid = kBINOP->op_last;                              /* down to 2nd arg */
14122     if (kUNOP->op_first->op_type != OP_GV)
14123         return;
14124     kid = kUNOP->op_first;                              /* get past rv2sv */
14125     gv = kGVOP_gv;
14126     if (GvSTASH(gv) != PL_curstash)
14127         return;
14128     gvname = GvNAME(gv);
14129     if ( descending
14130          ? !(*gvname == 'a' && gvname[1] == '\0')
14131          : !(*gvname == 'b' && gvname[1] == '\0'))
14132         return;
14133     o->op_flags &= ~(OPf_STACKED | OPf_SPECIAL);
14134     if (descending)
14135         o->op_private |= OPpSORT_DESCEND;
14136     if (k->op_type == OP_NCMP)
14137         o->op_private |= OPpSORT_NUMERIC;
14138     if (k->op_type == OP_I_NCMP)
14139         o->op_private |= OPpSORT_NUMERIC | OPpSORT_INTEGER;
14140     kid = OpSIBLING(cLISTOPo->op_first);
14141     /* cut out and delete old block (second sibling) */
14142     op_sibling_splice(o, cLISTOPo->op_first, 1, NULL);
14143     op_free(kid);
14144 }
14145
14146 OP *
14147 Perl_ck_split(pTHX_ OP *o)
14148 {
14149     OP *kid;
14150     OP *sibs;
14151
14152     PERL_ARGS_ASSERT_CK_SPLIT;
14153
14154     assert(o->op_type == OP_LIST);
14155
14156     if (o->op_flags & OPf_STACKED)
14157         return no_fh_allowed(o);
14158
14159     kid = cLISTOPo->op_first;
14160     /* delete leading NULL node, then add a CONST if no other nodes */
14161     assert(kid->op_type == OP_NULL);
14162     op_sibling_splice(o, NULL, 1,
14163         OpHAS_SIBLING(kid) ? NULL : newSVOP(OP_CONST, 0, newSVpvs(" ")));
14164     op_free(kid);
14165     kid = cLISTOPo->op_first;
14166
14167     if (kid->op_type != OP_MATCH || kid->op_flags & OPf_STACKED) {
14168         /* remove match expression, and replace with new optree with
14169          * a match op at its head */
14170         op_sibling_splice(o, NULL, 1, NULL);
14171         /* pmruntime will handle split " " behavior with flag==2 */
14172         kid = pmruntime(newPMOP(OP_MATCH, 0), kid, NULL, 2, 0);
14173         op_sibling_splice(o, NULL, 0, kid);
14174     }
14175
14176     assert(kid->op_type == OP_MATCH || kid->op_type == OP_SPLIT);
14177
14178     if (((PMOP *)kid)->op_pmflags & PMf_GLOBAL) {
14179       Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP),
14180                      "Use of /g modifier is meaningless in split");
14181     }
14182
14183     /* eliminate the split op, and move the match op (plus any children)
14184      * into its place, then convert the match op into a split op. i.e.
14185      *
14186      *  SPLIT                    MATCH                 SPLIT(ex-MATCH)
14187      *    |                        |                     |
14188      *  MATCH - A - B - C   =>     R - A - B - C   =>    R - A - B - C
14189      *    |                        |                     |
14190      *    R                        X - Y                 X - Y
14191      *    |
14192      *    X - Y
14193      *
14194      * (R, if it exists, will be a regcomp op)
14195      */
14196
14197     op_sibling_splice(o, NULL, 1, NULL); /* detach match op from o */
14198     sibs = op_sibling_splice(o, NULL, -1, NULL); /* detach any other sibs */
14199     op_sibling_splice(kid, cLISTOPx(kid)->op_last, 0, sibs); /* and reattach */
14200     OpTYPE_set(kid, OP_SPLIT);
14201     kid->op_flags   = (o->op_flags | (kid->op_flags & OPf_KIDS));
14202     kid->op_private = o->op_private;
14203     op_free(o);
14204     o = kid;
14205     kid = sibs; /* kid is now the string arg of the split */
14206
14207     if (!kid) {
14208         kid = newDEFSVOP();
14209         op_append_elem(OP_SPLIT, o, kid);
14210     }
14211     scalar(kid);
14212
14213     kid = OpSIBLING(kid);
14214     if (!kid) {
14215         kid = newSVOP(OP_CONST, 0, newSViv(0));
14216         op_append_elem(OP_SPLIT, o, kid);
14217         o->op_private |= OPpSPLIT_IMPLIM;
14218     }
14219     scalar(kid);
14220
14221     if (OpHAS_SIBLING(kid))
14222         return too_many_arguments_pv(o,OP_DESC(o), 0);
14223
14224     return o;
14225 }
14226
14227 OP *
14228 Perl_ck_stringify(pTHX_ OP *o)
14229 {
14230     OP * const kid = OpSIBLING(cUNOPo->op_first);
14231     PERL_ARGS_ASSERT_CK_STRINGIFY;
14232     if ((   kid->op_type == OP_JOIN || kid->op_type == OP_QUOTEMETA
14233          || kid->op_type == OP_LC   || kid->op_type == OP_LCFIRST
14234          || kid->op_type == OP_UC   || kid->op_type == OP_UCFIRST)
14235         && !OpHAS_SIBLING(kid)) /* syntax errs can leave extra children */
14236     {
14237         op_sibling_splice(o, cUNOPo->op_first, -1, NULL);
14238         op_free(o);
14239         return kid;
14240     }
14241     return ck_fun(o);
14242 }
14243
14244 OP *
14245 Perl_ck_join(pTHX_ OP *o)
14246 {
14247     OP * const kid = OpSIBLING(cLISTOPo->op_first);
14248
14249     PERL_ARGS_ASSERT_CK_JOIN;
14250
14251     if (kid && kid->op_type == OP_MATCH) {
14252         if (ckWARN(WARN_SYNTAX)) {
14253             const REGEXP *re = PM_GETRE(kPMOP);
14254             const SV *msg = re
14255                     ? newSVpvn_flags( RX_PRECOMP_const(re), RX_PRELEN(re),
14256                                             SVs_TEMP | ( RX_UTF8(re) ? SVf_UTF8 : 0 ) )
14257                     : newSVpvs_flags( "STRING", SVs_TEMP );
14258             Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
14259                         "/%" SVf "/ should probably be written as \"%" SVf "\"",
14260                         SVfARG(msg), SVfARG(msg));
14261         }
14262     }
14263     if (kid
14264      && (kid->op_type == OP_CONST /* an innocent, unsuspicious separator */
14265         || (kid->op_type == OP_PADSV && !(kid->op_private & OPpLVAL_INTRO))
14266         || (  kid->op_type==OP_RV2SV && kUNOP->op_first->op_type == OP_GV
14267            && !(kid->op_private & (OPpLVAL_INTRO|OPpOUR_INTRO)))))
14268     {
14269         const OP * const bairn = OpSIBLING(kid); /* the list */
14270         if (bairn && !OpHAS_SIBLING(bairn) /* single-item list */
14271          && OP_GIMME(bairn,0) == G_SCALAR)
14272         {
14273             OP * const ret = op_convert_list(OP_STRINGIFY, OPf_FOLDED,
14274                                      op_sibling_splice(o, kid, 1, NULL));
14275             op_free(o);
14276             return ret;
14277         }
14278     }
14279
14280     return ck_fun(o);
14281 }
14282
14283 /*
14284 =for apidoc rv2cv_op_cv
14285
14286 Examines an op, which is expected to identify a subroutine at runtime,
14287 and attempts to determine at compile time which subroutine it identifies.
14288 This is normally used during Perl compilation to determine whether
14289 a prototype can be applied to a function call.  C<cvop> is the op
14290 being considered, normally an C<rv2cv> op.  A pointer to the identified
14291 subroutine is returned, if it could be determined statically, and a null
14292 pointer is returned if it was not possible to determine statically.
14293
14294 Currently, the subroutine can be identified statically if the RV that the
14295 C<rv2cv> is to operate on is provided by a suitable C<gv> or C<const> op.
14296 A C<gv> op is suitable if the GV's CV slot is populated.  A C<const> op is
14297 suitable if the constant value must be an RV pointing to a CV.  Details of
14298 this process may change in future versions of Perl.  If the C<rv2cv> op
14299 has the C<OPpENTERSUB_AMPER> flag set then no attempt is made to identify
14300 the subroutine statically: this flag is used to suppress compile-time
14301 magic on a subroutine call, forcing it to use default runtime behaviour.
14302
14303 If C<flags> has the bit C<RV2CVOPCV_MARK_EARLY> set, then the handling
14304 of a GV reference is modified.  If a GV was examined and its CV slot was
14305 found to be empty, then the C<gv> op has the C<OPpEARLY_CV> flag set.
14306 If the op is not optimised away, and the CV slot is later populated with
14307 a subroutine having a prototype, that flag eventually triggers the warning
14308 "called too early to check prototype".
14309
14310 If C<flags> has the bit C<RV2CVOPCV_RETURN_NAME_GV> set, then instead
14311 of returning a pointer to the subroutine it returns a pointer to the
14312 GV giving the most appropriate name for the subroutine in this context.
14313 Normally this is just the C<CvGV> of the subroutine, but for an anonymous
14314 (C<CvANON>) subroutine that is referenced through a GV it will be the
14315 referencing GV.  The resulting C<GV*> is cast to C<CV*> to be returned.
14316 A null pointer is returned as usual if there is no statically-determinable
14317 subroutine.
14318
14319 =for apidoc Amnh||OPpEARLY_CV
14320 =for apidoc Amnh||OPpENTERSUB_AMPER
14321 =for apidoc Amnh||RV2CVOPCV_MARK_EARLY
14322 =for apidoc Amnh||RV2CVOPCV_RETURN_NAME_GV
14323
14324 =cut
14325 */
14326
14327 /* shared by toke.c:yylex */
14328 CV *
14329 Perl_find_lexical_cv(pTHX_ PADOFFSET off)
14330 {
14331     PADNAME *name = PAD_COMPNAME(off);
14332     CV *compcv = PL_compcv;
14333     while (PadnameOUTER(name)) {
14334         assert(PARENT_PAD_INDEX(name));
14335         compcv = CvOUTSIDE(compcv);
14336         name = PadlistNAMESARRAY(CvPADLIST(compcv))
14337                 [off = PARENT_PAD_INDEX(name)];
14338     }
14339     assert(!PadnameIsOUR(name));
14340     if (!PadnameIsSTATE(name) && PadnamePROTOCV(name)) {
14341         return PadnamePROTOCV(name);
14342     }
14343     return (CV *)AvARRAY(PadlistARRAY(CvPADLIST(compcv))[1])[off];
14344 }
14345
14346 CV *
14347 Perl_rv2cv_op_cv(pTHX_ OP *cvop, U32 flags)
14348 {
14349     OP *rvop;
14350     CV *cv;
14351     GV *gv;
14352     PERL_ARGS_ASSERT_RV2CV_OP_CV;
14353     if (flags & ~RV2CVOPCV_FLAG_MASK)
14354         Perl_croak(aTHX_ "panic: rv2cv_op_cv bad flags %x", (unsigned)flags);
14355     if (cvop->op_type != OP_RV2CV)
14356         return NULL;
14357     if (cvop->op_private & OPpENTERSUB_AMPER)
14358         return NULL;
14359     if (!(cvop->op_flags & OPf_KIDS))
14360         return NULL;
14361     rvop = cUNOPx(cvop)->op_first;
14362     switch (rvop->op_type) {
14363         case OP_GV: {
14364             gv = cGVOPx_gv(rvop);
14365             if (!isGV(gv)) {
14366                 if (SvROK(gv) && SvTYPE(SvRV(gv)) == SVt_PVCV) {
14367                     cv = MUTABLE_CV(SvRV(gv));
14368                     gv = NULL;
14369                     break;
14370                 }
14371                 if (flags & RV2CVOPCV_RETURN_STUB)
14372                     return (CV *)gv;
14373                 else return NULL;
14374             }
14375             cv = GvCVu(gv);
14376             if (!cv) {
14377                 if (flags & RV2CVOPCV_MARK_EARLY)
14378                     rvop->op_private |= OPpEARLY_CV;
14379                 return NULL;
14380             }
14381         } break;
14382         case OP_CONST: {
14383             SV *rv = cSVOPx_sv(rvop);
14384             if (!SvROK(rv))
14385                 return NULL;
14386             cv = (CV*)SvRV(rv);
14387             gv = NULL;
14388         } break;
14389         case OP_PADCV: {
14390             cv = find_lexical_cv(rvop->op_targ);
14391             gv = NULL;
14392         } break;
14393         default: {
14394             return NULL;
14395         } NOT_REACHED; /* NOTREACHED */
14396     }
14397     if (SvTYPE((SV*)cv) != SVt_PVCV)
14398         return NULL;
14399     if (flags & RV2CVOPCV_RETURN_NAME_GV) {
14400         if ((!CvANON(cv) && !CvLEXICAL(cv)) || !gv)
14401             gv = CvGV(cv);
14402         return (CV*)gv;
14403     }
14404     else if (flags & RV2CVOPCV_MAYBE_NAME_GV) {
14405         if (CvLEXICAL(cv) || CvNAMED(cv))
14406             return NULL;
14407         if (!CvANON(cv) || !gv)
14408             gv = CvGV(cv);
14409         return (CV*)gv;
14410
14411     } else {
14412         return cv;
14413     }
14414 }
14415
14416 /*
14417 =for apidoc ck_entersub_args_list
14418
14419 Performs the default fixup of the arguments part of an C<entersub>
14420 op tree.  This consists of applying list context to each of the
14421 argument ops.  This is the standard treatment used on a call marked
14422 with C<&>, or a method call, or a call through a subroutine reference,
14423 or any other call where the callee can't be identified at compile time,
14424 or a call where the callee has no prototype.
14425
14426 =cut
14427 */
14428
14429 OP *
14430 Perl_ck_entersub_args_list(pTHX_ OP *entersubop)
14431 {
14432     OP *aop;
14433
14434     PERL_ARGS_ASSERT_CK_ENTERSUB_ARGS_LIST;
14435
14436     aop = cUNOPx(entersubop)->op_first;
14437     if (!OpHAS_SIBLING(aop))
14438         aop = cUNOPx(aop)->op_first;
14439     for (aop = OpSIBLING(aop); OpHAS_SIBLING(aop); aop = OpSIBLING(aop)) {
14440         /* skip the extra attributes->import() call implicitly added in
14441          * something like foo(my $x : bar)
14442          */
14443         if (   aop->op_type == OP_ENTERSUB
14444             && (aop->op_flags & OPf_WANT) == OPf_WANT_VOID
14445         )
14446             continue;
14447         list(aop);
14448         op_lvalue(aop, OP_ENTERSUB);
14449     }
14450     return entersubop;
14451 }
14452
14453 /*
14454 =for apidoc ck_entersub_args_proto
14455
14456 Performs the fixup of the arguments part of an C<entersub> op tree
14457 based on a subroutine prototype.  This makes various modifications to
14458 the argument ops, from applying context up to inserting C<refgen> ops,
14459 and checking the number and syntactic types of arguments, as directed by
14460 the prototype.  This is the standard treatment used on a subroutine call,
14461 not marked with C<&>, where the callee can be identified at compile time
14462 and has a prototype.
14463
14464 C<protosv> supplies the subroutine prototype to be applied to the call.
14465 It may be a normal defined scalar, of which the string value will be used.
14466 Alternatively, for convenience, it may be a subroutine object (a C<CV*>
14467 that has been cast to C<SV*>) which has a prototype.  The prototype
14468 supplied, in whichever form, does not need to match the actual callee
14469 referenced by the op tree.
14470
14471 If the argument ops disagree with the prototype, for example by having
14472 an unacceptable number of arguments, a valid op tree is returned anyway.
14473 The error is reflected in the parser state, normally resulting in a single
14474 exception at the top level of parsing which covers all the compilation
14475 errors that occurred.  In the error message, the callee is referred to
14476 by the name defined by the C<namegv> parameter.
14477
14478 =cut
14479 */
14480
14481 OP *
14482 Perl_ck_entersub_args_proto(pTHX_ OP *entersubop, GV *namegv, SV *protosv)
14483 {
14484     STRLEN proto_len;
14485     const char *proto, *proto_end;
14486     OP *aop, *prev, *cvop, *parent;
14487     int optional = 0;
14488     I32 arg = 0;
14489     I32 contextclass = 0;
14490     const char *e = NULL;
14491     PERL_ARGS_ASSERT_CK_ENTERSUB_ARGS_PROTO;
14492     if (SvTYPE(protosv) == SVt_PVCV ? !SvPOK(protosv) : !SvOK(protosv))
14493         Perl_croak(aTHX_ "panic: ck_entersub_args_proto CV with no proto, "
14494                    "flags=%lx", (unsigned long) SvFLAGS(protosv));
14495     if (SvTYPE(protosv) == SVt_PVCV)
14496          proto = CvPROTO(protosv), proto_len = CvPROTOLEN(protosv);
14497     else proto = SvPV(protosv, proto_len);
14498     proto = S_strip_spaces(aTHX_ proto, &proto_len);
14499     proto_end = proto + proto_len;
14500     parent = entersubop;
14501     aop = cUNOPx(entersubop)->op_first;
14502     if (!OpHAS_SIBLING(aop)) {
14503         parent = aop;
14504         aop = cUNOPx(aop)->op_first;
14505     }
14506     prev = aop;
14507     aop = OpSIBLING(aop);
14508     for (cvop = aop; OpHAS_SIBLING(cvop); cvop = OpSIBLING(cvop)) ;
14509     while (aop != cvop) {
14510         OP* o3 = aop;
14511
14512         if (proto >= proto_end)
14513         {
14514             SV * const namesv = cv_name((CV *)namegv, NULL, 0);
14515             yyerror_pv(Perl_form(aTHX_ "Too many arguments for %" SVf,
14516                                         SVfARG(namesv)), SvUTF8(namesv));
14517             return entersubop;
14518         }
14519
14520         switch (*proto) {
14521             case ';':
14522                 optional = 1;
14523                 proto++;
14524                 continue;
14525             case '_':
14526                 /* _ must be at the end */
14527                 if (proto[1] && !memCHRs(";@%", proto[1]))
14528                     goto oops;
14529                 /* FALLTHROUGH */
14530             case '$':
14531                 proto++;
14532                 arg++;
14533                 scalar(aop);
14534                 break;
14535             case '%':
14536             case '@':
14537                 list(aop);
14538                 arg++;
14539                 break;
14540             case '&':
14541                 proto++;
14542                 arg++;
14543                 if (    o3->op_type != OP_UNDEF
14544                     && (o3->op_type != OP_SREFGEN
14545                         || (  cUNOPx(cUNOPx(o3)->op_first)->op_first->op_type
14546                                 != OP_ANONCODE
14547                             && cUNOPx(cUNOPx(o3)->op_first)->op_first->op_type
14548                                 != OP_RV2CV)))
14549                     bad_type_gv(arg, namegv, o3,
14550                             arg == 1 ? "block or sub {}" : "sub {}");
14551                 break;
14552             case '*':
14553                 /* '*' allows any scalar type, including bareword */
14554                 proto++;
14555                 arg++;
14556                 if (o3->op_type == OP_RV2GV)
14557                     goto wrapref;       /* autoconvert GLOB -> GLOBref */
14558                 else if (o3->op_type == OP_CONST)
14559                     o3->op_private &= ~OPpCONST_STRICT;
14560                 scalar(aop);
14561                 break;
14562             case '+':
14563                 proto++;
14564                 arg++;
14565                 if (o3->op_type == OP_RV2AV ||
14566                     o3->op_type == OP_PADAV ||
14567                     o3->op_type == OP_RV2HV ||
14568                     o3->op_type == OP_PADHV
14569                 ) {
14570                     goto wrapref;
14571                 }
14572                 scalar(aop);
14573                 break;
14574             case '[': case ']':
14575                 goto oops;
14576
14577             case '\\':
14578                 proto++;
14579                 arg++;
14580             again:
14581                 switch (*proto++) {
14582                     case '[':
14583                         if (contextclass++ == 0) {
14584                             e = (char *) memchr(proto, ']', proto_end - proto);
14585                             if (!e || e == proto)
14586                                 goto oops;
14587                         }
14588                         else
14589                             goto oops;
14590                         goto again;
14591
14592                     case ']':
14593                         if (contextclass) {
14594                             const char *p = proto;
14595                             const char *const end = proto;
14596                             contextclass = 0;
14597                             while (*--p != '[')
14598                                 /* \[$] accepts any scalar lvalue */
14599                                 if (*p == '$'
14600                                  && Perl_op_lvalue_flags(aTHX_
14601                                      scalar(o3),
14602                                      OP_READ, /* not entersub */
14603                                      OP_LVALUE_NO_CROAK
14604                                     )) goto wrapref;
14605                             bad_type_gv(arg, namegv, o3,
14606                                     Perl_form(aTHX_ "one of %.*s",(int)(end - p), p));
14607                         } else
14608                             goto oops;
14609                         break;
14610                     case '*':
14611                         if (o3->op_type == OP_RV2GV)
14612                             goto wrapref;
14613                         if (!contextclass)
14614                             bad_type_gv(arg, namegv, o3, "symbol");
14615                         break;
14616                     case '&':
14617                         if (o3->op_type == OP_ENTERSUB
14618                          && !(o3->op_flags & OPf_STACKED))
14619                             goto wrapref;
14620                         if (!contextclass)
14621                             bad_type_gv(arg, namegv, o3, "subroutine");
14622                         break;
14623                     case '$':
14624                         if (o3->op_type == OP_RV2SV ||
14625                                 o3->op_type == OP_PADSV ||
14626                                 o3->op_type == OP_HELEM ||
14627                                 o3->op_type == OP_AELEM)
14628                             goto wrapref;
14629                         if (!contextclass) {
14630                             /* \$ accepts any scalar lvalue */
14631                             if (Perl_op_lvalue_flags(aTHX_
14632                                     scalar(o3),
14633                                     OP_READ,  /* not entersub */
14634                                     OP_LVALUE_NO_CROAK
14635                                )) goto wrapref;
14636                             bad_type_gv(arg, namegv, o3, "scalar");
14637                         }
14638                         break;
14639                     case '@':
14640                         if (o3->op_type == OP_RV2AV ||
14641                                 o3->op_type == OP_PADAV)
14642                         {
14643                             o3->op_flags &=~ OPf_PARENS;
14644                             goto wrapref;
14645                         }
14646                         if (!contextclass)
14647                             bad_type_gv(arg, namegv, o3, "array");
14648                         break;
14649                     case '%':
14650                         if (o3->op_type == OP_RV2HV ||
14651                                 o3->op_type == OP_PADHV)
14652                         {
14653                             o3->op_flags &=~ OPf_PARENS;
14654                             goto wrapref;
14655                         }
14656                         if (!contextclass)
14657                             bad_type_gv(arg, namegv, o3, "hash");
14658                         break;
14659                     wrapref:
14660                             aop = S_op_sibling_newUNOP(aTHX_ parent, prev,
14661                                                 OP_REFGEN, 0);
14662                         if (contextclass && e) {
14663                             proto = e + 1;
14664                             contextclass = 0;
14665                         }
14666                         break;
14667                     default: goto oops;
14668                 }
14669                 if (contextclass)
14670                     goto again;
14671                 break;
14672             case ' ':
14673                 proto++;
14674                 continue;
14675             default:
14676             oops: {
14677                 Perl_croak(aTHX_ "Malformed prototype for %" SVf ": %" SVf,
14678                                   SVfARG(cv_name((CV *)namegv, NULL, 0)),
14679                                   SVfARG(protosv));
14680             }
14681         }
14682
14683         op_lvalue(aop, OP_ENTERSUB);
14684         prev = aop;
14685         aop = OpSIBLING(aop);
14686     }
14687     if (aop == cvop && *proto == '_') {
14688         /* generate an access to $_ */
14689         op_sibling_splice(parent, prev, 0, newDEFSVOP());
14690     }
14691     if (!optional && proto_end > proto &&
14692         (*proto != '@' && *proto != '%' && *proto != ';' && *proto != '_'))
14693     {
14694         SV * const namesv = cv_name((CV *)namegv, NULL, 0);
14695         yyerror_pv(Perl_form(aTHX_ "Not enough arguments for %" SVf,
14696                                     SVfARG(namesv)), SvUTF8(namesv));
14697     }
14698     return entersubop;
14699 }
14700
14701 /*
14702 =for apidoc ck_entersub_args_proto_or_list
14703
14704 Performs the fixup of the arguments part of an C<entersub> op tree either
14705 based on a subroutine prototype or using default list-context processing.
14706 This is the standard treatment used on a subroutine call, not marked
14707 with C<&>, where the callee can be identified at compile time.
14708
14709 C<protosv> supplies the subroutine prototype to be applied to the call,
14710 or indicates that there is no prototype.  It may be a normal scalar,
14711 in which case if it is defined then the string value will be used
14712 as a prototype, and if it is undefined then there is no prototype.
14713 Alternatively, for convenience, it may be a subroutine object (a C<CV*>
14714 that has been cast to C<SV*>), of which the prototype will be used if it
14715 has one.  The prototype (or lack thereof) supplied, in whichever form,
14716 does not need to match the actual callee referenced by the op tree.
14717
14718 If the argument ops disagree with the prototype, for example by having
14719 an unacceptable number of arguments, a valid op tree is returned anyway.
14720 The error is reflected in the parser state, normally resulting in a single
14721 exception at the top level of parsing which covers all the compilation
14722 errors that occurred.  In the error message, the callee is referred to
14723 by the name defined by the C<namegv> parameter.
14724
14725 =cut
14726 */
14727
14728 OP *
14729 Perl_ck_entersub_args_proto_or_list(pTHX_ OP *entersubop,
14730         GV *namegv, SV *protosv)
14731 {
14732     PERL_ARGS_ASSERT_CK_ENTERSUB_ARGS_PROTO_OR_LIST;
14733     if (SvTYPE(protosv) == SVt_PVCV ? SvPOK(protosv) : SvOK(protosv))
14734         return ck_entersub_args_proto(entersubop, namegv, protosv);
14735     else
14736         return ck_entersub_args_list(entersubop);
14737 }
14738
14739 OP *
14740 Perl_ck_entersub_args_core(pTHX_ OP *entersubop, GV *namegv, SV *protosv)
14741 {
14742     IV cvflags = SvIVX(protosv);
14743     int opnum = cvflags & 0xffff;
14744     OP *aop = cUNOPx(entersubop)->op_first;
14745
14746     PERL_ARGS_ASSERT_CK_ENTERSUB_ARGS_CORE;
14747
14748     if (!opnum) {
14749         OP *cvop;
14750         if (!OpHAS_SIBLING(aop))
14751             aop = cUNOPx(aop)->op_first;
14752         aop = OpSIBLING(aop);
14753         for (cvop = aop; OpSIBLING(cvop); cvop = OpSIBLING(cvop)) ;
14754         if (aop != cvop) {
14755             SV *namesv = cv_name((CV *)namegv, NULL, CV_NAME_NOTQUAL);
14756             yyerror_pv(Perl_form(aTHX_ "Too many arguments for %" SVf,
14757                 SVfARG(namesv)), SvUTF8(namesv));
14758         }
14759
14760         op_free(entersubop);
14761         switch(cvflags >> 16) {
14762         case 'F': return newSVOP(OP_CONST, 0,
14763                                         newSVpv(CopFILE(PL_curcop),0));
14764         case 'L': return newSVOP(
14765                            OP_CONST, 0,
14766                            Perl_newSVpvf(aTHX_
14767                              "%" IVdf, (IV)CopLINE(PL_curcop)
14768                            )
14769                          );
14770         case 'P': return newSVOP(OP_CONST, 0,
14771                                    (PL_curstash
14772                                      ? newSVhek(HvNAME_HEK(PL_curstash))
14773                                      : &PL_sv_undef
14774                                    )
14775                                 );
14776         }
14777         NOT_REACHED; /* NOTREACHED */
14778     }
14779     else {
14780         OP *prev, *cvop, *first, *parent;
14781         U32 flags = 0;
14782
14783         parent = entersubop;
14784         if (!OpHAS_SIBLING(aop)) {
14785             parent = aop;
14786             aop = cUNOPx(aop)->op_first;
14787         }
14788
14789         first = prev = aop;
14790         aop = OpSIBLING(aop);
14791         /* find last sibling */
14792         for (cvop = aop;
14793              OpHAS_SIBLING(cvop);
14794              prev = cvop, cvop = OpSIBLING(cvop))
14795             ;
14796         if (!(cvop->op_private & OPpENTERSUB_NOPAREN)
14797             /* Usually, OPf_SPECIAL on an op with no args means that it had
14798              * parens, but these have their own meaning for that flag: */
14799             && opnum != OP_VALUES && opnum != OP_KEYS && opnum != OP_EACH
14800             && opnum != OP_DELETE && opnum != OP_EXISTS)
14801                 flags |= OPf_SPECIAL;
14802         /* excise cvop from end of sibling chain */
14803         op_sibling_splice(parent, prev, 1, NULL);
14804         op_free(cvop);
14805         if (aop == cvop) aop = NULL;
14806
14807         /* detach remaining siblings from the first sibling, then
14808          * dispose of original optree */
14809
14810         if (aop)
14811             op_sibling_splice(parent, first, -1, NULL);
14812         op_free(entersubop);
14813
14814         if (cvflags == (OP_ENTEREVAL | (1<<16)))
14815             flags |= OPpEVAL_BYTES <<8;
14816
14817         switch (PL_opargs[opnum] & OA_CLASS_MASK) {
14818         case OA_UNOP:
14819         case OA_BASEOP_OR_UNOP:
14820         case OA_FILESTATOP:
14821             if (!aop)
14822                 return newOP(opnum,flags);       /* zero args */
14823             if (aop == prev)
14824                 return newUNOP(opnum,flags,aop); /* one arg */
14825             /* too many args */
14826             /* FALLTHROUGH */
14827         case OA_BASEOP:
14828             if (aop) {
14829                 SV *namesv;
14830                 OP *nextop;
14831
14832                 namesv = cv_name((CV *)namegv, NULL, CV_NAME_NOTQUAL);
14833                 yyerror_pv(Perl_form(aTHX_ "Too many arguments for %" SVf,
14834                     SVfARG(namesv)), SvUTF8(namesv));
14835                 while (aop) {
14836                     nextop = OpSIBLING(aop);
14837                     op_free(aop);
14838                     aop = nextop;
14839                 }
14840
14841             }
14842             return opnum == OP_RUNCV
14843                 ? newPVOP(OP_RUNCV,0,NULL)
14844                 : newOP(opnum,0);
14845         default:
14846             return op_convert_list(opnum,0,aop);
14847         }
14848     }
14849     NOT_REACHED; /* NOTREACHED */
14850     return entersubop;
14851 }
14852
14853 /*
14854 =for apidoc cv_get_call_checker_flags
14855
14856 Retrieves the function that will be used to fix up a call to C<cv>.
14857 Specifically, the function is applied to an C<entersub> op tree for a
14858 subroutine call, not marked with C<&>, where the callee can be identified
14859 at compile time as C<cv>.
14860
14861 The C-level function pointer is returned in C<*ckfun_p>, an SV argument
14862 for it is returned in C<*ckobj_p>, and control flags are returned in
14863 C<*ckflags_p>.  The function is intended to be called in this manner:
14864
14865  entersubop = (*ckfun_p)(aTHX_ entersubop, namegv, (*ckobj_p));
14866
14867 In this call, C<entersubop> is a pointer to the C<entersub> op,
14868 which may be replaced by the check function, and C<namegv> supplies
14869 the name that should be used by the check function to refer
14870 to the callee of the C<entersub> op if it needs to emit any diagnostics.
14871 It is permitted to apply the check function in non-standard situations,
14872 such as to a call to a different subroutine or to a method call.
14873
14874 C<namegv> may not actually be a GV.  If the C<CALL_CHECKER_REQUIRE_GV>
14875 bit is clear in C<*ckflags_p>, it is permitted to pass a CV or other SV
14876 instead, anything that can be used as the first argument to L</cv_name>.
14877 If the C<CALL_CHECKER_REQUIRE_GV> bit is set in C<*ckflags_p> then the
14878 check function requires C<namegv> to be a genuine GV.
14879
14880 By default, the check function is
14881 L<Perl_ck_entersub_args_proto_or_list|/ck_entersub_args_proto_or_list>,
14882 the SV parameter is C<cv> itself, and the C<CALL_CHECKER_REQUIRE_GV>
14883 flag is clear.  This implements standard prototype processing.  It can
14884 be changed, for a particular subroutine, by L</cv_set_call_checker_flags>.
14885
14886 If the C<CALL_CHECKER_REQUIRE_GV> bit is set in C<gflags> then it
14887 indicates that the caller only knows about the genuine GV version of
14888 C<namegv>, and accordingly the corresponding bit will always be set in
14889 C<*ckflags_p>, regardless of the check function's recorded requirements.
14890 If the C<CALL_CHECKER_REQUIRE_GV> bit is clear in C<gflags> then it
14891 indicates the caller knows about the possibility of passing something
14892 other than a GV as C<namegv>, and accordingly the corresponding bit may
14893 be either set or clear in C<*ckflags_p>, indicating the check function's
14894 recorded requirements.
14895
14896 C<gflags> is a bitset passed into C<cv_get_call_checker_flags>, in which
14897 only the C<CALL_CHECKER_REQUIRE_GV> bit currently has a defined meaning
14898 (for which see above).  All other bits should be clear.
14899
14900 =for apidoc Amnh||CALL_CHECKER_REQUIRE_GV
14901
14902 =for apidoc cv_get_call_checker
14903
14904 The original form of L</cv_get_call_checker_flags>, which does not return
14905 checker flags.  When using a checker function returned by this function,
14906 it is only safe to call it with a genuine GV as its C<namegv> argument.
14907
14908 =cut
14909 */
14910
14911 void
14912 Perl_cv_get_call_checker_flags(pTHX_ CV *cv, U32 gflags,
14913         Perl_call_checker *ckfun_p, SV **ckobj_p, U32 *ckflags_p)
14914 {
14915     MAGIC *callmg;
14916     PERL_ARGS_ASSERT_CV_GET_CALL_CHECKER_FLAGS;
14917     PERL_UNUSED_CONTEXT;
14918     callmg = SvMAGICAL((SV*)cv) ? mg_find((SV*)cv, PERL_MAGIC_checkcall) : NULL;
14919     if (callmg) {
14920         *ckfun_p = DPTR2FPTR(Perl_call_checker, callmg->mg_ptr);
14921         *ckobj_p = callmg->mg_obj;
14922         *ckflags_p = (callmg->mg_flags | gflags) & MGf_REQUIRE_GV;
14923     } else {
14924         *ckfun_p = Perl_ck_entersub_args_proto_or_list;
14925         *ckobj_p = (SV*)cv;
14926         *ckflags_p = gflags & MGf_REQUIRE_GV;
14927     }
14928 }
14929
14930 void
14931 Perl_cv_get_call_checker(pTHX_ CV *cv, Perl_call_checker *ckfun_p, SV **ckobj_p)
14932 {
14933     U32 ckflags;
14934     PERL_ARGS_ASSERT_CV_GET_CALL_CHECKER;
14935     PERL_UNUSED_CONTEXT;
14936     cv_get_call_checker_flags(cv, CALL_CHECKER_REQUIRE_GV, ckfun_p, ckobj_p,
14937         &ckflags);
14938 }
14939
14940 /*
14941 =for apidoc cv_set_call_checker_flags
14942
14943 Sets the function that will be used to fix up a call to C<cv>.
14944 Specifically, the function is applied to an C<entersub> op tree for a
14945 subroutine call, not marked with C<&>, where the callee can be identified
14946 at compile time as C<cv>.
14947
14948 The C-level function pointer is supplied in C<ckfun>, an SV argument for
14949 it is supplied in C<ckobj>, and control flags are supplied in C<ckflags>.
14950 The function should be defined like this:
14951
14952     STATIC OP * ckfun(pTHX_ OP *op, GV *namegv, SV *ckobj)
14953
14954 It is intended to be called in this manner:
14955
14956     entersubop = ckfun(aTHX_ entersubop, namegv, ckobj);
14957
14958 In this call, C<entersubop> is a pointer to the C<entersub> op,
14959 which may be replaced by the check function, and C<namegv> supplies
14960 the name that should be used by the check function to refer
14961 to the callee of the C<entersub> op if it needs to emit any diagnostics.
14962 It is permitted to apply the check function in non-standard situations,
14963 such as to a call to a different subroutine or to a method call.
14964
14965 C<namegv> may not actually be a GV.  For efficiency, perl may pass a
14966 CV or other SV instead.  Whatever is passed can be used as the first
14967 argument to L</cv_name>.  You can force perl to pass a GV by including
14968 C<CALL_CHECKER_REQUIRE_GV> in the C<ckflags>.
14969
14970 C<ckflags> is a bitset, in which only the C<CALL_CHECKER_REQUIRE_GV>
14971 bit currently has a defined meaning (for which see above).  All other
14972 bits should be clear.
14973
14974 The current setting for a particular CV can be retrieved by
14975 L</cv_get_call_checker_flags>.
14976
14977 =for apidoc cv_set_call_checker
14978
14979 The original form of L</cv_set_call_checker_flags>, which passes it the
14980 C<CALL_CHECKER_REQUIRE_GV> flag for backward-compatibility.  The effect
14981 of that flag setting is that the check function is guaranteed to get a
14982 genuine GV as its C<namegv> argument.
14983
14984 =cut
14985 */
14986
14987 void
14988 Perl_cv_set_call_checker(pTHX_ CV *cv, Perl_call_checker ckfun, SV *ckobj)
14989 {
14990     PERL_ARGS_ASSERT_CV_SET_CALL_CHECKER;
14991     cv_set_call_checker_flags(cv, ckfun, ckobj, CALL_CHECKER_REQUIRE_GV);
14992 }
14993
14994 void
14995 Perl_cv_set_call_checker_flags(pTHX_ CV *cv, Perl_call_checker ckfun,
14996                                      SV *ckobj, U32 ckflags)
14997 {
14998     PERL_ARGS_ASSERT_CV_SET_CALL_CHECKER_FLAGS;
14999     if (ckfun == Perl_ck_entersub_args_proto_or_list && ckobj == (SV*)cv) {
15000         if (SvMAGICAL((SV*)cv))
15001             mg_free_type((SV*)cv, PERL_MAGIC_checkcall);
15002     } else {
15003         MAGIC *callmg;
15004         sv_magic((SV*)cv, &PL_sv_undef, PERL_MAGIC_checkcall, NULL, 0);
15005         callmg = mg_find((SV*)cv, PERL_MAGIC_checkcall);
15006         assert(callmg);
15007         if (callmg->mg_flags & MGf_REFCOUNTED) {
15008             SvREFCNT_dec(callmg->mg_obj);
15009             callmg->mg_flags &= ~MGf_REFCOUNTED;
15010         }
15011         callmg->mg_ptr = FPTR2DPTR(char *, ckfun);
15012         callmg->mg_obj = ckobj;
15013         if (ckobj != (SV*)cv) {
15014             SvREFCNT_inc_simple_void_NN(ckobj);
15015             callmg->mg_flags |= MGf_REFCOUNTED;
15016         }
15017         callmg->mg_flags = (callmg->mg_flags &~ MGf_REQUIRE_GV)
15018                          | (U8)(ckflags & MGf_REQUIRE_GV) | MGf_COPY;
15019     }
15020 }
15021
15022 static void
15023 S_entersub_alloc_targ(pTHX_ OP * const o)
15024 {
15025     o->op_targ = pad_alloc(OP_ENTERSUB, SVs_PADTMP);
15026     o->op_private |= OPpENTERSUB_HASTARG;
15027 }
15028
15029 OP *
15030 Perl_ck_subr(pTHX_ OP *o)
15031 {
15032     OP *aop, *cvop;
15033     CV *cv;
15034     GV *namegv;
15035     SV **const_class = NULL;
15036
15037     PERL_ARGS_ASSERT_CK_SUBR;
15038
15039     aop = cUNOPx(o)->op_first;
15040     if (!OpHAS_SIBLING(aop))
15041         aop = cUNOPx(aop)->op_first;
15042     aop = OpSIBLING(aop);
15043     for (cvop = aop; OpHAS_SIBLING(cvop); cvop = OpSIBLING(cvop)) ;
15044     cv = rv2cv_op_cv(cvop, RV2CVOPCV_MARK_EARLY);
15045     namegv = cv ? (GV*)rv2cv_op_cv(cvop, RV2CVOPCV_MAYBE_NAME_GV) : NULL;
15046
15047     o->op_private &= ~1;
15048     o->op_private |= (PL_hints & HINT_STRICT_REFS);
15049     if (PERLDB_SUB && PL_curstash != PL_debstash)
15050         o->op_private |= OPpENTERSUB_DB;
15051     switch (cvop->op_type) {
15052         case OP_RV2CV:
15053             o->op_private |= (cvop->op_private & OPpENTERSUB_AMPER);
15054             op_null(cvop);
15055             break;
15056         case OP_METHOD:
15057         case OP_METHOD_NAMED:
15058         case OP_METHOD_SUPER:
15059         case OP_METHOD_REDIR:
15060         case OP_METHOD_REDIR_SUPER:
15061             o->op_flags |= OPf_REF;
15062             if (aop->op_type == OP_CONST) {
15063                 aop->op_private &= ~OPpCONST_STRICT;
15064                 const_class = &cSVOPx(aop)->op_sv;
15065             }
15066             else if (aop->op_type == OP_LIST) {
15067                 OP * const sib = OpSIBLING(((UNOP*)aop)->op_first);
15068                 if (sib && sib->op_type == OP_CONST) {
15069                     sib->op_private &= ~OPpCONST_STRICT;
15070                     const_class = &cSVOPx(sib)->op_sv;
15071                 }
15072             }
15073             /* make class name a shared cow string to speedup method calls */
15074             /* constant string might be replaced with object, f.e. bigint */
15075             if (const_class && SvPOK(*const_class)) {
15076                 STRLEN len;
15077                 const char* str = SvPV(*const_class, len);
15078                 if (len) {
15079                     SV* const shared = newSVpvn_share(
15080                         str, SvUTF8(*const_class)
15081                                     ? -(SSize_t)len : (SSize_t)len,
15082                         0
15083                     );
15084                     if (SvREADONLY(*const_class))
15085                         SvREADONLY_on(shared);
15086                     SvREFCNT_dec(*const_class);
15087                     *const_class = shared;
15088                 }
15089             }
15090             break;
15091     }
15092
15093     if (!cv) {
15094         S_entersub_alloc_targ(aTHX_ o);
15095         return ck_entersub_args_list(o);
15096     } else {
15097         Perl_call_checker ckfun;
15098         SV *ckobj;
15099         U32 ckflags;
15100         cv_get_call_checker_flags(cv, 0, &ckfun, &ckobj, &ckflags);
15101         if (CvISXSUB(cv) || !CvROOT(cv))
15102             S_entersub_alloc_targ(aTHX_ o);
15103         if (!namegv) {
15104             /* The original call checker API guarantees that a GV will
15105                be provided with the right name.  So, if the old API was
15106                used (or the REQUIRE_GV flag was passed), we have to reify
15107                the CV’s GV, unless this is an anonymous sub.  This is not
15108                ideal for lexical subs, as its stringification will include
15109                the package.  But it is the best we can do.  */
15110             if (ckflags & CALL_CHECKER_REQUIRE_GV) {
15111                 if (!CvANON(cv) && (!CvNAMED(cv) || CvNAME_HEK(cv)))
15112                     namegv = CvGV(cv);
15113             }
15114             else namegv = MUTABLE_GV(cv);
15115             /* After a syntax error in a lexical sub, the cv that
15116                rv2cv_op_cv returns may be a nameless stub. */
15117             if (!namegv) return ck_entersub_args_list(o);
15118
15119         }
15120         return ckfun(aTHX_ o, namegv, ckobj);
15121     }
15122 }
15123
15124 OP *
15125 Perl_ck_svconst(pTHX_ OP *o)
15126 {
15127     SV * const sv = cSVOPo->op_sv;
15128     PERL_ARGS_ASSERT_CK_SVCONST;
15129     PERL_UNUSED_CONTEXT;
15130 #ifdef PERL_COPY_ON_WRITE
15131     /* Since the read-only flag may be used to protect a string buffer, we
15132        cannot do copy-on-write with existing read-only scalars that are not
15133        already copy-on-write scalars.  To allow $_ = "hello" to do COW with
15134        that constant, mark the constant as COWable here, if it is not
15135        already read-only. */
15136     if (!SvREADONLY(sv) && !SvIsCOW(sv) && SvCANCOW(sv)) {
15137         SvIsCOW_on(sv);
15138         CowREFCNT(sv) = 0;
15139 # ifdef PERL_DEBUG_READONLY_COW
15140         sv_buf_to_ro(sv);
15141 # endif
15142     }
15143 #endif
15144     SvREADONLY_on(sv);
15145     return o;
15146 }
15147
15148 OP *
15149 Perl_ck_trunc(pTHX_ OP *o)
15150 {
15151     PERL_ARGS_ASSERT_CK_TRUNC;
15152
15153     if (o->op_flags & OPf_KIDS) {
15154         SVOP *kid = (SVOP*)cUNOPo->op_first;
15155
15156         if (kid->op_type == OP_NULL)
15157             kid = (SVOP*)OpSIBLING(kid);
15158         if (kid && kid->op_type == OP_CONST &&
15159             (kid->op_private & OPpCONST_BARE) &&
15160             !kid->op_folded)
15161         {
15162             o->op_flags |= OPf_SPECIAL;
15163             kid->op_private &= ~OPpCONST_STRICT;
15164         }
15165     }
15166     return ck_fun(o);
15167 }
15168
15169 OP *
15170 Perl_ck_substr(pTHX_ OP *o)
15171 {
15172     PERL_ARGS_ASSERT_CK_SUBSTR;
15173
15174     o = ck_fun(o);
15175     if ((o->op_flags & OPf_KIDS) && (o->op_private == 4)) {
15176         OP *kid = cLISTOPo->op_first;
15177
15178         if (kid->op_type == OP_NULL)
15179             kid = OpSIBLING(kid);
15180         if (kid)
15181             /* Historically, substr(delete $foo{bar},...) has been allowed
15182                with 4-arg substr.  Keep it working by applying entersub
15183                lvalue context.  */
15184             op_lvalue(kid, OP_ENTERSUB);
15185
15186     }
15187     return o;
15188 }
15189
15190 OP *
15191 Perl_ck_tell(pTHX_ OP *o)
15192 {
15193     PERL_ARGS_ASSERT_CK_TELL;
15194     o = ck_fun(o);
15195     if (o->op_flags & OPf_KIDS) {
15196      OP *kid = cLISTOPo->op_first;
15197      if (kid->op_type == OP_NULL && OpHAS_SIBLING(kid)) kid = OpSIBLING(kid);
15198      if (kid->op_type == OP_RV2GV) kid->op_private |= OPpALLOW_FAKE;
15199     }
15200     return o;
15201 }
15202
15203 OP *
15204 Perl_ck_each(pTHX_ OP *o)
15205 {
15206     OP *kid = o->op_flags & OPf_KIDS ? cUNOPo->op_first : NULL;
15207     const unsigned orig_type  = o->op_type;
15208
15209     PERL_ARGS_ASSERT_CK_EACH;
15210
15211     if (kid) {
15212         switch (kid->op_type) {
15213             case OP_PADHV:
15214             case OP_RV2HV:
15215                 break;
15216             case OP_PADAV:
15217             case OP_RV2AV:
15218                 OpTYPE_set(o, orig_type == OP_EACH ? OP_AEACH
15219                             : orig_type == OP_KEYS ? OP_AKEYS
15220                             :                        OP_AVALUES);
15221                 break;
15222             case OP_CONST:
15223                 if (kid->op_private == OPpCONST_BARE
15224                  || !SvROK(cSVOPx_sv(kid))
15225                  || (  SvTYPE(SvRV(cSVOPx_sv(kid))) != SVt_PVAV
15226                     && SvTYPE(SvRV(cSVOPx_sv(kid))) != SVt_PVHV  )
15227                    )
15228                     goto bad;
15229                 /* FALLTHROUGH */
15230             default:
15231                 qerror(Perl_mess(aTHX_
15232                     "Experimental %s on scalar is now forbidden",
15233                      PL_op_desc[orig_type]));
15234                bad:
15235                 bad_type_pv(1, "hash or array", o, kid);
15236                 return o;
15237         }
15238     }
15239     return ck_fun(o);
15240 }
15241
15242 OP *
15243 Perl_ck_length(pTHX_ OP *o)
15244 {
15245     PERL_ARGS_ASSERT_CK_LENGTH;
15246
15247     o = ck_fun(o);
15248
15249     if (ckWARN(WARN_SYNTAX)) {
15250         const OP *kid = o->op_flags & OPf_KIDS ? cLISTOPo->op_first : NULL;
15251
15252         if (kid) {
15253             SV *name = NULL;
15254             const bool hash = kid->op_type == OP_PADHV
15255                            || kid->op_type == OP_RV2HV;
15256             switch (kid->op_type) {
15257                 case OP_PADHV:
15258                 case OP_PADAV:
15259                 case OP_RV2HV:
15260                 case OP_RV2AV:
15261                     name = S_op_varname(aTHX_ kid);
15262                     break;
15263                 default:
15264                     return o;
15265             }
15266             if (name)
15267                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
15268                     "length() used on %" SVf " (did you mean \"scalar(%s%" SVf
15269                     ")\"?)",
15270                     SVfARG(name), hash ? "keys " : "", SVfARG(name)
15271                 );
15272             else if (hash)
15273      /* diag_listed_as: length() used on %s (did you mean "scalar(%s)"?) */
15274                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
15275                     "length() used on %%hash (did you mean \"scalar(keys %%hash)\"?)");
15276             else
15277      /* diag_listed_as: length() used on %s (did you mean "scalar(%s)"?) */
15278                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
15279                     "length() used on @array (did you mean \"scalar(@array)\"?)");
15280         }
15281     }
15282
15283     return o;
15284 }
15285
15286
15287 OP *
15288 Perl_ck_isa(pTHX_ OP *o)
15289 {
15290     OP *classop = cBINOPo->op_last;
15291
15292     PERL_ARGS_ASSERT_CK_ISA;
15293
15294     /* Convert barename into PV */
15295     if(classop->op_type == OP_CONST && classop->op_private & OPpCONST_BARE) {
15296         /* TODO: Optionally convert package to raw HV here */
15297         classop->op_private &= ~(OPpCONST_BARE|OPpCONST_STRICT);
15298     }
15299
15300     return o;
15301 }
15302
15303
15304 /*
15305    ---------------------------------------------------------
15306
15307    Common vars in list assignment
15308
15309    There now follows some enums and static functions for detecting
15310    common variables in list assignments. Here is a little essay I wrote
15311    for myself when trying to get my head around this. DAPM.
15312
15313    ----
15314
15315    First some random observations:
15316
15317    * If a lexical var is an alias of something else, e.g.
15318        for my $x ($lex, $pkg, $a[0]) {...}
15319      then the act of aliasing will increase the reference count of the SV
15320
15321    * If a package var is an alias of something else, it may still have a
15322      reference count of 1, depending on how the alias was created, e.g.
15323      in *a = *b, $a may have a refcount of 1 since the GP is shared
15324      with a single GvSV pointer to the SV. So If it's an alias of another
15325      package var, then RC may be 1; if it's an alias of another scalar, e.g.
15326      a lexical var or an array element, then it will have RC > 1.
15327
15328    * There are many ways to create a package alias; ultimately, XS code
15329      may quite legally do GvSV(gv) = SvREFCNT_inc(sv) for example, so
15330      run-time tracing mechanisms are unlikely to be able to catch all cases.
15331
15332    * When the LHS is all my declarations, the same vars can't appear directly
15333      on the RHS, but they can indirectly via closures, aliasing and lvalue
15334      subs. But those techniques all involve an increase in the lexical
15335      scalar's ref count.
15336
15337    * When the LHS is all lexical vars (but not necessarily my declarations),
15338      it is possible for the same lexicals to appear directly on the RHS, and
15339      without an increased ref count, since the stack isn't refcounted.
15340      This case can be detected at compile time by scanning for common lex
15341      vars with PL_generation.
15342
15343    * lvalue subs defeat common var detection, but they do at least
15344      return vars with a temporary ref count increment. Also, you can't
15345      tell at compile time whether a sub call is lvalue.
15346
15347
15348    So...
15349
15350    A: There are a few circumstances where there definitely can't be any
15351      commonality:
15352
15353        LHS empty:  () = (...);
15354        RHS empty:  (....) = ();
15355        RHS contains only constants or other 'can't possibly be shared'
15356            elements (e.g. ops that return PADTMPs):  (...) = (1,2, length)
15357            i.e. they only contain ops not marked as dangerous, whose children
15358            are also not dangerous;
15359        LHS ditto;
15360        LHS contains a single scalar element: e.g. ($x) = (....); because
15361            after $x has been modified, it won't be used again on the RHS;
15362        RHS contains a single element with no aggregate on LHS: e.g.
15363            ($a,$b,$c)  = ($x); again, once $a has been modified, its value
15364            won't be used again.
15365
15366    B: If LHS are all 'my' lexical var declarations (or safe ops, which
15367      we can ignore):
15368
15369        my ($a, $b, @c) = ...;
15370
15371        Due to closure and goto tricks, these vars may already have content.
15372        For the same reason, an element on the RHS may be a lexical or package
15373        alias of one of the vars on the left, or share common elements, for
15374        example:
15375
15376            my ($x,$y) = f(); # $x and $y on both sides
15377            sub f : lvalue { ($x,$y) = (1,2); $y, $x }
15378
15379        and
15380
15381            my $ra = f();
15382            my @a = @$ra;  # elements of @a on both sides
15383            sub f { @a = 1..4; \@a }
15384
15385
15386        First, just consider scalar vars on LHS:
15387
15388            RHS is safe only if (A), or in addition,
15389                * contains only lexical *scalar* vars, where neither side's
15390                  lexicals have been flagged as aliases
15391
15392            If RHS is not safe, then it's always legal to check LHS vars for
15393            RC==1, since the only RHS aliases will always be associated
15394            with an RC bump.
15395
15396            Note that in particular, RHS is not safe if:
15397
15398                * it contains package scalar vars; e.g.:
15399
15400                    f();
15401                    my ($x, $y) = (2, $x_alias);
15402                    sub f { $x = 1; *x_alias = \$x; }
15403
15404                * It contains other general elements, such as flattened or
15405                * spliced or single array or hash elements, e.g.
15406
15407                    f();
15408                    my ($x,$y) = @a; # or $a[0] or @a{@b} etc
15409
15410                    sub f {
15411                        ($x, $y) = (1,2);
15412                        use feature 'refaliasing';
15413                        \($a[0], $a[1]) = \($y,$x);
15414                    }
15415
15416                  It doesn't matter if the array/hash is lexical or package.
15417
15418                * it contains a function call that happens to be an lvalue
15419                  sub which returns one or more of the above, e.g.
15420
15421                    f();
15422                    my ($x,$y) = f();
15423
15424                    sub f : lvalue {
15425                        ($x, $y) = (1,2);
15426                        *x1 = \$x;
15427                        $y, $x1;
15428                    }
15429
15430                    (so a sub call on the RHS should be treated the same
15431                    as having a package var on the RHS).
15432
15433                * any other "dangerous" thing, such an op or built-in that
15434                  returns one of the above, e.g. pp_preinc
15435
15436
15437            If RHS is not safe, what we can do however is at compile time flag
15438            that the LHS are all my declarations, and at run time check whether
15439            all the LHS have RC == 1, and if so skip the full scan.
15440
15441        Now consider array and hash vars on LHS: e.g. my (...,@a) = ...;
15442
15443            Here the issue is whether there can be elements of @a on the RHS
15444            which will get prematurely freed when @a is cleared prior to
15445            assignment. This is only a problem if the aliasing mechanism
15446            is one which doesn't increase the refcount - only if RC == 1
15447            will the RHS element be prematurely freed.
15448
15449            Because the array/hash is being INTROed, it or its elements
15450            can't directly appear on the RHS:
15451
15452                my (@a) = ($a[0], @a, etc) # NOT POSSIBLE
15453
15454            but can indirectly, e.g.:
15455
15456                my $r = f();
15457                my (@a) = @$r;
15458                sub f { @a = 1..3; \@a }
15459
15460            So if the RHS isn't safe as defined by (A), we must always
15461            mortalise and bump the ref count of any remaining RHS elements
15462            when assigning to a non-empty LHS aggregate.
15463
15464            Lexical scalars on the RHS aren't safe if they've been involved in
15465            aliasing, e.g.
15466
15467                use feature 'refaliasing';
15468
15469                f();
15470                \(my $lex) = \$pkg;
15471                my @a = ($lex,3); # equivalent to ($a[0],3)
15472
15473                sub f {
15474                    @a = (1,2);
15475                    \$pkg = \$a[0];
15476                }
15477
15478            Similarly with lexical arrays and hashes on the RHS:
15479
15480                f();
15481                my @b;
15482                my @a = (@b);
15483
15484                sub f {
15485                    @a = (1,2);
15486                    \$b[0] = \$a[1];
15487                    \$b[1] = \$a[0];
15488                }
15489
15490
15491
15492    C: As (B), but in addition the LHS may contain non-intro lexicals, e.g.
15493        my $a; ($a, my $b) = (....);
15494
15495        The difference between (B) and (C) is that it is now physically
15496        possible for the LHS vars to appear on the RHS too, where they
15497        are not reference counted; but in this case, the compile-time
15498        PL_generation sweep will detect such common vars.
15499
15500        So the rules for (C) differ from (B) in that if common vars are
15501        detected, the runtime "test RC==1" optimisation can no longer be used,
15502        and a full mark and sweep is required
15503
15504    D: As (C), but in addition the LHS may contain package vars.
15505
15506        Since package vars can be aliased without a corresponding refcount
15507        increase, all bets are off. It's only safe if (A). E.g.
15508
15509            my ($x, $y) = (1,2);
15510
15511            for $x_alias ($x) {
15512                ($x_alias, $y) = (3, $x); # whoops
15513            }
15514
15515        Ditto for LHS aggregate package vars.
15516
15517    E: Any other dangerous ops on LHS, e.g.
15518            (f(), $a[0], @$r) = (...);
15519
15520        this is similar to (E) in that all bets are off. In addition, it's
15521        impossible to determine at compile time whether the LHS
15522        contains a scalar or an aggregate, e.g.
15523
15524            sub f : lvalue { @a }
15525            (f()) = 1..3;
15526
15527 * ---------------------------------------------------------
15528 */
15529
15530
15531 /* A set of bit flags returned by S_aassign_scan(). Each flag indicates
15532  * that at least one of the things flagged was seen.
15533  */
15534
15535 enum {
15536     AAS_MY_SCALAR       = 0x001, /* my $scalar */
15537     AAS_MY_AGG          = 0x002, /* aggregate: my @array or my %hash */
15538     AAS_LEX_SCALAR      = 0x004, /* $lexical */
15539     AAS_LEX_AGG         = 0x008, /* @lexical or %lexical aggregate */
15540     AAS_LEX_SCALAR_COMM = 0x010, /* $lexical seen on both sides */
15541     AAS_PKG_SCALAR      = 0x020, /* $scalar (where $scalar is pkg var) */
15542     AAS_PKG_AGG         = 0x040, /* package @array or %hash aggregate */
15543     AAS_DANGEROUS       = 0x080, /* an op (other than the above)
15544                                          that's flagged OA_DANGEROUS */
15545     AAS_SAFE_SCALAR     = 0x100, /* produces at least one scalar SV that's
15546                                         not in any of the categories above */
15547     AAS_DEFAV           = 0x200  /* contains just a single '@_' on RHS */
15548 };
15549
15550
15551
15552 /* helper function for S_aassign_scan().
15553  * check a PAD-related op for commonality and/or set its generation number.
15554  * Returns a boolean indicating whether its shared */
15555
15556 static bool
15557 S_aassign_padcheck(pTHX_ OP* o, bool rhs)
15558 {
15559     if (PAD_COMPNAME_GEN(o->op_targ) == PERL_INT_MAX)
15560         /* lexical used in aliasing */
15561         return TRUE;
15562
15563     if (rhs)
15564         return cBOOL(PAD_COMPNAME_GEN(o->op_targ) == (STRLEN)PL_generation);
15565     else
15566         PAD_COMPNAME_GEN_set(o->op_targ, PL_generation);
15567
15568     return FALSE;
15569 }
15570
15571
15572 /*
15573   Helper function for OPpASSIGN_COMMON* detection in rpeep().
15574   It scans the left or right hand subtree of the aassign op, and returns a
15575   set of flags indicating what sorts of things it found there.
15576   'rhs' indicates whether we're scanning the LHS or RHS. If the former, we
15577   set PL_generation on lexical vars; if the latter, we see if
15578   PL_generation matches.
15579   'scalars_p' is a pointer to a counter of the number of scalar SVs seen.
15580   This fn will increment it by the number seen. It's not intended to
15581   be an accurate count (especially as many ops can push a variable
15582   number of SVs onto the stack); rather it's used as to test whether there
15583   can be at most 1 SV pushed; so it's only meanings are "0, 1, many".
15584 */
15585
15586 static int
15587 S_aassign_scan(pTHX_ OP* o, bool rhs, int *scalars_p)
15588 {
15589     OP *top_op           = o;
15590     OP *effective_top_op = o;
15591     int all_flags = 0;
15592
15593     while (1) {
15594     bool top = o == effective_top_op;
15595     int flags = 0;
15596     OP* next_kid = NULL;
15597
15598     /* first, look for a solitary @_ on the RHS */
15599     if (   rhs
15600         && top
15601         && (o->op_flags & OPf_KIDS)
15602         && OP_TYPE_IS_OR_WAS(o, OP_LIST)
15603     ) {
15604         OP *kid = cUNOPo->op_first;
15605         if (   (   kid->op_type == OP_PUSHMARK
15606                 || kid->op_type == OP_PADRANGE) /* ex-pushmark */
15607             && ((kid = OpSIBLING(kid)))
15608             && !OpHAS_SIBLING(kid)
15609             && kid->op_type == OP_RV2AV
15610             && !(kid->op_flags & OPf_REF)
15611             && !(kid->op_private & (OPpLVAL_INTRO|OPpMAYBE_LVSUB))
15612             && ((kid->op_flags & OPf_WANT) == OPf_WANT_LIST)
15613             && ((kid = cUNOPx(kid)->op_first))
15614             && kid->op_type == OP_GV
15615             && cGVOPx_gv(kid) == PL_defgv
15616         )
15617             flags = AAS_DEFAV;
15618     }
15619
15620     switch (o->op_type) {
15621     case OP_GVSV:
15622         (*scalars_p)++;
15623         all_flags |= AAS_PKG_SCALAR;
15624         goto do_next;
15625
15626     case OP_PADAV:
15627     case OP_PADHV:
15628         (*scalars_p) += 2;
15629         /* if !top, could be e.g. @a[0,1] */
15630         all_flags |=  (top && (o->op_flags & OPf_REF))
15631                         ? ((o->op_private & OPpLVAL_INTRO)
15632                             ? AAS_MY_AGG : AAS_LEX_AGG)
15633                         : AAS_DANGEROUS;
15634         goto do_next;
15635
15636     case OP_PADSV:
15637         {
15638             int comm = S_aassign_padcheck(aTHX_ o, rhs)
15639                         ?  AAS_LEX_SCALAR_COMM : 0;
15640             (*scalars_p)++;
15641             all_flags |= (o->op_private & OPpLVAL_INTRO)
15642                 ? (AAS_MY_SCALAR|comm) : (AAS_LEX_SCALAR|comm);
15643             goto do_next;
15644
15645         }
15646
15647     case OP_RV2AV:
15648     case OP_RV2HV:
15649         (*scalars_p) += 2;
15650         if (cUNOPx(o)->op_first->op_type != OP_GV)
15651             all_flags |= AAS_DANGEROUS; /* @{expr}, %{expr} */
15652         /* @pkg, %pkg */
15653         /* if !top, could be e.g. @a[0,1] */
15654         else if (top && (o->op_flags & OPf_REF))
15655             all_flags |= AAS_PKG_AGG;
15656         else
15657             all_flags |= AAS_DANGEROUS;
15658         goto do_next;
15659
15660     case OP_RV2SV:
15661         (*scalars_p)++;
15662         if (cUNOPx(o)->op_first->op_type != OP_GV) {
15663             (*scalars_p) += 2;
15664             all_flags |= AAS_DANGEROUS; /* ${expr} */
15665         }
15666         else
15667             all_flags |= AAS_PKG_SCALAR; /* $pkg */
15668         goto do_next;
15669
15670     case OP_SPLIT:
15671         if (o->op_private & OPpSPLIT_ASSIGN) {
15672             /* the assign in @a = split() has been optimised away
15673              * and the @a attached directly to the split op
15674              * Treat the array as appearing on the RHS, i.e.
15675              *    ... = (@a = split)
15676              * is treated like
15677              *    ... = @a;
15678              */
15679
15680             if (o->op_flags & OPf_STACKED) {
15681                 /* @{expr} = split() - the array expression is tacked
15682                  * on as an extra child to split - process kid */
15683                 next_kid = cLISTOPo->op_last;
15684                 goto do_next;
15685             }
15686
15687             /* ... else array is directly attached to split op */
15688             (*scalars_p) += 2;
15689             all_flags |= (PL_op->op_private & OPpSPLIT_LEX)
15690                             ? ((o->op_private & OPpLVAL_INTRO)
15691                                 ? AAS_MY_AGG : AAS_LEX_AGG)
15692                             : AAS_PKG_AGG;
15693             goto do_next;
15694         }
15695         (*scalars_p)++;
15696         /* other args of split can't be returned */
15697         all_flags |= AAS_SAFE_SCALAR;
15698         goto do_next;
15699
15700     case OP_UNDEF:
15701         /* undef on LHS following a var is significant, e.g.
15702          *    my $x = 1;
15703          *    @a = (($x, undef) = (2 => $x));
15704          *    # @a shoul be (2,1) not (2,2)
15705          *
15706          * undef on RHS counts as a scalar:
15707          *   ($x, $y)    = (undef, $x); # 2 scalars on RHS: unsafe
15708          */
15709         if ((!rhs && *scalars_p) || rhs)
15710             (*scalars_p)++;
15711         flags = AAS_SAFE_SCALAR;
15712         break;
15713
15714     case OP_PUSHMARK:
15715     case OP_STUB:
15716         /* these are all no-ops; they don't push a potentially common SV
15717          * onto the stack, so they are neither AAS_DANGEROUS nor
15718          * AAS_SAFE_SCALAR */
15719         goto do_next;
15720
15721     case OP_PADRANGE: /* Ignore padrange; checking its siblings is enough */
15722         break;
15723
15724     case OP_NULL:
15725     case OP_LIST:
15726         /* these do nothing, but may have children */
15727         break;
15728
15729     default:
15730         if (PL_opargs[o->op_type] & OA_DANGEROUS) {
15731             (*scalars_p) += 2;
15732             flags = AAS_DANGEROUS;
15733             break;
15734         }
15735
15736         if (   (PL_opargs[o->op_type] & OA_TARGLEX)
15737             && (o->op_private & OPpTARGET_MY))
15738         {
15739             (*scalars_p)++;
15740             all_flags |= S_aassign_padcheck(aTHX_ o, rhs)
15741                             ? AAS_LEX_SCALAR_COMM : AAS_LEX_SCALAR;
15742             goto do_next;
15743         }
15744
15745         /* if its an unrecognised, non-dangerous op, assume that it
15746          * is the cause of at least one safe scalar */
15747         (*scalars_p)++;
15748         flags = AAS_SAFE_SCALAR;
15749         break;
15750     }
15751
15752     all_flags |= flags;
15753
15754     /* by default, process all kids next
15755      * XXX this assumes that all other ops are "transparent" - i.e. that
15756      * they can return some of their children. While this true for e.g.
15757      * sort and grep, it's not true for e.g. map. We really need a
15758      * 'transparent' flag added to regen/opcodes
15759      */
15760     if (o->op_flags & OPf_KIDS) {
15761         next_kid = cUNOPo->op_first;
15762         /* these ops do nothing but may have children; but their
15763          * children should also be treated as top-level */
15764         if (   o == effective_top_op
15765             && (o->op_type == OP_NULL || o->op_type == OP_LIST)
15766         )
15767             effective_top_op = next_kid;
15768     }
15769
15770
15771     /* If next_kid is set, someone in the code above wanted us to process
15772      * that kid and all its remaining siblings.  Otherwise, work our way
15773      * back up the tree */
15774   do_next:
15775     while (!next_kid) {
15776         if (o == top_op)
15777             return all_flags; /* at top; no parents/siblings to try */
15778         if (OpHAS_SIBLING(o)) {
15779             next_kid = o->op_sibparent;
15780             if (o == effective_top_op)
15781                 effective_top_op = next_kid;
15782         }
15783         else
15784             if (o == effective_top_op)
15785                 effective_top_op = o->op_sibparent;
15786             o = o->op_sibparent; /* try parent's next sibling */
15787
15788     }
15789     o = next_kid;
15790     } /* while */
15791
15792 }
15793
15794
15795 /* Check for in place reverse and sort assignments like "@a = reverse @a"
15796    and modify the optree to make them work inplace */
15797
15798 STATIC void
15799 S_inplace_aassign(pTHX_ OP *o) {
15800
15801     OP *modop, *modop_pushmark;
15802     OP *oright;
15803     OP *oleft, *oleft_pushmark;
15804
15805     PERL_ARGS_ASSERT_INPLACE_AASSIGN;
15806
15807     assert((o->op_flags & OPf_WANT) == OPf_WANT_VOID);
15808
15809     assert(cUNOPo->op_first->op_type == OP_NULL);
15810     modop_pushmark = cUNOPx(cUNOPo->op_first)->op_first;
15811     assert(modop_pushmark->op_type == OP_PUSHMARK);
15812     modop = OpSIBLING(modop_pushmark);
15813
15814     if (modop->op_type != OP_SORT && modop->op_type != OP_REVERSE)
15815         return;
15816
15817     /* no other operation except sort/reverse */
15818     if (OpHAS_SIBLING(modop))
15819         return;
15820
15821     assert(cUNOPx(modop)->op_first->op_type == OP_PUSHMARK);
15822     if (!(oright = OpSIBLING(cUNOPx(modop)->op_first))) return;
15823
15824     if (modop->op_flags & OPf_STACKED) {
15825         /* skip sort subroutine/block */
15826         assert(oright->op_type == OP_NULL);
15827         oright = OpSIBLING(oright);
15828     }
15829
15830     assert(OpSIBLING(cUNOPo->op_first)->op_type == OP_NULL);
15831     oleft_pushmark = cUNOPx(OpSIBLING(cUNOPo->op_first))->op_first;
15832     assert(oleft_pushmark->op_type == OP_PUSHMARK);
15833     oleft = OpSIBLING(oleft_pushmark);
15834
15835     /* Check the lhs is an array */
15836     if (!oleft ||
15837         (oleft->op_type != OP_RV2AV && oleft->op_type != OP_PADAV)
15838         || OpHAS_SIBLING(oleft)
15839         || (oleft->op_private & OPpLVAL_INTRO)
15840     )
15841         return;
15842
15843     /* Only one thing on the rhs */
15844     if (OpHAS_SIBLING(oright))
15845         return;
15846
15847     /* check the array is the same on both sides */
15848     if (oleft->op_type == OP_RV2AV) {
15849         if (oright->op_type != OP_RV2AV
15850             || !cUNOPx(oright)->op_first
15851             || cUNOPx(oright)->op_first->op_type != OP_GV
15852             || cUNOPx(oleft )->op_first->op_type != OP_GV
15853             || cGVOPx_gv(cUNOPx(oleft)->op_first) !=
15854                cGVOPx_gv(cUNOPx(oright)->op_first)
15855         )
15856             return;
15857     }
15858     else if (oright->op_type != OP_PADAV
15859         || oright->op_targ != oleft->op_targ
15860     )
15861         return;
15862
15863     /* This actually is an inplace assignment */
15864
15865     modop->op_private |= OPpSORT_INPLACE;
15866
15867     /* transfer MODishness etc from LHS arg to RHS arg */
15868     oright->op_flags = oleft->op_flags;
15869
15870     /* remove the aassign op and the lhs */
15871     op_null(o);
15872     op_null(oleft_pushmark);
15873     if (oleft->op_type == OP_RV2AV && cUNOPx(oleft)->op_first)
15874         op_null(cUNOPx(oleft)->op_first);
15875     op_null(oleft);
15876 }
15877
15878
15879
15880 /* S_maybe_multideref(): given an op_next chain of ops beginning at 'start'
15881  * that potentially represent a series of one or more aggregate derefs
15882  * (such as $a->[1]{$key}), examine the chain, and if appropriate, convert
15883  * the whole chain to a single OP_MULTIDEREF op (maybe with a few
15884  * additional ops left in too).
15885  *
15886  * The caller will have already verified that the first few ops in the
15887  * chain following 'start' indicate a multideref candidate, and will have
15888  * set 'orig_o' to the point further on in the chain where the first index
15889  * expression (if any) begins.  'orig_action' specifies what type of
15890  * beginning has already been determined by the ops between start..orig_o
15891  * (e.g.  $lex_ary[], $pkg_ary->{}, expr->[], etc).
15892  *
15893  * 'hints' contains any hints flags that need adding (currently just
15894  * OPpHINT_STRICT_REFS) as found in any rv2av/hv skipped by the caller.
15895  */
15896
15897 STATIC void
15898 S_maybe_multideref(pTHX_ OP *start, OP *orig_o, UV orig_action, U8 hints)
15899 {
15900     int pass;
15901     UNOP_AUX_item *arg_buf = NULL;
15902     bool reset_start_targ  = FALSE; /* start->op_targ needs zeroing */
15903     int index_skip         = -1;    /* don't output index arg on this action */
15904
15905     /* similar to regex compiling, do two passes; the first pass
15906      * determines whether the op chain is convertible and calculates the
15907      * buffer size; the second pass populates the buffer and makes any
15908      * changes necessary to ops (such as moving consts to the pad on
15909      * threaded builds).
15910      *
15911      * NB: for things like Coverity, note that both passes take the same
15912      * path through the logic tree (except for 'if (pass)' bits), since
15913      * both passes are following the same op_next chain; and in
15914      * particular, if it would return early on the second pass, it would
15915      * already have returned early on the first pass.
15916      */
15917     for (pass = 0; pass < 2; pass++) {
15918         OP *o                = orig_o;
15919         UV action            = orig_action;
15920         OP *first_elem_op    = NULL;  /* first seen aelem/helem */
15921         OP *top_op           = NULL;  /* highest [ah]elem/exists/del/rv2[ah]v */
15922         int action_count     = 0;     /* number of actions seen so far */
15923         int action_ix        = 0;     /* action_count % (actions per IV) */
15924         bool next_is_hash    = FALSE; /* is the next lookup to be a hash? */
15925         bool is_last         = FALSE; /* no more derefs to follow */
15926         bool maybe_aelemfast = FALSE; /* we can replace with aelemfast? */
15927         UV action_word       = 0;     /* all actions so far */
15928         UNOP_AUX_item *arg     = arg_buf;
15929         UNOP_AUX_item *action_ptr = arg_buf;
15930
15931         arg++; /* reserve slot for first action word */
15932
15933         switch (action) {
15934         case MDEREF_HV_gvsv_vivify_rv2hv_helem:
15935         case MDEREF_HV_gvhv_helem:
15936             next_is_hash = TRUE;
15937             /* FALLTHROUGH */
15938         case MDEREF_AV_gvsv_vivify_rv2av_aelem:
15939         case MDEREF_AV_gvav_aelem:
15940             if (pass) {
15941 #ifdef USE_ITHREADS
15942                 arg->pad_offset = cPADOPx(start)->op_padix;
15943                 /* stop it being swiped when nulled */
15944                 cPADOPx(start)->op_padix = 0;
15945 #else
15946                 arg->sv = cSVOPx(start)->op_sv;
15947                 cSVOPx(start)->op_sv = NULL;
15948 #endif
15949             }
15950             arg++;
15951             break;
15952
15953         case MDEREF_HV_padhv_helem:
15954         case MDEREF_HV_padsv_vivify_rv2hv_helem:
15955             next_is_hash = TRUE;
15956             /* FALLTHROUGH */
15957         case MDEREF_AV_padav_aelem:
15958         case MDEREF_AV_padsv_vivify_rv2av_aelem:
15959             if (pass) {
15960                 arg->pad_offset = start->op_targ;
15961                 /* we skip setting op_targ = 0 for now, since the intact
15962                  * OP_PADXV is needed by S_check_hash_fields_and_hekify */
15963                 reset_start_targ = TRUE;
15964             }
15965             arg++;
15966             break;
15967
15968         case MDEREF_HV_pop_rv2hv_helem:
15969             next_is_hash = TRUE;
15970             /* FALLTHROUGH */
15971         case MDEREF_AV_pop_rv2av_aelem:
15972             break;
15973
15974         default:
15975             NOT_REACHED; /* NOTREACHED */
15976             return;
15977         }
15978
15979         while (!is_last) {
15980             /* look for another (rv2av/hv; get index;
15981              * aelem/helem/exists/delele) sequence */
15982
15983             OP *kid;
15984             bool is_deref;
15985             bool ok;
15986             UV index_type = MDEREF_INDEX_none;
15987
15988             if (action_count) {
15989                 /* if this is not the first lookup, consume the rv2av/hv  */
15990
15991                 /* for N levels of aggregate lookup, we normally expect
15992                  * that the first N-1 [ah]elem ops will be flagged as
15993                  * /DEREF (so they autovivifiy if necessary), and the last
15994                  * lookup op not to be.
15995                  * For other things (like @{$h{k1}{k2}}) extra scope or
15996                  * leave ops can appear, so abandon the effort in that
15997                  * case */
15998                 if (o->op_type != OP_RV2AV && o->op_type != OP_RV2HV)
15999                     return;
16000
16001                 /* rv2av or rv2hv sKR/1 */
16002
16003                 ASSUME(!(o->op_flags & ~(OPf_WANT|OPf_KIDS|OPf_PARENS
16004                                             |OPf_REF|OPf_MOD|OPf_SPECIAL)));
16005                 if (o->op_flags != (OPf_WANT_SCALAR|OPf_KIDS|OPf_REF))
16006                     return;
16007
16008                 /* at this point, we wouldn't expect any of these
16009                  * possible private flags:
16010                  * OPpMAYBE_LVSUB, OPpOUR_INTRO, OPpLVAL_INTRO
16011                  * OPpTRUEBOOL, OPpMAYBE_TRUEBOOL (rv2hv only)
16012                  */
16013                 ASSUME(!(o->op_private &
16014                     ~(OPpHINT_STRICT_REFS|OPpARG1_MASK|OPpSLICEWARNING)));
16015
16016                 hints = (o->op_private & OPpHINT_STRICT_REFS);
16017
16018                 /* make sure the type of the previous /DEREF matches the
16019                  * type of the next lookup */
16020                 ASSUME(o->op_type == (next_is_hash ? OP_RV2HV : OP_RV2AV));
16021                 top_op = o;
16022
16023                 action = next_is_hash
16024                             ? MDEREF_HV_vivify_rv2hv_helem
16025                             : MDEREF_AV_vivify_rv2av_aelem;
16026                 o = o->op_next;
16027             }
16028
16029             /* if this is the second pass, and we're at the depth where
16030              * previously we encountered a non-simple index expression,
16031              * stop processing the index at this point */
16032             if (action_count != index_skip) {
16033
16034                 /* look for one or more simple ops that return an array
16035                  * index or hash key */
16036
16037                 switch (o->op_type) {
16038                 case OP_PADSV:
16039                     /* it may be a lexical var index */
16040                     ASSUME(!(o->op_flags & ~(OPf_WANT|OPf_PARENS
16041                                             |OPf_REF|OPf_MOD|OPf_SPECIAL)));
16042                     ASSUME(!(o->op_private &
16043                             ~(OPpPAD_STATE|OPpDEREF|OPpLVAL_INTRO)));
16044
16045                     if (   OP_GIMME(o,0) == G_SCALAR
16046                         && !(o->op_flags & (OPf_REF|OPf_MOD))
16047                         && o->op_private == 0)
16048                     {
16049                         if (pass)
16050                             arg->pad_offset = o->op_targ;
16051                         arg++;
16052                         index_type = MDEREF_INDEX_padsv;
16053                         o = o->op_next;
16054                     }
16055                     break;
16056
16057                 case OP_CONST:
16058                     if (next_is_hash) {
16059                         /* it's a constant hash index */
16060                         if (!(SvFLAGS(cSVOPo_sv) & (SVf_IOK|SVf_NOK|SVf_POK)))
16061                             /* "use constant foo => FOO; $h{+foo}" for
16062                              * some weird FOO, can leave you with constants
16063                              * that aren't simple strings. It's not worth
16064                              * the extra hassle for those edge cases */
16065                             break;
16066
16067                         {
16068                             UNOP *rop = NULL;
16069                             OP * helem_op = o->op_next;
16070
16071                             ASSUME(   helem_op->op_type == OP_HELEM
16072                                    || helem_op->op_type == OP_NULL
16073                                    || pass == 0);
16074                             if (helem_op->op_type == OP_HELEM) {
16075                                 rop = (UNOP*)(((BINOP*)helem_op)->op_first);
16076                                 if (   helem_op->op_private & OPpLVAL_INTRO
16077                                     || rop->op_type != OP_RV2HV
16078                                 )
16079                                     rop = NULL;
16080                             }
16081                             /* on first pass just check; on second pass
16082                              * hekify */
16083                             S_check_hash_fields_and_hekify(aTHX_ rop, cSVOPo,
16084                                                             pass);
16085                         }
16086
16087                         if (pass) {
16088 #ifdef USE_ITHREADS
16089                             /* Relocate sv to the pad for thread safety */
16090                             op_relocate_sv(&cSVOPo->op_sv, &o->op_targ);
16091                             arg->pad_offset = o->op_targ;
16092                             o->op_targ = 0;
16093 #else
16094                             arg->sv = cSVOPx_sv(o);
16095 #endif
16096                         }
16097                     }
16098                     else {
16099                         /* it's a constant array index */
16100                         IV iv;
16101                         SV *ix_sv = cSVOPo->op_sv;
16102                         if (!SvIOK(ix_sv))
16103                             break;
16104                         iv = SvIV(ix_sv);
16105
16106                         if (   action_count == 0
16107                             && iv >= -128
16108                             && iv <= 127
16109                             && (   action == MDEREF_AV_padav_aelem
16110                                 || action == MDEREF_AV_gvav_aelem)
16111                         )
16112                             maybe_aelemfast = TRUE;
16113
16114                         if (pass) {
16115                             arg->iv = iv;
16116                             SvREFCNT_dec_NN(cSVOPo->op_sv);
16117                         }
16118                     }
16119                     if (pass)
16120                         /* we've taken ownership of the SV */
16121                         cSVOPo->op_sv = NULL;
16122                     arg++;
16123                     index_type = MDEREF_INDEX_const;
16124                     o = o->op_next;
16125                     break;
16126
16127                 case OP_GV:
16128                     /* it may be a package var index */
16129
16130                     ASSUME(!(o->op_flags & ~(OPf_WANT|OPf_PARENS|OPf_SPECIAL)));
16131                     ASSUME(!(o->op_private & ~(OPpEARLY_CV)));
16132                     if (  (o->op_flags & ~(OPf_PARENS|OPf_SPECIAL)) != OPf_WANT_SCALAR
16133                         || o->op_private != 0
16134                     )
16135                         break;
16136
16137                     kid = o->op_next;
16138                     if (kid->op_type != OP_RV2SV)
16139                         break;
16140
16141                     ASSUME(!(kid->op_flags &
16142                             ~(OPf_WANT|OPf_KIDS|OPf_MOD|OPf_REF
16143                              |OPf_SPECIAL|OPf_PARENS)));
16144                     ASSUME(!(kid->op_private &
16145                                     ~(OPpARG1_MASK
16146                                      |OPpHINT_STRICT_REFS|OPpOUR_INTRO
16147                                      |OPpDEREF|OPpLVAL_INTRO)));
16148                     if(   (kid->op_flags &~ OPf_PARENS)
16149                             != (OPf_WANT_SCALAR|OPf_KIDS)
16150                        || (kid->op_private & ~(OPpARG1_MASK|HINT_STRICT_REFS))
16151                     )
16152                         break;
16153
16154                     if (pass) {
16155 #ifdef USE_ITHREADS
16156                         arg->pad_offset = cPADOPx(o)->op_padix;
16157                         /* stop it being swiped when nulled */
16158                         cPADOPx(o)->op_padix = 0;
16159 #else
16160                         arg->sv = cSVOPx(o)->op_sv;
16161                         cSVOPo->op_sv = NULL;
16162 #endif
16163                     }
16164                     arg++;
16165                     index_type = MDEREF_INDEX_gvsv;
16166                     o = kid->op_next;
16167                     break;
16168
16169                 } /* switch */
16170             } /* action_count != index_skip */
16171
16172             action |= index_type;
16173
16174
16175             /* at this point we have either:
16176              *   * detected what looks like a simple index expression,
16177              *     and expect the next op to be an [ah]elem, or
16178              *     an nulled  [ah]elem followed by a delete or exists;
16179              *  * found a more complex expression, so something other
16180              *    than the above follows.
16181              */
16182
16183             /* possibly an optimised away [ah]elem (where op_next is
16184              * exists or delete) */
16185             if (o->op_type == OP_NULL)
16186                 o = o->op_next;
16187
16188             /* at this point we're looking for an OP_AELEM, OP_HELEM,
16189              * OP_EXISTS or OP_DELETE */
16190
16191             /* if a custom array/hash access checker is in scope,
16192              * abandon optimisation attempt */
16193             if (  (o->op_type == OP_AELEM || o->op_type == OP_HELEM)
16194                && PL_check[o->op_type] != Perl_ck_null)
16195                 return;
16196             /* similarly for customised exists and delete */
16197             if (  (o->op_type == OP_EXISTS)
16198                && PL_check[o->op_type] != Perl_ck_exists)
16199                 return;
16200             if (  (o->op_type == OP_DELETE)
16201                && PL_check[o->op_type] != Perl_ck_delete)
16202                 return;
16203
16204             if (   o->op_type != OP_AELEM
16205                 || (o->op_private &
16206                       (OPpLVAL_INTRO|OPpLVAL_DEFER|OPpDEREF|OPpMAYBE_LVSUB))
16207                 )
16208                 maybe_aelemfast = FALSE;
16209
16210             /* look for aelem/helem/exists/delete. If it's not the last elem
16211              * lookup, it *must* have OPpDEREF_AV/HV, but not many other
16212              * flags; if it's the last, then it mustn't have
16213              * OPpDEREF_AV/HV, but may have lots of other flags, like
16214              * OPpLVAL_INTRO etc
16215              */
16216
16217             if (   index_type == MDEREF_INDEX_none
16218                 || (   o->op_type != OP_AELEM  && o->op_type != OP_HELEM
16219                     && o->op_type != OP_EXISTS && o->op_type != OP_DELETE)
16220             )
16221                 ok = FALSE;
16222             else {
16223                 /* we have aelem/helem/exists/delete with valid simple index */
16224
16225                 is_deref =    (o->op_type == OP_AELEM || o->op_type == OP_HELEM)
16226                            && (   (o->op_private & OPpDEREF) == OPpDEREF_AV
16227                                || (o->op_private & OPpDEREF) == OPpDEREF_HV);
16228
16229                 /* This doesn't make much sense but is legal:
16230                  *    @{ local $x[0][0] } = 1
16231                  * Since scope exit will undo the autovivification,
16232                  * don't bother in the first place. The OP_LEAVE
16233                  * assertion is in case there are other cases of both
16234                  * OPpLVAL_INTRO and OPpDEREF which don't include a scope
16235                  * exit that would undo the local - in which case this
16236                  * block of code would need rethinking.
16237                  */
16238                 if (is_deref && (o->op_private & OPpLVAL_INTRO)) {
16239 #ifdef DEBUGGING
16240                     OP *n = o->op_next;
16241                     while (n && (  n->op_type == OP_NULL
16242                                 || n->op_type == OP_LIST
16243                                 || n->op_type == OP_SCALAR))
16244                         n = n->op_next;
16245                     assert(n && n->op_type == OP_LEAVE);
16246 #endif
16247                     o->op_private &= ~OPpDEREF;
16248                     is_deref = FALSE;
16249                 }
16250
16251                 if (is_deref) {
16252                     ASSUME(!(o->op_flags &
16253                                  ~(OPf_WANT|OPf_KIDS|OPf_MOD|OPf_PARENS)));
16254                     ASSUME(!(o->op_private & ~(OPpARG2_MASK|OPpDEREF)));
16255
16256                     ok =    (o->op_flags &~ OPf_PARENS)
16257                                == (OPf_WANT_SCALAR|OPf_KIDS|OPf_MOD)
16258                          && !(o->op_private & ~(OPpDEREF|OPpARG2_MASK));
16259                 }
16260                 else if (o->op_type == OP_EXISTS) {
16261                     ASSUME(!(o->op_flags & ~(OPf_WANT|OPf_KIDS|OPf_PARENS
16262                                 |OPf_REF|OPf_MOD|OPf_SPECIAL)));
16263                     ASSUME(!(o->op_private & ~(OPpARG1_MASK|OPpEXISTS_SUB)));
16264                     ok =  !(o->op_private & ~OPpARG1_MASK);
16265                 }
16266                 else if (o->op_type == OP_DELETE) {
16267                     ASSUME(!(o->op_flags & ~(OPf_WANT|OPf_KIDS|OPf_PARENS
16268                                 |OPf_REF|OPf_MOD|OPf_SPECIAL)));
16269                     ASSUME(!(o->op_private &
16270                                     ~(OPpARG1_MASK|OPpSLICE|OPpLVAL_INTRO)));
16271                     /* don't handle slices or 'local delete'; the latter
16272                      * is fairly rare, and has a complex runtime */
16273                     ok =  !(o->op_private & ~OPpARG1_MASK);
16274                     if (OP_TYPE_IS_OR_WAS(cUNOPo->op_first, OP_AELEM))
16275                         /* skip handling run-tome error */
16276                         ok = (ok && cBOOL(o->op_flags & OPf_SPECIAL));
16277                 }
16278                 else {
16279                     ASSUME(o->op_type == OP_AELEM || o->op_type == OP_HELEM);
16280                     ASSUME(!(o->op_flags & ~(OPf_WANT|OPf_KIDS|OPf_MOD
16281                                             |OPf_PARENS|OPf_REF|OPf_SPECIAL)));
16282                     ASSUME(!(o->op_private & ~(OPpARG2_MASK|OPpMAYBE_LVSUB
16283                                     |OPpLVAL_DEFER|OPpDEREF|OPpLVAL_INTRO)));
16284                     ok = (o->op_private & OPpDEREF) != OPpDEREF_SV;
16285                 }
16286             }
16287
16288             if (ok) {
16289                 if (!first_elem_op)
16290                     first_elem_op = o;
16291                 top_op = o;
16292                 if (is_deref) {
16293                     next_is_hash = cBOOL((o->op_private & OPpDEREF) == OPpDEREF_HV);
16294                     o = o->op_next;
16295                 }
16296                 else {
16297                     is_last = TRUE;
16298                     action |= MDEREF_FLAG_last;
16299                 }
16300             }
16301             else {
16302                 /* at this point we have something that started
16303                  * promisingly enough (with rv2av or whatever), but failed
16304                  * to find a simple index followed by an
16305                  * aelem/helem/exists/delete. If this is the first action,
16306                  * give up; but if we've already seen at least one
16307                  * aelem/helem, then keep them and add a new action with
16308                  * MDEREF_INDEX_none, which causes it to do the vivify
16309                  * from the end of the previous lookup, and do the deref,
16310                  * but stop at that point. So $a[0][expr] will do one
16311                  * av_fetch, vivify and deref, then continue executing at
16312                  * expr */
16313                 if (!action_count)
16314                     return;
16315                 is_last = TRUE;
16316                 index_skip = action_count;
16317                 action |= MDEREF_FLAG_last;
16318                 if (index_type != MDEREF_INDEX_none)
16319                     arg--;
16320             }
16321
16322             action_word |= (action << (action_ix * MDEREF_SHIFT));
16323             action_ix++;
16324             action_count++;
16325             /* if there's no space for the next action, reserve a new slot
16326              * for it *before* we start adding args for that action */
16327             if ((action_ix + 1) * MDEREF_SHIFT > UVSIZE*8) {
16328                 if (pass)
16329                     action_ptr->uv = action_word;
16330                 action_word = 0;
16331                 action_ptr = arg;
16332                 arg++;
16333                 action_ix = 0;
16334             }
16335         } /* while !is_last */
16336
16337         /* success! */
16338
16339         if (!action_ix)
16340             /* slot reserved for next action word not now needed */
16341             arg--;
16342         else if (pass)
16343             action_ptr->uv = action_word;
16344
16345         if (pass) {
16346             OP *mderef;
16347             OP *p, *q;
16348
16349             mderef = newUNOP_AUX(OP_MULTIDEREF, 0, NULL, arg_buf);
16350             if (index_skip == -1) {
16351                 mderef->op_flags = o->op_flags
16352                         & (OPf_WANT|OPf_MOD|(next_is_hash ? OPf_SPECIAL : 0));
16353                 if (o->op_type == OP_EXISTS)
16354                     mderef->op_private = OPpMULTIDEREF_EXISTS;
16355                 else if (o->op_type == OP_DELETE)
16356                     mderef->op_private = OPpMULTIDEREF_DELETE;
16357                 else
16358                     mderef->op_private = o->op_private
16359                         & (OPpMAYBE_LVSUB|OPpLVAL_DEFER|OPpLVAL_INTRO);
16360             }
16361             /* accumulate strictness from every level (although I don't think
16362              * they can actually vary) */
16363             mderef->op_private |= hints;
16364
16365             /* integrate the new multideref op into the optree and the
16366              * op_next chain.
16367              *
16368              * In general an op like aelem or helem has two child
16369              * sub-trees: the aggregate expression (a_expr) and the
16370              * index expression (i_expr):
16371              *
16372              *     aelem
16373              *       |
16374              *     a_expr - i_expr
16375              *
16376              * The a_expr returns an AV or HV, while the i-expr returns an
16377              * index. In general a multideref replaces most or all of a
16378              * multi-level tree, e.g.
16379              *
16380              *     exists
16381              *       |
16382              *     ex-aelem
16383              *       |
16384              *     rv2av  - i_expr1
16385              *       |
16386              *     helem
16387              *       |
16388              *     rv2hv  - i_expr2
16389              *       |
16390              *     aelem
16391              *       |
16392              *     a_expr - i_expr3
16393              *
16394              * With multideref, all the i_exprs will be simple vars or
16395              * constants, except that i_expr1 may be arbitrary in the case
16396              * of MDEREF_INDEX_none.
16397              *
16398              * The bottom-most a_expr will be either:
16399              *   1) a simple var (so padXv or gv+rv2Xv);
16400              *   2) a simple scalar var dereferenced (e.g. $r->[0]):
16401              *      so a simple var with an extra rv2Xv;
16402              *   3) or an arbitrary expression.
16403              *
16404              * 'start', the first op in the execution chain, will point to
16405              *   1),2): the padXv or gv op;
16406              *   3):    the rv2Xv which forms the last op in the a_expr
16407              *          execution chain, and the top-most op in the a_expr
16408              *          subtree.
16409              *
16410              * For all cases, the 'start' node is no longer required,
16411              * but we can't free it since one or more external nodes
16412              * may point to it. E.g. consider
16413              *     $h{foo} = $a ? $b : $c
16414              * Here, both the op_next and op_other branches of the
16415              * cond_expr point to the gv[*h] of the hash expression, so
16416              * we can't free the 'start' op.
16417              *
16418              * For expr->[...], we need to save the subtree containing the
16419              * expression; for the other cases, we just need to save the
16420              * start node.
16421              * So in all cases, we null the start op and keep it around by
16422              * making it the child of the multideref op; for the expr->
16423              * case, the expr will be a subtree of the start node.
16424              *
16425              * So in the simple 1,2 case the  optree above changes to
16426              *
16427              *     ex-exists
16428              *       |
16429              *     multideref
16430              *       |
16431              *     ex-gv (or ex-padxv)
16432              *
16433              *  with the op_next chain being
16434              *
16435              *  -> ex-gv -> multideref -> op-following-ex-exists ->
16436              *
16437              *  In the 3 case, we have
16438              *
16439              *     ex-exists
16440              *       |
16441              *     multideref
16442              *       |
16443              *     ex-rv2xv
16444              *       |
16445              *    rest-of-a_expr
16446              *      subtree
16447              *
16448              *  and
16449              *
16450              *  -> rest-of-a_expr subtree ->
16451              *    ex-rv2xv -> multideref -> op-following-ex-exists ->
16452              *
16453              *
16454              * Where the last i_expr is non-simple (i.e. MDEREF_INDEX_none,
16455              * e.g. $a[0]{foo}[$x+1], the next rv2xv is nulled and the
16456              * multideref attached as the child, e.g.
16457              *
16458              *     exists
16459              *       |
16460              *     ex-aelem
16461              *       |
16462              *     ex-rv2av  - i_expr1
16463              *       |
16464              *     multideref
16465              *       |
16466              *     ex-whatever
16467              *
16468              */
16469
16470             /* if we free this op, don't free the pad entry */
16471             if (reset_start_targ)
16472                 start->op_targ = 0;
16473
16474
16475             /* Cut the bit we need to save out of the tree and attach to
16476              * the multideref op, then free the rest of the tree */
16477
16478             /* find parent of node to be detached (for use by splice) */
16479             p = first_elem_op;
16480             if (   orig_action == MDEREF_AV_pop_rv2av_aelem
16481                 || orig_action == MDEREF_HV_pop_rv2hv_helem)
16482             {
16483                 /* there is an arbitrary expression preceding us, e.g.
16484                  * expr->[..]? so we need to save the 'expr' subtree */
16485                 if (p->op_type == OP_EXISTS || p->op_type == OP_DELETE)
16486                     p = cUNOPx(p)->op_first;
16487                 ASSUME(   start->op_type == OP_RV2AV
16488                        || start->op_type == OP_RV2HV);
16489             }
16490             else {
16491                 /* either a padXv or rv2Xv+gv, maybe with an ex-Xelem
16492                  * above for exists/delete. */
16493                 while (   (p->op_flags & OPf_KIDS)
16494                        && cUNOPx(p)->op_first != start
16495                 )
16496                     p = cUNOPx(p)->op_first;
16497             }
16498             ASSUME(cUNOPx(p)->op_first == start);
16499
16500             /* detach from main tree, and re-attach under the multideref */
16501             op_sibling_splice(mderef, NULL, 0,
16502                     op_sibling_splice(p, NULL, 1, NULL));
16503             op_null(start);
16504
16505             start->op_next = mderef;
16506
16507             mderef->op_next = index_skip == -1 ? o->op_next : o;
16508
16509             /* excise and free the original tree, and replace with
16510              * the multideref op */
16511             p = op_sibling_splice(top_op, NULL, -1, mderef);
16512             while (p) {
16513                 q = OpSIBLING(p);
16514                 op_free(p);
16515                 p = q;
16516             }
16517             op_null(top_op);
16518         }
16519         else {
16520             Size_t size = arg - arg_buf;
16521
16522             if (maybe_aelemfast && action_count == 1)
16523                 return;
16524
16525             arg_buf = (UNOP_AUX_item*)PerlMemShared_malloc(
16526                                 sizeof(UNOP_AUX_item) * (size + 1));
16527             /* for dumping etc: store the length in a hidden first slot;
16528              * we set the op_aux pointer to the second slot */
16529             arg_buf->uv = size;
16530             arg_buf++;
16531         }
16532     } /* for (pass = ...) */
16533 }
16534
16535 /* See if the ops following o are such that o will always be executed in
16536  * boolean context: that is, the SV which o pushes onto the stack will
16537  * only ever be consumed by later ops via SvTRUE(sv) or similar.
16538  * If so, set a suitable private flag on o. Normally this will be
16539  * bool_flag; but see below why maybe_flag is needed too.
16540  *
16541  * Typically the two flags you pass will be the generic OPpTRUEBOOL and
16542  * OPpMAYBE_TRUEBOOL, buts it's possible that for some ops those bits may
16543  * already be taken, so you'll have to give that op two different flags.
16544  *
16545  * More explanation of 'maybe_flag' and 'safe_and' parameters.
16546  * The binary logical ops &&, ||, // (plus 'if' and 'unless' which use
16547  * those underlying ops) short-circuit, which means that rather than
16548  * necessarily returning a truth value, they may return the LH argument,
16549  * which may not be boolean. For example in $x = (keys %h || -1), keys
16550  * should return a key count rather than a boolean, even though its
16551  * sort-of being used in boolean context.
16552  *
16553  * So we only consider such logical ops to provide boolean context to
16554  * their LH argument if they themselves are in void or boolean context.
16555  * However, sometimes the context isn't known until run-time. In this
16556  * case the op is marked with the maybe_flag flag it.
16557  *
16558  * Consider the following.
16559  *
16560  *     sub f { ....;  if (%h) { .... } }
16561  *
16562  * This is actually compiled as
16563  *
16564  *     sub f { ....;  %h && do { .... } }
16565  *
16566  * Here we won't know until runtime whether the final statement (and hence
16567  * the &&) is in void context and so is safe to return a boolean value.
16568  * So mark o with maybe_flag rather than the bool_flag.
16569  * Note that there is cost associated with determining context at runtime
16570  * (e.g. a call to block_gimme()), so it may not be worth setting (at
16571  * compile time) and testing (at runtime) maybe_flag if the scalar verses
16572  * boolean costs savings are marginal.
16573  *
16574  * However, we can do slightly better with && (compared to || and //):
16575  * this op only returns its LH argument when that argument is false. In
16576  * this case, as long as the op promises to return a false value which is
16577  * valid in both boolean and scalar contexts, we can mark an op consumed
16578  * by && with bool_flag rather than maybe_flag.
16579  * For example as long as pp_padhv and pp_rv2hv return &PL_sv_zero rather
16580  * than &PL_sv_no for a false result in boolean context, then it's safe. An
16581  * op which promises to handle this case is indicated by setting safe_and
16582  * to true.
16583  */
16584
16585 static void
16586 S_check_for_bool_cxt(OP*o, bool safe_and, U8 bool_flag, U8 maybe_flag)
16587 {
16588     OP *lop;
16589     U8 flag = 0;
16590
16591     assert((o->op_flags & OPf_WANT) == OPf_WANT_SCALAR);
16592
16593     /* OPpTARGET_MY and boolean context probably don't mix well.
16594      * If someone finds a valid use case, maybe add an extra flag to this
16595      * function which indicates its safe to do so for this op? */
16596     assert(!(   (PL_opargs[o->op_type] & OA_TARGLEX)
16597              && (o->op_private & OPpTARGET_MY)));
16598
16599     lop = o->op_next;
16600
16601     while (lop) {
16602         switch (lop->op_type) {
16603         case OP_NULL:
16604         case OP_SCALAR:
16605             break;
16606
16607         /* these two consume the stack argument in the scalar case,
16608          * and treat it as a boolean in the non linenumber case */
16609         case OP_FLIP:
16610         case OP_FLOP:
16611             if (   ((lop->op_flags & OPf_WANT) == OPf_WANT_LIST)
16612                 || (lop->op_private & OPpFLIP_LINENUM))
16613             {
16614                 lop = NULL;
16615                 break;
16616             }
16617             /* FALLTHROUGH */
16618         /* these never leave the original value on the stack */
16619         case OP_NOT:
16620         case OP_XOR:
16621         case OP_COND_EXPR:
16622         case OP_GREPWHILE:
16623             flag = bool_flag;
16624             lop = NULL;
16625             break;
16626
16627         /* OR DOR and AND evaluate their arg as a boolean, but then may
16628          * leave the original scalar value on the stack when following the
16629          * op_next route. If not in void context, we need to ensure
16630          * that whatever follows consumes the arg only in boolean context
16631          * too.
16632          */
16633         case OP_AND:
16634             if (safe_and) {
16635                 flag = bool_flag;
16636                 lop = NULL;
16637                 break;
16638             }
16639             /* FALLTHROUGH */
16640         case OP_OR:
16641         case OP_DOR:
16642             if ((lop->op_flags & OPf_WANT) == OPf_WANT_VOID) {
16643                 flag = bool_flag;
16644                 lop = NULL;
16645             }
16646             else if (!(lop->op_flags & OPf_WANT)) {
16647                 /* unknown context - decide at runtime */
16648                 flag = maybe_flag;
16649                 lop = NULL;
16650             }
16651             break;
16652
16653         default:
16654             lop = NULL;
16655             break;
16656         }
16657
16658         if (lop)
16659             lop = lop->op_next;
16660     }
16661
16662     o->op_private |= flag;
16663 }
16664
16665
16666
16667 /* mechanism for deferring recursion in rpeep() */
16668
16669 #define MAX_DEFERRED 4
16670
16671 #define DEFER(o) \
16672   STMT_START { \
16673     if (defer_ix == (MAX_DEFERRED-1)) { \
16674         OP **defer = defer_queue[defer_base]; \
16675         CALL_RPEEP(*defer); \
16676         S_prune_chain_head(defer); \
16677         defer_base = (defer_base + 1) % MAX_DEFERRED; \
16678         defer_ix--; \
16679     } \
16680     defer_queue[(defer_base + ++defer_ix) % MAX_DEFERRED] = &(o); \
16681   } STMT_END
16682
16683 #define IS_AND_OP(o)   (o->op_type == OP_AND)
16684 #define IS_OR_OP(o)    (o->op_type == OP_OR)
16685
16686
16687 /* A peephole optimizer.  We visit the ops in the order they're to execute.
16688  * See the comments at the top of this file for more details about when
16689  * peep() is called */
16690
16691 void
16692 Perl_rpeep(pTHX_ OP *o)
16693 {
16694     OP* oldop = NULL;
16695     OP* oldoldop = NULL;
16696     OP** defer_queue[MAX_DEFERRED]; /* small queue of deferred branches */
16697     int defer_base = 0;
16698     int defer_ix = -1;
16699
16700     if (!o || o->op_opt)
16701         return;
16702
16703     assert(o->op_type != OP_FREED);
16704
16705     ENTER;
16706     SAVEOP();
16707     SAVEVPTR(PL_curcop);
16708     for (;; o = o->op_next) {
16709         if (o && o->op_opt)
16710             o = NULL;
16711         if (!o) {
16712             while (defer_ix >= 0) {
16713                 OP **defer =
16714                         defer_queue[(defer_base + defer_ix--) % MAX_DEFERRED];
16715                 CALL_RPEEP(*defer);
16716                 S_prune_chain_head(defer);
16717             }
16718             break;
16719         }
16720
16721       redo:
16722
16723         /* oldoldop -> oldop -> o should be a chain of 3 adjacent ops */
16724         assert(!oldoldop || oldoldop->op_next == oldop);
16725         assert(!oldop    || oldop->op_next    == o);
16726
16727         /* By default, this op has now been optimised. A couple of cases below
16728            clear this again.  */
16729         o->op_opt = 1;
16730         PL_op = o;
16731
16732         /* look for a series of 1 or more aggregate derefs, e.g.
16733          *   $a[1]{foo}[$i]{$k}
16734          * and replace with a single OP_MULTIDEREF op.
16735          * Each index must be either a const, or a simple variable,
16736          *
16737          * First, look for likely combinations of starting ops,
16738          * corresponding to (global and lexical variants of)
16739          *     $a[...]   $h{...}
16740          *     $r->[...] $r->{...}
16741          *     (preceding expression)->[...]
16742          *     (preceding expression)->{...}
16743          * and if so, call maybe_multideref() to do a full inspection
16744          * of the op chain and if appropriate, replace with an
16745          * OP_MULTIDEREF
16746          */
16747         {
16748             UV action;
16749             OP *o2 = o;
16750             U8 hints = 0;
16751
16752             switch (o2->op_type) {
16753             case OP_GV:
16754                 /* $pkg[..]   :   gv[*pkg]
16755                  * $pkg->[...]:   gv[*pkg]; rv2sv sKM/DREFAV */
16756
16757                 /* Fail if there are new op flag combinations that we're
16758                  * not aware of, rather than:
16759                  *  * silently failing to optimise, or
16760                  *  * silently optimising the flag away.
16761                  * If this ASSUME starts failing, examine what new flag
16762                  * has been added to the op, and decide whether the
16763                  * optimisation should still occur with that flag, then
16764                  * update the code accordingly. This applies to all the
16765                  * other ASSUMEs in the block of code too.
16766                  */
16767                 ASSUME(!(o2->op_flags &
16768                             ~(OPf_WANT|OPf_MOD|OPf_PARENS|OPf_SPECIAL)));
16769                 ASSUME(!(o2->op_private & ~OPpEARLY_CV));
16770
16771                 o2 = o2->op_next;
16772
16773                 if (o2->op_type == OP_RV2AV) {
16774                     action = MDEREF_AV_gvav_aelem;
16775                     goto do_deref;
16776                 }
16777
16778                 if (o2->op_type == OP_RV2HV) {
16779                     action = MDEREF_HV_gvhv_helem;
16780                     goto do_deref;
16781                 }
16782
16783                 if (o2->op_type != OP_RV2SV)
16784                     break;
16785
16786                 /* at this point we've seen gv,rv2sv, so the only valid
16787                  * construct left is $pkg->[] or $pkg->{} */
16788
16789                 ASSUME(!(o2->op_flags & OPf_STACKED));
16790                 if ((o2->op_flags & (OPf_WANT|OPf_REF|OPf_MOD|OPf_SPECIAL))
16791                             != (OPf_WANT_SCALAR|OPf_MOD))
16792                     break;
16793
16794                 ASSUME(!(o2->op_private & ~(OPpARG1_MASK|HINT_STRICT_REFS
16795                                     |OPpOUR_INTRO|OPpDEREF|OPpLVAL_INTRO)));
16796                 if (o2->op_private & (OPpOUR_INTRO|OPpLVAL_INTRO))
16797                     break;
16798                 if (   (o2->op_private & OPpDEREF) != OPpDEREF_AV
16799                     && (o2->op_private & OPpDEREF) != OPpDEREF_HV)
16800                     break;
16801
16802                 o2 = o2->op_next;
16803                 if (o2->op_type == OP_RV2AV) {
16804                     action = MDEREF_AV_gvsv_vivify_rv2av_aelem;
16805                     goto do_deref;
16806                 }
16807                 if (o2->op_type == OP_RV2HV) {
16808                     action = MDEREF_HV_gvsv_vivify_rv2hv_helem;
16809                     goto do_deref;
16810                 }
16811                 break;
16812
16813             case OP_PADSV:
16814                 /* $lex->[...]: padsv[$lex] sM/DREFAV */
16815
16816                 ASSUME(!(o2->op_flags &
16817                     ~(OPf_WANT|OPf_PARENS|OPf_REF|OPf_MOD|OPf_SPECIAL)));
16818                 if ((o2->op_flags &
16819                         (OPf_WANT|OPf_REF|OPf_MOD|OPf_SPECIAL))
16820                      != (OPf_WANT_SCALAR|OPf_MOD))
16821                     break;
16822
16823                 ASSUME(!(o2->op_private &
16824                                 ~(OPpPAD_STATE|OPpDEREF|OPpLVAL_INTRO)));
16825                 /* skip if state or intro, or not a deref */
16826                 if (      o2->op_private != OPpDEREF_AV
16827                        && o2->op_private != OPpDEREF_HV)
16828                     break;
16829
16830                 o2 = o2->op_next;
16831                 if (o2->op_type == OP_RV2AV) {
16832                     action = MDEREF_AV_padsv_vivify_rv2av_aelem;
16833                     goto do_deref;
16834                 }
16835                 if (o2->op_type == OP_RV2HV) {
16836                     action = MDEREF_HV_padsv_vivify_rv2hv_helem;
16837                     goto do_deref;
16838                 }
16839                 break;
16840
16841             case OP_PADAV:
16842             case OP_PADHV:
16843                 /*    $lex[..]:  padav[@lex:1,2] sR *
16844                  * or $lex{..}:  padhv[%lex:1,2] sR */
16845                 ASSUME(!(o2->op_flags & ~(OPf_WANT|OPf_MOD|OPf_PARENS|
16846                                             OPf_REF|OPf_SPECIAL)));
16847                 if ((o2->op_flags &
16848                         (OPf_WANT|OPf_REF|OPf_MOD|OPf_SPECIAL))
16849                      != (OPf_WANT_SCALAR|OPf_REF))
16850                     break;
16851                 if (o2->op_flags != (OPf_WANT_SCALAR|OPf_REF))
16852                     break;
16853                 /* OPf_PARENS isn't currently used in this case;
16854                  * if that changes, let us know! */
16855                 ASSUME(!(o2->op_flags & OPf_PARENS));
16856
16857                 /* at this point, we wouldn't expect any of the remaining
16858                  * possible private flags:
16859                  * OPpPAD_STATE, OPpLVAL_INTRO, OPpTRUEBOOL,
16860                  * OPpMAYBE_TRUEBOOL, OPpMAYBE_LVSUB
16861                  *
16862                  * OPpSLICEWARNING shouldn't affect runtime
16863                  */
16864                 ASSUME(!(o2->op_private & ~(OPpSLICEWARNING)));
16865
16866                 action = o2->op_type == OP_PADAV
16867                             ? MDEREF_AV_padav_aelem
16868                             : MDEREF_HV_padhv_helem;
16869                 o2 = o2->op_next;
16870                 S_maybe_multideref(aTHX_ o, o2, action, 0);
16871                 break;
16872
16873
16874             case OP_RV2AV:
16875             case OP_RV2HV:
16876                 action = o2->op_type == OP_RV2AV
16877                             ? MDEREF_AV_pop_rv2av_aelem
16878                             : MDEREF_HV_pop_rv2hv_helem;
16879                 /* FALLTHROUGH */
16880             do_deref:
16881                 /* (expr)->[...]:  rv2av sKR/1;
16882                  * (expr)->{...}:  rv2hv sKR/1; */
16883
16884                 ASSUME(o2->op_type == OP_RV2AV || o2->op_type == OP_RV2HV);
16885
16886                 ASSUME(!(o2->op_flags & ~(OPf_WANT|OPf_KIDS|OPf_PARENS
16887                                 |OPf_REF|OPf_MOD|OPf_STACKED|OPf_SPECIAL)));
16888                 if (o2->op_flags != (OPf_WANT_SCALAR|OPf_KIDS|OPf_REF))
16889                     break;
16890
16891                 /* at this point, we wouldn't expect any of these
16892                  * possible private flags:
16893                  * OPpMAYBE_LVSUB, OPpLVAL_INTRO
16894                  * OPpTRUEBOOL, OPpMAYBE_TRUEBOOL, (rv2hv only)
16895                  */
16896                 ASSUME(!(o2->op_private &
16897                     ~(OPpHINT_STRICT_REFS|OPpARG1_MASK|OPpSLICEWARNING
16898                      |OPpOUR_INTRO)));
16899                 hints |= (o2->op_private & OPpHINT_STRICT_REFS);
16900
16901                 o2 = o2->op_next;
16902
16903                 S_maybe_multideref(aTHX_ o, o2, action, hints);
16904                 break;
16905
16906             default:
16907                 break;
16908             }
16909         }
16910
16911
16912         switch (o->op_type) {
16913         case OP_DBSTATE:
16914             PL_curcop = ((COP*)o);              /* for warnings */
16915             break;
16916         case OP_NEXTSTATE:
16917             PL_curcop = ((COP*)o);              /* for warnings */
16918
16919             /* Optimise a "return ..." at the end of a sub to just be "...".
16920              * This saves 2 ops. Before:
16921              * 1  <;> nextstate(main 1 -e:1) v ->2
16922              * 4  <@> return K ->5
16923              * 2    <0> pushmark s ->3
16924              * -    <1> ex-rv2sv sK/1 ->4
16925              * 3      <#> gvsv[*cat] s ->4
16926              *
16927              * After:
16928              * -  <@> return K ->-
16929              * -    <0> pushmark s ->2
16930              * -    <1> ex-rv2sv sK/1 ->-
16931              * 2      <$> gvsv(*cat) s ->3
16932              */
16933             {
16934                 OP *next = o->op_next;
16935                 OP *sibling = OpSIBLING(o);
16936                 if (   OP_TYPE_IS(next, OP_PUSHMARK)
16937                     && OP_TYPE_IS(sibling, OP_RETURN)
16938                     && OP_TYPE_IS(sibling->op_next, OP_LINESEQ)
16939                     && ( OP_TYPE_IS(sibling->op_next->op_next, OP_LEAVESUB)
16940                        ||OP_TYPE_IS(sibling->op_next->op_next,
16941                                     OP_LEAVESUBLV))
16942                     && cUNOPx(sibling)->op_first == next
16943                     && OpHAS_SIBLING(next) && OpSIBLING(next)->op_next
16944                     && next->op_next
16945                 ) {
16946                     /* Look through the PUSHMARK's siblings for one that
16947                      * points to the RETURN */
16948                     OP *top = OpSIBLING(next);
16949                     while (top && top->op_next) {
16950                         if (top->op_next == sibling) {
16951                             top->op_next = sibling->op_next;
16952                             o->op_next = next->op_next;
16953                             break;
16954                         }
16955                         top = OpSIBLING(top);
16956                     }
16957                 }
16958             }
16959
16960             /* Optimise 'my $x; my $y;' into 'my ($x, $y);'
16961              *
16962              * This latter form is then suitable for conversion into padrange
16963              * later on. Convert:
16964              *
16965              *   nextstate1 -> padop1 -> nextstate2 -> padop2 -> nextstate3
16966              *
16967              * into:
16968              *
16969              *   nextstate1 ->     listop     -> nextstate3
16970              *                 /            \
16971              *         pushmark -> padop1 -> padop2
16972              */
16973             if (o->op_next && (
16974                     o->op_next->op_type == OP_PADSV
16975                  || o->op_next->op_type == OP_PADAV
16976                  || o->op_next->op_type == OP_PADHV
16977                 )
16978                 && !(o->op_next->op_private & ~OPpLVAL_INTRO)
16979                 && o->op_next->op_next && o->op_next->op_next->op_type == OP_NEXTSTATE
16980                 && o->op_next->op_next->op_next && (
16981                     o->op_next->op_next->op_next->op_type == OP_PADSV
16982                  || o->op_next->op_next->op_next->op_type == OP_PADAV
16983                  || o->op_next->op_next->op_next->op_type == OP_PADHV
16984                 )
16985                 && !(o->op_next->op_next->op_next->op_private & ~OPpLVAL_INTRO)
16986                 && o->op_next->op_next->op_next->op_next && o->op_next->op_next->op_next->op_next->op_type == OP_NEXTSTATE
16987                 && (!CopLABEL((COP*)o)) /* Don't mess with labels */
16988                 && (!CopLABEL((COP*)o->op_next->op_next)) /* ... */
16989             ) {
16990                 OP *pad1, *ns2, *pad2, *ns3, *newop, *newpm;
16991
16992                 pad1 =    o->op_next;
16993                 ns2  = pad1->op_next;
16994                 pad2 =  ns2->op_next;
16995                 ns3  = pad2->op_next;
16996
16997                 /* we assume here that the op_next chain is the same as
16998                  * the op_sibling chain */
16999                 assert(OpSIBLING(o)    == pad1);
17000                 assert(OpSIBLING(pad1) == ns2);
17001                 assert(OpSIBLING(ns2)  == pad2);
17002                 assert(OpSIBLING(pad2) == ns3);
17003
17004                 /* excise and delete ns2 */
17005                 op_sibling_splice(NULL, pad1, 1, NULL);
17006                 op_free(ns2);
17007
17008                 /* excise pad1 and pad2 */
17009                 op_sibling_splice(NULL, o, 2, NULL);
17010
17011                 /* create new listop, with children consisting of:
17012                  * a new pushmark, pad1, pad2. */
17013                 newop = newLISTOP(OP_LIST, 0, pad1, pad2);
17014                 newop->op_flags |= OPf_PARENS;
17015                 newop->op_flags = (newop->op_flags & ~OPf_WANT) | OPf_WANT_VOID;
17016
17017                 /* insert newop between o and ns3 */
17018                 op_sibling_splice(NULL, o, 0, newop);
17019
17020                 /*fixup op_next chain */
17021                 newpm = cUNOPx(newop)->op_first; /* pushmark */
17022                 o    ->op_next = newpm;
17023                 newpm->op_next = pad1;
17024                 pad1 ->op_next = pad2;
17025                 pad2 ->op_next = newop; /* listop */
17026                 newop->op_next = ns3;
17027
17028                 /* Ensure pushmark has this flag if padops do */
17029                 if (pad1->op_flags & OPf_MOD && pad2->op_flags & OPf_MOD) {
17030                     newpm->op_flags |= OPf_MOD;
17031                 }
17032
17033                 break;
17034             }
17035
17036             /* Two NEXTSTATEs in a row serve no purpose. Except if they happen
17037                to carry two labels. For now, take the easier option, and skip
17038                this optimisation if the first NEXTSTATE has a label.  */
17039             if (!CopLABEL((COP*)o) && !PERLDB_NOOPT) {
17040                 OP *nextop = o->op_next;
17041                 while (nextop) {
17042                     switch (nextop->op_type) {
17043                         case OP_NULL:
17044                         case OP_SCALAR:
17045                         case OP_LINESEQ:
17046                         case OP_SCOPE:
17047                             nextop = nextop->op_next;
17048                             continue;
17049                     }
17050                     break;
17051                 }
17052
17053                 if (nextop && (nextop->op_type == OP_NEXTSTATE)) {
17054                     op_null(o);
17055                     if (oldop)
17056                         oldop->op_next = nextop;
17057                     o = nextop;
17058                     /* Skip (old)oldop assignment since the current oldop's
17059                        op_next already points to the next op.  */
17060                     goto redo;
17061                 }
17062             }
17063             break;
17064
17065         case OP_CONCAT:
17066             if (o->op_next && o->op_next->op_type == OP_STRINGIFY) {
17067                 if (o->op_next->op_private & OPpTARGET_MY) {
17068                     if (o->op_flags & OPf_STACKED) /* chained concats */
17069                         break; /* ignore_optimization */
17070                     else {
17071                         /* assert(PL_opargs[o->op_type] & OA_TARGLEX); */
17072                         o->op_targ = o->op_next->op_targ;
17073                         o->op_next->op_targ = 0;
17074                         o->op_private |= OPpTARGET_MY;
17075                     }
17076                 }
17077                 op_null(o->op_next);
17078             }
17079             break;
17080         case OP_STUB:
17081             if ((o->op_flags & OPf_WANT) != OPf_WANT_LIST) {
17082                 break; /* Scalar stub must produce undef.  List stub is noop */
17083             }
17084             goto nothin;
17085         case OP_NULL:
17086             if (o->op_targ == OP_NEXTSTATE
17087                 || o->op_targ == OP_DBSTATE)
17088             {
17089                 PL_curcop = ((COP*)o);
17090             }
17091             /* XXX: We avoid setting op_seq here to prevent later calls
17092                to rpeep() from mistakenly concluding that optimisation
17093                has already occurred. This doesn't fix the real problem,
17094                though (See 20010220.007 (#5874)). AMS 20010719 */
17095             /* op_seq functionality is now replaced by op_opt */
17096             o->op_opt = 0;
17097             /* FALLTHROUGH */
17098         case OP_SCALAR:
17099         case OP_LINESEQ:
17100         case OP_SCOPE:
17101         nothin:
17102             if (oldop) {
17103                 oldop->op_next = o->op_next;
17104                 o->op_opt = 0;
17105                 continue;
17106             }
17107             break;
17108
17109         case OP_PUSHMARK:
17110
17111             /* Given
17112                  5 repeat/DOLIST
17113                  3   ex-list
17114                  1     pushmark
17115                  2     scalar or const
17116                  4   const[0]
17117                convert repeat into a stub with no kids.
17118              */
17119             if (o->op_next->op_type == OP_CONST
17120              || (  o->op_next->op_type == OP_PADSV
17121                 && !(o->op_next->op_private & OPpLVAL_INTRO))
17122              || (  o->op_next->op_type == OP_GV
17123                 && o->op_next->op_next->op_type == OP_RV2SV
17124                 && !(o->op_next->op_next->op_private
17125                         & (OPpLVAL_INTRO|OPpOUR_INTRO))))
17126             {
17127                 const OP *kid = o->op_next->op_next;
17128                 if (o->op_next->op_type == OP_GV)
17129                    kid = kid->op_next;
17130                 /* kid is now the ex-list.  */
17131                 if (kid->op_type == OP_NULL
17132                  && (kid = kid->op_next)->op_type == OP_CONST
17133                     /* kid is now the repeat count.  */
17134                  && kid->op_next->op_type == OP_REPEAT
17135                  && kid->op_next->op_private & OPpREPEAT_DOLIST
17136                  && (kid->op_next->op_flags & OPf_WANT) == OPf_WANT_LIST
17137                  && SvIOK(kSVOP_sv) && SvIVX(kSVOP_sv) == 0
17138                  && oldop)
17139                 {
17140                     o = kid->op_next; /* repeat */
17141                     oldop->op_next = o;
17142                     op_free(cBINOPo->op_first);
17143                     op_free(cBINOPo->op_last );
17144                     o->op_flags &=~ OPf_KIDS;
17145                     /* stub is a baseop; repeat is a binop */
17146                     STATIC_ASSERT_STMT(sizeof(OP) <= sizeof(BINOP));
17147                     OpTYPE_set(o, OP_STUB);
17148                     o->op_private = 0;
17149                     break;
17150                 }
17151             }
17152
17153             /* Convert a series of PAD ops for my vars plus support into a
17154              * single padrange op. Basically
17155              *
17156              *    pushmark -> pad[ahs]v -> pad[ahs]?v -> ... -> (list) -> rest
17157              *
17158              * becomes, depending on circumstances, one of
17159              *
17160              *    padrange  ----------------------------------> (list) -> rest
17161              *    padrange  --------------------------------------------> rest
17162              *
17163              * where all the pad indexes are sequential and of the same type
17164              * (INTRO or not).
17165              * We convert the pushmark into a padrange op, then skip
17166              * any other pad ops, and possibly some trailing ops.
17167              * Note that we don't null() the skipped ops, to make it
17168              * easier for Deparse to undo this optimisation (and none of
17169              * the skipped ops are holding any resourses). It also makes
17170              * it easier for find_uninit_var(), as it can just ignore
17171              * padrange, and examine the original pad ops.
17172              */
17173         {
17174             OP *p;
17175             OP *followop = NULL; /* the op that will follow the padrange op */
17176             U8 count = 0;
17177             U8 intro = 0;
17178             PADOFFSET base = 0; /* init only to stop compiler whining */
17179             bool gvoid = 0;     /* init only to stop compiler whining */
17180             bool defav = 0;  /* seen (...) = @_ */
17181             bool reuse = 0;  /* reuse an existing padrange op */
17182
17183             /* look for a pushmark -> gv[_] -> rv2av */
17184
17185             {
17186                 OP *rv2av, *q;
17187                 p = o->op_next;
17188                 if (   p->op_type == OP_GV
17189                     && cGVOPx_gv(p) == PL_defgv
17190                     && (rv2av = p->op_next)
17191                     && rv2av->op_type == OP_RV2AV
17192                     && !(rv2av->op_flags & OPf_REF)
17193                     && !(rv2av->op_private & (OPpLVAL_INTRO|OPpMAYBE_LVSUB))
17194                     && ((rv2av->op_flags & OPf_WANT) == OPf_WANT_LIST)
17195                 ) {
17196                     q = rv2av->op_next;
17197                     if (q->op_type == OP_NULL)
17198                         q = q->op_next;
17199                     if (q->op_type == OP_PUSHMARK) {
17200                         defav = 1;
17201                         p = q;
17202                     }
17203                 }
17204             }
17205             if (!defav) {
17206                 p = o;
17207             }
17208
17209             /* scan for PAD ops */
17210
17211             for (p = p->op_next; p; p = p->op_next) {
17212                 if (p->op_type == OP_NULL)
17213                     continue;
17214
17215                 if ((     p->op_type != OP_PADSV
17216                        && p->op_type != OP_PADAV
17217                        && p->op_type != OP_PADHV
17218                     )
17219                       /* any private flag other than INTRO? e.g. STATE */
17220                    || (p->op_private & ~OPpLVAL_INTRO)
17221                 )
17222                     break;
17223
17224                 /* let $a[N] potentially be optimised into AELEMFAST_LEX
17225                  * instead */
17226                 if (   p->op_type == OP_PADAV
17227                     && p->op_next
17228                     && p->op_next->op_type == OP_CONST
17229                     && p->op_next->op_next
17230                     && p->op_next->op_next->op_type == OP_AELEM
17231                 )
17232                     break;
17233
17234                 /* for 1st padop, note what type it is and the range
17235                  * start; for the others, check that it's the same type
17236                  * and that the targs are contiguous */
17237                 if (count == 0) {
17238                     intro = (p->op_private & OPpLVAL_INTRO);
17239                     base = p->op_targ;
17240                     gvoid = OP_GIMME(p,0) == G_VOID;
17241                 }
17242                 else {
17243                     if ((p->op_private & OPpLVAL_INTRO) != intro)
17244                         break;
17245                     /* Note that you'd normally  expect targs to be
17246                      * contiguous in my($a,$b,$c), but that's not the case
17247                      * when external modules start doing things, e.g.
17248                      * Function::Parameters */
17249                     if (p->op_targ != base + count)
17250                         break;
17251                     assert(p->op_targ == base + count);
17252                     /* Either all the padops or none of the padops should
17253                        be in void context.  Since we only do the optimisa-
17254                        tion for av/hv when the aggregate itself is pushed
17255                        on to the stack (one item), there is no need to dis-
17256                        tinguish list from scalar context.  */
17257                     if (gvoid != (OP_GIMME(p,0) == G_VOID))
17258                         break;
17259                 }
17260
17261                 /* for AV, HV, only when we're not flattening */
17262                 if (   p->op_type != OP_PADSV
17263                     && !gvoid
17264                     && !(p->op_flags & OPf_REF)
17265                 )
17266                     break;
17267
17268                 if (count >= OPpPADRANGE_COUNTMASK)
17269                     break;
17270
17271                 /* there's a biggest base we can fit into a
17272                  * SAVEt_CLEARPADRANGE in pp_padrange.
17273                  * (The sizeof() stuff will be constant-folded, and is
17274                  * intended to avoid getting "comparison is always false"
17275                  * compiler warnings. See the comments above
17276                  * MEM_WRAP_CHECK for more explanation on why we do this
17277                  * in a weird way to avoid compiler warnings.)
17278                  */
17279                 if (   intro
17280                     && (8*sizeof(base) >
17281                         8*sizeof(UV)-OPpPADRANGE_COUNTSHIFT-SAVE_TIGHT_SHIFT
17282                         ? (Size_t)base
17283                         : (UV_MAX >> (OPpPADRANGE_COUNTSHIFT+SAVE_TIGHT_SHIFT))
17284                         ) >
17285                         (UV_MAX >> (OPpPADRANGE_COUNTSHIFT+SAVE_TIGHT_SHIFT))
17286                 )
17287                     break;
17288
17289                 /* Success! We've got another valid pad op to optimise away */
17290                 count++;
17291                 followop = p->op_next;
17292             }
17293
17294             if (count < 1 || (count == 1 && !defav))
17295                 break;
17296
17297             /* pp_padrange in specifically compile-time void context
17298              * skips pushing a mark and lexicals; in all other contexts
17299              * (including unknown till runtime) it pushes a mark and the
17300              * lexicals. We must be very careful then, that the ops we
17301              * optimise away would have exactly the same effect as the
17302              * padrange.
17303              * In particular in void context, we can only optimise to
17304              * a padrange if we see the complete sequence
17305              *     pushmark, pad*v, ...., list
17306              * which has the net effect of leaving the markstack as it
17307              * was.  Not pushing onto the stack (whereas padsv does touch
17308              * the stack) makes no difference in void context.
17309              */
17310             assert(followop);
17311             if (gvoid) {
17312                 if (followop->op_type == OP_LIST
17313                         && OP_GIMME(followop,0) == G_VOID
17314                    )
17315                 {
17316                     followop = followop->op_next; /* skip OP_LIST */
17317
17318                     /* consolidate two successive my(...);'s */
17319
17320                     if (   oldoldop
17321                         && oldoldop->op_type == OP_PADRANGE
17322                         && (oldoldop->op_flags & OPf_WANT) == OPf_WANT_VOID
17323                         && (oldoldop->op_private & OPpLVAL_INTRO) == intro
17324                         && !(oldoldop->op_flags & OPf_SPECIAL)
17325                     ) {
17326                         U8 old_count;
17327                         assert(oldoldop->op_next == oldop);
17328                         assert(   oldop->op_type == OP_NEXTSTATE
17329                                || oldop->op_type == OP_DBSTATE);
17330                         assert(oldop->op_next == o);
17331
17332                         old_count
17333                             = (oldoldop->op_private & OPpPADRANGE_COUNTMASK);
17334
17335                        /* Do not assume pad offsets for $c and $d are con-
17336                           tiguous in
17337                             my ($a,$b,$c);
17338                             my ($d,$e,$f);
17339                         */
17340                         if (  oldoldop->op_targ + old_count == base
17341                            && old_count < OPpPADRANGE_COUNTMASK - count) {
17342                             base = oldoldop->op_targ;
17343                             count += old_count;
17344                             reuse = 1;
17345                         }
17346                     }
17347
17348                     /* if there's any immediately following singleton
17349                      * my var's; then swallow them and the associated
17350                      * nextstates; i.e.
17351                      *    my ($a,$b); my $c; my $d;
17352                      * is treated as
17353                      *    my ($a,$b,$c,$d);
17354                      */
17355
17356                     while (    ((p = followop->op_next))
17357                             && (  p->op_type == OP_PADSV
17358                                || p->op_type == OP_PADAV
17359                                || p->op_type == OP_PADHV)
17360                             && (p->op_flags & OPf_WANT) == OPf_WANT_VOID
17361                             && (p->op_private & OPpLVAL_INTRO) == intro
17362                             && !(p->op_private & ~OPpLVAL_INTRO)
17363                             && p->op_next
17364                             && (   p->op_next->op_type == OP_NEXTSTATE
17365                                 || p->op_next->op_type == OP_DBSTATE)
17366                             && count < OPpPADRANGE_COUNTMASK
17367                             && base + count == p->op_targ
17368                     ) {
17369                         count++;
17370                         followop = p->op_next;
17371                     }
17372                 }
17373                 else
17374                     break;
17375             }
17376
17377             if (reuse) {
17378                 assert(oldoldop->op_type == OP_PADRANGE);
17379                 oldoldop->op_next = followop;
17380                 oldoldop->op_private = (intro | count);
17381                 o = oldoldop;
17382                 oldop = NULL;
17383                 oldoldop = NULL;
17384             }
17385             else {
17386                 /* Convert the pushmark into a padrange.
17387                  * To make Deparse easier, we guarantee that a padrange was
17388                  * *always* formerly a pushmark */
17389                 assert(o->op_type == OP_PUSHMARK);
17390                 o->op_next = followop;
17391                 OpTYPE_set(o, OP_PADRANGE);
17392                 o->op_targ = base;
17393                 /* bit 7: INTRO; bit 6..0: count */
17394                 o->op_private = (intro | count);
17395                 o->op_flags = ((o->op_flags & ~(OPf_WANT|OPf_SPECIAL))
17396                               | gvoid * OPf_WANT_VOID
17397                               | (defav ? OPf_SPECIAL : 0));
17398             }
17399             break;
17400         }
17401
17402         case OP_RV2AV:
17403             if ((o->op_flags & OPf_WANT) == OPf_WANT_SCALAR)
17404                 S_check_for_bool_cxt(o, 1, OPpTRUEBOOL, 0);
17405             break;
17406
17407         case OP_RV2HV:
17408         case OP_PADHV:
17409             /*'keys %h' in void or scalar context: skip the OP_KEYS
17410              * and perform the functionality directly in the RV2HV/PADHV
17411              * op
17412              */
17413             if (o->op_flags & OPf_REF) {
17414                 OP *k = o->op_next;
17415                 U8 want = (k->op_flags & OPf_WANT);
17416                 if (   k
17417                     && k->op_type == OP_KEYS
17418                     && (   want == OPf_WANT_VOID
17419                         || want == OPf_WANT_SCALAR)
17420                     && !(k->op_private & OPpMAYBE_LVSUB)
17421                     && !(k->op_flags & OPf_MOD)
17422                 ) {
17423                     o->op_next     = k->op_next;
17424                     o->op_flags   &= ~(OPf_REF|OPf_WANT);
17425                     o->op_flags   |= want;
17426                     o->op_private |= (o->op_type == OP_PADHV ?
17427                                       OPpPADHV_ISKEYS : OPpRV2HV_ISKEYS);
17428                     /* for keys(%lex), hold onto the OP_KEYS's targ
17429                      * since padhv doesn't have its own targ to return
17430                      * an int with */
17431                     if (!(o->op_type ==OP_PADHV && want == OPf_WANT_SCALAR))
17432                         op_null(k);
17433                 }
17434             }
17435
17436             /* see if %h is used in boolean context */
17437             if ((o->op_flags & OPf_WANT) == OPf_WANT_SCALAR)
17438                 S_check_for_bool_cxt(o, 1, OPpTRUEBOOL, OPpMAYBE_TRUEBOOL);
17439
17440
17441             if (o->op_type != OP_PADHV)
17442                 break;
17443             /* FALLTHROUGH */
17444         case OP_PADAV:
17445             if (   o->op_type == OP_PADAV
17446                 && (o->op_flags & OPf_WANT) == OPf_WANT_SCALAR
17447             )
17448                 S_check_for_bool_cxt(o, 1, OPpTRUEBOOL, 0);
17449             /* FALLTHROUGH */
17450         case OP_PADSV:
17451             /* Skip over state($x) in void context.  */
17452             if (oldop && o->op_private == (OPpPAD_STATE|OPpLVAL_INTRO)
17453              && (o->op_flags & OPf_WANT) == OPf_WANT_VOID)
17454             {
17455                 oldop->op_next = o->op_next;
17456                 goto redo_nextstate;
17457             }
17458             if (o->op_type != OP_PADAV)
17459                 break;
17460             /* FALLTHROUGH */
17461         case OP_GV:
17462             if (o->op_type == OP_PADAV || o->op_next->op_type == OP_RV2AV) {
17463                 OP* const pop = (o->op_type == OP_PADAV) ?
17464                             o->op_next : o->op_next->op_next;
17465                 IV i;
17466                 if (pop && pop->op_type == OP_CONST &&
17467                     ((PL_op = pop->op_next)) &&
17468                     pop->op_next->op_type == OP_AELEM &&
17469                     !(pop->op_next->op_private &
17470                       (OPpLVAL_INTRO|OPpLVAL_DEFER|OPpDEREF|OPpMAYBE_LVSUB)) &&
17471                     (i = SvIV(((SVOP*)pop)->op_sv)) >= -128 && i <= 127)
17472                 {
17473                     GV *gv;
17474                     if (cSVOPx(pop)->op_private & OPpCONST_STRICT)
17475                         no_bareword_allowed(pop);
17476                     if (o->op_type == OP_GV)
17477                         op_null(o->op_next);
17478                     op_null(pop->op_next);
17479                     op_null(pop);
17480                     o->op_flags |= pop->op_next->op_flags & OPf_MOD;
17481                     o->op_next = pop->op_next->op_next;
17482                     o->op_ppaddr = PL_ppaddr[OP_AELEMFAST];
17483                     o->op_private = (U8)i;
17484                     if (o->op_type == OP_GV) {
17485                         gv = cGVOPo_gv;
17486                         GvAVn(gv);
17487                         o->op_type = OP_AELEMFAST;
17488                     }
17489                     else
17490                         o->op_type = OP_AELEMFAST_LEX;
17491                 }
17492                 if (o->op_type != OP_GV)
17493                     break;
17494             }
17495
17496             /* Remove $foo from the op_next chain in void context.  */
17497             if (oldop
17498              && (  o->op_next->op_type == OP_RV2SV
17499                 || o->op_next->op_type == OP_RV2AV
17500                 || o->op_next->op_type == OP_RV2HV  )
17501              && (o->op_next->op_flags & OPf_WANT) == OPf_WANT_VOID
17502              && !(o->op_next->op_private & OPpLVAL_INTRO))
17503             {
17504                 oldop->op_next = o->op_next->op_next;
17505                 /* Reprocess the previous op if it is a nextstate, to
17506                    allow double-nextstate optimisation.  */
17507               redo_nextstate:
17508                 if (oldop->op_type == OP_NEXTSTATE) {
17509                     oldop->op_opt = 0;
17510                     o = oldop;
17511                     oldop = oldoldop;
17512                     oldoldop = NULL;
17513                     goto redo;
17514                 }
17515                 o = oldop->op_next;
17516                 goto redo;
17517             }
17518             else if (o->op_next->op_type == OP_RV2SV) {
17519                 if (!(o->op_next->op_private & OPpDEREF)) {
17520                     op_null(o->op_next);
17521                     o->op_private |= o->op_next->op_private & (OPpLVAL_INTRO
17522                                                                | OPpOUR_INTRO);
17523                     o->op_next = o->op_next->op_next;
17524                     OpTYPE_set(o, OP_GVSV);
17525                 }
17526             }
17527             else if (o->op_next->op_type == OP_READLINE
17528                     && o->op_next->op_next->op_type == OP_CONCAT
17529                     && (o->op_next->op_next->op_flags & OPf_STACKED))
17530             {
17531                 /* Turn "$a .= <FH>" into an OP_RCATLINE. AMS 20010917 */
17532                 OpTYPE_set(o, OP_RCATLINE);
17533                 o->op_flags |= OPf_STACKED;
17534                 op_null(o->op_next->op_next);
17535                 op_null(o->op_next);
17536             }
17537
17538             break;
17539
17540         case OP_NOT:
17541             break;
17542
17543         case OP_AND:
17544         case OP_OR:
17545         case OP_DOR:
17546         case OP_CMPCHAIN_AND:
17547             while (cLOGOP->op_other->op_type == OP_NULL)
17548                 cLOGOP->op_other = cLOGOP->op_other->op_next;
17549             while (o->op_next && (   o->op_type == o->op_next->op_type
17550                                   || o->op_next->op_type == OP_NULL))
17551                 o->op_next = o->op_next->op_next;
17552
17553             /* If we're an OR and our next is an AND in void context, we'll
17554                follow its op_other on short circuit, same for reverse.
17555                We can't do this with OP_DOR since if it's true, its return
17556                value is the underlying value which must be evaluated
17557                by the next op. */
17558             if (o->op_next &&
17559                 (
17560                     (IS_AND_OP(o) && IS_OR_OP(o->op_next))
17561                  || (IS_OR_OP(o) && IS_AND_OP(o->op_next))
17562                 )
17563                 && (o->op_next->op_flags & OPf_WANT) == OPf_WANT_VOID
17564             ) {
17565                 o->op_next = ((LOGOP*)o->op_next)->op_other;
17566             }
17567             DEFER(cLOGOP->op_other);
17568             o->op_opt = 1;
17569             break;
17570
17571         case OP_GREPWHILE:
17572             if ((o->op_flags & OPf_WANT) == OPf_WANT_SCALAR)
17573                 S_check_for_bool_cxt(o, 1, OPpTRUEBOOL, 0);
17574             /* FALLTHROUGH */
17575         case OP_COND_EXPR:
17576         case OP_MAPWHILE:
17577         case OP_ANDASSIGN:
17578         case OP_ORASSIGN:
17579         case OP_DORASSIGN:
17580         case OP_RANGE:
17581         case OP_ONCE:
17582         case OP_ARGDEFELEM:
17583             while (cLOGOP->op_other->op_type == OP_NULL)
17584                 cLOGOP->op_other = cLOGOP->op_other->op_next;
17585             DEFER(cLOGOP->op_other);
17586             break;
17587
17588         case OP_ENTERLOOP:
17589         case OP_ENTERITER:
17590             while (cLOOP->op_redoop->op_type == OP_NULL)
17591                 cLOOP->op_redoop = cLOOP->op_redoop->op_next;
17592             while (cLOOP->op_nextop->op_type == OP_NULL)
17593                 cLOOP->op_nextop = cLOOP->op_nextop->op_next;
17594             while (cLOOP->op_lastop->op_type == OP_NULL)
17595                 cLOOP->op_lastop = cLOOP->op_lastop->op_next;
17596             /* a while(1) loop doesn't have an op_next that escapes the
17597              * loop, so we have to explicitly follow the op_lastop to
17598              * process the rest of the code */
17599             DEFER(cLOOP->op_lastop);
17600             break;
17601
17602         case OP_ENTERTRY:
17603             assert(cLOGOPo->op_other->op_type == OP_LEAVETRY);
17604             DEFER(cLOGOPo->op_other);
17605             break;
17606
17607         case OP_SUBST:
17608             if ((o->op_flags & OPf_WANT) == OPf_WANT_SCALAR)
17609                 S_check_for_bool_cxt(o, 1, OPpTRUEBOOL, 0);
17610             assert(!(cPMOP->op_pmflags & PMf_ONCE));
17611             while (cPMOP->op_pmstashstartu.op_pmreplstart &&
17612                    cPMOP->op_pmstashstartu.op_pmreplstart->op_type == OP_NULL)
17613                 cPMOP->op_pmstashstartu.op_pmreplstart
17614                     = cPMOP->op_pmstashstartu.op_pmreplstart->op_next;
17615             DEFER(cPMOP->op_pmstashstartu.op_pmreplstart);
17616             break;
17617
17618         case OP_SORT: {
17619             OP *oright;
17620
17621             if (o->op_flags & OPf_SPECIAL) {
17622                 /* first arg is a code block */
17623                 OP * const nullop = OpSIBLING(cLISTOP->op_first);
17624                 OP * kid          = cUNOPx(nullop)->op_first;
17625
17626                 assert(nullop->op_type == OP_NULL);
17627                 assert(kid->op_type == OP_SCOPE
17628                  || (kid->op_type == OP_NULL && kid->op_targ == OP_LEAVE));
17629                 /* since OP_SORT doesn't have a handy op_other-style
17630                  * field that can point directly to the start of the code
17631                  * block, store it in the otherwise-unused op_next field
17632                  * of the top-level OP_NULL. This will be quicker at
17633                  * run-time, and it will also allow us to remove leading
17634                  * OP_NULLs by just messing with op_nexts without
17635                  * altering the basic op_first/op_sibling layout. */
17636                 kid = kLISTOP->op_first;
17637                 assert(
17638                       (kid->op_type == OP_NULL
17639                       && (  kid->op_targ == OP_NEXTSTATE
17640                          || kid->op_targ == OP_DBSTATE  ))
17641                     || kid->op_type == OP_STUB
17642                     || kid->op_type == OP_ENTER
17643                     || (PL_parser && PL_parser->error_count));
17644                 nullop->op_next = kid->op_next;
17645                 DEFER(nullop->op_next);
17646             }
17647
17648             /* check that RHS of sort is a single plain array */
17649             oright = cUNOPo->op_first;
17650             if (!oright || oright->op_type != OP_PUSHMARK)
17651                 break;
17652
17653             if (o->op_private & OPpSORT_INPLACE)
17654                 break;
17655
17656             /* reverse sort ... can be optimised.  */
17657             if (!OpHAS_SIBLING(cUNOPo)) {
17658                 /* Nothing follows us on the list. */
17659                 OP * const reverse = o->op_next;
17660
17661                 if (reverse->op_type == OP_REVERSE &&
17662                     (reverse->op_flags & OPf_WANT) == OPf_WANT_LIST) {
17663                     OP * const pushmark = cUNOPx(reverse)->op_first;
17664                     if (pushmark && (pushmark->op_type == OP_PUSHMARK)
17665                         && (OpSIBLING(cUNOPx(pushmark)) == o)) {
17666                         /* reverse -> pushmark -> sort */
17667                         o->op_private |= OPpSORT_REVERSE;
17668                         op_null(reverse);
17669                         pushmark->op_next = oright->op_next;
17670                         op_null(oright);
17671                     }
17672                 }
17673             }
17674
17675             break;
17676         }
17677
17678         case OP_REVERSE: {
17679             OP *ourmark, *theirmark, *ourlast, *iter, *expushmark, *rv2av;
17680             OP *gvop = NULL;
17681             LISTOP *enter, *exlist;
17682
17683             if (o->op_private & OPpSORT_INPLACE)
17684                 break;
17685
17686             enter = (LISTOP *) o->op_next;
17687             if (!enter)
17688                 break;
17689             if (enter->op_type == OP_NULL) {
17690                 enter = (LISTOP *) enter->op_next;
17691                 if (!enter)
17692                     break;
17693             }
17694             /* for $a (...) will have OP_GV then OP_RV2GV here.
17695                for (...) just has an OP_GV.  */
17696             if (enter->op_type == OP_GV) {
17697                 gvop = (OP *) enter;
17698                 enter = (LISTOP *) enter->op_next;
17699                 if (!enter)
17700                     break;
17701                 if (enter->op_type == OP_RV2GV) {
17702                   enter = (LISTOP *) enter->op_next;
17703                   if (!enter)
17704                     break;
17705                 }
17706             }
17707
17708             if (enter->op_type != OP_ENTERITER)
17709                 break;
17710
17711             iter = enter->op_next;
17712             if (!iter || iter->op_type != OP_ITER)
17713                 break;
17714
17715             expushmark = enter->op_first;
17716             if (!expushmark || expushmark->op_type != OP_NULL
17717                 || expushmark->op_targ != OP_PUSHMARK)
17718                 break;
17719
17720             exlist = (LISTOP *) OpSIBLING(expushmark);
17721             if (!exlist || exlist->op_type != OP_NULL
17722                 || exlist->op_targ != OP_LIST)
17723                 break;
17724
17725             if (exlist->op_last != o) {
17726                 /* Mmm. Was expecting to point back to this op.  */
17727                 break;
17728             }
17729             theirmark = exlist->op_first;
17730             if (!theirmark || theirmark->op_type != OP_PUSHMARK)
17731                 break;
17732
17733             if (OpSIBLING(theirmark) != o) {
17734                 /* There's something between the mark and the reverse, eg
17735                    for (1, reverse (...))
17736                    so no go.  */
17737                 break;
17738             }
17739
17740             ourmark = ((LISTOP *)o)->op_first;
17741             if (!ourmark || ourmark->op_type != OP_PUSHMARK)
17742                 break;
17743
17744             ourlast = ((LISTOP *)o)->op_last;
17745             if (!ourlast || ourlast->op_next != o)
17746                 break;
17747
17748             rv2av = OpSIBLING(ourmark);
17749             if (rv2av && rv2av->op_type == OP_RV2AV && !OpHAS_SIBLING(rv2av)
17750                 && rv2av->op_flags == (OPf_WANT_LIST | OPf_KIDS)) {
17751                 /* We're just reversing a single array.  */
17752                 rv2av->op_flags = OPf_WANT_SCALAR | OPf_KIDS | OPf_REF;
17753                 enter->op_flags |= OPf_STACKED;
17754             }
17755
17756             /* We don't have control over who points to theirmark, so sacrifice
17757                ours.  */
17758             theirmark->op_next = ourmark->op_next;
17759             theirmark->op_flags = ourmark->op_flags;
17760             ourlast->op_next = gvop ? gvop : (OP *) enter;
17761             op_null(ourmark);
17762             op_null(o);
17763             enter->op_private |= OPpITER_REVERSED;
17764             iter->op_private |= OPpITER_REVERSED;
17765
17766             oldoldop = NULL;
17767             oldop    = ourlast;
17768             o        = oldop->op_next;
17769             goto redo;
17770             NOT_REACHED; /* NOTREACHED */
17771             break;
17772         }
17773
17774         case OP_QR:
17775         case OP_MATCH:
17776             if (!(cPMOP->op_pmflags & PMf_ONCE)) {
17777                 assert (!cPMOP->op_pmstashstartu.op_pmreplstart);
17778             }
17779             break;
17780
17781         case OP_RUNCV:
17782             if (!(o->op_private & OPpOFFBYONE) && !CvCLONE(PL_compcv)
17783              && (!CvANON(PL_compcv) || (!PL_cv_has_eval && !PL_perldb)))
17784             {
17785                 SV *sv;
17786                 if (CvEVAL(PL_compcv)) sv = &PL_sv_undef;
17787                 else {
17788                     sv = newRV((SV *)PL_compcv);
17789                     sv_rvweaken(sv);
17790                     SvREADONLY_on(sv);
17791                 }
17792                 OpTYPE_set(o, OP_CONST);
17793                 o->op_flags |= OPf_SPECIAL;
17794                 cSVOPo->op_sv = sv;
17795             }
17796             break;
17797
17798         case OP_SASSIGN:
17799             if (OP_GIMME(o,0) == G_VOID
17800              || (  o->op_next->op_type == OP_LINESEQ
17801                 && (  o->op_next->op_next->op_type == OP_LEAVESUB
17802                    || (  o->op_next->op_next->op_type == OP_RETURN
17803                       && !CvLVALUE(PL_compcv)))))
17804             {
17805                 OP *right = cBINOP->op_first;
17806                 if (right) {
17807                     /*   sassign
17808                     *      RIGHT
17809                     *      substr
17810                     *         pushmark
17811                     *         arg1
17812                     *         arg2
17813                     *         ...
17814                     * becomes
17815                     *
17816                     *  ex-sassign
17817                     *     substr
17818                     *        pushmark
17819                     *        RIGHT
17820                     *        arg1
17821                     *        arg2
17822                     *        ...
17823                     */
17824                     OP *left = OpSIBLING(right);
17825                     if (left->op_type == OP_SUBSTR
17826                          && (left->op_private & 7) < 4) {
17827                         op_null(o);
17828                         /* cut out right */
17829                         op_sibling_splice(o, NULL, 1, NULL);
17830                         /* and insert it as second child of OP_SUBSTR */
17831                         op_sibling_splice(left, cBINOPx(left)->op_first, 0,
17832                                     right);
17833                         left->op_private |= OPpSUBSTR_REPL_FIRST;
17834                         left->op_flags =
17835                             (o->op_flags & ~OPf_WANT) | OPf_WANT_VOID;
17836                     }
17837                 }
17838             }
17839             break;
17840
17841         case OP_AASSIGN: {
17842             int l, r, lr, lscalars, rscalars;
17843
17844             /* handle common vars detection, e.g. ($a,$b) = ($b,$a).
17845                Note that we do this now rather than in newASSIGNOP(),
17846                since only by now are aliased lexicals flagged as such
17847
17848                See the essay "Common vars in list assignment" above for
17849                the full details of the rationale behind all the conditions
17850                below.
17851
17852                PL_generation sorcery:
17853                To detect whether there are common vars, the global var
17854                PL_generation is incremented for each assign op we scan.
17855                Then we run through all the lexical variables on the LHS,
17856                of the assignment, setting a spare slot in each of them to
17857                PL_generation.  Then we scan the RHS, and if any lexicals
17858                already have that value, we know we've got commonality.
17859                Also, if the generation number is already set to
17860                PERL_INT_MAX, then the variable is involved in aliasing, so
17861                we also have potential commonality in that case.
17862              */
17863
17864             PL_generation++;
17865             /* scan LHS */
17866             lscalars = 0;
17867             l = S_aassign_scan(aTHX_ cLISTOPo->op_last,  FALSE, &lscalars);
17868             /* scan RHS */
17869             rscalars = 0;
17870             r = S_aassign_scan(aTHX_ cLISTOPo->op_first, TRUE, &rscalars);
17871             lr = (l|r);
17872
17873
17874             /* After looking for things which are *always* safe, this main
17875              * if/else chain selects primarily based on the type of the
17876              * LHS, gradually working its way down from the more dangerous
17877              * to the more restrictive and thus safer cases */
17878
17879             if (   !l                      /* () = ....; */
17880                 || !r                      /* .... = (); */
17881                 || !(l & ~AAS_SAFE_SCALAR) /* (undef, pos()) = ...; */
17882                 || !(r & ~AAS_SAFE_SCALAR) /* ... = (1,2,length,undef); */
17883                 || (lscalars < 2)          /* ($x, undef) = ... */
17884             ) {
17885                 NOOP; /* always safe */
17886             }
17887             else if (l & AAS_DANGEROUS) {
17888                 /* always dangerous */
17889                 o->op_private |= OPpASSIGN_COMMON_SCALAR;
17890                 o->op_private |= OPpASSIGN_COMMON_AGG;
17891             }
17892             else if (l & (AAS_PKG_SCALAR|AAS_PKG_AGG)) {
17893                 /* package vars are always dangerous - too many
17894                  * aliasing possibilities */
17895                 if (l & AAS_PKG_SCALAR)
17896                     o->op_private |= OPpASSIGN_COMMON_SCALAR;
17897                 if (l & AAS_PKG_AGG)
17898                     o->op_private |= OPpASSIGN_COMMON_AGG;
17899             }
17900             else if (l & ( AAS_MY_SCALAR|AAS_MY_AGG
17901                           |AAS_LEX_SCALAR|AAS_LEX_AGG))
17902             {
17903                 /* LHS contains only lexicals and safe ops */
17904
17905                 if (l & (AAS_MY_AGG|AAS_LEX_AGG))
17906                     o->op_private |= OPpASSIGN_COMMON_AGG;
17907
17908                 if (l & (AAS_MY_SCALAR|AAS_LEX_SCALAR)) {
17909                     if (lr & AAS_LEX_SCALAR_COMM)
17910                         o->op_private |= OPpASSIGN_COMMON_SCALAR;
17911                     else if (   !(l & AAS_LEX_SCALAR)
17912                              && (r & AAS_DEFAV))
17913                     {
17914                         /* falsely mark
17915                          *    my (...) = @_
17916                          * as scalar-safe for performance reasons.
17917                          * (it will still have been marked _AGG if necessary */
17918                         NOOP;
17919                     }
17920                     else if (r  & (AAS_PKG_SCALAR|AAS_PKG_AGG|AAS_DANGEROUS))
17921                         /* if there are only lexicals on the LHS and no
17922                          * common ones on the RHS, then we assume that the
17923                          * only way those lexicals could also get
17924                          * on the RHS is via some sort of dereffing or
17925                          * closure, e.g.
17926                          *    $r = \$lex;
17927                          *    ($lex, $x) = (1, $$r)
17928                          * and in this case we assume the var must have
17929                          *  a bumped ref count. So if its ref count is 1,
17930                          *  it must only be on the LHS.
17931                          */
17932                         o->op_private |= OPpASSIGN_COMMON_RC1;
17933                 }
17934             }
17935
17936             /* ... = ($x)
17937              * may have to handle aggregate on LHS, but we can't
17938              * have common scalars. */
17939             if (rscalars < 2)
17940                 o->op_private &=
17941                         ~(OPpASSIGN_COMMON_SCALAR|OPpASSIGN_COMMON_RC1);
17942
17943             if ((o->op_flags & OPf_WANT) == OPf_WANT_SCALAR)
17944                 S_check_for_bool_cxt(o, 1, OPpASSIGN_TRUEBOOL, 0);
17945             break;
17946         }
17947
17948         case OP_REF:
17949             /* see if ref() is used in boolean context */
17950             if ((o->op_flags & OPf_WANT) == OPf_WANT_SCALAR)
17951                 S_check_for_bool_cxt(o, 1, OPpTRUEBOOL, OPpMAYBE_TRUEBOOL);
17952             break;
17953
17954         case OP_LENGTH:
17955             /* see if the op is used in known boolean context,
17956              * but not if OA_TARGLEX optimisation is enabled */
17957             if (   (o->op_flags & OPf_WANT) == OPf_WANT_SCALAR
17958                 && !(o->op_private & OPpTARGET_MY)
17959             )
17960                 S_check_for_bool_cxt(o, 1, OPpTRUEBOOL, 0);
17961             break;
17962
17963         case OP_POS:
17964             /* see if the op is used in known boolean context */
17965             if ((o->op_flags & OPf_WANT) == OPf_WANT_SCALAR)
17966                 S_check_for_bool_cxt(o, 1, OPpTRUEBOOL, 0);
17967             break;
17968
17969         case OP_CUSTOM: {
17970             Perl_cpeep_t cpeep =
17971                 XopENTRYCUSTOM(o, xop_peep);
17972             if (cpeep)
17973                 cpeep(aTHX_ o, oldop);
17974             break;
17975         }
17976
17977         }
17978         /* did we just null the current op? If so, re-process it to handle
17979          * eliding "empty" ops from the chain */
17980         if (o->op_type == OP_NULL && oldop && oldop->op_next == o) {
17981             o->op_opt = 0;
17982             o = oldop;
17983         }
17984         else {
17985             oldoldop = oldop;
17986             oldop = o;
17987         }
17988     }
17989     LEAVE;
17990 }
17991
17992 void
17993 Perl_peep(pTHX_ OP *o)
17994 {
17995     CALL_RPEEP(o);
17996 }
17997
17998 /*
17999 =for apidoc_section Custom Operators
18000
18001 =for apidoc Perl_custom_op_xop
18002 Return the XOP structure for a given custom op.  This macro should be
18003 considered internal to C<OP_NAME> and the other access macros: use them instead.
18004 This macro does call a function.  Prior
18005 to 5.19.6, this was implemented as a
18006 function.
18007
18008 =cut
18009 */
18010
18011
18012 /* use PERL_MAGIC_ext to call a function to free the xop structure when
18013  * freeing PL_custom_ops */
18014
18015 static int
18016 custom_op_register_free(pTHX_ SV *sv, MAGIC *mg)
18017 {
18018     XOP *xop;
18019
18020     PERL_UNUSED_ARG(mg);
18021     xop = INT2PTR(XOP *, SvIV(sv));
18022     Safefree(xop->xop_name);
18023     Safefree(xop->xop_desc);
18024     Safefree(xop);
18025     return 0;
18026 }
18027
18028
18029 static const MGVTBL custom_op_register_vtbl = {
18030     0,                          /* get */
18031     0,                          /* set */
18032     0,                          /* len */
18033     0,                          /* clear */
18034     custom_op_register_free,     /* free */
18035     0,                          /* copy */
18036     0,                          /* dup */
18037 #ifdef MGf_LOCAL
18038     0,                          /* local */
18039 #endif
18040 };
18041
18042
18043 XOPRETANY
18044 Perl_custom_op_get_field(pTHX_ const OP *o, const xop_flags_enum field)
18045 {
18046     SV *keysv;
18047     HE *he = NULL;
18048     XOP *xop;
18049
18050     static const XOP xop_null = { 0, 0, 0, 0, 0 };
18051
18052     PERL_ARGS_ASSERT_CUSTOM_OP_GET_FIELD;
18053     assert(o->op_type == OP_CUSTOM);
18054
18055     /* This is wrong. It assumes a function pointer can be cast to IV,
18056      * which isn't guaranteed, but this is what the old custom OP code
18057      * did. In principle it should be safer to Copy the bytes of the
18058      * pointer into a PV: since the new interface is hidden behind
18059      * functions, this can be changed later if necessary.  */
18060     /* Change custom_op_xop if this ever happens */
18061     keysv = sv_2mortal(newSViv(PTR2IV(o->op_ppaddr)));
18062
18063     if (PL_custom_ops)
18064         he = hv_fetch_ent(PL_custom_ops, keysv, 0, 0);
18065
18066     /* See if the op isn't registered, but its name *is* registered.
18067      * That implies someone is using the pre-5.14 API,where only name and
18068      * description could be registered. If so, fake up a real
18069      * registration.
18070      * We only check for an existing name, and assume no one will have
18071      * just registered a desc */
18072     if (!he && PL_custom_op_names &&
18073         (he = hv_fetch_ent(PL_custom_op_names, keysv, 0, 0))
18074     ) {
18075         const char *pv;
18076         STRLEN l;
18077
18078         /* XXX does all this need to be shared mem? */
18079         Newxz(xop, 1, XOP);
18080         pv = SvPV(HeVAL(he), l);
18081         XopENTRY_set(xop, xop_name, savepvn(pv, l));
18082         if (PL_custom_op_descs &&
18083             (he = hv_fetch_ent(PL_custom_op_descs, keysv, 0, 0))
18084         ) {
18085             pv = SvPV(HeVAL(he), l);
18086             XopENTRY_set(xop, xop_desc, savepvn(pv, l));
18087         }
18088         Perl_custom_op_register(aTHX_ o->op_ppaddr, xop);
18089         he = hv_fetch_ent(PL_custom_ops, keysv, 0, 0);
18090         /* add magic to the SV so that the xop struct (pointed to by
18091          * SvIV(sv)) is freed. Normally a static xop is registered, but
18092          * for this backcompat hack, we've alloced one */
18093         (void)sv_magicext(HeVAL(he), NULL, PERL_MAGIC_ext,
18094                 &custom_op_register_vtbl, NULL, 0);
18095
18096     }
18097     else {
18098         if (!he)
18099             xop = (XOP *)&xop_null;
18100         else
18101             xop = INT2PTR(XOP *, SvIV(HeVAL(he)));
18102     }
18103     {
18104         XOPRETANY any;
18105         if(field == XOPe_xop_ptr) {
18106             any.xop_ptr = xop;
18107         } else {
18108             const U32 flags = XopFLAGS(xop);
18109             if(flags & field) {
18110                 switch(field) {
18111                 case XOPe_xop_name:
18112                     any.xop_name = xop->xop_name;
18113                     break;
18114                 case XOPe_xop_desc:
18115                     any.xop_desc = xop->xop_desc;
18116                     break;
18117                 case XOPe_xop_class:
18118                     any.xop_class = xop->xop_class;
18119                     break;
18120                 case XOPe_xop_peep:
18121                     any.xop_peep = xop->xop_peep;
18122                     break;
18123                 default:
18124                     NOT_REACHED; /* NOTREACHED */
18125                     break;
18126                 }
18127             } else {
18128                 switch(field) {
18129                 case XOPe_xop_name:
18130                     any.xop_name = XOPd_xop_name;
18131                     break;
18132                 case XOPe_xop_desc:
18133                     any.xop_desc = XOPd_xop_desc;
18134                     break;
18135                 case XOPe_xop_class:
18136                     any.xop_class = XOPd_xop_class;
18137                     break;
18138                 case XOPe_xop_peep:
18139                     any.xop_peep = XOPd_xop_peep;
18140                     break;
18141                 default:
18142                     NOT_REACHED; /* NOTREACHED */
18143                     break;
18144                 }
18145             }
18146         }
18147         /* On some platforms (HP-UX, IA64) gcc emits a warning for this function:
18148          * op.c: In function 'Perl_custom_op_get_field':
18149          * op.c:...: warning: 'any.xop_name' may be used uninitialized in this function [-Wmaybe-uninitialized]
18150          * This is because on those platforms (with -DEBUGGING) NOT_REACHED
18151          * expands to assert(0), which expands to ((0) ? (void)0 :
18152          * __assert(...)), and gcc doesn't know that __assert can never return. */
18153         return any;
18154     }
18155 }
18156
18157 /*
18158 =for apidoc custom_op_register
18159 Register a custom op.  See L<perlguts/"Custom Operators">.
18160
18161 =cut
18162 */
18163
18164 void
18165 Perl_custom_op_register(pTHX_ Perl_ppaddr_t ppaddr, const XOP *xop)
18166 {
18167     SV *keysv;
18168
18169     PERL_ARGS_ASSERT_CUSTOM_OP_REGISTER;
18170
18171     /* see the comment in custom_op_xop */
18172     keysv = sv_2mortal(newSViv(PTR2IV(ppaddr)));
18173
18174     if (!PL_custom_ops)
18175         PL_custom_ops = newHV();
18176
18177     if (!hv_store_ent(PL_custom_ops, keysv, newSViv(PTR2IV(xop)), 0))
18178         Perl_croak(aTHX_ "panic: can't register custom OP %s", xop->xop_name);
18179 }
18180
18181 /*
18182
18183 =for apidoc core_prototype
18184
18185 This function assigns the prototype of the named core function to C<sv>, or
18186 to a new mortal SV if C<sv> is C<NULL>.  It returns the modified C<sv>, or
18187 C<NULL> if the core function has no prototype.  C<code> is a code as returned
18188 by C<keyword()>.  It must not be equal to 0.
18189
18190 =cut
18191 */
18192
18193 SV *
18194 Perl_core_prototype(pTHX_ SV *sv, const char *name, const int code,
18195                           int * const opnum)
18196 {
18197     int i = 0, n = 0, seen_question = 0, defgv = 0;
18198     I32 oa;
18199 #define MAX_ARGS_OP ((sizeof(I32) - 1) * 2)
18200     char str[ MAX_ARGS_OP * 2 + 2 ]; /* One ';', one '\0' */
18201     bool nullret = FALSE;
18202
18203     PERL_ARGS_ASSERT_CORE_PROTOTYPE;
18204
18205     assert (code);
18206
18207     if (!sv) sv = sv_newmortal();
18208
18209 #define retsetpvs(x,y) sv_setpvs(sv, x); if(opnum) *opnum=(y); return sv
18210
18211     switch (code < 0 ? -code : code) {
18212     case KEY_and   : case KEY_chop: case KEY_chomp:
18213     case KEY_cmp   : case KEY_defined: case KEY_delete: case KEY_exec  :
18214     case KEY_exists: case KEY_eq     : case KEY_ge    : case KEY_goto  :
18215     case KEY_grep  : case KEY_gt     : case KEY_last  : case KEY_le    :
18216     case KEY_lt    : case KEY_map    : case KEY_ne    : case KEY_next  :
18217     case KEY_or    : case KEY_print  : case KEY_printf: case KEY_qr    :
18218     case KEY_redo  : case KEY_require: case KEY_return: case KEY_say   :
18219     case KEY_select: case KEY_sort   : case KEY_split : case KEY_system:
18220     case KEY_x     : case KEY_xor    :
18221         if (!opnum) return NULL; nullret = TRUE; goto findopnum;
18222     case KEY_glob:    retsetpvs("_;", OP_GLOB);
18223     case KEY_keys:    retsetpvs("\\[%@]", OP_KEYS);
18224     case KEY_values:  retsetpvs("\\[%@]", OP_VALUES);
18225     case KEY_each:    retsetpvs("\\[%@]", OP_EACH);
18226     case KEY_pos:     retsetpvs(";\\[$*]", OP_POS);
18227     case KEY___FILE__: case KEY___LINE__: case KEY___PACKAGE__:
18228         retsetpvs("", 0);
18229     case KEY_evalbytes:
18230         name = "entereval"; break;
18231     case KEY_readpipe:
18232         name = "backtick";
18233     }
18234
18235 #undef retsetpvs
18236
18237   findopnum:
18238     while (i < MAXO) {  /* The slow way. */
18239         if (strEQ(name, PL_op_name[i])
18240             || strEQ(name, PL_op_desc[i]))
18241         {
18242             if (nullret) { assert(opnum); *opnum = i; return NULL; }
18243             goto found;
18244         }
18245         i++;
18246     }
18247     return NULL;
18248   found:
18249     defgv = PL_opargs[i] & OA_DEFGV;
18250     oa = PL_opargs[i] >> OASHIFT;
18251     while (oa) {
18252         if (oa & OA_OPTIONAL && !seen_question && (
18253               !defgv || (oa & (OA_OPTIONAL - 1)) == OA_FILEREF
18254         )) {
18255             seen_question = 1;
18256             str[n++] = ';';
18257         }
18258         if ((oa & (OA_OPTIONAL - 1)) >= OA_AVREF
18259             && (oa & (OA_OPTIONAL - 1)) <= OA_SCALARREF
18260             /* But globs are already references (kinda) */
18261             && (oa & (OA_OPTIONAL - 1)) != OA_FILEREF
18262         ) {
18263             str[n++] = '\\';
18264         }
18265         if ((oa & (OA_OPTIONAL - 1)) == OA_SCALARREF
18266          && !scalar_mod_type(NULL, i)) {
18267             str[n++] = '[';
18268             str[n++] = '$';
18269             str[n++] = '@';
18270             str[n++] = '%';
18271             if (i == OP_LOCK || i == OP_UNDEF) str[n++] = '&';
18272             str[n++] = '*';
18273             str[n++] = ']';
18274         }
18275         else str[n++] = ("?$@@%&*$")[oa & (OA_OPTIONAL - 1)];
18276         if (oa & OA_OPTIONAL && defgv && str[n-1] == '$') {
18277             str[n-1] = '_'; defgv = 0;
18278         }
18279         oa = oa >> 4;
18280     }
18281     if (code == -KEY_not || code == -KEY_getprotobynumber) str[n++] = ';';
18282     str[n++] = '\0';
18283     sv_setpvn(sv, str, n - 1);
18284     if (opnum) *opnum = i;
18285     return sv;
18286 }
18287
18288 OP *
18289 Perl_coresub_op(pTHX_ SV * const coreargssv, const int code,
18290                       const int opnum)
18291 {
18292     OP * const argop = (opnum == OP_SELECT && code) ? NULL :
18293                                         newSVOP(OP_COREARGS,0,coreargssv);
18294     OP *o;
18295
18296     PERL_ARGS_ASSERT_CORESUB_OP;
18297
18298     switch(opnum) {
18299     case 0:
18300         return op_append_elem(OP_LINESEQ,
18301                        argop,
18302                        newSLICEOP(0,
18303                                   newSVOP(OP_CONST, 0, newSViv(-code % 3)),
18304                                   newOP(OP_CALLER,0)
18305                        )
18306                );
18307     case OP_EACH:
18308     case OP_KEYS:
18309     case OP_VALUES:
18310         o = newUNOP(OP_AVHVSWITCH,0,argop);
18311         o->op_private = opnum-OP_EACH;
18312         return o;
18313     case OP_SELECT: /* which represents OP_SSELECT as well */
18314         if (code)
18315             return newCONDOP(
18316                          0,
18317                          newBINOP(OP_GT, 0,
18318                                   newAVREF(newGVOP(OP_GV, 0, PL_defgv)),
18319                                   newSVOP(OP_CONST, 0, newSVuv(1))
18320                                  ),
18321                          coresub_op(newSVuv((UV)OP_SSELECT), 0,
18322                                     OP_SSELECT),
18323                          coresub_op(coreargssv, 0, OP_SELECT)
18324                    );
18325         /* FALLTHROUGH */
18326     default:
18327         switch (PL_opargs[opnum] & OA_CLASS_MASK) {
18328         case OA_BASEOP:
18329             return op_append_elem(
18330                         OP_LINESEQ, argop,
18331                         newOP(opnum,
18332                               opnum == OP_WANTARRAY || opnum == OP_RUNCV
18333                                 ? OPpOFFBYONE << 8 : 0)
18334                    );
18335         case OA_BASEOP_OR_UNOP:
18336             if (opnum == OP_ENTEREVAL) {
18337                 o = newUNOP(OP_ENTEREVAL,OPpEVAL_COPHH<<8,argop);
18338                 if (code == -KEY_evalbytes) o->op_private |= OPpEVAL_BYTES;
18339             }
18340             else o = newUNOP(opnum,0,argop);
18341             if (opnum == OP_CALLER) o->op_private |= OPpOFFBYONE;
18342             else {
18343           onearg:
18344               if (is_handle_constructor(o, 1))
18345                 argop->op_private |= OPpCOREARGS_DEREF1;
18346               if (scalar_mod_type(NULL, opnum))
18347                 argop->op_private |= OPpCOREARGS_SCALARMOD;
18348             }
18349             return o;
18350         default:
18351             o = op_convert_list(opnum,OPf_SPECIAL*(opnum == OP_GLOB),argop);
18352             if (is_handle_constructor(o, 2))
18353                 argop->op_private |= OPpCOREARGS_DEREF2;
18354             if (opnum == OP_SUBSTR) {
18355                 o->op_private |= OPpMAYBE_LVSUB;
18356                 return o;
18357             }
18358             else goto onearg;
18359         }
18360     }
18361 }
18362
18363 void
18364 Perl_report_redefined_cv(pTHX_ const SV *name, const CV *old_cv,
18365                                SV * const *new_const_svp)
18366 {
18367     const char *hvname;
18368     bool is_const = !!CvCONST(old_cv);
18369     SV *old_const_sv = is_const ? cv_const_sv(old_cv) : NULL;
18370
18371     PERL_ARGS_ASSERT_REPORT_REDEFINED_CV;
18372
18373     if (is_const && new_const_svp && old_const_sv == *new_const_svp)
18374         return;
18375         /* They are 2 constant subroutines generated from
18376            the same constant. This probably means that
18377            they are really the "same" proxy subroutine
18378            instantiated in 2 places. Most likely this is
18379            when a constant is exported twice.  Don't warn.
18380         */
18381     if (
18382         (ckWARN(WARN_REDEFINE)
18383          && !(
18384                 CvGV(old_cv) && GvSTASH(CvGV(old_cv))
18385              && HvNAMELEN(GvSTASH(CvGV(old_cv))) == 7
18386              && (hvname = HvNAME(GvSTASH(CvGV(old_cv))),
18387                  strEQ(hvname, "autouse"))
18388              )
18389         )
18390      || (is_const
18391          && ckWARN_d(WARN_REDEFINE)
18392          && (!new_const_svp || sv_cmp(old_const_sv, *new_const_svp))
18393         )
18394     )
18395         Perl_warner(aTHX_ packWARN(WARN_REDEFINE),
18396                           is_const
18397                             ? "Constant subroutine %" SVf " redefined"
18398                             : "Subroutine %" SVf " redefined",
18399                           SVfARG(name));
18400 }
18401
18402 /*
18403 =for apidoc_section Hook manipulation
18404
18405 These functions provide convenient and thread-safe means of manipulating
18406 hook variables.
18407
18408 =cut
18409 */
18410
18411 /*
18412 =for apidoc wrap_op_checker
18413
18414 Puts a C function into the chain of check functions for a specified op
18415 type.  This is the preferred way to manipulate the L</PL_check> array.
18416 C<opcode> specifies which type of op is to be affected.  C<new_checker>
18417 is a pointer to the C function that is to be added to that opcode's
18418 check chain, and C<old_checker_p> points to the storage location where a
18419 pointer to the next function in the chain will be stored.  The value of
18420 C<new_checker> is written into the L</PL_check> array, while the value
18421 previously stored there is written to C<*old_checker_p>.
18422
18423 L</PL_check> is global to an entire process, and a module wishing to
18424 hook op checking may find itself invoked more than once per process,
18425 typically in different threads.  To handle that situation, this function
18426 is idempotent.  The location C<*old_checker_p> must initially (once
18427 per process) contain a null pointer.  A C variable of static duration
18428 (declared at file scope, typically also marked C<static> to give
18429 it internal linkage) will be implicitly initialised appropriately,
18430 if it does not have an explicit initialiser.  This function will only
18431 actually modify the check chain if it finds C<*old_checker_p> to be null.
18432 This function is also thread safe on the small scale.  It uses appropriate
18433 locking to avoid race conditions in accessing L</PL_check>.
18434
18435 When this function is called, the function referenced by C<new_checker>
18436 must be ready to be called, except for C<*old_checker_p> being unfilled.
18437 In a threading situation, C<new_checker> may be called immediately,
18438 even before this function has returned.  C<*old_checker_p> will always
18439 be appropriately set before C<new_checker> is called.  If C<new_checker>
18440 decides not to do anything special with an op that it is given (which
18441 is the usual case for most uses of op check hooking), it must chain the
18442 check function referenced by C<*old_checker_p>.
18443
18444 Taken all together, XS code to hook an op checker should typically look
18445 something like this:
18446
18447     static Perl_check_t nxck_frob;
18448     static OP *myck_frob(pTHX_ OP *op) {
18449         ...
18450         op = nxck_frob(aTHX_ op);
18451         ...
18452         return op;
18453     }
18454     BOOT:
18455         wrap_op_checker(OP_FROB, myck_frob, &nxck_frob);
18456
18457 If you want to influence compilation of calls to a specific subroutine,
18458 then use L</cv_set_call_checker_flags> rather than hooking checking of
18459 all C<entersub> ops.
18460
18461 =cut
18462 */
18463
18464 void
18465 Perl_wrap_op_checker(pTHX_ Optype opcode,
18466     Perl_check_t new_checker, Perl_check_t *old_checker_p)
18467 {
18468
18469     PERL_UNUSED_CONTEXT;
18470     PERL_ARGS_ASSERT_WRAP_OP_CHECKER;
18471     if (*old_checker_p) return;
18472     OP_CHECK_MUTEX_LOCK;
18473     if (!*old_checker_p) {
18474         *old_checker_p = PL_check[opcode];
18475         PL_check[opcode] = new_checker;
18476     }
18477     OP_CHECK_MUTEX_UNLOCK;
18478 }
18479
18480 #include "XSUB.h"
18481
18482 /* Efficient sub that returns a constant scalar value. */
18483 static void
18484 const_sv_xsub(pTHX_ CV* cv)
18485 {
18486     dXSARGS;
18487     SV *const sv = MUTABLE_SV(XSANY.any_ptr);
18488     PERL_UNUSED_ARG(items);
18489     if (!sv) {
18490         XSRETURN(0);
18491     }
18492     EXTEND(sp, 1);
18493     ST(0) = sv;
18494     XSRETURN(1);
18495 }
18496
18497 static void
18498 const_av_xsub(pTHX_ CV* cv)
18499 {
18500     dXSARGS;
18501     AV * const av = MUTABLE_AV(XSANY.any_ptr);
18502     SP -= items;
18503     assert(av);
18504 #ifndef DEBUGGING
18505     if (!av) {
18506         XSRETURN(0);
18507     }
18508 #endif
18509     if (SvRMAGICAL(av))
18510         Perl_croak(aTHX_ "Magical list constants are not supported");
18511     if (GIMME_V != G_ARRAY) {
18512         EXTEND(SP, 1);
18513         ST(0) = sv_2mortal(newSViv((IV)AvFILLp(av)+1));
18514         XSRETURN(1);
18515     }
18516     EXTEND(SP, AvFILLp(av)+1);
18517     Copy(AvARRAY(av), &ST(0), AvFILLp(av)+1, SV *);
18518     XSRETURN(AvFILLp(av)+1);
18519 }
18520
18521 /* Copy an existing cop->cop_warnings field.
18522  * If it's one of the standard addresses, just re-use the address.
18523  * This is the e implementation for the DUP_WARNINGS() macro
18524  */
18525
18526 STRLEN*
18527 Perl_dup_warnings(pTHX_ STRLEN* warnings)
18528 {
18529     Size_t size;
18530     STRLEN *new_warnings;
18531
18532     if (warnings == NULL || specialWARN(warnings))
18533         return warnings;
18534
18535     size = sizeof(*warnings) + *warnings;
18536
18537     new_warnings = (STRLEN*)PerlMemShared_malloc(size);
18538     Copy(warnings, new_warnings, size, char);
18539     return new_warnings;
18540 }
18541
18542 /*
18543  * ex: set ts=8 sts=4 sw=4 et:
18544  */