This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
perl.h: Fix comment
[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 =head1 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 =head1 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         OP * const o2
5971             = newSVREF(newGVOP(OP_GV, 0, gv_fetchpvs(";", GV_ADD|GV_NOTQUAL, SVt_PV)));
5972         o = op_convert_list(OP_JOIN, 0, op_prepend_elem(OP_LIST, o2, o));
5973     }
5974     return o;
5975 }
5976
5977 PERL_STATIC_INLINE OP *
5978 S_op_std_init(pTHX_ OP *o)
5979 {
5980     I32 type = o->op_type;
5981
5982     PERL_ARGS_ASSERT_OP_STD_INIT;
5983
5984     if (PL_opargs[type] & OA_RETSCALAR)
5985         scalar(o);
5986     if (PL_opargs[type] & OA_TARGET && !o->op_targ)
5987         o->op_targ = pad_alloc(type, SVs_PADTMP);
5988
5989     return o;
5990 }
5991
5992 PERL_STATIC_INLINE OP *
5993 S_op_integerize(pTHX_ OP *o)
5994 {
5995     I32 type = o->op_type;
5996
5997     PERL_ARGS_ASSERT_OP_INTEGERIZE;
5998
5999     /* integerize op. */
6000     if ((PL_opargs[type] & OA_OTHERINT) && (PL_hints & HINT_INTEGER))
6001     {
6002         o->op_ppaddr = PL_ppaddr[++(o->op_type)];
6003     }
6004
6005     if (type == OP_NEGATE)
6006         /* XXX might want a ck_negate() for this */
6007         cUNOPo->op_first->op_private &= ~OPpCONST_STRICT;
6008
6009     return o;
6010 }
6011
6012 /* This function exists solely to provide a scope to limit
6013    setjmp/longjmp() messing with auto variables.  It cannot be inlined because
6014    it uses setjmp
6015  */
6016 STATIC int
6017 S_fold_constants_eval(pTHX) {
6018     int ret = 0;
6019     dJMPENV;
6020
6021     JMPENV_PUSH(ret);
6022
6023     if (ret == 0) {
6024         CALLRUNOPS(aTHX);
6025     }
6026
6027     JMPENV_POP;
6028
6029     return ret;
6030 }
6031
6032 static OP *
6033 S_fold_constants(pTHX_ OP *const o)
6034 {
6035     OP *curop;
6036     OP *newop;
6037     I32 type = o->op_type;
6038     bool is_stringify;
6039     SV *sv = NULL;
6040     int ret = 0;
6041     OP *old_next;
6042     SV * const oldwarnhook = PL_warnhook;
6043     SV * const olddiehook  = PL_diehook;
6044     COP not_compiling;
6045     U8 oldwarn = PL_dowarn;
6046     I32 old_cxix;
6047
6048     PERL_ARGS_ASSERT_FOLD_CONSTANTS;
6049
6050     if (!(PL_opargs[type] & OA_FOLDCONST))
6051         goto nope;
6052
6053     switch (type) {
6054     case OP_UCFIRST:
6055     case OP_LCFIRST:
6056     case OP_UC:
6057     case OP_LC:
6058     case OP_FC:
6059 #ifdef USE_LOCALE_CTYPE
6060         if (IN_LC_COMPILETIME(LC_CTYPE))
6061             goto nope;
6062 #endif
6063         break;
6064     case OP_SLT:
6065     case OP_SGT:
6066     case OP_SLE:
6067     case OP_SGE:
6068     case OP_SCMP:
6069 #ifdef USE_LOCALE_COLLATE
6070         if (IN_LC_COMPILETIME(LC_COLLATE))
6071             goto nope;
6072 #endif
6073         break;
6074     case OP_SPRINTF:
6075         /* XXX what about the numeric ops? */
6076 #ifdef USE_LOCALE_NUMERIC
6077         if (IN_LC_COMPILETIME(LC_NUMERIC))
6078             goto nope;
6079 #endif
6080         break;
6081     case OP_PACK:
6082         if (!OpHAS_SIBLING(cLISTOPo->op_first)
6083           || OpSIBLING(cLISTOPo->op_first)->op_type != OP_CONST)
6084             goto nope;
6085         {
6086             SV * const sv = cSVOPx_sv(OpSIBLING(cLISTOPo->op_first));
6087             if (!SvPOK(sv) || SvGMAGICAL(sv)) goto nope;
6088             {
6089                 const char *s = SvPVX_const(sv);
6090                 while (s < SvEND(sv)) {
6091                     if (isALPHA_FOLD_EQ(*s, 'p')) goto nope;
6092                     s++;
6093                 }
6094             }
6095         }
6096         break;
6097     case OP_REPEAT:
6098         if (o->op_private & OPpREPEAT_DOLIST) goto nope;
6099         break;
6100     case OP_SREFGEN:
6101         if (cUNOPx(cUNOPo->op_first)->op_first->op_type != OP_CONST
6102          || SvPADTMP(cSVOPx_sv(cUNOPx(cUNOPo->op_first)->op_first)))
6103             goto nope;
6104     }
6105
6106     if (PL_parser && PL_parser->error_count)
6107         goto nope;              /* Don't try to run w/ errors */
6108
6109     for (curop = LINKLIST(o); curop != o; curop = LINKLIST(curop)) {
6110         switch (curop->op_type) {
6111         case OP_CONST:
6112             if (   (curop->op_private & OPpCONST_BARE)
6113                 && (curop->op_private & OPpCONST_STRICT)) {
6114                 no_bareword_allowed(curop);
6115                 goto nope;
6116             }
6117             /* FALLTHROUGH */
6118         case OP_LIST:
6119         case OP_SCALAR:
6120         case OP_NULL:
6121         case OP_PUSHMARK:
6122             /* Foldable; move to next op in list */
6123             break;
6124
6125         default:
6126             /* No other op types are considered foldable */
6127             goto nope;
6128         }
6129     }
6130
6131     curop = LINKLIST(o);
6132     old_next = o->op_next;
6133     o->op_next = 0;
6134     PL_op = curop;
6135
6136     old_cxix = cxstack_ix;
6137     create_eval_scope(NULL, G_FAKINGEVAL);
6138
6139     /* Verify that we don't need to save it:  */
6140     assert(PL_curcop == &PL_compiling);
6141     StructCopy(&PL_compiling, &not_compiling, COP);
6142     PL_curcop = &not_compiling;
6143     /* The above ensures that we run with all the correct hints of the
6144        currently compiling COP, but that IN_PERL_RUNTIME is true. */
6145     assert(IN_PERL_RUNTIME);
6146     PL_warnhook = PERL_WARNHOOK_FATAL;
6147     PL_diehook  = NULL;
6148
6149     /* Effective $^W=1.  */
6150     if ( ! (PL_dowarn & G_WARN_ALL_MASK))
6151         PL_dowarn |= G_WARN_ON;
6152
6153     ret = S_fold_constants_eval(aTHX);
6154
6155     switch (ret) {
6156     case 0:
6157         sv = *(PL_stack_sp--);
6158         if (o->op_targ && sv == PAD_SV(o->op_targ)) {   /* grab pad temp? */
6159             pad_swipe(o->op_targ,  FALSE);
6160         }
6161         else if (SvTEMP(sv)) {                  /* grab mortal temp? */
6162             SvREFCNT_inc_simple_void(sv);
6163             SvTEMP_off(sv);
6164         }
6165         else { assert(SvIMMORTAL(sv)); }
6166         break;
6167     case 3:
6168         /* Something tried to die.  Abandon constant folding.  */
6169         /* Pretend the error never happened.  */
6170         CLEAR_ERRSV();
6171         o->op_next = old_next;
6172         break;
6173     default:
6174         /* Don't expect 1 (setjmp failed) or 2 (something called my_exit)  */
6175         PL_warnhook = oldwarnhook;
6176         PL_diehook  = olddiehook;
6177         /* XXX note that this croak may fail as we've already blown away
6178          * the stack - eg any nested evals */
6179         Perl_croak(aTHX_ "panic: fold_constants JMPENV_PUSH returned %d", ret);
6180     }
6181     PL_dowarn   = oldwarn;
6182     PL_warnhook = oldwarnhook;
6183     PL_diehook  = olddiehook;
6184     PL_curcop = &PL_compiling;
6185
6186     /* if we croaked, depending on how we croaked the eval scope
6187      * may or may not have already been popped */
6188     if (cxstack_ix > old_cxix) {
6189         assert(cxstack_ix == old_cxix + 1);
6190         assert(CxTYPE(CX_CUR()) == CXt_EVAL);
6191         delete_eval_scope();
6192     }
6193     if (ret)
6194         goto nope;
6195
6196     /* OP_STRINGIFY and constant folding are used to implement qq.
6197        Here the constant folding is an implementation detail that we
6198        want to hide.  If the stringify op is itself already marked
6199        folded, however, then it is actually a folded join.  */
6200     is_stringify = type == OP_STRINGIFY && !o->op_folded;
6201     op_free(o);
6202     assert(sv);
6203     if (is_stringify)
6204         SvPADTMP_off(sv);
6205     else if (!SvIMMORTAL(sv)) {
6206         SvPADTMP_on(sv);
6207         SvREADONLY_on(sv);
6208     }
6209     newop = newSVOP(OP_CONST, 0, MUTABLE_SV(sv));
6210     if (!is_stringify) newop->op_folded = 1;
6211     return newop;
6212
6213  nope:
6214     return o;
6215 }
6216
6217 /* convert a constant range in list context into an OP_RV2AV, OP_CONST pair;
6218  * the constant value being an AV holding the flattened range.
6219  */
6220
6221 static void
6222 S_gen_constant_list(pTHX_ OP *o)
6223 {
6224     OP *curop, *old_next;
6225     SV * const oldwarnhook = PL_warnhook;
6226     SV * const olddiehook  = PL_diehook;
6227     COP *old_curcop;
6228     U8 oldwarn = PL_dowarn;
6229     SV **svp;
6230     AV *av;
6231     I32 old_cxix;
6232     COP not_compiling;
6233     int ret = 0;
6234     dJMPENV;
6235     bool op_was_null;
6236
6237     list(o);
6238     if (PL_parser && PL_parser->error_count)
6239         return;         /* Don't attempt to run with errors */
6240
6241     curop = LINKLIST(o);
6242     old_next = o->op_next;
6243     o->op_next = 0;
6244     op_was_null = o->op_type == OP_NULL;
6245     if (op_was_null) /* b3698342565fb462291fba4b432cfcd05b6eb4e1 */
6246         o->op_type = OP_CUSTOM;
6247     CALL_PEEP(curop);
6248     if (op_was_null)
6249         o->op_type = OP_NULL;
6250     S_prune_chain_head(&curop);
6251     PL_op = curop;
6252
6253     old_cxix = cxstack_ix;
6254     create_eval_scope(NULL, G_FAKINGEVAL);
6255
6256     old_curcop = PL_curcop;
6257     StructCopy(old_curcop, &not_compiling, COP);
6258     PL_curcop = &not_compiling;
6259     /* The above ensures that we run with all the correct hints of the
6260        current COP, but that IN_PERL_RUNTIME is true. */
6261     assert(IN_PERL_RUNTIME);
6262     PL_warnhook = PERL_WARNHOOK_FATAL;
6263     PL_diehook  = NULL;
6264     JMPENV_PUSH(ret);
6265
6266     /* Effective $^W=1.  */
6267     if ( ! (PL_dowarn & G_WARN_ALL_MASK))
6268         PL_dowarn |= G_WARN_ON;
6269
6270     switch (ret) {
6271     case 0:
6272 #if defined DEBUGGING && !defined DEBUGGING_RE_ONLY
6273         PL_curstackinfo->si_stack_hwm = 0; /* stop valgrind complaining */
6274 #endif
6275         Perl_pp_pushmark(aTHX);
6276         CALLRUNOPS(aTHX);
6277         PL_op = curop;
6278         assert (!(curop->op_flags & OPf_SPECIAL));
6279         assert(curop->op_type == OP_RANGE);
6280         Perl_pp_anonlist(aTHX);
6281         break;
6282     case 3:
6283         CLEAR_ERRSV();
6284         o->op_next = old_next;
6285         break;
6286     default:
6287         JMPENV_POP;
6288         PL_warnhook = oldwarnhook;
6289         PL_diehook = olddiehook;
6290         Perl_croak(aTHX_ "panic: gen_constant_list JMPENV_PUSH returned %d",
6291             ret);
6292     }
6293
6294     JMPENV_POP;
6295     PL_dowarn = oldwarn;
6296     PL_warnhook = oldwarnhook;
6297     PL_diehook = olddiehook;
6298     PL_curcop = old_curcop;
6299
6300     if (cxstack_ix > old_cxix) {
6301         assert(cxstack_ix == old_cxix + 1);
6302         assert(CxTYPE(CX_CUR()) == CXt_EVAL);
6303         delete_eval_scope();
6304     }
6305     if (ret)
6306         return;
6307
6308     OpTYPE_set(o, OP_RV2AV);
6309     o->op_flags &= ~OPf_REF;    /* treat \(1..2) like an ordinary list */
6310     o->op_flags |= OPf_PARENS;  /* and flatten \(1..2,3) */
6311     o->op_opt = 0;              /* needs to be revisited in rpeep() */
6312     av = (AV *)SvREFCNT_inc_NN(*PL_stack_sp--);
6313
6314     /* replace subtree with an OP_CONST */
6315     curop = ((UNOP*)o)->op_first;
6316     op_sibling_splice(o, NULL, -1, newSVOP(OP_CONST, 0, (SV *)av));
6317     op_free(curop);
6318
6319     if (AvFILLp(av) != -1)
6320         for (svp = AvARRAY(av) + AvFILLp(av); svp >= AvARRAY(av); --svp)
6321         {
6322             SvPADTMP_on(*svp);
6323             SvREADONLY_on(*svp);
6324         }
6325     LINKLIST(o);
6326     list(o);
6327     return;
6328 }
6329
6330 /*
6331 =head1 Optree Manipulation Functions
6332 */
6333
6334 /* List constructors */
6335
6336 /*
6337 =for apidoc op_append_elem
6338
6339 Append an item to the list of ops contained directly within a list-type
6340 op, returning the lengthened list.  C<first> is the list-type op,
6341 and C<last> is the op to append to the list.  C<optype> specifies the
6342 intended opcode for the list.  If C<first> is not already a list of the
6343 right type, it will be upgraded into one.  If either C<first> or C<last>
6344 is null, the other is returned unchanged.
6345
6346 =cut
6347 */
6348
6349 OP *
6350 Perl_op_append_elem(pTHX_ I32 type, OP *first, OP *last)
6351 {
6352     if (!first)
6353         return last;
6354
6355     if (!last)
6356         return first;
6357
6358     if (first->op_type != (unsigned)type
6359         || (type == OP_LIST && (first->op_flags & OPf_PARENS)))
6360     {
6361         return newLISTOP(type, 0, first, last);
6362     }
6363
6364     op_sibling_splice(first, ((LISTOP*)first)->op_last, 0, last);
6365     first->op_flags |= OPf_KIDS;
6366     return first;
6367 }
6368
6369 /*
6370 =for apidoc op_append_list
6371
6372 Concatenate the lists of ops contained directly within two list-type ops,
6373 returning the combined list.  C<first> and C<last> are the list-type ops
6374 to concatenate.  C<optype> specifies the intended opcode for the list.
6375 If either C<first> or C<last> is not already a list of the right type,
6376 it will be upgraded into one.  If either C<first> or C<last> is null,
6377 the other is returned unchanged.
6378
6379 =cut
6380 */
6381
6382 OP *
6383 Perl_op_append_list(pTHX_ I32 type, OP *first, OP *last)
6384 {
6385     if (!first)
6386         return last;
6387
6388     if (!last)
6389         return first;
6390
6391     if (first->op_type != (unsigned)type)
6392         return op_prepend_elem(type, first, last);
6393
6394     if (last->op_type != (unsigned)type)
6395         return op_append_elem(type, first, last);
6396
6397     OpMORESIB_set(((LISTOP*)first)->op_last, ((LISTOP*)last)->op_first);
6398     ((LISTOP*)first)->op_last = ((LISTOP*)last)->op_last;
6399     OpLASTSIB_set(((LISTOP*)first)->op_last, first);
6400     first->op_flags |= (last->op_flags & OPf_KIDS);
6401
6402     S_op_destroy(aTHX_ last);
6403
6404     return first;
6405 }
6406
6407 /*
6408 =for apidoc op_prepend_elem
6409
6410 Prepend an item to the list of ops contained directly within a list-type
6411 op, returning the lengthened list.  C<first> is the op to prepend to the
6412 list, and C<last> is the list-type op.  C<optype> specifies the intended
6413 opcode for the list.  If C<last> is not already a list of the right type,
6414 it will be upgraded into one.  If either C<first> or C<last> is null,
6415 the other is returned unchanged.
6416
6417 =cut
6418 */
6419
6420 OP *
6421 Perl_op_prepend_elem(pTHX_ I32 type, OP *first, OP *last)
6422 {
6423     if (!first)
6424         return last;
6425
6426     if (!last)
6427         return first;
6428
6429     if (last->op_type == (unsigned)type) {
6430         if (type == OP_LIST) {  /* already a PUSHMARK there */
6431             /* insert 'first' after pushmark */
6432             op_sibling_splice(last, cLISTOPx(last)->op_first, 0, first);
6433             if (!(first->op_flags & OPf_PARENS))
6434                 last->op_flags &= ~OPf_PARENS;
6435         }
6436         else
6437             op_sibling_splice(last, NULL, 0, first);
6438         last->op_flags |= OPf_KIDS;
6439         return last;
6440     }
6441
6442     return newLISTOP(type, 0, first, last);
6443 }
6444
6445 /*
6446 =for apidoc op_convert_list
6447
6448 Converts C<o> into a list op if it is not one already, and then converts it
6449 into the specified C<type>, calling its check function, allocating a target if
6450 it needs one, and folding constants.
6451
6452 A list-type op is usually constructed one kid at a time via C<newLISTOP>,
6453 C<op_prepend_elem> and C<op_append_elem>.  Then finally it is passed to
6454 C<op_convert_list> to make it the right type.
6455
6456 =cut
6457 */
6458
6459 OP *
6460 Perl_op_convert_list(pTHX_ I32 type, I32 flags, OP *o)
6461 {
6462     if (type < 0) type = -type, flags |= OPf_SPECIAL;
6463     if (!o || o->op_type != OP_LIST)
6464         o = force_list(o, 0);
6465     else
6466     {
6467         o->op_flags &= ~OPf_WANT;
6468         o->op_private &= ~OPpLVAL_INTRO;
6469     }
6470
6471     if (!(PL_opargs[type] & OA_MARK))
6472         op_null(cLISTOPo->op_first);
6473     else {
6474         OP * const kid2 = OpSIBLING(cLISTOPo->op_first);
6475         if (kid2 && kid2->op_type == OP_COREARGS) {
6476             op_null(cLISTOPo->op_first);
6477             kid2->op_private |= OPpCOREARGS_PUSHMARK;
6478         }
6479     }
6480
6481     if (type != OP_SPLIT)
6482         /* At this point o is a LISTOP, but OP_SPLIT is a PMOP; let
6483          * ck_split() create a real PMOP and leave the op's type as listop
6484          * for now. Otherwise op_free() etc will crash.
6485          */
6486         OpTYPE_set(o, type);
6487
6488     o->op_flags |= flags;
6489     if (flags & OPf_FOLDED)
6490         o->op_folded = 1;
6491
6492     o = CHECKOP(type, o);
6493     if (o->op_type != (unsigned)type)
6494         return o;
6495
6496     return fold_constants(op_integerize(op_std_init(o)));
6497 }
6498
6499 /* Constructors */
6500
6501
6502 /*
6503 =head1 Optree construction
6504
6505 =for apidoc newNULLLIST
6506
6507 Constructs, checks, and returns a new C<stub> op, which represents an
6508 empty list expression.
6509
6510 =cut
6511 */
6512
6513 OP *
6514 Perl_newNULLLIST(pTHX)
6515 {
6516     return newOP(OP_STUB, 0);
6517 }
6518
6519 /* promote o and any siblings to be a list if its not already; i.e.
6520  *
6521  *  o - A - B
6522  *
6523  * becomes
6524  *
6525  *  list
6526  *    |
6527  *  pushmark - o - A - B
6528  *
6529  * If nullit it true, the list op is nulled.
6530  */
6531
6532 static OP *
6533 S_force_list(pTHX_ OP *o, bool nullit)
6534 {
6535     if (!o || o->op_type != OP_LIST) {
6536         OP *rest = NULL;
6537         if (o) {
6538             /* manually detach any siblings then add them back later */
6539             rest = OpSIBLING(o);
6540             OpLASTSIB_set(o, NULL);
6541         }
6542         o = newLISTOP(OP_LIST, 0, o, NULL);
6543         if (rest)
6544             op_sibling_splice(o, cLISTOPo->op_last, 0, rest);
6545     }
6546     if (nullit)
6547         op_null(o);
6548     return o;
6549 }
6550
6551 /*
6552 =for apidoc newLISTOP
6553
6554 Constructs, checks, and returns an op of any list type.  C<type> is
6555 the opcode.  C<flags> gives the eight bits of C<op_flags>, except that
6556 C<OPf_KIDS> will be set automatically if required.  C<first> and C<last>
6557 supply up to two ops to be direct children of the list op; they are
6558 consumed by this function and become part of the constructed op tree.
6559
6560 For most list operators, the check function expects all the kid ops to be
6561 present already, so calling C<newLISTOP(OP_JOIN, ...)> (e.g.) is not
6562 appropriate.  What you want to do in that case is create an op of type
6563 C<OP_LIST>, append more children to it, and then call L</op_convert_list>.
6564 See L</op_convert_list> for more information.
6565
6566
6567 =cut
6568 */
6569
6570 OP *
6571 Perl_newLISTOP(pTHX_ I32 type, I32 flags, OP *first, OP *last)
6572 {
6573     LISTOP *listop;
6574     /* Note that allocating an OP_PUSHMARK can die under Safe.pm if
6575      * pushmark is banned. So do it now while existing ops are in a
6576      * consistent state, in case they suddenly get freed */
6577     OP* const pushop = type == OP_LIST ? newOP(OP_PUSHMARK, 0) : NULL;
6578
6579     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_LISTOP
6580         || type == OP_CUSTOM);
6581
6582     NewOp(1101, listop, 1, LISTOP);
6583     OpTYPE_set(listop, type);
6584     if (first || last)
6585         flags |= OPf_KIDS;
6586     listop->op_flags = (U8)flags;
6587
6588     if (!last && first)
6589         last = first;
6590     else if (!first && last)
6591         first = last;
6592     else if (first)
6593         OpMORESIB_set(first, last);
6594     listop->op_first = first;
6595     listop->op_last = last;
6596
6597     if (pushop) {
6598         OpMORESIB_set(pushop, first);
6599         listop->op_first = pushop;
6600         listop->op_flags |= OPf_KIDS;
6601         if (!last)
6602             listop->op_last = pushop;
6603     }
6604     if (listop->op_last)
6605         OpLASTSIB_set(listop->op_last, (OP*)listop);
6606
6607     return CHECKOP(type, listop);
6608 }
6609
6610 /*
6611 =for apidoc newOP
6612
6613 Constructs, checks, and returns an op of any base type (any type that
6614 has no extra fields).  C<type> is the opcode.  C<flags> gives the
6615 eight bits of C<op_flags>, and, shifted up eight bits, the eight bits
6616 of C<op_private>.
6617
6618 =cut
6619 */
6620
6621 OP *
6622 Perl_newOP(pTHX_ I32 type, I32 flags)
6623 {
6624     OP *o;
6625
6626     if (type == -OP_ENTEREVAL) {
6627         type = OP_ENTEREVAL;
6628         flags |= OPpEVAL_BYTES<<8;
6629     }
6630
6631     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_BASEOP
6632         || (PL_opargs[type] & OA_CLASS_MASK) == OA_BASEOP_OR_UNOP
6633         || (PL_opargs[type] & OA_CLASS_MASK) == OA_FILESTATOP
6634         || (PL_opargs[type] & OA_CLASS_MASK) == OA_LOOPEXOP);
6635
6636     NewOp(1101, o, 1, OP);
6637     OpTYPE_set(o, type);
6638     o->op_flags = (U8)flags;
6639
6640     o->op_next = o;
6641     o->op_private = (U8)(0 | (flags >> 8));
6642     if (PL_opargs[type] & OA_RETSCALAR)
6643         scalar(o);
6644     if (PL_opargs[type] & OA_TARGET)
6645         o->op_targ = pad_alloc(type, SVs_PADTMP);
6646     return CHECKOP(type, o);
6647 }
6648
6649 /*
6650 =for apidoc newUNOP
6651
6652 Constructs, checks, and returns an op of any unary type.  C<type> is
6653 the opcode.  C<flags> gives the eight bits of C<op_flags>, except that
6654 C<OPf_KIDS> will be set automatically if required, and, shifted up eight
6655 bits, the eight bits of C<op_private>, except that the bit with value 1
6656 is automatically set.  C<first> supplies an optional op to be the direct
6657 child of the unary op; it is consumed by this function and become part
6658 of the constructed op tree.
6659
6660 =for apidoc Amnh||OPf_KIDS
6661
6662 =cut
6663 */
6664
6665 OP *
6666 Perl_newUNOP(pTHX_ I32 type, I32 flags, OP *first)
6667 {
6668     UNOP *unop;
6669
6670     if (type == -OP_ENTEREVAL) {
6671         type = OP_ENTEREVAL;
6672         flags |= OPpEVAL_BYTES<<8;
6673     }
6674
6675     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_UNOP
6676         || (PL_opargs[type] & OA_CLASS_MASK) == OA_BASEOP_OR_UNOP
6677         || (PL_opargs[type] & OA_CLASS_MASK) == OA_FILESTATOP
6678         || (PL_opargs[type] & OA_CLASS_MASK) == OA_LOOPEXOP
6679         || type == OP_SASSIGN
6680         || type == OP_ENTERTRY
6681         || type == OP_CUSTOM
6682         || type == OP_NULL );
6683
6684     if (!first)
6685         first = newOP(OP_STUB, 0);
6686     if (PL_opargs[type] & OA_MARK)
6687         first = force_list(first, 1);
6688
6689     NewOp(1101, unop, 1, UNOP);
6690     OpTYPE_set(unop, type);
6691     unop->op_first = first;
6692     unop->op_flags = (U8)(flags | OPf_KIDS);
6693     unop->op_private = (U8)(1 | (flags >> 8));
6694
6695     if (!OpHAS_SIBLING(first)) /* true unless weird syntax error */
6696         OpLASTSIB_set(first, (OP*)unop);
6697
6698     unop = (UNOP*) CHECKOP(type, unop);
6699     if (unop->op_next)
6700         return (OP*)unop;
6701
6702     return fold_constants(op_integerize(op_std_init((OP *) unop)));
6703 }
6704
6705 /*
6706 =for apidoc newUNOP_AUX
6707
6708 Similar to C<newUNOP>, but creates an C<UNOP_AUX> struct instead, with C<op_aux>
6709 initialised to C<aux>
6710
6711 =cut
6712 */
6713
6714 OP *
6715 Perl_newUNOP_AUX(pTHX_ I32 type, I32 flags, OP *first, UNOP_AUX_item *aux)
6716 {
6717     UNOP_AUX *unop;
6718
6719     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_UNOP_AUX
6720         || type == OP_CUSTOM);
6721
6722     NewOp(1101, unop, 1, UNOP_AUX);
6723     unop->op_type = (OPCODE)type;
6724     unop->op_ppaddr = PL_ppaddr[type];
6725     unop->op_first = first;
6726     unop->op_flags = (U8)(flags | (first ? OPf_KIDS : 0));
6727     unop->op_private = (U8)((first ? 1 : 0) | (flags >> 8));
6728     unop->op_aux = aux;
6729
6730     if (first && !OpHAS_SIBLING(first)) /* true unless weird syntax error */
6731         OpLASTSIB_set(first, (OP*)unop);
6732
6733     unop = (UNOP_AUX*) CHECKOP(type, unop);
6734
6735     return op_std_init((OP *) unop);
6736 }
6737
6738 /*
6739 =for apidoc newMETHOP
6740
6741 Constructs, checks, and returns an op of method type with a method name
6742 evaluated at runtime.  C<type> is the opcode.  C<flags> gives the eight
6743 bits of C<op_flags>, except that C<OPf_KIDS> will be set automatically,
6744 and, shifted up eight bits, the eight bits of C<op_private>, except that
6745 the bit with value 1 is automatically set.  C<dynamic_meth> supplies an
6746 op which evaluates method name; it is consumed by this function and
6747 become part of the constructed op tree.
6748 Supported optypes: C<OP_METHOD>.
6749
6750 =cut
6751 */
6752
6753 static OP*
6754 S_newMETHOP_internal(pTHX_ I32 type, I32 flags, OP* dynamic_meth, SV* const_meth) {
6755     METHOP *methop;
6756
6757     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_METHOP
6758         || type == OP_CUSTOM);
6759
6760     NewOp(1101, methop, 1, METHOP);
6761     if (dynamic_meth) {
6762         if (PL_opargs[type] & OA_MARK) dynamic_meth = force_list(dynamic_meth, 1);
6763         methop->op_flags = (U8)(flags | OPf_KIDS);
6764         methop->op_u.op_first = dynamic_meth;
6765         methop->op_private = (U8)(1 | (flags >> 8));
6766
6767         if (!OpHAS_SIBLING(dynamic_meth))
6768             OpLASTSIB_set(dynamic_meth, (OP*)methop);
6769     }
6770     else {
6771         assert(const_meth);
6772         methop->op_flags = (U8)(flags & ~OPf_KIDS);
6773         methop->op_u.op_meth_sv = const_meth;
6774         methop->op_private = (U8)(0 | (flags >> 8));
6775         methop->op_next = (OP*)methop;
6776     }
6777
6778 #ifdef USE_ITHREADS
6779     methop->op_rclass_targ = 0;
6780 #else
6781     methop->op_rclass_sv = NULL;
6782 #endif
6783
6784     OpTYPE_set(methop, type);
6785     return CHECKOP(type, methop);
6786 }
6787
6788 OP *
6789 Perl_newMETHOP (pTHX_ I32 type, I32 flags, OP* dynamic_meth) {
6790     PERL_ARGS_ASSERT_NEWMETHOP;
6791     return newMETHOP_internal(type, flags, dynamic_meth, NULL);
6792 }
6793
6794 /*
6795 =for apidoc newMETHOP_named
6796
6797 Constructs, checks, and returns an op of method type with a constant
6798 method name.  C<type> is the opcode.  C<flags> gives the eight bits of
6799 C<op_flags>, and, shifted up eight bits, the eight bits of
6800 C<op_private>.  C<const_meth> supplies a constant method name;
6801 it must be a shared COW string.
6802 Supported optypes: C<OP_METHOD_NAMED>.
6803
6804 =cut
6805 */
6806
6807 OP *
6808 Perl_newMETHOP_named (pTHX_ I32 type, I32 flags, SV* const_meth) {
6809     PERL_ARGS_ASSERT_NEWMETHOP_NAMED;
6810     return newMETHOP_internal(type, flags, NULL, const_meth);
6811 }
6812
6813 /*
6814 =for apidoc newBINOP
6815
6816 Constructs, checks, and returns an op of any binary type.  C<type>
6817 is the opcode.  C<flags> gives the eight bits of C<op_flags>, except
6818 that C<OPf_KIDS> will be set automatically, and, shifted up eight bits,
6819 the eight bits of C<op_private>, except that the bit with value 1 or
6820 2 is automatically set as required.  C<first> and C<last> supply up to
6821 two ops to be the direct children of the binary op; they are consumed
6822 by this function and become part of the constructed op tree.
6823
6824 =cut
6825 */
6826
6827 OP *
6828 Perl_newBINOP(pTHX_ I32 type, I32 flags, OP *first, OP *last)
6829 {
6830     BINOP *binop;
6831
6832     ASSUME((PL_opargs[type] & OA_CLASS_MASK) == OA_BINOP
6833         || type == OP_NULL || type == OP_CUSTOM);
6834
6835     NewOp(1101, binop, 1, BINOP);
6836
6837     if (!first)
6838         first = newOP(OP_NULL, 0);
6839
6840     OpTYPE_set(binop, type);
6841     binop->op_first = first;
6842     binop->op_flags = (U8)(flags | OPf_KIDS);
6843     if (!last) {
6844         last = first;
6845         binop->op_private = (U8)(1 | (flags >> 8));
6846     }
6847     else {
6848         binop->op_private = (U8)(2 | (flags >> 8));
6849         OpMORESIB_set(first, last);
6850     }
6851
6852     if (!OpHAS_SIBLING(last)) /* true unless weird syntax error */
6853         OpLASTSIB_set(last, (OP*)binop);
6854
6855     binop->op_last = OpSIBLING(binop->op_first);
6856     if (binop->op_last)
6857         OpLASTSIB_set(binop->op_last, (OP*)binop);
6858
6859     binop = (BINOP*)CHECKOP(type, binop);
6860     if (binop->op_next || binop->op_type != (OPCODE)type)
6861         return (OP*)binop;
6862
6863     return fold_constants(op_integerize(op_std_init((OP *)binop)));
6864 }
6865
6866 void
6867 Perl_invmap_dump(pTHX_ SV* invlist, UV *map)
6868 {
6869     const char indent[] = "    ";
6870
6871     UV len = _invlist_len(invlist);
6872     UV * array = invlist_array(invlist);
6873     UV i;
6874
6875     PERL_ARGS_ASSERT_INVMAP_DUMP;
6876
6877     for (i = 0; i < len; i++) {
6878         UV start = array[i];
6879         UV end   = (i + 1 < len) ? array[i+1] - 1 : IV_MAX;
6880
6881         PerlIO_printf(Perl_debug_log, "%s[%" UVuf "] 0x%04" UVXf, indent, i, start);
6882         if (end == IV_MAX) {
6883             PerlIO_printf(Perl_debug_log, " .. INFTY");
6884         }
6885         else if (end != start) {
6886             PerlIO_printf(Perl_debug_log, " .. 0x%04" UVXf, end);
6887         }
6888         else {
6889             PerlIO_printf(Perl_debug_log, "            ");
6890         }
6891
6892         PerlIO_printf(Perl_debug_log, "\t");
6893
6894         if (map[i] == TR_UNLISTED) {
6895             PerlIO_printf(Perl_debug_log, "TR_UNLISTED\n");
6896         }
6897         else if (map[i] == TR_SPECIAL_HANDLING) {
6898             PerlIO_printf(Perl_debug_log, "TR_SPECIAL_HANDLING\n");
6899         }
6900         else {
6901             PerlIO_printf(Perl_debug_log, "0x%04" UVXf "\n", map[i]);
6902         }
6903     }
6904 }
6905
6906 /* Given an OP_TRANS / OP_TRANSR op o, plus OP_CONST ops expr and repl
6907  * containing the search and replacement strings, assemble into
6908  * a translation table attached as o->op_pv.
6909  * Free expr and repl.
6910  * It expects the toker to have already set the
6911  *   OPpTRANS_COMPLEMENT
6912  *   OPpTRANS_SQUASH
6913  *   OPpTRANS_DELETE
6914  * flags as appropriate; this function may add
6915  *   OPpTRANS_USE_SVOP
6916  *   OPpTRANS_CAN_FORCE_UTF8
6917  *   OPpTRANS_IDENTICAL
6918  *   OPpTRANS_GROWS
6919  * flags
6920  */
6921
6922 static OP *
6923 S_pmtrans(pTHX_ OP *o, OP *expr, OP *repl)
6924 {
6925     /* This function compiles a tr///, from data gathered from toke.c, into a
6926      * form suitable for use by do_trans() in doop.c at runtime.
6927      *
6928      * It first normalizes the data, while discarding extraneous inputs; then
6929      * writes out the compiled data.  The normalization allows for complete
6930      * analysis, and avoids some false negatives and positives earlier versions
6931      * of this code had.
6932      *
6933      * The normalization form is an inversion map (described below in detail).
6934      * This is essentially the compiled form for tr///'s that require UTF-8,
6935      * and its easy to use it to write the 257-byte table for tr///'s that
6936      * don't need UTF-8.  That table is identical to what's been in use for
6937      * many perl versions, except that it doesn't handle some edge cases that
6938      * it used to, involving code points above 255.  The UTF-8 form now handles
6939      * these.  (This could be changed with extra coding should it shown to be
6940      * desirable.)
6941      *
6942      * If the complement (/c) option is specified, the lhs string (tstr) is
6943      * parsed into an inversion list.  Complementing these is trivial.  Then a
6944      * complemented tstr is built from that, and used thenceforth.  This hides
6945      * the fact that it was complemented from almost all successive code.
6946      *
6947      * One of the important characteristics to know about the input is whether
6948      * the transliteration may be done in place, or does a temporary need to be
6949      * allocated, then copied.  If the replacement for every character in every
6950      * possible string takes up no more bytes than the character it
6951      * replaces, then it can be edited in place.  Otherwise the replacement
6952      * could overwrite a byte we are about to read, depending on the strings
6953      * being processed.  The comments and variable names here refer to this as
6954      * "growing".  Some inputs won't grow, and might even shrink under /d, but
6955      * some inputs could grow, so we have to assume any given one might grow.
6956      * On very long inputs, the temporary could eat up a lot of memory, so we
6957      * want to avoid it if possible.  For non-UTF-8 inputs, everything is
6958      * single-byte, so can be edited in place, unless there is something in the
6959      * pattern that could force it into UTF-8.  The inversion map makes it
6960      * feasible to determine this.  Previous versions of this code pretty much
6961      * punted on determining if UTF-8 could be edited in place.  Now, this code
6962      * is rigorous in making that determination.
6963      *
6964      * Another characteristic we need to know is whether the lhs and rhs are
6965      * identical.  If so, and no other flags are present, the only effect of
6966      * the tr/// is to count the characters present in the input that are
6967      * mentioned in the lhs string.  The implementation of that is easier and
6968      * runs faster than the more general case.  Normalizing here allows for
6969      * accurate determination of this.  Previously there were false negatives
6970      * possible.
6971      *
6972      * Instead of 'transliterated', the comments here use 'unmapped' for the
6973      * characters that are left unchanged by the operation; otherwise they are
6974      * 'mapped'
6975      *
6976      * The lhs of the tr/// is here referred to as the t side.
6977      * The rhs of the tr/// is here referred to as the r side.
6978      */
6979
6980     SV * const tstr = ((SVOP*)expr)->op_sv;
6981     SV * const rstr = ((SVOP*)repl)->op_sv;
6982     STRLEN tlen;
6983     STRLEN rlen;
6984     const U8 * t0 = (U8*)SvPV_const(tstr, tlen);
6985     const U8 * r0 = (U8*)SvPV_const(rstr, rlen);
6986     const U8 * t = t0;
6987     const U8 * r = r0;
6988     UV t_count = 0, r_count = 0;  /* Number of characters in search and
6989                                          replacement lists */
6990
6991     /* khw thinks some of the private flags for this op are quaintly named.
6992      * OPpTRANS_GROWS for example is TRUE if the replacement for some lhs
6993      * character when represented in UTF-8 is longer than the original
6994      * character's UTF-8 representation */
6995     const bool complement = cBOOL(o->op_private & OPpTRANS_COMPLEMENT);
6996     const bool squash     = cBOOL(o->op_private & OPpTRANS_SQUASH);
6997     const bool del        = cBOOL(o->op_private & OPpTRANS_DELETE);
6998
6999     /* Set to true if there is some character < 256 in the lhs that maps to
7000      * above 255.  If so, a non-UTF-8 match string can be forced into being in
7001      * UTF-8 by a tr/// operation. */
7002     bool can_force_utf8 = FALSE;
7003
7004     /* What is the maximum expansion factor in UTF-8 transliterations.  If a
7005      * 2-byte UTF-8 encoded character is to be replaced by a 3-byte one, its
7006      * expansion factor is 1.5.  This number is used at runtime to calculate
7007      * how much space to allocate for non-inplace transliterations.  Without
7008      * this number, the worst case is 14, which is extremely unlikely to happen
7009      * in real life, and could require significant memory overhead. */
7010     NV max_expansion = 1.;
7011
7012     UV t_range_count, r_range_count, min_range_count;
7013     UV* t_array;
7014     SV* t_invlist;
7015     UV* r_map;
7016     UV r_cp, t_cp;
7017     UV t_cp_end = (UV) -1;
7018     UV r_cp_end;
7019     Size_t len;
7020     AV* invmap;
7021     UV final_map = TR_UNLISTED;    /* The final character in the replacement
7022                                       list, updated as we go along.  Initialize
7023                                       to something illegal */
7024
7025     bool rstr_utf8 = cBOOL(SvUTF8(rstr));
7026     bool tstr_utf8 = cBOOL(SvUTF8(tstr));
7027
7028     const U8* tend = t + tlen;
7029     const U8* rend = r + rlen;
7030
7031     SV * inverted_tstr = NULL;
7032
7033     Size_t i;
7034     unsigned int pass2;
7035
7036     /* This routine implements detection of a transliteration having a longer
7037      * UTF-8 representation than its source, by partitioning all the possible
7038      * code points of the platform into equivalence classes of the same UTF-8
7039      * byte length in the first pass.  As it constructs the mappings, it carves
7040      * these up into smaller chunks, but doesn't merge any together.  This
7041      * makes it easy to find the instances it's looking for.  A second pass is
7042      * done after this has been determined which merges things together to
7043      * shrink the table for runtime.  The table below is used for both ASCII
7044      * and EBCDIC platforms.  On EBCDIC, the byte length is not monotonically
7045      * increasing for code points below 256.  To correct for that, the macro
7046      * CP_ADJUST defined below converts those code points to ASCII in the first
7047      * pass, and we use the ASCII partition values.  That works because the
7048      * growth factor will be unaffected, which is all that is calculated during
7049      * the first pass. */
7050     UV PL_partition_by_byte_length[] = {
7051         0,
7052         0x80,   /* Below this is 1 byte representations */
7053         (32 * (1UL << (    UTF_ACCUMULATION_SHIFT))),   /* 2 bytes below this */
7054         (16 * (1UL << (2 * UTF_ACCUMULATION_SHIFT))),   /* 3 bytes below this */
7055         ( 8 * (1UL << (3 * UTF_ACCUMULATION_SHIFT))),   /* 4 bytes below this */
7056         ( 4 * (1UL << (4 * UTF_ACCUMULATION_SHIFT))),   /* 5 bytes below this */
7057         ( 2 * (1UL << (5 * UTF_ACCUMULATION_SHIFT)))    /* 6 bytes below this */
7058
7059 #  ifdef UV_IS_QUAD
7060                                                     ,
7061         ( ((UV) 1U << (6 * UTF_ACCUMULATION_SHIFT)))    /* 7 bytes below this */
7062 #  endif
7063
7064     };
7065
7066     PERL_ARGS_ASSERT_PMTRANS;
7067
7068     PL_hints |= HINT_BLOCK_SCOPE;
7069
7070     /* If /c, the search list is sorted and complemented.  This is now done by
7071      * creating an inversion list from it, and then trivially inverting that.
7072      * The previous implementation used qsort, but creating the list
7073      * automatically keeps it sorted as we go along */
7074     if (complement) {
7075         UV start, end;
7076         SV * inverted_tlist = _new_invlist(tlen);
7077         Size_t temp_len;
7078
7079         DEBUG_y(PerlIO_printf(Perl_debug_log,
7080                     "%s: %d: tstr before inversion=\n%s\n",
7081                     __FILE__, __LINE__, _byte_dump_string(t, tend - t, 0)));
7082
7083         while (t < tend) {
7084
7085             /* Non-utf8 strings don't have ranges, so each character is listed
7086              * out */
7087             if (! tstr_utf8) {
7088                 inverted_tlist = add_cp_to_invlist(inverted_tlist, *t);
7089                 t++;
7090             }
7091             else {  /* But UTF-8 strings have been parsed in toke.c to have
7092                  * ranges if appropriate. */
7093                 UV t_cp;
7094                 Size_t t_char_len;
7095
7096                 /* Get the first character */
7097                 t_cp = valid_utf8_to_uvchr(t, &t_char_len);
7098                 t += t_char_len;
7099
7100                 /* If the next byte indicates that this wasn't the first
7101                  * element of a range, the range is just this one */
7102                 if (t >= tend || *t != RANGE_INDICATOR) {
7103                     inverted_tlist = add_cp_to_invlist(inverted_tlist, t_cp);
7104                 }
7105                 else { /* Otherwise, ignore the indicator byte, and get the
7106                           final element, and add the whole range */
7107                     t++;
7108                     t_cp_end = valid_utf8_to_uvchr(t, &t_char_len);
7109                     t += t_char_len;
7110
7111                     inverted_tlist = _add_range_to_invlist(inverted_tlist,
7112                                                       t_cp, t_cp_end);
7113                 }
7114             }
7115         } /* End of parse through tstr */
7116
7117         /* The inversion list is done; now invert it */
7118         _invlist_invert(inverted_tlist);
7119
7120         /* Now go through the inverted list and create a new tstr for the rest
7121          * of the routine to use.  Since the UTF-8 version can have ranges, and
7122          * can be much more compact than the non-UTF-8 version, we create the
7123          * string in UTF-8 even if not necessary.  (This is just an intermediate
7124          * value that gets thrown away anyway.) */
7125         invlist_iterinit(inverted_tlist);
7126         inverted_tstr = newSVpvs("");
7127         while (invlist_iternext(inverted_tlist, &start, &end)) {
7128             U8 temp[UTF8_MAXBYTES];
7129             U8 * temp_end_pos;
7130
7131             /* IV_MAX keeps things from going out of bounds */
7132             start = MIN(IV_MAX, start);
7133             end   = MIN(IV_MAX, end);
7134
7135             temp_end_pos = uvchr_to_utf8(temp, start);
7136             sv_catpvn(inverted_tstr, (char *) temp, temp_end_pos - temp);
7137
7138             if (start != end) {
7139                 Perl_sv_catpvf(aTHX_ inverted_tstr, "%c", RANGE_INDICATOR);
7140                 temp_end_pos = uvchr_to_utf8(temp, end);
7141                 sv_catpvn(inverted_tstr, (char *) temp, temp_end_pos - temp);
7142             }
7143         }
7144
7145         /* Set up so the remainder of the routine uses this complement, instead
7146          * of the actual input */
7147         t0 = t = (U8*)SvPV_const(inverted_tstr, temp_len);
7148         tend = t0 + temp_len;
7149         tstr_utf8 = TRUE;
7150
7151         SvREFCNT_dec_NN(inverted_tlist);
7152     }
7153
7154     /* For non-/d, an empty rhs means to use the lhs */
7155     if (rlen == 0 && ! del) {
7156         r0 = t0;
7157         rend = tend;
7158         rstr_utf8  = tstr_utf8;
7159     }
7160
7161     t_invlist = _new_invlist(1);
7162
7163     /* Initialize to a single range */
7164     t_invlist = _add_range_to_invlist(t_invlist, 0, UV_MAX);
7165
7166     /* For the first pass, the lhs is partitioned such that the
7167      * number of UTF-8 bytes required to represent a code point in each
7168      * partition is the same as the number for any other code point in
7169      * that partion.  We copy the pre-compiled partion. */
7170     len = C_ARRAY_LENGTH(PL_partition_by_byte_length);
7171     invlist_extend(t_invlist, len);
7172     t_array = invlist_array(t_invlist);
7173     Copy(PL_partition_by_byte_length, t_array, len, UV);
7174     invlist_set_len(t_invlist, len, *(get_invlist_offset_addr(t_invlist)));
7175     Newx(r_map, len + 1, UV);
7176
7177     /* Parse the (potentially adjusted) input, creating the inversion map.
7178      * This is done in two passes.  The first pass is to determine if the
7179      * transliteration can be done in place.  The inversion map it creates
7180      * could be used, but generally would be larger and slower to run than the
7181      * output of the second pass, which starts with a more compact table and
7182      * allows more ranges to be merged */
7183     for (pass2 = 0; pass2 < 2; pass2++) {
7184         if (pass2) {
7185             /* Initialize to a single range */
7186             t_invlist = _add_range_to_invlist(t_invlist, 0, UV_MAX);
7187
7188             /* In the second pass, we just have the single range */
7189             len = 1;
7190             t_array = invlist_array(t_invlist);
7191         }
7192
7193 /* As noted earlier, we convert EBCDIC code points to Unicode in the first pass
7194  * so as to get the well-behaved length 1 vs length 2 boundary.  Only code
7195  * points below 256 differ between the two character sets in this regard.  For
7196  * these, we also can't have any ranges, as they have to be individually
7197  * converted. */
7198 #ifdef EBCDIC
7199 #  define CP_ADJUST(x)          ((pass2) ? (x) : NATIVE_TO_UNI(x))
7200 #  define FORCE_RANGE_LEN_1(x)  ((pass2) ? 0 : ((x) < 256))
7201 #  define CP_SKIP(x)            ((pass2) ? UVCHR_SKIP(x) : OFFUNISKIP(x))
7202 #else
7203 #  define CP_ADJUST(x)          (x)
7204 #  define FORCE_RANGE_LEN_1(x)  0
7205 #  define CP_SKIP(x)            UVCHR_SKIP(x)
7206 #endif
7207
7208         /* And the mapping of each of the ranges is initialized.  Initially,
7209          * everything is TR_UNLISTED. */
7210         for (i = 0; i < len; i++) {
7211             r_map[i] = TR_UNLISTED;
7212         }
7213
7214         t = t0;
7215         t_count = 0;
7216         r = r0;
7217         r_count = 0;
7218         t_range_count = r_range_count = 0;
7219
7220         DEBUG_y(PerlIO_printf(Perl_debug_log, "%s: %d:\ntstr=%s\n",
7221                     __FILE__, __LINE__, _byte_dump_string(t, tend - t, 0)));
7222         DEBUG_y(PerlIO_printf(Perl_debug_log, "rstr=%s\n",
7223                                         _byte_dump_string(r, rend - r, 0)));
7224         DEBUG_y(PerlIO_printf(Perl_debug_log, "/c=%d; /s=%d; /d=%d\n",
7225                                                   complement, squash, del));
7226         DEBUG_y(invmap_dump(t_invlist, r_map));
7227
7228         /* Now go through the search list constructing an inversion map.  The
7229          * input is not necessarily in any particular order.  Making it an
7230          * inversion map orders it, potentially simplifying, and makes it easy
7231          * to deal with at run time.  This is the only place in core that
7232          * generates an inversion map; if others were introduced, it might be
7233          * better to create general purpose routines to handle them.
7234          * (Inversion maps are created in perl in other places.)
7235          *
7236          * An inversion map consists of two parallel arrays.  One is
7237          * essentially an inversion list: an ordered list of code points such
7238          * that each element gives the first code point of a range of
7239          * consecutive code points that map to the element in the other array
7240          * that has the same index as this one (in other words, the
7241          * corresponding element).  Thus the range extends up to (but not
7242          * including) the code point given by the next higher element.  In a
7243          * true inversion map, the corresponding element in the other array
7244          * gives the mapping of the first code point in the range, with the
7245          * understanding that the next higher code point in the inversion
7246          * list's range will map to the next higher code point in the map.
7247          *
7248          * So if at element [i], let's say we have:
7249          *
7250          *     t_invlist  r_map
7251          * [i]    A         a
7252          *
7253          * This means that A => a, B => b, C => c....  Let's say that the
7254          * situation is such that:
7255          *
7256          * [i+1]  L        -1
7257          *
7258          * This means the sequence that started at [i] stops at K => k.  This
7259          * illustrates that you need to look at the next element to find where
7260          * a sequence stops.  Except, the highest element in the inversion list
7261          * begins a range that is understood to extend to the platform's
7262          * infinity.
7263          *
7264          * This routine modifies traditional inversion maps to reserve two
7265          * mappings:
7266          *
7267          *  TR_UNLISTED (or -1) indicates that no code point in the range
7268          *      is listed in the tr/// searchlist.  At runtime, these are
7269          *      always passed through unchanged.  In the inversion map, all
7270          *      points in the range are mapped to -1, instead of increasing,
7271          *      like the 'L' in the example above.
7272          *
7273          *      We start the parse with every code point mapped to this, and as
7274          *      we parse and find ones that are listed in the search list, we
7275          *      carve out ranges as we go along that override that.
7276          *
7277          *  TR_SPECIAL_HANDLING (or -2) indicates that every code point in the
7278          *      range needs special handling.  Again, all code points in the
7279          *      range are mapped to -2, instead of increasing.
7280          *
7281          *      Under /d this value means the code point should be deleted from
7282          *      the transliteration when encountered.
7283          *
7284          *      Otherwise, it marks that every code point in the range is to
7285          *      map to the final character in the replacement list.  This
7286          *      happens only when the replacement list is shorter than the
7287          *      search one, so there are things in the search list that have no
7288          *      correspondence in the replacement list.  For example, in
7289          *      tr/a-z/A/, 'A' is the final value, and the inversion map
7290          *      generated for this would be like this:
7291          *          \0  =>  -1
7292          *          a   =>   A
7293          *          b-z =>  -2
7294          *          z+1 =>  -1
7295          *      'A' appears once, then the remainder of the range maps to -2.
7296          *      The use of -2 isn't strictly necessary, as an inversion map is
7297          *      capable of representing this situation, but not nearly so
7298          *      compactly, and this is actually quite commonly encountered.
7299          *      Indeed, the original design of this code used a full inversion
7300          *      map for this.  But things like
7301          *          tr/\0-\x{FFFF}/A/
7302          *      generated huge data structures, slowly, and the execution was
7303          *      also slow.  So the current scheme was implemented.
7304          *
7305          *  So, if the next element in our example is:
7306          *
7307          * [i+2]  Q        q
7308          *
7309          * Then all of L, M, N, O, and P map to TR_UNLISTED.  If the next
7310          * elements are
7311          *
7312          * [i+3]  R        z
7313          * [i+4]  S       TR_UNLISTED
7314          *
7315          * Then Q => q; R => z; and S => TR_UNLISTED.  If [i+4] (the 'S') is
7316          * the final element in the arrays, every code point from S to infinity
7317          * maps to TR_UNLISTED.
7318          *
7319          */
7320                            /* Finish up range started in what otherwise would
7321                             * have been the final iteration */
7322         while (t < tend || t_range_count > 0) {
7323             bool adjacent_to_range_above = FALSE;
7324             bool adjacent_to_range_below = FALSE;
7325
7326             bool merge_with_range_above = FALSE;
7327             bool merge_with_range_below = FALSE;
7328
7329             UV span, invmap_range_length_remaining;
7330             SSize_t j;
7331             Size_t i;
7332
7333             /* If we are in the middle of processing a range in the 'target'
7334              * side, the previous iteration has set us up.  Otherwise, look at
7335              * the next character in the search list */
7336             if (t_range_count <= 0) {
7337                 if (! tstr_utf8) {
7338
7339                     /* Here, not in the middle of a range, and not UTF-8.  The
7340                      * next code point is the single byte where we're at */
7341                     t_cp = CP_ADJUST(*t);
7342                     t_range_count = 1;
7343                     t++;
7344                 }
7345                 else {
7346                     Size_t t_char_len;
7347
7348                     /* Here, not in the middle of a range, and is UTF-8.  The
7349                      * next code point is the next UTF-8 char in the input.  We
7350                      * know the input is valid, because the toker constructed
7351                      * it */
7352                     t_cp = CP_ADJUST(valid_utf8_to_uvchr(t, &t_char_len));
7353                     t += t_char_len;
7354
7355                     /* UTF-8 strings (only) have been parsed in toke.c to have
7356                      * ranges.  See if the next byte indicates that this was
7357                      * the first element of a range.  If so, get the final
7358                      * element and calculate the range size.  If not, the range
7359                      * size is 1 */
7360                     if (   t < tend && *t == RANGE_INDICATOR
7361                         && ! FORCE_RANGE_LEN_1(t_cp))
7362                     {
7363                         t++;
7364                         t_range_count = valid_utf8_to_uvchr(t, &t_char_len)
7365                                       - t_cp + 1;
7366                         t += t_char_len;
7367                     }
7368                     else {
7369                         t_range_count = 1;
7370                     }
7371                 }
7372
7373                 /* Count the total number of listed code points * */
7374                 t_count += t_range_count;
7375             }
7376
7377             /* Similarly, get the next character in the replacement list */
7378             if (r_range_count <= 0) {
7379                 if (r >= rend) {
7380
7381                     /* But if we've exhausted the rhs, there is nothing to map
7382                      * to, except the special handling one, and we make the
7383                      * range the same size as the lhs one. */
7384                     r_cp = TR_SPECIAL_HANDLING;
7385                     r_range_count = t_range_count;
7386
7387                     if (! del) {
7388                         DEBUG_yv(PerlIO_printf(Perl_debug_log,
7389                                         "final_map =%" UVXf "\n", final_map));
7390                     }
7391                 }
7392                 else {
7393                     if (! rstr_utf8) {
7394                         r_cp = CP_ADJUST(*r);
7395                         r_range_count = 1;
7396                         r++;
7397                     }
7398                     else {
7399                         Size_t r_char_len;
7400
7401                         r_cp = CP_ADJUST(valid_utf8_to_uvchr(r, &r_char_len));
7402                         r += r_char_len;
7403                         if (   r < rend && *r == RANGE_INDICATOR
7404                             && ! FORCE_RANGE_LEN_1(r_cp))
7405                         {
7406                             r++;
7407                             r_range_count = valid_utf8_to_uvchr(r,
7408                                                     &r_char_len) - r_cp + 1;
7409                             r += r_char_len;
7410                         }
7411                         else {
7412                             r_range_count = 1;
7413                         }
7414                     }
7415
7416                     if (r_cp == TR_SPECIAL_HANDLING) {
7417                         r_range_count = t_range_count;
7418                     }
7419
7420                     /* This is the final character so far */
7421                     final_map = r_cp + r_range_count - 1;
7422
7423                     r_count += r_range_count;
7424                 }
7425             }
7426
7427             /* Here, we have the next things ready in both sides.  They are
7428              * potentially ranges.  We try to process as big a chunk as
7429              * possible at once, but the lhs and rhs must be synchronized, so
7430              * things like tr/A-Z/a-ij-z/ will need to be processed in 2 chunks
7431              * */
7432             min_range_count = MIN(t_range_count, r_range_count);
7433
7434             /* Search the inversion list for the entry that contains the input
7435              * code point <cp>.  The inversion map was initialized to cover the
7436              * entire range of possible inputs, so this should not fail.  So
7437              * the return value is the index into the list's array of the range
7438              * that contains <cp>, that is, 'i' such that array[i] <= cp <
7439              * array[i+1] */
7440             j = _invlist_search(t_invlist, t_cp);
7441             assert(j >= 0);
7442             i = j;
7443
7444             /* Here, the data structure might look like:
7445              *
7446              * index    t   r     Meaning
7447              * [i-1]    J   j   # J-L => j-l
7448              * [i]      M  -1   # M => default; as do N, O, P, Q
7449              * [i+1]    R   x   # R => x, S => x+1, T => x+2
7450              * [i+2]    U   y   # U => y, V => y+1, ...
7451              * ...
7452              * [-1]     Z  -1   # Z => default; as do Z+1, ... infinity
7453              *
7454              * where 'x' and 'y' above are not to be taken literally.
7455              *
7456              * The maximum chunk we can handle in this loop iteration, is the
7457              * smallest of the three components: the lhs 't_', the rhs 'r_',
7458              * and the remainder of the range in element [i].  (In pass 1, that
7459              * range will have everything in it be of the same class; we can't
7460              * cross into another class.)  'min_range_count' already contains
7461              * the smallest of the first two values.  The final one is
7462              * irrelevant if the map is to the special indicator */
7463
7464             invmap_range_length_remaining = (i + 1 < len)
7465                                             ? t_array[i+1] - t_cp
7466                                             : IV_MAX - t_cp;
7467             span = MAX(1, MIN(min_range_count, invmap_range_length_remaining));
7468
7469             /* The end point of this chunk is where we are, plus the span, but
7470              * never larger than the platform's infinity */
7471             t_cp_end = MIN(IV_MAX, t_cp + span - 1);
7472
7473             if (r_cp == TR_SPECIAL_HANDLING) {
7474
7475                 /* If unmatched lhs code points map to the final map, use that
7476                  * value.  This being set to TR_SPECIAL_HANDLING indicates that
7477                  * we don't have a final map: unmatched lhs code points are
7478                  * simply deleted */
7479                 r_cp_end = (del) ? TR_SPECIAL_HANDLING : final_map;
7480             }
7481             else {
7482                 r_cp_end = MIN(IV_MAX, r_cp + span - 1);
7483
7484                 /* If something on the lhs is below 256, and something on the
7485                  * rhs is above, there is a potential mapping here across that
7486                  * boundary.  Indeed the only way there isn't is if both sides
7487                  * start at the same point.  That means they both cross at the
7488                  * same time.  But otherwise one crosses before the other */
7489                 if (t_cp < 256 && r_cp_end > 255 && r_cp != t_cp) {
7490                     can_force_utf8 = TRUE;
7491                 }
7492             }
7493
7494             /* If a character appears in the search list more than once, the
7495              * 2nd and succeeding occurrences are ignored, so only do this
7496              * range if haven't already processed this character.  (The range
7497              * has been set up so that all members in it will be of the same
7498              * ilk) */
7499             if (r_map[i] == TR_UNLISTED) {
7500                 DEBUG_yv(PerlIO_printf(Perl_debug_log,
7501                     "Processing %" UVxf "-%" UVxf " => %" UVxf "-%" UVxf "\n",
7502                     t_cp, t_cp_end, r_cp, r_cp_end));
7503
7504                 /* This is the first definition for this chunk, hence is valid
7505                  * and needs to be processed.  Here and in the comments below,
7506                  * we use the above sample data.  The t_cp chunk must be any
7507                  * contiguous subset of M, N, O, P, and/or Q.
7508                  *
7509                  * In the first pass, calculate if there is any possible input
7510                  * string that has a character whose transliteration will be
7511                  * longer than it.  If none, the transliteration may be done
7512                  * in-place, as it can't write over a so-far unread byte.
7513                  * Otherwise, a copy must first be made.  This could be
7514                  * expensive for long inputs.
7515                  *
7516                  * In the first pass, the t_invlist has been partitioned so
7517                  * that all elements in any single range have the same number
7518                  * of bytes in their UTF-8 representations.  And the r space is
7519                  * either a single byte, or a range of strictly monotonically
7520                  * increasing code points.  So the final element in the range
7521                  * will be represented by no fewer bytes than the initial one.
7522                  * That means that if the final code point in the t range has
7523                  * at least as many bytes as the final code point in the r,
7524                  * then all code points in the t range have at least as many
7525                  * bytes as their corresponding r range element.  But if that's
7526                  * not true, the transliteration of at least the final code
7527                  * point grows in length.  As an example, suppose we had
7528                  *      tr/\x{fff0}-\x{fff1}/\x{ffff}-\x{10000}/
7529                  * The UTF-8 for all but 10000 occupies 3 bytes on ASCII
7530                  * platforms.  We have deliberately set up the data structure
7531                  * so that any range in the lhs gets split into chunks for
7532                  * processing, such that every code point in a chunk has the
7533                  * same number of UTF-8 bytes.  We only have to check the final
7534                  * code point in the rhs against any code point in the lhs. */
7535                 if ( ! pass2
7536                     && r_cp_end != TR_SPECIAL_HANDLING
7537                     && CP_SKIP(t_cp_end) < CP_SKIP(r_cp_end))
7538                 {
7539                     /* Here, we will need to make a copy of the input string
7540                      * before doing the transliteration.  The worst possible
7541                      * case is an expansion ratio of 14:1. This is rare, and
7542                      * we'd rather allocate only the necessary amount of extra
7543                      * memory for that copy.  We can calculate the worst case
7544                      * for this particular transliteration is by keeping track
7545                      * of the expansion factor for each range.
7546                      *
7547                      * Consider tr/\xCB/\X{E000}/.  The maximum expansion
7548                      * factor is 1 byte going to 3 if the target string is not
7549                      * UTF-8, but 2 bytes going to 3 if it is in UTF-8.  We
7550                      * could pass two different values so doop could choose
7551                      * based on the UTF-8ness of the target.  But khw thinks
7552                      * (perhaps wrongly) that is overkill.  It is used only to
7553                      * make sure we malloc enough space.
7554                      *
7555                      * If no target string can force the result to be UTF-8,
7556                      * then we don't have to worry about the case of the target
7557                      * string not being UTF-8 */
7558                     NV t_size = (can_force_utf8 && t_cp < 256)
7559                                 ? 1
7560                                 : CP_SKIP(t_cp_end);
7561                     NV ratio = CP_SKIP(r_cp_end) / t_size;
7562
7563                     o->op_private |= OPpTRANS_GROWS;
7564
7565                     /* Now that we know it grows, we can keep track of the
7566                      * largest ratio */
7567                     if (ratio > max_expansion) {
7568                         max_expansion = ratio;
7569                         DEBUG_y(PerlIO_printf(Perl_debug_log,
7570                                         "New expansion factor: %" NVgf "\n",
7571                                         max_expansion));
7572                     }
7573                 }
7574
7575                 /* The very first range is marked as adjacent to the
7576                  * non-existent range below it, as it causes things to "just
7577                  * work" (TradeMark)
7578                  *
7579                  * If the lowest code point in this chunk is M, it adjoins the
7580                  * J-L range */
7581                 if (t_cp == t_array[i]) {
7582                     adjacent_to_range_below = TRUE;
7583
7584                     /* And if the map has the same offset from the beginning of
7585                      * the range as does this new code point (or both are for
7586                      * TR_SPECIAL_HANDLING), this chunk can be completely
7587                      * merged with the range below.  EXCEPT, in the first pass,
7588                      * we don't merge ranges whose UTF-8 byte representations
7589                      * have different lengths, so that we can more easily
7590                      * detect if a replacement is longer than the source, that
7591                      * is if it 'grows'.  But in the 2nd pass, there's no
7592                      * reason to not merge */
7593                     if (   (i > 0 && (   pass2
7594                                       || CP_SKIP(t_array[i-1])
7595                                                             == CP_SKIP(t_cp)))
7596                         && (   (   r_cp == TR_SPECIAL_HANDLING
7597                                 && r_map[i-1] == TR_SPECIAL_HANDLING)
7598                             || (   r_cp != TR_SPECIAL_HANDLING
7599                                 && r_cp - r_map[i-1] == t_cp - t_array[i-1])))
7600                     {
7601                         merge_with_range_below = TRUE;
7602                     }
7603                 }
7604
7605                 /* Similarly, if the highest code point in this chunk is 'Q',
7606                  * it adjoins the range above, and if the map is suitable, can
7607                  * be merged with it */
7608                 if (    t_cp_end >= IV_MAX - 1
7609                     || (   i + 1 < len
7610                         && t_cp_end + 1 == t_array[i+1]))
7611                 {
7612                     adjacent_to_range_above = TRUE;
7613                     if (i + 1 < len)
7614                     if (    (   pass2
7615                              || CP_SKIP(t_cp) == CP_SKIP(t_array[i+1]))
7616                         && (   (   r_cp == TR_SPECIAL_HANDLING
7617                                 && r_map[i+1] == (UV) TR_SPECIAL_HANDLING)
7618                             || (   r_cp != TR_SPECIAL_HANDLING
7619                                 && r_cp_end == r_map[i+1] - 1)))
7620                     {
7621                         merge_with_range_above = TRUE;
7622                     }
7623                 }
7624
7625                 if (merge_with_range_below && merge_with_range_above) {
7626
7627                     /* Here the new chunk looks like M => m, ... Q => q; and
7628                      * the range above is like R => r, ....  Thus, the [i-1]
7629                      * and [i+1] ranges should be seamlessly melded so the
7630                      * result looks like
7631                      *
7632                      * [i-1]    J   j   # J-T => j-t
7633                      * [i]      U   y   # U => y, V => y+1, ...
7634                      * ...
7635                      * [-1]     Z  -1   # Z => default; as do Z+1, ... infinity
7636                      */
7637                     Move(t_array + i + 2, t_array + i, len - i - 2, UV);
7638                     Move(r_map   + i + 2, r_map   + i, len - i - 2, UV);
7639                     len -= 2;
7640                     invlist_set_len(t_invlist,
7641                                     len,
7642                                     *(get_invlist_offset_addr(t_invlist)));
7643                 }
7644                 else if (merge_with_range_below) {
7645
7646                     /* Here the new chunk looks like M => m, .... But either
7647                      * (or both) it doesn't extend all the way up through Q; or
7648                      * the range above doesn't start with R => r. */
7649                     if (! adjacent_to_range_above) {
7650
7651                         /* In the first case, let's say the new chunk extends
7652                          * through O.  We then want:
7653                          *
7654                          * [i-1]    J   j   # J-O => j-o
7655                          * [i]      P  -1   # P => -1, Q => -1
7656                          * [i+1]    R   x   # R => x, S => x+1, T => x+2
7657                          * [i+2]    U   y   # U => y, V => y+1, ...
7658                          * ...
7659                          * [-1]     Z  -1   # Z => default; as do Z+1, ...
7660                          *                                            infinity
7661                          */
7662                         t_array[i] = t_cp_end + 1;
7663                         r_map[i] = TR_UNLISTED;
7664                     }
7665                     else { /* Adjoins the range above, but can't merge with it
7666                               (because 'x' is not the next map after q) */
7667                         /*
7668                          * [i-1]    J   j   # J-Q => j-q
7669                          * [i]      R   x   # R => x, S => x+1, T => x+2
7670                          * [i+1]    U   y   # U => y, V => y+1, ...
7671                          * ...
7672                          * [-1]     Z  -1   # Z => default; as do Z+1, ...
7673                          *                                          infinity
7674                          */
7675
7676                         Move(t_array + i + 1, t_array + i, len - i - 1, UV);
7677                         Move(r_map + i + 1, r_map + i, len - i - 1, UV);
7678                         len--;
7679                         invlist_set_len(t_invlist, len,
7680                                         *(get_invlist_offset_addr(t_invlist)));
7681                     }
7682                 }
7683                 else if (merge_with_range_above) {
7684
7685                     /* Here the new chunk ends with Q => q, and the range above
7686                      * must start with R => r, so the two can be merged. But
7687                      * either (or both) the new chunk doesn't extend all the
7688                      * way down to M; or the mapping of the final code point
7689                      * range below isn't m */
7690                     if (! adjacent_to_range_below) {
7691
7692                         /* In the first case, let's assume the new chunk starts
7693                          * with P => p.  Then, because it's merge-able with the
7694                          * range above, that range must be R => r.  We want:
7695                          *
7696                          * [i-1]    J   j   # J-L => j-l
7697                          * [i]      M  -1   # M => -1, N => -1
7698                          * [i+1]    P   p   # P-T => p-t
7699                          * [i+2]    U   y   # U => y, V => y+1, ...
7700                          * ...
7701                          * [-1]     Z  -1   # Z => default; as do Z+1, ...
7702                          *                                          infinity
7703                          */
7704                         t_array[i+1] = t_cp;
7705                         r_map[i+1] = r_cp;
7706                     }
7707                     else { /* Adjoins the range below, but can't merge with it
7708                             */
7709                         /*
7710                          * [i-1]    J   j   # J-L => j-l
7711                          * [i]      M   x   # M-T => x-5 .. x+2
7712                          * [i+1]    U   y   # U => y, V => y+1, ...
7713                          * ...
7714                          * [-1]     Z  -1   # Z => default; as do Z+1, ...
7715                          *                                          infinity
7716                          */
7717                         Move(t_array + i + 1, t_array + i, len - i - 1, UV);
7718                         Move(r_map   + i + 1, r_map   + i, len - i - 1, UV);
7719                         len--;
7720                         t_array[i] = t_cp;
7721                         r_map[i] = r_cp;
7722                         invlist_set_len(t_invlist, len,
7723                                         *(get_invlist_offset_addr(t_invlist)));
7724                     }
7725                 }
7726                 else if (adjacent_to_range_below && adjacent_to_range_above) {
7727                     /* The new chunk completely fills the gap between the
7728                      * ranges on either side, but can't merge with either of
7729                      * them.
7730                      *
7731                      * [i-1]    J   j   # J-L => j-l
7732                      * [i]      M   z   # M => z, N => z+1 ... Q => z+4
7733                      * [i+1]    R   x   # R => x, S => x+1, T => x+2
7734                      * [i+2]    U   y   # U => y, V => y+1, ...
7735                      * ...
7736                      * [-1]     Z  -1   # Z => default; as do Z+1, ... infinity
7737                      */
7738                     r_map[i] = r_cp;
7739                 }
7740                 else if (adjacent_to_range_below) {
7741                     /* The new chunk adjoins the range below, but not the range
7742                      * above, and can't merge.  Let's assume the chunk ends at
7743                      * O.
7744                      *
7745                      * [i-1]    J   j   # J-L => j-l
7746                      * [i]      M   z   # M => z, N => z+1, O => z+2
7747                      * [i+1]    P   -1  # P => -1, Q => -1
7748                      * [i+2]    R   x   # R => x, S => x+1, T => x+2
7749                      * [i+3]    U   y   # U => y, V => y+1, ...
7750                      * ...
7751                      * [-w]     Z  -1   # Z => default; as do Z+1, ... infinity
7752                      */
7753                     invlist_extend(t_invlist, len + 1);
7754                     t_array = invlist_array(t_invlist);
7755                     Renew(r_map, len + 1, UV);
7756
7757                     Move(t_array + i + 1, t_array + i + 2, len - i - 1, UV);
7758                     Move(r_map + i + 1,   r_map   + i + 2, len - i - 1, UV);
7759                     r_map[i] = r_cp;
7760                     t_array[i+1] = t_cp_end + 1;
7761                     r_map[i+1] = TR_UNLISTED;
7762                     len++;
7763                     invlist_set_len(t_invlist, len,
7764                                     *(get_invlist_offset_addr(t_invlist)));
7765                 }
7766                 else if (adjacent_to_range_above) {
7767                     /* The new chunk adjoins the range above, but not the range
7768                      * below, and can't merge.  Let's assume the new chunk
7769                      * starts at O
7770                      *
7771                      * [i-1]    J   j   # J-L => j-l
7772                      * [i]      M  -1   # M => default, N => default
7773                      * [i+1]    O   z   # O => z, P => z+1, Q => z+2
7774                      * [i+2]    R   x   # R => x, S => x+1, T => x+2
7775                      * [i+3]    U   y   # U => y, V => y+1, ...
7776                      * ...
7777                      * [-1]     Z  -1   # Z => default; as do Z+1, ... infinity
7778                      */
7779                     invlist_extend(t_invlist, len + 1);
7780                     t_array = invlist_array(t_invlist);
7781                     Renew(r_map, len + 1, UV);
7782
7783                     Move(t_array + i + 1, t_array + i + 2, len - i - 1, UV);
7784                     Move(r_map   + i + 1, r_map   + i + 2, len - i - 1, UV);
7785                     t_array[i+1] = t_cp;
7786                     r_map[i+1] = r_cp;
7787                     len++;
7788                     invlist_set_len(t_invlist, len,
7789                                     *(get_invlist_offset_addr(t_invlist)));
7790                 }
7791                 else {
7792                     /* The new chunk adjoins neither the range above, nor the
7793                      * range below.  Lets assume it is N..P => n..p
7794                      *
7795                      * [i-1]    J   j   # J-L => j-l
7796                      * [i]      M  -1   # M => default
7797                      * [i+1]    N   n   # N..P => n..p
7798                      * [i+2]    Q  -1   # Q => default
7799                      * [i+3]    R   x   # R => x, S => x+1, T => x+2
7800                      * [i+4]    U   y   # U => y, V => y+1, ...
7801                      * ...
7802                      * [-1]     Z  -1   # Z => default; as do Z+1, ... infinity
7803                      */
7804
7805                     DEBUG_yv(PerlIO_printf(Perl_debug_log,
7806                                         "Before fixing up: len=%d, i=%d\n",
7807                                         (int) len, (int) i));
7808                     DEBUG_yv(invmap_dump(t_invlist, r_map));
7809
7810                     invlist_extend(t_invlist, len + 2);
7811                     t_array = invlist_array(t_invlist);
7812                     Renew(r_map, len + 2, UV);
7813
7814                     Move(t_array + i + 1,
7815                          t_array + i + 2 + 1, len - i - (2 - 1), UV);
7816                     Move(r_map   + i + 1,
7817                          r_map   + i + 2 + 1, len - i - (2 - 1), UV);
7818
7819                     len += 2;
7820                     invlist_set_len(t_invlist, len,
7821                                     *(get_invlist_offset_addr(t_invlist)));
7822
7823                     t_array[i+1] = t_cp;
7824                     r_map[i+1] = r_cp;
7825
7826                     t_array[i+2] = t_cp_end + 1;
7827                     r_map[i+2] = TR_UNLISTED;
7828                 }
7829                 DEBUG_yv(PerlIO_printf(Perl_debug_log,
7830                           "After iteration: span=%" UVuf ", t_range_count=%"
7831                           UVuf " r_range_count=%" UVuf "\n",
7832                           span, t_range_count, r_range_count));
7833                 DEBUG_yv(invmap_dump(t_invlist, r_map));
7834             } /* End of this chunk needs to be processed */
7835
7836             /* Done with this chunk. */
7837             t_cp += span;
7838             if (t_cp >= IV_MAX) {
7839                 break;
7840             }
7841             t_range_count -= span;
7842             if (r_cp != TR_SPECIAL_HANDLING) {
7843                 r_cp += span;
7844                 r_range_count -= span;
7845             }
7846             else {
7847                 r_range_count = 0;
7848             }
7849
7850         } /* End of loop through the search list */
7851
7852         /* We don't need an exact count, but we do need to know if there is
7853          * anything left over in the replacement list.  So, just assume it's
7854          * one byte per character */
7855         if (rend > r) {
7856             r_count++;
7857         }
7858     } /* End of passes */
7859
7860     SvREFCNT_dec(inverted_tstr);
7861
7862     DEBUG_y(PerlIO_printf(Perl_debug_log, "After everything: \n"));
7863     DEBUG_y(invmap_dump(t_invlist, r_map));
7864
7865     /* We now have normalized the input into an inversion map.
7866      *
7867      * See if the lhs and rhs are equivalent.  If so, this tr/// is a no-op
7868      * except for the count, and streamlined runtime code can be used */
7869     if (!del && !squash) {
7870
7871         /* They are identical if they point to same address, or if everything
7872          * maps to UNLISTED or to itself.  This catches things that not looking
7873          * at the normalized inversion map doesn't catch, like tr/aa/ab/ or
7874          * tr/\x{100}-\x{104}/\x{100}-\x{102}\x{103}-\x{104}  */
7875         if (r0 != t0) {
7876             for (i = 0; i < len; i++) {
7877                 if (r_map[i] != TR_UNLISTED && r_map[i] != t_array[i]) {
7878                     goto done_identical_check;
7879                 }
7880             }
7881         }
7882
7883         /* Here have gone through entire list, and didn't find any
7884          * non-identical mappings */
7885         o->op_private |= OPpTRANS_IDENTICAL;
7886
7887       done_identical_check: ;
7888     }
7889
7890     t_array = invlist_array(t_invlist);
7891
7892     /* If has components above 255, we generally need to use the inversion map
7893      * implementation */
7894     if (   can_force_utf8
7895         || (   len > 0
7896             && t_array[len-1] > 255
7897                  /* If the final range is 0x100-INFINITY and is a special
7898                   * mapping, the table implementation can handle it */
7899             && ! (   t_array[len-1] == 256
7900                   && (   r_map[len-1] == TR_UNLISTED
7901                       || r_map[len-1] == TR_SPECIAL_HANDLING))))
7902     {
7903         SV* r_map_sv;
7904
7905         /* A UTF-8 op is generated, indicated by this flag.  This op is an
7906          * sv_op */
7907         o->op_private |= OPpTRANS_USE_SVOP;
7908
7909         if (can_force_utf8) {
7910             o->op_private |= OPpTRANS_CAN_FORCE_UTF8;
7911         }
7912
7913         /* The inversion map is pushed; first the list. */
7914         invmap = MUTABLE_AV(newAV());
7915         av_push(invmap, t_invlist);
7916
7917         /* 2nd is the mapping */
7918         r_map_sv = newSVpvn((char *) r_map, len * sizeof(UV));
7919         av_push(invmap, r_map_sv);
7920
7921         /* 3rd is the max possible expansion factor */
7922         av_push(invmap, newSVnv(max_expansion));
7923
7924         /* Characters that are in the search list, but not in the replacement
7925          * list are mapped to the final character in the replacement list */
7926         if (! del && r_count < t_count) {
7927             av_push(invmap, newSVuv(final_map));
7928         }
7929
7930 #ifdef USE_ITHREADS
7931         cPADOPo->op_padix = pad_alloc(OP_TRANS, SVf_READONLY);
7932         SvREFCNT_dec(PAD_SVl(cPADOPo->op_padix));
7933         PAD_SETSV(cPADOPo->op_padix, (SV *) invmap);
7934         SvPADTMP_on(invmap);
7935         SvREADONLY_on(invmap);
7936 #else
7937         cSVOPo->op_sv = (SV *) invmap;
7938 #endif
7939
7940     }
7941     else {
7942         OPtrans_map *tbl;
7943         unsigned short i;
7944
7945         /* The OPtrans_map struct already contains one slot; hence the -1. */
7946         SSize_t struct_size = sizeof(OPtrans_map)
7947                             + (256 - 1 + 1)*sizeof(short);
7948
7949         /* Non-utf8 case: set o->op_pv to point to a simple 256+ entry lookup
7950         * table. Entries with the value TR_UNMAPPED indicate chars not to be
7951         * translated, while TR_DELETE indicates a search char without a
7952         * corresponding replacement char under /d.
7953         *
7954         * In addition, an extra slot at the end is used to store the final
7955         * repeating char, or TR_R_EMPTY under an empty replacement list, or
7956         * TR_DELETE under /d; which makes the runtime code easier.
7957         */
7958
7959         /* Indicate this is an op_pv */
7960         o->op_private &= ~OPpTRANS_USE_SVOP;
7961
7962         tbl = (OPtrans_map*)PerlMemShared_calloc(struct_size, 1);
7963         tbl->size = 256;
7964         cPVOPo->op_pv = (char*)tbl;
7965
7966         for (i = 0; i < len; i++) {
7967             STATIC_ASSERT_DECL(TR_SPECIAL_HANDLING == TR_DELETE);
7968             short upper = i >= len - 1 ? 256 : (short) t_array[i+1];
7969             short to = (short) r_map[i];
7970             short j;
7971             bool do_increment = TRUE;
7972
7973             /* Any code points above our limit should be irrelevant */
7974             if (t_array[i] >= tbl->size) break;
7975
7976             /* Set up the map */
7977             if (to == (short) TR_SPECIAL_HANDLING && ! del) {
7978                 to = (short) final_map;
7979                 do_increment = FALSE;
7980             }
7981             else if (to < 0) {
7982                 do_increment = FALSE;
7983             }
7984
7985             /* Create a map for everything in this range.  The value increases
7986              * except for the special cases */
7987             for (j = (short) t_array[i]; j < upper; j++) {
7988                 tbl->map[j] = to;
7989                 if (do_increment) to++;
7990             }
7991         }
7992
7993         tbl->map[tbl->size] = del
7994                               ? (short) TR_DELETE
7995                               : (short) rlen
7996                                 ? (short) final_map
7997                                 : (short) TR_R_EMPTY;
7998         DEBUG_y(PerlIO_printf(Perl_debug_log,"%s: %d\n", __FILE__, __LINE__));
7999         for (i = 0; i < tbl->size; i++) {
8000             if (tbl->map[i] < 0) {
8001                 DEBUG_y(PerlIO_printf(Perl_debug_log," %02x=>%d",
8002                                                 (unsigned) i, tbl->map[i]));
8003             }
8004             else {
8005                 DEBUG_y(PerlIO_printf(Perl_debug_log," %02x=>%02x",
8006                                                 (unsigned) i, tbl->map[i]));
8007             }
8008             if ((i+1) % 8 == 0 || i + 1 == (short) tbl->size) {
8009                 DEBUG_y(PerlIO_printf(Perl_debug_log,"\n"));
8010             }
8011         }
8012         DEBUG_y(PerlIO_printf(Perl_debug_log,"Final map 0x%x=>%02x\n",
8013                                 (unsigned) tbl->size, tbl->map[tbl->size]));
8014
8015         SvREFCNT_dec(t_invlist);
8016
8017 #if 0   /* code that added excess above-255 chars at the end of the table, in
8018            case we ever want to not use the inversion map implementation for
8019            this */
8020
8021         ASSUME(j <= rlen);
8022         excess = rlen - j;
8023
8024         if (excess) {
8025             /* More replacement chars than search chars:
8026              * store excess replacement chars at end of main table.
8027              */
8028
8029             struct_size += excess;
8030             tbl = (OPtrans_map*)PerlMemShared_realloc(tbl,
8031                         struct_size + excess * sizeof(short));
8032             tbl->size += excess;
8033             cPVOPo->op_pv = (char*)tbl;
8034
8035             for (i = 0; i < excess; i++)
8036                 tbl->map[i + 256] = r[j+i];
8037         }
8038         else {
8039             /* no more replacement chars than search chars */
8040         }
8041 #endif
8042
8043     }
8044
8045     DEBUG_y(PerlIO_printf(Perl_debug_log,
8046             "/d=%d, /s=%d, /c=%d, identical=%d, grows=%d,"
8047             " use_svop=%d, can_force_utf8=%d,\nexpansion=%" NVgf "\n",
8048             del, squash, complement,
8049             cBOOL(o->op_private & OPpTRANS_IDENTICAL),
8050             cBOOL(o->op_private & OPpTRANS_USE_SVOP),
8051             cBOOL(o->op_private & OPpTRANS_GROWS),
8052             cBOOL(o->op_private & OPpTRANS_CAN_FORCE_UTF8),
8053             max_expansion));
8054
8055     Safefree(r_map);
8056
8057     if(del && rlen != 0 && r_count == t_count) {
8058         Perl_ck_warner(aTHX_ packWARN(WARN_MISC), "Useless use of /d modifier in transliteration operator");
8059     } else if(r_count > t_count) {
8060         Perl_ck_warner(aTHX_ packWARN(WARN_MISC), "Replacement list is longer than search list");
8061     }
8062
8063     op_free(expr);
8064     op_free(repl);
8065
8066     return o;
8067 }
8068
8069
8070 /*
8071 =for apidoc newPMOP
8072
8073 Constructs, checks, and returns an op of any pattern matching type.
8074 C<type> is the opcode.  C<flags> gives the eight bits of C<op_flags>
8075 and, shifted up eight bits, the eight bits of C<op_private>.
8076
8077 =cut
8078 */
8079
8080 OP *
8081 Perl_newPMOP(pTHX_ I32 type, I32 flags)
8082 {
8083     PMOP *pmop;
8084
8085     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_PMOP
8086         || type == OP_CUSTOM);
8087
8088     NewOp(1101, pmop, 1, PMOP);
8089     OpTYPE_set(pmop, type);
8090     pmop->op_flags = (U8)flags;
8091     pmop->op_private = (U8)(0 | (flags >> 8));
8092     if (PL_opargs[type] & OA_RETSCALAR)
8093         scalar((OP *)pmop);
8094
8095     if (PL_hints & HINT_RE_TAINT)
8096         pmop->op_pmflags |= PMf_RETAINT;
8097 #ifdef USE_LOCALE_CTYPE
8098     if (IN_LC_COMPILETIME(LC_CTYPE)) {
8099         set_regex_charset(&(pmop->op_pmflags), REGEX_LOCALE_CHARSET);
8100     }
8101     else
8102 #endif
8103          if (IN_UNI_8_BIT) {
8104         set_regex_charset(&(pmop->op_pmflags), REGEX_UNICODE_CHARSET);
8105     }
8106     if (PL_hints & HINT_RE_FLAGS) {
8107         SV *reflags = Perl_refcounted_he_fetch_pvn(aTHX_
8108          PL_compiling.cop_hints_hash, STR_WITH_LEN("reflags"), 0, 0
8109         );
8110         if (reflags && SvOK(reflags)) pmop->op_pmflags |= SvIV(reflags);
8111         reflags = Perl_refcounted_he_fetch_pvn(aTHX_
8112          PL_compiling.cop_hints_hash, STR_WITH_LEN("reflags_charset"), 0, 0
8113         );
8114         if (reflags && SvOK(reflags)) {
8115             set_regex_charset(&(pmop->op_pmflags), (regex_charset)SvIV(reflags));
8116         }
8117     }
8118
8119
8120 #ifdef USE_ITHREADS
8121     assert(SvPOK(PL_regex_pad[0]));
8122     if (SvCUR(PL_regex_pad[0])) {
8123         /* Pop off the "packed" IV from the end.  */
8124         SV *const repointer_list = PL_regex_pad[0];
8125         const char *p = SvEND(repointer_list) - sizeof(IV);
8126         const IV offset = *((IV*)p);
8127
8128         assert(SvCUR(repointer_list) % sizeof(IV) == 0);
8129
8130         SvEND_set(repointer_list, p);
8131
8132         pmop->op_pmoffset = offset;
8133         /* This slot should be free, so assert this:  */
8134         assert(PL_regex_pad[offset] == &PL_sv_undef);
8135     } else {
8136         SV * const repointer = &PL_sv_undef;
8137         av_push(PL_regex_padav, repointer);
8138         pmop->op_pmoffset = av_tindex(PL_regex_padav);
8139         PL_regex_pad = AvARRAY(PL_regex_padav);
8140     }
8141 #endif
8142
8143     return CHECKOP(type, pmop);
8144 }
8145
8146 static void
8147 S_set_haseval(pTHX)
8148 {
8149     PADOFFSET i = 1;
8150     PL_cv_has_eval = 1;
8151     /* Any pad names in scope are potentially lvalues.  */
8152     for (; i < PadnamelistMAXNAMED(PL_comppad_name); i++) {
8153         PADNAME *pn = PAD_COMPNAME_SV(i);
8154         if (!pn || !PadnameLEN(pn))
8155             continue;
8156         if (PadnameOUTER(pn) || PadnameIN_SCOPE(pn, PL_cop_seqmax))
8157             S_mark_padname_lvalue(aTHX_ pn);
8158     }
8159 }
8160
8161 /* Given some sort of match op o, and an expression expr containing a
8162  * pattern, either compile expr into a regex and attach it to o (if it's
8163  * constant), or convert expr into a runtime regcomp op sequence (if it's
8164  * not)
8165  *
8166  * Flags currently has 2 bits of meaning:
8167  * 1: isreg indicates that the pattern is part of a regex construct, eg
8168  *      $x =~ /pattern/ or split /pattern/, as opposed to $x =~ $pattern or
8169  *      split "pattern", which aren't. In the former case, expr will be a list
8170  *      if the pattern contains more than one term (eg /a$b/).
8171  * 2: The pattern is for a split.
8172  *
8173  * When the pattern has been compiled within a new anon CV (for
8174  * qr/(?{...})/ ), then floor indicates the savestack level just before
8175  * the new sub was created
8176  *
8177  * tr/// is also handled.
8178  */
8179
8180 OP *
8181 Perl_pmruntime(pTHX_ OP *o, OP *expr, OP *repl, UV flags, I32 floor)
8182 {
8183     PMOP *pm;
8184     LOGOP *rcop;
8185     I32 repl_has_vars = 0;
8186     bool is_trans = (o->op_type == OP_TRANS || o->op_type == OP_TRANSR);
8187     bool is_compiletime;
8188     bool has_code;
8189     bool isreg    = cBOOL(flags & 1);
8190     bool is_split = cBOOL(flags & 2);
8191
8192     PERL_ARGS_ASSERT_PMRUNTIME;
8193
8194     if (is_trans) {
8195         return pmtrans(o, expr, repl);
8196     }
8197
8198     /* find whether we have any runtime or code elements;
8199      * at the same time, temporarily set the op_next of each DO block;
8200      * then when we LINKLIST, this will cause the DO blocks to be excluded
8201      * from the op_next chain (and from having LINKLIST recursively
8202      * applied to them). We fix up the DOs specially later */
8203
8204     is_compiletime = 1;
8205     has_code = 0;
8206     if (expr->op_type == OP_LIST) {
8207         OP *child;
8208         for (child = cLISTOPx(expr)->op_first; child; child = OpSIBLING(child)) {
8209             if (child->op_type == OP_NULL && (child->op_flags & OPf_SPECIAL)) {
8210                 has_code = 1;
8211                 assert(!child->op_next);
8212                 if (UNLIKELY(!OpHAS_SIBLING(child))) {
8213                     assert(PL_parser && PL_parser->error_count);
8214                     /* This can happen with qr/ (?{(^{})/.  Just fake up
8215                        the op we were expecting to see, to avoid crashing
8216                        elsewhere.  */
8217                     op_sibling_splice(expr, child, 0,
8218                               newSVOP(OP_CONST, 0, &PL_sv_no));
8219                 }
8220                 child->op_next = OpSIBLING(child);
8221             }
8222             else if (child->op_type != OP_CONST && child->op_type != OP_PUSHMARK)
8223             is_compiletime = 0;
8224         }
8225     }
8226     else if (expr->op_type != OP_CONST)
8227         is_compiletime = 0;
8228
8229     LINKLIST(expr);
8230
8231     /* fix up DO blocks; treat each one as a separate little sub;
8232      * also, mark any arrays as LIST/REF */
8233
8234     if (expr->op_type == OP_LIST) {
8235         OP *child;
8236         for (child = cLISTOPx(expr)->op_first; child; child = OpSIBLING(child)) {
8237
8238             if (child->op_type == OP_PADAV || child->op_type == OP_RV2AV) {
8239                 assert( !(child->op_flags  & OPf_WANT));
8240                 /* push the array rather than its contents. The regex
8241                  * engine will retrieve and join the elements later */
8242                 child->op_flags |= (OPf_WANT_LIST | OPf_REF);
8243                 continue;
8244             }
8245
8246             if (!(child->op_type == OP_NULL && (child->op_flags & OPf_SPECIAL)))
8247                 continue;
8248             child->op_next = NULL; /* undo temporary hack from above */
8249             scalar(child);
8250             LINKLIST(child);
8251             if (cLISTOPx(child)->op_first->op_type == OP_LEAVE) {
8252                 LISTOP *leaveop = cLISTOPx(cLISTOPx(child)->op_first);
8253                 /* skip ENTER */
8254                 assert(leaveop->op_first->op_type == OP_ENTER);
8255                 assert(OpHAS_SIBLING(leaveop->op_first));
8256                 child->op_next = OpSIBLING(leaveop->op_first);
8257                 /* skip leave */
8258                 assert(leaveop->op_flags & OPf_KIDS);
8259                 assert(leaveop->op_last->op_next == (OP*)leaveop);
8260                 leaveop->op_next = NULL; /* stop on last op */
8261                 op_null((OP*)leaveop);
8262             }
8263             else {
8264                 /* skip SCOPE */
8265                 OP *scope = cLISTOPx(child)->op_first;
8266                 assert(scope->op_type == OP_SCOPE);
8267                 assert(scope->op_flags & OPf_KIDS);
8268                 scope->op_next = NULL; /* stop on last op */
8269                 op_null(scope);
8270             }
8271
8272             /* XXX optimize_optree() must be called on o before
8273              * CALL_PEEP(), as currently S_maybe_multiconcat() can't
8274              * currently cope with a peephole-optimised optree.
8275              * Calling optimize_optree() here ensures that condition
8276              * is met, but may mean optimize_optree() is applied
8277              * to the same optree later (where hopefully it won't do any
8278              * harm as it can't convert an op to multiconcat if it's
8279              * already been converted */
8280             optimize_optree(child);
8281
8282             /* have to peep the DOs individually as we've removed it from
8283              * the op_next chain */
8284             CALL_PEEP(child);
8285             S_prune_chain_head(&(child->op_next));
8286             if (is_compiletime)
8287                 /* runtime finalizes as part of finalizing whole tree */
8288                 finalize_optree(child);
8289         }
8290     }
8291     else if (expr->op_type == OP_PADAV || expr->op_type == OP_RV2AV) {
8292         assert( !(expr->op_flags  & OPf_WANT));
8293         /* push the array rather than its contents. The regex
8294          * engine will retrieve and join the elements later */
8295         expr->op_flags |= (OPf_WANT_LIST | OPf_REF);
8296     }
8297
8298     PL_hints |= HINT_BLOCK_SCOPE;
8299     pm = (PMOP*)o;
8300     assert(floor==0 || (pm->op_pmflags & PMf_HAS_CV));
8301
8302     if (is_compiletime) {
8303         U32 rx_flags = pm->op_pmflags & RXf_PMf_COMPILETIME;
8304         regexp_engine const *eng = current_re_engine();
8305
8306         if (is_split) {
8307             /* make engine handle split ' ' specially */
8308             pm->op_pmflags |= PMf_SPLIT;
8309             rx_flags |= RXf_SPLIT;
8310         }
8311
8312         if (!has_code || !eng->op_comp) {
8313             /* compile-time simple constant pattern */
8314
8315             if ((pm->op_pmflags & PMf_HAS_CV) && !has_code) {
8316                 /* whoops! we guessed that a qr// had a code block, but we
8317                  * were wrong (e.g. /[(?{}]/ ). Throw away the PL_compcv
8318                  * that isn't required now. Note that we have to be pretty
8319                  * confident that nothing used that CV's pad while the
8320                  * regex was parsed, except maybe op targets for \Q etc.
8321                  * If there were any op targets, though, they should have
8322                  * been stolen by constant folding.
8323                  */
8324 #ifdef DEBUGGING
8325                 SSize_t i = 0;
8326                 assert(PadnamelistMAXNAMED(PL_comppad_name) == 0);
8327                 while (++i <= AvFILLp(PL_comppad)) {
8328 #  ifdef USE_PAD_RESET
8329                     /* under USE_PAD_RESET, pad swipe replaces a swiped
8330                      * folded constant with a fresh padtmp */
8331                     assert(!PL_curpad[i] || SvPADTMP(PL_curpad[i]));
8332 #  else
8333                     assert(!PL_curpad[i]);
8334 #  endif
8335                 }
8336 #endif
8337                 /* This LEAVE_SCOPE will restore PL_compcv to point to the
8338                  * outer CV (the one whose slab holds the pm op). The
8339                  * inner CV (which holds expr) will be freed later, once
8340                  * all the entries on the parse stack have been popped on
8341                  * return from this function. Which is why its safe to
8342                  * call op_free(expr) below.
8343                  */
8344                 LEAVE_SCOPE(floor);
8345                 pm->op_pmflags &= ~PMf_HAS_CV;
8346             }
8347
8348             /* Skip compiling if parser found an error for this pattern */
8349             if (pm->op_pmflags & PMf_HAS_ERROR) {
8350                 return o;
8351             }
8352
8353             PM_SETRE(pm,
8354                 eng->op_comp
8355                     ? eng->op_comp(aTHX_ NULL, 0, expr, eng, NULL, NULL,
8356                                         rx_flags, pm->op_pmflags)
8357                     : Perl_re_op_compile(aTHX_ NULL, 0, expr, eng, NULL, NULL,
8358                                         rx_flags, pm->op_pmflags)
8359             );
8360             op_free(expr);
8361         }
8362         else {
8363             /* compile-time pattern that includes literal code blocks */
8364
8365             REGEXP* re;
8366
8367             /* Skip compiling if parser found an error for this pattern */
8368             if (pm->op_pmflags & PMf_HAS_ERROR) {
8369                 return o;
8370             }
8371
8372             re = eng->op_comp(aTHX_ NULL, 0, expr, eng, NULL, NULL,
8373                         rx_flags,
8374                         (pm->op_pmflags |
8375                             ((PL_hints & HINT_RE_EVAL) ? PMf_USE_RE_EVAL : 0))
8376                     );
8377             PM_SETRE(pm, re);
8378             if (pm->op_pmflags & PMf_HAS_CV) {
8379                 CV *cv;
8380                 /* this QR op (and the anon sub we embed it in) is never
8381                  * actually executed. It's just a placeholder where we can
8382                  * squirrel away expr in op_code_list without the peephole
8383                  * optimiser etc processing it for a second time */
8384                 OP *qr = newPMOP(OP_QR, 0);
8385                 ((PMOP*)qr)->op_code_list = expr;
8386
8387                 /* handle the implicit sub{} wrapped round the qr/(?{..})/ */
8388                 SvREFCNT_inc_simple_void(PL_compcv);
8389                 cv = newATTRSUB(floor, 0, NULL, NULL, qr);
8390                 ReANY(re)->qr_anoncv = cv;
8391
8392                 /* attach the anon CV to the pad so that
8393                  * pad_fixup_inner_anons() can find it */
8394                 (void)pad_add_anon(cv, o->op_type);
8395                 SvREFCNT_inc_simple_void(cv);
8396             }
8397             else {
8398                 pm->op_code_list = expr;
8399             }
8400         }
8401     }
8402     else {
8403         /* runtime pattern: build chain of regcomp etc ops */
8404         bool reglist;
8405         PADOFFSET cv_targ = 0;
8406
8407         reglist = isreg && expr->op_type == OP_LIST;
8408         if (reglist)
8409             op_null(expr);
8410
8411         if (has_code) {
8412             pm->op_code_list = expr;
8413             /* don't free op_code_list; its ops are embedded elsewhere too */
8414             pm->op_pmflags |= PMf_CODELIST_PRIVATE;
8415         }
8416
8417         if (is_split)
8418             /* make engine handle split ' ' specially */
8419             pm->op_pmflags |= PMf_SPLIT;
8420
8421         /* the OP_REGCMAYBE is a placeholder in the non-threaded case
8422          * to allow its op_next to be pointed past the regcomp and
8423          * preceding stacking ops;
8424          * OP_REGCRESET is there to reset taint before executing the
8425          * stacking ops */
8426         if (pm->op_pmflags & PMf_KEEP || TAINTING_get)
8427             expr = newUNOP((TAINTING_get ? OP_REGCRESET : OP_REGCMAYBE),0,expr);
8428
8429         if (pm->op_pmflags & PMf_HAS_CV) {
8430             /* we have a runtime qr with literal code. This means
8431              * that the qr// has been wrapped in a new CV, which
8432              * means that runtime consts, vars etc will have been compiled
8433              * against a new pad. So... we need to execute those ops
8434              * within the environment of the new CV. So wrap them in a call
8435              * to a new anon sub. i.e. for
8436              *
8437              *     qr/a$b(?{...})/,
8438              *
8439              * we build an anon sub that looks like
8440              *
8441              *     sub { "a", $b, '(?{...})' }
8442              *
8443              * and call it, passing the returned list to regcomp.
8444              * Or to put it another way, the list of ops that get executed
8445              * are:
8446              *
8447              *     normal              PMf_HAS_CV
8448              *     ------              -------------------
8449              *                         pushmark (for regcomp)
8450              *                         pushmark (for entersub)
8451              *                         anoncode
8452              *                         srefgen
8453              *                         entersub
8454              *     regcreset                  regcreset
8455              *     pushmark                   pushmark
8456              *     const("a")                 const("a")
8457              *     gvsv(b)                    gvsv(b)
8458              *     const("(?{...})")          const("(?{...})")
8459              *                                leavesub
8460              *     regcomp             regcomp
8461              */
8462
8463             SvREFCNT_inc_simple_void(PL_compcv);
8464             CvLVALUE_on(PL_compcv);
8465             /* these lines are just an unrolled newANONATTRSUB */
8466             expr = newSVOP(OP_ANONCODE, 0,
8467                     MUTABLE_SV(newATTRSUB(floor, 0, NULL, NULL, expr)));
8468             cv_targ = expr->op_targ;
8469             expr = newUNOP(OP_REFGEN, 0, expr);
8470
8471             expr = list(force_list(newUNOP(OP_ENTERSUB, 0, scalar(expr)), 1));
8472         }
8473
8474         rcop = alloc_LOGOP(OP_REGCOMP, scalar(expr), o);
8475         rcop->op_flags |=  ((PL_hints & HINT_RE_EVAL) ? OPf_SPECIAL : 0)
8476                            | (reglist ? OPf_STACKED : 0);
8477         rcop->op_targ = cv_targ;
8478
8479         /* /$x/ may cause an eval, since $x might be qr/(?{..})/  */
8480         if (PL_hints & HINT_RE_EVAL)
8481             S_set_haseval(aTHX);
8482
8483         /* establish postfix order */
8484         if (expr->op_type == OP_REGCRESET || expr->op_type == OP_REGCMAYBE) {
8485             LINKLIST(expr);
8486             rcop->op_next = expr;
8487             ((UNOP*)expr)->op_first->op_next = (OP*)rcop;
8488         }
8489         else {
8490             rcop->op_next = LINKLIST(expr);
8491             expr->op_next = (OP*)rcop;
8492         }
8493
8494         op_prepend_elem(o->op_type, scalar((OP*)rcop), o);
8495     }
8496
8497     if (repl) {
8498         OP *curop = repl;
8499         bool konst;
8500         /* If we are looking at s//.../e with a single statement, get past
8501            the implicit do{}. */
8502         if (curop->op_type == OP_NULL && curop->op_flags & OPf_KIDS
8503              && cUNOPx(curop)->op_first->op_type == OP_SCOPE
8504              && cUNOPx(curop)->op_first->op_flags & OPf_KIDS)
8505          {
8506             OP *sib;
8507             OP *kid = cUNOPx(cUNOPx(curop)->op_first)->op_first;
8508             if (kid->op_type == OP_NULL && (sib = OpSIBLING(kid))
8509              && !OpHAS_SIBLING(sib))
8510                 curop = sib;
8511         }
8512         if (curop->op_type == OP_CONST)
8513             konst = TRUE;
8514         else if (( (curop->op_type == OP_RV2SV ||
8515                     curop->op_type == OP_RV2AV ||
8516                     curop->op_type == OP_RV2HV ||
8517                     curop->op_type == OP_RV2GV)
8518                    && cUNOPx(curop)->op_first
8519                    && cUNOPx(curop)->op_first->op_type == OP_GV )
8520                 || curop->op_type == OP_PADSV
8521                 || curop->op_type == OP_PADAV
8522                 || curop->op_type == OP_PADHV
8523                 || curop->op_type == OP_PADANY) {
8524             repl_has_vars = 1;
8525             konst = TRUE;
8526         }
8527         else konst = FALSE;
8528         if (konst
8529             && !(repl_has_vars
8530                  && (!PM_GETRE(pm)
8531                      || !RX_PRELEN(PM_GETRE(pm))
8532                      || RX_EXTFLAGS(PM_GETRE(pm)) & RXf_EVAL_SEEN)))
8533         {
8534             pm->op_pmflags |= PMf_CONST;        /* const for long enough */
8535             op_prepend_elem(o->op_type, scalar(repl), o);
8536         }
8537         else {
8538             rcop = alloc_LOGOP(OP_SUBSTCONT, scalar(repl), o);
8539             rcop->op_private = 1;
8540
8541             /* establish postfix order */
8542             rcop->op_next = LINKLIST(repl);
8543             repl->op_next = (OP*)rcop;
8544
8545             pm->op_pmreplrootu.op_pmreplroot = scalar((OP*)rcop);
8546             assert(!(pm->op_pmflags & PMf_ONCE));
8547             pm->op_pmstashstartu.op_pmreplstart = LINKLIST(rcop);
8548             rcop->op_next = 0;
8549         }
8550     }
8551
8552     return (OP*)pm;
8553 }
8554
8555 /*
8556 =for apidoc newSVOP
8557
8558 Constructs, checks, and returns an op of any type that involves an
8559 embedded SV.  C<type> is the opcode.  C<flags> gives the eight bits
8560 of C<op_flags>.  C<sv> gives the SV to embed in the op; this function
8561 takes ownership of one reference to it.
8562
8563 =cut
8564 */
8565
8566 OP *
8567 Perl_newSVOP(pTHX_ I32 type, I32 flags, SV *sv)
8568 {
8569     SVOP *svop;
8570
8571     PERL_ARGS_ASSERT_NEWSVOP;
8572
8573     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_SVOP
8574         || (PL_opargs[type] & OA_CLASS_MASK) == OA_PVOP_OR_SVOP
8575         || (PL_opargs[type] & OA_CLASS_MASK) == OA_FILESTATOP
8576         || type == OP_CUSTOM);
8577
8578     NewOp(1101, svop, 1, SVOP);
8579     OpTYPE_set(svop, type);
8580     svop->op_sv = sv;
8581     svop->op_next = (OP*)svop;
8582     svop->op_flags = (U8)flags;
8583     svop->op_private = (U8)(0 | (flags >> 8));
8584     if (PL_opargs[type] & OA_RETSCALAR)
8585         scalar((OP*)svop);
8586     if (PL_opargs[type] & OA_TARGET)
8587         svop->op_targ = pad_alloc(type, SVs_PADTMP);
8588     return CHECKOP(type, svop);
8589 }
8590
8591 /*
8592 =for apidoc newDEFSVOP
8593
8594 Constructs and returns an op to access C<$_>.
8595
8596 =cut
8597 */
8598
8599 OP *
8600 Perl_newDEFSVOP(pTHX)
8601 {
8602         return newSVREF(newGVOP(OP_GV, 0, PL_defgv));
8603 }
8604
8605 #ifdef USE_ITHREADS
8606
8607 /*
8608 =for apidoc newPADOP
8609
8610 Constructs, checks, and returns an op of any type that involves a
8611 reference to a pad element.  C<type> is the opcode.  C<flags> gives the
8612 eight bits of C<op_flags>.  A pad slot is automatically allocated, and
8613 is populated with C<sv>; this function takes ownership of one reference
8614 to it.
8615
8616 This function only exists if Perl has been compiled to use ithreads.
8617
8618 =cut
8619 */
8620
8621 OP *
8622 Perl_newPADOP(pTHX_ I32 type, I32 flags, SV *sv)
8623 {
8624     PADOP *padop;
8625
8626     PERL_ARGS_ASSERT_NEWPADOP;
8627
8628     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_SVOP
8629         || (PL_opargs[type] & OA_CLASS_MASK) == OA_PVOP_OR_SVOP
8630         || (PL_opargs[type] & OA_CLASS_MASK) == OA_FILESTATOP
8631         || type == OP_CUSTOM);
8632
8633     NewOp(1101, padop, 1, PADOP);
8634     OpTYPE_set(padop, type);
8635     padop->op_padix =
8636         pad_alloc(type, isGV(sv) ? SVf_READONLY : SVs_PADTMP);
8637     SvREFCNT_dec(PAD_SVl(padop->op_padix));
8638     PAD_SETSV(padop->op_padix, sv);
8639     assert(sv);
8640     padop->op_next = (OP*)padop;
8641     padop->op_flags = (U8)flags;
8642     if (PL_opargs[type] & OA_RETSCALAR)
8643         scalar((OP*)padop);
8644     if (PL_opargs[type] & OA_TARGET)
8645         padop->op_targ = pad_alloc(type, SVs_PADTMP);
8646     return CHECKOP(type, padop);
8647 }
8648
8649 #endif /* USE_ITHREADS */
8650
8651 /*
8652 =for apidoc newGVOP
8653
8654 Constructs, checks, and returns an op of any type that involves an
8655 embedded reference to a GV.  C<type> is the opcode.  C<flags> gives the
8656 eight bits of C<op_flags>.  C<gv> identifies the GV that the op should
8657 reference; calling this function does not transfer ownership of any
8658 reference to it.
8659
8660 =cut
8661 */
8662
8663 OP *
8664 Perl_newGVOP(pTHX_ I32 type, I32 flags, GV *gv)
8665 {
8666     PERL_ARGS_ASSERT_NEWGVOP;
8667
8668 #ifdef USE_ITHREADS
8669     return newPADOP(type, flags, SvREFCNT_inc_simple_NN(gv));
8670 #else
8671     return newSVOP(type, flags, SvREFCNT_inc_simple_NN(gv));
8672 #endif
8673 }
8674
8675 /*
8676 =for apidoc newPVOP
8677
8678 Constructs, checks, and returns an op of any type that involves an
8679 embedded C-level pointer (PV).  C<type> is the opcode.  C<flags> gives
8680 the eight bits of C<op_flags>.  C<pv> supplies the C-level pointer.
8681 Depending on the op type, the memory referenced by C<pv> may be freed
8682 when the op is destroyed.  If the op is of a freeing type, C<pv> must
8683 have been allocated using C<PerlMemShared_malloc>.
8684
8685 =cut
8686 */
8687
8688 OP *
8689 Perl_newPVOP(pTHX_ I32 type, I32 flags, char *pv)
8690 {
8691     const bool utf8 = cBOOL(flags & SVf_UTF8);
8692     PVOP *pvop;
8693
8694     flags &= ~SVf_UTF8;
8695
8696     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_PVOP_OR_SVOP
8697         || type == OP_RUNCV || type == OP_CUSTOM
8698         || (PL_opargs[type] & OA_CLASS_MASK) == OA_LOOPEXOP);
8699
8700     NewOp(1101, pvop, 1, PVOP);
8701     OpTYPE_set(pvop, type);
8702     pvop->op_pv = pv;
8703     pvop->op_next = (OP*)pvop;
8704     pvop->op_flags = (U8)flags;
8705     pvop->op_private = utf8 ? OPpPV_IS_UTF8 : 0;
8706     if (PL_opargs[type] & OA_RETSCALAR)
8707         scalar((OP*)pvop);
8708     if (PL_opargs[type] & OA_TARGET)
8709         pvop->op_targ = pad_alloc(type, SVs_PADTMP);
8710     return CHECKOP(type, pvop);
8711 }
8712
8713 void
8714 Perl_package(pTHX_ OP *o)
8715 {
8716     SV *const sv = cSVOPo->op_sv;
8717
8718     PERL_ARGS_ASSERT_PACKAGE;
8719
8720     SAVEGENERICSV(PL_curstash);
8721     save_item(PL_curstname);
8722
8723     PL_curstash = (HV *)SvREFCNT_inc(gv_stashsv(sv, GV_ADD));
8724
8725     sv_setsv(PL_curstname, sv);
8726
8727     PL_hints |= HINT_BLOCK_SCOPE;
8728     PL_parser->copline = NOLINE;
8729
8730     op_free(o);
8731 }
8732
8733 void
8734 Perl_package_version( pTHX_ OP *v )
8735 {
8736     U32 savehints = PL_hints;
8737     PERL_ARGS_ASSERT_PACKAGE_VERSION;
8738     PL_hints &= ~HINT_STRICT_VARS;
8739     sv_setsv( GvSV(gv_fetchpvs("VERSION", GV_ADDMULTI, SVt_PV)), cSVOPx(v)->op_sv );
8740     PL_hints = savehints;
8741     op_free(v);
8742 }
8743
8744 void
8745 Perl_utilize(pTHX_ int aver, I32 floor, OP *version, OP *idop, OP *arg)
8746 {
8747     OP *pack;
8748     OP *imop;
8749     OP *veop;
8750     SV *use_version = NULL;
8751
8752     PERL_ARGS_ASSERT_UTILIZE;
8753
8754     if (idop->op_type != OP_CONST)
8755         Perl_croak(aTHX_ "Module name must be constant");
8756
8757     veop = NULL;
8758
8759     if (version) {
8760         SV * const vesv = ((SVOP*)version)->op_sv;
8761
8762         if (!arg && !SvNIOKp(vesv)) {
8763             arg = version;
8764         }
8765         else {
8766             OP *pack;
8767             SV *meth;
8768
8769             if (version->op_type != OP_CONST || !SvNIOKp(vesv))
8770                 Perl_croak(aTHX_ "Version number must be a constant number");
8771
8772             /* Make copy of idop so we don't free it twice */
8773             pack = newSVOP(OP_CONST, 0, newSVsv(((SVOP*)idop)->op_sv));
8774
8775             /* Fake up a method call to VERSION */
8776             meth = newSVpvs_share("VERSION");
8777             veop = op_convert_list(OP_ENTERSUB, OPf_STACKED|OPf_SPECIAL,
8778                             op_append_elem(OP_LIST,
8779                                         op_prepend_elem(OP_LIST, pack, version),
8780                                         newMETHOP_named(OP_METHOD_NAMED, 0, meth)));
8781         }
8782     }
8783
8784     /* Fake up an import/unimport */
8785     if (arg && arg->op_type == OP_STUB) {
8786         imop = arg;             /* no import on explicit () */
8787     }
8788     else if (SvNIOKp(((SVOP*)idop)->op_sv)) {
8789         imop = NULL;            /* use 5.0; */
8790         if (aver)
8791             use_version = ((SVOP*)idop)->op_sv;
8792         else
8793             idop->op_private |= OPpCONST_NOVER;
8794     }
8795     else {
8796         SV *meth;
8797
8798         /* Make copy of idop so we don't free it twice */
8799         pack = newSVOP(OP_CONST, 0, newSVsv(((SVOP*)idop)->op_sv));
8800
8801         /* Fake up a method call to import/unimport */
8802         meth = aver
8803             ? newSVpvs_share("import") : newSVpvs_share("unimport");
8804         imop = op_convert_list(OP_ENTERSUB, OPf_STACKED|OPf_SPECIAL,
8805                        op_append_elem(OP_LIST,
8806                                    op_prepend_elem(OP_LIST, pack, arg),
8807                                    newMETHOP_named(OP_METHOD_NAMED, 0, meth)
8808                        ));
8809     }
8810
8811     /* Fake up the BEGIN {}, which does its thing immediately. */
8812     newATTRSUB(floor,
8813         newSVOP(OP_CONST, 0, newSVpvs_share("BEGIN")),
8814         NULL,
8815         NULL,
8816         op_append_elem(OP_LINESEQ,
8817             op_append_elem(OP_LINESEQ,
8818                 newSTATEOP(0, NULL, newUNOP(OP_REQUIRE, 0, idop)),
8819                 newSTATEOP(0, NULL, veop)),
8820             newSTATEOP(0, NULL, imop) ));
8821
8822     if (use_version) {
8823         /* Enable the
8824          * feature bundle that corresponds to the required version. */
8825         use_version = sv_2mortal(new_version(use_version));
8826         S_enable_feature_bundle(aTHX_ use_version);
8827
8828         /* If a version >= 5.11.0 is requested, strictures are on by default! */
8829         if (vcmp(use_version,
8830                  sv_2mortal(upg_version(newSVnv(5.011000), FALSE))) >= 0) {
8831             if (!(PL_hints & HINT_EXPLICIT_STRICT_REFS))
8832                 PL_hints |= HINT_STRICT_REFS;
8833             if (!(PL_hints & HINT_EXPLICIT_STRICT_SUBS))
8834                 PL_hints |= HINT_STRICT_SUBS;
8835             if (!(PL_hints & HINT_EXPLICIT_STRICT_VARS))
8836                 PL_hints |= HINT_STRICT_VARS;
8837         }
8838         /* otherwise they are off */
8839         else {
8840             if (!(PL_hints & HINT_EXPLICIT_STRICT_REFS))
8841                 PL_hints &= ~HINT_STRICT_REFS;
8842             if (!(PL_hints & HINT_EXPLICIT_STRICT_SUBS))
8843                 PL_hints &= ~HINT_STRICT_SUBS;
8844             if (!(PL_hints & HINT_EXPLICIT_STRICT_VARS))
8845                 PL_hints &= ~HINT_STRICT_VARS;
8846         }
8847     }
8848
8849     /* The "did you use incorrect case?" warning used to be here.
8850      * The problem is that on case-insensitive filesystems one
8851      * might get false positives for "use" (and "require"):
8852      * "use Strict" or "require CARP" will work.  This causes
8853      * portability problems for the script: in case-strict
8854      * filesystems the script will stop working.
8855      *
8856      * The "incorrect case" warning checked whether "use Foo"
8857      * imported "Foo" to your namespace, but that is wrong, too:
8858      * there is no requirement nor promise in the language that
8859      * a Foo.pm should or would contain anything in package "Foo".
8860      *
8861      * There is very little Configure-wise that can be done, either:
8862      * the case-sensitivity of the build filesystem of Perl does not
8863      * help in guessing the case-sensitivity of the runtime environment.
8864      */
8865
8866     PL_hints |= HINT_BLOCK_SCOPE;
8867     PL_parser->copline = NOLINE;
8868     COP_SEQMAX_INC; /* Purely for B::*'s benefit */
8869 }
8870
8871 /*
8872 =head1 Embedding Functions
8873
8874 =for apidoc load_module
8875
8876 Loads the module whose name is pointed to by the string part of C<name>.
8877 Note that the actual module name, not its filename, should be given.
8878 Eg, "Foo::Bar" instead of "Foo/Bar.pm". ver, if specified and not NULL,
8879 provides version semantics similar to C<use Foo::Bar VERSION>. The optional
8880 trailing arguments can be used to specify arguments to the module's C<import()>
8881 method, similar to C<use Foo::Bar VERSION LIST>; their precise handling depends
8882 on the flags. The flags argument is a bitwise-ORed collection of any of
8883 C<PERL_LOADMOD_DENY>, C<PERL_LOADMOD_NOIMPORT>, or C<PERL_LOADMOD_IMPORT_OPS>
8884 (or 0 for no flags).
8885
8886 If C<PERL_LOADMOD_NOIMPORT> is set, the module is loaded as if with an empty
8887 import list, as in C<use Foo::Bar ()>; this is the only circumstance in which
8888 the trailing optional arguments may be omitted entirely. Otherwise, if
8889 C<PERL_LOADMOD_IMPORT_OPS> is set, the trailing arguments must consist of
8890 exactly one C<OP*>, containing the op tree that produces the relevant import
8891 arguments. Otherwise, the trailing arguments must all be C<SV*> values that
8892 will be used as import arguments; and the list must be terminated with C<(SV*)
8893 NULL>. If neither C<PERL_LOADMOD_NOIMPORT> nor C<PERL_LOADMOD_IMPORT_OPS> is
8894 set, the trailing C<NULL> pointer is needed even if no import arguments are
8895 desired. The reference count for each specified C<SV*> argument is
8896 decremented. In addition, the C<name> argument is modified.
8897
8898 If C<PERL_LOADMOD_DENY> is set, the module is loaded as if with C<no> rather
8899 than C<use>.
8900
8901 =for apidoc Amnh||PERL_LOADMOD_DENY
8902 =for apidoc Amnh||PERL_LOADMOD_NOIMPORT
8903 =for apidoc Amnh||PERL_LOADMOD_IMPORT_OPS
8904
8905 =cut */
8906
8907 void
8908 Perl_load_module(pTHX_ U32 flags, SV *name, SV *ver, ...)
8909 {
8910     va_list args;
8911
8912     PERL_ARGS_ASSERT_LOAD_MODULE;
8913
8914     va_start(args, ver);
8915     vload_module(flags, name, ver, &args);
8916     va_end(args);
8917 }
8918
8919 #ifdef PERL_IMPLICIT_CONTEXT
8920 void
8921 Perl_load_module_nocontext(U32 flags, SV *name, SV *ver, ...)
8922 {
8923     dTHX;
8924     va_list args;
8925     PERL_ARGS_ASSERT_LOAD_MODULE_NOCONTEXT;
8926     va_start(args, ver);
8927     vload_module(flags, name, ver, &args);
8928     va_end(args);
8929 }
8930 #endif
8931
8932 void
8933 Perl_vload_module(pTHX_ U32 flags, SV *name, SV *ver, va_list *args)
8934 {
8935     OP *veop, *imop;
8936     OP * modname;
8937     I32 floor;
8938
8939     PERL_ARGS_ASSERT_VLOAD_MODULE;
8940
8941     /* utilize() fakes up a BEGIN { require ..; import ... }, so make sure
8942      * that it has a PL_parser to play with while doing that, and also
8943      * that it doesn't mess with any existing parser, by creating a tmp
8944      * new parser with lex_start(). This won't actually be used for much,
8945      * since pp_require() will create another parser for the real work.
8946      * The ENTER/LEAVE pair protect callers from any side effects of use.
8947      *
8948      * start_subparse() creates a new PL_compcv. This means that any ops
8949      * allocated below will be allocated from that CV's op slab, and so
8950      * will be automatically freed if the utilise() fails
8951      */
8952
8953     ENTER;
8954     SAVEVPTR(PL_curcop);
8955     lex_start(NULL, NULL, LEX_START_SAME_FILTER);
8956     floor = start_subparse(FALSE, 0);
8957
8958     modname = newSVOP(OP_CONST, 0, name);
8959     modname->op_private |= OPpCONST_BARE;
8960     if (ver) {
8961         veop = newSVOP(OP_CONST, 0, ver);
8962     }
8963     else
8964         veop = NULL;
8965     if (flags & PERL_LOADMOD_NOIMPORT) {
8966         imop = sawparens(newNULLLIST());
8967     }
8968     else if (flags & PERL_LOADMOD_IMPORT_OPS) {
8969         imop = va_arg(*args, OP*);
8970     }
8971     else {
8972         SV *sv;
8973         imop = NULL;
8974         sv = va_arg(*args, SV*);
8975         while (sv) {
8976             imop = op_append_elem(OP_LIST, imop, newSVOP(OP_CONST, 0, sv));
8977             sv = va_arg(*args, SV*);
8978         }
8979     }
8980
8981     utilize(!(flags & PERL_LOADMOD_DENY), floor, veop, modname, imop);
8982     LEAVE;
8983 }
8984
8985 PERL_STATIC_INLINE OP *
8986 S_new_entersubop(pTHX_ GV *gv, OP *arg)
8987 {
8988     return newUNOP(OP_ENTERSUB, OPf_STACKED,
8989                    newLISTOP(OP_LIST, 0, arg,
8990                              newUNOP(OP_RV2CV, 0,
8991                                      newGVOP(OP_GV, 0, gv))));
8992 }
8993
8994 OP *
8995 Perl_dofile(pTHX_ OP *term, I32 force_builtin)
8996 {
8997     OP *doop;
8998     GV *gv;
8999
9000     PERL_ARGS_ASSERT_DOFILE;
9001
9002     if (!force_builtin && (gv = gv_override("do", 2))) {
9003         doop = S_new_entersubop(aTHX_ gv, term);
9004     }
9005     else {
9006         doop = newUNOP(OP_DOFILE, 0, scalar(term));
9007     }
9008     return doop;
9009 }
9010
9011 /*
9012 =head1 Optree construction
9013
9014 =for apidoc newSLICEOP
9015
9016 Constructs, checks, and returns an C<lslice> (list slice) op.  C<flags>
9017 gives the eight bits of C<op_flags>, except that C<OPf_KIDS> will
9018 be set automatically, and, shifted up eight bits, the eight bits of
9019 C<op_private>, except that the bit with value 1 or 2 is automatically
9020 set as required.  C<listval> and C<subscript> supply the parameters of
9021 the slice; they are consumed by this function and become part of the
9022 constructed op tree.
9023
9024 =cut
9025 */
9026
9027 OP *
9028 Perl_newSLICEOP(pTHX_ I32 flags, OP *subscript, OP *listval)
9029 {
9030     return newBINOP(OP_LSLICE, flags,
9031             list(force_list(subscript, 1)),
9032             list(force_list(listval,   1)) );
9033 }
9034
9035 #define ASSIGN_SCALAR 0
9036 #define ASSIGN_LIST   1
9037 #define ASSIGN_REF    2
9038
9039 /* given the optree o on the LHS of an assignment, determine whether its:
9040  *  ASSIGN_SCALAR   $x  = ...
9041  *  ASSIGN_LIST    ($x) = ...
9042  *  ASSIGN_REF     \$x  = ...
9043  */
9044
9045 STATIC I32
9046 S_assignment_type(pTHX_ const OP *o)
9047 {
9048     unsigned type;
9049     U8 flags;
9050     U8 ret;
9051
9052     if (!o)
9053         return ASSIGN_LIST;
9054
9055     if (o->op_type == OP_SREFGEN)
9056     {
9057         OP * const kid = cUNOPx(cUNOPo->op_first)->op_first;
9058         type = kid->op_type;
9059         flags = o->op_flags | kid->op_flags;
9060         if (!(flags & OPf_PARENS)
9061           && (kid->op_type == OP_RV2AV || kid->op_type == OP_PADAV ||
9062               kid->op_type == OP_RV2HV || kid->op_type == OP_PADHV ))
9063             return ASSIGN_REF;
9064         ret = ASSIGN_REF;
9065     } else {
9066         if ((o->op_type == OP_NULL) && (o->op_flags & OPf_KIDS))
9067             o = cUNOPo->op_first;
9068         flags = o->op_flags;
9069         type = o->op_type;
9070         ret = ASSIGN_SCALAR;
9071     }
9072
9073     if (type == OP_COND_EXPR) {
9074         OP * const sib = OpSIBLING(cLOGOPo->op_first);
9075         const I32 t = assignment_type(sib);
9076         const I32 f = assignment_type(OpSIBLING(sib));
9077
9078         if (t == ASSIGN_LIST && f == ASSIGN_LIST)
9079             return ASSIGN_LIST;
9080         if ((t == ASSIGN_LIST) ^ (f == ASSIGN_LIST))
9081             yyerror("Assignment to both a list and a scalar");
9082         return ASSIGN_SCALAR;
9083     }
9084
9085     if (type == OP_LIST &&
9086         (flags & OPf_WANT) == OPf_WANT_SCALAR &&
9087         o->op_private & OPpLVAL_INTRO)
9088         return ret;
9089
9090     if (type == OP_LIST || flags & OPf_PARENS ||
9091         type == OP_RV2AV || type == OP_RV2HV ||
9092         type == OP_ASLICE || type == OP_HSLICE ||
9093         type == OP_KVASLICE || type == OP_KVHSLICE || type == OP_REFGEN)
9094         return ASSIGN_LIST;
9095
9096     if (type == OP_PADAV || type == OP_PADHV)
9097         return ASSIGN_LIST;
9098
9099     if (type == OP_RV2SV)
9100         return ret;
9101
9102     return ret;
9103 }
9104
9105 static OP *
9106 S_newONCEOP(pTHX_ OP *initop, OP *padop)
9107 {
9108     const PADOFFSET target = padop->op_targ;
9109     OP *const other = newOP(OP_PADSV,
9110                             padop->op_flags
9111                             | ((padop->op_private & ~OPpLVAL_INTRO) << 8));
9112     OP *const first = newOP(OP_NULL, 0);
9113     OP *const nullop = newCONDOP(0, first, initop, other);
9114     /* XXX targlex disabled for now; see ticket #124160
9115         newCONDOP(0, first, S_maybe_targlex(aTHX_ initop), other);
9116      */
9117     OP *const condop = first->op_next;
9118
9119     OpTYPE_set(condop, OP_ONCE);
9120     other->op_targ = target;
9121     nullop->op_flags |= OPf_WANT_SCALAR;
9122
9123     /* Store the initializedness of state vars in a separate
9124        pad entry.  */
9125     condop->op_targ =
9126       pad_add_name_pvn("$",1,padadd_NO_DUP_CHECK|padadd_STATE,0,0);
9127     /* hijacking PADSTALE for uninitialized state variables */
9128     SvPADSTALE_on(PAD_SVl(condop->op_targ));
9129
9130     return nullop;
9131 }
9132
9133 /*
9134 =for apidoc newASSIGNOP
9135
9136 Constructs, checks, and returns an assignment op.  C<left> and C<right>
9137 supply the parameters of the assignment; they are consumed by this
9138 function and become part of the constructed op tree.
9139
9140 If C<optype> is C<OP_ANDASSIGN>, C<OP_ORASSIGN>, or C<OP_DORASSIGN>, then
9141 a suitable conditional optree is constructed.  If C<optype> is the opcode
9142 of a binary operator, such as C<OP_BIT_OR>, then an op is constructed that
9143 performs the binary operation and assigns the result to the left argument.
9144 Either way, if C<optype> is non-zero then C<flags> has no effect.
9145
9146 If C<optype> is zero, then a plain scalar or list assignment is
9147 constructed.  Which type of assignment it is is automatically determined.
9148 C<flags> gives the eight bits of C<op_flags>, except that C<OPf_KIDS>
9149 will be set automatically, and, shifted up eight bits, the eight bits
9150 of C<op_private>, except that the bit with value 1 or 2 is automatically
9151 set as required.
9152
9153 =cut
9154 */
9155
9156 OP *
9157 Perl_newASSIGNOP(pTHX_ I32 flags, OP *left, I32 optype, OP *right)
9158 {
9159     OP *o;
9160     I32 assign_type;
9161
9162     if (optype) {
9163         if (optype == OP_ANDASSIGN || optype == OP_ORASSIGN || optype == OP_DORASSIGN) {
9164             right = scalar(right);
9165             return newLOGOP(optype, 0,
9166                 op_lvalue(scalar(left), optype),
9167                 newBINOP(OP_SASSIGN, OPpASSIGN_BACKWARDS<<8, right, right));
9168         }
9169         else {
9170             return newBINOP(optype, OPf_STACKED,
9171                 op_lvalue(scalar(left), optype), scalar(right));
9172         }
9173     }
9174
9175     if ((assign_type = assignment_type(left)) == ASSIGN_LIST) {
9176         OP *state_var_op = NULL;
9177         static const char no_list_state[] = "Initialization of state variables"
9178             " in list currently forbidden";
9179         OP *curop;
9180
9181         if (left->op_type == OP_ASLICE || left->op_type == OP_HSLICE)
9182             left->op_private &= ~ OPpSLICEWARNING;
9183
9184         PL_modcount = 0;
9185         left = op_lvalue(left, OP_AASSIGN);
9186         curop = list(force_list(left, 1));
9187         o = newBINOP(OP_AASSIGN, flags, list(force_list(right, 1)), curop);
9188         o->op_private = (U8)(0 | (flags >> 8));
9189
9190         if (OP_TYPE_IS_OR_WAS(left, OP_LIST))
9191         {
9192             OP *lop = ((LISTOP*)left)->op_first, *vop, *eop;
9193             if (!(left->op_flags & OPf_PARENS) &&
9194                     lop->op_type == OP_PUSHMARK &&
9195                     (vop = OpSIBLING(lop)) &&
9196                     (vop->op_type == OP_PADAV || vop->op_type == OP_PADHV) &&
9197                     !(vop->op_flags & OPf_PARENS) &&
9198                     (vop->op_private & (OPpLVAL_INTRO|OPpPAD_STATE)) ==
9199                         (OPpLVAL_INTRO|OPpPAD_STATE) &&
9200                     (eop = OpSIBLING(vop)) &&
9201                     eop->op_type == OP_ENTERSUB &&
9202                     !OpHAS_SIBLING(eop)) {
9203                 state_var_op = vop;
9204             } else {
9205                 while (lop) {
9206                     if ((lop->op_type == OP_PADSV ||
9207                          lop->op_type == OP_PADAV ||
9208                          lop->op_type == OP_PADHV ||
9209                          lop->op_type == OP_PADANY)
9210                       && (lop->op_private & OPpPAD_STATE)
9211                     )
9212                         yyerror(no_list_state);
9213                     lop = OpSIBLING(lop);
9214                 }
9215             }
9216         }
9217         else if (  (left->op_private & OPpLVAL_INTRO)
9218                 && (left->op_private & OPpPAD_STATE)
9219                 && (   left->op_type == OP_PADSV
9220                     || left->op_type == OP_PADAV
9221                     || left->op_type == OP_PADHV
9222                     || left->op_type == OP_PADANY)
9223         ) {
9224                 /* All single variable list context state assignments, hence
9225                    state ($a) = ...
9226                    (state $a) = ...
9227                    state @a = ...
9228                    state (@a) = ...
9229                    (state @a) = ...
9230                    state %a = ...
9231                    state (%a) = ...
9232                    (state %a) = ...
9233                 */
9234                 if (left->op_flags & OPf_PARENS)
9235                     yyerror(no_list_state);
9236                 else
9237                     state_var_op = left;
9238         }
9239
9240         /* optimise @a = split(...) into:
9241         * @{expr}:              split(..., @{expr}) (where @a is not flattened)
9242         * @a, my @a, local @a:  split(...)          (where @a is attached to
9243         *                                            the split op itself)
9244         */
9245
9246         if (   right
9247             && right->op_type == OP_SPLIT
9248             /* don't do twice, e.g. @b = (@a = split) */
9249             && !(right->op_private & OPpSPLIT_ASSIGN))
9250         {
9251             OP *gvop = NULL;
9252
9253             if (   (  left->op_type == OP_RV2AV
9254                    && (gvop=((UNOP*)left)->op_first)->op_type==OP_GV)
9255                 || left->op_type == OP_PADAV)
9256             {
9257                 /* @pkg or @lex or local @pkg' or 'my @lex' */
9258                 OP *tmpop;
9259                 if (gvop) {
9260 #ifdef USE_ITHREADS
9261                     ((PMOP*)right)->op_pmreplrootu.op_pmtargetoff
9262                         = cPADOPx(gvop)->op_padix;
9263                     cPADOPx(gvop)->op_padix = 0;        /* steal it */
9264 #else
9265                     ((PMOP*)right)->op_pmreplrootu.op_pmtargetgv
9266                         = MUTABLE_GV(cSVOPx(gvop)->op_sv);
9267                     cSVOPx(gvop)->op_sv = NULL; /* steal it */
9268 #endif
9269                     right->op_private |=
9270                         left->op_private & OPpOUR_INTRO;
9271                 }
9272                 else {
9273                     ((PMOP*)right)->op_pmreplrootu.op_pmtargetoff = left->op_targ;
9274                     left->op_targ = 0;  /* steal it */
9275                     right->op_private |= OPpSPLIT_LEX;
9276                 }
9277                 right->op_private |= left->op_private & OPpLVAL_INTRO;
9278
9279               detach_split:
9280                 tmpop = cUNOPo->op_first;       /* to list (nulled) */
9281                 tmpop = ((UNOP*)tmpop)->op_first; /* to pushmark */
9282                 assert(OpSIBLING(tmpop) == right);
9283                 assert(!OpHAS_SIBLING(right));
9284                 /* detach the split subtreee from the o tree,
9285                  * then free the residual o tree */
9286                 op_sibling_splice(cUNOPo->op_first, tmpop, 1, NULL);
9287                 op_free(o);                     /* blow off assign */
9288                 right->op_private |= OPpSPLIT_ASSIGN;
9289                 right->op_flags &= ~OPf_WANT;
9290                         /* "I don't know and I don't care." */
9291                 return right;
9292             }
9293             else if (left->op_type == OP_RV2AV) {
9294                 /* @{expr} */
9295
9296                 OP *pushop = cUNOPx(cBINOPo->op_last)->op_first;
9297                 assert(OpSIBLING(pushop) == left);
9298                 /* Detach the array ...  */
9299                 op_sibling_splice(cBINOPo->op_last, pushop, 1, NULL);
9300                 /* ... and attach it to the split.  */
9301                 op_sibling_splice(right, cLISTOPx(right)->op_last,
9302                                   0, left);
9303                 right->op_flags |= OPf_STACKED;
9304                 /* Detach split and expunge aassign as above.  */
9305                 goto detach_split;
9306             }
9307             else if (PL_modcount < RETURN_UNLIMITED_NUMBER &&
9308                     ((LISTOP*)right)->op_last->op_type == OP_CONST)
9309             {
9310                 /* convert split(...,0) to split(..., PL_modcount+1) */
9311                 SV ** const svp =
9312                     &((SVOP*)((LISTOP*)right)->op_last)->op_sv;
9313                 SV * const sv = *svp;
9314                 if (SvIOK(sv) && SvIVX(sv) == 0)
9315                 {
9316                   if (right->op_private & OPpSPLIT_IMPLIM) {
9317                     /* our own SV, created in ck_split */
9318                     SvREADONLY_off(sv);
9319                     sv_setiv(sv, PL_modcount+1);
9320                   }
9321                   else {
9322                     /* SV may belong to someone else */
9323                     SvREFCNT_dec(sv);
9324                     *svp = newSViv(PL_modcount+1);
9325                   }
9326                 }
9327             }
9328         }
9329
9330         if (state_var_op)
9331             o = S_newONCEOP(aTHX_ o, state_var_op);
9332         return o;
9333     }
9334     if (assign_type == ASSIGN_REF)
9335         return newBINOP(OP_REFASSIGN, flags, scalar(right), left);
9336     if (!right)
9337         right = newOP(OP_UNDEF, 0);
9338     if (right->op_type == OP_READLINE) {
9339         right->op_flags |= OPf_STACKED;
9340         return newBINOP(OP_NULL, flags, op_lvalue(scalar(left), OP_SASSIGN),
9341                 scalar(right));
9342     }
9343     else {
9344         o = newBINOP(OP_SASSIGN, flags,
9345             scalar(right), op_lvalue(scalar(left), OP_SASSIGN) );
9346     }
9347     return o;
9348 }
9349
9350 /*
9351 =for apidoc newSTATEOP
9352
9353 Constructs a state op (COP).  The state op is normally a C<nextstate> op,
9354 but will be a C<dbstate> op if debugging is enabled for currently-compiled
9355 code.  The state op is populated from C<PL_curcop> (or C<PL_compiling>).
9356 If C<label> is non-null, it supplies the name of a label to attach to
9357 the state op; this function takes ownership of the memory pointed at by
9358 C<label>, and will free it.  C<flags> gives the eight bits of C<op_flags>
9359 for the state op.
9360
9361 If C<o> is null, the state op is returned.  Otherwise the state op is
9362 combined with C<o> into a C<lineseq> list op, which is returned.  C<o>
9363 is consumed by this function and becomes part of the returned op tree.
9364
9365 =cut
9366 */
9367
9368 OP *
9369 Perl_newSTATEOP(pTHX_ I32 flags, char *label, OP *o)
9370 {
9371     const U32 seq = intro_my();
9372     const U32 utf8 = flags & SVf_UTF8;
9373     COP *cop;
9374
9375     PL_parser->parsed_sub = 0;
9376
9377     flags &= ~SVf_UTF8;
9378
9379     NewOp(1101, cop, 1, COP);
9380     if (PERLDB_LINE && CopLINE(PL_curcop) && PL_curstash != PL_debstash) {
9381         OpTYPE_set(cop, OP_DBSTATE);
9382     }
9383     else {
9384         OpTYPE_set(cop, OP_NEXTSTATE);
9385     }
9386     cop->op_flags = (U8)flags;
9387     CopHINTS_set(cop, PL_hints);
9388 #ifdef VMS
9389     if (VMSISH_HUSHED) cop->op_private |= OPpHUSH_VMSISH;
9390 #endif
9391     cop->op_next = (OP*)cop;
9392
9393     cop->cop_seq = seq;
9394     cop->cop_warnings = DUP_WARNINGS(PL_curcop->cop_warnings);
9395     CopHINTHASH_set(cop, cophh_copy(CopHINTHASH_get(PL_curcop)));
9396     if (label) {
9397         Perl_cop_store_label(aTHX_ cop, label, strlen(label), utf8);
9398
9399         PL_hints |= HINT_BLOCK_SCOPE;
9400         /* It seems that we need to defer freeing this pointer, as other parts
9401            of the grammar end up wanting to copy it after this op has been
9402            created. */
9403         SAVEFREEPV(label);
9404     }
9405
9406     if (PL_parser->preambling != NOLINE) {
9407         CopLINE_set(cop, PL_parser->preambling);
9408         PL_parser->copline = NOLINE;
9409     }
9410     else if (PL_parser->copline == NOLINE)
9411         CopLINE_set(cop, CopLINE(PL_curcop));
9412     else {
9413         CopLINE_set(cop, PL_parser->copline);
9414         PL_parser->copline = NOLINE;
9415     }
9416 #ifdef USE_ITHREADS
9417     CopFILE_set(cop, CopFILE(PL_curcop));       /* XXX share in a pvtable? */
9418 #else
9419     CopFILEGV_set(cop, CopFILEGV(PL_curcop));
9420 #endif
9421     CopSTASH_set(cop, PL_curstash);
9422
9423     if (cop->op_type == OP_DBSTATE) {
9424         /* this line can have a breakpoint - store the cop in IV */
9425         AV *av = CopFILEAVx(PL_curcop);
9426         if (av) {
9427             SV * const * const svp = av_fetch(av, CopLINE(cop), FALSE);
9428             if (svp && *svp != &PL_sv_undef ) {
9429                 (void)SvIOK_on(*svp);
9430                 SvIV_set(*svp, PTR2IV(cop));
9431             }
9432         }
9433     }
9434
9435     if (flags & OPf_SPECIAL)
9436         op_null((OP*)cop);
9437     return op_prepend_elem(OP_LINESEQ, (OP*)cop, o);
9438 }
9439
9440 /*
9441 =for apidoc newLOGOP
9442
9443 Constructs, checks, and returns a logical (flow control) op.  C<type>
9444 is the opcode.  C<flags> gives the eight bits of C<op_flags>, except
9445 that C<OPf_KIDS> will be set automatically, and, shifted up eight bits,
9446 the eight bits of C<op_private>, except that the bit with value 1 is
9447 automatically set.  C<first> supplies the expression controlling the
9448 flow, and C<other> supplies the side (alternate) chain of ops; they are
9449 consumed by this function and become part of the constructed op tree.
9450
9451 =cut
9452 */
9453
9454 OP *
9455 Perl_newLOGOP(pTHX_ I32 type, I32 flags, OP *first, OP *other)
9456 {
9457     PERL_ARGS_ASSERT_NEWLOGOP;
9458
9459     return new_logop(type, flags, &first, &other);
9460 }
9461
9462
9463 /* See if the optree o contains a single OP_CONST (plus possibly
9464  * surrounding enter/nextstate/null etc). If so, return it, else return
9465  * NULL.
9466  */
9467
9468 STATIC OP *
9469 S_search_const(pTHX_ OP *o)
9470 {
9471     PERL_ARGS_ASSERT_SEARCH_CONST;
9472
9473   redo:
9474     switch (o->op_type) {
9475         case OP_CONST:
9476             return o;
9477         case OP_NULL:
9478             if (o->op_flags & OPf_KIDS) {
9479                 o = cUNOPo->op_first;
9480                 goto redo;
9481             }
9482             break;
9483         case OP_LEAVE:
9484         case OP_SCOPE:
9485         case OP_LINESEQ:
9486         {
9487             OP *kid;
9488             if (!(o->op_flags & OPf_KIDS))
9489                 return NULL;
9490             kid = cLISTOPo->op_first;
9491
9492             do {
9493                 switch (kid->op_type) {
9494                     case OP_ENTER:
9495                     case OP_NULL:
9496                     case OP_NEXTSTATE:
9497                         kid = OpSIBLING(kid);
9498                         break;
9499                     default:
9500                         if (kid != cLISTOPo->op_last)
9501                             return NULL;
9502                         goto last;
9503                 }
9504             } while (kid);
9505
9506             if (!kid)
9507                 kid = cLISTOPo->op_last;
9508           last:
9509              o = kid;
9510              goto redo;
9511         }
9512     }
9513
9514     return NULL;
9515 }
9516
9517
9518 STATIC OP *
9519 S_new_logop(pTHX_ I32 type, I32 flags, OP** firstp, OP** otherp)
9520 {
9521     LOGOP *logop;
9522     OP *o;
9523     OP *first;
9524     OP *other;
9525     OP *cstop = NULL;
9526     int prepend_not = 0;
9527
9528     PERL_ARGS_ASSERT_NEW_LOGOP;
9529
9530     first = *firstp;
9531     other = *otherp;
9532
9533     /* [perl #59802]: Warn about things like "return $a or $b", which
9534        is parsed as "(return $a) or $b" rather than "return ($a or
9535        $b)".  NB: This also applies to xor, which is why we do it
9536        here.
9537      */
9538     switch (first->op_type) {
9539     case OP_NEXT:
9540     case OP_LAST:
9541     case OP_REDO:
9542         /* XXX: Perhaps we should emit a stronger warning for these.
9543            Even with the high-precedence operator they don't seem to do
9544            anything sensible.
9545
9546            But until we do, fall through here.
9547          */
9548     case OP_RETURN:
9549     case OP_EXIT:
9550     case OP_DIE:
9551     case OP_GOTO:
9552         /* XXX: Currently we allow people to "shoot themselves in the
9553            foot" by explicitly writing "(return $a) or $b".
9554
9555            Warn unless we are looking at the result from folding or if
9556            the programmer explicitly grouped the operators like this.
9557            The former can occur with e.g.
9558
9559                 use constant FEATURE => ( $] >= ... );
9560                 sub { not FEATURE and return or do_stuff(); }
9561          */
9562         if (!first->op_folded && !(first->op_flags & OPf_PARENS))
9563             Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX),
9564                            "Possible precedence issue with control flow operator");
9565         /* XXX: Should we optimze this to "return $a;" (i.e. remove
9566            the "or $b" part)?
9567         */
9568         break;
9569     }
9570
9571     if (type == OP_XOR)         /* Not short circuit, but here by precedence. */
9572         return newBINOP(type, flags, scalar(first), scalar(other));
9573
9574     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_LOGOP
9575         || type == OP_CUSTOM);
9576
9577     scalarboolean(first);
9578
9579     /* search for a constant op that could let us fold the test */
9580     if ((cstop = search_const(first))) {
9581         if (cstop->op_private & OPpCONST_STRICT)
9582             no_bareword_allowed(cstop);
9583         else if ((cstop->op_private & OPpCONST_BARE))
9584                 Perl_ck_warner(aTHX_ packWARN(WARN_BAREWORD), "Bareword found in conditional");
9585         if ((type == OP_AND &&  SvTRUE(((SVOP*)cstop)->op_sv)) ||
9586             (type == OP_OR  && !SvTRUE(((SVOP*)cstop)->op_sv)) ||
9587             (type == OP_DOR && !SvOK(((SVOP*)cstop)->op_sv))) {
9588             /* Elide the (constant) lhs, since it can't affect the outcome */
9589             *firstp = NULL;
9590             if (other->op_type == OP_CONST)
9591                 other->op_private |= OPpCONST_SHORTCIRCUIT;
9592             op_free(first);
9593             if (other->op_type == OP_LEAVE)
9594                 other = newUNOP(OP_NULL, OPf_SPECIAL, other);
9595             else if (other->op_type == OP_MATCH
9596                   || other->op_type == OP_SUBST
9597                   || other->op_type == OP_TRANSR
9598                   || other->op_type == OP_TRANS)
9599                 /* Mark the op as being unbindable with =~ */
9600                 other->op_flags |= OPf_SPECIAL;
9601
9602             other->op_folded = 1;
9603             return other;
9604         }
9605         else {
9606             /* Elide the rhs, since the outcome is entirely determined by
9607              * the (constant) lhs */
9608
9609             /* check for C<my $x if 0>, or C<my($x,$y) if 0> */
9610             const OP *o2 = other;
9611             if ( ! (o2->op_type == OP_LIST
9612                     && (( o2 = cUNOPx(o2)->op_first))
9613                     && o2->op_type == OP_PUSHMARK
9614                     && (( o2 = OpSIBLING(o2))) )
9615             )
9616                 o2 = other;
9617             if ((o2->op_type == OP_PADSV || o2->op_type == OP_PADAV
9618                         || o2->op_type == OP_PADHV)
9619                 && o2->op_private & OPpLVAL_INTRO
9620                 && !(o2->op_private & OPpPAD_STATE))
9621             {
9622         Perl_croak(aTHX_ "This use of my() in false conditional is "
9623                           "no longer allowed");
9624             }
9625
9626             *otherp = NULL;
9627             if (cstop->op_type == OP_CONST)
9628                 cstop->op_private |= OPpCONST_SHORTCIRCUIT;
9629             op_free(other);
9630             return first;
9631         }
9632     }
9633     else if ((first->op_flags & OPf_KIDS) && type != OP_DOR
9634         && ckWARN(WARN_MISC)) /* [#24076] Don't warn for <FH> err FOO. */
9635     {
9636         const OP * const k1 = ((UNOP*)first)->op_first;
9637         const OP * const k2 = OpSIBLING(k1);
9638         OPCODE warnop = 0;
9639         switch (first->op_type)
9640         {
9641         case OP_NULL:
9642             if (k2 && k2->op_type == OP_READLINE
9643                   && (k2->op_flags & OPf_STACKED)
9644                   && ((k1->op_flags & OPf_WANT) == OPf_WANT_SCALAR))
9645             {
9646                 warnop = k2->op_type;
9647             }
9648             break;
9649
9650         case OP_SASSIGN:
9651             if (k1->op_type == OP_READDIR
9652                   || k1->op_type == OP_GLOB
9653                   || (k1->op_type == OP_NULL && k1->op_targ == OP_GLOB)
9654                  || k1->op_type == OP_EACH
9655                  || k1->op_type == OP_AEACH)
9656             {
9657                 warnop = ((k1->op_type == OP_NULL)
9658                           ? (OPCODE)k1->op_targ : k1->op_type);
9659             }
9660             break;
9661         }
9662         if (warnop) {
9663             const line_t oldline = CopLINE(PL_curcop);
9664             /* This ensures that warnings are reported at the first line
9665                of the construction, not the last.  */
9666             CopLINE_set(PL_curcop, PL_parser->copline);
9667             Perl_warner(aTHX_ packWARN(WARN_MISC),
9668                  "Value of %s%s can be \"0\"; test with defined()",
9669                  PL_op_desc[warnop],
9670                  ((warnop == OP_READLINE || warnop == OP_GLOB)
9671                   ? " construct" : "() operator"));
9672             CopLINE_set(PL_curcop, oldline);
9673         }
9674     }
9675
9676     /* optimize AND and OR ops that have NOTs as children */
9677     if (first->op_type == OP_NOT
9678         && (first->op_flags & OPf_KIDS)
9679         && ((first->op_flags & OPf_SPECIAL) /* unless ($x) { } */
9680             || (other->op_type == OP_NOT))  /* if (!$x && !$y) { } */
9681         ) {
9682         if (type == OP_AND || type == OP_OR) {
9683             if (type == OP_AND)
9684                 type = OP_OR;
9685             else
9686                 type = OP_AND;
9687             op_null(first);
9688             if (other->op_type == OP_NOT) { /* !a AND|OR !b => !(a OR|AND b) */
9689                 op_null(other);
9690                 prepend_not = 1; /* prepend a NOT op later */
9691             }
9692         }
9693     }
9694
9695     logop = alloc_LOGOP(type, first, LINKLIST(other));
9696     logop->op_flags |= (U8)flags;
9697     logop->op_private = (U8)(1 | (flags >> 8));
9698
9699     /* establish postfix order */
9700     logop->op_next = LINKLIST(first);
9701     first->op_next = (OP*)logop;
9702     assert(!OpHAS_SIBLING(first));
9703     op_sibling_splice((OP*)logop, first, 0, other);
9704
9705     CHECKOP(type,logop);
9706
9707     o = newUNOP(prepend_not ? OP_NOT : OP_NULL,
9708                 PL_opargs[type] & OA_RETSCALAR ? OPf_WANT_SCALAR : 0,
9709                 (OP*)logop);
9710     other->op_next = o;
9711
9712     return o;
9713 }
9714
9715 /*
9716 =for apidoc newCONDOP
9717
9718 Constructs, checks, and returns a conditional-expression (C<cond_expr>)
9719 op.  C<flags> gives the eight bits of C<op_flags>, except that C<OPf_KIDS>
9720 will be set automatically, and, shifted up eight bits, the eight bits of
9721 C<op_private>, except that the bit with value 1 is automatically set.
9722 C<first> supplies the expression selecting between the two branches,
9723 and C<trueop> and C<falseop> supply the branches; they are consumed by
9724 this function and become part of the constructed op tree.
9725
9726 =cut
9727 */
9728
9729 OP *
9730 Perl_newCONDOP(pTHX_ I32 flags, OP *first, OP *trueop, OP *falseop)
9731 {
9732     LOGOP *logop;
9733     OP *start;
9734     OP *o;
9735     OP *cstop;
9736
9737     PERL_ARGS_ASSERT_NEWCONDOP;
9738
9739     if (!falseop)
9740         return newLOGOP(OP_AND, 0, first, trueop);
9741     if (!trueop)
9742         return newLOGOP(OP_OR, 0, first, falseop);
9743
9744     scalarboolean(first);
9745     if ((cstop = search_const(first))) {
9746         /* Left or right arm of the conditional?  */
9747         const bool left = SvTRUE(((SVOP*)cstop)->op_sv);
9748         OP *live = left ? trueop : falseop;
9749         OP *const dead = left ? falseop : trueop;
9750         if (cstop->op_private & OPpCONST_BARE &&
9751             cstop->op_private & OPpCONST_STRICT) {
9752             no_bareword_allowed(cstop);
9753         }
9754         op_free(first);
9755         op_free(dead);
9756         if (live->op_type == OP_LEAVE)
9757             live = newUNOP(OP_NULL, OPf_SPECIAL, live);
9758         else if (live->op_type == OP_MATCH || live->op_type == OP_SUBST
9759               || live->op_type == OP_TRANS || live->op_type == OP_TRANSR)
9760             /* Mark the op as being unbindable with =~ */
9761             live->op_flags |= OPf_SPECIAL;
9762         live->op_folded = 1;
9763         return live;
9764     }
9765     logop = alloc_LOGOP(OP_COND_EXPR, first, LINKLIST(trueop));
9766     logop->op_flags |= (U8)flags;
9767     logop->op_private = (U8)(1 | (flags >> 8));
9768     logop->op_next = LINKLIST(falseop);
9769
9770     CHECKOP(OP_COND_EXPR, /* that's logop->op_type */
9771             logop);
9772
9773     /* establish postfix order */
9774     start = LINKLIST(first);
9775     first->op_next = (OP*)logop;
9776
9777     /* make first, trueop, falseop siblings */
9778     op_sibling_splice((OP*)logop, first,  0, trueop);
9779     op_sibling_splice((OP*)logop, trueop, 0, falseop);
9780
9781     o = newUNOP(OP_NULL, 0, (OP*)logop);
9782
9783     trueop->op_next = falseop->op_next = o;
9784
9785     o->op_next = start;
9786     return o;
9787 }
9788
9789 /*
9790 =for apidoc newRANGE
9791
9792 Constructs and returns a C<range> op, with subordinate C<flip> and
9793 C<flop> ops.  C<flags> gives the eight bits of C<op_flags> for the
9794 C<flip> op and, shifted up eight bits, the eight bits of C<op_private>
9795 for both the C<flip> and C<range> ops, except that the bit with value
9796 1 is automatically set.  C<left> and C<right> supply the expressions
9797 controlling the endpoints of the range; they are consumed by this function
9798 and become part of the constructed op tree.
9799
9800 =cut
9801 */
9802
9803 OP *
9804 Perl_newRANGE(pTHX_ I32 flags, OP *left, OP *right)
9805 {
9806     LOGOP *range;
9807     OP *flip;
9808     OP *flop;
9809     OP *leftstart;
9810     OP *o;
9811
9812     PERL_ARGS_ASSERT_NEWRANGE;
9813
9814     range = alloc_LOGOP(OP_RANGE, left, LINKLIST(right));
9815     range->op_flags = OPf_KIDS;
9816     leftstart = LINKLIST(left);
9817     range->op_private = (U8)(1 | (flags >> 8));
9818
9819     /* make left and right siblings */
9820     op_sibling_splice((OP*)range, left, 0, right);
9821
9822     range->op_next = (OP*)range;
9823     flip = newUNOP(OP_FLIP, flags, (OP*)range);
9824     flop = newUNOP(OP_FLOP, 0, flip);
9825     o = newUNOP(OP_NULL, 0, flop);
9826     LINKLIST(flop);
9827     range->op_next = leftstart;
9828
9829     left->op_next = flip;
9830     right->op_next = flop;
9831
9832     range->op_targ =
9833         pad_add_name_pvn("$", 1, padadd_NO_DUP_CHECK|padadd_STATE, 0, 0);
9834     sv_upgrade(PAD_SV(range->op_targ), SVt_PVNV);
9835     flip->op_targ =
9836         pad_add_name_pvn("$", 1, padadd_NO_DUP_CHECK|padadd_STATE, 0, 0);;
9837     sv_upgrade(PAD_SV(flip->op_targ), SVt_PVNV);
9838     SvPADTMP_on(PAD_SV(flip->op_targ));
9839
9840     flip->op_private =  left->op_type == OP_CONST ? OPpFLIP_LINENUM : 0;
9841     flop->op_private = right->op_type == OP_CONST ? OPpFLIP_LINENUM : 0;
9842
9843     /* check barewords before they might be optimized aways */
9844     if (flip->op_private && cSVOPx(left)->op_private & OPpCONST_STRICT)
9845         no_bareword_allowed(left);
9846     if (flop->op_private && cSVOPx(right)->op_private & OPpCONST_STRICT)
9847         no_bareword_allowed(right);
9848
9849     flip->op_next = o;
9850     if (!flip->op_private || !flop->op_private)
9851         LINKLIST(o);            /* blow off optimizer unless constant */
9852
9853     return o;
9854 }
9855
9856 /*
9857 =for apidoc newLOOPOP
9858
9859 Constructs, checks, and returns an op tree expressing a loop.  This is
9860 only a loop in the control flow through the op tree; it does not have
9861 the heavyweight loop structure that allows exiting the loop by C<last>
9862 and suchlike.  C<flags> gives the eight bits of C<op_flags> for the
9863 top-level op, except that some bits will be set automatically as required.
9864 C<expr> supplies the expression controlling loop iteration, and C<block>
9865 supplies the body of the loop; they are consumed by this function and
9866 become part of the constructed op tree.  C<debuggable> is currently
9867 unused and should always be 1.
9868
9869 =cut
9870 */
9871
9872 OP *
9873 Perl_newLOOPOP(pTHX_ I32 flags, I32 debuggable, OP *expr, OP *block)
9874 {
9875     OP* listop;
9876     OP* o;
9877     const bool once = block && block->op_flags & OPf_SPECIAL &&
9878                       block->op_type == OP_NULL;
9879
9880     PERL_UNUSED_ARG(debuggable);
9881
9882     if (expr) {
9883         if (once && (
9884               (expr->op_type == OP_CONST && !SvTRUE(((SVOP*)expr)->op_sv))
9885            || (  expr->op_type == OP_NOT
9886               && cUNOPx(expr)->op_first->op_type == OP_CONST
9887               && SvTRUE(cSVOPx_sv(cUNOPx(expr)->op_first))
9888               )
9889            ))
9890             /* Return the block now, so that S_new_logop does not try to
9891                fold it away. */
9892         {
9893             op_free(expr);
9894             return block;       /* do {} while 0 does once */
9895         }
9896
9897         if (expr->op_type == OP_READLINE
9898             || expr->op_type == OP_READDIR
9899             || expr->op_type == OP_GLOB
9900             || expr->op_type == OP_EACH || expr->op_type == OP_AEACH
9901             || (expr->op_type == OP_NULL && expr->op_targ == OP_GLOB)) {
9902             expr = newUNOP(OP_DEFINED, 0,
9903                 newASSIGNOP(0, newDEFSVOP(), 0, expr) );
9904         } else if (expr->op_flags & OPf_KIDS) {
9905             const OP * const k1 = ((UNOP*)expr)->op_first;
9906             const OP * const k2 = k1 ? OpSIBLING(k1) : NULL;
9907             switch (expr->op_type) {
9908               case OP_NULL:
9909                 if (k2 && (k2->op_type == OP_READLINE || k2->op_type == OP_READDIR)
9910                       && (k2->op_flags & OPf_STACKED)
9911                       && ((k1->op_flags & OPf_WANT) == OPf_WANT_SCALAR))
9912                     expr = newUNOP(OP_DEFINED, 0, expr);
9913                 break;
9914
9915               case OP_SASSIGN:
9916                 if (k1 && (k1->op_type == OP_READDIR
9917                       || k1->op_type == OP_GLOB
9918                       || (k1->op_type == OP_NULL && k1->op_targ == OP_GLOB)
9919                      || k1->op_type == OP_EACH
9920                      || k1->op_type == OP_AEACH))
9921                     expr = newUNOP(OP_DEFINED, 0, expr);
9922                 break;
9923             }
9924         }
9925     }
9926
9927     /* if block is null, the next op_append_elem() would put UNSTACK, a scalar
9928      * op, in listop. This is wrong. [perl #27024] */
9929     if (!block)
9930         block = newOP(OP_NULL, 0);
9931     listop = op_append_elem(OP_LINESEQ, block, newOP(OP_UNSTACK, 0));
9932     o = new_logop(OP_AND, 0, &expr, &listop);
9933
9934     if (once) {
9935         ASSUME(listop);
9936     }
9937
9938     if (listop)
9939         ((LISTOP*)listop)->op_last->op_next = LINKLIST(o);
9940
9941     if (once && o != listop)
9942     {
9943         assert(cUNOPo->op_first->op_type == OP_AND
9944             || cUNOPo->op_first->op_type == OP_OR);
9945         o->op_next = ((LOGOP*)cUNOPo->op_first)->op_other;
9946     }
9947
9948     if (o == listop)
9949         o = newUNOP(OP_NULL, 0, o);     /* or do {} while 1 loses outer block */
9950
9951     o->op_flags |= flags;
9952     o = op_scope(o);
9953     o->op_flags |= OPf_SPECIAL; /* suppress cx_popblock() curpm restoration*/
9954     return o;
9955 }
9956
9957 /*
9958 =for apidoc newWHILEOP
9959
9960 Constructs, checks, and returns an op tree expressing a C<while> loop.
9961 This is a heavyweight loop, with structure that allows exiting the loop
9962 by C<last> and suchlike.
9963
9964 C<loop> is an optional preconstructed C<enterloop> op to use in the
9965 loop; if it is null then a suitable op will be constructed automatically.
9966 C<expr> supplies the loop's controlling expression.  C<block> supplies the
9967 main body of the loop, and C<cont> optionally supplies a C<continue> block
9968 that operates as a second half of the body.  All of these optree inputs
9969 are consumed by this function and become part of the constructed op tree.
9970
9971 C<flags> gives the eight bits of C<op_flags> for the C<leaveloop>
9972 op and, shifted up eight bits, the eight bits of C<op_private> for
9973 the C<leaveloop> op, except that (in both cases) some bits will be set
9974 automatically.  C<debuggable> is currently unused and should always be 1.
9975 C<has_my> can be supplied as true to force the
9976 loop body to be enclosed in its own scope.
9977
9978 =cut
9979 */
9980
9981 OP *
9982 Perl_newWHILEOP(pTHX_ I32 flags, I32 debuggable, LOOP *loop,
9983         OP *expr, OP *block, OP *cont, I32 has_my)
9984 {
9985     OP *redo;
9986     OP *next = NULL;
9987     OP *listop;
9988     OP *o;
9989     U8 loopflags = 0;
9990
9991     PERL_UNUSED_ARG(debuggable);
9992
9993     if (expr) {
9994         if (expr->op_type == OP_READLINE
9995          || expr->op_type == OP_READDIR
9996          || expr->op_type == OP_GLOB
9997          || expr->op_type == OP_EACH || expr->op_type == OP_AEACH
9998                      || (expr->op_type == OP_NULL && expr->op_targ == OP_GLOB)) {
9999             expr = newUNOP(OP_DEFINED, 0,
10000                 newASSIGNOP(0, newDEFSVOP(), 0, expr) );
10001         } else if (expr->op_flags & OPf_KIDS) {
10002             const OP * const k1 = ((UNOP*)expr)->op_first;
10003             const OP * const k2 = (k1) ? OpSIBLING(k1) : NULL;
10004             switch (expr->op_type) {
10005               case OP_NULL:
10006                 if (k2 && (k2->op_type == OP_READLINE || k2->op_type == OP_READDIR)
10007                       && (k2->op_flags & OPf_STACKED)
10008                       && ((k1->op_flags & OPf_WANT) == OPf_WANT_SCALAR))
10009                     expr = newUNOP(OP_DEFINED, 0, expr);
10010                 break;
10011
10012               case OP_SASSIGN:
10013                 if (k1 && (k1->op_type == OP_READDIR
10014                       || k1->op_type == OP_GLOB
10015                       || (k1->op_type == OP_NULL && k1->op_targ == OP_GLOB)
10016                      || k1->op_type == OP_EACH
10017                      || k1->op_type == OP_AEACH))
10018                     expr = newUNOP(OP_DEFINED, 0, expr);
10019                 break;
10020             }
10021         }
10022     }
10023
10024     if (!block)
10025         block = newOP(OP_NULL, 0);
10026     else if (cont || has_my) {
10027         block = op_scope(block);
10028     }
10029
10030     if (cont) {
10031         next = LINKLIST(cont);
10032     }
10033     if (expr) {
10034         OP * const unstack = newOP(OP_UNSTACK, 0);
10035         if (!next)
10036             next = unstack;
10037         cont = op_append_elem(OP_LINESEQ, cont, unstack);
10038     }
10039
10040     assert(block);
10041     listop = op_append_list(OP_LINESEQ, block, cont);
10042     assert(listop);
10043     redo = LINKLIST(listop);
10044
10045     if (expr) {
10046         scalar(listop);
10047         o = new_logop(OP_AND, 0, &expr, &listop);
10048         if (o == expr && o->op_type == OP_CONST && !SvTRUE(cSVOPo->op_sv)) {
10049             op_free((OP*)loop);
10050             return expr;                /* listop already freed by new_logop */
10051         }
10052         if (listop)
10053             ((LISTOP*)listop)->op_last->op_next =
10054                 (o == listop ? redo : LINKLIST(o));
10055     }
10056     else
10057         o = listop;
10058
10059     if (!loop) {
10060         NewOp(1101,loop,1,LOOP);
10061         OpTYPE_set(loop, OP_ENTERLOOP);
10062         loop->op_private = 0;
10063         loop->op_next = (OP*)loop;
10064     }
10065
10066     o = newBINOP(OP_LEAVELOOP, 0, (OP*)loop, o);
10067
10068     loop->op_redoop = redo;
10069     loop->op_lastop = o;
10070     o->op_private |= loopflags;
10071
10072     if (next)
10073         loop->op_nextop = next;
10074     else
10075         loop->op_nextop = o;
10076
10077     o->op_flags |= flags;
10078     o->op_private |= (flags >> 8);
10079     return o;
10080 }
10081
10082 /*
10083 =for apidoc newFOROP
10084
10085 Constructs, checks, and returns an op tree expressing a C<foreach>
10086 loop (iteration through a list of values).  This is a heavyweight loop,
10087 with structure that allows exiting the loop by C<last> and suchlike.
10088
10089 C<sv> optionally supplies the variable that will be aliased to each
10090 item in turn; if null, it defaults to C<$_>.
10091 C<expr> supplies the list of values to iterate over.  C<block> supplies
10092 the main body of the loop, and C<cont> optionally supplies a C<continue>
10093 block that operates as a second half of the body.  All of these optree
10094 inputs are consumed by this function and become part of the constructed
10095 op tree.
10096
10097 C<flags> gives the eight bits of C<op_flags> for the C<leaveloop>
10098 op and, shifted up eight bits, the eight bits of C<op_private> for
10099 the C<leaveloop> op, except that (in both cases) some bits will be set
10100 automatically.
10101
10102 =cut
10103 */
10104
10105 OP *
10106 Perl_newFOROP(pTHX_ I32 flags, OP *sv, OP *expr, OP *block, OP *cont)
10107 {
10108     LOOP *loop;
10109     OP *wop;
10110     PADOFFSET padoff = 0;
10111     I32 iterflags = 0;
10112     I32 iterpflags = 0;
10113
10114     PERL_ARGS_ASSERT_NEWFOROP;
10115
10116     if (sv) {
10117         if (sv->op_type == OP_RV2SV) {  /* symbol table variable */
10118             iterpflags = sv->op_private & OPpOUR_INTRO; /* for our $x () */
10119             OpTYPE_set(sv, OP_RV2GV);
10120
10121             /* The op_type check is needed to prevent a possible segfault
10122              * if the loop variable is undeclared and 'strict vars' is in
10123              * effect. This is illegal but is nonetheless parsed, so we
10124              * may reach this point with an OP_CONST where we're expecting
10125              * an OP_GV.
10126              */
10127             if (cUNOPx(sv)->op_first->op_type == OP_GV
10128              && cGVOPx_gv(cUNOPx(sv)->op_first) == PL_defgv)
10129                 iterpflags |= OPpITER_DEF;
10130         }
10131         else if (sv->op_type == OP_PADSV) { /* private variable */
10132             iterpflags = sv->op_private & OPpLVAL_INTRO; /* for my $x () */
10133             padoff = sv->op_targ;
10134             sv->op_targ = 0;
10135             op_free(sv);
10136             sv = NULL;
10137             PAD_COMPNAME_GEN_set(padoff, PERL_INT_MAX);
10138         }
10139         else if (sv->op_type == OP_NULL && sv->op_targ == OP_SREFGEN)
10140             NOOP;
10141         else
10142             Perl_croak(aTHX_ "Can't use %s for loop variable", PL_op_desc[sv->op_type]);
10143         if (padoff) {
10144             PADNAME * const pn = PAD_COMPNAME(padoff);
10145             const char * const name = PadnamePV(pn);
10146
10147             if (PadnameLEN(pn) == 2 && name[0] == '$' && name[1] == '_')
10148                 iterpflags |= OPpITER_DEF;
10149         }
10150     }
10151     else {
10152         sv = newGVOP(OP_GV, 0, PL_defgv);
10153         iterpflags |= OPpITER_DEF;
10154     }
10155
10156     if (expr->op_type == OP_RV2AV || expr->op_type == OP_PADAV) {
10157         expr = op_lvalue(force_list(scalar(ref(expr, OP_ITER)), 1), OP_GREPSTART);
10158         iterflags |= OPf_STACKED;
10159     }
10160     else if (expr->op_type == OP_NULL &&
10161              (expr->op_flags & OPf_KIDS) &&
10162              ((BINOP*)expr)->op_first->op_type == OP_FLOP)
10163     {
10164         /* Basically turn for($x..$y) into the same as for($x,$y), but we
10165          * set the STACKED flag to indicate that these values are to be
10166          * treated as min/max values by 'pp_enteriter'.
10167          */
10168         const UNOP* const flip = (UNOP*)((UNOP*)((BINOP*)expr)->op_first)->op_first;
10169         LOGOP* const range = (LOGOP*) flip->op_first;
10170         OP* const left  = range->op_first;
10171         OP* const right = OpSIBLING(left);
10172         LISTOP* listop;
10173
10174         range->op_flags &= ~OPf_KIDS;
10175         /* detach range's children */
10176         op_sibling_splice((OP*)range, NULL, -1, NULL);
10177
10178         listop = (LISTOP*)newLISTOP(OP_LIST, 0, left, right);
10179         listop->op_first->op_next = range->op_next;
10180         left->op_next = range->op_other;
10181         right->op_next = (OP*)listop;
10182         listop->op_next = listop->op_first;
10183
10184         op_free(expr);
10185         expr = (OP*)(listop);
10186         op_null(expr);
10187         iterflags |= OPf_STACKED;
10188     }
10189     else {
10190         expr = op_lvalue(force_list(expr, 1), OP_GREPSTART);
10191     }
10192
10193     loop = (LOOP*)op_convert_list(OP_ENTERITER, iterflags,
10194                                   op_append_elem(OP_LIST, list(expr),
10195                                                  scalar(sv)));
10196     assert(!loop->op_next);
10197     /* for my  $x () sets OPpLVAL_INTRO;
10198      * for our $x () sets OPpOUR_INTRO */
10199     loop->op_private = (U8)iterpflags;
10200
10201     /* upgrade loop from a LISTOP to a LOOPOP;
10202      * keep it in-place if there's space */
10203     if (loop->op_slabbed
10204         &&    OpSLOT(loop)->opslot_size
10205             < SIZE_TO_PSIZE(sizeof(LOOP) + OPSLOT_HEADER))
10206     {
10207         /* no space; allocate new op */
10208         LOOP *tmp;
10209         NewOp(1234,tmp,1,LOOP);
10210         Copy(loop,tmp,1,LISTOP);
10211         assert(loop->op_last->op_sibparent == (OP*)loop);
10212         OpLASTSIB_set(loop->op_last, (OP*)tmp); /*point back to new parent */
10213         S_op_destroy(aTHX_ (OP*)loop);
10214         loop = tmp;
10215     }
10216     else if (!loop->op_slabbed)
10217     {
10218         /* loop was malloc()ed */
10219         loop = (LOOP*)PerlMemShared_realloc(loop, sizeof(LOOP));
10220         OpLASTSIB_set(loop->op_last, (OP*)loop);
10221     }
10222     loop->op_targ = padoff;
10223     wop = newWHILEOP(flags, 1, loop, newOP(OP_ITER, 0), block, cont, 0);
10224     return wop;
10225 }
10226
10227 /*
10228 =for apidoc newLOOPEX
10229
10230 Constructs, checks, and returns a loop-exiting op (such as C<goto>
10231 or C<last>).  C<type> is the opcode.  C<label> supplies the parameter
10232 determining the target of the op; it is consumed by this function and
10233 becomes part of the constructed op tree.
10234
10235 =cut
10236 */
10237
10238 OP*
10239 Perl_newLOOPEX(pTHX_ I32 type, OP *label)
10240 {
10241     OP *o = NULL;
10242
10243     PERL_ARGS_ASSERT_NEWLOOPEX;
10244
10245     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_LOOPEXOP
10246         || type == OP_CUSTOM);
10247
10248     if (type != OP_GOTO) {
10249         /* "last()" means "last" */
10250         if (label->op_type == OP_STUB && (label->op_flags & OPf_PARENS)) {
10251             o = newOP(type, OPf_SPECIAL);
10252         }
10253     }
10254     else {
10255         /* Check whether it's going to be a goto &function */
10256         if (label->op_type == OP_ENTERSUB
10257                 && !(label->op_flags & OPf_STACKED))
10258             label = newUNOP(OP_REFGEN, 0, op_lvalue(label, OP_REFGEN));
10259     }
10260
10261     /* Check for a constant argument */
10262     if (label->op_type == OP_CONST) {
10263             SV * const sv = ((SVOP *)label)->op_sv;
10264             STRLEN l;
10265             const char *s = SvPV_const(sv,l);
10266             if (l == strlen(s)) {
10267                 o = newPVOP(type,
10268                             SvUTF8(((SVOP*)label)->op_sv),
10269                             savesharedpv(
10270                                 SvPV_nolen_const(((SVOP*)label)->op_sv)));
10271             }
10272     }
10273
10274     /* If we have already created an op, we do not need the label. */
10275     if (o)
10276                 op_free(label);
10277     else o = newUNOP(type, OPf_STACKED, label);
10278
10279     PL_hints |= HINT_BLOCK_SCOPE;
10280     return o;
10281 }
10282
10283 /* if the condition is a literal array or hash
10284    (or @{ ... } etc), make a reference to it.
10285  */
10286 STATIC OP *
10287 S_ref_array_or_hash(pTHX_ OP *cond)
10288 {
10289     if (cond
10290     && (cond->op_type == OP_RV2AV
10291     ||  cond->op_type == OP_PADAV
10292     ||  cond->op_type == OP_RV2HV
10293     ||  cond->op_type == OP_PADHV))
10294
10295         return newUNOP(OP_REFGEN, 0, op_lvalue(cond, OP_REFGEN));
10296
10297     else if(cond
10298     && (cond->op_type == OP_ASLICE
10299     ||  cond->op_type == OP_KVASLICE
10300     ||  cond->op_type == OP_HSLICE
10301     ||  cond->op_type == OP_KVHSLICE)) {
10302
10303         /* anonlist now needs a list from this op, was previously used in
10304          * scalar context */
10305         cond->op_flags &= ~(OPf_WANT_SCALAR | OPf_REF);
10306         cond->op_flags |= OPf_WANT_LIST;
10307
10308         return newANONLIST(op_lvalue(cond, OP_ANONLIST));
10309     }
10310
10311     else
10312         return cond;
10313 }
10314
10315 /* These construct the optree fragments representing given()
10316    and when() blocks.
10317
10318    entergiven and enterwhen are LOGOPs; the op_other pointer
10319    points up to the associated leave op. We need this so we
10320    can put it in the context and make break/continue work.
10321    (Also, of course, pp_enterwhen will jump straight to
10322    op_other if the match fails.)
10323  */
10324
10325 STATIC OP *
10326 S_newGIVWHENOP(pTHX_ OP *cond, OP *block,
10327                    I32 enter_opcode, I32 leave_opcode,
10328                    PADOFFSET entertarg)
10329 {
10330     LOGOP *enterop;
10331     OP *o;
10332
10333     PERL_ARGS_ASSERT_NEWGIVWHENOP;
10334     PERL_UNUSED_ARG(entertarg); /* used to indicate targ of lexical $_ */
10335
10336     enterop = alloc_LOGOP(enter_opcode, block, NULL);
10337     enterop->op_targ = 0;
10338     enterop->op_private = 0;
10339
10340     o = newUNOP(leave_opcode, 0, (OP *) enterop);
10341
10342     if (cond) {
10343         /* prepend cond if we have one */
10344         op_sibling_splice((OP*)enterop, NULL, 0, scalar(cond));
10345
10346         o->op_next = LINKLIST(cond);
10347         cond->op_next = (OP *) enterop;
10348     }
10349     else {
10350         /* This is a default {} block */
10351         enterop->op_flags |= OPf_SPECIAL;
10352         o      ->op_flags |= OPf_SPECIAL;
10353
10354         o->op_next = (OP *) enterop;
10355     }
10356
10357     CHECKOP(enter_opcode, enterop); /* Currently does nothing, since
10358                                        entergiven and enterwhen both
10359                                        use ck_null() */
10360
10361     enterop->op_next = LINKLIST(block);
10362     block->op_next = enterop->op_other = o;
10363
10364     return o;
10365 }
10366
10367
10368 /* For the purposes of 'when(implied_smartmatch)'
10369  *              versus 'when(boolean_expression)',
10370  * does this look like a boolean operation? For these purposes
10371    a boolean operation is:
10372      - a subroutine call [*]
10373      - a logical connective
10374      - a comparison operator
10375      - a filetest operator, with the exception of -s -M -A -C
10376      - defined(), exists() or eof()
10377      - /$re/ or $foo =~ /$re/
10378
10379    [*] possibly surprising
10380  */
10381 STATIC bool
10382 S_looks_like_bool(pTHX_ const OP *o)
10383 {
10384     PERL_ARGS_ASSERT_LOOKS_LIKE_BOOL;
10385
10386     switch(o->op_type) {
10387         case OP_OR:
10388         case OP_DOR:
10389             return looks_like_bool(cLOGOPo->op_first);
10390
10391         case OP_AND:
10392         {
10393             OP* sibl = OpSIBLING(cLOGOPo->op_first);
10394             ASSUME(sibl);
10395             return (
10396                 looks_like_bool(cLOGOPo->op_first)
10397              && looks_like_bool(sibl));
10398         }
10399
10400         case OP_NULL:
10401         case OP_SCALAR:
10402             return (
10403                 o->op_flags & OPf_KIDS
10404             && looks_like_bool(cUNOPo->op_first));
10405
10406         case OP_ENTERSUB:
10407
10408         case OP_NOT:    case OP_XOR:
10409
10410         case OP_EQ:     case OP_NE:     case OP_LT:
10411         case OP_GT:     case OP_LE:     case OP_GE:
10412
10413         case OP_I_EQ:   case OP_I_NE:   case OP_I_LT:
10414         case OP_I_GT:   case OP_I_LE:   case OP_I_GE:
10415
10416         case OP_SEQ:    case OP_SNE:    case OP_SLT:
10417         case OP_SGT:    case OP_SLE:    case OP_SGE:
10418
10419         case OP_SMARTMATCH:
10420
10421         case OP_FTRREAD:  case OP_FTRWRITE: case OP_FTREXEC:
10422         case OP_FTEREAD:  case OP_FTEWRITE: case OP_FTEEXEC:
10423         case OP_FTIS:     case OP_FTEOWNED: case OP_FTROWNED:
10424         case OP_FTZERO:   case OP_FTSOCK:   case OP_FTCHR:
10425         case OP_FTBLK:    case OP_FTFILE:   case OP_FTDIR:
10426         case OP_FTPIPE:   case OP_FTLINK:   case OP_FTSUID:
10427         case OP_FTSGID:   case OP_FTSVTX:   case OP_FTTTY:
10428         case OP_FTTEXT:   case OP_FTBINARY:
10429
10430         case OP_DEFINED: case OP_EXISTS:
10431         case OP_MATCH:   case OP_EOF:
10432
10433         case OP_FLOP:
10434
10435             return TRUE;
10436
10437         case OP_INDEX:
10438         case OP_RINDEX:
10439             /* optimised-away (index() != -1) or similar comparison */
10440             if (o->op_private & OPpTRUEBOOL)
10441                 return TRUE;
10442             return FALSE;
10443
10444         case OP_CONST:
10445             /* Detect comparisons that have been optimized away */
10446             if (cSVOPo->op_sv == &PL_sv_yes
10447             ||  cSVOPo->op_sv == &PL_sv_no)
10448
10449                 return TRUE;
10450             else
10451                 return FALSE;
10452         /* FALLTHROUGH */
10453         default:
10454             return FALSE;
10455     }
10456 }
10457
10458
10459 /*
10460 =for apidoc newGIVENOP
10461
10462 Constructs, checks, and returns an op tree expressing a C<given> block.
10463 C<cond> supplies the expression to whose value C<$_> will be locally
10464 aliased, and C<block> supplies the body of the C<given> construct; they
10465 are consumed by this function and become part of the constructed op tree.
10466 C<defsv_off> must be zero (it used to identity the pad slot of lexical $_).
10467
10468 =cut
10469 */
10470
10471 OP *
10472 Perl_newGIVENOP(pTHX_ OP *cond, OP *block, PADOFFSET defsv_off)
10473 {
10474     PERL_ARGS_ASSERT_NEWGIVENOP;
10475     PERL_UNUSED_ARG(defsv_off);
10476
10477     assert(!defsv_off);
10478     return newGIVWHENOP(
10479         ref_array_or_hash(cond),
10480         block,
10481         OP_ENTERGIVEN, OP_LEAVEGIVEN,
10482         0);
10483 }
10484
10485 /*
10486 =for apidoc newWHENOP
10487
10488 Constructs, checks, and returns an op tree expressing a C<when> block.
10489 C<cond> supplies the test expression, and C<block> supplies the block
10490 that will be executed if the test evaluates to true; they are consumed
10491 by this function and become part of the constructed op tree.  C<cond>
10492 will be interpreted DWIMically, often as a comparison against C<$_>,
10493 and may be null to generate a C<default> block.
10494
10495 =cut
10496 */
10497
10498 OP *
10499 Perl_newWHENOP(pTHX_ OP *cond, OP *block)
10500 {
10501     const bool cond_llb = (!cond || looks_like_bool(cond));
10502     OP *cond_op;
10503
10504     PERL_ARGS_ASSERT_NEWWHENOP;
10505
10506     if (cond_llb)
10507         cond_op = cond;
10508     else {
10509         cond_op = newBINOP(OP_SMARTMATCH, OPf_SPECIAL,
10510                 newDEFSVOP(),
10511                 scalar(ref_array_or_hash(cond)));
10512     }
10513
10514     return newGIVWHENOP(cond_op, block, OP_ENTERWHEN, OP_LEAVEWHEN, 0);
10515 }
10516
10517 /* must not conflict with SVf_UTF8 */
10518 #define CV_CKPROTO_CURSTASH     0x1
10519
10520 void
10521 Perl_cv_ckproto_len_flags(pTHX_ const CV *cv, const GV *gv, const char *p,
10522                     const STRLEN len, const U32 flags)
10523 {
10524     SV *name = NULL, *msg;
10525     const char * cvp = SvROK(cv)
10526                         ? SvTYPE(SvRV_const(cv)) == SVt_PVCV
10527                            ? (cv = (const CV *)SvRV_const(cv), CvPROTO(cv))
10528                            : ""
10529                         : CvPROTO(cv);
10530     STRLEN clen = CvPROTOLEN(cv), plen = len;
10531
10532     PERL_ARGS_ASSERT_CV_CKPROTO_LEN_FLAGS;
10533
10534     if (p == NULL && cvp == NULL)
10535         return;
10536
10537     if (!ckWARN_d(WARN_PROTOTYPE))
10538         return;
10539
10540     if (p && cvp) {
10541         p = S_strip_spaces(aTHX_ p, &plen);
10542         cvp = S_strip_spaces(aTHX_ cvp, &clen);
10543         if ((flags & SVf_UTF8) == SvUTF8(cv)) {
10544             if (plen == clen && memEQ(cvp, p, plen))
10545                 return;
10546         } else {
10547             if (flags & SVf_UTF8) {
10548                 if (bytes_cmp_utf8((const U8 *)cvp, clen, (const U8 *)p, plen) == 0)
10549                     return;
10550             }
10551             else {
10552                 if (bytes_cmp_utf8((const U8 *)p, plen, (const U8 *)cvp, clen) == 0)
10553                     return;
10554             }
10555         }
10556     }
10557
10558     msg = sv_newmortal();
10559
10560     if (gv)
10561     {
10562         if (isGV(gv))
10563             gv_efullname3(name = sv_newmortal(), gv, NULL);
10564         else if (SvPOK(gv) && *SvPVX((SV *)gv) == '&')
10565             name = newSVpvn_flags(SvPVX((SV *)gv)+1, SvCUR(gv)-1, SvUTF8(gv)|SVs_TEMP);
10566         else if (flags & CV_CKPROTO_CURSTASH || SvROK(gv)) {
10567             name = sv_2mortal(newSVhek(HvNAME_HEK(PL_curstash)));
10568             sv_catpvs(name, "::");
10569             if (SvROK(gv)) {
10570                 assert (SvTYPE(SvRV_const(gv)) == SVt_PVCV);
10571                 assert (CvNAMED(SvRV_const(gv)));
10572                 sv_cathek(name, CvNAME_HEK(MUTABLE_CV(SvRV_const(gv))));
10573             }
10574             else sv_catsv(name, (SV *)gv);
10575         }
10576         else name = (SV *)gv;
10577     }
10578     sv_setpvs(msg, "Prototype mismatch:");
10579     if (name)
10580         Perl_sv_catpvf(aTHX_ msg, " sub %" SVf, SVfARG(name));
10581     if (cvp)
10582         Perl_sv_catpvf(aTHX_ msg, " (%" UTF8f ")",
10583             UTF8fARG(SvUTF8(cv),clen,cvp)
10584         );
10585     else
10586         sv_catpvs(msg, ": none");
10587     sv_catpvs(msg, " vs ");
10588     if (p)
10589         Perl_sv_catpvf(aTHX_ msg, "(%" UTF8f ")", UTF8fARG(flags & SVf_UTF8,len,p));
10590     else
10591         sv_catpvs(msg, "none");
10592     Perl_warner(aTHX_ packWARN(WARN_PROTOTYPE), "%" SVf, SVfARG(msg));
10593 }
10594
10595 static void const_sv_xsub(pTHX_ CV* cv);
10596 static void const_av_xsub(pTHX_ CV* cv);
10597
10598 /*
10599
10600 =head1 Optree Manipulation Functions
10601
10602 =for apidoc cv_const_sv
10603
10604 If C<cv> is a constant sub eligible for inlining, returns the constant
10605 value returned by the sub.  Otherwise, returns C<NULL>.
10606
10607 Constant subs can be created with C<newCONSTSUB> or as described in
10608 L<perlsub/"Constant Functions">.
10609
10610 =cut
10611 */
10612 SV *
10613 Perl_cv_const_sv(const CV *const cv)
10614 {
10615     SV *sv;
10616     if (!cv)
10617         return NULL;
10618     if (!(SvTYPE(cv) == SVt_PVCV || SvTYPE(cv) == SVt_PVFM))
10619         return NULL;
10620     sv = CvCONST(cv) ? MUTABLE_SV(CvXSUBANY(cv).any_ptr) : NULL;
10621     if (sv && SvTYPE(sv) == SVt_PVAV) return NULL;
10622     return sv;
10623 }
10624
10625 SV *
10626 Perl_cv_const_sv_or_av(const CV * const cv)
10627 {
10628     if (!cv)
10629         return NULL;
10630     if (SvROK(cv)) return SvRV((SV *)cv);
10631     assert (SvTYPE(cv) == SVt_PVCV || SvTYPE(cv) == SVt_PVFM);
10632     return CvCONST(cv) ? MUTABLE_SV(CvXSUBANY(cv).any_ptr) : NULL;
10633 }
10634
10635 /* op_const_sv:  examine an optree to determine whether it's in-lineable.
10636  * Can be called in 2 ways:
10637  *
10638  * !allow_lex
10639  *      look for a single OP_CONST with attached value: return the value
10640  *
10641  * allow_lex && !CvCONST(cv);
10642  *
10643  *      examine the clone prototype, and if contains only a single
10644  *      OP_CONST, return the value; or if it contains a single PADSV ref-
10645  *      erencing an outer lexical, turn on CvCONST to indicate the CV is
10646  *      a candidate for "constizing" at clone time, and return NULL.
10647  */
10648
10649 static SV *
10650 S_op_const_sv(pTHX_ const OP *o, CV *cv, bool allow_lex)
10651 {
10652     SV *sv = NULL;
10653     bool padsv = FALSE;
10654
10655     assert(o);
10656     assert(cv);
10657
10658     for (; o; o = o->op_next) {
10659         const OPCODE type = o->op_type;
10660
10661         if (type == OP_NEXTSTATE || type == OP_LINESEQ
10662              || type == OP_NULL
10663              || type == OP_PUSHMARK)
10664                 continue;
10665         if (type == OP_DBSTATE)
10666                 continue;
10667         if (type == OP_LEAVESUB)
10668             break;
10669         if (sv)
10670             return NULL;
10671         if (type == OP_CONST && cSVOPo->op_sv)
10672             sv = cSVOPo->op_sv;
10673         else if (type == OP_UNDEF && !o->op_private) {
10674             sv = newSV(0);
10675             SAVEFREESV(sv);
10676         }
10677         else if (allow_lex && type == OP_PADSV) {
10678                 if (PAD_COMPNAME_FLAGS(o->op_targ) & PADNAMEt_OUTER)
10679                 {
10680                     sv = &PL_sv_undef; /* an arbitrary non-null value */
10681                     padsv = TRUE;
10682                 }
10683                 else
10684                     return NULL;
10685         }
10686         else {
10687             return NULL;
10688         }
10689     }
10690     if (padsv) {
10691         CvCONST_on(cv);
10692         return NULL;
10693     }
10694     return sv;
10695 }
10696
10697 static void
10698 S_already_defined(pTHX_ CV *const cv, OP * const block, OP * const o,
10699                         PADNAME * const name, SV ** const const_svp)
10700 {
10701     assert (cv);
10702     assert (o || name);
10703     assert (const_svp);
10704     if (!block) {
10705         if (CvFLAGS(PL_compcv)) {
10706             /* might have had built-in attrs applied */
10707             const bool pureperl = !CvISXSUB(cv) && CvROOT(cv);
10708             if (CvLVALUE(PL_compcv) && ! CvLVALUE(cv) && pureperl
10709              && ckWARN(WARN_MISC))
10710             {
10711                 /* protect against fatal warnings leaking compcv */
10712                 SAVEFREESV(PL_compcv);
10713                 Perl_warner(aTHX_ packWARN(WARN_MISC), "lvalue attribute ignored after the subroutine has been defined");
10714                 SvREFCNT_inc_simple_void_NN(PL_compcv);
10715             }
10716             CvFLAGS(cv) |=
10717                 (CvFLAGS(PL_compcv) & CVf_BUILTIN_ATTRS
10718                   & ~(CVf_LVALUE * pureperl));
10719         }
10720         return;
10721     }
10722
10723     /* redundant check for speed: */
10724     if (CvCONST(cv) || ckWARN(WARN_REDEFINE)) {
10725         const line_t oldline = CopLINE(PL_curcop);
10726         SV *namesv = o
10727             ? cSVOPo->op_sv
10728             : sv_2mortal(newSVpvn_utf8(
10729                 PadnamePV(name)+1,PadnameLEN(name)-1, PadnameUTF8(name)
10730               ));
10731         if (PL_parser && PL_parser->copline != NOLINE)
10732             /* This ensures that warnings are reported at the first
10733                line of a redefinition, not the last.  */
10734             CopLINE_set(PL_curcop, PL_parser->copline);
10735         /* protect against fatal warnings leaking compcv */
10736         SAVEFREESV(PL_compcv);
10737         report_redefined_cv(namesv, cv, const_svp);
10738         SvREFCNT_inc_simple_void_NN(PL_compcv);
10739         CopLINE_set(PL_curcop, oldline);
10740     }
10741     SAVEFREESV(cv);
10742     return;
10743 }
10744
10745 CV *
10746 Perl_newMYSUB(pTHX_ I32 floor, OP *o, OP *proto, OP *attrs, OP *block)
10747 {
10748     CV **spot;
10749     SV **svspot;
10750     const char *ps;
10751     STRLEN ps_len = 0; /* init it to avoid false uninit warning from icc */
10752     U32 ps_utf8 = 0;
10753     CV *cv = NULL;
10754     CV *compcv = PL_compcv;
10755     SV *const_sv;
10756     PADNAME *name;
10757     PADOFFSET pax = o->op_targ;
10758     CV *outcv = CvOUTSIDE(PL_compcv);
10759     CV *clonee = NULL;
10760     HEK *hek = NULL;
10761     bool reusable = FALSE;
10762     OP *start = NULL;
10763 #ifdef PERL_DEBUG_READONLY_OPS
10764     OPSLAB *slab = NULL;
10765 #endif
10766
10767     PERL_ARGS_ASSERT_NEWMYSUB;
10768
10769     PL_hints |= HINT_BLOCK_SCOPE;
10770
10771     /* Find the pad slot for storing the new sub.
10772        We cannot use PL_comppad, as it is the pad owned by the new sub.  We
10773        need to look in CvOUTSIDE and find the pad belonging to the enclos-
10774        ing sub.  And then we need to dig deeper if this is a lexical from
10775        outside, as in:
10776            my sub foo; sub { sub foo { } }
10777      */
10778   redo:
10779     name = PadlistNAMESARRAY(CvPADLIST(outcv))[pax];
10780     if (PadnameOUTER(name) && PARENT_PAD_INDEX(name)) {
10781         pax = PARENT_PAD_INDEX(name);
10782         outcv = CvOUTSIDE(outcv);
10783         assert(outcv);
10784         goto redo;
10785     }
10786     svspot =
10787         &PadARRAY(PadlistARRAY(CvPADLIST(outcv))
10788                         [CvDEPTH(outcv) ? CvDEPTH(outcv) : 1])[pax];
10789     spot = (CV **)svspot;
10790
10791     if (!(PL_parser && PL_parser->error_count))
10792         move_proto_attr(&proto, &attrs, (GV *)PadnameSV(name), 0);
10793
10794     if (proto) {
10795         assert(proto->op_type == OP_CONST);
10796         ps = SvPV_const(((SVOP*)proto)->op_sv, ps_len);
10797         ps_utf8 = SvUTF8(((SVOP*)proto)->op_sv);
10798     }
10799     else
10800         ps = NULL;
10801
10802     if (proto)
10803         SAVEFREEOP(proto);
10804     if (attrs)
10805         SAVEFREEOP(attrs);
10806
10807     if (PL_parser && PL_parser->error_count) {
10808         op_free(block);
10809         SvREFCNT_dec(PL_compcv);
10810         PL_compcv = 0;
10811         goto done;
10812     }
10813
10814     if (CvDEPTH(outcv) && CvCLONE(compcv)) {
10815         cv = *spot;
10816         svspot = (SV **)(spot = &clonee);
10817     }
10818     else if (PadnameIsSTATE(name) || CvDEPTH(outcv))
10819         cv = *spot;
10820     else {
10821         assert (SvTYPE(*spot) == SVt_PVCV);
10822         if (CvNAMED(*spot))
10823             hek = CvNAME_HEK(*spot);
10824         else {
10825             U32 hash;
10826             PERL_HASH(hash, PadnamePV(name)+1, PadnameLEN(name)-1);
10827             CvNAME_HEK_set(*spot, hek =
10828                 share_hek(
10829                     PadnamePV(name)+1,
10830                     (PadnameLEN(name)-1) * (PadnameUTF8(name) ? -1 : 1),
10831                     hash
10832                 )
10833             );
10834             CvLEXICAL_on(*spot);
10835         }
10836         cv = PadnamePROTOCV(name);
10837         svspot = (SV **)(spot = &PadnamePROTOCV(name));
10838     }
10839
10840     if (block) {
10841         /* This makes sub {}; work as expected.  */
10842         if (block->op_type == OP_STUB) {
10843             const line_t l = PL_parser->copline;
10844             op_free(block);
10845             block = newSTATEOP(0, NULL, 0);
10846             PL_parser->copline = l;
10847         }
10848         block = CvLVALUE(compcv)
10849              || (cv && CvLVALUE(cv) && !CvROOT(cv) && !CvXSUB(cv))
10850                    ? newUNOP(OP_LEAVESUBLV, 0,
10851                              op_lvalue(scalarseq(block), OP_LEAVESUBLV))
10852                    : newUNOP(OP_LEAVESUB, 0, scalarseq(block));
10853         start = LINKLIST(block);
10854         block->op_next = 0;
10855         if (ps && !*ps && !attrs && !CvLVALUE(compcv))
10856             const_sv = S_op_const_sv(aTHX_ start, compcv, FALSE);
10857         else
10858             const_sv = NULL;
10859     }
10860     else
10861         const_sv = NULL;
10862
10863     if (cv) {
10864         const bool exists = CvROOT(cv) || CvXSUB(cv);
10865
10866         /* if the subroutine doesn't exist and wasn't pre-declared
10867          * with a prototype, assume it will be AUTOLOADed,
10868          * skipping the prototype check
10869          */
10870         if (exists || SvPOK(cv))
10871             cv_ckproto_len_flags(cv, (GV *)PadnameSV(name), ps, ps_len,
10872                                  ps_utf8);
10873         /* already defined? */
10874         if (exists) {
10875             S_already_defined(aTHX_ cv, block, NULL, name, &const_sv);
10876             if (block)
10877                 cv = NULL;
10878             else {
10879                 if (attrs)
10880                     goto attrs;
10881                 /* just a "sub foo;" when &foo is already defined */
10882                 SAVEFREESV(compcv);
10883                 goto done;
10884             }
10885         }
10886         else if (CvDEPTH(outcv) && CvCLONE(compcv)) {
10887             cv = NULL;
10888             reusable = TRUE;
10889         }
10890     }
10891
10892     if (const_sv) {
10893         SvREFCNT_inc_simple_void_NN(const_sv);
10894         SvFLAGS(const_sv) |= SVs_PADTMP;
10895         if (cv) {
10896             assert(!CvROOT(cv) && !CvCONST(cv));
10897             cv_forget_slab(cv);
10898         }
10899         else {
10900             cv = MUTABLE_CV(newSV_type(SVt_PVCV));
10901             CvFILE_set_from_cop(cv, PL_curcop);
10902             CvSTASH_set(cv, PL_curstash);
10903             *spot = cv;
10904         }
10905         SvPVCLEAR(MUTABLE_SV(cv));  /* prototype is "" */
10906         CvXSUBANY(cv).any_ptr = const_sv;
10907         CvXSUB(cv) = const_sv_xsub;
10908         CvCONST_on(cv);
10909         CvISXSUB_on(cv);
10910         PoisonPADLIST(cv);
10911         CvFLAGS(cv) |= CvMETHOD(compcv);
10912         op_free(block);
10913         SvREFCNT_dec(compcv);
10914         PL_compcv = NULL;
10915         goto setname;
10916     }
10917
10918     /* Checking whether outcv is CvOUTSIDE(compcv) is not sufficient to
10919        determine whether this sub definition is in the same scope as its
10920        declaration.  If this sub definition is inside an inner named pack-
10921        age sub (my sub foo; sub bar { sub foo { ... } }), outcv points to
10922        the package sub.  So check PadnameOUTER(name) too.
10923      */
10924     if (outcv == CvOUTSIDE(compcv) && !PadnameOUTER(name)) {
10925         assert(!CvWEAKOUTSIDE(compcv));
10926         SvREFCNT_dec(CvOUTSIDE(compcv));
10927         CvWEAKOUTSIDE_on(compcv);
10928     }
10929     /* XXX else do we have a circular reference? */
10930
10931     if (cv) {   /* must reuse cv in case stub is referenced elsewhere */
10932         /* transfer PL_compcv to cv */
10933         if (block) {
10934             bool free_file = CvFILE(cv) && CvDYNFILE(cv);
10935             cv_flags_t preserved_flags =
10936                 CvFLAGS(cv) & (CVf_BUILTIN_ATTRS|CVf_NAMED);
10937             PADLIST *const temp_padl = CvPADLIST(cv);
10938             CV *const temp_cv = CvOUTSIDE(cv);
10939             const cv_flags_t other_flags =
10940                 CvFLAGS(cv) & (CVf_SLABBED|CVf_WEAKOUTSIDE);
10941             OP * const cvstart = CvSTART(cv);
10942
10943             SvPOK_off(cv);
10944             CvFLAGS(cv) =
10945                 CvFLAGS(compcv) | preserved_flags;
10946             CvOUTSIDE(cv) = CvOUTSIDE(compcv);
10947             CvOUTSIDE_SEQ(cv) = CvOUTSIDE_SEQ(compcv);
10948             CvPADLIST_set(cv, CvPADLIST(compcv));
10949             CvOUTSIDE(compcv) = temp_cv;
10950             CvPADLIST_set(compcv, temp_padl);
10951             CvSTART(cv) = CvSTART(compcv);
10952             CvSTART(compcv) = cvstart;
10953             CvFLAGS(compcv) &= ~(CVf_SLABBED|CVf_WEAKOUTSIDE);
10954             CvFLAGS(compcv) |= other_flags;
10955
10956             if (free_file) {
10957                 Safefree(CvFILE(cv));
10958                 CvFILE(cv) = NULL;
10959             }
10960
10961             /* inner references to compcv must be fixed up ... */
10962             pad_fixup_inner_anons(CvPADLIST(cv), compcv, cv);
10963             if (PERLDB_INTER)/* Advice debugger on the new sub. */
10964                 ++PL_sub_generation;
10965         }
10966         else {
10967             /* Might have had built-in attributes applied -- propagate them. */
10968             CvFLAGS(cv) |= (CvFLAGS(compcv) & CVf_BUILTIN_ATTRS);
10969         }
10970         /* ... before we throw it away */
10971         SvREFCNT_dec(compcv);
10972         PL_compcv = compcv = cv;
10973     }
10974     else {
10975         cv = compcv;
10976         *spot = cv;
10977     }
10978
10979   setname:
10980     CvLEXICAL_on(cv);
10981     if (!CvNAME_HEK(cv)) {
10982         if (hek) (void)share_hek_hek(hek);
10983         else {
10984             U32 hash;
10985             PERL_HASH(hash, PadnamePV(name)+1, PadnameLEN(name)-1);
10986             hek = share_hek(PadnamePV(name)+1,
10987                       (PadnameLEN(name)-1) * (PadnameUTF8(name) ? -1 : 1),
10988                       hash);
10989         }
10990         CvNAME_HEK_set(cv, hek);
10991     }
10992
10993     if (const_sv)
10994         goto clone;
10995
10996     if (CvFILE(cv) && CvDYNFILE(cv))
10997         Safefree(CvFILE(cv));
10998     CvFILE_set_from_cop(cv, PL_curcop);
10999     CvSTASH_set(cv, PL_curstash);
11000
11001     if (ps) {
11002         sv_setpvn(MUTABLE_SV(cv), ps, ps_len);
11003         if (ps_utf8)
11004             SvUTF8_on(MUTABLE_SV(cv));
11005     }
11006
11007     if (block) {
11008         /* If we assign an optree to a PVCV, then we've defined a
11009          * subroutine that the debugger could be able to set a breakpoint
11010          * in, so signal to pp_entereval that it should not throw away any
11011          * saved lines at scope exit.  */
11012
11013         PL_breakable_sub_gen++;
11014         CvROOT(cv) = block;
11015         /* The cv no longer needs to hold a refcount on the slab, as CvROOT
11016            itself has a refcount. */
11017         CvSLABBED_off(cv);
11018         OpslabREFCNT_dec_padok((OPSLAB *)CvSTART(cv));
11019 #ifdef PERL_DEBUG_READONLY_OPS
11020         slab = (OPSLAB *)CvSTART(cv);
11021 #endif
11022         S_process_optree(aTHX_ cv, block, start);
11023     }
11024
11025   attrs:
11026     if (attrs) {
11027         /* Need to do a C<use attributes $stash_of_cv,\&cv,@attrs>. */
11028         apply_attrs(PL_curstash, MUTABLE_SV(cv), attrs);
11029     }
11030
11031     if (block) {
11032         if (PERLDB_SUBLINE && PL_curstash != PL_debstash) {
11033             SV * const tmpstr = sv_newmortal();
11034             GV * const db_postponed = gv_fetchpvs("DB::postponed",
11035                                                   GV_ADDMULTI, SVt_PVHV);
11036             HV *hv;
11037             SV * const sv = Perl_newSVpvf(aTHX_ "%s:%ld-%ld",
11038                                           CopFILE(PL_curcop),
11039                                           (long)PL_subline,
11040                                           (long)CopLINE(PL_curcop));
11041             if (HvNAME_HEK(PL_curstash)) {
11042                 sv_sethek(tmpstr, HvNAME_HEK(PL_curstash));
11043                 sv_catpvs(tmpstr, "::");
11044             }
11045             else
11046                 sv_setpvs(tmpstr, "__ANON__::");
11047
11048             sv_catpvn_flags(tmpstr, PadnamePV(name)+1, PadnameLEN(name)-1,
11049                             PadnameUTF8(name) ? SV_CATUTF8 : SV_CATBYTES);
11050             (void)hv_store(GvHV(PL_DBsub), SvPVX_const(tmpstr),
11051                     SvUTF8(tmpstr) ? -(I32)SvCUR(tmpstr) : (I32)SvCUR(tmpstr), sv, 0);
11052             hv = GvHVn(db_postponed);
11053             if (HvTOTALKEYS(hv) > 0 && hv_exists(hv, SvPVX_const(tmpstr), SvUTF8(tmpstr) ? -(I32)SvCUR(tmpstr) : (I32)SvCUR(tmpstr))) {
11054                 CV * const pcv = GvCV(db_postponed);
11055                 if (pcv) {
11056                     dSP;
11057                     PUSHMARK(SP);
11058                     XPUSHs(tmpstr);
11059                     PUTBACK;
11060                     call_sv(MUTABLE_SV(pcv), G_DISCARD);
11061                 }
11062             }
11063         }
11064     }
11065
11066   clone:
11067     if (clonee) {
11068         assert(CvDEPTH(outcv));
11069         spot = (CV **)
11070             &PadARRAY(PadlistARRAY(CvPADLIST(outcv))[CvDEPTH(outcv)])[pax];
11071         if (reusable)
11072             cv_clone_into(clonee, *spot);
11073         else *spot = cv_clone(clonee);
11074         SvREFCNT_dec_NN(clonee);
11075         cv = *spot;
11076     }
11077
11078     if (CvDEPTH(outcv) && !reusable && PadnameIsSTATE(name)) {
11079         PADOFFSET depth = CvDEPTH(outcv);
11080         while (--depth) {
11081             SV *oldcv;
11082             svspot = &PadARRAY(PadlistARRAY(CvPADLIST(outcv))[depth])[pax];
11083             oldcv = *svspot;
11084             *svspot = SvREFCNT_inc_simple_NN(cv);
11085             SvREFCNT_dec(oldcv);
11086         }
11087     }
11088
11089   done:
11090     if (PL_parser)
11091         PL_parser->copline = NOLINE;
11092     LEAVE_SCOPE(floor);
11093 #ifdef PERL_DEBUG_READONLY_OPS
11094     if (slab)
11095         Slab_to_ro(slab);
11096 #endif
11097     op_free(o);
11098     return cv;
11099 }
11100
11101 /*
11102 =for apidoc newATTRSUB_x
11103
11104 Construct a Perl subroutine, also performing some surrounding jobs.
11105
11106 This function is expected to be called in a Perl compilation context,
11107 and some aspects of the subroutine are taken from global variables
11108 associated with compilation.  In particular, C<PL_compcv> represents
11109 the subroutine that is currently being compiled.  It must be non-null
11110 when this function is called, and some aspects of the subroutine being
11111 constructed are taken from it.  The constructed subroutine may actually
11112 be a reuse of the C<PL_compcv> object, but will not necessarily be so.
11113
11114 If C<block> is null then the subroutine will have no body, and for the
11115 time being it will be an error to call it.  This represents a forward
11116 subroutine declaration such as S<C<sub foo ($$);>>.  If C<block> is
11117 non-null then it provides the Perl code of the subroutine body, which
11118 will be executed when the subroutine is called.  This body includes
11119 any argument unwrapping code resulting from a subroutine signature or
11120 similar.  The pad use of the code must correspond to the pad attached
11121 to C<PL_compcv>.  The code is not expected to include a C<leavesub> or
11122 C<leavesublv> op; this function will add such an op.  C<block> is consumed
11123 by this function and will become part of the constructed subroutine.
11124
11125 C<proto> specifies the subroutine's prototype, unless one is supplied
11126 as an attribute (see below).  If C<proto> is null, then the subroutine
11127 will not have a prototype.  If C<proto> is non-null, it must point to a
11128 C<const> op whose value is a string, and the subroutine will have that
11129 string as its prototype.  If a prototype is supplied as an attribute, the
11130 attribute takes precedence over C<proto>, but in that case C<proto> should
11131 preferably be null.  In any case, C<proto> is consumed by this function.
11132
11133 C<attrs> supplies attributes to be applied the subroutine.  A handful of
11134 attributes take effect by built-in means, being applied to C<PL_compcv>
11135 immediately when seen.  Other attributes are collected up and attached
11136 to the subroutine by this route.  C<attrs> may be null to supply no
11137 attributes, or point to a C<const> op for a single attribute, or point
11138 to a C<list> op whose children apart from the C<pushmark> are C<const>
11139 ops for one or more attributes.  Each C<const> op must be a string,
11140 giving the attribute name optionally followed by parenthesised arguments,
11141 in the manner in which attributes appear in Perl source.  The attributes
11142 will be applied to the sub by this function.  C<attrs> is consumed by
11143 this function.
11144
11145 If C<o_is_gv> is false and C<o> is null, then the subroutine will
11146 be anonymous.  If C<o_is_gv> is false and C<o> is non-null, then C<o>
11147 must point to a C<const> op, which will be consumed by this function,
11148 and its string value supplies a name for the subroutine.  The name may
11149 be qualified or unqualified, and if it is unqualified then a default
11150 stash will be selected in some manner.  If C<o_is_gv> is true, then C<o>
11151 doesn't point to an C<OP> at all, but is instead a cast pointer to a C<GV>
11152 by which the subroutine will be named.
11153
11154 If there is already a subroutine of the specified name, then the new
11155 sub will either replace the existing one in the glob or be merged with
11156 the existing one.  A warning may be generated about redefinition.
11157
11158 If the subroutine has one of a few special names, such as C<BEGIN> or
11159 C<END>, then it will be claimed by the appropriate queue for automatic
11160 running of phase-related subroutines.  In this case the relevant glob will
11161 be left not containing any subroutine, even if it did contain one before.
11162 In the case of C<BEGIN>, the subroutine will be executed and the reference
11163 to it disposed of before this function returns.
11164
11165 The function returns a pointer to the constructed subroutine.  If the sub
11166 is anonymous then ownership of one counted reference to the subroutine
11167 is transferred to the caller.  If the sub is named then the caller does
11168 not get ownership of a reference.  In most such cases, where the sub
11169 has a non-phase name, the sub will be alive at the point it is returned
11170 by virtue of being contained in the glob that names it.  A phase-named
11171 subroutine will usually be alive by virtue of the reference owned by the
11172 phase's automatic run queue.  But a C<BEGIN> subroutine, having already
11173 been executed, will quite likely have been destroyed already by the
11174 time this function returns, making it erroneous for the caller to make
11175 any use of the returned pointer.  It is the caller's responsibility to
11176 ensure that it knows which of these situations applies.
11177
11178 =cut
11179 */
11180
11181 /* _x = extended */
11182 CV *
11183 Perl_newATTRSUB_x(pTHX_ I32 floor, OP *o, OP *proto, OP *attrs,
11184                             OP *block, bool o_is_gv)
11185 {
11186     GV *gv;
11187     const char *ps;
11188     STRLEN ps_len = 0; /* init it to avoid false uninit warning from icc */
11189     U32 ps_utf8 = 0;
11190     CV *cv = NULL;     /* the previous CV with this name, if any */
11191     SV *const_sv;
11192     const bool ec = PL_parser && PL_parser->error_count;
11193     /* If the subroutine has no body, no attributes, and no builtin attributes
11194        then it's just a sub declaration, and we may be able to get away with
11195        storing with a placeholder scalar in the symbol table, rather than a
11196        full CV.  If anything is present then it will take a full CV to
11197        store it.  */
11198     const I32 gv_fetch_flags
11199         = ec ? GV_NOADD_NOINIT :
11200         (block || attrs || (CvFLAGS(PL_compcv) & CVf_BUILTIN_ATTRS))
11201         ? GV_ADDMULTI : GV_ADDMULTI | GV_NOINIT;
11202     STRLEN namlen = 0;
11203     const char * const name =
11204          o ? SvPV_const(o_is_gv ? (SV *)o : cSVOPo->op_sv, namlen) : NULL;
11205     bool has_name;
11206     bool name_is_utf8 = o && !o_is_gv && SvUTF8(cSVOPo->op_sv);
11207     bool evanescent = FALSE;
11208     OP *start = NULL;
11209 #ifdef PERL_DEBUG_READONLY_OPS
11210     OPSLAB *slab = NULL;
11211 #endif
11212
11213     if (o_is_gv) {
11214         gv = (GV*)o;
11215         o = NULL;
11216         has_name = TRUE;
11217     } else if (name) {
11218         /* Try to optimise and avoid creating a GV.  Instead, the CV’s name
11219            hek and CvSTASH pointer together can imply the GV.  If the name
11220            contains a package name, then GvSTASH(CvGV(cv)) may differ from
11221            CvSTASH, so forego the optimisation if we find any.
11222            Also, we may be called from load_module at run time, so
11223            PL_curstash (which sets CvSTASH) may not point to the stash the
11224            sub is stored in.  */
11225         /* XXX This optimization is currently disabled for packages other
11226                than main, since there was too much CPAN breakage.  */
11227         const I32 flags =
11228            ec ? GV_NOADD_NOINIT
11229               :   (IN_PERL_RUNTIME && PL_curstash != CopSTASH(PL_curcop))
11230                || PL_curstash != PL_defstash
11231                || memchr(name, ':', namlen) || memchr(name, '\'', namlen)
11232                     ? gv_fetch_flags
11233                     : GV_ADDMULTI | GV_NOINIT | GV_NOTQUAL;
11234         gv = gv_fetchsv(cSVOPo->op_sv, flags, SVt_PVCV);
11235         has_name = TRUE;
11236     } else if (PERLDB_NAMEANON && CopLINE(PL_curcop)) {
11237         SV * const sv = sv_newmortal();
11238         Perl_sv_setpvf(aTHX_ sv, "%s[%s:%" IVdf "]",
11239                        PL_curstash ? "__ANON__" : "__ANON__::__ANON__",
11240                        CopFILE(PL_curcop), (IV)CopLINE(PL_curcop));
11241         gv = gv_fetchsv(sv, gv_fetch_flags, SVt_PVCV);
11242         has_name = TRUE;
11243     } else if (PL_curstash) {
11244         gv = gv_fetchpvs("__ANON__", gv_fetch_flags, SVt_PVCV);
11245         has_name = FALSE;
11246     } else {
11247         gv = gv_fetchpvs("__ANON__::__ANON__", gv_fetch_flags, SVt_PVCV);
11248         has_name = FALSE;
11249     }
11250
11251     if (!ec) {
11252         if (isGV(gv)) {
11253             move_proto_attr(&proto, &attrs, gv, 0);
11254         } else {
11255             assert(cSVOPo);
11256             move_proto_attr(&proto, &attrs, (GV *)cSVOPo->op_sv, 1);
11257         }
11258     }
11259
11260     if (proto) {
11261         assert(proto->op_type == OP_CONST);
11262         ps = SvPV_const(((SVOP*)proto)->op_sv, ps_len);
11263         ps_utf8 = SvUTF8(((SVOP*)proto)->op_sv);
11264     }
11265     else
11266         ps = NULL;
11267
11268     if (o)
11269         SAVEFREEOP(o);
11270     if (proto)
11271         SAVEFREEOP(proto);
11272     if (attrs)
11273         SAVEFREEOP(attrs);
11274
11275     if (ec) {
11276         op_free(block);
11277
11278         if (name)
11279             SvREFCNT_dec(PL_compcv);
11280         else
11281             cv = PL_compcv;
11282
11283         PL_compcv = 0;
11284         if (name && block) {
11285             const char *s = (char *) my_memrchr(name, ':', namlen);
11286             s = s ? s+1 : name;
11287             if (strEQ(s, "BEGIN")) {
11288                 if (PL_in_eval & EVAL_KEEPERR)
11289                     Perl_croak_nocontext("BEGIN not safe after errors--compilation aborted");
11290                 else {
11291                     SV * const errsv = ERRSV;
11292                     /* force display of errors found but not reported */
11293                     sv_catpvs(errsv, "BEGIN not safe after errors--compilation aborted");
11294                     Perl_croak_nocontext("%" SVf, SVfARG(errsv));
11295                 }
11296             }
11297         }
11298         goto done;
11299     }
11300
11301     if (!block && SvTYPE(gv) != SVt_PVGV) {
11302         /* If we are not defining a new sub and the existing one is not a
11303            full GV + CV... */
11304         if (attrs || (CvFLAGS(PL_compcv) & CVf_BUILTIN_ATTRS)) {
11305             /* We are applying attributes to an existing sub, so we need it
11306                upgraded if it is a constant.  */
11307             if (SvROK(gv) && SvTYPE(SvRV(gv)) != SVt_PVCV)
11308                 gv_init_pvn(gv, PL_curstash, name, namlen,
11309                             SVf_UTF8 * name_is_utf8);
11310         }
11311         else {                  /* Maybe prototype now, and had at maximum
11312                                    a prototype or const/sub ref before.  */
11313             if (SvTYPE(gv) > SVt_NULL) {
11314                 cv_ckproto_len_flags((const CV *)gv,
11315                                     o ? (const GV *)cSVOPo->op_sv : NULL, ps,
11316                                     ps_len, ps_utf8);
11317             }
11318
11319             if (!SvROK(gv)) {
11320                 if (ps) {
11321                     sv_setpvn(MUTABLE_SV(gv), ps, ps_len);
11322                     if (ps_utf8)
11323                         SvUTF8_on(MUTABLE_SV(gv));
11324                 }
11325                 else
11326                     sv_setiv(MUTABLE_SV(gv), -1);
11327             }
11328
11329             SvREFCNT_dec(PL_compcv);
11330             cv = PL_compcv = NULL;
11331             goto done;
11332         }
11333     }
11334
11335     cv = (!name || (isGV(gv) && GvCVGEN(gv)))
11336         ? NULL
11337         : isGV(gv)
11338             ? GvCV(gv)
11339             : SvROK(gv) && SvTYPE(SvRV(gv)) == SVt_PVCV
11340                 ? (CV *)SvRV(gv)
11341                 : NULL;
11342
11343     if (block) {
11344         assert(PL_parser);
11345         /* This makes sub {}; work as expected.  */
11346         if (block->op_type == OP_STUB) {
11347             const line_t l = PL_parser->copline;
11348             op_free(block);
11349             block = newSTATEOP(0, NULL, 0);
11350             PL_parser->copline = l;
11351         }
11352         block = CvLVALUE(PL_compcv)
11353              || (cv && CvLVALUE(cv) && !CvROOT(cv) && !CvXSUB(cv)
11354                     && (!isGV(gv) || !GvASSUMECV(gv)))
11355                    ? newUNOP(OP_LEAVESUBLV, 0,
11356                              op_lvalue(scalarseq(block), OP_LEAVESUBLV))
11357                    : newUNOP(OP_LEAVESUB, 0, scalarseq(block));
11358         start = LINKLIST(block);
11359         block->op_next = 0;
11360         if (ps && !*ps && !attrs && !CvLVALUE(PL_compcv))
11361             const_sv =
11362                 S_op_const_sv(aTHX_ start, PL_compcv,
11363                                         cBOOL(CvCLONE(PL_compcv)));
11364         else
11365             const_sv = NULL;
11366     }
11367     else
11368         const_sv = NULL;
11369
11370     if (SvPOK(gv) || (SvROK(gv) && SvTYPE(SvRV(gv)) != SVt_PVCV)) {
11371         cv_ckproto_len_flags((const CV *)gv,
11372                              o ? (const GV *)cSVOPo->op_sv : NULL, ps,
11373                              ps_len, ps_utf8|CV_CKPROTO_CURSTASH);
11374         if (SvROK(gv)) {
11375             /* All the other code for sub redefinition warnings expects the
11376                clobbered sub to be a CV.  Instead of making all those code
11377                paths more complex, just inline the RV version here.  */
11378             const line_t oldline = CopLINE(PL_curcop);
11379             assert(IN_PERL_COMPILETIME);
11380             if (PL_parser && PL_parser->copline != NOLINE)
11381                 /* This ensures that warnings are reported at the first
11382                    line of a redefinition, not the last.  */
11383                 CopLINE_set(PL_curcop, PL_parser->copline);
11384             /* protect against fatal warnings leaking compcv */
11385             SAVEFREESV(PL_compcv);
11386
11387             if (ckWARN(WARN_REDEFINE)
11388              || (  ckWARN_d(WARN_REDEFINE)
11389                 && (  !const_sv || SvRV(gv) == const_sv
11390                    || sv_cmp(SvRV(gv), const_sv)  ))) {
11391                 assert(cSVOPo);
11392                 Perl_warner(aTHX_ packWARN(WARN_REDEFINE),
11393                           "Constant subroutine %" SVf " redefined",
11394                           SVfARG(cSVOPo->op_sv));
11395             }
11396
11397             SvREFCNT_inc_simple_void_NN(PL_compcv);
11398             CopLINE_set(PL_curcop, oldline);
11399             SvREFCNT_dec(SvRV(gv));
11400         }
11401     }
11402
11403     if (cv) {
11404         const bool exists = CvROOT(cv) || CvXSUB(cv);
11405
11406         /* if the subroutine doesn't exist and wasn't pre-declared
11407          * with a prototype, assume it will be AUTOLOADed,
11408          * skipping the prototype check
11409          */
11410         if (exists || SvPOK(cv))
11411             cv_ckproto_len_flags(cv, gv, ps, ps_len, ps_utf8);
11412         /* already defined (or promised)? */
11413         if (exists || (isGV(gv) && GvASSUMECV(gv))) {
11414             S_already_defined(aTHX_ cv, block, o, NULL, &const_sv);
11415             if (block)
11416                 cv = NULL;
11417             else {
11418                 if (attrs)
11419                     goto attrs;
11420                 /* just a "sub foo;" when &foo is already defined */
11421                 SAVEFREESV(PL_compcv);
11422                 goto done;
11423             }
11424         }
11425     }
11426
11427     if (const_sv) {
11428         SvREFCNT_inc_simple_void_NN(const_sv);
11429         SvFLAGS(const_sv) |= SVs_PADTMP;
11430         if (cv) {
11431             assert(!CvROOT(cv) && !CvCONST(cv));
11432             cv_forget_slab(cv);
11433             SvPVCLEAR(MUTABLE_SV(cv));  /* prototype is "" */
11434             CvXSUBANY(cv).any_ptr = const_sv;
11435             CvXSUB(cv) = const_sv_xsub;
11436             CvCONST_on(cv);
11437             CvISXSUB_on(cv);
11438             PoisonPADLIST(cv);
11439             CvFLAGS(cv) |= CvMETHOD(PL_compcv);
11440         }
11441         else {
11442             if (isGV(gv) || CvMETHOD(PL_compcv)) {
11443                 if (name && isGV(gv))
11444                     GvCV_set(gv, NULL);
11445                 cv = newCONSTSUB_flags(
11446                     NULL, name, namlen, name_is_utf8 ? SVf_UTF8 : 0,
11447                     const_sv
11448                 );
11449                 assert(cv);
11450                 assert(SvREFCNT((SV*)cv) != 0);
11451                 CvFLAGS(cv) |= CvMETHOD(PL_compcv);
11452             }
11453             else {
11454                 if (!SvROK(gv)) {
11455                     SV_CHECK_THINKFIRST_COW_DROP((SV *)gv);
11456                     prepare_SV_for_RV((SV *)gv);
11457                     SvOK_off((SV *)gv);
11458                     SvROK_on(gv);
11459                 }
11460                 SvRV_set(gv, const_sv);
11461             }
11462         }
11463         op_free(block);
11464         SvREFCNT_dec(PL_compcv);
11465         PL_compcv = NULL;
11466         goto done;
11467     }
11468
11469     /* don't copy new BEGIN CV to old BEGIN CV - RT #129099 */
11470     if (name && cv && *name == 'B' && strEQ(name, "BEGIN"))
11471         cv = NULL;
11472
11473     if (cv) {                           /* must reuse cv if autoloaded */
11474         /* transfer PL_compcv to cv */
11475         if (block) {
11476             bool free_file = CvFILE(cv) && CvDYNFILE(cv);
11477             cv_flags_t existing_builtin_attrs = CvFLAGS(cv) & CVf_BUILTIN_ATTRS;
11478             PADLIST *const temp_av = CvPADLIST(cv);
11479             CV *const temp_cv = CvOUTSIDE(cv);
11480             const cv_flags_t other_flags =
11481                 CvFLAGS(cv) & (CVf_SLABBED|CVf_WEAKOUTSIDE);
11482             OP * const cvstart = CvSTART(cv);
11483
11484             if (isGV(gv)) {
11485                 CvGV_set(cv,gv);
11486                 assert(!CvCVGV_RC(cv));
11487                 assert(CvGV(cv) == gv);
11488             }
11489             else {
11490                 U32 hash;
11491                 PERL_HASH(hash, name, namlen);
11492                 CvNAME_HEK_set(cv,
11493                                share_hek(name,
11494                                          name_is_utf8
11495                                             ? -(SSize_t)namlen
11496                                             :  (SSize_t)namlen,
11497                                          hash));
11498             }
11499
11500             SvPOK_off(cv);
11501             CvFLAGS(cv) = CvFLAGS(PL_compcv) | existing_builtin_attrs
11502                                              | CvNAMED(cv);
11503             CvOUTSIDE(cv) = CvOUTSIDE(PL_compcv);
11504             CvOUTSIDE_SEQ(cv) = CvOUTSIDE_SEQ(PL_compcv);
11505             CvPADLIST_set(cv,CvPADLIST(PL_compcv));
11506             CvOUTSIDE(PL_compcv) = temp_cv;
11507             CvPADLIST_set(PL_compcv, temp_av);
11508             CvSTART(cv) = CvSTART(PL_compcv);
11509             CvSTART(PL_compcv) = cvstart;
11510             CvFLAGS(PL_compcv) &= ~(CVf_SLABBED|CVf_WEAKOUTSIDE);
11511             CvFLAGS(PL_compcv) |= other_flags;
11512
11513             if (free_file) {
11514                 Safefree(CvFILE(cv));
11515             }
11516             CvFILE_set_from_cop(cv, PL_curcop);
11517             CvSTASH_set(cv, PL_curstash);
11518
11519             /* inner references to PL_compcv must be fixed up ... */
11520             pad_fixup_inner_anons(CvPADLIST(cv), PL_compcv, cv);
11521             if (PERLDB_INTER)/* Advice debugger on the new sub. */
11522                 ++PL_sub_generation;
11523         }
11524         else {
11525             /* Might have had built-in attributes applied -- propagate them. */
11526             CvFLAGS(cv) |= (CvFLAGS(PL_compcv) & CVf_BUILTIN_ATTRS);
11527         }
11528         /* ... before we throw it away */
11529         SvREFCNT_dec(PL_compcv);
11530         PL_compcv = cv;
11531     }
11532     else {
11533         cv = PL_compcv;
11534         if (name && isGV(gv)) {
11535             GvCV_set(gv, cv);
11536             GvCVGEN(gv) = 0;
11537             if (HvENAME_HEK(GvSTASH(gv)))
11538                 /* sub Foo::bar { (shift)+1 } */
11539                 gv_method_changed(gv);
11540         }
11541         else if (name) {
11542             if (!SvROK(gv)) {
11543                 SV_CHECK_THINKFIRST_COW_DROP((SV *)gv);
11544                 prepare_SV_for_RV((SV *)gv);
11545                 SvOK_off((SV *)gv);
11546                 SvROK_on(gv);
11547             }
11548             SvRV_set(gv, (SV *)cv);
11549             if (HvENAME_HEK(PL_curstash))
11550                 mro_method_changed_in(PL_curstash);
11551         }
11552     }
11553     assert(cv);
11554     assert(SvREFCNT((SV*)cv) != 0);
11555
11556     if (!CvHASGV(cv)) {
11557         if (isGV(gv))
11558             CvGV_set(cv, gv);
11559         else {
11560             U32 hash;
11561             PERL_HASH(hash, name, namlen);
11562             CvNAME_HEK_set(cv, share_hek(name,
11563                                          name_is_utf8
11564                                             ? -(SSize_t)namlen
11565                                             :  (SSize_t)namlen,
11566                                          hash));
11567         }
11568         CvFILE_set_from_cop(cv, PL_curcop);
11569         CvSTASH_set(cv, PL_curstash);
11570     }
11571
11572     if (ps) {
11573         sv_setpvn(MUTABLE_SV(cv), ps, ps_len);
11574         if ( ps_utf8 )
11575             SvUTF8_on(MUTABLE_SV(cv));
11576     }
11577
11578     if (block) {
11579         /* If we assign an optree to a PVCV, then we've defined a
11580          * subroutine that the debugger could be able to set a breakpoint
11581          * in, so signal to pp_entereval that it should not throw away any
11582          * saved lines at scope exit.  */
11583
11584         PL_breakable_sub_gen++;
11585         CvROOT(cv) = block;
11586         /* The cv no longer needs to hold a refcount on the slab, as CvROOT
11587            itself has a refcount. */
11588         CvSLABBED_off(cv);
11589         OpslabREFCNT_dec_padok((OPSLAB *)CvSTART(cv));
11590 #ifdef PERL_DEBUG_READONLY_OPS
11591         slab = (OPSLAB *)CvSTART(cv);
11592 #endif
11593         S_process_optree(aTHX_ cv, block, start);
11594     }
11595
11596   attrs:
11597     if (attrs) {
11598         /* Need to do a C<use attributes $stash_of_cv,\&cv,@attrs>. */
11599         HV *stash = name && !CvNAMED(cv) && GvSTASH(CvGV(cv))
11600                         ? GvSTASH(CvGV(cv))
11601                         : PL_curstash;
11602         if (!name)
11603             SAVEFREESV(cv);
11604         apply_attrs(stash, MUTABLE_SV(cv), attrs);
11605         if (!name)
11606             SvREFCNT_inc_simple_void_NN(cv);
11607     }
11608
11609     if (block && has_name) {
11610         if (PERLDB_SUBLINE && PL_curstash != PL_debstash) {
11611             SV * const tmpstr = cv_name(cv,NULL,0);
11612             GV * const db_postponed = gv_fetchpvs("DB::postponed",
11613                                                   GV_ADDMULTI, SVt_PVHV);
11614             HV *hv;
11615             SV * const sv = Perl_newSVpvf(aTHX_ "%s:%ld-%ld",
11616                                           CopFILE(PL_curcop),
11617                                           (long)PL_subline,
11618                                           (long)CopLINE(PL_curcop));
11619             (void)hv_store(GvHV(PL_DBsub), SvPVX_const(tmpstr),
11620                     SvUTF8(tmpstr) ? -(I32)SvCUR(tmpstr) : (I32)SvCUR(tmpstr), sv, 0);
11621             hv = GvHVn(db_postponed);
11622             if (HvTOTALKEYS(hv) > 0 && hv_exists(hv, SvPVX_const(tmpstr), SvUTF8(tmpstr) ? -(I32)SvCUR(tmpstr) : (I32)SvCUR(tmpstr))) {
11623                 CV * const pcv = GvCV(db_postponed);
11624                 if (pcv) {
11625                     dSP;
11626                     PUSHMARK(SP);
11627                     XPUSHs(tmpstr);
11628                     PUTBACK;
11629                     call_sv(MUTABLE_SV(pcv), G_DISCARD);
11630                 }
11631             }
11632         }
11633
11634         if (name) {
11635             if (PL_parser && PL_parser->error_count)
11636                 clear_special_blocks(name, gv, cv);
11637             else
11638                 evanescent =
11639                     process_special_blocks(floor, name, gv, cv);
11640         }
11641     }
11642     assert(cv);
11643
11644   done:
11645     assert(!cv || evanescent || SvREFCNT((SV*)cv) != 0);
11646     if (PL_parser)
11647         PL_parser->copline = NOLINE;
11648     LEAVE_SCOPE(floor);
11649
11650     assert(!cv || evanescent || SvREFCNT((SV*)cv) != 0);
11651     if (!evanescent) {
11652 #ifdef PERL_DEBUG_READONLY_OPS
11653     if (slab)
11654         Slab_to_ro(slab);
11655 #endif
11656     if (cv && name && block && CvOUTSIDE(cv) && !CvEVAL(CvOUTSIDE(cv)))
11657         pad_add_weakref(cv);
11658     }
11659     return cv;
11660 }
11661
11662 STATIC void
11663 S_clear_special_blocks(pTHX_ const char *const fullname,
11664                        GV *const gv, CV *const cv) {
11665     const char *colon;
11666     const char *name;
11667
11668     PERL_ARGS_ASSERT_CLEAR_SPECIAL_BLOCKS;
11669
11670     colon = strrchr(fullname,':');
11671     name = colon ? colon + 1 : fullname;
11672
11673     if ((*name == 'B' && strEQ(name, "BEGIN"))
11674         || (*name == 'E' && strEQ(name, "END"))
11675         || (*name == 'U' && strEQ(name, "UNITCHECK"))
11676         || (*name == 'C' && strEQ(name, "CHECK"))
11677         || (*name == 'I' && strEQ(name, "INIT"))) {
11678         if (!isGV(gv)) {
11679             (void)CvGV(cv);
11680             assert(isGV(gv));
11681         }
11682         GvCV_set(gv, NULL);
11683         SvREFCNT_dec_NN(MUTABLE_SV(cv));
11684     }
11685 }
11686
11687 /* Returns true if the sub has been freed.  */
11688 STATIC bool
11689 S_process_special_blocks(pTHX_ I32 floor, const char *const fullname,
11690                          GV *const gv,
11691                          CV *const cv)
11692 {
11693     const char *const colon = strrchr(fullname,':');
11694     const char *const name = colon ? colon + 1 : fullname;
11695
11696     PERL_ARGS_ASSERT_PROCESS_SPECIAL_BLOCKS;
11697
11698     if (*name == 'B') {
11699         if (strEQ(name, "BEGIN")) {
11700             const I32 oldscope = PL_scopestack_ix;
11701             dSP;
11702             (void)CvGV(cv);
11703             if (floor) LEAVE_SCOPE(floor);
11704             ENTER;
11705             PUSHSTACKi(PERLSI_REQUIRE);
11706             SAVECOPFILE(&PL_compiling);
11707             SAVECOPLINE(&PL_compiling);
11708             SAVEVPTR(PL_curcop);
11709
11710             DEBUG_x( dump_sub(gv) );
11711             Perl_av_create_and_push(aTHX_ &PL_beginav, MUTABLE_SV(cv));
11712             GvCV_set(gv,0);             /* cv has been hijacked */
11713             call_list(oldscope, PL_beginav);
11714
11715             POPSTACK;
11716             LEAVE;
11717             return !PL_savebegin;
11718         }
11719         else
11720             return FALSE;
11721     } else {
11722         if (*name == 'E') {
11723             if (strEQ(name, "END")) {
11724                 DEBUG_x( dump_sub(gv) );
11725                 Perl_av_create_and_unshift_one(aTHX_ &PL_endav, MUTABLE_SV(cv));
11726             } else
11727                 return FALSE;
11728         } else if (*name == 'U') {
11729             if (strEQ(name, "UNITCHECK")) {
11730                 /* It's never too late to run a unitcheck block */
11731                 Perl_av_create_and_unshift_one(aTHX_ &PL_unitcheckav, MUTABLE_SV(cv));
11732             }
11733             else
11734                 return FALSE;
11735         } else if (*name == 'C') {
11736             if (strEQ(name, "CHECK")) {
11737                 if (PL_main_start)
11738                     /* diag_listed_as: Too late to run %s block */
11739                     Perl_ck_warner(aTHX_ packWARN(WARN_VOID),
11740                                    "Too late to run CHECK block");
11741                 Perl_av_create_and_unshift_one(aTHX_ &PL_checkav, MUTABLE_SV(cv));
11742             }
11743             else
11744                 return FALSE;
11745         } else if (*name == 'I') {
11746             if (strEQ(name, "INIT")) {
11747                 if (PL_main_start)
11748                     /* diag_listed_as: Too late to run %s block */
11749                     Perl_ck_warner(aTHX_ packWARN(WARN_VOID),
11750                                    "Too late to run INIT block");
11751                 Perl_av_create_and_push(aTHX_ &PL_initav, MUTABLE_SV(cv));
11752             }
11753             else
11754                 return FALSE;
11755         } else
11756             return FALSE;
11757         DEBUG_x( dump_sub(gv) );
11758         (void)CvGV(cv);
11759         GvCV_set(gv,0);         /* cv has been hijacked */
11760         return FALSE;
11761     }
11762 }
11763
11764 /*
11765 =for apidoc newCONSTSUB
11766
11767 Behaves like L</newCONSTSUB_flags>, except that C<name> is nul-terminated
11768 rather than of counted length, and no flags are set.  (This means that
11769 C<name> is always interpreted as Latin-1.)
11770
11771 =cut
11772 */
11773
11774 CV *
11775 Perl_newCONSTSUB(pTHX_ HV *stash, const char *name, SV *sv)
11776 {
11777     return newCONSTSUB_flags(stash, name, name ? strlen(name) : 0, 0, sv);
11778 }
11779
11780 /*
11781 =for apidoc newCONSTSUB_flags
11782
11783 Construct a constant subroutine, also performing some surrounding
11784 jobs.  A scalar constant-valued subroutine is eligible for inlining
11785 at compile-time, and in Perl code can be created by S<C<sub FOO () {
11786 123 }>>.  Other kinds of constant subroutine have other treatment.
11787
11788 The subroutine will have an empty prototype and will ignore any arguments
11789 when called.  Its constant behaviour is determined by C<sv>.  If C<sv>
11790 is null, the subroutine will yield an empty list.  If C<sv> points to a
11791 scalar, the subroutine will always yield that scalar.  If C<sv> points
11792 to an array, the subroutine will always yield a list of the elements of
11793 that array in list context, or the number of elements in the array in
11794 scalar context.  This function takes ownership of one counted reference
11795 to the scalar or array, and will arrange for the object to live as long
11796 as the subroutine does.  If C<sv> points to a scalar then the inlining
11797 assumes that the value of the scalar will never change, so the caller
11798 must ensure that the scalar is not subsequently written to.  If C<sv>
11799 points to an array then no such assumption is made, so it is ostensibly
11800 safe to mutate the array or its elements, but whether this is really
11801 supported has not been determined.
11802
11803 The subroutine will have C<CvFILE> set according to C<PL_curcop>.
11804 Other aspects of the subroutine will be left in their default state.
11805 The caller is free to mutate the subroutine beyond its initial state
11806 after this function has returned.
11807
11808 If C<name> is null then the subroutine will be anonymous, with its
11809 C<CvGV> referring to an C<__ANON__> glob.  If C<name> is non-null then the
11810 subroutine will be named accordingly, referenced by the appropriate glob.
11811 C<name> is a string of length C<len> bytes giving a sigilless symbol
11812 name, in UTF-8 if C<flags> has the C<SVf_UTF8> bit set and in Latin-1
11813 otherwise.  The name may be either qualified or unqualified.  If the
11814 name is unqualified then it defaults to being in the stash specified by
11815 C<stash> if that is non-null, or to C<PL_curstash> if C<stash> is null.
11816 The symbol is always added to the stash if necessary, with C<GV_ADDMULTI>
11817 semantics.
11818
11819 C<flags> should not have bits set other than C<SVf_UTF8>.
11820
11821 If there is already a subroutine of the specified name, then the new sub
11822 will replace the existing one in the glob.  A warning may be generated
11823 about the redefinition.
11824
11825 If the subroutine has one of a few special names, such as C<BEGIN> or
11826 C<END>, then it will be claimed by the appropriate queue for automatic
11827 running of phase-related subroutines.  In this case the relevant glob will
11828 be left not containing any subroutine, even if it did contain one before.
11829 Execution of the subroutine will likely be a no-op, unless C<sv> was
11830 a tied array or the caller modified the subroutine in some interesting
11831 way before it was executed.  In the case of C<BEGIN>, the treatment is
11832 buggy: the sub will be executed when only half built, and may be deleted
11833 prematurely, possibly causing a crash.
11834
11835 The function returns a pointer to the constructed subroutine.  If the sub
11836 is anonymous then ownership of one counted reference to the subroutine
11837 is transferred to the caller.  If the sub is named then the caller does
11838 not get ownership of a reference.  In most such cases, where the sub
11839 has a non-phase name, the sub will be alive at the point it is returned
11840 by virtue of being contained in the glob that names it.  A phase-named
11841 subroutine will usually be alive by virtue of the reference owned by
11842 the phase's automatic run queue.  A C<BEGIN> subroutine may have been
11843 destroyed already by the time this function returns, but currently bugs
11844 occur in that case before the caller gets control.  It is the caller's
11845 responsibility to ensure that it knows which of these situations applies.
11846
11847 =cut
11848 */
11849
11850 CV *
11851 Perl_newCONSTSUB_flags(pTHX_ HV *stash, const char *name, STRLEN len,
11852                              U32 flags, SV *sv)
11853 {
11854     CV* cv;
11855     const char *const file = CopFILE(PL_curcop);
11856
11857     ENTER;
11858
11859     if (IN_PERL_RUNTIME) {
11860         /* at runtime, it's not safe to manipulate PL_curcop: it may be
11861          * an op shared between threads. Use a non-shared COP for our
11862          * dirty work */
11863          SAVEVPTR(PL_curcop);
11864          SAVECOMPILEWARNINGS();
11865          PL_compiling.cop_warnings = DUP_WARNINGS(PL_curcop->cop_warnings);
11866          PL_curcop = &PL_compiling;
11867     }
11868     SAVECOPLINE(PL_curcop);
11869     CopLINE_set(PL_curcop, PL_parser ? PL_parser->copline : NOLINE);
11870
11871     SAVEHINTS();
11872     PL_hints &= ~HINT_BLOCK_SCOPE;
11873
11874     if (stash) {
11875         SAVEGENERICSV(PL_curstash);
11876         PL_curstash = (HV *)SvREFCNT_inc_simple_NN(stash);
11877     }
11878
11879     /* Protect sv against leakage caused by fatal warnings. */
11880     if (sv) SAVEFREESV(sv);
11881
11882     /* file becomes the CvFILE. For an XS, it's usually static storage,
11883        and so doesn't get free()d.  (It's expected to be from the C pre-
11884        processor __FILE__ directive). But we need a dynamically allocated one,
11885        and we need it to get freed.  */
11886     cv = newXS_len_flags(name, len,
11887                          sv && SvTYPE(sv) == SVt_PVAV
11888                              ? const_av_xsub
11889                              : const_sv_xsub,
11890                          file ? file : "", "",
11891                          &sv, XS_DYNAMIC_FILENAME | flags);
11892     assert(cv);
11893     assert(SvREFCNT((SV*)cv) != 0);
11894     CvXSUBANY(cv).any_ptr = SvREFCNT_inc_simple(sv);
11895     CvCONST_on(cv);
11896
11897     LEAVE;
11898
11899     return cv;
11900 }
11901
11902 /*
11903 =for apidoc newXS
11904
11905 Used by C<xsubpp> to hook up XSUBs as Perl subs.  C<filename> needs to be
11906 static storage, as it is used directly as CvFILE(), without a copy being made.
11907
11908 =cut
11909 */
11910
11911 CV *
11912 Perl_newXS(pTHX_ const char *name, XSUBADDR_t subaddr, const char *filename)
11913 {
11914     PERL_ARGS_ASSERT_NEWXS;
11915     return newXS_len_flags(
11916         name, name ? strlen(name) : 0, subaddr, filename, NULL, NULL, 0
11917     );
11918 }
11919
11920 CV *
11921 Perl_newXS_flags(pTHX_ const char *name, XSUBADDR_t subaddr,
11922                  const char *const filename, const char *const proto,
11923                  U32 flags)
11924 {
11925     PERL_ARGS_ASSERT_NEWXS_FLAGS;
11926     return newXS_len_flags(
11927        name, name ? strlen(name) : 0, subaddr, filename, proto, NULL, flags
11928     );
11929 }
11930
11931 CV *
11932 Perl_newXS_deffile(pTHX_ const char *name, XSUBADDR_t subaddr)
11933 {
11934     PERL_ARGS_ASSERT_NEWXS_DEFFILE;
11935     return newXS_len_flags(
11936         name, strlen(name), subaddr, NULL, NULL, NULL, 0
11937     );
11938 }
11939
11940 /*
11941 =for apidoc newXS_len_flags
11942
11943 Construct an XS subroutine, also performing some surrounding jobs.
11944
11945 The subroutine will have the entry point C<subaddr>.  It will have
11946 the prototype specified by the nul-terminated string C<proto>, or
11947 no prototype if C<proto> is null.  The prototype string is copied;
11948 the caller can mutate the supplied string afterwards.  If C<filename>
11949 is non-null, it must be a nul-terminated filename, and the subroutine
11950 will have its C<CvFILE> set accordingly.  By default C<CvFILE> is set to
11951 point directly to the supplied string, which must be static.  If C<flags>
11952 has the C<XS_DYNAMIC_FILENAME> bit set, then a copy of the string will
11953 be taken instead.
11954
11955 Other aspects of the subroutine will be left in their default state.
11956 If anything else needs to be done to the subroutine for it to function
11957 correctly, it is the caller's responsibility to do that after this
11958 function has constructed it.  However, beware of the subroutine
11959 potentially being destroyed before this function returns, as described
11960 below.
11961
11962 If C<name> is null then the subroutine will be anonymous, with its
11963 C<CvGV> referring to an C<__ANON__> glob.  If C<name> is non-null then the
11964 subroutine will be named accordingly, referenced by the appropriate glob.
11965 C<name> is a string of length C<len> bytes giving a sigilless symbol name,
11966 in UTF-8 if C<flags> has the C<SVf_UTF8> bit set and in Latin-1 otherwise.
11967 The name may be either qualified or unqualified, with the stash defaulting
11968 in the same manner as for C<gv_fetchpvn_flags>.  C<flags> may contain
11969 flag bits understood by C<gv_fetchpvn_flags> with the same meaning as
11970 they have there, such as C<GV_ADDWARN>.  The symbol is always added to
11971 the stash if necessary, with C<GV_ADDMULTI> semantics.
11972
11973 If there is already a subroutine of the specified name, then the new sub
11974 will replace the existing one in the glob.  A warning may be generated
11975 about the redefinition.  If the old subroutine was C<CvCONST> then the
11976 decision about whether to warn is influenced by an expectation about
11977 whether the new subroutine will become a constant of similar value.
11978 That expectation is determined by C<const_svp>.  (Note that the call to
11979 this function doesn't make the new subroutine C<CvCONST> in any case;
11980 that is left to the caller.)  If C<const_svp> is null then it indicates
11981 that the new subroutine will not become a constant.  If C<const_svp>
11982 is non-null then it indicates that the new subroutine will become a
11983 constant, and it points to an C<SV*> that provides the constant value
11984 that the subroutine will have.
11985
11986 If the subroutine has one of a few special names, such as C<BEGIN> or
11987 C<END>, then it will be claimed by the appropriate queue for automatic
11988 running of phase-related subroutines.  In this case the relevant glob will
11989 be left not containing any subroutine, even if it did contain one before.
11990 In the case of C<BEGIN>, the subroutine will be executed and the reference
11991 to it disposed of before this function returns, and also before its
11992 prototype is set.  If a C<BEGIN> subroutine would not be sufficiently
11993 constructed by this function to be ready for execution then the caller
11994 must prevent this happening by giving the subroutine a different name.
11995
11996 The function returns a pointer to the constructed subroutine.  If the sub
11997 is anonymous then ownership of one counted reference to the subroutine
11998 is transferred to the caller.  If the sub is named then the caller does
11999 not get ownership of a reference.  In most such cases, where the sub
12000 has a non-phase name, the sub will be alive at the point it is returned
12001 by virtue of being contained in the glob that names it.  A phase-named
12002 subroutine will usually be alive by virtue of the reference owned by the
12003 phase's automatic run queue.  But a C<BEGIN> subroutine, having already
12004 been executed, will quite likely have been destroyed already by the
12005 time this function returns, making it erroneous for the caller to make
12006 any use of the returned pointer.  It is the caller's responsibility to
12007 ensure that it knows which of these situations applies.
12008
12009 =cut
12010 */
12011
12012 CV *
12013 Perl_newXS_len_flags(pTHX_ const char *name, STRLEN len,
12014                            XSUBADDR_t subaddr, const char *const filename,
12015                            const char *const proto, SV **const_svp,
12016                            U32 flags)
12017 {
12018     CV *cv;
12019     bool interleave = FALSE;
12020     bool evanescent = FALSE;
12021
12022     PERL_ARGS_ASSERT_NEWXS_LEN_FLAGS;
12023
12024     {
12025         GV * const gv = gv_fetchpvn(
12026                             name ? name : PL_curstash ? "__ANON__" : "__ANON__::__ANON__",
12027                             name ? len : PL_curstash ? sizeof("__ANON__") - 1:
12028                                 sizeof("__ANON__::__ANON__") - 1,
12029                             GV_ADDMULTI | flags, SVt_PVCV);
12030
12031         if ((cv = (name ? GvCV(gv) : NULL))) {
12032             if (GvCVGEN(gv)) {
12033                 /* just a cached method */
12034                 SvREFCNT_dec(cv);
12035                 cv = NULL;
12036             }
12037             else if (CvROOT(cv) || CvXSUB(cv) || GvASSUMECV(gv)) {
12038                 /* already defined (or promised) */
12039                 /* Redundant check that allows us to avoid creating an SV
12040                    most of the time: */
12041                 if (CvCONST(cv) || ckWARN(WARN_REDEFINE)) {
12042                     report_redefined_cv(newSVpvn_flags(
12043                                          name,len,(flags&SVf_UTF8)|SVs_TEMP
12044                                         ),
12045                                         cv, const_svp);
12046                 }
12047                 interleave = TRUE;
12048                 ENTER;
12049                 SAVEFREESV(cv);
12050                 cv = NULL;
12051             }
12052         }
12053
12054         if (cv)                         /* must reuse cv if autoloaded */
12055             cv_undef(cv);
12056         else {
12057             cv = MUTABLE_CV(newSV_type(SVt_PVCV));
12058             if (name) {
12059                 GvCV_set(gv,cv);
12060                 GvCVGEN(gv) = 0;
12061                 if (HvENAME_HEK(GvSTASH(gv)))
12062                     gv_method_changed(gv); /* newXS */
12063             }
12064         }
12065         assert(cv);
12066         assert(SvREFCNT((SV*)cv) != 0);
12067
12068         CvGV_set(cv, gv);
12069         if(filename) {
12070             /* XSUBs can't be perl lang/perl5db.pl debugged
12071             if (PERLDB_LINE_OR_SAVESRC)
12072                 (void)gv_fetchfile(filename); */
12073             assert(!CvDYNFILE(cv)); /* cv_undef should have turned it off */
12074             if (flags & XS_DYNAMIC_FILENAME) {
12075                 CvDYNFILE_on(cv);
12076                 CvFILE(cv) = savepv(filename);
12077             } else {
12078             /* NOTE: not copied, as it is expected to be an external constant string */
12079                 CvFILE(cv) = (char *)filename;
12080             }
12081         } else {
12082             assert((flags & XS_DYNAMIC_FILENAME) == 0 && PL_xsubfilename);
12083             CvFILE(cv) = (char*)PL_xsubfilename;
12084         }
12085         CvISXSUB_on(cv);
12086         CvXSUB(cv) = subaddr;
12087 #ifndef PERL_IMPLICIT_CONTEXT
12088         CvHSCXT(cv) = &PL_stack_sp;
12089 #else
12090         PoisonPADLIST(cv);
12091 #endif
12092
12093         if (name)
12094             evanescent = process_special_blocks(0, name, gv, cv);
12095         else
12096             CvANON_on(cv);
12097     } /* <- not a conditional branch */
12098
12099     assert(cv);
12100     assert(evanescent || SvREFCNT((SV*)cv) != 0);
12101
12102     if (!evanescent) sv_setpv(MUTABLE_SV(cv), proto);
12103     if (interleave) LEAVE;
12104     assert(evanescent || SvREFCNT((SV*)cv) != 0);
12105     return cv;
12106 }
12107
12108 /* Add a stub CV to a typeglob.
12109  * This is the implementation of a forward declaration, 'sub foo';'
12110  */
12111
12112 CV *
12113 Perl_newSTUB(pTHX_ GV *gv, bool fake)
12114 {
12115     CV *cv = MUTABLE_CV(newSV_type(SVt_PVCV));
12116     GV *cvgv;
12117     PERL_ARGS_ASSERT_NEWSTUB;
12118     assert(!GvCVu(gv));
12119     GvCV_set(gv, cv);
12120     GvCVGEN(gv) = 0;
12121     if (!fake && GvSTASH(gv) && HvENAME_HEK(GvSTASH(gv)))
12122         gv_method_changed(gv);
12123     if (SvFAKE(gv)) {
12124         cvgv = gv_fetchsv((SV *)gv, GV_ADDMULTI, SVt_PVCV);
12125         SvFAKE_off(cvgv);
12126     }
12127     else cvgv = gv;
12128     CvGV_set(cv, cvgv);
12129     CvFILE_set_from_cop(cv, PL_curcop);
12130     CvSTASH_set(cv, PL_curstash);
12131     GvMULTI_on(gv);
12132     return cv;
12133 }
12134
12135 void
12136 Perl_newFORM(pTHX_ I32 floor, OP *o, OP *block)
12137 {
12138     CV *cv;
12139     GV *gv;
12140     OP *root;
12141     OP *start;
12142
12143     if (PL_parser && PL_parser->error_count) {
12144         op_free(block);
12145         goto finish;
12146     }
12147
12148     gv = o
12149         ? gv_fetchsv(cSVOPo->op_sv, GV_ADD, SVt_PVFM)
12150         : gv_fetchpvs("STDOUT", GV_ADD|GV_NOTQUAL, SVt_PVFM);
12151
12152     GvMULTI_on(gv);
12153     if ((cv = GvFORM(gv))) {
12154         if (ckWARN(WARN_REDEFINE)) {
12155             const line_t oldline = CopLINE(PL_curcop);
12156             if (PL_parser && PL_parser->copline != NOLINE)
12157                 CopLINE_set(PL_curcop, PL_parser->copline);
12158             if (o) {
12159                 Perl_warner(aTHX_ packWARN(WARN_REDEFINE),
12160                             "Format %" SVf " redefined", SVfARG(cSVOPo->op_sv));
12161             } else {
12162                 /* diag_listed_as: Format %s redefined */
12163                 Perl_warner(aTHX_ packWARN(WARN_REDEFINE),
12164                             "Format STDOUT redefined");
12165             }
12166             CopLINE_set(PL_curcop, oldline);
12167         }
12168         SvREFCNT_dec(cv);
12169     }
12170     cv = PL_compcv;
12171     GvFORM(gv) = (CV *)SvREFCNT_inc_simple_NN(cv);
12172     CvGV_set(cv, gv);
12173     CvFILE_set_from_cop(cv, PL_curcop);
12174
12175
12176     root = newUNOP(OP_LEAVEWRITE, 0, scalarseq(block));
12177     CvROOT(cv) = root;
12178     start = LINKLIST(root);
12179     root->op_next = 0;
12180     S_process_optree(aTHX_ cv, root, start);
12181     cv_forget_slab(cv);
12182
12183   finish:
12184     op_free(o);
12185     if (PL_parser)
12186         PL_parser->copline = NOLINE;
12187     LEAVE_SCOPE(floor);
12188     PL_compiling.cop_seq = 0;
12189 }
12190
12191 OP *
12192 Perl_newANONLIST(pTHX_ OP *o)
12193 {
12194     return op_convert_list(OP_ANONLIST, OPf_SPECIAL, o);
12195 }
12196
12197 OP *
12198 Perl_newANONHASH(pTHX_ OP *o)
12199 {
12200     return op_convert_list(OP_ANONHASH, OPf_SPECIAL, o);
12201 }
12202
12203 OP *
12204 Perl_newANONSUB(pTHX_ I32 floor, OP *proto, OP *block)
12205 {
12206     return newANONATTRSUB(floor, proto, NULL, block);
12207 }
12208
12209 OP *
12210 Perl_newANONATTRSUB(pTHX_ I32 floor, OP *proto, OP *attrs, OP *block)
12211 {
12212     SV * const cv = MUTABLE_SV(newATTRSUB(floor, 0, proto, attrs, block));
12213     OP * anoncode =
12214         newSVOP(OP_ANONCODE, 0,
12215                 cv);
12216     if (CvANONCONST(cv))
12217         anoncode = newUNOP(OP_ANONCONST, 0,
12218                            op_convert_list(OP_ENTERSUB,
12219                                            OPf_STACKED|OPf_WANT_SCALAR,
12220                                            anoncode));
12221     return newUNOP(OP_REFGEN, 0, anoncode);
12222 }
12223
12224 OP *
12225 Perl_oopsAV(pTHX_ OP *o)
12226 {
12227
12228     PERL_ARGS_ASSERT_OOPSAV;
12229
12230     switch (o->op_type) {
12231     case OP_PADSV:
12232     case OP_PADHV:
12233         OpTYPE_set(o, OP_PADAV);
12234         return ref(o, OP_RV2AV);
12235
12236     case OP_RV2SV:
12237     case OP_RV2HV:
12238         OpTYPE_set(o, OP_RV2AV);
12239         ref(o, OP_RV2AV);
12240         break;
12241
12242     default:
12243         Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL), "oops: oopsAV");
12244         break;
12245     }
12246     return o;
12247 }
12248
12249 OP *
12250 Perl_oopsHV(pTHX_ OP *o)
12251 {
12252
12253     PERL_ARGS_ASSERT_OOPSHV;
12254
12255     switch (o->op_type) {
12256     case OP_PADSV:
12257     case OP_PADAV:
12258         OpTYPE_set(o, OP_PADHV);
12259         return ref(o, OP_RV2HV);
12260
12261     case OP_RV2SV:
12262     case OP_RV2AV:
12263         OpTYPE_set(o, OP_RV2HV);
12264         /* rv2hv steals the bottom bit for its own uses */
12265         o->op_private &= ~OPpARG1_MASK;
12266         ref(o, OP_RV2HV);
12267         break;
12268
12269     default:
12270         Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL), "oops: oopsHV");
12271         break;
12272     }
12273     return o;
12274 }
12275
12276 OP *
12277 Perl_newAVREF(pTHX_ OP *o)
12278 {
12279
12280     PERL_ARGS_ASSERT_NEWAVREF;
12281
12282     if (o->op_type == OP_PADANY) {
12283         OpTYPE_set(o, OP_PADAV);
12284         return o;
12285     }
12286     else if ((o->op_type == OP_RV2AV || o->op_type == OP_PADAV)) {
12287         Perl_croak(aTHX_ "Can't use an array as a reference");
12288     }
12289     return newUNOP(OP_RV2AV, 0, scalar(o));
12290 }
12291
12292 OP *
12293 Perl_newGVREF(pTHX_ I32 type, OP *o)
12294 {
12295     if (type == OP_MAPSTART || type == OP_GREPSTART || type == OP_SORT)
12296         return newUNOP(OP_NULL, 0, o);
12297     return ref(newUNOP(OP_RV2GV, OPf_REF, o), type);
12298 }
12299
12300 OP *
12301 Perl_newHVREF(pTHX_ OP *o)
12302 {
12303
12304     PERL_ARGS_ASSERT_NEWHVREF;
12305
12306     if (o->op_type == OP_PADANY) {
12307         OpTYPE_set(o, OP_PADHV);
12308         return o;
12309     }
12310     else if ((o->op_type == OP_RV2HV || o->op_type == OP_PADHV)) {
12311         Perl_croak(aTHX_ "Can't use a hash as a reference");
12312     }
12313     return newUNOP(OP_RV2HV, 0, scalar(o));
12314 }
12315
12316 OP *
12317 Perl_newCVREF(pTHX_ I32 flags, OP *o)
12318 {
12319     if (o->op_type == OP_PADANY) {
12320         OpTYPE_set(o, OP_PADCV);
12321     }
12322     return newUNOP(OP_RV2CV, flags, scalar(o));
12323 }
12324
12325 OP *
12326 Perl_newSVREF(pTHX_ OP *o)
12327 {
12328
12329     PERL_ARGS_ASSERT_NEWSVREF;
12330
12331     if (o->op_type == OP_PADANY) {
12332         OpTYPE_set(o, OP_PADSV);
12333         scalar(o);
12334         return o;
12335     }
12336     return newUNOP(OP_RV2SV, 0, scalar(o));
12337 }
12338
12339 /* Check routines. See the comments at the top of this file for details
12340  * on when these are called */
12341
12342 OP *
12343 Perl_ck_anoncode(pTHX_ OP *o)
12344 {
12345     PERL_ARGS_ASSERT_CK_ANONCODE;
12346
12347     cSVOPo->op_targ = pad_add_anon((CV*)cSVOPo->op_sv, o->op_type);
12348     cSVOPo->op_sv = NULL;
12349     return o;
12350 }
12351
12352 static void
12353 S_io_hints(pTHX_ OP *o)
12354 {
12355 #if O_BINARY != 0 || O_TEXT != 0
12356     HV * const table =
12357         PL_hints & HINT_LOCALIZE_HH ? GvHV(PL_hintgv) : NULL;;
12358     if (table) {
12359         SV **svp = hv_fetchs(table, "open_IN", FALSE);
12360         if (svp && *svp) {
12361             STRLEN len = 0;
12362             const char *d = SvPV_const(*svp, len);
12363             const I32 mode = mode_from_discipline(d, len);
12364             /* bit-and:ing with zero O_BINARY or O_TEXT would be useless. */
12365 #  if O_BINARY != 0
12366             if (mode & O_BINARY)
12367                 o->op_private |= OPpOPEN_IN_RAW;
12368 #  endif
12369 #  if O_TEXT != 0
12370             if (mode & O_TEXT)
12371                 o->op_private |= OPpOPEN_IN_CRLF;
12372 #  endif
12373         }
12374
12375         svp = hv_fetchs(table, "open_OUT", FALSE);
12376         if (svp && *svp) {
12377             STRLEN len = 0;
12378             const char *d = SvPV_const(*svp, len);
12379             const I32 mode = mode_from_discipline(d, len);
12380             /* bit-and:ing with zero O_BINARY or O_TEXT would be useless. */
12381 #  if O_BINARY != 0
12382             if (mode & O_BINARY)
12383                 o->op_private |= OPpOPEN_OUT_RAW;
12384 #  endif
12385 #  if O_TEXT != 0
12386             if (mode & O_TEXT)
12387                 o->op_private |= OPpOPEN_OUT_CRLF;
12388 #  endif
12389         }
12390     }
12391 #else
12392     PERL_UNUSED_CONTEXT;
12393     PERL_UNUSED_ARG(o);
12394 #endif
12395 }
12396
12397 OP *
12398 Perl_ck_backtick(pTHX_ OP *o)
12399 {
12400     GV *gv;
12401     OP *newop = NULL;
12402     OP *sibl;
12403     PERL_ARGS_ASSERT_CK_BACKTICK;
12404     o = ck_fun(o);
12405     /* qx and `` have a null pushmark; CORE::readpipe has only one kid. */
12406     if (o->op_flags & OPf_KIDS && (sibl = OpSIBLING(cUNOPo->op_first))
12407      && (gv = gv_override("readpipe",8)))
12408     {
12409         /* detach rest of siblings from o and its first child */
12410         op_sibling_splice(o, cUNOPo->op_first, -1, NULL);
12411         newop = S_new_entersubop(aTHX_ gv, sibl);
12412     }
12413     else if (!(o->op_flags & OPf_KIDS))
12414         newop = newUNOP(OP_BACKTICK, 0, newDEFSVOP());
12415     if (newop) {
12416         op_free(o);
12417         return newop;
12418     }
12419     S_io_hints(aTHX_ o);
12420     return o;
12421 }
12422
12423 OP *
12424 Perl_ck_bitop(pTHX_ OP *o)
12425 {
12426     PERL_ARGS_ASSERT_CK_BITOP;
12427
12428     o->op_private = (U8)(PL_hints & HINT_INTEGER);
12429
12430     if (!(o->op_flags & OPf_STACKED) /* Not an assignment */
12431             && OP_IS_INFIX_BIT(o->op_type))
12432     {
12433         const OP * const left = cBINOPo->op_first;
12434         const OP * const right = OpSIBLING(left);
12435         if ((OP_IS_NUMCOMPARE(left->op_type) &&
12436                 (left->op_flags & OPf_PARENS) == 0) ||
12437             (OP_IS_NUMCOMPARE(right->op_type) &&
12438                 (right->op_flags & OPf_PARENS) == 0))
12439             Perl_ck_warner(aTHX_ packWARN(WARN_PRECEDENCE),
12440                           "Possible precedence problem on bitwise %s operator",
12441                            o->op_type ==  OP_BIT_OR
12442                          ||o->op_type == OP_NBIT_OR  ? "|"
12443                         :  o->op_type ==  OP_BIT_AND
12444                          ||o->op_type == OP_NBIT_AND ? "&"
12445                         :  o->op_type ==  OP_BIT_XOR
12446                          ||o->op_type == OP_NBIT_XOR ? "^"
12447                         :  o->op_type == OP_SBIT_OR  ? "|."
12448                         :  o->op_type == OP_SBIT_AND ? "&." : "^."
12449                            );
12450     }
12451     return o;
12452 }
12453
12454 PERL_STATIC_INLINE bool
12455 is_dollar_bracket(pTHX_ const OP * const o)
12456 {
12457     const OP *kid;
12458     PERL_UNUSED_CONTEXT;
12459     return o->op_type == OP_RV2SV && o->op_flags & OPf_KIDS
12460         && (kid = cUNOPx(o)->op_first)
12461         && kid->op_type == OP_GV
12462         && strEQ(GvNAME(cGVOPx_gv(kid)), "[");
12463 }
12464
12465 /* for lt, gt, le, ge, eq, ne and their i_ variants */
12466
12467 OP *
12468 Perl_ck_cmp(pTHX_ OP *o)
12469 {
12470     bool is_eq;
12471     bool neg;
12472     bool reverse;
12473     bool iv0;
12474     OP *indexop, *constop, *start;
12475     SV *sv;
12476     IV iv;
12477
12478     PERL_ARGS_ASSERT_CK_CMP;
12479
12480     is_eq = (   o->op_type == OP_EQ
12481              || o->op_type == OP_NE
12482              || o->op_type == OP_I_EQ
12483              || o->op_type == OP_I_NE);
12484
12485     if (!is_eq && ckWARN(WARN_SYNTAX)) {
12486         const OP *kid = cUNOPo->op_first;
12487         if (kid &&
12488             (
12489                 (   is_dollar_bracket(aTHX_ kid)
12490                  && OpSIBLING(kid) && OpSIBLING(kid)->op_type == OP_CONST
12491                 )
12492              || (   kid->op_type == OP_CONST
12493                  && (kid = OpSIBLING(kid)) && is_dollar_bracket(aTHX_ kid)
12494                 )
12495            )
12496         )
12497             Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
12498                         "$[ used in %s (did you mean $] ?)", OP_DESC(o));
12499     }
12500
12501     /* convert (index(...) == -1) and variations into
12502      *   (r)index/BOOL(,NEG)
12503      */
12504
12505     reverse = FALSE;
12506
12507     indexop = cUNOPo->op_first;
12508     constop = OpSIBLING(indexop);
12509     start = NULL;
12510     if (indexop->op_type == OP_CONST) {
12511         constop = indexop;
12512         indexop = OpSIBLING(constop);
12513         start = constop;
12514         reverse = TRUE;
12515     }
12516
12517     if (indexop->op_type != OP_INDEX && indexop->op_type != OP_RINDEX)
12518         return o;
12519
12520     /* ($lex = index(....)) == -1 */
12521     if (indexop->op_private & OPpTARGET_MY)
12522         return o;
12523
12524     if (constop->op_type != OP_CONST)
12525         return o;
12526
12527     sv = cSVOPx_sv(constop);
12528     if (!(sv && SvIOK_notUV(sv)))
12529         return o;
12530
12531     iv = SvIVX(sv);
12532     if (iv != -1 && iv != 0)
12533         return o;
12534     iv0 = (iv == 0);
12535
12536     if (o->op_type == OP_LT || o->op_type == OP_I_LT) {
12537         if (!(iv0 ^ reverse))
12538             return o;
12539         neg = iv0;
12540     }
12541     else if (o->op_type == OP_LE || o->op_type == OP_I_LE) {
12542         if (iv0 ^ reverse)
12543             return o;
12544         neg = !iv0;
12545     }
12546     else if (o->op_type == OP_GE || o->op_type == OP_I_GE) {
12547         if (!(iv0 ^ reverse))
12548             return o;
12549         neg = !iv0;
12550     }
12551     else if (o->op_type == OP_GT || o->op_type == OP_I_GT) {
12552         if (iv0 ^ reverse)
12553             return o;
12554         neg = iv0;
12555     }
12556     else if (o->op_type == OP_EQ || o->op_type == OP_I_EQ) {
12557         if (iv0)
12558             return o;
12559         neg = TRUE;
12560     }
12561     else {
12562         assert(o->op_type == OP_NE || o->op_type == OP_I_NE);
12563         if (iv0)
12564             return o;
12565         neg = FALSE;
12566     }
12567
12568     indexop->op_flags &= ~OPf_PARENS;
12569     indexop->op_flags |= (o->op_flags & OPf_PARENS);
12570     indexop->op_private |= OPpTRUEBOOL;
12571     if (neg)
12572         indexop->op_private |= OPpINDEX_BOOLNEG;
12573     /* cut out the index op and free the eq,const ops */
12574     (void)op_sibling_splice(o, start, 1, NULL);
12575     op_free(o);
12576
12577     return indexop;
12578 }
12579
12580
12581 OP *
12582 Perl_ck_concat(pTHX_ OP *o)
12583 {
12584     const OP * const kid = cUNOPo->op_first;
12585
12586     PERL_ARGS_ASSERT_CK_CONCAT;
12587     PERL_UNUSED_CONTEXT;
12588
12589     /* reuse the padtmp returned by the concat child */
12590     if (kid->op_type == OP_CONCAT && !(kid->op_private & OPpTARGET_MY) &&
12591             !(kUNOP->op_first->op_flags & OPf_MOD))
12592     {
12593         o->op_flags |= OPf_STACKED;
12594         o->op_private |= OPpCONCAT_NESTED;
12595     }
12596     return o;
12597 }
12598
12599 OP *
12600 Perl_ck_spair(pTHX_ OP *o)
12601 {
12602
12603     PERL_ARGS_ASSERT_CK_SPAIR;
12604
12605     if (o->op_flags & OPf_KIDS) {
12606         OP* newop;
12607         OP* kid;
12608         OP* kidkid;
12609         const OPCODE type = o->op_type;
12610         o = modkids(ck_fun(o), type);
12611         kid    = cUNOPo->op_first;
12612         kidkid = kUNOP->op_first;
12613         newop = OpSIBLING(kidkid);
12614         if (newop) {
12615             const OPCODE type = newop->op_type;
12616             if (OpHAS_SIBLING(newop))
12617                 return o;
12618             if (o->op_type == OP_REFGEN
12619              && (  type == OP_RV2CV
12620                 || (  !(newop->op_flags & OPf_PARENS)
12621                    && (  type == OP_RV2AV || type == OP_PADAV
12622                       || type == OP_RV2HV || type == OP_PADHV))))
12623                 NOOP; /* OK (allow srefgen for \@a and \%h) */
12624             else if (OP_GIMME(newop,0) != G_SCALAR)
12625                 return o;
12626         }
12627         /* excise first sibling */
12628         op_sibling_splice(kid, NULL, 1, NULL);
12629         op_free(kidkid);
12630     }
12631     /* transforms OP_REFGEN into OP_SREFGEN, OP_CHOP into OP_SCHOP,
12632      * and OP_CHOMP into OP_SCHOMP */
12633     o->op_ppaddr = PL_ppaddr[++o->op_type];
12634     return ck_fun(o);
12635 }
12636
12637 OP *
12638 Perl_ck_delete(pTHX_ OP *o)
12639 {
12640     PERL_ARGS_ASSERT_CK_DELETE;
12641
12642     o = ck_fun(o);
12643     o->op_private = 0;
12644     if (o->op_flags & OPf_KIDS) {
12645         OP * const kid = cUNOPo->op_first;
12646         switch (kid->op_type) {
12647         case OP_ASLICE:
12648             o->op_flags |= OPf_SPECIAL;
12649             /* FALLTHROUGH */
12650         case OP_HSLICE:
12651             o->op_private |= OPpSLICE;
12652             break;
12653         case OP_AELEM:
12654             o->op_flags |= OPf_SPECIAL;
12655             /* FALLTHROUGH */
12656         case OP_HELEM:
12657             break;
12658         case OP_KVASLICE:
12659             o->op_flags |= OPf_SPECIAL;
12660             /* FALLTHROUGH */
12661         case OP_KVHSLICE:
12662             o->op_private |= OPpKVSLICE;
12663             break;
12664         default:
12665             Perl_croak(aTHX_ "delete argument is not a HASH or ARRAY "
12666                              "element or slice");
12667         }
12668         if (kid->op_private & OPpLVAL_INTRO)
12669             o->op_private |= OPpLVAL_INTRO;
12670         op_null(kid);
12671     }
12672     return o;
12673 }
12674
12675 OP *
12676 Perl_ck_eof(pTHX_ OP *o)
12677 {
12678     PERL_ARGS_ASSERT_CK_EOF;
12679
12680     if (o->op_flags & OPf_KIDS) {
12681         OP *kid;
12682         if (cLISTOPo->op_first->op_type == OP_STUB) {
12683             OP * const newop
12684                 = newUNOP(o->op_type, OPf_SPECIAL, newGVOP(OP_GV, 0, PL_argvgv));
12685             op_free(o);
12686             o = newop;
12687         }
12688         o = ck_fun(o);
12689         kid = cLISTOPo->op_first;
12690         if (kid->op_type == OP_RV2GV)
12691             kid->op_private |= OPpALLOW_FAKE;
12692     }
12693     return o;
12694 }
12695
12696
12697 OP *
12698 Perl_ck_eval(pTHX_ OP *o)
12699 {
12700
12701     PERL_ARGS_ASSERT_CK_EVAL;
12702
12703     PL_hints |= HINT_BLOCK_SCOPE;
12704     if (o->op_flags & OPf_KIDS) {
12705         SVOP * const kid = (SVOP*)cUNOPo->op_first;
12706         assert(kid);
12707
12708         if (o->op_type == OP_ENTERTRY) {
12709             LOGOP *enter;
12710
12711             /* cut whole sibling chain free from o */
12712             op_sibling_splice(o, NULL, -1, NULL);
12713             op_free(o);
12714
12715             enter = alloc_LOGOP(OP_ENTERTRY, NULL, NULL);
12716
12717             /* establish postfix order */
12718             enter->op_next = (OP*)enter;
12719
12720             o = op_prepend_elem(OP_LINESEQ, (OP*)enter, (OP*)kid);
12721             OpTYPE_set(o, OP_LEAVETRY);
12722             enter->op_other = o;
12723             return o;
12724         }
12725         else {
12726             scalar((OP*)kid);
12727             S_set_haseval(aTHX);
12728         }
12729     }
12730     else {
12731         const U8 priv = o->op_private;
12732         op_free(o);
12733         /* the newUNOP will recursively call ck_eval(), which will handle
12734          * all the stuff at the end of this function, like adding
12735          * OP_HINTSEVAL
12736          */
12737         return newUNOP(OP_ENTEREVAL, priv <<8, newDEFSVOP());
12738     }
12739     o->op_targ = (PADOFFSET)PL_hints;
12740     if (o->op_private & OPpEVAL_BYTES) o->op_targ &= ~HINT_UTF8;
12741     if ((PL_hints & HINT_LOCALIZE_HH) != 0
12742      && !(o->op_private & OPpEVAL_COPHH) && GvHV(PL_hintgv)) {
12743         /* Store a copy of %^H that pp_entereval can pick up. */
12744         HV *hh = hv_copy_hints_hv(GvHV(PL_hintgv));
12745         OP *hhop;
12746         STOREFEATUREBITSHH(hh);
12747         hhop = newSVOP(OP_HINTSEVAL, 0, MUTABLE_SV(hh));
12748         /* append hhop to only child  */
12749         op_sibling_splice(o, cUNOPo->op_first, 0, hhop);
12750
12751         o->op_private |= OPpEVAL_HAS_HH;
12752     }
12753     if (!(o->op_private & OPpEVAL_BYTES)
12754          && FEATURE_UNIEVAL_IS_ENABLED)
12755             o->op_private |= OPpEVAL_UNICODE;
12756     return o;
12757 }
12758
12759 OP *
12760 Perl_ck_exec(pTHX_ OP *o)
12761 {
12762     PERL_ARGS_ASSERT_CK_EXEC;
12763
12764     if (o->op_flags & OPf_STACKED) {
12765         OP *kid;
12766         o = ck_fun(o);
12767         kid = OpSIBLING(cUNOPo->op_first);
12768         if (kid->op_type == OP_RV2GV)
12769             op_null(kid);
12770     }
12771     else
12772         o = listkids(o);
12773     return o;
12774 }
12775
12776 OP *
12777 Perl_ck_exists(pTHX_ OP *o)
12778 {
12779     PERL_ARGS_ASSERT_CK_EXISTS;
12780
12781     o = ck_fun(o);
12782     if (o->op_flags & OPf_KIDS) {
12783         OP * const kid = cUNOPo->op_first;
12784         if (kid->op_type == OP_ENTERSUB) {
12785             (void) ref(kid, o->op_type);
12786             if (kid->op_type != OP_RV2CV
12787                         && !(PL_parser && PL_parser->error_count))
12788                 Perl_croak(aTHX_
12789                           "exists argument is not a subroutine name");
12790             o->op_private |= OPpEXISTS_SUB;
12791         }
12792         else if (kid->op_type == OP_AELEM)
12793             o->op_flags |= OPf_SPECIAL;
12794         else if (kid->op_type != OP_HELEM)
12795             Perl_croak(aTHX_ "exists argument is not a HASH or ARRAY "
12796                              "element or a subroutine");
12797         op_null(kid);
12798     }
12799     return o;
12800 }
12801
12802 OP *
12803 Perl_ck_rvconst(pTHX_ OP *o)
12804 {
12805     SVOP * const kid = (SVOP*)cUNOPo->op_first;
12806
12807     PERL_ARGS_ASSERT_CK_RVCONST;
12808
12809     if (o->op_type == OP_RV2HV)
12810         /* rv2hv steals the bottom bit for its own uses */
12811         o->op_private &= ~OPpARG1_MASK;
12812
12813     o->op_private |= (PL_hints & HINT_STRICT_REFS);
12814
12815     if (kid->op_type == OP_CONST) {
12816         int iscv;
12817         GV *gv;
12818         SV * const kidsv = kid->op_sv;
12819
12820         /* Is it a constant from cv_const_sv()? */
12821         if ((SvROK(kidsv) || isGV_with_GP(kidsv)) && SvREADONLY(kidsv)) {
12822             return o;
12823         }
12824         if (SvTYPE(kidsv) == SVt_PVAV) return o;
12825         if ((o->op_private & HINT_STRICT_REFS) && (kid->op_private & OPpCONST_BARE)) {
12826             const char *badthing;
12827             switch (o->op_type) {
12828             case OP_RV2SV:
12829                 badthing = "a SCALAR";
12830                 break;
12831             case OP_RV2AV:
12832                 badthing = "an ARRAY";
12833                 break;
12834             case OP_RV2HV:
12835                 badthing = "a HASH";
12836                 break;
12837             default:
12838                 badthing = NULL;
12839                 break;
12840             }
12841             if (badthing)
12842                 Perl_croak(aTHX_
12843                            "Can't use bareword (\"%" SVf "\") as %s ref while \"strict refs\" in use",
12844                            SVfARG(kidsv), badthing);
12845         }
12846         /*
12847          * This is a little tricky.  We only want to add the symbol if we
12848          * didn't add it in the lexer.  Otherwise we get duplicate strict
12849          * warnings.  But if we didn't add it in the lexer, we must at
12850          * least pretend like we wanted to add it even if it existed before,
12851          * or we get possible typo warnings.  OPpCONST_ENTERED says
12852          * whether the lexer already added THIS instance of this symbol.
12853          */
12854         iscv = o->op_type == OP_RV2CV ? GV_NOEXPAND|GV_ADDMULTI : 0;
12855         gv = gv_fetchsv(kidsv,
12856                 o->op_type == OP_RV2CV
12857                         && o->op_private & OPpMAY_RETURN_CONSTANT
12858                     ? GV_NOEXPAND
12859                     : iscv | !(kid->op_private & OPpCONST_ENTERED),
12860                 iscv
12861                     ? SVt_PVCV
12862                     : o->op_type == OP_RV2SV
12863                         ? SVt_PV
12864                         : o->op_type == OP_RV2AV
12865                             ? SVt_PVAV
12866                             : o->op_type == OP_RV2HV
12867                                 ? SVt_PVHV
12868                                 : SVt_PVGV);
12869         if (gv) {
12870             if (!isGV(gv)) {
12871                 assert(iscv);
12872                 assert(SvROK(gv));
12873                 if (!(o->op_private & OPpMAY_RETURN_CONSTANT)
12874                   && SvTYPE(SvRV(gv)) != SVt_PVCV)
12875                     gv_fetchsv(kidsv, GV_ADDMULTI, SVt_PVCV);
12876             }
12877             OpTYPE_set(kid, OP_GV);
12878             SvREFCNT_dec(kid->op_sv);
12879 #ifdef USE_ITHREADS
12880             /* XXX hack: dependence on sizeof(PADOP) <= sizeof(SVOP) */
12881             STATIC_ASSERT_STMT(sizeof(PADOP) <= sizeof(SVOP));
12882             kPADOP->op_padix = pad_alloc(OP_GV, SVf_READONLY);
12883             SvREFCNT_dec(PAD_SVl(kPADOP->op_padix));
12884             PAD_SETSV(kPADOP->op_padix, MUTABLE_SV(SvREFCNT_inc_simple_NN(gv)));
12885 #else
12886             kid->op_sv = SvREFCNT_inc_simple_NN(gv);
12887 #endif
12888             kid->op_private = 0;
12889             /* FAKE globs in the symbol table cause weird bugs (#77810) */
12890             SvFAKE_off(gv);
12891         }
12892     }
12893     return o;
12894 }
12895
12896 OP *
12897 Perl_ck_ftst(pTHX_ OP *o)
12898 {
12899     const I32 type = o->op_type;
12900
12901     PERL_ARGS_ASSERT_CK_FTST;
12902
12903     if (o->op_flags & OPf_REF) {
12904         NOOP;
12905     }
12906     else if (o->op_flags & OPf_KIDS && cUNOPo->op_first->op_type != OP_STUB) {
12907         SVOP * const kid = (SVOP*)cUNOPo->op_first;
12908         const OPCODE kidtype = kid->op_type;
12909
12910         if (kidtype == OP_CONST && (kid->op_private & OPpCONST_BARE)
12911          && !kid->op_folded) {
12912             OP * const newop = newGVOP(type, OPf_REF,
12913                 gv_fetchsv(kid->op_sv, GV_ADD, SVt_PVIO));
12914             op_free(o);
12915             return newop;
12916         }
12917
12918         if ((kidtype == OP_RV2AV || kidtype == OP_PADAV) && ckWARN(WARN_SYNTAX)) {
12919             SV *name = S_op_varname_subscript(aTHX_ (OP*)kid, 2);
12920             if (name) {
12921                 /* diag_listed_as: Array passed to stat will be coerced to a scalar%s */
12922                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX), "%s (did you want stat %" SVf "?)",
12923                             array_passed_to_stat, name);
12924             }
12925             else {
12926                 /* diag_listed_as: Array passed to stat will be coerced to a scalar%s */
12927                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX), "%s", array_passed_to_stat);
12928             }
12929        }
12930         scalar((OP *) kid);
12931         if ((PL_hints & HINT_FILETEST_ACCESS) && OP_IS_FILETEST_ACCESS(o->op_type))
12932             o->op_private |= OPpFT_ACCESS;
12933         if (OP_IS_FILETEST(type)
12934             && OP_IS_FILETEST(kidtype)
12935         ) {
12936             o->op_private |= OPpFT_STACKED;
12937             kid->op_private |= OPpFT_STACKING;
12938             if (kidtype == OP_FTTTY && (
12939                    !(kid->op_private & OPpFT_STACKED)
12940                 || kid->op_private & OPpFT_AFTER_t
12941                ))
12942                 o->op_private |= OPpFT_AFTER_t;
12943         }
12944     }
12945     else {
12946         op_free(o);
12947         if (type == OP_FTTTY)
12948             o = newGVOP(type, OPf_REF, PL_stdingv);
12949         else
12950             o = newUNOP(type, 0, newDEFSVOP());
12951     }
12952     return o;
12953 }
12954
12955 OP *
12956 Perl_ck_fun(pTHX_ OP *o)
12957 {
12958     const int type = o->op_type;
12959     I32 oa = PL_opargs[type] >> OASHIFT;
12960
12961     PERL_ARGS_ASSERT_CK_FUN;
12962
12963     if (o->op_flags & OPf_STACKED) {
12964         if ((oa & OA_OPTIONAL) && (oa >> 4) && !((oa >> 4) & OA_OPTIONAL))
12965             oa &= ~OA_OPTIONAL;
12966         else
12967             return no_fh_allowed(o);
12968     }
12969
12970     if (o->op_flags & OPf_KIDS) {
12971         OP *prev_kid = NULL;
12972         OP *kid = cLISTOPo->op_first;
12973         I32 numargs = 0;
12974         bool seen_optional = FALSE;
12975
12976         if (kid->op_type == OP_PUSHMARK ||
12977             (kid->op_type == OP_NULL && kid->op_targ == OP_PUSHMARK))
12978         {
12979             prev_kid = kid;
12980             kid = OpSIBLING(kid);
12981         }
12982         if (kid && kid->op_type == OP_COREARGS) {
12983             bool optional = FALSE;
12984             while (oa) {
12985                 numargs++;
12986                 if (oa & OA_OPTIONAL) optional = TRUE;
12987                 oa = oa >> 4;
12988             }
12989             if (optional) o->op_private |= numargs;
12990             return o;
12991         }
12992
12993         while (oa) {
12994             if (oa & OA_OPTIONAL || (oa & 7) == OA_LIST) {
12995                 if (!kid && !seen_optional && PL_opargs[type] & OA_DEFGV) {
12996                     kid = newDEFSVOP();
12997                     /* append kid to chain */
12998                     op_sibling_splice(o, prev_kid, 0, kid);
12999                 }
13000                 seen_optional = TRUE;
13001             }
13002             if (!kid) break;
13003
13004             numargs++;
13005             switch (oa & 7) {
13006             case OA_SCALAR:
13007                 /* list seen where single (scalar) arg expected? */
13008                 if (numargs == 1 && !(oa >> 4)
13009                     && kid->op_type == OP_LIST && type != OP_SCALAR)
13010                 {
13011                     return too_many_arguments_pv(o,PL_op_desc[type], 0);
13012                 }
13013                 if (type != OP_DELETE) scalar(kid);
13014                 break;
13015             case OA_LIST:
13016                 if (oa < 16) {
13017                     kid = 0;
13018                     continue;
13019                 }
13020                 else
13021                     list(kid);
13022                 break;
13023             case OA_AVREF:
13024                 if ((type == OP_PUSH || type == OP_UNSHIFT)
13025                     && !OpHAS_SIBLING(kid))
13026                     Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX),
13027                                    "Useless use of %s with no values",
13028                                    PL_op_desc[type]);
13029
13030                 if (kid->op_type == OP_CONST
13031                       && (  !SvROK(cSVOPx_sv(kid))
13032                          || SvTYPE(SvRV(cSVOPx_sv(kid))) != SVt_PVAV  )
13033                         )
13034                     bad_type_pv(numargs, "array", o, kid);
13035                 else if (kid->op_type == OP_RV2HV || kid->op_type == OP_PADHV
13036                          || kid->op_type == OP_RV2GV) {
13037                     bad_type_pv(1, "array", o, kid);
13038                 }
13039                 else if (kid->op_type != OP_RV2AV && kid->op_type != OP_PADAV) {
13040                     yyerror_pv(Perl_form(aTHX_ "Experimental %s on scalar is now forbidden",
13041                                          PL_op_desc[type]), 0);
13042                 }
13043                 else {
13044                     op_lvalue(kid, type);
13045                 }
13046                 break;
13047             case OA_HVREF:
13048                 if (kid->op_type != OP_RV2HV && kid->op_type != OP_PADHV)
13049                     bad_type_pv(numargs, "hash", o, kid);
13050                 op_lvalue(kid, type);
13051                 break;
13052             case OA_CVREF:
13053                 {
13054                     /* replace kid with newop in chain */
13055                     OP * const newop =
13056                         S_op_sibling_newUNOP(aTHX_ o, prev_kid, OP_NULL, 0);
13057                     newop->op_next = newop;
13058                     kid = newop;
13059                 }
13060                 break;
13061             case OA_FILEREF:
13062                 if (kid->op_type != OP_GV && kid->op_type != OP_RV2GV) {
13063                     if (kid->op_type == OP_CONST &&
13064                         (kid->op_private & OPpCONST_BARE))
13065                     {
13066                         OP * const newop = newGVOP(OP_GV, 0,
13067                             gv_fetchsv(((SVOP*)kid)->op_sv, GV_ADD, SVt_PVIO));
13068                         /* replace kid with newop in chain */
13069                         op_sibling_splice(o, prev_kid, 1, newop);
13070                         op_free(kid);
13071                         kid = newop;
13072                     }
13073                     else if (kid->op_type == OP_READLINE) {
13074                         /* neophyte patrol: open(<FH>), close(<FH>) etc. */
13075                         bad_type_pv(numargs, "HANDLE", o, kid);
13076                     }
13077                     else {
13078                         I32 flags = OPf_SPECIAL;
13079                         I32 priv = 0;
13080                         PADOFFSET targ = 0;
13081
13082                         /* is this op a FH constructor? */
13083                         if (is_handle_constructor(o,numargs)) {
13084                             const char *name = NULL;
13085                             STRLEN len = 0;
13086                             U32 name_utf8 = 0;
13087                             bool want_dollar = TRUE;
13088
13089                             flags = 0;
13090                             /* Set a flag to tell rv2gv to vivify
13091                              * need to "prove" flag does not mean something
13092                              * else already - NI-S 1999/05/07
13093                              */
13094                             priv = OPpDEREF;
13095                             if (kid->op_type == OP_PADSV) {
13096                                 PADNAME * const pn
13097                                     = PAD_COMPNAME_SV(kid->op_targ);
13098                                 name = PadnamePV (pn);
13099                                 len  = PadnameLEN(pn);
13100                                 name_utf8 = PadnameUTF8(pn);
13101                             }
13102                             else if (kid->op_type == OP_RV2SV
13103                                      && kUNOP->op_first->op_type == OP_GV)
13104                             {
13105                                 GV * const gv = cGVOPx_gv(kUNOP->op_first);
13106                                 name = GvNAME(gv);
13107                                 len = GvNAMELEN(gv);
13108                                 name_utf8 = GvNAMEUTF8(gv) ? SVf_UTF8 : 0;
13109                             }
13110                             else if (kid->op_type == OP_AELEM
13111                                      || kid->op_type == OP_HELEM)
13112                             {
13113                                  OP *firstop;
13114                                  OP *op = ((BINOP*)kid)->op_first;
13115                                  name = NULL;
13116                                  if (op) {
13117                                       SV *tmpstr = NULL;
13118                                       const char * const a =
13119                                            kid->op_type == OP_AELEM ?
13120                                            "[]" : "{}";
13121                                       if (((op->op_type == OP_RV2AV) ||
13122                                            (op->op_type == OP_RV2HV)) &&
13123                                           (firstop = ((UNOP*)op)->op_first) &&
13124                                           (firstop->op_type == OP_GV)) {
13125                                            /* packagevar $a[] or $h{} */
13126                                            GV * const gv = cGVOPx_gv(firstop);
13127                                            if (gv)
13128                                                 tmpstr =
13129                                                      Perl_newSVpvf(aTHX_
13130                                                                    "%s%c...%c",
13131                                                                    GvNAME(gv),
13132                                                                    a[0], a[1]);
13133                                       }
13134                                       else if (op->op_type == OP_PADAV
13135                                                || op->op_type == OP_PADHV) {
13136                                            /* lexicalvar $a[] or $h{} */
13137                                            const char * const padname =
13138                                                 PAD_COMPNAME_PV(op->op_targ);
13139                                            if (padname)
13140                                                 tmpstr =
13141                                                      Perl_newSVpvf(aTHX_
13142                                                                    "%s%c...%c",
13143                                                                    padname + 1,
13144                                                                    a[0], a[1]);
13145                                       }
13146                                       if (tmpstr) {
13147                                            name = SvPV_const(tmpstr, len);
13148                                            name_utf8 = SvUTF8(tmpstr);
13149                                            sv_2mortal(tmpstr);
13150                                       }
13151                                  }
13152                                  if (!name) {
13153                                       name = "__ANONIO__";
13154                                       len = 10;
13155                                       want_dollar = FALSE;
13156                                  }
13157                                  op_lvalue(kid, type);
13158                             }
13159                             if (name) {
13160                                 SV *namesv;
13161                                 targ = pad_alloc(OP_RV2GV, SVf_READONLY);
13162                                 namesv = PAD_SVl(targ);
13163                                 if (want_dollar && *name != '$')
13164                                     sv_setpvs(namesv, "$");
13165                                 else
13166                                     SvPVCLEAR(namesv);
13167                                 sv_catpvn(namesv, name, len);
13168                                 if ( name_utf8 ) SvUTF8_on(namesv);
13169                             }
13170                         }
13171                         scalar(kid);
13172                         kid = S_op_sibling_newUNOP(aTHX_ o, prev_kid,
13173                                     OP_RV2GV, flags);
13174                         kid->op_targ = targ;
13175                         kid->op_private |= priv;
13176                     }
13177                 }
13178                 scalar(kid);
13179                 break;
13180             case OA_SCALARREF:
13181                 if ((type == OP_UNDEF || type == OP_POS)
13182                     && numargs == 1 && !(oa >> 4)
13183                     && kid->op_type == OP_LIST)
13184                     return too_many_arguments_pv(o,PL_op_desc[type], 0);
13185                 op_lvalue(scalar(kid), type);
13186                 break;
13187             }
13188             oa >>= 4;
13189             prev_kid = kid;
13190             kid = OpSIBLING(kid);
13191         }
13192         /* FIXME - should the numargs or-ing move after the too many
13193          * arguments check? */
13194         o->op_private |= numargs;
13195         if (kid)
13196             return too_many_arguments_pv(o,OP_DESC(o), 0);
13197         listkids(o);
13198     }
13199     else if (PL_opargs[type] & OA_DEFGV) {
13200         /* Ordering of these two is important to keep f_map.t passing.  */
13201         op_free(o);
13202         return newUNOP(type, 0, newDEFSVOP());
13203     }
13204
13205     if (oa) {
13206         while (oa & OA_OPTIONAL)
13207             oa >>= 4;
13208         if (oa && oa != OA_LIST)
13209             return too_few_arguments_pv(o,OP_DESC(o), 0);
13210     }
13211     return o;
13212 }
13213
13214 OP *
13215 Perl_ck_glob(pTHX_ OP *o)
13216 {
13217     GV *gv;
13218
13219     PERL_ARGS_ASSERT_CK_GLOB;
13220
13221     o = ck_fun(o);
13222     if ((o->op_flags & OPf_KIDS) && !OpHAS_SIBLING(cLISTOPo->op_first))
13223         op_append_elem(OP_GLOB, o, newDEFSVOP()); /* glob() => glob($_) */
13224
13225     if (!(o->op_flags & OPf_SPECIAL) && (gv = gv_override("glob", 4)))
13226     {
13227         /* convert
13228          *     glob
13229          *       \ null - const(wildcard)
13230          * into
13231          *     null
13232          *       \ enter
13233          *            \ list
13234          *                 \ mark - glob - rv2cv
13235          *                             |        \ gv(CORE::GLOBAL::glob)
13236          *                             |
13237          *                              \ null - const(wildcard)
13238          */
13239         o->op_flags |= OPf_SPECIAL;
13240         o->op_targ = pad_alloc(OP_GLOB, SVs_PADTMP);
13241         o = S_new_entersubop(aTHX_ gv, o);
13242         o = newUNOP(OP_NULL, 0, o);
13243         o->op_targ = OP_GLOB; /* hint at what it used to be: eg in newWHILEOP */
13244         return o;
13245     }
13246     else o->op_flags &= ~OPf_SPECIAL;
13247 #if !defined(PERL_EXTERNAL_GLOB)
13248     if (!PL_globhook) {
13249         ENTER;
13250         Perl_load_module(aTHX_ PERL_LOADMOD_NOIMPORT,
13251                                newSVpvs("File::Glob"), NULL, NULL, NULL);
13252         LEAVE;
13253     }
13254 #endif /* !PERL_EXTERNAL_GLOB */
13255     gv = (GV *)newSV(0);
13256     gv_init(gv, 0, "", 0, 0);
13257     gv_IOadd(gv);
13258     op_append_elem(OP_GLOB, o, newGVOP(OP_GV, 0, gv));
13259     SvREFCNT_dec_NN(gv); /* newGVOP increased it */
13260     scalarkids(o);
13261     return o;
13262 }
13263
13264 OP *
13265 Perl_ck_grep(pTHX_ OP *o)
13266 {
13267     LOGOP *gwop;
13268     OP *kid;
13269     const OPCODE type = o->op_type == OP_GREPSTART ? OP_GREPWHILE : OP_MAPWHILE;
13270
13271     PERL_ARGS_ASSERT_CK_GREP;
13272
13273     /* don't allocate gwop here, as we may leak it if PL_parser->error_count > 0 */
13274
13275     if (o->op_flags & OPf_STACKED) {
13276         kid = cUNOPx(OpSIBLING(cLISTOPo->op_first))->op_first;
13277         if (kid->op_type != OP_SCOPE && kid->op_type != OP_LEAVE)
13278             return no_fh_allowed(o);
13279         o->op_flags &= ~OPf_STACKED;
13280     }
13281     kid = OpSIBLING(cLISTOPo->op_first);
13282     if (type == OP_MAPWHILE)
13283         list(kid);
13284     else
13285         scalar(kid);
13286     o = ck_fun(o);
13287     if (PL_parser && PL_parser->error_count)
13288         return o;
13289     kid = OpSIBLING(cLISTOPo->op_first);
13290     if (kid->op_type != OP_NULL)
13291         Perl_croak(aTHX_ "panic: ck_grep, type=%u", (unsigned) kid->op_type);
13292     kid = kUNOP->op_first;
13293
13294     gwop = alloc_LOGOP(type, o, LINKLIST(kid));
13295     kid->op_next = (OP*)gwop;
13296     o->op_private = gwop->op_private = 0;
13297     gwop->op_targ = pad_alloc(type, SVs_PADTMP);
13298
13299     kid = OpSIBLING(cLISTOPo->op_first);
13300     for (kid = OpSIBLING(kid); kid; kid = OpSIBLING(kid))
13301         op_lvalue(kid, OP_GREPSTART);
13302
13303     return (OP*)gwop;
13304 }
13305
13306 OP *
13307 Perl_ck_index(pTHX_ OP *o)
13308 {
13309     PERL_ARGS_ASSERT_CK_INDEX;
13310
13311     if (o->op_flags & OPf_KIDS) {
13312         OP *kid = OpSIBLING(cLISTOPo->op_first);        /* get past pushmark */
13313         if (kid)
13314             kid = OpSIBLING(kid);                       /* get past "big" */
13315         if (kid && kid->op_type == OP_CONST) {
13316             const bool save_taint = TAINT_get;
13317             SV *sv = kSVOP->op_sv;
13318             if (   (!SvPOK(sv) || SvNIOKp(sv) || isREGEXP(sv))
13319                 && SvOK(sv) && !SvROK(sv))
13320             {
13321                 sv = newSV(0);
13322                 sv_copypv(sv, kSVOP->op_sv);
13323                 SvREFCNT_dec_NN(kSVOP->op_sv);
13324                 kSVOP->op_sv = sv;
13325             }
13326             if (SvOK(sv)) fbm_compile(sv, 0);
13327             TAINT_set(save_taint);
13328 #ifdef NO_TAINT_SUPPORT
13329             PERL_UNUSED_VAR(save_taint);
13330 #endif
13331         }
13332     }
13333     return ck_fun(o);
13334 }
13335
13336 OP *
13337 Perl_ck_lfun(pTHX_ OP *o)
13338 {
13339     const OPCODE type = o->op_type;
13340
13341     PERL_ARGS_ASSERT_CK_LFUN;
13342
13343     return modkids(ck_fun(o), type);
13344 }
13345
13346 OP *
13347 Perl_ck_defined(pTHX_ OP *o)            /* 19990527 MJD */
13348 {
13349     PERL_ARGS_ASSERT_CK_DEFINED;
13350
13351     if ((o->op_flags & OPf_KIDS)) {
13352         switch (cUNOPo->op_first->op_type) {
13353         case OP_RV2AV:
13354         case OP_PADAV:
13355             Perl_croak(aTHX_ "Can't use 'defined(@array)'"
13356                              " (Maybe you should just omit the defined()?)");
13357             NOT_REACHED; /* NOTREACHED */
13358             break;
13359         case OP_RV2HV:
13360         case OP_PADHV:
13361             Perl_croak(aTHX_ "Can't use 'defined(%%hash)'"
13362                              " (Maybe you should just omit the defined()?)");
13363             NOT_REACHED; /* NOTREACHED */
13364             break;
13365         default:
13366             /* no warning */
13367             break;
13368         }
13369     }
13370     return ck_rfun(o);
13371 }
13372
13373 OP *
13374 Perl_ck_readline(pTHX_ OP *o)
13375 {
13376     PERL_ARGS_ASSERT_CK_READLINE;
13377
13378     if (o->op_flags & OPf_KIDS) {
13379          OP *kid = cLISTOPo->op_first;
13380          if (kid->op_type == OP_RV2GV) kid->op_private |= OPpALLOW_FAKE;
13381          scalar(kid);
13382     }
13383     else {
13384         OP * const newop
13385             = newUNOP(OP_READLINE, 0, newGVOP(OP_GV, 0, PL_argvgv));
13386         op_free(o);
13387         return newop;
13388     }
13389     return o;
13390 }
13391
13392 OP *
13393 Perl_ck_rfun(pTHX_ OP *o)
13394 {
13395     const OPCODE type = o->op_type;
13396
13397     PERL_ARGS_ASSERT_CK_RFUN;
13398
13399     return refkids(ck_fun(o), type);
13400 }
13401
13402 OP *
13403 Perl_ck_listiob(pTHX_ OP *o)
13404 {
13405     OP *kid;
13406
13407     PERL_ARGS_ASSERT_CK_LISTIOB;
13408
13409     kid = cLISTOPo->op_first;
13410     if (!kid) {
13411         o = force_list(o, 1);
13412         kid = cLISTOPo->op_first;
13413     }
13414     if (kid->op_type == OP_PUSHMARK)
13415         kid = OpSIBLING(kid);
13416     if (kid && o->op_flags & OPf_STACKED)
13417         kid = OpSIBLING(kid);
13418     else if (kid && !OpHAS_SIBLING(kid)) {              /* print HANDLE; */
13419         if (kid->op_type == OP_CONST && kid->op_private & OPpCONST_BARE
13420          && !kid->op_folded) {
13421             o->op_flags |= OPf_STACKED; /* make it a filehandle */
13422             scalar(kid);
13423             /* replace old const op with new OP_RV2GV parent */
13424             kid = S_op_sibling_newUNOP(aTHX_ o, cLISTOPo->op_first,
13425                                         OP_RV2GV, OPf_REF);
13426             kid = OpSIBLING(kid);
13427         }
13428     }
13429
13430     if (!kid)
13431         op_append_elem(o->op_type, o, newDEFSVOP());
13432
13433     if (o->op_type == OP_PRTF) return modkids(listkids(o), OP_PRTF);
13434     return listkids(o);
13435 }
13436
13437 OP *
13438 Perl_ck_smartmatch(pTHX_ OP *o)
13439 {
13440     PERL_ARGS_ASSERT_CK_SMARTMATCH;
13441     if (0 == (o->op_flags & OPf_SPECIAL)) {
13442         OP *first  = cBINOPo->op_first;
13443         OP *second = OpSIBLING(first);
13444
13445         /* Implicitly take a reference to an array or hash */
13446
13447         /* remove the original two siblings, then add back the
13448          * (possibly different) first and second sibs.
13449          */
13450         op_sibling_splice(o, NULL, 1, NULL);
13451         op_sibling_splice(o, NULL, 1, NULL);
13452         first  = ref_array_or_hash(first);
13453         second = ref_array_or_hash(second);
13454         op_sibling_splice(o, NULL, 0, second);
13455         op_sibling_splice(o, NULL, 0, first);
13456
13457         /* Implicitly take a reference to a regular expression */
13458         if (first->op_type == OP_MATCH && !(first->op_flags & OPf_STACKED)) {
13459             OpTYPE_set(first, OP_QR);
13460         }
13461         if (second->op_type == OP_MATCH && !(second->op_flags & OPf_STACKED)) {
13462             OpTYPE_set(second, OP_QR);
13463         }
13464     }
13465
13466     return o;
13467 }
13468
13469
13470 static OP *
13471 S_maybe_targlex(pTHX_ OP *o)
13472 {
13473     OP * const kid = cLISTOPo->op_first;
13474     /* has a disposable target? */
13475     if ((PL_opargs[kid->op_type] & OA_TARGLEX)
13476         && !(kid->op_flags & OPf_STACKED)
13477         /* Cannot steal the second time! */
13478         && !(kid->op_private & OPpTARGET_MY)
13479         )
13480     {
13481         OP * const kkid = OpSIBLING(kid);
13482
13483         /* Can just relocate the target. */
13484         if (kkid && kkid->op_type == OP_PADSV
13485             && (!(kkid->op_private & OPpLVAL_INTRO)
13486                || kkid->op_private & OPpPAD_STATE))
13487         {
13488             kid->op_targ = kkid->op_targ;
13489             kkid->op_targ = 0;
13490             /* Now we do not need PADSV and SASSIGN.
13491              * Detach kid and free the rest. */
13492             op_sibling_splice(o, NULL, 1, NULL);
13493             op_free(o);
13494             kid->op_private |= OPpTARGET_MY;    /* Used for context settings */
13495             return kid;
13496         }
13497     }
13498     return o;
13499 }
13500
13501 OP *
13502 Perl_ck_sassign(pTHX_ OP *o)
13503 {
13504     OP * const kid = cBINOPo->op_first;
13505
13506     PERL_ARGS_ASSERT_CK_SASSIGN;
13507
13508     if (OpHAS_SIBLING(kid)) {
13509         OP *kkid = OpSIBLING(kid);
13510         /* For state variable assignment with attributes, kkid is a list op
13511            whose op_last is a padsv. */
13512         if ((kkid->op_type == OP_PADSV ||
13513              (OP_TYPE_IS_OR_WAS(kkid, OP_LIST) &&
13514               (kkid = cLISTOPx(kkid)->op_last)->op_type == OP_PADSV
13515              )
13516             )
13517                 && (kkid->op_private & (OPpLVAL_INTRO|OPpPAD_STATE))
13518                     == (OPpLVAL_INTRO|OPpPAD_STATE)) {
13519             return S_newONCEOP(aTHX_ o, kkid);
13520         }
13521     }
13522     return S_maybe_targlex(aTHX_ o);
13523 }
13524
13525
13526 OP *
13527 Perl_ck_match(pTHX_ OP *o)
13528 {
13529     PERL_UNUSED_CONTEXT;
13530     PERL_ARGS_ASSERT_CK_MATCH;
13531
13532     return o;
13533 }
13534
13535 OP *
13536 Perl_ck_method(pTHX_ OP *o)
13537 {
13538     SV *sv, *methsv, *rclass;
13539     const char* method;
13540     char* compatptr;
13541     int utf8;
13542     STRLEN len, nsplit = 0, i;
13543     OP* new_op;
13544     OP * const kid = cUNOPo->op_first;
13545
13546     PERL_ARGS_ASSERT_CK_METHOD;
13547     if (kid->op_type != OP_CONST) return o;
13548
13549     sv = kSVOP->op_sv;
13550
13551     /* replace ' with :: */
13552     while ((compatptr = (char *) memchr(SvPVX(sv), '\'',
13553                                         SvEND(sv) - SvPVX(sv) )))
13554     {
13555         *compatptr = ':';
13556         sv_insert(sv, compatptr - SvPVX_const(sv), 0, ":", 1);
13557     }
13558
13559     method = SvPVX_const(sv);
13560     len = SvCUR(sv);
13561     utf8 = SvUTF8(sv) ? -1 : 1;
13562
13563     for (i = len - 1; i > 0; --i) if (method[i] == ':') {
13564         nsplit = i+1;
13565         break;
13566     }
13567
13568     methsv = newSVpvn_share(method+nsplit, utf8*(len - nsplit), 0);
13569
13570     if (!nsplit) { /* $proto->method() */
13571         op_free(o);
13572         return newMETHOP_named(OP_METHOD_NAMED, 0, methsv);
13573     }
13574
13575     if (memEQs(method, nsplit, "SUPER::")) { /* $proto->SUPER::method() */
13576         op_free(o);
13577         return newMETHOP_named(OP_METHOD_SUPER, 0, methsv);
13578     }
13579
13580     /* $proto->MyClass::method() and $proto->MyClass::SUPER::method() */
13581     if (nsplit >= 9 && strBEGINs(method+nsplit-9, "::SUPER::")) {
13582         rclass = newSVpvn_share(method, utf8*(nsplit-9), 0);
13583         new_op = newMETHOP_named(OP_METHOD_REDIR_SUPER, 0, methsv);
13584     } else {
13585         rclass = newSVpvn_share(method, utf8*(nsplit-2), 0);
13586         new_op = newMETHOP_named(OP_METHOD_REDIR, 0, methsv);
13587     }
13588 #ifdef USE_ITHREADS
13589     op_relocate_sv(&rclass, &cMETHOPx(new_op)->op_rclass_targ);
13590 #else
13591     cMETHOPx(new_op)->op_rclass_sv = rclass;
13592 #endif
13593     op_free(o);
13594     return new_op;
13595 }
13596
13597 OP *
13598 Perl_ck_null(pTHX_ OP *o)
13599 {
13600     PERL_ARGS_ASSERT_CK_NULL;
13601     PERL_UNUSED_CONTEXT;
13602     return o;
13603 }
13604
13605 OP *
13606 Perl_ck_open(pTHX_ OP *o)
13607 {
13608     PERL_ARGS_ASSERT_CK_OPEN;
13609
13610     S_io_hints(aTHX_ o);
13611     {
13612          /* In case of three-arg dup open remove strictness
13613           * from the last arg if it is a bareword. */
13614          OP * const first = cLISTOPx(o)->op_first; /* The pushmark. */
13615          OP * const last  = cLISTOPx(o)->op_last;  /* The bareword. */
13616          OP *oa;
13617          const char *mode;
13618
13619          if ((last->op_type == OP_CONST) &&             /* The bareword. */
13620              (last->op_private & OPpCONST_BARE) &&
13621              (last->op_private & OPpCONST_STRICT) &&
13622              (oa = OpSIBLING(first)) &&         /* The fh. */
13623              (oa = OpSIBLING(oa)) &&                    /* The mode. */
13624              (oa->op_type == OP_CONST) &&
13625              SvPOK(((SVOP*)oa)->op_sv) &&
13626              (mode = SvPVX_const(((SVOP*)oa)->op_sv)) &&
13627              mode[0] == '>' && mode[1] == '&' &&        /* A dup open. */
13628              (last == OpSIBLING(oa)))                   /* The bareword. */
13629               last->op_private &= ~OPpCONST_STRICT;
13630     }
13631     return ck_fun(o);
13632 }
13633
13634 OP *
13635 Perl_ck_prototype(pTHX_ OP *o)
13636 {
13637     PERL_ARGS_ASSERT_CK_PROTOTYPE;
13638     if (!(o->op_flags & OPf_KIDS)) {
13639         op_free(o);
13640         return newUNOP(OP_PROTOTYPE, 0, newDEFSVOP());
13641     }
13642     return o;
13643 }
13644
13645 OP *
13646 Perl_ck_refassign(pTHX_ OP *o)
13647 {
13648     OP * const right = cLISTOPo->op_first;
13649     OP * const left = OpSIBLING(right);
13650     OP *varop = cUNOPx(cUNOPx(left)->op_first)->op_first;
13651     bool stacked = 0;
13652
13653     PERL_ARGS_ASSERT_CK_REFASSIGN;
13654     assert (left);
13655     assert (left->op_type == OP_SREFGEN);
13656
13657     o->op_private = 0;
13658     /* we use OPpPAD_STATE in refassign to mean either of those things,
13659      * and the code assumes the two flags occupy the same bit position
13660      * in the various ops below */
13661     assert(OPpPAD_STATE == OPpOUR_INTRO);
13662
13663     switch (varop->op_type) {
13664     case OP_PADAV:
13665         o->op_private |= OPpLVREF_AV;
13666         goto settarg;
13667     case OP_PADHV:
13668         o->op_private |= OPpLVREF_HV;
13669         /* FALLTHROUGH */
13670     case OP_PADSV:
13671       settarg:
13672         o->op_private |= (varop->op_private & (OPpLVAL_INTRO|OPpPAD_STATE));
13673         o->op_targ = varop->op_targ;
13674         varop->op_targ = 0;
13675         PAD_COMPNAME_GEN_set(o->op_targ, PERL_INT_MAX);
13676         break;
13677
13678     case OP_RV2AV:
13679         o->op_private |= OPpLVREF_AV;
13680         goto checkgv;
13681         NOT_REACHED; /* NOTREACHED */
13682     case OP_RV2HV:
13683         o->op_private |= OPpLVREF_HV;
13684         /* FALLTHROUGH */
13685     case OP_RV2SV:
13686       checkgv:
13687         o->op_private |= (varop->op_private & (OPpLVAL_INTRO|OPpOUR_INTRO));
13688         if (cUNOPx(varop)->op_first->op_type != OP_GV) goto bad;
13689       detach_and_stack:
13690         /* Point varop to its GV kid, detached.  */
13691         varop = op_sibling_splice(varop, NULL, -1, NULL);
13692         stacked = TRUE;
13693         break;
13694     case OP_RV2CV: {
13695         OP * const kidparent =
13696             OpSIBLING(cUNOPx(cUNOPx(varop)->op_first)->op_first);
13697         OP * const kid = cUNOPx(kidparent)->op_first;
13698         o->op_private |= OPpLVREF_CV;
13699         if (kid->op_type == OP_GV) {
13700             SV *sv = (SV*)cGVOPx_gv(kid);
13701             varop = kidparent;
13702             if (SvROK(sv) && SvTYPE(SvRV(sv)) == SVt_PVCV) {
13703                 /* a CVREF here confuses pp_refassign, so make sure
13704                    it gets a GV */
13705                 CV *const cv = (CV*)SvRV(sv);
13706                 SV *name_sv = sv_2mortal(newSVhek(CvNAME_HEK(cv)));
13707                 (void)gv_init_sv((GV*)sv, CvSTASH(cv), name_sv, 0);
13708                 assert(SvTYPE(sv) == SVt_PVGV);
13709             }
13710             goto detach_and_stack;
13711         }
13712         if (kid->op_type != OP_PADCV)   goto bad;
13713         o->op_targ = kid->op_targ;
13714         kid->op_targ = 0;
13715         break;
13716     }
13717     case OP_AELEM:
13718     case OP_HELEM:
13719         o->op_private |= (varop->op_private & OPpLVAL_INTRO);
13720         o->op_private |= OPpLVREF_ELEM;
13721         op_null(varop);
13722         stacked = TRUE;
13723         /* Detach varop.  */
13724         op_sibling_splice(cUNOPx(left)->op_first, NULL, -1, NULL);
13725         break;
13726     default:
13727       bad:
13728         /* diag_listed_as: Can't modify reference to %s in %s assignment */
13729         yyerror(Perl_form(aTHX_ "Can't modify reference to %s in scalar "
13730                                 "assignment",
13731                                  OP_DESC(varop)));
13732         return o;
13733     }
13734     if (!FEATURE_REFALIASING_IS_ENABLED)
13735         Perl_croak(aTHX_
13736                   "Experimental aliasing via reference not enabled");
13737     Perl_ck_warner_d(aTHX_
13738                      packWARN(WARN_EXPERIMENTAL__REFALIASING),
13739                     "Aliasing via reference is experimental");
13740     if (stacked) {
13741         o->op_flags |= OPf_STACKED;
13742         op_sibling_splice(o, right, 1, varop);
13743     }
13744     else {
13745         o->op_flags &=~ OPf_STACKED;
13746         op_sibling_splice(o, right, 1, NULL);
13747     }
13748     op_free(left);
13749     return o;
13750 }
13751
13752 OP *
13753 Perl_ck_repeat(pTHX_ OP *o)
13754 {
13755     PERL_ARGS_ASSERT_CK_REPEAT;
13756
13757     if (cBINOPo->op_first->op_flags & OPf_PARENS) {
13758         OP* kids;
13759         o->op_private |= OPpREPEAT_DOLIST;
13760         kids = op_sibling_splice(o, NULL, 1, NULL); /* detach first kid */
13761         kids = force_list(kids, 1); /* promote it to a list */
13762         op_sibling_splice(o, NULL, 0, kids); /* and add back */
13763     }
13764     else
13765         scalar(o);
13766     return o;
13767 }
13768
13769 OP *
13770 Perl_ck_require(pTHX_ OP *o)
13771 {
13772     GV* gv;
13773
13774     PERL_ARGS_ASSERT_CK_REQUIRE;
13775
13776     if (o->op_flags & OPf_KIDS) {       /* Shall we supply missing .pm? */
13777         SVOP * const kid = (SVOP*)cUNOPo->op_first;
13778         U32 hash;
13779         char *s;
13780         STRLEN len;
13781         if (kid->op_type == OP_CONST) {
13782           SV * const sv = kid->op_sv;
13783           U32 const was_readonly = SvREADONLY(sv);
13784           if (kid->op_private & OPpCONST_BARE) {
13785             const char *end;
13786             HEK *hek;
13787
13788             if (was_readonly) {
13789                 SvREADONLY_off(sv);
13790             }
13791
13792             if (SvIsCOW(sv)) sv_force_normal_flags(sv, 0);
13793
13794             s = SvPVX(sv);
13795             len = SvCUR(sv);
13796             end = s + len;
13797             /* treat ::foo::bar as foo::bar */
13798             if (len >= 2 && s[0] == ':' && s[1] == ':')
13799                 DIE(aTHX_ "Bareword in require must not start with a double-colon: \"%s\"\n", s);
13800             if (s == end)
13801                 DIE(aTHX_ "Bareword in require maps to empty filename");
13802
13803             for (; s < end; s++) {
13804                 if (*s == ':' && s[1] == ':') {
13805                     *s = '/';
13806                     Move(s+2, s+1, end - s - 1, char);
13807                     --end;
13808                 }
13809             }
13810             SvEND_set(sv, end);
13811             sv_catpvs(sv, ".pm");
13812             PERL_HASH(hash, SvPVX(sv), SvCUR(sv));
13813             hek = share_hek(SvPVX(sv),
13814                             (SSize_t)SvCUR(sv) * (SvUTF8(sv) ? -1 : 1),
13815                             hash);
13816             sv_sethek(sv, hek);
13817             unshare_hek(hek);
13818             SvFLAGS(sv) |= was_readonly;
13819           }
13820           else if (SvPOK(sv) && !SvNIOK(sv) && !SvGMAGICAL(sv)
13821                 && !SvVOK(sv)) {
13822             s = SvPV(sv, len);
13823             if (SvREFCNT(sv) > 1) {
13824                 kid->op_sv = newSVpvn_share(
13825                     s, SvUTF8(sv) ? -(SSize_t)len : (SSize_t)len, 0);
13826                 SvREFCNT_dec_NN(sv);
13827             }
13828             else {
13829                 HEK *hek;
13830                 if (was_readonly) SvREADONLY_off(sv);
13831                 PERL_HASH(hash, s, len);
13832                 hek = share_hek(s,
13833                                 SvUTF8(sv) ? -(SSize_t)len : (SSize_t)len,
13834                                 hash);
13835                 sv_sethek(sv, hek);
13836                 unshare_hek(hek);
13837                 SvFLAGS(sv) |= was_readonly;
13838             }
13839           }
13840         }
13841     }
13842
13843     if (!(o->op_flags & OPf_SPECIAL) /* Wasn't written as CORE::require */
13844         /* handle override, if any */
13845      && (gv = gv_override("require", 7))) {
13846         OP *kid, *newop;
13847         if (o->op_flags & OPf_KIDS) {
13848             kid = cUNOPo->op_first;
13849             op_sibling_splice(o, NULL, -1, NULL);
13850         }
13851         else {
13852             kid = newDEFSVOP();
13853         }
13854         op_free(o);
13855         newop = S_new_entersubop(aTHX_ gv, kid);
13856         return newop;
13857     }
13858
13859     return ck_fun(o);
13860 }
13861
13862 OP *
13863 Perl_ck_return(pTHX_ OP *o)
13864 {
13865     OP *kid;
13866
13867     PERL_ARGS_ASSERT_CK_RETURN;
13868
13869     kid = OpSIBLING(cLISTOPo->op_first);
13870     if (PL_compcv && CvLVALUE(PL_compcv)) {
13871         for (; kid; kid = OpSIBLING(kid))
13872             op_lvalue(kid, OP_LEAVESUBLV);
13873     }
13874
13875     return o;
13876 }
13877
13878 OP *
13879 Perl_ck_select(pTHX_ OP *o)
13880 {
13881     OP* kid;
13882
13883     PERL_ARGS_ASSERT_CK_SELECT;
13884
13885     if (o->op_flags & OPf_KIDS) {
13886         kid = OpSIBLING(cLISTOPo->op_first);     /* get past pushmark */
13887         if (kid && OpHAS_SIBLING(kid)) {
13888             OpTYPE_set(o, OP_SSELECT);
13889             o = ck_fun(o);
13890             return fold_constants(op_integerize(op_std_init(o)));
13891         }
13892     }
13893     o = ck_fun(o);
13894     kid = OpSIBLING(cLISTOPo->op_first);    /* get past pushmark */
13895     if (kid && kid->op_type == OP_RV2GV)
13896         kid->op_private &= ~HINT_STRICT_REFS;
13897     return o;
13898 }
13899
13900 OP *
13901 Perl_ck_shift(pTHX_ OP *o)
13902 {
13903     const I32 type = o->op_type;
13904
13905     PERL_ARGS_ASSERT_CK_SHIFT;
13906
13907     if (!(o->op_flags & OPf_KIDS)) {
13908         OP *argop;
13909
13910         if (!CvUNIQUE(PL_compcv)) {
13911             o->op_flags |= OPf_SPECIAL;
13912             return o;
13913         }
13914
13915         argop = newUNOP(OP_RV2AV, 0, scalar(newGVOP(OP_GV, 0, PL_argvgv)));
13916         op_free(o);
13917         return newUNOP(type, 0, scalar(argop));
13918     }
13919     return scalar(ck_fun(o));
13920 }
13921
13922 OP *
13923 Perl_ck_sort(pTHX_ OP *o)
13924 {
13925     OP *firstkid;
13926     OP *kid;
13927     HV * const hinthv =
13928         PL_hints & HINT_LOCALIZE_HH ? GvHV(PL_hintgv) : NULL;
13929     U8 stacked;
13930
13931     PERL_ARGS_ASSERT_CK_SORT;
13932
13933     if (hinthv) {
13934             SV ** const svp = hv_fetchs(hinthv, "sort", FALSE);
13935             if (svp) {
13936                 const I32 sorthints = (I32)SvIV(*svp);
13937                 if ((sorthints & HINT_SORT_STABLE) != 0)
13938                     o->op_private |= OPpSORT_STABLE;
13939                 if ((sorthints & HINT_SORT_UNSTABLE) != 0)
13940                     o->op_private |= OPpSORT_UNSTABLE;
13941             }
13942     }
13943
13944     if (o->op_flags & OPf_STACKED)
13945         simplify_sort(o);
13946     firstkid = OpSIBLING(cLISTOPo->op_first);           /* get past pushmark */
13947
13948     if ((stacked = o->op_flags & OPf_STACKED)) {        /* may have been cleared */
13949         OP *kid = cUNOPx(firstkid)->op_first;           /* get past null */
13950
13951         /* if the first arg is a code block, process it and mark sort as
13952          * OPf_SPECIAL */
13953         if (kid->op_type == OP_SCOPE || kid->op_type == OP_LEAVE) {
13954             LINKLIST(kid);
13955             if (kid->op_type == OP_LEAVE)
13956                     op_null(kid);                       /* wipe out leave */
13957             /* Prevent execution from escaping out of the sort block. */
13958             kid->op_next = 0;
13959
13960             /* provide scalar context for comparison function/block */
13961             kid = scalar(firstkid);
13962             kid->op_next = kid;
13963             o->op_flags |= OPf_SPECIAL;
13964         }
13965         else if (kid->op_type == OP_CONST
13966               && kid->op_private & OPpCONST_BARE) {
13967             char tmpbuf[256];
13968             STRLEN len;
13969             PADOFFSET off;
13970             const char * const name = SvPV(kSVOP_sv, len);
13971             *tmpbuf = '&';
13972             assert (len < 256);
13973             Copy(name, tmpbuf+1, len, char);
13974             off = pad_findmy_pvn(tmpbuf, len+1, 0);
13975             if (off != NOT_IN_PAD) {
13976                 if (PAD_COMPNAME_FLAGS_isOUR(off)) {
13977                     SV * const fq =
13978                         newSVhek(HvNAME_HEK(PAD_COMPNAME_OURSTASH(off)));
13979                     sv_catpvs(fq, "::");
13980                     sv_catsv(fq, kSVOP_sv);
13981                     SvREFCNT_dec_NN(kSVOP_sv);
13982                     kSVOP->op_sv = fq;
13983                 }
13984                 else {
13985                     OP * const padop = newOP(OP_PADCV, 0);
13986                     padop->op_targ = off;
13987                     /* replace the const op with the pad op */
13988                     op_sibling_splice(firstkid, NULL, 1, padop);
13989                     op_free(kid);
13990                 }
13991             }
13992         }
13993
13994         firstkid = OpSIBLING(firstkid);
13995     }
13996
13997     for (kid = firstkid; kid; kid = OpSIBLING(kid)) {
13998         /* provide list context for arguments */
13999         list(kid);
14000         if (stacked)
14001             op_lvalue(kid, OP_GREPSTART);
14002     }
14003
14004     return o;
14005 }
14006
14007 /* for sort { X } ..., where X is one of
14008  *   $a <=> $b, $b <=> $a, $a cmp $b, $b cmp $a
14009  * elide the second child of the sort (the one containing X),
14010  * and set these flags as appropriate
14011         OPpSORT_NUMERIC;
14012         OPpSORT_INTEGER;
14013         OPpSORT_DESCEND;
14014  * Also, check and warn on lexical $a, $b.
14015  */
14016
14017 STATIC void
14018 S_simplify_sort(pTHX_ OP *o)
14019 {
14020     OP *kid = OpSIBLING(cLISTOPo->op_first);    /* get past pushmark */
14021     OP *k;
14022     int descending;
14023     GV *gv;
14024     const char *gvname;
14025     bool have_scopeop;
14026
14027     PERL_ARGS_ASSERT_SIMPLIFY_SORT;
14028
14029     kid = kUNOP->op_first;                              /* get past null */
14030     if (!(have_scopeop = kid->op_type == OP_SCOPE)
14031      && kid->op_type != OP_LEAVE)
14032         return;
14033     kid = kLISTOP->op_last;                             /* get past scope */
14034     switch(kid->op_type) {
14035         case OP_NCMP:
14036         case OP_I_NCMP:
14037         case OP_SCMP:
14038             if (!have_scopeop) goto padkids;
14039             break;
14040         default:
14041             return;
14042     }
14043     k = kid;                                            /* remember this node*/
14044     if (kBINOP->op_first->op_type != OP_RV2SV
14045      || kBINOP->op_last ->op_type != OP_RV2SV)
14046     {
14047         /*
14048            Warn about my($a) or my($b) in a sort block, *if* $a or $b is
14049            then used in a comparison.  This catches most, but not
14050            all cases.  For instance, it catches
14051                sort { my($a); $a <=> $b }
14052            but not
14053                sort { my($a); $a < $b ? -1 : $a == $b ? 0 : 1; }
14054            (although why you'd do that is anyone's guess).
14055         */
14056
14057        padkids:
14058         if (!ckWARN(WARN_SYNTAX)) return;
14059         kid = kBINOP->op_first;
14060         do {
14061             if (kid->op_type == OP_PADSV) {
14062                 PADNAME * const name = PAD_COMPNAME(kid->op_targ);
14063                 if (PadnameLEN(name) == 2 && *PadnamePV(name) == '$'
14064                  && (  PadnamePV(name)[1] == 'a'
14065                     || PadnamePV(name)[1] == 'b'  ))
14066                     /* diag_listed_as: "my %s" used in sort comparison */
14067                     Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
14068                                      "\"%s %s\" used in sort comparison",
14069                                       PadnameIsSTATE(name)
14070                                         ? "state"
14071                                         : "my",
14072                                       PadnamePV(name));
14073             }
14074         } while ((kid = OpSIBLING(kid)));
14075         return;
14076     }
14077     kid = kBINOP->op_first;                             /* get past cmp */
14078     if (kUNOP->op_first->op_type != OP_GV)
14079         return;
14080     kid = kUNOP->op_first;                              /* get past rv2sv */
14081     gv = kGVOP_gv;
14082     if (GvSTASH(gv) != PL_curstash)
14083         return;
14084     gvname = GvNAME(gv);
14085     if (*gvname == 'a' && gvname[1] == '\0')
14086         descending = 0;
14087     else if (*gvname == 'b' && gvname[1] == '\0')
14088         descending = 1;
14089     else
14090         return;
14091
14092     kid = k;                                            /* back to cmp */
14093     /* already checked above that it is rv2sv */
14094     kid = kBINOP->op_last;                              /* down to 2nd arg */
14095     if (kUNOP->op_first->op_type != OP_GV)
14096         return;
14097     kid = kUNOP->op_first;                              /* get past rv2sv */
14098     gv = kGVOP_gv;
14099     if (GvSTASH(gv) != PL_curstash)
14100         return;
14101     gvname = GvNAME(gv);
14102     if ( descending
14103          ? !(*gvname == 'a' && gvname[1] == '\0')
14104          : !(*gvname == 'b' && gvname[1] == '\0'))
14105         return;
14106     o->op_flags &= ~(OPf_STACKED | OPf_SPECIAL);
14107     if (descending)
14108         o->op_private |= OPpSORT_DESCEND;
14109     if (k->op_type == OP_NCMP)
14110         o->op_private |= OPpSORT_NUMERIC;
14111     if (k->op_type == OP_I_NCMP)
14112         o->op_private |= OPpSORT_NUMERIC | OPpSORT_INTEGER;
14113     kid = OpSIBLING(cLISTOPo->op_first);
14114     /* cut out and delete old block (second sibling) */
14115     op_sibling_splice(o, cLISTOPo->op_first, 1, NULL);
14116     op_free(kid);
14117 }
14118
14119 OP *
14120 Perl_ck_split(pTHX_ OP *o)
14121 {
14122     OP *kid;
14123     OP *sibs;
14124
14125     PERL_ARGS_ASSERT_CK_SPLIT;
14126
14127     assert(o->op_type == OP_LIST);
14128
14129     if (o->op_flags & OPf_STACKED)
14130         return no_fh_allowed(o);
14131
14132     kid = cLISTOPo->op_first;
14133     /* delete leading NULL node, then add a CONST if no other nodes */
14134     assert(kid->op_type == OP_NULL);
14135     op_sibling_splice(o, NULL, 1,
14136         OpHAS_SIBLING(kid) ? NULL : newSVOP(OP_CONST, 0, newSVpvs(" ")));
14137     op_free(kid);
14138     kid = cLISTOPo->op_first;
14139
14140     if (kid->op_type != OP_MATCH || kid->op_flags & OPf_STACKED) {
14141         /* remove match expression, and replace with new optree with
14142          * a match op at its head */
14143         op_sibling_splice(o, NULL, 1, NULL);
14144         /* pmruntime will handle split " " behavior with flag==2 */
14145         kid = pmruntime(newPMOP(OP_MATCH, 0), kid, NULL, 2, 0);
14146         op_sibling_splice(o, NULL, 0, kid);
14147     }
14148
14149     assert(kid->op_type == OP_MATCH || kid->op_type == OP_SPLIT);
14150
14151     if (((PMOP *)kid)->op_pmflags & PMf_GLOBAL) {
14152       Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP),
14153                      "Use of /g modifier is meaningless in split");
14154     }
14155
14156     /* eliminate the split op, and move the match op (plus any children)
14157      * into its place, then convert the match op into a split op. i.e.
14158      *
14159      *  SPLIT                    MATCH                 SPLIT(ex-MATCH)
14160      *    |                        |                     |
14161      *  MATCH - A - B - C   =>     R - A - B - C   =>    R - A - B - C
14162      *    |                        |                     |
14163      *    R                        X - Y                 X - Y
14164      *    |
14165      *    X - Y
14166      *
14167      * (R, if it exists, will be a regcomp op)
14168      */
14169
14170     op_sibling_splice(o, NULL, 1, NULL); /* detach match op from o */
14171     sibs = op_sibling_splice(o, NULL, -1, NULL); /* detach any other sibs */
14172     op_sibling_splice(kid, cLISTOPx(kid)->op_last, 0, sibs); /* and reattach */
14173     OpTYPE_set(kid, OP_SPLIT);
14174     kid->op_flags   = (o->op_flags | (kid->op_flags & OPf_KIDS));
14175     kid->op_private = o->op_private;
14176     op_free(o);
14177     o = kid;
14178     kid = sibs; /* kid is now the string arg of the split */
14179
14180     if (!kid) {
14181         kid = newDEFSVOP();
14182         op_append_elem(OP_SPLIT, o, kid);
14183     }
14184     scalar(kid);
14185
14186     kid = OpSIBLING(kid);
14187     if (!kid) {
14188         kid = newSVOP(OP_CONST, 0, newSViv(0));
14189         op_append_elem(OP_SPLIT, o, kid);
14190         o->op_private |= OPpSPLIT_IMPLIM;
14191     }
14192     scalar(kid);
14193
14194     if (OpHAS_SIBLING(kid))
14195         return too_many_arguments_pv(o,OP_DESC(o), 0);
14196
14197     return o;
14198 }
14199
14200 OP *
14201 Perl_ck_stringify(pTHX_ OP *o)
14202 {
14203     OP * const kid = OpSIBLING(cUNOPo->op_first);
14204     PERL_ARGS_ASSERT_CK_STRINGIFY;
14205     if ((   kid->op_type == OP_JOIN || kid->op_type == OP_QUOTEMETA
14206          || kid->op_type == OP_LC   || kid->op_type == OP_LCFIRST
14207          || kid->op_type == OP_UC   || kid->op_type == OP_UCFIRST)
14208         && !OpHAS_SIBLING(kid)) /* syntax errs can leave extra children */
14209     {
14210         op_sibling_splice(o, cUNOPo->op_first, -1, NULL);
14211         op_free(o);
14212         return kid;
14213     }
14214     return ck_fun(o);
14215 }
14216
14217 OP *
14218 Perl_ck_join(pTHX_ OP *o)
14219 {
14220     OP * const kid = OpSIBLING(cLISTOPo->op_first);
14221
14222     PERL_ARGS_ASSERT_CK_JOIN;
14223
14224     if (kid && kid->op_type == OP_MATCH) {
14225         if (ckWARN(WARN_SYNTAX)) {
14226             const REGEXP *re = PM_GETRE(kPMOP);
14227             const SV *msg = re
14228                     ? newSVpvn_flags( RX_PRECOMP_const(re), RX_PRELEN(re),
14229                                             SVs_TEMP | ( RX_UTF8(re) ? SVf_UTF8 : 0 ) )
14230                     : newSVpvs_flags( "STRING", SVs_TEMP );
14231             Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
14232                         "/%" SVf "/ should probably be written as \"%" SVf "\"",
14233                         SVfARG(msg), SVfARG(msg));
14234         }
14235     }
14236     if (kid
14237      && (kid->op_type == OP_CONST /* an innocent, unsuspicious separator */
14238         || (kid->op_type == OP_PADSV && !(kid->op_private & OPpLVAL_INTRO))
14239         || (  kid->op_type==OP_RV2SV && kUNOP->op_first->op_type == OP_GV
14240            && !(kid->op_private & (OPpLVAL_INTRO|OPpOUR_INTRO)))))
14241     {
14242         const OP * const bairn = OpSIBLING(kid); /* the list */
14243         if (bairn && !OpHAS_SIBLING(bairn) /* single-item list */
14244          && OP_GIMME(bairn,0) == G_SCALAR)
14245         {
14246             OP * const ret = op_convert_list(OP_STRINGIFY, OPf_FOLDED,
14247                                      op_sibling_splice(o, kid, 1, NULL));
14248             op_free(o);
14249             return ret;
14250         }
14251     }
14252
14253     return ck_fun(o);
14254 }
14255
14256 /*
14257 =for apidoc rv2cv_op_cv
14258
14259 Examines an op, which is expected to identify a subroutine at runtime,
14260 and attempts to determine at compile time which subroutine it identifies.
14261 This is normally used during Perl compilation to determine whether
14262 a prototype can be applied to a function call.  C<cvop> is the op
14263 being considered, normally an C<rv2cv> op.  A pointer to the identified
14264 subroutine is returned, if it could be determined statically, and a null
14265 pointer is returned if it was not possible to determine statically.
14266
14267 Currently, the subroutine can be identified statically if the RV that the
14268 C<rv2cv> is to operate on is provided by a suitable C<gv> or C<const> op.
14269 A C<gv> op is suitable if the GV's CV slot is populated.  A C<const> op is
14270 suitable if the constant value must be an RV pointing to a CV.  Details of
14271 this process may change in future versions of Perl.  If the C<rv2cv> op
14272 has the C<OPpENTERSUB_AMPER> flag set then no attempt is made to identify
14273 the subroutine statically: this flag is used to suppress compile-time
14274 magic on a subroutine call, forcing it to use default runtime behaviour.
14275
14276 If C<flags> has the bit C<RV2CVOPCV_MARK_EARLY> set, then the handling
14277 of a GV reference is modified.  If a GV was examined and its CV slot was
14278 found to be empty, then the C<gv> op has the C<OPpEARLY_CV> flag set.
14279 If the op is not optimised away, and the CV slot is later populated with
14280 a subroutine having a prototype, that flag eventually triggers the warning
14281 "called too early to check prototype".
14282
14283 If C<flags> has the bit C<RV2CVOPCV_RETURN_NAME_GV> set, then instead
14284 of returning a pointer to the subroutine it returns a pointer to the
14285 GV giving the most appropriate name for the subroutine in this context.
14286 Normally this is just the C<CvGV> of the subroutine, but for an anonymous
14287 (C<CvANON>) subroutine that is referenced through a GV it will be the
14288 referencing GV.  The resulting C<GV*> is cast to C<CV*> to be returned.
14289 A null pointer is returned as usual if there is no statically-determinable
14290 subroutine.
14291
14292 =for apidoc Amnh||OPpEARLY_CV
14293 =for apidoc Amnh||OPpENTERSUB_AMPER
14294 =for apidoc Amnh||RV2CVOPCV_MARK_EARLY
14295 =for apidoc Amnh||RV2CVOPCV_RETURN_NAME_GV
14296
14297 =cut
14298 */
14299
14300 /* shared by toke.c:yylex */
14301 CV *
14302 Perl_find_lexical_cv(pTHX_ PADOFFSET off)
14303 {
14304     PADNAME *name = PAD_COMPNAME(off);
14305     CV *compcv = PL_compcv;
14306     while (PadnameOUTER(name)) {
14307         assert(PARENT_PAD_INDEX(name));
14308         compcv = CvOUTSIDE(compcv);
14309         name = PadlistNAMESARRAY(CvPADLIST(compcv))
14310                 [off = PARENT_PAD_INDEX(name)];
14311     }
14312     assert(!PadnameIsOUR(name));
14313     if (!PadnameIsSTATE(name) && PadnamePROTOCV(name)) {
14314         return PadnamePROTOCV(name);
14315     }
14316     return (CV *)AvARRAY(PadlistARRAY(CvPADLIST(compcv))[1])[off];
14317 }
14318
14319 CV *
14320 Perl_rv2cv_op_cv(pTHX_ OP *cvop, U32 flags)
14321 {
14322     OP *rvop;
14323     CV *cv;
14324     GV *gv;
14325     PERL_ARGS_ASSERT_RV2CV_OP_CV;
14326     if (flags & ~RV2CVOPCV_FLAG_MASK)
14327         Perl_croak(aTHX_ "panic: rv2cv_op_cv bad flags %x", (unsigned)flags);
14328     if (cvop->op_type != OP_RV2CV)
14329         return NULL;
14330     if (cvop->op_private & OPpENTERSUB_AMPER)
14331         return NULL;
14332     if (!(cvop->op_flags & OPf_KIDS))
14333         return NULL;
14334     rvop = cUNOPx(cvop)->op_first;
14335     switch (rvop->op_type) {
14336         case OP_GV: {
14337             gv = cGVOPx_gv(rvop);
14338             if (!isGV(gv)) {
14339                 if (SvROK(gv) && SvTYPE(SvRV(gv)) == SVt_PVCV) {
14340                     cv = MUTABLE_CV(SvRV(gv));
14341                     gv = NULL;
14342                     break;
14343                 }
14344                 if (flags & RV2CVOPCV_RETURN_STUB)
14345                     return (CV *)gv;
14346                 else return NULL;
14347             }
14348             cv = GvCVu(gv);
14349             if (!cv) {
14350                 if (flags & RV2CVOPCV_MARK_EARLY)
14351                     rvop->op_private |= OPpEARLY_CV;
14352                 return NULL;
14353             }
14354         } break;
14355         case OP_CONST: {
14356             SV *rv = cSVOPx_sv(rvop);
14357             if (!SvROK(rv))
14358                 return NULL;
14359             cv = (CV*)SvRV(rv);
14360             gv = NULL;
14361         } break;
14362         case OP_PADCV: {
14363             cv = find_lexical_cv(rvop->op_targ);
14364             gv = NULL;
14365         } break;
14366         default: {
14367             return NULL;
14368         } NOT_REACHED; /* NOTREACHED */
14369     }
14370     if (SvTYPE((SV*)cv) != SVt_PVCV)
14371         return NULL;
14372     if (flags & RV2CVOPCV_RETURN_NAME_GV) {
14373         if ((!CvANON(cv) && !CvLEXICAL(cv)) || !gv)
14374             gv = CvGV(cv);
14375         return (CV*)gv;
14376     }
14377     else if (flags & RV2CVOPCV_MAYBE_NAME_GV) {
14378         if (CvLEXICAL(cv) || CvNAMED(cv))
14379             return NULL;
14380         if (!CvANON(cv) || !gv)
14381             gv = CvGV(cv);
14382         return (CV*)gv;
14383
14384     } else {
14385         return cv;
14386     }
14387 }
14388
14389 /*
14390 =for apidoc ck_entersub_args_list
14391
14392 Performs the default fixup of the arguments part of an C<entersub>
14393 op tree.  This consists of applying list context to each of the
14394 argument ops.  This is the standard treatment used on a call marked
14395 with C<&>, or a method call, or a call through a subroutine reference,
14396 or any other call where the callee can't be identified at compile time,
14397 or a call where the callee has no prototype.
14398
14399 =cut
14400 */
14401
14402 OP *
14403 Perl_ck_entersub_args_list(pTHX_ OP *entersubop)
14404 {
14405     OP *aop;
14406
14407     PERL_ARGS_ASSERT_CK_ENTERSUB_ARGS_LIST;
14408
14409     aop = cUNOPx(entersubop)->op_first;
14410     if (!OpHAS_SIBLING(aop))
14411         aop = cUNOPx(aop)->op_first;
14412     for (aop = OpSIBLING(aop); OpHAS_SIBLING(aop); aop = OpSIBLING(aop)) {
14413         /* skip the extra attributes->import() call implicitly added in
14414          * something like foo(my $x : bar)
14415          */
14416         if (   aop->op_type == OP_ENTERSUB
14417             && (aop->op_flags & OPf_WANT) == OPf_WANT_VOID
14418         )
14419             continue;
14420         list(aop);
14421         op_lvalue(aop, OP_ENTERSUB);
14422     }
14423     return entersubop;
14424 }
14425
14426 /*
14427 =for apidoc ck_entersub_args_proto
14428
14429 Performs the fixup of the arguments part of an C<entersub> op tree
14430 based on a subroutine prototype.  This makes various modifications to
14431 the argument ops, from applying context up to inserting C<refgen> ops,
14432 and checking the number and syntactic types of arguments, as directed by
14433 the prototype.  This is the standard treatment used on a subroutine call,
14434 not marked with C<&>, where the callee can be identified at compile time
14435 and has a prototype.
14436
14437 C<protosv> supplies the subroutine prototype to be applied to the call.
14438 It may be a normal defined scalar, of which the string value will be used.
14439 Alternatively, for convenience, it may be a subroutine object (a C<CV*>
14440 that has been cast to C<SV*>) which has a prototype.  The prototype
14441 supplied, in whichever form, does not need to match the actual callee
14442 referenced by the op tree.
14443
14444 If the argument ops disagree with the prototype, for example by having
14445 an unacceptable number of arguments, a valid op tree is returned anyway.
14446 The error is reflected in the parser state, normally resulting in a single
14447 exception at the top level of parsing which covers all the compilation
14448 errors that occurred.  In the error message, the callee is referred to
14449 by the name defined by the C<namegv> parameter.
14450
14451 =cut
14452 */
14453
14454 OP *
14455 Perl_ck_entersub_args_proto(pTHX_ OP *entersubop, GV *namegv, SV *protosv)
14456 {
14457     STRLEN proto_len;
14458     const char *proto, *proto_end;
14459     OP *aop, *prev, *cvop, *parent;
14460     int optional = 0;
14461     I32 arg = 0;
14462     I32 contextclass = 0;
14463     const char *e = NULL;
14464     PERL_ARGS_ASSERT_CK_ENTERSUB_ARGS_PROTO;
14465     if (SvTYPE(protosv) == SVt_PVCV ? !SvPOK(protosv) : !SvOK(protosv))
14466         Perl_croak(aTHX_ "panic: ck_entersub_args_proto CV with no proto, "
14467                    "flags=%lx", (unsigned long) SvFLAGS(protosv));
14468     if (SvTYPE(protosv) == SVt_PVCV)
14469          proto = CvPROTO(protosv), proto_len = CvPROTOLEN(protosv);
14470     else proto = SvPV(protosv, proto_len);
14471     proto = S_strip_spaces(aTHX_ proto, &proto_len);
14472     proto_end = proto + proto_len;
14473     parent = entersubop;
14474     aop = cUNOPx(entersubop)->op_first;
14475     if (!OpHAS_SIBLING(aop)) {
14476         parent = aop;
14477         aop = cUNOPx(aop)->op_first;
14478     }
14479     prev = aop;
14480     aop = OpSIBLING(aop);
14481     for (cvop = aop; OpHAS_SIBLING(cvop); cvop = OpSIBLING(cvop)) ;
14482     while (aop != cvop) {
14483         OP* o3 = aop;
14484
14485         if (proto >= proto_end)
14486         {
14487             SV * const namesv = cv_name((CV *)namegv, NULL, 0);
14488             yyerror_pv(Perl_form(aTHX_ "Too many arguments for %" SVf,
14489                                         SVfARG(namesv)), SvUTF8(namesv));
14490             return entersubop;
14491         }
14492
14493         switch (*proto) {
14494             case ';':
14495                 optional = 1;
14496                 proto++;
14497                 continue;
14498             case '_':
14499                 /* _ must be at the end */
14500                 if (proto[1] && !memCHRs(";@%", proto[1]))
14501                     goto oops;
14502                 /* FALLTHROUGH */
14503             case '$':
14504                 proto++;
14505                 arg++;
14506                 scalar(aop);
14507                 break;
14508             case '%':
14509             case '@':
14510                 list(aop);
14511                 arg++;
14512                 break;
14513             case '&':
14514                 proto++;
14515                 arg++;
14516                 if (    o3->op_type != OP_UNDEF
14517                     && (o3->op_type != OP_SREFGEN
14518                         || (  cUNOPx(cUNOPx(o3)->op_first)->op_first->op_type
14519                                 != OP_ANONCODE
14520                             && cUNOPx(cUNOPx(o3)->op_first)->op_first->op_type
14521                                 != OP_RV2CV)))
14522                     bad_type_gv(arg, namegv, o3,
14523                             arg == 1 ? "block or sub {}" : "sub {}");
14524                 break;
14525             case '*':
14526                 /* '*' allows any scalar type, including bareword */
14527                 proto++;
14528                 arg++;
14529                 if (o3->op_type == OP_RV2GV)
14530                     goto wrapref;       /* autoconvert GLOB -> GLOBref */
14531                 else if (o3->op_type == OP_CONST)
14532                     o3->op_private &= ~OPpCONST_STRICT;
14533                 scalar(aop);
14534                 break;
14535             case '+':
14536                 proto++;
14537                 arg++;
14538                 if (o3->op_type == OP_RV2AV ||
14539                     o3->op_type == OP_PADAV ||
14540                     o3->op_type == OP_RV2HV ||
14541                     o3->op_type == OP_PADHV
14542                 ) {
14543                     goto wrapref;
14544                 }
14545                 scalar(aop);
14546                 break;
14547             case '[': case ']':
14548                 goto oops;
14549
14550             case '\\':
14551                 proto++;
14552                 arg++;
14553             again:
14554                 switch (*proto++) {
14555                     case '[':
14556                         if (contextclass++ == 0) {
14557                             e = (char *) memchr(proto, ']', proto_end - proto);
14558                             if (!e || e == proto)
14559                                 goto oops;
14560                         }
14561                         else
14562                             goto oops;
14563                         goto again;
14564
14565                     case ']':
14566                         if (contextclass) {
14567                             const char *p = proto;
14568                             const char *const end = proto;
14569                             contextclass = 0;
14570                             while (*--p != '[')
14571                                 /* \[$] accepts any scalar lvalue */
14572                                 if (*p == '$'
14573                                  && Perl_op_lvalue_flags(aTHX_
14574                                      scalar(o3),
14575                                      OP_READ, /* not entersub */
14576                                      OP_LVALUE_NO_CROAK
14577                                     )) goto wrapref;
14578                             bad_type_gv(arg, namegv, o3,
14579                                     Perl_form(aTHX_ "one of %.*s",(int)(end - p), p));
14580                         } else
14581                             goto oops;
14582                         break;
14583                     case '*':
14584                         if (o3->op_type == OP_RV2GV)
14585                             goto wrapref;
14586                         if (!contextclass)
14587                             bad_type_gv(arg, namegv, o3, "symbol");
14588                         break;
14589                     case '&':
14590                         if (o3->op_type == OP_ENTERSUB
14591                          && !(o3->op_flags & OPf_STACKED))
14592                             goto wrapref;
14593                         if (!contextclass)
14594                             bad_type_gv(arg, namegv, o3, "subroutine");
14595                         break;
14596                     case '$':
14597                         if (o3->op_type == OP_RV2SV ||
14598                                 o3->op_type == OP_PADSV ||
14599                                 o3->op_type == OP_HELEM ||
14600                                 o3->op_type == OP_AELEM)
14601                             goto wrapref;
14602                         if (!contextclass) {
14603                             /* \$ accepts any scalar lvalue */
14604                             if (Perl_op_lvalue_flags(aTHX_
14605                                     scalar(o3),
14606                                     OP_READ,  /* not entersub */
14607                                     OP_LVALUE_NO_CROAK
14608                                )) goto wrapref;
14609                             bad_type_gv(arg, namegv, o3, "scalar");
14610                         }
14611                         break;
14612                     case '@':
14613                         if (o3->op_type == OP_RV2AV ||
14614                                 o3->op_type == OP_PADAV)
14615                         {
14616                             o3->op_flags &=~ OPf_PARENS;
14617                             goto wrapref;
14618                         }
14619                         if (!contextclass)
14620                             bad_type_gv(arg, namegv, o3, "array");
14621                         break;
14622                     case '%':
14623                         if (o3->op_type == OP_RV2HV ||
14624                                 o3->op_type == OP_PADHV)
14625                         {
14626                             o3->op_flags &=~ OPf_PARENS;
14627                             goto wrapref;
14628                         }
14629                         if (!contextclass)
14630                             bad_type_gv(arg, namegv, o3, "hash");
14631                         break;
14632                     wrapref:
14633                             aop = S_op_sibling_newUNOP(aTHX_ parent, prev,
14634                                                 OP_REFGEN, 0);
14635                         if (contextclass && e) {
14636                             proto = e + 1;
14637                             contextclass = 0;
14638                         }
14639                         break;
14640                     default: goto oops;
14641                 }
14642                 if (contextclass)
14643                     goto again;
14644                 break;
14645             case ' ':
14646                 proto++;
14647                 continue;
14648             default:
14649             oops: {
14650                 Perl_croak(aTHX_ "Malformed prototype for %" SVf ": %" SVf,
14651                                   SVfARG(cv_name((CV *)namegv, NULL, 0)),
14652                                   SVfARG(protosv));
14653             }
14654         }
14655
14656         op_lvalue(aop, OP_ENTERSUB);
14657         prev = aop;
14658         aop = OpSIBLING(aop);
14659     }
14660     if (aop == cvop && *proto == '_') {
14661         /* generate an access to $_ */
14662         op_sibling_splice(parent, prev, 0, newDEFSVOP());
14663     }
14664     if (!optional && proto_end > proto &&
14665         (*proto != '@' && *proto != '%' && *proto != ';' && *proto != '_'))
14666     {
14667         SV * const namesv = cv_name((CV *)namegv, NULL, 0);
14668         yyerror_pv(Perl_form(aTHX_ "Not enough arguments for %" SVf,
14669                                     SVfARG(namesv)), SvUTF8(namesv));
14670     }
14671     return entersubop;
14672 }
14673
14674 /*
14675 =for apidoc ck_entersub_args_proto_or_list
14676
14677 Performs the fixup of the arguments part of an C<entersub> op tree either
14678 based on a subroutine prototype or using default list-context processing.
14679 This is the standard treatment used on a subroutine call, not marked
14680 with C<&>, where the callee can be identified at compile time.
14681
14682 C<protosv> supplies the subroutine prototype to be applied to the call,
14683 or indicates that there is no prototype.  It may be a normal scalar,
14684 in which case if it is defined then the string value will be used
14685 as a prototype, and if it is undefined then there is no prototype.
14686 Alternatively, for convenience, it may be a subroutine object (a C<CV*>
14687 that has been cast to C<SV*>), of which the prototype will be used if it
14688 has one.  The prototype (or lack thereof) supplied, in whichever form,
14689 does not need to match the actual callee referenced by the op tree.
14690
14691 If the argument ops disagree with the prototype, for example by having
14692 an unacceptable number of arguments, a valid op tree is returned anyway.
14693 The error is reflected in the parser state, normally resulting in a single
14694 exception at the top level of parsing which covers all the compilation
14695 errors that occurred.  In the error message, the callee is referred to
14696 by the name defined by the C<namegv> parameter.
14697
14698 =cut
14699 */
14700
14701 OP *
14702 Perl_ck_entersub_args_proto_or_list(pTHX_ OP *entersubop,
14703         GV *namegv, SV *protosv)
14704 {
14705     PERL_ARGS_ASSERT_CK_ENTERSUB_ARGS_PROTO_OR_LIST;
14706     if (SvTYPE(protosv) == SVt_PVCV ? SvPOK(protosv) : SvOK(protosv))
14707         return ck_entersub_args_proto(entersubop, namegv, protosv);
14708     else
14709         return ck_entersub_args_list(entersubop);
14710 }
14711
14712 OP *
14713 Perl_ck_entersub_args_core(pTHX_ OP *entersubop, GV *namegv, SV *protosv)
14714 {
14715     IV cvflags = SvIVX(protosv);
14716     int opnum = cvflags & 0xffff;
14717     OP *aop = cUNOPx(entersubop)->op_first;
14718
14719     PERL_ARGS_ASSERT_CK_ENTERSUB_ARGS_CORE;
14720
14721     if (!opnum) {
14722         OP *cvop;
14723         if (!OpHAS_SIBLING(aop))
14724             aop = cUNOPx(aop)->op_first;
14725         aop = OpSIBLING(aop);
14726         for (cvop = aop; OpSIBLING(cvop); cvop = OpSIBLING(cvop)) ;
14727         if (aop != cvop) {
14728             SV *namesv = cv_name((CV *)namegv, NULL, CV_NAME_NOTQUAL);
14729             yyerror_pv(Perl_form(aTHX_ "Too many arguments for %" SVf,
14730                 SVfARG(namesv)), SvUTF8(namesv));
14731         }
14732
14733         op_free(entersubop);
14734         switch(cvflags >> 16) {
14735         case 'F': return newSVOP(OP_CONST, 0,
14736                                         newSVpv(CopFILE(PL_curcop),0));
14737         case 'L': return newSVOP(
14738                            OP_CONST, 0,
14739                            Perl_newSVpvf(aTHX_
14740                              "%" IVdf, (IV)CopLINE(PL_curcop)
14741                            )
14742                          );
14743         case 'P': return newSVOP(OP_CONST, 0,
14744                                    (PL_curstash
14745                                      ? newSVhek(HvNAME_HEK(PL_curstash))
14746                                      : &PL_sv_undef
14747                                    )
14748                                 );
14749         }
14750         NOT_REACHED; /* NOTREACHED */
14751     }
14752     else {
14753         OP *prev, *cvop, *first, *parent;
14754         U32 flags = 0;
14755
14756         parent = entersubop;
14757         if (!OpHAS_SIBLING(aop)) {
14758             parent = aop;
14759             aop = cUNOPx(aop)->op_first;
14760         }
14761
14762         first = prev = aop;
14763         aop = OpSIBLING(aop);
14764         /* find last sibling */
14765         for (cvop = aop;
14766              OpHAS_SIBLING(cvop);
14767              prev = cvop, cvop = OpSIBLING(cvop))
14768             ;
14769         if (!(cvop->op_private & OPpENTERSUB_NOPAREN)
14770             /* Usually, OPf_SPECIAL on an op with no args means that it had
14771              * parens, but these have their own meaning for that flag: */
14772             && opnum != OP_VALUES && opnum != OP_KEYS && opnum != OP_EACH
14773             && opnum != OP_DELETE && opnum != OP_EXISTS)
14774                 flags |= OPf_SPECIAL;
14775         /* excise cvop from end of sibling chain */
14776         op_sibling_splice(parent, prev, 1, NULL);
14777         op_free(cvop);
14778         if (aop == cvop) aop = NULL;
14779
14780         /* detach remaining siblings from the first sibling, then
14781          * dispose of original optree */
14782
14783         if (aop)
14784             op_sibling_splice(parent, first, -1, NULL);
14785         op_free(entersubop);
14786
14787         if (cvflags == (OP_ENTEREVAL | (1<<16)))
14788             flags |= OPpEVAL_BYTES <<8;
14789
14790         switch (PL_opargs[opnum] & OA_CLASS_MASK) {
14791         case OA_UNOP:
14792         case OA_BASEOP_OR_UNOP:
14793         case OA_FILESTATOP:
14794             if (!aop)
14795                 return newOP(opnum,flags);       /* zero args */
14796             if (aop == prev)
14797                 return newUNOP(opnum,flags,aop); /* one arg */
14798             /* too many args */
14799             /* FALLTHROUGH */
14800         case OA_BASEOP:
14801             if (aop) {
14802                 SV *namesv;
14803                 OP *nextop;
14804
14805                 namesv = cv_name((CV *)namegv, NULL, CV_NAME_NOTQUAL);
14806                 yyerror_pv(Perl_form(aTHX_ "Too many arguments for %" SVf,
14807                     SVfARG(namesv)), SvUTF8(namesv));
14808                 while (aop) {
14809                     nextop = OpSIBLING(aop);
14810                     op_free(aop);
14811                     aop = nextop;
14812                 }
14813
14814             }
14815             return opnum == OP_RUNCV
14816                 ? newPVOP(OP_RUNCV,0,NULL)
14817                 : newOP(opnum,0);
14818         default:
14819             return op_convert_list(opnum,0,aop);
14820         }
14821     }
14822     NOT_REACHED; /* NOTREACHED */
14823     return entersubop;
14824 }
14825
14826 /*
14827 =for apidoc cv_get_call_checker_flags
14828
14829 Retrieves the function that will be used to fix up a call to C<cv>.
14830 Specifically, the function is applied to an C<entersub> op tree for a
14831 subroutine call, not marked with C<&>, where the callee can be identified
14832 at compile time as C<cv>.
14833
14834 The C-level function pointer is returned in C<*ckfun_p>, an SV argument
14835 for it is returned in C<*ckobj_p>, and control flags are returned in
14836 C<*ckflags_p>.  The function is intended to be called in this manner:
14837
14838  entersubop = (*ckfun_p)(aTHX_ entersubop, namegv, (*ckobj_p));
14839
14840 In this call, C<entersubop> is a pointer to the C<entersub> op,
14841 which may be replaced by the check function, and C<namegv> supplies
14842 the name that should be used by the check function to refer
14843 to the callee of the C<entersub> op if it needs to emit any diagnostics.
14844 It is permitted to apply the check function in non-standard situations,
14845 such as to a call to a different subroutine or to a method call.
14846
14847 C<namegv> may not actually be a GV.  If the C<CALL_CHECKER_REQUIRE_GV>
14848 bit is clear in C<*ckflags_p>, it is permitted to pass a CV or other SV
14849 instead, anything that can be used as the first argument to L</cv_name>.
14850 If the C<CALL_CHECKER_REQUIRE_GV> bit is set in C<*ckflags_p> then the
14851 check function requires C<namegv> to be a genuine GV.
14852
14853 By default, the check function is
14854 L<Perl_ck_entersub_args_proto_or_list|/ck_entersub_args_proto_or_list>,
14855 the SV parameter is C<cv> itself, and the C<CALL_CHECKER_REQUIRE_GV>
14856 flag is clear.  This implements standard prototype processing.  It can
14857 be changed, for a particular subroutine, by L</cv_set_call_checker_flags>.
14858
14859 If the C<CALL_CHECKER_REQUIRE_GV> bit is set in C<gflags> then it
14860 indicates that the caller only knows about the genuine GV version of
14861 C<namegv>, and accordingly the corresponding bit will always be set in
14862 C<*ckflags_p>, regardless of the check function's recorded requirements.
14863 If the C<CALL_CHECKER_REQUIRE_GV> bit is clear in C<gflags> then it
14864 indicates the caller knows about the possibility of passing something
14865 other than a GV as C<namegv>, and accordingly the corresponding bit may
14866 be either set or clear in C<*ckflags_p>, indicating the check function's
14867 recorded requirements.
14868
14869 C<gflags> is a bitset passed into C<cv_get_call_checker_flags>, in which
14870 only the C<CALL_CHECKER_REQUIRE_GV> bit currently has a defined meaning
14871 (for which see above).  All other bits should be clear.
14872
14873 =for apidoc Amnh||CALL_CHECKER_REQUIRE_GV
14874
14875 =for apidoc cv_get_call_checker
14876
14877 The original form of L</cv_get_call_checker_flags>, which does not return
14878 checker flags.  When using a checker function returned by this function,
14879 it is only safe to call it with a genuine GV as its C<namegv> argument.
14880
14881 =cut
14882 */
14883
14884 void
14885 Perl_cv_get_call_checker_flags(pTHX_ CV *cv, U32 gflags,
14886         Perl_call_checker *ckfun_p, SV **ckobj_p, U32 *ckflags_p)
14887 {
14888     MAGIC *callmg;
14889     PERL_ARGS_ASSERT_CV_GET_CALL_CHECKER_FLAGS;
14890     PERL_UNUSED_CONTEXT;
14891     callmg = SvMAGICAL((SV*)cv) ? mg_find((SV*)cv, PERL_MAGIC_checkcall) : NULL;
14892     if (callmg) {
14893         *ckfun_p = DPTR2FPTR(Perl_call_checker, callmg->mg_ptr);
14894         *ckobj_p = callmg->mg_obj;
14895         *ckflags_p = (callmg->mg_flags | gflags) & MGf_REQUIRE_GV;
14896     } else {
14897         *ckfun_p = Perl_ck_entersub_args_proto_or_list;
14898         *ckobj_p = (SV*)cv;
14899         *ckflags_p = gflags & MGf_REQUIRE_GV;
14900     }
14901 }
14902
14903 void
14904 Perl_cv_get_call_checker(pTHX_ CV *cv, Perl_call_checker *ckfun_p, SV **ckobj_p)
14905 {
14906     U32 ckflags;
14907     PERL_ARGS_ASSERT_CV_GET_CALL_CHECKER;
14908     PERL_UNUSED_CONTEXT;
14909     cv_get_call_checker_flags(cv, CALL_CHECKER_REQUIRE_GV, ckfun_p, ckobj_p,
14910         &ckflags);
14911 }
14912
14913 /*
14914 =for apidoc cv_set_call_checker_flags
14915
14916 Sets the function that will be used to fix up a call to C<cv>.
14917 Specifically, the function is applied to an C<entersub> op tree for a
14918 subroutine call, not marked with C<&>, where the callee can be identified
14919 at compile time as C<cv>.
14920
14921 The C-level function pointer is supplied in C<ckfun>, an SV argument for
14922 it is supplied in C<ckobj>, and control flags are supplied in C<ckflags>.
14923 The function should be defined like this:
14924
14925     STATIC OP * ckfun(pTHX_ OP *op, GV *namegv, SV *ckobj)
14926
14927 It is intended to be called in this manner:
14928
14929     entersubop = ckfun(aTHX_ entersubop, namegv, ckobj);
14930
14931 In this call, C<entersubop> is a pointer to the C<entersub> op,
14932 which may be replaced by the check function, and C<namegv> supplies
14933 the name that should be used by the check function to refer
14934 to the callee of the C<entersub> op if it needs to emit any diagnostics.
14935 It is permitted to apply the check function in non-standard situations,
14936 such as to a call to a different subroutine or to a method call.
14937
14938 C<namegv> may not actually be a GV.  For efficiency, perl may pass a
14939 CV or other SV instead.  Whatever is passed can be used as the first
14940 argument to L</cv_name>.  You can force perl to pass a GV by including
14941 C<CALL_CHECKER_REQUIRE_GV> in the C<ckflags>.
14942
14943 C<ckflags> is a bitset, in which only the C<CALL_CHECKER_REQUIRE_GV>
14944 bit currently has a defined meaning (for which see above).  All other
14945 bits should be clear.
14946
14947 The current setting for a particular CV can be retrieved by
14948 L</cv_get_call_checker_flags>.
14949
14950 =for apidoc cv_set_call_checker
14951
14952 The original form of L</cv_set_call_checker_flags>, which passes it the
14953 C<CALL_CHECKER_REQUIRE_GV> flag for backward-compatibility.  The effect
14954 of that flag setting is that the check function is guaranteed to get a
14955 genuine GV as its C<namegv> argument.
14956
14957 =cut
14958 */
14959
14960 void
14961 Perl_cv_set_call_checker(pTHX_ CV *cv, Perl_call_checker ckfun, SV *ckobj)
14962 {
14963     PERL_ARGS_ASSERT_CV_SET_CALL_CHECKER;
14964     cv_set_call_checker_flags(cv, ckfun, ckobj, CALL_CHECKER_REQUIRE_GV);
14965 }
14966
14967 void
14968 Perl_cv_set_call_checker_flags(pTHX_ CV *cv, Perl_call_checker ckfun,
14969                                      SV *ckobj, U32 ckflags)
14970 {
14971     PERL_ARGS_ASSERT_CV_SET_CALL_CHECKER_FLAGS;
14972     if (ckfun == Perl_ck_entersub_args_proto_or_list && ckobj == (SV*)cv) {
14973         if (SvMAGICAL((SV*)cv))
14974             mg_free_type((SV*)cv, PERL_MAGIC_checkcall);
14975     } else {
14976         MAGIC *callmg;
14977         sv_magic((SV*)cv, &PL_sv_undef, PERL_MAGIC_checkcall, NULL, 0);
14978         callmg = mg_find((SV*)cv, PERL_MAGIC_checkcall);
14979         assert(callmg);
14980         if (callmg->mg_flags & MGf_REFCOUNTED) {
14981             SvREFCNT_dec(callmg->mg_obj);
14982             callmg->mg_flags &= ~MGf_REFCOUNTED;
14983         }
14984         callmg->mg_ptr = FPTR2DPTR(char *, ckfun);
14985         callmg->mg_obj = ckobj;
14986         if (ckobj != (SV*)cv) {
14987             SvREFCNT_inc_simple_void_NN(ckobj);
14988             callmg->mg_flags |= MGf_REFCOUNTED;
14989         }
14990         callmg->mg_flags = (callmg->mg_flags &~ MGf_REQUIRE_GV)
14991                          | (U8)(ckflags & MGf_REQUIRE_GV) | MGf_COPY;
14992     }
14993 }
14994
14995 static void
14996 S_entersub_alloc_targ(pTHX_ OP * const o)
14997 {
14998     o->op_targ = pad_alloc(OP_ENTERSUB, SVs_PADTMP);
14999     o->op_private |= OPpENTERSUB_HASTARG;
15000 }
15001
15002 OP *
15003 Perl_ck_subr(pTHX_ OP *o)
15004 {
15005     OP *aop, *cvop;
15006     CV *cv;
15007     GV *namegv;
15008     SV **const_class = NULL;
15009
15010     PERL_ARGS_ASSERT_CK_SUBR;
15011
15012     aop = cUNOPx(o)->op_first;
15013     if (!OpHAS_SIBLING(aop))
15014         aop = cUNOPx(aop)->op_first;
15015     aop = OpSIBLING(aop);
15016     for (cvop = aop; OpHAS_SIBLING(cvop); cvop = OpSIBLING(cvop)) ;
15017     cv = rv2cv_op_cv(cvop, RV2CVOPCV_MARK_EARLY);
15018     namegv = cv ? (GV*)rv2cv_op_cv(cvop, RV2CVOPCV_MAYBE_NAME_GV) : NULL;
15019
15020     o->op_private &= ~1;
15021     o->op_private |= (PL_hints & HINT_STRICT_REFS);
15022     if (PERLDB_SUB && PL_curstash != PL_debstash)
15023         o->op_private |= OPpENTERSUB_DB;
15024     switch (cvop->op_type) {
15025         case OP_RV2CV:
15026             o->op_private |= (cvop->op_private & OPpENTERSUB_AMPER);
15027             op_null(cvop);
15028             break;
15029         case OP_METHOD:
15030         case OP_METHOD_NAMED:
15031         case OP_METHOD_SUPER:
15032         case OP_METHOD_REDIR:
15033         case OP_METHOD_REDIR_SUPER:
15034             o->op_flags |= OPf_REF;
15035             if (aop->op_type == OP_CONST) {
15036                 aop->op_private &= ~OPpCONST_STRICT;
15037                 const_class = &cSVOPx(aop)->op_sv;
15038             }
15039             else if (aop->op_type == OP_LIST) {
15040                 OP * const sib = OpSIBLING(((UNOP*)aop)->op_first);
15041                 if (sib && sib->op_type == OP_CONST) {
15042                     sib->op_private &= ~OPpCONST_STRICT;
15043                     const_class = &cSVOPx(sib)->op_sv;
15044                 }
15045             }
15046             /* make class name a shared cow string to speedup method calls */
15047             /* constant string might be replaced with object, f.e. bigint */
15048             if (const_class && SvPOK(*const_class)) {
15049                 STRLEN len;
15050                 const char* str = SvPV(*const_class, len);
15051                 if (len) {
15052                     SV* const shared = newSVpvn_share(
15053                         str, SvUTF8(*const_class)
15054                                     ? -(SSize_t)len : (SSize_t)len,
15055                         0
15056                     );
15057                     if (SvREADONLY(*const_class))
15058                         SvREADONLY_on(shared);
15059                     SvREFCNT_dec(*const_class);
15060                     *const_class = shared;
15061                 }
15062             }
15063             break;
15064     }
15065
15066     if (!cv) {
15067         S_entersub_alloc_targ(aTHX_ o);
15068         return ck_entersub_args_list(o);
15069     } else {
15070         Perl_call_checker ckfun;
15071         SV *ckobj;
15072         U32 ckflags;
15073         cv_get_call_checker_flags(cv, 0, &ckfun, &ckobj, &ckflags);
15074         if (CvISXSUB(cv) || !CvROOT(cv))
15075             S_entersub_alloc_targ(aTHX_ o);
15076         if (!namegv) {
15077             /* The original call checker API guarantees that a GV will
15078                be provided with the right name.  So, if the old API was
15079                used (or the REQUIRE_GV flag was passed), we have to reify
15080                the CV’s GV, unless this is an anonymous sub.  This is not
15081                ideal for lexical subs, as its stringification will include
15082                the package.  But it is the best we can do.  */
15083             if (ckflags & CALL_CHECKER_REQUIRE_GV) {
15084                 if (!CvANON(cv) && (!CvNAMED(cv) || CvNAME_HEK(cv)))
15085                     namegv = CvGV(cv);
15086             }
15087             else namegv = MUTABLE_GV(cv);
15088             /* After a syntax error in a lexical sub, the cv that
15089                rv2cv_op_cv returns may be a nameless stub. */
15090             if (!namegv) return ck_entersub_args_list(o);
15091
15092         }
15093         return ckfun(aTHX_ o, namegv, ckobj);
15094     }
15095 }
15096
15097 OP *
15098 Perl_ck_svconst(pTHX_ OP *o)
15099 {
15100     SV * const sv = cSVOPo->op_sv;
15101     PERL_ARGS_ASSERT_CK_SVCONST;
15102     PERL_UNUSED_CONTEXT;
15103 #ifdef PERL_COPY_ON_WRITE
15104     /* Since the read-only flag may be used to protect a string buffer, we
15105        cannot do copy-on-write with existing read-only scalars that are not
15106        already copy-on-write scalars.  To allow $_ = "hello" to do COW with
15107        that constant, mark the constant as COWable here, if it is not
15108        already read-only. */
15109     if (!SvREADONLY(sv) && !SvIsCOW(sv) && SvCANCOW(sv)) {
15110         SvIsCOW_on(sv);
15111         CowREFCNT(sv) = 0;
15112 # ifdef PERL_DEBUG_READONLY_COW
15113         sv_buf_to_ro(sv);
15114 # endif
15115     }
15116 #endif
15117     SvREADONLY_on(sv);
15118     return o;
15119 }
15120
15121 OP *
15122 Perl_ck_trunc(pTHX_ OP *o)
15123 {
15124     PERL_ARGS_ASSERT_CK_TRUNC;
15125
15126     if (o->op_flags & OPf_KIDS) {
15127         SVOP *kid = (SVOP*)cUNOPo->op_first;
15128
15129         if (kid->op_type == OP_NULL)
15130             kid = (SVOP*)OpSIBLING(kid);
15131         if (kid && kid->op_type == OP_CONST &&
15132             (kid->op_private & OPpCONST_BARE) &&
15133             !kid->op_folded)
15134         {
15135             o->op_flags |= OPf_SPECIAL;
15136             kid->op_private &= ~OPpCONST_STRICT;
15137         }
15138     }
15139     return ck_fun(o);
15140 }
15141
15142 OP *
15143 Perl_ck_substr(pTHX_ OP *o)
15144 {
15145     PERL_ARGS_ASSERT_CK_SUBSTR;
15146
15147     o = ck_fun(o);
15148     if ((o->op_flags & OPf_KIDS) && (o->op_private == 4)) {
15149         OP *kid = cLISTOPo->op_first;
15150
15151         if (kid->op_type == OP_NULL)
15152             kid = OpSIBLING(kid);
15153         if (kid)
15154             /* Historically, substr(delete $foo{bar},...) has been allowed
15155                with 4-arg substr.  Keep it working by applying entersub
15156                lvalue context.  */
15157             op_lvalue(kid, OP_ENTERSUB);
15158
15159     }
15160     return o;
15161 }
15162
15163 OP *
15164 Perl_ck_tell(pTHX_ OP *o)
15165 {
15166     PERL_ARGS_ASSERT_CK_TELL;
15167     o = ck_fun(o);
15168     if (o->op_flags & OPf_KIDS) {
15169      OP *kid = cLISTOPo->op_first;
15170      if (kid->op_type == OP_NULL && OpHAS_SIBLING(kid)) kid = OpSIBLING(kid);
15171      if (kid->op_type == OP_RV2GV) kid->op_private |= OPpALLOW_FAKE;
15172     }
15173     return o;
15174 }
15175
15176 OP *
15177 Perl_ck_each(pTHX_ OP *o)
15178 {
15179     OP *kid = o->op_flags & OPf_KIDS ? cUNOPo->op_first : NULL;
15180     const unsigned orig_type  = o->op_type;
15181
15182     PERL_ARGS_ASSERT_CK_EACH;
15183
15184     if (kid) {
15185         switch (kid->op_type) {
15186             case OP_PADHV:
15187             case OP_RV2HV:
15188                 break;
15189             case OP_PADAV:
15190             case OP_RV2AV:
15191                 OpTYPE_set(o, orig_type == OP_EACH ? OP_AEACH
15192                             : orig_type == OP_KEYS ? OP_AKEYS
15193                             :                        OP_AVALUES);
15194                 break;
15195             case OP_CONST:
15196                 if (kid->op_private == OPpCONST_BARE
15197                  || !SvROK(cSVOPx_sv(kid))
15198                  || (  SvTYPE(SvRV(cSVOPx_sv(kid))) != SVt_PVAV
15199                     && SvTYPE(SvRV(cSVOPx_sv(kid))) != SVt_PVHV  )
15200                    )
15201                     goto bad;
15202                 /* FALLTHROUGH */
15203             default:
15204                 qerror(Perl_mess(aTHX_
15205                     "Experimental %s on scalar is now forbidden",
15206                      PL_op_desc[orig_type]));
15207                bad:
15208                 bad_type_pv(1, "hash or array", o, kid);
15209                 return o;
15210         }
15211     }
15212     return ck_fun(o);
15213 }
15214
15215 OP *
15216 Perl_ck_length(pTHX_ OP *o)
15217 {
15218     PERL_ARGS_ASSERT_CK_LENGTH;
15219
15220     o = ck_fun(o);
15221
15222     if (ckWARN(WARN_SYNTAX)) {
15223         const OP *kid = o->op_flags & OPf_KIDS ? cLISTOPo->op_first : NULL;
15224
15225         if (kid) {
15226             SV *name = NULL;
15227             const bool hash = kid->op_type == OP_PADHV
15228                            || kid->op_type == OP_RV2HV;
15229             switch (kid->op_type) {
15230                 case OP_PADHV:
15231                 case OP_PADAV:
15232                 case OP_RV2HV:
15233                 case OP_RV2AV:
15234                     name = S_op_varname(aTHX_ kid);
15235                     break;
15236                 default:
15237                     return o;
15238             }
15239             if (name)
15240                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
15241                     "length() used on %" SVf " (did you mean \"scalar(%s%" SVf
15242                     ")\"?)",
15243                     SVfARG(name), hash ? "keys " : "", SVfARG(name)
15244                 );
15245             else if (hash)
15246      /* diag_listed_as: length() used on %s (did you mean "scalar(%s)"?) */
15247                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
15248                     "length() used on %%hash (did you mean \"scalar(keys %%hash)\"?)");
15249             else
15250      /* diag_listed_as: length() used on %s (did you mean "scalar(%s)"?) */
15251                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
15252                     "length() used on @array (did you mean \"scalar(@array)\"?)");
15253         }
15254     }
15255
15256     return o;
15257 }
15258
15259
15260 OP *
15261 Perl_ck_isa(pTHX_ OP *o)
15262 {
15263     OP *classop = cBINOPo->op_last;
15264
15265     PERL_ARGS_ASSERT_CK_ISA;
15266
15267     /* Convert barename into PV */
15268     if(classop->op_type == OP_CONST && classop->op_private & OPpCONST_BARE) {
15269         /* TODO: Optionally convert package to raw HV here */
15270         classop->op_private &= ~(OPpCONST_BARE|OPpCONST_STRICT);
15271     }
15272
15273     return o;
15274 }
15275
15276
15277 /*
15278    ---------------------------------------------------------
15279
15280    Common vars in list assignment
15281
15282    There now follows some enums and static functions for detecting
15283    common variables in list assignments. Here is a little essay I wrote
15284    for myself when trying to get my head around this. DAPM.
15285
15286    ----
15287
15288    First some random observations:
15289
15290    * If a lexical var is an alias of something else, e.g.
15291        for my $x ($lex, $pkg, $a[0]) {...}
15292      then the act of aliasing will increase the reference count of the SV
15293
15294    * If a package var is an alias of something else, it may still have a
15295      reference count of 1, depending on how the alias was created, e.g.
15296      in *a = *b, $a may have a refcount of 1 since the GP is shared
15297      with a single GvSV pointer to the SV. So If it's an alias of another
15298      package var, then RC may be 1; if it's an alias of another scalar, e.g.
15299      a lexical var or an array element, then it will have RC > 1.
15300
15301    * There are many ways to create a package alias; ultimately, XS code
15302      may quite legally do GvSV(gv) = SvREFCNT_inc(sv) for example, so
15303      run-time tracing mechanisms are unlikely to be able to catch all cases.
15304
15305    * When the LHS is all my declarations, the same vars can't appear directly
15306      on the RHS, but they can indirectly via closures, aliasing and lvalue
15307      subs. But those techniques all involve an increase in the lexical
15308      scalar's ref count.
15309
15310    * When the LHS is all lexical vars (but not necessarily my declarations),
15311      it is possible for the same lexicals to appear directly on the RHS, and
15312      without an increased ref count, since the stack isn't refcounted.
15313      This case can be detected at compile time by scanning for common lex
15314      vars with PL_generation.
15315
15316    * lvalue subs defeat common var detection, but they do at least
15317      return vars with a temporary ref count increment. Also, you can't
15318      tell at compile time whether a sub call is lvalue.
15319
15320
15321    So...
15322
15323    A: There are a few circumstances where there definitely can't be any
15324      commonality:
15325
15326        LHS empty:  () = (...);
15327        RHS empty:  (....) = ();
15328        RHS contains only constants or other 'can't possibly be shared'
15329            elements (e.g. ops that return PADTMPs):  (...) = (1,2, length)
15330            i.e. they only contain ops not marked as dangerous, whose children
15331            are also not dangerous;
15332        LHS ditto;
15333        LHS contains a single scalar element: e.g. ($x) = (....); because
15334            after $x has been modified, it won't be used again on the RHS;
15335        RHS contains a single element with no aggregate on LHS: e.g.
15336            ($a,$b,$c)  = ($x); again, once $a has been modified, its value
15337            won't be used again.
15338
15339    B: If LHS are all 'my' lexical var declarations (or safe ops, which
15340      we can ignore):
15341
15342        my ($a, $b, @c) = ...;
15343
15344        Due to closure and goto tricks, these vars may already have content.
15345        For the same reason, an element on the RHS may be a lexical or package
15346        alias of one of the vars on the left, or share common elements, for
15347        example:
15348
15349            my ($x,$y) = f(); # $x and $y on both sides
15350            sub f : lvalue { ($x,$y) = (1,2); $y, $x }
15351
15352        and
15353
15354            my $ra = f();
15355            my @a = @$ra;  # elements of @a on both sides
15356            sub f { @a = 1..4; \@a }
15357
15358
15359        First, just consider scalar vars on LHS:
15360
15361            RHS is safe only if (A), or in addition,
15362                * contains only lexical *scalar* vars, where neither side's
15363                  lexicals have been flagged as aliases
15364
15365            If RHS is not safe, then it's always legal to check LHS vars for
15366            RC==1, since the only RHS aliases will always be associated
15367            with an RC bump.
15368
15369            Note that in particular, RHS is not safe if:
15370
15371                * it contains package scalar vars; e.g.:
15372
15373                    f();
15374                    my ($x, $y) = (2, $x_alias);
15375                    sub f { $x = 1; *x_alias = \$x; }
15376
15377                * It contains other general elements, such as flattened or
15378                * spliced or single array or hash elements, e.g.
15379
15380                    f();
15381                    my ($x,$y) = @a; # or $a[0] or @a{@b} etc
15382
15383                    sub f {
15384                        ($x, $y) = (1,2);
15385                        use feature 'refaliasing';
15386                        \($a[0], $a[1]) = \($y,$x);
15387                    }
15388
15389                  It doesn't matter if the array/hash is lexical or package.
15390
15391                * it contains a function call that happens to be an lvalue
15392                  sub which returns one or more of the above, e.g.
15393
15394                    f();
15395                    my ($x,$y) = f();
15396
15397                    sub f : lvalue {
15398                        ($x, $y) = (1,2);
15399                        *x1 = \$x;
15400                        $y, $x1;
15401                    }
15402
15403                    (so a sub call on the RHS should be treated the same
15404                    as having a package var on the RHS).
15405
15406                * any other "dangerous" thing, such an op or built-in that
15407                  returns one of the above, e.g. pp_preinc
15408
15409
15410            If RHS is not safe, what we can do however is at compile time flag
15411            that the LHS are all my declarations, and at run time check whether
15412            all the LHS have RC == 1, and if so skip the full scan.
15413
15414        Now consider array and hash vars on LHS: e.g. my (...,@a) = ...;
15415
15416            Here the issue is whether there can be elements of @a on the RHS
15417            which will get prematurely freed when @a is cleared prior to
15418            assignment. This is only a problem if the aliasing mechanism
15419            is one which doesn't increase the refcount - only if RC == 1
15420            will the RHS element be prematurely freed.
15421
15422            Because the array/hash is being INTROed, it or its elements
15423            can't directly appear on the RHS:
15424
15425                my (@a) = ($a[0], @a, etc) # NOT POSSIBLE
15426
15427            but can indirectly, e.g.:
15428
15429                my $r = f();
15430                my (@a) = @$r;
15431                sub f { @a = 1..3; \@a }
15432
15433            So if the RHS isn't safe as defined by (A), we must always
15434            mortalise and bump the ref count of any remaining RHS elements
15435            when assigning to a non-empty LHS aggregate.
15436
15437            Lexical scalars on the RHS aren't safe if they've been involved in
15438            aliasing, e.g.
15439
15440                use feature 'refaliasing';
15441
15442                f();
15443                \(my $lex) = \$pkg;
15444                my @a = ($lex,3); # equivalent to ($a[0],3)
15445
15446                sub f {
15447                    @a = (1,2);
15448                    \$pkg = \$a[0];
15449                }
15450
15451            Similarly with lexical arrays and hashes on the RHS:
15452
15453                f();
15454                my @b;
15455                my @a = (@b);
15456
15457                sub f {
15458                    @a = (1,2);
15459                    \$b[0] = \$a[1];
15460                    \$b[1] = \$a[0];
15461                }
15462
15463
15464
15465    C: As (B), but in addition the LHS may contain non-intro lexicals, e.g.
15466        my $a; ($a, my $b) = (....);
15467
15468        The difference between (B) and (C) is that it is now physically
15469        possible for the LHS vars to appear on the RHS too, where they
15470        are not reference counted; but in this case, the compile-time
15471        PL_generation sweep will detect such common vars.
15472
15473        So the rules for (C) differ from (B) in that if common vars are
15474        detected, the runtime "test RC==1" optimisation can no longer be used,
15475        and a full mark and sweep is required
15476
15477    D: As (C), but in addition the LHS may contain package vars.
15478
15479        Since package vars can be aliased without a corresponding refcount
15480        increase, all bets are off. It's only safe if (A). E.g.
15481
15482            my ($x, $y) = (1,2);
15483
15484            for $x_alias ($x) {
15485                ($x_alias, $y) = (3, $x); # whoops
15486            }
15487
15488        Ditto for LHS aggregate package vars.
15489
15490    E: Any other dangerous ops on LHS, e.g.
15491            (f(), $a[0], @$r) = (...);
15492
15493        this is similar to (E) in that all bets are off. In addition, it's
15494        impossible to determine at compile time whether the LHS
15495        contains a scalar or an aggregate, e.g.
15496
15497            sub f : lvalue { @a }
15498            (f()) = 1..3;
15499
15500 * ---------------------------------------------------------
15501 */
15502
15503
15504 /* A set of bit flags returned by S_aassign_scan(). Each flag indicates
15505  * that at least one of the things flagged was seen.
15506  */
15507
15508 enum {
15509     AAS_MY_SCALAR       = 0x001, /* my $scalar */
15510     AAS_MY_AGG          = 0x002, /* aggregate: my @array or my %hash */
15511     AAS_LEX_SCALAR      = 0x004, /* $lexical */
15512     AAS_LEX_AGG         = 0x008, /* @lexical or %lexical aggregate */
15513     AAS_LEX_SCALAR_COMM = 0x010, /* $lexical seen on both sides */
15514     AAS_PKG_SCALAR      = 0x020, /* $scalar (where $scalar is pkg var) */
15515     AAS_PKG_AGG         = 0x040, /* package @array or %hash aggregate */
15516     AAS_DANGEROUS       = 0x080, /* an op (other than the above)
15517                                          that's flagged OA_DANGEROUS */
15518     AAS_SAFE_SCALAR     = 0x100, /* produces at least one scalar SV that's
15519                                         not in any of the categories above */
15520     AAS_DEFAV           = 0x200  /* contains just a single '@_' on RHS */
15521 };
15522
15523
15524
15525 /* helper function for S_aassign_scan().
15526  * check a PAD-related op for commonality and/or set its generation number.
15527  * Returns a boolean indicating whether its shared */
15528
15529 static bool
15530 S_aassign_padcheck(pTHX_ OP* o, bool rhs)
15531 {
15532     if (PAD_COMPNAME_GEN(o->op_targ) == PERL_INT_MAX)
15533         /* lexical used in aliasing */
15534         return TRUE;
15535
15536     if (rhs)
15537         return cBOOL(PAD_COMPNAME_GEN(o->op_targ) == (STRLEN)PL_generation);
15538     else
15539         PAD_COMPNAME_GEN_set(o->op_targ, PL_generation);
15540
15541     return FALSE;
15542 }
15543
15544
15545 /*
15546   Helper function for OPpASSIGN_COMMON* detection in rpeep().
15547   It scans the left or right hand subtree of the aassign op, and returns a
15548   set of flags indicating what sorts of things it found there.
15549   'rhs' indicates whether we're scanning the LHS or RHS. If the former, we
15550   set PL_generation on lexical vars; if the latter, we see if
15551   PL_generation matches.
15552   'scalars_p' is a pointer to a counter of the number of scalar SVs seen.
15553   This fn will increment it by the number seen. It's not intended to
15554   be an accurate count (especially as many ops can push a variable
15555   number of SVs onto the stack); rather it's used as to test whether there
15556   can be at most 1 SV pushed; so it's only meanings are "0, 1, many".
15557 */
15558
15559 static int
15560 S_aassign_scan(pTHX_ OP* o, bool rhs, int *scalars_p)
15561 {
15562     OP *top_op           = o;
15563     OP *effective_top_op = o;
15564     int all_flags = 0;
15565
15566     while (1) {
15567     bool top = o == effective_top_op;
15568     int flags = 0;
15569     OP* next_kid = NULL;
15570
15571     /* first, look for a solitary @_ on the RHS */
15572     if (   rhs
15573         && top
15574         && (o->op_flags & OPf_KIDS)
15575         && OP_TYPE_IS_OR_WAS(o, OP_LIST)
15576     ) {
15577         OP *kid = cUNOPo->op_first;
15578         if (   (   kid->op_type == OP_PUSHMARK
15579                 || kid->op_type == OP_PADRANGE) /* ex-pushmark */
15580             && ((kid = OpSIBLING(kid)))
15581             && !OpHAS_SIBLING(kid)
15582             && kid->op_type == OP_RV2AV
15583             && !(kid->op_flags & OPf_REF)
15584             && !(kid->op_private & (OPpLVAL_INTRO|OPpMAYBE_LVSUB))
15585             && ((kid->op_flags & OPf_WANT) == OPf_WANT_LIST)
15586             && ((kid = cUNOPx(kid)->op_first))
15587             && kid->op_type == OP_GV
15588             && cGVOPx_gv(kid) == PL_defgv
15589         )
15590             flags = AAS_DEFAV;
15591     }
15592
15593     switch (o->op_type) {
15594     case OP_GVSV:
15595         (*scalars_p)++;
15596         all_flags |= AAS_PKG_SCALAR;
15597         goto do_next;
15598
15599     case OP_PADAV:
15600     case OP_PADHV:
15601         (*scalars_p) += 2;
15602         /* if !top, could be e.g. @a[0,1] */
15603         all_flags |=  (top && (o->op_flags & OPf_REF))
15604                         ? ((o->op_private & OPpLVAL_INTRO)
15605                             ? AAS_MY_AGG : AAS_LEX_AGG)
15606                         : AAS_DANGEROUS;
15607         goto do_next;
15608
15609     case OP_PADSV:
15610         {
15611             int comm = S_aassign_padcheck(aTHX_ o, rhs)
15612                         ?  AAS_LEX_SCALAR_COMM : 0;
15613             (*scalars_p)++;
15614             all_flags |= (o->op_private & OPpLVAL_INTRO)
15615                 ? (AAS_MY_SCALAR|comm) : (AAS_LEX_SCALAR|comm);
15616             goto do_next;
15617
15618         }
15619
15620     case OP_RV2AV:
15621     case OP_RV2HV:
15622         (*scalars_p) += 2;
15623         if (cUNOPx(o)->op_first->op_type != OP_GV)
15624             all_flags |= AAS_DANGEROUS; /* @{expr}, %{expr} */
15625         /* @pkg, %pkg */
15626         /* if !top, could be e.g. @a[0,1] */
15627         else if (top && (o->op_flags & OPf_REF))
15628             all_flags |= AAS_PKG_AGG;
15629         else
15630             all_flags |= AAS_DANGEROUS;
15631         goto do_next;
15632
15633     case OP_RV2SV:
15634         (*scalars_p)++;
15635         if (cUNOPx(o)->op_first->op_type != OP_GV) {
15636             (*scalars_p) += 2;
15637             all_flags |= AAS_DANGEROUS; /* ${expr} */
15638         }
15639         else
15640             all_flags |= AAS_PKG_SCALAR; /* $pkg */
15641         goto do_next;
15642
15643     case OP_SPLIT:
15644         if (o->op_private & OPpSPLIT_ASSIGN) {
15645             /* the assign in @a = split() has been optimised away
15646              * and the @a attached directly to the split op
15647              * Treat the array as appearing on the RHS, i.e.
15648              *    ... = (@a = split)
15649              * is treated like
15650              *    ... = @a;
15651              */
15652
15653             if (o->op_flags & OPf_STACKED) {
15654                 /* @{expr} = split() - the array expression is tacked
15655                  * on as an extra child to split - process kid */
15656                 next_kid = cLISTOPo->op_last;
15657                 goto do_next;
15658             }
15659
15660             /* ... else array is directly attached to split op */
15661             (*scalars_p) += 2;
15662             all_flags |= (PL_op->op_private & OPpSPLIT_LEX)
15663                             ? ((o->op_private & OPpLVAL_INTRO)
15664                                 ? AAS_MY_AGG : AAS_LEX_AGG)
15665                             : AAS_PKG_AGG;
15666             goto do_next;
15667         }
15668         (*scalars_p)++;
15669         /* other args of split can't be returned */
15670         all_flags |= AAS_SAFE_SCALAR;
15671         goto do_next;
15672
15673     case OP_UNDEF:
15674         /* undef counts as a scalar on the RHS:
15675          *   (undef, $x) = ...;         # only 1 scalar on LHS: always safe
15676          *   ($x, $y)    = (undef, $x); # 2 scalars on RHS: unsafe
15677          */
15678         if (rhs)
15679             (*scalars_p)++;
15680         flags = AAS_SAFE_SCALAR;
15681         break;
15682
15683     case OP_PUSHMARK:
15684     case OP_STUB:
15685         /* these are all no-ops; they don't push a potentially common SV
15686          * onto the stack, so they are neither AAS_DANGEROUS nor
15687          * AAS_SAFE_SCALAR */
15688         goto do_next;
15689
15690     case OP_PADRANGE: /* Ignore padrange; checking its siblings is enough */
15691         break;
15692
15693     case OP_NULL:
15694     case OP_LIST:
15695         /* these do nothing, but may have children */
15696         break;
15697
15698     default:
15699         if (PL_opargs[o->op_type] & OA_DANGEROUS) {
15700             (*scalars_p) += 2;
15701             flags = AAS_DANGEROUS;
15702             break;
15703         }
15704
15705         if (   (PL_opargs[o->op_type] & OA_TARGLEX)
15706             && (o->op_private & OPpTARGET_MY))
15707         {
15708             (*scalars_p)++;
15709             all_flags |= S_aassign_padcheck(aTHX_ o, rhs)
15710                             ? AAS_LEX_SCALAR_COMM : AAS_LEX_SCALAR;
15711             goto do_next;
15712         }
15713
15714         /* if its an unrecognised, non-dangerous op, assume that it
15715          * is the cause of at least one safe scalar */
15716         (*scalars_p)++;
15717         flags = AAS_SAFE_SCALAR;
15718         break;
15719     }
15720
15721     all_flags |= flags;
15722
15723     /* by default, process all kids next
15724      * XXX this assumes that all other ops are "transparent" - i.e. that
15725      * they can return some of their children. While this true for e.g.
15726      * sort and grep, it's not true for e.g. map. We really need a
15727      * 'transparent' flag added to regen/opcodes
15728      */
15729     if (o->op_flags & OPf_KIDS) {
15730         next_kid = cUNOPo->op_first;
15731         /* these ops do nothing but may have children; but their
15732          * children should also be treated as top-level */
15733         if (   o == effective_top_op
15734             && (o->op_type == OP_NULL || o->op_type == OP_LIST)
15735         )
15736             effective_top_op = next_kid;
15737     }
15738
15739
15740     /* If next_kid is set, someone in the code above wanted us to process
15741      * that kid and all its remaining siblings.  Otherwise, work our way
15742      * back up the tree */
15743   do_next:
15744     while (!next_kid) {
15745         if (o == top_op)
15746             return all_flags; /* at top; no parents/siblings to try */
15747         if (OpHAS_SIBLING(o)) {
15748             next_kid = o->op_sibparent;
15749             if (o == effective_top_op)
15750                 effective_top_op = next_kid;
15751         }
15752         else
15753             if (o == effective_top_op)
15754                 effective_top_op = o->op_sibparent;
15755             o = o->op_sibparent; /* try parent's next sibling */
15756
15757     }
15758     o = next_kid;
15759     } /* while */
15760
15761 }
15762
15763
15764 /* Check for in place reverse and sort assignments like "@a = reverse @a"
15765    and modify the optree to make them work inplace */
15766
15767 STATIC void
15768 S_inplace_aassign(pTHX_ OP *o) {
15769
15770     OP *modop, *modop_pushmark;
15771     OP *oright;
15772     OP *oleft, *oleft_pushmark;
15773
15774     PERL_ARGS_ASSERT_INPLACE_AASSIGN;
15775
15776     assert((o->op_flags & OPf_WANT) == OPf_WANT_VOID);
15777
15778     assert(cUNOPo->op_first->op_type == OP_NULL);
15779     modop_pushmark = cUNOPx(cUNOPo->op_first)->op_first;
15780     assert(modop_pushmark->op_type == OP_PUSHMARK);
15781     modop = OpSIBLING(modop_pushmark);
15782
15783     if (modop->op_type != OP_SORT && modop->op_type != OP_REVERSE)
15784         return;
15785
15786     /* no other operation except sort/reverse */
15787     if (OpHAS_SIBLING(modop))
15788         return;
15789
15790     assert(cUNOPx(modop)->op_first->op_type == OP_PUSHMARK);
15791     if (!(oright = OpSIBLING(cUNOPx(modop)->op_first))) return;
15792
15793     if (modop->op_flags & OPf_STACKED) {
15794         /* skip sort subroutine/block */
15795         assert(oright->op_type == OP_NULL);
15796         oright = OpSIBLING(oright);
15797     }
15798
15799     assert(OpSIBLING(cUNOPo->op_first)->op_type == OP_NULL);
15800     oleft_pushmark = cUNOPx(OpSIBLING(cUNOPo->op_first))->op_first;
15801     assert(oleft_pushmark->op_type == OP_PUSHMARK);
15802     oleft = OpSIBLING(oleft_pushmark);
15803
15804     /* Check the lhs is an array */
15805     if (!oleft ||
15806         (oleft->op_type != OP_RV2AV && oleft->op_type != OP_PADAV)
15807         || OpHAS_SIBLING(oleft)
15808         || (oleft->op_private & OPpLVAL_INTRO)
15809     )
15810         return;
15811
15812     /* Only one thing on the rhs */
15813     if (OpHAS_SIBLING(oright))
15814         return;
15815
15816     /* check the array is the same on both sides */
15817     if (oleft->op_type == OP_RV2AV) {
15818         if (oright->op_type != OP_RV2AV
15819             || !cUNOPx(oright)->op_first
15820             || cUNOPx(oright)->op_first->op_type != OP_GV
15821             || cUNOPx(oleft )->op_first->op_type != OP_GV
15822             || cGVOPx_gv(cUNOPx(oleft)->op_first) !=
15823                cGVOPx_gv(cUNOPx(oright)->op_first)
15824         )
15825             return;
15826     }
15827     else if (oright->op_type != OP_PADAV
15828         || oright->op_targ != oleft->op_targ
15829     )
15830         return;
15831
15832     /* This actually is an inplace assignment */
15833
15834     modop->op_private |= OPpSORT_INPLACE;
15835
15836     /* transfer MODishness etc from LHS arg to RHS arg */
15837     oright->op_flags = oleft->op_flags;
15838
15839     /* remove the aassign op and the lhs */
15840     op_null(o);
15841     op_null(oleft_pushmark);
15842     if (oleft->op_type == OP_RV2AV && cUNOPx(oleft)->op_first)
15843         op_null(cUNOPx(oleft)->op_first);
15844     op_null(oleft);
15845 }
15846
15847
15848
15849 /* S_maybe_multideref(): given an op_next chain of ops beginning at 'start'
15850  * that potentially represent a series of one or more aggregate derefs
15851  * (such as $a->[1]{$key}), examine the chain, and if appropriate, convert
15852  * the whole chain to a single OP_MULTIDEREF op (maybe with a few
15853  * additional ops left in too).
15854  *
15855  * The caller will have already verified that the first few ops in the
15856  * chain following 'start' indicate a multideref candidate, and will have
15857  * set 'orig_o' to the point further on in the chain where the first index
15858  * expression (if any) begins.  'orig_action' specifies what type of
15859  * beginning has already been determined by the ops between start..orig_o
15860  * (e.g.  $lex_ary[], $pkg_ary->{}, expr->[], etc).
15861  *
15862  * 'hints' contains any hints flags that need adding (currently just
15863  * OPpHINT_STRICT_REFS) as found in any rv2av/hv skipped by the caller.
15864  */
15865
15866 STATIC void
15867 S_maybe_multideref(pTHX_ OP *start, OP *orig_o, UV orig_action, U8 hints)
15868 {
15869     int pass;
15870     UNOP_AUX_item *arg_buf = NULL;
15871     bool reset_start_targ  = FALSE; /* start->op_targ needs zeroing */
15872     int index_skip         = -1;    /* don't output index arg on this action */
15873
15874     /* similar to regex compiling, do two passes; the first pass
15875      * determines whether the op chain is convertible and calculates the
15876      * buffer size; the second pass populates the buffer and makes any
15877      * changes necessary to ops (such as moving consts to the pad on
15878      * threaded builds).
15879      *
15880      * NB: for things like Coverity, note that both passes take the same
15881      * path through the logic tree (except for 'if (pass)' bits), since
15882      * both passes are following the same op_next chain; and in
15883      * particular, if it would return early on the second pass, it would
15884      * already have returned early on the first pass.
15885      */
15886     for (pass = 0; pass < 2; pass++) {
15887         OP *o                = orig_o;
15888         UV action            = orig_action;
15889         OP *first_elem_op    = NULL;  /* first seen aelem/helem */
15890         OP *top_op           = NULL;  /* highest [ah]elem/exists/del/rv2[ah]v */
15891         int action_count     = 0;     /* number of actions seen so far */
15892         int action_ix        = 0;     /* action_count % (actions per IV) */
15893         bool next_is_hash    = FALSE; /* is the next lookup to be a hash? */
15894         bool is_last         = FALSE; /* no more derefs to follow */
15895         bool maybe_aelemfast = FALSE; /* we can replace with aelemfast? */
15896         UV action_word       = 0;     /* all actions so far */
15897         UNOP_AUX_item *arg     = arg_buf;
15898         UNOP_AUX_item *action_ptr = arg_buf;
15899
15900         arg++; /* reserve slot for first action word */
15901
15902         switch (action) {
15903         case MDEREF_HV_gvsv_vivify_rv2hv_helem:
15904         case MDEREF_HV_gvhv_helem:
15905             next_is_hash = TRUE;
15906             /* FALLTHROUGH */
15907         case MDEREF_AV_gvsv_vivify_rv2av_aelem:
15908         case MDEREF_AV_gvav_aelem:
15909             if (pass) {
15910 #ifdef USE_ITHREADS
15911                 arg->pad_offset = cPADOPx(start)->op_padix;
15912                 /* stop it being swiped when nulled */
15913                 cPADOPx(start)->op_padix = 0;
15914 #else
15915                 arg->sv = cSVOPx(start)->op_sv;
15916                 cSVOPx(start)->op_sv = NULL;
15917 #endif
15918             }
15919             arg++;
15920             break;
15921
15922         case MDEREF_HV_padhv_helem:
15923         case MDEREF_HV_padsv_vivify_rv2hv_helem:
15924             next_is_hash = TRUE;
15925             /* FALLTHROUGH */
15926         case MDEREF_AV_padav_aelem:
15927         case MDEREF_AV_padsv_vivify_rv2av_aelem:
15928             if (pass) {
15929                 arg->pad_offset = start->op_targ;
15930                 /* we skip setting op_targ = 0 for now, since the intact
15931                  * OP_PADXV is needed by S_check_hash_fields_and_hekify */
15932                 reset_start_targ = TRUE;
15933             }
15934             arg++;
15935             break;
15936
15937         case MDEREF_HV_pop_rv2hv_helem:
15938             next_is_hash = TRUE;
15939             /* FALLTHROUGH */
15940         case MDEREF_AV_pop_rv2av_aelem:
15941             break;
15942
15943         default:
15944             NOT_REACHED; /* NOTREACHED */
15945             return;
15946         }
15947
15948         while (!is_last) {
15949             /* look for another (rv2av/hv; get index;
15950              * aelem/helem/exists/delele) sequence */
15951
15952             OP *kid;
15953             bool is_deref;
15954             bool ok;
15955             UV index_type = MDEREF_INDEX_none;
15956
15957             if (action_count) {
15958                 /* if this is not the first lookup, consume the rv2av/hv  */
15959
15960                 /* for N levels of aggregate lookup, we normally expect
15961                  * that the first N-1 [ah]elem ops will be flagged as
15962                  * /DEREF (so they autovivifiy if necessary), and the last
15963                  * lookup op not to be.
15964                  * For other things (like @{$h{k1}{k2}}) extra scope or
15965                  * leave ops can appear, so abandon the effort in that
15966                  * case */
15967                 if (o->op_type != OP_RV2AV && o->op_type != OP_RV2HV)
15968                     return;
15969
15970                 /* rv2av or rv2hv sKR/1 */
15971
15972                 ASSUME(!(o->op_flags & ~(OPf_WANT|OPf_KIDS|OPf_PARENS
15973                                             |OPf_REF|OPf_MOD|OPf_SPECIAL)));
15974                 if (o->op_flags != (OPf_WANT_SCALAR|OPf_KIDS|OPf_REF))
15975                     return;
15976
15977                 /* at this point, we wouldn't expect any of these
15978                  * possible private flags:
15979                  * OPpMAYBE_LVSUB, OPpOUR_INTRO, OPpLVAL_INTRO
15980                  * OPpTRUEBOOL, OPpMAYBE_TRUEBOOL (rv2hv only)
15981                  */
15982                 ASSUME(!(o->op_private &
15983                     ~(OPpHINT_STRICT_REFS|OPpARG1_MASK|OPpSLICEWARNING)));
15984
15985                 hints = (o->op_private & OPpHINT_STRICT_REFS);
15986
15987                 /* make sure the type of the previous /DEREF matches the
15988                  * type of the next lookup */
15989                 ASSUME(o->op_type == (next_is_hash ? OP_RV2HV : OP_RV2AV));
15990                 top_op = o;
15991
15992                 action = next_is_hash
15993                             ? MDEREF_HV_vivify_rv2hv_helem
15994                             : MDEREF_AV_vivify_rv2av_aelem;
15995                 o = o->op_next;
15996             }
15997
15998             /* if this is the second pass, and we're at the depth where
15999              * previously we encountered a non-simple index expression,
16000              * stop processing the index at this point */
16001             if (action_count != index_skip) {
16002
16003                 /* look for one or more simple ops that return an array
16004                  * index or hash key */
16005
16006                 switch (o->op_type) {
16007                 case OP_PADSV:
16008                     /* it may be a lexical var index */
16009                     ASSUME(!(o->op_flags & ~(OPf_WANT|OPf_PARENS
16010                                             |OPf_REF|OPf_MOD|OPf_SPECIAL)));
16011                     ASSUME(!(o->op_private &
16012                             ~(OPpPAD_STATE|OPpDEREF|OPpLVAL_INTRO)));
16013
16014                     if (   OP_GIMME(o,0) == G_SCALAR
16015                         && !(o->op_flags & (OPf_REF|OPf_MOD))
16016                         && o->op_private == 0)
16017                     {
16018                         if (pass)
16019                             arg->pad_offset = o->op_targ;
16020                         arg++;
16021                         index_type = MDEREF_INDEX_padsv;
16022                         o = o->op_next;
16023                     }
16024                     break;
16025
16026                 case OP_CONST:
16027                     if (next_is_hash) {
16028                         /* it's a constant hash index */
16029                         if (!(SvFLAGS(cSVOPo_sv) & (SVf_IOK|SVf_NOK|SVf_POK)))
16030                             /* "use constant foo => FOO; $h{+foo}" for
16031                              * some weird FOO, can leave you with constants
16032                              * that aren't simple strings. It's not worth
16033                              * the extra hassle for those edge cases */
16034                             break;
16035
16036                         {
16037                             UNOP *rop = NULL;
16038                             OP * helem_op = o->op_next;
16039
16040                             ASSUME(   helem_op->op_type == OP_HELEM
16041                                    || helem_op->op_type == OP_NULL
16042                                    || pass == 0);
16043                             if (helem_op->op_type == OP_HELEM) {
16044                                 rop = (UNOP*)(((BINOP*)helem_op)->op_first);
16045                                 if (   helem_op->op_private & OPpLVAL_INTRO
16046                                     || rop->op_type != OP_RV2HV
16047                                 )
16048                                     rop = NULL;
16049                             }
16050                             /* on first pass just check; on second pass
16051                              * hekify */
16052                             S_check_hash_fields_and_hekify(aTHX_ rop, cSVOPo,
16053                                                             pass);
16054                         }
16055
16056                         if (pass) {
16057 #ifdef USE_ITHREADS
16058                             /* Relocate sv to the pad for thread safety */
16059                             op_relocate_sv(&cSVOPo->op_sv, &o->op_targ);
16060                             arg->pad_offset = o->op_targ;
16061                             o->op_targ = 0;
16062 #else
16063                             arg->sv = cSVOPx_sv(o);
16064 #endif
16065                         }
16066                     }
16067                     else {
16068                         /* it's a constant array index */
16069                         IV iv;
16070                         SV *ix_sv = cSVOPo->op_sv;
16071                         if (!SvIOK(ix_sv))
16072                             break;
16073                         iv = SvIV(ix_sv);
16074
16075                         if (   action_count == 0
16076                             && iv >= -128
16077                             && iv <= 127
16078                             && (   action == MDEREF_AV_padav_aelem
16079                                 || action == MDEREF_AV_gvav_aelem)
16080                         )
16081                             maybe_aelemfast = TRUE;
16082
16083                         if (pass) {
16084                             arg->iv = iv;
16085                             SvREFCNT_dec_NN(cSVOPo->op_sv);
16086                         }
16087                     }
16088                     if (pass)
16089                         /* we've taken ownership of the SV */
16090                         cSVOPo->op_sv = NULL;
16091                     arg++;
16092                     index_type = MDEREF_INDEX_const;
16093                     o = o->op_next;
16094                     break;
16095
16096                 case OP_GV:
16097                     /* it may be a package var index */
16098
16099                     ASSUME(!(o->op_flags & ~(OPf_WANT|OPf_PARENS|OPf_SPECIAL)));
16100                     ASSUME(!(o->op_private & ~(OPpEARLY_CV)));
16101                     if (  (o->op_flags & ~(OPf_PARENS|OPf_SPECIAL)) != OPf_WANT_SCALAR
16102                         || o->op_private != 0
16103                     )
16104                         break;
16105
16106                     kid = o->op_next;
16107                     if (kid->op_type != OP_RV2SV)
16108                         break;
16109
16110                     ASSUME(!(kid->op_flags &
16111                             ~(OPf_WANT|OPf_KIDS|OPf_MOD|OPf_REF
16112                              |OPf_SPECIAL|OPf_PARENS)));
16113                     ASSUME(!(kid->op_private &
16114                                     ~(OPpARG1_MASK
16115                                      |OPpHINT_STRICT_REFS|OPpOUR_INTRO
16116                                      |OPpDEREF|OPpLVAL_INTRO)));
16117                     if(   (kid->op_flags &~ OPf_PARENS)
16118                             != (OPf_WANT_SCALAR|OPf_KIDS)
16119                        || (kid->op_private & ~(OPpARG1_MASK|HINT_STRICT_REFS))
16120                     )
16121                         break;
16122
16123                     if (pass) {
16124 #ifdef USE_ITHREADS
16125                         arg->pad_offset = cPADOPx(o)->op_padix;
16126                         /* stop it being swiped when nulled */
16127                         cPADOPx(o)->op_padix = 0;
16128 #else
16129                         arg->sv = cSVOPx(o)->op_sv;
16130                         cSVOPo->op_sv = NULL;
16131 #endif
16132                     }
16133                     arg++;
16134                     index_type = MDEREF_INDEX_gvsv;
16135                     o = kid->op_next;
16136                     break;
16137
16138                 } /* switch */
16139             } /* action_count != index_skip */
16140
16141             action |= index_type;
16142
16143
16144             /* at this point we have either:
16145              *   * detected what looks like a simple index expression,
16146              *     and expect the next op to be an [ah]elem, or
16147              *     an nulled  [ah]elem followed by a delete or exists;
16148              *  * found a more complex expression, so something other
16149              *    than the above follows.
16150              */
16151
16152             /* possibly an optimised away [ah]elem (where op_next is
16153              * exists or delete) */
16154             if (o->op_type == OP_NULL)
16155                 o = o->op_next;
16156
16157             /* at this point we're looking for an OP_AELEM, OP_HELEM,
16158              * OP_EXISTS or OP_DELETE */
16159
16160             /* if a custom array/hash access checker is in scope,
16161              * abandon optimisation attempt */
16162             if (  (o->op_type == OP_AELEM || o->op_type == OP_HELEM)
16163                && PL_check[o->op_type] != Perl_ck_null)
16164                 return;
16165             /* similarly for customised exists and delete */
16166             if (  (o->op_type == OP_EXISTS)
16167                && PL_check[o->op_type] != Perl_ck_exists)
16168                 return;
16169             if (  (o->op_type == OP_DELETE)
16170                && PL_check[o->op_type] != Perl_ck_delete)
16171                 return;
16172
16173             if (   o->op_type != OP_AELEM
16174                 || (o->op_private &
16175                       (OPpLVAL_INTRO|OPpLVAL_DEFER|OPpDEREF|OPpMAYBE_LVSUB))
16176                 )
16177                 maybe_aelemfast = FALSE;
16178
16179             /* look for aelem/helem/exists/delete. If it's not the last elem
16180              * lookup, it *must* have OPpDEREF_AV/HV, but not many other
16181              * flags; if it's the last, then it mustn't have
16182              * OPpDEREF_AV/HV, but may have lots of other flags, like
16183              * OPpLVAL_INTRO etc
16184              */
16185
16186             if (   index_type == MDEREF_INDEX_none
16187                 || (   o->op_type != OP_AELEM  && o->op_type != OP_HELEM
16188                     && o->op_type != OP_EXISTS && o->op_type != OP_DELETE)
16189             )
16190                 ok = FALSE;
16191             else {
16192                 /* we have aelem/helem/exists/delete with valid simple index */
16193
16194                 is_deref =    (o->op_type == OP_AELEM || o->op_type == OP_HELEM)
16195                            && (   (o->op_private & OPpDEREF) == OPpDEREF_AV
16196                                || (o->op_private & OPpDEREF) == OPpDEREF_HV);
16197
16198                 /* This doesn't make much sense but is legal:
16199                  *    @{ local $x[0][0] } = 1
16200                  * Since scope exit will undo the autovivification,
16201                  * don't bother in the first place. The OP_LEAVE
16202                  * assertion is in case there are other cases of both
16203                  * OPpLVAL_INTRO and OPpDEREF which don't include a scope
16204                  * exit that would undo the local - in which case this
16205                  * block of code would need rethinking.
16206                  */
16207                 if (is_deref && (o->op_private & OPpLVAL_INTRO)) {
16208 #ifdef DEBUGGING
16209                     OP *n = o->op_next;
16210                     while (n && (  n->op_type == OP_NULL
16211                                 || n->op_type == OP_LIST
16212                                 || n->op_type == OP_SCALAR))
16213                         n = n->op_next;
16214                     assert(n && n->op_type == OP_LEAVE);
16215 #endif
16216                     o->op_private &= ~OPpDEREF;
16217                     is_deref = FALSE;
16218                 }
16219
16220                 if (is_deref) {
16221                     ASSUME(!(o->op_flags &
16222                                  ~(OPf_WANT|OPf_KIDS|OPf_MOD|OPf_PARENS)));
16223                     ASSUME(!(o->op_private & ~(OPpARG2_MASK|OPpDEREF)));
16224
16225                     ok =    (o->op_flags &~ OPf_PARENS)
16226                                == (OPf_WANT_SCALAR|OPf_KIDS|OPf_MOD)
16227                          && !(o->op_private & ~(OPpDEREF|OPpARG2_MASK));
16228                 }
16229                 else if (o->op_type == OP_EXISTS) {
16230                     ASSUME(!(o->op_flags & ~(OPf_WANT|OPf_KIDS|OPf_PARENS
16231                                 |OPf_REF|OPf_MOD|OPf_SPECIAL)));
16232                     ASSUME(!(o->op_private & ~(OPpARG1_MASK|OPpEXISTS_SUB)));
16233                     ok =  !(o->op_private & ~OPpARG1_MASK);
16234                 }
16235                 else if (o->op_type == OP_DELETE) {
16236                     ASSUME(!(o->op_flags & ~(OPf_WANT|OPf_KIDS|OPf_PARENS
16237                                 |OPf_REF|OPf_MOD|OPf_SPECIAL)));
16238                     ASSUME(!(o->op_private &
16239                                     ~(OPpARG1_MASK|OPpSLICE|OPpLVAL_INTRO)));
16240                     /* don't handle slices or 'local delete'; the latter
16241                      * is fairly rare, and has a complex runtime */
16242                     ok =  !(o->op_private & ~OPpARG1_MASK);
16243                     if (OP_TYPE_IS_OR_WAS(cUNOPo->op_first, OP_AELEM))
16244                         /* skip handling run-tome error */
16245                         ok = (ok && cBOOL(o->op_flags & OPf_SPECIAL));
16246                 }
16247                 else {
16248                     ASSUME(o->op_type == OP_AELEM || o->op_type == OP_HELEM);
16249                     ASSUME(!(o->op_flags & ~(OPf_WANT|OPf_KIDS|OPf_MOD
16250                                             |OPf_PARENS|OPf_REF|OPf_SPECIAL)));
16251                     ASSUME(!(o->op_private & ~(OPpARG2_MASK|OPpMAYBE_LVSUB
16252                                     |OPpLVAL_DEFER|OPpDEREF|OPpLVAL_INTRO)));
16253                     ok = (o->op_private & OPpDEREF) != OPpDEREF_SV;
16254                 }
16255             }
16256
16257             if (ok) {
16258                 if (!first_elem_op)
16259                     first_elem_op = o;
16260                 top_op = o;
16261                 if (is_deref) {
16262                     next_is_hash = cBOOL((o->op_private & OPpDEREF) == OPpDEREF_HV);
16263                     o = o->op_next;
16264                 }
16265                 else {
16266                     is_last = TRUE;
16267                     action |= MDEREF_FLAG_last;
16268                 }
16269             }
16270             else {
16271                 /* at this point we have something that started
16272                  * promisingly enough (with rv2av or whatever), but failed
16273                  * to find a simple index followed by an
16274                  * aelem/helem/exists/delete. If this is the first action,
16275                  * give up; but if we've already seen at least one
16276                  * aelem/helem, then keep them and add a new action with
16277                  * MDEREF_INDEX_none, which causes it to do the vivify
16278                  * from the end of the previous lookup, and do the deref,
16279                  * but stop at that point. So $a[0][expr] will do one
16280                  * av_fetch, vivify and deref, then continue executing at
16281                  * expr */
16282                 if (!action_count)
16283                     return;
16284                 is_last = TRUE;
16285                 index_skip = action_count;
16286                 action |= MDEREF_FLAG_last;
16287                 if (index_type != MDEREF_INDEX_none)
16288                     arg--;
16289             }
16290
16291             action_word |= (action << (action_ix * MDEREF_SHIFT));
16292             action_ix++;
16293             action_count++;
16294             /* if there's no space for the next action, reserve a new slot
16295              * for it *before* we start adding args for that action */
16296             if ((action_ix + 1) * MDEREF_SHIFT > UVSIZE*8) {
16297                 if (pass)
16298                     action_ptr->uv = action_word;
16299                 action_word = 0;
16300                 action_ptr = arg;
16301                 arg++;
16302                 action_ix = 0;
16303             }
16304         } /* while !is_last */
16305
16306         /* success! */
16307
16308         if (!action_ix)
16309             /* slot reserved for next action word not now needed */
16310             arg--;
16311         else if (pass)
16312             action_ptr->uv = action_word;
16313
16314         if (pass) {
16315             OP *mderef;
16316             OP *p, *q;
16317
16318             mderef = newUNOP_AUX(OP_MULTIDEREF, 0, NULL, arg_buf);
16319             if (index_skip == -1) {
16320                 mderef->op_flags = o->op_flags
16321                         & (OPf_WANT|OPf_MOD|(next_is_hash ? OPf_SPECIAL : 0));
16322                 if (o->op_type == OP_EXISTS)
16323                     mderef->op_private = OPpMULTIDEREF_EXISTS;
16324                 else if (o->op_type == OP_DELETE)
16325                     mderef->op_private = OPpMULTIDEREF_DELETE;
16326                 else
16327                     mderef->op_private = o->op_private
16328                         & (OPpMAYBE_LVSUB|OPpLVAL_DEFER|OPpLVAL_INTRO);
16329             }
16330             /* accumulate strictness from every level (although I don't think
16331              * they can actually vary) */
16332             mderef->op_private |= hints;
16333
16334             /* integrate the new multideref op into the optree and the
16335              * op_next chain.
16336              *
16337              * In general an op like aelem or helem has two child
16338              * sub-trees: the aggregate expression (a_expr) and the
16339              * index expression (i_expr):
16340              *
16341              *     aelem
16342              *       |
16343              *     a_expr - i_expr
16344              *
16345              * The a_expr returns an AV or HV, while the i-expr returns an
16346              * index. In general a multideref replaces most or all of a
16347              * multi-level tree, e.g.
16348              *
16349              *     exists
16350              *       |
16351              *     ex-aelem
16352              *       |
16353              *     rv2av  - i_expr1
16354              *       |
16355              *     helem
16356              *       |
16357              *     rv2hv  - i_expr2
16358              *       |
16359              *     aelem
16360              *       |
16361              *     a_expr - i_expr3
16362              *
16363              * With multideref, all the i_exprs will be simple vars or
16364              * constants, except that i_expr1 may be arbitrary in the case
16365              * of MDEREF_INDEX_none.
16366              *
16367              * The bottom-most a_expr will be either:
16368              *   1) a simple var (so padXv or gv+rv2Xv);
16369              *   2) a simple scalar var dereferenced (e.g. $r->[0]):
16370              *      so a simple var with an extra rv2Xv;
16371              *   3) or an arbitrary expression.
16372              *
16373              * 'start', the first op in the execution chain, will point to
16374              *   1),2): the padXv or gv op;
16375              *   3):    the rv2Xv which forms the last op in the a_expr
16376              *          execution chain, and the top-most op in the a_expr
16377              *          subtree.
16378              *
16379              * For all cases, the 'start' node is no longer required,
16380              * but we can't free it since one or more external nodes
16381              * may point to it. E.g. consider
16382              *     $h{foo} = $a ? $b : $c
16383              * Here, both the op_next and op_other branches of the
16384              * cond_expr point to the gv[*h] of the hash expression, so
16385              * we can't free the 'start' op.
16386              *
16387              * For expr->[...], we need to save the subtree containing the
16388              * expression; for the other cases, we just need to save the
16389              * start node.
16390              * So in all cases, we null the start op and keep it around by
16391              * making it the child of the multideref op; for the expr->
16392              * case, the expr will be a subtree of the start node.
16393              *
16394              * So in the simple 1,2 case the  optree above changes to
16395              *
16396              *     ex-exists
16397              *       |
16398              *     multideref
16399              *       |
16400              *     ex-gv (or ex-padxv)
16401              *
16402              *  with the op_next chain being
16403              *
16404              *  -> ex-gv -> multideref -> op-following-ex-exists ->
16405              *
16406              *  In the 3 case, we have
16407              *
16408              *     ex-exists
16409              *       |
16410              *     multideref
16411              *       |
16412              *     ex-rv2xv
16413              *       |
16414              *    rest-of-a_expr
16415              *      subtree
16416              *
16417              *  and
16418              *
16419              *  -> rest-of-a_expr subtree ->
16420              *    ex-rv2xv -> multideref -> op-following-ex-exists ->
16421              *
16422              *
16423              * Where the last i_expr is non-simple (i.e. MDEREF_INDEX_none,
16424              * e.g. $a[0]{foo}[$x+1], the next rv2xv is nulled and the
16425              * multideref attached as the child, e.g.
16426              *
16427              *     exists
16428              *       |
16429              *     ex-aelem
16430              *       |
16431              *     ex-rv2av  - i_expr1
16432              *       |
16433              *     multideref
16434              *       |
16435              *     ex-whatever
16436              *
16437              */
16438
16439             /* if we free this op, don't free the pad entry */
16440             if (reset_start_targ)
16441                 start->op_targ = 0;
16442
16443
16444             /* Cut the bit we need to save out of the tree and attach to
16445              * the multideref op, then free the rest of the tree */
16446
16447             /* find parent of node to be detached (for use by splice) */
16448             p = first_elem_op;
16449             if (   orig_action == MDEREF_AV_pop_rv2av_aelem
16450                 || orig_action == MDEREF_HV_pop_rv2hv_helem)
16451             {
16452                 /* there is an arbitrary expression preceding us, e.g.
16453                  * expr->[..]? so we need to save the 'expr' subtree */
16454                 if (p->op_type == OP_EXISTS || p->op_type == OP_DELETE)
16455                     p = cUNOPx(p)->op_first;
16456                 ASSUME(   start->op_type == OP_RV2AV
16457                        || start->op_type == OP_RV2HV);
16458             }
16459             else {
16460                 /* either a padXv or rv2Xv+gv, maybe with an ex-Xelem
16461                  * above for exists/delete. */
16462                 while (   (p->op_flags & OPf_KIDS)
16463                        && cUNOPx(p)->op_first != start
16464                 )
16465                     p = cUNOPx(p)->op_first;
16466             }
16467             ASSUME(cUNOPx(p)->op_first == start);
16468
16469             /* detach from main tree, and re-attach under the multideref */
16470             op_sibling_splice(mderef, NULL, 0,
16471                     op_sibling_splice(p, NULL, 1, NULL));
16472             op_null(start);
16473
16474             start->op_next = mderef;
16475
16476             mderef->op_next = index_skip == -1 ? o->op_next : o;
16477
16478             /* excise and free the original tree, and replace with
16479              * the multideref op */
16480             p = op_sibling_splice(top_op, NULL, -1, mderef);
16481             while (p) {
16482                 q = OpSIBLING(p);
16483                 op_free(p);
16484                 p = q;
16485             }
16486             op_null(top_op);
16487         }
16488         else {
16489             Size_t size = arg - arg_buf;
16490
16491             if (maybe_aelemfast && action_count == 1)
16492                 return;
16493
16494             arg_buf = (UNOP_AUX_item*)PerlMemShared_malloc(
16495                                 sizeof(UNOP_AUX_item) * (size + 1));
16496             /* for dumping etc: store the length in a hidden first slot;
16497              * we set the op_aux pointer to the second slot */
16498             arg_buf->uv = size;
16499             arg_buf++;
16500         }
16501     } /* for (pass = ...) */
16502 }
16503
16504 /* See if the ops following o are such that o will always be executed in
16505  * boolean context: that is, the SV which o pushes onto the stack will
16506  * only ever be consumed by later ops via SvTRUE(sv) or similar.
16507  * If so, set a suitable private flag on o. Normally this will be
16508  * bool_flag; but see below why maybe_flag is needed too.
16509  *
16510  * Typically the two flags you pass will be the generic OPpTRUEBOOL and
16511  * OPpMAYBE_TRUEBOOL, buts it's possible that for some ops those bits may
16512  * already be taken, so you'll have to give that op two different flags.
16513  *
16514  * More explanation of 'maybe_flag' and 'safe_and' parameters.
16515  * The binary logical ops &&, ||, // (plus 'if' and 'unless' which use
16516  * those underlying ops) short-circuit, which means that rather than
16517  * necessarily returning a truth value, they may return the LH argument,
16518  * which may not be boolean. For example in $x = (keys %h || -1), keys
16519  * should return a key count rather than a boolean, even though its
16520  * sort-of being used in boolean context.
16521  *
16522  * So we only consider such logical ops to provide boolean context to
16523  * their LH argument if they themselves are in void or boolean context.
16524  * However, sometimes the context isn't known until run-time. In this
16525  * case the op is marked with the maybe_flag flag it.
16526  *
16527  * Consider the following.
16528  *
16529  *     sub f { ....;  if (%h) { .... } }
16530  *
16531  * This is actually compiled as
16532  *
16533  *     sub f { ....;  %h && do { .... } }
16534  *
16535  * Here we won't know until runtime whether the final statement (and hence
16536  * the &&) is in void context and so is safe to return a boolean value.
16537  * So mark o with maybe_flag rather than the bool_flag.
16538  * Note that there is cost associated with determining context at runtime
16539  * (e.g. a call to block_gimme()), so it may not be worth setting (at
16540  * compile time) and testing (at runtime) maybe_flag if the scalar verses
16541  * boolean costs savings are marginal.
16542  *
16543  * However, we can do slightly better with && (compared to || and //):
16544  * this op only returns its LH argument when that argument is false. In
16545  * this case, as long as the op promises to return a false value which is
16546  * valid in both boolean and scalar contexts, we can mark an op consumed
16547  * by && with bool_flag rather than maybe_flag.
16548  * For example as long as pp_padhv and pp_rv2hv return &PL_sv_zero rather
16549  * than &PL_sv_no for a false result in boolean context, then it's safe. An
16550  * op which promises to handle this case is indicated by setting safe_and
16551  * to true.
16552  */
16553
16554 static void
16555 S_check_for_bool_cxt(OP*o, bool safe_and, U8 bool_flag, U8 maybe_flag)
16556 {
16557     OP *lop;
16558     U8 flag = 0;
16559
16560     assert((o->op_flags & OPf_WANT) == OPf_WANT_SCALAR);
16561
16562     /* OPpTARGET_MY and boolean context probably don't mix well.
16563      * If someone finds a valid use case, maybe add an extra flag to this
16564      * function which indicates its safe to do so for this op? */
16565     assert(!(   (PL_opargs[o->op_type] & OA_TARGLEX)
16566              && (o->op_private & OPpTARGET_MY)));
16567
16568     lop = o->op_next;
16569
16570     while (lop) {
16571         switch (lop->op_type) {
16572         case OP_NULL:
16573         case OP_SCALAR:
16574             break;
16575
16576         /* these two consume the stack argument in the scalar case,
16577          * and treat it as a boolean in the non linenumber case */
16578         case OP_FLIP:
16579         case OP_FLOP:
16580             if (   ((lop->op_flags & OPf_WANT) == OPf_WANT_LIST)
16581                 || (lop->op_private & OPpFLIP_LINENUM))
16582             {
16583                 lop = NULL;
16584                 break;
16585             }
16586             /* FALLTHROUGH */
16587         /* these never leave the original value on the stack */
16588         case OP_NOT:
16589         case OP_XOR:
16590         case OP_COND_EXPR:
16591         case OP_GREPWHILE:
16592             flag = bool_flag;
16593             lop = NULL;
16594             break;
16595
16596         /* OR DOR and AND evaluate their arg as a boolean, but then may
16597          * leave the original scalar value on the stack when following the
16598          * op_next route. If not in void context, we need to ensure
16599          * that whatever follows consumes the arg only in boolean context
16600          * too.
16601          */
16602         case OP_AND:
16603             if (safe_and) {
16604                 flag = bool_flag;
16605                 lop = NULL;
16606                 break;
16607             }
16608             /* FALLTHROUGH */
16609         case OP_OR:
16610         case OP_DOR:
16611             if ((lop->op_flags & OPf_WANT) == OPf_WANT_VOID) {
16612                 flag = bool_flag;
16613                 lop = NULL;
16614             }
16615             else if (!(lop->op_flags & OPf_WANT)) {
16616                 /* unknown context - decide at runtime */
16617                 flag = maybe_flag;
16618                 lop = NULL;
16619             }
16620             break;
16621
16622         default:
16623             lop = NULL;
16624             break;
16625         }
16626
16627         if (lop)
16628             lop = lop->op_next;
16629     }
16630
16631     o->op_private |= flag;
16632 }
16633
16634
16635
16636 /* mechanism for deferring recursion in rpeep() */
16637
16638 #define MAX_DEFERRED 4
16639
16640 #define DEFER(o) \
16641   STMT_START { \
16642     if (defer_ix == (MAX_DEFERRED-1)) { \
16643         OP **defer = defer_queue[defer_base]; \
16644         CALL_RPEEP(*defer); \
16645         S_prune_chain_head(defer); \
16646         defer_base = (defer_base + 1) % MAX_DEFERRED; \
16647         defer_ix--; \
16648     } \
16649     defer_queue[(defer_base + ++defer_ix) % MAX_DEFERRED] = &(o); \
16650   } STMT_END
16651
16652 #define IS_AND_OP(o)   (o->op_type == OP_AND)
16653 #define IS_OR_OP(o)    (o->op_type == OP_OR)
16654
16655
16656 /* A peephole optimizer.  We visit the ops in the order they're to execute.
16657  * See the comments at the top of this file for more details about when
16658  * peep() is called */
16659
16660 void
16661 Perl_rpeep(pTHX_ OP *o)
16662 {
16663     OP* oldop = NULL;
16664     OP* oldoldop = NULL;
16665     OP** defer_queue[MAX_DEFERRED]; /* small queue of deferred branches */
16666     int defer_base = 0;
16667     int defer_ix = -1;
16668
16669     if (!o || o->op_opt)
16670         return;
16671
16672     assert(o->op_type != OP_FREED);
16673
16674     ENTER;
16675     SAVEOP();
16676     SAVEVPTR(PL_curcop);
16677     for (;; o = o->op_next) {
16678         if (o && o->op_opt)
16679             o = NULL;
16680         if (!o) {
16681             while (defer_ix >= 0) {
16682                 OP **defer =
16683                         defer_queue[(defer_base + defer_ix--) % MAX_DEFERRED];
16684                 CALL_RPEEP(*defer);
16685                 S_prune_chain_head(defer);
16686             }
16687             break;
16688         }
16689
16690       redo:
16691
16692         /* oldoldop -> oldop -> o should be a chain of 3 adjacent ops */
16693         assert(!oldoldop || oldoldop->op_next == oldop);
16694         assert(!oldop    || oldop->op_next    == o);
16695
16696         /* By default, this op has now been optimised. A couple of cases below
16697            clear this again.  */
16698         o->op_opt = 1;
16699         PL_op = o;
16700
16701         /* look for a series of 1 or more aggregate derefs, e.g.
16702          *   $a[1]{foo}[$i]{$k}
16703          * and replace with a single OP_MULTIDEREF op.
16704          * Each index must be either a const, or a simple variable,
16705          *
16706          * First, look for likely combinations of starting ops,
16707          * corresponding to (global and lexical variants of)
16708          *     $a[...]   $h{...}
16709          *     $r->[...] $r->{...}
16710          *     (preceding expression)->[...]
16711          *     (preceding expression)->{...}
16712          * and if so, call maybe_multideref() to do a full inspection
16713          * of the op chain and if appropriate, replace with an
16714          * OP_MULTIDEREF
16715          */
16716         {
16717             UV action;
16718             OP *o2 = o;
16719             U8 hints = 0;
16720
16721             switch (o2->op_type) {
16722             case OP_GV:
16723                 /* $pkg[..]   :   gv[*pkg]
16724                  * $pkg->[...]:   gv[*pkg]; rv2sv sKM/DREFAV */
16725
16726                 /* Fail if there are new op flag combinations that we're
16727                  * not aware of, rather than:
16728                  *  * silently failing to optimise, or
16729                  *  * silently optimising the flag away.
16730                  * If this ASSUME starts failing, examine what new flag
16731                  * has been added to the op, and decide whether the
16732                  * optimisation should still occur with that flag, then
16733                  * update the code accordingly. This applies to all the
16734                  * other ASSUMEs in the block of code too.
16735                  */
16736                 ASSUME(!(o2->op_flags &
16737                             ~(OPf_WANT|OPf_MOD|OPf_PARENS|OPf_SPECIAL)));
16738                 ASSUME(!(o2->op_private & ~OPpEARLY_CV));
16739
16740                 o2 = o2->op_next;
16741
16742                 if (o2->op_type == OP_RV2AV) {
16743                     action = MDEREF_AV_gvav_aelem;
16744                     goto do_deref;
16745                 }
16746
16747                 if (o2->op_type == OP_RV2HV) {
16748                     action = MDEREF_HV_gvhv_helem;
16749                     goto do_deref;
16750                 }
16751
16752                 if (o2->op_type != OP_RV2SV)
16753                     break;
16754
16755                 /* at this point we've seen gv,rv2sv, so the only valid
16756                  * construct left is $pkg->[] or $pkg->{} */
16757
16758                 ASSUME(!(o2->op_flags & OPf_STACKED));
16759                 if ((o2->op_flags & (OPf_WANT|OPf_REF|OPf_MOD|OPf_SPECIAL))
16760                             != (OPf_WANT_SCALAR|OPf_MOD))
16761                     break;
16762
16763                 ASSUME(!(o2->op_private & ~(OPpARG1_MASK|HINT_STRICT_REFS
16764                                     |OPpOUR_INTRO|OPpDEREF|OPpLVAL_INTRO)));
16765                 if (o2->op_private & (OPpOUR_INTRO|OPpLVAL_INTRO))
16766                     break;
16767                 if (   (o2->op_private & OPpDEREF) != OPpDEREF_AV
16768                     && (o2->op_private & OPpDEREF) != OPpDEREF_HV)
16769                     break;
16770
16771                 o2 = o2->op_next;
16772                 if (o2->op_type == OP_RV2AV) {
16773                     action = MDEREF_AV_gvsv_vivify_rv2av_aelem;
16774                     goto do_deref;
16775                 }
16776                 if (o2->op_type == OP_RV2HV) {
16777                     action = MDEREF_HV_gvsv_vivify_rv2hv_helem;
16778                     goto do_deref;
16779                 }
16780                 break;
16781
16782             case OP_PADSV:
16783                 /* $lex->[...]: padsv[$lex] sM/DREFAV */
16784
16785                 ASSUME(!(o2->op_flags &
16786                     ~(OPf_WANT|OPf_PARENS|OPf_REF|OPf_MOD|OPf_SPECIAL)));
16787                 if ((o2->op_flags &
16788                         (OPf_WANT|OPf_REF|OPf_MOD|OPf_SPECIAL))
16789                      != (OPf_WANT_SCALAR|OPf_MOD))
16790                     break;
16791
16792                 ASSUME(!(o2->op_private &
16793                                 ~(OPpPAD_STATE|OPpDEREF|OPpLVAL_INTRO)));
16794                 /* skip if state or intro, or not a deref */
16795                 if (      o2->op_private != OPpDEREF_AV
16796                        && o2->op_private != OPpDEREF_HV)
16797                     break;
16798
16799                 o2 = o2->op_next;
16800                 if (o2->op_type == OP_RV2AV) {
16801                     action = MDEREF_AV_padsv_vivify_rv2av_aelem;
16802                     goto do_deref;
16803                 }
16804                 if (o2->op_type == OP_RV2HV) {
16805                     action = MDEREF_HV_padsv_vivify_rv2hv_helem;
16806                     goto do_deref;
16807                 }
16808                 break;
16809
16810             case OP_PADAV:
16811             case OP_PADHV:
16812                 /*    $lex[..]:  padav[@lex:1,2] sR *
16813                  * or $lex{..}:  padhv[%lex:1,2] sR */
16814                 ASSUME(!(o2->op_flags & ~(OPf_WANT|OPf_MOD|OPf_PARENS|
16815                                             OPf_REF|OPf_SPECIAL)));
16816                 if ((o2->op_flags &
16817                         (OPf_WANT|OPf_REF|OPf_MOD|OPf_SPECIAL))
16818                      != (OPf_WANT_SCALAR|OPf_REF))
16819                     break;
16820                 if (o2->op_flags != (OPf_WANT_SCALAR|OPf_REF))
16821                     break;
16822                 /* OPf_PARENS isn't currently used in this case;
16823                  * if that changes, let us know! */
16824                 ASSUME(!(o2->op_flags & OPf_PARENS));
16825
16826                 /* at this point, we wouldn't expect any of the remaining
16827                  * possible private flags:
16828                  * OPpPAD_STATE, OPpLVAL_INTRO, OPpTRUEBOOL,
16829                  * OPpMAYBE_TRUEBOOL, OPpMAYBE_LVSUB
16830                  *
16831                  * OPpSLICEWARNING shouldn't affect runtime
16832                  */
16833                 ASSUME(!(o2->op_private & ~(OPpSLICEWARNING)));
16834
16835                 action = o2->op_type == OP_PADAV
16836                             ? MDEREF_AV_padav_aelem
16837                             : MDEREF_HV_padhv_helem;
16838                 o2 = o2->op_next;
16839                 S_maybe_multideref(aTHX_ o, o2, action, 0);
16840                 break;
16841
16842
16843             case OP_RV2AV:
16844             case OP_RV2HV:
16845                 action = o2->op_type == OP_RV2AV
16846                             ? MDEREF_AV_pop_rv2av_aelem
16847                             : MDEREF_HV_pop_rv2hv_helem;
16848                 /* FALLTHROUGH */
16849             do_deref:
16850                 /* (expr)->[...]:  rv2av sKR/1;
16851                  * (expr)->{...}:  rv2hv sKR/1; */
16852
16853                 ASSUME(o2->op_type == OP_RV2AV || o2->op_type == OP_RV2HV);
16854
16855                 ASSUME(!(o2->op_flags & ~(OPf_WANT|OPf_KIDS|OPf_PARENS
16856                                 |OPf_REF|OPf_MOD|OPf_STACKED|OPf_SPECIAL)));
16857                 if (o2->op_flags != (OPf_WANT_SCALAR|OPf_KIDS|OPf_REF))
16858                     break;
16859
16860                 /* at this point, we wouldn't expect any of these
16861                  * possible private flags:
16862                  * OPpMAYBE_LVSUB, OPpLVAL_INTRO
16863                  * OPpTRUEBOOL, OPpMAYBE_TRUEBOOL, (rv2hv only)
16864                  */
16865                 ASSUME(!(o2->op_private &
16866                     ~(OPpHINT_STRICT_REFS|OPpARG1_MASK|OPpSLICEWARNING
16867                      |OPpOUR_INTRO)));
16868                 hints |= (o2->op_private & OPpHINT_STRICT_REFS);
16869
16870                 o2 = o2->op_next;
16871
16872                 S_maybe_multideref(aTHX_ o, o2, action, hints);
16873                 break;
16874
16875             default:
16876                 break;
16877             }
16878         }
16879
16880
16881         switch (o->op_type) {
16882         case OP_DBSTATE:
16883             PL_curcop = ((COP*)o);              /* for warnings */
16884             break;
16885         case OP_NEXTSTATE:
16886             PL_curcop = ((COP*)o);              /* for warnings */
16887
16888             /* Optimise a "return ..." at the end of a sub to just be "...".
16889              * This saves 2 ops. Before:
16890              * 1  <;> nextstate(main 1 -e:1) v ->2
16891              * 4  <@> return K ->5
16892              * 2    <0> pushmark s ->3
16893              * -    <1> ex-rv2sv sK/1 ->4
16894              * 3      <#> gvsv[*cat] s ->4
16895              *
16896              * After:
16897              * -  <@> return K ->-
16898              * -    <0> pushmark s ->2
16899              * -    <1> ex-rv2sv sK/1 ->-
16900              * 2      <$> gvsv(*cat) s ->3
16901              */
16902             {
16903                 OP *next = o->op_next;
16904                 OP *sibling = OpSIBLING(o);
16905                 if (   OP_TYPE_IS(next, OP_PUSHMARK)
16906                     && OP_TYPE_IS(sibling, OP_RETURN)
16907                     && OP_TYPE_IS(sibling->op_next, OP_LINESEQ)
16908                     && ( OP_TYPE_IS(sibling->op_next->op_next, OP_LEAVESUB)
16909                        ||OP_TYPE_IS(sibling->op_next->op_next,
16910                                     OP_LEAVESUBLV))
16911                     && cUNOPx(sibling)->op_first == next
16912                     && OpHAS_SIBLING(next) && OpSIBLING(next)->op_next
16913                     && next->op_next
16914                 ) {
16915                     /* Look through the PUSHMARK's siblings for one that
16916                      * points to the RETURN */
16917                     OP *top = OpSIBLING(next);
16918                     while (top && top->op_next) {
16919                         if (top->op_next == sibling) {
16920                             top->op_next = sibling->op_next;
16921                             o->op_next = next->op_next;
16922                             break;
16923                         }
16924                         top = OpSIBLING(top);
16925                     }
16926                 }
16927             }
16928
16929             /* Optimise 'my $x; my $y;' into 'my ($x, $y);'
16930              *
16931              * This latter form is then suitable for conversion into padrange
16932              * later on. Convert:
16933              *
16934              *   nextstate1 -> padop1 -> nextstate2 -> padop2 -> nextstate3
16935              *
16936              * into:
16937              *
16938              *   nextstate1 ->     listop     -> nextstate3
16939              *                 /            \
16940              *         pushmark -> padop1 -> padop2
16941              */
16942             if (o->op_next && (
16943                     o->op_next->op_type == OP_PADSV
16944                  || o->op_next->op_type == OP_PADAV
16945                  || o->op_next->op_type == OP_PADHV
16946                 )
16947                 && !(o->op_next->op_private & ~OPpLVAL_INTRO)
16948                 && o->op_next->op_next && o->op_next->op_next->op_type == OP_NEXTSTATE
16949                 && o->op_next->op_next->op_next && (
16950                     o->op_next->op_next->op_next->op_type == OP_PADSV
16951                  || o->op_next->op_next->op_next->op_type == OP_PADAV
16952                  || o->op_next->op_next->op_next->op_type == OP_PADHV
16953                 )
16954                 && !(o->op_next->op_next->op_next->op_private & ~OPpLVAL_INTRO)
16955                 && o->op_next->op_next->op_next->op_next && o->op_next->op_next->op_next->op_next->op_type == OP_NEXTSTATE
16956                 && (!CopLABEL((COP*)o)) /* Don't mess with labels */
16957                 && (!CopLABEL((COP*)o->op_next->op_next)) /* ... */
16958             ) {
16959                 OP *pad1, *ns2, *pad2, *ns3, *newop, *newpm;
16960
16961                 pad1 =    o->op_next;
16962                 ns2  = pad1->op_next;
16963                 pad2 =  ns2->op_next;
16964                 ns3  = pad2->op_next;
16965
16966                 /* we assume here that the op_next chain is the same as
16967                  * the op_sibling chain */
16968                 assert(OpSIBLING(o)    == pad1);
16969                 assert(OpSIBLING(pad1) == ns2);
16970                 assert(OpSIBLING(ns2)  == pad2);
16971                 assert(OpSIBLING(pad2) == ns3);
16972
16973                 /* excise and delete ns2 */
16974                 op_sibling_splice(NULL, pad1, 1, NULL);
16975                 op_free(ns2);
16976
16977                 /* excise pad1 and pad2 */
16978                 op_sibling_splice(NULL, o, 2, NULL);
16979
16980                 /* create new listop, with children consisting of:
16981                  * a new pushmark, pad1, pad2. */
16982                 newop = newLISTOP(OP_LIST, 0, pad1, pad2);
16983                 newop->op_flags |= OPf_PARENS;
16984                 newop->op_flags = (newop->op_flags & ~OPf_WANT) | OPf_WANT_VOID;
16985
16986                 /* insert newop between o and ns3 */
16987                 op_sibling_splice(NULL, o, 0, newop);
16988
16989                 /*fixup op_next chain */
16990                 newpm = cUNOPx(newop)->op_first; /* pushmark */
16991                 o    ->op_next = newpm;
16992                 newpm->op_next = pad1;
16993                 pad1 ->op_next = pad2;
16994                 pad2 ->op_next = newop; /* listop */
16995                 newop->op_next = ns3;
16996
16997                 /* Ensure pushmark has this flag if padops do */
16998                 if (pad1->op_flags & OPf_MOD && pad2->op_flags & OPf_MOD) {
16999                     newpm->op_flags |= OPf_MOD;
17000                 }
17001
17002                 break;
17003             }
17004
17005             /* Two NEXTSTATEs in a row serve no purpose. Except if they happen
17006                to carry two labels. For now, take the easier option, and skip
17007                this optimisation if the first NEXTSTATE has a label.  */
17008             if (!CopLABEL((COP*)o) && !PERLDB_NOOPT) {
17009                 OP *nextop = o->op_next;
17010                 while (nextop) {
17011                     switch (nextop->op_type) {
17012                         case OP_NULL:
17013                         case OP_SCALAR:
17014                         case OP_LINESEQ:
17015                         case OP_SCOPE:
17016                             nextop = nextop->op_next;
17017                             continue;
17018                     }
17019                     break;
17020                 }
17021
17022                 if (nextop && (nextop->op_type == OP_NEXTSTATE)) {
17023                     op_null(o);
17024                     if (oldop)
17025                         oldop->op_next = nextop;
17026                     o = nextop;
17027                     /* Skip (old)oldop assignment since the current oldop's
17028                        op_next already points to the next op.  */
17029                     goto redo;
17030                 }
17031             }
17032             break;
17033
17034         case OP_CONCAT:
17035             if (o->op_next && o->op_next->op_type == OP_STRINGIFY) {
17036                 if (o->op_next->op_private & OPpTARGET_MY) {
17037                     if (o->op_flags & OPf_STACKED) /* chained concats */
17038                         break; /* ignore_optimization */
17039                     else {
17040                         /* assert(PL_opargs[o->op_type] & OA_TARGLEX); */
17041                         o->op_targ = o->op_next->op_targ;
17042                         o->op_next->op_targ = 0;
17043                         o->op_private |= OPpTARGET_MY;
17044                     }
17045                 }
17046                 op_null(o->op_next);
17047             }
17048             break;
17049         case OP_STUB:
17050             if ((o->op_flags & OPf_WANT) != OPf_WANT_LIST) {
17051                 break; /* Scalar stub must produce undef.  List stub is noop */
17052             }
17053             goto nothin;
17054         case OP_NULL:
17055             if (o->op_targ == OP_NEXTSTATE
17056                 || o->op_targ == OP_DBSTATE)
17057             {
17058                 PL_curcop = ((COP*)o);
17059             }
17060             /* XXX: We avoid setting op_seq here to prevent later calls
17061                to rpeep() from mistakenly concluding that optimisation
17062                has already occurred. This doesn't fix the real problem,
17063                though (See 20010220.007 (#5874)). AMS 20010719 */
17064             /* op_seq functionality is now replaced by op_opt */
17065             o->op_opt = 0;
17066             /* FALLTHROUGH */
17067         case OP_SCALAR:
17068         case OP_LINESEQ:
17069         case OP_SCOPE:
17070         nothin:
17071             if (oldop) {
17072                 oldop->op_next = o->op_next;
17073                 o->op_opt = 0;
17074                 continue;
17075             }
17076             break;
17077
17078         case OP_PUSHMARK:
17079
17080             /* Given
17081                  5 repeat/DOLIST
17082                  3   ex-list
17083                  1     pushmark
17084                  2     scalar or const
17085                  4   const[0]
17086                convert repeat into a stub with no kids.
17087              */
17088             if (o->op_next->op_type == OP_CONST
17089              || (  o->op_next->op_type == OP_PADSV
17090                 && !(o->op_next->op_private & OPpLVAL_INTRO))
17091              || (  o->op_next->op_type == OP_GV
17092                 && o->op_next->op_next->op_type == OP_RV2SV
17093                 && !(o->op_next->op_next->op_private
17094                         & (OPpLVAL_INTRO|OPpOUR_INTRO))))
17095             {
17096                 const OP *kid = o->op_next->op_next;
17097                 if (o->op_next->op_type == OP_GV)
17098                    kid = kid->op_next;
17099                 /* kid is now the ex-list.  */
17100                 if (kid->op_type == OP_NULL
17101                  && (kid = kid->op_next)->op_type == OP_CONST
17102                     /* kid is now the repeat count.  */
17103                  && kid->op_next->op_type == OP_REPEAT
17104                  && kid->op_next->op_private & OPpREPEAT_DOLIST
17105                  && (kid->op_next->op_flags & OPf_WANT) == OPf_WANT_LIST
17106                  && SvIOK(kSVOP_sv) && SvIVX(kSVOP_sv) == 0
17107                  && oldop)
17108                 {
17109                     o = kid->op_next; /* repeat */
17110                     oldop->op_next = o;
17111                     op_free(cBINOPo->op_first);
17112                     op_free(cBINOPo->op_last );
17113                     o->op_flags &=~ OPf_KIDS;
17114                     /* stub is a baseop; repeat is a binop */
17115                     STATIC_ASSERT_STMT(sizeof(OP) <= sizeof(BINOP));
17116                     OpTYPE_set(o, OP_STUB);
17117                     o->op_private = 0;
17118                     break;
17119                 }
17120             }
17121
17122             /* Convert a series of PAD ops for my vars plus support into a
17123              * single padrange op. Basically
17124              *
17125              *    pushmark -> pad[ahs]v -> pad[ahs]?v -> ... -> (list) -> rest
17126              *
17127              * becomes, depending on circumstances, one of
17128              *
17129              *    padrange  ----------------------------------> (list) -> rest
17130              *    padrange  --------------------------------------------> rest
17131              *
17132              * where all the pad indexes are sequential and of the same type
17133              * (INTRO or not).
17134              * We convert the pushmark into a padrange op, then skip
17135              * any other pad ops, and possibly some trailing ops.
17136              * Note that we don't null() the skipped ops, to make it
17137              * easier for Deparse to undo this optimisation (and none of
17138              * the skipped ops are holding any resourses). It also makes
17139              * it easier for find_uninit_var(), as it can just ignore
17140              * padrange, and examine the original pad ops.
17141              */
17142         {
17143             OP *p;
17144             OP *followop = NULL; /* the op that will follow the padrange op */
17145             U8 count = 0;
17146             U8 intro = 0;
17147             PADOFFSET base = 0; /* init only to stop compiler whining */
17148             bool gvoid = 0;     /* init only to stop compiler whining */
17149             bool defav = 0;  /* seen (...) = @_ */
17150             bool reuse = 0;  /* reuse an existing padrange op */
17151
17152             /* look for a pushmark -> gv[_] -> rv2av */
17153
17154             {
17155                 OP *rv2av, *q;
17156                 p = o->op_next;
17157                 if (   p->op_type == OP_GV
17158                     && cGVOPx_gv(p) == PL_defgv
17159                     && (rv2av = p->op_next)
17160                     && rv2av->op_type == OP_RV2AV
17161                     && !(rv2av->op_flags & OPf_REF)
17162                     && !(rv2av->op_private & (OPpLVAL_INTRO|OPpMAYBE_LVSUB))
17163                     && ((rv2av->op_flags & OPf_WANT) == OPf_WANT_LIST)
17164                 ) {
17165                     q = rv2av->op_next;
17166                     if (q->op_type == OP_NULL)
17167                         q = q->op_next;
17168                     if (q->op_type == OP_PUSHMARK) {
17169                         defav = 1;
17170                         p = q;
17171                     }
17172                 }
17173             }
17174             if (!defav) {
17175                 p = o;
17176             }
17177
17178             /* scan for PAD ops */
17179
17180             for (p = p->op_next; p; p = p->op_next) {
17181                 if (p->op_type == OP_NULL)
17182                     continue;
17183
17184                 if ((     p->op_type != OP_PADSV
17185                        && p->op_type != OP_PADAV
17186                        && p->op_type != OP_PADHV
17187                     )
17188                       /* any private flag other than INTRO? e.g. STATE */
17189                    || (p->op_private & ~OPpLVAL_INTRO)
17190                 )
17191                     break;
17192
17193                 /* let $a[N] potentially be optimised into AELEMFAST_LEX
17194                  * instead */
17195                 if (   p->op_type == OP_PADAV
17196                     && p->op_next
17197                     && p->op_next->op_type == OP_CONST
17198                     && p->op_next->op_next
17199                     && p->op_next->op_next->op_type == OP_AELEM
17200                 )
17201                     break;
17202
17203                 /* for 1st padop, note what type it is and the range
17204                  * start; for the others, check that it's the same type
17205                  * and that the targs are contiguous */
17206                 if (count == 0) {
17207                     intro = (p->op_private & OPpLVAL_INTRO);
17208                     base = p->op_targ;
17209                     gvoid = OP_GIMME(p,0) == G_VOID;
17210                 }
17211                 else {
17212                     if ((p->op_private & OPpLVAL_INTRO) != intro)
17213                         break;
17214                     /* Note that you'd normally  expect targs to be
17215                      * contiguous in my($a,$b,$c), but that's not the case
17216                      * when external modules start doing things, e.g.
17217                      * Function::Parameters */
17218                     if (p->op_targ != base + count)
17219                         break;
17220                     assert(p->op_targ == base + count);
17221                     /* Either all the padops or none of the padops should
17222                        be in void context.  Since we only do the optimisa-
17223                        tion for av/hv when the aggregate itself is pushed
17224                        on to the stack (one item), there is no need to dis-
17225                        tinguish list from scalar context.  */
17226                     if (gvoid != (OP_GIMME(p,0) == G_VOID))
17227                         break;
17228                 }
17229
17230                 /* for AV, HV, only when we're not flattening */
17231                 if (   p->op_type != OP_PADSV
17232                     && !gvoid
17233                     && !(p->op_flags & OPf_REF)
17234                 )
17235                     break;
17236
17237                 if (count >= OPpPADRANGE_COUNTMASK)
17238                     break;
17239
17240                 /* there's a biggest base we can fit into a
17241                  * SAVEt_CLEARPADRANGE in pp_padrange.
17242                  * (The sizeof() stuff will be constant-folded, and is
17243                  * intended to avoid getting "comparison is always false"
17244                  * compiler warnings. See the comments above
17245                  * MEM_WRAP_CHECK for more explanation on why we do this
17246                  * in a weird way to avoid compiler warnings.)
17247                  */
17248                 if (   intro
17249                     && (8*sizeof(base) >
17250                         8*sizeof(UV)-OPpPADRANGE_COUNTSHIFT-SAVE_TIGHT_SHIFT
17251                         ? (Size_t)base
17252                         : (UV_MAX >> (OPpPADRANGE_COUNTSHIFT+SAVE_TIGHT_SHIFT))
17253                         ) >
17254                         (UV_MAX >> (OPpPADRANGE_COUNTSHIFT+SAVE_TIGHT_SHIFT))
17255                 )
17256                     break;
17257
17258                 /* Success! We've got another valid pad op to optimise away */
17259                 count++;
17260                 followop = p->op_next;
17261             }
17262
17263             if (count < 1 || (count == 1 && !defav))
17264                 break;
17265
17266             /* pp_padrange in specifically compile-time void context
17267              * skips pushing a mark and lexicals; in all other contexts
17268              * (including unknown till runtime) it pushes a mark and the
17269              * lexicals. We must be very careful then, that the ops we
17270              * optimise away would have exactly the same effect as the
17271              * padrange.
17272              * In particular in void context, we can only optimise to
17273              * a padrange if we see the complete sequence
17274              *     pushmark, pad*v, ...., list
17275              * which has the net effect of leaving the markstack as it
17276              * was.  Not pushing onto the stack (whereas padsv does touch
17277              * the stack) makes no difference in void context.
17278              */
17279             assert(followop);
17280             if (gvoid) {
17281                 if (followop->op_type == OP_LIST
17282                         && OP_GIMME(followop,0) == G_VOID
17283                    )
17284                 {
17285                     followop = followop->op_next; /* skip OP_LIST */
17286
17287                     /* consolidate two successive my(...);'s */
17288
17289                     if (   oldoldop
17290                         && oldoldop->op_type == OP_PADRANGE
17291                         && (oldoldop->op_flags & OPf_WANT) == OPf_WANT_VOID
17292                         && (oldoldop->op_private & OPpLVAL_INTRO) == intro
17293                         && !(oldoldop->op_flags & OPf_SPECIAL)
17294                     ) {
17295                         U8 old_count;
17296                         assert(oldoldop->op_next == oldop);
17297                         assert(   oldop->op_type == OP_NEXTSTATE
17298                                || oldop->op_type == OP_DBSTATE);
17299                         assert(oldop->op_next == o);
17300
17301                         old_count
17302                             = (oldoldop->op_private & OPpPADRANGE_COUNTMASK);
17303
17304                        /* Do not assume pad offsets for $c and $d are con-
17305                           tiguous in
17306                             my ($a,$b,$c);
17307                             my ($d,$e,$f);
17308                         */
17309                         if (  oldoldop->op_targ + old_count == base
17310                            && old_count < OPpPADRANGE_COUNTMASK - count) {
17311                             base = oldoldop->op_targ;
17312                             count += old_count;
17313                             reuse = 1;
17314                         }
17315                     }
17316
17317                     /* if there's any immediately following singleton
17318                      * my var's; then swallow them and the associated
17319                      * nextstates; i.e.
17320                      *    my ($a,$b); my $c; my $d;
17321                      * is treated as
17322                      *    my ($a,$b,$c,$d);
17323                      */
17324
17325                     while (    ((p = followop->op_next))
17326                             && (  p->op_type == OP_PADSV
17327                                || p->op_type == OP_PADAV
17328                                || p->op_type == OP_PADHV)
17329                             && (p->op_flags & OPf_WANT) == OPf_WANT_VOID
17330                             && (p->op_private & OPpLVAL_INTRO) == intro
17331                             && !(p->op_private & ~OPpLVAL_INTRO)
17332                             && p->op_next
17333                             && (   p->op_next->op_type == OP_NEXTSTATE
17334                                 || p->op_next->op_type == OP_DBSTATE)
17335                             && count < OPpPADRANGE_COUNTMASK
17336                             && base + count == p->op_targ
17337                     ) {
17338                         count++;
17339                         followop = p->op_next;
17340                     }
17341                 }
17342                 else
17343                     break;
17344             }
17345
17346             if (reuse) {
17347                 assert(oldoldop->op_type == OP_PADRANGE);
17348                 oldoldop->op_next = followop;
17349                 oldoldop->op_private = (intro | count);
17350                 o = oldoldop;
17351                 oldop = NULL;
17352                 oldoldop = NULL;
17353             }
17354             else {
17355                 /* Convert the pushmark into a padrange.
17356                  * To make Deparse easier, we guarantee that a padrange was
17357                  * *always* formerly a pushmark */
17358                 assert(o->op_type == OP_PUSHMARK);
17359                 o->op_next = followop;
17360                 OpTYPE_set(o, OP_PADRANGE);
17361                 o->op_targ = base;
17362                 /* bit 7: INTRO; bit 6..0: count */
17363                 o->op_private = (intro | count);
17364                 o->op_flags = ((o->op_flags & ~(OPf_WANT|OPf_SPECIAL))
17365                               | gvoid * OPf_WANT_VOID
17366                               | (defav ? OPf_SPECIAL : 0));
17367             }
17368             break;
17369         }
17370
17371         case OP_RV2AV:
17372             if ((o->op_flags & OPf_WANT) == OPf_WANT_SCALAR)
17373                 S_check_for_bool_cxt(o, 1, OPpTRUEBOOL, 0);
17374             break;
17375
17376         case OP_RV2HV:
17377         case OP_PADHV:
17378             /*'keys %h' in void or scalar context: skip the OP_KEYS
17379              * and perform the functionality directly in the RV2HV/PADHV
17380              * op
17381              */
17382             if (o->op_flags & OPf_REF) {
17383                 OP *k = o->op_next;
17384                 U8 want = (k->op_flags & OPf_WANT);
17385                 if (   k
17386                     && k->op_type == OP_KEYS
17387                     && (   want == OPf_WANT_VOID
17388                         || want == OPf_WANT_SCALAR)
17389                     && !(k->op_private & OPpMAYBE_LVSUB)
17390                     && !(k->op_flags & OPf_MOD)
17391                 ) {
17392                     o->op_next     = k->op_next;
17393                     o->op_flags   &= ~(OPf_REF|OPf_WANT);
17394                     o->op_flags   |= want;
17395                     o->op_private |= (o->op_type == OP_PADHV ?
17396                                       OPpPADHV_ISKEYS : OPpRV2HV_ISKEYS);
17397                     /* for keys(%lex), hold onto the OP_KEYS's targ
17398                      * since padhv doesn't have its own targ to return
17399                      * an int with */
17400                     if (!(o->op_type ==OP_PADHV && want == OPf_WANT_SCALAR))
17401                         op_null(k);
17402                 }
17403             }
17404
17405             /* see if %h is used in boolean context */
17406             if ((o->op_flags & OPf_WANT) == OPf_WANT_SCALAR)
17407                 S_check_for_bool_cxt(o, 1, OPpTRUEBOOL, OPpMAYBE_TRUEBOOL);
17408
17409
17410             if (o->op_type != OP_PADHV)
17411                 break;
17412             /* FALLTHROUGH */
17413         case OP_PADAV:
17414             if (   o->op_type == OP_PADAV
17415                 && (o->op_flags & OPf_WANT) == OPf_WANT_SCALAR
17416             )
17417                 S_check_for_bool_cxt(o, 1, OPpTRUEBOOL, 0);
17418             /* FALLTHROUGH */
17419         case OP_PADSV:
17420             /* Skip over state($x) in void context.  */
17421             if (oldop && o->op_private == (OPpPAD_STATE|OPpLVAL_INTRO)
17422              && (o->op_flags & OPf_WANT) == OPf_WANT_VOID)
17423             {
17424                 oldop->op_next = o->op_next;
17425                 goto redo_nextstate;
17426             }
17427             if (o->op_type != OP_PADAV)
17428                 break;
17429             /* FALLTHROUGH */
17430         case OP_GV:
17431             if (o->op_type == OP_PADAV || o->op_next->op_type == OP_RV2AV) {
17432                 OP* const pop = (o->op_type == OP_PADAV) ?
17433                             o->op_next : o->op_next->op_next;
17434                 IV i;
17435                 if (pop && pop->op_type == OP_CONST &&
17436                     ((PL_op = pop->op_next)) &&
17437                     pop->op_next->op_type == OP_AELEM &&
17438                     !(pop->op_next->op_private &
17439                       (OPpLVAL_INTRO|OPpLVAL_DEFER|OPpDEREF|OPpMAYBE_LVSUB)) &&
17440                     (i = SvIV(((SVOP*)pop)->op_sv)) >= -128 && i <= 127)
17441                 {
17442                     GV *gv;
17443                     if (cSVOPx(pop)->op_private & OPpCONST_STRICT)
17444                         no_bareword_allowed(pop);
17445                     if (o->op_type == OP_GV)
17446                         op_null(o->op_next);
17447                     op_null(pop->op_next);
17448                     op_null(pop);
17449                     o->op_flags |= pop->op_next->op_flags & OPf_MOD;
17450                     o->op_next = pop->op_next->op_next;
17451                     o->op_ppaddr = PL_ppaddr[OP_AELEMFAST];
17452                     o->op_private = (U8)i;
17453                     if (o->op_type == OP_GV) {
17454                         gv = cGVOPo_gv;
17455                         GvAVn(gv);
17456                         o->op_type = OP_AELEMFAST;
17457                     }
17458                     else
17459                         o->op_type = OP_AELEMFAST_LEX;
17460                 }
17461                 if (o->op_type != OP_GV)
17462                     break;
17463             }
17464
17465             /* Remove $foo from the op_next chain in void context.  */
17466             if (oldop
17467              && (  o->op_next->op_type == OP_RV2SV
17468                 || o->op_next->op_type == OP_RV2AV
17469                 || o->op_next->op_type == OP_RV2HV  )
17470              && (o->op_next->op_flags & OPf_WANT) == OPf_WANT_VOID
17471              && !(o->op_next->op_private & OPpLVAL_INTRO))
17472             {
17473                 oldop->op_next = o->op_next->op_next;
17474                 /* Reprocess the previous op if it is a nextstate, to
17475                    allow double-nextstate optimisation.  */
17476               redo_nextstate:
17477                 if (oldop->op_type == OP_NEXTSTATE) {
17478                     oldop->op_opt = 0;
17479                     o = oldop;
17480                     oldop = oldoldop;
17481                     oldoldop = NULL;
17482                     goto redo;
17483                 }
17484                 o = oldop->op_next;
17485                 goto redo;
17486             }
17487             else if (o->op_next->op_type == OP_RV2SV) {
17488                 if (!(o->op_next->op_private & OPpDEREF)) {
17489                     op_null(o->op_next);
17490                     o->op_private |= o->op_next->op_private & (OPpLVAL_INTRO
17491                                                                | OPpOUR_INTRO);
17492                     o->op_next = o->op_next->op_next;
17493                     OpTYPE_set(o, OP_GVSV);
17494                 }
17495             }
17496             else if (o->op_next->op_type == OP_READLINE
17497                     && o->op_next->op_next->op_type == OP_CONCAT
17498                     && (o->op_next->op_next->op_flags & OPf_STACKED))
17499             {
17500                 /* Turn "$a .= <FH>" into an OP_RCATLINE. AMS 20010917 */
17501                 OpTYPE_set(o, OP_RCATLINE);
17502                 o->op_flags |= OPf_STACKED;
17503                 op_null(o->op_next->op_next);
17504                 op_null(o->op_next);
17505             }
17506
17507             break;
17508
17509         case OP_NOT:
17510             break;
17511
17512         case OP_AND:
17513         case OP_OR:
17514         case OP_DOR:
17515         case OP_CMPCHAIN_AND:
17516             while (cLOGOP->op_other->op_type == OP_NULL)
17517                 cLOGOP->op_other = cLOGOP->op_other->op_next;
17518             while (o->op_next && (   o->op_type == o->op_next->op_type
17519                                   || o->op_next->op_type == OP_NULL))
17520                 o->op_next = o->op_next->op_next;
17521
17522             /* If we're an OR and our next is an AND in void context, we'll
17523                follow its op_other on short circuit, same for reverse.
17524                We can't do this with OP_DOR since if it's true, its return
17525                value is the underlying value which must be evaluated
17526                by the next op. */
17527             if (o->op_next &&
17528                 (
17529                     (IS_AND_OP(o) && IS_OR_OP(o->op_next))
17530                  || (IS_OR_OP(o) && IS_AND_OP(o->op_next))
17531                 )
17532                 && (o->op_next->op_flags & OPf_WANT) == OPf_WANT_VOID
17533             ) {
17534                 o->op_next = ((LOGOP*)o->op_next)->op_other;
17535             }
17536             DEFER(cLOGOP->op_other);
17537             o->op_opt = 1;
17538             break;
17539
17540         case OP_GREPWHILE:
17541             if ((o->op_flags & OPf_WANT) == OPf_WANT_SCALAR)
17542                 S_check_for_bool_cxt(o, 1, OPpTRUEBOOL, 0);
17543             /* FALLTHROUGH */
17544         case OP_COND_EXPR:
17545         case OP_MAPWHILE:
17546         case OP_ANDASSIGN:
17547         case OP_ORASSIGN:
17548         case OP_DORASSIGN:
17549         case OP_RANGE:
17550         case OP_ONCE:
17551         case OP_ARGDEFELEM:
17552             while (cLOGOP->op_other->op_type == OP_NULL)
17553                 cLOGOP->op_other = cLOGOP->op_other->op_next;
17554             DEFER(cLOGOP->op_other);
17555             break;
17556
17557         case OP_ENTERLOOP:
17558         case OP_ENTERITER:
17559             while (cLOOP->op_redoop->op_type == OP_NULL)
17560                 cLOOP->op_redoop = cLOOP->op_redoop->op_next;
17561             while (cLOOP->op_nextop->op_type == OP_NULL)
17562                 cLOOP->op_nextop = cLOOP->op_nextop->op_next;
17563             while (cLOOP->op_lastop->op_type == OP_NULL)
17564                 cLOOP->op_lastop = cLOOP->op_lastop->op_next;
17565             /* a while(1) loop doesn't have an op_next that escapes the
17566              * loop, so we have to explicitly follow the op_lastop to
17567              * process the rest of the code */
17568             DEFER(cLOOP->op_lastop);
17569             break;
17570
17571         case OP_ENTERTRY:
17572             assert(cLOGOPo->op_other->op_type == OP_LEAVETRY);
17573             DEFER(cLOGOPo->op_other);
17574             break;
17575
17576         case OP_SUBST:
17577             if ((o->op_flags & OPf_WANT) == OPf_WANT_SCALAR)
17578                 S_check_for_bool_cxt(o, 1, OPpTRUEBOOL, 0);
17579             assert(!(cPMOP->op_pmflags & PMf_ONCE));
17580             while (cPMOP->op_pmstashstartu.op_pmreplstart &&
17581                    cPMOP->op_pmstashstartu.op_pmreplstart->op_type == OP_NULL)
17582                 cPMOP->op_pmstashstartu.op_pmreplstart
17583                     = cPMOP->op_pmstashstartu.op_pmreplstart->op_next;
17584             DEFER(cPMOP->op_pmstashstartu.op_pmreplstart);
17585             break;
17586
17587         case OP_SORT: {
17588             OP *oright;
17589
17590             if (o->op_flags & OPf_SPECIAL) {
17591                 /* first arg is a code block */
17592                 OP * const nullop = OpSIBLING(cLISTOP->op_first);
17593                 OP * kid          = cUNOPx(nullop)->op_first;
17594
17595                 assert(nullop->op_type == OP_NULL);
17596                 assert(kid->op_type == OP_SCOPE
17597                  || (kid->op_type == OP_NULL && kid->op_targ == OP_LEAVE));
17598                 /* since OP_SORT doesn't have a handy op_other-style
17599                  * field that can point directly to the start of the code
17600                  * block, store it in the otherwise-unused op_next field
17601                  * of the top-level OP_NULL. This will be quicker at
17602                  * run-time, and it will also allow us to remove leading
17603                  * OP_NULLs by just messing with op_nexts without
17604                  * altering the basic op_first/op_sibling layout. */
17605                 kid = kLISTOP->op_first;
17606                 assert(
17607                       (kid->op_type == OP_NULL
17608                       && (  kid->op_targ == OP_NEXTSTATE
17609                          || kid->op_targ == OP_DBSTATE  ))
17610                     || kid->op_type == OP_STUB
17611                     || kid->op_type == OP_ENTER
17612                     || (PL_parser && PL_parser->error_count));
17613                 nullop->op_next = kid->op_next;
17614                 DEFER(nullop->op_next);
17615             }
17616
17617             /* check that RHS of sort is a single plain array */
17618             oright = cUNOPo->op_first;
17619             if (!oright || oright->op_type != OP_PUSHMARK)
17620                 break;
17621
17622             if (o->op_private & OPpSORT_INPLACE)
17623                 break;
17624
17625             /* reverse sort ... can be optimised.  */
17626             if (!OpHAS_SIBLING(cUNOPo)) {
17627                 /* Nothing follows us on the list. */
17628                 OP * const reverse = o->op_next;
17629
17630                 if (reverse->op_type == OP_REVERSE &&
17631                     (reverse->op_flags & OPf_WANT) == OPf_WANT_LIST) {
17632                     OP * const pushmark = cUNOPx(reverse)->op_first;
17633                     if (pushmark && (pushmark->op_type == OP_PUSHMARK)
17634                         && (OpSIBLING(cUNOPx(pushmark)) == o)) {
17635                         /* reverse -> pushmark -> sort */
17636                         o->op_private |= OPpSORT_REVERSE;
17637                         op_null(reverse);
17638                         pushmark->op_next = oright->op_next;
17639                         op_null(oright);
17640                     }
17641                 }
17642             }
17643
17644             break;
17645         }
17646
17647         case OP_REVERSE: {
17648             OP *ourmark, *theirmark, *ourlast, *iter, *expushmark, *rv2av;
17649             OP *gvop = NULL;
17650             LISTOP *enter, *exlist;
17651
17652             if (o->op_private & OPpSORT_INPLACE)
17653                 break;
17654
17655             enter = (LISTOP *) o->op_next;
17656             if (!enter)
17657                 break;
17658             if (enter->op_type == OP_NULL) {
17659                 enter = (LISTOP *) enter->op_next;
17660                 if (!enter)
17661                     break;
17662             }
17663             /* for $a (...) will have OP_GV then OP_RV2GV here.
17664                for (...) just has an OP_GV.  */
17665             if (enter->op_type == OP_GV) {
17666                 gvop = (OP *) enter;
17667                 enter = (LISTOP *) enter->op_next;
17668                 if (!enter)
17669                     break;
17670                 if (enter->op_type == OP_RV2GV) {
17671                   enter = (LISTOP *) enter->op_next;
17672                   if (!enter)
17673                     break;
17674                 }
17675             }
17676
17677             if (enter->op_type != OP_ENTERITER)
17678                 break;
17679
17680             iter = enter->op_next;
17681             if (!iter || iter->op_type != OP_ITER)
17682                 break;
17683
17684             expushmark = enter->op_first;
17685             if (!expushmark || expushmark->op_type != OP_NULL
17686                 || expushmark->op_targ != OP_PUSHMARK)
17687                 break;
17688
17689             exlist = (LISTOP *) OpSIBLING(expushmark);
17690             if (!exlist || exlist->op_type != OP_NULL
17691                 || exlist->op_targ != OP_LIST)
17692                 break;
17693
17694             if (exlist->op_last != o) {
17695                 /* Mmm. Was expecting to point back to this op.  */
17696                 break;
17697             }
17698             theirmark = exlist->op_first;
17699             if (!theirmark || theirmark->op_type != OP_PUSHMARK)
17700                 break;
17701
17702             if (OpSIBLING(theirmark) != o) {
17703                 /* There's something between the mark and the reverse, eg
17704                    for (1, reverse (...))
17705                    so no go.  */
17706                 break;
17707             }
17708
17709             ourmark = ((LISTOP *)o)->op_first;
17710             if (!ourmark || ourmark->op_type != OP_PUSHMARK)
17711                 break;
17712
17713             ourlast = ((LISTOP *)o)->op_last;
17714             if (!ourlast || ourlast->op_next != o)
17715                 break;
17716
17717             rv2av = OpSIBLING(ourmark);
17718             if (rv2av && rv2av->op_type == OP_RV2AV && !OpHAS_SIBLING(rv2av)
17719                 && rv2av->op_flags == (OPf_WANT_LIST | OPf_KIDS)) {
17720                 /* We're just reversing a single array.  */
17721                 rv2av->op_flags = OPf_WANT_SCALAR | OPf_KIDS | OPf_REF;
17722                 enter->op_flags |= OPf_STACKED;
17723             }
17724
17725             /* We don't have control over who points to theirmark, so sacrifice
17726                ours.  */
17727             theirmark->op_next = ourmark->op_next;
17728             theirmark->op_flags = ourmark->op_flags;
17729             ourlast->op_next = gvop ? gvop : (OP *) enter;
17730             op_null(ourmark);
17731             op_null(o);
17732             enter->op_private |= OPpITER_REVERSED;
17733             iter->op_private |= OPpITER_REVERSED;
17734
17735             oldoldop = NULL;
17736             oldop    = ourlast;
17737             o        = oldop->op_next;
17738             goto redo;
17739             NOT_REACHED; /* NOTREACHED */
17740             break;
17741         }
17742
17743         case OP_QR:
17744         case OP_MATCH:
17745             if (!(cPMOP->op_pmflags & PMf_ONCE)) {
17746                 assert (!cPMOP->op_pmstashstartu.op_pmreplstart);
17747             }
17748             break;
17749
17750         case OP_RUNCV:
17751             if (!(o->op_private & OPpOFFBYONE) && !CvCLONE(PL_compcv)
17752              && (!CvANON(PL_compcv) || (!PL_cv_has_eval && !PL_perldb)))
17753             {
17754                 SV *sv;
17755                 if (CvEVAL(PL_compcv)) sv = &PL_sv_undef;
17756                 else {
17757                     sv = newRV((SV *)PL_compcv);
17758                     sv_rvweaken(sv);
17759                     SvREADONLY_on(sv);
17760                 }
17761                 OpTYPE_set(o, OP_CONST);
17762                 o->op_flags |= OPf_SPECIAL;
17763                 cSVOPo->op_sv = sv;
17764             }
17765             break;
17766
17767         case OP_SASSIGN:
17768             if (OP_GIMME(o,0) == G_VOID
17769              || (  o->op_next->op_type == OP_LINESEQ
17770                 && (  o->op_next->op_next->op_type == OP_LEAVESUB
17771                    || (  o->op_next->op_next->op_type == OP_RETURN
17772                       && !CvLVALUE(PL_compcv)))))
17773             {
17774                 OP *right = cBINOP->op_first;
17775                 if (right) {
17776                     /*   sassign
17777                     *      RIGHT
17778                     *      substr
17779                     *         pushmark
17780                     *         arg1
17781                     *         arg2
17782                     *         ...
17783                     * becomes
17784                     *
17785                     *  ex-sassign
17786                     *     substr
17787                     *        pushmark
17788                     *        RIGHT
17789                     *        arg1
17790                     *        arg2
17791                     *        ...
17792                     */
17793                     OP *left = OpSIBLING(right);
17794                     if (left->op_type == OP_SUBSTR
17795                          && (left->op_private & 7) < 4) {
17796                         op_null(o);
17797                         /* cut out right */
17798                         op_sibling_splice(o, NULL, 1, NULL);
17799                         /* and insert it as second child of OP_SUBSTR */
17800                         op_sibling_splice(left, cBINOPx(left)->op_first, 0,
17801                                     right);
17802                         left->op_private |= OPpSUBSTR_REPL_FIRST;
17803                         left->op_flags =
17804                             (o->op_flags & ~OPf_WANT) | OPf_WANT_VOID;
17805                     }
17806                 }
17807             }
17808             break;
17809
17810         case OP_AASSIGN: {
17811             int l, r, lr, lscalars, rscalars;
17812
17813             /* handle common vars detection, e.g. ($a,$b) = ($b,$a).
17814                Note that we do this now rather than in newASSIGNOP(),
17815                since only by now are aliased lexicals flagged as such
17816
17817                See the essay "Common vars in list assignment" above for
17818                the full details of the rationale behind all the conditions
17819                below.
17820
17821                PL_generation sorcery:
17822                To detect whether there are common vars, the global var
17823                PL_generation is incremented for each assign op we scan.
17824                Then we run through all the lexical variables on the LHS,
17825                of the assignment, setting a spare slot in each of them to
17826                PL_generation.  Then we scan the RHS, and if any lexicals
17827                already have that value, we know we've got commonality.
17828                Also, if the generation number is already set to
17829                PERL_INT_MAX, then the variable is involved in aliasing, so
17830                we also have potential commonality in that case.
17831              */
17832
17833             PL_generation++;
17834             /* scan LHS */
17835             lscalars = 0;
17836             l = S_aassign_scan(aTHX_ cLISTOPo->op_last,  FALSE, &lscalars);
17837             /* scan RHS */
17838             rscalars = 0;
17839             r = S_aassign_scan(aTHX_ cLISTOPo->op_first, TRUE, &rscalars);
17840             lr = (l|r);
17841
17842
17843             /* After looking for things which are *always* safe, this main
17844              * if/else chain selects primarily based on the type of the
17845              * LHS, gradually working its way down from the more dangerous
17846              * to the more restrictive and thus safer cases */
17847
17848             if (   !l                      /* () = ....; */
17849                 || !r                      /* .... = (); */
17850                 || !(l & ~AAS_SAFE_SCALAR) /* (undef, pos()) = ...; */
17851                 || !(r & ~AAS_SAFE_SCALAR) /* ... = (1,2,length,undef); */
17852                 || (lscalars < 2)          /* ($x, undef) = ... */
17853             ) {
17854                 NOOP; /* always safe */
17855             }
17856             else if (l & AAS_DANGEROUS) {
17857                 /* always dangerous */
17858                 o->op_private |= OPpASSIGN_COMMON_SCALAR;
17859                 o->op_private |= OPpASSIGN_COMMON_AGG;
17860             }
17861             else if (l & (AAS_PKG_SCALAR|AAS_PKG_AGG)) {
17862                 /* package vars are always dangerous - too many
17863                  * aliasing possibilities */
17864                 if (l & AAS_PKG_SCALAR)
17865                     o->op_private |= OPpASSIGN_COMMON_SCALAR;
17866                 if (l & AAS_PKG_AGG)
17867                     o->op_private |= OPpASSIGN_COMMON_AGG;
17868             }
17869             else if (l & ( AAS_MY_SCALAR|AAS_MY_AGG
17870                           |AAS_LEX_SCALAR|AAS_LEX_AGG))
17871             {
17872                 /* LHS contains only lexicals and safe ops */
17873
17874                 if (l & (AAS_MY_AGG|AAS_LEX_AGG))
17875                     o->op_private |= OPpASSIGN_COMMON_AGG;
17876
17877                 if (l & (AAS_MY_SCALAR|AAS_LEX_SCALAR)) {
17878                     if (lr & AAS_LEX_SCALAR_COMM)
17879                         o->op_private |= OPpASSIGN_COMMON_SCALAR;
17880                     else if (   !(l & AAS_LEX_SCALAR)
17881                              && (r & AAS_DEFAV))
17882                     {
17883                         /* falsely mark
17884                          *    my (...) = @_
17885                          * as scalar-safe for performance reasons.
17886                          * (it will still have been marked _AGG if necessary */
17887                         NOOP;
17888                     }
17889                     else if (r  & (AAS_PKG_SCALAR|AAS_PKG_AGG|AAS_DANGEROUS))
17890                         /* if there are only lexicals on the LHS and no
17891                          * common ones on the RHS, then we assume that the
17892                          * only way those lexicals could also get
17893                          * on the RHS is via some sort of dereffing or
17894                          * closure, e.g.
17895                          *    $r = \$lex;
17896                          *    ($lex, $x) = (1, $$r)
17897                          * and in this case we assume the var must have
17898                          *  a bumped ref count. So if its ref count is 1,
17899                          *  it must only be on the LHS.
17900                          */
17901                         o->op_private |= OPpASSIGN_COMMON_RC1;
17902                 }
17903             }
17904
17905             /* ... = ($x)
17906              * may have to handle aggregate on LHS, but we can't
17907              * have common scalars. */
17908             if (rscalars < 2)
17909                 o->op_private &=
17910                         ~(OPpASSIGN_COMMON_SCALAR|OPpASSIGN_COMMON_RC1);
17911
17912             if ((o->op_flags & OPf_WANT) == OPf_WANT_SCALAR)
17913                 S_check_for_bool_cxt(o, 1, OPpASSIGN_TRUEBOOL, 0);
17914             break;
17915         }
17916
17917         case OP_REF:
17918             /* see if ref() is used in boolean context */
17919             if ((o->op_flags & OPf_WANT) == OPf_WANT_SCALAR)
17920                 S_check_for_bool_cxt(o, 1, OPpTRUEBOOL, OPpMAYBE_TRUEBOOL);
17921             break;
17922
17923         case OP_LENGTH:
17924             /* see if the op is used in known boolean context,
17925              * but not if OA_TARGLEX optimisation is enabled */
17926             if (   (o->op_flags & OPf_WANT) == OPf_WANT_SCALAR
17927                 && !(o->op_private & OPpTARGET_MY)
17928             )
17929                 S_check_for_bool_cxt(o, 1, OPpTRUEBOOL, 0);
17930             break;
17931
17932         case OP_POS:
17933             /* see if the op is used in known boolean context */
17934             if ((o->op_flags & OPf_WANT) == OPf_WANT_SCALAR)
17935                 S_check_for_bool_cxt(o, 1, OPpTRUEBOOL, 0);
17936             break;
17937
17938         case OP_CUSTOM: {
17939             Perl_cpeep_t cpeep =
17940                 XopENTRYCUSTOM(o, xop_peep);
17941             if (cpeep)
17942                 cpeep(aTHX_ o, oldop);
17943             break;
17944         }
17945
17946         }
17947         /* did we just null the current op? If so, re-process it to handle
17948          * eliding "empty" ops from the chain */
17949         if (o->op_type == OP_NULL && oldop && oldop->op_next == o) {
17950             o->op_opt = 0;
17951             o = oldop;
17952         }
17953         else {
17954             oldoldop = oldop;
17955             oldop = o;
17956         }
17957     }
17958     LEAVE;
17959 }
17960
17961 void
17962 Perl_peep(pTHX_ OP *o)
17963 {
17964     CALL_RPEEP(o);
17965 }
17966
17967 /*
17968 =head1 Custom Operators
17969
17970 =for apidoc Perl_custom_op_xop
17971 Return the XOP structure for a given custom op.  This macro should be
17972 considered internal to C<OP_NAME> and the other access macros: use them instead.
17973 This macro does call a function.  Prior
17974 to 5.19.6, this was implemented as a
17975 function.
17976
17977 =cut
17978 */
17979
17980
17981 /* use PERL_MAGIC_ext to call a function to free the xop structure when
17982  * freeing PL_custom_ops */
17983
17984 static int
17985 custom_op_register_free(pTHX_ SV *sv, MAGIC *mg)
17986 {
17987     XOP *xop;
17988
17989     PERL_UNUSED_ARG(mg);
17990     xop = INT2PTR(XOP *, SvIV(sv));
17991     Safefree(xop->xop_name);
17992     Safefree(xop->xop_desc);
17993     Safefree(xop);
17994     return 0;
17995 }
17996
17997
17998 static const MGVTBL custom_op_register_vtbl = {
17999     0,                          /* get */
18000     0,                          /* set */
18001     0,                          /* len */
18002     0,                          /* clear */
18003     custom_op_register_free,     /* free */
18004     0,                          /* copy */
18005     0,                          /* dup */
18006 #ifdef MGf_LOCAL
18007     0,                          /* local */
18008 #endif
18009 };
18010
18011
18012 XOPRETANY
18013 Perl_custom_op_get_field(pTHX_ const OP *o, const xop_flags_enum field)
18014 {
18015     SV *keysv;
18016     HE *he = NULL;
18017     XOP *xop;
18018
18019     static const XOP xop_null = { 0, 0, 0, 0, 0 };
18020
18021     PERL_ARGS_ASSERT_CUSTOM_OP_GET_FIELD;
18022     assert(o->op_type == OP_CUSTOM);
18023
18024     /* This is wrong. It assumes a function pointer can be cast to IV,
18025      * which isn't guaranteed, but this is what the old custom OP code
18026      * did. In principle it should be safer to Copy the bytes of the
18027      * pointer into a PV: since the new interface is hidden behind
18028      * functions, this can be changed later if necessary.  */
18029     /* Change custom_op_xop if this ever happens */
18030     keysv = sv_2mortal(newSViv(PTR2IV(o->op_ppaddr)));
18031
18032     if (PL_custom_ops)
18033         he = hv_fetch_ent(PL_custom_ops, keysv, 0, 0);
18034
18035     /* See if the op isn't registered, but its name *is* registered.
18036      * That implies someone is using the pre-5.14 API,where only name and
18037      * description could be registered. If so, fake up a real
18038      * registration.
18039      * We only check for an existing name, and assume no one will have
18040      * just registered a desc */
18041     if (!he && PL_custom_op_names &&
18042         (he = hv_fetch_ent(PL_custom_op_names, keysv, 0, 0))
18043     ) {
18044         const char *pv;
18045         STRLEN l;
18046
18047         /* XXX does all this need to be shared mem? */
18048         Newxz(xop, 1, XOP);
18049         pv = SvPV(HeVAL(he), l);
18050         XopENTRY_set(xop, xop_name, savepvn(pv, l));
18051         if (PL_custom_op_descs &&
18052             (he = hv_fetch_ent(PL_custom_op_descs, keysv, 0, 0))
18053         ) {
18054             pv = SvPV(HeVAL(he), l);
18055             XopENTRY_set(xop, xop_desc, savepvn(pv, l));
18056         }
18057         Perl_custom_op_register(aTHX_ o->op_ppaddr, xop);
18058         he = hv_fetch_ent(PL_custom_ops, keysv, 0, 0);
18059         /* add magic to the SV so that the xop struct (pointed to by
18060          * SvIV(sv)) is freed. Normally a static xop is registered, but
18061          * for this backcompat hack, we've alloced one */
18062         (void)sv_magicext(HeVAL(he), NULL, PERL_MAGIC_ext,
18063                 &custom_op_register_vtbl, NULL, 0);
18064
18065     }
18066     else {
18067         if (!he)
18068             xop = (XOP *)&xop_null;
18069         else
18070             xop = INT2PTR(XOP *, SvIV(HeVAL(he)));
18071     }
18072     {
18073         XOPRETANY any;
18074         if(field == XOPe_xop_ptr) {
18075             any.xop_ptr = xop;
18076         } else {
18077             const U32 flags = XopFLAGS(xop);
18078             if(flags & field) {
18079                 switch(field) {
18080                 case XOPe_xop_name:
18081                     any.xop_name = xop->xop_name;
18082                     break;
18083                 case XOPe_xop_desc:
18084                     any.xop_desc = xop->xop_desc;
18085                     break;
18086                 case XOPe_xop_class:
18087                     any.xop_class = xop->xop_class;
18088                     break;
18089                 case XOPe_xop_peep:
18090                     any.xop_peep = xop->xop_peep;
18091                     break;
18092                 default:
18093                     NOT_REACHED; /* NOTREACHED */
18094                     break;
18095                 }
18096             } else {
18097                 switch(field) {
18098                 case XOPe_xop_name:
18099                     any.xop_name = XOPd_xop_name;
18100                     break;
18101                 case XOPe_xop_desc:
18102                     any.xop_desc = XOPd_xop_desc;
18103                     break;
18104                 case XOPe_xop_class:
18105                     any.xop_class = XOPd_xop_class;
18106                     break;
18107                 case XOPe_xop_peep:
18108                     any.xop_peep = XOPd_xop_peep;
18109                     break;
18110                 default:
18111                     NOT_REACHED; /* NOTREACHED */
18112                     break;
18113                 }
18114             }
18115         }
18116         /* On some platforms (HP-UX, IA64) gcc emits a warning for this function:
18117          * op.c: In function 'Perl_custom_op_get_field':
18118          * op.c:...: warning: 'any.xop_name' may be used uninitialized in this function [-Wmaybe-uninitialized]
18119          * This is because on those platforms (with -DEBUGGING) NOT_REACHED
18120          * expands to assert(0), which expands to ((0) ? (void)0 :
18121          * __assert(...)), and gcc doesn't know that __assert can never return. */
18122         return any;
18123     }
18124 }
18125
18126 /*
18127 =for apidoc custom_op_register
18128 Register a custom op.  See L<perlguts/"Custom Operators">.
18129
18130 =cut
18131 */
18132
18133 void
18134 Perl_custom_op_register(pTHX_ Perl_ppaddr_t ppaddr, const XOP *xop)
18135 {
18136     SV *keysv;
18137
18138     PERL_ARGS_ASSERT_CUSTOM_OP_REGISTER;
18139
18140     /* see the comment in custom_op_xop */
18141     keysv = sv_2mortal(newSViv(PTR2IV(ppaddr)));
18142
18143     if (!PL_custom_ops)
18144         PL_custom_ops = newHV();
18145
18146     if (!hv_store_ent(PL_custom_ops, keysv, newSViv(PTR2IV(xop)), 0))
18147         Perl_croak(aTHX_ "panic: can't register custom OP %s", xop->xop_name);
18148 }
18149
18150 /*
18151
18152 =for apidoc core_prototype
18153
18154 This function assigns the prototype of the named core function to C<sv>, or
18155 to a new mortal SV if C<sv> is C<NULL>.  It returns the modified C<sv>, or
18156 C<NULL> if the core function has no prototype.  C<code> is a code as returned
18157 by C<keyword()>.  It must not be equal to 0.
18158
18159 =cut
18160 */
18161
18162 SV *
18163 Perl_core_prototype(pTHX_ SV *sv, const char *name, const int code,
18164                           int * const opnum)
18165 {
18166     int i = 0, n = 0, seen_question = 0, defgv = 0;
18167     I32 oa;
18168 #define MAX_ARGS_OP ((sizeof(I32) - 1) * 2)
18169     char str[ MAX_ARGS_OP * 2 + 2 ]; /* One ';', one '\0' */
18170     bool nullret = FALSE;
18171
18172     PERL_ARGS_ASSERT_CORE_PROTOTYPE;
18173
18174     assert (code);
18175
18176     if (!sv) sv = sv_newmortal();
18177
18178 #define retsetpvs(x,y) sv_setpvs(sv, x); if(opnum) *opnum=(y); return sv
18179
18180     switch (code < 0 ? -code : code) {
18181     case KEY_and   : case KEY_chop: case KEY_chomp:
18182     case KEY_cmp   : case KEY_defined: case KEY_delete: case KEY_exec  :
18183     case KEY_exists: case KEY_eq     : case KEY_ge    : case KEY_goto  :
18184     case KEY_grep  : case KEY_gt     : case KEY_last  : case KEY_le    :
18185     case KEY_lt    : case KEY_map    : case KEY_ne    : case KEY_next  :
18186     case KEY_or    : case KEY_print  : case KEY_printf: case KEY_qr    :
18187     case KEY_redo  : case KEY_require: case KEY_return: case KEY_say   :
18188     case KEY_select: case KEY_sort   : case KEY_split : case KEY_system:
18189     case KEY_x     : case KEY_xor    :
18190         if (!opnum) return NULL; nullret = TRUE; goto findopnum;
18191     case KEY_glob:    retsetpvs("_;", OP_GLOB);
18192     case KEY_keys:    retsetpvs("\\[%@]", OP_KEYS);
18193     case KEY_values:  retsetpvs("\\[%@]", OP_VALUES);
18194     case KEY_each:    retsetpvs("\\[%@]", OP_EACH);
18195     case KEY_pos:     retsetpvs(";\\[$*]", OP_POS);
18196     case KEY___FILE__: case KEY___LINE__: case KEY___PACKAGE__:
18197         retsetpvs("", 0);
18198     case KEY_evalbytes:
18199         name = "entereval"; break;
18200     case KEY_readpipe:
18201         name = "backtick";
18202     }
18203
18204 #undef retsetpvs
18205
18206   findopnum:
18207     while (i < MAXO) {  /* The slow way. */
18208         if (strEQ(name, PL_op_name[i])
18209             || strEQ(name, PL_op_desc[i]))
18210         {
18211             if (nullret) { assert(opnum); *opnum = i; return NULL; }
18212             goto found;
18213         }
18214         i++;
18215     }
18216     return NULL;
18217   found:
18218     defgv = PL_opargs[i] & OA_DEFGV;
18219     oa = PL_opargs[i] >> OASHIFT;
18220     while (oa) {
18221         if (oa & OA_OPTIONAL && !seen_question && (
18222               !defgv || (oa & (OA_OPTIONAL - 1)) == OA_FILEREF
18223         )) {
18224             seen_question = 1;
18225             str[n++] = ';';
18226         }
18227         if ((oa & (OA_OPTIONAL - 1)) >= OA_AVREF
18228             && (oa & (OA_OPTIONAL - 1)) <= OA_SCALARREF
18229             /* But globs are already references (kinda) */
18230             && (oa & (OA_OPTIONAL - 1)) != OA_FILEREF
18231         ) {
18232             str[n++] = '\\';
18233         }
18234         if ((oa & (OA_OPTIONAL - 1)) == OA_SCALARREF
18235          && !scalar_mod_type(NULL, i)) {
18236             str[n++] = '[';
18237             str[n++] = '$';
18238             str[n++] = '@';
18239             str[n++] = '%';
18240             if (i == OP_LOCK || i == OP_UNDEF) str[n++] = '&';
18241             str[n++] = '*';
18242             str[n++] = ']';
18243         }
18244         else str[n++] = ("?$@@%&*$")[oa & (OA_OPTIONAL - 1)];
18245         if (oa & OA_OPTIONAL && defgv && str[n-1] == '$') {
18246             str[n-1] = '_'; defgv = 0;
18247         }
18248         oa = oa >> 4;
18249     }
18250     if (code == -KEY_not || code == -KEY_getprotobynumber) str[n++] = ';';
18251     str[n++] = '\0';
18252     sv_setpvn(sv, str, n - 1);
18253     if (opnum) *opnum = i;
18254     return sv;
18255 }
18256
18257 OP *
18258 Perl_coresub_op(pTHX_ SV * const coreargssv, const int code,
18259                       const int opnum)
18260 {
18261     OP * const argop = (opnum == OP_SELECT && code) ? NULL :
18262                                         newSVOP(OP_COREARGS,0,coreargssv);
18263     OP *o;
18264
18265     PERL_ARGS_ASSERT_CORESUB_OP;
18266
18267     switch(opnum) {
18268     case 0:
18269         return op_append_elem(OP_LINESEQ,
18270                        argop,
18271                        newSLICEOP(0,
18272                                   newSVOP(OP_CONST, 0, newSViv(-code % 3)),
18273                                   newOP(OP_CALLER,0)
18274                        )
18275                );
18276     case OP_EACH:
18277     case OP_KEYS:
18278     case OP_VALUES:
18279         o = newUNOP(OP_AVHVSWITCH,0,argop);
18280         o->op_private = opnum-OP_EACH;
18281         return o;
18282     case OP_SELECT: /* which represents OP_SSELECT as well */
18283         if (code)
18284             return newCONDOP(
18285                          0,
18286                          newBINOP(OP_GT, 0,
18287                                   newAVREF(newGVOP(OP_GV, 0, PL_defgv)),
18288                                   newSVOP(OP_CONST, 0, newSVuv(1))
18289                                  ),
18290                          coresub_op(newSVuv((UV)OP_SSELECT), 0,
18291                                     OP_SSELECT),
18292                          coresub_op(coreargssv, 0, OP_SELECT)
18293                    );
18294         /* FALLTHROUGH */
18295     default:
18296         switch (PL_opargs[opnum] & OA_CLASS_MASK) {
18297         case OA_BASEOP:
18298             return op_append_elem(
18299                         OP_LINESEQ, argop,
18300                         newOP(opnum,
18301                               opnum == OP_WANTARRAY || opnum == OP_RUNCV
18302                                 ? OPpOFFBYONE << 8 : 0)
18303                    );
18304         case OA_BASEOP_OR_UNOP:
18305             if (opnum == OP_ENTEREVAL) {
18306                 o = newUNOP(OP_ENTEREVAL,OPpEVAL_COPHH<<8,argop);
18307                 if (code == -KEY_evalbytes) o->op_private |= OPpEVAL_BYTES;
18308             }
18309             else o = newUNOP(opnum,0,argop);
18310             if (opnum == OP_CALLER) o->op_private |= OPpOFFBYONE;
18311             else {
18312           onearg:
18313               if (is_handle_constructor(o, 1))
18314                 argop->op_private |= OPpCOREARGS_DEREF1;
18315               if (scalar_mod_type(NULL, opnum))
18316                 argop->op_private |= OPpCOREARGS_SCALARMOD;
18317             }
18318             return o;
18319         default:
18320             o = op_convert_list(opnum,OPf_SPECIAL*(opnum == OP_GLOB),argop);
18321             if (is_handle_constructor(o, 2))
18322                 argop->op_private |= OPpCOREARGS_DEREF2;
18323             if (opnum == OP_SUBSTR) {
18324                 o->op_private |= OPpMAYBE_LVSUB;
18325                 return o;
18326             }
18327             else goto onearg;
18328         }
18329     }
18330 }
18331
18332 void
18333 Perl_report_redefined_cv(pTHX_ const SV *name, const CV *old_cv,
18334                                SV * const *new_const_svp)
18335 {
18336     const char *hvname;
18337     bool is_const = !!CvCONST(old_cv);
18338     SV *old_const_sv = is_const ? cv_const_sv(old_cv) : NULL;
18339
18340     PERL_ARGS_ASSERT_REPORT_REDEFINED_CV;
18341
18342     if (is_const && new_const_svp && old_const_sv == *new_const_svp)
18343         return;
18344         /* They are 2 constant subroutines generated from
18345            the same constant. This probably means that
18346            they are really the "same" proxy subroutine
18347            instantiated in 2 places. Most likely this is
18348            when a constant is exported twice.  Don't warn.
18349         */
18350     if (
18351         (ckWARN(WARN_REDEFINE)
18352          && !(
18353                 CvGV(old_cv) && GvSTASH(CvGV(old_cv))
18354              && HvNAMELEN(GvSTASH(CvGV(old_cv))) == 7
18355              && (hvname = HvNAME(GvSTASH(CvGV(old_cv))),
18356                  strEQ(hvname, "autouse"))
18357              )
18358         )
18359      || (is_const
18360          && ckWARN_d(WARN_REDEFINE)
18361          && (!new_const_svp || sv_cmp(old_const_sv, *new_const_svp))
18362         )
18363     )
18364         Perl_warner(aTHX_ packWARN(WARN_REDEFINE),
18365                           is_const
18366                             ? "Constant subroutine %" SVf " redefined"
18367                             : "Subroutine %" SVf " redefined",
18368                           SVfARG(name));
18369 }
18370
18371 /*
18372 =head1 Hook manipulation
18373
18374 These functions provide convenient and thread-safe means of manipulating
18375 hook variables.
18376
18377 =cut
18378 */
18379
18380 /*
18381 =for apidoc wrap_op_checker
18382
18383 Puts a C function into the chain of check functions for a specified op
18384 type.  This is the preferred way to manipulate the L</PL_check> array.
18385 C<opcode> specifies which type of op is to be affected.  C<new_checker>
18386 is a pointer to the C function that is to be added to that opcode's
18387 check chain, and C<old_checker_p> points to the storage location where a
18388 pointer to the next function in the chain will be stored.  The value of
18389 C<new_checker> is written into the L</PL_check> array, while the value
18390 previously stored there is written to C<*old_checker_p>.
18391
18392 L</PL_check> is global to an entire process, and a module wishing to
18393 hook op checking may find itself invoked more than once per process,
18394 typically in different threads.  To handle that situation, this function
18395 is idempotent.  The location C<*old_checker_p> must initially (once
18396 per process) contain a null pointer.  A C variable of static duration
18397 (declared at file scope, typically also marked C<static> to give
18398 it internal linkage) will be implicitly initialised appropriately,
18399 if it does not have an explicit initialiser.  This function will only
18400 actually modify the check chain if it finds C<*old_checker_p> to be null.
18401 This function is also thread safe on the small scale.  It uses appropriate
18402 locking to avoid race conditions in accessing L</PL_check>.
18403
18404 When this function is called, the function referenced by C<new_checker>
18405 must be ready to be called, except for C<*old_checker_p> being unfilled.
18406 In a threading situation, C<new_checker> may be called immediately,
18407 even before this function has returned.  C<*old_checker_p> will always
18408 be appropriately set before C<new_checker> is called.  If C<new_checker>
18409 decides not to do anything special with an op that it is given (which
18410 is the usual case for most uses of op check hooking), it must chain the
18411 check function referenced by C<*old_checker_p>.
18412
18413 Taken all together, XS code to hook an op checker should typically look
18414 something like this:
18415
18416     static Perl_check_t nxck_frob;
18417     static OP *myck_frob(pTHX_ OP *op) {
18418         ...
18419         op = nxck_frob(aTHX_ op);
18420         ...
18421         return op;
18422     }
18423     BOOT:
18424         wrap_op_checker(OP_FROB, myck_frob, &nxck_frob);
18425
18426 If you want to influence compilation of calls to a specific subroutine,
18427 then use L</cv_set_call_checker_flags> rather than hooking checking of
18428 all C<entersub> ops.
18429
18430 =cut
18431 */
18432
18433 void
18434 Perl_wrap_op_checker(pTHX_ Optype opcode,
18435     Perl_check_t new_checker, Perl_check_t *old_checker_p)
18436 {
18437
18438     PERL_UNUSED_CONTEXT;
18439     PERL_ARGS_ASSERT_WRAP_OP_CHECKER;
18440     if (*old_checker_p) return;
18441     OP_CHECK_MUTEX_LOCK;
18442     if (!*old_checker_p) {
18443         *old_checker_p = PL_check[opcode];
18444         PL_check[opcode] = new_checker;
18445     }
18446     OP_CHECK_MUTEX_UNLOCK;
18447 }
18448
18449 #include "XSUB.h"
18450
18451 /* Efficient sub that returns a constant scalar value. */
18452 static void
18453 const_sv_xsub(pTHX_ CV* cv)
18454 {
18455     dXSARGS;
18456     SV *const sv = MUTABLE_SV(XSANY.any_ptr);
18457     PERL_UNUSED_ARG(items);
18458     if (!sv) {
18459         XSRETURN(0);
18460     }
18461     EXTEND(sp, 1);
18462     ST(0) = sv;
18463     XSRETURN(1);
18464 }
18465
18466 static void
18467 const_av_xsub(pTHX_ CV* cv)
18468 {
18469     dXSARGS;
18470     AV * const av = MUTABLE_AV(XSANY.any_ptr);
18471     SP -= items;
18472     assert(av);
18473 #ifndef DEBUGGING
18474     if (!av) {
18475         XSRETURN(0);
18476     }
18477 #endif
18478     if (SvRMAGICAL(av))
18479         Perl_croak(aTHX_ "Magical list constants are not supported");
18480     if (GIMME_V != G_ARRAY) {
18481         EXTEND(SP, 1);
18482         ST(0) = sv_2mortal(newSViv((IV)AvFILLp(av)+1));
18483         XSRETURN(1);
18484     }
18485     EXTEND(SP, AvFILLp(av)+1);
18486     Copy(AvARRAY(av), &ST(0), AvFILLp(av)+1, SV *);
18487     XSRETURN(AvFILLp(av)+1);
18488 }
18489
18490 /* Copy an existing cop->cop_warnings field.
18491  * If it's one of the standard addresses, just re-use the address.
18492  * This is the e implementation for the DUP_WARNINGS() macro
18493  */
18494
18495 STRLEN*
18496 Perl_dup_warnings(pTHX_ STRLEN* warnings)
18497 {
18498     Size_t size;
18499     STRLEN *new_warnings;
18500
18501     if (warnings == NULL || specialWARN(warnings))
18502         return warnings;
18503
18504     size = sizeof(*warnings) + *warnings;
18505
18506     new_warnings = (STRLEN*)PerlMemShared_malloc(size);
18507     Copy(warnings, new_warnings, size, char);
18508     return new_warnings;
18509 }
18510
18511 /*
18512  * ex: set ts=8 sts=4 sw=4 et:
18513  */