This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
perlapi: capitalize 'op'
[perl5.git] / op.c
1 #line 2 "op.c"
2 /*    op.c
3  *
4  *    Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
5  *    2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008 by Larry Wall and others
6  *
7  *    You may distribute under the terms of either the GNU General Public
8  *    License or the Artistic License, as specified in the README file.
9  *
10  */
11
12 /*
13  * 'You see: Mr. Drogo, he married poor Miss Primula Brandybuck.  She was
14  *  our Mr. Bilbo's first cousin on the mother's side (her mother being the
15  *  youngest of the Old Took's daughters); and Mr. Drogo was his second
16  *  cousin.  So Mr. Frodo is his first *and* second cousin, once removed
17  *  either way, as the saying is, if you follow me.'       --the Gaffer
18  *
19  *     [p.23 of _The Lord of the Rings_, I/i: "A Long-Expected Party"]
20  */
21
22 /* This file contains the functions that create, manipulate and optimize
23  * the OP structures that hold a compiled perl program.
24  *
25  * Note that during the build of miniperl, a temporary copy of this file
26  * is made, called opmini.c.
27  *
28  * A Perl program is compiled into a tree of OP nodes. Each op contains:
29  *  * structural OP pointers to its children and siblings (op_sibling,
30  *    op_first etc) that define the tree structure;
31  *  * execution order OP pointers (op_next, plus sometimes op_other,
32  *    op_lastop  etc) that define the execution sequence plus variants;
33  *  * a pointer to the C "pp" function that would execute the op;
34  *  * any data specific to that op.
35  * For example, an OP_CONST op points to the pp_const() function and to an
36  * SV containing the constant value. When pp_const() is executed, its job
37  * is to push that SV onto the stack.
38  *
39  * OPs are mainly created by the newFOO() functions, which are mainly
40  * called from the parser (in perly.y) as the code is parsed. For example
41  * the Perl code $a + $b * $c would cause the equivalent of the following
42  * to be called (oversimplifying a bit):
43  *
44  *  newBINOP(OP_ADD, flags,
45  *      newSVREF($a),
46  *      newBINOP(OP_MULTIPLY, flags, newSVREF($b), newSVREF($c))
47  *  )
48  *
49  * As the parser reduces low-level rules, it creates little op subtrees;
50  * as higher-level rules are resolved, these subtrees get joined together
51  * as branches on a bigger subtree, until eventually a top-level rule like
52  * a subroutine definition is reduced, at which point there is one large
53  * parse tree left.
54  *
55  * The execution order pointers (op_next) are generated as the subtrees
56  * are joined together. Consider this sub-expression: A*B + C/D: at the
57  * point when it's just been parsed, the op tree looks like:
58  *
59  *   [+]
60  *    |
61  *   [*]------[/]
62  *    |        |
63  *    A---B    C---D
64  *
65  * with the intended execution order being:
66  *
67  *   [PREV] => A => B => [*] => C => D => [/] =>  [+] => [NEXT]
68  *
69  * At this point all the nodes' op_next pointers will have been set,
70  * except that:
71  *    * we don't know what the [NEXT] node will be yet;
72  *    * we don't know what the [PREV] node will be yet, but when it gets
73  *      created and needs its op_next set, it needs to be set to point to
74  *      A, which is non-obvious.
75  * To handle both those cases, we temporarily set the top node's
76  * op_next to point to the first node to be executed in this subtree (A in
77  * this case). This means that initially a subtree's op_next chain,
78  * starting from the top node, will visit each node in execution sequence
79  * then point back at the top node.
80  * When we embed this subtree in a larger tree, its top op_next is used
81  * to get the start node, then is set to point to its new neighbour.
82  * For example the two separate [*],A,B and [/],C,D subtrees would
83  * initially have had:
84  *   [*] => A;  A => B;  B => [*]
85  * and
86  *   [/] => C;  C => D;  D => [/]
87  * When these two subtrees were joined together to make the [+] subtree,
88  * [+]'s op_next was set to [*]'s op_next, i.e. A; then [*]'s op_next was
89  * set to point to [/]'s op_next, i.e. C.
90  *
91  * This op_next linking is done by the LINKLIST() macro and its underlying
92  * op_linklist() function. Given a top-level op, if its op_next is
93  * non-null, it's already been linked, so leave it. Otherwise link it with
94  * its children as described above, possibly recursively if any of the
95  * children have a null op_next.
96  *
97  * In summary: given a subtree, its top-level node's op_next will either
98  * be:
99  *   NULL: the subtree hasn't been LINKLIST()ed yet;
100  *   fake: points to the start op for this subtree;
101  *   real: once the subtree has been embedded into a larger tree
102  */
103
104 /*
105
106 Here's an older description from Larry.
107
108 Perl's compiler is essentially a 3-pass compiler with interleaved phases:
109
110     A bottom-up pass
111     A top-down pass
112     An execution-order pass
113
114 The bottom-up pass is represented by all the "newOP" routines and
115 the ck_ routines.  The bottom-upness is actually driven by yacc.
116 So at the point that a ck_ routine fires, we have no idea what the
117 context is, either upward in the syntax tree, or either forward or
118 backward in the execution order.  (The bottom-up parser builds that
119 part of the execution order it knows about, but if you follow the "next"
120 links around, you'll find it's actually a closed loop through the
121 top level node.)
122
123 Whenever the bottom-up parser gets to a node that supplies context to
124 its components, it invokes that portion of the top-down pass that applies
125 to that part of the subtree (and marks the top node as processed, so
126 if a node further up supplies context, it doesn't have to take the
127 plunge again).  As a particular subcase of this, as the new node is
128 built, it takes all the closed execution loops of its subcomponents
129 and links them into a new closed loop for the higher level node.  But
130 it's still not the real execution order.
131
132 The actual execution order is not known till we get a grammar reduction
133 to a top-level unit like a subroutine or file that will be called by
134 "name" rather than via a "next" pointer.  At that point, we can call
135 into peep() to do that code's portion of the 3rd pass.  It has to be
136 recursive, but it's recursive on basic blocks, not on tree nodes.
137 */
138
139 /* To implement user lexical pragmas, there needs to be a way at run time to
140    get the compile time state of %^H for that block.  Storing %^H in every
141    block (or even COP) would be very expensive, so a different approach is
142    taken.  The (running) state of %^H is serialised into a tree of HE-like
143    structs.  Stores into %^H are chained onto the current leaf as a struct
144    refcounted_he * with the key and the value.  Deletes from %^H are saved
145    with a value of PL_sv_placeholder.  The state of %^H at any point can be
146    turned back into a regular HV by walking back up the tree from that point's
147    leaf, ignoring any key you've already seen (placeholder or not), storing
148    the rest into the HV structure, then removing the placeholders. Hence
149    memory is only used to store the %^H deltas from the enclosing COP, rather
150    than the entire %^H on each COP.
151
152    To cause actions on %^H to write out the serialisation records, it has
153    magic type 'H'. This magic (itself) does nothing, but its presence causes
154    the values to gain magic type 'h', which has entries for set and clear.
155    C<Perl_magic_sethint> updates C<PL_compiling.cop_hints_hash> with a store
156    record, with deletes written by C<Perl_magic_clearhint>. C<SAVEHINTS>
157    saves the current C<PL_compiling.cop_hints_hash> on the save stack, so that
158    it will be correctly restored when any inner compiling scope is exited.
159 */
160
161 #include "EXTERN.h"
162 #define PERL_IN_OP_C
163 #include "perl.h"
164 #include "keywords.h"
165 #include "feature.h"
166 #include "regcomp.h"
167 #include "invlist_inline.h"
168
169 #define CALL_PEEP(o) PL_peepp(aTHX_ o)
170 #define CALL_RPEEP(o) PL_rpeepp(aTHX_ o)
171 #define CALL_OPFREEHOOK(o) if (PL_opfreehook) PL_opfreehook(aTHX_ o)
172
173 static const char array_passed_to_stat[] = "Array passed to stat will be coerced to a scalar";
174
175 /* remove any leading "empty" ops from the op_next chain whose first
176  * node's address is stored in op_p. Store the updated address of the
177  * first node in op_p.
178  */
179
180 STATIC void
181 S_prune_chain_head(OP** op_p)
182 {
183     while (*op_p
184         && (   (*op_p)->op_type == OP_NULL
185             || (*op_p)->op_type == OP_SCOPE
186             || (*op_p)->op_type == OP_SCALAR
187             || (*op_p)->op_type == OP_LINESEQ)
188     )
189         *op_p = (*op_p)->op_next;
190 }
191
192
193 /* See the explanatory comments above struct opslab in op.h. */
194
195 #ifdef PERL_DEBUG_READONLY_OPS
196 #  define PERL_SLAB_SIZE 128
197 #  define PERL_MAX_SLAB_SIZE 4096
198 #  include <sys/mman.h>
199 #endif
200
201 #ifndef PERL_SLAB_SIZE
202 #  define PERL_SLAB_SIZE 64
203 #endif
204 #ifndef PERL_MAX_SLAB_SIZE
205 #  define PERL_MAX_SLAB_SIZE 2048
206 #endif
207
208 /* rounds up to nearest pointer */
209 #define SIZE_TO_PSIZE(x)        (((x) + sizeof(I32 *) - 1)/sizeof(I32 *))
210
211 #define DIFF(o,p)       \
212     (assert(((char *)(p) - (char *)(o)) % sizeof(I32**) == 0), \
213       ((size_t)((I32 **)(p) - (I32**)(o))))
214
215 /* requires double parens and aTHX_ */
216 #define DEBUG_S_warn(args)                                             \
217     DEBUG_S(                                                            \
218         PerlIO_printf(Perl_debug_log, "%s", SvPVx_nolen(Perl_mess args)) \
219     )
220
221 /* opslot_size includes the size of the slot header, and an op can't be smaller than BASEOP */
222 #define OPSLOT_SIZE_BASE (SIZE_TO_PSIZE(sizeof(OPSLOT)))
223
224 /* the number of bytes to allocate for a slab with sz * sizeof(I32 **) space for op */
225 #define OpSLABSizeBytes(sz) \
226     ((sz) * sizeof(I32 *) + STRUCT_OFFSET(OPSLAB, opslab_slots))
227
228 /* malloc a new op slab (suitable for attaching to PL_compcv).
229  * sz is in units of pointers from the beginning of opslab_opslots */
230
231 static OPSLAB *
232 S_new_slab(pTHX_ OPSLAB *head, size_t sz)
233 {
234     OPSLAB *slab;
235     size_t sz_bytes = OpSLABSizeBytes(sz);
236
237     /* opslot_offset is only U16 */
238     assert(sz < U16_MAX);
239     /* room for at least one op */
240     assert(sz >= OPSLOT_SIZE_BASE);
241
242 #ifdef PERL_DEBUG_READONLY_OPS
243     slab = (OPSLAB *) mmap(0, sz_bytes,
244                                    PROT_READ|PROT_WRITE,
245                                    MAP_ANON|MAP_PRIVATE, -1, 0);
246     DEBUG_m(PerlIO_printf(Perl_debug_log, "mapped %lu at %p\n",
247                           (unsigned long) sz, slab));
248     if (slab == MAP_FAILED) {
249         perror("mmap failed");
250         abort();
251     }
252 #else
253     slab = (OPSLAB *)PerlMemShared_malloc(sz_bytes);
254     Zero(slab, sz_bytes, char);
255 #endif
256     slab->opslab_size = (U16)sz;
257
258 #ifndef WIN32
259     /* The context is unused in non-Windows */
260     PERL_UNUSED_CONTEXT;
261 #endif
262     slab->opslab_free_space = sz;
263     slab->opslab_head = head ? head : slab;
264     DEBUG_S_warn((aTHX_ "allocated new op slab sz 0x%x, %p, head slab %p",
265         (unsigned int)slab->opslab_size, (void*)slab,
266         (void*)(slab->opslab_head)));
267     return slab;
268 }
269
270 #define OPSLOT_SIZE_TO_INDEX(sz) ((sz) - OPSLOT_SIZE_BASE)
271
272 #define link_freed_op(slab, o) S_link_freed_op(aTHX_ slab, o)
273 static void
274 S_link_freed_op(pTHX_ OPSLAB *slab, OP *o) {
275     U16 sz = OpSLOT(o)->opslot_size;
276     U16 index = OPSLOT_SIZE_TO_INDEX(sz);
277
278     assert(sz >= OPSLOT_SIZE_BASE);
279     /* make sure the array is large enough to include ops this large */
280     if (!slab->opslab_freed) {
281         /* we don't have a free list array yet, make a new one */
282         slab->opslab_freed_size = index+1;
283         slab->opslab_freed = (OP**)PerlMemShared_calloc((slab->opslab_freed_size), sizeof(OP*));
284
285         if (!slab->opslab_freed)
286             croak_no_mem();
287     }
288     else if (index >= slab->opslab_freed_size) {
289         /* It's probably not worth doing exponential expansion here, the number of op sizes
290            is small.
291         */
292         /* We already have a list that isn't large enough, expand it */
293         size_t newsize = index+1;
294         OP **p = (OP **)PerlMemShared_realloc(slab->opslab_freed, newsize * sizeof(OP*));
295
296         if (!p)
297             croak_no_mem();
298
299         Zero(p+slab->opslab_freed_size, newsize - slab->opslab_freed_size, OP *);
300
301         slab->opslab_freed = p;
302         slab->opslab_freed_size = newsize;
303     }
304
305     o->op_next = slab->opslab_freed[index];
306     slab->opslab_freed[index] = o;
307 }
308
309 /* Returns a sz-sized block of memory (suitable for holding an op) from
310  * a free slot in the chain of op slabs attached to PL_compcv.
311  * Allocates a new slab if necessary.
312  * if PL_compcv isn't compiling, malloc() instead.
313  */
314
315 void *
316 Perl_Slab_Alloc(pTHX_ size_t sz)
317 {
318     OPSLAB *head_slab; /* first slab in the chain */
319     OPSLAB *slab2;
320     OPSLOT *slot;
321     OP *o;
322     size_t sz_in_p; /* size in pointer units, including the OPSLOT header */
323
324     /* We only allocate ops from the slab during subroutine compilation.
325        We find the slab via PL_compcv, hence that must be non-NULL. It could
326        also be pointing to a subroutine which is now fully set up (CvROOT()
327        pointing to the top of the optree for that sub), or a subroutine
328        which isn't using the slab allocator. If our sanity checks aren't met,
329        don't use a slab, but allocate the OP directly from the heap.  */
330     if (!PL_compcv || CvROOT(PL_compcv)
331      || (CvSTART(PL_compcv) && !CvSLABBED(PL_compcv)))
332     {
333         o = (OP*)PerlMemShared_calloc(1, sz);
334         goto gotit;
335     }
336
337     /* While the subroutine is under construction, the slabs are accessed via
338        CvSTART(), to avoid needing to expand PVCV by one pointer for something
339        unneeded at runtime. Once a subroutine is constructed, the slabs are
340        accessed via CvROOT(). So if CvSTART() is NULL, no slab has been
341        allocated yet.  See the commit message for 8be227ab5eaa23f2 for more
342        details.  */
343     if (!CvSTART(PL_compcv)) {
344         CvSTART(PL_compcv) =
345             (OP *)(head_slab = S_new_slab(aTHX_ NULL, PERL_SLAB_SIZE));
346         CvSLABBED_on(PL_compcv);
347         head_slab->opslab_refcnt = 2; /* one for the CV; one for the new OP */
348     }
349     else ++(head_slab = (OPSLAB *)CvSTART(PL_compcv))->opslab_refcnt;
350
351     sz_in_p = SIZE_TO_PSIZE(sz + OPSLOT_HEADER);
352
353     /* The head slab for each CV maintains a free list of OPs. In particular, constant folding
354        will free up OPs, so it makes sense to re-use them where possible. A
355        freed up slot is used in preference to a new allocation.  */
356     if (head_slab->opslab_freed &&
357         OPSLOT_SIZE_TO_INDEX(sz_in_p) < head_slab->opslab_freed_size) {
358         U16 base_index;
359
360         /* look for a large enough size with any freed ops */
361         for (base_index = OPSLOT_SIZE_TO_INDEX(sz_in_p);
362              base_index < head_slab->opslab_freed_size && !head_slab->opslab_freed[base_index];
363              ++base_index) {
364         }
365
366         if (base_index < head_slab->opslab_freed_size) {
367             /* found a freed op */
368             o = head_slab->opslab_freed[base_index];
369
370             DEBUG_S_warn((aTHX_ "realloced  op at %p, slab %p, head slab %p",
371                           (void *)o, (void *)OpMySLAB(o), (void *)head_slab));
372             head_slab->opslab_freed[base_index] = o->op_next;
373             Zero(o, sz, char);
374             o->op_slabbed = 1;
375             goto gotit;
376         }
377     }
378
379 #define INIT_OPSLOT(s) \
380             slot->opslot_offset = DIFF(&slab2->opslab_slots, slot) ;    \
381             slot->opslot_size = s;                      \
382             slab2->opslab_free_space -= s;              \
383             o = &slot->opslot_op;                       \
384             o->op_slabbed = 1
385
386     /* The partially-filled slab is next in the chain. */
387     slab2 = head_slab->opslab_next ? head_slab->opslab_next : head_slab;
388     if (slab2->opslab_free_space < sz_in_p) {
389         /* Remaining space is too small. */
390         /* If we can fit a BASEOP, add it to the free chain, so as not
391            to waste it. */
392         if (slab2->opslab_free_space >= OPSLOT_SIZE_BASE) {
393             slot = &slab2->opslab_slots;
394             INIT_OPSLOT(slab2->opslab_free_space);
395             o->op_type = OP_FREED;
396             DEBUG_S_warn((aTHX_ "linked unused op space at %p, slab %p, head slab %p",
397                           (void *)o, (void *)slab2, (void *)head_slab));
398             link_freed_op(head_slab, o);
399         }
400
401         /* Create a new slab.  Make this one twice as big. */
402         slab2 = S_new_slab(aTHX_ head_slab,
403                             slab2->opslab_size  > PERL_MAX_SLAB_SIZE / 2
404                                 ? PERL_MAX_SLAB_SIZE
405                                 : slab2->opslab_size * 2);
406         slab2->opslab_next = head_slab->opslab_next;
407         head_slab->opslab_next = slab2;
408     }
409     assert(slab2->opslab_size >= sz_in_p);
410
411     /* Create a new op slot */
412     slot = OpSLOToff(slab2, slab2->opslab_free_space - sz_in_p);
413     assert(slot >= &slab2->opslab_slots);
414     INIT_OPSLOT(sz_in_p);
415     DEBUG_S_warn((aTHX_ "allocating op at %p, slab %p, head slab %p",
416         (void*)o, (void*)slab2, (void*)head_slab));
417
418   gotit:
419     /* moresib == 0, op_sibling == 0 implies a solitary unattached op */
420     assert(!o->op_moresib);
421     assert(!o->op_sibparent);
422
423     return (void *)o;
424 }
425
426 #undef INIT_OPSLOT
427
428 #ifdef PERL_DEBUG_READONLY_OPS
429 void
430 Perl_Slab_to_ro(pTHX_ OPSLAB *slab)
431 {
432     PERL_ARGS_ASSERT_SLAB_TO_RO;
433
434     if (slab->opslab_readonly) return;
435     slab->opslab_readonly = 1;
436     for (; slab; slab = slab->opslab_next) {
437         /*DEBUG_U(PerlIO_printf(Perl_debug_log,"mprotect ->ro %lu at %p\n",
438                               (unsigned long) slab->opslab_size, (void *)slab));*/
439         if (mprotect(slab, OpSLABSizeBytes(slab->opslab_size), PROT_READ))
440             Perl_warn(aTHX_ "mprotect for %p %lu failed with %d", (void *)slab,
441                              (unsigned long)slab->opslab_size, errno);
442     }
443 }
444
445 void
446 Perl_Slab_to_rw(pTHX_ OPSLAB *const slab)
447 {
448     OPSLAB *slab2;
449
450     PERL_ARGS_ASSERT_SLAB_TO_RW;
451
452     if (!slab->opslab_readonly) return;
453     slab2 = slab;
454     for (; slab2; slab2 = slab2->opslab_next) {
455         /*DEBUG_U(PerlIO_printf(Perl_debug_log,"mprotect ->rw %lu at %p\n",
456                               (unsigned long) size, (void *)slab2));*/
457         if (mprotect((void *)slab2, OpSLABSizeBytes(slab2->opslab_size),
458                      PROT_READ|PROT_WRITE)) {
459             Perl_warn(aTHX_ "mprotect RW for %p %lu failed with %d", (void *)slab,
460                              (unsigned long)slab2->opslab_size, errno);
461         }
462     }
463     slab->opslab_readonly = 0;
464 }
465
466 #else
467 #  define Slab_to_rw(op)    NOOP
468 #endif
469
470 /* This cannot possibly be right, but it was copied from the old slab
471    allocator, to which it was originally added, without explanation, in
472    commit 083fcd5. */
473 #ifdef NETWARE
474 #    define PerlMemShared PerlMem
475 #endif
476
477 /* make freed ops die if they're inadvertently executed */
478 #ifdef DEBUGGING
479 static OP *
480 S_pp_freed(pTHX)
481 {
482     DIE(aTHX_ "panic: freed op 0x%p called\n", PL_op);
483 }
484 #endif
485
486
487 /* Return the block of memory used by an op to the free list of
488  * the OP slab associated with that op.
489  */
490
491 void
492 Perl_Slab_Free(pTHX_ void *op)
493 {
494     OP * const o = (OP *)op;
495     OPSLAB *slab;
496
497     PERL_ARGS_ASSERT_SLAB_FREE;
498
499 #ifdef DEBUGGING
500     o->op_ppaddr = S_pp_freed;
501 #endif
502
503     if (!o->op_slabbed) {
504         if (!o->op_static)
505             PerlMemShared_free(op);
506         return;
507     }
508
509     slab = OpSLAB(o);
510     /* If this op is already freed, our refcount will get screwy. */
511     assert(o->op_type != OP_FREED);
512     o->op_type = OP_FREED;
513     link_freed_op(slab, o);
514     DEBUG_S_warn((aTHX_ "freeing    op at %p, slab %p, head slab %p",
515         (void*)o, (void *)OpMySLAB(o), (void*)slab));
516     OpslabREFCNT_dec_padok(slab);
517 }
518
519 void
520 Perl_opslab_free_nopad(pTHX_ OPSLAB *slab)
521 {
522     const bool havepad = !!PL_comppad;
523     PERL_ARGS_ASSERT_OPSLAB_FREE_NOPAD;
524     if (havepad) {
525         ENTER;
526         PAD_SAVE_SETNULLPAD();
527     }
528     opslab_free(slab);
529     if (havepad) LEAVE;
530 }
531
532 /* Free a chain of OP slabs. Should only be called after all ops contained
533  * in it have been freed. At this point, its reference count should be 1,
534  * because OpslabREFCNT_dec() skips doing rc-- when it detects that rc == 1,
535  * and just directly calls opslab_free().
536  * (Note that the reference count which PL_compcv held on the slab should
537  * have been removed once compilation of the sub was complete).
538  *
539  *
540  */
541
542 void
543 Perl_opslab_free(pTHX_ OPSLAB *slab)
544 {
545     OPSLAB *slab2;
546     PERL_ARGS_ASSERT_OPSLAB_FREE;
547     PERL_UNUSED_CONTEXT;
548     DEBUG_S_warn((aTHX_ "freeing slab %p", (void*)slab));
549     assert(slab->opslab_refcnt == 1);
550     PerlMemShared_free(slab->opslab_freed);
551     do {
552         slab2 = slab->opslab_next;
553 #ifdef DEBUGGING
554         slab->opslab_refcnt = ~(size_t)0;
555 #endif
556 #ifdef PERL_DEBUG_READONLY_OPS
557         DEBUG_m(PerlIO_printf(Perl_debug_log, "Deallocate slab at %p\n",
558                                                (void*)slab));
559         if (munmap(slab, OpSLABSizeBytes(slab->opslab_size))) {
560             perror("munmap failed");
561             abort();
562         }
563 #else
564         PerlMemShared_free(slab);
565 #endif
566         slab = slab2;
567     } while (slab);
568 }
569
570 /* like opslab_free(), but first calls op_free() on any ops in the slab
571  * not marked as OP_FREED
572  */
573
574 void
575 Perl_opslab_force_free(pTHX_ OPSLAB *slab)
576 {
577     OPSLAB *slab2;
578 #ifdef DEBUGGING
579     size_t savestack_count = 0;
580 #endif
581     PERL_ARGS_ASSERT_OPSLAB_FORCE_FREE;
582     slab2 = slab;
583     do {
584         OPSLOT *slot = OpSLOToff(slab2, slab2->opslab_free_space);
585         OPSLOT *end  = OpSLOToff(slab2, slab2->opslab_size);
586         for (; slot < end;
587                 slot = (OPSLOT*) ((I32**)slot + slot->opslot_size) )
588         {
589             if (slot->opslot_op.op_type != OP_FREED
590              && !(slot->opslot_op.op_savefree
591 #ifdef DEBUGGING
592                   && ++savestack_count
593 #endif
594                  )
595             ) {
596                 assert(slot->opslot_op.op_slabbed);
597                 op_free(&slot->opslot_op);
598                 if (slab->opslab_refcnt == 1) goto free;
599             }
600         }
601     } while ((slab2 = slab2->opslab_next));
602     /* > 1 because the CV still holds a reference count. */
603     if (slab->opslab_refcnt > 1) { /* still referenced by the savestack */
604 #ifdef DEBUGGING
605         assert(savestack_count == slab->opslab_refcnt-1);
606 #endif
607         /* Remove the CV’s reference count. */
608         slab->opslab_refcnt--;
609         return;
610     }
611    free:
612     opslab_free(slab);
613 }
614
615 #ifdef PERL_DEBUG_READONLY_OPS
616 OP *
617 Perl_op_refcnt_inc(pTHX_ OP *o)
618 {
619     if(o) {
620         OPSLAB *const slab = o->op_slabbed ? OpSLAB(o) : NULL;
621         if (slab && slab->opslab_readonly) {
622             Slab_to_rw(slab);
623             ++o->op_targ;
624             Slab_to_ro(slab);
625         } else {
626             ++o->op_targ;
627         }
628     }
629     return o;
630
631 }
632
633 PADOFFSET
634 Perl_op_refcnt_dec(pTHX_ OP *o)
635 {
636     PADOFFSET result;
637     OPSLAB *const slab = o->op_slabbed ? OpSLAB(o) : NULL;
638
639     PERL_ARGS_ASSERT_OP_REFCNT_DEC;
640
641     if (slab && slab->opslab_readonly) {
642         Slab_to_rw(slab);
643         result = --o->op_targ;
644         Slab_to_ro(slab);
645     } else {
646         result = --o->op_targ;
647     }
648     return result;
649 }
650 #endif
651 /*
652  * In the following definition, the ", (OP*)0" is just to make the compiler
653  * think the expression is of the right type: croak actually does a Siglongjmp.
654  */
655 #define CHECKOP(type,o) \
656     ((PL_op_mask && PL_op_mask[type])                           \
657      ? ( op_free((OP*)o),                                       \
658          Perl_croak(aTHX_ "'%s' trapped by operation mask", PL_op_desc[type]),  \
659          (OP*)0 )                                               \
660      : PL_check[type](aTHX_ (OP*)o))
661
662 #define RETURN_UNLIMITED_NUMBER (PERL_INT_MAX / 2)
663
664 #define OpTYPE_set(o,type) \
665     STMT_START {                                \
666         o->op_type = (OPCODE)type;              \
667         o->op_ppaddr = PL_ppaddr[type];         \
668     } STMT_END
669
670 STATIC OP *
671 S_no_fh_allowed(pTHX_ OP *o)
672 {
673     PERL_ARGS_ASSERT_NO_FH_ALLOWED;
674
675     yyerror(Perl_form(aTHX_ "Missing comma after first argument to %s function",
676                  OP_DESC(o)));
677     return o;
678 }
679
680 STATIC OP *
681 S_too_few_arguments_pv(pTHX_ OP *o, const char* name, U32 flags)
682 {
683     PERL_ARGS_ASSERT_TOO_FEW_ARGUMENTS_PV;
684     yyerror_pv(Perl_form(aTHX_ "Not enough arguments for %s", name), flags);
685     return o;
686 }
687
688 STATIC OP *
689 S_too_many_arguments_pv(pTHX_ OP *o, const char *name, U32 flags)
690 {
691     PERL_ARGS_ASSERT_TOO_MANY_ARGUMENTS_PV;
692
693     yyerror_pv(Perl_form(aTHX_ "Too many arguments for %s", name), flags);
694     return o;
695 }
696
697 STATIC void
698 S_bad_type_pv(pTHX_ I32 n, const char *t, const OP *o, const OP *kid)
699 {
700     PERL_ARGS_ASSERT_BAD_TYPE_PV;
701
702     yyerror_pv(Perl_form(aTHX_ "Type of arg %d to %s must be %s (not %s)",
703                  (int)n, PL_op_desc[(o)->op_type], t, OP_DESC(kid)), 0);
704 }
705
706 STATIC void
707 S_bad_type_gv(pTHX_ I32 n, GV *gv, const OP *kid, const char *t)
708 {
709     SV * const namesv = cv_name((CV *)gv, NULL, 0);
710     PERL_ARGS_ASSERT_BAD_TYPE_GV;
711
712     yyerror_pv(Perl_form(aTHX_ "Type of arg %d to %" SVf " must be %s (not %s)",
713                  (int)n, SVfARG(namesv), t, OP_DESC(kid)), SvUTF8(namesv));
714 }
715
716 STATIC void
717 S_no_bareword_allowed(pTHX_ OP *o)
718 {
719     PERL_ARGS_ASSERT_NO_BAREWORD_ALLOWED;
720
721     qerror(Perl_mess(aTHX_
722                      "Bareword \"%" SVf "\" not allowed while \"strict subs\" in use",
723                      SVfARG(cSVOPo_sv)));
724     o->op_private &= ~OPpCONST_STRICT; /* prevent warning twice about the same OP */
725 }
726
727 /* "register" allocation */
728
729 PADOFFSET
730 Perl_allocmy(pTHX_ const char *const name, const STRLEN len, const U32 flags)
731 {
732     PADOFFSET off;
733     const bool is_our = (PL_parser->in_my == KEY_our);
734
735     PERL_ARGS_ASSERT_ALLOCMY;
736
737     if (flags & ~SVf_UTF8)
738         Perl_croak(aTHX_ "panic: allocmy illegal flag bits 0x%" UVxf,
739                    (UV)flags);
740
741     /* complain about "my $<special_var>" etc etc */
742     if (   len
743         && !(  is_our
744             || isALPHA(name[1])
745             || (   (flags & SVf_UTF8)
746                 && isIDFIRST_utf8_safe((U8 *)name+1, name + len))
747             || (name[1] == '_' && len > 2)))
748     {
749         const char * const type =
750               PL_parser->in_my == KEY_sigvar ? "subroutine signature" :
751               PL_parser->in_my == KEY_state  ? "\"state\""     : "\"my\"";
752
753         if (!(flags & SVf_UTF8 && UTF8_IS_START(name[1]))
754          && isASCII(name[1])
755          && (!isPRINT(name[1]) || memCHRs("\t\n\r\f", name[1]))) {
756             /* diag_listed_as: Can't use global %s in %s */
757             yyerror(Perl_form(aTHX_ "Can't use global %c^%c%.*s in %s",
758                               name[0], toCTRL(name[1]),
759                               (int)(len - 2), name + 2,
760                               type));
761         } else {
762             yyerror_pv(Perl_form(aTHX_ "Can't use global %.*s in %s",
763                               (int) len, name,
764                               type), flags & SVf_UTF8);
765         }
766     }
767
768     /* allocate a spare slot and store the name in that slot */
769
770     off = pad_add_name_pvn(name, len,
771                        (is_our ? padadd_OUR :
772                         PL_parser->in_my == KEY_state ? padadd_STATE : 0),
773                     PL_parser->in_my_stash,
774                     (is_our
775                         /* $_ is always in main::, even with our */
776                         ? (PL_curstash && !memEQs(name,len,"$_")
777                             ? PL_curstash
778                             : PL_defstash)
779                         : NULL
780                     )
781     );
782     /* anon sub prototypes contains state vars should always be cloned,
783      * otherwise the state var would be shared between anon subs */
784
785     if (PL_parser->in_my == KEY_state && CvANON(PL_compcv))
786         CvCLONE_on(PL_compcv);
787
788     return off;
789 }
790
791 /*
792 =for apidoc_section Optree Manipulation Functions
793
794 =for apidoc alloccopstash
795
796 Available only under threaded builds, this function allocates an entry in
797 C<PL_stashpad> for the stash passed to it.
798
799 =cut
800 */
801
802 #ifdef USE_ITHREADS
803 PADOFFSET
804 Perl_alloccopstash(pTHX_ HV *hv)
805 {
806     PADOFFSET off = 0, o = 1;
807     bool found_slot = FALSE;
808
809     PERL_ARGS_ASSERT_ALLOCCOPSTASH;
810
811     if (PL_stashpad[PL_stashpadix] == hv) return PL_stashpadix;
812
813     for (; o < PL_stashpadmax; ++o) {
814         if (PL_stashpad[o] == hv) return PL_stashpadix = o;
815         if (!PL_stashpad[o] || SvTYPE(PL_stashpad[o]) != SVt_PVHV)
816             found_slot = TRUE, off = o;
817     }
818     if (!found_slot) {
819         Renew(PL_stashpad, PL_stashpadmax + 10, HV *);
820         Zero(PL_stashpad + PL_stashpadmax, 10, HV *);
821         off = PL_stashpadmax;
822         PL_stashpadmax += 10;
823     }
824
825     PL_stashpad[PL_stashpadix = off] = hv;
826     return off;
827 }
828 #endif
829
830 /* free the body of an op without examining its contents.
831  * Always use this rather than FreeOp directly */
832
833 static void
834 S_op_destroy(pTHX_ OP *o)
835 {
836     FreeOp(o);
837 }
838
839 /* Destructor */
840
841 /*
842 =for apidoc op_free
843
844 Free an op and its children. Only use this when an op is no longer linked
845 to from any optree.
846
847 =cut
848 */
849
850 void
851 Perl_op_free(pTHX_ OP *o)
852 {
853     OPCODE type;
854     OP *top_op = o;
855     OP *next_op = o;
856     bool went_up = FALSE; /* whether we reached the current node by
857                             following the parent pointer from a child, and
858                             so have already seen this node */
859
860     if (!o || o->op_type == OP_FREED)
861         return;
862
863     if (o->op_private & OPpREFCOUNTED) {
864         /* if base of tree is refcounted, just decrement */
865         switch (o->op_type) {
866         case OP_LEAVESUB:
867         case OP_LEAVESUBLV:
868         case OP_LEAVEEVAL:
869         case OP_LEAVE:
870         case OP_SCOPE:
871         case OP_LEAVEWRITE:
872             {
873                 PADOFFSET refcnt;
874                 OP_REFCNT_LOCK;
875                 refcnt = OpREFCNT_dec(o);
876                 OP_REFCNT_UNLOCK;
877                 if (refcnt) {
878                     /* Need to find and remove any pattern match ops from
879                      * the list we maintain for reset().  */
880                     find_and_forget_pmops(o);
881                     return;
882                 }
883             }
884             break;
885         default:
886             break;
887         }
888     }
889
890     while (next_op) {
891         o = next_op;
892
893         /* free child ops before ourself, (then free ourself "on the
894          * way back up") */
895
896         if (!went_up && o->op_flags & OPf_KIDS) {
897             next_op = cUNOPo->op_first;
898             continue;
899         }
900
901         /* find the next node to visit, *then* free the current node
902          * (can't rely on o->op_* fields being valid after o has been
903          * freed) */
904
905         /* The next node to visit will be either the sibling, or the
906          * parent if no siblings left, or NULL if we've worked our way
907          * back up to the top node in the tree */
908         next_op = (o == top_op) ? NULL : o->op_sibparent;
909         went_up = cBOOL(!OpHAS_SIBLING(o)); /* parents are already visited */
910
911         /* Now process the current node */
912
913         /* Though ops may be freed twice, freeing the op after its slab is a
914            big no-no. */
915         assert(!o->op_slabbed || OpSLAB(o)->opslab_refcnt != ~(size_t)0);
916         /* During the forced freeing of ops after compilation failure, kidops
917            may be freed before their parents. */
918         if (!o || o->op_type == OP_FREED)
919             continue;
920
921         type = o->op_type;
922
923         /* an op should only ever acquire op_private flags that we know about.
924          * If this fails, you may need to fix something in regen/op_private.
925          * Don't bother testing if:
926          *   * the op_ppaddr doesn't match the op; someone may have
927          *     overridden the op and be doing strange things with it;
928          *   * we've errored, as op flags are often left in an
929          *     inconsistent state then. Note that an error when
930          *     compiling the main program leaves PL_parser NULL, so
931          *     we can't spot faults in the main code, only
932          *     evaled/required code */
933 #ifdef DEBUGGING
934         if (   o->op_ppaddr == PL_ppaddr[type]
935             && PL_parser
936             && !PL_parser->error_count)
937         {
938             assert(!(o->op_private & ~PL_op_private_valid[type]));
939         }
940 #endif
941
942
943         /* Call the op_free hook if it has been set. Do it now so that it's called
944          * at the right time for refcounted ops, but still before all of the kids
945          * are freed. */
946         CALL_OPFREEHOOK(o);
947
948         if (type == OP_NULL)
949             type = (OPCODE)o->op_targ;
950
951         if (o->op_slabbed)
952             Slab_to_rw(OpSLAB(o));
953
954         /* COP* is not cleared by op_clear() so that we may track line
955          * numbers etc even after null() */
956         if (type == OP_NEXTSTATE || type == OP_DBSTATE) {
957             cop_free((COP*)o);
958         }
959
960         op_clear(o);
961         FreeOp(o);
962         if (PL_op == o)
963             PL_op = NULL;
964     }
965 }
966
967
968 /* S_op_clear_gv(): free a GV attached to an OP */
969
970 STATIC
971 #ifdef USE_ITHREADS
972 void S_op_clear_gv(pTHX_ OP *o, PADOFFSET *ixp)
973 #else
974 void S_op_clear_gv(pTHX_ OP *o, SV**svp)
975 #endif
976 {
977
978     GV *gv = (o->op_type == OP_GV || o->op_type == OP_GVSV
979             || o->op_type == OP_MULTIDEREF)
980 #ifdef USE_ITHREADS
981                 && PL_curpad
982                 ? ((GV*)PAD_SVl(*ixp)) : NULL;
983 #else
984                 ? (GV*)(*svp) : NULL;
985 #endif
986     /* It's possible during global destruction that the GV is freed
987        before the optree. Whilst the SvREFCNT_inc is happy to bump from
988        0 to 1 on a freed SV, the corresponding SvREFCNT_dec from 1 to 0
989        will trigger an assertion failure, because the entry to sv_clear
990        checks that the scalar is not already freed.  A check of for
991        !SvIS_FREED(gv) turns out to be invalid, because during global
992        destruction the reference count can be forced down to zero
993        (with SVf_BREAK set).  In which case raising to 1 and then
994        dropping to 0 triggers cleanup before it should happen.  I
995        *think* that this might actually be a general, systematic,
996        weakness of the whole idea of SVf_BREAK, in that code *is*
997        allowed to raise and lower references during global destruction,
998        so any *valid* code that happens to do this during global
999        destruction might well trigger premature cleanup.  */
1000     bool still_valid = gv && SvREFCNT(gv);
1001
1002     if (still_valid)
1003         SvREFCNT_inc_simple_void(gv);
1004 #ifdef USE_ITHREADS
1005     if (*ixp > 0) {
1006         pad_swipe(*ixp, TRUE);
1007         *ixp = 0;
1008     }
1009 #else
1010     SvREFCNT_dec(*svp);
1011     *svp = NULL;
1012 #endif
1013     if (still_valid) {
1014         int try_downgrade = SvREFCNT(gv) == 2;
1015         SvREFCNT_dec_NN(gv);
1016         if (try_downgrade)
1017             gv_try_downgrade(gv);
1018     }
1019 }
1020
1021
1022 void
1023 Perl_op_clear(pTHX_ OP *o)
1024 {
1025
1026
1027     PERL_ARGS_ASSERT_OP_CLEAR;
1028
1029     switch (o->op_type) {
1030     case OP_NULL:       /* Was holding old type, if any. */
1031         /* FALLTHROUGH */
1032     case OP_ENTERTRY:
1033     case OP_ENTEREVAL:  /* Was holding hints. */
1034     case OP_ARGDEFELEM: /* Was holding signature index. */
1035         o->op_targ = 0;
1036         break;
1037     default:
1038         if (!(o->op_flags & OPf_REF) || !OP_IS_STAT(o->op_type))
1039             break;
1040         /* FALLTHROUGH */
1041     case OP_GVSV:
1042     case OP_GV:
1043     case OP_AELEMFAST:
1044 #ifdef USE_ITHREADS
1045             S_op_clear_gv(aTHX_ o, &(cPADOPx(o)->op_padix));
1046 #else
1047             S_op_clear_gv(aTHX_ o, &(cSVOPx(o)->op_sv));
1048 #endif
1049         break;
1050     case OP_METHOD_REDIR:
1051     case OP_METHOD_REDIR_SUPER:
1052 #ifdef USE_ITHREADS
1053         if (cMETHOPx(o)->op_rclass_targ) {
1054             pad_swipe(cMETHOPx(o)->op_rclass_targ, 1);
1055             cMETHOPx(o)->op_rclass_targ = 0;
1056         }
1057 #else
1058         SvREFCNT_dec(cMETHOPx(o)->op_rclass_sv);
1059         cMETHOPx(o)->op_rclass_sv = NULL;
1060 #endif
1061         /* FALLTHROUGH */
1062     case OP_METHOD_NAMED:
1063     case OP_METHOD_SUPER:
1064         SvREFCNT_dec(cMETHOPx(o)->op_u.op_meth_sv);
1065         cMETHOPx(o)->op_u.op_meth_sv = NULL;
1066 #ifdef USE_ITHREADS
1067         if (o->op_targ) {
1068             pad_swipe(o->op_targ, 1);
1069             o->op_targ = 0;
1070         }
1071 #endif
1072         break;
1073     case OP_CONST:
1074     case OP_HINTSEVAL:
1075         SvREFCNT_dec(cSVOPo->op_sv);
1076         cSVOPo->op_sv = NULL;
1077 #ifdef USE_ITHREADS
1078         /** Bug #15654
1079           Even if op_clear does a pad_free for the target of the op,
1080           pad_free doesn't actually remove the sv that exists in the pad;
1081           instead it lives on. This results in that it could be reused as
1082           a target later on when the pad was reallocated.
1083         **/
1084         if(o->op_targ) {
1085           pad_swipe(o->op_targ,1);
1086           o->op_targ = 0;
1087         }
1088 #endif
1089         break;
1090     case OP_DUMP:
1091     case OP_GOTO:
1092     case OP_NEXT:
1093     case OP_LAST:
1094     case OP_REDO:
1095         if (o->op_flags & (OPf_SPECIAL|OPf_STACKED|OPf_KIDS))
1096             break;
1097         /* FALLTHROUGH */
1098     case OP_TRANS:
1099     case OP_TRANSR:
1100         if (   (o->op_type == OP_TRANS || o->op_type == OP_TRANSR)
1101             && (o->op_private & OPpTRANS_USE_SVOP))
1102         {
1103 #ifdef USE_ITHREADS
1104             if (cPADOPo->op_padix > 0) {
1105                 pad_swipe(cPADOPo->op_padix, TRUE);
1106                 cPADOPo->op_padix = 0;
1107             }
1108 #else
1109             SvREFCNT_dec(cSVOPo->op_sv);
1110             cSVOPo->op_sv = NULL;
1111 #endif
1112         }
1113         else {
1114             PerlMemShared_free(cPVOPo->op_pv);
1115             cPVOPo->op_pv = NULL;
1116         }
1117         break;
1118     case OP_SUBST:
1119         op_free(cPMOPo->op_pmreplrootu.op_pmreplroot);
1120         goto clear_pmop;
1121
1122     case OP_SPLIT:
1123         if (     (o->op_private & OPpSPLIT_ASSIGN) /* @array  = split */
1124             && !(o->op_flags & OPf_STACKED))       /* @{expr} = split */
1125         {
1126             if (o->op_private & OPpSPLIT_LEX)
1127                 pad_free(cPMOPo->op_pmreplrootu.op_pmtargetoff);
1128             else
1129 #ifdef USE_ITHREADS
1130                 pad_swipe(cPMOPo->op_pmreplrootu.op_pmtargetoff, TRUE);
1131 #else
1132                 SvREFCNT_dec(MUTABLE_SV(cPMOPo->op_pmreplrootu.op_pmtargetgv));
1133 #endif
1134         }
1135         /* FALLTHROUGH */
1136     case OP_MATCH:
1137     case OP_QR:
1138     clear_pmop:
1139         if (!(cPMOPo->op_pmflags & PMf_CODELIST_PRIVATE))
1140             op_free(cPMOPo->op_code_list);
1141         cPMOPo->op_code_list = NULL;
1142         forget_pmop(cPMOPo);
1143         cPMOPo->op_pmreplrootu.op_pmreplroot = NULL;
1144         /* we use the same protection as the "SAFE" version of the PM_ macros
1145          * here since sv_clean_all might release some PMOPs
1146          * after PL_regex_padav has been cleared
1147          * and the clearing of PL_regex_padav needs to
1148          * happen before sv_clean_all
1149          */
1150 #ifdef USE_ITHREADS
1151         if(PL_regex_pad) {        /* We could be in destruction */
1152             const IV offset = (cPMOPo)->op_pmoffset;
1153             ReREFCNT_dec(PM_GETRE(cPMOPo));
1154             PL_regex_pad[offset] = &PL_sv_undef;
1155             sv_catpvn_nomg(PL_regex_pad[0], (const char *)&offset,
1156                            sizeof(offset));
1157         }
1158 #else
1159         ReREFCNT_dec(PM_GETRE(cPMOPo));
1160         PM_SETRE(cPMOPo, NULL);
1161 #endif
1162
1163         break;
1164
1165     case OP_ARGCHECK:
1166         PerlMemShared_free(cUNOP_AUXo->op_aux);
1167         break;
1168
1169     case OP_MULTICONCAT:
1170         {
1171             UNOP_AUX_item *aux = cUNOP_AUXo->op_aux;
1172             /* aux[PERL_MULTICONCAT_IX_PLAIN_PV] and/or
1173              * aux[PERL_MULTICONCAT_IX_UTF8_PV] point to plain and/or
1174              * utf8 shared strings */
1175             char *p1 = aux[PERL_MULTICONCAT_IX_PLAIN_PV].pv;
1176             char *p2 = aux[PERL_MULTICONCAT_IX_UTF8_PV].pv;
1177             if (p1)
1178                 PerlMemShared_free(p1);
1179             if (p2 && p1 != p2)
1180                 PerlMemShared_free(p2);
1181             PerlMemShared_free(aux);
1182         }
1183         break;
1184
1185     case OP_MULTIDEREF:
1186         {
1187             UNOP_AUX_item *items = cUNOP_AUXo->op_aux;
1188             UV actions = items->uv;
1189             bool last = 0;
1190             bool is_hash = FALSE;
1191
1192             while (!last) {
1193                 switch (actions & MDEREF_ACTION_MASK) {
1194
1195                 case MDEREF_reload:
1196                     actions = (++items)->uv;
1197                     continue;
1198
1199                 case MDEREF_HV_padhv_helem:
1200                     is_hash = TRUE;
1201                     /* FALLTHROUGH */
1202                 case MDEREF_AV_padav_aelem:
1203                     pad_free((++items)->pad_offset);
1204                     goto do_elem;
1205
1206                 case MDEREF_HV_gvhv_helem:
1207                     is_hash = TRUE;
1208                     /* FALLTHROUGH */
1209                 case MDEREF_AV_gvav_aelem:
1210 #ifdef USE_ITHREADS
1211                     S_op_clear_gv(aTHX_ o, &((++items)->pad_offset));
1212 #else
1213                     S_op_clear_gv(aTHX_ o, &((++items)->sv));
1214 #endif
1215                     goto do_elem;
1216
1217                 case MDEREF_HV_gvsv_vivify_rv2hv_helem:
1218                     is_hash = TRUE;
1219                     /* FALLTHROUGH */
1220                 case MDEREF_AV_gvsv_vivify_rv2av_aelem:
1221 #ifdef USE_ITHREADS
1222                     S_op_clear_gv(aTHX_ o, &((++items)->pad_offset));
1223 #else
1224                     S_op_clear_gv(aTHX_ o, &((++items)->sv));
1225 #endif
1226                     goto do_vivify_rv2xv_elem;
1227
1228                 case MDEREF_HV_padsv_vivify_rv2hv_helem:
1229                     is_hash = TRUE;
1230                     /* FALLTHROUGH */
1231                 case MDEREF_AV_padsv_vivify_rv2av_aelem:
1232                     pad_free((++items)->pad_offset);
1233                     goto do_vivify_rv2xv_elem;
1234
1235                 case MDEREF_HV_pop_rv2hv_helem:
1236                 case MDEREF_HV_vivify_rv2hv_helem:
1237                     is_hash = TRUE;
1238                     /* FALLTHROUGH */
1239                 do_vivify_rv2xv_elem:
1240                 case MDEREF_AV_pop_rv2av_aelem:
1241                 case MDEREF_AV_vivify_rv2av_aelem:
1242                 do_elem:
1243                     switch (actions & MDEREF_INDEX_MASK) {
1244                     case MDEREF_INDEX_none:
1245                         last = 1;
1246                         break;
1247                     case MDEREF_INDEX_const:
1248                         if (is_hash) {
1249 #ifdef USE_ITHREADS
1250                             /* see RT #15654 */
1251                             pad_swipe((++items)->pad_offset, 1);
1252 #else
1253                             SvREFCNT_dec((++items)->sv);
1254 #endif
1255                         }
1256                         else
1257                             items++;
1258                         break;
1259                     case MDEREF_INDEX_padsv:
1260                         pad_free((++items)->pad_offset);
1261                         break;
1262                     case MDEREF_INDEX_gvsv:
1263 #ifdef USE_ITHREADS
1264                         S_op_clear_gv(aTHX_ o, &((++items)->pad_offset));
1265 #else
1266                         S_op_clear_gv(aTHX_ o, &((++items)->sv));
1267 #endif
1268                         break;
1269                     }
1270
1271                     if (actions & MDEREF_FLAG_last)
1272                         last = 1;
1273                     is_hash = FALSE;
1274
1275                     break;
1276
1277                 default:
1278                     assert(0);
1279                     last = 1;
1280                     break;
1281
1282                 } /* switch */
1283
1284                 actions >>= MDEREF_SHIFT;
1285             } /* while */
1286
1287             /* start of malloc is at op_aux[-1], where the length is
1288              * stored */
1289             PerlMemShared_free(cUNOP_AUXo->op_aux - 1);
1290         }
1291         break;
1292     }
1293
1294     if (o->op_targ > 0) {
1295         pad_free(o->op_targ);
1296         o->op_targ = 0;
1297     }
1298 }
1299
1300 STATIC void
1301 S_cop_free(pTHX_ COP* cop)
1302 {
1303     PERL_ARGS_ASSERT_COP_FREE;
1304
1305     CopFILE_free(cop);
1306     if (! specialWARN(cop->cop_warnings))
1307         PerlMemShared_free(cop->cop_warnings);
1308     cophh_free(CopHINTHASH_get(cop));
1309     if (PL_curcop == cop)
1310        PL_curcop = NULL;
1311 }
1312
1313 STATIC void
1314 S_forget_pmop(pTHX_ PMOP *const o)
1315 {
1316     HV * const pmstash = PmopSTASH(o);
1317
1318     PERL_ARGS_ASSERT_FORGET_PMOP;
1319
1320     if (pmstash && !SvIS_FREED(pmstash) && SvMAGICAL(pmstash)) {
1321         MAGIC * const mg = mg_find((const SV *)pmstash, PERL_MAGIC_symtab);
1322         if (mg) {
1323             PMOP **const array = (PMOP**) mg->mg_ptr;
1324             U32 count = mg->mg_len / sizeof(PMOP**);
1325             U32 i = count;
1326
1327             while (i--) {
1328                 if (array[i] == o) {
1329                     /* Found it. Move the entry at the end to overwrite it.  */
1330                     array[i] = array[--count];
1331                     mg->mg_len = count * sizeof(PMOP**);
1332                     /* Could realloc smaller at this point always, but probably
1333                        not worth it. Probably worth free()ing if we're the
1334                        last.  */
1335                     if(!count) {
1336                         Safefree(mg->mg_ptr);
1337                         mg->mg_ptr = NULL;
1338                     }
1339                     break;
1340                 }
1341             }
1342         }
1343     }
1344     if (PL_curpm == o)
1345         PL_curpm = NULL;
1346 }
1347
1348
1349 STATIC void
1350 S_find_and_forget_pmops(pTHX_ OP *o)
1351 {
1352     OP* top_op = o;
1353
1354     PERL_ARGS_ASSERT_FIND_AND_FORGET_PMOPS;
1355
1356     while (1) {
1357         switch (o->op_type) {
1358         case OP_SUBST:
1359         case OP_SPLIT:
1360         case OP_MATCH:
1361         case OP_QR:
1362             forget_pmop((PMOP*)o);
1363         }
1364
1365         if (o->op_flags & OPf_KIDS) {
1366             o = cUNOPo->op_first;
1367             continue;
1368         }
1369
1370         while (1) {
1371             if (o == top_op)
1372                 return; /* at top; no parents/siblings to try */
1373             if (OpHAS_SIBLING(o)) {
1374                 o = o->op_sibparent; /* process next sibling */
1375                 break;
1376             }
1377             o = o->op_sibparent; /*try parent's next sibling */
1378         }
1379     }
1380 }
1381
1382
1383 /*
1384 =for apidoc op_null
1385
1386 Neutralizes an op when it is no longer needed, but is still linked to from
1387 other ops.
1388
1389 =cut
1390 */
1391
1392 void
1393 Perl_op_null(pTHX_ OP *o)
1394 {
1395
1396     PERL_ARGS_ASSERT_OP_NULL;
1397
1398     if (o->op_type == OP_NULL)
1399         return;
1400     op_clear(o);
1401     o->op_targ = o->op_type;
1402     OpTYPE_set(o, OP_NULL);
1403 }
1404
1405 void
1406 Perl_op_refcnt_lock(pTHX)
1407   PERL_TSA_ACQUIRE(PL_op_mutex)
1408 {
1409 #ifdef USE_ITHREADS
1410 #endif
1411     PERL_UNUSED_CONTEXT;
1412     OP_REFCNT_LOCK;
1413 }
1414
1415 void
1416 Perl_op_refcnt_unlock(pTHX)
1417   PERL_TSA_RELEASE(PL_op_mutex)
1418 {
1419 #ifdef USE_ITHREADS
1420 #endif
1421     PERL_UNUSED_CONTEXT;
1422     OP_REFCNT_UNLOCK;
1423 }
1424
1425
1426 /*
1427 =for apidoc op_sibling_splice
1428
1429 A general function for editing the structure of an existing chain of
1430 op_sibling nodes.  By analogy with the perl-level C<splice()> function, allows
1431 you to delete zero or more sequential nodes, replacing them with zero or
1432 more different nodes.  Performs the necessary op_first/op_last
1433 housekeeping on the parent node and op_sibling manipulation on the
1434 children.  The last deleted node will be marked as the last node by
1435 updating the op_sibling/op_sibparent or op_moresib field as appropriate.
1436
1437 Note that op_next is not manipulated, and nodes are not freed; that is the
1438 responsibility of the caller.  It also won't create a new list op for an
1439 empty list etc; use higher-level functions like op_append_elem() for that.
1440
1441 C<parent> is the parent node of the sibling chain. It may passed as C<NULL> if
1442 the splicing doesn't affect the first or last op in the chain.
1443
1444 C<start> is the node preceding the first node to be spliced.  Node(s)
1445 following it will be deleted, and ops will be inserted after it.  If it is
1446 C<NULL>, the first node onwards is deleted, and nodes are inserted at the
1447 beginning.
1448
1449 C<del_count> is the number of nodes to delete.  If zero, no nodes are deleted.
1450 If -1 or greater than or equal to the number of remaining kids, all
1451 remaining kids are deleted.
1452
1453 C<insert> is the first of a chain of nodes to be inserted in place of the nodes.
1454 If C<NULL>, no nodes are inserted.
1455
1456 The head of the chain of deleted ops is returned, or C<NULL> if no ops were
1457 deleted.
1458
1459 For example:
1460
1461     action                    before      after         returns
1462     ------                    -----       -----         -------
1463
1464                               P           P
1465     splice(P, A, 2, X-Y-Z)    |           |             B-C
1466                               A-B-C-D     A-X-Y-Z-D
1467
1468                               P           P
1469     splice(P, NULL, 1, X-Y)   |           |             A
1470                               A-B-C-D     X-Y-B-C-D
1471
1472                               P           P
1473     splice(P, NULL, 3, NULL)  |           |             A-B-C
1474                               A-B-C-D     D
1475
1476                               P           P
1477     splice(P, B, 0, X-Y)      |           |             NULL
1478                               A-B-C-D     A-B-X-Y-C-D
1479
1480
1481 For lower-level direct manipulation of C<op_sibparent> and C<op_moresib>,
1482 see C<L</OpMORESIB_set>>, C<L</OpLASTSIB_set>>, C<L</OpMAYBESIB_set>>.
1483
1484 =cut
1485 */
1486
1487 OP *
1488 Perl_op_sibling_splice(OP *parent, OP *start, int del_count, OP* insert)
1489 {
1490     OP *first;
1491     OP *rest;
1492     OP *last_del = NULL;
1493     OP *last_ins = NULL;
1494
1495     if (start)
1496         first = OpSIBLING(start);
1497     else if (!parent)
1498         goto no_parent;
1499     else
1500         first = cLISTOPx(parent)->op_first;
1501
1502     assert(del_count >= -1);
1503
1504     if (del_count && first) {
1505         last_del = first;
1506         while (--del_count && OpHAS_SIBLING(last_del))
1507             last_del = OpSIBLING(last_del);
1508         rest = OpSIBLING(last_del);
1509         OpLASTSIB_set(last_del, NULL);
1510     }
1511     else
1512         rest = first;
1513
1514     if (insert) {
1515         last_ins = insert;
1516         while (OpHAS_SIBLING(last_ins))
1517             last_ins = OpSIBLING(last_ins);
1518         OpMAYBESIB_set(last_ins, rest, NULL);
1519     }
1520     else
1521         insert = rest;
1522
1523     if (start) {
1524         OpMAYBESIB_set(start, insert, NULL);
1525     }
1526     else {
1527         assert(parent);
1528         cLISTOPx(parent)->op_first = insert;
1529         if (insert)
1530             parent->op_flags |= OPf_KIDS;
1531         else
1532             parent->op_flags &= ~OPf_KIDS;
1533     }
1534
1535     if (!rest) {
1536         /* update op_last etc */
1537         U32 type;
1538         OP *lastop;
1539
1540         if (!parent)
1541             goto no_parent;
1542
1543         /* ought to use OP_CLASS(parent) here, but that can't handle
1544          * ex-foo OP_NULL ops. Also note that XopENTRYCUSTOM() can't
1545          * either */
1546         type = parent->op_type;
1547         if (type == OP_CUSTOM) {
1548             dTHX;
1549             type = XopENTRYCUSTOM(parent, xop_class);
1550         }
1551         else {
1552             if (type == OP_NULL)
1553                 type = parent->op_targ;
1554             type = PL_opargs[type] & OA_CLASS_MASK;
1555         }
1556
1557         lastop = last_ins ? last_ins : start ? start : NULL;
1558         if (   type == OA_BINOP
1559             || type == OA_LISTOP
1560             || type == OA_PMOP
1561             || type == OA_LOOP
1562         )
1563             cLISTOPx(parent)->op_last = lastop;
1564
1565         if (lastop)
1566             OpLASTSIB_set(lastop, parent);
1567     }
1568     return last_del ? first : NULL;
1569
1570   no_parent:
1571     Perl_croak_nocontext("panic: op_sibling_splice(): NULL parent");
1572 }
1573
1574 /*
1575 =for apidoc op_parent
1576
1577 Returns the parent OP of C<o>, if it has a parent. Returns C<NULL> otherwise.
1578
1579 =cut
1580 */
1581
1582 OP *
1583 Perl_op_parent(OP *o)
1584 {
1585     PERL_ARGS_ASSERT_OP_PARENT;
1586     while (OpHAS_SIBLING(o))
1587         o = OpSIBLING(o);
1588     return o->op_sibparent;
1589 }
1590
1591 /* replace the sibling following start with a new UNOP, which becomes
1592  * the parent of the original sibling; e.g.
1593  *
1594  *  op_sibling_newUNOP(P, A, unop-args...)
1595  *
1596  *  P              P
1597  *  |      becomes |
1598  *  A-B-C          A-U-C
1599  *                   |
1600  *                   B
1601  *
1602  * where U is the new UNOP.
1603  *
1604  * parent and start args are the same as for op_sibling_splice();
1605  * type and flags args are as newUNOP().
1606  *
1607  * Returns the new UNOP.
1608  */
1609
1610 STATIC OP *
1611 S_op_sibling_newUNOP(pTHX_ OP *parent, OP *start, I32 type, I32 flags)
1612 {
1613     OP *kid, *newop;
1614
1615     kid = op_sibling_splice(parent, start, 1, NULL);
1616     newop = newUNOP(type, flags, kid);
1617     op_sibling_splice(parent, start, 0, newop);
1618     return newop;
1619 }
1620
1621
1622 /* lowest-level newLOGOP-style function - just allocates and populates
1623  * the struct. Higher-level stuff should be done by S_new_logop() /
1624  * newLOGOP(). This function exists mainly to avoid op_first assignment
1625  * being spread throughout this file.
1626  */
1627
1628 LOGOP *
1629 Perl_alloc_LOGOP(pTHX_ I32 type, OP *first, OP* other)
1630 {
1631     LOGOP *logop;
1632     OP *kid = first;
1633     NewOp(1101, logop, 1, LOGOP);
1634     OpTYPE_set(logop, type);
1635     logop->op_first = first;
1636     logop->op_other = other;
1637     if (first)
1638         logop->op_flags = OPf_KIDS;
1639     while (kid && OpHAS_SIBLING(kid))
1640         kid = OpSIBLING(kid);
1641     if (kid)
1642         OpLASTSIB_set(kid, (OP*)logop);
1643     return logop;
1644 }
1645
1646
1647 /* Contextualizers */
1648
1649 /*
1650 =for apidoc op_contextualize
1651
1652 Applies a syntactic context to an op tree representing an expression.
1653 C<o> is the op tree, and C<context> must be C<G_SCALAR>, C<G_ARRAY>,
1654 or C<G_VOID> to specify the context to apply.  The modified op tree
1655 is returned.
1656
1657 =cut
1658 */
1659
1660 OP *
1661 Perl_op_contextualize(pTHX_ OP *o, I32 context)
1662 {
1663     PERL_ARGS_ASSERT_OP_CONTEXTUALIZE;
1664     switch (context) {
1665         case G_SCALAR: return scalar(o);
1666         case G_ARRAY:  return list(o);
1667         case G_VOID:   return scalarvoid(o);
1668         default:
1669             Perl_croak(aTHX_ "panic: op_contextualize bad context %ld",
1670                        (long) context);
1671     }
1672 }
1673
1674 /*
1675
1676 =for apidoc op_linklist
1677 This function is the implementation of the L</LINKLIST> macro.  It should
1678 not be called directly.
1679
1680 =cut
1681 */
1682
1683
1684 OP *
1685 Perl_op_linklist(pTHX_ OP *o)
1686 {
1687
1688     OP **prevp;
1689     OP *kid;
1690     OP * top_op = o;
1691
1692     PERL_ARGS_ASSERT_OP_LINKLIST;
1693
1694     while (1) {
1695         /* Descend down the tree looking for any unprocessed subtrees to
1696          * do first */
1697         if (!o->op_next) {
1698             if (o->op_flags & OPf_KIDS) {
1699                 o = cUNOPo->op_first;
1700                 continue;
1701             }
1702             o->op_next = o; /* leaf node; link to self initially */
1703         }
1704
1705         /* if we're at the top level, there either weren't any children
1706          * to process, or we've worked our way back to the top. */
1707         if (o == top_op)
1708             return o->op_next;
1709
1710         /* o is now processed. Next, process any sibling subtrees */
1711
1712         if (OpHAS_SIBLING(o)) {
1713             o = OpSIBLING(o);
1714             continue;
1715         }
1716
1717         /* Done all the subtrees at this level. Go back up a level and
1718          * link the parent in with all its (processed) children.
1719          */
1720
1721         o = o->op_sibparent;
1722         assert(!o->op_next);
1723         prevp = &(o->op_next);
1724         kid   = (o->op_flags & OPf_KIDS) ? cUNOPo->op_first : NULL;
1725         while (kid) {
1726             *prevp = kid->op_next;
1727             prevp = &(kid->op_next);
1728             kid = OpSIBLING(kid);
1729         }
1730         *prevp = o;
1731     }
1732 }
1733
1734
1735 static OP *
1736 S_scalarkids(pTHX_ OP *o)
1737 {
1738     if (o && o->op_flags & OPf_KIDS) {
1739         OP *kid;
1740         for (kid = cLISTOPo->op_first; kid; kid = OpSIBLING(kid))
1741             scalar(kid);
1742     }
1743     return o;
1744 }
1745
1746 STATIC OP *
1747 S_scalarboolean(pTHX_ OP *o)
1748 {
1749     PERL_ARGS_ASSERT_SCALARBOOLEAN;
1750
1751     if ((o->op_type == OP_SASSIGN && cBINOPo->op_first->op_type == OP_CONST &&
1752          !(cBINOPo->op_first->op_flags & OPf_SPECIAL)) ||
1753         (o->op_type == OP_NOT     && cUNOPo->op_first->op_type == OP_SASSIGN &&
1754          cBINOPx(cUNOPo->op_first)->op_first->op_type == OP_CONST &&
1755          !(cBINOPx(cUNOPo->op_first)->op_first->op_flags & OPf_SPECIAL))) {
1756         if (ckWARN(WARN_SYNTAX)) {
1757             const line_t oldline = CopLINE(PL_curcop);
1758
1759             if (PL_parser && PL_parser->copline != NOLINE) {
1760                 /* This ensures that warnings are reported at the first line
1761                    of the conditional, not the last.  */
1762                 CopLINE_set(PL_curcop, PL_parser->copline);
1763             }
1764             Perl_warner(aTHX_ packWARN(WARN_SYNTAX), "Found = in conditional, should be ==");
1765             CopLINE_set(PL_curcop, oldline);
1766         }
1767     }
1768     return scalar(o);
1769 }
1770
1771 static SV *
1772 S_op_varname_subscript(pTHX_ const OP *o, int subscript_type)
1773 {
1774     assert(o);
1775     assert(o->op_type == OP_PADAV || o->op_type == OP_RV2AV ||
1776            o->op_type == OP_PADHV || o->op_type == OP_RV2HV);
1777     {
1778         const char funny  = o->op_type == OP_PADAV
1779                          || o->op_type == OP_RV2AV ? '@' : '%';
1780         if (o->op_type == OP_RV2AV || o->op_type == OP_RV2HV) {
1781             GV *gv;
1782             if (cUNOPo->op_first->op_type != OP_GV
1783              || !(gv = cGVOPx_gv(cUNOPo->op_first)))
1784                 return NULL;
1785             return varname(gv, funny, 0, NULL, 0, subscript_type);
1786         }
1787         return
1788             varname(MUTABLE_GV(PL_compcv), funny, o->op_targ, NULL, 0, subscript_type);
1789     }
1790 }
1791
1792 static SV *
1793 S_op_varname(pTHX_ const OP *o)
1794 {
1795     return S_op_varname_subscript(aTHX_ o, 1);
1796 }
1797
1798 static void
1799 S_op_pretty(pTHX_ const OP *o, SV **retsv, const char **retpv)
1800 { /* or not so pretty :-) */
1801     if (o->op_type == OP_CONST) {
1802         *retsv = cSVOPo_sv;
1803         if (SvPOK(*retsv)) {
1804             SV *sv = *retsv;
1805             *retsv = sv_newmortal();
1806             pv_pretty(*retsv, SvPVX_const(sv), SvCUR(sv), 32, NULL, NULL,
1807                       PERL_PV_PRETTY_DUMP |PERL_PV_ESCAPE_UNI_DETECT);
1808         }
1809         else if (!SvOK(*retsv))
1810             *retpv = "undef";
1811     }
1812     else *retpv = "...";
1813 }
1814
1815 static void
1816 S_scalar_slice_warning(pTHX_ const OP *o)
1817 {
1818     OP *kid;
1819     const bool h = o->op_type == OP_HSLICE
1820                 || (o->op_type == OP_NULL && o->op_targ == OP_HSLICE);
1821     const char lbrack =
1822         h ? '{' : '[';
1823     const char rbrack =
1824         h ? '}' : ']';
1825     SV *name;
1826     SV *keysv = NULL; /* just to silence compiler warnings */
1827     const char *key = NULL;
1828
1829     if (!(o->op_private & OPpSLICEWARNING))
1830         return;
1831     if (PL_parser && PL_parser->error_count)
1832         /* This warning can be nonsensical when there is a syntax error. */
1833         return;
1834
1835     kid = cLISTOPo->op_first;
1836     kid = OpSIBLING(kid); /* get past pushmark */
1837     /* weed out false positives: any ops that can return lists */
1838     switch (kid->op_type) {
1839     case OP_BACKTICK:
1840     case OP_GLOB:
1841     case OP_READLINE:
1842     case OP_MATCH:
1843     case OP_RV2AV:
1844     case OP_EACH:
1845     case OP_VALUES:
1846     case OP_KEYS:
1847     case OP_SPLIT:
1848     case OP_LIST:
1849     case OP_SORT:
1850     case OP_REVERSE:
1851     case OP_ENTERSUB:
1852     case OP_CALLER:
1853     case OP_LSTAT:
1854     case OP_STAT:
1855     case OP_READDIR:
1856     case OP_SYSTEM:
1857     case OP_TMS:
1858     case OP_LOCALTIME:
1859     case OP_GMTIME:
1860     case OP_ENTEREVAL:
1861         return;
1862     }
1863
1864     /* Don't warn if we have a nulled list either. */
1865     if (kid->op_type == OP_NULL && kid->op_targ == OP_LIST)
1866         return;
1867
1868     assert(OpSIBLING(kid));
1869     name = S_op_varname(aTHX_ OpSIBLING(kid));
1870     if (!name) /* XS module fiddling with the op tree */
1871         return;
1872     S_op_pretty(aTHX_ kid, &keysv, &key);
1873     assert(SvPOK(name));
1874     sv_chop(name,SvPVX(name)+1);
1875     if (key)
1876        /* diag_listed_as: Scalar value @%s[%s] better written as $%s[%s] */
1877         Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
1878                    "Scalar value @%" SVf "%c%s%c better written as $%" SVf
1879                    "%c%s%c",
1880                     SVfARG(name), lbrack, key, rbrack, SVfARG(name),
1881                     lbrack, key, rbrack);
1882     else
1883        /* diag_listed_as: Scalar value @%s[%s] better written as $%s[%s] */
1884         Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
1885                    "Scalar value @%" SVf "%c%" SVf "%c better written as $%"
1886                     SVf "%c%" SVf "%c",
1887                     SVfARG(name), lbrack, SVfARG(keysv), rbrack,
1888                     SVfARG(name), lbrack, SVfARG(keysv), rbrack);
1889 }
1890
1891
1892
1893 /* apply scalar context to the o subtree */
1894
1895 OP *
1896 Perl_scalar(pTHX_ OP *o)
1897 {
1898     OP * top_op = o;
1899
1900     while (1) {
1901         OP *next_kid = NULL; /* what op (if any) to process next */
1902         OP *kid;
1903
1904         /* assumes no premature commitment */
1905         if (!o || (PL_parser && PL_parser->error_count)
1906              || (o->op_flags & OPf_WANT)
1907              || o->op_type == OP_RETURN)
1908         {
1909             goto do_next;
1910         }
1911
1912         o->op_flags = (o->op_flags & ~OPf_WANT) | OPf_WANT_SCALAR;
1913
1914         switch (o->op_type) {
1915         case OP_REPEAT:
1916             scalar(cBINOPo->op_first);
1917             /* convert what initially looked like a list repeat into a
1918              * scalar repeat, e.g. $s = (1) x $n
1919              */
1920             if (o->op_private & OPpREPEAT_DOLIST) {
1921                 kid = cLISTOPx(cUNOPo->op_first)->op_first;
1922                 assert(kid->op_type == OP_PUSHMARK);
1923                 if (OpHAS_SIBLING(kid) && !OpHAS_SIBLING(OpSIBLING(kid))) {
1924                     op_null(cLISTOPx(cUNOPo->op_first)->op_first);
1925                     o->op_private &=~ OPpREPEAT_DOLIST;
1926                 }
1927             }
1928             break;
1929
1930         case OP_OR:
1931         case OP_AND:
1932         case OP_COND_EXPR:
1933             /* impose scalar context on everything except the condition */
1934             next_kid = OpSIBLING(cUNOPo->op_first);
1935             break;
1936
1937         default:
1938             if (o->op_flags & OPf_KIDS)
1939                 next_kid = cUNOPo->op_first; /* do all kids */
1940             break;
1941
1942         /* the children of these ops are usually a list of statements,
1943          * except the leaves, whose first child is a corresponding enter
1944          */
1945         case OP_SCOPE:
1946         case OP_LINESEQ:
1947         case OP_LIST:
1948             kid = cLISTOPo->op_first;
1949             goto do_kids;
1950         case OP_LEAVE:
1951         case OP_LEAVETRY:
1952             kid = cLISTOPo->op_first;
1953             scalar(kid);
1954             kid = OpSIBLING(kid);
1955         do_kids:
1956             while (kid) {
1957                 OP *sib = OpSIBLING(kid);
1958                 /* Apply void context to all kids except the last, which
1959                  * is scalar (ignoring a trailing ex-nextstate in determining
1960                  * if it's the last kid). E.g.
1961                  *      $scalar = do { void; void; scalar }
1962                  * Except that 'when's are always scalar, e.g.
1963                  *      $scalar = do { given(..) {
1964                     *                 when (..) { scalar }
1965                     *                 when (..) { scalar }
1966                     *                 ...
1967                     *                }}
1968                     */
1969                 if (!sib
1970                      || (  !OpHAS_SIBLING(sib)
1971                          && sib->op_type == OP_NULL
1972                          && (   sib->op_targ == OP_NEXTSTATE
1973                              || sib->op_targ == OP_DBSTATE  )
1974                         )
1975                 )
1976                 {
1977                     /* tail call optimise calling scalar() on the last kid */
1978                     next_kid = kid;
1979                     goto do_next;
1980                 }
1981                 else if (kid->op_type == OP_LEAVEWHEN)
1982                     scalar(kid);
1983                 else
1984                     scalarvoid(kid);
1985                 kid = sib;
1986             }
1987             NOT_REACHED; /* NOTREACHED */
1988             break;
1989
1990         case OP_SORT:
1991             Perl_ck_warner(aTHX_ packWARN(WARN_VOID), "Useless use of sort in scalar context");
1992             break;
1993
1994         case OP_KVHSLICE:
1995         case OP_KVASLICE:
1996         {
1997             /* Warn about scalar context */
1998             const char lbrack = o->op_type == OP_KVHSLICE ? '{' : '[';
1999             const char rbrack = o->op_type == OP_KVHSLICE ? '}' : ']';
2000             SV *name;
2001             SV *keysv;
2002             const char *key = NULL;
2003
2004             /* This warning can be nonsensical when there is a syntax error. */
2005             if (PL_parser && PL_parser->error_count)
2006                 break;
2007
2008             if (!ckWARN(WARN_SYNTAX)) break;
2009
2010             kid = cLISTOPo->op_first;
2011             kid = OpSIBLING(kid); /* get past pushmark */
2012             assert(OpSIBLING(kid));
2013             name = S_op_varname(aTHX_ OpSIBLING(kid));
2014             if (!name) /* XS module fiddling with the op tree */
2015                 break;
2016             S_op_pretty(aTHX_ kid, &keysv, &key);
2017             assert(SvPOK(name));
2018             sv_chop(name,SvPVX(name)+1);
2019             if (key)
2020       /* diag_listed_as: %%s[%s] in scalar context better written as $%s[%s] */
2021                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
2022                            "%%%" SVf "%c%s%c in scalar context better written "
2023                            "as $%" SVf "%c%s%c",
2024                             SVfARG(name), lbrack, key, rbrack, SVfARG(name),
2025                             lbrack, key, rbrack);
2026             else
2027       /* diag_listed_as: %%s[%s] in scalar context better written as $%s[%s] */
2028                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
2029                            "%%%" SVf "%c%" SVf "%c in scalar context better "
2030                            "written as $%" SVf "%c%" SVf "%c",
2031                             SVfARG(name), lbrack, SVfARG(keysv), rbrack,
2032                             SVfARG(name), lbrack, SVfARG(keysv), rbrack);
2033         }
2034         } /* switch */
2035
2036         /* If next_kid is set, someone in the code above wanted us to process
2037          * that kid and all its remaining siblings.  Otherwise, work our way
2038          * back up the tree */
2039       do_next:
2040         while (!next_kid) {
2041             if (o == top_op)
2042                 return top_op; /* at top; no parents/siblings to try */
2043             if (OpHAS_SIBLING(o))
2044                 next_kid = o->op_sibparent;
2045             else {
2046                 o = o->op_sibparent; /*try parent's next sibling */
2047                 switch (o->op_type) {
2048                 case OP_SCOPE:
2049                 case OP_LINESEQ:
2050                 case OP_LIST:
2051                 case OP_LEAVE:
2052                 case OP_LEAVETRY:
2053                     /* should really restore PL_curcop to its old value, but
2054                      * setting it to PL_compiling is better than do nothing */
2055                     PL_curcop = &PL_compiling;
2056                 }
2057             }
2058         }
2059         o = next_kid;
2060     } /* while */
2061 }
2062
2063
2064 /* apply void context to the optree arg */
2065
2066 OP *
2067 Perl_scalarvoid(pTHX_ OP *arg)
2068 {
2069     OP *kid;
2070     SV* sv;
2071     OP *o = arg;
2072
2073     PERL_ARGS_ASSERT_SCALARVOID;
2074
2075     while (1) {
2076         U8 want;
2077         SV *useless_sv = NULL;
2078         const char* useless = NULL;
2079         OP * next_kid = NULL;
2080
2081         if (o->op_type == OP_NEXTSTATE
2082             || o->op_type == OP_DBSTATE
2083             || (o->op_type == OP_NULL && (o->op_targ == OP_NEXTSTATE
2084                                           || o->op_targ == OP_DBSTATE)))
2085             PL_curcop = (COP*)o;                /* for warning below */
2086
2087         /* assumes no premature commitment */
2088         want = o->op_flags & OPf_WANT;
2089         if ((want && want != OPf_WANT_SCALAR)
2090             || (PL_parser && PL_parser->error_count)
2091             || o->op_type == OP_RETURN || o->op_type == OP_REQUIRE || o->op_type == OP_LEAVEWHEN)
2092         {
2093             goto get_next_op;
2094         }
2095
2096         if ((o->op_private & OPpTARGET_MY)
2097             && (PL_opargs[o->op_type] & OA_TARGLEX))/* OPp share the meaning */
2098         {
2099             /* newASSIGNOP has already applied scalar context, which we
2100                leave, as if this op is inside SASSIGN.  */
2101             goto get_next_op;
2102         }
2103
2104         o->op_flags = (o->op_flags & ~OPf_WANT) | OPf_WANT_VOID;
2105
2106         switch (o->op_type) {
2107         default:
2108             if (!(PL_opargs[o->op_type] & OA_FOLDCONST))
2109                 break;
2110             /* FALLTHROUGH */
2111         case OP_REPEAT:
2112             if (o->op_flags & OPf_STACKED)
2113                 break;
2114             if (o->op_type == OP_REPEAT)
2115                 scalar(cBINOPo->op_first);
2116             goto func_ops;
2117         case OP_CONCAT:
2118             if ((o->op_flags & OPf_STACKED) &&
2119                     !(o->op_private & OPpCONCAT_NESTED))
2120                 break;
2121             goto func_ops;
2122         case OP_SUBSTR:
2123             if (o->op_private == 4)
2124                 break;
2125             /* FALLTHROUGH */
2126         case OP_WANTARRAY:
2127         case OP_GV:
2128         case OP_SMARTMATCH:
2129         case OP_AV2ARYLEN:
2130         case OP_REF:
2131         case OP_REFGEN:
2132         case OP_SREFGEN:
2133         case OP_DEFINED:
2134         case OP_HEX:
2135         case OP_OCT:
2136         case OP_LENGTH:
2137         case OP_VEC:
2138         case OP_INDEX:
2139         case OP_RINDEX:
2140         case OP_SPRINTF:
2141         case OP_KVASLICE:
2142         case OP_KVHSLICE:
2143         case OP_UNPACK:
2144         case OP_PACK:
2145         case OP_JOIN:
2146         case OP_LSLICE:
2147         case OP_ANONLIST:
2148         case OP_ANONHASH:
2149         case OP_SORT:
2150         case OP_REVERSE:
2151         case OP_RANGE:
2152         case OP_FLIP:
2153         case OP_FLOP:
2154         case OP_CALLER:
2155         case OP_FILENO:
2156         case OP_EOF:
2157         case OP_TELL:
2158         case OP_GETSOCKNAME:
2159         case OP_GETPEERNAME:
2160         case OP_READLINK:
2161         case OP_TELLDIR:
2162         case OP_GETPPID:
2163         case OP_GETPGRP:
2164         case OP_GETPRIORITY:
2165         case OP_TIME:
2166         case OP_TMS:
2167         case OP_LOCALTIME:
2168         case OP_GMTIME:
2169         case OP_GHBYNAME:
2170         case OP_GHBYADDR:
2171         case OP_GHOSTENT:
2172         case OP_GNBYNAME:
2173         case OP_GNBYADDR:
2174         case OP_GNETENT:
2175         case OP_GPBYNAME:
2176         case OP_GPBYNUMBER:
2177         case OP_GPROTOENT:
2178         case OP_GSBYNAME:
2179         case OP_GSBYPORT:
2180         case OP_GSERVENT:
2181         case OP_GPWNAM:
2182         case OP_GPWUID:
2183         case OP_GGRNAM:
2184         case OP_GGRGID:
2185         case OP_GETLOGIN:
2186         case OP_PROTOTYPE:
2187         case OP_RUNCV:
2188         func_ops:
2189             useless = OP_DESC(o);
2190             break;
2191
2192         case OP_GVSV:
2193         case OP_PADSV:
2194         case OP_PADAV:
2195         case OP_PADHV:
2196         case OP_PADANY:
2197         case OP_AELEM:
2198         case OP_AELEMFAST:
2199         case OP_AELEMFAST_LEX:
2200         case OP_ASLICE:
2201         case OP_HELEM:
2202         case OP_HSLICE:
2203             if (!(o->op_private & (OPpLVAL_INTRO|OPpOUR_INTRO)))
2204                 /* Otherwise it's "Useless use of grep iterator" */
2205                 useless = OP_DESC(o);
2206             break;
2207
2208         case OP_SPLIT:
2209             if (!(o->op_private & OPpSPLIT_ASSIGN))
2210                 useless = OP_DESC(o);
2211             break;
2212
2213         case OP_NOT:
2214             kid = cUNOPo->op_first;
2215             if (kid->op_type != OP_MATCH && kid->op_type != OP_SUBST &&
2216                 kid->op_type != OP_TRANS && kid->op_type != OP_TRANSR) {
2217                 goto func_ops;
2218             }
2219             useless = "negative pattern binding (!~)";
2220             break;
2221
2222         case OP_SUBST:
2223             if (cPMOPo->op_pmflags & PMf_NONDESTRUCT)
2224                 useless = "non-destructive substitution (s///r)";
2225             break;
2226
2227         case OP_TRANSR:
2228             useless = "non-destructive transliteration (tr///r)";
2229             break;
2230
2231         case OP_RV2GV:
2232         case OP_RV2SV:
2233         case OP_RV2AV:
2234         case OP_RV2HV:
2235             if (!(o->op_private & (OPpLVAL_INTRO|OPpOUR_INTRO)) &&
2236                 (!OpHAS_SIBLING(o) || OpSIBLING(o)->op_type != OP_READLINE))
2237                 useless = "a variable";
2238             break;
2239
2240         case OP_CONST:
2241             sv = cSVOPo_sv;
2242             if (cSVOPo->op_private & OPpCONST_STRICT)
2243                 no_bareword_allowed(o);
2244             else {
2245                 if (ckWARN(WARN_VOID)) {
2246                     NV nv;
2247                     /* don't warn on optimised away booleans, eg
2248                      * use constant Foo, 5; Foo || print; */
2249                     if (cSVOPo->op_private & OPpCONST_SHORTCIRCUIT)
2250                         useless = NULL;
2251                     /* the constants 0 and 1 are permitted as they are
2252                        conventionally used as dummies in constructs like
2253                        1 while some_condition_with_side_effects;  */
2254                     else if (SvNIOK(sv) && ((nv = SvNV(sv)) == 0.0 || nv == 1.0))
2255                         useless = NULL;
2256                     else if (SvPOK(sv)) {
2257                         SV * const dsv = newSVpvs("");
2258                         useless_sv
2259                             = Perl_newSVpvf(aTHX_
2260                                             "a constant (%s)",
2261                                             pv_pretty(dsv, SvPVX_const(sv),
2262                                                       SvCUR(sv), 32, NULL, NULL,
2263                                                       PERL_PV_PRETTY_DUMP
2264                                                       | PERL_PV_ESCAPE_NOCLEAR
2265                                                       | PERL_PV_ESCAPE_UNI_DETECT));
2266                         SvREFCNT_dec_NN(dsv);
2267                     }
2268                     else if (SvOK(sv)) {
2269                         useless_sv = Perl_newSVpvf(aTHX_ "a constant (%" SVf ")", SVfARG(sv));
2270                     }
2271                     else
2272                         useless = "a constant (undef)";
2273                 }
2274             }
2275             op_null(o);         /* don't execute or even remember it */
2276             break;
2277
2278         case OP_POSTINC:
2279             OpTYPE_set(o, OP_PREINC);  /* pre-increment is faster */
2280             break;
2281
2282         case OP_POSTDEC:
2283             OpTYPE_set(o, OP_PREDEC);  /* pre-decrement is faster */
2284             break;
2285
2286         case OP_I_POSTINC:
2287             OpTYPE_set(o, OP_I_PREINC);        /* pre-increment is faster */
2288             break;
2289
2290         case OP_I_POSTDEC:
2291             OpTYPE_set(o, OP_I_PREDEC);        /* pre-decrement is faster */
2292             break;
2293
2294         case OP_SASSIGN: {
2295             OP *rv2gv;
2296             UNOP *refgen, *rv2cv;
2297             LISTOP *exlist;
2298
2299             if ((o->op_private & ~OPpASSIGN_BACKWARDS) != 2)
2300                 break;
2301
2302             rv2gv = ((BINOP *)o)->op_last;
2303             if (!rv2gv || rv2gv->op_type != OP_RV2GV)
2304                 break;
2305
2306             refgen = (UNOP *)((BINOP *)o)->op_first;
2307
2308             if (!refgen || (refgen->op_type != OP_REFGEN
2309                             && refgen->op_type != OP_SREFGEN))
2310                 break;
2311
2312             exlist = (LISTOP *)refgen->op_first;
2313             if (!exlist || exlist->op_type != OP_NULL
2314                 || exlist->op_targ != OP_LIST)
2315                 break;
2316
2317             if (exlist->op_first->op_type != OP_PUSHMARK
2318                 && exlist->op_first != exlist->op_last)
2319                 break;
2320
2321             rv2cv = (UNOP*)exlist->op_last;
2322
2323             if (rv2cv->op_type != OP_RV2CV)
2324                 break;
2325
2326             assert ((rv2gv->op_private & OPpDONT_INIT_GV) == 0);
2327             assert ((o->op_private & OPpASSIGN_CV_TO_GV) == 0);
2328             assert ((rv2cv->op_private & OPpMAY_RETURN_CONSTANT) == 0);
2329
2330             o->op_private |= OPpASSIGN_CV_TO_GV;
2331             rv2gv->op_private |= OPpDONT_INIT_GV;
2332             rv2cv->op_private |= OPpMAY_RETURN_CONSTANT;
2333
2334             break;
2335         }
2336
2337         case OP_AASSIGN: {
2338             inplace_aassign(o);
2339             break;
2340         }
2341
2342         case OP_OR:
2343         case OP_AND:
2344             kid = cLOGOPo->op_first;
2345             if (kid->op_type == OP_NOT
2346                 && (kid->op_flags & OPf_KIDS)) {
2347                 if (o->op_type == OP_AND) {
2348                     OpTYPE_set(o, OP_OR);
2349                 } else {
2350                     OpTYPE_set(o, OP_AND);
2351                 }
2352                 op_null(kid);
2353             }
2354             /* FALLTHROUGH */
2355
2356         case OP_DOR:
2357         case OP_COND_EXPR:
2358         case OP_ENTERGIVEN:
2359         case OP_ENTERWHEN:
2360             next_kid = OpSIBLING(cUNOPo->op_first);
2361         break;
2362
2363         case OP_NULL:
2364             if (o->op_flags & OPf_STACKED)
2365                 break;
2366             /* FALLTHROUGH */
2367         case OP_NEXTSTATE:
2368         case OP_DBSTATE:
2369         case OP_ENTERTRY:
2370         case OP_ENTER:
2371             if (!(o->op_flags & OPf_KIDS))
2372                 break;
2373             /* FALLTHROUGH */
2374         case OP_SCOPE:
2375         case OP_LEAVE:
2376         case OP_LEAVETRY:
2377         case OP_LEAVELOOP:
2378         case OP_LINESEQ:
2379         case OP_LEAVEGIVEN:
2380         case OP_LEAVEWHEN:
2381         kids:
2382             next_kid = cLISTOPo->op_first;
2383             break;
2384         case OP_LIST:
2385             /* If the first kid after pushmark is something that the padrange
2386                optimisation would reject, then null the list and the pushmark.
2387             */
2388             if ((kid = cLISTOPo->op_first)->op_type == OP_PUSHMARK
2389                 && (  !(kid = OpSIBLING(kid))
2390                       || (  kid->op_type != OP_PADSV
2391                             && kid->op_type != OP_PADAV
2392                             && kid->op_type != OP_PADHV)
2393                       || kid->op_private & ~OPpLVAL_INTRO
2394                       || !(kid = OpSIBLING(kid))
2395                       || (  kid->op_type != OP_PADSV
2396                             && kid->op_type != OP_PADAV
2397                             && kid->op_type != OP_PADHV)
2398                       || kid->op_private & ~OPpLVAL_INTRO)
2399             ) {
2400                 op_null(cUNOPo->op_first); /* NULL the pushmark */
2401                 op_null(o); /* NULL the list */
2402             }
2403             goto kids;
2404         case OP_ENTEREVAL:
2405             scalarkids(o);
2406             break;
2407         case OP_SCALAR:
2408             scalar(o);
2409             break;
2410         }
2411
2412         if (useless_sv) {
2413             /* mortalise it, in case warnings are fatal.  */
2414             Perl_ck_warner(aTHX_ packWARN(WARN_VOID),
2415                            "Useless use of %" SVf " in void context",
2416                            SVfARG(sv_2mortal(useless_sv)));
2417         }
2418         else if (useless) {
2419             Perl_ck_warner(aTHX_ packWARN(WARN_VOID),
2420                            "Useless use of %s in void context",
2421                            useless);
2422         }
2423
2424       get_next_op:
2425         /* if a kid hasn't been nominated to process, continue with the
2426          * next sibling, or if no siblings left, go back to the parent's
2427          * siblings and so on
2428          */
2429         while (!next_kid) {
2430             if (o == arg)
2431                 return arg; /* at top; no parents/siblings to try */
2432             if (OpHAS_SIBLING(o))
2433                 next_kid = o->op_sibparent;
2434             else
2435                 o = o->op_sibparent; /*try parent's next sibling */
2436         }
2437         o = next_kid;
2438     }
2439
2440     return arg;
2441 }
2442
2443
2444 static OP *
2445 S_listkids(pTHX_ OP *o)
2446 {
2447     if (o && o->op_flags & OPf_KIDS) {
2448         OP *kid;
2449         for (kid = cLISTOPo->op_first; kid; kid = OpSIBLING(kid))
2450             list(kid);
2451     }
2452     return o;
2453 }
2454
2455
2456 /* apply list context to the o subtree */
2457
2458 OP *
2459 Perl_list(pTHX_ OP *o)
2460 {
2461     OP * top_op = o;
2462
2463     while (1) {
2464         OP *next_kid = NULL; /* what op (if any) to process next */
2465
2466         OP *kid;
2467
2468         /* assumes no premature commitment */
2469         if (!o || (o->op_flags & OPf_WANT)
2470              || (PL_parser && PL_parser->error_count)
2471              || o->op_type == OP_RETURN)
2472         {
2473             goto do_next;
2474         }
2475
2476         if ((o->op_private & OPpTARGET_MY)
2477             && (PL_opargs[o->op_type] & OA_TARGLEX))/* OPp share the meaning */
2478         {
2479             goto do_next;                               /* As if inside SASSIGN */
2480         }
2481
2482         o->op_flags = (o->op_flags & ~OPf_WANT) | OPf_WANT_LIST;
2483
2484         switch (o->op_type) {
2485         case OP_REPEAT:
2486             if (o->op_private & OPpREPEAT_DOLIST
2487              && !(o->op_flags & OPf_STACKED))
2488             {
2489                 list(cBINOPo->op_first);
2490                 kid = cBINOPo->op_last;
2491                 /* optimise away (.....) x 1 */
2492                 if (kid->op_type == OP_CONST && SvIOK(kSVOP_sv)
2493                  && SvIVX(kSVOP_sv) == 1)
2494                 {
2495                     op_null(o); /* repeat */
2496                     op_null(cUNOPx(cBINOPo->op_first)->op_first);/* pushmark */
2497                     /* const (rhs): */
2498                     op_free(op_sibling_splice(o, cBINOPo->op_first, 1, NULL));
2499                 }
2500             }
2501             break;
2502
2503         case OP_OR:
2504         case OP_AND:
2505         case OP_COND_EXPR:
2506             /* impose list context on everything except the condition */
2507             next_kid = OpSIBLING(cUNOPo->op_first);
2508             break;
2509
2510         default:
2511             if (!(o->op_flags & OPf_KIDS))
2512                 break;
2513             /* possibly flatten 1..10 into a constant array */
2514             if (!o->op_next && cUNOPo->op_first->op_type == OP_FLOP) {
2515                 list(cBINOPo->op_first);
2516                 gen_constant_list(o);
2517                 goto do_next;
2518             }
2519             next_kid = cUNOPo->op_first; /* do all kids */
2520             break;
2521
2522         case OP_LIST:
2523             if (cLISTOPo->op_first->op_type == OP_PUSHMARK) {
2524                 op_null(cUNOPo->op_first); /* NULL the pushmark */
2525                 op_null(o); /* NULL the list */
2526             }
2527             if (o->op_flags & OPf_KIDS)
2528                 next_kid = cUNOPo->op_first; /* do all kids */
2529             break;
2530
2531         /* the children of these ops are usually a list of statements,
2532          * except the leaves, whose first child is a corresponding enter
2533          */
2534         case OP_SCOPE:
2535         case OP_LINESEQ:
2536             kid = cLISTOPo->op_first;
2537             goto do_kids;
2538         case OP_LEAVE:
2539         case OP_LEAVETRY:
2540             kid = cLISTOPo->op_first;
2541             list(kid);
2542             kid = OpSIBLING(kid);
2543         do_kids:
2544             while (kid) {
2545                 OP *sib = OpSIBLING(kid);
2546                 /* Apply void context to all kids except the last, which
2547                  * is list. E.g.
2548                  *      @a = do { void; void; list }
2549                  * Except that 'when's are always list context, e.g.
2550                  *      @a = do { given(..) {
2551                     *                 when (..) { list }
2552                     *                 when (..) { list }
2553                     *                 ...
2554                     *                }}
2555                     */
2556                 if (!sib) {
2557                     /* tail call optimise calling list() on the last kid */
2558                     next_kid = kid;
2559                     goto do_next;
2560                 }
2561                 else if (kid->op_type == OP_LEAVEWHEN)
2562                     list(kid);
2563                 else
2564                     scalarvoid(kid);
2565                 kid = sib;
2566             }
2567             NOT_REACHED; /* NOTREACHED */
2568             break;
2569
2570         }
2571
2572         /* If next_kid is set, someone in the code above wanted us to process
2573          * that kid and all its remaining siblings.  Otherwise, work our way
2574          * back up the tree */
2575       do_next:
2576         while (!next_kid) {
2577             if (o == top_op)
2578                 return top_op; /* at top; no parents/siblings to try */
2579             if (OpHAS_SIBLING(o))
2580                 next_kid = o->op_sibparent;
2581             else {
2582                 o = o->op_sibparent; /*try parent's next sibling */
2583                 switch (o->op_type) {
2584                 case OP_SCOPE:
2585                 case OP_LINESEQ:
2586                 case OP_LIST:
2587                 case OP_LEAVE:
2588                 case OP_LEAVETRY:
2589                     /* should really restore PL_curcop to its old value, but
2590                      * setting it to PL_compiling is better than do nothing */
2591                     PL_curcop = &PL_compiling;
2592                 }
2593             }
2594
2595
2596         }
2597         o = next_kid;
2598     } /* while */
2599 }
2600
2601
2602 static OP *
2603 S_scalarseq(pTHX_ OP *o)
2604 {
2605     if (o) {
2606         const OPCODE type = o->op_type;
2607
2608         if (type == OP_LINESEQ || type == OP_SCOPE ||
2609             type == OP_LEAVE || type == OP_LEAVETRY)
2610         {
2611             OP *kid, *sib;
2612             for (kid = cLISTOPo->op_first; kid; kid = sib) {
2613                 if ((sib = OpSIBLING(kid))
2614                  && (  OpHAS_SIBLING(sib) || sib->op_type != OP_NULL
2615                     || (  sib->op_targ != OP_NEXTSTATE
2616                        && sib->op_targ != OP_DBSTATE  )))
2617                 {
2618                     scalarvoid(kid);
2619                 }
2620             }
2621             PL_curcop = &PL_compiling;
2622         }
2623         o->op_flags &= ~OPf_PARENS;
2624         if (PL_hints & HINT_BLOCK_SCOPE)
2625             o->op_flags |= OPf_PARENS;
2626     }
2627     else
2628         o = newOP(OP_STUB, 0);
2629     return o;
2630 }
2631
2632 STATIC OP *
2633 S_modkids(pTHX_ OP *o, I32 type)
2634 {
2635     if (o && o->op_flags & OPf_KIDS) {
2636         OP *kid;
2637         for (kid = cLISTOPo->op_first; kid; kid = OpSIBLING(kid))
2638             op_lvalue(kid, type);
2639     }
2640     return o;
2641 }
2642
2643
2644 /* for a helem/hslice/kvslice, if its a fixed hash, croak on invalid
2645  * const fields. Also, convert CONST keys to HEK-in-SVs.
2646  * rop    is the op that retrieves the hash;
2647  * key_op is the first key
2648  * real   if false, only check (and possibly croak); don't update op
2649  */
2650
2651 STATIC void
2652 S_check_hash_fields_and_hekify(pTHX_ UNOP *rop, SVOP *key_op, int real)
2653 {
2654     PADNAME *lexname;
2655     GV **fields;
2656     bool check_fields;
2657
2658     /* find the padsv corresponding to $lex->{} or @{$lex}{} */
2659     if (rop) {
2660         if (rop->op_first->op_type == OP_PADSV)
2661             /* @$hash{qw(keys here)} */
2662             rop = (UNOP*)rop->op_first;
2663         else {
2664             /* @{$hash}{qw(keys here)} */
2665             if (rop->op_first->op_type == OP_SCOPE
2666                 && cLISTOPx(rop->op_first)->op_last->op_type == OP_PADSV)
2667                 {
2668                     rop = (UNOP*)cLISTOPx(rop->op_first)->op_last;
2669                 }
2670             else
2671                 rop = NULL;
2672         }
2673     }
2674
2675     lexname = NULL; /* just to silence compiler warnings */
2676     fields  = NULL; /* just to silence compiler warnings */
2677
2678     check_fields =
2679             rop
2680          && (lexname = padnamelist_fetch(PL_comppad_name, rop->op_targ),
2681              SvPAD_TYPED(lexname))
2682          && (fields = (GV**)hv_fetchs(PadnameTYPE(lexname), "FIELDS", FALSE))
2683          && isGV(*fields) && GvHV(*fields);
2684
2685     for (; key_op; key_op = (SVOP*)OpSIBLING(key_op)) {
2686         SV **svp, *sv;
2687         if (key_op->op_type != OP_CONST)
2688             continue;
2689         svp = cSVOPx_svp(key_op);
2690
2691         /* make sure it's not a bareword under strict subs */
2692         if (key_op->op_private & OPpCONST_BARE &&
2693             key_op->op_private & OPpCONST_STRICT)
2694         {
2695             no_bareword_allowed((OP*)key_op);
2696         }
2697
2698         /* Make the CONST have a shared SV */
2699         if (   !SvIsCOW_shared_hash(sv = *svp)
2700             && SvTYPE(sv) < SVt_PVMG
2701             && SvOK(sv)
2702             && !SvROK(sv)
2703             && real)
2704         {
2705             SSize_t keylen;
2706             const char * const key = SvPV_const(sv, *(STRLEN*)&keylen);
2707             SV *nsv = newSVpvn_share(key, SvUTF8(sv) ? -keylen : keylen, 0);
2708             SvREFCNT_dec_NN(sv);
2709             *svp = nsv;
2710         }
2711
2712         if (   check_fields
2713             && !hv_fetch_ent(GvHV(*fields), *svp, FALSE, 0))
2714         {
2715             Perl_croak(aTHX_ "No such class field \"%" SVf "\" "
2716                         "in variable %" PNf " of type %" HEKf,
2717                         SVfARG(*svp), PNfARG(lexname),
2718                         HEKfARG(HvNAME_HEK(PadnameTYPE(lexname))));
2719         }
2720     }
2721 }
2722
2723 /* info returned by S_sprintf_is_multiconcatable() */
2724
2725 struct sprintf_ismc_info {
2726     SSize_t nargs;    /* num of args to sprintf (not including the format) */
2727     char  *start;     /* start of raw format string */
2728     char  *end;       /* bytes after end of raw format string */
2729     STRLEN total_len; /* total length (in bytes) of format string, not
2730                          including '%s' and  half of '%%' */
2731     STRLEN variant;   /* number of bytes by which total_len_p would grow
2732                          if upgraded to utf8 */
2733     bool   utf8;      /* whether the format is utf8 */
2734 };
2735
2736
2737 /* is the OP_SPRINTF o suitable for converting into a multiconcat op?
2738  * i.e. its format argument is a const string with only '%s' and '%%'
2739  * formats, and the number of args is known, e.g.
2740  *    sprintf "a=%s f=%s", $a[0], scalar(f());
2741  * but not
2742  *    sprintf "i=%d a=%s f=%s", $i, @a, f();
2743  *
2744  * If successful, the sprintf_ismc_info struct pointed to by info will be
2745  * populated.
2746  */
2747
2748 STATIC bool
2749 S_sprintf_is_multiconcatable(pTHX_ OP *o,struct sprintf_ismc_info *info)
2750 {
2751     OP    *pm, *constop, *kid;
2752     SV    *sv;
2753     char  *s, *e, *p;
2754     SSize_t nargs, nformats;
2755     STRLEN cur, total_len, variant;
2756     bool   utf8;
2757
2758     /* if sprintf's behaviour changes, die here so that someone
2759      * can decide whether to enhance this function or skip optimising
2760      * under those new circumstances */
2761     assert(!(o->op_flags & OPf_STACKED));
2762     assert(!(PL_opargs[OP_SPRINTF] & OA_TARGLEX));
2763     assert(!(o->op_private & ~OPpARG4_MASK));
2764
2765     pm = cUNOPo->op_first;
2766     if (pm->op_type != OP_PUSHMARK) /* weird coreargs stuff */
2767         return FALSE;
2768     constop = OpSIBLING(pm);
2769     if (!constop || constop->op_type != OP_CONST)
2770         return FALSE;
2771     sv = cSVOPx_sv(constop);
2772     if (SvMAGICAL(sv) || !SvPOK(sv))
2773         return FALSE;
2774
2775     s = SvPV(sv, cur);
2776     e = s + cur;
2777
2778     /* Scan format for %% and %s and work out how many %s there are.
2779      * Abandon if other format types are found.
2780      */
2781
2782     nformats  = 0;
2783     total_len = 0;
2784     variant   = 0;
2785
2786     for (p = s; p < e; p++) {
2787         if (*p != '%') {
2788             total_len++;
2789             if (!UTF8_IS_INVARIANT(*p))
2790                 variant++;
2791             continue;
2792         }
2793         p++;
2794         if (p >= e)
2795             return FALSE; /* lone % at end gives "Invalid conversion" */
2796         if (*p == '%')
2797             total_len++;
2798         else if (*p == 's')
2799             nformats++;
2800         else
2801             return FALSE;
2802     }
2803
2804     if (!nformats || nformats > PERL_MULTICONCAT_MAXARG)
2805         return FALSE;
2806
2807     utf8 = cBOOL(SvUTF8(sv));
2808     if (utf8)
2809         variant = 0;
2810
2811     /* scan args; they must all be in scalar cxt */
2812
2813     nargs = 0;
2814     kid = OpSIBLING(constop);
2815
2816     while (kid) {
2817         if ((kid->op_flags & OPf_WANT) != OPf_WANT_SCALAR)
2818             return FALSE;
2819         nargs++;
2820         kid = OpSIBLING(kid);
2821     }
2822
2823     if (nargs != nformats)
2824         return FALSE; /* e.g. sprintf("%s%s", $a); */
2825
2826
2827     info->nargs      = nargs;
2828     info->start      = s;
2829     info->end        = e;
2830     info->total_len  = total_len;
2831     info->variant    = variant;
2832     info->utf8       = utf8;
2833
2834     return TRUE;
2835 }
2836
2837
2838
2839 /* S_maybe_multiconcat():
2840  *
2841  * given an OP_STRINGIFY, OP_SASSIGN, OP_CONCAT or OP_SPRINTF op, possibly
2842  * convert it (and its children) into an OP_MULTICONCAT. See the code
2843  * comments just before pp_multiconcat() for the full details of what
2844  * OP_MULTICONCAT supports.
2845  *
2846  * Basically we're looking for an optree with a chain of OP_CONCATS down
2847  * the LHS (or an OP_SPRINTF), with possibly an OP_SASSIGN, and/or
2848  * OP_STRINGIFY, and/or OP_CONCAT acting as '.=' at its head, e.g.
2849  *
2850  *      $x = "$a$b-$c"
2851  *
2852  *  looks like
2853  *
2854  *      SASSIGN
2855  *         |
2856  *      STRINGIFY   -- PADSV[$x]
2857  *         |
2858  *         |
2859  *      ex-PUSHMARK -- CONCAT/S
2860  *                        |
2861  *                     CONCAT/S  -- PADSV[$d]
2862  *                        |
2863  *                     CONCAT    -- CONST["-"]
2864  *                        |
2865  *                     PADSV[$a] -- PADSV[$b]
2866  *
2867  * Note that at this stage the OP_SASSIGN may have already been optimised
2868  * away with OPpTARGET_MY set on the OP_STRINGIFY or OP_CONCAT.
2869  */
2870
2871 STATIC void
2872 S_maybe_multiconcat(pTHX_ OP *o)
2873 {
2874     OP *lastkidop;   /* the right-most of any kids unshifted onto o */
2875     OP *topop;       /* the top-most op in the concat tree (often equals o,
2876                         unless there are assign/stringify ops above it */
2877     OP *parentop;    /* the parent op of topop (or itself if no parent) */
2878     OP *targmyop;    /* the op (if any) with the OPpTARGET_MY flag */
2879     OP *targetop;    /* the op corresponding to target=... or target.=... */
2880     OP *stringop;    /* the OP_STRINGIFY op, if any */
2881     OP *nextop;      /* used for recreating the op_next chain without consts */
2882     OP *kid;         /* general-purpose op pointer */
2883     UNOP_AUX_item *aux;
2884     UNOP_AUX_item *lenp;
2885     char *const_str, *p;
2886     struct sprintf_ismc_info sprintf_info;
2887
2888                      /* store info about each arg in args[];
2889                       * toparg is the highest used slot; argp is a general
2890                       * pointer to args[] slots */
2891     struct {
2892         void *p;      /* initially points to const sv (or null for op);
2893                          later, set to SvPV(constsv), with ... */
2894         STRLEN len;   /* ... len set to SvPV(..., len) */
2895     } *argp, *toparg, args[PERL_MULTICONCAT_MAXARG*2 + 1];
2896
2897     SSize_t nargs  = 0;
2898     SSize_t nconst = 0;
2899     SSize_t nadjconst  = 0; /* adjacent consts - may be demoted to args */
2900     STRLEN variant;
2901     bool utf8 = FALSE;
2902     bool kid_is_last = FALSE; /* most args will be the RHS kid of a concat op;
2903                                  the last-processed arg will the LHS of one,
2904                                  as args are processed in reverse order */
2905     U8   stacked_last = 0;   /* whether the last seen concat op was STACKED */
2906     STRLEN total_len  = 0;   /* sum of the lengths of the const segments */
2907     U8 flags          = 0;   /* what will become the op_flags and ... */
2908     U8 private_flags  = 0;   /* ... op_private of the multiconcat op */
2909     bool is_sprintf = FALSE; /* we're optimising an sprintf */
2910     bool is_targable  = FALSE; /* targetop is an OPpTARGET_MY candidate */
2911     bool prev_was_const = FALSE; /* previous arg was a const */
2912
2913     /* -----------------------------------------------------------------
2914      * Phase 1:
2915      *
2916      * Examine the optree non-destructively to determine whether it's
2917      * suitable to be converted into an OP_MULTICONCAT. Accumulate
2918      * information about the optree in args[].
2919      */
2920
2921     argp     = args;
2922     targmyop = NULL;
2923     targetop = NULL;
2924     stringop = NULL;
2925     topop    = o;
2926     parentop = o;
2927
2928     assert(   o->op_type == OP_SASSIGN
2929            || o->op_type == OP_CONCAT
2930            || o->op_type == OP_SPRINTF
2931            || o->op_type == OP_STRINGIFY);
2932
2933     Zero(&sprintf_info, 1, struct sprintf_ismc_info);
2934
2935     /* first see if, at the top of the tree, there is an assign,
2936      * append and/or stringify */
2937
2938     if (topop->op_type == OP_SASSIGN) {
2939         /* expr = ..... */
2940         if (o->op_ppaddr != PL_ppaddr[OP_SASSIGN])
2941             return;
2942         if (o->op_private & (OPpASSIGN_BACKWARDS|OPpASSIGN_CV_TO_GV))
2943             return;
2944         assert(!(o->op_private & ~OPpARG2_MASK)); /* barf on unknown flags */
2945
2946         parentop = topop;
2947         topop = cBINOPo->op_first;
2948         targetop = OpSIBLING(topop);
2949         if (!targetop) /* probably some sort of syntax error */
2950             return;
2951
2952         /* don't optimise away assign in 'local $foo = ....' */
2953         if (   (targetop->op_private & OPpLVAL_INTRO)
2954             /* these are the common ops which do 'local', but
2955              * not all */
2956             && (   targetop->op_type == OP_GVSV
2957                 || targetop->op_type == OP_RV2SV
2958                 || targetop->op_type == OP_AELEM
2959                 || targetop->op_type == OP_HELEM
2960                 )
2961         )
2962             return;
2963     }
2964     else if (   topop->op_type == OP_CONCAT
2965              && (topop->op_flags & OPf_STACKED)
2966              && (!(topop->op_private & OPpCONCAT_NESTED))
2967             )
2968     {
2969         /* expr .= ..... */
2970
2971         /* OPpTARGET_MY shouldn't be able to be set here. If it is,
2972          * decide what to do about it */
2973         assert(!(o->op_private & OPpTARGET_MY));
2974
2975         /* barf on unknown flags */
2976         assert(!(o->op_private & ~(OPpARG2_MASK|OPpTARGET_MY)));
2977         private_flags |= OPpMULTICONCAT_APPEND;
2978         targetop = cBINOPo->op_first;
2979         parentop = topop;
2980         topop    = OpSIBLING(targetop);
2981
2982         /* $x .= <FOO> gets optimised to rcatline instead */
2983         if (topop->op_type == OP_READLINE)
2984             return;
2985     }
2986
2987     if (targetop) {
2988         /* Can targetop (the LHS) if it's a padsv, be optimised
2989          * away and use OPpTARGET_MY instead?
2990          */
2991         if (    (targetop->op_type == OP_PADSV)
2992             && !(targetop->op_private & OPpDEREF)
2993             && !(targetop->op_private & OPpPAD_STATE)
2994                /* we don't support 'my $x .= ...' */
2995             && (   o->op_type == OP_SASSIGN
2996                 || !(targetop->op_private & OPpLVAL_INTRO))
2997         )
2998             is_targable = TRUE;
2999     }
3000
3001     if (topop->op_type == OP_STRINGIFY) {
3002         if (topop->op_ppaddr != PL_ppaddr[OP_STRINGIFY])
3003             return;
3004         stringop = topop;
3005
3006         /* barf on unknown flags */
3007         assert(!(o->op_private & ~(OPpARG4_MASK|OPpTARGET_MY)));
3008
3009         if ((topop->op_private & OPpTARGET_MY)) {
3010             if (o->op_type == OP_SASSIGN)
3011                 return; /* can't have two assigns */
3012             targmyop = topop;
3013         }
3014
3015         private_flags |= OPpMULTICONCAT_STRINGIFY;
3016         parentop = topop;
3017         topop = cBINOPx(topop)->op_first;
3018         assert(OP_TYPE_IS_OR_WAS_NN(topop, OP_PUSHMARK));
3019         topop = OpSIBLING(topop);
3020     }
3021
3022     if (topop->op_type == OP_SPRINTF) {
3023         if (topop->op_ppaddr != PL_ppaddr[OP_SPRINTF])
3024             return;
3025         if (S_sprintf_is_multiconcatable(aTHX_ topop, &sprintf_info)) {
3026             nargs     = sprintf_info.nargs;
3027             total_len = sprintf_info.total_len;
3028             variant   = sprintf_info.variant;
3029             utf8      = sprintf_info.utf8;
3030             is_sprintf = TRUE;
3031             private_flags |= OPpMULTICONCAT_FAKE;
3032             toparg = argp;
3033             /* we have an sprintf op rather than a concat optree.
3034              * Skip most of the code below which is associated with
3035              * processing that optree. We also skip phase 2, determining
3036              * whether its cost effective to optimise, since for sprintf,
3037              * multiconcat is *always* faster */
3038             goto create_aux;
3039         }
3040         /* note that even if the sprintf itself isn't multiconcatable,
3041          * the expression as a whole may be, e.g. in
3042          *    $x .= sprintf("%d",...)
3043          * the sprintf op will be left as-is, but the concat/S op may
3044          * be upgraded to multiconcat
3045          */
3046     }
3047     else if (topop->op_type == OP_CONCAT) {
3048         if (topop->op_ppaddr != PL_ppaddr[OP_CONCAT])
3049             return;
3050
3051         if ((topop->op_private & OPpTARGET_MY)) {
3052             if (o->op_type == OP_SASSIGN || targmyop)
3053                 return; /* can't have two assigns */
3054             targmyop = topop;
3055         }
3056     }
3057
3058     /* Is it safe to convert a sassign/stringify/concat op into
3059      * a multiconcat? */
3060     assert((PL_opargs[OP_SASSIGN]   & OA_CLASS_MASK) == OA_BINOP);
3061     assert((PL_opargs[OP_CONCAT]    & OA_CLASS_MASK) == OA_BINOP);
3062     assert((PL_opargs[OP_STRINGIFY] & OA_CLASS_MASK) == OA_LISTOP);
3063     assert((PL_opargs[OP_SPRINTF]   & OA_CLASS_MASK) == OA_LISTOP);
3064     STATIC_ASSERT_STMT(   STRUCT_OFFSET(BINOP,    op_last)
3065                        == STRUCT_OFFSET(UNOP_AUX, op_aux));
3066     STATIC_ASSERT_STMT(   STRUCT_OFFSET(LISTOP,   op_last)
3067                        == STRUCT_OFFSET(UNOP_AUX, op_aux));
3068
3069     /* Now scan the down the tree looking for a series of
3070      * CONCAT/OPf_STACKED ops on the LHS (with the last one not
3071      * stacked). For example this tree:
3072      *
3073      *     |
3074      *   CONCAT/STACKED
3075      *     |
3076      *   CONCAT/STACKED -- EXPR5
3077      *     |
3078      *   CONCAT/STACKED -- EXPR4
3079      *     |
3080      *   CONCAT -- EXPR3
3081      *     |
3082      *   EXPR1  -- EXPR2
3083      *
3084      * corresponds to an expression like
3085      *
3086      *   (EXPR1 . EXPR2 . EXPR3 . EXPR4 . EXPR5)
3087      *
3088      * Record info about each EXPR in args[]: in particular, whether it is
3089      * a stringifiable OP_CONST and if so what the const sv is.
3090      *
3091      * The reason why the last concat can't be STACKED is the difference
3092      * between
3093      *
3094      *    ((($a .= $a) .= $a) .= $a) .= $a
3095      *
3096      * and
3097      *    $a . $a . $a . $a . $a
3098      *
3099      * The main difference between the optrees for those two constructs
3100      * is the presence of the last STACKED. As well as modifying $a,
3101      * the former sees the changed $a between each concat, so if $s is
3102      * initially 'a', the first returns 'a' x 16, while the latter returns
3103      * 'a' x 5. And pp_multiconcat can't handle that kind of thing.
3104      */
3105
3106     kid = topop;
3107
3108     for (;;) {
3109         OP *argop;
3110         SV *sv;
3111         bool last = FALSE;
3112
3113         if (    kid->op_type == OP_CONCAT
3114             && !kid_is_last
3115         ) {
3116             OP *k1, *k2;
3117             k1 = cUNOPx(kid)->op_first;
3118             k2 = OpSIBLING(k1);
3119             /* shouldn't happen except maybe after compile err? */
3120             if (!k2)
3121                 return;
3122
3123             /* avoid turning (A . B . ($lex = C) ...)  into  (A . B . C ...) */
3124             if (kid->op_private & OPpTARGET_MY)
3125                 kid_is_last = TRUE;
3126
3127             stacked_last = (kid->op_flags & OPf_STACKED);
3128             if (!stacked_last)
3129                 kid_is_last = TRUE;
3130
3131             kid   = k1;
3132             argop = k2;
3133         }
3134         else {
3135             argop = kid;
3136             last = TRUE;
3137         }
3138
3139         if (   nargs + nadjconst  >  PERL_MULTICONCAT_MAXARG        - 2
3140             || (argp - args + 1)  > (PERL_MULTICONCAT_MAXARG*2 + 1) - 2)
3141         {
3142             /* At least two spare slots are needed to decompose both
3143              * concat args. If there are no slots left, continue to
3144              * examine the rest of the optree, but don't push new values
3145              * on args[]. If the optree as a whole is legal for conversion
3146              * (in particular that the last concat isn't STACKED), then
3147              * the first PERL_MULTICONCAT_MAXARG elements of the optree
3148              * can be converted into an OP_MULTICONCAT now, with the first
3149              * child of that op being the remainder of the optree -
3150              * which may itself later be converted to a multiconcat op
3151              * too.
3152              */
3153             if (last) {
3154                 /* the last arg is the rest of the optree */
3155                 argp++->p = NULL;
3156                 nargs++;
3157             }
3158         }
3159         else if (   argop->op_type == OP_CONST
3160             && ((sv = cSVOPx_sv(argop)))
3161             /* defer stringification until runtime of 'constant'
3162              * things that might stringify variantly, e.g. the radix
3163              * point of NVs, or overloaded RVs */
3164             && (SvPOK(sv) || SvIOK(sv))
3165             && (!SvGMAGICAL(sv))
3166         ) {
3167             if (argop->op_private & OPpCONST_STRICT)
3168                 no_bareword_allowed(argop);
3169             argp++->p = sv;
3170             utf8   |= cBOOL(SvUTF8(sv));
3171             nconst++;
3172             if (prev_was_const)
3173                 /* this const may be demoted back to a plain arg later;
3174                  * make sure we have enough arg slots left */
3175                 nadjconst++;
3176             prev_was_const = !prev_was_const;
3177         }
3178         else {
3179             argp++->p = NULL;
3180             nargs++;
3181             prev_was_const = FALSE;
3182         }
3183
3184         if (last)
3185             break;
3186     }
3187
3188     toparg = argp - 1;
3189
3190     if (stacked_last)
3191         return; /* we don't support ((A.=B).=C)...) */
3192
3193     /* look for two adjacent consts and don't fold them together:
3194      *     $o . "a" . "b"
3195      * should do
3196      *     $o->concat("a")->concat("b")
3197      * rather than
3198      *     $o->concat("ab")
3199      * (but $o .=  "a" . "b" should still fold)
3200      */
3201     {
3202         bool seen_nonconst = FALSE;
3203         for (argp = toparg; argp >= args; argp--) {
3204             if (argp->p == NULL) {
3205                 seen_nonconst = TRUE;
3206                 continue;
3207             }
3208             if (!seen_nonconst)
3209                 continue;
3210             if (argp[1].p) {
3211                 /* both previous and current arg were constants;
3212                  * leave the current OP_CONST as-is */
3213                 argp->p = NULL;
3214                 nconst--;
3215                 nargs++;
3216             }
3217         }
3218     }
3219
3220     /* -----------------------------------------------------------------
3221      * Phase 2:
3222      *
3223      * At this point we have determined that the optree *can* be converted
3224      * into a multiconcat. Having gathered all the evidence, we now decide
3225      * whether it *should*.
3226      */
3227
3228
3229     /* we need at least one concat action, e.g.:
3230      *
3231      *  Y . Z
3232      *  X = Y . Z
3233      *  X .= Y
3234      *
3235      * otherwise we could be doing something like $x = "foo", which
3236      * if treated as a concat, would fail to COW.
3237      */
3238     if (nargs + nconst + cBOOL(private_flags & OPpMULTICONCAT_APPEND) < 2)
3239         return;
3240
3241     /* Benchmarking seems to indicate that we gain if:
3242      * * we optimise at least two actions into a single multiconcat
3243      *    (e.g concat+concat, sassign+concat);
3244      * * or if we can eliminate at least 1 OP_CONST;
3245      * * or if we can eliminate a padsv via OPpTARGET_MY
3246      */
3247
3248     if (
3249            /* eliminated at least one OP_CONST */
3250            nconst >= 1
3251            /* eliminated an OP_SASSIGN */
3252         || o->op_type == OP_SASSIGN
3253            /* eliminated an OP_PADSV */
3254         || (!targmyop && is_targable)
3255     )
3256         /* definitely a net gain to optimise */
3257         goto optimise;
3258
3259     /* ... if not, what else? */
3260
3261     /* special-case '$lex1 = expr . $lex1' (where expr isn't lex1):
3262      * multiconcat is faster (due to not creating a temporary copy of
3263      * $lex1), whereas for a general $lex1 = $lex2 . $lex3, concat is
3264      * faster.
3265      */
3266     if (   nconst == 0
3267          && nargs == 2
3268          && targmyop
3269          && topop->op_type == OP_CONCAT
3270     ) {
3271         PADOFFSET t = targmyop->op_targ;
3272         OP *k1 = cBINOPx(topop)->op_first;
3273         OP *k2 = cBINOPx(topop)->op_last;
3274         if (   k2->op_type == OP_PADSV
3275             && k2->op_targ == t
3276             && (   k1->op_type != OP_PADSV
3277                 || k1->op_targ != t)
3278         )
3279             goto optimise;
3280     }
3281
3282     /* need at least two concats */
3283     if (nargs + nconst + cBOOL(private_flags & OPpMULTICONCAT_APPEND) < 3)
3284         return;
3285
3286
3287
3288     /* -----------------------------------------------------------------
3289      * Phase 3:
3290      *
3291      * At this point the optree has been verified as ok to be optimised
3292      * into an OP_MULTICONCAT. Now start changing things.
3293      */
3294
3295    optimise:
3296
3297     /* stringify all const args and determine utf8ness */
3298
3299     variant = 0;
3300     for (argp = args; argp <= toparg; argp++) {
3301         SV *sv = (SV*)argp->p;
3302         if (!sv)
3303             continue; /* not a const op */
3304         if (utf8 && !SvUTF8(sv))
3305             sv_utf8_upgrade_nomg(sv);
3306         argp->p = SvPV_nomg(sv, argp->len);
3307         total_len += argp->len;
3308
3309         /* see if any strings would grow if converted to utf8 */
3310         if (!utf8) {
3311             variant += variant_under_utf8_count((U8 *) argp->p,
3312                                                 (U8 *) argp->p + argp->len);
3313         }
3314     }
3315
3316     /* create and populate aux struct */
3317
3318   create_aux:
3319
3320     aux = (UNOP_AUX_item*)PerlMemShared_malloc(
3321                     sizeof(UNOP_AUX_item)
3322                     *  (
3323                            PERL_MULTICONCAT_HEADER_SIZE
3324                          + ((nargs + 1) * (variant ? 2 : 1))
3325                         )
3326                     );
3327     const_str = (char *)PerlMemShared_malloc(total_len ? total_len : 1);
3328
3329     /* Extract all the non-const expressions from the concat tree then
3330      * dispose of the old tree, e.g. convert the tree from this:
3331      *
3332      *  o => SASSIGN
3333      *         |
3334      *       STRINGIFY   -- TARGET
3335      *         |
3336      *       ex-PUSHMARK -- CONCAT
3337      *                        |
3338      *                      CONCAT -- EXPR5
3339      *                        |
3340      *                      CONCAT -- EXPR4
3341      *                        |
3342      *                      CONCAT -- EXPR3
3343      *                        |
3344      *                      EXPR1  -- EXPR2
3345      *
3346      *
3347      * to:
3348      *
3349      *  o => MULTICONCAT
3350      *         |
3351      *       ex-PUSHMARK -- EXPR1 -- EXPR2 -- EXPR3 -- EXPR4 -- EXPR5 -- TARGET
3352      *
3353      * except that if EXPRi is an OP_CONST, it's discarded.
3354      *
3355      * During the conversion process, EXPR ops are stripped from the tree
3356      * and unshifted onto o. Finally, any of o's remaining original
3357      * childen are discarded and o is converted into an OP_MULTICONCAT.
3358      *
3359      * In this middle of this, o may contain both: unshifted args on the
3360      * left, and some remaining original args on the right. lastkidop
3361      * is set to point to the right-most unshifted arg to delineate
3362      * between the two sets.
3363      */
3364
3365
3366     if (is_sprintf) {
3367         /* create a copy of the format with the %'s removed, and record
3368          * the sizes of the const string segments in the aux struct */
3369         char *q, *oldq;
3370         lenp = aux + PERL_MULTICONCAT_IX_LENGTHS;
3371
3372         p    = sprintf_info.start;
3373         q    = const_str;
3374         oldq = q;
3375         for (; p < sprintf_info.end; p++) {
3376             if (*p == '%') {
3377                 p++;
3378                 if (*p != '%') {
3379                     (lenp++)->ssize = q - oldq;
3380                     oldq = q;
3381                     continue;
3382                 }
3383             }
3384             *q++ = *p;
3385         }
3386         lenp->ssize = q - oldq;
3387         assert((STRLEN)(q - const_str) == total_len);
3388
3389         /* Attach all the args (i.e. the kids of the sprintf) to o (which
3390          * may or may not be topop) The pushmark and const ops need to be
3391          * kept in case they're an op_next entry point.
3392          */
3393         lastkidop = cLISTOPx(topop)->op_last;
3394         kid = cUNOPx(topop)->op_first; /* pushmark */
3395         op_null(kid);
3396         op_null(OpSIBLING(kid));       /* const */
3397         if (o != topop) {
3398             kid = op_sibling_splice(topop, NULL, -1, NULL); /* cut all args */
3399             op_sibling_splice(o, NULL, 0, kid); /* and attach to o */
3400             lastkidop->op_next = o;
3401         }
3402     }
3403     else {
3404         p = const_str;
3405         lenp = aux + PERL_MULTICONCAT_IX_LENGTHS;
3406
3407         lenp->ssize = -1;
3408
3409         /* Concatenate all const strings into const_str.
3410          * Note that args[] contains the RHS args in reverse order, so
3411          * we scan args[] from top to bottom to get constant strings
3412          * in L-R order
3413          */
3414         for (argp = toparg; argp >= args; argp--) {
3415             if (!argp->p)
3416                 /* not a const op */
3417                 (++lenp)->ssize = -1;
3418             else {
3419                 STRLEN l = argp->len;
3420                 Copy(argp->p, p, l, char);
3421                 p += l;
3422                 if (lenp->ssize == -1)
3423                     lenp->ssize = l;
3424                 else
3425                     lenp->ssize += l;
3426             }
3427         }
3428
3429         kid = topop;
3430         nextop = o;
3431         lastkidop = NULL;
3432
3433         for (argp = args; argp <= toparg; argp++) {
3434             /* only keep non-const args, except keep the first-in-next-chain
3435              * arg no matter what it is (but nulled if OP_CONST), because it
3436              * may be the entry point to this subtree from the previous
3437              * op_next.
3438              */
3439             bool last = (argp == toparg);
3440             OP *prev;
3441
3442             /* set prev to the sibling *before* the arg to be cut out,
3443              * e.g. when cutting EXPR:
3444              *
3445              *         |
3446              * kid=  CONCAT
3447              *         |
3448              * prev= CONCAT -- EXPR
3449              *         |
3450              */
3451             if (argp == args && kid->op_type != OP_CONCAT) {
3452                 /* in e.g. '$x .= f(1)' there's no RHS concat tree
3453                  * so the expression to be cut isn't kid->op_last but
3454                  * kid itself */
3455                 OP *o1, *o2;
3456                 /* find the op before kid */
3457                 o1 = NULL;
3458                 o2 = cUNOPx(parentop)->op_first;
3459                 while (o2 && o2 != kid) {
3460                     o1 = o2;
3461                     o2 = OpSIBLING(o2);
3462                 }
3463                 assert(o2 == kid);
3464                 prev = o1;
3465                 kid  = parentop;
3466             }
3467             else if (kid == o && lastkidop)
3468                 prev = last ? lastkidop : OpSIBLING(lastkidop);
3469             else
3470                 prev = last ? NULL : cUNOPx(kid)->op_first;
3471
3472             if (!argp->p || last) {
3473                 /* cut RH op */
3474                 OP *aop = op_sibling_splice(kid, prev, 1, NULL);
3475                 /* and unshift to front of o */
3476                 op_sibling_splice(o, NULL, 0, aop);
3477                 /* record the right-most op added to o: later we will
3478                  * free anything to the right of it */
3479                 if (!lastkidop)
3480                     lastkidop = aop;
3481                 aop->op_next = nextop;
3482                 if (last) {
3483                     if (argp->p)
3484                         /* null the const at start of op_next chain */
3485                         op_null(aop);
3486                 }
3487                 else if (prev)
3488                     nextop = prev->op_next;
3489             }
3490
3491             /* the last two arguments are both attached to the same concat op */
3492             if (argp < toparg - 1)
3493                 kid = prev;
3494         }
3495     }
3496
3497     /* Populate the aux struct */
3498
3499     aux[PERL_MULTICONCAT_IX_NARGS].ssize     = nargs;
3500     aux[PERL_MULTICONCAT_IX_PLAIN_PV].pv    = utf8 ? NULL : const_str;
3501     aux[PERL_MULTICONCAT_IX_PLAIN_LEN].ssize = utf8 ?    0 : total_len;
3502     aux[PERL_MULTICONCAT_IX_UTF8_PV].pv     = const_str;
3503     aux[PERL_MULTICONCAT_IX_UTF8_LEN].ssize  = total_len;
3504
3505     /* if variant > 0, calculate a variant const string and lengths where
3506      * the utf8 version of the string will take 'variant' more bytes than
3507      * the plain one. */
3508
3509     if (variant) {
3510         char              *p = const_str;
3511         STRLEN          ulen = total_len + variant;
3512         UNOP_AUX_item  *lens = aux + PERL_MULTICONCAT_IX_LENGTHS;
3513         UNOP_AUX_item *ulens = lens + (nargs + 1);
3514         char             *up = (char*)PerlMemShared_malloc(ulen);
3515         SSize_t            n;
3516
3517         aux[PERL_MULTICONCAT_IX_UTF8_PV].pv    = up;
3518         aux[PERL_MULTICONCAT_IX_UTF8_LEN].ssize = ulen;
3519
3520         for (n = 0; n < (nargs + 1); n++) {
3521             SSize_t i;
3522             char * orig_up = up;
3523             for (i = (lens++)->ssize; i > 0; i--) {
3524                 U8 c = *p++;
3525                 append_utf8_from_native_byte(c, (U8**)&up);
3526             }
3527             (ulens++)->ssize = (i < 0) ? i : up - orig_up;
3528         }
3529     }
3530
3531     if (stringop) {
3532         /* if there was a top(ish)-level OP_STRINGIFY, we need to keep
3533          * that op's first child - an ex-PUSHMARK - because the op_next of
3534          * the previous op may point to it (i.e. it's the entry point for
3535          * the o optree)
3536          */
3537         OP *pmop =
3538             (stringop == o)
3539                 ? op_sibling_splice(o, lastkidop, 1, NULL)
3540                 : op_sibling_splice(stringop, NULL, 1, NULL);
3541         assert(OP_TYPE_IS_OR_WAS_NN(pmop, OP_PUSHMARK));
3542         op_sibling_splice(o, NULL, 0, pmop);
3543         if (!lastkidop)
3544             lastkidop = pmop;
3545     }
3546
3547     /* Optimise
3548      *    target  = A.B.C...
3549      *    target .= A.B.C...
3550      */
3551
3552     if (targetop) {
3553         assert(!targmyop);
3554
3555         if (o->op_type == OP_SASSIGN) {
3556             /* Move the target subtree from being the last of o's children
3557              * to being the last of o's preserved children.
3558              * Note the difference between 'target = ...' and 'target .= ...':
3559              * for the former, target is executed last; for the latter,
3560              * first.
3561              */
3562             kid = OpSIBLING(lastkidop);
3563             op_sibling_splice(o, kid, 1, NULL); /* cut target op */
3564             op_sibling_splice(o, lastkidop, 0, targetop); /* and paste */
3565             lastkidop->op_next = kid->op_next;
3566             lastkidop = targetop;
3567         }
3568         else {
3569             /* Move the target subtree from being the first of o's
3570              * original children to being the first of *all* o's children.
3571              */
3572             if (lastkidop) {
3573                 op_sibling_splice(o, lastkidop, 1, NULL); /* cut target op */
3574                 op_sibling_splice(o, NULL, 0, targetop);  /* and paste*/
3575             }
3576             else {
3577                 /* if the RHS of .= doesn't contain a concat (e.g.
3578                  * $x .= "foo"), it gets missed by the "strip ops from the
3579                  * tree and add to o" loop earlier */
3580                 assert(topop->op_type != OP_CONCAT);
3581                 if (stringop) {
3582                     /* in e.g. $x .= "$y", move the $y expression
3583                      * from being a child of OP_STRINGIFY to being the
3584                      * second child of the OP_CONCAT
3585                      */
3586                     assert(cUNOPx(stringop)->op_first == topop);
3587                     op_sibling_splice(stringop, NULL, 1, NULL);
3588                     op_sibling_splice(o, cUNOPo->op_first, 0, topop);
3589                 }
3590                 assert(topop == OpSIBLING(cBINOPo->op_first));
3591                 if (toparg->p)
3592                     op_null(topop);
3593                 lastkidop = topop;
3594             }
3595         }
3596
3597         if (is_targable) {
3598             /* optimise
3599              *  my $lex  = A.B.C...
3600              *     $lex  = A.B.C...
3601              *     $lex .= A.B.C...
3602              * The original padsv op is kept but nulled in case it's the
3603              * entry point for the optree (which it will be for
3604              * '$lex .=  ... '
3605              */
3606             private_flags |= OPpTARGET_MY;
3607             private_flags |= (targetop->op_private & OPpLVAL_INTRO);
3608             o->op_targ = targetop->op_targ;
3609             targetop->op_targ = 0;
3610             op_null(targetop);
3611         }
3612         else
3613             flags |= OPf_STACKED;
3614     }
3615     else if (targmyop) {
3616         private_flags |= OPpTARGET_MY;
3617         if (o != targmyop) {
3618             o->op_targ = targmyop->op_targ;
3619             targmyop->op_targ = 0;
3620         }
3621     }
3622
3623     /* detach the emaciated husk of the sprintf/concat optree and free it */
3624     for (;;) {
3625         kid = op_sibling_splice(o, lastkidop, 1, NULL);
3626         if (!kid)
3627             break;
3628         op_free(kid);
3629     }
3630
3631     /* and convert o into a multiconcat */
3632
3633     o->op_flags        = (flags|OPf_KIDS|stacked_last
3634                          |(o->op_flags & (OPf_WANT|OPf_PARENS)));
3635     o->op_private      = private_flags;
3636     o->op_type         = OP_MULTICONCAT;
3637     o->op_ppaddr       = PL_ppaddr[OP_MULTICONCAT];
3638     cUNOP_AUXo->op_aux = aux;
3639 }
3640
3641
3642 /* do all the final processing on an optree (e.g. running the peephole
3643  * optimiser on it), then attach it to cv (if cv is non-null)
3644  */
3645
3646 static void
3647 S_process_optree(pTHX_ CV *cv, OP *optree, OP* start)
3648 {
3649     OP **startp;
3650
3651     /* XXX for some reason, evals, require and main optrees are
3652      * never attached to their CV; instead they just hang off
3653      * PL_main_root + PL_main_start or PL_eval_root + PL_eval_start
3654      * and get manually freed when appropriate */
3655     if (cv)
3656         startp = &CvSTART(cv);
3657     else
3658         startp = PL_in_eval? &PL_eval_start : &PL_main_start;
3659
3660     *startp = start;
3661     optree->op_private |= OPpREFCOUNTED;
3662     OpREFCNT_set(optree, 1);
3663     optimize_optree(optree);
3664     CALL_PEEP(*startp);
3665     finalize_optree(optree);
3666     S_prune_chain_head(startp);
3667
3668     if (cv) {
3669         /* now that optimizer has done its work, adjust pad values */
3670         pad_tidy(optree->op_type == OP_LEAVEWRITE ? padtidy_FORMAT
3671                  : CvCLONE(cv) ? padtidy_SUBCLONE : padtidy_SUB);
3672     }
3673 }
3674
3675
3676 /*
3677 =for apidoc optimize_optree
3678
3679 This function applies some optimisations to the optree in top-down order.
3680 It is called before the peephole optimizer, which processes ops in
3681 execution order. Note that finalize_optree() also does a top-down scan,
3682 but is called *after* the peephole optimizer.
3683
3684 =cut
3685 */
3686
3687 void
3688 Perl_optimize_optree(pTHX_ OP* o)
3689 {
3690     PERL_ARGS_ASSERT_OPTIMIZE_OPTREE;
3691
3692     ENTER;
3693     SAVEVPTR(PL_curcop);
3694
3695     optimize_op(o);
3696
3697     LEAVE;
3698 }
3699
3700
3701 /* helper for optimize_optree() which optimises one op then recurses
3702  * to optimise any children.
3703  */
3704
3705 STATIC void
3706 S_optimize_op(pTHX_ OP* o)
3707 {
3708     OP *top_op = o;
3709
3710     PERL_ARGS_ASSERT_OPTIMIZE_OP;
3711
3712     while (1) {
3713         OP * next_kid = NULL;
3714
3715         assert(o->op_type != OP_FREED);
3716
3717         switch (o->op_type) {
3718         case OP_NEXTSTATE:
3719         case OP_DBSTATE:
3720             PL_curcop = ((COP*)o);              /* for warnings */
3721             break;
3722
3723
3724         case OP_CONCAT:
3725         case OP_SASSIGN:
3726         case OP_STRINGIFY:
3727         case OP_SPRINTF:
3728             S_maybe_multiconcat(aTHX_ o);
3729             break;
3730
3731         case OP_SUBST:
3732             if (cPMOPo->op_pmreplrootu.op_pmreplroot) {
3733                 /* we can't assume that op_pmreplroot->op_sibparent == o
3734                  * and that it is thus possible to walk back up the tree
3735                  * past op_pmreplroot. So, although we try to avoid
3736                  * recursing through op trees, do it here. After all,
3737                  * there are unlikely to be many nested s///e's within
3738                  * the replacement part of a s///e.
3739                  */
3740                 optimize_op(cPMOPo->op_pmreplrootu.op_pmreplroot);
3741             }
3742             break;
3743
3744         default:
3745             break;
3746         }
3747
3748         if (o->op_flags & OPf_KIDS)
3749             next_kid = cUNOPo->op_first;
3750
3751         /* if a kid hasn't been nominated to process, continue with the
3752          * next sibling, or if no siblings left, go back to the parent's
3753          * siblings and so on
3754          */
3755         while (!next_kid) {
3756             if (o == top_op)
3757                 return; /* at top; no parents/siblings to try */
3758             if (OpHAS_SIBLING(o))
3759                 next_kid = o->op_sibparent;
3760             else
3761                 o = o->op_sibparent; /*try parent's next sibling */
3762         }
3763
3764       /* this label not yet used. Goto here if any code above sets
3765        * next-kid
3766        get_next_op:
3767        */
3768         o = next_kid;
3769     }
3770 }
3771
3772
3773 /*
3774 =for apidoc finalize_optree
3775
3776 This function finalizes the optree.  Should be called directly after
3777 the complete optree is built.  It does some additional
3778 checking which can't be done in the normal C<ck_>xxx functions and makes
3779 the tree thread-safe.
3780
3781 =cut
3782 */
3783 void
3784 Perl_finalize_optree(pTHX_ OP* o)
3785 {
3786     PERL_ARGS_ASSERT_FINALIZE_OPTREE;
3787
3788     ENTER;
3789     SAVEVPTR(PL_curcop);
3790
3791     finalize_op(o);
3792
3793     LEAVE;
3794 }
3795
3796 #ifdef USE_ITHREADS
3797 /* Relocate sv to the pad for thread safety.
3798  * Despite being a "constant", the SV is written to,
3799  * for reference counts, sv_upgrade() etc. */
3800 PERL_STATIC_INLINE void
3801 S_op_relocate_sv(pTHX_ SV** svp, PADOFFSET* targp)
3802 {
3803     PADOFFSET ix;
3804     PERL_ARGS_ASSERT_OP_RELOCATE_SV;
3805     if (!*svp) return;
3806     ix = pad_alloc(OP_CONST, SVf_READONLY);
3807     SvREFCNT_dec(PAD_SVl(ix));
3808     PAD_SETSV(ix, *svp);
3809     /* XXX I don't know how this isn't readonly already. */
3810     if (!SvIsCOW(PAD_SVl(ix))) SvREADONLY_on(PAD_SVl(ix));
3811     *svp = NULL;
3812     *targp = ix;
3813 }
3814 #endif
3815
3816 /*
3817 =for apidoc traverse_op_tree
3818
3819 Return the next op in a depth-first traversal of the op tree,
3820 returning NULL when the traversal is complete.
3821
3822 The initial call must supply the root of the tree as both top and o.
3823
3824 For now it's static, but it may be exposed to the API in the future.
3825
3826 =cut
3827 */
3828
3829 STATIC OP*
3830 S_traverse_op_tree(pTHX_ OP *top, OP *o) {
3831     OP *sib;
3832
3833     PERL_ARGS_ASSERT_TRAVERSE_OP_TREE;
3834
3835     if ((o->op_flags & OPf_KIDS) && cUNOPo->op_first) {
3836         return cUNOPo->op_first;
3837     }
3838     else if ((sib = OpSIBLING(o))) {
3839         return sib;
3840     }
3841     else {
3842         OP *parent = o->op_sibparent;
3843         assert(!(o->op_moresib));
3844         while (parent && parent != top) {
3845             OP *sib = OpSIBLING(parent);
3846             if (sib)
3847                 return sib;
3848             parent = parent->op_sibparent;
3849         }
3850
3851         return NULL;
3852     }
3853 }
3854
3855 STATIC void
3856 S_finalize_op(pTHX_ OP* o)
3857 {
3858     OP * const top = o;
3859     PERL_ARGS_ASSERT_FINALIZE_OP;
3860
3861     do {
3862         assert(o->op_type != OP_FREED);
3863
3864         switch (o->op_type) {
3865         case OP_NEXTSTATE:
3866         case OP_DBSTATE:
3867             PL_curcop = ((COP*)o);              /* for warnings */
3868             break;
3869         case OP_EXEC:
3870             if (OpHAS_SIBLING(o)) {
3871                 OP *sib = OpSIBLING(o);
3872                 if ((  sib->op_type == OP_NEXTSTATE || sib->op_type == OP_DBSTATE)
3873                     && ckWARN(WARN_EXEC)
3874                     && OpHAS_SIBLING(sib))
3875                 {
3876                     const OPCODE type = OpSIBLING(sib)->op_type;
3877                     if (type != OP_EXIT && type != OP_WARN && type != OP_DIE) {
3878                         const line_t oldline = CopLINE(PL_curcop);
3879                         CopLINE_set(PL_curcop, CopLINE((COP*)sib));
3880                         Perl_warner(aTHX_ packWARN(WARN_EXEC),
3881                             "Statement unlikely to be reached");
3882                         Perl_warner(aTHX_ packWARN(WARN_EXEC),
3883                             "\t(Maybe you meant system() when you said exec()?)\n");
3884                         CopLINE_set(PL_curcop, oldline);
3885                     }
3886                 }
3887             }
3888             break;
3889
3890         case OP_GV:
3891             if ((o->op_private & OPpEARLY_CV) && ckWARN(WARN_PROTOTYPE)) {
3892                 GV * const gv = cGVOPo_gv;
3893                 if (SvTYPE(gv) == SVt_PVGV && GvCV(gv) && SvPVX_const(GvCV(gv))) {
3894                     /* XXX could check prototype here instead of just carping */
3895                     SV * const sv = sv_newmortal();
3896                     gv_efullname3(sv, gv, NULL);
3897                     Perl_warner(aTHX_ packWARN(WARN_PROTOTYPE),
3898                                 "%" SVf "() called too early to check prototype",
3899                                 SVfARG(sv));
3900                 }
3901             }
3902             break;
3903
3904         case OP_CONST:
3905             if (cSVOPo->op_private & OPpCONST_STRICT)
3906                 no_bareword_allowed(o);
3907 #ifdef USE_ITHREADS
3908             /* FALLTHROUGH */
3909         case OP_HINTSEVAL:
3910             op_relocate_sv(&cSVOPo->op_sv, &o->op_targ);
3911 #endif
3912             break;
3913
3914 #ifdef USE_ITHREADS
3915             /* Relocate all the METHOP's SVs to the pad for thread safety. */
3916         case OP_METHOD_NAMED:
3917         case OP_METHOD_SUPER:
3918         case OP_METHOD_REDIR:
3919         case OP_METHOD_REDIR_SUPER:
3920             op_relocate_sv(&cMETHOPx(o)->op_u.op_meth_sv, &o->op_targ);
3921             break;
3922 #endif
3923
3924         case OP_HELEM: {
3925             UNOP *rop;
3926             SVOP *key_op;
3927             OP *kid;
3928
3929             if ((key_op = cSVOPx(((BINOP*)o)->op_last))->op_type != OP_CONST)
3930                 break;
3931
3932             rop = (UNOP*)((BINOP*)o)->op_first;
3933
3934             goto check_keys;
3935
3936             case OP_HSLICE:
3937                 S_scalar_slice_warning(aTHX_ o);
3938                 /* FALLTHROUGH */
3939
3940             case OP_KVHSLICE:
3941                 kid = OpSIBLING(cLISTOPo->op_first);
3942             if (/* I bet there's always a pushmark... */
3943                 OP_TYPE_ISNT_AND_WASNT_NN(kid, OP_LIST)
3944                 && OP_TYPE_ISNT_NN(kid, OP_CONST))
3945             {
3946                 break;
3947             }
3948
3949             key_op = (SVOP*)(kid->op_type == OP_CONST
3950                              ? kid
3951                              : OpSIBLING(kLISTOP->op_first));
3952
3953             rop = (UNOP*)((LISTOP*)o)->op_last;
3954
3955         check_keys:
3956             if (o->op_private & OPpLVAL_INTRO || rop->op_type != OP_RV2HV)
3957                 rop = NULL;
3958             S_check_hash_fields_and_hekify(aTHX_ rop, key_op, 1);
3959             break;
3960         }
3961         case OP_NULL:
3962             if (o->op_targ != OP_HSLICE && o->op_targ != OP_ASLICE)
3963                 break;
3964             /* FALLTHROUGH */
3965         case OP_ASLICE:
3966             S_scalar_slice_warning(aTHX_ o);
3967             break;
3968
3969         case OP_SUBST: {
3970             if (cPMOPo->op_pmreplrootu.op_pmreplroot)
3971                 finalize_op(cPMOPo->op_pmreplrootu.op_pmreplroot);
3972             break;
3973         }
3974         default:
3975             break;
3976         }
3977
3978 #ifdef DEBUGGING
3979         if (o->op_flags & OPf_KIDS) {
3980             OP *kid;
3981
3982             /* check that op_last points to the last sibling, and that
3983              * the last op_sibling/op_sibparent field points back to the
3984              * parent, and that the only ops with KIDS are those which are
3985              * entitled to them */
3986             U32 type = o->op_type;
3987             U32 family;
3988             bool has_last;
3989
3990             if (type == OP_NULL) {
3991                 type = o->op_targ;
3992                 /* ck_glob creates a null UNOP with ex-type GLOB
3993                  * (which is a list op. So pretend it wasn't a listop */
3994                 if (type == OP_GLOB)
3995                     type = OP_NULL;
3996             }
3997             family = PL_opargs[type] & OA_CLASS_MASK;
3998
3999             has_last = (   family == OA_BINOP
4000                         || family == OA_LISTOP
4001                         || family == OA_PMOP
4002                         || family == OA_LOOP
4003                        );
4004             assert(  has_last /* has op_first and op_last, or ...
4005                   ... has (or may have) op_first: */
4006                   || family == OA_UNOP
4007                   || family == OA_UNOP_AUX
4008                   || family == OA_LOGOP
4009                   || family == OA_BASEOP_OR_UNOP
4010                   || family == OA_FILESTATOP
4011                   || family == OA_LOOPEXOP
4012                   || family == OA_METHOP
4013                   || type == OP_CUSTOM
4014                   || type == OP_NULL /* new_logop does this */
4015                   );
4016
4017             for (kid = cUNOPo->op_first; kid; kid = OpSIBLING(kid)) {
4018                 if (!OpHAS_SIBLING(kid)) {
4019                     if (has_last)
4020                         assert(kid == cLISTOPo->op_last);
4021                     assert(kid->op_sibparent == o);
4022                 }
4023             }
4024         }
4025 #endif
4026     } while (( o = traverse_op_tree(top, o)) != NULL);
4027 }
4028
4029 static void
4030 S_mark_padname_lvalue(pTHX_ PADNAME *pn)
4031 {
4032     CV *cv = PL_compcv;
4033     PadnameLVALUE_on(pn);
4034     while (PadnameOUTER(pn) && PARENT_PAD_INDEX(pn)) {
4035         cv = CvOUTSIDE(cv);
4036         /* RT #127786: cv can be NULL due to an eval within the DB package
4037          * called from an anon sub - anon subs don't have CvOUTSIDE() set
4038          * unless they contain an eval, but calling eval within DB
4039          * pretends the eval was done in the caller's scope.
4040          */
4041         if (!cv)
4042             break;
4043         assert(CvPADLIST(cv));
4044         pn =
4045            PadlistNAMESARRAY(CvPADLIST(cv))[PARENT_PAD_INDEX(pn)];
4046         assert(PadnameLEN(pn));
4047         PadnameLVALUE_on(pn);
4048     }
4049 }
4050
4051 static bool
4052 S_vivifies(const OPCODE type)
4053 {
4054     switch(type) {
4055     case OP_RV2AV:     case   OP_ASLICE:
4056     case OP_RV2HV:     case OP_KVASLICE:
4057     case OP_RV2SV:     case   OP_HSLICE:
4058     case OP_AELEMFAST: case OP_KVHSLICE:
4059     case OP_HELEM:
4060     case OP_AELEM:
4061         return 1;
4062     }
4063     return 0;
4064 }
4065
4066
4067 /* apply lvalue reference (aliasing) context to the optree o.
4068  * E.g. in
4069  *     \($x,$y) = (...)
4070  * o would be the list ($x,$y) and type would be OP_AASSIGN.
4071  * It may descend and apply this to children too, for example in
4072  * \( $cond ? $x, $y) = (...)
4073  */
4074
4075 static void
4076 S_lvref(pTHX_ OP *o, I32 type)
4077 {
4078     OP *kid;
4079     OP * top_op = o;
4080
4081     while (1) {
4082         switch (o->op_type) {
4083         case OP_COND_EXPR:
4084             o = OpSIBLING(cUNOPo->op_first);
4085             continue;
4086
4087         case OP_PUSHMARK:
4088             goto do_next;
4089
4090         case OP_RV2AV:
4091             if (cUNOPo->op_first->op_type != OP_GV) goto badref;
4092             o->op_flags |= OPf_STACKED;
4093             if (o->op_flags & OPf_PARENS) {
4094                 if (o->op_private & OPpLVAL_INTRO) {
4095                      yyerror(Perl_form(aTHX_ "Can't modify reference to "
4096                           "localized parenthesized array in list assignment"));
4097                     goto do_next;
4098                 }
4099               slurpy:
4100                 OpTYPE_set(o, OP_LVAVREF);
4101                 o->op_private &= OPpLVAL_INTRO|OPpPAD_STATE;
4102                 o->op_flags |= OPf_MOD|OPf_REF;
4103                 goto do_next;
4104             }
4105             o->op_private |= OPpLVREF_AV;
4106             goto checkgv;
4107
4108         case OP_RV2CV:
4109             kid = cUNOPo->op_first;
4110             if (kid->op_type == OP_NULL)
4111                 kid = cUNOPx(OpSIBLING(kUNOP->op_first))
4112                     ->op_first;
4113             o->op_private = OPpLVREF_CV;
4114             if (kid->op_type == OP_GV)
4115                 o->op_flags |= OPf_STACKED;
4116             else if (kid->op_type == OP_PADCV) {
4117                 o->op_targ = kid->op_targ;
4118                 kid->op_targ = 0;
4119                 op_free(cUNOPo->op_first);
4120                 cUNOPo->op_first = NULL;
4121                 o->op_flags &=~ OPf_KIDS;
4122             }
4123             else goto badref;
4124             break;
4125
4126         case OP_RV2HV:
4127             if (o->op_flags & OPf_PARENS) {
4128               parenhash:
4129                 yyerror(Perl_form(aTHX_ "Can't modify reference to "
4130                                      "parenthesized hash in list assignment"));
4131                     goto do_next;
4132             }
4133             o->op_private |= OPpLVREF_HV;
4134             /* FALLTHROUGH */
4135         case OP_RV2SV:
4136           checkgv:
4137             if (cUNOPo->op_first->op_type != OP_GV) goto badref;
4138             o->op_flags |= OPf_STACKED;
4139             break;
4140
4141         case OP_PADHV:
4142             if (o->op_flags & OPf_PARENS) goto parenhash;
4143             o->op_private |= OPpLVREF_HV;
4144             /* FALLTHROUGH */
4145         case OP_PADSV:
4146             PAD_COMPNAME_GEN_set(o->op_targ, PERL_INT_MAX);
4147             break;
4148
4149         case OP_PADAV:
4150             PAD_COMPNAME_GEN_set(o->op_targ, PERL_INT_MAX);
4151             if (o->op_flags & OPf_PARENS) goto slurpy;
4152             o->op_private |= OPpLVREF_AV;
4153             break;
4154
4155         case OP_AELEM:
4156         case OP_HELEM:
4157             o->op_private |= OPpLVREF_ELEM;
4158             o->op_flags   |= OPf_STACKED;
4159             break;
4160
4161         case OP_ASLICE:
4162         case OP_HSLICE:
4163             OpTYPE_set(o, OP_LVREFSLICE);
4164             o->op_private &= OPpLVAL_INTRO;
4165             goto do_next;
4166
4167         case OP_NULL:
4168             if (o->op_flags & OPf_SPECIAL)              /* do BLOCK */
4169                 goto badref;
4170             else if (!(o->op_flags & OPf_KIDS))
4171                 goto do_next;
4172
4173             /* the code formerly only recursed into the first child of
4174              * a non ex-list OP_NULL. if we ever encounter such a null op with
4175              * more than one child, need to decide whether its ok to process
4176              * *all* its kids or not */
4177             assert(o->op_targ == OP_LIST
4178                     || !(OpHAS_SIBLING(cBINOPo->op_first)));
4179             /* FALLTHROUGH */
4180         case OP_LIST:
4181             o = cLISTOPo->op_first;
4182             continue;
4183
4184         case OP_STUB:
4185             if (o->op_flags & OPf_PARENS)
4186                 goto do_next;
4187             /* FALLTHROUGH */
4188         default:
4189           badref:
4190             /* diag_listed_as: Can't modify reference to %s in %s assignment */
4191             yyerror(Perl_form(aTHX_ "Can't modify reference to %s in %s",
4192                          o->op_type == OP_NULL && o->op_flags & OPf_SPECIAL
4193                           ? "do block"
4194                           : OP_DESC(o),
4195                          PL_op_desc[type]));
4196             goto do_next;
4197         }
4198
4199         OpTYPE_set(o, OP_LVREF);
4200         o->op_private &=
4201             OPpLVAL_INTRO|OPpLVREF_ELEM|OPpLVREF_TYPE|OPpPAD_STATE;
4202         if (type == OP_ENTERLOOP)
4203             o->op_private |= OPpLVREF_ITER;
4204
4205       do_next:
4206         while (1) {
4207             if (o == top_op)
4208                 return; /* at top; no parents/siblings to try */
4209             if (OpHAS_SIBLING(o)) {
4210                 o = o->op_sibparent;
4211                 break;
4212             }
4213             o = o->op_sibparent; /*try parent's next sibling */
4214         }
4215     } /* while */
4216 }
4217
4218
4219 PERL_STATIC_INLINE bool
4220 S_potential_mod_type(I32 type)
4221 {
4222     /* Types that only potentially result in modification.  */
4223     return type == OP_GREPSTART || type == OP_ENTERSUB
4224         || type == OP_REFGEN    || type == OP_LEAVESUBLV;
4225 }
4226
4227
4228 /*
4229 =for apidoc op_lvalue
4230
4231 Propagate lvalue ("modifiable") context to an op and its children.
4232 C<type> represents the context type, roughly based on the type of op that
4233 would do the modifying, although C<local()> is represented by C<OP_NULL>,
4234 because it has no op type of its own (it is signalled by a flag on
4235 the lvalue op).
4236
4237 This function detects things that can't be modified, such as C<$x+1>, and
4238 generates errors for them.  For example, C<$x+1 = 2> would cause it to be
4239 called with an op of type C<OP_ADD> and a C<type> argument of C<OP_SASSIGN>.
4240
4241 It also flags things that need to behave specially in an lvalue context,
4242 such as C<$$x = 5> which might have to vivify a reference in C<$x>.
4243
4244 =cut
4245
4246 Perl_op_lvalue_flags() is a non-API lower-level interface to
4247 op_lvalue().  The flags param has these bits:
4248     OP_LVALUE_NO_CROAK:  return rather than croaking on error
4249
4250 */
4251
4252 OP *
4253 Perl_op_lvalue_flags(pTHX_ OP *o, I32 type, U32 flags)
4254 {
4255     OP *top_op = o;
4256
4257     if (!o || (PL_parser && PL_parser->error_count))
4258         return o;
4259
4260     while (1) {
4261     OP *kid;
4262     /* -1 = error on localize, 0 = ignore localize, 1 = ok to localize */
4263     int localize = -1;
4264     OP *next_kid = NULL;
4265
4266     if ((o->op_private & OPpTARGET_MY)
4267         && (PL_opargs[o->op_type] & OA_TARGLEX))/* OPp share the meaning */
4268     {
4269         goto do_next;
4270     }
4271
4272     /* elements of a list might be in void context because the list is
4273        in scalar context or because they are attribute sub calls */
4274     if ((o->op_flags & OPf_WANT) == OPf_WANT_VOID)
4275         goto do_next;
4276
4277     if (type == OP_PRTF || type == OP_SPRINTF) type = OP_ENTERSUB;
4278
4279     switch (o->op_type) {
4280     case OP_UNDEF:
4281         PL_modcount++;
4282         goto do_next;
4283
4284     case OP_STUB:
4285         if ((o->op_flags & OPf_PARENS))
4286             break;
4287         goto nomod;
4288
4289     case OP_ENTERSUB:
4290         if ((type == OP_UNDEF || type == OP_REFGEN || type == OP_LOCK) &&
4291             !(o->op_flags & OPf_STACKED)) {
4292             OpTYPE_set(o, OP_RV2CV);            /* entersub => rv2cv */
4293             assert(cUNOPo->op_first->op_type == OP_NULL);
4294             op_null(((LISTOP*)cUNOPo->op_first)->op_first);/* disable pushmark */
4295             break;
4296         }
4297         else {                          /* lvalue subroutine call */
4298             o->op_private |= OPpLVAL_INTRO;
4299             PL_modcount = RETURN_UNLIMITED_NUMBER;
4300             if (S_potential_mod_type(type)) {
4301                 o->op_private |= OPpENTERSUB_INARGS;
4302                 break;
4303             }
4304             else {                      /* Compile-time error message: */
4305                 OP *kid = cUNOPo->op_first;
4306                 CV *cv;
4307                 GV *gv;
4308                 SV *namesv;
4309
4310                 if (kid->op_type != OP_PUSHMARK) {
4311                     if (kid->op_type != OP_NULL || kid->op_targ != OP_LIST)
4312                         Perl_croak(aTHX_
4313                                 "panic: unexpected lvalue entersub "
4314                                 "args: type/targ %ld:%" UVuf,
4315                                 (long)kid->op_type, (UV)kid->op_targ);
4316                     kid = kLISTOP->op_first;
4317                 }
4318                 while (OpHAS_SIBLING(kid))
4319                     kid = OpSIBLING(kid);
4320                 if (!(kid->op_type == OP_NULL && kid->op_targ == OP_RV2CV)) {
4321                     break;      /* Postpone until runtime */
4322                 }
4323
4324                 kid = kUNOP->op_first;
4325                 if (kid->op_type == OP_NULL && kid->op_targ == OP_RV2SV)
4326                     kid = kUNOP->op_first;
4327                 if (kid->op_type == OP_NULL)
4328                     Perl_croak(aTHX_
4329                                "Unexpected constant lvalue entersub "
4330                                "entry via type/targ %ld:%" UVuf,
4331                                (long)kid->op_type, (UV)kid->op_targ);
4332                 if (kid->op_type != OP_GV) {
4333                     break;
4334                 }
4335
4336                 gv = kGVOP_gv;
4337                 cv = isGV(gv)
4338                     ? GvCV(gv)
4339                     : SvROK(gv) && SvTYPE(SvRV(gv)) == SVt_PVCV
4340                         ? MUTABLE_CV(SvRV(gv))
4341                         : NULL;
4342                 if (!cv)
4343                     break;
4344                 if (CvLVALUE(cv))
4345                     break;
4346                 if (flags & OP_LVALUE_NO_CROAK)
4347                     return NULL;
4348
4349                 namesv = cv_name(cv, NULL, 0);
4350                 yyerror_pv(Perl_form(aTHX_ "Can't modify non-lvalue "
4351                                      "subroutine call of &%" SVf " in %s",
4352                                      SVfARG(namesv), PL_op_desc[type]),
4353                            SvUTF8(namesv));
4354                 goto do_next;
4355             }
4356         }
4357         /* FALLTHROUGH */
4358     default:
4359       nomod:
4360         if (flags & OP_LVALUE_NO_CROAK) return NULL;
4361         /* grep, foreach, subcalls, refgen */
4362         if (S_potential_mod_type(type))
4363             break;
4364         yyerror(Perl_form(aTHX_ "Can't modify %s in %s",
4365                      (o->op_type == OP_NULL && (o->op_flags & OPf_SPECIAL)
4366                       ? "do block"
4367                       : OP_DESC(o)),
4368                      type ? PL_op_desc[type] : "local"));
4369         goto do_next;
4370
4371     case OP_PREINC:
4372     case OP_PREDEC:
4373     case OP_POW:
4374     case OP_MULTIPLY:
4375     case OP_DIVIDE:
4376     case OP_MODULO:
4377     case OP_ADD:
4378     case OP_SUBTRACT:
4379     case OP_CONCAT:
4380     case OP_LEFT_SHIFT:
4381     case OP_RIGHT_SHIFT:
4382     case OP_BIT_AND:
4383     case OP_BIT_XOR:
4384     case OP_BIT_OR:
4385     case OP_I_MULTIPLY:
4386     case OP_I_DIVIDE:
4387     case OP_I_MODULO:
4388     case OP_I_ADD:
4389     case OP_I_SUBTRACT:
4390         if (!(o->op_flags & OPf_STACKED))
4391             goto nomod;
4392         PL_modcount++;
4393         break;
4394
4395     case OP_REPEAT:
4396         if (o->op_flags & OPf_STACKED) {
4397             PL_modcount++;
4398             break;
4399         }
4400         if (!(o->op_private & OPpREPEAT_DOLIST))
4401             goto nomod;
4402         else {
4403             const I32 mods = PL_modcount;
4404             /* we recurse rather than iterate here because we need to
4405              * calculate and use the delta applied to PL_modcount by the
4406              * first child. So in something like
4407              *     ($x, ($y) x 3) = split;
4408              * split knows that 4 elements are wanted
4409              */
4410             modkids(cBINOPo->op_first, type);
4411             if (type != OP_AASSIGN)
4412                 goto nomod;
4413             kid = cBINOPo->op_last;
4414             if (kid->op_type == OP_CONST && SvIOK(kSVOP_sv)) {
4415                 const IV iv = SvIV(kSVOP_sv);
4416                 if (PL_modcount != RETURN_UNLIMITED_NUMBER)
4417                     PL_modcount =
4418                         mods + (PL_modcount - mods) * (iv < 0 ? 0 : iv);
4419             }
4420             else
4421                 PL_modcount = RETURN_UNLIMITED_NUMBER;
4422         }
4423         break;
4424
4425     case OP_COND_EXPR:
4426         localize = 1;
4427         next_kid = OpSIBLING(cUNOPo->op_first);
4428         break;
4429
4430     case OP_RV2AV:
4431     case OP_RV2HV:
4432         if (type == OP_REFGEN && o->op_flags & OPf_PARENS) {
4433            PL_modcount = RETURN_UNLIMITED_NUMBER;
4434            /* Treat \(@foo) like ordinary list, but still mark it as modi-
4435               fiable since some contexts need to know.  */
4436            o->op_flags |= OPf_MOD;
4437            goto do_next;
4438         }
4439         /* FALLTHROUGH */
4440     case OP_RV2GV:
4441         if (scalar_mod_type(o, type))
4442             goto nomod;
4443         ref(cUNOPo->op_first, o->op_type);
4444         /* FALLTHROUGH */
4445     case OP_ASLICE:
4446     case OP_HSLICE:
4447         localize = 1;
4448         /* FALLTHROUGH */
4449     case OP_AASSIGN:
4450         /* Do not apply the lvsub flag for rv2[ah]v in scalar context.  */
4451         if (type == OP_LEAVESUBLV && (
4452                 (o->op_type != OP_RV2AV && o->op_type != OP_RV2HV)
4453              || (o->op_flags & OPf_WANT) != OPf_WANT_SCALAR
4454            ))
4455             o->op_private |= OPpMAYBE_LVSUB;
4456         /* FALLTHROUGH */
4457     case OP_NEXTSTATE:
4458     case OP_DBSTATE:
4459        PL_modcount = RETURN_UNLIMITED_NUMBER;
4460         break;
4461
4462     case OP_KVHSLICE:
4463     case OP_KVASLICE:
4464     case OP_AKEYS:
4465         if (type == OP_LEAVESUBLV)
4466             o->op_private |= OPpMAYBE_LVSUB;
4467         goto nomod;
4468
4469     case OP_AVHVSWITCH:
4470         if (type == OP_LEAVESUBLV
4471          && (o->op_private & OPpAVHVSWITCH_MASK) + OP_EACH == OP_KEYS)
4472             o->op_private |= OPpMAYBE_LVSUB;
4473         goto nomod;
4474
4475     case OP_AV2ARYLEN:
4476         PL_hints |= HINT_BLOCK_SCOPE;
4477         if (type == OP_LEAVESUBLV)
4478             o->op_private |= OPpMAYBE_LVSUB;
4479         PL_modcount++;
4480         break;
4481
4482     case OP_RV2SV:
4483         ref(cUNOPo->op_first, o->op_type);
4484         localize = 1;
4485         /* FALLTHROUGH */
4486     case OP_GV:
4487         PL_hints |= HINT_BLOCK_SCOPE;
4488         /* FALLTHROUGH */
4489     case OP_SASSIGN:
4490     case OP_ANDASSIGN:
4491     case OP_ORASSIGN:
4492     case OP_DORASSIGN:
4493         PL_modcount++;
4494         break;
4495
4496     case OP_AELEMFAST:
4497     case OP_AELEMFAST_LEX:
4498         localize = -1;
4499         PL_modcount++;
4500         break;
4501
4502     case OP_PADAV:
4503     case OP_PADHV:
4504        PL_modcount = RETURN_UNLIMITED_NUMBER;
4505         if (type == OP_REFGEN && o->op_flags & OPf_PARENS)
4506         {
4507            /* Treat \(@foo) like ordinary list, but still mark it as modi-
4508               fiable since some contexts need to know.  */
4509             o->op_flags |= OPf_MOD;
4510             goto do_next;
4511         }
4512         if (scalar_mod_type(o, type))
4513             goto nomod;
4514         if ((o->op_flags & OPf_WANT) != OPf_WANT_SCALAR
4515           && type == OP_LEAVESUBLV)
4516             o->op_private |= OPpMAYBE_LVSUB;
4517         /* FALLTHROUGH */
4518     case OP_PADSV:
4519         PL_modcount++;
4520         if (!type) /* local() */
4521             Perl_croak(aTHX_ "Can't localize lexical variable %" PNf,
4522                               PNfARG(PAD_COMPNAME(o->op_targ)));
4523         if (!(o->op_private & OPpLVAL_INTRO)
4524          || (  type != OP_SASSIGN && type != OP_AASSIGN
4525             && PadnameIsSTATE(PAD_COMPNAME_SV(o->op_targ))  ))
4526             S_mark_padname_lvalue(aTHX_ PAD_COMPNAME_SV(o->op_targ));
4527         break;
4528
4529     case OP_PUSHMARK:
4530         localize = 0;
4531         break;
4532
4533     case OP_KEYS:
4534         if (type != OP_LEAVESUBLV && !scalar_mod_type(NULL, type))
4535             goto nomod;
4536         goto lvalue_func;
4537     case OP_SUBSTR:
4538         if (o->op_private == 4) /* don't allow 4 arg substr as lvalue */
4539             goto nomod;
4540         /* FALLTHROUGH */
4541     case OP_POS:
4542     case OP_VEC:
4543       lvalue_func:
4544         if (type == OP_LEAVESUBLV)
4545             o->op_private |= OPpMAYBE_LVSUB;
4546         if (o->op_flags & OPf_KIDS && OpHAS_SIBLING(cBINOPo->op_first)) {
4547             /* we recurse rather than iterate here because the child
4548              * needs to be processed with a different 'type' parameter */
4549
4550             /* substr and vec */
4551             /* If this op is in merely potential (non-fatal) modifiable
4552                context, then apply OP_ENTERSUB context to
4553                the kid op (to avoid croaking).  Other-
4554                wise pass this op’s own type so the correct op is mentioned
4555                in error messages.  */
4556             op_lvalue(OpSIBLING(cBINOPo->op_first),
4557                       S_potential_mod_type(type)
4558                         ? (I32)OP_ENTERSUB
4559                         : o->op_type);
4560         }
4561         break;
4562
4563     case OP_AELEM:
4564     case OP_HELEM:
4565         ref(cBINOPo->op_first, o->op_type);
4566         if (type == OP_ENTERSUB &&
4567              !(o->op_private & (OPpLVAL_INTRO | OPpDEREF)))
4568             o->op_private |= OPpLVAL_DEFER;
4569         if (type == OP_LEAVESUBLV)
4570             o->op_private |= OPpMAYBE_LVSUB;
4571         localize = 1;
4572         PL_modcount++;
4573         break;
4574
4575     case OP_LEAVE:
4576     case OP_LEAVELOOP:
4577         o->op_private |= OPpLVALUE;
4578         /* FALLTHROUGH */
4579     case OP_SCOPE:
4580     case OP_ENTER:
4581     case OP_LINESEQ:
4582         localize = 0;
4583         if (o->op_flags & OPf_KIDS)
4584             next_kid = cLISTOPo->op_last;
4585         break;
4586
4587     case OP_NULL:
4588         localize = 0;
4589         if (o->op_flags & OPf_SPECIAL)          /* do BLOCK */
4590             goto nomod;
4591         else if (!(o->op_flags & OPf_KIDS))
4592             break;
4593
4594         if (o->op_targ != OP_LIST) {
4595             OP *sib = OpSIBLING(cLISTOPo->op_first);
4596             /* OP_TRANS and OP_TRANSR with argument have a weird optree
4597              * that looks like
4598              *
4599              *   null
4600              *      arg
4601              *      trans
4602              *
4603              * compared with things like OP_MATCH which have the argument
4604              * as a child:
4605              *
4606              *   match
4607              *      arg
4608              *
4609              * so handle specially to correctly get "Can't modify" croaks etc
4610              */
4611
4612             if (sib && (sib->op_type == OP_TRANS || sib->op_type == OP_TRANSR))
4613             {
4614                 /* this should trigger a "Can't modify transliteration" err */
4615                 op_lvalue(sib, type);
4616             }
4617             next_kid = cBINOPo->op_first;
4618             /* we assume OP_NULLs which aren't ex-list have no more than 2
4619              * children. If this assumption is wrong, increase the scan
4620              * limit below */
4621             assert(   !OpHAS_SIBLING(next_kid)
4622                    || !OpHAS_SIBLING(OpSIBLING(next_kid)));
4623             break;
4624         }
4625         /* FALLTHROUGH */
4626     case OP_LIST:
4627         localize = 0;
4628         next_kid = cLISTOPo->op_first;
4629         break;
4630
4631     case OP_COREARGS:
4632         goto do_next;
4633
4634     case OP_AND:
4635     case OP_OR:
4636         if (type == OP_LEAVESUBLV
4637          || !S_vivifies(cLOGOPo->op_first->op_type))
4638             next_kid = cLOGOPo->op_first;
4639         else if (type == OP_LEAVESUBLV
4640          || !S_vivifies(OpSIBLING(cLOGOPo->op_first)->op_type))
4641             next_kid = OpSIBLING(cLOGOPo->op_first);
4642         goto nomod;
4643
4644     case OP_SREFGEN:
4645         if (type == OP_NULL) { /* local */
4646           local_refgen:
4647             if (!FEATURE_MYREF_IS_ENABLED)
4648                 Perl_croak(aTHX_ "The experimental declared_refs "
4649                                  "feature is not enabled");
4650             Perl_ck_warner_d(aTHX_
4651                      packWARN(WARN_EXPERIMENTAL__DECLARED_REFS),
4652                     "Declaring references is experimental");
4653             next_kid = cUNOPo->op_first;
4654             goto do_next;
4655         }
4656         if (type != OP_AASSIGN && type != OP_SASSIGN
4657          && type != OP_ENTERLOOP)
4658             goto nomod;
4659         /* Don’t bother applying lvalue context to the ex-list.  */
4660         kid = cUNOPx(cUNOPo->op_first)->op_first;
4661         assert (!OpHAS_SIBLING(kid));
4662         goto kid_2lvref;
4663     case OP_REFGEN:
4664         if (type == OP_NULL) /* local */
4665             goto local_refgen;
4666         if (type != OP_AASSIGN) goto nomod;
4667         kid = cUNOPo->op_first;
4668       kid_2lvref:
4669         {
4670             const U8 ec = PL_parser ? PL_parser->error_count : 0;
4671             S_lvref(aTHX_ kid, type);
4672             if (!PL_parser || PL_parser->error_count == ec) {
4673                 if (!FEATURE_REFALIASING_IS_ENABLED)
4674                     Perl_croak(aTHX_
4675                        "Experimental aliasing via reference not enabled");
4676                 Perl_ck_warner_d(aTHX_
4677                                  packWARN(WARN_EXPERIMENTAL__REFALIASING),
4678                                 "Aliasing via reference is experimental");
4679             }
4680         }
4681         if (o->op_type == OP_REFGEN)
4682             op_null(cUNOPx(cUNOPo->op_first)->op_first); /* pushmark */
4683         op_null(o);
4684         goto do_next;
4685
4686     case OP_SPLIT:
4687         if ((o->op_private & OPpSPLIT_ASSIGN)) {
4688             /* This is actually @array = split.  */
4689             PL_modcount = RETURN_UNLIMITED_NUMBER;
4690             break;
4691         }
4692         goto nomod;
4693
4694     case OP_SCALAR:
4695         op_lvalue(cUNOPo->op_first, OP_ENTERSUB);
4696         goto nomod;
4697     }
4698
4699     /* [20011101.069 (#7861)] File test operators interpret OPf_REF to mean that
4700        their argument is a filehandle; thus \stat(".") should not set
4701        it. AMS 20011102 */
4702     if (type == OP_REFGEN && OP_IS_STAT(o->op_type))
4703         goto do_next;
4704
4705     if (type != OP_LEAVESUBLV)
4706         o->op_flags |= OPf_MOD;
4707
4708     if (type == OP_AASSIGN || type == OP_SASSIGN)
4709         o->op_flags |= OPf_SPECIAL
4710                       |(o->op_type == OP_ENTERSUB ? 0 : OPf_REF);
4711     else if (!type) { /* local() */
4712         switch (localize) {
4713         case 1:
4714             o->op_private |= OPpLVAL_INTRO;
4715             o->op_flags &= ~OPf_SPECIAL;
4716             PL_hints |= HINT_BLOCK_SCOPE;
4717             break;
4718         case 0:
4719             break;
4720         case -1:
4721             Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX),
4722                            "Useless localization of %s", OP_DESC(o));
4723         }
4724     }
4725     else if (type != OP_GREPSTART && type != OP_ENTERSUB
4726              && type != OP_LEAVESUBLV && o->op_type != OP_ENTERSUB)
4727         o->op_flags |= OPf_REF;
4728
4729   do_next:
4730     while (!next_kid) {
4731         if (o == top_op)
4732             return top_op; /* at top; no parents/siblings to try */
4733         if (OpHAS_SIBLING(o)) {
4734             next_kid = o->op_sibparent;
4735             if (!OpHAS_SIBLING(next_kid)) {
4736                 /* a few node types don't recurse into their second child */
4737                 OP *parent = next_kid->op_sibparent;
4738                 I32 ptype  = parent->op_type;
4739                 if (   (ptype == OP_NULL && parent->op_targ != OP_LIST)
4740                     || (   (ptype == OP_AND || ptype == OP_OR)
4741                         && (type != OP_LEAVESUBLV 
4742                             && S_vivifies(next_kid->op_type))
4743                        )
4744                 )  {
4745                     /*try parent's next sibling */
4746                     o = parent;
4747                     next_kid =  NULL;
4748                 }
4749             }
4750         }
4751         else
4752             o = o->op_sibparent; /*try parent's next sibling */
4753
4754     }
4755     o = next_kid;
4756
4757     } /* while */
4758
4759 }
4760
4761
4762 STATIC bool
4763 S_scalar_mod_type(const OP *o, I32 type)
4764 {
4765     switch (type) {
4766     case OP_POS:
4767     case OP_SASSIGN:
4768         if (o && o->op_type == OP_RV2GV)
4769             return FALSE;
4770         /* FALLTHROUGH */
4771     case OP_PREINC:
4772     case OP_PREDEC:
4773     case OP_POSTINC:
4774     case OP_POSTDEC:
4775     case OP_I_PREINC:
4776     case OP_I_PREDEC:
4777     case OP_I_POSTINC:
4778     case OP_I_POSTDEC:
4779     case OP_POW:
4780     case OP_MULTIPLY:
4781     case OP_DIVIDE:
4782     case OP_MODULO:
4783     case OP_REPEAT:
4784     case OP_ADD:
4785     case OP_SUBTRACT:
4786     case OP_I_MULTIPLY:
4787     case OP_I_DIVIDE:
4788     case OP_I_MODULO:
4789     case OP_I_ADD:
4790     case OP_I_SUBTRACT:
4791     case OP_LEFT_SHIFT:
4792     case OP_RIGHT_SHIFT:
4793     case OP_BIT_AND:
4794     case OP_BIT_XOR:
4795     case OP_BIT_OR:
4796     case OP_NBIT_AND:
4797     case OP_NBIT_XOR:
4798     case OP_NBIT_OR:
4799     case OP_SBIT_AND:
4800     case OP_SBIT_XOR:
4801     case OP_SBIT_OR:
4802     case OP_CONCAT:
4803     case OP_SUBST:
4804     case OP_TRANS:
4805     case OP_TRANSR:
4806     case OP_READ:
4807     case OP_SYSREAD:
4808     case OP_RECV:
4809     case OP_ANDASSIGN:
4810     case OP_ORASSIGN:
4811     case OP_DORASSIGN:
4812     case OP_VEC:
4813     case OP_SUBSTR:
4814         return TRUE;
4815     default:
4816         return FALSE;
4817     }
4818 }
4819
4820 STATIC bool
4821 S_is_handle_constructor(const OP *o, I32 numargs)
4822 {
4823     PERL_ARGS_ASSERT_IS_HANDLE_CONSTRUCTOR;
4824
4825     switch (o->op_type) {
4826     case OP_PIPE_OP:
4827     case OP_SOCKPAIR:
4828         if (numargs == 2)
4829             return TRUE;
4830         /* FALLTHROUGH */
4831     case OP_SYSOPEN:
4832     case OP_OPEN:
4833     case OP_SELECT:             /* XXX c.f. SelectSaver.pm */
4834     case OP_SOCKET:
4835     case OP_OPEN_DIR:
4836     case OP_ACCEPT:
4837         if (numargs == 1)
4838             return TRUE;
4839         /* FALLTHROUGH */
4840     default:
4841         return FALSE;
4842     }
4843 }
4844
4845 static OP *
4846 S_refkids(pTHX_ OP *o, I32 type)
4847 {
4848     if (o && o->op_flags & OPf_KIDS) {
4849         OP *kid;
4850         for (kid = cLISTOPo->op_first; kid; kid = OpSIBLING(kid))
4851             ref(kid, type);
4852     }
4853     return o;
4854 }
4855
4856
4857 /* Apply reference (autovivification) context to the subtree at o.
4858  * For example in
4859  *     push @{expression}, ....;
4860  * o will be the head of 'expression' and type will be OP_RV2AV.
4861  * It marks the op o (or a suitable child) as autovivifying, e.g. by
4862  * setting  OPf_MOD.
4863  * For OP_RV2AV/OP_PADAV and OP_RV2HV/OP_PADHV sets OPf_REF too if
4864  * set_op_ref is true.
4865  *
4866  * Also calls scalar(o).
4867  */
4868
4869 OP *
4870 Perl_doref(pTHX_ OP *o, I32 type, bool set_op_ref)
4871 {
4872     OP * top_op = o;
4873
4874     PERL_ARGS_ASSERT_DOREF;
4875
4876     if (PL_parser && PL_parser->error_count)
4877         return o;
4878
4879     while (1) {
4880         switch (o->op_type) {
4881         case OP_ENTERSUB:
4882             if ((type == OP_EXISTS || type == OP_DEFINED) &&
4883                 !(o->op_flags & OPf_STACKED)) {
4884                 OpTYPE_set(o, OP_RV2CV);             /* entersub => rv2cv */
4885                 assert(cUNOPo->op_first->op_type == OP_NULL);
4886                 /* disable pushmark */
4887                 op_null(((LISTOP*)cUNOPo->op_first)->op_first);
4888                 o->op_flags |= OPf_SPECIAL;
4889             }
4890             else if (type == OP_RV2SV || type == OP_RV2AV || type == OP_RV2HV){
4891                 o->op_private |= (type == OP_RV2AV ? OPpDEREF_AV
4892                                   : type == OP_RV2HV ? OPpDEREF_HV
4893                                   : OPpDEREF_SV);
4894                 o->op_flags |= OPf_MOD;
4895             }
4896
4897             break;
4898
4899         case OP_COND_EXPR:
4900             o = OpSIBLING(cUNOPo->op_first);
4901             continue;
4902
4903         case OP_RV2SV:
4904             if (type == OP_DEFINED)
4905                 o->op_flags |= OPf_SPECIAL;             /* don't create GV */
4906             /* FALLTHROUGH */
4907         case OP_PADSV:
4908             if (type == OP_RV2SV || type == OP_RV2AV || type == OP_RV2HV) {
4909                 o->op_private |= (type == OP_RV2AV ? OPpDEREF_AV
4910                                   : type == OP_RV2HV ? OPpDEREF_HV
4911                                   : OPpDEREF_SV);
4912                 o->op_flags |= OPf_MOD;
4913             }
4914             if (o->op_flags & OPf_KIDS) {
4915                 type = o->op_type;
4916                 o = cUNOPo->op_first;
4917                 continue;
4918             }
4919             break;
4920
4921         case OP_RV2AV:
4922         case OP_RV2HV:
4923             if (set_op_ref)
4924                 o->op_flags |= OPf_REF;
4925             /* FALLTHROUGH */
4926         case OP_RV2GV:
4927             if (type == OP_DEFINED)
4928                 o->op_flags |= OPf_SPECIAL;             /* don't create GV */
4929             type = o->op_type;
4930             o = cUNOPo->op_first;
4931             continue;
4932
4933         case OP_PADAV:
4934         case OP_PADHV:
4935             if (set_op_ref)
4936                 o->op_flags |= OPf_REF;
4937             break;
4938
4939         case OP_SCALAR:
4940         case OP_NULL:
4941             if (!(o->op_flags & OPf_KIDS) || type == OP_DEFINED)
4942                 break;
4943              o = cBINOPo->op_first;
4944             continue;
4945
4946         case OP_AELEM:
4947         case OP_HELEM:
4948             if (type == OP_RV2SV || type == OP_RV2AV || type == OP_RV2HV) {
4949                 o->op_private |= (type == OP_RV2AV ? OPpDEREF_AV
4950                                   : type == OP_RV2HV ? OPpDEREF_HV
4951                                   : OPpDEREF_SV);
4952                 o->op_flags |= OPf_MOD;
4953             }
4954             type = o->op_type;
4955             o = cBINOPo->op_first;
4956             continue;;
4957
4958         case OP_SCOPE:
4959         case OP_LEAVE:
4960             set_op_ref = FALSE;
4961             /* FALLTHROUGH */
4962         case OP_ENTER:
4963         case OP_LIST:
4964             if (!(o->op_flags & OPf_KIDS))
4965                 break;
4966             o = cLISTOPo->op_last;
4967             continue;
4968
4969         default:
4970             break;
4971         } /* switch */
4972
4973         while (1) {
4974             if (o == top_op)
4975                 return scalar(top_op); /* at top; no parents/siblings to try */
4976             if (OpHAS_SIBLING(o)) {
4977                 o = o->op_sibparent;
4978                 /* Normally skip all siblings and go straight to the parent;
4979                  * the only op that requires two children to be processed
4980                  * is OP_COND_EXPR */
4981                 if (!OpHAS_SIBLING(o)
4982                         && o->op_sibparent->op_type == OP_COND_EXPR)
4983                     break;
4984                 continue;
4985             }
4986             o = o->op_sibparent; /*try parent's next sibling */
4987         }
4988     } /* while */
4989 }
4990
4991
4992 STATIC OP *
4993 S_dup_attrlist(pTHX_ OP *o)
4994 {
4995     OP *rop;
4996
4997     PERL_ARGS_ASSERT_DUP_ATTRLIST;
4998
4999     /* An attrlist is either a simple OP_CONST or an OP_LIST with kids,
5000      * where the first kid is OP_PUSHMARK and the remaining ones
5001      * are OP_CONST.  We need to push the OP_CONST values.
5002      */
5003     if (o->op_type == OP_CONST)
5004         rop = newSVOP(OP_CONST, o->op_flags, SvREFCNT_inc_NN(cSVOPo->op_sv));
5005     else {
5006         assert((o->op_type == OP_LIST) && (o->op_flags & OPf_KIDS));
5007         rop = NULL;
5008         for (o = cLISTOPo->op_first; o; o = OpSIBLING(o)) {
5009             if (o->op_type == OP_CONST)
5010                 rop = op_append_elem(OP_LIST, rop,
5011                                   newSVOP(OP_CONST, o->op_flags,
5012                                           SvREFCNT_inc_NN(cSVOPo->op_sv)));
5013         }
5014     }
5015     return rop;
5016 }
5017
5018 STATIC void
5019 S_apply_attrs(pTHX_ HV *stash, SV *target, OP *attrs)
5020 {
5021     PERL_ARGS_ASSERT_APPLY_ATTRS;
5022     {
5023         SV * const stashsv = newSVhek(HvNAME_HEK(stash));
5024
5025         /* fake up C<use attributes $pkg,$rv,@attrs> */
5026
5027 #define ATTRSMODULE "attributes"
5028 #define ATTRSMODULE_PM "attributes.pm"
5029
5030         Perl_load_module(
5031           aTHX_ PERL_LOADMOD_IMPORT_OPS,
5032           newSVpvs(ATTRSMODULE),
5033           NULL,
5034           op_prepend_elem(OP_LIST,
5035                           newSVOP(OP_CONST, 0, stashsv),
5036                           op_prepend_elem(OP_LIST,
5037                                           newSVOP(OP_CONST, 0,
5038                                                   newRV(target)),
5039                                           dup_attrlist(attrs))));
5040     }
5041 }
5042
5043 STATIC void
5044 S_apply_attrs_my(pTHX_ HV *stash, OP *target, OP *attrs, OP **imopsp)
5045 {
5046     OP *pack, *imop, *arg;
5047     SV *meth, *stashsv, **svp;
5048
5049     PERL_ARGS_ASSERT_APPLY_ATTRS_MY;
5050
5051     if (!attrs)
5052         return;
5053
5054     assert(target->op_type == OP_PADSV ||
5055            target->op_type == OP_PADHV ||
5056            target->op_type == OP_PADAV);
5057
5058     /* Ensure that attributes.pm is loaded. */
5059     /* Don't force the C<use> if we don't need it. */
5060     svp = hv_fetchs(GvHVn(PL_incgv), ATTRSMODULE_PM, FALSE);
5061     if (svp && *svp != &PL_sv_undef)
5062         NOOP;   /* already in %INC */
5063     else
5064         Perl_load_module(aTHX_ PERL_LOADMOD_NOIMPORT,
5065                                newSVpvs(ATTRSMODULE), NULL);
5066
5067     /* Need package name for method call. */
5068     pack = newSVOP(OP_CONST, 0, newSVpvs(ATTRSMODULE));
5069
5070     /* Build up the real arg-list. */
5071     stashsv = newSVhek(HvNAME_HEK(stash));
5072
5073     arg = newOP(OP_PADSV, 0);
5074     arg->op_targ = target->op_targ;
5075     arg = op_prepend_elem(OP_LIST,
5076                        newSVOP(OP_CONST, 0, stashsv),
5077                        op_prepend_elem(OP_LIST,
5078                                     newUNOP(OP_REFGEN, 0,
5079                                             arg),
5080                                     dup_attrlist(attrs)));
5081
5082     /* Fake up a method call to import */
5083     meth = newSVpvs_share("import");
5084     imop = op_convert_list(OP_ENTERSUB, OPf_STACKED|OPf_SPECIAL|OPf_WANT_VOID,
5085                    op_append_elem(OP_LIST,
5086                                op_prepend_elem(OP_LIST, pack, arg),
5087                                newMETHOP_named(OP_METHOD_NAMED, 0, meth)));
5088
5089     /* Combine the ops. */
5090     *imopsp = op_append_elem(OP_LIST, *imopsp, imop);
5091 }
5092
5093 /*
5094 =notfor apidoc apply_attrs_string
5095
5096 Attempts to apply a list of attributes specified by the C<attrstr> and
5097 C<len> arguments to the subroutine identified by the C<cv> argument which
5098 is expected to be associated with the package identified by the C<stashpv>
5099 argument (see L<attributes>).  It gets this wrong, though, in that it
5100 does not correctly identify the boundaries of the individual attribute
5101 specifications within C<attrstr>.  This is not really intended for the
5102 public API, but has to be listed here for systems such as AIX which
5103 need an explicit export list for symbols.  (It's called from XS code
5104 in support of the C<ATTRS:> keyword from F<xsubpp>.)  Patches to fix it
5105 to respect attribute syntax properly would be welcome.
5106
5107 =cut
5108 */
5109
5110 void
5111 Perl_apply_attrs_string(pTHX_ const char *stashpv, CV *cv,
5112                         const char *attrstr, STRLEN len)
5113 {
5114     OP *attrs = NULL;
5115
5116     PERL_ARGS_ASSERT_APPLY_ATTRS_STRING;
5117
5118     if (!len) {
5119         len = strlen(attrstr);
5120     }
5121
5122     while (len) {
5123         for (; isSPACE(*attrstr) && len; --len, ++attrstr) ;
5124         if (len) {
5125             const char * const sstr = attrstr;
5126             for (; !isSPACE(*attrstr) && len; --len, ++attrstr) ;
5127             attrs = op_append_elem(OP_LIST, attrs,
5128                                 newSVOP(OP_CONST, 0,
5129                                         newSVpvn(sstr, attrstr-sstr)));
5130         }
5131     }
5132
5133     Perl_load_module(aTHX_ PERL_LOADMOD_IMPORT_OPS,
5134                      newSVpvs(ATTRSMODULE),
5135                      NULL, op_prepend_elem(OP_LIST,
5136                                   newSVOP(OP_CONST, 0, newSVpv(stashpv,0)),
5137                                   op_prepend_elem(OP_LIST,
5138                                                newSVOP(OP_CONST, 0,
5139                                                        newRV(MUTABLE_SV(cv))),
5140                                                attrs)));
5141 }
5142
5143 STATIC void
5144 S_move_proto_attr(pTHX_ OP **proto, OP **attrs, const GV * name,
5145                         bool curstash)
5146 {
5147     OP *new_proto = NULL;
5148     STRLEN pvlen;
5149     char *pv;
5150     OP *o;
5151
5152     PERL_ARGS_ASSERT_MOVE_PROTO_ATTR;
5153
5154     if (!*attrs)
5155         return;
5156
5157     o = *attrs;
5158     if (o->op_type == OP_CONST) {
5159         pv = SvPV(cSVOPo_sv, pvlen);
5160         if (memBEGINs(pv, pvlen, "prototype(")) {
5161             SV * const tmpsv = newSVpvn_flags(pv + 10, pvlen - 11, SvUTF8(cSVOPo_sv));
5162             SV ** const tmpo = cSVOPx_svp(o);
5163             SvREFCNT_dec(cSVOPo_sv);
5164             *tmpo = tmpsv;
5165             new_proto = o;
5166             *attrs = NULL;
5167         }
5168     } else if (o->op_type == OP_LIST) {
5169         OP * lasto;
5170         assert(o->op_flags & OPf_KIDS);
5171         lasto = cLISTOPo->op_first;
5172         assert(lasto->op_type == OP_PUSHMARK);
5173         for (o = OpSIBLING(lasto); o; o = OpSIBLING(o)) {
5174             if (o->op_type == OP_CONST) {
5175                 pv = SvPV(cSVOPo_sv, pvlen);
5176                 if (memBEGINs(pv, pvlen, "prototype(")) {
5177                     SV * const tmpsv = newSVpvn_flags(pv + 10, pvlen - 11, SvUTF8(cSVOPo_sv));
5178                     SV ** const tmpo = cSVOPx_svp(o);
5179                     SvREFCNT_dec(cSVOPo_sv);
5180                     *tmpo = tmpsv;
5181                     if (new_proto && ckWARN(WARN_MISC)) {
5182                         STRLEN new_len;
5183                         const char * newp = SvPV(cSVOPo_sv, new_len);
5184                         Perl_warner(aTHX_ packWARN(WARN_MISC),
5185                             "Attribute prototype(%" UTF8f ") discards earlier prototype attribute in same sub",
5186                             UTF8fARG(SvUTF8(cSVOPo_sv), new_len, newp));
5187                         op_free(new_proto);
5188                     }
5189                     else if (new_proto)
5190                         op_free(new_proto);
5191                     new_proto = o;
5192                     /* excise new_proto from the list */
5193                     op_sibling_splice(*attrs, lasto, 1, NULL);
5194                     o = lasto;
5195                     continue;
5196                 }
5197             }
5198             lasto = o;
5199         }
5200         /* If the list is now just the PUSHMARK, scrap the whole thing; otherwise attributes.xs
5201            would get pulled in with no real need */
5202         if (!OpHAS_SIBLING(cLISTOPx(*attrs)->op_first)) {
5203             op_free(*attrs);
5204             *attrs = NULL;
5205         }
5206     }
5207
5208     if (new_proto) {
5209         SV *svname;
5210         if (isGV(name)) {
5211             svname = sv_newmortal();
5212             gv_efullname3(svname, name, NULL);
5213         }
5214         else if (SvPOK(name) && *SvPVX((SV *)name) == '&')
5215             svname = newSVpvn_flags(SvPVX((SV *)name)+1, SvCUR(name)-1, SvUTF8(name)|SVs_TEMP);
5216         else
5217             svname = (SV *)name;
5218         if (ckWARN(WARN_ILLEGALPROTO))
5219             (void)validate_proto(svname, cSVOPx_sv(new_proto), TRUE,
5220                                  curstash);
5221         if (*proto && ckWARN(WARN_PROTOTYPE)) {
5222             STRLEN old_len, new_len;
5223             const char * oldp = SvPV(cSVOPx_sv(*proto), old_len);
5224             const char * newp = SvPV(cSVOPx_sv(new_proto), new_len);
5225
5226             if (curstash && svname == (SV *)name
5227              && !memchr(SvPVX(svname), ':', SvCUR(svname))) {
5228                 svname = sv_2mortal(newSVsv(PL_curstname));
5229                 sv_catpvs(svname, "::");
5230                 sv_catsv(svname, (SV *)name);
5231             }
5232
5233             Perl_warner(aTHX_ packWARN(WARN_PROTOTYPE),
5234                 "Prototype '%" UTF8f "' overridden by attribute 'prototype(%" UTF8f ")'"
5235                 " in %" SVf,
5236                 UTF8fARG(SvUTF8(cSVOPx_sv(*proto)), old_len, oldp),
5237                 UTF8fARG(SvUTF8(cSVOPx_sv(new_proto)), new_len, newp),
5238                 SVfARG(svname));
5239         }
5240         if (*proto)
5241             op_free(*proto);
5242         *proto = new_proto;
5243     }
5244 }
5245
5246 static void
5247 S_cant_declare(pTHX_ OP *o)
5248 {
5249     if (o->op_type == OP_NULL
5250      && (o->op_flags & (OPf_SPECIAL|OPf_KIDS)) == OPf_KIDS)
5251         o = cUNOPo->op_first;
5252     yyerror(Perl_form(aTHX_ "Can't declare %s in \"%s\"",
5253                              o->op_type == OP_NULL
5254                                && o->op_flags & OPf_SPECIAL
5255                                  ? "do block"
5256                                  : OP_DESC(o),
5257                              PL_parser->in_my == KEY_our   ? "our"   :
5258                              PL_parser->in_my == KEY_state ? "state" :
5259                                                              "my"));
5260 }
5261
5262 STATIC OP *
5263 S_my_kid(pTHX_ OP *o, OP *attrs, OP **imopsp)
5264 {
5265     I32 type;
5266     const bool stately = PL_parser && PL_parser->in_my == KEY_state;
5267
5268     PERL_ARGS_ASSERT_MY_KID;
5269
5270     if (!o || (PL_parser && PL_parser->error_count))
5271         return o;
5272
5273     type = o->op_type;
5274
5275     if (OP_TYPE_IS_OR_WAS(o, OP_LIST)) {
5276         OP *kid;
5277         for (kid = cLISTOPo->op_first; kid; kid = OpSIBLING(kid))
5278             my_kid(kid, attrs, imopsp);
5279         return o;
5280     } else if (type == OP_UNDEF || type == OP_STUB) {
5281         return o;
5282     } else if (type == OP_RV2SV ||      /* "our" declaration */
5283                type == OP_RV2AV ||
5284                type == OP_RV2HV) {
5285         if (cUNOPo->op_first->op_type != OP_GV) { /* MJD 20011224 */
5286             S_cant_declare(aTHX_ o);
5287         } else if (attrs) {
5288             GV * const gv = cGVOPx_gv(cUNOPo->op_first);
5289             assert(PL_parser);
5290             PL_parser->in_my = FALSE;
5291             PL_parser->in_my_stash = NULL;
5292             apply_attrs(GvSTASH(gv),
5293                         (type == OP_RV2SV ? GvSVn(gv) :
5294                          type == OP_RV2AV ? MUTABLE_SV(GvAVn(gv)) :
5295                          type == OP_RV2HV ? MUTABLE_SV(GvHVn(gv)) : MUTABLE_SV(gv)),
5296                         attrs);
5297         }
5298         o->op_private |= OPpOUR_INTRO;
5299         return o;
5300     }
5301     else if (type == OP_REFGEN || type == OP_SREFGEN) {
5302         if (!FEATURE_MYREF_IS_ENABLED)
5303             Perl_croak(aTHX_ "The experimental declared_refs "
5304                              "feature is not enabled");
5305         Perl_ck_warner_d(aTHX_
5306              packWARN(WARN_EXPERIMENTAL__DECLARED_REFS),
5307             "Declaring references is experimental");
5308         /* Kid is a nulled OP_LIST, handled above.  */
5309         my_kid(cUNOPo->op_first, attrs, imopsp);
5310         return o;
5311     }
5312     else if (type != OP_PADSV &&
5313              type != OP_PADAV &&
5314              type != OP_PADHV &&
5315              type != OP_PUSHMARK)
5316     {
5317         S_cant_declare(aTHX_ o);
5318         return o;
5319     }
5320     else if (attrs && type != OP_PUSHMARK) {
5321         HV *stash;
5322
5323         assert(PL_parser);
5324         PL_parser->in_my = FALSE;
5325         PL_parser->in_my_stash = NULL;
5326
5327         /* check for C<my Dog $spot> when deciding package */
5328         stash = PAD_COMPNAME_TYPE(o->op_targ);
5329         if (!stash)
5330             stash = PL_curstash;
5331         apply_attrs_my(stash, o, attrs, imopsp);
5332     }
5333     o->op_flags |= OPf_MOD;
5334     o->op_private |= OPpLVAL_INTRO;
5335     if (stately)
5336         o->op_private |= OPpPAD_STATE;
5337     return o;
5338 }
5339
5340 OP *
5341 Perl_my_attrs(pTHX_ OP *o, OP *attrs)
5342 {
5343     OP *rops;
5344     int maybe_scalar = 0;
5345
5346     PERL_ARGS_ASSERT_MY_ATTRS;
5347
5348 /* [perl #17376]: this appears to be premature, and results in code such as
5349    C< our(%x); > executing in list mode rather than void mode */
5350 #if 0
5351     if (o->op_flags & OPf_PARENS)
5352         list(o);
5353     else
5354         maybe_scalar = 1;
5355 #else
5356     maybe_scalar = 1;
5357 #endif
5358     if (attrs)
5359         SAVEFREEOP(attrs);
5360     rops = NULL;
5361     o = my_kid(o, attrs, &rops);
5362     if (rops) {
5363         if (maybe_scalar && o->op_type == OP_PADSV) {
5364             o = scalar(op_append_list(OP_LIST, rops, o));
5365             o->op_private |= OPpLVAL_INTRO;
5366         }
5367         else {
5368             /* The listop in rops might have a pushmark at the beginning,
5369                which will mess up list assignment. */
5370             LISTOP * const lrops = (LISTOP *)rops; /* for brevity */
5371             if (rops->op_type == OP_LIST &&
5372                 lrops->op_first && lrops->op_first->op_type == OP_PUSHMARK)
5373             {
5374                 OP * const pushmark = lrops->op_first;
5375                 /* excise pushmark */
5376                 op_sibling_splice(rops, NULL, 1, NULL);
5377                 op_free(pushmark);
5378             }
5379             o = op_append_list(OP_LIST, o, rops);
5380         }
5381     }
5382     PL_parser->in_my = FALSE;
5383     PL_parser->in_my_stash = NULL;
5384     return o;
5385 }
5386
5387 OP *
5388 Perl_sawparens(pTHX_ OP *o)
5389 {
5390     PERL_UNUSED_CONTEXT;
5391     if (o)
5392         o->op_flags |= OPf_PARENS;
5393     return o;
5394 }
5395
5396 OP *
5397 Perl_bind_match(pTHX_ I32 type, OP *left, OP *right)
5398 {
5399     OP *o;
5400     bool ismatchop = 0;
5401     const OPCODE ltype = left->op_type;
5402     const OPCODE rtype = right->op_type;
5403
5404     PERL_ARGS_ASSERT_BIND_MATCH;
5405
5406     if ( (ltype == OP_RV2AV || ltype == OP_RV2HV || ltype == OP_PADAV
5407           || ltype == OP_PADHV) && ckWARN(WARN_MISC))
5408     {
5409       const char * const desc
5410           = PL_op_desc[(
5411                           rtype == OP_SUBST || rtype == OP_TRANS
5412                        || rtype == OP_TRANSR
5413                        )
5414                        ? (int)rtype : OP_MATCH];
5415       const bool isary = ltype == OP_RV2AV || ltype == OP_PADAV;
5416       SV * const name =
5417         S_op_varname(aTHX_ left);
5418       if (name)
5419         Perl_warner(aTHX_ packWARN(WARN_MISC),
5420              "Applying %s to %" SVf " will act on scalar(%" SVf ")",
5421              desc, SVfARG(name), SVfARG(name));
5422       else {
5423         const char * const sample = (isary
5424              ? "@array" : "%hash");
5425         Perl_warner(aTHX_ packWARN(WARN_MISC),
5426              "Applying %s to %s will act on scalar(%s)",
5427              desc, sample, sample);
5428       }
5429     }
5430
5431     if (rtype == OP_CONST &&
5432         cSVOPx(right)->op_private & OPpCONST_BARE &&
5433         cSVOPx(right)->op_private & OPpCONST_STRICT)
5434     {
5435         no_bareword_allowed(right);
5436     }
5437
5438     /* !~ doesn't make sense with /r, so error on it for now */
5439     if (rtype == OP_SUBST && (cPMOPx(right)->op_pmflags & PMf_NONDESTRUCT) &&
5440         type == OP_NOT)
5441         /* diag_listed_as: Using !~ with %s doesn't make sense */
5442         yyerror("Using !~ with s///r doesn't make sense");
5443     if (rtype == OP_TRANSR && type == OP_NOT)
5444         /* diag_listed_as: Using !~ with %s doesn't make sense */
5445         yyerror("Using !~ with tr///r doesn't make sense");
5446
5447     ismatchop = (rtype == OP_MATCH ||
5448                  rtype == OP_SUBST ||
5449                  rtype == OP_TRANS || rtype == OP_TRANSR)
5450              && !(right->op_flags & OPf_SPECIAL);
5451     if (ismatchop && right->op_private & OPpTARGET_MY) {
5452         right->op_targ = 0;
5453         right->op_private &= ~OPpTARGET_MY;
5454     }
5455     if (!(right->op_flags & OPf_STACKED) && !right->op_targ && ismatchop) {
5456         if (left->op_type == OP_PADSV
5457          && !(left->op_private & OPpLVAL_INTRO))
5458         {
5459             right->op_targ = left->op_targ;
5460             op_free(left);
5461             o = right;
5462         }
5463         else {
5464             right->op_flags |= OPf_STACKED;
5465             if (rtype != OP_MATCH && rtype != OP_TRANSR &&
5466             ! (rtype == OP_TRANS &&
5467                right->op_private & OPpTRANS_IDENTICAL) &&
5468             ! (rtype == OP_SUBST &&
5469                (cPMOPx(right)->op_pmflags & PMf_NONDESTRUCT)))
5470                 left = op_lvalue(left, rtype);
5471             if (right->op_type == OP_TRANS || right->op_type == OP_TRANSR)
5472                 o = newBINOP(OP_NULL, OPf_STACKED, scalar(left), right);
5473             else
5474                 o = op_prepend_elem(rtype, scalar(left), right);
5475         }
5476         if (type == OP_NOT)
5477             return newUNOP(OP_NOT, 0, scalar(o));
5478         return o;
5479     }
5480     else
5481         return bind_match(type, left,
5482                 pmruntime(newPMOP(OP_MATCH, 0), right, NULL, 0, 0));
5483 }
5484
5485 OP *
5486 Perl_invert(pTHX_ OP *o)
5487 {
5488     if (!o)
5489         return NULL;
5490     return newUNOP(OP_NOT, OPf_SPECIAL, scalar(o));
5491 }
5492
5493 OP *
5494 Perl_cmpchain_start(pTHX_ I32 type, OP *left, OP *right)
5495 {
5496     BINOP *bop;
5497     OP *op;
5498
5499     if (!left)
5500         left = newOP(OP_NULL, 0);
5501     if (!right)
5502         right = newOP(OP_NULL, 0);
5503     scalar(left);
5504     scalar(right);
5505     NewOp(0, bop, 1, BINOP);
5506     op = (OP*)bop;
5507     ASSUME((PL_opargs[type] & OA_CLASS_MASK) == OA_BINOP);
5508     OpTYPE_set(op, type);
5509     cBINOPx(op)->op_flags = OPf_KIDS;
5510     cBINOPx(op)->op_private = 2;
5511     cBINOPx(op)->op_first = left;
5512     cBINOPx(op)->op_last = right;
5513     OpMORESIB_set(left, right);
5514     OpLASTSIB_set(right, op);
5515     return op;
5516 }
5517
5518 OP *
5519 Perl_cmpchain_extend(pTHX_ I32 type, OP *ch, OP *right)
5520 {
5521     BINOP *bop;
5522     OP *op;
5523
5524     PERL_ARGS_ASSERT_CMPCHAIN_EXTEND;
5525     if (!right)
5526         right = newOP(OP_NULL, 0);
5527     scalar(right);
5528     NewOp(0, bop, 1, BINOP);
5529     op = (OP*)bop;
5530     ASSUME((PL_opargs[type] & OA_CLASS_MASK) == OA_BINOP);
5531     OpTYPE_set(op, type);
5532     if (ch->op_type != OP_NULL) {
5533         UNOP *lch;
5534         OP *nch, *cleft, *cright;
5535         NewOp(0, lch, 1, UNOP);
5536         nch = (OP*)lch;
5537         OpTYPE_set(nch, OP_NULL);
5538         nch->op_flags = OPf_KIDS;
5539         cleft = cBINOPx(ch)->op_first;
5540         cright = cBINOPx(ch)->op_last;
5541         cBINOPx(ch)->op_first = NULL;
5542         cBINOPx(ch)->op_last = NULL;
5543         cBINOPx(ch)->op_private = 0;
5544         cBINOPx(ch)->op_flags = 0;
5545         cUNOPx(nch)->op_first = cright;
5546         OpMORESIB_set(cright, ch);
5547         OpMORESIB_set(ch, cleft);
5548         OpLASTSIB_set(cleft, nch);
5549         ch = nch;
5550     }
5551     OpMORESIB_set(right, op);
5552     OpMORESIB_set(op, cUNOPx(ch)->op_first);
5553     cUNOPx(ch)->op_first = right;
5554     return ch;
5555 }
5556
5557 OP *
5558 Perl_cmpchain_finish(pTHX_ OP *ch)
5559 {
5560
5561     PERL_ARGS_ASSERT_CMPCHAIN_FINISH;
5562     if (ch->op_type != OP_NULL) {
5563         OPCODE cmpoptype = ch->op_type;
5564         ch = CHECKOP(cmpoptype, ch);
5565         if(!ch->op_next && ch->op_type == cmpoptype)
5566             ch = fold_constants(op_integerize(op_std_init(ch)));
5567         return ch;
5568     } else {
5569         OP *condop = NULL;
5570         OP *rightarg = cUNOPx(ch)->op_first;
5571         cUNOPx(ch)->op_first = OpSIBLING(rightarg);
5572         OpLASTSIB_set(rightarg, NULL);
5573         while (1) {
5574             OP *cmpop = cUNOPx(ch)->op_first;
5575             OP *leftarg = OpSIBLING(cmpop);
5576             OPCODE cmpoptype = cmpop->op_type;
5577             OP *nextrightarg;
5578             bool is_last;
5579             is_last = !(cUNOPx(ch)->op_first = OpSIBLING(leftarg));
5580             OpLASTSIB_set(cmpop, NULL);
5581             OpLASTSIB_set(leftarg, NULL);
5582             if (is_last) {
5583                 ch->op_flags = 0;
5584                 op_free(ch);
5585                 nextrightarg = NULL;
5586             } else {
5587                 nextrightarg = newUNOP(OP_CMPCHAIN_DUP, 0, leftarg);
5588                 leftarg = newOP(OP_NULL, 0);
5589             }
5590             cBINOPx(cmpop)->op_first = leftarg;
5591             cBINOPx(cmpop)->op_last = rightarg;
5592             OpMORESIB_set(leftarg, rightarg);
5593             OpLASTSIB_set(rightarg, cmpop);
5594             cmpop->op_flags = OPf_KIDS;
5595             cmpop->op_private = 2;
5596             cmpop = CHECKOP(cmpoptype, cmpop);
5597             if(!cmpop->op_next && cmpop->op_type == cmpoptype)
5598                 cmpop = fold_constants(op_integerize(op_std_init(cmpop)));
5599             condop = condop ? newLOGOP(OP_CMPCHAIN_AND, 0, cmpop, condop) :
5600                         cmpop;
5601             if (!nextrightarg)
5602                 return condop;
5603             rightarg = nextrightarg;
5604         }
5605     }
5606 }
5607
5608 /*
5609 =for apidoc op_scope
5610
5611 Wraps up an op tree with some additional ops so that at runtime a dynamic
5612 scope will be created.  The original ops run in the new dynamic scope,
5613 and then, provided that they exit normally, the scope will be unwound.
5614 The additional ops used to create and unwind the dynamic scope will
5615 normally be an C<enter>/C<leave> pair, but a C<scope> op may be used
5616 instead if the ops are simple enough to not need the full dynamic scope
5617 structure.
5618
5619 =cut
5620 */
5621
5622 OP *
5623 Perl_op_scope(pTHX_ OP *o)
5624 {
5625     if (o) {
5626         if (o->op_flags & OPf_PARENS || PERLDB_NOOPT || TAINTING_get) {
5627             o = op_prepend_elem(OP_LINESEQ,
5628                     newOP(OP_ENTER, (o->op_flags & OPf_WANT)), o);
5629             OpTYPE_set(o, OP_LEAVE);
5630         }
5631         else if (o->op_type == OP_LINESEQ) {
5632             OP *kid;
5633             OpTYPE_set(o, OP_SCOPE);
5634             kid = ((LISTOP*)o)->op_first;
5635             if (kid->op_type == OP_NEXTSTATE || kid->op_type == OP_DBSTATE) {
5636                 op_null(kid);
5637
5638                 /* The following deals with things like 'do {1 for 1}' */
5639                 kid = OpSIBLING(kid);
5640                 if (kid &&
5641                     (kid->op_type == OP_NEXTSTATE || kid->op_type == OP_DBSTATE))
5642                     op_null(kid);
5643             }
5644         }
5645         else
5646             o = newLISTOP(OP_SCOPE, 0, o, NULL);
5647     }
5648     return o;
5649 }
5650
5651 OP *
5652 Perl_op_unscope(pTHX_ OP *o)
5653 {
5654     if (o && o->op_type == OP_LINESEQ) {
5655         OP *kid = cLISTOPo->op_first;
5656         for(; kid; kid = OpSIBLING(kid))
5657             if (kid->op_type == OP_NEXTSTATE || kid->op_type == OP_DBSTATE)
5658                 op_null(kid);
5659     }
5660     return o;
5661 }
5662
5663 /*
5664 =for apidoc block_start
5665
5666 Handles compile-time scope entry.
5667 Arranges for hints to be restored on block
5668 exit and also handles pad sequence numbers to make lexical variables scope
5669 right.  Returns a savestack index for use with C<block_end>.
5670
5671 =cut
5672 */
5673
5674 int
5675 Perl_block_start(pTHX_ int full)
5676 {
5677     const int retval = PL_savestack_ix;
5678
5679     PL_compiling.cop_seq = PL_cop_seqmax;
5680     COP_SEQMAX_INC;
5681     pad_block_start(full);
5682     SAVEHINTS();
5683     PL_hints &= ~HINT_BLOCK_SCOPE;
5684     SAVECOMPILEWARNINGS();
5685     PL_compiling.cop_warnings = DUP_WARNINGS(PL_compiling.cop_warnings);
5686     SAVEI32(PL_compiling.cop_seq);
5687     PL_compiling.cop_seq = 0;
5688
5689     CALL_BLOCK_HOOKS(bhk_start, full);
5690
5691     return retval;
5692 }
5693
5694 /*
5695 =for apidoc block_end
5696
5697 Handles compile-time scope exit.  C<floor>
5698 is the savestack index returned by
5699 C<block_start>, and C<seq> is the body of the block.  Returns the block,
5700 possibly modified.
5701
5702 =cut
5703 */
5704
5705 OP*
5706 Perl_block_end(pTHX_ I32 floor, OP *seq)
5707 {
5708     const int needblockscope = PL_hints & HINT_BLOCK_SCOPE;
5709     OP* retval = scalarseq(seq);
5710     OP *o;
5711
5712     /* XXX Is the null PL_parser check necessary here? */
5713     assert(PL_parser); /* Let’s find out under debugging builds.  */
5714     if (PL_parser && PL_parser->parsed_sub) {
5715         o = newSTATEOP(0, NULL, NULL);
5716         op_null(o);
5717         retval = op_append_elem(OP_LINESEQ, retval, o);
5718     }
5719
5720     CALL_BLOCK_HOOKS(bhk_pre_end, &retval);
5721
5722     LEAVE_SCOPE(floor);
5723     if (needblockscope)
5724         PL_hints |= HINT_BLOCK_SCOPE; /* propagate out */
5725     o = pad_leavemy();
5726
5727     if (o) {
5728         /* pad_leavemy has created a sequence of introcv ops for all my
5729            subs declared in the block.  We have to replicate that list with
5730            clonecv ops, to deal with this situation:
5731
5732                sub {
5733                    my sub s1;
5734                    my sub s2;
5735                    sub s1 { state sub foo { \&s2 } }
5736                }->()
5737
5738            Originally, I was going to have introcv clone the CV and turn
5739            off the stale flag.  Since &s1 is declared before &s2, the
5740            introcv op for &s1 is executed (on sub entry) before the one for
5741            &s2.  But the &foo sub inside &s1 (which is cloned when &s1 is
5742            cloned, since it is a state sub) closes over &s2 and expects
5743            to see it in its outer CV’s pad.  If the introcv op clones &s1,
5744            then &s2 is still marked stale.  Since &s1 is not active, and
5745            &foo closes over &s1’s implicit entry for &s2, we get a â€˜Varia-
5746            ble will not stay shared’ warning.  Because it is the same stub
5747            that will be used when the introcv op for &s2 is executed, clos-
5748            ing over it is safe.  Hence, we have to turn off the stale flag
5749            on all lexical subs in the block before we clone any of them.
5750            Hence, having introcv clone the sub cannot work.  So we create a
5751            list of ops like this:
5752
5753                lineseq
5754                   |
5755                   +-- introcv
5756                   |
5757                   +-- introcv
5758                   |
5759                   +-- introcv
5760                   |
5761                   .
5762                   .
5763                   .
5764                   |
5765                   +-- clonecv
5766                   |
5767                   +-- clonecv
5768                   |
5769                   +-- clonecv
5770                   |
5771                   .
5772                   .
5773                   .
5774          */
5775         OP *kid = o->op_flags & OPf_KIDS ? cLISTOPo->op_first : o;
5776         OP * const last = o->op_flags & OPf_KIDS ? cLISTOPo->op_last : o;
5777         for (;; kid = OpSIBLING(kid)) {
5778             OP *newkid = newOP(OP_CLONECV, 0);
5779             newkid->op_targ = kid->op_targ;
5780             o = op_append_elem(OP_LINESEQ, o, newkid);
5781             if (kid == last) break;
5782         }
5783         retval = op_prepend_elem(OP_LINESEQ, o, retval);
5784     }
5785
5786     CALL_BLOCK_HOOKS(bhk_post_end, &retval);
5787
5788     return retval;
5789 }
5790
5791 /*
5792 =for apidoc_section Compile-time scope hooks
5793
5794 =for apidoc blockhook_register
5795
5796 Register a set of hooks to be called when the Perl lexical scope changes
5797 at compile time.  See L<perlguts/"Compile-time scope hooks">.
5798
5799 =cut
5800 */
5801
5802 void
5803 Perl_blockhook_register(pTHX_ BHK *hk)
5804 {
5805     PERL_ARGS_ASSERT_BLOCKHOOK_REGISTER;
5806
5807     Perl_av_create_and_push(aTHX_ &PL_blockhooks, newSViv(PTR2IV(hk)));
5808 }
5809
5810 void
5811 Perl_newPROG(pTHX_ OP *o)
5812 {
5813     OP *start;
5814
5815     PERL_ARGS_ASSERT_NEWPROG;
5816
5817     if (PL_in_eval) {
5818         PERL_CONTEXT *cx;
5819         I32 i;
5820         if (PL_eval_root)
5821                 return;
5822         PL_eval_root = newUNOP(OP_LEAVEEVAL,
5823                                ((PL_in_eval & EVAL_KEEPERR)
5824                                 ? OPf_SPECIAL : 0), o);
5825
5826         cx = CX_CUR();
5827         assert(CxTYPE(cx) == CXt_EVAL);
5828
5829         if ((cx->blk_gimme & G_WANT) == G_VOID)
5830             scalarvoid(PL_eval_root);
5831         else if ((cx->blk_gimme & G_WANT) == G_ARRAY)
5832             list(PL_eval_root);
5833         else
5834             scalar(PL_eval_root);
5835
5836         start = op_linklist(PL_eval_root);
5837         PL_eval_root->op_next = 0;
5838         i = PL_savestack_ix;
5839         SAVEFREEOP(o);
5840         ENTER;
5841         S_process_optree(aTHX_ NULL, PL_eval_root, start);
5842         LEAVE;
5843         PL_savestack_ix = i;
5844     }
5845     else {
5846         if (o->op_type == OP_STUB) {
5847             /* This block is entered if nothing is compiled for the main
5848                program. This will be the case for an genuinely empty main
5849                program, or one which only has BEGIN blocks etc, so already
5850                run and freed.
5851
5852                Historically (5.000) the guard above was !o. However, commit
5853                f8a08f7b8bd67b28 (Jun 2001), integrated to blead as
5854                c71fccf11fde0068, changed perly.y so that newPROG() is now
5855                called with the output of block_end(), which returns a new
5856                OP_STUB for the case of an empty optree. ByteLoader (and
5857                maybe other things) also take this path, because they set up
5858                PL_main_start and PL_main_root directly, without generating an
5859                optree.
5860
5861                If the parsing the main program aborts (due to parse errors,
5862                or due to BEGIN or similar calling exit), then newPROG()
5863                isn't even called, and hence this code path and its cleanups
5864                are skipped. This shouldn't make a make a difference:
5865                * a non-zero return from perl_parse is a failure, and
5866                  perl_destruct() should be called immediately.
5867                * however, if exit(0) is called during the parse, then
5868                  perl_parse() returns 0, and perl_run() is called. As
5869                  PL_main_start will be NULL, perl_run() will return
5870                  promptly, and the exit code will remain 0.
5871             */
5872
5873             PL_comppad_name = 0;
5874             PL_compcv = 0;
5875             S_op_destroy(aTHX_ o);
5876             return;
5877         }
5878         PL_main_root = op_scope(sawparens(scalarvoid(o)));
5879         PL_curcop = &PL_compiling;
5880         start = LINKLIST(PL_main_root);
5881         PL_main_root->op_next = 0;
5882         S_process_optree(aTHX_ NULL, PL_main_root, start);
5883         if (!PL_parser->error_count)
5884             /* on error, leave CV slabbed so that ops left lying around
5885              * will eb cleaned up. Else unslab */
5886             cv_forget_slab(PL_compcv);
5887         PL_compcv = 0;
5888
5889         /* Register with debugger */
5890         if (PERLDB_INTER) {
5891             CV * const cv = get_cvs("DB::postponed", 0);
5892             if (cv) {
5893                 dSP;
5894                 PUSHMARK(SP);
5895                 XPUSHs(MUTABLE_SV(CopFILEGV(&PL_compiling)));
5896                 PUTBACK;
5897                 call_sv(MUTABLE_SV(cv), G_DISCARD);
5898             }
5899         }
5900     }
5901 }
5902
5903 OP *
5904 Perl_localize(pTHX_ OP *o, I32 lex)
5905 {
5906     PERL_ARGS_ASSERT_LOCALIZE;
5907
5908     if (o->op_flags & OPf_PARENS)
5909 /* [perl #17376]: this appears to be premature, and results in code such as
5910    C< our(%x); > executing in list mode rather than void mode */
5911 #if 0
5912         list(o);
5913 #else
5914         NOOP;
5915 #endif
5916     else {
5917         if ( PL_parser->bufptr > PL_parser->oldbufptr
5918             && PL_parser->bufptr[-1] == ','
5919             && ckWARN(WARN_PARENTHESIS))
5920         {
5921             char *s = PL_parser->bufptr;
5922             bool sigil = FALSE;
5923
5924             /* some heuristics to detect a potential error */
5925             while (*s && (memCHRs(", \t\n", *s)))
5926                 s++;
5927
5928             while (1) {
5929                 if (*s && (memCHRs("@$%", *s) || (!lex && *s == '*'))
5930                        && *++s
5931                        && (isWORDCHAR(*s) || UTF8_IS_CONTINUED(*s))) {
5932                     s++;
5933                     sigil = TRUE;
5934                     while (*s && (isWORDCHAR(*s) || UTF8_IS_CONTINUED(*s)))
5935                         s++;
5936                     while (*s && (memCHRs(", \t\n", *s)))
5937                         s++;
5938                 }
5939                 else
5940                     break;
5941             }
5942             if (sigil && (*s == ';' || *s == '=')) {
5943                 Perl_warner(aTHX_ packWARN(WARN_PARENTHESIS),
5944                                 "Parentheses missing around \"%s\" list",
5945                                 lex
5946                                     ? (PL_parser->in_my == KEY_our
5947                                         ? "our"
5948                                         : PL_parser->in_my == KEY_state
5949                                             ? "state"
5950                                             : "my")
5951                                     : "local");
5952             }
5953         }
5954     }
5955     if (lex)
5956         o = my(o);
5957     else
5958         o = op_lvalue(o, OP_NULL);              /* a bit kludgey */
5959     PL_parser->in_my = FALSE;
5960     PL_parser->in_my_stash = NULL;
5961     return o;
5962 }
5963
5964 OP *
5965 Perl_jmaybe(pTHX_ OP *o)
5966 {
5967     PERL_ARGS_ASSERT_JMAYBE;
5968
5969     if (o->op_type == OP_LIST) {
5970         if (FEATURE_MULTIDIMENSIONAL_IS_ENABLED) {
5971             OP * const o2
5972                 = newSVREF(newGVOP(OP_GV, 0, gv_fetchpvs(";", GV_ADD|GV_NOTQUAL, SVt_PV)));
5973             o = op_convert_list(OP_JOIN, 0, op_prepend_elem(OP_LIST, o2, o));
5974         }
5975         else {
5976             /* If the user disables this, then a warning might not be enough to alert
5977                them to a possible change of behaviour here, so throw an exception.
5978             */
5979             yyerror("Multidimensional hash lookup is disabled");
5980         }
5981     }
5982     return o;
5983 }
5984
5985 PERL_STATIC_INLINE OP *
5986 S_op_std_init(pTHX_ OP *o)
5987 {
5988     I32 type = o->op_type;
5989
5990     PERL_ARGS_ASSERT_OP_STD_INIT;
5991
5992     if (PL_opargs[type] & OA_RETSCALAR)
5993         scalar(o);
5994     if (PL_opargs[type] & OA_TARGET && !o->op_targ)
5995         o->op_targ = pad_alloc(type, SVs_PADTMP);
5996
5997     return o;
5998 }
5999
6000 PERL_STATIC_INLINE OP *
6001 S_op_integerize(pTHX_ OP *o)
6002 {
6003     I32 type = o->op_type;
6004
6005     PERL_ARGS_ASSERT_OP_INTEGERIZE;
6006
6007     /* integerize op. */
6008     if ((PL_opargs[type] & OA_OTHERINT) && (PL_hints & HINT_INTEGER))
6009     {
6010         o->op_ppaddr = PL_ppaddr[++(o->op_type)];
6011     }
6012
6013     if (type == OP_NEGATE)
6014         /* XXX might want a ck_negate() for this */
6015         cUNOPo->op_first->op_private &= ~OPpCONST_STRICT;
6016
6017     return o;
6018 }
6019
6020 /* This function exists solely to provide a scope to limit
6021    setjmp/longjmp() messing with auto variables.  It cannot be inlined because
6022    it uses setjmp
6023  */
6024 STATIC int
6025 S_fold_constants_eval(pTHX) {
6026     int ret = 0;
6027     dJMPENV;
6028
6029     JMPENV_PUSH(ret);
6030
6031     if (ret == 0) {
6032         CALLRUNOPS(aTHX);
6033     }
6034
6035     JMPENV_POP;
6036
6037     return ret;
6038 }
6039
6040 static OP *
6041 S_fold_constants(pTHX_ OP *const o)
6042 {
6043     OP *curop;
6044     OP *newop;
6045     I32 type = o->op_type;
6046     bool is_stringify;
6047     SV *sv = NULL;
6048     int ret = 0;
6049     OP *old_next;
6050     SV * const oldwarnhook = PL_warnhook;
6051     SV * const olddiehook  = PL_diehook;
6052     COP not_compiling;
6053     U8 oldwarn = PL_dowarn;
6054     I32 old_cxix;
6055
6056     PERL_ARGS_ASSERT_FOLD_CONSTANTS;
6057
6058     if (!(PL_opargs[type] & OA_FOLDCONST))
6059         goto nope;
6060
6061     switch (type) {
6062     case OP_UCFIRST:
6063     case OP_LCFIRST:
6064     case OP_UC:
6065     case OP_LC:
6066     case OP_FC:
6067 #ifdef USE_LOCALE_CTYPE
6068         if (IN_LC_COMPILETIME(LC_CTYPE))
6069             goto nope;
6070 #endif
6071         break;
6072     case OP_SLT:
6073     case OP_SGT:
6074     case OP_SLE:
6075     case OP_SGE:
6076     case OP_SCMP:
6077 #ifdef USE_LOCALE_COLLATE
6078         if (IN_LC_COMPILETIME(LC_COLLATE))
6079             goto nope;
6080 #endif
6081         break;
6082     case OP_SPRINTF:
6083         /* XXX what about the numeric ops? */
6084 #ifdef USE_LOCALE_NUMERIC
6085         if (IN_LC_COMPILETIME(LC_NUMERIC))
6086             goto nope;
6087 #endif
6088         break;
6089     case OP_PACK:
6090         if (!OpHAS_SIBLING(cLISTOPo->op_first)
6091           || OpSIBLING(cLISTOPo->op_first)->op_type != OP_CONST)
6092             goto nope;
6093         {
6094             SV * const sv = cSVOPx_sv(OpSIBLING(cLISTOPo->op_first));
6095             if (!SvPOK(sv) || SvGMAGICAL(sv)) goto nope;
6096             {
6097                 const char *s = SvPVX_const(sv);
6098                 while (s < SvEND(sv)) {
6099                     if (isALPHA_FOLD_EQ(*s, 'p')) goto nope;
6100                     s++;
6101                 }
6102             }
6103         }
6104         break;
6105     case OP_REPEAT:
6106         if (o->op_private & OPpREPEAT_DOLIST) goto nope;
6107         break;
6108     case OP_SREFGEN:
6109         if (cUNOPx(cUNOPo->op_first)->op_first->op_type != OP_CONST
6110          || SvPADTMP(cSVOPx_sv(cUNOPx(cUNOPo->op_first)->op_first)))
6111             goto nope;
6112     }
6113
6114     if (PL_parser && PL_parser->error_count)
6115         goto nope;              /* Don't try to run w/ errors */
6116
6117     for (curop = LINKLIST(o); curop != o; curop = LINKLIST(curop)) {
6118         switch (curop->op_type) {
6119         case OP_CONST:
6120             if (   (curop->op_private & OPpCONST_BARE)
6121                 && (curop->op_private & OPpCONST_STRICT)) {
6122                 no_bareword_allowed(curop);
6123                 goto nope;
6124             }
6125             /* FALLTHROUGH */
6126         case OP_LIST:
6127         case OP_SCALAR:
6128         case OP_NULL:
6129         case OP_PUSHMARK:
6130             /* Foldable; move to next op in list */
6131             break;
6132
6133         default:
6134             /* No other op types are considered foldable */
6135             goto nope;
6136         }
6137     }
6138
6139     curop = LINKLIST(o);
6140     old_next = o->op_next;
6141     o->op_next = 0;
6142     PL_op = curop;
6143
6144     old_cxix = cxstack_ix;
6145     create_eval_scope(NULL, G_FAKINGEVAL);
6146
6147     /* Verify that we don't need to save it:  */
6148     assert(PL_curcop == &PL_compiling);
6149     StructCopy(&PL_compiling, &not_compiling, COP);
6150     PL_curcop = &not_compiling;
6151     /* The above ensures that we run with all the correct hints of the
6152        currently compiling COP, but that IN_PERL_RUNTIME is true. */
6153     assert(IN_PERL_RUNTIME);
6154     PL_warnhook = PERL_WARNHOOK_FATAL;
6155     PL_diehook  = NULL;
6156
6157     /* Effective $^W=1.  */
6158     if ( ! (PL_dowarn & G_WARN_ALL_MASK))
6159         PL_dowarn |= G_WARN_ON;
6160
6161     ret = S_fold_constants_eval(aTHX);
6162
6163     switch (ret) {
6164     case 0:
6165         sv = *(PL_stack_sp--);
6166         if (o->op_targ && sv == PAD_SV(o->op_targ)) {   /* grab pad temp? */
6167             pad_swipe(o->op_targ,  FALSE);
6168         }
6169         else if (SvTEMP(sv)) {                  /* grab mortal temp? */
6170             SvREFCNT_inc_simple_void(sv);
6171             SvTEMP_off(sv);
6172         }
6173         else { assert(SvIMMORTAL(sv)); }
6174         break;
6175     case 3:
6176         /* Something tried to die.  Abandon constant folding.  */
6177         /* Pretend the error never happened.  */
6178         CLEAR_ERRSV();
6179         o->op_next = old_next;
6180         break;
6181     default:
6182         /* Don't expect 1 (setjmp failed) or 2 (something called my_exit)  */
6183         PL_warnhook = oldwarnhook;
6184         PL_diehook  = olddiehook;
6185         /* XXX note that this croak may fail as we've already blown away
6186          * the stack - eg any nested evals */
6187         Perl_croak(aTHX_ "panic: fold_constants JMPENV_PUSH returned %d", ret);
6188     }
6189     PL_dowarn   = oldwarn;
6190     PL_warnhook = oldwarnhook;
6191     PL_diehook  = olddiehook;
6192     PL_curcop = &PL_compiling;
6193
6194     /* if we croaked, depending on how we croaked the eval scope
6195      * may or may not have already been popped */
6196     if (cxstack_ix > old_cxix) {
6197         assert(cxstack_ix == old_cxix + 1);
6198         assert(CxTYPE(CX_CUR()) == CXt_EVAL);
6199         delete_eval_scope();
6200     }
6201     if (ret)
6202         goto nope;
6203
6204     /* OP_STRINGIFY and constant folding are used to implement qq.
6205        Here the constant folding is an implementation detail that we
6206        want to hide.  If the stringify op is itself already marked
6207        folded, however, then it is actually a folded join.  */
6208     is_stringify = type == OP_STRINGIFY && !o->op_folded;
6209     op_free(o);
6210     assert(sv);
6211     if (is_stringify)
6212         SvPADTMP_off(sv);
6213     else if (!SvIMMORTAL(sv)) {
6214         SvPADTMP_on(sv);
6215         SvREADONLY_on(sv);
6216     }
6217     newop = newSVOP(OP_CONST, 0, MUTABLE_SV(sv));
6218     if (!is_stringify) newop->op_folded = 1;
6219     return newop;
6220
6221  nope:
6222     return o;
6223 }
6224
6225 /* convert a constant range in list context into an OP_RV2AV, OP_CONST pair;
6226  * the constant value being an AV holding the flattened range.
6227  */
6228
6229 static void
6230 S_gen_constant_list(pTHX_ OP *o)
6231 {
6232     OP *curop, *old_next;
6233     SV * const oldwarnhook = PL_warnhook;
6234     SV * const olddiehook  = PL_diehook;
6235     COP *old_curcop;
6236     U8 oldwarn = PL_dowarn;
6237     SV **svp;
6238     AV *av;
6239     I32 old_cxix;
6240     COP not_compiling;
6241     int ret = 0;
6242     dJMPENV;
6243     bool op_was_null;
6244
6245     list(o);
6246     if (PL_parser && PL_parser->error_count)
6247         return;         /* Don't attempt to run with errors */
6248
6249     curop = LINKLIST(o);
6250     old_next = o->op_next;
6251     o->op_next = 0;
6252     op_was_null = o->op_type == OP_NULL;
6253     if (op_was_null) /* b3698342565fb462291fba4b432cfcd05b6eb4e1 */
6254         o->op_type = OP_CUSTOM;
6255     CALL_PEEP(curop);
6256     if (op_was_null)
6257         o->op_type = OP_NULL;
6258     S_prune_chain_head(&curop);
6259     PL_op = curop;
6260
6261     old_cxix = cxstack_ix;
6262     create_eval_scope(NULL, G_FAKINGEVAL);
6263
6264     old_curcop = PL_curcop;
6265     StructCopy(old_curcop, &not_compiling, COP);
6266     PL_curcop = &not_compiling;
6267     /* The above ensures that we run with all the correct hints of the
6268        current COP, but that IN_PERL_RUNTIME is true. */
6269     assert(IN_PERL_RUNTIME);
6270     PL_warnhook = PERL_WARNHOOK_FATAL;
6271     PL_diehook  = NULL;
6272     JMPENV_PUSH(ret);
6273
6274     /* Effective $^W=1.  */
6275     if ( ! (PL_dowarn & G_WARN_ALL_MASK))
6276         PL_dowarn |= G_WARN_ON;
6277
6278     switch (ret) {
6279     case 0:
6280 #if defined DEBUGGING && !defined DEBUGGING_RE_ONLY
6281         PL_curstackinfo->si_stack_hwm = 0; /* stop valgrind complaining */
6282 #endif
6283         Perl_pp_pushmark(aTHX);
6284         CALLRUNOPS(aTHX);
6285         PL_op = curop;
6286         assert (!(curop->op_flags & OPf_SPECIAL));
6287         assert(curop->op_type == OP_RANGE);
6288         Perl_pp_anonlist(aTHX);
6289         break;
6290     case 3:
6291         CLEAR_ERRSV();
6292         o->op_next = old_next;
6293         break;
6294     default:
6295         JMPENV_POP;
6296         PL_warnhook = oldwarnhook;
6297         PL_diehook = olddiehook;
6298         Perl_croak(aTHX_ "panic: gen_constant_list JMPENV_PUSH returned %d",
6299             ret);
6300     }
6301
6302     JMPENV_POP;
6303     PL_dowarn = oldwarn;
6304     PL_warnhook = oldwarnhook;
6305     PL_diehook = olddiehook;
6306     PL_curcop = old_curcop;
6307
6308     if (cxstack_ix > old_cxix) {
6309         assert(cxstack_ix == old_cxix + 1);
6310         assert(CxTYPE(CX_CUR()) == CXt_EVAL);
6311         delete_eval_scope();
6312     }
6313     if (ret)
6314         return;
6315
6316     OpTYPE_set(o, OP_RV2AV);
6317     o->op_flags &= ~OPf_REF;    /* treat \(1..2) like an ordinary list */
6318     o->op_flags |= OPf_PARENS;  /* and flatten \(1..2,3) */
6319     o->op_opt = 0;              /* needs to be revisited in rpeep() */
6320     av = (AV *)SvREFCNT_inc_NN(*PL_stack_sp--);
6321
6322     /* replace subtree with an OP_CONST */
6323     curop = ((UNOP*)o)->op_first;
6324     op_sibling_splice(o, NULL, -1, newSVOP(OP_CONST, 0, (SV *)av));
6325     op_free(curop);
6326
6327     if (AvFILLp(av) != -1)
6328         for (svp = AvARRAY(av) + AvFILLp(av); svp >= AvARRAY(av); --svp)
6329         {
6330             SvPADTMP_on(*svp);
6331             SvREADONLY_on(*svp);
6332         }
6333     LINKLIST(o);
6334     list(o);
6335     return;
6336 }
6337
6338 /*
6339 =for apidoc_section Optree Manipulation Functions
6340 */
6341
6342 /* List constructors */
6343
6344 /*
6345 =for apidoc op_append_elem
6346
6347 Append an item to the list of ops contained directly within a list-type
6348 op, returning the lengthened list.  C<first> is the list-type op,
6349 and C<last> is the op to append to the list.  C<optype> specifies the
6350 intended opcode for the list.  If C<first> is not already a list of the
6351 right type, it will be upgraded into one.  If either C<first> or C<last>
6352 is null, the other is returned unchanged.
6353
6354 =cut
6355 */
6356
6357 OP *
6358 Perl_op_append_elem(pTHX_ I32 type, OP *first, OP *last)
6359 {
6360     if (!first)
6361         return last;
6362
6363     if (!last)
6364         return first;
6365
6366     if (first->op_type != (unsigned)type
6367         || (type == OP_LIST && (first->op_flags & OPf_PARENS)))
6368     {
6369         return newLISTOP(type, 0, first, last);
6370     }
6371
6372     op_sibling_splice(first, ((LISTOP*)first)->op_last, 0, last);
6373     first->op_flags |= OPf_KIDS;
6374     return first;
6375 }
6376
6377 /*
6378 =for apidoc op_append_list
6379
6380 Concatenate the lists of ops contained directly within two list-type ops,
6381 returning the combined list.  C<first> and C<last> are the list-type ops
6382 to concatenate.  C<optype> specifies the intended opcode for the list.
6383 If either C<first> or C<last> is not already a list of the right type,
6384 it will be upgraded into one.  If either C<first> or C<last> is null,
6385 the other is returned unchanged.
6386
6387 =cut
6388 */
6389
6390 OP *
6391 Perl_op_append_list(pTHX_ I32 type, OP *first, OP *last)
6392 {
6393     if (!first)
6394         return last;
6395
6396     if (!last)
6397         return first;
6398
6399     if (first->op_type != (unsigned)type)
6400         return op_prepend_elem(type, first, last);
6401
6402     if (last->op_type != (unsigned)type)
6403         return op_append_elem(type, first, last);
6404
6405     OpMORESIB_set(((LISTOP*)first)->op_last, ((LISTOP*)last)->op_first);
6406     ((LISTOP*)first)->op_last = ((LISTOP*)last)->op_last;
6407     OpLASTSIB_set(((LISTOP*)first)->op_last, first);
6408     first->op_flags |= (last->op_flags & OPf_KIDS);
6409
6410     S_op_destroy(aTHX_ last);
6411
6412     return first;
6413 }
6414
6415 /*
6416 =for apidoc op_prepend_elem
6417
6418 Prepend an item to the list of ops contained directly within a list-type
6419 op, returning the lengthened list.  C<first> is the op to prepend to the
6420 list, and C<last> is the list-type op.  C<optype> specifies the intended
6421 opcode for the list.  If C<last> is not already a list of the right type,
6422 it will be upgraded into one.  If either C<first> or C<last> is null,
6423 the other is returned unchanged.
6424
6425 =cut
6426 */
6427
6428 OP *
6429 Perl_op_prepend_elem(pTHX_ I32 type, OP *first, OP *last)
6430 {
6431     if (!first)
6432         return last;
6433
6434     if (!last)
6435         return first;
6436
6437     if (last->op_type == (unsigned)type) {
6438         if (type == OP_LIST) {  /* already a PUSHMARK there */
6439             /* insert 'first' after pushmark */
6440             op_sibling_splice(last, cLISTOPx(last)->op_first, 0, first);
6441             if (!(first->op_flags & OPf_PARENS))
6442                 last->op_flags &= ~OPf_PARENS;
6443         }
6444         else
6445             op_sibling_splice(last, NULL, 0, first);
6446         last->op_flags |= OPf_KIDS;
6447         return last;
6448     }
6449
6450     return newLISTOP(type, 0, first, last);
6451 }
6452
6453 /*
6454 =for apidoc op_convert_list
6455
6456 Converts C<o> into a list op if it is not one already, and then converts it
6457 into the specified C<type>, calling its check function, allocating a target if
6458 it needs one, and folding constants.
6459
6460 A list-type op is usually constructed one kid at a time via C<newLISTOP>,
6461 C<op_prepend_elem> and C<op_append_elem>.  Then finally it is passed to
6462 C<op_convert_list> to make it the right type.
6463
6464 =cut
6465 */
6466
6467 OP *
6468 Perl_op_convert_list(pTHX_ I32 type, I32 flags, OP *o)
6469 {
6470     if (type < 0) type = -type, flags |= OPf_SPECIAL;
6471     if (!o || o->op_type != OP_LIST)
6472         o = force_list(o, 0);
6473     else
6474     {
6475         o->op_flags &= ~OPf_WANT;
6476         o->op_private &= ~OPpLVAL_INTRO;
6477     }
6478
6479     if (!(PL_opargs[type] & OA_MARK))
6480         op_null(cLISTOPo->op_first);
6481     else {
6482         OP * const kid2 = OpSIBLING(cLISTOPo->op_first);
6483         if (kid2 && kid2->op_type == OP_COREARGS) {
6484             op_null(cLISTOPo->op_first);
6485             kid2->op_private |= OPpCOREARGS_PUSHMARK;
6486         }
6487     }
6488
6489     if (type != OP_SPLIT)
6490         /* At this point o is a LISTOP, but OP_SPLIT is a PMOP; let
6491          * ck_split() create a real PMOP and leave the op's type as listop
6492          * for now. Otherwise op_free() etc will crash.
6493          */
6494         OpTYPE_set(o, type);
6495
6496     o->op_flags |= flags;
6497     if (flags & OPf_FOLDED)
6498         o->op_folded = 1;
6499
6500     o = CHECKOP(type, o);
6501     if (o->op_type != (unsigned)type)
6502         return o;
6503
6504     return fold_constants(op_integerize(op_std_init(o)));
6505 }
6506
6507 /* Constructors */
6508
6509
6510 /*
6511 =for apidoc_section Optree construction
6512
6513 =for apidoc newNULLLIST
6514
6515 Constructs, checks, and returns a new C<stub> op, which represents an
6516 empty list expression.
6517
6518 =cut
6519 */
6520
6521 OP *
6522 Perl_newNULLLIST(pTHX)
6523 {
6524     return newOP(OP_STUB, 0);
6525 }
6526
6527 /* promote o and any siblings to be a list if its not already; i.e.
6528  *
6529  *  o - A - B
6530  *
6531  * becomes
6532  *
6533  *  list
6534  *    |
6535  *  pushmark - o - A - B
6536  *
6537  * If nullit it true, the list op is nulled.
6538  */
6539
6540 static OP *
6541 S_force_list(pTHX_ OP *o, bool nullit)
6542 {
6543     if (!o || o->op_type != OP_LIST) {
6544         OP *rest = NULL;
6545         if (o) {
6546             /* manually detach any siblings then add them back later */
6547             rest = OpSIBLING(o);
6548             OpLASTSIB_set(o, NULL);
6549         }
6550         o = newLISTOP(OP_LIST, 0, o, NULL);
6551         if (rest)
6552             op_sibling_splice(o, cLISTOPo->op_last, 0, rest);
6553     }
6554     if (nullit)
6555         op_null(o);
6556     return o;
6557 }
6558
6559 /*
6560 =for apidoc newLISTOP
6561
6562 Constructs, checks, and returns an op of any list type.  C<type> is
6563 the opcode.  C<flags> gives the eight bits of C<op_flags>, except that
6564 C<OPf_KIDS> will be set automatically if required.  C<first> and C<last>
6565 supply up to two ops to be direct children of the list op; they are
6566 consumed by this function and become part of the constructed op tree.
6567
6568 For most list operators, the check function expects all the kid ops to be
6569 present already, so calling C<newLISTOP(OP_JOIN, ...)> (e.g.) is not
6570 appropriate.  What you want to do in that case is create an op of type
6571 C<OP_LIST>, append more children to it, and then call L</op_convert_list>.
6572 See L</op_convert_list> for more information.
6573
6574
6575 =cut
6576 */
6577
6578 OP *
6579 Perl_newLISTOP(pTHX_ I32 type, I32 flags, OP *first, OP *last)
6580 {
6581     LISTOP *listop;
6582     /* Note that allocating an OP_PUSHMARK can die under Safe.pm if
6583      * pushmark is banned. So do it now while existing ops are in a
6584      * consistent state, in case they suddenly get freed */
6585     OP* const pushop = type == OP_LIST ? newOP(OP_PUSHMARK, 0) : NULL;
6586
6587     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_LISTOP
6588         || type == OP_CUSTOM);
6589
6590     NewOp(1101, listop, 1, LISTOP);
6591     OpTYPE_set(listop, type);
6592     if (first || last)
6593         flags |= OPf_KIDS;
6594     listop->op_flags = (U8)flags;
6595
6596     if (!last && first)
6597         last = first;
6598     else if (!first && last)
6599         first = last;
6600     else if (first)
6601         OpMORESIB_set(first, last);
6602     listop->op_first = first;
6603     listop->op_last = last;
6604
6605     if (pushop) {
6606         OpMORESIB_set(pushop, first);
6607         listop->op_first = pushop;
6608         listop->op_flags |= OPf_KIDS;
6609         if (!last)
6610             listop->op_last = pushop;
6611     }
6612     if (listop->op_last)
6613         OpLASTSIB_set(listop->op_last, (OP*)listop);
6614
6615     return CHECKOP(type, listop);
6616 }
6617
6618 /*
6619 =for apidoc newOP
6620
6621 Constructs, checks, and returns an op of any base type (any type that
6622 has no extra fields).  C<type> is the opcode.  C<flags> gives the
6623 eight bits of C<op_flags>, and, shifted up eight bits, the eight bits
6624 of C<op_private>.
6625
6626 =cut
6627 */
6628
6629 OP *
6630 Perl_newOP(pTHX_ I32 type, I32 flags)
6631 {
6632     OP *o;
6633
6634     if (type == -OP_ENTEREVAL) {
6635         type = OP_ENTEREVAL;
6636         flags |= OPpEVAL_BYTES<<8;
6637     }
6638
6639     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_BASEOP
6640         || (PL_opargs[type] & OA_CLASS_MASK) == OA_BASEOP_OR_UNOP
6641         || (PL_opargs[type] & OA_CLASS_MASK) == OA_FILESTATOP
6642         || (PL_opargs[type] & OA_CLASS_MASK) == OA_LOOPEXOP);
6643
6644     NewOp(1101, o, 1, OP);
6645     OpTYPE_set(o, type);
6646     o->op_flags = (U8)flags;
6647
6648     o->op_next = o;
6649     o->op_private = (U8)(0 | (flags >> 8));
6650     if (PL_opargs[type] & OA_RETSCALAR)
6651         scalar(o);
6652     if (PL_opargs[type] & OA_TARGET)
6653         o->op_targ = pad_alloc(type, SVs_PADTMP);
6654     return CHECKOP(type, o);
6655 }
6656
6657 /*
6658 =for apidoc newUNOP
6659
6660 Constructs, checks, and returns an op of any unary type.  C<type> is
6661 the opcode.  C<flags> gives the eight bits of C<op_flags>, except that
6662 C<OPf_KIDS> will be set automatically if required, and, shifted up eight
6663 bits, the eight bits of C<op_private>, except that the bit with value 1
6664 is automatically set.  C<first> supplies an optional op to be the direct
6665 child of the unary op; it is consumed by this function and become part
6666 of the constructed op tree.
6667
6668 =for apidoc Amnh||OPf_KIDS
6669
6670 =cut
6671 */
6672
6673 OP *
6674 Perl_newUNOP(pTHX_ I32 type, I32 flags, OP *first)
6675 {
6676     UNOP *unop;
6677
6678     if (type == -OP_ENTEREVAL) {
6679         type = OP_ENTEREVAL;
6680         flags |= OPpEVAL_BYTES<<8;
6681     }
6682
6683     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_UNOP
6684         || (PL_opargs[type] & OA_CLASS_MASK) == OA_BASEOP_OR_UNOP
6685         || (PL_opargs[type] & OA_CLASS_MASK) == OA_FILESTATOP
6686         || (PL_opargs[type] & OA_CLASS_MASK) == OA_LOOPEXOP
6687         || type == OP_SASSIGN
6688         || type == OP_ENTERTRY
6689         || type == OP_CUSTOM
6690         || type == OP_NULL );
6691
6692     if (!first)
6693         first = newOP(OP_STUB, 0);
6694     if (PL_opargs[type] & OA_MARK)
6695         first = force_list(first, 1);
6696
6697     NewOp(1101, unop, 1, UNOP);
6698     OpTYPE_set(unop, type);
6699     unop->op_first = first;
6700     unop->op_flags = (U8)(flags | OPf_KIDS);
6701     unop->op_private = (U8)(1 | (flags >> 8));
6702
6703     if (!OpHAS_SIBLING(first)) /* true unless weird syntax error */
6704         OpLASTSIB_set(first, (OP*)unop);
6705
6706     unop = (UNOP*) CHECKOP(type, unop);
6707     if (unop->op_next)
6708         return (OP*)unop;
6709
6710     return fold_constants(op_integerize(op_std_init((OP *) unop)));
6711 }
6712
6713 /*
6714 =for apidoc newUNOP_AUX
6715
6716 Similar to C<newUNOP>, but creates an C<UNOP_AUX> struct instead, with C<op_aux>
6717 initialised to C<aux>
6718
6719 =cut
6720 */
6721
6722 OP *
6723 Perl_newUNOP_AUX(pTHX_ I32 type, I32 flags, OP *first, UNOP_AUX_item *aux)
6724 {
6725     UNOP_AUX *unop;
6726
6727     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_UNOP_AUX
6728         || type == OP_CUSTOM);
6729
6730     NewOp(1101, unop, 1, UNOP_AUX);
6731     unop->op_type = (OPCODE)type;
6732     unop->op_ppaddr = PL_ppaddr[type];
6733     unop->op_first = first;
6734     unop->op_flags = (U8)(flags | (first ? OPf_KIDS : 0));
6735     unop->op_private = (U8)((first ? 1 : 0) | (flags >> 8));
6736     unop->op_aux = aux;
6737
6738     if (first && !OpHAS_SIBLING(first)) /* true unless weird syntax error */
6739         OpLASTSIB_set(first, (OP*)unop);
6740
6741     unop = (UNOP_AUX*) CHECKOP(type, unop);
6742
6743     return op_std_init((OP *) unop);
6744 }
6745
6746 /*
6747 =for apidoc newMETHOP
6748
6749 Constructs, checks, and returns an op of method type with a method name
6750 evaluated at runtime.  C<type> is the opcode.  C<flags> gives the eight
6751 bits of C<op_flags>, except that C<OPf_KIDS> will be set automatically,
6752 and, shifted up eight bits, the eight bits of C<op_private>, except that
6753 the bit with value 1 is automatically set.  C<dynamic_meth> supplies an
6754 op which evaluates method name; it is consumed by this function and
6755 become part of the constructed op tree.
6756 Supported optypes: C<OP_METHOD>.
6757
6758 =cut
6759 */
6760
6761 static OP*
6762 S_newMETHOP_internal(pTHX_ I32 type, I32 flags, OP* dynamic_meth, SV* const_meth) {
6763     METHOP *methop;
6764
6765     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_METHOP
6766         || type == OP_CUSTOM);
6767
6768     NewOp(1101, methop, 1, METHOP);
6769     if (dynamic_meth) {
6770         if (PL_opargs[type] & OA_MARK) dynamic_meth = force_list(dynamic_meth, 1);
6771         methop->op_flags = (U8)(flags | OPf_KIDS);
6772         methop->op_u.op_first = dynamic_meth;
6773         methop->op_private = (U8)(1 | (flags >> 8));
6774
6775         if (!OpHAS_SIBLING(dynamic_meth))
6776             OpLASTSIB_set(dynamic_meth, (OP*)methop);
6777     }
6778     else {
6779         assert(const_meth);
6780         methop->op_flags = (U8)(flags & ~OPf_KIDS);
6781         methop->op_u.op_meth_sv = const_meth;
6782         methop->op_private = (U8)(0 | (flags >> 8));
6783         methop->op_next = (OP*)methop;
6784     }
6785
6786 #ifdef USE_ITHREADS
6787     methop->op_rclass_targ = 0;
6788 #else
6789     methop->op_rclass_sv = NULL;
6790 #endif
6791
6792     OpTYPE_set(methop, type);
6793     return CHECKOP(type, methop);
6794 }
6795
6796 OP *
6797 Perl_newMETHOP (pTHX_ I32 type, I32 flags, OP* dynamic_meth) {
6798     PERL_ARGS_ASSERT_NEWMETHOP;
6799     return newMETHOP_internal(type, flags, dynamic_meth, NULL);
6800 }
6801
6802 /*
6803 =for apidoc newMETHOP_named
6804
6805 Constructs, checks, and returns an op of method type with a constant
6806 method name.  C<type> is the opcode.  C<flags> gives the eight bits of
6807 C<op_flags>, and, shifted up eight bits, the eight bits of
6808 C<op_private>.  C<const_meth> supplies a constant method name;
6809 it must be a shared COW string.
6810 Supported optypes: C<OP_METHOD_NAMED>.
6811
6812 =cut
6813 */
6814
6815 OP *
6816 Perl_newMETHOP_named (pTHX_ I32 type, I32 flags, SV* const_meth) {
6817     PERL_ARGS_ASSERT_NEWMETHOP_NAMED;
6818     return newMETHOP_internal(type, flags, NULL, const_meth);
6819 }
6820
6821 /*
6822 =for apidoc newBINOP
6823
6824 Constructs, checks, and returns an op of any binary type.  C<type>
6825 is the opcode.  C<flags> gives the eight bits of C<op_flags>, except
6826 that C<OPf_KIDS> will be set automatically, and, shifted up eight bits,
6827 the eight bits of C<op_private>, except that the bit with value 1 or
6828 2 is automatically set as required.  C<first> and C<last> supply up to
6829 two ops to be the direct children of the binary op; they are consumed
6830 by this function and become part of the constructed op tree.
6831
6832 =cut
6833 */
6834
6835 OP *
6836 Perl_newBINOP(pTHX_ I32 type, I32 flags, OP *first, OP *last)
6837 {
6838     BINOP *binop;
6839
6840     ASSUME((PL_opargs[type] & OA_CLASS_MASK) == OA_BINOP
6841         || type == OP_NULL || type == OP_CUSTOM);
6842
6843     NewOp(1101, binop, 1, BINOP);
6844
6845     if (!first)
6846         first = newOP(OP_NULL, 0);
6847
6848     OpTYPE_set(binop, type);
6849     binop->op_first = first;
6850     binop->op_flags = (U8)(flags | OPf_KIDS);
6851     if (!last) {
6852         last = first;
6853         binop->op_private = (U8)(1 | (flags >> 8));
6854     }
6855     else {
6856         binop->op_private = (U8)(2 | (flags >> 8));
6857         OpMORESIB_set(first, last);
6858     }
6859
6860     if (!OpHAS_SIBLING(last)) /* true unless weird syntax error */
6861         OpLASTSIB_set(last, (OP*)binop);
6862
6863     binop->op_last = OpSIBLING(binop->op_first);
6864     if (binop->op_last)
6865         OpLASTSIB_set(binop->op_last, (OP*)binop);
6866
6867     binop = (BINOP*)CHECKOP(type, binop);
6868     if (binop->op_next || binop->op_type != (OPCODE)type)
6869         return (OP*)binop;
6870
6871     return fold_constants(op_integerize(op_std_init((OP *)binop)));
6872 }
6873
6874 void
6875 Perl_invmap_dump(pTHX_ SV* invlist, UV *map)
6876 {
6877     const char indent[] = "    ";
6878
6879     UV len = _invlist_len(invlist);
6880     UV * array = invlist_array(invlist);
6881     UV i;
6882
6883     PERL_ARGS_ASSERT_INVMAP_DUMP;
6884
6885     for (i = 0; i < len; i++) {
6886         UV start = array[i];
6887         UV end   = (i + 1 < len) ? array[i+1] - 1 : IV_MAX;
6888
6889         PerlIO_printf(Perl_debug_log, "%s[%" UVuf "] 0x%04" UVXf, indent, i, start);
6890         if (end == IV_MAX) {
6891             PerlIO_printf(Perl_debug_log, " .. INFTY");
6892         }
6893         else if (end != start) {
6894             PerlIO_printf(Perl_debug_log, " .. 0x%04" UVXf, end);
6895         }
6896         else {
6897             PerlIO_printf(Perl_debug_log, "            ");
6898         }
6899
6900         PerlIO_printf(Perl_debug_log, "\t");
6901
6902         if (map[i] == TR_UNLISTED) {
6903             PerlIO_printf(Perl_debug_log, "TR_UNLISTED\n");
6904         }
6905         else if (map[i] == TR_SPECIAL_HANDLING) {
6906             PerlIO_printf(Perl_debug_log, "TR_SPECIAL_HANDLING\n");
6907         }
6908         else {
6909             PerlIO_printf(Perl_debug_log, "0x%04" UVXf "\n", map[i]);
6910         }
6911     }
6912 }
6913
6914 /* Given an OP_TRANS / OP_TRANSR op o, plus OP_CONST ops expr and repl
6915  * containing the search and replacement strings, assemble into
6916  * a translation table attached as o->op_pv.
6917  * Free expr and repl.
6918  * It expects the toker to have already set the
6919  *   OPpTRANS_COMPLEMENT
6920  *   OPpTRANS_SQUASH
6921  *   OPpTRANS_DELETE
6922  * flags as appropriate; this function may add
6923  *   OPpTRANS_USE_SVOP
6924  *   OPpTRANS_CAN_FORCE_UTF8
6925  *   OPpTRANS_IDENTICAL
6926  *   OPpTRANS_GROWS
6927  * flags
6928  */
6929
6930 static OP *
6931 S_pmtrans(pTHX_ OP *o, OP *expr, OP *repl)
6932 {
6933     /* This function compiles a tr///, from data gathered from toke.c, into a
6934      * form suitable for use by do_trans() in doop.c at runtime.
6935      *
6936      * It first normalizes the data, while discarding extraneous inputs; then
6937      * writes out the compiled data.  The normalization allows for complete
6938      * analysis, and avoids some false negatives and positives earlier versions
6939      * of this code had.
6940      *
6941      * The normalization form is an inversion map (described below in detail).
6942      * This is essentially the compiled form for tr///'s that require UTF-8,
6943      * and its easy to use it to write the 257-byte table for tr///'s that
6944      * don't need UTF-8.  That table is identical to what's been in use for
6945      * many perl versions, except that it doesn't handle some edge cases that
6946      * it used to, involving code points above 255.  The UTF-8 form now handles
6947      * these.  (This could be changed with extra coding should it shown to be
6948      * desirable.)
6949      *
6950      * If the complement (/c) option is specified, the lhs string (tstr) is
6951      * parsed into an inversion list.  Complementing these is trivial.  Then a
6952      * complemented tstr is built from that, and used thenceforth.  This hides
6953      * the fact that it was complemented from almost all successive code.
6954      *
6955      * One of the important characteristics to know about the input is whether
6956      * the transliteration may be done in place, or does a temporary need to be
6957      * allocated, then copied.  If the replacement for every character in every
6958      * possible string takes up no more bytes than the character it
6959      * replaces, then it can be edited in place.  Otherwise the replacement
6960      * could overwrite a byte we are about to read, depending on the strings
6961      * being processed.  The comments and variable names here refer to this as
6962      * "growing".  Some inputs won't grow, and might even shrink under /d, but
6963      * some inputs could grow, so we have to assume any given one might grow.
6964      * On very long inputs, the temporary could eat up a lot of memory, so we
6965      * want to avoid it if possible.  For non-UTF-8 inputs, everything is
6966      * single-byte, so can be edited in place, unless there is something in the
6967      * pattern that could force it into UTF-8.  The inversion map makes it
6968      * feasible to determine this.  Previous versions of this code pretty much
6969      * punted on determining if UTF-8 could be edited in place.  Now, this code
6970      * is rigorous in making that determination.
6971      *
6972      * Another characteristic we need to know is whether the lhs and rhs are
6973      * identical.  If so, and no other flags are present, the only effect of
6974      * the tr/// is to count the characters present in the input that are
6975      * mentioned in the lhs string.  The implementation of that is easier and
6976      * runs faster than the more general case.  Normalizing here allows for
6977      * accurate determination of this.  Previously there were false negatives
6978      * possible.
6979      *
6980      * Instead of 'transliterated', the comments here use 'unmapped' for the
6981      * characters that are left unchanged by the operation; otherwise they are
6982      * 'mapped'
6983      *
6984      * The lhs of the tr/// is here referred to as the t side.
6985      * The rhs of the tr/// is here referred to as the r side.
6986      */
6987
6988     SV * const tstr = ((SVOP*)expr)->op_sv;
6989     SV * const rstr = ((SVOP*)repl)->op_sv;
6990     STRLEN tlen;
6991     STRLEN rlen;
6992     const U8 * t0 = (U8*)SvPV_const(tstr, tlen);
6993     const U8 * r0 = (U8*)SvPV_const(rstr, rlen);
6994     const U8 * t = t0;
6995     const U8 * r = r0;
6996     UV t_count = 0, r_count = 0;  /* Number of characters in search and
6997                                          replacement lists */
6998
6999     /* khw thinks some of the private flags for this op are quaintly named.
7000      * OPpTRANS_GROWS for example is TRUE if the replacement for some lhs
7001      * character when represented in UTF-8 is longer than the original
7002      * character's UTF-8 representation */
7003     const bool complement = cBOOL(o->op_private & OPpTRANS_COMPLEMENT);
7004     const bool squash     = cBOOL(o->op_private & OPpTRANS_SQUASH);
7005     const bool del        = cBOOL(o->op_private & OPpTRANS_DELETE);
7006
7007     /* Set to true if there is some character < 256 in the lhs that maps to
7008      * above 255.  If so, a non-UTF-8 match string can be forced into being in
7009      * UTF-8 by a tr/// operation. */
7010     bool can_force_utf8 = FALSE;
7011
7012     /* What is the maximum expansion factor in UTF-8 transliterations.  If a
7013      * 2-byte UTF-8 encoded character is to be replaced by a 3-byte one, its
7014      * expansion factor is 1.5.  This number is used at runtime to calculate
7015      * how much space to allocate for non-inplace transliterations.  Without
7016      * this number, the worst case is 14, which is extremely unlikely to happen
7017      * in real life, and could require significant memory overhead. */
7018     NV max_expansion = 1.;
7019
7020     UV t_range_count, r_range_count, min_range_count;
7021     UV* t_array;
7022     SV* t_invlist;
7023     UV* r_map;
7024     UV r_cp, t_cp;
7025     UV t_cp_end = (UV) -1;
7026     UV r_cp_end;
7027     Size_t len;
7028     AV* invmap;
7029     UV final_map = TR_UNLISTED;    /* The final character in the replacement
7030                                       list, updated as we go along.  Initialize
7031                                       to something illegal */
7032
7033     bool rstr_utf8 = cBOOL(SvUTF8(rstr));
7034     bool tstr_utf8 = cBOOL(SvUTF8(tstr));
7035
7036     const U8* tend = t + tlen;
7037     const U8* rend = r + rlen;
7038
7039     SV * inverted_tstr = NULL;
7040
7041     Size_t i;
7042     unsigned int pass2;
7043
7044     /* This routine implements detection of a transliteration having a longer
7045      * UTF-8 representation than its source, by partitioning all the possible
7046      * code points of the platform into equivalence classes of the same UTF-8
7047      * byte length in the first pass.  As it constructs the mappings, it carves
7048      * these up into smaller chunks, but doesn't merge any together.  This
7049      * makes it easy to find the instances it's looking for.  A second pass is
7050      * done after this has been determined which merges things together to
7051      * shrink the table for runtime.  The table below is used for both ASCII
7052      * and EBCDIC platforms.  On EBCDIC, the byte length is not monotonically
7053      * increasing for code points below 256.  To correct for that, the macro
7054      * CP_ADJUST defined below converts those code points to ASCII in the first
7055      * pass, and we use the ASCII partition values.  That works because the
7056      * growth factor will be unaffected, which is all that is calculated during
7057      * the first pass. */
7058     UV PL_partition_by_byte_length[] = {
7059         0,
7060         0x80,   /* Below this is 1 byte representations */
7061         (32 * (1UL << (    UTF_ACCUMULATION_SHIFT))),   /* 2 bytes below this */
7062         (16 * (1UL << (2 * UTF_ACCUMULATION_SHIFT))),   /* 3 bytes below this */
7063         ( 8 * (1UL << (3 * UTF_ACCUMULATION_SHIFT))),   /* 4 bytes below this */
7064         ( 4 * (1UL << (4 * UTF_ACCUMULATION_SHIFT))),   /* 5 bytes below this */
7065         ( 2 * (1UL << (5 * UTF_ACCUMULATION_SHIFT)))    /* 6 bytes below this */
7066
7067 #  ifdef UV_IS_QUAD
7068                                                     ,
7069         ( ((UV) 1U << (6 * UTF_ACCUMULATION_SHIFT)))    /* 7 bytes below this */
7070 #  endif
7071
7072     };
7073
7074     PERL_ARGS_ASSERT_PMTRANS;
7075
7076     PL_hints |= HINT_BLOCK_SCOPE;
7077
7078     /* If /c, the search list is sorted and complemented.  This is now done by
7079      * creating an inversion list from it, and then trivially inverting that.
7080      * The previous implementation used qsort, but creating the list
7081      * automatically keeps it sorted as we go along */
7082     if (complement) {
7083         UV start, end;
7084         SV * inverted_tlist = _new_invlist(tlen);
7085         Size_t temp_len;
7086
7087         DEBUG_y(PerlIO_printf(Perl_debug_log,
7088                     "%s: %d: tstr before inversion=\n%s\n",
7089                     __FILE__, __LINE__, _byte_dump_string(t, tend - t, 0)));
7090
7091         while (t < tend) {
7092
7093             /* Non-utf8 strings don't have ranges, so each character is listed
7094              * out */
7095             if (! tstr_utf8) {
7096                 inverted_tlist = add_cp_to_invlist(inverted_tlist, *t);
7097                 t++;
7098             }
7099             else {  /* But UTF-8 strings have been parsed in toke.c to have
7100                  * ranges if appropriate. */
7101                 UV t_cp;
7102                 Size_t t_char_len;
7103
7104                 /* Get the first character */
7105                 t_cp = valid_utf8_to_uvchr(t, &t_char_len);
7106                 t += t_char_len;
7107
7108                 /* If the next byte indicates that this wasn't the first
7109                  * element of a range, the range is just this one */
7110                 if (t >= tend || *t != RANGE_INDICATOR) {
7111                     inverted_tlist = add_cp_to_invlist(inverted_tlist, t_cp);
7112                 }
7113                 else { /* Otherwise, ignore the indicator byte, and get the
7114                           final element, and add the whole range */
7115                     t++;
7116                     t_cp_end = valid_utf8_to_uvchr(t, &t_char_len);
7117                     t += t_char_len;
7118
7119                     inverted_tlist = _add_range_to_invlist(inverted_tlist,
7120                                                       t_cp, t_cp_end);
7121                 }
7122             }
7123         } /* End of parse through tstr */
7124
7125         /* The inversion list is done; now invert it */
7126         _invlist_invert(inverted_tlist);
7127
7128         /* Now go through the inverted list and create a new tstr for the rest
7129          * of the routine to use.  Since the UTF-8 version can have ranges, and
7130          * can be much more compact than the non-UTF-8 version, we create the
7131          * string in UTF-8 even if not necessary.  (This is just an intermediate
7132          * value that gets thrown away anyway.) */
7133         invlist_iterinit(inverted_tlist);
7134         inverted_tstr = newSVpvs("");
7135         while (invlist_iternext(inverted_tlist, &start, &end)) {
7136             U8 temp[UTF8_MAXBYTES];
7137             U8 * temp_end_pos;
7138
7139             /* IV_MAX keeps things from going out of bounds */
7140             start = MIN(IV_MAX, start);
7141             end   = MIN(IV_MAX, end);
7142
7143             temp_end_pos = uvchr_to_utf8(temp, start);
7144             sv_catpvn(inverted_tstr, (char *) temp, temp_end_pos - temp);
7145
7146             if (start != end) {
7147                 Perl_sv_catpvf(aTHX_ inverted_tstr, "%c", RANGE_INDICATOR);
7148                 temp_end_pos = uvchr_to_utf8(temp, end);
7149                 sv_catpvn(inverted_tstr, (char *) temp, temp_end_pos - temp);
7150             }
7151         }
7152
7153         /* Set up so the remainder of the routine uses this complement, instead
7154          * of the actual input */
7155         t0 = t = (U8*)SvPV_const(inverted_tstr, temp_len);
7156         tend = t0 + temp_len;
7157         tstr_utf8 = TRUE;
7158
7159         SvREFCNT_dec_NN(inverted_tlist);
7160     }
7161
7162     /* For non-/d, an empty rhs means to use the lhs */
7163     if (rlen == 0 && ! del) {
7164         r0 = t0;
7165         rend = tend;
7166         rstr_utf8  = tstr_utf8;
7167     }
7168
7169     t_invlist = _new_invlist(1);
7170
7171     /* Initialize to a single range */
7172     t_invlist = _add_range_to_invlist(t_invlist, 0, UV_MAX);
7173
7174     /* For the first pass, the lhs is partitioned such that the
7175      * number of UTF-8 bytes required to represent a code point in each
7176      * partition is the same as the number for any other code point in
7177      * that partion.  We copy the pre-compiled partion. */
7178     len = C_ARRAY_LENGTH(PL_partition_by_byte_length);
7179     invlist_extend(t_invlist, len);
7180     t_array = invlist_array(t_invlist);
7181     Copy(PL_partition_by_byte_length, t_array, len, UV);
7182     invlist_set_len(t_invlist, len, *(get_invlist_offset_addr(t_invlist)));
7183     Newx(r_map, len + 1, UV);
7184
7185     /* Parse the (potentially adjusted) input, creating the inversion map.
7186      * This is done in two passes.  The first pass is to determine if the
7187      * transliteration can be done in place.  The inversion map it creates
7188      * could be used, but generally would be larger and slower to run than the
7189      * output of the second pass, which starts with a more compact table and
7190      * allows more ranges to be merged */
7191     for (pass2 = 0; pass2 < 2; pass2++) {
7192         if (pass2) {
7193             /* Initialize to a single range */
7194             t_invlist = _add_range_to_invlist(t_invlist, 0, UV_MAX);
7195
7196             /* In the second pass, we just have the single range */
7197             len = 1;
7198             t_array = invlist_array(t_invlist);
7199         }
7200
7201 /* As noted earlier, we convert EBCDIC code points to Unicode in the first pass
7202  * so as to get the well-behaved length 1 vs length 2 boundary.  Only code
7203  * points below 256 differ between the two character sets in this regard.  For
7204  * these, we also can't have any ranges, as they have to be individually
7205  * converted. */
7206 #ifdef EBCDIC
7207 #  define CP_ADJUST(x)          ((pass2) ? (x) : NATIVE_TO_UNI(x))
7208 #  define FORCE_RANGE_LEN_1(x)  ((pass2) ? 0 : ((x) < 256))
7209 #  define CP_SKIP(x)            ((pass2) ? UVCHR_SKIP(x) : OFFUNISKIP(x))
7210 #else
7211 #  define CP_ADJUST(x)          (x)
7212 #  define FORCE_RANGE_LEN_1(x)  0
7213 #  define CP_SKIP(x)            UVCHR_SKIP(x)
7214 #endif
7215
7216         /* And the mapping of each of the ranges is initialized.  Initially,
7217          * everything is TR_UNLISTED. */
7218         for (i = 0; i < len; i++) {
7219             r_map[i] = TR_UNLISTED;
7220         }
7221
7222         t = t0;
7223         t_count = 0;
7224         r = r0;
7225         r_count = 0;
7226         t_range_count = r_range_count = 0;
7227
7228         DEBUG_y(PerlIO_printf(Perl_debug_log, "%s: %d:\ntstr=%s\n",
7229                     __FILE__, __LINE__, _byte_dump_string(t, tend - t, 0)));
7230         DEBUG_y(PerlIO_printf(Perl_debug_log, "rstr=%s\n",
7231                                         _byte_dump_string(r, rend - r, 0)));
7232         DEBUG_y(PerlIO_printf(Perl_debug_log, "/c=%d; /s=%d; /d=%d\n",
7233                                                   complement, squash, del));
7234         DEBUG_y(invmap_dump(t_invlist, r_map));
7235
7236         /* Now go through the search list constructing an inversion map.  The
7237          * input is not necessarily in any particular order.  Making it an
7238          * inversion map orders it, potentially simplifying, and makes it easy
7239          * to deal with at run time.  This is the only place in core that
7240          * generates an inversion map; if others were introduced, it might be
7241          * better to create general purpose routines to handle them.
7242          * (Inversion maps are created in perl in other places.)
7243          *
7244          * An inversion map consists of two parallel arrays.  One is
7245          * essentially an inversion list: an ordered list of code points such
7246          * that each element gives the first code point of a range of
7247          * consecutive code points that map to the element in the other array
7248          * that has the same index as this one (in other words, the
7249          * corresponding element).  Thus the range extends up to (but not
7250          * including) the code point given by the next higher element.  In a
7251          * true inversion map, the corresponding element in the other array
7252          * gives the mapping of the first code point in the range, with the
7253          * understanding that the next higher code point in the inversion
7254          * list's range will map to the next higher code point in the map.
7255          *
7256          * So if at element [i], let's say we have:
7257          *
7258          *     t_invlist  r_map
7259          * [i]    A         a
7260          *
7261          * This means that A => a, B => b, C => c....  Let's say that the
7262          * situation is such that:
7263          *
7264          * [i+1]  L        -1
7265          *
7266          * This means the sequence that started at [i] stops at K => k.  This
7267          * illustrates that you need to look at the next element to find where
7268          * a sequence stops.  Except, the highest element in the inversion list
7269          * begins a range that is understood to extend to the platform's
7270          * infinity.
7271          *
7272          * This routine modifies traditional inversion maps to reserve two
7273          * mappings:
7274          *
7275          *  TR_UNLISTED (or -1) indicates that no code point in the range
7276          *      is listed in the tr/// searchlist.  At runtime, these are
7277          *      always passed through unchanged.  In the inversion map, all
7278          *      points in the range are mapped to -1, instead of increasing,
7279          *      like the 'L' in the example above.
7280          *
7281          *      We start the parse with every code point mapped to this, and as
7282          *      we parse and find ones that are listed in the search list, we
7283          *      carve out ranges as we go along that override that.
7284          *
7285          *  TR_SPECIAL_HANDLING (or -2) indicates that every code point in the
7286          *      range needs special handling.  Again, all code points in the
7287          *      range are mapped to -2, instead of increasing.
7288          *
7289          *      Under /d this value means the code point should be deleted from
7290          *      the transliteration when encountered.
7291          *
7292          *      Otherwise, it marks that every code point in the range is to
7293          *      map to the final character in the replacement list.  This
7294          *      happens only when the replacement list is shorter than the
7295          *      search one, so there are things in the search list that have no
7296          *      correspondence in the replacement list.  For example, in
7297          *      tr/a-z/A/, 'A' is the final value, and the inversion map
7298          *      generated for this would be like this:
7299          *          \0  =>  -1
7300          *          a   =>   A
7301          *          b-z =>  -2
7302          *          z+1 =>  -1
7303          *      'A' appears once, then the remainder of the range maps to -2.
7304          *      The use of -2 isn't strictly necessary, as an inversion map is
7305          *      capable of representing this situation, but not nearly so
7306          *      compactly, and this is actually quite commonly encountered.
7307          *      Indeed, the original design of this code used a full inversion
7308          *      map for this.  But things like
7309          *          tr/\0-\x{FFFF}/A/
7310          *      generated huge data structures, slowly, and the execution was
7311          *      also slow.  So the current scheme was implemented.
7312          *
7313          *  So, if the next element in our example is:
7314          *
7315          * [i+2]  Q        q
7316          *
7317          * Then all of L, M, N, O, and P map to TR_UNLISTED.  If the next
7318          * elements are
7319          *
7320          * [i+3]  R        z
7321          * [i+4]  S       TR_UNLISTED
7322          *
7323          * Then Q => q; R => z; and S => TR_UNLISTED.  If [i+4] (the 'S') is
7324          * the final element in the arrays, every code point from S to infinity
7325          * maps to TR_UNLISTED.
7326          *
7327          */
7328                            /* Finish up range started in what otherwise would
7329                             * have been the final iteration */
7330         while (t < tend || t_range_count > 0) {
7331             bool adjacent_to_range_above = FALSE;
7332             bool adjacent_to_range_below = FALSE;
7333
7334             bool merge_with_range_above = FALSE;
7335             bool merge_with_range_below = FALSE;
7336
7337             UV span, invmap_range_length_remaining;
7338             SSize_t j;
7339             Size_t i;
7340
7341             /* If we are in the middle of processing a range in the 'target'
7342              * side, the previous iteration has set us up.  Otherwise, look at
7343              * the next character in the search list */
7344             if (t_range_count <= 0) {
7345                 if (! tstr_utf8) {
7346
7347                     /* Here, not in the middle of a range, and not UTF-8.  The
7348                      * next code point is the single byte where we're at */
7349                     t_cp = CP_ADJUST(*t);
7350                     t_range_count = 1;
7351                     t++;
7352                 }
7353                 else {
7354                     Size_t t_char_len;
7355
7356                     /* Here, not in the middle of a range, and is UTF-8.  The
7357                      * next code point is the next UTF-8 char in the input.  We
7358                      * know the input is valid, because the toker constructed
7359                      * it */
7360                     t_cp = CP_ADJUST(valid_utf8_to_uvchr(t, &t_char_len));
7361                     t += t_char_len;
7362
7363                     /* UTF-8 strings (only) have been parsed in toke.c to have
7364                      * ranges.  See if the next byte indicates that this was
7365                      * the first element of a range.  If so, get the final
7366                      * element and calculate the range size.  If not, the range
7367                      * size is 1 */
7368                     if (   t < tend && *t == RANGE_INDICATOR
7369                         && ! FORCE_RANGE_LEN_1(t_cp))
7370                     {
7371                         t++;
7372                         t_range_count = valid_utf8_to_uvchr(t, &t_char_len)
7373                                       - t_cp + 1;
7374                         t += t_char_len;
7375                     }
7376                     else {
7377                         t_range_count = 1;
7378                     }
7379                 }
7380
7381                 /* Count the total number of listed code points * */
7382                 t_count += t_range_count;
7383             }
7384
7385             /* Similarly, get the next character in the replacement list */
7386             if (r_range_count <= 0) {
7387                 if (r >= rend) {
7388
7389                     /* But if we've exhausted the rhs, there is nothing to map
7390                      * to, except the special handling one, and we make the
7391                      * range the same size as the lhs one. */
7392                     r_cp = TR_SPECIAL_HANDLING;
7393                     r_range_count = t_range_count;
7394
7395                     if (! del) {
7396                         DEBUG_yv(PerlIO_printf(Perl_debug_log,
7397                                         "final_map =%" UVXf "\n", final_map));
7398                     }
7399                 }
7400                 else {
7401                     if (! rstr_utf8) {
7402                         r_cp = CP_ADJUST(*r);
7403                         r_range_count = 1;
7404                         r++;
7405                     }
7406                     else {
7407                         Size_t r_char_len;
7408
7409                         r_cp = CP_ADJUST(valid_utf8_to_uvchr(r, &r_char_len));
7410                         r += r_char_len;
7411                         if (   r < rend && *r == RANGE_INDICATOR
7412                             && ! FORCE_RANGE_LEN_1(r_cp))
7413                         {
7414                             r++;
7415                             r_range_count = valid_utf8_to_uvchr(r,
7416                                                     &r_char_len) - r_cp + 1;
7417                             r += r_char_len;
7418                         }
7419                         else {
7420                             r_range_count = 1;
7421                         }
7422                     }
7423
7424                     if (r_cp == TR_SPECIAL_HANDLING) {
7425                         r_range_count = t_range_count;
7426                     }
7427
7428                     /* This is the final character so far */
7429                     final_map = r_cp + r_range_count - 1;
7430
7431                     r_count += r_range_count;
7432                 }
7433             }
7434
7435             /* Here, we have the next things ready in both sides.  They are
7436              * potentially ranges.  We try to process as big a chunk as
7437              * possible at once, but the lhs and rhs must be synchronized, so
7438              * things like tr/A-Z/a-ij-z/ will need to be processed in 2 chunks
7439              * */
7440             min_range_count = MIN(t_range_count, r_range_count);
7441
7442             /* Search the inversion list for the entry that contains the input
7443              * code point <cp>.  The inversion map was initialized to cover the
7444              * entire range of possible inputs, so this should not fail.  So
7445              * the return value is the index into the list's array of the range
7446              * that contains <cp>, that is, 'i' such that array[i] <= cp <
7447              * array[i+1] */
7448             j = _invlist_search(t_invlist, t_cp);
7449             assert(j >= 0);
7450             i = j;
7451
7452             /* Here, the data structure might look like:
7453              *
7454              * index    t   r     Meaning
7455              * [i-1]    J   j   # J-L => j-l
7456              * [i]      M  -1   # M => default; as do N, O, P, Q
7457              * [i+1]    R   x   # R => x, S => x+1, T => x+2
7458              * [i+2]    U   y   # U => y, V => y+1, ...
7459              * ...
7460              * [-1]     Z  -1   # Z => default; as do Z+1, ... infinity
7461              *
7462              * where 'x' and 'y' above are not to be taken literally.
7463              *
7464              * The maximum chunk we can handle in this loop iteration, is the
7465              * smallest of the three components: the lhs 't_', the rhs 'r_',
7466              * and the remainder of the range in element [i].  (In pass 1, that
7467              * range will have everything in it be of the same class; we can't
7468              * cross into another class.)  'min_range_count' already contains
7469              * the smallest of the first two values.  The final one is
7470              * irrelevant if the map is to the special indicator */
7471
7472             invmap_range_length_remaining = (i + 1 < len)
7473                                             ? t_array[i+1] - t_cp
7474                                             : IV_MAX - t_cp;
7475             span = MAX(1, MIN(min_range_count, invmap_range_length_remaining));
7476
7477             /* The end point of this chunk is where we are, plus the span, but
7478              * never larger than the platform's infinity */
7479             t_cp_end = MIN(IV_MAX, t_cp + span - 1);
7480
7481             if (r_cp == TR_SPECIAL_HANDLING) {
7482
7483                 /* If unmatched lhs code points map to the final map, use that
7484                  * value.  This being set to TR_SPECIAL_HANDLING indicates that
7485                  * we don't have a final map: unmatched lhs code points are
7486                  * simply deleted */
7487                 r_cp_end = (del) ? TR_SPECIAL_HANDLING : final_map;
7488             }
7489             else {
7490                 r_cp_end = MIN(IV_MAX, r_cp + span - 1);
7491
7492                 /* If something on the lhs is below 256, and something on the
7493                  * rhs is above, there is a potential mapping here across that
7494                  * boundary.  Indeed the only way there isn't is if both sides
7495                  * start at the same point.  That means they both cross at the
7496                  * same time.  But otherwise one crosses before the other */
7497                 if (t_cp < 256 && r_cp_end > 255 && r_cp != t_cp) {
7498                     can_force_utf8 = TRUE;
7499                 }
7500             }
7501
7502             /* If a character appears in the search list more than once, the
7503              * 2nd and succeeding occurrences are ignored, so only do this
7504              * range if haven't already processed this character.  (The range
7505              * has been set up so that all members in it will be of the same
7506              * ilk) */
7507             if (r_map[i] == TR_UNLISTED) {
7508                 DEBUG_yv(PerlIO_printf(Perl_debug_log,
7509                     "Processing %" UVxf "-%" UVxf " => %" UVxf "-%" UVxf "\n",
7510                     t_cp, t_cp_end, r_cp, r_cp_end));
7511
7512                 /* This is the first definition for this chunk, hence is valid
7513                  * and needs to be processed.  Here and in the comments below,
7514                  * we use the above sample data.  The t_cp chunk must be any
7515                  * contiguous subset of M, N, O, P, and/or Q.
7516                  *
7517                  * In the first pass, calculate if there is any possible input
7518                  * string that has a character whose transliteration will be
7519                  * longer than it.  If none, the transliteration may be done
7520                  * in-place, as it can't write over a so-far unread byte.
7521                  * Otherwise, a copy must first be made.  This could be
7522                  * expensive for long inputs.
7523                  *
7524                  * In the first pass, the t_invlist has been partitioned so
7525                  * that all elements in any single range have the same number
7526                  * of bytes in their UTF-8 representations.  And the r space is
7527                  * either a single byte, or a range of strictly monotonically
7528                  * increasing code points.  So the final element in the range
7529                  * will be represented by no fewer bytes than the initial one.
7530                  * That means that if the final code point in the t range has
7531                  * at least as many bytes as the final code point in the r,
7532                  * then all code points in the t range have at least as many
7533                  * bytes as their corresponding r range element.  But if that's
7534                  * not true, the transliteration of at least the final code
7535                  * point grows in length.  As an example, suppose we had
7536                  *      tr/\x{fff0}-\x{fff1}/\x{ffff}-\x{10000}/
7537                  * The UTF-8 for all but 10000 occupies 3 bytes on ASCII
7538                  * platforms.  We have deliberately set up the data structure
7539                  * so that any range in the lhs gets split into chunks for
7540                  * processing, such that every code point in a chunk has the
7541                  * same number of UTF-8 bytes.  We only have to check the final
7542                  * code point in the rhs against any code point in the lhs. */
7543                 if ( ! pass2
7544                     && r_cp_end != TR_SPECIAL_HANDLING
7545                     && CP_SKIP(t_cp_end) < CP_SKIP(r_cp_end))
7546                 {
7547                     /* Here, we will need to make a copy of the input string
7548                      * before doing the transliteration.  The worst possible
7549                      * case is an expansion ratio of 14:1. This is rare, and
7550                      * we'd rather allocate only the necessary amount of extra
7551                      * memory for that copy.  We can calculate the worst case
7552                      * for this particular transliteration is by keeping track
7553                      * of the expansion factor for each range.
7554                      *
7555                      * Consider tr/\xCB/\X{E000}/.  The maximum expansion
7556                      * factor is 1 byte going to 3 if the target string is not
7557                      * UTF-8, but 2 bytes going to 3 if it is in UTF-8.  We
7558                      * could pass two different values so doop could choose
7559                      * based on the UTF-8ness of the target.  But khw thinks
7560                      * (perhaps wrongly) that is overkill.  It is used only to
7561                      * make sure we malloc enough space.
7562                      *
7563                      * If no target string can force the result to be UTF-8,
7564                      * then we don't have to worry about the case of the target
7565                      * string not being UTF-8 */
7566                     NV t_size = (can_force_utf8 && t_cp < 256)
7567                                 ? 1
7568                                 : CP_SKIP(t_cp_end);
7569                     NV ratio = CP_SKIP(r_cp_end) / t_size;
7570
7571                     o->op_private |= OPpTRANS_GROWS;
7572
7573                     /* Now that we know it grows, we can keep track of the
7574                      * largest ratio */
7575                     if (ratio > max_expansion) {
7576                         max_expansion = ratio;
7577                         DEBUG_y(PerlIO_printf(Perl_debug_log,
7578                                         "New expansion factor: %" NVgf "\n",
7579                                         max_expansion));
7580                     }
7581                 }
7582
7583                 /* The very first range is marked as adjacent to the
7584                  * non-existent range below it, as it causes things to "just
7585                  * work" (TradeMark)
7586                  *
7587                  * If the lowest code point in this chunk is M, it adjoins the
7588                  * J-L range */
7589                 if (t_cp == t_array[i]) {
7590                     adjacent_to_range_below = TRUE;
7591
7592                     /* And if the map has the same offset from the beginning of
7593                      * the range as does this new code point (or both are for
7594                      * TR_SPECIAL_HANDLING), this chunk can be completely
7595                      * merged with the range below.  EXCEPT, in the first pass,
7596                      * we don't merge ranges whose UTF-8 byte representations
7597                      * have different lengths, so that we can more easily
7598                      * detect if a replacement is longer than the source, that
7599                      * is if it 'grows'.  But in the 2nd pass, there's no
7600                      * reason to not merge */
7601                     if (   (i > 0 && (   pass2
7602                                       || CP_SKIP(t_array[i-1])
7603                                                             == CP_SKIP(t_cp)))
7604                         && (   (   r_cp == TR_SPECIAL_HANDLING
7605                                 && r_map[i-1] == TR_SPECIAL_HANDLING)
7606                             || (   r_cp != TR_SPECIAL_HANDLING
7607                                 && r_cp - r_map[i-1] == t_cp - t_array[i-1])))
7608                     {
7609                         merge_with_range_below = TRUE;
7610                     }
7611                 }
7612
7613                 /* Similarly, if the highest code point in this chunk is 'Q',
7614                  * it adjoins the range above, and if the map is suitable, can
7615                  * be merged with it */
7616                 if (    t_cp_end >= IV_MAX - 1
7617                     || (   i + 1 < len
7618                         && t_cp_end + 1 == t_array[i+1]))
7619                 {
7620                     adjacent_to_range_above = TRUE;
7621                     if (i + 1 < len)
7622                     if (    (   pass2
7623                              || CP_SKIP(t_cp) == CP_SKIP(t_array[i+1]))
7624                         && (   (   r_cp == TR_SPECIAL_HANDLING
7625                                 && r_map[i+1] == (UV) TR_SPECIAL_HANDLING)
7626                             || (   r_cp != TR_SPECIAL_HANDLING
7627                                 && r_cp_end == r_map[i+1] - 1)))
7628                     {
7629                         merge_with_range_above = TRUE;
7630                     }
7631                 }
7632
7633                 if (merge_with_range_below && merge_with_range_above) {
7634
7635                     /* Here the new chunk looks like M => m, ... Q => q; and
7636                      * the range above is like R => r, ....  Thus, the [i-1]
7637                      * and [i+1] ranges should be seamlessly melded so the
7638                      * result looks like
7639                      *
7640                      * [i-1]    J   j   # J-T => j-t
7641                      * [i]      U   y   # U => y, V => y+1, ...
7642                      * ...
7643                      * [-1]     Z  -1   # Z => default; as do Z+1, ... infinity
7644                      */
7645                     Move(t_array + i + 2, t_array + i, len - i - 2, UV);
7646                     Move(r_map   + i + 2, r_map   + i, len - i - 2, UV);
7647                     len -= 2;
7648                     invlist_set_len(t_invlist,
7649                                     len,
7650                                     *(get_invlist_offset_addr(t_invlist)));
7651                 }
7652                 else if (merge_with_range_below) {
7653
7654                     /* Here the new chunk looks like M => m, .... But either
7655                      * (or both) it doesn't extend all the way up through Q; or
7656                      * the range above doesn't start with R => r. */
7657                     if (! adjacent_to_range_above) {
7658
7659                         /* In the first case, let's say the new chunk extends
7660                          * through O.  We then want:
7661                          *
7662                          * [i-1]    J   j   # J-O => j-o
7663                          * [i]      P  -1   # P => -1, Q => -1
7664                          * [i+1]    R   x   # R => x, S => x+1, T => x+2
7665                          * [i+2]    U   y   # U => y, V => y+1, ...
7666                          * ...
7667                          * [-1]     Z  -1   # Z => default; as do Z+1, ...
7668                          *                                            infinity
7669                          */
7670                         t_array[i] = t_cp_end + 1;
7671                         r_map[i] = TR_UNLISTED;
7672                     }
7673                     else { /* Adjoins the range above, but can't merge with it
7674                               (because 'x' is not the next map after q) */
7675                         /*
7676                          * [i-1]    J   j   # J-Q => j-q
7677                          * [i]      R   x   # R => x, S => x+1, T => x+2
7678                          * [i+1]    U   y   # U => y, V => y+1, ...
7679                          * ...
7680                          * [-1]     Z  -1   # Z => default; as do Z+1, ...
7681                          *                                          infinity
7682                          */
7683
7684                         Move(t_array + i + 1, t_array + i, len - i - 1, UV);
7685                         Move(r_map + i + 1, r_map + i, len - i - 1, UV);
7686                         len--;
7687                         invlist_set_len(t_invlist, len,
7688                                         *(get_invlist_offset_addr(t_invlist)));
7689                     }
7690                 }
7691                 else if (merge_with_range_above) {
7692
7693                     /* Here the new chunk ends with Q => q, and the range above
7694                      * must start with R => r, so the two can be merged. But
7695                      * either (or both) the new chunk doesn't extend all the
7696                      * way down to M; or the mapping of the final code point
7697                      * range below isn't m */
7698                     if (! adjacent_to_range_below) {
7699
7700                         /* In the first case, let's assume the new chunk starts
7701                          * with P => p.  Then, because it's merge-able with the
7702                          * range above, that range must be R => r.  We want:
7703                          *
7704                          * [i-1]    J   j   # J-L => j-l
7705                          * [i]      M  -1   # M => -1, N => -1
7706                          * [i+1]    P   p   # P-T => p-t
7707                          * [i+2]    U   y   # U => y, V => y+1, ...
7708                          * ...
7709                          * [-1]     Z  -1   # Z => default; as do Z+1, ...
7710                          *                                          infinity
7711                          */
7712                         t_array[i+1] = t_cp;
7713                         r_map[i+1] = r_cp;
7714                     }
7715                     else { /* Adjoins the range below, but can't merge with it
7716                             */
7717                         /*
7718                          * [i-1]    J   j   # J-L => j-l
7719                          * [i]      M   x   # M-T => x-5 .. x+2
7720                          * [i+1]    U   y   # U => y, V => y+1, ...
7721                          * ...
7722                          * [-1]     Z  -1   # Z => default; as do Z+1, ...
7723                          *                                          infinity
7724                          */
7725                         Move(t_array + i + 1, t_array + i, len - i - 1, UV);
7726                         Move(r_map   + i + 1, r_map   + i, len - i - 1, UV);
7727                         len--;
7728                         t_array[i] = t_cp;
7729                         r_map[i] = r_cp;
7730                         invlist_set_len(t_invlist, len,
7731                                         *(get_invlist_offset_addr(t_invlist)));
7732                     }
7733                 }
7734                 else if (adjacent_to_range_below && adjacent_to_range_above) {
7735                     /* The new chunk completely fills the gap between the
7736                      * ranges on either side, but can't merge with either of
7737                      * them.
7738                      *
7739                      * [i-1]    J   j   # J-L => j-l
7740                      * [i]      M   z   # M => z, N => z+1 ... Q => z+4
7741                      * [i+1]    R   x   # R => x, S => x+1, T => x+2
7742                      * [i+2]    U   y   # U => y, V => y+1, ...
7743                      * ...
7744                      * [-1]     Z  -1   # Z => default; as do Z+1, ... infinity
7745                      */
7746                     r_map[i] = r_cp;
7747                 }
7748                 else if (adjacent_to_range_below) {
7749                     /* The new chunk adjoins the range below, but not the range
7750                      * above, and can't merge.  Let's assume the chunk ends at
7751                      * O.
7752                      *
7753                      * [i-1]    J   j   # J-L => j-l
7754                      * [i]      M   z   # M => z, N => z+1, O => z+2
7755                      * [i+1]    P   -1  # P => -1, Q => -1
7756                      * [i+2]    R   x   # R => x, S => x+1, T => x+2
7757                      * [i+3]    U   y   # U => y, V => y+1, ...
7758                      * ...
7759                      * [-w]     Z  -1   # Z => default; as do Z+1, ... infinity
7760                      */
7761                     invlist_extend(t_invlist, len + 1);
7762                     t_array = invlist_array(t_invlist);
7763                     Renew(r_map, len + 1, UV);
7764
7765                     Move(t_array + i + 1, t_array + i + 2, len - i - 1, UV);
7766                     Move(r_map + i + 1,   r_map   + i + 2, len - i - 1, UV);
7767                     r_map[i] = r_cp;
7768                     t_array[i+1] = t_cp_end + 1;
7769                     r_map[i+1] = TR_UNLISTED;
7770                     len++;
7771                     invlist_set_len(t_invlist, len,
7772                                     *(get_invlist_offset_addr(t_invlist)));
7773                 }
7774                 else if (adjacent_to_range_above) {
7775                     /* The new chunk adjoins the range above, but not the range
7776                      * below, and can't merge.  Let's assume the new chunk
7777                      * starts at O
7778                      *
7779                      * [i-1]    J   j   # J-L => j-l
7780                      * [i]      M  -1   # M => default, N => default
7781                      * [i+1]    O   z   # O => z, P => z+1, Q => z+2
7782                      * [i+2]    R   x   # R => x, S => x+1, T => x+2
7783                      * [i+3]    U   y   # U => y, V => y+1, ...
7784                      * ...
7785                      * [-1]     Z  -1   # Z => default; as do Z+1, ... infinity
7786                      */
7787                     invlist_extend(t_invlist, len + 1);
7788                     t_array = invlist_array(t_invlist);
7789                     Renew(r_map, len + 1, UV);
7790
7791                     Move(t_array + i + 1, t_array + i + 2, len - i - 1, UV);
7792                     Move(r_map   + i + 1, r_map   + i + 2, len - i - 1, UV);
7793                     t_array[i+1] = t_cp;
7794                     r_map[i+1] = r_cp;
7795                     len++;
7796                     invlist_set_len(t_invlist, len,
7797                                     *(get_invlist_offset_addr(t_invlist)));
7798                 }
7799                 else {
7800                     /* The new chunk adjoins neither the range above, nor the
7801                      * range below.  Lets assume it is N..P => n..p
7802                      *
7803                      * [i-1]    J   j   # J-L => j-l
7804                      * [i]      M  -1   # M => default
7805                      * [i+1]    N   n   # N..P => n..p
7806                      * [i+2]    Q  -1   # Q => default
7807                      * [i+3]    R   x   # R => x, S => x+1, T => x+2
7808                      * [i+4]    U   y   # U => y, V => y+1, ...
7809                      * ...
7810                      * [-1]     Z  -1   # Z => default; as do Z+1, ... infinity
7811                      */
7812
7813                     DEBUG_yv(PerlIO_printf(Perl_debug_log,
7814                                         "Before fixing up: len=%d, i=%d\n",
7815                                         (int) len, (int) i));
7816                     DEBUG_yv(invmap_dump(t_invlist, r_map));
7817
7818                     invlist_extend(t_invlist, len + 2);
7819                     t_array = invlist_array(t_invlist);
7820                     Renew(r_map, len + 2, UV);
7821
7822                     Move(t_array + i + 1,
7823                          t_array + i + 2 + 1, len - i - (2 - 1), UV);
7824                     Move(r_map   + i + 1,
7825                          r_map   + i + 2 + 1, len - i - (2 - 1), UV);
7826
7827                     len += 2;
7828                     invlist_set_len(t_invlist, len,
7829                                     *(get_invlist_offset_addr(t_invlist)));
7830
7831                     t_array[i+1] = t_cp;
7832                     r_map[i+1] = r_cp;
7833
7834                     t_array[i+2] = t_cp_end + 1;
7835                     r_map[i+2] = TR_UNLISTED;
7836                 }
7837                 DEBUG_yv(PerlIO_printf(Perl_debug_log,
7838                           "After iteration: span=%" UVuf ", t_range_count=%"
7839                           UVuf " r_range_count=%" UVuf "\n",
7840                           span, t_range_count, r_range_count));
7841                 DEBUG_yv(invmap_dump(t_invlist, r_map));
7842             } /* End of this chunk needs to be processed */
7843
7844             /* Done with this chunk. */
7845             t_cp += span;
7846             if (t_cp >= IV_MAX) {
7847                 break;
7848             }
7849             t_range_count -= span;
7850             if (r_cp != TR_SPECIAL_HANDLING) {
7851                 r_cp += span;
7852                 r_range_count -= span;
7853             }
7854             else {
7855                 r_range_count = 0;
7856             }
7857
7858         } /* End of loop through the search list */
7859
7860         /* We don't need an exact count, but we do need to know if there is
7861          * anything left over in the replacement list.  So, just assume it's
7862          * one byte per character */
7863         if (rend > r) {
7864             r_count++;
7865         }
7866     } /* End of passes */
7867
7868     SvREFCNT_dec(inverted_tstr);
7869
7870     DEBUG_y(PerlIO_printf(Perl_debug_log, "After everything: \n"));
7871     DEBUG_y(invmap_dump(t_invlist, r_map));
7872
7873     /* We now have normalized the input into an inversion map.
7874      *
7875      * See if the lhs and rhs are equivalent.  If so, this tr/// is a no-op
7876      * except for the count, and streamlined runtime code can be used */
7877     if (!del && !squash) {
7878
7879         /* They are identical if they point to same address, or if everything
7880          * maps to UNLISTED or to itself.  This catches things that not looking
7881          * at the normalized inversion map doesn't catch, like tr/aa/ab/ or
7882          * tr/\x{100}-\x{104}/\x{100}-\x{102}\x{103}-\x{104}  */
7883         if (r0 != t0) {
7884             for (i = 0; i < len; i++) {
7885                 if (r_map[i] != TR_UNLISTED && r_map[i] != t_array[i]) {
7886                     goto done_identical_check;
7887                 }
7888             }
7889         }
7890
7891         /* Here have gone through entire list, and didn't find any
7892          * non-identical mappings */
7893         o->op_private |= OPpTRANS_IDENTICAL;
7894
7895       done_identical_check: ;
7896     }
7897
7898     t_array = invlist_array(t_invlist);
7899
7900     /* If has components above 255, we generally need to use the inversion map
7901      * implementation */
7902     if (   can_force_utf8
7903         || (   len > 0
7904             && t_array[len-1] > 255
7905                  /* If the final range is 0x100-INFINITY and is a special
7906                   * mapping, the table implementation can handle it */
7907             && ! (   t_array[len-1] == 256
7908                   && (   r_map[len-1] == TR_UNLISTED
7909                       || r_map[len-1] == TR_SPECIAL_HANDLING))))
7910     {
7911         SV* r_map_sv;
7912
7913         /* A UTF-8 op is generated, indicated by this flag.  This op is an
7914          * sv_op */
7915         o->op_private |= OPpTRANS_USE_SVOP;
7916
7917         if (can_force_utf8) {
7918             o->op_private |= OPpTRANS_CAN_FORCE_UTF8;
7919         }
7920
7921         /* The inversion map is pushed; first the list. */
7922         invmap = MUTABLE_AV(newAV());
7923         av_push(invmap, t_invlist);
7924
7925         /* 2nd is the mapping */
7926         r_map_sv = newSVpvn((char *) r_map, len * sizeof(UV));
7927         av_push(invmap, r_map_sv);
7928
7929         /* 3rd is the max possible expansion factor */
7930         av_push(invmap, newSVnv(max_expansion));
7931
7932         /* Characters that are in the search list, but not in the replacement
7933          * list are mapped to the final character in the replacement list */
7934         if (! del && r_count < t_count) {
7935             av_push(invmap, newSVuv(final_map));
7936         }
7937
7938 #ifdef USE_ITHREADS
7939         cPADOPo->op_padix = pad_alloc(OP_TRANS, SVf_READONLY);
7940         SvREFCNT_dec(PAD_SVl(cPADOPo->op_padix));
7941         PAD_SETSV(cPADOPo->op_padix, (SV *) invmap);
7942         SvPADTMP_on(invmap);
7943         SvREADONLY_on(invmap);
7944 #else
7945         cSVOPo->op_sv = (SV *) invmap;
7946 #endif
7947
7948     }
7949     else {
7950         OPtrans_map *tbl;
7951         unsigned short i;
7952
7953         /* The OPtrans_map struct already contains one slot; hence the -1. */
7954         SSize_t struct_size = sizeof(OPtrans_map)
7955                             + (256 - 1 + 1)*sizeof(short);
7956
7957         /* Non-utf8 case: set o->op_pv to point to a simple 256+ entry lookup
7958         * table. Entries with the value TR_UNMAPPED indicate chars not to be
7959         * translated, while TR_DELETE indicates a search char without a
7960         * corresponding replacement char under /d.
7961         *
7962         * In addition, an extra slot at the end is used to store the final
7963         * repeating char, or TR_R_EMPTY under an empty replacement list, or
7964         * TR_DELETE under /d; which makes the runtime code easier.
7965         */
7966
7967         /* Indicate this is an op_pv */
7968         o->op_private &= ~OPpTRANS_USE_SVOP;
7969
7970         tbl = (OPtrans_map*)PerlMemShared_calloc(struct_size, 1);
7971         tbl->size = 256;
7972         cPVOPo->op_pv = (char*)tbl;
7973
7974         for (i = 0; i < len; i++) {
7975             STATIC_ASSERT_DECL(TR_SPECIAL_HANDLING == TR_DELETE);
7976             short upper = i >= len - 1 ? 256 : (short) t_array[i+1];
7977             short to = (short) r_map[i];
7978             short j;
7979             bool do_increment = TRUE;
7980
7981             /* Any code points above our limit should be irrelevant */
7982             if (t_array[i] >= tbl->size) break;
7983
7984             /* Set up the map */
7985             if (to == (short) TR_SPECIAL_HANDLING && ! del) {
7986                 to = (short) final_map;
7987                 do_increment = FALSE;
7988             }
7989             else if (to < 0) {
7990                 do_increment = FALSE;
7991             }
7992
7993             /* Create a map for everything in this range.  The value increases
7994              * except for the special cases */
7995             for (j = (short) t_array[i]; j < upper; j++) {
7996                 tbl->map[j] = to;
7997                 if (do_increment) to++;
7998             }
7999         }
8000
8001         tbl->map[tbl->size] = del
8002                               ? (short) TR_DELETE
8003                               : (short) rlen
8004                                 ? (short) final_map
8005                                 : (short) TR_R_EMPTY;
8006         DEBUG_y(PerlIO_printf(Perl_debug_log,"%s: %d\n", __FILE__, __LINE__));
8007         for (i = 0; i < tbl->size; i++) {
8008             if (tbl->map[i] < 0) {
8009                 DEBUG_y(PerlIO_printf(Perl_debug_log," %02x=>%d",
8010                                                 (unsigned) i, tbl->map[i]));
8011             }
8012             else {
8013                 DEBUG_y(PerlIO_printf(Perl_debug_log," %02x=>%02x",
8014                                                 (unsigned) i, tbl->map[i]));
8015             }
8016             if ((i+1) % 8 == 0 || i + 1 == (short) tbl->size) {
8017                 DEBUG_y(PerlIO_printf(Perl_debug_log,"\n"));
8018             }
8019         }
8020         DEBUG_y(PerlIO_printf(Perl_debug_log,"Final map 0x%x=>%02x\n",
8021                                 (unsigned) tbl->size, tbl->map[tbl->size]));
8022
8023         SvREFCNT_dec(t_invlist);
8024
8025 #if 0   /* code that added excess above-255 chars at the end of the table, in
8026            case we ever want to not use the inversion map implementation for
8027            this */
8028
8029         ASSUME(j <= rlen);
8030         excess = rlen - j;
8031
8032         if (excess) {
8033             /* More replacement chars than search chars:
8034              * store excess replacement chars at end of main table.
8035              */
8036
8037             struct_size += excess;
8038             tbl = (OPtrans_map*)PerlMemShared_realloc(tbl,
8039                         struct_size + excess * sizeof(short));
8040             tbl->size += excess;
8041             cPVOPo->op_pv = (char*)tbl;
8042
8043             for (i = 0; i < excess; i++)
8044                 tbl->map[i + 256] = r[j+i];
8045         }
8046         else {
8047             /* no more replacement chars than search chars */
8048         }
8049 #endif
8050
8051     }
8052
8053     DEBUG_y(PerlIO_printf(Perl_debug_log,
8054             "/d=%d, /s=%d, /c=%d, identical=%d, grows=%d,"
8055             " use_svop=%d, can_force_utf8=%d,\nexpansion=%" NVgf "\n",
8056             del, squash, complement,
8057             cBOOL(o->op_private & OPpTRANS_IDENTICAL),
8058             cBOOL(o->op_private & OPpTRANS_USE_SVOP),
8059             cBOOL(o->op_private & OPpTRANS_GROWS),
8060             cBOOL(o->op_private & OPpTRANS_CAN_FORCE_UTF8),
8061             max_expansion));
8062
8063     Safefree(r_map);
8064
8065     if(del && rlen != 0 && r_count == t_count) {
8066         Perl_ck_warner(aTHX_ packWARN(WARN_MISC), "Useless use of /d modifier in transliteration operator");
8067     } else if(r_count > t_count) {
8068         Perl_ck_warner(aTHX_ packWARN(WARN_MISC), "Replacement list is longer than search list");
8069     }
8070
8071     op_free(expr);
8072     op_free(repl);
8073
8074     return o;
8075 }
8076
8077
8078 /*
8079 =for apidoc newPMOP
8080
8081 Constructs, checks, and returns an op of any pattern matching type.
8082 C<type> is the opcode.  C<flags> gives the eight bits of C<op_flags>
8083 and, shifted up eight bits, the eight bits of C<op_private>.
8084
8085 =cut
8086 */
8087
8088 OP *
8089 Perl_newPMOP(pTHX_ I32 type, I32 flags)
8090 {
8091     PMOP *pmop;
8092
8093     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_PMOP
8094         || type == OP_CUSTOM);
8095
8096     NewOp(1101, pmop, 1, PMOP);
8097     OpTYPE_set(pmop, type);
8098     pmop->op_flags = (U8)flags;
8099     pmop->op_private = (U8)(0 | (flags >> 8));
8100     if (PL_opargs[type] & OA_RETSCALAR)
8101         scalar((OP *)pmop);
8102
8103     if (PL_hints & HINT_RE_TAINT)
8104         pmop->op_pmflags |= PMf_RETAINT;
8105 #ifdef USE_LOCALE_CTYPE
8106     if (IN_LC_COMPILETIME(LC_CTYPE)) {
8107         set_regex_charset(&(pmop->op_pmflags), REGEX_LOCALE_CHARSET);
8108     }
8109     else
8110 #endif
8111          if (IN_UNI_8_BIT) {
8112         set_regex_charset(&(pmop->op_pmflags), REGEX_UNICODE_CHARSET);
8113     }
8114     if (PL_hints & HINT_RE_FLAGS) {
8115         SV *reflags = Perl_refcounted_he_fetch_pvn(aTHX_
8116          PL_compiling.cop_hints_hash, STR_WITH_LEN("reflags"), 0, 0
8117         );
8118         if (reflags && SvOK(reflags)) pmop->op_pmflags |= SvIV(reflags);
8119         reflags = Perl_refcounted_he_fetch_pvn(aTHX_
8120          PL_compiling.cop_hints_hash, STR_WITH_LEN("reflags_charset"), 0, 0
8121         );
8122         if (reflags && SvOK(reflags)) {
8123             set_regex_charset(&(pmop->op_pmflags), (regex_charset)SvIV(reflags));
8124         }
8125     }
8126
8127
8128 #ifdef USE_ITHREADS
8129     assert(SvPOK(PL_regex_pad[0]));
8130     if (SvCUR(PL_regex_pad[0])) {
8131         /* Pop off the "packed" IV from the end.  */
8132         SV *const repointer_list = PL_regex_pad[0];
8133         const char *p = SvEND(repointer_list) - sizeof(IV);
8134         const IV offset = *((IV*)p);
8135
8136         assert(SvCUR(repointer_list) % sizeof(IV) == 0);
8137
8138         SvEND_set(repointer_list, p);
8139
8140         pmop->op_pmoffset = offset;
8141         /* This slot should be free, so assert this:  */
8142         assert(PL_regex_pad[offset] == &PL_sv_undef);
8143     } else {
8144         SV * const repointer = &PL_sv_undef;
8145         av_push(PL_regex_padav, repointer);
8146         pmop->op_pmoffset = av_top_index(PL_regex_padav);
8147         PL_regex_pad = AvARRAY(PL_regex_padav);
8148     }
8149 #endif
8150
8151     return CHECKOP(type, pmop);
8152 }
8153
8154 static void
8155 S_set_haseval(pTHX)
8156 {
8157     PADOFFSET i = 1;
8158     PL_cv_has_eval = 1;
8159     /* Any pad names in scope are potentially lvalues.  */
8160     for (; i < PadnamelistMAXNAMED(PL_comppad_name); i++) {
8161         PADNAME *pn = PAD_COMPNAME_SV(i);
8162         if (!pn || !PadnameLEN(pn))
8163             continue;
8164         if (PadnameOUTER(pn) || PadnameIN_SCOPE(pn, PL_cop_seqmax))
8165             S_mark_padname_lvalue(aTHX_ pn);
8166     }
8167 }
8168
8169 /* Given some sort of match op o, and an expression expr containing a
8170  * pattern, either compile expr into a regex and attach it to o (if it's
8171  * constant), or convert expr into a runtime regcomp op sequence (if it's
8172  * not)
8173  *
8174  * Flags currently has 2 bits of meaning:
8175  * 1: isreg indicates that the pattern is part of a regex construct, eg
8176  *      $x =~ /pattern/ or split /pattern/, as opposed to $x =~ $pattern or
8177  *      split "pattern", which aren't. In the former case, expr will be a list
8178  *      if the pattern contains more than one term (eg /a$b/).
8179  * 2: The pattern is for a split.
8180  *
8181  * When the pattern has been compiled within a new anon CV (for
8182  * qr/(?{...})/ ), then floor indicates the savestack level just before
8183  * the new sub was created
8184  *
8185  * tr/// is also handled.
8186  */
8187
8188 OP *
8189 Perl_pmruntime(pTHX_ OP *o, OP *expr, OP *repl, UV flags, I32 floor)
8190 {
8191     PMOP *pm;
8192     LOGOP *rcop;
8193     I32 repl_has_vars = 0;
8194     bool is_trans = (o->op_type == OP_TRANS || o->op_type == OP_TRANSR);
8195     bool is_compiletime;
8196     bool has_code;
8197     bool isreg    = cBOOL(flags & 1);
8198     bool is_split = cBOOL(flags & 2);
8199
8200     PERL_ARGS_ASSERT_PMRUNTIME;
8201
8202     if (is_trans) {
8203         return pmtrans(o, expr, repl);
8204     }
8205
8206     /* find whether we have any runtime or code elements;
8207      * at the same time, temporarily set the op_next of each DO block;
8208      * then when we LINKLIST, this will cause the DO blocks to be excluded
8209      * from the op_next chain (and from having LINKLIST recursively
8210      * applied to them). We fix up the DOs specially later */
8211
8212     is_compiletime = 1;
8213     has_code = 0;
8214     if (expr->op_type == OP_LIST) {
8215         OP *child;
8216         for (child = cLISTOPx(expr)->op_first; child; child = OpSIBLING(child)) {
8217             if (child->op_type == OP_NULL && (child->op_flags & OPf_SPECIAL)) {
8218                 has_code = 1;
8219                 assert(!child->op_next);
8220                 if (UNLIKELY(!OpHAS_SIBLING(child))) {
8221                     assert(PL_parser && PL_parser->error_count);
8222                     /* This can happen with qr/ (?{(^{})/.  Just fake up
8223                        the op we were expecting to see, to avoid crashing
8224                        elsewhere.  */
8225                     op_sibling_splice(expr, child, 0,
8226                               newSVOP(OP_CONST, 0, &PL_sv_no));
8227                 }
8228                 child->op_next = OpSIBLING(child);
8229             }
8230             else if (child->op_type != OP_CONST && child->op_type != OP_PUSHMARK)
8231             is_compiletime = 0;
8232         }
8233     }
8234     else if (expr->op_type != OP_CONST)
8235         is_compiletime = 0;
8236
8237     LINKLIST(expr);
8238
8239     /* fix up DO blocks; treat each one as a separate little sub;
8240      * also, mark any arrays as LIST/REF */
8241
8242     if (expr->op_type == OP_LIST) {
8243         OP *child;
8244         for (child = cLISTOPx(expr)->op_first; child; child = OpSIBLING(child)) {
8245
8246             if (child->op_type == OP_PADAV || child->op_type == OP_RV2AV) {
8247                 assert( !(child->op_flags  & OPf_WANT));
8248                 /* push the array rather than its contents. The regex
8249                  * engine will retrieve and join the elements later */
8250                 child->op_flags |= (OPf_WANT_LIST | OPf_REF);
8251                 continue;
8252             }
8253
8254             if (!(child->op_type == OP_NULL && (child->op_flags & OPf_SPECIAL)))
8255                 continue;
8256             child->op_next = NULL; /* undo temporary hack from above */
8257             scalar(child);
8258             LINKLIST(child);
8259             if (cLISTOPx(child)->op_first->op_type == OP_LEAVE) {
8260                 LISTOP *leaveop = cLISTOPx(cLISTOPx(child)->op_first);
8261                 /* skip ENTER */
8262                 assert(leaveop->op_first->op_type == OP_ENTER);
8263                 assert(OpHAS_SIBLING(leaveop->op_first));
8264                 child->op_next = OpSIBLING(leaveop->op_first);
8265                 /* skip leave */
8266                 assert(leaveop->op_flags & OPf_KIDS);
8267                 assert(leaveop->op_last->op_next == (OP*)leaveop);
8268                 leaveop->op_next = NULL; /* stop on last op */
8269                 op_null((OP*)leaveop);
8270             }
8271             else {
8272                 /* skip SCOPE */
8273                 OP *scope = cLISTOPx(child)->op_first;
8274                 assert(scope->op_type == OP_SCOPE);
8275                 assert(scope->op_flags & OPf_KIDS);
8276                 scope->op_next = NULL; /* stop on last op */
8277                 op_null(scope);
8278             }
8279
8280             /* XXX optimize_optree() must be called on o before
8281              * CALL_PEEP(), as currently S_maybe_multiconcat() can't
8282              * currently cope with a peephole-optimised optree.
8283              * Calling optimize_optree() here ensures that condition
8284              * is met, but may mean optimize_optree() is applied
8285              * to the same optree later (where hopefully it won't do any
8286              * harm as it can't convert an op to multiconcat if it's
8287              * already been converted */
8288             optimize_optree(child);
8289
8290             /* have to peep the DOs individually as we've removed it from
8291              * the op_next chain */
8292             CALL_PEEP(child);
8293             S_prune_chain_head(&(child->op_next));
8294             if (is_compiletime)
8295                 /* runtime finalizes as part of finalizing whole tree */
8296                 finalize_optree(child);
8297         }
8298     }
8299     else if (expr->op_type == OP_PADAV || expr->op_type == OP_RV2AV) {
8300         assert( !(expr->op_flags  & OPf_WANT));
8301         /* push the array rather than its contents. The regex
8302          * engine will retrieve and join the elements later */
8303         expr->op_flags |= (OPf_WANT_LIST | OPf_REF);
8304     }
8305
8306     PL_hints |= HINT_BLOCK_SCOPE;
8307     pm = (PMOP*)o;
8308     assert(floor==0 || (pm->op_pmflags & PMf_HAS_CV));
8309
8310     if (is_compiletime) {
8311         U32 rx_flags = pm->op_pmflags & RXf_PMf_COMPILETIME;
8312         regexp_engine const *eng = current_re_engine();
8313
8314         if (is_split) {
8315             /* make engine handle split ' ' specially */
8316             pm->op_pmflags |= PMf_SPLIT;
8317             rx_flags |= RXf_SPLIT;
8318         }
8319
8320         if (!has_code || !eng->op_comp) {
8321             /* compile-time simple constant pattern */
8322
8323             if ((pm->op_pmflags & PMf_HAS_CV) && !has_code) {
8324                 /* whoops! we guessed that a qr// had a code block, but we
8325                  * were wrong (e.g. /[(?{}]/ ). Throw away the PL_compcv
8326                  * that isn't required now. Note that we have to be pretty
8327                  * confident that nothing used that CV's pad while the
8328                  * regex was parsed, except maybe op targets for \Q etc.
8329                  * If there were any op targets, though, they should have
8330                  * been stolen by constant folding.
8331                  */
8332 #ifdef DEBUGGING
8333                 SSize_t i = 0;
8334                 assert(PadnamelistMAXNAMED(PL_comppad_name) == 0);
8335                 while (++i <= AvFILLp(PL_comppad)) {
8336 #  ifdef USE_PAD_RESET
8337                     /* under USE_PAD_RESET, pad swipe replaces a swiped
8338                      * folded constant with a fresh padtmp */
8339                     assert(!PL_curpad[i] || SvPADTMP(PL_curpad[i]));
8340 #  else
8341                     assert(!PL_curpad[i]);
8342 #  endif
8343                 }
8344 #endif
8345                 /* This LEAVE_SCOPE will restore PL_compcv to point to the
8346                  * outer CV (the one whose slab holds the pm op). The
8347                  * inner CV (which holds expr) will be freed later, once
8348                  * all the entries on the parse stack have been popped on
8349                  * return from this function. Which is why its safe to
8350                  * call op_free(expr) below.
8351                  */
8352                 LEAVE_SCOPE(floor);
8353                 pm->op_pmflags &= ~PMf_HAS_CV;
8354             }
8355
8356             /* Skip compiling if parser found an error for this pattern */
8357             if (pm->op_pmflags & PMf_HAS_ERROR) {
8358                 return o;
8359             }
8360
8361             PM_SETRE(pm,
8362                 eng->op_comp
8363                     ? eng->op_comp(aTHX_ NULL, 0, expr, eng, NULL, NULL,
8364                                         rx_flags, pm->op_pmflags)
8365                     : Perl_re_op_compile(aTHX_ NULL, 0, expr, eng, NULL, NULL,
8366                                         rx_flags, pm->op_pmflags)
8367             );
8368             op_free(expr);
8369         }
8370         else {
8371             /* compile-time pattern that includes literal code blocks */
8372
8373             REGEXP* re;
8374
8375             /* Skip compiling if parser found an error for this pattern */
8376             if (pm->op_pmflags & PMf_HAS_ERROR) {
8377                 return o;
8378             }
8379
8380             re = eng->op_comp(aTHX_ NULL, 0, expr, eng, NULL, NULL,
8381                         rx_flags,
8382                         (pm->op_pmflags |
8383                             ((PL_hints & HINT_RE_EVAL) ? PMf_USE_RE_EVAL : 0))
8384                     );
8385             PM_SETRE(pm, re);
8386             if (pm->op_pmflags & PMf_HAS_CV) {
8387                 CV *cv;
8388                 /* this QR op (and the anon sub we embed it in) is never
8389                  * actually executed. It's just a placeholder where we can
8390                  * squirrel away expr in op_code_list without the peephole
8391                  * optimiser etc processing it for a second time */
8392                 OP *qr = newPMOP(OP_QR, 0);
8393                 ((PMOP*)qr)->op_code_list = expr;
8394
8395                 /* handle the implicit sub{} wrapped round the qr/(?{..})/ */
8396                 SvREFCNT_inc_simple_void(PL_compcv);
8397                 cv = newATTRSUB(floor, 0, NULL, NULL, qr);
8398                 ReANY(re)->qr_anoncv = cv;
8399
8400                 /* attach the anon CV to the pad so that
8401                  * pad_fixup_inner_anons() can find it */
8402                 (void)pad_add_anon(cv, o->op_type);
8403                 SvREFCNT_inc_simple_void(cv);
8404             }
8405             else {
8406                 pm->op_code_list = expr;
8407             }
8408         }
8409     }
8410     else {
8411         /* runtime pattern: build chain of regcomp etc ops */
8412         bool reglist;
8413         PADOFFSET cv_targ = 0;
8414
8415         reglist = isreg && expr->op_type == OP_LIST;
8416         if (reglist)
8417             op_null(expr);
8418
8419         if (has_code) {
8420             pm->op_code_list = expr;
8421             /* don't free op_code_list; its ops are embedded elsewhere too */
8422             pm->op_pmflags |= PMf_CODELIST_PRIVATE;
8423         }
8424
8425         if (is_split)
8426             /* make engine handle split ' ' specially */
8427             pm->op_pmflags |= PMf_SPLIT;
8428
8429         /* the OP_REGCMAYBE is a placeholder in the non-threaded case
8430          * to allow its op_next to be pointed past the regcomp and
8431          * preceding stacking ops;
8432          * OP_REGCRESET is there to reset taint before executing the
8433          * stacking ops */
8434         if (pm->op_pmflags & PMf_KEEP || TAINTING_get)
8435             expr = newUNOP((TAINTING_get ? OP_REGCRESET : OP_REGCMAYBE),0,expr);
8436
8437         if (pm->op_pmflags & PMf_HAS_CV) {
8438             /* we have a runtime qr with literal code. This means
8439              * that the qr// has been wrapped in a new CV, which
8440              * means that runtime consts, vars etc will have been compiled
8441              * against a new pad. So... we need to execute those ops
8442              * within the environment of the new CV. So wrap them in a call
8443              * to a new anon sub. i.e. for
8444              *
8445              *     qr/a$b(?{...})/,
8446              *
8447              * we build an anon sub that looks like
8448              *
8449              *     sub { "a", $b, '(?{...})' }
8450              *
8451              * and call it, passing the returned list to regcomp.
8452              * Or to put it another way, the list of ops that get executed
8453              * are:
8454              *
8455              *     normal              PMf_HAS_CV
8456              *     ------              -------------------
8457              *                         pushmark (for regcomp)
8458              *                         pushmark (for entersub)
8459              *                         anoncode
8460              *                         srefgen
8461              *                         entersub
8462              *     regcreset                  regcreset
8463              *     pushmark                   pushmark
8464              *     const("a")                 const("a")
8465              *     gvsv(b)                    gvsv(b)
8466              *     const("(?{...})")          const("(?{...})")
8467              *                                leavesub
8468              *     regcomp             regcomp
8469              */
8470
8471             SvREFCNT_inc_simple_void(PL_compcv);
8472             CvLVALUE_on(PL_compcv);
8473             /* these lines are just an unrolled newANONATTRSUB */
8474             expr = newSVOP(OP_ANONCODE, 0,
8475                     MUTABLE_SV(newATTRSUB(floor, 0, NULL, NULL, expr)));
8476             cv_targ = expr->op_targ;
8477             expr = newUNOP(OP_REFGEN, 0, expr);
8478
8479             expr = list(force_list(newUNOP(OP_ENTERSUB, 0, scalar(expr)), 1));
8480         }
8481
8482         rcop = alloc_LOGOP(OP_REGCOMP, scalar(expr), o);
8483         rcop->op_flags |=  ((PL_hints & HINT_RE_EVAL) ? OPf_SPECIAL : 0)
8484                            | (reglist ? OPf_STACKED : 0);
8485         rcop->op_targ = cv_targ;
8486
8487         /* /$x/ may cause an eval, since $x might be qr/(?{..})/  */
8488         if (PL_hints & HINT_RE_EVAL)
8489             S_set_haseval(aTHX);
8490
8491         /* establish postfix order */
8492         if (expr->op_type == OP_REGCRESET || expr->op_type == OP_REGCMAYBE) {
8493             LINKLIST(expr);
8494             rcop->op_next = expr;
8495             ((UNOP*)expr)->op_first->op_next = (OP*)rcop;
8496         }
8497         else {
8498             rcop->op_next = LINKLIST(expr);
8499             expr->op_next = (OP*)rcop;
8500         }
8501
8502         op_prepend_elem(o->op_type, scalar((OP*)rcop), o);
8503     }
8504
8505     if (repl) {
8506         OP *curop = repl;
8507         bool konst;
8508         /* If we are looking at s//.../e with a single statement, get past
8509            the implicit do{}. */
8510         if (curop->op_type == OP_NULL && curop->op_flags & OPf_KIDS
8511              && cUNOPx(curop)->op_first->op_type == OP_SCOPE
8512              && cUNOPx(curop)->op_first->op_flags & OPf_KIDS)
8513          {
8514             OP *sib;
8515             OP *kid = cUNOPx(cUNOPx(curop)->op_first)->op_first;
8516             if (kid->op_type == OP_NULL && (sib = OpSIBLING(kid))
8517              && !OpHAS_SIBLING(sib))
8518                 curop = sib;
8519         }
8520         if (curop->op_type == OP_CONST)
8521             konst = TRUE;
8522         else if (( (curop->op_type == OP_RV2SV ||
8523                     curop->op_type == OP_RV2AV ||
8524                     curop->op_type == OP_RV2HV ||
8525                     curop->op_type == OP_RV2GV)
8526                    && cUNOPx(curop)->op_first
8527                    && cUNOPx(curop)->op_first->op_type == OP_GV )
8528                 || curop->op_type == OP_PADSV
8529                 || curop->op_type == OP_PADAV
8530                 || curop->op_type == OP_PADHV
8531                 || curop->op_type == OP_PADANY) {
8532             repl_has_vars = 1;
8533             konst = TRUE;
8534         }
8535         else konst = FALSE;
8536         if (konst
8537             && !(repl_has_vars
8538                  && (!PM_GETRE(pm)
8539                      || !RX_PRELEN(PM_GETRE(pm))
8540                      || RX_EXTFLAGS(PM_GETRE(pm)) & RXf_EVAL_SEEN)))
8541         {
8542             pm->op_pmflags |= PMf_CONST;        /* const for long enough */
8543             op_prepend_elem(o->op_type, scalar(repl), o);
8544         }
8545         else {
8546             rcop = alloc_LOGOP(OP_SUBSTCONT, scalar(repl), o);
8547             rcop->op_private = 1;
8548
8549             /* establish postfix order */
8550             rcop->op_next = LINKLIST(repl);
8551             repl->op_next = (OP*)rcop;
8552
8553             pm->op_pmreplrootu.op_pmreplroot = scalar((OP*)rcop);
8554             assert(!(pm->op_pmflags & PMf_ONCE));
8555             pm->op_pmstashstartu.op_pmreplstart = LINKLIST(rcop);
8556             rcop->op_next = 0;
8557         }
8558     }
8559
8560     return (OP*)pm;
8561 }
8562
8563 /*
8564 =for apidoc newSVOP
8565
8566 Constructs, checks, and returns an op of any type that involves an
8567 embedded SV.  C<type> is the opcode.  C<flags> gives the eight bits
8568 of C<op_flags>.  C<sv> gives the SV to embed in the op; this function
8569 takes ownership of one reference to it.
8570
8571 =cut
8572 */
8573
8574 OP *
8575 Perl_newSVOP(pTHX_ I32 type, I32 flags, SV *sv)
8576 {
8577     SVOP *svop;
8578
8579     PERL_ARGS_ASSERT_NEWSVOP;
8580
8581     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_SVOP
8582         || (PL_opargs[type] & OA_CLASS_MASK) == OA_PVOP_OR_SVOP
8583         || (PL_opargs[type] & OA_CLASS_MASK) == OA_FILESTATOP
8584         || type == OP_CUSTOM);
8585
8586     NewOp(1101, svop, 1, SVOP);
8587     OpTYPE_set(svop, type);
8588     svop->op_sv = sv;
8589     svop->op_next = (OP*)svop;
8590     svop->op_flags = (U8)flags;
8591     svop->op_private = (U8)(0 | (flags >> 8));
8592     if (PL_opargs[type] & OA_RETSCALAR)
8593         scalar((OP*)svop);
8594     if (PL_opargs[type] & OA_TARGET)
8595         svop->op_targ = pad_alloc(type, SVs_PADTMP);
8596     return CHECKOP(type, svop);
8597 }
8598
8599 /*
8600 =for apidoc newDEFSVOP
8601
8602 Constructs and returns an op to access C<$_>.
8603
8604 =cut
8605 */
8606
8607 OP *
8608 Perl_newDEFSVOP(pTHX)
8609 {
8610         return newSVREF(newGVOP(OP_GV, 0, PL_defgv));
8611 }
8612
8613 #ifdef USE_ITHREADS
8614
8615 /*
8616 =for apidoc newPADOP
8617
8618 Constructs, checks, and returns an op of any type that involves a
8619 reference to a pad element.  C<type> is the opcode.  C<flags> gives the
8620 eight bits of C<op_flags>.  A pad slot is automatically allocated, and
8621 is populated with C<sv>; this function takes ownership of one reference
8622 to it.
8623
8624 This function only exists if Perl has been compiled to use ithreads.
8625
8626 =cut
8627 */
8628
8629 OP *
8630 Perl_newPADOP(pTHX_ I32 type, I32 flags, SV *sv)
8631 {
8632     PADOP *padop;
8633
8634     PERL_ARGS_ASSERT_NEWPADOP;
8635
8636     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_SVOP
8637         || (PL_opargs[type] & OA_CLASS_MASK) == OA_PVOP_OR_SVOP
8638         || (PL_opargs[type] & OA_CLASS_MASK) == OA_FILESTATOP
8639         || type == OP_CUSTOM);
8640
8641     NewOp(1101, padop, 1, PADOP);
8642     OpTYPE_set(padop, type);
8643     padop->op_padix =
8644         pad_alloc(type, isGV(sv) ? SVf_READONLY : SVs_PADTMP);
8645     SvREFCNT_dec(PAD_SVl(padop->op_padix));
8646     PAD_SETSV(padop->op_padix, sv);
8647     assert(sv);
8648     padop->op_next = (OP*)padop;
8649     padop->op_flags = (U8)flags;
8650     if (PL_opargs[type] & OA_RETSCALAR)
8651         scalar((OP*)padop);
8652     if (PL_opargs[type] & OA_TARGET)
8653         padop->op_targ = pad_alloc(type, SVs_PADTMP);
8654     return CHECKOP(type, padop);
8655 }
8656
8657 #endif /* USE_ITHREADS */
8658
8659 /*
8660 =for apidoc newGVOP
8661
8662 Constructs, checks, and returns an op of any type that involves an
8663 embedded reference to a GV.  C<type> is the opcode.  C<flags> gives the
8664 eight bits of C<op_flags>.  C<gv> identifies the GV that the op should
8665 reference; calling this function does not transfer ownership of any
8666 reference to it.
8667
8668 =cut
8669 */
8670
8671 OP *
8672 Perl_newGVOP(pTHX_ I32 type, I32 flags, GV *gv)
8673 {
8674     PERL_ARGS_ASSERT_NEWGVOP;
8675
8676 #ifdef USE_ITHREADS
8677     return newPADOP(type, flags, SvREFCNT_inc_simple_NN(gv));
8678 #else
8679     return newSVOP(type, flags, SvREFCNT_inc_simple_NN(gv));
8680 #endif
8681 }
8682
8683 /*
8684 =for apidoc newPVOP
8685
8686 Constructs, checks, and returns an op of any type that involves an
8687 embedded C-level pointer (PV).  C<type> is the opcode.  C<flags> gives
8688 the eight bits of C<op_flags>.  C<pv> supplies the C-level pointer.
8689 Depending on the op type, the memory referenced by C<pv> may be freed
8690 when the op is destroyed.  If the op is of a freeing type, C<pv> must
8691 have been allocated using C<PerlMemShared_malloc>.
8692
8693 =cut
8694 */
8695
8696 OP *
8697 Perl_newPVOP(pTHX_ I32 type, I32 flags, char *pv)
8698 {
8699     const bool utf8 = cBOOL(flags & SVf_UTF8);
8700     PVOP *pvop;
8701
8702     flags &= ~SVf_UTF8;
8703
8704     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_PVOP_OR_SVOP
8705         || type == OP_RUNCV || type == OP_CUSTOM
8706         || (PL_opargs[type] & OA_CLASS_MASK) == OA_LOOPEXOP);
8707
8708     NewOp(1101, pvop, 1, PVOP);
8709     OpTYPE_set(pvop, type);
8710     pvop->op_pv = pv;
8711     pvop->op_next = (OP*)pvop;
8712     pvop->op_flags = (U8)flags;
8713     pvop->op_private = utf8 ? OPpPV_IS_UTF8 : 0;
8714     if (PL_opargs[type] & OA_RETSCALAR)
8715         scalar((OP*)pvop);
8716     if (PL_opargs[type] & OA_TARGET)
8717         pvop->op_targ = pad_alloc(type, SVs_PADTMP);
8718     return CHECKOP(type, pvop);
8719 }
8720
8721 void
8722 Perl_package(pTHX_ OP *o)
8723 {
8724     SV *const sv = cSVOPo->op_sv;
8725
8726     PERL_ARGS_ASSERT_PACKAGE;
8727
8728     SAVEGENERICSV(PL_curstash);
8729     save_item(PL_curstname);
8730
8731     PL_curstash = (HV *)SvREFCNT_inc(gv_stashsv(sv, GV_ADD));
8732
8733     sv_setsv(PL_curstname, sv);
8734
8735     PL_hints |= HINT_BLOCK_SCOPE;
8736     PL_parser->copline = NOLINE;
8737
8738     op_free(o);
8739 }
8740
8741 void
8742 Perl_package_version( pTHX_ OP *v )
8743 {
8744     U32 savehints = PL_hints;
8745     PERL_ARGS_ASSERT_PACKAGE_VERSION;
8746     PL_hints &= ~HINT_STRICT_VARS;
8747     sv_setsv( GvSV(gv_fetchpvs("VERSION", GV_ADDMULTI, SVt_PV)), cSVOPx(v)->op_sv );
8748     PL_hints = savehints;
8749     op_free(v);
8750 }
8751
8752 void
8753 Perl_utilize(pTHX_ int aver, I32 floor, OP *version, OP *idop, OP *arg)
8754 {
8755     OP *pack;
8756     OP *imop;
8757     OP *veop;
8758     SV *use_version = NULL;
8759
8760     PERL_ARGS_ASSERT_UTILIZE;
8761
8762     if (idop->op_type != OP_CONST)
8763         Perl_croak(aTHX_ "Module name must be constant");
8764
8765     veop = NULL;
8766
8767     if (version) {
8768         SV * const vesv = ((SVOP*)version)->op_sv;
8769
8770         if (!arg && !SvNIOKp(vesv)) {
8771             arg = version;
8772         }
8773         else {
8774             OP *pack;
8775             SV *meth;
8776
8777             if (version->op_type != OP_CONST || !SvNIOKp(vesv))
8778                 Perl_croak(aTHX_ "Version number must be a constant number");
8779
8780             /* Make copy of idop so we don't free it twice */
8781             pack = newSVOP(OP_CONST, 0, newSVsv(((SVOP*)idop)->op_sv));
8782
8783             /* Fake up a method call to VERSION */
8784             meth = newSVpvs_share("VERSION");
8785             veop = op_convert_list(OP_ENTERSUB, OPf_STACKED|OPf_SPECIAL,
8786                             op_append_elem(OP_LIST,
8787                                         op_prepend_elem(OP_LIST, pack, version),
8788                                         newMETHOP_named(OP_METHOD_NAMED, 0, meth)));
8789         }
8790     }
8791
8792     /* Fake up an import/unimport */
8793     if (arg && arg->op_type == OP_STUB) {
8794         imop = arg;             /* no import on explicit () */
8795     }
8796     else if (SvNIOKp(((SVOP*)idop)->op_sv)) {
8797         imop = NULL;            /* use 5.0; */
8798         if (aver)
8799             use_version = ((SVOP*)idop)->op_sv;
8800         else
8801             idop->op_private |= OPpCONST_NOVER;
8802     }
8803     else {
8804         SV *meth;
8805
8806         /* Make copy of idop so we don't free it twice */
8807         pack = newSVOP(OP_CONST, 0, newSVsv(((SVOP*)idop)->op_sv));
8808
8809         /* Fake up a method call to import/unimport */
8810         meth = aver
8811             ? newSVpvs_share("import") : newSVpvs_share("unimport");
8812         imop = op_convert_list(OP_ENTERSUB, OPf_STACKED|OPf_SPECIAL,
8813                        op_append_elem(OP_LIST,
8814                                    op_prepend_elem(OP_LIST, pack, arg),
8815                                    newMETHOP_named(OP_METHOD_NAMED, 0, meth)
8816                        ));
8817     }
8818
8819     /* Fake up the BEGIN {}, which does its thing immediately. */
8820     newATTRSUB(floor,
8821         newSVOP(OP_CONST, 0, newSVpvs_share("BEGIN")),
8822         NULL,
8823         NULL,
8824         op_append_elem(OP_LINESEQ,
8825             op_append_elem(OP_LINESEQ,
8826                 newSTATEOP(0, NULL, newUNOP(OP_REQUIRE, 0, idop)),
8827                 newSTATEOP(0, NULL, veop)),
8828             newSTATEOP(0, NULL, imop) ));
8829
8830     if (use_version) {
8831         /* Enable the
8832          * feature bundle that corresponds to the required version. */
8833         use_version = sv_2mortal(new_version(use_version));
8834         S_enable_feature_bundle(aTHX_ use_version);
8835
8836         /* If a version >= 5.11.0 is requested, strictures are on by default! */
8837         if (vcmp(use_version,
8838                  sv_2mortal(upg_version(newSVnv(5.011000), FALSE))) >= 0) {
8839             if (!(PL_hints & HINT_EXPLICIT_STRICT_REFS))
8840                 PL_hints |= HINT_STRICT_REFS;
8841             if (!(PL_hints & HINT_EXPLICIT_STRICT_SUBS))
8842                 PL_hints |= HINT_STRICT_SUBS;
8843             if (!(PL_hints & HINT_EXPLICIT_STRICT_VARS))
8844                 PL_hints |= HINT_STRICT_VARS;
8845         }
8846         /* otherwise they are off */
8847         else {
8848             if (!(PL_hints & HINT_EXPLICIT_STRICT_REFS))
8849                 PL_hints &= ~HINT_STRICT_REFS;
8850             if (!(PL_hints & HINT_EXPLICIT_STRICT_SUBS))
8851                 PL_hints &= ~HINT_STRICT_SUBS;
8852             if (!(PL_hints & HINT_EXPLICIT_STRICT_VARS))
8853                 PL_hints &= ~HINT_STRICT_VARS;
8854         }
8855     }
8856
8857     /* The "did you use incorrect case?" warning used to be here.
8858      * The problem is that on case-insensitive filesystems one
8859      * might get false positives for "use" (and "require"):
8860      * "use Strict" or "require CARP" will work.  This causes
8861      * portability problems for the script: in case-strict
8862      * filesystems the script will stop working.
8863      *
8864      * The "incorrect case" warning checked whether "use Foo"
8865      * imported "Foo" to your namespace, but that is wrong, too:
8866      * there is no requirement nor promise in the language that
8867      * a Foo.pm should or would contain anything in package "Foo".
8868      *
8869      * There is very little Configure-wise that can be done, either:
8870      * the case-sensitivity of the build filesystem of Perl does not
8871      * help in guessing the case-sensitivity of the runtime environment.
8872      */
8873
8874     PL_hints |= HINT_BLOCK_SCOPE;
8875     PL_parser->copline = NOLINE;
8876     COP_SEQMAX_INC; /* Purely for B::*'s benefit */
8877 }
8878
8879 /*
8880 =for apidoc_section Embedding and Interpreter Cloning
8881
8882 =for apidoc load_module
8883
8884 Loads the module whose name is pointed to by the string part of C<name>.
8885 Note that the actual module name, not its filename, should be given.
8886 Eg, "Foo::Bar" instead of "Foo/Bar.pm". ver, if specified and not NULL,
8887 provides version semantics similar to C<use Foo::Bar VERSION>. The optional
8888 trailing arguments can be used to specify arguments to the module's C<import()>
8889 method, similar to C<use Foo::Bar VERSION LIST>; their precise handling depends
8890 on the flags. The flags argument is a bitwise-ORed collection of any of
8891 C<PERL_LOADMOD_DENY>, C<PERL_LOADMOD_NOIMPORT>, or C<PERL_LOADMOD_IMPORT_OPS>
8892 (or 0 for no flags).
8893
8894 If C<PERL_LOADMOD_NOIMPORT> is set, the module is loaded as if with an empty
8895 import list, as in C<use Foo::Bar ()>; this is the only circumstance in which
8896 the trailing optional arguments may be omitted entirely. Otherwise, if
8897 C<PERL_LOADMOD_IMPORT_OPS> is set, the trailing arguments must consist of
8898 exactly one C<OP*>, containing the op tree that produces the relevant import
8899 arguments. Otherwise, the trailing arguments must all be C<SV*> values that
8900 will be used as import arguments; and the list must be terminated with C<(SV*)
8901 NULL>. If neither C<PERL_LOADMOD_NOIMPORT> nor C<PERL_LOADMOD_IMPORT_OPS> is
8902 set, the trailing C<NULL> pointer is needed even if no import arguments are
8903 desired. The reference count for each specified C<SV*> argument is
8904 decremented. In addition, the C<name> argument is modified.
8905
8906 If C<PERL_LOADMOD_DENY> is set, the module is loaded as if with C<no> rather
8907 than C<use>.
8908
8909 =for apidoc Amnh||PERL_LOADMOD_DENY
8910 =for apidoc Amnh||PERL_LOADMOD_NOIMPORT
8911 =for apidoc Amnh||PERL_LOADMOD_IMPORT_OPS
8912
8913 =for apidoc load_module_nocontext
8914 Like C<L</load_module>> but does not take a thread context (C<aTHX>) parameter,
8915 so is used in situations where the caller doesn't already have the thread
8916 context.
8917
8918 =cut */
8919
8920 void
8921 Perl_load_module(pTHX_ U32 flags, SV *name, SV *ver, ...)
8922 {
8923     va_list args;
8924
8925     PERL_ARGS_ASSERT_LOAD_MODULE;
8926
8927     va_start(args, ver);
8928     vload_module(flags, name, ver, &args);
8929     va_end(args);
8930 }
8931
8932 #ifdef PERL_IMPLICIT_CONTEXT
8933 void
8934 Perl_load_module_nocontext(U32 flags, SV *name, SV *ver, ...)
8935 {
8936     dTHX;
8937     va_list args;
8938     PERL_ARGS_ASSERT_LOAD_MODULE_NOCONTEXT;
8939     va_start(args, ver);
8940     vload_module(flags, name, ver, &args);
8941     va_end(args);
8942 }
8943 #endif
8944
8945 void
8946 Perl_vload_module(pTHX_ U32 flags, SV *name, SV *ver, va_list *args)
8947 {
8948     OP *veop, *imop;
8949     OP * modname;
8950     I32 floor;
8951
8952     PERL_ARGS_ASSERT_VLOAD_MODULE;
8953
8954     /* utilize() fakes up a BEGIN { require ..; import ... }, so make sure
8955      * that it has a PL_parser to play with while doing that, and also
8956      * that it doesn't mess with any existing parser, by creating a tmp
8957      * new parser with lex_start(). This won't actually be used for much,
8958      * since pp_require() will create another parser for the real work.
8959      * The ENTER/LEAVE pair protect callers from any side effects of use.
8960      *
8961      * start_subparse() creates a new PL_compcv. This means that any ops
8962      * allocated below will be allocated from that CV's op slab, and so
8963      * will be automatically freed if the utilise() fails
8964      */
8965
8966     ENTER;
8967     SAVEVPTR(PL_curcop);
8968     lex_start(NULL, NULL, LEX_START_SAME_FILTER);
8969     floor = start_subparse(FALSE, 0);
8970
8971     modname = newSVOP(OP_CONST, 0, name);
8972     modname->op_private |= OPpCONST_BARE;
8973     if (ver) {
8974         veop = newSVOP(OP_CONST, 0, ver);
8975     }
8976     else
8977         veop = NULL;
8978     if (flags & PERL_LOADMOD_NOIMPORT) {
8979         imop = sawparens(newNULLLIST());
8980     }
8981     else if (flags & PERL_LOADMOD_IMPORT_OPS) {
8982         imop = va_arg(*args, OP*);
8983     }
8984     else {
8985         SV *sv;
8986         imop = NULL;
8987         sv = va_arg(*args, SV*);
8988         while (sv) {
8989             imop = op_append_elem(OP_LIST, imop, newSVOP(OP_CONST, 0, sv));
8990             sv = va_arg(*args, SV*);
8991         }
8992     }
8993
8994     utilize(!(flags & PERL_LOADMOD_DENY), floor, veop, modname, imop);
8995     LEAVE;
8996 }
8997
8998 PERL_STATIC_INLINE OP *
8999 S_new_entersubop(pTHX_ GV *gv, OP *arg)
9000 {
9001     return newUNOP(OP_ENTERSUB, OPf_STACKED,
9002                    newLISTOP(OP_LIST, 0, arg,
9003                              newUNOP(OP_RV2CV, 0,
9004                                      newGVOP(OP_GV, 0, gv))));
9005 }
9006
9007 OP *
9008 Perl_dofile(pTHX_ OP *term, I32 force_builtin)
9009 {
9010     OP *doop;
9011     GV *gv;
9012
9013     PERL_ARGS_ASSERT_DOFILE;
9014
9015     if (!force_builtin && (gv = gv_override("do", 2))) {
9016         doop = S_new_entersubop(aTHX_ gv, term);
9017     }
9018     else {
9019         doop = newUNOP(OP_DOFILE, 0, scalar(term));
9020     }
9021     return doop;
9022 }
9023
9024 /*
9025 =for apidoc_section Optree construction
9026
9027 =for apidoc newSLICEOP
9028
9029 Constructs, checks, and returns an C<lslice> (list slice) op.  C<flags>
9030 gives the eight bits of C<op_flags>, except that C<OPf_KIDS> will
9031 be set automatically, and, shifted up eight bits, the eight bits of
9032 C<op_private>, except that the bit with value 1 or 2 is automatically
9033 set as required.  C<listval> and C<subscript> supply the parameters of
9034 the slice; they are consumed by this function and become part of the
9035 constructed op tree.
9036
9037 =cut
9038 */
9039
9040 OP *
9041 Perl_newSLICEOP(pTHX_ I32 flags, OP *subscript, OP *listval)
9042 {
9043     return newBINOP(OP_LSLICE, flags,
9044             list(force_list(subscript, 1)),
9045             list(force_list(listval,   1)) );
9046 }
9047
9048 #define ASSIGN_SCALAR 0
9049 #define ASSIGN_LIST   1
9050 #define ASSIGN_REF    2
9051
9052 /* given the optree o on the LHS of an assignment, determine whether its:
9053  *  ASSIGN_SCALAR   $x  = ...
9054  *  ASSIGN_LIST    ($x) = ...
9055  *  ASSIGN_REF     \$x  = ...
9056  */
9057
9058 STATIC I32
9059 S_assignment_type(pTHX_ const OP *o)
9060 {
9061     unsigned type;
9062     U8 flags;
9063     U8 ret;
9064
9065     if (!o)
9066         return ASSIGN_LIST;
9067
9068     if (o->op_type == OP_SREFGEN)
9069     {
9070         OP * const kid = cUNOPx(cUNOPo->op_first)->op_first;
9071         type = kid->op_type;
9072         flags = o->op_flags | kid->op_flags;
9073         if (!(flags & OPf_PARENS)
9074           && (kid->op_type == OP_RV2AV || kid->op_type == OP_PADAV ||
9075               kid->op_type == OP_RV2HV || kid->op_type == OP_PADHV ))
9076             return ASSIGN_REF;
9077         ret = ASSIGN_REF;
9078     } else {
9079         if ((o->op_type == OP_NULL) && (o->op_flags & OPf_KIDS))
9080             o = cUNOPo->op_first;
9081         flags = o->op_flags;
9082         type = o->op_type;
9083         ret = ASSIGN_SCALAR;
9084     }
9085
9086     if (type == OP_COND_EXPR) {
9087         OP * const sib = OpSIBLING(cLOGOPo->op_first);
9088         const I32 t = assignment_type(sib);
9089         const I32 f = assignment_type(OpSIBLING(sib));
9090
9091         if (t == ASSIGN_LIST && f == ASSIGN_LIST)
9092             return ASSIGN_LIST;
9093         if ((t == ASSIGN_LIST) ^ (f == ASSIGN_LIST))
9094             yyerror("Assignment to both a list and a scalar");
9095         return ASSIGN_SCALAR;
9096     }
9097
9098     if (type == OP_LIST &&
9099         (flags & OPf_WANT) == OPf_WANT_SCALAR &&
9100         o->op_private & OPpLVAL_INTRO)
9101         return ret;
9102
9103     if (type == OP_LIST || flags & OPf_PARENS ||
9104         type == OP_RV2AV || type == OP_RV2HV ||
9105         type == OP_ASLICE || type == OP_HSLICE ||
9106         type == OP_KVASLICE || type == OP_KVHSLICE || type == OP_REFGEN)
9107         return ASSIGN_LIST;
9108
9109     if (type == OP_PADAV || type == OP_PADHV)
9110         return ASSIGN_LIST;
9111
9112     if (type == OP_RV2SV)
9113         return ret;
9114
9115     return ret;
9116 }
9117
9118 static OP *
9119 S_newONCEOP(pTHX_ OP *initop, OP *padop)
9120 {
9121     const PADOFFSET target = padop->op_targ;
9122     OP *const other = newOP(OP_PADSV,
9123                             padop->op_flags
9124                             | ((padop->op_private & ~OPpLVAL_INTRO) << 8));
9125     OP *const first = newOP(OP_NULL, 0);
9126     OP *const nullop = newCONDOP(0, first, initop, other);
9127     /* XXX targlex disabled for now; see ticket #124160
9128         newCONDOP(0, first, S_maybe_targlex(aTHX_ initop), other);
9129      */
9130     OP *const condop = first->op_next;
9131
9132     OpTYPE_set(condop, OP_ONCE);
9133     other->op_targ = target;
9134     nullop->op_flags |= OPf_WANT_SCALAR;
9135
9136     /* Store the initializedness of state vars in a separate
9137        pad entry.  */
9138     condop->op_targ =
9139       pad_add_name_pvn("$",1,padadd_NO_DUP_CHECK|padadd_STATE,0,0);
9140     /* hijacking PADSTALE for uninitialized state variables */
9141     SvPADSTALE_on(PAD_SVl(condop->op_targ));
9142
9143     return nullop;
9144 }
9145
9146 /*
9147 =for apidoc newASSIGNOP
9148
9149 Constructs, checks, and returns an assignment op.  C<left> and C<right>
9150 supply the parameters of the assignment; they are consumed by this
9151 function and become part of the constructed op tree.
9152
9153 If C<optype> is C<OP_ANDASSIGN>, C<OP_ORASSIGN>, or C<OP_DORASSIGN>, then
9154 a suitable conditional optree is constructed.  If C<optype> is the opcode
9155 of a binary operator, such as C<OP_BIT_OR>, then an op is constructed that
9156 performs the binary operation and assigns the result to the left argument.
9157 Either way, if C<optype> is non-zero then C<flags> has no effect.
9158
9159 If C<optype> is zero, then a plain scalar or list assignment is
9160 constructed.  Which type of assignment it is is automatically determined.
9161 C<flags> gives the eight bits of C<op_flags>, except that C<OPf_KIDS>
9162 will be set automatically, and, shifted up eight bits, the eight bits
9163 of C<op_private>, except that the bit with value 1 or 2 is automatically
9164 set as required.
9165
9166 =cut
9167 */
9168
9169 OP *
9170 Perl_newASSIGNOP(pTHX_ I32 flags, OP *left, I32 optype, OP *right)
9171 {
9172     OP *o;
9173     I32 assign_type;
9174
9175     if (optype) {
9176         if (optype == OP_ANDASSIGN || optype == OP_ORASSIGN || optype == OP_DORASSIGN) {
9177             right = scalar(right);
9178             return newLOGOP(optype, 0,
9179                 op_lvalue(scalar(left), optype),
9180                 newBINOP(OP_SASSIGN, OPpASSIGN_BACKWARDS<<8, right, right));
9181         }
9182         else {
9183             return newBINOP(optype, OPf_STACKED,
9184                 op_lvalue(scalar(left), optype), scalar(right));
9185         }
9186     }
9187
9188     if ((assign_type = assignment_type(left)) == ASSIGN_LIST) {
9189         OP *state_var_op = NULL;
9190         static const char no_list_state[] = "Initialization of state variables"
9191             " in list currently forbidden";
9192         OP *curop;
9193
9194         if (left->op_type == OP_ASLICE || left->op_type == OP_HSLICE)
9195             left->op_private &= ~ OPpSLICEWARNING;
9196
9197         PL_modcount = 0;
9198         left = op_lvalue(left, OP_AASSIGN);
9199         curop = list(force_list(left, 1));
9200         o = newBINOP(OP_AASSIGN, flags, list(force_list(right, 1)), curop);
9201         o->op_private = (U8)(0 | (flags >> 8));
9202
9203         if (OP_TYPE_IS_OR_WAS(left, OP_LIST))
9204         {
9205             OP *lop = ((LISTOP*)left)->op_first, *vop, *eop;
9206             if (!(left->op_flags & OPf_PARENS) &&
9207                     lop->op_type == OP_PUSHMARK &&
9208                     (vop = OpSIBLING(lop)) &&
9209                     (vop->op_type == OP_PADAV || vop->op_type == OP_PADHV) &&
9210                     !(vop->op_flags & OPf_PARENS) &&
9211                     (vop->op_private & (OPpLVAL_INTRO|OPpPAD_STATE)) ==
9212                         (OPpLVAL_INTRO|OPpPAD_STATE) &&
9213                     (eop = OpSIBLING(vop)) &&
9214                     eop->op_type == OP_ENTERSUB &&
9215                     !OpHAS_SIBLING(eop)) {
9216                 state_var_op = vop;
9217             } else {
9218                 while (lop) {
9219                     if ((lop->op_type == OP_PADSV ||
9220                          lop->op_type == OP_PADAV ||
9221                          lop->op_type == OP_PADHV ||
9222                          lop->op_type == OP_PADANY)
9223                       && (lop->op_private & OPpPAD_STATE)
9224                     )
9225                         yyerror(no_list_state);
9226                     lop = OpSIBLING(lop);
9227                 }
9228             }
9229         }
9230         else if (  (left->op_private & OPpLVAL_INTRO)
9231                 && (left->op_private & OPpPAD_STATE)
9232                 && (   left->op_type == OP_PADSV
9233                     || left->op_type == OP_PADAV
9234                     || left->op_type == OP_PADHV
9235                     || left->op_type == OP_PADANY)
9236         ) {
9237                 /* All single variable list context state assignments, hence
9238                    state ($a) = ...
9239                    (state $a) = ...
9240                    state @a = ...
9241                    state (@a) = ...
9242                    (state @a) = ...
9243                    state %a = ...
9244                    state (%a) = ...
9245                    (state %a) = ...
9246                 */
9247                 if (left->op_flags & OPf_PARENS)
9248                     yyerror(no_list_state);
9249                 else
9250                     state_var_op = left;
9251         }
9252
9253         /* optimise @a = split(...) into:
9254         * @{expr}:              split(..., @{expr}) (where @a is not flattened)
9255         * @a, my @a, local @a:  split(...)          (where @a is attached to
9256         *                                            the split op itself)
9257         */
9258
9259         if (   right
9260             && right->op_type == OP_SPLIT
9261             /* don't do twice, e.g. @b = (@a = split) */
9262             && !(right->op_private & OPpSPLIT_ASSIGN))
9263         {
9264             OP *gvop = NULL;
9265
9266             if (   (  left->op_type == OP_RV2AV
9267                    && (gvop=((UNOP*)left)->op_first)->op_type==OP_GV)
9268                 || left->op_type == OP_PADAV)
9269             {
9270                 /* @pkg or @lex or local @pkg' or 'my @lex' */
9271                 OP *tmpop;
9272                 if (gvop) {
9273 #ifdef USE_ITHREADS
9274                     ((PMOP*)right)->op_pmreplrootu.op_pmtargetoff
9275                         = cPADOPx(gvop)->op_padix;
9276                     cPADOPx(gvop)->op_padix = 0;        /* steal it */
9277 #else
9278                     ((PMOP*)right)->op_pmreplrootu.op_pmtargetgv
9279                         = MUTABLE_GV(cSVOPx(gvop)->op_sv);
9280                     cSVOPx(gvop)->op_sv = NULL; /* steal it */
9281 #endif
9282                     right->op_private |=
9283                         left->op_private & OPpOUR_INTRO;
9284                 }
9285                 else {
9286                     ((PMOP*)right)->op_pmreplrootu.op_pmtargetoff = left->op_targ;
9287                     left->op_targ = 0;  /* steal it */
9288                     right->op_private |= OPpSPLIT_LEX;
9289                 }
9290                 right->op_private |= left->op_private & OPpLVAL_INTRO;
9291
9292               detach_split:
9293                 tmpop = cUNOPo->op_first;       /* to list (nulled) */
9294                 tmpop = ((UNOP*)tmpop)->op_first; /* to pushmark */
9295                 assert(OpSIBLING(tmpop) == right);
9296                 assert(!OpHAS_SIBLING(right));
9297                 /* detach the split subtreee from the o tree,
9298                  * then free the residual o tree */
9299                 op_sibling_splice(cUNOPo->op_first, tmpop, 1, NULL);
9300                 op_free(o);                     /* blow off assign */
9301                 right->op_private |= OPpSPLIT_ASSIGN;
9302                 right->op_flags &= ~OPf_WANT;
9303                         /* "I don't know and I don't care." */
9304                 return right;
9305             }
9306             else if (left->op_type == OP_RV2AV) {
9307                 /* @{expr} */
9308
9309                 OP *pushop = cUNOPx(cBINOPo->op_last)->op_first;
9310                 assert(OpSIBLING(pushop) == left);
9311                 /* Detach the array ...  */
9312                 op_sibling_splice(cBINOPo->op_last, pushop, 1, NULL);
9313                 /* ... and attach it to the split.  */
9314                 op_sibling_splice(right, cLISTOPx(right)->op_last,
9315                                   0, left);
9316                 right->op_flags |= OPf_STACKED;
9317                 /* Detach split and expunge aassign as above.  */
9318                 goto detach_split;
9319             }
9320             else if (PL_modcount < RETURN_UNLIMITED_NUMBER &&
9321                     ((LISTOP*)right)->op_last->op_type == OP_CONST)
9322             {
9323                 /* convert split(...,0) to split(..., PL_modcount+1) */
9324                 SV ** const svp =
9325                     &((SVOP*)((LISTOP*)right)->op_last)->op_sv;
9326                 SV * const sv = *svp;
9327                 if (SvIOK(sv) && SvIVX(sv) == 0)
9328                 {
9329                   if (right->op_private & OPpSPLIT_IMPLIM) {
9330                     /* our own SV, created in ck_split */
9331                     SvREADONLY_off(sv);
9332                     sv_setiv(sv, PL_modcount+1);
9333                   }
9334                   else {
9335                     /* SV may belong to someone else */
9336                     SvREFCNT_dec(sv);
9337                     *svp = newSViv(PL_modcount+1);
9338                   }
9339                 }
9340             }
9341         }
9342
9343         if (state_var_op)
9344             o = S_newONCEOP(aTHX_ o, state_var_op);
9345         return o;
9346     }
9347     if (assign_type == ASSIGN_REF)
9348         return newBINOP(OP_REFASSIGN, flags, scalar(right), left);
9349     if (!right)
9350         right = newOP(OP_UNDEF, 0);
9351     if (right->op_type == OP_READLINE) {
9352         right->op_flags |= OPf_STACKED;
9353         return newBINOP(OP_NULL, flags, op_lvalue(scalar(left), OP_SASSIGN),
9354                 scalar(right));
9355     }
9356     else {
9357         o = newBINOP(OP_SASSIGN, flags,
9358             scalar(right), op_lvalue(scalar(left), OP_SASSIGN) );
9359     }
9360     return o;
9361 }
9362
9363 /*
9364 =for apidoc newSTATEOP
9365
9366 Constructs a state op (COP).  The state op is normally a C<nextstate> op,
9367 but will be a C<dbstate> op if debugging is enabled for currently-compiled
9368 code.  The state op is populated from C<PL_curcop> (or C<PL_compiling>).
9369 If C<label> is non-null, it supplies the name of a label to attach to
9370 the state op; this function takes ownership of the memory pointed at by
9371 C<label>, and will free it.  C<flags> gives the eight bits of C<op_flags>
9372 for the state op.
9373
9374 If C<o> is null, the state op is returned.  Otherwise the state op is
9375 combined with C<o> into a C<lineseq> list op, which is returned.  C<o>
9376 is consumed by this function and becomes part of the returned op tree.
9377
9378 =cut
9379 */
9380
9381 OP *
9382 Perl_newSTATEOP(pTHX_ I32 flags, char *label, OP *o)
9383 {
9384     const U32 seq = intro_my();
9385     const U32 utf8 = flags & SVf_UTF8;
9386     COP *cop;
9387
9388     PL_parser->parsed_sub = 0;
9389
9390     flags &= ~SVf_UTF8;
9391
9392     NewOp(1101, cop, 1, COP);
9393     if (PERLDB_LINE && CopLINE(PL_curcop) && PL_curstash != PL_debstash) {
9394         OpTYPE_set(cop, OP_DBSTATE);
9395     }
9396     else {
9397         OpTYPE_set(cop, OP_NEXTSTATE);
9398     }
9399     cop->op_flags = (U8)flags;
9400     CopHINTS_set(cop, PL_hints);
9401 #ifdef VMS
9402     if (VMSISH_HUSHED) cop->op_private |= OPpHUSH_VMSISH;
9403 #endif
9404     cop->op_next = (OP*)cop;
9405
9406     cop->cop_seq = seq;
9407     cop->cop_warnings = DUP_WARNINGS(PL_curcop->cop_warnings);
9408     CopHINTHASH_set(cop, cophh_copy(CopHINTHASH_get(PL_curcop)));
9409     if (label) {
9410         Perl_cop_store_label(aTHX_ cop, label, strlen(label), utf8);
9411
9412         PL_hints |= HINT_BLOCK_SCOPE;
9413         /* It seems that we need to defer freeing this pointer, as other parts
9414            of the grammar end up wanting to copy it after this op has been
9415            created. */
9416         SAVEFREEPV(label);
9417     }
9418
9419     if (PL_parser->preambling != NOLINE) {
9420         CopLINE_set(cop, PL_parser->preambling);
9421         PL_parser->copline = NOLINE;
9422     }
9423     else if (PL_parser->copline == NOLINE)
9424         CopLINE_set(cop, CopLINE(PL_curcop));
9425     else {
9426         CopLINE_set(cop, PL_parser->copline);
9427         PL_parser->copline = NOLINE;
9428     }
9429 #ifdef USE_ITHREADS
9430     CopFILE_set(cop, CopFILE(PL_curcop));       /* XXX share in a pvtable? */
9431 #else
9432     CopFILEGV_set(cop, CopFILEGV(PL_curcop));
9433 #endif
9434     CopSTASH_set(cop, PL_curstash);
9435
9436     if (cop->op_type == OP_DBSTATE) {
9437         /* this line can have a breakpoint - store the cop in IV */
9438         AV *av = CopFILEAVx(PL_curcop);
9439         if (av) {
9440             SV * const * const svp = av_fetch(av, CopLINE(cop), FALSE);
9441             if (svp && *svp != &PL_sv_undef ) {
9442                 (void)SvIOK_on(*svp);
9443                 SvIV_set(*svp, PTR2IV(cop));
9444             }
9445         }
9446     }
9447
9448     if (flags & OPf_SPECIAL)
9449         op_null((OP*)cop);
9450     return op_prepend_elem(OP_LINESEQ, (OP*)cop, o);
9451 }
9452
9453 /*
9454 =for apidoc newLOGOP
9455
9456 Constructs, checks, and returns a logical (flow control) op.  C<type>
9457 is the opcode.  C<flags> gives the eight bits of C<op_flags>, except
9458 that C<OPf_KIDS> will be set automatically, and, shifted up eight bits,
9459 the eight bits of C<op_private>, except that the bit with value 1 is
9460 automatically set.  C<first> supplies the expression controlling the
9461 flow, and C<other> supplies the side (alternate) chain of ops; they are
9462 consumed by this function and become part of the constructed op tree.
9463
9464 =cut
9465 */
9466
9467 OP *
9468 Perl_newLOGOP(pTHX_ I32 type, I32 flags, OP *first, OP *other)
9469 {
9470     PERL_ARGS_ASSERT_NEWLOGOP;
9471
9472     return new_logop(type, flags, &first, &other);
9473 }
9474
9475
9476 /* See if the optree o contains a single OP_CONST (plus possibly
9477  * surrounding enter/nextstate/null etc). If so, return it, else return
9478  * NULL.
9479  */
9480
9481 STATIC OP *
9482 S_search_const(pTHX_ OP *o)
9483 {
9484     PERL_ARGS_ASSERT_SEARCH_CONST;
9485
9486   redo:
9487     switch (o->op_type) {
9488         case OP_CONST:
9489             return o;
9490         case OP_NULL:
9491             if (o->op_flags & OPf_KIDS) {
9492                 o = cUNOPo->op_first;
9493                 goto redo;
9494             }
9495             break;
9496         case OP_LEAVE:
9497         case OP_SCOPE:
9498         case OP_LINESEQ:
9499         {
9500             OP *kid;
9501             if (!(o->op_flags & OPf_KIDS))
9502                 return NULL;
9503             kid = cLISTOPo->op_first;
9504
9505             do {
9506                 switch (kid->op_type) {
9507                     case OP_ENTER:
9508                     case OP_NULL:
9509                     case OP_NEXTSTATE:
9510                         kid = OpSIBLING(kid);
9511                         break;
9512                     default:
9513                         if (kid != cLISTOPo->op_last)
9514                             return NULL;
9515                         goto last;
9516                 }
9517             } while (kid);
9518
9519             if (!kid)
9520                 kid = cLISTOPo->op_last;
9521           last:
9522              o = kid;
9523              goto redo;
9524         }
9525     }
9526
9527     return NULL;
9528 }
9529
9530
9531 STATIC OP *
9532 S_new_logop(pTHX_ I32 type, I32 flags, OP** firstp, OP** otherp)
9533 {
9534     LOGOP *logop;
9535     OP *o;
9536     OP *first;
9537     OP *other;
9538     OP *cstop = NULL;
9539     int prepend_not = 0;
9540
9541     PERL_ARGS_ASSERT_NEW_LOGOP;
9542
9543     first = *firstp;
9544     other = *otherp;
9545
9546     /* [perl #59802]: Warn about things like "return $a or $b", which
9547        is parsed as "(return $a) or $b" rather than "return ($a or
9548        $b)".  NB: This also applies to xor, which is why we do it
9549        here.
9550      */
9551     switch (first->op_type) {
9552     case OP_NEXT:
9553     case OP_LAST:
9554     case OP_REDO:
9555         /* XXX: Perhaps we should emit a stronger warning for these.
9556            Even with the high-precedence operator they don't seem to do
9557            anything sensible.
9558
9559            But until we do, fall through here.
9560          */
9561     case OP_RETURN:
9562     case OP_EXIT:
9563     case OP_DIE:
9564     case OP_GOTO:
9565         /* XXX: Currently we allow people to "shoot themselves in the
9566            foot" by explicitly writing "(return $a) or $b".
9567
9568            Warn unless we are looking at the result from folding or if
9569            the programmer explicitly grouped the operators like this.
9570            The former can occur with e.g.
9571
9572                 use constant FEATURE => ( $] >= ... );
9573                 sub { not FEATURE and return or do_stuff(); }
9574          */
9575         if (!first->op_folded && !(first->op_flags & OPf_PARENS))
9576             Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX),
9577                            "Possible precedence issue with control flow operator");
9578         /* XXX: Should we optimze this to "return $a;" (i.e. remove
9579            the "or $b" part)?
9580         */
9581         break;
9582     }
9583
9584     if (type == OP_XOR)         /* Not short circuit, but here by precedence. */
9585         return newBINOP(type, flags, scalar(first), scalar(other));
9586
9587     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_LOGOP
9588         || type == OP_CUSTOM);
9589
9590     scalarboolean(first);
9591
9592     /* search for a constant op that could let us fold the test */
9593     if ((cstop = search_const(first))) {
9594         if (cstop->op_private & OPpCONST_STRICT)
9595             no_bareword_allowed(cstop);
9596         else if ((cstop->op_private & OPpCONST_BARE))
9597                 Perl_ck_warner(aTHX_ packWARN(WARN_BAREWORD), "Bareword found in conditional");
9598         if ((type == OP_AND &&  SvTRUE(((SVOP*)cstop)->op_sv)) ||
9599             (type == OP_OR  && !SvTRUE(((SVOP*)cstop)->op_sv)) ||
9600             (type == OP_DOR && !SvOK(((SVOP*)cstop)->op_sv))) {
9601             /* Elide the (constant) lhs, since it can't affect the outcome */
9602             *firstp = NULL;
9603             if (other->op_type == OP_CONST)
9604                 other->op_private |= OPpCONST_SHORTCIRCUIT;
9605             op_free(first);
9606             if (other->op_type == OP_LEAVE)
9607                 other = newUNOP(OP_NULL, OPf_SPECIAL, other);
9608             else if (other->op_type == OP_MATCH
9609                   || other->op_type == OP_SUBST
9610                   || other->op_type == OP_TRANSR
9611                   || other->op_type == OP_TRANS)
9612                 /* Mark the op as being unbindable with =~ */
9613                 other->op_flags |= OPf_SPECIAL;
9614
9615             other->op_folded = 1;
9616             return other;
9617         }
9618         else {
9619             /* Elide the rhs, since the outcome is entirely determined by
9620              * the (constant) lhs */
9621
9622             /* check for C<my $x if 0>, or C<my($x,$y) if 0> */
9623             const OP *o2 = other;
9624             if ( ! (o2->op_type == OP_LIST
9625                     && (( o2 = cUNOPx(o2)->op_first))
9626                     && o2->op_type == OP_PUSHMARK
9627                     && (( o2 = OpSIBLING(o2))) )
9628             )
9629                 o2 = other;
9630             if ((o2->op_type == OP_PADSV || o2->op_type == OP_PADAV
9631                         || o2->op_type == OP_PADHV)
9632                 && o2->op_private & OPpLVAL_INTRO
9633                 && !(o2->op_private & OPpPAD_STATE))
9634             {
9635         Perl_croak(aTHX_ "This use of my() in false conditional is "
9636                           "no longer allowed");
9637             }
9638
9639             *otherp = NULL;
9640             if (cstop->op_type == OP_CONST)
9641                 cstop->op_private |= OPpCONST_SHORTCIRCUIT;
9642             op_free(other);
9643             return first;
9644         }
9645     }
9646     else if ((first->op_flags & OPf_KIDS) && type != OP_DOR
9647         && ckWARN(WARN_MISC)) /* [#24076] Don't warn for <FH> err FOO. */
9648     {
9649         const OP * const k1 = ((UNOP*)first)->op_first;
9650         const OP * const k2 = OpSIBLING(k1);
9651         OPCODE warnop = 0;
9652         switch (first->op_type)
9653         {
9654         case OP_NULL:
9655             if (k2 && k2->op_type == OP_READLINE
9656                   && (k2->op_flags & OPf_STACKED)
9657                   && ((k1->op_flags & OPf_WANT) == OPf_WANT_SCALAR))
9658             {
9659                 warnop = k2->op_type;
9660             }
9661             break;
9662
9663         case OP_SASSIGN:
9664             if (k1->op_type == OP_READDIR
9665                   || k1->op_type == OP_GLOB
9666                   || (k1->op_type == OP_NULL && k1->op_targ == OP_GLOB)
9667                  || k1->op_type == OP_EACH
9668                  || k1->op_type == OP_AEACH)
9669             {
9670                 warnop = ((k1->op_type == OP_NULL)
9671                           ? (OPCODE)k1->op_targ : k1->op_type);
9672             }
9673             break;
9674         }
9675         if (warnop) {
9676             const line_t oldline = CopLINE(PL_curcop);
9677             /* This ensures that warnings are reported at the first line
9678                of the construction, not the last.  */
9679             CopLINE_set(PL_curcop, PL_parser->copline);
9680             Perl_warner(aTHX_ packWARN(WARN_MISC),
9681                  "Value of %s%s can be \"0\"; test with defined()",
9682                  PL_op_desc[warnop],
9683                  ((warnop == OP_READLINE || warnop == OP_GLOB)
9684                   ? " construct" : "() operator"));
9685             CopLINE_set(PL_curcop, oldline);
9686         }
9687     }
9688
9689     /* optimize AND and OR ops that have NOTs as children */
9690     if (first->op_type == OP_NOT
9691         && (first->op_flags & OPf_KIDS)
9692         && ((first->op_flags & OPf_SPECIAL) /* unless ($x) { } */
9693             || (other->op_type == OP_NOT))  /* if (!$x && !$y) { } */
9694         ) {
9695         if (type == OP_AND || type == OP_OR) {
9696             if (type == OP_AND)
9697                 type = OP_OR;
9698             else
9699                 type = OP_AND;
9700             op_null(first);
9701             if (other->op_type == OP_NOT) { /* !a AND|OR !b => !(a OR|AND b) */
9702                 op_null(other);
9703                 prepend_not = 1; /* prepend a NOT op later */
9704             }
9705         }
9706     }
9707
9708     logop = alloc_LOGOP(type, first, LINKLIST(other));
9709     logop->op_flags |= (U8)flags;
9710     logop->op_private = (U8)(1 | (flags >> 8));
9711
9712     /* establish postfix order */
9713     logop->op_next = LINKLIST(first);
9714     first->op_next = (OP*)logop;
9715     assert(!OpHAS_SIBLING(first));
9716     op_sibling_splice((OP*)logop, first, 0, other);
9717
9718     CHECKOP(type,logop);
9719
9720     o = newUNOP(prepend_not ? OP_NOT : OP_NULL,
9721                 PL_opargs[type] & OA_RETSCALAR ? OPf_WANT_SCALAR : 0,
9722                 (OP*)logop);
9723     other->op_next = o;
9724
9725     return o;
9726 }
9727
9728 /*
9729 =for apidoc newCONDOP
9730
9731 Constructs, checks, and returns a conditional-expression (C<cond_expr>)
9732 op.  C<flags> gives the eight bits of C<op_flags>, except that C<OPf_KIDS>
9733 will be set automatically, and, shifted up eight bits, the eight bits of
9734 C<op_private>, except that the bit with value 1 is automatically set.
9735 C<first> supplies the expression selecting between the two branches,
9736 and C<trueop> and C<falseop> supply the branches; they are consumed by
9737 this function and become part of the constructed op tree.
9738
9739 =cut
9740 */
9741
9742 OP *
9743 Perl_newCONDOP(pTHX_ I32 flags, OP *first, OP *trueop, OP *falseop)
9744 {
9745     LOGOP *logop;
9746     OP *start;
9747     OP *o;
9748     OP *cstop;
9749
9750     PERL_ARGS_ASSERT_NEWCONDOP;
9751
9752     if (!falseop)
9753         return newLOGOP(OP_AND, 0, first, trueop);
9754     if (!trueop)
9755         return newLOGOP(OP_OR, 0, first, falseop);
9756
9757     scalarboolean(first);
9758     if ((cstop = search_const(first))) {
9759         /* Left or right arm of the conditional?  */
9760         const bool left = SvTRUE(((SVOP*)cstop)->op_sv);
9761         OP *live = left ? trueop : falseop;
9762         OP *const dead = left ? falseop : trueop;
9763         if (cstop->op_private & OPpCONST_BARE &&
9764             cstop->op_private & OPpCONST_STRICT) {
9765             no_bareword_allowed(cstop);
9766         }
9767         op_free(first);
9768         op_free(dead);
9769         if (live->op_type == OP_LEAVE)
9770             live = newUNOP(OP_NULL, OPf_SPECIAL, live);
9771         else if (live->op_type == OP_MATCH || live->op_type == OP_SUBST
9772               || live->op_type == OP_TRANS || live->op_type == OP_TRANSR)
9773             /* Mark the op as being unbindable with =~ */
9774             live->op_flags |= OPf_SPECIAL;
9775         live->op_folded = 1;
9776         return live;
9777     }
9778     logop = alloc_LOGOP(OP_COND_EXPR, first, LINKLIST(trueop));
9779     logop->op_flags |= (U8)flags;
9780     logop->op_private = (U8)(1 | (flags >> 8));
9781     logop->op_next = LINKLIST(falseop);
9782
9783     CHECKOP(OP_COND_EXPR, /* that's logop->op_type */
9784             logop);
9785
9786     /* establish postfix order */
9787     start = LINKLIST(first);
9788     first->op_next = (OP*)logop;
9789
9790     /* make first, trueop, falseop siblings */
9791     op_sibling_splice((OP*)logop, first,  0, trueop);
9792     op_sibling_splice((OP*)logop, trueop, 0, falseop);
9793
9794     o = newUNOP(OP_NULL, 0, (OP*)logop);
9795
9796     trueop->op_next = falseop->op_next = o;
9797
9798     o->op_next = start;
9799     return o;
9800 }
9801
9802 /*
9803 =for apidoc newRANGE
9804
9805 Constructs and returns a C<range> op, with subordinate C<flip> and
9806 C<flop> ops.  C<flags> gives the eight bits of C<op_flags> for the
9807 C<flip> op and, shifted up eight bits, the eight bits of C<op_private>
9808 for both the C<flip> and C<range> ops, except that the bit with value
9809 1 is automatically set.  C<left> and C<right> supply the expressions
9810 controlling the endpoints of the range; they are consumed by this function
9811 and become part of the constructed op tree.
9812
9813 =cut
9814 */
9815
9816 OP *
9817 Perl_newRANGE(pTHX_ I32 flags, OP *left, OP *right)
9818 {
9819     LOGOP *range;
9820     OP *flip;
9821     OP *flop;
9822     OP *leftstart;
9823     OP *o;
9824
9825     PERL_ARGS_ASSERT_NEWRANGE;
9826
9827     range = alloc_LOGOP(OP_RANGE, left, LINKLIST(right));
9828     range->op_flags = OPf_KIDS;
9829     leftstart = LINKLIST(left);
9830     range->op_private = (U8)(1 | (flags >> 8));
9831
9832     /* make left and right siblings */
9833     op_sibling_splice((OP*)range, left, 0, right);
9834
9835     range->op_next = (OP*)range;
9836     flip = newUNOP(OP_FLIP, flags, (OP*)range);
9837     flop = newUNOP(OP_FLOP, 0, flip);
9838     o = newUNOP(OP_NULL, 0, flop);
9839     LINKLIST(flop);
9840     range->op_next = leftstart;
9841
9842     left->op_next = flip;
9843     right->op_next = flop;
9844
9845     range->op_targ =
9846         pad_add_name_pvn("$", 1, padadd_NO_DUP_CHECK|padadd_STATE, 0, 0);
9847     sv_upgrade(PAD_SV(range->op_targ), SVt_PVNV);
9848     flip->op_targ =
9849         pad_add_name_pvn("$", 1, padadd_NO_DUP_CHECK|padadd_STATE, 0, 0);;
9850     sv_upgrade(PAD_SV(flip->op_targ), SVt_PVNV);
9851     SvPADTMP_on(PAD_SV(flip->op_targ));
9852
9853     flip->op_private =  left->op_type == OP_CONST ? OPpFLIP_LINENUM : 0;
9854     flop->op_private = right->op_type == OP_CONST ? OPpFLIP_LINENUM : 0;
9855
9856     /* check barewords before they might be optimized aways */
9857     if (flip->op_private && cSVOPx(left)->op_private & OPpCONST_STRICT)
9858         no_bareword_allowed(left);
9859     if (flop->op_private && cSVOPx(right)->op_private & OPpCONST_STRICT)
9860         no_bareword_allowed(right);
9861
9862     flip->op_next = o;
9863     if (!flip->op_private || !flop->op_private)
9864         LINKLIST(o);            /* blow off optimizer unless constant */
9865
9866     return o;
9867 }
9868
9869 /*
9870 =for apidoc newLOOPOP
9871
9872 Constructs, checks, and returns an op tree expressing a loop.  This is
9873 only a loop in the control flow through the op tree; it does not have
9874 the heavyweight loop structure that allows exiting the loop by C<last>
9875 and suchlike.  C<flags> gives the eight bits of C<op_flags> for the
9876 top-level op, except that some bits will be set automatically as required.
9877 C<expr> supplies the expression controlling loop iteration, and C<block>
9878 supplies the body of the loop; they are consumed by this function and
9879 become part of the constructed op tree.  C<debuggable> is currently
9880 unused and should always be 1.
9881
9882 =cut
9883 */
9884
9885 OP *
9886 Perl_newLOOPOP(pTHX_ I32 flags, I32 debuggable, OP *expr, OP *block)
9887 {
9888     OP* listop;
9889     OP* o;
9890     const bool once = block && block->op_flags & OPf_SPECIAL &&
9891                       block->op_type == OP_NULL;
9892
9893     PERL_UNUSED_ARG(debuggable);
9894
9895     if (expr) {
9896         if (once && (
9897               (expr->op_type == OP_CONST && !SvTRUE(((SVOP*)expr)->op_sv))
9898            || (  expr->op_type == OP_NOT
9899               && cUNOPx(expr)->op_first->op_type == OP_CONST
9900               && SvTRUE(cSVOPx_sv(cUNOPx(expr)->op_first))
9901               )
9902            ))
9903             /* Return the block now, so that S_new_logop does not try to
9904                fold it away. */
9905         {
9906             op_free(expr);
9907             return block;       /* do {} while 0 does once */
9908         }
9909
9910         if (expr->op_type == OP_READLINE
9911             || expr->op_type == OP_READDIR
9912             || expr->op_type == OP_GLOB
9913             || expr->op_type == OP_EACH || expr->op_type == OP_AEACH
9914             || (expr->op_type == OP_NULL && expr->op_targ == OP_GLOB)) {
9915             expr = newUNOP(OP_DEFINED, 0,
9916                 newASSIGNOP(0, newDEFSVOP(), 0, expr) );
9917         } else if (expr->op_flags & OPf_KIDS) {
9918             const OP * const k1 = ((UNOP*)expr)->op_first;
9919             const OP * const k2 = k1 ? OpSIBLING(k1) : NULL;
9920             switch (expr->op_type) {
9921               case OP_NULL:
9922                 if (k2 && (k2->op_type == OP_READLINE || k2->op_type == OP_READDIR)
9923                       && (k2->op_flags & OPf_STACKED)
9924                       && ((k1->op_flags & OPf_WANT) == OPf_WANT_SCALAR))
9925                     expr = newUNOP(OP_DEFINED, 0, expr);
9926                 break;
9927
9928               case OP_SASSIGN:
9929                 if (k1 && (k1->op_type == OP_READDIR
9930                       || k1->op_type == OP_GLOB
9931                       || (k1->op_type == OP_NULL && k1->op_targ == OP_GLOB)
9932                      || k1->op_type == OP_EACH
9933                      || k1->op_type == OP_AEACH))
9934                     expr = newUNOP(OP_DEFINED, 0, expr);
9935                 break;
9936             }
9937         }
9938     }
9939
9940     /* if block is null, the next op_append_elem() would put UNSTACK, a scalar
9941      * op, in listop. This is wrong. [perl #27024] */
9942     if (!block)
9943         block = newOP(OP_NULL, 0);
9944     listop = op_append_elem(OP_LINESEQ, block, newOP(OP_UNSTACK, 0));
9945     o = new_logop(OP_AND, 0, &expr, &listop);
9946
9947     if (once) {
9948         ASSUME(listop);
9949     }
9950
9951     if (listop)
9952         ((LISTOP*)listop)->op_last->op_next = LINKLIST(o);
9953
9954     if (once && o != listop)
9955     {
9956         assert(cUNOPo->op_first->op_type == OP_AND
9957             || cUNOPo->op_first->op_type == OP_OR);
9958         o->op_next = ((LOGOP*)cUNOPo->op_first)->op_other;
9959     }
9960
9961     if (o == listop)
9962         o = newUNOP(OP_NULL, 0, o);     /* or do {} while 1 loses outer block */
9963
9964     o->op_flags |= flags;
9965     o = op_scope(o);
9966     o->op_flags |= OPf_SPECIAL; /* suppress cx_popblock() curpm restoration*/
9967     return o;
9968 }
9969
9970 /*
9971 =for apidoc newWHILEOP
9972
9973 Constructs, checks, and returns an op tree expressing a C<while> loop.
9974 This is a heavyweight loop, with structure that allows exiting the loop
9975 by C<last> and suchlike.
9976
9977 C<loop> is an optional preconstructed C<enterloop> op to use in the
9978 loop; if it is null then a suitable op will be constructed automatically.
9979 C<expr> supplies the loop's controlling expression.  C<block> supplies the
9980 main body of the loop, and C<cont> optionally supplies a C<continue> block
9981 that operates as a second half of the body.  All of these optree inputs
9982 are consumed by this function and become part of the constructed op tree.
9983
9984 C<flags> gives the eight bits of C<op_flags> for the C<leaveloop>
9985 op and, shifted up eight bits, the eight bits of C<op_private> for
9986 the C<leaveloop> op, except that (in both cases) some bits will be set
9987 automatically.  C<debuggable> is currently unused and should always be 1.
9988 C<has_my> can be supplied as true to force the
9989 loop body to be enclosed in its own scope.
9990
9991 =cut
9992 */
9993
9994 OP *
9995 Perl_newWHILEOP(pTHX_ I32 flags, I32 debuggable, LOOP *loop,
9996         OP *expr, OP *block, OP *cont, I32 has_my)
9997 {
9998     OP *redo;
9999     OP *next = NULL;
10000     OP *listop;
10001     OP *o;
10002     U8 loopflags = 0;
10003
10004     PERL_UNUSED_ARG(debuggable);
10005
10006     if (expr) {
10007         if (expr->op_type == OP_READLINE
10008          || expr->op_type == OP_READDIR
10009          || expr->op_type == OP_GLOB
10010          || expr->op_type == OP_EACH || expr->op_type == OP_AEACH
10011                      || (expr->op_type == OP_NULL && expr->op_targ == OP_GLOB)) {
10012             expr = newUNOP(OP_DEFINED, 0,
10013                 newASSIGNOP(0, newDEFSVOP(), 0, expr) );
10014         } else if (expr->op_flags & OPf_KIDS) {
10015             const OP * const k1 = ((UNOP*)expr)->op_first;
10016             const OP * const k2 = (k1) ? OpSIBLING(k1) : NULL;
10017             switch (expr->op_type) {
10018               case OP_NULL:
10019                 if (k2 && (k2->op_type == OP_READLINE || k2->op_type == OP_READDIR)
10020                       && (k2->op_flags & OPf_STACKED)
10021                       && ((k1->op_flags & OPf_WANT) == OPf_WANT_SCALAR))
10022                     expr = newUNOP(OP_DEFINED, 0, expr);
10023                 break;
10024
10025               case OP_SASSIGN:
10026                 if (k1 && (k1->op_type == OP_READDIR
10027                       || k1->op_type == OP_GLOB
10028                       || (k1->op_type == OP_NULL && k1->op_targ == OP_GLOB)
10029                      || k1->op_type == OP_EACH
10030                      || k1->op_type == OP_AEACH))
10031                     expr = newUNOP(OP_DEFINED, 0, expr);
10032                 break;
10033             }
10034         }
10035     }
10036
10037     if (!block)
10038         block = newOP(OP_NULL, 0);
10039     else if (cont || has_my) {
10040         block = op_scope(block);
10041     }
10042
10043     if (cont) {
10044         next = LINKLIST(cont);
10045     }
10046     if (expr) {
10047         OP * const unstack = newOP(OP_UNSTACK, 0);
10048         if (!next)
10049             next = unstack;
10050         cont = op_append_elem(OP_LINESEQ, cont, unstack);
10051     }
10052
10053     assert(block);
10054     listop = op_append_list(OP_LINESEQ, block, cont);
10055     assert(listop);
10056     redo = LINKLIST(listop);
10057
10058     if (expr) {
10059         scalar(listop);
10060         o = new_logop(OP_AND, 0, &expr, &listop);
10061         if (o == expr && o->op_type == OP_CONST && !SvTRUE(cSVOPo->op_sv)) {
10062             op_free((OP*)loop);
10063             return expr;                /* listop already freed by new_logop */
10064         }
10065         if (listop)
10066             ((LISTOP*)listop)->op_last->op_next =
10067                 (o == listop ? redo : LINKLIST(o));
10068     }
10069     else
10070         o = listop;
10071
10072     if (!loop) {
10073         NewOp(1101,loop,1,LOOP);
10074         OpTYPE_set(loop, OP_ENTERLOOP);
10075         loop->op_private = 0;
10076         loop->op_next = (OP*)loop;
10077     }
10078
10079     o = newBINOP(OP_LEAVELOOP, 0, (OP*)loop, o);
10080
10081     loop->op_redoop = redo;
10082     loop->op_lastop = o;
10083     o->op_private |= loopflags;
10084
10085     if (next)
10086         loop->op_nextop = next;
10087     else
10088         loop->op_nextop = o;
10089
10090     o->op_flags |= flags;
10091     o->op_private |= (flags >> 8);
10092     return o;
10093 }
10094
10095 /*
10096 =for apidoc newFOROP
10097
10098 Constructs, checks, and returns an op tree expressing a C<foreach>
10099 loop (iteration through a list of values).  This is a heavyweight loop,
10100 with structure that allows exiting the loop by C<last> and suchlike.
10101
10102 C<sv> optionally supplies the variable that will be aliased to each
10103 item in turn; if null, it defaults to C<$_>.
10104 C<expr> supplies the list of values to iterate over.  C<block> supplies
10105 the main body of the loop, and C<cont> optionally supplies a C<continue>
10106 block that operates as a second half of the body.  All of these optree
10107 inputs are consumed by this function and become part of the constructed
10108 op tree.
10109
10110 C<flags> gives the eight bits of C<op_flags> for the C<leaveloop>
10111 op and, shifted up eight bits, the eight bits of C<op_private> for
10112 the C<leaveloop> op, except that (in both cases) some bits will be set
10113 automatically.
10114
10115 =cut
10116 */
10117
10118 OP *
10119 Perl_newFOROP(pTHX_ I32 flags, OP *sv, OP *expr, OP *block, OP *cont)
10120 {
10121     LOOP *loop;
10122     OP *wop;
10123     PADOFFSET padoff = 0;
10124     I32 iterflags = 0;
10125     I32 iterpflags = 0;
10126
10127     PERL_ARGS_ASSERT_NEWFOROP;
10128
10129     if (sv) {
10130         if (sv->op_type == OP_RV2SV) {  /* symbol table variable */
10131             iterpflags = sv->op_private & OPpOUR_INTRO; /* for our $x () */
10132             OpTYPE_set(sv, OP_RV2GV);
10133
10134             /* The op_type check is needed to prevent a possible segfault
10135              * if the loop variable is undeclared and 'strict vars' is in
10136              * effect. This is illegal but is nonetheless parsed, so we
10137              * may reach this point with an OP_CONST where we're expecting
10138              * an OP_GV.
10139              */
10140             if (cUNOPx(sv)->op_first->op_type == OP_GV
10141              && cGVOPx_gv(cUNOPx(sv)->op_first) == PL_defgv)
10142                 iterpflags |= OPpITER_DEF;
10143         }
10144         else if (sv->op_type == OP_PADSV) { /* private variable */
10145             iterpflags = sv->op_private & OPpLVAL_INTRO; /* for my $x () */
10146             padoff = sv->op_targ;
10147             sv->op_targ = 0;
10148             op_free(sv);
10149             sv = NULL;
10150             PAD_COMPNAME_GEN_set(padoff, PERL_INT_MAX);
10151         }
10152         else if (sv->op_type == OP_NULL && sv->op_targ == OP_SREFGEN)
10153             NOOP;
10154         else
10155             Perl_croak(aTHX_ "Can't use %s for loop variable", PL_op_desc[sv->op_type]);
10156         if (padoff) {
10157             PADNAME * const pn = PAD_COMPNAME(padoff);
10158             const char * const name = PadnamePV(pn);
10159
10160             if (PadnameLEN(pn) == 2 && name[0] == '$' && name[1] == '_')
10161                 iterpflags |= OPpITER_DEF;
10162         }
10163     }
10164     else {
10165         sv = newGVOP(OP_GV, 0, PL_defgv);
10166         iterpflags |= OPpITER_DEF;
10167     }
10168
10169     if (expr->op_type == OP_RV2AV || expr->op_type == OP_PADAV) {
10170         expr = op_lvalue(force_list(scalar(ref(expr, OP_ITER)), 1), OP_GREPSTART);
10171         iterflags |= OPf_STACKED;
10172     }
10173     else if (expr->op_type == OP_NULL &&
10174              (expr->op_flags & OPf_KIDS) &&
10175              ((BINOP*)expr)->op_first->op_type == OP_FLOP)
10176     {
10177         /* Basically turn for($x..$y) into the same as for($x,$y), but we
10178          * set the STACKED flag to indicate that these values are to be
10179          * treated as min/max values by 'pp_enteriter'.
10180          */
10181         const UNOP* const flip = (UNOP*)((UNOP*)((BINOP*)expr)->op_first)->op_first;
10182         LOGOP* const range = (LOGOP*) flip->op_first;
10183         OP* const left  = range->op_first;
10184         OP* const right = OpSIBLING(left);
10185         LISTOP* listop;
10186
10187         range->op_flags &= ~OPf_KIDS;
10188         /* detach range's children */
10189         op_sibling_splice((OP*)range, NULL, -1, NULL);
10190
10191         listop = (LISTOP*)newLISTOP(OP_LIST, 0, left, right);
10192         listop->op_first->op_next = range->op_next;
10193         left->op_next = range->op_other;
10194         right->op_next = (OP*)listop;
10195         listop->op_next = listop->op_first;
10196
10197         op_free(expr);
10198         expr = (OP*)(listop);
10199         op_null(expr);
10200         iterflags |= OPf_STACKED;
10201     }
10202     else {
10203         expr = op_lvalue(force_list(expr, 1), OP_GREPSTART);
10204     }
10205
10206     loop = (LOOP*)op_convert_list(OP_ENTERITER, iterflags,
10207                                   op_append_elem(OP_LIST, list(expr),
10208                                                  scalar(sv)));
10209     assert(!loop->op_next);
10210     /* for my  $x () sets OPpLVAL_INTRO;
10211      * for our $x () sets OPpOUR_INTRO */
10212     loop->op_private = (U8)iterpflags;
10213
10214     /* upgrade loop from a LISTOP to a LOOPOP;
10215      * keep it in-place if there's space */
10216     if (loop->op_slabbed
10217         &&    OpSLOT(loop)->opslot_size
10218             < SIZE_TO_PSIZE(sizeof(LOOP) + OPSLOT_HEADER))
10219     {
10220         /* no space; allocate new op */
10221         LOOP *tmp;
10222         NewOp(1234,tmp,1,LOOP);
10223         Copy(loop,tmp,1,LISTOP);
10224         assert(loop->op_last->op_sibparent == (OP*)loop);
10225         OpLASTSIB_set(loop->op_last, (OP*)tmp); /*point back to new parent */
10226         S_op_destroy(aTHX_ (OP*)loop);
10227         loop = tmp;
10228     }
10229     else if (!loop->op_slabbed)
10230     {
10231         /* loop was malloc()ed */
10232         loop = (LOOP*)PerlMemShared_realloc(loop, sizeof(LOOP));
10233         OpLASTSIB_set(loop->op_last, (OP*)loop);
10234     }
10235     loop->op_targ = padoff;
10236     wop = newWHILEOP(flags, 1, loop, newOP(OP_ITER, 0), block, cont, 0);
10237     return wop;
10238 }
10239
10240 /*
10241 =for apidoc newLOOPEX
10242
10243 Constructs, checks, and returns a loop-exiting op (such as C<goto>
10244 or C<last>).  C<type> is the opcode.  C<label> supplies the parameter
10245 determining the target of the op; it is consumed by this function and
10246 becomes part of the constructed op tree.
10247
10248 =cut
10249 */
10250
10251 OP*
10252 Perl_newLOOPEX(pTHX_ I32 type, OP *label)
10253 {
10254     OP *o = NULL;
10255
10256     PERL_ARGS_ASSERT_NEWLOOPEX;
10257
10258     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_LOOPEXOP
10259         || type == OP_CUSTOM);
10260
10261     if (type != OP_GOTO) {
10262         /* "last()" means "last" */
10263         if (label->op_type == OP_STUB && (label->op_flags & OPf_PARENS)) {
10264             o = newOP(type, OPf_SPECIAL);
10265         }
10266     }
10267     else {
10268         /* Check whether it's going to be a goto &function */
10269         if (label->op_type == OP_ENTERSUB
10270                 && !(label->op_flags & OPf_STACKED))
10271             label = newUNOP(OP_REFGEN, 0, op_lvalue(label, OP_REFGEN));
10272     }
10273
10274     /* Check for a constant argument */
10275     if (label->op_type == OP_CONST) {
10276             SV * const sv = ((SVOP *)label)->op_sv;
10277             STRLEN l;
10278             const char *s = SvPV_const(sv,l);
10279             if (l == strlen(s)) {
10280                 o = newPVOP(type,
10281                             SvUTF8(((SVOP*)label)->op_sv),
10282                             savesharedpv(
10283                                 SvPV_nolen_const(((SVOP*)label)->op_sv)));
10284             }
10285     }
10286
10287     /* If we have already created an op, we do not need the label. */
10288     if (o)
10289                 op_free(label);
10290     else o = newUNOP(type, OPf_STACKED, label);
10291
10292     PL_hints |= HINT_BLOCK_SCOPE;
10293     return o;
10294 }
10295
10296 /* if the condition is a literal array or hash
10297    (or @{ ... } etc), make a reference to it.
10298  */
10299 STATIC OP *
10300 S_ref_array_or_hash(pTHX_ OP *cond)
10301 {
10302     if (cond
10303     && (cond->op_type == OP_RV2AV
10304     ||  cond->op_type == OP_PADAV
10305     ||  cond->op_type == OP_RV2HV
10306     ||  cond->op_type == OP_PADHV))
10307
10308         return newUNOP(OP_REFGEN, 0, op_lvalue(cond, OP_REFGEN));
10309
10310     else if(cond
10311     && (cond->op_type == OP_ASLICE
10312     ||  cond->op_type == OP_KVASLICE
10313     ||  cond->op_type == OP_HSLICE
10314     ||  cond->op_type == OP_KVHSLICE)) {
10315
10316         /* anonlist now needs a list from this op, was previously used in
10317          * scalar context */
10318         cond->op_flags &= ~(OPf_WANT_SCALAR | OPf_REF);
10319         cond->op_flags |= OPf_WANT_LIST;
10320
10321         return newANONLIST(op_lvalue(cond, OP_ANONLIST));
10322     }
10323
10324     else
10325         return cond;
10326 }
10327
10328 /* These construct the optree fragments representing given()
10329    and when() blocks.
10330
10331    entergiven and enterwhen are LOGOPs; the op_other pointer
10332    points up to the associated leave op. We need this so we
10333    can put it in the context and make break/continue work.
10334    (Also, of course, pp_enterwhen will jump straight to
10335    op_other if the match fails.)
10336  */
10337
10338 STATIC OP *
10339 S_newGIVWHENOP(pTHX_ OP *cond, OP *block,
10340                    I32 enter_opcode, I32 leave_opcode,
10341                    PADOFFSET entertarg)
10342 {
10343     LOGOP *enterop;
10344     OP *o;
10345
10346     PERL_ARGS_ASSERT_NEWGIVWHENOP;
10347     PERL_UNUSED_ARG(entertarg); /* used to indicate targ of lexical $_ */
10348
10349     enterop = alloc_LOGOP(enter_opcode, block, NULL);
10350     enterop->op_targ = 0;
10351     enterop->op_private = 0;
10352
10353     o = newUNOP(leave_opcode, 0, (OP *) enterop);
10354
10355     if (cond) {
10356         /* prepend cond if we have one */
10357         op_sibling_splice((OP*)enterop, NULL, 0, scalar(cond));
10358
10359         o->op_next = LINKLIST(cond);
10360         cond->op_next = (OP *) enterop;
10361     }
10362     else {
10363         /* This is a default {} block */
10364         enterop->op_flags |= OPf_SPECIAL;
10365         o      ->op_flags |= OPf_SPECIAL;
10366
10367         o->op_next = (OP *) enterop;
10368     }
10369
10370     CHECKOP(enter_opcode, enterop); /* Currently does nothing, since
10371                                        entergiven and enterwhen both
10372                                        use ck_null() */
10373
10374     enterop->op_next = LINKLIST(block);
10375     block->op_next = enterop->op_other = o;
10376
10377     return o;
10378 }
10379
10380
10381 /* For the purposes of 'when(implied_smartmatch)'
10382  *              versus 'when(boolean_expression)',
10383  * does this look like a boolean operation? For these purposes
10384    a boolean operation is:
10385      - a subroutine call [*]
10386      - a logical connective
10387      - a comparison operator
10388      - a filetest operator, with the exception of -s -M -A -C
10389      - defined(), exists() or eof()
10390      - /$re/ or $foo =~ /$re/
10391
10392    [*] possibly surprising
10393  */
10394 STATIC bool
10395 S_looks_like_bool(pTHX_ const OP *o)
10396 {
10397     PERL_ARGS_ASSERT_LOOKS_LIKE_BOOL;
10398
10399     switch(o->op_type) {
10400         case OP_OR:
10401         case OP_DOR:
10402             return looks_like_bool(cLOGOPo->op_first);
10403
10404         case OP_AND:
10405         {
10406             OP* sibl = OpSIBLING(cLOGOPo->op_first);
10407             ASSUME(sibl);
10408             return (
10409                 looks_like_bool(cLOGOPo->op_first)
10410              && looks_like_bool(sibl));
10411         }
10412
10413         case OP_NULL:
10414         case OP_SCALAR:
10415             return (
10416                 o->op_flags & OPf_KIDS
10417             && looks_like_bool(cUNOPo->op_first));
10418
10419         case OP_ENTERSUB:
10420
10421         case OP_NOT:    case OP_XOR:
10422
10423         case OP_EQ:     case OP_NE:     case OP_LT:
10424         case OP_GT:     case OP_LE:     case OP_GE:
10425
10426         case OP_I_EQ:   case OP_I_NE:   case OP_I_LT:
10427         case OP_I_GT:   case OP_I_LE:   case OP_I_GE:
10428
10429         case OP_SEQ:    case OP_SNE:    case OP_SLT:
10430         case OP_SGT:    case OP_SLE:    case OP_SGE:
10431
10432         case OP_SMARTMATCH:
10433
10434         case OP_FTRREAD:  case OP_FTRWRITE: case OP_FTREXEC:
10435         case OP_FTEREAD:  case OP_FTEWRITE: case OP_FTEEXEC:
10436         case OP_FTIS:     case OP_FTEOWNED: case OP_FTROWNED:
10437         case OP_FTZERO:   case OP_FTSOCK:   case OP_FTCHR:
10438         case OP_FTBLK:    case OP_FTFILE:   case OP_FTDIR:
10439         case OP_FTPIPE:   case OP_FTLINK:   case OP_FTSUID:
10440         case OP_FTSGID:   case OP_FTSVTX:   case OP_FTTTY:
10441         case OP_FTTEXT:   case OP_FTBINARY:
10442
10443         case OP_DEFINED: case OP_EXISTS:
10444         case OP_MATCH:   case OP_EOF:
10445
10446         case OP_FLOP:
10447
10448             return TRUE;
10449
10450         case OP_INDEX:
10451         case OP_RINDEX:
10452             /* optimised-away (index() != -1) or similar comparison */
10453             if (o->op_private & OPpTRUEBOOL)
10454                 return TRUE;
10455             return FALSE;
10456
10457         case OP_CONST:
10458             /* Detect comparisons that have been optimized away */
10459             if (cSVOPo->op_sv == &PL_sv_yes
10460             ||  cSVOPo->op_sv == &PL_sv_no)
10461
10462                 return TRUE;
10463             else
10464                 return FALSE;
10465         /* FALLTHROUGH */
10466         default:
10467             return FALSE;
10468     }
10469 }
10470
10471
10472 /*
10473 =for apidoc newGIVENOP
10474
10475 Constructs, checks, and returns an op tree expressing a C<given> block.
10476 C<cond> supplies the expression to whose value C<$_> will be locally
10477 aliased, and C<block> supplies the body of the C<given> construct; they
10478 are consumed by this function and become part of the constructed op tree.
10479 C<defsv_off> must be zero (it used to identity the pad slot of lexical $_).
10480
10481 =cut
10482 */
10483
10484 OP *
10485 Perl_newGIVENOP(pTHX_ OP *cond, OP *block, PADOFFSET defsv_off)
10486 {
10487     PERL_ARGS_ASSERT_NEWGIVENOP;
10488     PERL_UNUSED_ARG(defsv_off);
10489
10490     assert(!defsv_off);
10491     return newGIVWHENOP(
10492         ref_array_or_hash(cond),
10493         block,
10494         OP_ENTERGIVEN, OP_LEAVEGIVEN,
10495         0);
10496 }
10497
10498 /*
10499 =for apidoc newWHENOP
10500
10501 Constructs, checks, and returns an op tree expressing a C<when> block.
10502 C<cond> supplies the test expression, and C<block> supplies the block
10503 that will be executed if the test evaluates to true; they are consumed
10504 by this function and become part of the constructed op tree.  C<cond>
10505 will be interpreted DWIMically, often as a comparison against C<$_>,
10506 and may be null to generate a C<default> block.
10507
10508 =cut
10509 */
10510
10511 OP *
10512 Perl_newWHENOP(pTHX_ OP *cond, OP *block)
10513 {
10514     const bool cond_llb = (!cond || looks_like_bool(cond));
10515     OP *cond_op;
10516
10517     PERL_ARGS_ASSERT_NEWWHENOP;
10518
10519     if (cond_llb)
10520         cond_op = cond;
10521     else {
10522         cond_op = newBINOP(OP_SMARTMATCH, OPf_SPECIAL,
10523                 newDEFSVOP(),
10524                 scalar(ref_array_or_hash(cond)));
10525     }
10526
10527     return newGIVWHENOP(cond_op, block, OP_ENTERWHEN, OP_LEAVEWHEN, 0);
10528 }
10529
10530 /* must not conflict with SVf_UTF8 */
10531 #define CV_CKPROTO_CURSTASH     0x1
10532
10533 void
10534 Perl_cv_ckproto_len_flags(pTHX_ const CV *cv, const GV *gv, const char *p,
10535                     const STRLEN len, const U32 flags)
10536 {
10537     SV *name = NULL, *msg;
10538     const char * cvp = SvROK(cv)
10539                         ? SvTYPE(SvRV_const(cv)) == SVt_PVCV
10540                            ? (cv = (const CV *)SvRV_const(cv), CvPROTO(cv))
10541                            : ""
10542                         : CvPROTO(cv);
10543     STRLEN clen = CvPROTOLEN(cv), plen = len;
10544
10545     PERL_ARGS_ASSERT_CV_CKPROTO_LEN_FLAGS;
10546
10547     if (p == NULL && cvp == NULL)
10548         return;
10549
10550     if (!ckWARN_d(WARN_PROTOTYPE))
10551         return;
10552
10553     if (p && cvp) {
10554         p = S_strip_spaces(aTHX_ p, &plen);
10555         cvp = S_strip_spaces(aTHX_ cvp, &clen);
10556         if ((flags & SVf_UTF8) == SvUTF8(cv)) {
10557             if (plen == clen && memEQ(cvp, p, plen))
10558                 return;
10559         } else {
10560             if (flags & SVf_UTF8) {
10561                 if (bytes_cmp_utf8((const U8 *)cvp, clen, (const U8 *)p, plen) == 0)
10562                     return;
10563             }
10564             else {
10565                 if (bytes_cmp_utf8((const U8 *)p, plen, (const U8 *)cvp, clen) == 0)
10566                     return;
10567             }
10568         }
10569     }
10570
10571     msg = sv_newmortal();
10572
10573     if (gv)
10574     {
10575         if (isGV(gv))
10576             gv_efullname3(name = sv_newmortal(), gv, NULL);
10577         else if (SvPOK(gv) && *SvPVX((SV *)gv) == '&')
10578             name = newSVpvn_flags(SvPVX((SV *)gv)+1, SvCUR(gv)-1, SvUTF8(gv)|SVs_TEMP);
10579         else if (flags & CV_CKPROTO_CURSTASH || SvROK(gv)) {
10580             name = sv_2mortal(newSVhek(HvNAME_HEK(PL_curstash)));
10581             sv_catpvs(name, "::");
10582             if (SvROK(gv)) {
10583                 assert (SvTYPE(SvRV_const(gv)) == SVt_PVCV);
10584                 assert (CvNAMED(SvRV_const(gv)));
10585                 sv_cathek(name, CvNAME_HEK(MUTABLE_CV(SvRV_const(gv))));
10586             }
10587             else sv_catsv(name, (SV *)gv);
10588         }
10589         else name = (SV *)gv;
10590     }
10591     sv_setpvs(msg, "Prototype mismatch:");
10592     if (name)
10593         Perl_sv_catpvf(aTHX_ msg, " sub %" SVf, SVfARG(name));
10594     if (cvp)
10595         Perl_sv_catpvf(aTHX_ msg, " (%" UTF8f ")",
10596             UTF8fARG(SvUTF8(cv),clen,cvp)
10597         );
10598     else
10599         sv_catpvs(msg, ": none");
10600     sv_catpvs(msg, " vs ");
10601     if (p)
10602         Perl_sv_catpvf(aTHX_ msg, "(%" UTF8f ")", UTF8fARG(flags & SVf_UTF8,len,p));
10603     else
10604         sv_catpvs(msg, "none");
10605     Perl_warner(aTHX_ packWARN(WARN_PROTOTYPE), "%" SVf, SVfARG(msg));
10606 }
10607
10608 static void const_sv_xsub(pTHX_ CV* cv);
10609 static void const_av_xsub(pTHX_ CV* cv);
10610
10611 /*
10612
10613 =for apidoc_section Optree Manipulation Functions
10614
10615 =for apidoc cv_const_sv
10616
10617 If C<cv> is a constant sub eligible for inlining, returns the constant
10618 value returned by the sub.  Otherwise, returns C<NULL>.
10619
10620 Constant subs can be created with C<newCONSTSUB> or as described in
10621 L<perlsub/"Constant Functions">.
10622
10623 =cut
10624 */
10625 SV *
10626 Perl_cv_const_sv(const CV *const cv)
10627 {
10628     SV *sv;
10629     if (!cv)
10630         return NULL;
10631     if (!(SvTYPE(cv) == SVt_PVCV || SvTYPE(cv) == SVt_PVFM))
10632         return NULL;
10633     sv = CvCONST(cv) ? MUTABLE_SV(CvXSUBANY(cv).any_ptr) : NULL;
10634     if (sv && SvTYPE(sv) == SVt_PVAV) return NULL;
10635     return sv;
10636 }
10637
10638 SV *
10639 Perl_cv_const_sv_or_av(const CV * const cv)
10640 {
10641     if (!cv)
10642         return NULL;
10643     if (SvROK(cv)) return SvRV((SV *)cv);
10644     assert (SvTYPE(cv) == SVt_PVCV || SvTYPE(cv) == SVt_PVFM);
10645     return CvCONST(cv) ? MUTABLE_SV(CvXSUBANY(cv).any_ptr) : NULL;
10646 }
10647
10648 /* op_const_sv:  examine an optree to determine whether it's in-lineable.
10649  * Can be called in 2 ways:
10650  *
10651  * !allow_lex
10652  *      look for a single OP_CONST with attached value: return the value
10653  *
10654  * allow_lex && !CvCONST(cv);
10655  *
10656  *      examine the clone prototype, and if contains only a single
10657  *      OP_CONST, return the value; or if it contains a single PADSV ref-
10658  *      erencing an outer lexical, turn on CvCONST to indicate the CV is
10659  *      a candidate for "constizing" at clone time, and return NULL.
10660  */
10661
10662 static SV *
10663 S_op_const_sv(pTHX_ const OP *o, CV *cv, bool allow_lex)
10664 {
10665     SV *sv = NULL;
10666     bool padsv = FALSE;
10667
10668     assert(o);
10669     assert(cv);
10670
10671     for (; o; o = o->op_next) {
10672         const OPCODE type = o->op_type;
10673
10674         if (type == OP_NEXTSTATE || type == OP_LINESEQ
10675              || type == OP_NULL
10676              || type == OP_PUSHMARK)
10677                 continue;
10678         if (type == OP_DBSTATE)
10679                 continue;
10680         if (type == OP_LEAVESUB)
10681             break;
10682         if (sv)
10683             return NULL;
10684         if (type == OP_CONST && cSVOPo->op_sv)
10685             sv = cSVOPo->op_sv;
10686         else if (type == OP_UNDEF && !o->op_private) {
10687             sv = newSV(0);
10688             SAVEFREESV(sv);
10689         }
10690         else if (allow_lex && type == OP_PADSV) {
10691                 if (PAD_COMPNAME_FLAGS(o->op_targ) & PADNAMEt_OUTER)
10692                 {
10693                     sv = &PL_sv_undef; /* an arbitrary non-null value */
10694                     padsv = TRUE;
10695                 }
10696                 else
10697                     return NULL;
10698         }
10699         else {
10700             return NULL;
10701         }
10702     }
10703     if (padsv) {
10704         CvCONST_on(cv);
10705         return NULL;
10706     }
10707     return sv;
10708 }
10709
10710 static void
10711 S_already_defined(pTHX_ CV *const cv, OP * const block, OP * const o,
10712                         PADNAME * const name, SV ** const const_svp)
10713 {
10714     assert (cv);
10715     assert (o || name);
10716     assert (const_svp);
10717     if (!block) {
10718         if (CvFLAGS(PL_compcv)) {
10719             /* might have had built-in attrs applied */
10720             const bool pureperl = !CvISXSUB(cv) && CvROOT(cv);
10721             if (CvLVALUE(PL_compcv) && ! CvLVALUE(cv) && pureperl
10722              && ckWARN(WARN_MISC))
10723             {
10724                 /* protect against fatal warnings leaking compcv */
10725                 SAVEFREESV(PL_compcv);
10726                 Perl_warner(aTHX_ packWARN(WARN_MISC), "lvalue attribute ignored after the subroutine has been defined");
10727                 SvREFCNT_inc_simple_void_NN(PL_compcv);
10728             }
10729             CvFLAGS(cv) |=
10730                 (CvFLAGS(PL_compcv) & CVf_BUILTIN_ATTRS
10731                   & ~(CVf_LVALUE * pureperl));
10732         }
10733         return;
10734     }
10735
10736     /* redundant check for speed: */
10737     if (CvCONST(cv) || ckWARN(WARN_REDEFINE)) {
10738         const line_t oldline = CopLINE(PL_curcop);
10739         SV *namesv = o
10740             ? cSVOPo->op_sv
10741             : sv_2mortal(newSVpvn_utf8(
10742                 PadnamePV(name)+1,PadnameLEN(name)-1, PadnameUTF8(name)
10743               ));
10744         if (PL_parser && PL_parser->copline != NOLINE)
10745             /* This ensures that warnings are reported at the first
10746                line of a redefinition, not the last.  */
10747             CopLINE_set(PL_curcop, PL_parser->copline);
10748         /* protect against fatal warnings leaking compcv */
10749         SAVEFREESV(PL_compcv);
10750         report_redefined_cv(namesv, cv, const_svp);
10751         SvREFCNT_inc_simple_void_NN(PL_compcv);
10752         CopLINE_set(PL_curcop, oldline);
10753     }
10754     SAVEFREESV(cv);
10755     return;
10756 }
10757
10758 CV *
10759 Perl_newMYSUB(pTHX_ I32 floor, OP *o, OP *proto, OP *attrs, OP *block)
10760 {
10761     CV **spot;
10762     SV **svspot;
10763     const char *ps;
10764     STRLEN ps_len = 0; /* init it to avoid false uninit warning from icc */
10765     U32 ps_utf8 = 0;
10766     CV *cv = NULL;
10767     CV *compcv = PL_compcv;
10768     SV *const_sv;
10769     PADNAME *name;
10770     PADOFFSET pax = o->op_targ;
10771     CV *outcv = CvOUTSIDE(PL_compcv);
10772     CV *clonee = NULL;
10773     HEK *hek = NULL;
10774     bool reusable = FALSE;
10775     OP *start = NULL;
10776 #ifdef PERL_DEBUG_READONLY_OPS
10777     OPSLAB *slab = NULL;
10778 #endif
10779
10780     PERL_ARGS_ASSERT_NEWMYSUB;
10781
10782     PL_hints |= HINT_BLOCK_SCOPE;
10783
10784     /* Find the pad slot for storing the new sub.
10785        We cannot use PL_comppad, as it is the pad owned by the new sub.  We
10786        need to look in CvOUTSIDE and find the pad belonging to the enclos-
10787        ing sub.  And then we need to dig deeper if this is a lexical from
10788        outside, as in:
10789            my sub foo; sub { sub foo { } }
10790      */
10791   redo:
10792     name = PadlistNAMESARRAY(CvPADLIST(outcv))[pax];
10793     if (PadnameOUTER(name) && PARENT_PAD_INDEX(name)) {
10794         pax = PARENT_PAD_INDEX(name);
10795         outcv = CvOUTSIDE(outcv);
10796         assert(outcv);
10797         goto redo;
10798     }
10799     svspot =
10800         &PadARRAY(PadlistARRAY(CvPADLIST(outcv))
10801                         [CvDEPTH(outcv) ? CvDEPTH(outcv) : 1])[pax];
10802     spot = (CV **)svspot;
10803
10804     if (!(PL_parser && PL_parser->error_count))
10805         move_proto_attr(&proto, &attrs, (GV *)PadnameSV(name), 0);
10806
10807     if (proto) {
10808         assert(proto->op_type == OP_CONST);
10809         ps = SvPV_const(((SVOP*)proto)->op_sv, ps_len);
10810         ps_utf8 = SvUTF8(((SVOP*)proto)->op_sv);
10811     }
10812     else
10813         ps = NULL;
10814
10815     if (proto)
10816         SAVEFREEOP(proto);
10817     if (attrs)
10818         SAVEFREEOP(attrs);
10819
10820     if (PL_parser && PL_parser->error_count) {
10821         op_free(block);
10822         SvREFCNT_dec(PL_compcv);
10823         PL_compcv = 0;
10824         goto done;
10825     }
10826
10827     if (CvDEPTH(outcv) && CvCLONE(compcv)) {
10828         cv = *spot;
10829         svspot = (SV **)(spot = &clonee);
10830     }
10831     else if (PadnameIsSTATE(name) || CvDEPTH(outcv))
10832         cv = *spot;
10833     else {
10834         assert (SvTYPE(*spot) == SVt_PVCV);
10835         if (CvNAMED(*spot))
10836             hek = CvNAME_HEK(*spot);
10837         else {
10838             U32 hash;
10839             PERL_HASH(hash, PadnamePV(name)+1, PadnameLEN(name)-1);
10840             CvNAME_HEK_set(*spot, hek =
10841                 share_hek(
10842                     PadnamePV(name)+1,
10843                     (PadnameLEN(name)-1) * (PadnameUTF8(name) ? -1 : 1),
10844                     hash
10845                 )
10846             );
10847             CvLEXICAL_on(*spot);
10848         }
10849         cv = PadnamePROTOCV(name);
10850         svspot = (SV **)(spot = &PadnamePROTOCV(name));
10851     }
10852
10853     if (block) {
10854         /* This makes sub {}; work as expected.  */
10855         if (block->op_type == OP_STUB) {
10856             const line_t l = PL_parser->copline;
10857             op_free(block);
10858             block = newSTATEOP(0, NULL, 0);
10859             PL_parser->copline = l;
10860         }
10861         block = CvLVALUE(compcv)
10862              || (cv && CvLVALUE(cv) && !CvROOT(cv) && !CvXSUB(cv))
10863                    ? newUNOP(OP_LEAVESUBLV, 0,
10864                              op_lvalue(scalarseq(block), OP_LEAVESUBLV))
10865                    : newUNOP(OP_LEAVESUB, 0, scalarseq(block));
10866         start = LINKLIST(block);
10867         block->op_next = 0;
10868         if (ps && !*ps && !attrs && !CvLVALUE(compcv))
10869             const_sv = S_op_const_sv(aTHX_ start, compcv, FALSE);
10870         else
10871             const_sv = NULL;
10872     }
10873     else
10874         const_sv = NULL;
10875
10876     if (cv) {
10877         const bool exists = CvROOT(cv) || CvXSUB(cv);
10878
10879         /* if the subroutine doesn't exist and wasn't pre-declared
10880          * with a prototype, assume it will be AUTOLOADed,
10881          * skipping the prototype check
10882          */
10883         if (exists || SvPOK(cv))
10884             cv_ckproto_len_flags(cv, (GV *)PadnameSV(name), ps, ps_len,
10885                                  ps_utf8);
10886         /* already defined? */
10887         if (exists) {
10888             S_already_defined(aTHX_ cv, block, NULL, name, &const_sv);
10889             if (block)
10890                 cv = NULL;
10891             else {
10892                 if (attrs)
10893                     goto attrs;
10894                 /* just a "sub foo;" when &foo is already defined */
10895                 SAVEFREESV(compcv);
10896                 goto done;
10897             }
10898         }
10899         else if (CvDEPTH(outcv) && CvCLONE(compcv)) {
10900             cv = NULL;
10901             reusable = TRUE;
10902         }
10903     }
10904
10905     if (const_sv) {
10906         SvREFCNT_inc_simple_void_NN(const_sv);
10907         SvFLAGS(const_sv) |= SVs_PADTMP;
10908         if (cv) {
10909             assert(!CvROOT(cv) && !CvCONST(cv));
10910             cv_forget_slab(cv);
10911         }
10912         else {
10913             cv = MUTABLE_CV(newSV_type(SVt_PVCV));
10914             CvFILE_set_from_cop(cv, PL_curcop);
10915             CvSTASH_set(cv, PL_curstash);
10916             *spot = cv;
10917         }
10918         SvPVCLEAR(MUTABLE_SV(cv));  /* prototype is "" */
10919         CvXSUBANY(cv).any_ptr = const_sv;
10920         CvXSUB(cv) = const_sv_xsub;
10921         CvCONST_on(cv);
10922         CvISXSUB_on(cv);
10923         PoisonPADLIST(cv);
10924         CvFLAGS(cv) |= CvMETHOD(compcv);
10925         op_free(block);
10926         SvREFCNT_dec(compcv);
10927         PL_compcv = NULL;
10928         goto setname;
10929     }
10930
10931     /* Checking whether outcv is CvOUTSIDE(compcv) is not sufficient to
10932        determine whether this sub definition is in the same scope as its
10933        declaration.  If this sub definition is inside an inner named pack-
10934        age sub (my sub foo; sub bar { sub foo { ... } }), outcv points to
10935        the package sub.  So check PadnameOUTER(name) too.
10936      */
10937     if (outcv == CvOUTSIDE(compcv) && !PadnameOUTER(name)) {
10938         assert(!CvWEAKOUTSIDE(compcv));
10939         SvREFCNT_dec(CvOUTSIDE(compcv));
10940         CvWEAKOUTSIDE_on(compcv);
10941     }
10942     /* XXX else do we have a circular reference? */
10943
10944     if (cv) {   /* must reuse cv in case stub is referenced elsewhere */
10945         /* transfer PL_compcv to cv */
10946         if (block) {
10947             bool free_file = CvFILE(cv) && CvDYNFILE(cv);
10948             cv_flags_t preserved_flags =
10949                 CvFLAGS(cv) & (CVf_BUILTIN_ATTRS|CVf_NAMED);
10950             PADLIST *const temp_padl = CvPADLIST(cv);
10951             CV *const temp_cv = CvOUTSIDE(cv);
10952             const cv_flags_t other_flags =
10953                 CvFLAGS(cv) & (CVf_SLABBED|CVf_WEAKOUTSIDE);
10954             OP * const cvstart = CvSTART(cv);
10955
10956             SvPOK_off(cv);
10957             CvFLAGS(cv) =
10958                 CvFLAGS(compcv) | preserved_flags;
10959             CvOUTSIDE(cv) = CvOUTSIDE(compcv);
10960             CvOUTSIDE_SEQ(cv) = CvOUTSIDE_SEQ(compcv);
10961             CvPADLIST_set(cv, CvPADLIST(compcv));
10962             CvOUTSIDE(compcv) = temp_cv;
10963             CvPADLIST_set(compcv, temp_padl);
10964             CvSTART(cv) = CvSTART(compcv);
10965             CvSTART(compcv) = cvstart;
10966             CvFLAGS(compcv) &= ~(CVf_SLABBED|CVf_WEAKOUTSIDE);
10967             CvFLAGS(compcv) |= other_flags;
10968
10969             if (free_file) {
10970                 Safefree(CvFILE(cv));
10971                 CvFILE(cv) = NULL;
10972             }
10973
10974             /* inner references to compcv must be fixed up ... */
10975             pad_fixup_inner_anons(CvPADLIST(cv), compcv, cv);
10976             if (PERLDB_INTER)/* Advice debugger on the new sub. */
10977                 ++PL_sub_generation;
10978         }
10979         else {
10980             /* Might have had built-in attributes applied -- propagate them. */
10981             CvFLAGS(cv) |= (CvFLAGS(compcv) & CVf_BUILTIN_ATTRS);
10982         }
10983         /* ... before we throw it away */
10984         SvREFCNT_dec(compcv);
10985         PL_compcv = compcv = cv;
10986     }
10987     else {
10988         cv = compcv;
10989         *spot = cv;
10990     }
10991
10992   setname:
10993     CvLEXICAL_on(cv);
10994     if (!CvNAME_HEK(cv)) {
10995         if (hek) (void)share_hek_hek(hek);
10996         else {
10997             U32 hash;
10998             PERL_HASH(hash, PadnamePV(name)+1, PadnameLEN(name)-1);
10999             hek = share_hek(PadnamePV(name)+1,
11000                       (PadnameLEN(name)-1) * (PadnameUTF8(name) ? -1 : 1),
11001                       hash);
11002         }
11003         CvNAME_HEK_set(cv, hek);
11004     }
11005
11006     if (const_sv)
11007         goto clone;
11008
11009     if (CvFILE(cv) && CvDYNFILE(cv))
11010         Safefree(CvFILE(cv));
11011     CvFILE_set_from_cop(cv, PL_curcop);
11012     CvSTASH_set(cv, PL_curstash);
11013
11014     if (ps) {
11015         sv_setpvn(MUTABLE_SV(cv), ps, ps_len);
11016         if (ps_utf8)
11017             SvUTF8_on(MUTABLE_SV(cv));
11018     }
11019
11020     if (block) {
11021         /* If we assign an optree to a PVCV, then we've defined a
11022          * subroutine that the debugger could be able to set a breakpoint
11023          * in, so signal to pp_entereval that it should not throw away any
11024          * saved lines at scope exit.  */
11025
11026         PL_breakable_sub_gen++;
11027         CvROOT(cv) = block;
11028         /* The cv no longer needs to hold a refcount on the slab, as CvROOT
11029            itself has a refcount. */
11030         CvSLABBED_off(cv);
11031         OpslabREFCNT_dec_padok((OPSLAB *)CvSTART(cv));
11032 #ifdef PERL_DEBUG_READONLY_OPS
11033         slab = (OPSLAB *)CvSTART(cv);
11034 #endif
11035         S_process_optree(aTHX_ cv, block, start);
11036     }
11037
11038   attrs:
11039     if (attrs) {
11040         /* Need to do a C<use attributes $stash_of_cv,\&cv,@attrs>. */
11041         apply_attrs(PL_curstash, MUTABLE_SV(cv), attrs);
11042     }
11043
11044     if (block) {
11045         if (PERLDB_SUBLINE && PL_curstash != PL_debstash) {
11046             SV * const tmpstr = sv_newmortal();
11047             GV * const db_postponed = gv_fetchpvs("DB::postponed",
11048                                                   GV_ADDMULTI, SVt_PVHV);
11049             HV *hv;
11050             SV * const sv = Perl_newSVpvf(aTHX_ "%s:%ld-%ld",
11051                                           CopFILE(PL_curcop),
11052                                           (long)PL_subline,
11053                                           (long)CopLINE(PL_curcop));
11054             if (HvNAME_HEK(PL_curstash)) {
11055                 sv_sethek(tmpstr, HvNAME_HEK(PL_curstash));
11056                 sv_catpvs(tmpstr, "::");
11057             }
11058             else
11059                 sv_setpvs(tmpstr, "__ANON__::");
11060
11061             sv_catpvn_flags(tmpstr, PadnamePV(name)+1, PadnameLEN(name)-1,
11062                             PadnameUTF8(name) ? SV_CATUTF8 : SV_CATBYTES);
11063             (void)hv_store(GvHV(PL_DBsub), SvPVX_const(tmpstr),
11064                     SvUTF8(tmpstr) ? -(I32)SvCUR(tmpstr) : (I32)SvCUR(tmpstr), sv, 0);
11065             hv = GvHVn(db_postponed);
11066             if (HvTOTALKEYS(hv) > 0 && hv_exists(hv, SvPVX_const(tmpstr), SvUTF8(tmpstr) ? -(I32)SvCUR(tmpstr) : (I32)SvCUR(tmpstr))) {
11067                 CV * const pcv = GvCV(db_postponed);
11068                 if (pcv) {
11069                     dSP;
11070                     PUSHMARK(SP);
11071                     XPUSHs(tmpstr);
11072                     PUTBACK;
11073                     call_sv(MUTABLE_SV(pcv), G_DISCARD);
11074                 }
11075             }
11076         }
11077     }
11078
11079   clone:
11080     if (clonee) {
11081         assert(CvDEPTH(outcv));
11082         spot = (CV **)
11083             &PadARRAY(PadlistARRAY(CvPADLIST(outcv))[CvDEPTH(outcv)])[pax];
11084         if (reusable)
11085             cv_clone_into(clonee, *spot);
11086         else *spot = cv_clone(clonee);
11087         SvREFCNT_dec_NN(clonee);
11088         cv = *spot;
11089     }
11090
11091     if (CvDEPTH(outcv) && !reusable && PadnameIsSTATE(name)) {
11092         PADOFFSET depth = CvDEPTH(outcv);
11093         while (--depth) {
11094             SV *oldcv;
11095             svspot = &PadARRAY(PadlistARRAY(CvPADLIST(outcv))[depth])[pax];
11096             oldcv = *svspot;
11097             *svspot = SvREFCNT_inc_simple_NN(cv);
11098             SvREFCNT_dec(oldcv);
11099         }
11100     }
11101
11102   done:
11103     if (PL_parser)
11104         PL_parser->copline = NOLINE;
11105     LEAVE_SCOPE(floor);
11106 #ifdef PERL_DEBUG_READONLY_OPS
11107     if (slab)
11108         Slab_to_ro(slab);
11109 #endif
11110     op_free(o);
11111     return cv;
11112 }
11113
11114 /*
11115 =for apidoc newATTRSUB_x
11116
11117 Construct a Perl subroutine, also performing some surrounding jobs.
11118
11119 This function is expected to be called in a Perl compilation context,
11120 and some aspects of the subroutine are taken from global variables
11121 associated with compilation.  In particular, C<PL_compcv> represents
11122 the subroutine that is currently being compiled.  It must be non-null
11123 when this function is called, and some aspects of the subroutine being
11124 constructed are taken from it.  The constructed subroutine may actually
11125 be a reuse of the C<PL_compcv> object, but will not necessarily be so.
11126
11127 If C<block> is null then the subroutine will have no body, and for the
11128 time being it will be an error to call it.  This represents a forward
11129 subroutine declaration such as S<C<sub foo ($$);>>.  If C<block> is
11130 non-null then it provides the Perl code of the subroutine body, which
11131 will be executed when the subroutine is called.  This body includes
11132 any argument unwrapping code resulting from a subroutine signature or
11133 similar.  The pad use of the code must correspond to the pad attached
11134 to C<PL_compcv>.  The code is not expected to include a C<leavesub> or
11135 C<leavesublv> op; this function will add such an op.  C<block> is consumed
11136 by this function and will become part of the constructed subroutine.
11137
11138 C<proto> specifies the subroutine's prototype, unless one is supplied
11139 as an attribute (see below).  If C<proto> is null, then the subroutine
11140 will not have a prototype.  If C<proto> is non-null, it must point to a
11141 C<const> op whose value is a string, and the subroutine will have that
11142 string as its prototype.  If a prototype is supplied as an attribute, the
11143 attribute takes precedence over C<proto>, but in that case C<proto> should
11144 preferably be null.  In any case, C<proto> is consumed by this function.
11145
11146 C<attrs> supplies attributes to be applied the subroutine.  A handful of
11147 attributes take effect by built-in means, being applied to C<PL_compcv>
11148 immediately when seen.  Other attributes are collected up and attached
11149 to the subroutine by this route.  C<attrs> may be null to supply no
11150 attributes, or point to a C<const> op for a single attribute, or point
11151 to a C<list> op whose children apart from the C<pushmark> are C<const>
11152 ops for one or more attributes.  Each C<const> op must be a string,
11153 giving the attribute name optionally followed by parenthesised arguments,
11154 in the manner in which attributes appear in Perl source.  The attributes
11155 will be applied to the sub by this function.  C<attrs> is consumed by
11156 this function.
11157
11158 If C<o_is_gv> is false and C<o> is null, then the subroutine will
11159 be anonymous.  If C<o_is_gv> is false and C<o> is non-null, then C<o>
11160 must point to a C<const> OP, which will be consumed by this function,
11161 and its string value supplies a name for the subroutine.  The name may
11162 be qualified or unqualified, and if it is unqualified then a default
11163 stash will be selected in some manner.  If C<o_is_gv> is true, then C<o>
11164 doesn't point to an C<OP> at all, but is instead a cast pointer to a C<GV>
11165 by which the subroutine will be named.
11166
11167 If there is already a subroutine of the specified name, then the new
11168 sub will either replace the existing one in the glob or be merged with
11169 the existing one.  A warning may be generated about redefinition.
11170
11171 If the subroutine has one of a few special names, such as C<BEGIN> or
11172 C<END>, then it will be claimed by the appropriate queue for automatic
11173 running of phase-related subroutines.  In this case the relevant glob will
11174 be left not containing any subroutine, even if it did contain one before.
11175 In the case of C<BEGIN>, the subroutine will be executed and the reference
11176 to it disposed of before this function returns.
11177
11178 The function returns a pointer to the constructed subroutine.  If the sub
11179 is anonymous then ownership of one counted reference to the subroutine
11180 is transferred to the caller.  If the sub is named then the caller does
11181 not get ownership of a reference.  In most such cases, where the sub
11182 has a non-phase name, the sub will be alive at the point it is returned
11183 by virtue of being contained in the glob that names it.  A phase-named
11184 subroutine will usually be alive by virtue of the reference owned by the
11185 phase's automatic run queue.  But a C<BEGIN> subroutine, having already
11186 been executed, will quite likely have been destroyed already by the
11187 time this function returns, making it erroneous for the caller to make
11188 any use of the returned pointer.  It is the caller's responsibility to
11189 ensure that it knows which of these situations applies.
11190
11191 =cut
11192 */
11193
11194 /* _x = extended */
11195 CV *
11196 Perl_newATTRSUB_x(pTHX_ I32 floor, OP *o, OP *proto, OP *attrs,
11197                             OP *block, bool o_is_gv)
11198 {
11199     GV *gv;
11200     const char *ps;
11201     STRLEN ps_len = 0; /* init it to avoid false uninit warning from icc */
11202     U32 ps_utf8 = 0;
11203     CV *cv = NULL;     /* the previous CV with this name, if any */
11204     SV *const_sv;
11205     const bool ec = PL_parser && PL_parser->error_count;
11206     /* If the subroutine has no body, no attributes, and no builtin attributes
11207        then it's just a sub declaration, and we may be able to get away with
11208        storing with a placeholder scalar in the symbol table, rather than a
11209        full CV.  If anything is present then it will take a full CV to
11210        store it.  */
11211     const I32 gv_fetch_flags
11212         = ec ? GV_NOADD_NOINIT :
11213         (block || attrs || (CvFLAGS(PL_compcv) & CVf_BUILTIN_ATTRS))
11214         ? GV_ADDMULTI : GV_ADDMULTI | GV_NOINIT;
11215     STRLEN namlen = 0;
11216     const char * const name =
11217          o ? SvPV_const(o_is_gv ? (SV *)o : cSVOPo->op_sv, namlen) : NULL;
11218     bool has_name;
11219     bool name_is_utf8 = o && !o_is_gv && SvUTF8(cSVOPo->op_sv);
11220     bool evanescent = FALSE;
11221     OP *start = NULL;
11222 #ifdef PERL_DEBUG_READONLY_OPS
11223     OPSLAB *slab = NULL;
11224 #endif
11225
11226     if (o_is_gv) {
11227         gv = (GV*)o;
11228         o = NULL;
11229         has_name = TRUE;
11230     } else if (name) {
11231         /* Try to optimise and avoid creating a GV.  Instead, the CV’s name
11232            hek and CvSTASH pointer together can imply the GV.  If the name
11233            contains a package name, then GvSTASH(CvGV(cv)) may differ from
11234            CvSTASH, so forego the optimisation if we find any.
11235            Also, we may be called from load_module at run time, so
11236            PL_curstash (which sets CvSTASH) may not point to the stash the
11237            sub is stored in.  */
11238         /* XXX This optimization is currently disabled for packages other
11239                than main, since there was too much CPAN breakage.  */
11240         const I32 flags =
11241            ec ? GV_NOADD_NOINIT
11242               :   (IN_PERL_RUNTIME && PL_curstash != CopSTASH(PL_curcop))
11243                || PL_curstash != PL_defstash
11244                || memchr(name, ':', namlen) || memchr(name, '\'', namlen)
11245                     ? gv_fetch_flags
11246                     : GV_ADDMULTI | GV_NOINIT | GV_NOTQUAL;
11247         gv = gv_fetchsv(cSVOPo->op_sv, flags, SVt_PVCV);
11248         has_name = TRUE;
11249     } else if (PERLDB_NAMEANON && CopLINE(PL_curcop)) {
11250         SV * const sv = sv_newmortal();
11251         Perl_sv_setpvf(aTHX_ sv, "%s[%s:%" IVdf "]",
11252                        PL_curstash ? "__ANON__" : "__ANON__::__ANON__",
11253                        CopFILE(PL_curcop), (IV)CopLINE(PL_curcop));
11254         gv = gv_fetchsv(sv, gv_fetch_flags, SVt_PVCV);
11255         has_name = TRUE;
11256     } else if (PL_curstash) {
11257         gv = gv_fetchpvs("__ANON__", gv_fetch_flags, SVt_PVCV);
11258         has_name = FALSE;
11259     } else {
11260         gv = gv_fetchpvs("__ANON__::__ANON__", gv_fetch_flags, SVt_PVCV);
11261         has_name = FALSE;
11262     }
11263
11264     if (!ec) {
11265         if (isGV(gv)) {
11266             move_proto_attr(&proto, &attrs, gv, 0);
11267         } else {
11268             assert(cSVOPo);
11269             move_proto_attr(&proto, &attrs, (GV *)cSVOPo->op_sv, 1);
11270         }
11271     }
11272
11273     if (proto) {
11274         assert(proto->op_type == OP_CONST);
11275         ps = SvPV_const(((SVOP*)proto)->op_sv, ps_len);
11276         ps_utf8 = SvUTF8(((SVOP*)proto)->op_sv);
11277     }
11278     else
11279         ps = NULL;
11280
11281     if (o)
11282         SAVEFREEOP(o);
11283     if (proto)
11284         SAVEFREEOP(proto);
11285     if (attrs)
11286         SAVEFREEOP(attrs);
11287
11288     if (ec) {
11289         op_free(block);
11290
11291         if (name)
11292             SvREFCNT_dec(PL_compcv);
11293         else
11294             cv = PL_compcv;
11295
11296         PL_compcv = 0;
11297         if (name && block) {
11298             const char *s = (char *) my_memrchr(name, ':', namlen);
11299             s = s ? s+1 : name;
11300             if (strEQ(s, "BEGIN")) {
11301                 if (PL_in_eval & EVAL_KEEPERR)
11302                     Perl_croak_nocontext("BEGIN not safe after errors--compilation aborted");
11303                 else {
11304                     SV * const errsv = ERRSV;
11305                     /* force display of errors found but not reported */
11306                     sv_catpvs(errsv, "BEGIN not safe after errors--compilation aborted");
11307                     Perl_croak_nocontext("%" SVf, SVfARG(errsv));
11308                 }
11309             }
11310         }
11311         goto done;
11312     }
11313
11314     if (!block && SvTYPE(gv) != SVt_PVGV) {
11315         /* If we are not defining a new sub and the existing one is not a
11316            full GV + CV... */
11317         if (attrs || (CvFLAGS(PL_compcv) & CVf_BUILTIN_ATTRS)) {
11318             /* We are applying attributes to an existing sub, so we need it
11319                upgraded if it is a constant.  */
11320             if (SvROK(gv) && SvTYPE(SvRV(gv)) != SVt_PVCV)
11321                 gv_init_pvn(gv, PL_curstash, name, namlen,
11322                             SVf_UTF8 * name_is_utf8);
11323         }
11324         else {                  /* Maybe prototype now, and had at maximum
11325                                    a prototype or const/sub ref before.  */
11326             if (SvTYPE(gv) > SVt_NULL) {
11327                 cv_ckproto_len_flags((const CV *)gv,
11328                                     o ? (const GV *)cSVOPo->op_sv : NULL, ps,
11329                                     ps_len, ps_utf8);
11330             }
11331
11332             if (!SvROK(gv)) {
11333                 if (ps) {
11334                     sv_setpvn(MUTABLE_SV(gv), ps, ps_len);
11335                     if (ps_utf8)
11336                         SvUTF8_on(MUTABLE_SV(gv));
11337                 }
11338                 else
11339                     sv_setiv(MUTABLE_SV(gv), -1);
11340             }
11341
11342             SvREFCNT_dec(PL_compcv);
11343             cv = PL_compcv = NULL;
11344             goto done;
11345         }
11346     }
11347
11348     cv = (!name || (isGV(gv) && GvCVGEN(gv)))
11349         ? NULL
11350         : isGV(gv)
11351             ? GvCV(gv)
11352             : SvROK(gv) && SvTYPE(SvRV(gv)) == SVt_PVCV
11353                 ? (CV *)SvRV(gv)
11354                 : NULL;
11355
11356     if (block) {
11357         assert(PL_parser);
11358         /* This makes sub {}; work as expected.  */
11359         if (block->op_type == OP_STUB) {
11360             const line_t l = PL_parser->copline;
11361             op_free(block);
11362             block = newSTATEOP(0, NULL, 0);
11363             PL_parser->copline = l;
11364         }
11365         block = CvLVALUE(PL_compcv)
11366              || (cv && CvLVALUE(cv) && !CvROOT(cv) && !CvXSUB(cv)
11367                     && (!isGV(gv) || !GvASSUMECV(gv)))
11368                    ? newUNOP(OP_LEAVESUBLV, 0,
11369                              op_lvalue(scalarseq(block), OP_LEAVESUBLV))
11370                    : newUNOP(OP_LEAVESUB, 0, scalarseq(block));
11371         start = LINKLIST(block);
11372         block->op_next = 0;
11373         if (ps && !*ps && !attrs && !CvLVALUE(PL_compcv))
11374             const_sv =
11375                 S_op_const_sv(aTHX_ start, PL_compcv,
11376                                         cBOOL(CvCLONE(PL_compcv)));
11377         else
11378             const_sv = NULL;
11379     }
11380     else
11381         const_sv = NULL;
11382
11383     if (SvPOK(gv) || (SvROK(gv) && SvTYPE(SvRV(gv)) != SVt_PVCV)) {
11384         cv_ckproto_len_flags((const CV *)gv,
11385                              o ? (const GV *)cSVOPo->op_sv : NULL, ps,
11386                              ps_len, ps_utf8|CV_CKPROTO_CURSTASH);
11387         if (SvROK(gv)) {
11388             /* All the other code for sub redefinition warnings expects the
11389                clobbered sub to be a CV.  Instead of making all those code
11390                paths more complex, just inline the RV version here.  */
11391             const line_t oldline = CopLINE(PL_curcop);
11392             assert(IN_PERL_COMPILETIME);
11393             if (PL_parser && PL_parser->copline != NOLINE)
11394                 /* This ensures that warnings are reported at the first
11395                    line of a redefinition, not the last.  */
11396                 CopLINE_set(PL_curcop, PL_parser->copline);
11397             /* protect against fatal warnings leaking compcv */
11398             SAVEFREESV(PL_compcv);
11399
11400             if (ckWARN(WARN_REDEFINE)
11401              || (  ckWARN_d(WARN_REDEFINE)
11402                 && (  !const_sv || SvRV(gv) == const_sv
11403                    || sv_cmp(SvRV(gv), const_sv)  ))) {
11404                 assert(cSVOPo);
11405                 Perl_warner(aTHX_ packWARN(WARN_REDEFINE),
11406                           "Constant subroutine %" SVf " redefined",
11407                           SVfARG(cSVOPo->op_sv));
11408             }
11409
11410             SvREFCNT_inc_simple_void_NN(PL_compcv);
11411             CopLINE_set(PL_curcop, oldline);
11412             SvREFCNT_dec(SvRV(gv));
11413         }
11414     }
11415
11416     if (cv) {
11417         const bool exists = CvROOT(cv) || CvXSUB(cv);
11418
11419         /* if the subroutine doesn't exist and wasn't pre-declared
11420          * with a prototype, assume it will be AUTOLOADed,
11421          * skipping the prototype check
11422          */
11423         if (exists || SvPOK(cv))
11424             cv_ckproto_len_flags(cv, gv, ps, ps_len, ps_utf8);
11425         /* already defined (or promised)? */
11426         if (exists || (isGV(gv) && GvASSUMECV(gv))) {
11427             S_already_defined(aTHX_ cv, block, o, NULL, &const_sv);
11428             if (block)
11429                 cv = NULL;
11430             else {
11431                 if (attrs)
11432                     goto attrs;
11433                 /* just a "sub foo;" when &foo is already defined */
11434                 SAVEFREESV(PL_compcv);
11435                 goto done;
11436             }
11437         }
11438     }
11439
11440     if (const_sv) {
11441         SvREFCNT_inc_simple_void_NN(const_sv);
11442         SvFLAGS(const_sv) |= SVs_PADTMP;
11443         if (cv) {
11444             assert(!CvROOT(cv) && !CvCONST(cv));
11445             cv_forget_slab(cv);
11446             SvPVCLEAR(MUTABLE_SV(cv));  /* prototype is "" */
11447             CvXSUBANY(cv).any_ptr = const_sv;
11448             CvXSUB(cv) = const_sv_xsub;
11449             CvCONST_on(cv);
11450             CvISXSUB_on(cv);
11451             PoisonPADLIST(cv);
11452             CvFLAGS(cv) |= CvMETHOD(PL_compcv);
11453         }
11454         else {
11455             if (isGV(gv) || CvMETHOD(PL_compcv)) {
11456                 if (name && isGV(gv))
11457                     GvCV_set(gv, NULL);
11458                 cv = newCONSTSUB_flags(
11459                     NULL, name, namlen, name_is_utf8 ? SVf_UTF8 : 0,
11460                     const_sv
11461                 );
11462                 assert(cv);
11463                 assert(SvREFCNT((SV*)cv) != 0);
11464                 CvFLAGS(cv) |= CvMETHOD(PL_compcv);
11465             }
11466             else {
11467                 if (!SvROK(gv)) {
11468                     SV_CHECK_THINKFIRST_COW_DROP((SV *)gv);
11469                     prepare_SV_for_RV((SV *)gv);
11470                     SvOK_off((SV *)gv);
11471                     SvROK_on(gv);
11472                 }
11473                 SvRV_set(gv, const_sv);
11474             }
11475         }
11476         op_free(block);
11477         SvREFCNT_dec(PL_compcv);
11478         PL_compcv = NULL;
11479         goto done;
11480     }
11481
11482     /* don't copy new BEGIN CV to old BEGIN CV - RT #129099 */
11483     if (name && cv && *name == 'B' && strEQ(name, "BEGIN"))
11484         cv = NULL;
11485
11486     if (cv) {                           /* must reuse cv if autoloaded */
11487         /* transfer PL_compcv to cv */
11488         if (block) {
11489             bool free_file = CvFILE(cv) && CvDYNFILE(cv);
11490             cv_flags_t existing_builtin_attrs = CvFLAGS(cv) & CVf_BUILTIN_ATTRS;
11491             PADLIST *const temp_av = CvPADLIST(cv);
11492             CV *const temp_cv = CvOUTSIDE(cv);
11493             const cv_flags_t other_flags =
11494                 CvFLAGS(cv) & (CVf_SLABBED|CVf_WEAKOUTSIDE);
11495             OP * const cvstart = CvSTART(cv);
11496
11497             if (isGV(gv)) {
11498                 CvGV_set(cv,gv);
11499                 assert(!CvCVGV_RC(cv));
11500                 assert(CvGV(cv) == gv);
11501             }
11502             else {
11503                 U32 hash;
11504                 PERL_HASH(hash, name, namlen);
11505                 CvNAME_HEK_set(cv,
11506                                share_hek(name,
11507                                          name_is_utf8
11508                                             ? -(SSize_t)namlen
11509                                             :  (SSize_t)namlen,
11510                                          hash));
11511             }
11512
11513             SvPOK_off(cv);
11514             CvFLAGS(cv) = CvFLAGS(PL_compcv) | existing_builtin_attrs
11515                                              | CvNAMED(cv);
11516             CvOUTSIDE(cv) = CvOUTSIDE(PL_compcv);
11517             CvOUTSIDE_SEQ(cv) = CvOUTSIDE_SEQ(PL_compcv);
11518             CvPADLIST_set(cv,CvPADLIST(PL_compcv));
11519             CvOUTSIDE(PL_compcv) = temp_cv;
11520             CvPADLIST_set(PL_compcv, temp_av);
11521             CvSTART(cv) = CvSTART(PL_compcv);
11522             CvSTART(PL_compcv) = cvstart;
11523             CvFLAGS(PL_compcv) &= ~(CVf_SLABBED|CVf_WEAKOUTSIDE);
11524             CvFLAGS(PL_compcv) |= other_flags;
11525
11526             if (free_file) {
11527                 Safefree(CvFILE(cv));
11528             }
11529             CvFILE_set_from_cop(cv, PL_curcop);
11530             CvSTASH_set(cv, PL_curstash);
11531
11532             /* inner references to PL_compcv must be fixed up ... */
11533             pad_fixup_inner_anons(CvPADLIST(cv), PL_compcv, cv);
11534             if (PERLDB_INTER)/* Advice debugger on the new sub. */
11535                 ++PL_sub_generation;
11536         }
11537         else {
11538             /* Might have had built-in attributes applied -- propagate them. */
11539             CvFLAGS(cv) |= (CvFLAGS(PL_compcv) & CVf_BUILTIN_ATTRS);
11540         }
11541         /* ... before we throw it away */
11542         SvREFCNT_dec(PL_compcv);
11543         PL_compcv = cv;
11544     }
11545     else {
11546         cv = PL_compcv;
11547         if (name && isGV(gv)) {
11548             GvCV_set(gv, cv);
11549             GvCVGEN(gv) = 0;
11550             if (HvENAME_HEK(GvSTASH(gv)))
11551                 /* sub Foo::bar { (shift)+1 } */
11552                 gv_method_changed(gv);
11553         }
11554         else if (name) {
11555             if (!SvROK(gv)) {
11556                 SV_CHECK_THINKFIRST_COW_DROP((SV *)gv);
11557                 prepare_SV_for_RV((SV *)gv);
11558                 SvOK_off((SV *)gv);
11559                 SvROK_on(gv);
11560             }
11561             SvRV_set(gv, (SV *)cv);
11562             if (HvENAME_HEK(PL_curstash))
11563                 mro_method_changed_in(PL_curstash);
11564         }
11565     }
11566     assert(cv);
11567     assert(SvREFCNT((SV*)cv) != 0);
11568
11569     if (!CvHASGV(cv)) {
11570         if (isGV(gv))
11571             CvGV_set(cv, gv);
11572         else {
11573             U32 hash;
11574             PERL_HASH(hash, name, namlen);
11575             CvNAME_HEK_set(cv, share_hek(name,
11576                                          name_is_utf8
11577                                             ? -(SSize_t)namlen
11578                                             :  (SSize_t)namlen,
11579                                          hash));
11580         }
11581         CvFILE_set_from_cop(cv, PL_curcop);
11582         CvSTASH_set(cv, PL_curstash);
11583     }
11584
11585     if (ps) {
11586         sv_setpvn(MUTABLE_SV(cv), ps, ps_len);
11587         if ( ps_utf8 )
11588             SvUTF8_on(MUTABLE_SV(cv));
11589     }
11590
11591     if (block) {
11592         /* If we assign an optree to a PVCV, then we've defined a
11593          * subroutine that the debugger could be able to set a breakpoint
11594          * in, so signal to pp_entereval that it should not throw away any
11595          * saved lines at scope exit.  */
11596
11597         PL_breakable_sub_gen++;
11598         CvROOT(cv) = block;
11599         /* The cv no longer needs to hold a refcount on the slab, as CvROOT
11600            itself has a refcount. */
11601         CvSLABBED_off(cv);
11602         OpslabREFCNT_dec_padok((OPSLAB *)CvSTART(cv));
11603 #ifdef PERL_DEBUG_READONLY_OPS
11604         slab = (OPSLAB *)CvSTART(cv);
11605 #endif
11606         S_process_optree(aTHX_ cv, block, start);
11607     }
11608
11609   attrs:
11610     if (attrs) {
11611         /* Need to do a C<use attributes $stash_of_cv,\&cv,@attrs>. */
11612         HV *stash = name && !CvNAMED(cv) && GvSTASH(CvGV(cv))
11613                         ? GvSTASH(CvGV(cv))
11614                         : PL_curstash;
11615         if (!name)
11616             SAVEFREESV(cv);
11617         apply_attrs(stash, MUTABLE_SV(cv), attrs);
11618         if (!name)
11619             SvREFCNT_inc_simple_void_NN(cv);
11620     }
11621
11622     if (block && has_name) {
11623         if (PERLDB_SUBLINE && PL_curstash != PL_debstash) {
11624             SV * const tmpstr = cv_name(cv,NULL,0);
11625             GV * const db_postponed = gv_fetchpvs("DB::postponed",
11626                                                   GV_ADDMULTI, SVt_PVHV);
11627             HV *hv;
11628             SV * const sv = Perl_newSVpvf(aTHX_ "%s:%ld-%ld",
11629                                           CopFILE(PL_curcop),
11630                                           (long)PL_subline,
11631                                           (long)CopLINE(PL_curcop));
11632             (void)hv_store(GvHV(PL_DBsub), SvPVX_const(tmpstr),
11633                     SvUTF8(tmpstr) ? -(I32)SvCUR(tmpstr) : (I32)SvCUR(tmpstr), sv, 0);
11634             hv = GvHVn(db_postponed);
11635             if (HvTOTALKEYS(hv) > 0 && hv_exists(hv, SvPVX_const(tmpstr), SvUTF8(tmpstr) ? -(I32)SvCUR(tmpstr) : (I32)SvCUR(tmpstr))) {
11636                 CV * const pcv = GvCV(db_postponed);
11637                 if (pcv) {
11638                     dSP;
11639                     PUSHMARK(SP);
11640                     XPUSHs(tmpstr);
11641                     PUTBACK;
11642                     call_sv(MUTABLE_SV(pcv), G_DISCARD);
11643                 }
11644             }
11645         }
11646
11647         if (name) {
11648             if (PL_parser && PL_parser->error_count)
11649                 clear_special_blocks(name, gv, cv);
11650             else
11651                 evanescent =
11652                     process_special_blocks(floor, name, gv, cv);
11653         }
11654     }
11655     assert(cv);
11656
11657   done:
11658     assert(!cv || evanescent || SvREFCNT((SV*)cv) != 0);
11659     if (PL_parser)
11660         PL_parser->copline = NOLINE;
11661     LEAVE_SCOPE(floor);
11662
11663     assert(!cv || evanescent || SvREFCNT((SV*)cv) != 0);
11664     if (!evanescent) {
11665 #ifdef PERL_DEBUG_READONLY_OPS
11666     if (slab)
11667         Slab_to_ro(slab);
11668 #endif
11669     if (cv && name && block && CvOUTSIDE(cv) && !CvEVAL(CvOUTSIDE(cv)))
11670         pad_add_weakref(cv);
11671     }
11672     return cv;
11673 }
11674
11675 STATIC void
11676 S_clear_special_blocks(pTHX_ const char *const fullname,
11677                        GV *const gv, CV *const cv) {
11678     const char *colon;
11679     const char *name;
11680
11681     PERL_ARGS_ASSERT_CLEAR_SPECIAL_BLOCKS;
11682
11683     colon = strrchr(fullname,':');
11684     name = colon ? colon + 1 : fullname;
11685
11686     if ((*name == 'B' && strEQ(name, "BEGIN"))
11687         || (*name == 'E' && strEQ(name, "END"))
11688         || (*name == 'U' && strEQ(name, "UNITCHECK"))
11689         || (*name == 'C' && strEQ(name, "CHECK"))
11690         || (*name == 'I' && strEQ(name, "INIT"))) {
11691         if (!isGV(gv)) {
11692             (void)CvGV(cv);
11693             assert(isGV(gv));
11694         }
11695         GvCV_set(gv, NULL);
11696         SvREFCNT_dec_NN(MUTABLE_SV(cv));
11697     }
11698 }
11699
11700 /* Returns true if the sub has been freed.  */
11701 STATIC bool
11702 S_process_special_blocks(pTHX_ I32 floor, const char *const fullname,
11703                          GV *const gv,
11704                          CV *const cv)
11705 {
11706     const char *const colon = strrchr(fullname,':');
11707     const char *const name = colon ? colon + 1 : fullname;
11708
11709     PERL_ARGS_ASSERT_PROCESS_SPECIAL_BLOCKS;
11710
11711     if (*name == 'B') {
11712         if (strEQ(name, "BEGIN")) {
11713             const I32 oldscope = PL_scopestack_ix;
11714             dSP;
11715             (void)CvGV(cv);
11716             if (floor) LEAVE_SCOPE(floor);
11717             ENTER;
11718             PUSHSTACKi(PERLSI_REQUIRE);
11719             SAVECOPFILE(&PL_compiling);
11720             SAVECOPLINE(&PL_compiling);
11721             SAVEVPTR(PL_curcop);
11722
11723             DEBUG_x( dump_sub(gv) );
11724             Perl_av_create_and_push(aTHX_ &PL_beginav, MUTABLE_SV(cv));
11725             GvCV_set(gv,0);             /* cv has been hijacked */
11726             call_list(oldscope, PL_beginav);
11727
11728             POPSTACK;
11729             LEAVE;
11730             return !PL_savebegin;
11731         }
11732         else
11733             return FALSE;
11734     } else {
11735         if (*name == 'E') {
11736             if (strEQ(name, "END")) {
11737                 DEBUG_x( dump_sub(gv) );
11738                 Perl_av_create_and_unshift_one(aTHX_ &PL_endav, MUTABLE_SV(cv));
11739             } else
11740                 return FALSE;
11741         } else if (*name == 'U') {
11742             if (strEQ(name, "UNITCHECK")) {
11743                 /* It's never too late to run a unitcheck block */
11744                 Perl_av_create_and_unshift_one(aTHX_ &PL_unitcheckav, MUTABLE_SV(cv));
11745             }
11746             else
11747                 return FALSE;
11748         } else if (*name == 'C') {
11749             if (strEQ(name, "CHECK")) {
11750                 if (PL_main_start)
11751                     /* diag_listed_as: Too late to run %s block */
11752                     Perl_ck_warner(aTHX_ packWARN(WARN_VOID),
11753                                    "Too late to run CHECK block");
11754                 Perl_av_create_and_unshift_one(aTHX_ &PL_checkav, MUTABLE_SV(cv));
11755             }
11756             else
11757                 return FALSE;
11758         } else if (*name == 'I') {
11759             if (strEQ(name, "INIT")) {
11760                 if (PL_main_start)
11761                     /* diag_listed_as: Too late to run %s block */
11762                     Perl_ck_warner(aTHX_ packWARN(WARN_VOID),
11763                                    "Too late to run INIT block");
11764                 Perl_av_create_and_push(aTHX_ &PL_initav, MUTABLE_SV(cv));
11765             }
11766             else
11767                 return FALSE;
11768         } else
11769             return FALSE;
11770         DEBUG_x( dump_sub(gv) );
11771         (void)CvGV(cv);
11772         GvCV_set(gv,0);         /* cv has been hijacked */
11773         return FALSE;
11774     }
11775 }
11776
11777 /*
11778 =for apidoc newCONSTSUB
11779
11780 Behaves like L</newCONSTSUB_flags>, except that C<name> is nul-terminated
11781 rather than of counted length, and no flags are set.  (This means that
11782 C<name> is always interpreted as Latin-1.)
11783
11784 =cut
11785 */
11786
11787 CV *
11788 Perl_newCONSTSUB(pTHX_ HV *stash, const char *name, SV *sv)
11789 {
11790     return newCONSTSUB_flags(stash, name, name ? strlen(name) : 0, 0, sv);
11791 }
11792
11793 /*
11794 =for apidoc newCONSTSUB_flags
11795
11796 Construct a constant subroutine, also performing some surrounding
11797 jobs.  A scalar constant-valued subroutine is eligible for inlining
11798 at compile-time, and in Perl code can be created by S<C<sub FOO () {
11799 123 }>>.  Other kinds of constant subroutine have other treatment.
11800
11801 The subroutine will have an empty prototype and will ignore any arguments
11802 when called.  Its constant behaviour is determined by C<sv>.  If C<sv>
11803 is null, the subroutine will yield an empty list.  If C<sv> points to a
11804 scalar, the subroutine will always yield that scalar.  If C<sv> points
11805 to an array, the subroutine will always yield a list of the elements of
11806 that array in list context, or the number of elements in the array in
11807 scalar context.  This function takes ownership of one counted reference
11808 to the scalar or array, and will arrange for the object to live as long
11809 as the subroutine does.  If C<sv> points to a scalar then the inlining
11810 assumes that the value of the scalar will never change, so the caller
11811 must ensure that the scalar is not subsequently written to.  If C<sv>
11812 points to an array then no such assumption is made, so it is ostensibly
11813 safe to mutate the array or its elements, but whether this is really
11814 supported has not been determined.
11815
11816 The subroutine will have C<CvFILE> set according to C<PL_curcop>.
11817 Other aspects of the subroutine will be left in their default state.
11818 The caller is free to mutate the subroutine beyond its initial state
11819 after this function has returned.
11820
11821 If C<name> is null then the subroutine will be anonymous, with its
11822 C<CvGV> referring to an C<__ANON__> glob.  If C<name> is non-null then the
11823 subroutine will be named accordingly, referenced by the appropriate glob.
11824 C<name> is a string of length C<len> bytes giving a sigilless symbol
11825 name, in UTF-8 if C<flags> has the C<SVf_UTF8> bit set and in Latin-1
11826 otherwise.  The name may be either qualified or unqualified.  If the
11827 name is unqualified then it defaults to being in the stash specified by
11828 C<stash> if that is non-null, or to C<PL_curstash> if C<stash> is null.
11829 The symbol is always added to the stash if necessary, with C<GV_ADDMULTI>
11830 semantics.
11831
11832 C<flags> should not have bits set other than C<SVf_UTF8>.
11833
11834 If there is already a subroutine of the specified name, then the new sub
11835 will replace the existing one in the glob.  A warning may be generated
11836 about the redefinition.
11837
11838 If the subroutine has one of a few special names, such as C<BEGIN> or
11839 C<END>, then it will be claimed by the appropriate queue for automatic
11840 running of phase-related subroutines.  In this case the relevant glob will
11841 be left not containing any subroutine, even if it did contain one before.
11842 Execution of the subroutine will likely be a no-op, unless C<sv> was
11843 a tied array or the caller modified the subroutine in some interesting
11844 way before it was executed.  In the case of C<BEGIN>, the treatment is
11845 buggy: the sub will be executed when only half built, and may be deleted
11846 prematurely, possibly causing a crash.
11847
11848 The function returns a pointer to the constructed subroutine.  If the sub
11849 is anonymous then ownership of one counted reference to the subroutine
11850 is transferred to the caller.  If the sub is named then the caller does
11851 not get ownership of a reference.  In most such cases, where the sub
11852 has a non-phase name, the sub will be alive at the point it is returned
11853 by virtue of being contained in the glob that names it.  A phase-named
11854 subroutine will usually be alive by virtue of the reference owned by
11855 the phase's automatic run queue.  A C<BEGIN> subroutine may have been
11856 destroyed already by the time this function returns, but currently bugs
11857 occur in that case before the caller gets control.  It is the caller's
11858 responsibility to ensure that it knows which of these situations applies.
11859
11860 =cut
11861 */
11862
11863 CV *
11864 Perl_newCONSTSUB_flags(pTHX_ HV *stash, const char *name, STRLEN len,
11865                              U32 flags, SV *sv)
11866 {
11867     CV* cv;
11868     const char *const file = CopFILE(PL_curcop);
11869
11870     ENTER;
11871
11872     if (IN_PERL_RUNTIME) {
11873         /* at runtime, it's not safe to manipulate PL_curcop: it may be
11874          * an op shared between threads. Use a non-shared COP for our
11875          * dirty work */
11876          SAVEVPTR(PL_curcop);
11877          SAVECOMPILEWARNINGS();
11878          PL_compiling.cop_warnings = DUP_WARNINGS(PL_curcop->cop_warnings);
11879          PL_curcop = &PL_compiling;
11880     }
11881     SAVECOPLINE(PL_curcop);
11882     CopLINE_set(PL_curcop, PL_parser ? PL_parser->copline : NOLINE);
11883
11884     SAVEHINTS();
11885     PL_hints &= ~HINT_BLOCK_SCOPE;
11886
11887     if (stash) {
11888         SAVEGENERICSV(PL_curstash);
11889         PL_curstash = (HV *)SvREFCNT_inc_simple_NN(stash);
11890     }
11891
11892     /* Protect sv against leakage caused by fatal warnings. */
11893     if (sv) SAVEFREESV(sv);
11894
11895     /* file becomes the CvFILE. For an XS, it's usually static storage,
11896        and so doesn't get free()d.  (It's expected to be from the C pre-
11897        processor __FILE__ directive). But we need a dynamically allocated one,
11898        and we need it to get freed.  */
11899     cv = newXS_len_flags(name, len,
11900                          sv && SvTYPE(sv) == SVt_PVAV
11901                              ? const_av_xsub
11902                              : const_sv_xsub,
11903                          file ? file : "", "",
11904                          &sv, XS_DYNAMIC_FILENAME | flags);
11905     assert(cv);
11906     assert(SvREFCNT((SV*)cv) != 0);
11907     CvXSUBANY(cv).any_ptr = SvREFCNT_inc_simple(sv);
11908     CvCONST_on(cv);
11909
11910     LEAVE;
11911
11912     return cv;
11913 }
11914
11915 /*
11916 =for apidoc newXS
11917
11918 Used by C<xsubpp> to hook up XSUBs as Perl subs.  C<filename> needs to be
11919 static storage, as it is used directly as CvFILE(), without a copy being made.
11920
11921 =cut
11922 */
11923
11924 CV *
11925 Perl_newXS(pTHX_ const char *name, XSUBADDR_t subaddr, const char *filename)
11926 {
11927     PERL_ARGS_ASSERT_NEWXS;
11928     return newXS_len_flags(
11929         name, name ? strlen(name) : 0, subaddr, filename, NULL, NULL, 0
11930     );
11931 }
11932
11933 CV *
11934 Perl_newXS_flags(pTHX_ const char *name, XSUBADDR_t subaddr,
11935                  const char *const filename, const char *const proto,
11936                  U32 flags)
11937 {
11938     PERL_ARGS_ASSERT_NEWXS_FLAGS;
11939     return newXS_len_flags(
11940        name, name ? strlen(name) : 0, subaddr, filename, proto, NULL, flags
11941     );
11942 }
11943
11944 CV *
11945 Perl_newXS_deffile(pTHX_ const char *name, XSUBADDR_t subaddr)
11946 {
11947     PERL_ARGS_ASSERT_NEWXS_DEFFILE;
11948     return newXS_len_flags(
11949         name, strlen(name), subaddr, NULL, NULL, NULL, 0
11950     );
11951 }
11952
11953 /*
11954 =for apidoc newXS_len_flags
11955
11956 Construct an XS subroutine, also performing some surrounding jobs.
11957
11958 The subroutine will have the entry point C<subaddr>.  It will have
11959 the prototype specified by the nul-terminated string C<proto>, or
11960 no prototype if C<proto> is null.  The prototype string is copied;
11961 the caller can mutate the supplied string afterwards.  If C<filename>
11962 is non-null, it must be a nul-terminated filename, and the subroutine
11963 will have its C<CvFILE> set accordingly.  By default C<CvFILE> is set to
11964 point directly to the supplied string, which must be static.  If C<flags>
11965 has the C<XS_DYNAMIC_FILENAME> bit set, then a copy of the string will
11966 be taken instead.
11967
11968 Other aspects of the subroutine will be left in their default state.
11969 If anything else needs to be done to the subroutine for it to function
11970 correctly, it is the caller's responsibility to do that after this
11971 function has constructed it.  However, beware of the subroutine
11972 potentially being destroyed before this function returns, as described
11973 below.
11974
11975 If C<name> is null then the subroutine will be anonymous, with its
11976 C<CvGV> referring to an C<__ANON__> glob.  If C<name> is non-null then the
11977 subroutine will be named accordingly, referenced by the appropriate glob.
11978 C<name> is a string of length C<len> bytes giving a sigilless symbol name,
11979 in UTF-8 if C<flags> has the C<SVf_UTF8> bit set and in Latin-1 otherwise.
11980 The name may be either qualified or unqualified, with the stash defaulting
11981 in the same manner as for C<gv_fetchpvn_flags>.  C<flags> may contain
11982 flag bits understood by C<gv_fetchpvn_flags> with the same meaning as
11983 they have there, such as C<GV_ADDWARN>.  The symbol is always added to
11984 the stash if necessary, with C<GV_ADDMULTI> semantics.
11985
11986 If there is already a subroutine of the specified name, then the new sub
11987 will replace the existing one in the glob.  A warning may be generated
11988 about the redefinition.  If the old subroutine was C<CvCONST> then the
11989 decision about whether to warn is influenced by an expectation about
11990 whether the new subroutine will become a constant of similar value.
11991 That expectation is determined by C<const_svp>.  (Note that the call to
11992 this function doesn't make the new subroutine C<CvCONST> in any case;
11993 that is left to the caller.)  If C<const_svp> is null then it indicates
11994 that the new subroutine will not become a constant.  If C<const_svp>
11995 is non-null then it indicates that the new subroutine will become a
11996 constant, and it points to an C<SV*> that provides the constant value
11997 that the subroutine will have.
11998
11999 If the subroutine has one of a few special names, such as C<BEGIN> or
12000 C<END>, then it will be claimed by the appropriate queue for automatic
12001 running of phase-related subroutines.  In this case the relevant glob will
12002 be left not containing any subroutine, even if it did contain one before.
12003 In the case of C<BEGIN>, the subroutine will be executed and the reference
12004 to it disposed of before this function returns, and also before its
12005 prototype is set.  If a C<BEGIN> subroutine would not be sufficiently
12006 constructed by this function to be ready for execution then the caller
12007 must prevent this happening by giving the subroutine a different name.
12008
12009 The function returns a pointer to the constructed subroutine.  If the sub
12010 is anonymous then ownership of one counted reference to the subroutine
12011 is transferred to the caller.  If the sub is named then the caller does
12012 not get ownership of a reference.  In most such cases, where the sub
12013 has a non-phase name, the sub will be alive at the point it is returned
12014 by virtue of being contained in the glob that names it.  A phase-named
12015 subroutine will usually be alive by virtue of the reference owned by the
12016 phase's automatic run queue.  But a C<BEGIN> subroutine, having already
12017 been executed, will quite likely have been destroyed already by the
12018 time this function returns, making it erroneous for the caller to make
12019 any use of the returned pointer.  It is the caller's responsibility to
12020 ensure that it knows which of these situations applies.
12021
12022 =cut
12023 */
12024
12025 CV *
12026 Perl_newXS_len_flags(pTHX_ const char *name, STRLEN len,
12027                            XSUBADDR_t subaddr, const char *const filename,
12028                            const char *const proto, SV **const_svp,
12029                            U32 flags)
12030 {
12031     CV *cv;
12032     bool interleave = FALSE;
12033     bool evanescent = FALSE;
12034
12035     PERL_ARGS_ASSERT_NEWXS_LEN_FLAGS;
12036
12037     {
12038         GV * const gv = gv_fetchpvn(
12039                             name ? name : PL_curstash ? "__ANON__" : "__ANON__::__ANON__",
12040                             name ? len : PL_curstash ? sizeof("__ANON__") - 1:
12041                                 sizeof("__ANON__::__ANON__") - 1,
12042                             GV_ADDMULTI | flags, SVt_PVCV);
12043
12044         if ((cv = (name ? GvCV(gv) : NULL))) {
12045             if (GvCVGEN(gv)) {
12046                 /* just a cached method */
12047                 SvREFCNT_dec(cv);
12048                 cv = NULL;
12049             }
12050             else if (CvROOT(cv) || CvXSUB(cv) || GvASSUMECV(gv)) {
12051                 /* already defined (or promised) */
12052                 /* Redundant check that allows us to avoid creating an SV
12053                    most of the time: */
12054                 if (CvCONST(cv) || ckWARN(WARN_REDEFINE)) {
12055                     report_redefined_cv(newSVpvn_flags(
12056                                          name,len,(flags&SVf_UTF8)|SVs_TEMP
12057                                         ),
12058                                         cv, const_svp);
12059                 }
12060                 interleave = TRUE;
12061                 ENTER;
12062                 SAVEFREESV(cv);
12063                 cv = NULL;
12064             }
12065         }
12066
12067         if (cv)                         /* must reuse cv if autoloaded */
12068             cv_undef(cv);
12069         else {
12070             cv = MUTABLE_CV(newSV_type(SVt_PVCV));
12071             if (name) {
12072                 GvCV_set(gv,cv);
12073                 GvCVGEN(gv) = 0;
12074                 if (HvENAME_HEK(GvSTASH(gv)))
12075                     gv_method_changed(gv); /* newXS */
12076             }
12077         }
12078         assert(cv);
12079         assert(SvREFCNT((SV*)cv) != 0);
12080
12081         CvGV_set(cv, gv);
12082         if(filename) {
12083             /* XSUBs can't be perl lang/perl5db.pl debugged
12084             if (PERLDB_LINE_OR_SAVESRC)
12085                 (void)gv_fetchfile(filename); */
12086             assert(!CvDYNFILE(cv)); /* cv_undef should have turned it off */
12087             if (flags & XS_DYNAMIC_FILENAME) {
12088                 CvDYNFILE_on(cv);
12089                 CvFILE(cv) = savepv(filename);
12090             } else {
12091             /* NOTE: not copied, as it is expected to be an external constant string */
12092                 CvFILE(cv) = (char *)filename;
12093             }
12094         } else {
12095             assert((flags & XS_DYNAMIC_FILENAME) == 0 && PL_xsubfilename);
12096             CvFILE(cv) = (char*)PL_xsubfilename;
12097         }
12098         CvISXSUB_on(cv);
12099         CvXSUB(cv) = subaddr;
12100 #ifndef PERL_IMPLICIT_CONTEXT
12101         CvHSCXT(cv) = &PL_stack_sp;
12102 #else
12103         PoisonPADLIST(cv);
12104 #endif
12105
12106         if (name)
12107             evanescent = process_special_blocks(0, name, gv, cv);
12108         else
12109             CvANON_on(cv);
12110     } /* <- not a conditional branch */
12111
12112     assert(cv);
12113     assert(evanescent || SvREFCNT((SV*)cv) != 0);
12114
12115     if (!evanescent) sv_setpv(MUTABLE_SV(cv), proto);
12116     if (interleave) LEAVE;
12117     assert(evanescent || SvREFCNT((SV*)cv) != 0);
12118     return cv;
12119 }
12120
12121 /* Add a stub CV to a typeglob.
12122  * This is the implementation of a forward declaration, 'sub foo';'
12123  */
12124
12125 CV *
12126 Perl_newSTUB(pTHX_ GV *gv, bool fake)
12127 {
12128     CV *cv = MUTABLE_CV(newSV_type(SVt_PVCV));
12129     GV *cvgv;
12130     PERL_ARGS_ASSERT_NEWSTUB;
12131     assert(!GvCVu(gv));
12132     GvCV_set(gv, cv);
12133     GvCVGEN(gv) = 0;
12134     if (!fake && GvSTASH(gv) && HvENAME_HEK(GvSTASH(gv)))
12135         gv_method_changed(gv);
12136     if (SvFAKE(gv)) {
12137         cvgv = gv_fetchsv((SV *)gv, GV_ADDMULTI, SVt_PVCV);
12138         SvFAKE_off(cvgv);
12139     }
12140     else cvgv = gv;
12141     CvGV_set(cv, cvgv);
12142     CvFILE_set_from_cop(cv, PL_curcop);
12143     CvSTASH_set(cv, PL_curstash);
12144     GvMULTI_on(gv);
12145     return cv;
12146 }
12147
12148 void
12149 Perl_newFORM(pTHX_ I32 floor, OP *o, OP *block)
12150 {
12151     CV *cv;
12152     GV *gv;
12153     OP *root;
12154     OP *start;
12155
12156     if (PL_parser && PL_parser->error_count) {
12157         op_free(block);
12158         goto finish;
12159     }
12160
12161     gv = o
12162         ? gv_fetchsv(cSVOPo->op_sv, GV_ADD, SVt_PVFM)
12163         : gv_fetchpvs("STDOUT", GV_ADD|GV_NOTQUAL, SVt_PVFM);
12164
12165     GvMULTI_on(gv);
12166     if ((cv = GvFORM(gv))) {
12167         if (ckWARN(WARN_REDEFINE)) {
12168             const line_t oldline = CopLINE(PL_curcop);
12169             if (PL_parser && PL_parser->copline != NOLINE)
12170                 CopLINE_set(PL_curcop, PL_parser->copline);
12171             if (o) {
12172                 Perl_warner(aTHX_ packWARN(WARN_REDEFINE),
12173                             "Format %" SVf " redefined", SVfARG(cSVOPo->op_sv));
12174             } else {
12175                 /* diag_listed_as: Format %s redefined */
12176                 Perl_warner(aTHX_ packWARN(WARN_REDEFINE),
12177                             "Format STDOUT redefined");
12178             }
12179             CopLINE_set(PL_curcop, oldline);
12180         }
12181         SvREFCNT_dec(cv);
12182     }
12183     cv = PL_compcv;
12184     GvFORM(gv) = (CV *)SvREFCNT_inc_simple_NN(cv);
12185     CvGV_set(cv, gv);
12186     CvFILE_set_from_cop(cv, PL_curcop);
12187
12188
12189     root = newUNOP(OP_LEAVEWRITE, 0, scalarseq(block));
12190     CvROOT(cv) = root;
12191     start = LINKLIST(root);
12192     root->op_next = 0;
12193     S_process_optree(aTHX_ cv, root, start);
12194     cv_forget_slab(cv);
12195
12196   finish:
12197     op_free(o);
12198     if (PL_parser)
12199         PL_parser->copline = NOLINE;
12200     LEAVE_SCOPE(floor);
12201     PL_compiling.cop_seq = 0;
12202 }
12203
12204 OP *
12205 Perl_newANONLIST(pTHX_ OP *o)
12206 {
12207     return op_convert_list(OP_ANONLIST, OPf_SPECIAL, o);
12208 }
12209
12210 OP *
12211 Perl_newANONHASH(pTHX_ OP *o)
12212 {
12213     return op_convert_list(OP_ANONHASH, OPf_SPECIAL, o);
12214 }
12215
12216 OP *
12217 Perl_newANONSUB(pTHX_ I32 floor, OP *proto, OP *block)
12218 {
12219     return newANONATTRSUB(floor, proto, NULL, block);
12220 }
12221
12222 OP *
12223 Perl_newANONATTRSUB(pTHX_ I32 floor, OP *proto, OP *attrs, OP *block)
12224 {
12225     SV * const cv = MUTABLE_SV(newATTRSUB(floor, 0, proto, attrs, block));
12226     OP * anoncode =
12227         newSVOP(OP_ANONCODE, 0,
12228                 cv);
12229     if (CvANONCONST(cv))
12230         anoncode = newUNOP(OP_ANONCONST, 0,
12231                            op_convert_list(OP_ENTERSUB,
12232                                            OPf_STACKED|OPf_WANT_SCALAR,
12233                                            anoncode));
12234     return newUNOP(OP_REFGEN, 0, anoncode);
12235 }
12236
12237 OP *
12238 Perl_oopsAV(pTHX_ OP *o)
12239 {
12240
12241     PERL_ARGS_ASSERT_OOPSAV;
12242
12243     switch (o->op_type) {
12244     case OP_PADSV:
12245     case OP_PADHV:
12246         OpTYPE_set(o, OP_PADAV);
12247         return ref(o, OP_RV2AV);
12248
12249     case OP_RV2SV:
12250     case OP_RV2HV:
12251         OpTYPE_set(o, OP_RV2AV);
12252         ref(o, OP_RV2AV);
12253         break;
12254
12255     default:
12256         Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL), "oops: oopsAV");
12257         break;
12258     }
12259     return o;
12260 }
12261
12262 OP *
12263 Perl_oopsHV(pTHX_ OP *o)
12264 {
12265
12266     PERL_ARGS_ASSERT_OOPSHV;
12267
12268     switch (o->op_type) {
12269     case OP_PADSV:
12270     case OP_PADAV:
12271         OpTYPE_set(o, OP_PADHV);
12272         return ref(o, OP_RV2HV);
12273
12274     case OP_RV2SV:
12275     case OP_RV2AV:
12276         OpTYPE_set(o, OP_RV2HV);
12277         /* rv2hv steals the bottom bit for its own uses */
12278         o->op_private &= ~OPpARG1_MASK;
12279         ref(o, OP_RV2HV);
12280         break;
12281
12282     default:
12283         Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL), "oops: oopsHV");
12284         break;
12285     }
12286     return o;
12287 }
12288
12289 OP *
12290 Perl_newAVREF(pTHX_ OP *o)
12291 {
12292
12293     PERL_ARGS_ASSERT_NEWAVREF;
12294
12295     if (o->op_type == OP_PADANY) {
12296         OpTYPE_set(o, OP_PADAV);
12297         return o;
12298     }
12299     else if ((o->op_type == OP_RV2AV || o->op_type == OP_PADAV)) {
12300         Perl_croak(aTHX_ "Can't use an array as a reference");
12301     }
12302     return newUNOP(OP_RV2AV, 0, scalar(o));
12303 }
12304
12305 OP *
12306 Perl_newGVREF(pTHX_ I32 type, OP *o)
12307 {
12308     if (type == OP_MAPSTART || type == OP_GREPSTART || type == OP_SORT)
12309         return newUNOP(OP_NULL, 0, o);
12310     return ref(newUNOP(OP_RV2GV, OPf_REF, o), type);
12311 }
12312
12313 OP *
12314 Perl_newHVREF(pTHX_ OP *o)
12315 {
12316
12317     PERL_ARGS_ASSERT_NEWHVREF;
12318
12319     if (o->op_type == OP_PADANY) {
12320         OpTYPE_set(o, OP_PADHV);
12321         return o;
12322     }
12323     else if ((o->op_type == OP_RV2HV || o->op_type == OP_PADHV)) {
12324         Perl_croak(aTHX_ "Can't use a hash as a reference");
12325     }
12326     return newUNOP(OP_RV2HV, 0, scalar(o));
12327 }
12328
12329 OP *
12330 Perl_newCVREF(pTHX_ I32 flags, OP *o)
12331 {
12332     if (o->op_type == OP_PADANY) {
12333         OpTYPE_set(o, OP_PADCV);
12334     }
12335     return newUNOP(OP_RV2CV, flags, scalar(o));
12336 }
12337
12338 OP *
12339 Perl_newSVREF(pTHX_ OP *o)
12340 {
12341
12342     PERL_ARGS_ASSERT_NEWSVREF;
12343
12344     if (o->op_type == OP_PADANY) {
12345         OpTYPE_set(o, OP_PADSV);
12346         scalar(o);
12347         return o;
12348     }
12349     return newUNOP(OP_RV2SV, 0, scalar(o));
12350 }
12351
12352 /* Check routines. See the comments at the top of this file for details
12353  * on when these are called */
12354
12355 OP *
12356 Perl_ck_anoncode(pTHX_ OP *o)
12357 {
12358     PERL_ARGS_ASSERT_CK_ANONCODE;
12359
12360     cSVOPo->op_targ = pad_add_anon((CV*)cSVOPo->op_sv, o->op_type);
12361     cSVOPo->op_sv = NULL;
12362     return o;
12363 }
12364
12365 static void
12366 S_io_hints(pTHX_ OP *o)
12367 {
12368 #if O_BINARY != 0 || O_TEXT != 0
12369     HV * const table =
12370         PL_hints & HINT_LOCALIZE_HH ? GvHV(PL_hintgv) : NULL;;
12371     if (table) {
12372         SV **svp = hv_fetchs(table, "open_IN", FALSE);
12373         if (svp && *svp) {
12374             STRLEN len = 0;
12375             const char *d = SvPV_const(*svp, len);
12376             const I32 mode = mode_from_discipline(d, len);
12377             /* bit-and:ing with zero O_BINARY or O_TEXT would be useless. */
12378 #  if O_BINARY != 0
12379             if (mode & O_BINARY)
12380                 o->op_private |= OPpOPEN_IN_RAW;
12381 #  endif
12382 #  if O_TEXT != 0
12383             if (mode & O_TEXT)
12384                 o->op_private |= OPpOPEN_IN_CRLF;
12385 #  endif
12386         }
12387
12388         svp = hv_fetchs(table, "open_OUT", FALSE);
12389         if (svp && *svp) {
12390             STRLEN len = 0;
12391             const char *d = SvPV_const(*svp, len);
12392             const I32 mode = mode_from_discipline(d, len);
12393             /* bit-and:ing with zero O_BINARY or O_TEXT would be useless. */
12394 #  if O_BINARY != 0
12395             if (mode & O_BINARY)
12396                 o->op_private |= OPpOPEN_OUT_RAW;
12397 #  endif
12398 #  if O_TEXT != 0
12399             if (mode & O_TEXT)
12400                 o->op_private |= OPpOPEN_OUT_CRLF;
12401 #  endif
12402         }
12403     }
12404 #else
12405     PERL_UNUSED_CONTEXT;
12406     PERL_UNUSED_ARG(o);
12407 #endif
12408 }
12409
12410 OP *
12411 Perl_ck_backtick(pTHX_ OP *o)
12412 {
12413     GV *gv;
12414     OP *newop = NULL;
12415     OP *sibl;
12416     PERL_ARGS_ASSERT_CK_BACKTICK;
12417     o = ck_fun(o);
12418     /* qx and `` have a null pushmark; CORE::readpipe has only one kid. */
12419     if (o->op_flags & OPf_KIDS && (sibl = OpSIBLING(cUNOPo->op_first))
12420      && (gv = gv_override("readpipe",8)))
12421     {
12422         /* detach rest of siblings from o and its first child */
12423         op_sibling_splice(o, cUNOPo->op_first, -1, NULL);
12424         newop = S_new_entersubop(aTHX_ gv, sibl);
12425     }
12426     else if (!(o->op_flags & OPf_KIDS))
12427         newop = newUNOP(OP_BACKTICK, 0, newDEFSVOP());
12428     if (newop) {
12429         op_free(o);
12430         return newop;
12431     }
12432     S_io_hints(aTHX_ o);
12433     return o;
12434 }
12435
12436 OP *
12437 Perl_ck_bitop(pTHX_ OP *o)
12438 {
12439     PERL_ARGS_ASSERT_CK_BITOP;
12440
12441     o->op_private = (U8)(PL_hints & HINT_INTEGER);
12442
12443     if (!(o->op_flags & OPf_STACKED) /* Not an assignment */
12444             && OP_IS_INFIX_BIT(o->op_type))
12445     {
12446         const OP * const left = cBINOPo->op_first;
12447         const OP * const right = OpSIBLING(left);
12448         if ((OP_IS_NUMCOMPARE(left->op_type) &&
12449                 (left->op_flags & OPf_PARENS) == 0) ||
12450             (OP_IS_NUMCOMPARE(right->op_type) &&
12451                 (right->op_flags & OPf_PARENS) == 0))
12452             Perl_ck_warner(aTHX_ packWARN(WARN_PRECEDENCE),
12453                           "Possible precedence problem on bitwise %s operator",
12454                            o->op_type ==  OP_BIT_OR
12455                          ||o->op_type == OP_NBIT_OR  ? "|"
12456                         :  o->op_type ==  OP_BIT_AND
12457                          ||o->op_type == OP_NBIT_AND ? "&"
12458                         :  o->op_type ==  OP_BIT_XOR
12459                          ||o->op_type == OP_NBIT_XOR ? "^"
12460                         :  o->op_type == OP_SBIT_OR  ? "|."
12461                         :  o->op_type == OP_SBIT_AND ? "&." : "^."
12462                            );
12463     }
12464     return o;
12465 }
12466
12467 PERL_STATIC_INLINE bool
12468 is_dollar_bracket(pTHX_ const OP * const o)
12469 {
12470     const OP *kid;
12471     PERL_UNUSED_CONTEXT;
12472     return o->op_type == OP_RV2SV && o->op_flags & OPf_KIDS
12473         && (kid = cUNOPx(o)->op_first)
12474         && kid->op_type == OP_GV
12475         && strEQ(GvNAME(cGVOPx_gv(kid)), "[");
12476 }
12477
12478 /* for lt, gt, le, ge, eq, ne and their i_ variants */
12479
12480 OP *
12481 Perl_ck_cmp(pTHX_ OP *o)
12482 {
12483     bool is_eq;
12484     bool neg;
12485     bool reverse;
12486     bool iv0;
12487     OP *indexop, *constop, *start;
12488     SV *sv;
12489     IV iv;
12490
12491     PERL_ARGS_ASSERT_CK_CMP;
12492
12493     is_eq = (   o->op_type == OP_EQ
12494              || o->op_type == OP_NE
12495              || o->op_type == OP_I_EQ
12496              || o->op_type == OP_I_NE);
12497
12498     if (!is_eq && ckWARN(WARN_SYNTAX)) {
12499         const OP *kid = cUNOPo->op_first;
12500         if (kid &&
12501             (
12502                 (   is_dollar_bracket(aTHX_ kid)
12503                  && OpSIBLING(kid) && OpSIBLING(kid)->op_type == OP_CONST
12504                 )
12505              || (   kid->op_type == OP_CONST
12506                  && (kid = OpSIBLING(kid)) && is_dollar_bracket(aTHX_ kid)
12507                 )
12508            )
12509         )
12510             Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
12511                         "$[ used in %s (did you mean $] ?)", OP_DESC(o));
12512     }
12513
12514     /* convert (index(...) == -1) and variations into
12515      *   (r)index/BOOL(,NEG)
12516      */
12517
12518     reverse = FALSE;
12519
12520     indexop = cUNOPo->op_first;
12521     constop = OpSIBLING(indexop);
12522     start = NULL;
12523     if (indexop->op_type == OP_CONST) {
12524         constop = indexop;
12525         indexop = OpSIBLING(constop);
12526         start = constop;
12527         reverse = TRUE;
12528     }
12529
12530     if (indexop->op_type != OP_INDEX && indexop->op_type != OP_RINDEX)
12531         return o;
12532
12533     /* ($lex = index(....)) == -1 */
12534     if (indexop->op_private & OPpTARGET_MY)
12535         return o;
12536
12537     if (constop->op_type != OP_CONST)
12538         return o;
12539
12540     sv = cSVOPx_sv(constop);
12541     if (!(sv && SvIOK_notUV(sv)))
12542         return o;
12543
12544     iv = SvIVX(sv);
12545     if (iv != -1 && iv != 0)
12546         return o;
12547     iv0 = (iv == 0);
12548
12549     if (o->op_type == OP_LT || o->op_type == OP_I_LT) {
12550         if (!(iv0 ^ reverse))
12551             return o;
12552         neg = iv0;
12553     }
12554     else if (o->op_type == OP_LE || o->op_type == OP_I_LE) {
12555         if (iv0 ^ reverse)
12556             return o;
12557         neg = !iv0;
12558     }
12559     else if (o->op_type == OP_GE || o->op_type == OP_I_GE) {
12560         if (!(iv0 ^ reverse))
12561             return o;
12562         neg = !iv0;
12563     }
12564     else if (o->op_type == OP_GT || o->op_type == OP_I_GT) {
12565         if (iv0 ^ reverse)
12566             return o;
12567         neg = iv0;
12568     }
12569     else if (o->op_type == OP_EQ || o->op_type == OP_I_EQ) {
12570         if (iv0)
12571             return o;
12572         neg = TRUE;
12573     }
12574     else {
12575         assert(o->op_type == OP_NE || o->op_type == OP_I_NE);
12576         if (iv0)
12577             return o;
12578         neg = FALSE;
12579     }
12580
12581     indexop->op_flags &= ~OPf_PARENS;
12582     indexop->op_flags |= (o->op_flags & OPf_PARENS);
12583     indexop->op_private |= OPpTRUEBOOL;
12584     if (neg)
12585         indexop->op_private |= OPpINDEX_BOOLNEG;
12586     /* cut out the index op and free the eq,const ops */
12587     (void)op_sibling_splice(o, start, 1, NULL);
12588     op_free(o);
12589
12590     return indexop;
12591 }
12592
12593
12594 OP *
12595 Perl_ck_concat(pTHX_ OP *o)
12596 {
12597     const OP * const kid = cUNOPo->op_first;
12598
12599     PERL_ARGS_ASSERT_CK_CONCAT;
12600     PERL_UNUSED_CONTEXT;
12601
12602     /* reuse the padtmp returned by the concat child */
12603     if (kid->op_type == OP_CONCAT && !(kid->op_private & OPpTARGET_MY) &&
12604             !(kUNOP->op_first->op_flags & OPf_MOD))
12605     {
12606         o->op_flags |= OPf_STACKED;
12607         o->op_private |= OPpCONCAT_NESTED;
12608     }
12609     return o;
12610 }
12611
12612 OP *
12613 Perl_ck_spair(pTHX_ OP *o)
12614 {
12615
12616     PERL_ARGS_ASSERT_CK_SPAIR;
12617
12618     if (o->op_flags & OPf_KIDS) {
12619         OP* newop;
12620         OP* kid;
12621         OP* kidkid;
12622         const OPCODE type = o->op_type;
12623         o = modkids(ck_fun(o), type);
12624         kid    = cUNOPo->op_first;
12625         kidkid = kUNOP->op_first;
12626         newop = OpSIBLING(kidkid);
12627         if (newop) {
12628             const OPCODE type = newop->op_type;
12629             if (OpHAS_SIBLING(newop))
12630                 return o;
12631             if (o->op_type == OP_REFGEN
12632              && (  type == OP_RV2CV
12633                 || (  !(newop->op_flags & OPf_PARENS)
12634                    && (  type == OP_RV2AV || type == OP_PADAV
12635                       || type == OP_RV2HV || type == OP_PADHV))))
12636                 NOOP; /* OK (allow srefgen for \@a and \%h) */
12637             else if (OP_GIMME(newop,0) != G_SCALAR)
12638                 return o;
12639         }
12640         /* excise first sibling */
12641         op_sibling_splice(kid, NULL, 1, NULL);
12642         op_free(kidkid);
12643     }
12644     /* transforms OP_REFGEN into OP_SREFGEN, OP_CHOP into OP_SCHOP,
12645      * and OP_CHOMP into OP_SCHOMP */
12646     o->op_ppaddr = PL_ppaddr[++o->op_type];
12647     return ck_fun(o);
12648 }
12649
12650 OP *
12651 Perl_ck_delete(pTHX_ OP *o)
12652 {
12653     PERL_ARGS_ASSERT_CK_DELETE;
12654
12655     o = ck_fun(o);
12656     o->op_private = 0;
12657     if (o->op_flags & OPf_KIDS) {
12658         OP * const kid = cUNOPo->op_first;
12659         switch (kid->op_type) {
12660         case OP_ASLICE:
12661             o->op_flags |= OPf_SPECIAL;
12662             /* FALLTHROUGH */
12663         case OP_HSLICE:
12664             o->op_private |= OPpSLICE;
12665             break;
12666         case OP_AELEM:
12667             o->op_flags |= OPf_SPECIAL;
12668             /* FALLTHROUGH */
12669         case OP_HELEM:
12670             break;
12671         case OP_KVASLICE:
12672             o->op_flags |= OPf_SPECIAL;
12673             /* FALLTHROUGH */
12674         case OP_KVHSLICE:
12675             o->op_private |= OPpKVSLICE;
12676             break;
12677         default:
12678             Perl_croak(aTHX_ "delete argument is not a HASH or ARRAY "
12679                              "element or slice");
12680         }
12681         if (kid->op_private & OPpLVAL_INTRO)
12682             o->op_private |= OPpLVAL_INTRO;
12683         op_null(kid);
12684     }
12685     return o;
12686 }
12687
12688 OP *
12689 Perl_ck_eof(pTHX_ OP *o)
12690 {
12691     PERL_ARGS_ASSERT_CK_EOF;
12692
12693     if (o->op_flags & OPf_KIDS) {
12694         OP *kid;
12695         if (cLISTOPo->op_first->op_type == OP_STUB) {
12696             OP * const newop
12697                 = newUNOP(o->op_type, OPf_SPECIAL, newGVOP(OP_GV, 0, PL_argvgv));
12698             op_free(o);
12699             o = newop;
12700         }
12701         o = ck_fun(o);
12702         kid = cLISTOPo->op_first;
12703         if (kid->op_type == OP_RV2GV)
12704             kid->op_private |= OPpALLOW_FAKE;
12705     }
12706     return o;
12707 }
12708
12709
12710 OP *
12711 Perl_ck_eval(pTHX_ OP *o)
12712 {
12713
12714     PERL_ARGS_ASSERT_CK_EVAL;
12715
12716     PL_hints |= HINT_BLOCK_SCOPE;
12717     if (o->op_flags & OPf_KIDS) {
12718         SVOP * const kid = (SVOP*)cUNOPo->op_first;
12719         assert(kid);
12720
12721         if (o->op_type == OP_ENTERTRY) {
12722             LOGOP *enter;
12723
12724             /* cut whole sibling chain free from o */
12725             op_sibling_splice(o, NULL, -1, NULL);
12726             op_free(o);
12727
12728             enter = alloc_LOGOP(OP_ENTERTRY, NULL, NULL);
12729
12730             /* establish postfix order */
12731             enter->op_next = (OP*)enter;
12732
12733             o = op_prepend_elem(OP_LINESEQ, (OP*)enter, (OP*)kid);
12734             OpTYPE_set(o, OP_LEAVETRY);
12735             enter->op_other = o;
12736             return o;
12737         }
12738         else {
12739             scalar((OP*)kid);
12740             S_set_haseval(aTHX);
12741         }
12742     }
12743     else {
12744         const U8 priv = o->op_private;
12745         op_free(o);
12746         /* the newUNOP will recursively call ck_eval(), which will handle
12747          * all the stuff at the end of this function, like adding
12748          * OP_HINTSEVAL
12749          */
12750         return newUNOP(OP_ENTEREVAL, priv <<8, newDEFSVOP());
12751     }
12752     o->op_targ = (PADOFFSET)PL_hints;
12753     if (o->op_private & OPpEVAL_BYTES) o->op_targ &= ~HINT_UTF8;
12754     if ((PL_hints & HINT_LOCALIZE_HH) != 0
12755      && !(o->op_private & OPpEVAL_COPHH) && GvHV(PL_hintgv)) {
12756         /* Store a copy of %^H that pp_entereval can pick up. */
12757         HV *hh = hv_copy_hints_hv(GvHV(PL_hintgv));
12758         OP *hhop;
12759         STOREFEATUREBITSHH(hh);
12760         hhop = newSVOP(OP_HINTSEVAL, 0, MUTABLE_SV(hh));
12761         /* append hhop to only child  */
12762         op_sibling_splice(o, cUNOPo->op_first, 0, hhop);
12763
12764         o->op_private |= OPpEVAL_HAS_HH;
12765     }
12766     if (!(o->op_private & OPpEVAL_BYTES)
12767          && FEATURE_UNIEVAL_IS_ENABLED)
12768             o->op_private |= OPpEVAL_UNICODE;
12769     return o;
12770 }
12771
12772 OP *
12773 Perl_ck_exec(pTHX_ OP *o)
12774 {
12775     PERL_ARGS_ASSERT_CK_EXEC;
12776
12777     if (o->op_flags & OPf_STACKED) {
12778         OP *kid;
12779         o = ck_fun(o);
12780         kid = OpSIBLING(cUNOPo->op_first);
12781         if (kid->op_type == OP_RV2GV)
12782             op_null(kid);
12783     }
12784     else
12785         o = listkids(o);
12786     return o;
12787 }
12788
12789 OP *
12790 Perl_ck_exists(pTHX_ OP *o)
12791 {
12792     PERL_ARGS_ASSERT_CK_EXISTS;
12793
12794     o = ck_fun(o);
12795     if (o->op_flags & OPf_KIDS) {
12796         OP * const kid = cUNOPo->op_first;
12797         if (kid->op_type == OP_ENTERSUB) {
12798             (void) ref(kid, o->op_type);
12799             if (kid->op_type != OP_RV2CV
12800                         && !(PL_parser && PL_parser->error_count))
12801                 Perl_croak(aTHX_
12802                           "exists argument is not a subroutine name");
12803             o->op_private |= OPpEXISTS_SUB;
12804         }
12805         else if (kid->op_type == OP_AELEM)
12806             o->op_flags |= OPf_SPECIAL;
12807         else if (kid->op_type != OP_HELEM)
12808             Perl_croak(aTHX_ "exists argument is not a HASH or ARRAY "
12809                              "element or a subroutine");
12810         op_null(kid);
12811     }
12812     return o;
12813 }
12814
12815 OP *
12816 Perl_ck_rvconst(pTHX_ OP *o)
12817 {
12818     SVOP * const kid = (SVOP*)cUNOPo->op_first;
12819
12820     PERL_ARGS_ASSERT_CK_RVCONST;
12821
12822     if (o->op_type == OP_RV2HV)
12823         /* rv2hv steals the bottom bit for its own uses */
12824         o->op_private &= ~OPpARG1_MASK;
12825
12826     o->op_private |= (PL_hints & HINT_STRICT_REFS);
12827
12828     if (kid->op_type == OP_CONST) {
12829         int iscv;
12830         GV *gv;
12831         SV * const kidsv = kid->op_sv;
12832
12833         /* Is it a constant from cv_const_sv()? */
12834         if ((SvROK(kidsv) || isGV_with_GP(kidsv)) && SvREADONLY(kidsv)) {
12835             return o;
12836         }
12837         if (SvTYPE(kidsv) == SVt_PVAV) return o;
12838         if ((o->op_private & HINT_STRICT_REFS) && (kid->op_private & OPpCONST_BARE)) {
12839             const char *badthing;
12840             switch (o->op_type) {
12841             case OP_RV2SV:
12842                 badthing = "a SCALAR";
12843                 break;
12844             case OP_RV2AV:
12845                 badthing = "an ARRAY";
12846                 break;
12847             case OP_RV2HV:
12848                 badthing = "a HASH";
12849                 break;
12850             default:
12851                 badthing = NULL;
12852                 break;
12853             }
12854             if (badthing)
12855                 Perl_croak(aTHX_
12856                            "Can't use bareword (\"%" SVf "\") as %s ref while \"strict refs\" in use",
12857                            SVfARG(kidsv), badthing);
12858         }
12859         /*
12860          * This is a little tricky.  We only want to add the symbol if we
12861          * didn't add it in the lexer.  Otherwise we get duplicate strict
12862          * warnings.  But if we didn't add it in the lexer, we must at
12863          * least pretend like we wanted to add it even if it existed before,
12864          * or we get possible typo warnings.  OPpCONST_ENTERED says
12865          * whether the lexer already added THIS instance of this symbol.
12866          */
12867         iscv = o->op_type == OP_RV2CV ? GV_NOEXPAND|GV_ADDMULTI : 0;
12868         gv = gv_fetchsv(kidsv,
12869                 o->op_type == OP_RV2CV
12870                         && o->op_private & OPpMAY_RETURN_CONSTANT
12871                     ? GV_NOEXPAND
12872                     : iscv | !(kid->op_private & OPpCONST_ENTERED),
12873                 iscv
12874                     ? SVt_PVCV
12875                     : o->op_type == OP_RV2SV
12876                         ? SVt_PV
12877                         : o->op_type == OP_RV2AV
12878                             ? SVt_PVAV
12879                             : o->op_type == OP_RV2HV
12880                                 ? SVt_PVHV
12881                                 : SVt_PVGV);
12882         if (gv) {
12883             if (!isGV(gv)) {
12884                 assert(iscv);
12885                 assert(SvROK(gv));
12886                 if (!(o->op_private & OPpMAY_RETURN_CONSTANT)
12887                   && SvTYPE(SvRV(gv)) != SVt_PVCV)
12888                     gv_fetchsv(kidsv, GV_ADDMULTI, SVt_PVCV);
12889             }
12890             OpTYPE_set(kid, OP_GV);
12891             SvREFCNT_dec(kid->op_sv);
12892 #ifdef USE_ITHREADS
12893             /* XXX hack: dependence on sizeof(PADOP) <= sizeof(SVOP) */
12894             STATIC_ASSERT_STMT(sizeof(PADOP) <= sizeof(SVOP));
12895             kPADOP->op_padix = pad_alloc(OP_GV, SVf_READONLY);
12896             SvREFCNT_dec(PAD_SVl(kPADOP->op_padix));
12897             PAD_SETSV(kPADOP->op_padix, MUTABLE_SV(SvREFCNT_inc_simple_NN(gv)));
12898 #else
12899             kid->op_sv = SvREFCNT_inc_simple_NN(gv);
12900 #endif
12901             kid->op_private = 0;
12902             /* FAKE globs in the symbol table cause weird bugs (#77810) */
12903             SvFAKE_off(gv);
12904         }
12905     }
12906     return o;
12907 }
12908
12909 OP *
12910 Perl_ck_ftst(pTHX_ OP *o)
12911 {
12912     const I32 type = o->op_type;
12913
12914     PERL_ARGS_ASSERT_CK_FTST;
12915
12916     if (o->op_flags & OPf_REF) {
12917         NOOP;
12918     }
12919     else if (o->op_flags & OPf_KIDS && cUNOPo->op_first->op_type != OP_STUB) {
12920         SVOP * const kid = (SVOP*)cUNOPo->op_first;
12921         const OPCODE kidtype = kid->op_type;
12922
12923         if (kidtype == OP_CONST && (kid->op_private & OPpCONST_BARE)
12924          && !kid->op_folded) {
12925             OP * const newop = newGVOP(type, OPf_REF,
12926                 gv_fetchsv(kid->op_sv, GV_ADD, SVt_PVIO));
12927             op_free(o);
12928             return newop;
12929         }
12930
12931         if ((kidtype == OP_RV2AV || kidtype == OP_PADAV) && ckWARN(WARN_SYNTAX)) {
12932             SV *name = S_op_varname_subscript(aTHX_ (OP*)kid, 2);
12933             if (name) {
12934                 /* diag_listed_as: Array passed to stat will be coerced to a scalar%s */
12935                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX), "%s (did you want stat %" SVf "?)",
12936                             array_passed_to_stat, name);
12937             }
12938             else {
12939                 /* diag_listed_as: Array passed to stat will be coerced to a scalar%s */
12940                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX), "%s", array_passed_to_stat);
12941             }
12942        }
12943         scalar((OP *) kid);
12944         if ((PL_hints & HINT_FILETEST_ACCESS) && OP_IS_FILETEST_ACCESS(o->op_type))
12945             o->op_private |= OPpFT_ACCESS;
12946         if (OP_IS_FILETEST(type)
12947             && OP_IS_FILETEST(kidtype)
12948         ) {
12949             o->op_private |= OPpFT_STACKED;
12950             kid->op_private |= OPpFT_STACKING;
12951             if (kidtype == OP_FTTTY && (
12952                    !(kid->op_private & OPpFT_STACKED)
12953                 || kid->op_private & OPpFT_AFTER_t
12954                ))
12955                 o->op_private |= OPpFT_AFTER_t;
12956         }
12957     }
12958     else {
12959         op_free(o);
12960         if (type == OP_FTTTY)
12961             o = newGVOP(type, OPf_REF, PL_stdingv);
12962         else
12963             o = newUNOP(type, 0, newDEFSVOP());
12964     }
12965     return o;
12966 }
12967
12968 OP *
12969 Perl_ck_fun(pTHX_ OP *o)
12970 {
12971     const int type = o->op_type;
12972     I32 oa = PL_opargs[type] >> OASHIFT;
12973
12974     PERL_ARGS_ASSERT_CK_FUN;
12975
12976     if (o->op_flags & OPf_STACKED) {
12977         if ((oa & OA_OPTIONAL) && (oa >> 4) && !((oa >> 4) & OA_OPTIONAL))
12978             oa &= ~OA_OPTIONAL;
12979         else
12980             return no_fh_allowed(o);
12981     }
12982
12983     if (o->op_flags & OPf_KIDS) {
12984         OP *prev_kid = NULL;
12985         OP *kid = cLISTOPo->op_first;
12986         I32 numargs = 0;
12987         bool seen_optional = FALSE;
12988
12989         if (kid->op_type == OP_PUSHMARK ||
12990             (kid->op_type == OP_NULL && kid->op_targ == OP_PUSHMARK))
12991         {
12992             prev_kid = kid;
12993             kid = OpSIBLING(kid);
12994         }
12995         if (kid && kid->op_type == OP_COREARGS) {
12996             bool optional = FALSE;
12997             while (oa) {
12998                 numargs++;
12999                 if (oa & OA_OPTIONAL) optional = TRUE;
13000                 oa = oa >> 4;
13001             }
13002             if (optional) o->op_private |= numargs;
13003             return o;
13004         }
13005
13006         while (oa) {
13007             if (oa & OA_OPTIONAL || (oa & 7) == OA_LIST) {
13008                 if (!kid && !seen_optional && PL_opargs[type] & OA_DEFGV) {
13009                     kid = newDEFSVOP();
13010                     /* append kid to chain */
13011                     op_sibling_splice(o, prev_kid, 0, kid);
13012                 }
13013                 seen_optional = TRUE;
13014             }
13015             if (!kid) break;
13016
13017             numargs++;
13018             switch (oa & 7) {
13019             case OA_SCALAR:
13020                 /* list seen where single (scalar) arg expected? */
13021                 if (numargs == 1 && !(oa >> 4)
13022                     && kid->op_type == OP_LIST && type != OP_SCALAR)
13023                 {
13024                     return too_many_arguments_pv(o,PL_op_desc[type], 0);
13025                 }
13026                 if (type != OP_DELETE) scalar(kid);
13027                 break;
13028             case OA_LIST:
13029                 if (oa < 16) {
13030                     kid = 0;
13031                     continue;
13032                 }
13033                 else
13034                     list(kid);
13035                 break;
13036             case OA_AVREF:
13037                 if ((type == OP_PUSH || type == OP_UNSHIFT)
13038                     && !OpHAS_SIBLING(kid))
13039                     Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX),
13040                                    "Useless use of %s with no values",
13041                                    PL_op_desc[type]);
13042
13043                 if (kid->op_type == OP_CONST
13044                       && (  !SvROK(cSVOPx_sv(kid))
13045                          || SvTYPE(SvRV(cSVOPx_sv(kid))) != SVt_PVAV  )
13046                         )
13047                     bad_type_pv(numargs, "array", o, kid);
13048                 else if (kid->op_type == OP_RV2HV || kid->op_type == OP_PADHV
13049                          || kid->op_type == OP_RV2GV) {
13050                     bad_type_pv(1, "array", o, kid);
13051                 }
13052                 else if (kid->op_type != OP_RV2AV && kid->op_type != OP_PADAV) {
13053                     yyerror_pv(Perl_form(aTHX_ "Experimental %s on scalar is now forbidden",
13054                                          PL_op_desc[type]), 0);
13055                 }
13056                 else {
13057                     op_lvalue(kid, type);
13058                 }
13059                 break;
13060             case OA_HVREF:
13061                 if (kid->op_type != OP_RV2HV && kid->op_type != OP_PADHV)
13062                     bad_type_pv(numargs, "hash", o, kid);
13063                 op_lvalue(kid, type);
13064                 break;
13065             case OA_CVREF:
13066                 {
13067                     /* replace kid with newop in chain */
13068                     OP * const newop =
13069                         S_op_sibling_newUNOP(aTHX_ o, prev_kid, OP_NULL, 0);
13070                     newop->op_next = newop;
13071                     kid = newop;
13072                 }
13073                 break;
13074             case OA_FILEREF:
13075                 if (kid->op_type != OP_GV && kid->op_type != OP_RV2GV) {
13076                     if (kid->op_type == OP_CONST &&
13077                         (kid->op_private & OPpCONST_BARE))
13078                     {
13079                         OP * const newop = newGVOP(OP_GV, 0,
13080                             gv_fetchsv(((SVOP*)kid)->op_sv, GV_ADD, SVt_PVIO));
13081                         /* replace kid with newop in chain */
13082                         op_sibling_splice(o, prev_kid, 1, newop);
13083                         op_free(kid);
13084                         kid = newop;
13085                     }
13086                     else if (kid->op_type == OP_READLINE) {
13087                         /* neophyte patrol: open(<FH>), close(<FH>) etc. */
13088                         bad_type_pv(numargs, "HANDLE", o, kid);
13089                     }
13090                     else {
13091                         I32 flags = OPf_SPECIAL;
13092                         I32 priv = 0;
13093                         PADOFFSET targ = 0;
13094
13095                         /* is this op a FH constructor? */
13096                         if (is_handle_constructor(o,numargs)) {
13097                             const char *name = NULL;
13098                             STRLEN len = 0;
13099                             U32 name_utf8 = 0;
13100                             bool want_dollar = TRUE;
13101
13102                             flags = 0;
13103                             /* Set a flag to tell rv2gv to vivify
13104                              * need to "prove" flag does not mean something
13105                              * else already - NI-S 1999/05/07
13106                              */
13107                             priv = OPpDEREF;
13108                             if (kid->op_type == OP_PADSV) {
13109                                 PADNAME * const pn
13110                                     = PAD_COMPNAME_SV(kid->op_targ);
13111                                 name = PadnamePV (pn);
13112                                 len  = PadnameLEN(pn);
13113                                 name_utf8 = PadnameUTF8(pn);
13114                             }
13115                             else if (kid->op_type == OP_RV2SV
13116                                      && kUNOP->op_first->op_type == OP_GV)
13117                             {
13118                                 GV * const gv = cGVOPx_gv(kUNOP->op_first);
13119                                 name = GvNAME(gv);
13120                                 len = GvNAMELEN(gv);
13121                                 name_utf8 = GvNAMEUTF8(gv) ? SVf_UTF8 : 0;
13122                             }
13123                             else if (kid->op_type == OP_AELEM
13124                                      || kid->op_type == OP_HELEM)
13125                             {
13126                                  OP *firstop;
13127                                  OP *op = ((BINOP*)kid)->op_first;
13128                                  name = NULL;
13129                                  if (op) {
13130                                       SV *tmpstr = NULL;
13131                                       const char * const a =
13132                                            kid->op_type == OP_AELEM ?
13133                                            "[]" : "{}";
13134                                       if (((op->op_type == OP_RV2AV) ||
13135                                            (op->op_type == OP_RV2HV)) &&
13136                                           (firstop = ((UNOP*)op)->op_first) &&
13137                                           (firstop->op_type == OP_GV)) {
13138                                            /* packagevar $a[] or $h{} */
13139                                            GV * const gv = cGVOPx_gv(firstop);
13140                                            if (gv)
13141                                                 tmpstr =
13142                                                      Perl_newSVpvf(aTHX_
13143                                                                    "%s%c...%c",
13144                                                                    GvNAME(gv),
13145                                                                    a[0], a[1]);
13146                                       }
13147                                       else if (op->op_type == OP_PADAV
13148                                                || op->op_type == OP_PADHV) {
13149                                            /* lexicalvar $a[] or $h{} */
13150                                            const char * const padname =
13151                                                 PAD_COMPNAME_PV(op->op_targ);
13152                                            if (padname)
13153                                                 tmpstr =
13154                                                      Perl_newSVpvf(aTHX_
13155                                                                    "%s%c...%c",
13156                                                                    padname + 1,
13157                                                                    a[0], a[1]);
13158                                       }
13159                                       if (tmpstr) {
13160                                            name = SvPV_const(tmpstr, len);
13161                                            name_utf8 = SvUTF8(tmpstr);
13162                                            sv_2mortal(tmpstr);
13163                                       }
13164                                  }
13165                                  if (!name) {
13166                                       name = "__ANONIO__";
13167                                       len = 10;
13168                                       want_dollar = FALSE;
13169                                  }
13170                                  op_lvalue(kid, type);
13171                             }
13172                             if (name) {
13173                                 SV *namesv;
13174                                 targ = pad_alloc(OP_RV2GV, SVf_READONLY);
13175                                 namesv = PAD_SVl(targ);
13176                                 if (want_dollar && *name != '$')
13177                                     sv_setpvs(namesv, "$");
13178                                 else
13179                                     SvPVCLEAR(namesv);
13180                                 sv_catpvn(namesv, name, len);
13181                                 if ( name_utf8 ) SvUTF8_on(namesv);
13182                             }
13183                         }
13184                         scalar(kid);
13185                         kid = S_op_sibling_newUNOP(aTHX_ o, prev_kid,
13186                                     OP_RV2GV, flags);
13187                         kid->op_targ = targ;
13188                         kid->op_private |= priv;
13189                     }
13190                 }
13191                 scalar(kid);
13192                 break;
13193             case OA_SCALARREF:
13194                 if ((type == OP_UNDEF || type == OP_POS)
13195                     && numargs == 1 && !(oa >> 4)
13196                     && kid->op_type == OP_LIST)
13197                     return too_many_arguments_pv(o,PL_op_desc[type], 0);
13198                 op_lvalue(scalar(kid), type);
13199                 break;
13200             }
13201             oa >>= 4;
13202             prev_kid = kid;
13203             kid = OpSIBLING(kid);
13204         }
13205         /* FIXME - should the numargs or-ing move after the too many
13206          * arguments check? */
13207         o->op_private |= numargs;
13208         if (kid)
13209             return too_many_arguments_pv(o,OP_DESC(o), 0);
13210         listkids(o);
13211     }
13212     else if (PL_opargs[type] & OA_DEFGV) {
13213         /* Ordering of these two is important to keep f_map.t passing.  */
13214         op_free(o);
13215         return newUNOP(type, 0, newDEFSVOP());
13216     }
13217
13218     if (oa) {
13219         while (oa & OA_OPTIONAL)
13220             oa >>= 4;
13221         if (oa && oa != OA_LIST)
13222             return too_few_arguments_pv(o,OP_DESC(o), 0);
13223     }
13224     return o;
13225 }
13226
13227 OP *
13228 Perl_ck_glob(pTHX_ OP *o)
13229 {
13230     GV *gv;
13231
13232     PERL_ARGS_ASSERT_CK_GLOB;
13233
13234     o = ck_fun(o);
13235     if ((o->op_flags & OPf_KIDS) && !OpHAS_SIBLING(cLISTOPo->op_first))
13236         op_append_elem(OP_GLOB, o, newDEFSVOP()); /* glob() => glob($_) */
13237
13238     if (!(o->op_flags & OPf_SPECIAL) && (gv = gv_override("glob", 4)))
13239     {
13240         /* convert
13241          *     glob
13242          *       \ null - const(wildcard)
13243          * into
13244          *     null
13245          *       \ enter
13246          *            \ list
13247          *                 \ mark - glob - rv2cv
13248          *                             |        \ gv(CORE::GLOBAL::glob)
13249          *                             |
13250          *                              \ null - const(wildcard)
13251          */
13252         o->op_flags |= OPf_SPECIAL;
13253         o->op_targ = pad_alloc(OP_GLOB, SVs_PADTMP);
13254         o = S_new_entersubop(aTHX_ gv, o);
13255         o = newUNOP(OP_NULL, 0, o);
13256         o->op_targ = OP_GLOB; /* hint at what it used to be: eg in newWHILEOP */
13257         return o;
13258     }
13259     else o->op_flags &= ~OPf_SPECIAL;
13260 #if !defined(PERL_EXTERNAL_GLOB)
13261     if (!PL_globhook) {
13262         ENTER;
13263         Perl_load_module(aTHX_ PERL_LOADMOD_NOIMPORT,
13264                                newSVpvs("File::Glob"), NULL, NULL, NULL);
13265         LEAVE;
13266     }
13267 #endif /* !PERL_EXTERNAL_GLOB */
13268     gv = (GV *)newSV(0);
13269     gv_init(gv, 0, "", 0, 0);
13270     gv_IOadd(gv);
13271     op_append_elem(OP_GLOB, o, newGVOP(OP_GV, 0, gv));
13272     SvREFCNT_dec_NN(gv); /* newGVOP increased it */
13273     scalarkids(o);
13274     return o;
13275 }
13276
13277 OP *
13278 Perl_ck_grep(pTHX_ OP *o)
13279 {
13280     LOGOP *gwop;
13281     OP *kid;
13282     const OPCODE type = o->op_type == OP_GREPSTART ? OP_GREPWHILE : OP_MAPWHILE;
13283
13284     PERL_ARGS_ASSERT_CK_GREP;
13285
13286     /* don't allocate gwop here, as we may leak it if PL_parser->error_count > 0 */
13287
13288     if (o->op_flags & OPf_STACKED) {
13289         kid = cUNOPx(OpSIBLING(cLISTOPo->op_first))->op_first;
13290         if (kid->op_type != OP_SCOPE && kid->op_type != OP_LEAVE)
13291             return no_fh_allowed(o);
13292         o->op_flags &= ~OPf_STACKED;
13293     }
13294     kid = OpSIBLING(cLISTOPo->op_first);
13295     if (type == OP_MAPWHILE)
13296         list(kid);
13297     else
13298         scalar(kid);
13299     o = ck_fun(o);
13300     if (PL_parser && PL_parser->error_count)
13301         return o;
13302     kid = OpSIBLING(cLISTOPo->op_first);
13303     if (kid->op_type != OP_NULL)
13304         Perl_croak(aTHX_ "panic: ck_grep, type=%u", (unsigned) kid->op_type);
13305     kid = kUNOP->op_first;
13306
13307     gwop = alloc_LOGOP(type, o, LINKLIST(kid));
13308     kid->op_next = (OP*)gwop;
13309     o->op_private = gwop->op_private = 0;
13310     gwop->op_targ = pad_alloc(type, SVs_PADTMP);
13311
13312     kid = OpSIBLING(cLISTOPo->op_first);
13313     for (kid = OpSIBLING(kid); kid; kid = OpSIBLING(kid))
13314         op_lvalue(kid, OP_GREPSTART);
13315
13316     return (OP*)gwop;
13317 }
13318
13319 OP *
13320 Perl_ck_index(pTHX_ OP *o)
13321 {
13322     PERL_ARGS_ASSERT_CK_INDEX;
13323
13324     if (o->op_flags & OPf_KIDS) {
13325         OP *kid = OpSIBLING(cLISTOPo->op_first);        /* get past pushmark */
13326         if (kid)
13327             kid = OpSIBLING(kid);                       /* get past "big" */
13328         if (kid && kid->op_type == OP_CONST) {
13329             const bool save_taint = TAINT_get;
13330             SV *sv = kSVOP->op_sv;
13331             if (   (!SvPOK(sv) || SvNIOKp(sv) || isREGEXP(sv))
13332                 && SvOK(sv) && !SvROK(sv))
13333             {
13334                 sv = newSV(0);
13335                 sv_copypv(sv, kSVOP->op_sv);
13336                 SvREFCNT_dec_NN(kSVOP->op_sv);
13337                 kSVOP->op_sv = sv;
13338             }
13339             if (SvOK(sv)) fbm_compile(sv, 0);
13340             TAINT_set(save_taint);
13341 #ifdef NO_TAINT_SUPPORT
13342             PERL_UNUSED_VAR(save_taint);
13343 #endif
13344         }
13345     }
13346     return ck_fun(o);
13347 }
13348
13349 OP *
13350 Perl_ck_lfun(pTHX_ OP *o)
13351 {
13352     const OPCODE type = o->op_type;
13353
13354     PERL_ARGS_ASSERT_CK_LFUN;
13355
13356     return modkids(ck_fun(o), type);
13357 }
13358
13359 OP *
13360 Perl_ck_defined(pTHX_ OP *o)            /* 19990527 MJD */
13361 {
13362     PERL_ARGS_ASSERT_CK_DEFINED;
13363
13364     if ((o->op_flags & OPf_KIDS)) {
13365         switch (cUNOPo->op_first->op_type) {
13366         case OP_RV2AV:
13367         case OP_PADAV:
13368             Perl_croak(aTHX_ "Can't use 'defined(@array)'"
13369                              " (Maybe you should just omit the defined()?)");
13370             NOT_REACHED; /* NOTREACHED */
13371             break;
13372         case OP_RV2HV:
13373         case OP_PADHV:
13374             Perl_croak(aTHX_ "Can't use 'defined(%%hash)'"
13375                              " (Maybe you should just omit the defined()?)");
13376             NOT_REACHED; /* NOTREACHED */
13377             break;
13378         default:
13379             /* no warning */
13380             break;
13381         }
13382     }
13383     return ck_rfun(o);
13384 }
13385
13386 OP *
13387 Perl_ck_readline(pTHX_ OP *o)
13388 {
13389     PERL_ARGS_ASSERT_CK_READLINE;
13390
13391     if (o->op_flags & OPf_KIDS) {
13392          OP *kid = cLISTOPo->op_first;
13393          if (kid->op_type == OP_RV2GV) kid->op_private |= OPpALLOW_FAKE;
13394          scalar(kid);
13395     }
13396     else {
13397         OP * const newop
13398             = newUNOP(OP_READLINE, 0, newGVOP(OP_GV, 0, PL_argvgv));
13399         op_free(o);
13400         return newop;
13401     }
13402     return o;
13403 }
13404
13405 OP *
13406 Perl_ck_rfun(pTHX_ OP *o)
13407 {
13408     const OPCODE type = o->op_type;
13409
13410     PERL_ARGS_ASSERT_CK_RFUN;
13411
13412     return refkids(ck_fun(o), type);
13413 }
13414
13415 OP *
13416 Perl_ck_listiob(pTHX_ OP *o)
13417 {
13418     OP *kid;
13419
13420     PERL_ARGS_ASSERT_CK_LISTIOB;
13421
13422     kid = cLISTOPo->op_first;
13423     if (!kid) {
13424         o = force_list(o, 1);
13425         kid = cLISTOPo->op_first;
13426     }
13427     if (kid->op_type == OP_PUSHMARK)
13428         kid = OpSIBLING(kid);
13429     if (kid && o->op_flags & OPf_STACKED)
13430         kid = OpSIBLING(kid);
13431     else if (kid && !OpHAS_SIBLING(kid)) {              /* print HANDLE; */
13432         if (kid->op_type == OP_CONST && kid->op_private & OPpCONST_BARE
13433          && !kid->op_folded) {
13434             o->op_flags |= OPf_STACKED; /* make it a filehandle */
13435             scalar(kid);
13436             /* replace old const op with new OP_RV2GV parent */
13437             kid = S_op_sibling_newUNOP(aTHX_ o, cLISTOPo->op_first,
13438                                         OP_RV2GV, OPf_REF);
13439             kid = OpSIBLING(kid);
13440         }
13441     }
13442
13443     if (!kid)
13444         op_append_elem(o->op_type, o, newDEFSVOP());
13445
13446     if (o->op_type == OP_PRTF) return modkids(listkids(o), OP_PRTF);
13447     return listkids(o);
13448 }
13449
13450 OP *
13451 Perl_ck_smartmatch(pTHX_ OP *o)
13452 {
13453     PERL_ARGS_ASSERT_CK_SMARTMATCH;
13454     if (0 == (o->op_flags & OPf_SPECIAL)) {
13455         OP *first  = cBINOPo->op_first;
13456         OP *second = OpSIBLING(first);
13457
13458         /* Implicitly take a reference to an array or hash */
13459
13460         /* remove the original two siblings, then add back the
13461          * (possibly different) first and second sibs.
13462          */
13463         op_sibling_splice(o, NULL, 1, NULL);
13464         op_sibling_splice(o, NULL, 1, NULL);
13465         first  = ref_array_or_hash(first);
13466         second = ref_array_or_hash(second);
13467         op_sibling_splice(o, NULL, 0, second);
13468         op_sibling_splice(o, NULL, 0, first);
13469
13470         /* Implicitly take a reference to a regular expression */
13471         if (first->op_type == OP_MATCH && !(first->op_flags & OPf_STACKED)) {
13472             OpTYPE_set(first, OP_QR);
13473         }
13474         if (second->op_type == OP_MATCH && !(second->op_flags & OPf_STACKED)) {
13475             OpTYPE_set(second, OP_QR);
13476         }
13477     }
13478
13479     return o;
13480 }
13481
13482
13483 static OP *
13484 S_maybe_targlex(pTHX_ OP *o)
13485 {
13486     OP * const kid = cLISTOPo->op_first;
13487     /* has a disposable target? */
13488     if ((PL_opargs[kid->op_type] & OA_TARGLEX)
13489         && !(kid->op_flags & OPf_STACKED)
13490         /* Cannot steal the second time! */
13491         && !(kid->op_private & OPpTARGET_MY)
13492         )
13493     {
13494         OP * const kkid = OpSIBLING(kid);
13495
13496         /* Can just relocate the target. */
13497         if (kkid && kkid->op_type == OP_PADSV
13498             && (!(kkid->op_private & OPpLVAL_INTRO)
13499                || kkid->op_private & OPpPAD_STATE))
13500         {
13501             kid->op_targ = kkid->op_targ;
13502             kkid->op_targ = 0;
13503             /* Now we do not need PADSV and SASSIGN.
13504              * Detach kid and free the rest. */
13505             op_sibling_splice(o, NULL, 1, NULL);
13506             op_free(o);
13507             kid->op_private |= OPpTARGET_MY;    /* Used for context settings */
13508             return kid;
13509         }
13510     }
13511     return o;
13512 }
13513
13514 OP *
13515 Perl_ck_sassign(pTHX_ OP *o)
13516 {
13517     OP * const kid = cBINOPo->op_first;
13518
13519     PERL_ARGS_ASSERT_CK_SASSIGN;
13520
13521     if (OpHAS_SIBLING(kid)) {
13522         OP *kkid = OpSIBLING(kid);
13523         /* For state variable assignment with attributes, kkid is a list op
13524            whose op_last is a padsv. */
13525         if ((kkid->op_type == OP_PADSV ||
13526              (OP_TYPE_IS_OR_WAS(kkid, OP_LIST) &&
13527               (kkid = cLISTOPx(kkid)->op_last)->op_type == OP_PADSV
13528              )
13529             )
13530                 && (kkid->op_private & (OPpLVAL_INTRO|OPpPAD_STATE))
13531                     == (OPpLVAL_INTRO|OPpPAD_STATE)) {
13532             return S_newONCEOP(aTHX_ o, kkid);
13533         }
13534     }
13535     return S_maybe_targlex(aTHX_ o);
13536 }
13537
13538
13539 OP *
13540 Perl_ck_match(pTHX_ OP *o)
13541 {
13542     PERL_UNUSED_CONTEXT;
13543     PERL_ARGS_ASSERT_CK_MATCH;
13544
13545     return o;
13546 }
13547
13548 OP *
13549 Perl_ck_method(pTHX_ OP *o)
13550 {
13551     SV *sv, *methsv, *rclass;
13552     const char* method;
13553     char* compatptr;
13554     int utf8;
13555     STRLEN len, nsplit = 0, i;
13556     OP* new_op;
13557     OP * const kid = cUNOPo->op_first;
13558
13559     PERL_ARGS_ASSERT_CK_METHOD;
13560     if (kid->op_type != OP_CONST) return o;
13561
13562     sv = kSVOP->op_sv;
13563
13564     /* replace ' with :: */
13565     while ((compatptr = (char *) memchr(SvPVX(sv), '\'',
13566                                         SvEND(sv) - SvPVX(sv) )))
13567     {
13568         *compatptr = ':';
13569         sv_insert(sv, compatptr - SvPVX_const(sv), 0, ":", 1);
13570     }
13571
13572     method = SvPVX_const(sv);
13573     len = SvCUR(sv);
13574     utf8 = SvUTF8(sv) ? -1 : 1;
13575
13576     for (i = len - 1; i > 0; --i) if (method[i] == ':') {
13577         nsplit = i+1;
13578         break;
13579     }
13580
13581     methsv = newSVpvn_share(method+nsplit, utf8*(len - nsplit), 0);
13582
13583     if (!nsplit) { /* $proto->method() */
13584         op_free(o);
13585         return newMETHOP_named(OP_METHOD_NAMED, 0, methsv);
13586     }
13587
13588     if (memEQs(method, nsplit, "SUPER::")) { /* $proto->SUPER::method() */
13589         op_free(o);
13590         return newMETHOP_named(OP_METHOD_SUPER, 0, methsv);
13591     }
13592
13593     /* $proto->MyClass::method() and $proto->MyClass::SUPER::method() */
13594     if (nsplit >= 9 && strBEGINs(method+nsplit-9, "::SUPER::")) {
13595         rclass = newSVpvn_share(method, utf8*(nsplit-9), 0);
13596         new_op = newMETHOP_named(OP_METHOD_REDIR_SUPER, 0, methsv);
13597     } else {
13598         rclass = newSVpvn_share(method, utf8*(nsplit-2), 0);
13599         new_op = newMETHOP_named(OP_METHOD_REDIR, 0, methsv);
13600     }
13601 #ifdef USE_ITHREADS
13602     op_relocate_sv(&rclass, &cMETHOPx(new_op)->op_rclass_targ);
13603 #else
13604     cMETHOPx(new_op)->op_rclass_sv = rclass;
13605 #endif
13606     op_free(o);
13607     return new_op;
13608 }
13609
13610 OP *
13611 Perl_ck_null(pTHX_ OP *o)
13612 {
13613     PERL_ARGS_ASSERT_CK_NULL;
13614     PERL_UNUSED_CONTEXT;
13615     return o;
13616 }
13617
13618 OP *
13619 Perl_ck_open(pTHX_ OP *o)
13620 {
13621     PERL_ARGS_ASSERT_CK_OPEN;
13622
13623     S_io_hints(aTHX_ o);
13624     {
13625          /* In case of three-arg dup open remove strictness
13626           * from the last arg if it is a bareword. */
13627          OP * const first = cLISTOPx(o)->op_first; /* The pushmark. */
13628          OP * const last  = cLISTOPx(o)->op_last;  /* The bareword. */
13629          OP *oa;
13630          const char *mode;
13631
13632          if ((last->op_type == OP_CONST) &&             /* The bareword. */
13633              (last->op_private & OPpCONST_BARE) &&
13634              (last->op_private & OPpCONST_STRICT) &&
13635              (oa = OpSIBLING(first)) &&         /* The fh. */
13636              (oa = OpSIBLING(oa)) &&                    /* The mode. */
13637              (oa->op_type == OP_CONST) &&
13638              SvPOK(((SVOP*)oa)->op_sv) &&
13639              (mode = SvPVX_const(((SVOP*)oa)->op_sv)) &&
13640              mode[0] == '>' && mode[1] == '&' &&        /* A dup open. */
13641              (last == OpSIBLING(oa)))                   /* The bareword. */
13642               last->op_private &= ~OPpCONST_STRICT;
13643     }
13644     return ck_fun(o);
13645 }
13646
13647 OP *
13648 Perl_ck_prototype(pTHX_ OP *o)
13649 {
13650     PERL_ARGS_ASSERT_CK_PROTOTYPE;
13651     if (!(o->op_flags & OPf_KIDS)) {
13652         op_free(o);
13653         return newUNOP(OP_PROTOTYPE, 0, newDEFSVOP());
13654     }
13655     return o;
13656 }
13657
13658 OP *
13659 Perl_ck_refassign(pTHX_ OP *o)
13660 {
13661     OP * const right = cLISTOPo->op_first;
13662     OP * const left = OpSIBLING(right);
13663     OP *varop = cUNOPx(cUNOPx(left)->op_first)->op_first;
13664     bool stacked = 0;
13665
13666     PERL_ARGS_ASSERT_CK_REFASSIGN;
13667     assert (left);
13668     assert (left->op_type == OP_SREFGEN);
13669
13670     o->op_private = 0;
13671     /* we use OPpPAD_STATE in refassign to mean either of those things,
13672      * and the code assumes the two flags occupy the same bit position
13673      * in the various ops below */
13674     assert(OPpPAD_STATE == OPpOUR_INTRO);
13675
13676     switch (varop->op_type) {
13677     case OP_PADAV:
13678         o->op_private |= OPpLVREF_AV;
13679         goto settarg;
13680     case OP_PADHV:
13681         o->op_private |= OPpLVREF_HV;
13682         /* FALLTHROUGH */
13683     case OP_PADSV:
13684       settarg:
13685         o->op_private |= (varop->op_private & (OPpLVAL_INTRO|OPpPAD_STATE));
13686         o->op_targ = varop->op_targ;
13687         varop->op_targ = 0;
13688         PAD_COMPNAME_GEN_set(o->op_targ, PERL_INT_MAX);
13689         break;
13690
13691     case OP_RV2AV:
13692         o->op_private |= OPpLVREF_AV;
13693         goto checkgv;
13694         NOT_REACHED; /* NOTREACHED */
13695     case OP_RV2HV:
13696         o->op_private |= OPpLVREF_HV;
13697         /* FALLTHROUGH */
13698     case OP_RV2SV:
13699       checkgv:
13700         o->op_private |= (varop->op_private & (OPpLVAL_INTRO|OPpOUR_INTRO));
13701         if (cUNOPx(varop)->op_first->op_type != OP_GV) goto bad;
13702       detach_and_stack:
13703         /* Point varop to its GV kid, detached.  */
13704         varop = op_sibling_splice(varop, NULL, -1, NULL);
13705         stacked = TRUE;
13706         break;
13707     case OP_RV2CV: {
13708         OP * const kidparent =
13709             OpSIBLING(cUNOPx(cUNOPx(varop)->op_first)->op_first);
13710         OP * const kid = cUNOPx(kidparent)->op_first;
13711         o->op_private |= OPpLVREF_CV;
13712         if (kid->op_type == OP_GV) {
13713             SV *sv = (SV*)cGVOPx_gv(kid);
13714             varop = kidparent;
13715             if (SvROK(sv) && SvTYPE(SvRV(sv)) == SVt_PVCV) {
13716                 /* a CVREF here confuses pp_refassign, so make sure
13717                    it gets a GV */
13718                 CV *const cv = (CV*)SvRV(sv);
13719                 SV *name_sv = sv_2mortal(newSVhek(CvNAME_HEK(cv)));
13720                 (void)gv_init_sv((GV*)sv, CvSTASH(cv), name_sv, 0);
13721                 assert(SvTYPE(sv) == SVt_PVGV);
13722             }
13723             goto detach_and_stack;
13724         }
13725         if (kid->op_type != OP_PADCV)   goto bad;
13726         o->op_targ = kid->op_targ;
13727         kid->op_targ = 0;
13728         break;
13729     }
13730     case OP_AELEM:
13731     case OP_HELEM:
13732         o->op_private |= (varop->op_private & OPpLVAL_INTRO);
13733         o->op_private |= OPpLVREF_ELEM;
13734         op_null(varop);
13735         stacked = TRUE;
13736         /* Detach varop.  */
13737         op_sibling_splice(cUNOPx(left)->op_first, NULL, -1, NULL);
13738         break;
13739     default:
13740       bad:
13741         /* diag_listed_as: Can't modify reference to %s in %s assignment */
13742         yyerror(Perl_form(aTHX_ "Can't modify reference to %s in scalar "
13743                                 "assignment",
13744                                  OP_DESC(varop)));
13745         return o;
13746     }
13747     if (!FEATURE_REFALIASING_IS_ENABLED)
13748         Perl_croak(aTHX_
13749                   "Experimental aliasing via reference not enabled");
13750     Perl_ck_warner_d(aTHX_
13751                      packWARN(WARN_EXPERIMENTAL__REFALIASING),
13752                     "Aliasing via reference is experimental");
13753     if (stacked) {
13754         o->op_flags |= OPf_STACKED;
13755         op_sibling_splice(o, right, 1, varop);
13756     }
13757     else {
13758         o->op_flags &=~ OPf_STACKED;
13759         op_sibling_splice(o, right, 1, NULL);
13760     }
13761     op_free(left);
13762     return o;
13763 }
13764
13765 OP *
13766 Perl_ck_repeat(pTHX_ OP *o)
13767 {
13768     PERL_ARGS_ASSERT_CK_REPEAT;
13769
13770     if (cBINOPo->op_first->op_flags & OPf_PARENS) {
13771         OP* kids;
13772         o->op_private |= OPpREPEAT_DOLIST;
13773         kids = op_sibling_splice(o, NULL, 1, NULL); /* detach first kid */
13774         kids = force_list(kids, 1); /* promote it to a list */
13775         op_sibling_splice(o, NULL, 0, kids); /* and add back */
13776     }
13777     else
13778         scalar(o);
13779     return o;
13780 }
13781
13782 OP *
13783 Perl_ck_require(pTHX_ OP *o)
13784 {
13785     GV* gv;
13786
13787     PERL_ARGS_ASSERT_CK_REQUIRE;
13788
13789     if (o->op_flags & OPf_KIDS) {       /* Shall we supply missing .pm? */
13790         SVOP * const kid = (SVOP*)cUNOPo->op_first;
13791         U32 hash;
13792         char *s;
13793         STRLEN len;
13794         if (kid->op_type == OP_CONST) {
13795           SV * const sv = kid->op_sv;
13796           U32 const was_readonly = SvREADONLY(sv);
13797           if (kid->op_private & OPpCONST_BARE) {
13798             const char *end;
13799             HEK *hek;
13800
13801             if (was_readonly) {
13802                 SvREADONLY_off(sv);
13803             }
13804
13805             if (SvIsCOW(sv)) sv_force_normal_flags(sv, 0);
13806
13807             s = SvPVX(sv);
13808             len = SvCUR(sv);
13809             end = s + len;
13810             /* treat ::foo::bar as foo::bar */
13811             if (len >= 2 && s[0] == ':' && s[1] == ':')
13812                 DIE(aTHX_ "Bareword in require must not start with a double-colon: \"%s\"\n", s);
13813             if (s == end)
13814                 DIE(aTHX_ "Bareword in require maps to empty filename");
13815
13816             for (; s < end; s++) {
13817                 if (*s == ':' && s[1] == ':') {
13818                     *s = '/';
13819                     Move(s+2, s+1, end - s - 1, char);
13820                     --end;
13821                 }
13822             }
13823             SvEND_set(sv, end);
13824             sv_catpvs(sv, ".pm");
13825             PERL_HASH(hash, SvPVX(sv), SvCUR(sv));
13826             hek = share_hek(SvPVX(sv),
13827                             (SSize_t)SvCUR(sv) * (SvUTF8(sv) ? -1 : 1),
13828                             hash);
13829             sv_sethek(sv, hek);
13830             unshare_hek(hek);
13831             SvFLAGS(sv) |= was_readonly;
13832           }
13833           else if (SvPOK(sv) && !SvNIOK(sv) && !SvGMAGICAL(sv)
13834                 && !SvVOK(sv)) {
13835             s = SvPV(sv, len);
13836             if (SvREFCNT(sv) > 1) {
13837                 kid->op_sv = newSVpvn_share(
13838                     s, SvUTF8(sv) ? -(SSize_t)len : (SSize_t)len, 0);
13839                 SvREFCNT_dec_NN(sv);
13840             }
13841             else {
13842                 HEK *hek;
13843                 if (was_readonly) SvREADONLY_off(sv);
13844                 PERL_HASH(hash, s, len);
13845                 hek = share_hek(s,
13846                                 SvUTF8(sv) ? -(SSize_t)len : (SSize_t)len,
13847                                 hash);
13848                 sv_sethek(sv, hek);
13849                 unshare_hek(hek);
13850                 SvFLAGS(sv) |= was_readonly;
13851             }
13852           }
13853         }
13854     }
13855
13856     if (!(o->op_flags & OPf_SPECIAL) /* Wasn't written as CORE::require */
13857         /* handle override, if any */
13858      && (gv = gv_override("require", 7))) {
13859         OP *kid, *newop;
13860         if (o->op_flags & OPf_KIDS) {
13861             kid = cUNOPo->op_first;
13862             op_sibling_splice(o, NULL, -1, NULL);
13863         }
13864         else {
13865             kid = newDEFSVOP();
13866         }
13867         op_free(o);
13868         newop = S_new_entersubop(aTHX_ gv, kid);
13869         return newop;
13870     }
13871
13872     return ck_fun(o);
13873 }
13874
13875 OP *
13876 Perl_ck_return(pTHX_ OP *o)
13877 {
13878     OP *kid;
13879
13880     PERL_ARGS_ASSERT_CK_RETURN;
13881
13882     kid = OpSIBLING(cLISTOPo->op_first);
13883     if (PL_compcv && CvLVALUE(PL_compcv)) {
13884         for (; kid; kid = OpSIBLING(kid))
13885             op_lvalue(kid, OP_LEAVESUBLV);
13886     }
13887
13888     return o;
13889 }
13890
13891 OP *
13892 Perl_ck_select(pTHX_ OP *o)
13893 {
13894     OP* kid;
13895
13896     PERL_ARGS_ASSERT_CK_SELECT;
13897
13898     if (o->op_flags & OPf_KIDS) {
13899         kid = OpSIBLING(cLISTOPo->op_first);     /* get past pushmark */
13900         if (kid && OpHAS_SIBLING(kid)) {
13901             OpTYPE_set(o, OP_SSELECT);
13902             o = ck_fun(o);
13903             return fold_constants(op_integerize(op_std_init(o)));
13904         }
13905     }
13906     o = ck_fun(o);
13907     kid = OpSIBLING(cLISTOPo->op_first);    /* get past pushmark */
13908     if (kid && kid->op_type == OP_RV2GV)
13909         kid->op_private &= ~HINT_STRICT_REFS;
13910     return o;
13911 }
13912
13913 OP *
13914 Perl_ck_shift(pTHX_ OP *o)
13915 {
13916     const I32 type = o->op_type;
13917
13918     PERL_ARGS_ASSERT_CK_SHIFT;
13919
13920     if (!(o->op_flags & OPf_KIDS)) {
13921         OP *argop;
13922
13923         if (!CvUNIQUE(PL_compcv)) {
13924             o->op_flags |= OPf_SPECIAL;
13925             return o;
13926         }
13927
13928         argop = newUNOP(OP_RV2AV, 0, scalar(newGVOP(OP_GV, 0, PL_argvgv)));
13929         op_free(o);
13930         return newUNOP(type, 0, scalar(argop));
13931     }
13932     return scalar(ck_fun(o));
13933 }
13934
13935 OP *
13936 Perl_ck_sort(pTHX_ OP *o)
13937 {
13938     OP *firstkid;
13939     OP *kid;
13940     HV * const hinthv =
13941         PL_hints & HINT_LOCALIZE_HH ? GvHV(PL_hintgv) : NULL;
13942     U8 stacked;
13943
13944     PERL_ARGS_ASSERT_CK_SORT;
13945
13946     if (hinthv) {
13947             SV ** const svp = hv_fetchs(hinthv, "sort", FALSE);
13948             if (svp) {
13949                 const I32 sorthints = (I32)SvIV(*svp);
13950                 if ((sorthints & HINT_SORT_STABLE) != 0)
13951                     o->op_private |= OPpSORT_STABLE;
13952                 if ((sorthints & HINT_SORT_UNSTABLE) != 0)
13953                     o->op_private |= OPpSORT_UNSTABLE;
13954             }
13955     }
13956
13957     if (o->op_flags & OPf_STACKED)
13958         simplify_sort(o);
13959     firstkid = OpSIBLING(cLISTOPo->op_first);           /* get past pushmark */
13960
13961     if ((stacked = o->op_flags & OPf_STACKED)) {        /* may have been cleared */
13962         OP *kid = cUNOPx(firstkid)->op_first;           /* get past null */
13963
13964         /* if the first arg is a code block, process it and mark sort as
13965          * OPf_SPECIAL */
13966         if (kid->op_type == OP_SCOPE || kid->op_type == OP_LEAVE) {
13967             LINKLIST(kid);
13968             if (kid->op_type == OP_LEAVE)
13969                     op_null(kid);                       /* wipe out leave */
13970             /* Prevent execution from escaping out of the sort block. */
13971             kid->op_next = 0;
13972
13973             /* provide scalar context for comparison function/block */
13974             kid = scalar(firstkid);
13975             kid->op_next = kid;
13976             o->op_flags |= OPf_SPECIAL;
13977         }
13978         else if (kid->op_type == OP_CONST
13979               && kid->op_private & OPpCONST_BARE) {
13980             char tmpbuf[256];
13981             STRLEN len;
13982             PADOFFSET off;
13983             const char * const name = SvPV(kSVOP_sv, len);
13984             *tmpbuf = '&';
13985             assert (len < 256);
13986             Copy(name, tmpbuf+1, len, char);
13987             off = pad_findmy_pvn(tmpbuf, len+1, 0);
13988             if (off != NOT_IN_PAD) {
13989                 if (PAD_COMPNAME_FLAGS_isOUR(off)) {
13990                     SV * const fq =
13991                         newSVhek(HvNAME_HEK(PAD_COMPNAME_OURSTASH(off)));
13992                     sv_catpvs(fq, "::");
13993                     sv_catsv(fq, kSVOP_sv);
13994                     SvREFCNT_dec_NN(kSVOP_sv);
13995                     kSVOP->op_sv = fq;
13996                 }
13997                 else {
13998                     OP * const padop = newOP(OP_PADCV, 0);
13999                     padop->op_targ = off;
14000                     /* replace the const op with the pad op */
14001                     op_sibling_splice(firstkid, NULL, 1, padop);
14002                     op_free(kid);
14003                 }
14004             }
14005         }
14006
14007         firstkid = OpSIBLING(firstkid);
14008     }
14009
14010     for (kid = firstkid; kid; kid = OpSIBLING(kid)) {
14011         /* provide list context for arguments */
14012         list(kid);
14013         if (stacked)
14014             op_lvalue(kid, OP_GREPSTART);
14015     }
14016
14017     return o;
14018 }
14019
14020 /* for sort { X } ..., where X is one of
14021  *   $a <=> $b, $b <=> $a, $a cmp $b, $b cmp $a
14022  * elide the second child of the sort (the one containing X),
14023  * and set these flags as appropriate
14024         OPpSORT_NUMERIC;
14025         OPpSORT_INTEGER;
14026         OPpSORT_DESCEND;
14027  * Also, check and warn on lexical $a, $b.
14028  */
14029
14030 STATIC void
14031 S_simplify_sort(pTHX_ OP *o)
14032 {
14033     OP *kid = OpSIBLING(cLISTOPo->op_first);    /* get past pushmark */
14034     OP *k;
14035     int descending;
14036     GV *gv;
14037     const char *gvname;
14038     bool have_scopeop;
14039
14040     PERL_ARGS_ASSERT_SIMPLIFY_SORT;
14041
14042     kid = kUNOP->op_first;                              /* get past null */
14043     if (!(have_scopeop = kid->op_type == OP_SCOPE)
14044      && kid->op_type != OP_LEAVE)
14045         return;
14046     kid = kLISTOP->op_last;                             /* get past scope */
14047     switch(kid->op_type) {
14048         case OP_NCMP:
14049         case OP_I_NCMP:
14050         case OP_SCMP:
14051             if (!have_scopeop) goto padkids;
14052             break;
14053         default:
14054             return;
14055     }
14056     k = kid;                                            /* remember this node*/
14057     if (kBINOP->op_first->op_type != OP_RV2SV
14058      || kBINOP->op_last ->op_type != OP_RV2SV)
14059     {
14060         /*
14061            Warn about my($a) or my($b) in a sort block, *if* $a or $b is
14062            then used in a comparison.  This catches most, but not
14063            all cases.  For instance, it catches
14064                sort { my($a); $a <=> $b }
14065            but not
14066                sort { my($a); $a < $b ? -1 : $a == $b ? 0 : 1; }
14067            (although why you'd do that is anyone's guess).
14068         */
14069
14070        padkids:
14071         if (!ckWARN(WARN_SYNTAX)) return;
14072         kid = kBINOP->op_first;
14073         do {
14074             if (kid->op_type == OP_PADSV) {
14075                 PADNAME * const name = PAD_COMPNAME(kid->op_targ);
14076                 if (PadnameLEN(name) == 2 && *PadnamePV(name) == '$'
14077                  && (  PadnamePV(name)[1] == 'a'
14078                     || PadnamePV(name)[1] == 'b'  ))
14079                     /* diag_listed_as: "my %s" used in sort comparison */
14080                     Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
14081                                      "\"%s %s\" used in sort comparison",
14082                                       PadnameIsSTATE(name)
14083                                         ? "state"
14084                                         : "my",
14085                                       PadnamePV(name));
14086             }
14087         } while ((kid = OpSIBLING(kid)));
14088         return;
14089     }
14090     kid = kBINOP->op_first;                             /* get past cmp */
14091     if (kUNOP->op_first->op_type != OP_GV)
14092         return;
14093     kid = kUNOP->op_first;                              /* get past rv2sv */
14094     gv = kGVOP_gv;
14095     if (GvSTASH(gv) != PL_curstash)
14096         return;
14097     gvname = GvNAME(gv);
14098     if (*gvname == 'a' && gvname[1] == '\0')
14099         descending = 0;
14100     else if (*gvname == 'b' && gvname[1] == '\0')
14101         descending = 1;
14102     else
14103         return;
14104
14105     kid = k;                                            /* back to cmp */
14106     /* already checked above that it is rv2sv */
14107     kid = kBINOP->op_last;                              /* down to 2nd arg */
14108     if (kUNOP->op_first->op_type != OP_GV)
14109         return;
14110     kid = kUNOP->op_first;                              /* get past rv2sv */
14111     gv = kGVOP_gv;
14112     if (GvSTASH(gv) != PL_curstash)
14113         return;
14114     gvname = GvNAME(gv);
14115     if ( descending
14116          ? !(*gvname == 'a' && gvname[1] == '\0')
14117          : !(*gvname == 'b' && gvname[1] == '\0'))
14118         return;
14119     o->op_flags &= ~(OPf_STACKED | OPf_SPECIAL);
14120     if (descending)
14121         o->op_private |= OPpSORT_DESCEND;
14122     if (k->op_type == OP_NCMP)
14123         o->op_private |= OPpSORT_NUMERIC;
14124     if (k->op_type == OP_I_NCMP)
14125         o->op_private |= OPpSORT_NUMERIC | OPpSORT_INTEGER;
14126     kid = OpSIBLING(cLISTOPo->op_first);
14127     /* cut out and delete old block (second sibling) */
14128     op_sibling_splice(o, cLISTOPo->op_first, 1, NULL);
14129     op_free(kid);
14130 }
14131
14132 OP *
14133 Perl_ck_split(pTHX_ OP *o)
14134 {
14135     OP *kid;
14136     OP *sibs;
14137
14138     PERL_ARGS_ASSERT_CK_SPLIT;
14139
14140     assert(o->op_type == OP_LIST);
14141
14142     if (o->op_flags & OPf_STACKED)
14143         return no_fh_allowed(o);
14144
14145     kid = cLISTOPo->op_first;
14146     /* delete leading NULL node, then add a CONST if no other nodes */
14147     assert(kid->op_type == OP_NULL);
14148     op_sibling_splice(o, NULL, 1,
14149         OpHAS_SIBLING(kid) ? NULL : newSVOP(OP_CONST, 0, newSVpvs(" ")));
14150     op_free(kid);
14151     kid = cLISTOPo->op_first;
14152
14153     if (kid->op_type != OP_MATCH || kid->op_flags & OPf_STACKED) {
14154         /* remove match expression, and replace with new optree with
14155          * a match op at its head */
14156         op_sibling_splice(o, NULL, 1, NULL);
14157         /* pmruntime will handle split " " behavior with flag==2 */
14158         kid = pmruntime(newPMOP(OP_MATCH, 0), kid, NULL, 2, 0);
14159         op_sibling_splice(o, NULL, 0, kid);
14160     }
14161
14162     assert(kid->op_type == OP_MATCH || kid->op_type == OP_SPLIT);
14163
14164     if (((PMOP *)kid)->op_pmflags & PMf_GLOBAL) {
14165       Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP),
14166                      "Use of /g modifier is meaningless in split");
14167     }
14168
14169     /* eliminate the split op, and move the match op (plus any children)
14170      * into its place, then convert the match op into a split op. i.e.
14171      *
14172      *  SPLIT                    MATCH                 SPLIT(ex-MATCH)
14173      *    |                        |                     |
14174      *  MATCH - A - B - C   =>     R - A - B - C   =>    R - A - B - C
14175      *    |                        |                     |
14176      *    R                        X - Y                 X - Y
14177      *    |
14178      *    X - Y
14179      *
14180      * (R, if it exists, will be a regcomp op)
14181      */
14182
14183     op_sibling_splice(o, NULL, 1, NULL); /* detach match op from o */
14184     sibs = op_sibling_splice(o, NULL, -1, NULL); /* detach any other sibs */
14185     op_sibling_splice(kid, cLISTOPx(kid)->op_last, 0, sibs); /* and reattach */
14186     OpTYPE_set(kid, OP_SPLIT);
14187     kid->op_flags   = (o->op_flags | (kid->op_flags & OPf_KIDS));
14188     kid->op_private = o->op_private;
14189     op_free(o);
14190     o = kid;
14191     kid = sibs; /* kid is now the string arg of the split */
14192
14193     if (!kid) {
14194         kid = newDEFSVOP();
14195         op_append_elem(OP_SPLIT, o, kid);
14196     }
14197     scalar(kid);
14198
14199     kid = OpSIBLING(kid);
14200     if (!kid) {
14201         kid = newSVOP(OP_CONST, 0, newSViv(0));
14202         op_append_elem(OP_SPLIT, o, kid);
14203         o->op_private |= OPpSPLIT_IMPLIM;
14204     }
14205     scalar(kid);
14206
14207     if (OpHAS_SIBLING(kid))
14208         return too_many_arguments_pv(o,OP_DESC(o), 0);
14209
14210     return o;
14211 }
14212
14213 OP *
14214 Perl_ck_stringify(pTHX_ OP *o)
14215 {
14216     OP * const kid = OpSIBLING(cUNOPo->op_first);
14217     PERL_ARGS_ASSERT_CK_STRINGIFY;
14218     if ((   kid->op_type == OP_JOIN || kid->op_type == OP_QUOTEMETA
14219          || kid->op_type == OP_LC   || kid->op_type == OP_LCFIRST
14220          || kid->op_type == OP_UC   || kid->op_type == OP_UCFIRST)
14221         && !OpHAS_SIBLING(kid)) /* syntax errs can leave extra children */
14222     {
14223         op_sibling_splice(o, cUNOPo->op_first, -1, NULL);
14224         op_free(o);
14225         return kid;
14226     }
14227     return ck_fun(o);
14228 }
14229
14230 OP *
14231 Perl_ck_join(pTHX_ OP *o)
14232 {
14233     OP * const kid = OpSIBLING(cLISTOPo->op_first);
14234
14235     PERL_ARGS_ASSERT_CK_JOIN;
14236
14237     if (kid && kid->op_type == OP_MATCH) {
14238         if (ckWARN(WARN_SYNTAX)) {
14239             const REGEXP *re = PM_GETRE(kPMOP);
14240             const SV *msg = re
14241                     ? newSVpvn_flags( RX_PRECOMP_const(re), RX_PRELEN(re),
14242                                             SVs_TEMP | ( RX_UTF8(re) ? SVf_UTF8 : 0 ) )
14243                     : newSVpvs_flags( "STRING", SVs_TEMP );
14244             Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
14245                         "/%" SVf "/ should probably be written as \"%" SVf "\"",
14246                         SVfARG(msg), SVfARG(msg));
14247         }
14248     }
14249     if (kid
14250      && (kid->op_type == OP_CONST /* an innocent, unsuspicious separator */
14251         || (kid->op_type == OP_PADSV && !(kid->op_private & OPpLVAL_INTRO))
14252         || (  kid->op_type==OP_RV2SV && kUNOP->op_first->op_type == OP_GV
14253            && !(kid->op_private & (OPpLVAL_INTRO|OPpOUR_INTRO)))))
14254     {
14255         const OP * const bairn = OpSIBLING(kid); /* the list */
14256         if (bairn && !OpHAS_SIBLING(bairn) /* single-item list */
14257          && OP_GIMME(bairn,0) == G_SCALAR)
14258         {
14259             OP * const ret = op_convert_list(OP_STRINGIFY, OPf_FOLDED,
14260                                      op_sibling_splice(o, kid, 1, NULL));
14261             op_free(o);
14262             return ret;
14263         }
14264     }
14265
14266     return ck_fun(o);
14267 }
14268
14269 /*
14270 =for apidoc rv2cv_op_cv
14271
14272 Examines an op, which is expected to identify a subroutine at runtime,
14273 and attempts to determine at compile time which subroutine it identifies.
14274 This is normally used during Perl compilation to determine whether
14275 a prototype can be applied to a function call.  C<cvop> is the op
14276 being considered, normally an C<rv2cv> op.  A pointer to the identified
14277 subroutine is returned, if it could be determined statically, and a null
14278 pointer is returned if it was not possible to determine statically.
14279
14280 Currently, the subroutine can be identified statically if the RV that the
14281 C<rv2cv> is to operate on is provided by a suitable C<gv> or C<const> op.
14282 A C<gv> op is suitable if the GV's CV slot is populated.  A C<const> op is
14283 suitable if the constant value must be an RV pointing to a CV.  Details of
14284 this process may change in future versions of Perl.  If the C<rv2cv> op
14285 has the C<OPpENTERSUB_AMPER> flag set then no attempt is made to identify
14286 the subroutine statically: this flag is used to suppress compile-time
14287 magic on a subroutine call, forcing it to use default runtime behaviour.
14288
14289 If C<flags> has the bit C<RV2CVOPCV_MARK_EARLY> set, then the handling
14290 of a GV reference is modified.  If a GV was examined and its CV slot was
14291 found to be empty, then the C<gv> op has the C<OPpEARLY_CV> flag set.
14292 If the op is not optimised away, and the CV slot is later populated with
14293 a subroutine having a prototype, that flag eventually triggers the warning
14294 "called too early to check prototype".
14295
14296 If C<flags> has the bit C<RV2CVOPCV_RETURN_NAME_GV> set, then instead
14297 of returning a pointer to the subroutine it returns a pointer to the
14298 GV giving the most appropriate name for the subroutine in this context.
14299 Normally this is just the C<CvGV> of the subroutine, but for an anonymous
14300 (C<CvANON>) subroutine that is referenced through a GV it will be the
14301 referencing GV.  The resulting C<GV*> is cast to C<CV*> to be returned.
14302 A null pointer is returned as usual if there is no statically-determinable
14303 subroutine.
14304
14305 =for apidoc Amnh||OPpEARLY_CV
14306 =for apidoc Amnh||OPpENTERSUB_AMPER
14307 =for apidoc Amnh||RV2CVOPCV_MARK_EARLY
14308 =for apidoc Amnh||RV2CVOPCV_RETURN_NAME_GV
14309
14310 =cut
14311 */
14312
14313 /* shared by toke.c:yylex */
14314 CV *
14315 Perl_find_lexical_cv(pTHX_ PADOFFSET off)
14316 {
14317     PADNAME *name = PAD_COMPNAME(off);
14318     CV *compcv = PL_compcv;
14319     while (PadnameOUTER(name)) {
14320         assert(PARENT_PAD_INDEX(name));
14321         compcv = CvOUTSIDE(compcv);
14322         name = PadlistNAMESARRAY(CvPADLIST(compcv))
14323                 [off = PARENT_PAD_INDEX(name)];
14324     }
14325     assert(!PadnameIsOUR(name));
14326     if (!PadnameIsSTATE(name) && PadnamePROTOCV(name)) {
14327         return PadnamePROTOCV(name);
14328     }
14329     return (CV *)AvARRAY(PadlistARRAY(CvPADLIST(compcv))[1])[off];
14330 }
14331
14332 CV *
14333 Perl_rv2cv_op_cv(pTHX_ OP *cvop, U32 flags)
14334 {
14335     OP *rvop;
14336     CV *cv;
14337     GV *gv;
14338     PERL_ARGS_ASSERT_RV2CV_OP_CV;
14339     if (flags & ~RV2CVOPCV_FLAG_MASK)
14340         Perl_croak(aTHX_ "panic: rv2cv_op_cv bad flags %x", (unsigned)flags);
14341     if (cvop->op_type != OP_RV2CV)
14342         return NULL;
14343     if (cvop->op_private & OPpENTERSUB_AMPER)
14344         return NULL;
14345     if (!(cvop->op_flags & OPf_KIDS))
14346         return NULL;
14347     rvop = cUNOPx(cvop)->op_first;
14348     switch (rvop->op_type) {
14349         case OP_GV: {
14350             gv = cGVOPx_gv(rvop);
14351             if (!isGV(gv)) {
14352                 if (SvROK(gv) && SvTYPE(SvRV(gv)) == SVt_PVCV) {
14353                     cv = MUTABLE_CV(SvRV(gv));
14354                     gv = NULL;
14355                     break;
14356                 }
14357                 if (flags & RV2CVOPCV_RETURN_STUB)
14358                     return (CV *)gv;
14359                 else return NULL;
14360             }
14361             cv = GvCVu(gv);
14362             if (!cv) {
14363                 if (flags & RV2CVOPCV_MARK_EARLY)
14364                     rvop->op_private |= OPpEARLY_CV;
14365                 return NULL;
14366             }
14367         } break;
14368         case OP_CONST: {
14369             SV *rv = cSVOPx_sv(rvop);
14370             if (!SvROK(rv))
14371                 return NULL;
14372             cv = (CV*)SvRV(rv);
14373             gv = NULL;
14374         } break;
14375         case OP_PADCV: {
14376             cv = find_lexical_cv(rvop->op_targ);
14377             gv = NULL;
14378         } break;
14379         default: {
14380             return NULL;
14381         } NOT_REACHED; /* NOTREACHED */
14382     }
14383     if (SvTYPE((SV*)cv) != SVt_PVCV)
14384         return NULL;
14385     if (flags & RV2CVOPCV_RETURN_NAME_GV) {
14386         if ((!CvANON(cv) && !CvLEXICAL(cv)) || !gv)
14387             gv = CvGV(cv);
14388         return (CV*)gv;
14389     }
14390     else if (flags & RV2CVOPCV_MAYBE_NAME_GV) {
14391         if (CvLEXICAL(cv) || CvNAMED(cv))
14392             return NULL;
14393         if (!CvANON(cv) || !gv)
14394             gv = CvGV(cv);
14395         return (CV*)gv;
14396
14397     } else {
14398         return cv;
14399     }
14400 }
14401
14402 /*
14403 =for apidoc ck_entersub_args_list
14404
14405 Performs the default fixup of the arguments part of an C<entersub>
14406 op tree.  This consists of applying list context to each of the
14407 argument ops.  This is the standard treatment used on a call marked
14408 with C<&>, or a method call, or a call through a subroutine reference,
14409 or any other call where the callee can't be identified at compile time,
14410 or a call where the callee has no prototype.
14411
14412 =cut
14413 */
14414
14415 OP *
14416 Perl_ck_entersub_args_list(pTHX_ OP *entersubop)
14417 {
14418     OP *aop;
14419
14420     PERL_ARGS_ASSERT_CK_ENTERSUB_ARGS_LIST;
14421
14422     aop = cUNOPx(entersubop)->op_first;
14423     if (!OpHAS_SIBLING(aop))
14424         aop = cUNOPx(aop)->op_first;
14425     for (aop = OpSIBLING(aop); OpHAS_SIBLING(aop); aop = OpSIBLING(aop)) {
14426         /* skip the extra attributes->import() call implicitly added in
14427          * something like foo(my $x : bar)
14428          */
14429         if (   aop->op_type == OP_ENTERSUB
14430             && (aop->op_flags & OPf_WANT) == OPf_WANT_VOID
14431         )
14432             continue;
14433         list(aop);
14434         op_lvalue(aop, OP_ENTERSUB);
14435     }
14436     return entersubop;
14437 }
14438
14439 /*
14440 =for apidoc ck_entersub_args_proto
14441
14442 Performs the fixup of the arguments part of an C<entersub> op tree
14443 based on a subroutine prototype.  This makes various modifications to
14444 the argument ops, from applying context up to inserting C<refgen> ops,
14445 and checking the number and syntactic types of arguments, as directed by
14446 the prototype.  This is the standard treatment used on a subroutine call,
14447 not marked with C<&>, where the callee can be identified at compile time
14448 and has a prototype.
14449
14450 C<protosv> supplies the subroutine prototype to be applied to the call.
14451 It may be a normal defined scalar, of which the string value will be used.
14452 Alternatively, for convenience, it may be a subroutine object (a C<CV*>
14453 that has been cast to C<SV*>) which has a prototype.  The prototype
14454 supplied, in whichever form, does not need to match the actual callee
14455 referenced by the op tree.
14456
14457 If the argument ops disagree with the prototype, for example by having
14458 an unacceptable number of arguments, a valid op tree is returned anyway.
14459 The error is reflected in the parser state, normally resulting in a single
14460 exception at the top level of parsing which covers all the compilation
14461 errors that occurred.  In the error message, the callee is referred to
14462 by the name defined by the C<namegv> parameter.
14463
14464 =cut
14465 */
14466
14467 OP *
14468 Perl_ck_entersub_args_proto(pTHX_ OP *entersubop, GV *namegv, SV *protosv)
14469 {
14470     STRLEN proto_len;
14471     const char *proto, *proto_end;
14472     OP *aop, *prev, *cvop, *parent;
14473     int optional = 0;
14474     I32 arg = 0;
14475     I32 contextclass = 0;
14476     const char *e = NULL;
14477     PERL_ARGS_ASSERT_CK_ENTERSUB_ARGS_PROTO;
14478     if (SvTYPE(protosv) == SVt_PVCV ? !SvPOK(protosv) : !SvOK(protosv))
14479         Perl_croak(aTHX_ "panic: ck_entersub_args_proto CV with no proto, "
14480                    "flags=%lx", (unsigned long) SvFLAGS(protosv));
14481     if (SvTYPE(protosv) == SVt_PVCV)
14482          proto = CvPROTO(protosv), proto_len = CvPROTOLEN(protosv);
14483     else proto = SvPV(protosv, proto_len);
14484     proto = S_strip_spaces(aTHX_ proto, &proto_len);
14485     proto_end = proto + proto_len;
14486     parent = entersubop;
14487     aop = cUNOPx(entersubop)->op_first;
14488     if (!OpHAS_SIBLING(aop)) {
14489         parent = aop;
14490         aop = cUNOPx(aop)->op_first;
14491     }
14492     prev = aop;
14493     aop = OpSIBLING(aop);
14494     for (cvop = aop; OpHAS_SIBLING(cvop); cvop = OpSIBLING(cvop)) ;
14495     while (aop != cvop) {
14496         OP* o3 = aop;
14497
14498         if (proto >= proto_end)
14499         {
14500             SV * const namesv = cv_name((CV *)namegv, NULL, 0);
14501             yyerror_pv(Perl_form(aTHX_ "Too many arguments for %" SVf,
14502                                         SVfARG(namesv)), SvUTF8(namesv));
14503             return entersubop;
14504         }
14505
14506         switch (*proto) {
14507             case ';':
14508                 optional = 1;
14509                 proto++;
14510                 continue;
14511             case '_':
14512                 /* _ must be at the end */
14513                 if (proto[1] && !memCHRs(";@%", proto[1]))
14514                     goto oops;
14515                 /* FALLTHROUGH */
14516             case '$':
14517                 proto++;
14518                 arg++;
14519                 scalar(aop);
14520                 break;
14521             case '%':
14522             case '@':
14523                 list(aop);
14524                 arg++;
14525                 break;
14526             case '&':
14527                 proto++;
14528                 arg++;
14529                 if (    o3->op_type != OP_UNDEF
14530                     && (o3->op_type != OP_SREFGEN
14531                         || (  cUNOPx(cUNOPx(o3)->op_first)->op_first->op_type
14532                                 != OP_ANONCODE
14533                             && cUNOPx(cUNOPx(o3)->op_first)->op_first->op_type
14534                                 != OP_RV2CV)))
14535                     bad_type_gv(arg, namegv, o3,
14536                             arg == 1 ? "block or sub {}" : "sub {}");
14537                 break;
14538             case '*':
14539                 /* '*' allows any scalar type, including bareword */
14540                 proto++;
14541                 arg++;
14542                 if (o3->op_type == OP_RV2GV)
14543                     goto wrapref;       /* autoconvert GLOB -> GLOBref */
14544                 else if (o3->op_type == OP_CONST)
14545                     o3->op_private &= ~OPpCONST_STRICT;
14546                 scalar(aop);
14547                 break;
14548             case '+':
14549                 proto++;
14550                 arg++;
14551                 if (o3->op_type == OP_RV2AV ||
14552                     o3->op_type == OP_PADAV ||
14553                     o3->op_type == OP_RV2HV ||
14554                     o3->op_type == OP_PADHV
14555                 ) {
14556                     goto wrapref;
14557                 }
14558                 scalar(aop);
14559                 break;
14560             case '[': case ']':
14561                 goto oops;
14562
14563             case '\\':
14564                 proto++;
14565                 arg++;
14566             again:
14567                 switch (*proto++) {
14568                     case '[':
14569                         if (contextclass++ == 0) {
14570                             e = (char *) memchr(proto, ']', proto_end - proto);
14571                             if (!e || e == proto)
14572                                 goto oops;
14573                         }
14574                         else
14575                             goto oops;
14576                         goto again;
14577
14578                     case ']':
14579                         if (contextclass) {
14580                             const char *p = proto;
14581                             const char *const end = proto;
14582                             contextclass = 0;
14583                             while (*--p != '[')
14584                                 /* \[$] accepts any scalar lvalue */
14585                                 if (*p == '$'
14586                                  && Perl_op_lvalue_flags(aTHX_
14587                                      scalar(o3),
14588                                      OP_READ, /* not entersub */
14589                                      OP_LVALUE_NO_CROAK
14590                                     )) goto wrapref;
14591                             bad_type_gv(arg, namegv, o3,
14592                                     Perl_form(aTHX_ "one of %.*s",(int)(end - p), p));
14593                         } else
14594                             goto oops;
14595                         break;
14596                     case '*':
14597                         if (o3->op_type == OP_RV2GV)
14598                             goto wrapref;
14599                         if (!contextclass)
14600                             bad_type_gv(arg, namegv, o3, "symbol");
14601                         break;
14602                     case '&':
14603                         if (o3->op_type == OP_ENTERSUB
14604                          && !(o3->op_flags & OPf_STACKED))
14605                             goto wrapref;
14606                         if (!contextclass)
14607                             bad_type_gv(arg, namegv, o3, "subroutine");
14608                         break;
14609                     case '$':
14610                         if (o3->op_type == OP_RV2SV ||
14611                                 o3->op_type == OP_PADSV ||
14612                                 o3->op_type == OP_HELEM ||
14613                                 o3->op_type == OP_AELEM)
14614                             goto wrapref;
14615                         if (!contextclass) {
14616                             /* \$ accepts any scalar lvalue */
14617                             if (Perl_op_lvalue_flags(aTHX_
14618                                     scalar(o3),
14619                                     OP_READ,  /* not entersub */
14620                                     OP_LVALUE_NO_CROAK
14621                                )) goto wrapref;
14622                             bad_type_gv(arg, namegv, o3, "scalar");
14623                         }
14624                         break;
14625                     case '@':
14626                         if (o3->op_type == OP_RV2AV ||
14627                                 o3->op_type == OP_PADAV)
14628                         {
14629                             o3->op_flags &=~ OPf_PARENS;
14630                             goto wrapref;
14631                         }
14632                         if (!contextclass)
14633                             bad_type_gv(arg, namegv, o3, "array");
14634                         break;
14635                     case '%':
14636                         if (o3->op_type == OP_RV2HV ||
14637                                 o3->op_type == OP_PADHV)
14638                         {
14639                             o3->op_flags &=~ OPf_PARENS;
14640                             goto wrapref;
14641                         }
14642                         if (!contextclass)
14643                             bad_type_gv(arg, namegv, o3, "hash");
14644                         break;
14645                     wrapref:
14646                             aop = S_op_sibling_newUNOP(aTHX_ parent, prev,
14647                                                 OP_REFGEN, 0);
14648                         if (contextclass && e) {
14649                             proto = e + 1;
14650                             contextclass = 0;
14651                         }
14652                         break;
14653                     default: goto oops;
14654                 }
14655                 if (contextclass)
14656                     goto again;
14657                 break;
14658             case ' ':
14659                 proto++;
14660                 continue;
14661             default:
14662             oops: {
14663                 Perl_croak(aTHX_ "Malformed prototype for %" SVf ": %" SVf,
14664                                   SVfARG(cv_name((CV *)namegv, NULL, 0)),
14665                                   SVfARG(protosv));
14666             }
14667         }
14668
14669         op_lvalue(aop, OP_ENTERSUB);
14670         prev = aop;
14671         aop = OpSIBLING(aop);
14672     }
14673     if (aop == cvop && *proto == '_') {
14674         /* generate an access to $_ */
14675         op_sibling_splice(parent, prev, 0, newDEFSVOP());
14676     }
14677     if (!optional && proto_end > proto &&
14678         (*proto != '@' && *proto != '%' && *proto != ';' && *proto != '_'))
14679     {
14680         SV * const namesv = cv_name((CV *)namegv, NULL, 0);
14681         yyerror_pv(Perl_form(aTHX_ "Not enough arguments for %" SVf,
14682                                     SVfARG(namesv)), SvUTF8(namesv));
14683     }
14684     return entersubop;
14685 }
14686
14687 /*
14688 =for apidoc ck_entersub_args_proto_or_list
14689
14690 Performs the fixup of the arguments part of an C<entersub> op tree either
14691 based on a subroutine prototype or using default list-context processing.
14692 This is the standard treatment used on a subroutine call, not marked
14693 with C<&>, where the callee can be identified at compile time.
14694
14695 C<protosv> supplies the subroutine prototype to be applied to the call,
14696 or indicates that there is no prototype.  It may be a normal scalar,
14697 in which case if it is defined then the string value will be used
14698 as a prototype, and if it is undefined then there is no prototype.
14699 Alternatively, for convenience, it may be a subroutine object (a C<CV*>
14700 that has been cast to C<SV*>), of which the prototype will be used if it
14701 has one.  The prototype (or lack thereof) supplied, in whichever form,
14702 does not need to match the actual callee referenced by the op tree.
14703
14704 If the argument ops disagree with the prototype, for example by having
14705 an unacceptable number of arguments, a valid op tree is returned anyway.
14706 The error is reflected in the parser state, normally resulting in a single
14707 exception at the top level of parsing which covers all the compilation
14708 errors that occurred.  In the error message, the callee is referred to
14709 by the name defined by the C<namegv> parameter.
14710
14711 =cut
14712 */
14713
14714 OP *
14715 Perl_ck_entersub_args_proto_or_list(pTHX_ OP *entersubop,
14716         GV *namegv, SV *protosv)
14717 {
14718     PERL_ARGS_ASSERT_CK_ENTERSUB_ARGS_PROTO_OR_LIST;
14719     if (SvTYPE(protosv) == SVt_PVCV ? SvPOK(protosv) : SvOK(protosv))
14720         return ck_entersub_args_proto(entersubop, namegv, protosv);
14721     else
14722         return ck_entersub_args_list(entersubop);
14723 }
14724
14725 OP *
14726 Perl_ck_entersub_args_core(pTHX_ OP *entersubop, GV *namegv, SV *protosv)
14727 {
14728     IV cvflags = SvIVX(protosv);
14729     int opnum = cvflags & 0xffff;
14730     OP *aop = cUNOPx(entersubop)->op_first;
14731
14732     PERL_ARGS_ASSERT_CK_ENTERSUB_ARGS_CORE;
14733
14734     if (!opnum) {
14735         OP *cvop;
14736         if (!OpHAS_SIBLING(aop))
14737             aop = cUNOPx(aop)->op_first;
14738         aop = OpSIBLING(aop);
14739         for (cvop = aop; OpSIBLING(cvop); cvop = OpSIBLING(cvop)) ;
14740         if (aop != cvop) {
14741             SV *namesv = cv_name((CV *)namegv, NULL, CV_NAME_NOTQUAL);
14742             yyerror_pv(Perl_form(aTHX_ "Too many arguments for %" SVf,
14743                 SVfARG(namesv)), SvUTF8(namesv));
14744         }
14745
14746         op_free(entersubop);
14747         switch(cvflags >> 16) {
14748         case 'F': return newSVOP(OP_CONST, 0,
14749                                         newSVpv(CopFILE(PL_curcop),0));
14750         case 'L': return newSVOP(
14751                            OP_CONST, 0,
14752                            Perl_newSVpvf(aTHX_
14753                              "%" IVdf, (IV)CopLINE(PL_curcop)
14754                            )
14755                          );
14756         case 'P': return newSVOP(OP_CONST, 0,
14757                                    (PL_curstash
14758                                      ? newSVhek(HvNAME_HEK(PL_curstash))
14759                                      : &PL_sv_undef
14760                                    )
14761                                 );
14762         }
14763         NOT_REACHED; /* NOTREACHED */
14764     }
14765     else {
14766         OP *prev, *cvop, *first, *parent;
14767         U32 flags = 0;
14768
14769         parent = entersubop;
14770         if (!OpHAS_SIBLING(aop)) {
14771             parent = aop;
14772             aop = cUNOPx(aop)->op_first;
14773         }
14774
14775         first = prev = aop;
14776         aop = OpSIBLING(aop);
14777         /* find last sibling */
14778         for (cvop = aop;
14779              OpHAS_SIBLING(cvop);
14780              prev = cvop, cvop = OpSIBLING(cvop))
14781             ;
14782         if (!(cvop->op_private & OPpENTERSUB_NOPAREN)
14783             /* Usually, OPf_SPECIAL on an op with no args means that it had
14784              * parens, but these have their own meaning for that flag: */
14785             && opnum != OP_VALUES && opnum != OP_KEYS && opnum != OP_EACH
14786             && opnum != OP_DELETE && opnum != OP_EXISTS)
14787                 flags |= OPf_SPECIAL;
14788         /* excise cvop from end of sibling chain */
14789         op_sibling_splice(parent, prev, 1, NULL);
14790         op_free(cvop);
14791         if (aop == cvop) aop = NULL;
14792
14793         /* detach remaining siblings from the first sibling, then
14794          * dispose of original optree */
14795
14796         if (aop)
14797             op_sibling_splice(parent, first, -1, NULL);
14798         op_free(entersubop);
14799
14800         if (cvflags == (OP_ENTEREVAL | (1<<16)))
14801             flags |= OPpEVAL_BYTES <<8;
14802
14803         switch (PL_opargs[opnum] & OA_CLASS_MASK) {
14804         case OA_UNOP:
14805         case OA_BASEOP_OR_UNOP:
14806         case OA_FILESTATOP:
14807             if (!aop)
14808                 return newOP(opnum,flags);       /* zero args */
14809             if (aop == prev)
14810                 return newUNOP(opnum,flags,aop); /* one arg */
14811             /* too many args */
14812             /* FALLTHROUGH */
14813         case OA_BASEOP:
14814             if (aop) {
14815                 SV *namesv;
14816                 OP *nextop;
14817
14818                 namesv = cv_name((CV *)namegv, NULL, CV_NAME_NOTQUAL);
14819                 yyerror_pv(Perl_form(aTHX_ "Too many arguments for %" SVf,
14820                     SVfARG(namesv)), SvUTF8(namesv));
14821                 while (aop) {
14822                     nextop = OpSIBLING(aop);
14823                     op_free(aop);
14824                     aop = nextop;
14825                 }
14826
14827             }
14828             return opnum == OP_RUNCV
14829                 ? newPVOP(OP_RUNCV,0,NULL)
14830                 : newOP(opnum,0);
14831         default:
14832             return op_convert_list(opnum,0,aop);
14833         }
14834     }
14835     NOT_REACHED; /* NOTREACHED */
14836     return entersubop;
14837 }
14838
14839 /*
14840 =for apidoc cv_get_call_checker_flags
14841
14842 Retrieves the function that will be used to fix up a call to C<cv>.
14843 Specifically, the function is applied to an C<entersub> op tree for a
14844 subroutine call, not marked with C<&>, where the callee can be identified
14845 at compile time as C<cv>.
14846
14847 The C-level function pointer is returned in C<*ckfun_p>, an SV argument
14848 for it is returned in C<*ckobj_p>, and control flags are returned in
14849 C<*ckflags_p>.  The function is intended to be called in this manner:
14850
14851  entersubop = (*ckfun_p)(aTHX_ entersubop, namegv, (*ckobj_p));
14852
14853 In this call, C<entersubop> is a pointer to the C<entersub> op,
14854 which may be replaced by the check function, and C<namegv> supplies
14855 the name that should be used by the check function to refer
14856 to the callee of the C<entersub> op if it needs to emit any diagnostics.
14857 It is permitted to apply the check function in non-standard situations,
14858 such as to a call to a different subroutine or to a method call.
14859
14860 C<namegv> may not actually be a GV.  If the C<CALL_CHECKER_REQUIRE_GV>
14861 bit is clear in C<*ckflags_p>, it is permitted to pass a CV or other SV
14862 instead, anything that can be used as the first argument to L</cv_name>.
14863 If the C<CALL_CHECKER_REQUIRE_GV> bit is set in C<*ckflags_p> then the
14864 check function requires C<namegv> to be a genuine GV.
14865
14866 By default, the check function is
14867 L<Perl_ck_entersub_args_proto_or_list|/ck_entersub_args_proto_or_list>,
14868 the SV parameter is C<cv> itself, and the C<CALL_CHECKER_REQUIRE_GV>
14869 flag is clear.  This implements standard prototype processing.  It can
14870 be changed, for a particular subroutine, by L</cv_set_call_checker_flags>.
14871
14872 If the C<CALL_CHECKER_REQUIRE_GV> bit is set in C<gflags> then it
14873 indicates that the caller only knows about the genuine GV version of
14874 C<namegv>, and accordingly the corresponding bit will always be set in
14875 C<*ckflags_p>, regardless of the check function's recorded requirements.
14876 If the C<CALL_CHECKER_REQUIRE_GV> bit is clear in C<gflags> then it
14877 indicates the caller knows about the possibility of passing something
14878 other than a GV as C<namegv>, and accordingly the corresponding bit may
14879 be either set or clear in C<*ckflags_p>, indicating the check function's
14880 recorded requirements.
14881
14882 C<gflags> is a bitset passed into C<cv_get_call_checker_flags>, in which
14883 only the C<CALL_CHECKER_REQUIRE_GV> bit currently has a defined meaning
14884 (for which see above).  All other bits should be clear.
14885
14886 =for apidoc Amnh||CALL_CHECKER_REQUIRE_GV
14887
14888 =for apidoc cv_get_call_checker
14889
14890 The original form of L</cv_get_call_checker_flags>, which does not return
14891 checker flags.  When using a checker function returned by this function,
14892 it is only safe to call it with a genuine GV as its C<namegv> argument.
14893
14894 =cut
14895 */
14896
14897 void
14898 Perl_cv_get_call_checker_flags(pTHX_ CV *cv, U32 gflags,
14899         Perl_call_checker *ckfun_p, SV **ckobj_p, U32 *ckflags_p)
14900 {
14901     MAGIC *callmg;
14902     PERL_ARGS_ASSERT_CV_GET_CALL_CHECKER_FLAGS;
14903     PERL_UNUSED_CONTEXT;
14904     callmg = SvMAGICAL((SV*)cv) ? mg_find((SV*)cv, PERL_MAGIC_checkcall) : NULL;
14905     if (callmg) {
14906         *ckfun_p = DPTR2FPTR(Perl_call_checker, callmg->mg_ptr);
14907         *ckobj_p = callmg->mg_obj;
14908         *ckflags_p = (callmg->mg_flags | gflags) & MGf_REQUIRE_GV;
14909     } else {
14910         *ckfun_p = Perl_ck_entersub_args_proto_or_list;
14911         *ckobj_p = (SV*)cv;
14912         *ckflags_p = gflags & MGf_REQUIRE_GV;
14913     }
14914 }
14915
14916 void
14917 Perl_cv_get_call_checker(pTHX_ CV *cv, Perl_call_checker *ckfun_p, SV **ckobj_p)
14918 {
14919     U32 ckflags;
14920     PERL_ARGS_ASSERT_CV_GET_CALL_CHECKER;
14921     PERL_UNUSED_CONTEXT;
14922     cv_get_call_checker_flags(cv, CALL_CHECKER_REQUIRE_GV, ckfun_p, ckobj_p,
14923         &ckflags);
14924 }
14925
14926 /*
14927 =for apidoc cv_set_call_checker_flags
14928
14929 Sets the function that will be used to fix up a call to C<cv>.
14930 Specifically, the function is applied to an C<entersub> op tree for a
14931 subroutine call, not marked with C<&>, where the callee can be identified
14932 at compile time as C<cv>.
14933
14934 The C-level function pointer is supplied in C<ckfun>, an SV argument for
14935 it is supplied in C<ckobj>, and control flags are supplied in C<ckflags>.
14936 The function should be defined like this:
14937
14938     STATIC OP * ckfun(pTHX_ OP *op, GV *namegv, SV *ckobj)
14939
14940 It is intended to be called in this manner:
14941
14942     entersubop = ckfun(aTHX_ entersubop, namegv, ckobj);
14943
14944 In this call, C<entersubop> is a pointer to the C<entersub> op,
14945 which may be replaced by the check function, and C<namegv> supplies
14946 the name that should be used by the check function to refer
14947 to the callee of the C<entersub> op if it needs to emit any diagnostics.
14948 It is permitted to apply the check function in non-standard situations,
14949 such as to a call to a different subroutine or to a method call.
14950
14951 C<namegv> may not actually be a GV.  For efficiency, perl may pass a
14952 CV or other SV instead.  Whatever is passed can be used as the first
14953 argument to L</cv_name>.  You can force perl to pass a GV by including
14954 C<CALL_CHECKER_REQUIRE_GV> in the C<ckflags>.
14955
14956 C<ckflags> is a bitset, in which only the C<CALL_CHECKER_REQUIRE_GV>
14957 bit currently has a defined meaning (for which see above).  All other
14958 bits should be clear.
14959
14960 The current setting for a particular CV can be retrieved by
14961 L</cv_get_call_checker_flags>.
14962
14963 =for apidoc cv_set_call_checker
14964
14965 The original form of L</cv_set_call_checker_flags>, which passes it the
14966 C<CALL_CHECKER_REQUIRE_GV> flag for backward-compatibility.  The effect
14967 of that flag setting is that the check function is guaranteed to get a
14968 genuine GV as its C<namegv> argument.
14969
14970 =cut
14971 */
14972
14973 void
14974 Perl_cv_set_call_checker(pTHX_ CV *cv, Perl_call_checker ckfun, SV *ckobj)
14975 {
14976     PERL_ARGS_ASSERT_CV_SET_CALL_CHECKER;
14977     cv_set_call_checker_flags(cv, ckfun, ckobj, CALL_CHECKER_REQUIRE_GV);
14978 }
14979
14980 void
14981 Perl_cv_set_call_checker_flags(pTHX_ CV *cv, Perl_call_checker ckfun,
14982                                      SV *ckobj, U32 ckflags)
14983 {
14984     PERL_ARGS_ASSERT_CV_SET_CALL_CHECKER_FLAGS;
14985     if (ckfun == Perl_ck_entersub_args_proto_or_list && ckobj == (SV*)cv) {
14986         if (SvMAGICAL((SV*)cv))
14987             mg_free_type((SV*)cv, PERL_MAGIC_checkcall);
14988     } else {
14989         MAGIC *callmg;
14990         sv_magic((SV*)cv, &PL_sv_undef, PERL_MAGIC_checkcall, NULL, 0);
14991         callmg = mg_find((SV*)cv, PERL_MAGIC_checkcall);
14992         assert(callmg);
14993         if (callmg->mg_flags & MGf_REFCOUNTED) {
14994             SvREFCNT_dec(callmg->mg_obj);
14995             callmg->mg_flags &= ~MGf_REFCOUNTED;
14996         }
14997         callmg->mg_ptr = FPTR2DPTR(char *, ckfun);
14998         callmg->mg_obj = ckobj;
14999         if (ckobj != (SV*)cv) {
15000             SvREFCNT_inc_simple_void_NN(ckobj);
15001             callmg->mg_flags |= MGf_REFCOUNTED;
15002         }
15003         callmg->mg_flags = (callmg->mg_flags &~ MGf_REQUIRE_GV)
15004                          | (U8)(ckflags & MGf_REQUIRE_GV) | MGf_COPY;
15005     }
15006 }
15007
15008 static void
15009 S_entersub_alloc_targ(pTHX_ OP * const o)
15010 {
15011     o->op_targ = pad_alloc(OP_ENTERSUB, SVs_PADTMP);
15012     o->op_private |= OPpENTERSUB_HASTARG;
15013 }
15014
15015 OP *
15016 Perl_ck_subr(pTHX_ OP *o)
15017 {
15018     OP *aop, *cvop;
15019     CV *cv;
15020     GV *namegv;
15021     SV **const_class = NULL;
15022
15023     PERL_ARGS_ASSERT_CK_SUBR;
15024
15025     aop = cUNOPx(o)->op_first;
15026     if (!OpHAS_SIBLING(aop))
15027         aop = cUNOPx(aop)->op_first;
15028     aop = OpSIBLING(aop);
15029     for (cvop = aop; OpHAS_SIBLING(cvop); cvop = OpSIBLING(cvop)) ;
15030     cv = rv2cv_op_cv(cvop, RV2CVOPCV_MARK_EARLY);
15031     namegv = cv ? (GV*)rv2cv_op_cv(cvop, RV2CVOPCV_MAYBE_NAME_GV) : NULL;
15032
15033     o->op_private &= ~1;
15034     o->op_private |= (PL_hints & HINT_STRICT_REFS);
15035     if (PERLDB_SUB && PL_curstash != PL_debstash)
15036         o->op_private |= OPpENTERSUB_DB;
15037     switch (cvop->op_type) {
15038         case OP_RV2CV:
15039             o->op_private |= (cvop->op_private & OPpENTERSUB_AMPER);
15040             op_null(cvop);
15041             break;
15042         case OP_METHOD:
15043         case OP_METHOD_NAMED:
15044         case OP_METHOD_SUPER:
15045         case OP_METHOD_REDIR:
15046         case OP_METHOD_REDIR_SUPER:
15047             o->op_flags |= OPf_REF;
15048             if (aop->op_type == OP_CONST) {
15049                 aop->op_private &= ~OPpCONST_STRICT;
15050                 const_class = &cSVOPx(aop)->op_sv;
15051             }
15052             else if (aop->op_type == OP_LIST) {
15053                 OP * const sib = OpSIBLING(((UNOP*)aop)->op_first);
15054                 if (sib && sib->op_type == OP_CONST) {
15055                     sib->op_private &= ~OPpCONST_STRICT;
15056                     const_class = &cSVOPx(sib)->op_sv;
15057                 }
15058             }
15059             /* make class name a shared cow string to speedup method calls */
15060             /* constant string might be replaced with object, f.e. bigint */
15061             if (const_class && SvPOK(*const_class)) {
15062                 STRLEN len;
15063                 const char* str = SvPV(*const_class, len);
15064                 if (len) {
15065                     SV* const shared = newSVpvn_share(
15066                         str, SvUTF8(*const_class)
15067                                     ? -(SSize_t)len : (SSize_t)len,
15068                         0
15069                     );
15070                     if (SvREADONLY(*const_class))
15071                         SvREADONLY_on(shared);
15072                     SvREFCNT_dec(*const_class);
15073                     *const_class = shared;
15074                 }
15075             }
15076             break;
15077     }
15078
15079     if (!cv) {
15080         S_entersub_alloc_targ(aTHX_ o);
15081         return ck_entersub_args_list(o);
15082     } else {
15083         Perl_call_checker ckfun;
15084         SV *ckobj;
15085         U32 ckflags;
15086         cv_get_call_checker_flags(cv, 0, &ckfun, &ckobj, &ckflags);
15087         if (CvISXSUB(cv) || !CvROOT(cv))
15088             S_entersub_alloc_targ(aTHX_ o);
15089         if (!namegv) {
15090             /* The original call checker API guarantees that a GV will
15091                be provided with the right name.  So, if the old API was
15092                used (or the REQUIRE_GV flag was passed), we have to reify
15093                the CV’s GV, unless this is an anonymous sub.  This is not
15094                ideal for lexical subs, as its stringification will include
15095                the package.  But it is the best we can do.  */
15096             if (ckflags & CALL_CHECKER_REQUIRE_GV) {
15097                 if (!CvANON(cv) && (!CvNAMED(cv) || CvNAME_HEK(cv)))
15098                     namegv = CvGV(cv);
15099             }
15100             else namegv = MUTABLE_GV(cv);
15101             /* After a syntax error in a lexical sub, the cv that
15102                rv2cv_op_cv returns may be a nameless stub. */
15103             if (!namegv) return ck_entersub_args_list(o);
15104
15105         }
15106         return ckfun(aTHX_ o, namegv, ckobj);
15107     }
15108 }
15109
15110 OP *
15111 Perl_ck_svconst(pTHX_ OP *o)
15112 {
15113     SV * const sv = cSVOPo->op_sv;
15114     PERL_ARGS_ASSERT_CK_SVCONST;
15115     PERL_UNUSED_CONTEXT;
15116 #ifdef PERL_COPY_ON_WRITE
15117     /* Since the read-only flag may be used to protect a string buffer, we
15118        cannot do copy-on-write with existing read-only scalars that are not
15119        already copy-on-write scalars.  To allow $_ = "hello" to do COW with
15120        that constant, mark the constant as COWable here, if it is not
15121        already read-only. */
15122     if (!SvREADONLY(sv) && !SvIsCOW(sv) && SvCANCOW(sv)) {
15123         SvIsCOW_on(sv);
15124         CowREFCNT(sv) = 0;
15125 # ifdef PERL_DEBUG_READONLY_COW
15126         sv_buf_to_ro(sv);
15127 # endif
15128     }
15129 #endif
15130     SvREADONLY_on(sv);
15131     return o;
15132 }
15133
15134 OP *
15135 Perl_ck_trunc(pTHX_ OP *o)
15136 {
15137     PERL_ARGS_ASSERT_CK_TRUNC;
15138
15139     if (o->op_flags & OPf_KIDS) {
15140         SVOP *kid = (SVOP*)cUNOPo->op_first;
15141
15142         if (kid->op_type == OP_NULL)
15143             kid = (SVOP*)OpSIBLING(kid);
15144         if (kid && kid->op_type == OP_CONST &&
15145             (kid->op_private & OPpCONST_BARE) &&
15146             !kid->op_folded)
15147         {
15148             o->op_flags |= OPf_SPECIAL;
15149             kid->op_private &= ~OPpCONST_STRICT;
15150         }
15151     }
15152     return ck_fun(o);
15153 }
15154
15155 OP *
15156 Perl_ck_substr(pTHX_ OP *o)
15157 {
15158     PERL_ARGS_ASSERT_CK_SUBSTR;
15159
15160     o = ck_fun(o);
15161     if ((o->op_flags & OPf_KIDS) && (o->op_private == 4)) {
15162         OP *kid = cLISTOPo->op_first;
15163
15164         if (kid->op_type == OP_NULL)
15165             kid = OpSIBLING(kid);
15166         if (kid)
15167             /* Historically, substr(delete $foo{bar},...) has been allowed
15168                with 4-arg substr.  Keep it working by applying entersub
15169                lvalue context.  */
15170             op_lvalue(kid, OP_ENTERSUB);
15171
15172     }
15173     return o;
15174 }
15175
15176 OP *
15177 Perl_ck_tell(pTHX_ OP *o)
15178 {
15179     PERL_ARGS_ASSERT_CK_TELL;
15180     o = ck_fun(o);
15181     if (o->op_flags & OPf_KIDS) {
15182      OP *kid = cLISTOPo->op_first;
15183      if (kid->op_type == OP_NULL && OpHAS_SIBLING(kid)) kid = OpSIBLING(kid);
15184      if (kid->op_type == OP_RV2GV) kid->op_private |= OPpALLOW_FAKE;
15185     }
15186     return o;
15187 }
15188
15189 OP *
15190 Perl_ck_each(pTHX_ OP *o)
15191 {
15192     OP *kid = o->op_flags & OPf_KIDS ? cUNOPo->op_first : NULL;
15193     const unsigned orig_type  = o->op_type;
15194
15195     PERL_ARGS_ASSERT_CK_EACH;
15196
15197     if (kid) {
15198         switch (kid->op_type) {
15199             case OP_PADHV:
15200             case OP_RV2HV:
15201                 break;
15202             case OP_PADAV:
15203             case OP_RV2AV:
15204                 OpTYPE_set(o, orig_type == OP_EACH ? OP_AEACH
15205                             : orig_type == OP_KEYS ? OP_AKEYS
15206                             :                        OP_AVALUES);
15207                 break;
15208             case OP_CONST:
15209                 if (kid->op_private == OPpCONST_BARE
15210                  || !SvROK(cSVOPx_sv(kid))
15211                  || (  SvTYPE(SvRV(cSVOPx_sv(kid))) != SVt_PVAV
15212                     && SvTYPE(SvRV(cSVOPx_sv(kid))) != SVt_PVHV  )
15213                    )
15214                     goto bad;
15215                 /* FALLTHROUGH */
15216             default:
15217                 qerror(Perl_mess(aTHX_
15218                     "Experimental %s on scalar is now forbidden",
15219                      PL_op_desc[orig_type]));
15220                bad:
15221                 bad_type_pv(1, "hash or array", o, kid);
15222                 return o;
15223         }
15224     }
15225     return ck_fun(o);
15226 }
15227
15228 OP *
15229 Perl_ck_length(pTHX_ OP *o)
15230 {
15231     PERL_ARGS_ASSERT_CK_LENGTH;
15232
15233     o = ck_fun(o);
15234
15235     if (ckWARN(WARN_SYNTAX)) {
15236         const OP *kid = o->op_flags & OPf_KIDS ? cLISTOPo->op_first : NULL;
15237
15238         if (kid) {
15239             SV *name = NULL;
15240             const bool hash = kid->op_type == OP_PADHV
15241                            || kid->op_type == OP_RV2HV;
15242             switch (kid->op_type) {
15243                 case OP_PADHV:
15244                 case OP_PADAV:
15245                 case OP_RV2HV:
15246                 case OP_RV2AV:
15247                     name = S_op_varname(aTHX_ kid);
15248                     break;
15249                 default:
15250                     return o;
15251             }
15252             if (name)
15253                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
15254                     "length() used on %" SVf " (did you mean \"scalar(%s%" SVf
15255                     ")\"?)",
15256                     SVfARG(name), hash ? "keys " : "", SVfARG(name)
15257                 );
15258             else if (hash)
15259      /* diag_listed_as: length() used on %s (did you mean "scalar(%s)"?) */
15260                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
15261                     "length() used on %%hash (did you mean \"scalar(keys %%hash)\"?)");
15262             else
15263      /* diag_listed_as: length() used on %s (did you mean "scalar(%s)"?) */
15264                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
15265                     "length() used on @array (did you mean \"scalar(@array)\"?)");
15266         }
15267     }
15268
15269     return o;
15270 }
15271
15272
15273 OP *
15274 Perl_ck_isa(pTHX_ OP *o)
15275 {
15276     OP *classop = cBINOPo->op_last;
15277
15278     PERL_ARGS_ASSERT_CK_ISA;
15279
15280     /* Convert barename into PV */
15281     if(classop->op_type == OP_CONST && classop->op_private & OPpCONST_BARE) {
15282         /* TODO: Optionally convert package to raw HV here */
15283         classop->op_private &= ~(OPpCONST_BARE|OPpCONST_STRICT);
15284     }
15285
15286     return o;
15287 }
15288
15289
15290 /*
15291    ---------------------------------------------------------
15292
15293    Common vars in list assignment
15294
15295    There now follows some enums and static functions for detecting
15296    common variables in list assignments. Here is a little essay I wrote
15297    for myself when trying to get my head around this. DAPM.
15298
15299    ----
15300
15301    First some random observations:
15302
15303    * If a lexical var is an alias of something else, e.g.
15304        for my $x ($lex, $pkg, $a[0]) {...}
15305      then the act of aliasing will increase the reference count of the SV
15306
15307    * If a package var is an alias of something else, it may still have a
15308      reference count of 1, depending on how the alias was created, e.g.
15309      in *a = *b, $a may have a refcount of 1 since the GP is shared
15310      with a single GvSV pointer to the SV. So If it's an alias of another
15311      package var, then RC may be 1; if it's an alias of another scalar, e.g.
15312      a lexical var or an array element, then it will have RC > 1.
15313
15314    * There are many ways to create a package alias; ultimately, XS code
15315      may quite legally do GvSV(gv) = SvREFCNT_inc(sv) for example, so
15316      run-time tracing mechanisms are unlikely to be able to catch all cases.
15317
15318    * When the LHS is all my declarations, the same vars can't appear directly
15319      on the RHS, but they can indirectly via closures, aliasing and lvalue
15320      subs. But those techniques all involve an increase in the lexical
15321      scalar's ref count.
15322
15323    * When the LHS is all lexical vars (but not necessarily my declarations),
15324      it is possible for the same lexicals to appear directly on the RHS, and
15325      without an increased ref count, since the stack isn't refcounted.
15326      This case can be detected at compile time by scanning for common lex
15327      vars with PL_generation.
15328
15329    * lvalue subs defeat common var detection, but they do at least
15330      return vars with a temporary ref count increment. Also, you can't
15331      tell at compile time whether a sub call is lvalue.
15332
15333
15334    So...
15335
15336    A: There are a few circumstances where there definitely can't be any
15337      commonality:
15338
15339        LHS empty:  () = (...);
15340        RHS empty:  (....) = ();
15341        RHS contains only constants or other 'can't possibly be shared'
15342            elements (e.g. ops that return PADTMPs):  (...) = (1,2, length)
15343            i.e. they only contain ops not marked as dangerous, whose children
15344            are also not dangerous;
15345        LHS ditto;
15346        LHS contains a single scalar element: e.g. ($x) = (....); because
15347            after $x has been modified, it won't be used again on the RHS;
15348        RHS contains a single element with no aggregate on LHS: e.g.
15349            ($a,$b,$c)  = ($x); again, once $a has been modified, its value
15350            won't be used again.
15351
15352    B: If LHS are all 'my' lexical var declarations (or safe ops, which
15353      we can ignore):
15354
15355        my ($a, $b, @c) = ...;
15356
15357        Due to closure and goto tricks, these vars may already have content.
15358        For the same reason, an element on the RHS may be a lexical or package
15359        alias of one of the vars on the left, or share common elements, for
15360        example:
15361
15362            my ($x,$y) = f(); # $x and $y on both sides
15363            sub f : lvalue { ($x,$y) = (1,2); $y, $x }
15364
15365        and
15366
15367            my $ra = f();
15368            my @a = @$ra;  # elements of @a on both sides
15369            sub f { @a = 1..4; \@a }
15370
15371
15372        First, just consider scalar vars on LHS:
15373
15374            RHS is safe only if (A), or in addition,
15375                * contains only lexical *scalar* vars, where neither side's
15376                  lexicals have been flagged as aliases
15377
15378            If RHS is not safe, then it's always legal to check LHS vars for
15379            RC==1, since the only RHS aliases will always be associated
15380            with an RC bump.
15381
15382            Note that in particular, RHS is not safe if:
15383
15384                * it contains package scalar vars; e.g.:
15385
15386                    f();
15387                    my ($x, $y) = (2, $x_alias);
15388                    sub f { $x = 1; *x_alias = \$x; }
15389
15390                * It contains other general elements, such as flattened or
15391                * spliced or single array or hash elements, e.g.
15392
15393                    f();
15394                    my ($x,$y) = @a; # or $a[0] or @a{@b} etc
15395
15396                    sub f {
15397                        ($x, $y) = (1,2);
15398                        use feature 'refaliasing';
15399                        \($a[0], $a[1]) = \($y,$x);
15400                    }
15401
15402                  It doesn't matter if the array/hash is lexical or package.
15403
15404                * it contains a function call that happens to be an lvalue
15405                  sub which returns one or more of the above, e.g.
15406
15407                    f();
15408                    my ($x,$y) = f();
15409
15410                    sub f : lvalue {
15411                        ($x, $y) = (1,2);
15412                        *x1 = \$x;
15413                        $y, $x1;
15414                    }
15415
15416                    (so a sub call on the RHS should be treated the same
15417                    as having a package var on the RHS).
15418
15419                * any other "dangerous" thing, such an op or built-in that
15420                  returns one of the above, e.g. pp_preinc
15421
15422
15423            If RHS is not safe, what we can do however is at compile time flag
15424            that the LHS are all my declarations, and at run time check whether
15425            all the LHS have RC == 1, and if so skip the full scan.
15426
15427        Now consider array and hash vars on LHS: e.g. my (...,@a) = ...;
15428
15429            Here the issue is whether there can be elements of @a on the RHS
15430            which will get prematurely freed when @a is cleared prior to
15431            assignment. This is only a problem if the aliasing mechanism
15432            is one which doesn't increase the refcount - only if RC == 1
15433            will the RHS element be prematurely freed.
15434
15435            Because the array/hash is being INTROed, it or its elements
15436            can't directly appear on the RHS:
15437
15438                my (@a) = ($a[0], @a, etc) # NOT POSSIBLE
15439
15440            but can indirectly, e.g.:
15441
15442                my $r = f();
15443                my (@a) = @$r;
15444                sub f { @a = 1..3; \@a }
15445
15446            So if the RHS isn't safe as defined by (A), we must always
15447            mortalise and bump the ref count of any remaining RHS elements
15448            when assigning to a non-empty LHS aggregate.
15449
15450            Lexical scalars on the RHS aren't safe if they've been involved in
15451            aliasing, e.g.
15452
15453                use feature 'refaliasing';
15454
15455                f();
15456                \(my $lex) = \$pkg;
15457                my @a = ($lex,3); # equivalent to ($a[0],3)
15458
15459                sub f {
15460                    @a = (1,2);
15461                    \$pkg = \$a[0];
15462                }
15463
15464            Similarly with lexical arrays and hashes on the RHS:
15465
15466                f();
15467                my @b;
15468                my @a = (@b);
15469
15470                sub f {
15471                    @a = (1,2);
15472                    \$b[0] = \$a[1];
15473                    \$b[1] = \$a[0];
15474                }
15475
15476
15477
15478    C: As (B), but in addition the LHS may contain non-intro lexicals, e.g.
15479        my $a; ($a, my $b) = (....);
15480
15481        The difference between (B) and (C) is that it is now physically
15482        possible for the LHS vars to appear on the RHS too, where they
15483        are not reference counted; but in this case, the compile-time
15484        PL_generation sweep will detect such common vars.
15485
15486        So the rules for (C) differ from (B) in that if common vars are
15487        detected, the runtime "test RC==1" optimisation can no longer be used,
15488        and a full mark and sweep is required
15489
15490    D: As (C), but in addition the LHS may contain package vars.
15491
15492        Since package vars can be aliased without a corresponding refcount
15493        increase, all bets are off. It's only safe if (A). E.g.
15494
15495            my ($x, $y) = (1,2);
15496
15497            for $x_alias ($x) {
15498                ($x_alias, $y) = (3, $x); # whoops
15499            }
15500
15501        Ditto for LHS aggregate package vars.
15502
15503    E: Any other dangerous ops on LHS, e.g.
15504            (f(), $a[0], @$r) = (...);
15505
15506        this is similar to (E) in that all bets are off. In addition, it's
15507        impossible to determine at compile time whether the LHS
15508        contains a scalar or an aggregate, e.g.
15509
15510            sub f : lvalue { @a }
15511            (f()) = 1..3;
15512
15513 * ---------------------------------------------------------
15514 */
15515
15516
15517 /* A set of bit flags returned by S_aassign_scan(). Each flag indicates
15518  * that at least one of the things flagged was seen.
15519  */
15520
15521 enum {
15522     AAS_MY_SCALAR       = 0x001, /* my $scalar */
15523     AAS_MY_AGG          = 0x002, /* aggregate: my @array or my %hash */
15524     AAS_LEX_SCALAR      = 0x004, /* $lexical */
15525     AAS_LEX_AGG         = 0x008, /* @lexical or %lexical aggregate */
15526     AAS_LEX_SCALAR_COMM = 0x010, /* $lexical seen on both sides */
15527     AAS_PKG_SCALAR      = 0x020, /* $scalar (where $scalar is pkg var) */
15528     AAS_PKG_AGG         = 0x040, /* package @array or %hash aggregate */
15529     AAS_DANGEROUS       = 0x080, /* an op (other than the above)
15530                                          that's flagged OA_DANGEROUS */
15531     AAS_SAFE_SCALAR     = 0x100, /* produces at least one scalar SV that's
15532                                         not in any of the categories above */
15533     AAS_DEFAV           = 0x200  /* contains just a single '@_' on RHS */
15534 };
15535
15536
15537
15538 /* helper function for S_aassign_scan().
15539  * check a PAD-related op for commonality and/or set its generation number.
15540  * Returns a boolean indicating whether its shared */
15541
15542 static bool
15543 S_aassign_padcheck(pTHX_ OP* o, bool rhs)
15544 {
15545     if (PAD_COMPNAME_GEN(o->op_targ) == PERL_INT_MAX)
15546         /* lexical used in aliasing */
15547         return TRUE;
15548
15549     if (rhs)
15550         return cBOOL(PAD_COMPNAME_GEN(o->op_targ) == (STRLEN)PL_generation);
15551     else
15552         PAD_COMPNAME_GEN_set(o->op_targ, PL_generation);
15553
15554     return FALSE;
15555 }
15556
15557
15558 /*
15559   Helper function for OPpASSIGN_COMMON* detection in rpeep().
15560   It scans the left or right hand subtree of the aassign op, and returns a
15561   set of flags indicating what sorts of things it found there.
15562   'rhs' indicates whether we're scanning the LHS or RHS. If the former, we
15563   set PL_generation on lexical vars; if the latter, we see if
15564   PL_generation matches.
15565   'scalars_p' is a pointer to a counter of the number of scalar SVs seen.
15566   This fn will increment it by the number seen. It's not intended to
15567   be an accurate count (especially as many ops can push a variable
15568   number of SVs onto the stack); rather it's used as to test whether there
15569   can be at most 1 SV pushed; so it's only meanings are "0, 1, many".
15570 */
15571
15572 static int
15573 S_aassign_scan(pTHX_ OP* o, bool rhs, int *scalars_p)
15574 {
15575     OP *top_op           = o;
15576     OP *effective_top_op = o;
15577     int all_flags = 0;
15578
15579     while (1) {
15580     bool top = o == effective_top_op;
15581     int flags = 0;
15582     OP* next_kid = NULL;
15583
15584     /* first, look for a solitary @_ on the RHS */
15585     if (   rhs
15586         && top
15587         && (o->op_flags & OPf_KIDS)
15588         && OP_TYPE_IS_OR_WAS(o, OP_LIST)
15589     ) {
15590         OP *kid = cUNOPo->op_first;
15591         if (   (   kid->op_type == OP_PUSHMARK
15592                 || kid->op_type == OP_PADRANGE) /* ex-pushmark */
15593             && ((kid = OpSIBLING(kid)))
15594             && !OpHAS_SIBLING(kid)
15595             && kid->op_type == OP_RV2AV
15596             && !(kid->op_flags & OPf_REF)
15597             && !(kid->op_private & (OPpLVAL_INTRO|OPpMAYBE_LVSUB))
15598             && ((kid->op_flags & OPf_WANT) == OPf_WANT_LIST)
15599             && ((kid = cUNOPx(kid)->op_first))
15600             && kid->op_type == OP_GV
15601             && cGVOPx_gv(kid) == PL_defgv
15602         )
15603             flags = AAS_DEFAV;
15604     }
15605
15606     switch (o->op_type) {
15607     case OP_GVSV:
15608         (*scalars_p)++;
15609         all_flags |= AAS_PKG_SCALAR;
15610         goto do_next;
15611
15612     case OP_PADAV:
15613     case OP_PADHV:
15614         (*scalars_p) += 2;
15615         /* if !top, could be e.g. @a[0,1] */
15616         all_flags |=  (top && (o->op_flags & OPf_REF))
15617                         ? ((o->op_private & OPpLVAL_INTRO)
15618                             ? AAS_MY_AGG : AAS_LEX_AGG)
15619                         : AAS_DANGEROUS;
15620         goto do_next;
15621
15622     case OP_PADSV:
15623         {
15624             int comm = S_aassign_padcheck(aTHX_ o, rhs)
15625                         ?  AAS_LEX_SCALAR_COMM : 0;
15626             (*scalars_p)++;
15627             all_flags |= (o->op_private & OPpLVAL_INTRO)
15628                 ? (AAS_MY_SCALAR|comm) : (AAS_LEX_SCALAR|comm);
15629             goto do_next;
15630
15631         }
15632
15633     case OP_RV2AV:
15634     case OP_RV2HV:
15635         (*scalars_p) += 2;
15636         if (cUNOPx(o)->op_first->op_type != OP_GV)
15637             all_flags |= AAS_DANGEROUS; /* @{expr}, %{expr} */
15638         /* @pkg, %pkg */
15639         /* if !top, could be e.g. @a[0,1] */
15640         else if (top && (o->op_flags & OPf_REF))
15641             all_flags |= AAS_PKG_AGG;
15642         else
15643             all_flags |= AAS_DANGEROUS;
15644         goto do_next;
15645
15646     case OP_RV2SV:
15647         (*scalars_p)++;
15648         if (cUNOPx(o)->op_first->op_type != OP_GV) {
15649             (*scalars_p) += 2;
15650             all_flags |= AAS_DANGEROUS; /* ${expr} */
15651         }
15652         else
15653             all_flags |= AAS_PKG_SCALAR; /* $pkg */
15654         goto do_next;
15655
15656     case OP_SPLIT:
15657         if (o->op_private & OPpSPLIT_ASSIGN) {
15658             /* the assign in @a = split() has been optimised away
15659              * and the @a attached directly to the split op
15660              * Treat the array as appearing on the RHS, i.e.
15661              *    ... = (@a = split)
15662              * is treated like
15663              *    ... = @a;
15664              */
15665
15666             if (o->op_flags & OPf_STACKED) {
15667                 /* @{expr} = split() - the array expression is tacked
15668                  * on as an extra child to split - process kid */
15669                 next_kid = cLISTOPo->op_last;
15670                 goto do_next;
15671             }
15672
15673             /* ... else array is directly attached to split op */
15674             (*scalars_p) += 2;
15675             all_flags |= (PL_op->op_private & OPpSPLIT_LEX)
15676                             ? ((o->op_private & OPpLVAL_INTRO)
15677                                 ? AAS_MY_AGG : AAS_LEX_AGG)
15678                             : AAS_PKG_AGG;
15679             goto do_next;
15680         }
15681         (*scalars_p)++;
15682         /* other args of split can't be returned */
15683         all_flags |= AAS_SAFE_SCALAR;
15684         goto do_next;
15685
15686     case OP_UNDEF:
15687         /* undef on LHS following a var is significant, e.g.
15688          *    my $x = 1;
15689          *    @a = (($x, undef) = (2 => $x));
15690          *    # @a shoul be (2,1) not (2,2)
15691          *
15692          * undef on RHS counts as a scalar:
15693          *   ($x, $y)    = (undef, $x); # 2 scalars on RHS: unsafe
15694          */
15695         if ((!rhs && *scalars_p) || rhs)
15696             (*scalars_p)++;
15697         flags = AAS_SAFE_SCALAR;
15698         break;
15699
15700     case OP_PUSHMARK:
15701     case OP_STUB:
15702         /* these are all no-ops; they don't push a potentially common SV
15703          * onto the stack, so they are neither AAS_DANGEROUS nor
15704          * AAS_SAFE_SCALAR */
15705         goto do_next;
15706
15707     case OP_PADRANGE: /* Ignore padrange; checking its siblings is enough */
15708         break;
15709
15710     case OP_NULL:
15711     case OP_LIST:
15712         /* these do nothing, but may have children */
15713         break;
15714
15715     default:
15716         if (PL_opargs[o->op_type] & OA_DANGEROUS) {
15717             (*scalars_p) += 2;
15718             flags = AAS_DANGEROUS;
15719             break;
15720         }
15721
15722         if (   (PL_opargs[o->op_type] & OA_TARGLEX)
15723             && (o->op_private & OPpTARGET_MY))
15724         {
15725             (*scalars_p)++;
15726             all_flags |= S_aassign_padcheck(aTHX_ o, rhs)
15727                             ? AAS_LEX_SCALAR_COMM : AAS_LEX_SCALAR;
15728             goto do_next;
15729         }
15730
15731         /* if its an unrecognised, non-dangerous op, assume that it
15732          * is the cause of at least one safe scalar */
15733         (*scalars_p)++;
15734         flags = AAS_SAFE_SCALAR;
15735         break;
15736     }
15737
15738     all_flags |= flags;
15739
15740     /* by default, process all kids next
15741      * XXX this assumes that all other ops are "transparent" - i.e. that
15742      * they can return some of their children. While this true for e.g.
15743      * sort and grep, it's not true for e.g. map. We really need a
15744      * 'transparent' flag added to regen/opcodes
15745      */
15746     if (o->op_flags & OPf_KIDS) {
15747         next_kid = cUNOPo->op_first;
15748         /* these ops do nothing but may have children; but their
15749          * children should also be treated as top-level */
15750         if (   o == effective_top_op
15751             && (o->op_type == OP_NULL || o->op_type == OP_LIST)
15752         )
15753             effective_top_op = next_kid;
15754     }
15755
15756
15757     /* If next_kid is set, someone in the code above wanted us to process
15758      * that kid and all its remaining siblings.  Otherwise, work our way
15759      * back up the tree */
15760   do_next:
15761     while (!next_kid) {
15762         if (o == top_op)
15763             return all_flags; /* at top; no parents/siblings to try */
15764         if (OpHAS_SIBLING(o)) {
15765             next_kid = o->op_sibparent;
15766             if (o == effective_top_op)
15767                 effective_top_op = next_kid;
15768         }
15769         else
15770             if (o == effective_top_op)
15771                 effective_top_op = o->op_sibparent;
15772             o = o->op_sibparent; /* try parent's next sibling */
15773
15774     }
15775     o = next_kid;
15776     } /* while */
15777
15778 }
15779
15780
15781 /* Check for in place reverse and sort assignments like "@a = reverse @a"
15782    and modify the optree to make them work inplace */
15783
15784 STATIC void
15785 S_inplace_aassign(pTHX_ OP *o) {
15786
15787     OP *modop, *modop_pushmark;
15788     OP *oright;
15789     OP *oleft, *oleft_pushmark;
15790
15791     PERL_ARGS_ASSERT_INPLACE_AASSIGN;
15792
15793     assert((o->op_flags & OPf_WANT) == OPf_WANT_VOID);
15794
15795     assert(cUNOPo->op_first->op_type == OP_NULL);
15796     modop_pushmark = cUNOPx(cUNOPo->op_first)->op_first;
15797     assert(modop_pushmark->op_type == OP_PUSHMARK);
15798     modop = OpSIBLING(modop_pushmark);
15799
15800     if (modop->op_type != OP_SORT && modop->op_type != OP_REVERSE)
15801         return;
15802
15803     /* no other operation except sort/reverse */
15804     if (OpHAS_SIBLING(modop))
15805         return;
15806
15807     assert(cUNOPx(modop)->op_first->op_type == OP_PUSHMARK);
15808     if (!(oright = OpSIBLING(cUNOPx(modop)->op_first))) return;
15809
15810     if (modop->op_flags & OPf_STACKED) {
15811         /* skip sort subroutine/block */
15812         assert(oright->op_type == OP_NULL);
15813         oright = OpSIBLING(oright);
15814     }
15815
15816     assert(OpSIBLING(cUNOPo->op_first)->op_type == OP_NULL);
15817     oleft_pushmark = cUNOPx(OpSIBLING(cUNOPo->op_first))->op_first;
15818     assert(oleft_pushmark->op_type == OP_PUSHMARK);
15819     oleft = OpSIBLING(oleft_pushmark);
15820
15821     /* Check the lhs is an array */
15822     if (!oleft ||
15823         (oleft->op_type != OP_RV2AV && oleft->op_type != OP_PADAV)
15824         || OpHAS_SIBLING(oleft)
15825         || (oleft->op_private & OPpLVAL_INTRO)
15826     )
15827         return;
15828
15829     /* Only one thing on the rhs */
15830     if (OpHAS_SIBLING(oright))
15831         return;
15832
15833     /* check the array is the same on both sides */
15834     if (oleft->op_type == OP_RV2AV) {
15835         if (oright->op_type != OP_RV2AV
15836             || !cUNOPx(oright)->op_first
15837             || cUNOPx(oright)->op_first->op_type != OP_GV
15838             || cUNOPx(oleft )->op_first->op_type != OP_GV
15839             || cGVOPx_gv(cUNOPx(oleft)->op_first) !=
15840                cGVOPx_gv(cUNOPx(oright)->op_first)
15841         )
15842             return;
15843     }
15844     else if (oright->op_type != OP_PADAV
15845         || oright->op_targ != oleft->op_targ
15846     )
15847         return;
15848
15849     /* This actually is an inplace assignment */
15850
15851     modop->op_private |= OPpSORT_INPLACE;
15852
15853     /* transfer MODishness etc from LHS arg to RHS arg */
15854     oright->op_flags = oleft->op_flags;
15855
15856     /* remove the aassign op and the lhs */
15857     op_null(o);
15858     op_null(oleft_pushmark);
15859     if (oleft->op_type == OP_RV2AV && cUNOPx(oleft)->op_first)
15860         op_null(cUNOPx(oleft)->op_first);
15861     op_null(oleft);
15862 }
15863
15864
15865
15866 /* S_maybe_multideref(): given an op_next chain of ops beginning at 'start'
15867  * that potentially represent a series of one or more aggregate derefs
15868  * (such as $a->[1]{$key}), examine the chain, and if appropriate, convert
15869  * the whole chain to a single OP_MULTIDEREF op (maybe with a few
15870  * additional ops left in too).
15871  *
15872  * The caller will have already verified that the first few ops in the
15873  * chain following 'start' indicate a multideref candidate, and will have
15874  * set 'orig_o' to the point further on in the chain where the first index
15875  * expression (if any) begins.  'orig_action' specifies what type of
15876  * beginning has already been determined by the ops between start..orig_o
15877  * (e.g.  $lex_ary[], $pkg_ary->{}, expr->[], etc).
15878  *
15879  * 'hints' contains any hints flags that need adding (currently just
15880  * OPpHINT_STRICT_REFS) as found in any rv2av/hv skipped by the caller.
15881  */
15882
15883 STATIC void
15884 S_maybe_multideref(pTHX_ OP *start, OP *orig_o, UV orig_action, U8 hints)
15885 {
15886     int pass;
15887     UNOP_AUX_item *arg_buf = NULL;
15888     bool reset_start_targ  = FALSE; /* start->op_targ needs zeroing */
15889     int index_skip         = -1;    /* don't output index arg on this action */
15890
15891     /* similar to regex compiling, do two passes; the first pass
15892      * determines whether the op chain is convertible and calculates the
15893      * buffer size; the second pass populates the buffer and makes any
15894      * changes necessary to ops (such as moving consts to the pad on
15895      * threaded builds).
15896      *
15897      * NB: for things like Coverity, note that both passes take the same
15898      * path through the logic tree (except for 'if (pass)' bits), since
15899      * both passes are following the same op_next chain; and in
15900      * particular, if it would return early on the second pass, it would
15901      * already have returned early on the first pass.
15902      */
15903     for (pass = 0; pass < 2; pass++) {
15904         OP *o                = orig_o;
15905         UV action            = orig_action;
15906         OP *first_elem_op    = NULL;  /* first seen aelem/helem */
15907         OP *top_op           = NULL;  /* highest [ah]elem/exists/del/rv2[ah]v */
15908         int action_count     = 0;     /* number of actions seen so far */
15909         int action_ix        = 0;     /* action_count % (actions per IV) */
15910         bool next_is_hash    = FALSE; /* is the next lookup to be a hash? */
15911         bool is_last         = FALSE; /* no more derefs to follow */
15912         bool maybe_aelemfast = FALSE; /* we can replace with aelemfast? */
15913         UV action_word       = 0;     /* all actions so far */
15914         UNOP_AUX_item *arg     = arg_buf;
15915         UNOP_AUX_item *action_ptr = arg_buf;
15916
15917         arg++; /* reserve slot for first action word */
15918
15919         switch (action) {
15920         case MDEREF_HV_gvsv_vivify_rv2hv_helem:
15921         case MDEREF_HV_gvhv_helem:
15922             next_is_hash = TRUE;
15923             /* FALLTHROUGH */
15924         case MDEREF_AV_gvsv_vivify_rv2av_aelem:
15925         case MDEREF_AV_gvav_aelem:
15926             if (pass) {
15927 #ifdef USE_ITHREADS
15928                 arg->pad_offset = cPADOPx(start)->op_padix;
15929                 /* stop it being swiped when nulled */
15930                 cPADOPx(start)->op_padix = 0;
15931 #else
15932                 arg->sv = cSVOPx(start)->op_sv;
15933                 cSVOPx(start)->op_sv = NULL;
15934 #endif
15935             }
15936             arg++;
15937             break;
15938
15939         case MDEREF_HV_padhv_helem:
15940         case MDEREF_HV_padsv_vivify_rv2hv_helem:
15941             next_is_hash = TRUE;
15942             /* FALLTHROUGH */
15943         case MDEREF_AV_padav_aelem:
15944         case MDEREF_AV_padsv_vivify_rv2av_aelem:
15945             if (pass) {
15946                 arg->pad_offset = start->op_targ;
15947                 /* we skip setting op_targ = 0 for now, since the intact
15948                  * OP_PADXV is needed by S_check_hash_fields_and_hekify */
15949                 reset_start_targ = TRUE;
15950             }
15951             arg++;
15952             break;
15953
15954         case MDEREF_HV_pop_rv2hv_helem:
15955             next_is_hash = TRUE;
15956             /* FALLTHROUGH */
15957         case MDEREF_AV_pop_rv2av_aelem:
15958             break;
15959
15960         default:
15961             NOT_REACHED; /* NOTREACHED */
15962             return;
15963         }
15964
15965         while (!is_last) {
15966             /* look for another (rv2av/hv; get index;
15967              * aelem/helem/exists/delele) sequence */
15968
15969             OP *kid;
15970             bool is_deref;
15971             bool ok;
15972             UV index_type = MDEREF_INDEX_none;
15973
15974             if (action_count) {
15975                 /* if this is not the first lookup, consume the rv2av/hv  */
15976
15977                 /* for N levels of aggregate lookup, we normally expect
15978                  * that the first N-1 [ah]elem ops will be flagged as
15979                  * /DEREF (so they autovivifiy if necessary), and the last
15980                  * lookup op not to be.
15981                  * For other things (like @{$h{k1}{k2}}) extra scope or
15982                  * leave ops can appear, so abandon the effort in that
15983                  * case */
15984                 if (o->op_type != OP_RV2AV && o->op_type != OP_RV2HV)
15985                     return;
15986
15987                 /* rv2av or rv2hv sKR/1 */
15988
15989                 ASSUME(!(o->op_flags & ~(OPf_WANT|OPf_KIDS|OPf_PARENS
15990                                             |OPf_REF|OPf_MOD|OPf_SPECIAL)));
15991                 if (o->op_flags != (OPf_WANT_SCALAR|OPf_KIDS|OPf_REF))
15992                     return;
15993
15994                 /* at this point, we wouldn't expect any of these
15995                  * possible private flags:
15996                  * OPpMAYBE_LVSUB, OPpOUR_INTRO, OPpLVAL_INTRO
15997                  * OPpTRUEBOOL, OPpMAYBE_TRUEBOOL (rv2hv only)
15998                  */
15999                 ASSUME(!(o->op_private &
16000                     ~(OPpHINT_STRICT_REFS|OPpARG1_MASK|OPpSLICEWARNING)));
16001
16002                 hints = (o->op_private & OPpHINT_STRICT_REFS);
16003
16004                 /* make sure the type of the previous /DEREF matches the
16005                  * type of the next lookup */
16006                 ASSUME(o->op_type == (next_is_hash ? OP_RV2HV : OP_RV2AV));
16007                 top_op = o;
16008
16009                 action = next_is_hash
16010                             ? MDEREF_HV_vivify_rv2hv_helem
16011                             : MDEREF_AV_vivify_rv2av_aelem;
16012                 o = o->op_next;
16013             }
16014
16015             /* if this is the second pass, and we're at the depth where
16016              * previously we encountered a non-simple index expression,
16017              * stop processing the index at this point */
16018             if (action_count != index_skip) {
16019
16020                 /* look for one or more simple ops that return an array
16021                  * index or hash key */
16022
16023                 switch (o->op_type) {
16024                 case OP_PADSV:
16025                     /* it may be a lexical var index */
16026                     ASSUME(!(o->op_flags & ~(OPf_WANT|OPf_PARENS
16027                                             |OPf_REF|OPf_MOD|OPf_SPECIAL)));
16028                     ASSUME(!(o->op_private &
16029                             ~(OPpPAD_STATE|OPpDEREF|OPpLVAL_INTRO)));
16030
16031                     if (   OP_GIMME(o,0) == G_SCALAR
16032                         && !(o->op_flags & (OPf_REF|OPf_MOD))
16033                         && o->op_private == 0)
16034                     {
16035                         if (pass)
16036                             arg->pad_offset = o->op_targ;
16037                         arg++;
16038                         index_type = MDEREF_INDEX_padsv;
16039                         o = o->op_next;
16040                     }
16041                     break;
16042
16043                 case OP_CONST:
16044                     if (next_is_hash) {
16045                         /* it's a constant hash index */
16046                         if (!(SvFLAGS(cSVOPo_sv) & (SVf_IOK|SVf_NOK|SVf_POK)))
16047                             /* "use constant foo => FOO; $h{+foo}" for
16048                              * some weird FOO, can leave you with constants
16049                              * that aren't simple strings. It's not worth
16050                              * the extra hassle for those edge cases */
16051                             break;
16052
16053                         {
16054                             UNOP *rop = NULL;
16055                             OP * helem_op = o->op_next;
16056
16057                             ASSUME(   helem_op->op_type == OP_HELEM
16058                                    || helem_op->op_type == OP_NULL
16059                                    || pass == 0);
16060                             if (helem_op->op_type == OP_HELEM) {
16061                                 rop = (UNOP*)(((BINOP*)helem_op)->op_first);
16062                                 if (   helem_op->op_private & OPpLVAL_INTRO
16063                                     || rop->op_type != OP_RV2HV
16064                                 )
16065                                     rop = NULL;
16066                             }
16067                             /* on first pass just check; on second pass
16068                              * hekify */
16069                             S_check_hash_fields_and_hekify(aTHX_ rop, cSVOPo,
16070                                                             pass);
16071                         }
16072
16073                         if (pass) {
16074 #ifdef USE_ITHREADS
16075                             /* Relocate sv to the pad for thread safety */
16076                             op_relocate_sv(&cSVOPo->op_sv, &o->op_targ);
16077                             arg->pad_offset = o->op_targ;
16078                             o->op_targ = 0;
16079 #else
16080                             arg->sv = cSVOPx_sv(o);
16081 #endif
16082                         }
16083                     }
16084                     else {
16085                         /* it's a constant array index */
16086                         IV iv;
16087                         SV *ix_sv = cSVOPo->op_sv;
16088                         if (!SvIOK(ix_sv))
16089                             break;
16090                         iv = SvIV(ix_sv);
16091
16092                         if (   action_count == 0
16093                             && iv >= -128
16094                             && iv <= 127
16095                             && (   action == MDEREF_AV_padav_aelem
16096                                 || action == MDEREF_AV_gvav_aelem)
16097                         )
16098                             maybe_aelemfast = TRUE;
16099
16100                         if (pass) {
16101                             arg->iv = iv;
16102                             SvREFCNT_dec_NN(cSVOPo->op_sv);
16103                         }
16104                     }
16105                     if (pass)
16106                         /* we've taken ownership of the SV */
16107                         cSVOPo->op_sv = NULL;
16108                     arg++;
16109                     index_type = MDEREF_INDEX_const;
16110                     o = o->op_next;
16111                     break;
16112
16113                 case OP_GV:
16114                     /* it may be a package var index */
16115
16116                     ASSUME(!(o->op_flags & ~(OPf_WANT|OPf_PARENS|OPf_SPECIAL)));
16117                     ASSUME(!(o->op_private & ~(OPpEARLY_CV)));
16118                     if (  (o->op_flags & ~(OPf_PARENS|OPf_SPECIAL)) != OPf_WANT_SCALAR
16119                         || o->op_private != 0
16120                     )
16121                         break;
16122
16123                     kid = o->op_next;
16124                     if (kid->op_type != OP_RV2SV)
16125                         break;
16126
16127                     ASSUME(!(kid->op_flags &
16128                             ~(OPf_WANT|OPf_KIDS|OPf_MOD|OPf_REF
16129                              |OPf_SPECIAL|OPf_PARENS)));
16130                     ASSUME(!(kid->op_private &
16131                                     ~(OPpARG1_MASK
16132                                      |OPpHINT_STRICT_REFS|OPpOUR_INTRO
16133                                      |OPpDEREF|OPpLVAL_INTRO)));
16134                     if(   (kid->op_flags &~ OPf_PARENS)
16135                             != (OPf_WANT_SCALAR|OPf_KIDS)
16136                        || (kid->op_private & ~(OPpARG1_MASK|HINT_STRICT_REFS))
16137                     )
16138                         break;
16139
16140                     if (pass) {
16141 #ifdef USE_ITHREADS
16142                         arg->pad_offset = cPADOPx(o)->op_padix;
16143                         /* stop it being swiped when nulled */
16144                         cPADOPx(o)->op_padix = 0;
16145 #else
16146                         arg->sv = cSVOPx(o)->op_sv;
16147                         cSVOPo->op_sv = NULL;
16148 #endif
16149                     }
16150                     arg++;
16151                     index_type = MDEREF_INDEX_gvsv;
16152                     o = kid->op_next;
16153                     break;
16154
16155                 } /* switch */
16156             } /* action_count != index_skip */
16157
16158             action |= index_type;
16159
16160
16161             /* at this point we have either:
16162              *   * detected what looks like a simple index expression,
16163              *     and expect the next op to be an [ah]elem, or
16164              *     an nulled  [ah]elem followed by a delete or exists;
16165              *  * found a more complex expression, so something other
16166              *    than the above follows.
16167              */
16168
16169             /* possibly an optimised away [ah]elem (where op_next is
16170              * exists or delete) */
16171             if (o->op_type == OP_NULL)
16172                 o = o->op_next;
16173
16174             /* at this point we're looking for an OP_AELEM, OP_HELEM,
16175              * OP_EXISTS or OP_DELETE */
16176
16177             /* if a custom array/hash access checker is in scope,
16178              * abandon optimisation attempt */
16179             if (  (o->op_type == OP_AELEM || o->op_type == OP_HELEM)
16180                && PL_check[o->op_type] != Perl_ck_null)
16181                 return;
16182             /* similarly for customised exists and delete */
16183             if (  (o->op_type == OP_EXISTS)
16184                && PL_check[o->op_type] != Perl_ck_exists)
16185                 return;
16186             if (  (o->op_type == OP_DELETE)
16187                && PL_check[o->op_type] != Perl_ck_delete)
16188                 return;
16189
16190             if (   o->op_type != OP_AELEM
16191                 || (o->op_private &
16192                       (OPpLVAL_INTRO|OPpLVAL_DEFER|OPpDEREF|OPpMAYBE_LVSUB))
16193                 )
16194                 maybe_aelemfast = FALSE;
16195
16196             /* look for aelem/helem/exists/delete. If it's not the last elem
16197              * lookup, it *must* have OPpDEREF_AV/HV, but not many other
16198              * flags; if it's the last, then it mustn't have
16199              * OPpDEREF_AV/HV, but may have lots of other flags, like
16200              * OPpLVAL_INTRO etc
16201              */
16202
16203             if (   index_type == MDEREF_INDEX_none
16204                 || (   o->op_type != OP_AELEM  && o->op_type != OP_HELEM
16205                     && o->op_type != OP_EXISTS && o->op_type != OP_DELETE)
16206             )
16207                 ok = FALSE;
16208             else {
16209                 /* we have aelem/helem/exists/delete with valid simple index */
16210
16211                 is_deref =    (o->op_type == OP_AELEM || o->op_type == OP_HELEM)
16212                            && (   (o->op_private & OPpDEREF) == OPpDEREF_AV
16213                                || (o->op_private & OPpDEREF) == OPpDEREF_HV);
16214
16215                 /* This doesn't make much sense but is legal:
16216                  *    @{ local $x[0][0] } = 1
16217                  * Since scope exit will undo the autovivification,
16218                  * don't bother in the first place. The OP_LEAVE
16219                  * assertion is in case there are other cases of both
16220                  * OPpLVAL_INTRO and OPpDEREF which don't include a scope
16221                  * exit that would undo the local - in which case this
16222                  * block of code would need rethinking.
16223                  */
16224                 if (is_deref && (o->op_private & OPpLVAL_INTRO)) {
16225 #ifdef DEBUGGING
16226                     OP *n = o->op_next;
16227                     while (n && (  n->op_type == OP_NULL
16228                                 || n->op_type == OP_LIST
16229                                 || n->op_type == OP_SCALAR))
16230                         n = n->op_next;
16231                     assert(n && n->op_type == OP_LEAVE);
16232 #endif
16233                     o->op_private &= ~OPpDEREF;
16234                     is_deref = FALSE;
16235                 }
16236
16237                 if (is_deref) {
16238                     ASSUME(!(o->op_flags &
16239                                  ~(OPf_WANT|OPf_KIDS|OPf_MOD|OPf_PARENS)));
16240                     ASSUME(!(o->op_private & ~(OPpARG2_MASK|OPpDEREF)));
16241
16242                     ok =    (o->op_flags &~ OPf_PARENS)
16243                                == (OPf_WANT_SCALAR|OPf_KIDS|OPf_MOD)
16244                          && !(o->op_private & ~(OPpDEREF|OPpARG2_MASK));
16245                 }
16246                 else if (o->op_type == OP_EXISTS) {
16247                     ASSUME(!(o->op_flags & ~(OPf_WANT|OPf_KIDS|OPf_PARENS
16248                                 |OPf_REF|OPf_MOD|OPf_SPECIAL)));
16249                     ASSUME(!(o->op_private & ~(OPpARG1_MASK|OPpEXISTS_SUB)));
16250                     ok =  !(o->op_private & ~OPpARG1_MASK);
16251                 }
16252                 else if (o->op_type == OP_DELETE) {
16253                     ASSUME(!(o->op_flags & ~(OPf_WANT|OPf_KIDS|OPf_PARENS
16254                                 |OPf_REF|OPf_MOD|OPf_SPECIAL)));
16255                     ASSUME(!(o->op_private &
16256                                     ~(OPpARG1_MASK|OPpSLICE|OPpLVAL_INTRO)));
16257                     /* don't handle slices or 'local delete'; the latter
16258                      * is fairly rare, and has a complex runtime */
16259                     ok =  !(o->op_private & ~OPpARG1_MASK);
16260                     if (OP_TYPE_IS_OR_WAS(cUNOPo->op_first, OP_AELEM))
16261                         /* skip handling run-tome error */
16262                         ok = (ok && cBOOL(o->op_flags & OPf_SPECIAL));
16263                 }
16264                 else {
16265                     ASSUME(o->op_type == OP_AELEM || o->op_type == OP_HELEM);
16266                     ASSUME(!(o->op_flags & ~(OPf_WANT|OPf_KIDS|OPf_MOD
16267                                             |OPf_PARENS|OPf_REF|OPf_SPECIAL)));
16268                     ASSUME(!(o->op_private & ~(OPpARG2_MASK|OPpMAYBE_LVSUB
16269                                     |OPpLVAL_DEFER|OPpDEREF|OPpLVAL_INTRO)));
16270                     ok = (o->op_private & OPpDEREF) != OPpDEREF_SV;
16271                 }
16272             }
16273
16274             if (ok) {
16275                 if (!first_elem_op)
16276                     first_elem_op = o;
16277                 top_op = o;
16278                 if (is_deref) {
16279                     next_is_hash = cBOOL((o->op_private & OPpDEREF) == OPpDEREF_HV);
16280                     o = o->op_next;
16281                 }
16282                 else {
16283                     is_last = TRUE;
16284                     action |= MDEREF_FLAG_last;
16285                 }
16286             }
16287             else {
16288                 /* at this point we have something that started
16289                  * promisingly enough (with rv2av or whatever), but failed
16290                  * to find a simple index followed by an
16291                  * aelem/helem/exists/delete. If this is the first action,
16292                  * give up; but if we've already seen at least one
16293                  * aelem/helem, then keep them and add a new action with
16294                  * MDEREF_INDEX_none, which causes it to do the vivify
16295                  * from the end of the previous lookup, and do the deref,
16296                  * but stop at that point. So $a[0][expr] will do one
16297                  * av_fetch, vivify and deref, then continue executing at
16298                  * expr */
16299                 if (!action_count)
16300                     return;
16301                 is_last = TRUE;
16302                 index_skip = action_count;
16303                 action |= MDEREF_FLAG_last;
16304                 if (index_type != MDEREF_INDEX_none)
16305                     arg--;
16306             }
16307
16308             action_word |= (action << (action_ix * MDEREF_SHIFT));
16309             action_ix++;
16310             action_count++;
16311             /* if there's no space for the next action, reserve a new slot
16312              * for it *before* we start adding args for that action */
16313             if ((action_ix + 1) * MDEREF_SHIFT > UVSIZE*8) {
16314                 if (pass)
16315                     action_ptr->uv = action_word;
16316                 action_word = 0;
16317                 action_ptr = arg;
16318                 arg++;
16319                 action_ix = 0;
16320             }
16321         } /* while !is_last */
16322
16323         /* success! */
16324
16325         if (!action_ix)
16326             /* slot reserved for next action word not now needed */
16327             arg--;
16328         else if (pass)
16329             action_ptr->uv = action_word;
16330
16331         if (pass) {
16332             OP *mderef;
16333             OP *p, *q;
16334
16335             mderef = newUNOP_AUX(OP_MULTIDEREF, 0, NULL, arg_buf);
16336             if (index_skip == -1) {
16337                 mderef->op_flags = o->op_flags
16338                         & (OPf_WANT|OPf_MOD|(next_is_hash ? OPf_SPECIAL : 0));
16339                 if (o->op_type == OP_EXISTS)
16340                     mderef->op_private = OPpMULTIDEREF_EXISTS;
16341                 else if (o->op_type == OP_DELETE)
16342                     mderef->op_private = OPpMULTIDEREF_DELETE;
16343                 else
16344                     mderef->op_private = o->op_private
16345                         & (OPpMAYBE_LVSUB|OPpLVAL_DEFER|OPpLVAL_INTRO);
16346             }
16347             /* accumulate strictness from every level (although I don't think
16348              * they can actually vary) */
16349             mderef->op_private |= hints;
16350
16351             /* integrate the new multideref op into the optree and the
16352              * op_next chain.
16353              *
16354              * In general an op like aelem or helem has two child
16355              * sub-trees: the aggregate expression (a_expr) and the
16356              * index expression (i_expr):
16357              *
16358              *     aelem
16359              *       |
16360              *     a_expr - i_expr
16361              *
16362              * The a_expr returns an AV or HV, while the i-expr returns an
16363              * index. In general a multideref replaces most or all of a
16364              * multi-level tree, e.g.
16365              *
16366              *     exists
16367              *       |
16368              *     ex-aelem
16369              *       |
16370              *     rv2av  - i_expr1
16371              *       |
16372              *     helem
16373              *       |
16374              *     rv2hv  - i_expr2
16375              *       |
16376              *     aelem
16377              *       |
16378              *     a_expr - i_expr3
16379              *
16380              * With multideref, all the i_exprs will be simple vars or
16381              * constants, except that i_expr1 may be arbitrary in the case
16382              * of MDEREF_INDEX_none.
16383              *
16384              * The bottom-most a_expr will be either:
16385              *   1) a simple var (so padXv or gv+rv2Xv);
16386              *   2) a simple scalar var dereferenced (e.g. $r->[0]):
16387              *      so a simple var with an extra rv2Xv;
16388              *   3) or an arbitrary expression.
16389              *
16390              * 'start', the first op in the execution chain, will point to
16391              *   1),2): the padXv or gv op;
16392              *   3):    the rv2Xv which forms the last op in the a_expr
16393              *          execution chain, and the top-most op in the a_expr
16394              *          subtree.
16395              *
16396              * For all cases, the 'start' node is no longer required,
16397              * but we can't free it since one or more external nodes
16398              * may point to it. E.g. consider
16399              *     $h{foo} = $a ? $b : $c
16400              * Here, both the op_next and op_other branches of the
16401              * cond_expr point to the gv[*h] of the hash expression, so
16402              * we can't free the 'start' op.
16403              *
16404              * For expr->[...], we need to save the subtree containing the
16405              * expression; for the other cases, we just need to save the
16406              * start node.
16407              * So in all cases, we null the start op and keep it around by
16408              * making it the child of the multideref op; for the expr->
16409              * case, the expr will be a subtree of the start node.
16410              *
16411              * So in the simple 1,2 case the  optree above changes to
16412              *
16413              *     ex-exists
16414              *       |
16415              *     multideref
16416              *       |
16417              *     ex-gv (or ex-padxv)
16418              *
16419              *  with the op_next chain being
16420              *
16421              *  -> ex-gv -> multideref -> op-following-ex-exists ->
16422              *
16423              *  In the 3 case, we have
16424              *
16425              *     ex-exists
16426              *       |
16427              *     multideref
16428              *       |
16429              *     ex-rv2xv
16430              *       |
16431              *    rest-of-a_expr
16432              *      subtree
16433              *
16434              *  and
16435              *
16436              *  -> rest-of-a_expr subtree ->
16437              *    ex-rv2xv -> multideref -> op-following-ex-exists ->
16438              *
16439              *
16440              * Where the last i_expr is non-simple (i.e. MDEREF_INDEX_none,
16441              * e.g. $a[0]{foo}[$x+1], the next rv2xv is nulled and the
16442              * multideref attached as the child, e.g.
16443              *
16444              *     exists
16445              *       |
16446              *     ex-aelem
16447              *       |
16448              *     ex-rv2av  - i_expr1
16449              *       |
16450              *     multideref
16451              *       |
16452              *     ex-whatever
16453              *
16454              */
16455
16456             /* if we free this op, don't free the pad entry */
16457             if (reset_start_targ)
16458                 start->op_targ = 0;
16459
16460
16461             /* Cut the bit we need to save out of the tree and attach to
16462              * the multideref op, then free the rest of the tree */
16463
16464             /* find parent of node to be detached (for use by splice) */
16465             p = first_elem_op;
16466             if (   orig_action == MDEREF_AV_pop_rv2av_aelem
16467                 || orig_action == MDEREF_HV_pop_rv2hv_helem)
16468             {
16469                 /* there is an arbitrary expression preceding us, e.g.
16470                  * expr->[..]? so we need to save the 'expr' subtree */
16471                 if (p->op_type == OP_EXISTS || p->op_type == OP_DELETE)
16472                     p = cUNOPx(p)->op_first;
16473                 ASSUME(   start->op_type == OP_RV2AV
16474                        || start->op_type == OP_RV2HV);
16475             }
16476             else {
16477                 /* either a padXv or rv2Xv+gv, maybe with an ex-Xelem
16478                  * above for exists/delete. */
16479                 while (   (p->op_flags & OPf_KIDS)
16480                        && cUNOPx(p)->op_first != start
16481                 )
16482                     p = cUNOPx(p)->op_first;
16483             }
16484             ASSUME(cUNOPx(p)->op_first == start);
16485
16486             /* detach from main tree, and re-attach under the multideref */
16487             op_sibling_splice(mderef, NULL, 0,
16488                     op_sibling_splice(p, NULL, 1, NULL));
16489             op_null(start);
16490
16491             start->op_next = mderef;
16492
16493             mderef->op_next = index_skip == -1 ? o->op_next : o;
16494
16495             /* excise and free the original tree, and replace with
16496              * the multideref op */
16497             p = op_sibling_splice(top_op, NULL, -1, mderef);
16498             while (p) {
16499                 q = OpSIBLING(p);
16500                 op_free(p);
16501                 p = q;
16502             }
16503             op_null(top_op);
16504         }
16505         else {
16506             Size_t size = arg - arg_buf;
16507
16508             if (maybe_aelemfast && action_count == 1)
16509                 return;
16510
16511             arg_buf = (UNOP_AUX_item*)PerlMemShared_malloc(
16512                                 sizeof(UNOP_AUX_item) * (size + 1));
16513             /* for dumping etc: store the length in a hidden first slot;
16514              * we set the op_aux pointer to the second slot */
16515             arg_buf->uv = size;
16516             arg_buf++;
16517         }
16518     } /* for (pass = ...) */
16519 }
16520
16521 /* See if the ops following o are such that o will always be executed in
16522  * boolean context: that is, the SV which o pushes onto the stack will
16523  * only ever be consumed by later ops via SvTRUE(sv) or similar.
16524  * If so, set a suitable private flag on o. Normally this will be
16525  * bool_flag; but see below why maybe_flag is needed too.
16526  *
16527  * Typically the two flags you pass will be the generic OPpTRUEBOOL and
16528  * OPpMAYBE_TRUEBOOL, buts it's possible that for some ops those bits may
16529  * already be taken, so you'll have to give that op two different flags.
16530  *
16531  * More explanation of 'maybe_flag' and 'safe_and' parameters.
16532  * The binary logical ops &&, ||, // (plus 'if' and 'unless' which use
16533  * those underlying ops) short-circuit, which means that rather than
16534  * necessarily returning a truth value, they may return the LH argument,
16535  * which may not be boolean. For example in $x = (keys %h || -1), keys
16536  * should return a key count rather than a boolean, even though its
16537  * sort-of being used in boolean context.
16538  *
16539  * So we only consider such logical ops to provide boolean context to
16540  * their LH argument if they themselves are in void or boolean context.
16541  * However, sometimes the context isn't known until run-time. In this
16542  * case the op is marked with the maybe_flag flag it.
16543  *
16544  * Consider the following.
16545  *
16546  *     sub f { ....;  if (%h) { .... } }
16547  *
16548  * This is actually compiled as
16549  *
16550  *     sub f { ....;  %h && do { .... } }
16551  *
16552  * Here we won't know until runtime whether the final statement (and hence
16553  * the &&) is in void context and so is safe to return a boolean value.
16554  * So mark o with maybe_flag rather than the bool_flag.
16555  * Note that there is cost associated with determining context at runtime
16556  * (e.g. a call to block_gimme()), so it may not be worth setting (at
16557  * compile time) and testing (at runtime) maybe_flag if the scalar verses
16558  * boolean costs savings are marginal.
16559  *
16560  * However, we can do slightly better with && (compared to || and //):
16561  * this op only returns its LH argument when that argument is false. In
16562  * this case, as long as the op promises to return a false value which is
16563  * valid in both boolean and scalar contexts, we can mark an op consumed
16564  * by && with bool_flag rather than maybe_flag.
16565  * For example as long as pp_padhv and pp_rv2hv return &PL_sv_zero rather
16566  * than &PL_sv_no for a false result in boolean context, then it's safe. An
16567  * op which promises to handle this case is indicated by setting safe_and
16568  * to true.
16569  */
16570
16571 static void
16572 S_check_for_bool_cxt(OP*o, bool safe_and, U8 bool_flag, U8 maybe_flag)
16573 {
16574     OP *lop;
16575     U8 flag = 0;
16576
16577     assert((o->op_flags & OPf_WANT) == OPf_WANT_SCALAR);
16578
16579     /* OPpTARGET_MY and boolean context probably don't mix well.
16580      * If someone finds a valid use case, maybe add an extra flag to this
16581      * function which indicates its safe to do so for this op? */
16582     assert(!(   (PL_opargs[o->op_type] & OA_TARGLEX)
16583              && (o->op_private & OPpTARGET_MY)));
16584
16585     lop = o->op_next;
16586
16587     while (lop) {
16588         switch (lop->op_type) {
16589         case OP_NULL:
16590         case OP_SCALAR:
16591             break;
16592
16593         /* these two consume the stack argument in the scalar case,
16594          * and treat it as a boolean in the non linenumber case */
16595         case OP_FLIP:
16596         case OP_FLOP:
16597             if (   ((lop->op_flags & OPf_WANT) == OPf_WANT_LIST)
16598                 || (lop->op_private & OPpFLIP_LINENUM))
16599             {
16600                 lop = NULL;
16601                 break;
16602             }
16603             /* FALLTHROUGH */
16604         /* these never leave the original value on the stack */
16605         case OP_NOT:
16606         case OP_XOR:
16607         case OP_COND_EXPR:
16608         case OP_GREPWHILE:
16609             flag = bool_flag;
16610             lop = NULL;
16611             break;
16612
16613         /* OR DOR and AND evaluate their arg as a boolean, but then may
16614          * leave the original scalar value on the stack when following the
16615          * op_next route. If not in void context, we need to ensure
16616          * that whatever follows consumes the arg only in boolean context
16617          * too.
16618          */
16619         case OP_AND:
16620             if (safe_and) {
16621                 flag = bool_flag;
16622                 lop = NULL;
16623                 break;
16624             }
16625             /* FALLTHROUGH */
16626         case OP_OR:
16627         case OP_DOR:
16628             if ((lop->op_flags & OPf_WANT) == OPf_WANT_VOID) {
16629                 flag = bool_flag;
16630                 lop = NULL;
16631             }
16632             else if (!(lop->op_flags & OPf_WANT)) {
16633                 /* unknown context - decide at runtime */
16634                 flag = maybe_flag;
16635                 lop = NULL;
16636             }
16637             break;
16638
16639         default:
16640             lop = NULL;
16641             break;
16642         }
16643
16644         if (lop)
16645             lop = lop->op_next;
16646     }
16647
16648     o->op_private |= flag;
16649 }
16650
16651
16652
16653 /* mechanism for deferring recursion in rpeep() */
16654
16655 #define MAX_DEFERRED 4
16656
16657 #define DEFER(o) \
16658   STMT_START { \
16659     if (defer_ix == (MAX_DEFERRED-1)) { \
16660         OP **defer = defer_queue[defer_base]; \
16661         CALL_RPEEP(*defer); \
16662         S_prune_chain_head(defer); \
16663         defer_base = (defer_base + 1) % MAX_DEFERRED; \
16664         defer_ix--; \
16665     } \
16666     defer_queue[(defer_base + ++defer_ix) % MAX_DEFERRED] = &(o); \
16667   } STMT_END
16668
16669 #define IS_AND_OP(o)   (o->op_type == OP_AND)
16670 #define IS_OR_OP(o)    (o->op_type == OP_OR)
16671
16672
16673 /* A peephole optimizer.  We visit the ops in the order they're to execute.
16674  * See the comments at the top of this file for more details about when
16675  * peep() is called */
16676
16677 void
16678 Perl_rpeep(pTHX_ OP *o)
16679 {
16680     OP* oldop = NULL;
16681     OP* oldoldop = NULL;
16682     OP** defer_queue[MAX_DEFERRED]; /* small queue of deferred branches */
16683     int defer_base = 0;
16684     int defer_ix = -1;
16685
16686     if (!o || o->op_opt)
16687         return;
16688
16689     assert(o->op_type != OP_FREED);
16690
16691     ENTER;
16692     SAVEOP();
16693     SAVEVPTR(PL_curcop);
16694     for (;; o = o->op_next) {
16695         if (o && o->op_opt)
16696             o = NULL;
16697         if (!o) {
16698             while (defer_ix >= 0) {
16699                 OP **defer =
16700                         defer_queue[(defer_base + defer_ix--) % MAX_DEFERRED];
16701                 CALL_RPEEP(*defer);
16702                 S_prune_chain_head(defer);
16703             }
16704             break;
16705         }
16706
16707       redo:
16708
16709         /* oldoldop -> oldop -> o should be a chain of 3 adjacent ops */
16710         assert(!oldoldop || oldoldop->op_next == oldop);
16711         assert(!oldop    || oldop->op_next    == o);
16712
16713         /* By default, this op has now been optimised. A couple of cases below
16714            clear this again.  */
16715         o->op_opt = 1;
16716         PL_op = o;
16717
16718         /* look for a series of 1 or more aggregate derefs, e.g.
16719          *   $a[1]{foo}[$i]{$k}
16720          * and replace with a single OP_MULTIDEREF op.
16721          * Each index must be either a const, or a simple variable,
16722          *
16723          * First, look for likely combinations of starting ops,
16724          * corresponding to (global and lexical variants of)
16725          *     $a[...]   $h{...}
16726          *     $r->[...] $r->{...}
16727          *     (preceding expression)->[...]
16728          *     (preceding expression)->{...}
16729          * and if so, call maybe_multideref() to do a full inspection
16730          * of the op chain and if appropriate, replace with an
16731          * OP_MULTIDEREF
16732          */
16733         {
16734             UV action;
16735             OP *o2 = o;
16736             U8 hints = 0;
16737
16738             switch (o2->op_type) {
16739             case OP_GV:
16740                 /* $pkg[..]   :   gv[*pkg]
16741                  * $pkg->[...]:   gv[*pkg]; rv2sv sKM/DREFAV */
16742
16743                 /* Fail if there are new op flag combinations that we're
16744                  * not aware of, rather than:
16745                  *  * silently failing to optimise, or
16746                  *  * silently optimising the flag away.
16747                  * If this ASSUME starts failing, examine what new flag
16748                  * has been added to the op, and decide whether the
16749                  * optimisation should still occur with that flag, then
16750                  * update the code accordingly. This applies to all the
16751                  * other ASSUMEs in the block of code too.
16752                  */
16753                 ASSUME(!(o2->op_flags &
16754                             ~(OPf_WANT|OPf_MOD|OPf_PARENS|OPf_SPECIAL)));
16755                 ASSUME(!(o2->op_private & ~OPpEARLY_CV));
16756
16757                 o2 = o2->op_next;
16758
16759                 if (o2->op_type == OP_RV2AV) {
16760                     action = MDEREF_AV_gvav_aelem;
16761                     goto do_deref;
16762                 }
16763
16764                 if (o2->op_type == OP_RV2HV) {
16765                     action = MDEREF_HV_gvhv_helem;
16766                     goto do_deref;
16767                 }
16768
16769                 if (o2->op_type != OP_RV2SV)
16770                     break;
16771
16772                 /* at this point we've seen gv,rv2sv, so the only valid
16773                  * construct left is $pkg->[] or $pkg->{} */
16774
16775                 ASSUME(!(o2->op_flags & OPf_STACKED));
16776                 if ((o2->op_flags & (OPf_WANT|OPf_REF|OPf_MOD|OPf_SPECIAL))
16777                             != (OPf_WANT_SCALAR|OPf_MOD))
16778                     break;
16779
16780                 ASSUME(!(o2->op_private & ~(OPpARG1_MASK|HINT_STRICT_REFS
16781                                     |OPpOUR_INTRO|OPpDEREF|OPpLVAL_INTRO)));
16782                 if (o2->op_private & (OPpOUR_INTRO|OPpLVAL_INTRO))
16783                     break;
16784                 if (   (o2->op_private & OPpDEREF) != OPpDEREF_AV
16785                     && (o2->op_private & OPpDEREF) != OPpDEREF_HV)
16786                     break;
16787
16788                 o2 = o2->op_next;
16789                 if (o2->op_type == OP_RV2AV) {
16790                     action = MDEREF_AV_gvsv_vivify_rv2av_aelem;
16791                     goto do_deref;
16792                 }
16793                 if (o2->op_type == OP_RV2HV) {
16794                     action = MDEREF_HV_gvsv_vivify_rv2hv_helem;
16795                     goto do_deref;
16796                 }
16797                 break;
16798
16799             case OP_PADSV:
16800                 /* $lex->[...]: padsv[$lex] sM/DREFAV */
16801
16802                 ASSUME(!(o2->op_flags &
16803                     ~(OPf_WANT|OPf_PARENS|OPf_REF|OPf_MOD|OPf_SPECIAL)));
16804                 if ((o2->op_flags &
16805                         (OPf_WANT|OPf_REF|OPf_MOD|OPf_SPECIAL))
16806                      != (OPf_WANT_SCALAR|OPf_MOD))
16807                     break;
16808
16809                 ASSUME(!(o2->op_private &
16810                                 ~(OPpPAD_STATE|OPpDEREF|OPpLVAL_INTRO)));
16811                 /* skip if state or intro, or not a deref */
16812                 if (      o2->op_private != OPpDEREF_AV
16813                        && o2->op_private != OPpDEREF_HV)
16814                     break;
16815
16816                 o2 = o2->op_next;
16817                 if (o2->op_type == OP_RV2AV) {
16818                     action = MDEREF_AV_padsv_vivify_rv2av_aelem;
16819                     goto do_deref;
16820                 }
16821                 if (o2->op_type == OP_RV2HV) {
16822                     action = MDEREF_HV_padsv_vivify_rv2hv_helem;
16823                     goto do_deref;
16824                 }
16825                 break;
16826
16827             case OP_PADAV:
16828             case OP_PADHV:
16829                 /*    $lex[..]:  padav[@lex:1,2] sR *
16830                  * or $lex{..}:  padhv[%lex:1,2] sR */
16831                 ASSUME(!(o2->op_flags & ~(OPf_WANT|OPf_MOD|OPf_PARENS|
16832                                             OPf_REF|OPf_SPECIAL)));
16833                 if ((o2->op_flags &
16834                         (OPf_WANT|OPf_REF|OPf_MOD|OPf_SPECIAL))
16835                      != (OPf_WANT_SCALAR|OPf_REF))
16836                     break;
16837                 if (o2->op_flags != (OPf_WANT_SCALAR|OPf_REF))
16838                     break;
16839                 /* OPf_PARENS isn't currently used in this case;
16840                  * if that changes, let us know! */
16841                 ASSUME(!(o2->op_flags & OPf_PARENS));
16842
16843                 /* at this point, we wouldn't expect any of the remaining
16844                  * possible private flags:
16845                  * OPpPAD_STATE, OPpLVAL_INTRO, OPpTRUEBOOL,
16846                  * OPpMAYBE_TRUEBOOL, OPpMAYBE_LVSUB
16847                  *
16848                  * OPpSLICEWARNING shouldn't affect runtime
16849                  */
16850                 ASSUME(!(o2->op_private & ~(OPpSLICEWARNING)));
16851
16852                 action = o2->op_type == OP_PADAV
16853                             ? MDEREF_AV_padav_aelem
16854                             : MDEREF_HV_padhv_helem;
16855                 o2 = o2->op_next;
16856                 S_maybe_multideref(aTHX_ o, o2, action, 0);
16857                 break;
16858
16859
16860             case OP_RV2AV:
16861             case OP_RV2HV:
16862                 action = o2->op_type == OP_RV2AV
16863                             ? MDEREF_AV_pop_rv2av_aelem
16864                             : MDEREF_HV_pop_rv2hv_helem;
16865                 /* FALLTHROUGH */
16866             do_deref:
16867                 /* (expr)->[...]:  rv2av sKR/1;
16868                  * (expr)->{...}:  rv2hv sKR/1; */
16869
16870                 ASSUME(o2->op_type == OP_RV2AV || o2->op_type == OP_RV2HV);
16871
16872                 ASSUME(!(o2->op_flags & ~(OPf_WANT|OPf_KIDS|OPf_PARENS
16873                                 |OPf_REF|OPf_MOD|OPf_STACKED|OPf_SPECIAL)));
16874                 if (o2->op_flags != (OPf_WANT_SCALAR|OPf_KIDS|OPf_REF))
16875                     break;
16876
16877                 /* at this point, we wouldn't expect any of these
16878                  * possible private flags:
16879                  * OPpMAYBE_LVSUB, OPpLVAL_INTRO
16880                  * OPpTRUEBOOL, OPpMAYBE_TRUEBOOL, (rv2hv only)
16881                  */
16882                 ASSUME(!(o2->op_private &
16883                     ~(OPpHINT_STRICT_REFS|OPpARG1_MASK|OPpSLICEWARNING
16884                      |OPpOUR_INTRO)));
16885                 hints |= (o2->op_private & OPpHINT_STRICT_REFS);
16886
16887                 o2 = o2->op_next;
16888
16889                 S_maybe_multideref(aTHX_ o, o2, action, hints);
16890                 break;
16891
16892             default:
16893                 break;
16894             }
16895         }
16896
16897
16898         switch (o->op_type) {
16899         case OP_DBSTATE:
16900             PL_curcop = ((COP*)o);              /* for warnings */
16901             break;
16902         case OP_NEXTSTATE:
16903             PL_curcop = ((COP*)o);              /* for warnings */
16904
16905             /* Optimise a "return ..." at the end of a sub to just be "...".
16906              * This saves 2 ops. Before:
16907              * 1  <;> nextstate(main 1 -e:1) v ->2
16908              * 4  <@> return K ->5
16909              * 2    <0> pushmark s ->3
16910              * -    <1> ex-rv2sv sK/1 ->4
16911              * 3      <#> gvsv[*cat] s ->4
16912              *
16913              * After:
16914              * -  <@> return K ->-
16915              * -    <0> pushmark s ->2
16916              * -    <1> ex-rv2sv sK/1 ->-
16917              * 2      <$> gvsv(*cat) s ->3
16918              */
16919             {
16920                 OP *next = o->op_next;
16921                 OP *sibling = OpSIBLING(o);
16922                 if (   OP_TYPE_IS(next, OP_PUSHMARK)
16923                     && OP_TYPE_IS(sibling, OP_RETURN)
16924                     && OP_TYPE_IS(sibling->op_next, OP_LINESEQ)
16925                     && ( OP_TYPE_IS(sibling->op_next->op_next, OP_LEAVESUB)
16926                        ||OP_TYPE_IS(sibling->op_next->op_next,
16927                                     OP_LEAVESUBLV))
16928                     && cUNOPx(sibling)->op_first == next
16929                     && OpHAS_SIBLING(next) && OpSIBLING(next)->op_next
16930                     && next->op_next
16931                 ) {
16932                     /* Look through the PUSHMARK's siblings for one that
16933                      * points to the RETURN */
16934                     OP *top = OpSIBLING(next);
16935                     while (top && top->op_next) {
16936                         if (top->op_next == sibling) {
16937                             top->op_next = sibling->op_next;
16938                             o->op_next = next->op_next;
16939                             break;
16940                         }
16941                         top = OpSIBLING(top);
16942                     }
16943                 }
16944             }
16945
16946             /* Optimise 'my $x; my $y;' into 'my ($x, $y);'
16947              *
16948              * This latter form is then suitable for conversion into padrange
16949              * later on. Convert:
16950              *
16951              *   nextstate1 -> padop1 -> nextstate2 -> padop2 -> nextstate3
16952              *
16953              * into:
16954              *
16955              *   nextstate1 ->     listop     -> nextstate3
16956              *                 /            \
16957              *         pushmark -> padop1 -> padop2
16958              */
16959             if (o->op_next && (
16960                     o->op_next->op_type == OP_PADSV
16961                  || o->op_next->op_type == OP_PADAV
16962                  || o->op_next->op_type == OP_PADHV
16963                 )
16964                 && !(o->op_next->op_private & ~OPpLVAL_INTRO)
16965                 && o->op_next->op_next && o->op_next->op_next->op_type == OP_NEXTSTATE
16966                 && o->op_next->op_next->op_next && (
16967                     o->op_next->op_next->op_next->op_type == OP_PADSV
16968                  || o->op_next->op_next->op_next->op_type == OP_PADAV
16969                  || o->op_next->op_next->op_next->op_type == OP_PADHV
16970                 )
16971                 && !(o->op_next->op_next->op_next->op_private & ~OPpLVAL_INTRO)
16972                 && o->op_next->op_next->op_next->op_next && o->op_next->op_next->op_next->op_next->op_type == OP_NEXTSTATE
16973                 && (!CopLABEL((COP*)o)) /* Don't mess with labels */
16974                 && (!CopLABEL((COP*)o->op_next->op_next)) /* ... */
16975             ) {
16976                 OP *pad1, *ns2, *pad2, *ns3, *newop, *newpm;
16977
16978                 pad1 =    o->op_next;
16979                 ns2  = pad1->op_next;
16980                 pad2 =  ns2->op_next;
16981                 ns3  = pad2->op_next;
16982
16983                 /* we assume here that the op_next chain is the same as
16984                  * the op_sibling chain */
16985                 assert(OpSIBLING(o)    == pad1);
16986                 assert(OpSIBLING(pad1) == ns2);
16987                 assert(OpSIBLING(ns2)  == pad2);
16988                 assert(OpSIBLING(pad2) == ns3);
16989
16990                 /* excise and delete ns2 */
16991                 op_sibling_splice(NULL, pad1, 1, NULL);
16992                 op_free(ns2);
16993
16994                 /* excise pad1 and pad2 */
16995                 op_sibling_splice(NULL, o, 2, NULL);
16996
16997                 /* create new listop, with children consisting of:
16998                  * a new pushmark, pad1, pad2. */
16999                 newop = newLISTOP(OP_LIST, 0, pad1, pad2);
17000                 newop->op_flags |= OPf_PARENS;
17001                 newop->op_flags = (newop->op_flags & ~OPf_WANT) | OPf_WANT_VOID;
17002
17003                 /* insert newop between o and ns3 */
17004                 op_sibling_splice(NULL, o, 0, newop);
17005
17006                 /*fixup op_next chain */
17007                 newpm = cUNOPx(newop)->op_first; /* pushmark */
17008                 o    ->op_next = newpm;
17009                 newpm->op_next = pad1;
17010                 pad1 ->op_next = pad2;
17011                 pad2 ->op_next = newop; /* listop */
17012                 newop->op_next = ns3;
17013
17014                 /* Ensure pushmark has this flag if padops do */
17015                 if (pad1->op_flags & OPf_MOD && pad2->op_flags & OPf_MOD) {
17016                     newpm->op_flags |= OPf_MOD;
17017                 }
17018
17019                 break;
17020             }
17021
17022             /* Two NEXTSTATEs in a row serve no purpose. Except if they happen
17023                to carry two labels. For now, take the easier option, and skip
17024                this optimisation if the first NEXTSTATE has a label.  */
17025             if (!CopLABEL((COP*)o) && !PERLDB_NOOPT) {
17026                 OP *nextop = o->op_next;
17027                 while (nextop) {
17028                     switch (nextop->op_type) {
17029                         case OP_NULL:
17030                         case OP_SCALAR:
17031                         case OP_LINESEQ:
17032                         case OP_SCOPE:
17033                             nextop = nextop->op_next;
17034                             continue;
17035                     }
17036                     break;
17037                 }
17038
17039                 if (nextop && (nextop->op_type == OP_NEXTSTATE)) {
17040                     op_null(o);
17041                     if (oldop)
17042                         oldop->op_next = nextop;
17043                     o = nextop;
17044                     /* Skip (old)oldop assignment since the current oldop's
17045                        op_next already points to the next op.  */
17046                     goto redo;
17047                 }
17048             }
17049             break;
17050
17051         case OP_CONCAT:
17052             if (o->op_next && o->op_next->op_type == OP_STRINGIFY) {
17053                 if (o->op_next->op_private & OPpTARGET_MY) {
17054                     if (o->op_flags & OPf_STACKED) /* chained concats */
17055                         break; /* ignore_optimization */
17056                     else {
17057                         /* assert(PL_opargs[o->op_type] & OA_TARGLEX); */
17058                         o->op_targ = o->op_next->op_targ;
17059                         o->op_next->op_targ = 0;
17060                         o->op_private |= OPpTARGET_MY;
17061                     }
17062                 }
17063                 op_null(o->op_next);
17064             }
17065             break;
17066         case OP_STUB:
17067             if ((o->op_flags & OPf_WANT) != OPf_WANT_LIST) {
17068                 break; /* Scalar stub must produce undef.  List stub is noop */
17069             }
17070             goto nothin;
17071         case OP_NULL:
17072             if (o->op_targ == OP_NEXTSTATE
17073                 || o->op_targ == OP_DBSTATE)
17074             {
17075                 PL_curcop = ((COP*)o);
17076             }
17077             /* XXX: We avoid setting op_seq here to prevent later calls
17078                to rpeep() from mistakenly concluding that optimisation
17079                has already occurred. This doesn't fix the real problem,
17080                though (See 20010220.007 (#5874)). AMS 20010719 */
17081             /* op_seq functionality is now replaced by op_opt */
17082             o->op_opt = 0;
17083             /* FALLTHROUGH */
17084         case OP_SCALAR:
17085         case OP_LINESEQ:
17086         case OP_SCOPE:
17087         nothin:
17088             if (oldop) {
17089                 oldop->op_next = o->op_next;
17090                 o->op_opt = 0;
17091                 continue;
17092             }
17093             break;
17094
17095         case OP_PUSHMARK:
17096
17097             /* Given
17098                  5 repeat/DOLIST
17099                  3   ex-list
17100                  1     pushmark
17101                  2     scalar or const
17102                  4   const[0]
17103                convert repeat into a stub with no kids.
17104              */
17105             if (o->op_next->op_type == OP_CONST
17106              || (  o->op_next->op_type == OP_PADSV
17107                 && !(o->op_next->op_private & OPpLVAL_INTRO))
17108              || (  o->op_next->op_type == OP_GV
17109                 && o->op_next->op_next->op_type == OP_RV2SV
17110                 && !(o->op_next->op_next->op_private
17111                         & (OPpLVAL_INTRO|OPpOUR_INTRO))))
17112             {
17113                 const OP *kid = o->op_next->op_next;
17114                 if (o->op_next->op_type == OP_GV)
17115                    kid = kid->op_next;
17116                 /* kid is now the ex-list.  */
17117                 if (kid->op_type == OP_NULL
17118                  && (kid = kid->op_next)->op_type == OP_CONST
17119                     /* kid is now the repeat count.  */
17120                  && kid->op_next->op_type == OP_REPEAT
17121                  && kid->op_next->op_private & OPpREPEAT_DOLIST
17122                  && (kid->op_next->op_flags & OPf_WANT) == OPf_WANT_LIST
17123                  && SvIOK(kSVOP_sv) && SvIVX(kSVOP_sv) == 0
17124                  && oldop)
17125                 {
17126                     o = kid->op_next; /* repeat */
17127                     oldop->op_next = o;
17128                     op_free(cBINOPo->op_first);
17129                     op_free(cBINOPo->op_last );
17130                     o->op_flags &=~ OPf_KIDS;
17131                     /* stub is a baseop; repeat is a binop */
17132                     STATIC_ASSERT_STMT(sizeof(OP) <= sizeof(BINOP));
17133                     OpTYPE_set(o, OP_STUB);
17134                     o->op_private = 0;
17135                     break;
17136                 }
17137             }
17138
17139             /* Convert a series of PAD ops for my vars plus support into a
17140              * single padrange op. Basically
17141              *
17142              *    pushmark -> pad[ahs]v -> pad[ahs]?v -> ... -> (list) -> rest
17143              *
17144              * becomes, depending on circumstances, one of
17145              *
17146              *    padrange  ----------------------------------> (list) -> rest
17147              *    padrange  --------------------------------------------> rest
17148              *
17149              * where all the pad indexes are sequential and of the same type
17150              * (INTRO or not).
17151              * We convert the pushmark into a padrange op, then skip
17152              * any other pad ops, and possibly some trailing ops.
17153              * Note that we don't null() the skipped ops, to make it
17154              * easier for Deparse to undo this optimisation (and none of
17155              * the skipped ops are holding any resourses). It also makes
17156              * it easier for find_uninit_var(), as it can just ignore
17157              * padrange, and examine the original pad ops.
17158              */
17159         {
17160             OP *p;
17161             OP *followop = NULL; /* the op that will follow the padrange op */
17162             U8 count = 0;
17163             U8 intro = 0;
17164             PADOFFSET base = 0; /* init only to stop compiler whining */
17165             bool gvoid = 0;     /* init only to stop compiler whining */
17166             bool defav = 0;  /* seen (...) = @_ */
17167             bool reuse = 0;  /* reuse an existing padrange op */
17168
17169             /* look for a pushmark -> gv[_] -> rv2av */
17170
17171             {
17172                 OP *rv2av, *q;
17173                 p = o->op_next;
17174                 if (   p->op_type == OP_GV
17175                     && cGVOPx_gv(p) == PL_defgv
17176                     && (rv2av = p->op_next)
17177                     && rv2av->op_type == OP_RV2AV
17178                     && !(rv2av->op_flags & OPf_REF)
17179                     && !(rv2av->op_private & (OPpLVAL_INTRO|OPpMAYBE_LVSUB))
17180                     && ((rv2av->op_flags & OPf_WANT) == OPf_WANT_LIST)
17181                 ) {
17182                     q = rv2av->op_next;
17183                     if (q->op_type == OP_NULL)
17184                         q = q->op_next;
17185                     if (q->op_type == OP_PUSHMARK) {
17186                         defav = 1;
17187                         p = q;
17188                     }
17189                 }
17190             }
17191             if (!defav) {
17192                 p = o;
17193             }
17194
17195             /* scan for PAD ops */
17196
17197             for (p = p->op_next; p; p = p->op_next) {
17198                 if (p->op_type == OP_NULL)
17199                     continue;
17200
17201                 if ((     p->op_type != OP_PADSV
17202                        && p->op_type != OP_PADAV
17203                        && p->op_type != OP_PADHV
17204                     )
17205                       /* any private flag other than INTRO? e.g. STATE */
17206                    || (p->op_private & ~OPpLVAL_INTRO)
17207                 )
17208                     break;
17209
17210                 /* let $a[N] potentially be optimised into AELEMFAST_LEX
17211                  * instead */
17212                 if (   p->op_type == OP_PADAV
17213                     && p->op_next
17214                     && p->op_next->op_type == OP_CONST
17215                     && p->op_next->op_next
17216                     && p->op_next->op_next->op_type == OP_AELEM
17217                 )
17218                     break;
17219
17220                 /* for 1st padop, note what type it is and the range
17221                  * start; for the others, check that it's the same type
17222                  * and that the targs are contiguous */
17223                 if (count == 0) {
17224                     intro = (p->op_private & OPpLVAL_INTRO);
17225                     base = p->op_targ;
17226                     gvoid = OP_GIMME(p,0) == G_VOID;
17227                 }
17228                 else {
17229                     if ((p->op_private & OPpLVAL_INTRO) != intro)
17230                         break;
17231                     /* Note that you'd normally  expect targs to be
17232                      * contiguous in my($a,$b,$c), but that's not the case
17233                      * when external modules start doing things, e.g.
17234                      * Function::Parameters */
17235                     if (p->op_targ != base + count)
17236                         break;
17237                     assert(p->op_targ == base + count);
17238                     /* Either all the padops or none of the padops should
17239                        be in void context.  Since we only do the optimisa-
17240                        tion for av/hv when the aggregate itself is pushed
17241                        on to the stack (one item), there is no need to dis-
17242                        tinguish list from scalar context.  */
17243                     if (gvoid != (OP_GIMME(p,0) == G_VOID))
17244                         break;
17245                 }
17246
17247                 /* for AV, HV, only when we're not flattening */
17248                 if (   p->op_type != OP_PADSV
17249                     && !gvoid
17250                     && !(p->op_flags & OPf_REF)
17251                 )
17252                     break;
17253
17254                 if (count >= OPpPADRANGE_COUNTMASK)
17255                     break;
17256
17257                 /* there's a biggest base we can fit into a
17258                  * SAVEt_CLEARPADRANGE in pp_padrange.
17259                  * (The sizeof() stuff will be constant-folded, and is
17260                  * intended to avoid getting "comparison is always false"
17261                  * compiler warnings. See the comments above
17262                  * MEM_WRAP_CHECK for more explanation on why we do this
17263                  * in a weird way to avoid compiler warnings.)
17264                  */
17265                 if (   intro
17266                     && (8*sizeof(base) >
17267                         8*sizeof(UV)-OPpPADRANGE_COUNTSHIFT-SAVE_TIGHT_SHIFT
17268                         ? (Size_t)base
17269                         : (UV_MAX >> (OPpPADRANGE_COUNTSHIFT+SAVE_TIGHT_SHIFT))
17270                         ) >
17271                         (UV_MAX >> (OPpPADRANGE_COUNTSHIFT+SAVE_TIGHT_SHIFT))
17272                 )
17273                     break;
17274
17275                 /* Success! We've got another valid pad op to optimise away */
17276                 count++;
17277                 followop = p->op_next;
17278             }
17279
17280             if (count < 1 || (count == 1 && !defav))
17281                 break;
17282
17283             /* pp_padrange in specifically compile-time void context
17284              * skips pushing a mark and lexicals; in all other contexts
17285              * (including unknown till runtime) it pushes a mark and the
17286              * lexicals. We must be very careful then, that the ops we
17287              * optimise away would have exactly the same effect as the
17288              * padrange.
17289              * In particular in void context, we can only optimise to
17290              * a padrange if we see the complete sequence
17291              *     pushmark, pad*v, ...., list
17292              * which has the net effect of leaving the markstack as it
17293              * was.  Not pushing onto the stack (whereas padsv does touch
17294              * the stack) makes no difference in void context.
17295              */
17296             assert(followop);
17297             if (gvoid) {
17298                 if (followop->op_type == OP_LIST
17299                         && OP_GIMME(followop,0) == G_VOID
17300                    )
17301                 {
17302                     followop = followop->op_next; /* skip OP_LIST */
17303
17304                     /* consolidate two successive my(...);'s */
17305
17306                     if (   oldoldop
17307                         && oldoldop->op_type == OP_PADRANGE
17308                         && (oldoldop->op_flags & OPf_WANT) == OPf_WANT_VOID
17309                         && (oldoldop->op_private & OPpLVAL_INTRO) == intro
17310                         && !(oldoldop->op_flags & OPf_SPECIAL)
17311                     ) {
17312                         U8 old_count;
17313                         assert(oldoldop->op_next == oldop);
17314                         assert(   oldop->op_type == OP_NEXTSTATE
17315                                || oldop->op_type == OP_DBSTATE);
17316                         assert(oldop->op_next == o);
17317
17318                         old_count
17319                             = (oldoldop->op_private & OPpPADRANGE_COUNTMASK);
17320
17321                        /* Do not assume pad offsets for $c and $d are con-
17322                           tiguous in
17323                             my ($a,$b,$c);
17324                             my ($d,$e,$f);
17325                         */
17326                         if (  oldoldop->op_targ + old_count == base
17327                            && old_count < OPpPADRANGE_COUNTMASK - count) {
17328                             base = oldoldop->op_targ;
17329                             count += old_count;
17330                             reuse = 1;
17331                         }
17332                     }
17333
17334                     /* if there's any immediately following singleton
17335                      * my var's; then swallow them and the associated
17336                      * nextstates; i.e.
17337                      *    my ($a,$b); my $c; my $d;
17338                      * is treated as
17339                      *    my ($a,$b,$c,$d);
17340                      */
17341
17342                     while (    ((p = followop->op_next))
17343                             && (  p->op_type == OP_PADSV
17344                                || p->op_type == OP_PADAV
17345                                || p->op_type == OP_PADHV)
17346                             && (p->op_flags & OPf_WANT) == OPf_WANT_VOID
17347                             && (p->op_private & OPpLVAL_INTRO) == intro
17348                             && !(p->op_private & ~OPpLVAL_INTRO)
17349                             && p->op_next
17350                             && (   p->op_next->op_type == OP_NEXTSTATE
17351                                 || p->op_next->op_type == OP_DBSTATE)
17352                             && count < OPpPADRANGE_COUNTMASK
17353                             && base + count == p->op_targ
17354                     ) {
17355                         count++;
17356                         followop = p->op_next;
17357                     }
17358                 }
17359                 else
17360                     break;
17361             }
17362
17363             if (reuse) {
17364                 assert(oldoldop->op_type == OP_PADRANGE);
17365                 oldoldop->op_next = followop;
17366                 oldoldop->op_private = (intro | count);
17367                 o = oldoldop;
17368                 oldop = NULL;
17369                 oldoldop = NULL;
17370             }
17371             else {
17372                 /* Convert the pushmark into a padrange.
17373                  * To make Deparse easier, we guarantee that a padrange was
17374                  * *always* formerly a pushmark */
17375                 assert(o->op_type == OP_PUSHMARK);
17376                 o->op_next = followop;
17377                 OpTYPE_set(o, OP_PADRANGE);
17378                 o->op_targ = base;
17379                 /* bit 7: INTRO; bit 6..0: count */
17380                 o->op_private = (intro | count);
17381                 o->op_flags = ((o->op_flags & ~(OPf_WANT|OPf_SPECIAL))
17382                               | gvoid * OPf_WANT_VOID
17383                               | (defav ? OPf_SPECIAL : 0));
17384             }
17385             break;
17386         }
17387
17388         case OP_RV2AV:
17389             if ((o->op_flags & OPf_WANT) == OPf_WANT_SCALAR)
17390                 S_check_for_bool_cxt(o, 1, OPpTRUEBOOL, 0);
17391             break;
17392
17393         case OP_RV2HV:
17394         case OP_PADHV:
17395             /*'keys %h' in void or scalar context: skip the OP_KEYS
17396              * and perform the functionality directly in the RV2HV/PADHV
17397              * op
17398              */
17399             if (o->op_flags & OPf_REF) {
17400                 OP *k = o->op_next;
17401                 U8 want = (k->op_flags & OPf_WANT);
17402                 if (   k
17403                     && k->op_type == OP_KEYS
17404                     && (   want == OPf_WANT_VOID
17405                         || want == OPf_WANT_SCALAR)
17406                     && !(k->op_private & OPpMAYBE_LVSUB)
17407                     && !(k->op_flags & OPf_MOD)
17408                 ) {
17409                     o->op_next     = k->op_next;
17410                     o->op_flags   &= ~(OPf_REF|OPf_WANT);
17411                     o->op_flags   |= want;
17412                     o->op_private |= (o->op_type == OP_PADHV ?
17413                                       OPpPADHV_ISKEYS : OPpRV2HV_ISKEYS);
17414                     /* for keys(%lex), hold onto the OP_KEYS's targ
17415                      * since padhv doesn't have its own targ to return
17416                      * an int with */
17417                     if (!(o->op_type ==OP_PADHV && want == OPf_WANT_SCALAR))
17418                         op_null(k);
17419                 }
17420             }
17421
17422             /* see if %h is used in boolean context */
17423             if ((o->op_flags & OPf_WANT) == OPf_WANT_SCALAR)
17424                 S_check_for_bool_cxt(o, 1, OPpTRUEBOOL, OPpMAYBE_TRUEBOOL);
17425
17426
17427             if (o->op_type != OP_PADHV)
17428                 break;
17429             /* FALLTHROUGH */
17430         case OP_PADAV:
17431             if (   o->op_type == OP_PADAV
17432                 && (o->op_flags & OPf_WANT) == OPf_WANT_SCALAR
17433             )
17434                 S_check_for_bool_cxt(o, 1, OPpTRUEBOOL, 0);
17435             /* FALLTHROUGH */
17436         case OP_PADSV:
17437             /* Skip over state($x) in void context.  */
17438             if (oldop && o->op_private == (OPpPAD_STATE|OPpLVAL_INTRO)
17439              && (o->op_flags & OPf_WANT) == OPf_WANT_VOID)
17440             {
17441                 oldop->op_next = o->op_next;
17442                 goto redo_nextstate;
17443             }
17444             if (o->op_type != OP_PADAV)
17445                 break;
17446             /* FALLTHROUGH */
17447         case OP_GV:
17448             if (o->op_type == OP_PADAV || o->op_next->op_type == OP_RV2AV) {
17449                 OP* const pop = (o->op_type == OP_PADAV) ?
17450                             o->op_next : o->op_next->op_next;
17451                 IV i;
17452                 if (pop && pop->op_type == OP_CONST &&
17453                     ((PL_op = pop->op_next)) &&
17454                     pop->op_next->op_type == OP_AELEM &&
17455                     !(pop->op_next->op_private &
17456                       (OPpLVAL_INTRO|OPpLVAL_DEFER|OPpDEREF|OPpMAYBE_LVSUB)) &&
17457                     (i = SvIV(((SVOP*)pop)->op_sv)) >= -128 && i <= 127)
17458                 {
17459                     GV *gv;
17460                     if (cSVOPx(pop)->op_private & OPpCONST_STRICT)
17461                         no_bareword_allowed(pop);
17462                     if (o->op_type == OP_GV)
17463                         op_null(o->op_next);
17464                     op_null(pop->op_next);
17465                     op_null(pop);
17466                     o->op_flags |= pop->op_next->op_flags & OPf_MOD;
17467                     o->op_next = pop->op_next->op_next;
17468                     o->op_ppaddr = PL_ppaddr[OP_AELEMFAST];
17469                     o->op_private = (U8)i;
17470                     if (o->op_type == OP_GV) {
17471                         gv = cGVOPo_gv;
17472                         GvAVn(gv);
17473                         o->op_type = OP_AELEMFAST;
17474                     }
17475                     else
17476                         o->op_type = OP_AELEMFAST_LEX;
17477                 }
17478                 if (o->op_type != OP_GV)
17479                     break;
17480             }
17481
17482             /* Remove $foo from the op_next chain in void context.  */
17483             if (oldop
17484              && (  o->op_next->op_type == OP_RV2SV
17485                 || o->op_next->op_type == OP_RV2AV
17486                 || o->op_next->op_type == OP_RV2HV  )
17487              && (o->op_next->op_flags & OPf_WANT) == OPf_WANT_VOID
17488              && !(o->op_next->op_private & OPpLVAL_INTRO))
17489             {
17490                 oldop->op_next = o->op_next->op_next;
17491                 /* Reprocess the previous op if it is a nextstate, to
17492                    allow double-nextstate optimisation.  */
17493               redo_nextstate:
17494                 if (oldop->op_type == OP_NEXTSTATE) {
17495                     oldop->op_opt = 0;
17496                     o = oldop;
17497                     oldop = oldoldop;
17498                     oldoldop = NULL;
17499                     goto redo;
17500                 }
17501                 o = oldop->op_next;
17502                 goto redo;
17503             }
17504             else if (o->op_next->op_type == OP_RV2SV) {
17505                 if (!(o->op_next->op_private & OPpDEREF)) {
17506                     op_null(o->op_next);
17507                     o->op_private |= o->op_next->op_private & (OPpLVAL_INTRO
17508                                                                | OPpOUR_INTRO);
17509                     o->op_next = o->op_next->op_next;
17510                     OpTYPE_set(o, OP_GVSV);
17511                 }
17512             }
17513             else if (o->op_next->op_type == OP_READLINE
17514                     && o->op_next->op_next->op_type == OP_CONCAT
17515                     && (o->op_next->op_next->op_flags & OPf_STACKED))
17516             {
17517                 /* Turn "$a .= <FH>" into an OP_RCATLINE. AMS 20010917 */
17518                 OpTYPE_set(o, OP_RCATLINE);
17519                 o->op_flags |= OPf_STACKED;
17520                 op_null(o->op_next->op_next);
17521                 op_null(o->op_next);
17522             }
17523
17524             break;
17525
17526         case OP_NOT:
17527             break;
17528
17529         case OP_AND:
17530         case OP_OR:
17531         case OP_DOR:
17532         case OP_CMPCHAIN_AND:
17533             while (cLOGOP->op_other->op_type == OP_NULL)
17534                 cLOGOP->op_other = cLOGOP->op_other->op_next;
17535             while (o->op_next && (   o->op_type == o->op_next->op_type
17536                                   || o->op_next->op_type == OP_NULL))
17537                 o->op_next = o->op_next->op_next;
17538
17539             /* If we're an OR and our next is an AND in void context, we'll
17540                follow its op_other on short circuit, same for reverse.
17541                We can't do this with OP_DOR since if it's true, its return
17542                value is the underlying value which must be evaluated
17543                by the next op. */
17544             if (o->op_next &&
17545                 (
17546                     (IS_AND_OP(o) && IS_OR_OP(o->op_next))
17547                  || (IS_OR_OP(o) && IS_AND_OP(o->op_next))
17548                 )
17549                 && (o->op_next->op_flags & OPf_WANT) == OPf_WANT_VOID
17550             ) {
17551                 o->op_next = ((LOGOP*)o->op_next)->op_other;
17552             }
17553             DEFER(cLOGOP->op_other);
17554             o->op_opt = 1;
17555             break;
17556
17557         case OP_GREPWHILE:
17558             if ((o->op_flags & OPf_WANT) == OPf_WANT_SCALAR)
17559                 S_check_for_bool_cxt(o, 1, OPpTRUEBOOL, 0);
17560             /* FALLTHROUGH */
17561         case OP_COND_EXPR:
17562         case OP_MAPWHILE:
17563         case OP_ANDASSIGN:
17564         case OP_ORASSIGN:
17565         case OP_DORASSIGN:
17566         case OP_RANGE:
17567         case OP_ONCE:
17568         case OP_ARGDEFELEM:
17569             while (cLOGOP->op_other->op_type == OP_NULL)
17570                 cLOGOP->op_other = cLOGOP->op_other->op_next;
17571             DEFER(cLOGOP->op_other);
17572             break;
17573
17574         case OP_ENTERLOOP:
17575         case OP_ENTERITER:
17576             while (cLOOP->op_redoop->op_type == OP_NULL)
17577                 cLOOP->op_redoop = cLOOP->op_redoop->op_next;
17578             while (cLOOP->op_nextop->op_type == OP_NULL)
17579                 cLOOP->op_nextop = cLOOP->op_nextop->op_next;
17580             while (cLOOP->op_lastop->op_type == OP_NULL)
17581                 cLOOP->op_lastop = cLOOP->op_lastop->op_next;
17582             /* a while(1) loop doesn't have an op_next that escapes the
17583              * loop, so we have to explicitly follow the op_lastop to
17584              * process the rest of the code */
17585             DEFER(cLOOP->op_lastop);
17586             break;
17587
17588         case OP_ENTERTRY:
17589             assert(cLOGOPo->op_other->op_type == OP_LEAVETRY);
17590             DEFER(cLOGOPo->op_other);
17591             break;
17592
17593         case OP_SUBST:
17594             if ((o->op_flags & OPf_WANT) == OPf_WANT_SCALAR)
17595                 S_check_for_bool_cxt(o, 1, OPpTRUEBOOL, 0);
17596             assert(!(cPMOP->op_pmflags & PMf_ONCE));
17597             while (cPMOP->op_pmstashstartu.op_pmreplstart &&
17598                    cPMOP->op_pmstashstartu.op_pmreplstart->op_type == OP_NULL)
17599                 cPMOP->op_pmstashstartu.op_pmreplstart
17600                     = cPMOP->op_pmstashstartu.op_pmreplstart->op_next;
17601             DEFER(cPMOP->op_pmstashstartu.op_pmreplstart);
17602             break;
17603
17604         case OP_SORT: {
17605             OP *oright;
17606
17607             if (o->op_flags & OPf_SPECIAL) {
17608                 /* first arg is a code block */
17609                 OP * const nullop = OpSIBLING(cLISTOP->op_first);
17610                 OP * kid          = cUNOPx(nullop)->op_first;
17611
17612                 assert(nullop->op_type == OP_NULL);
17613                 assert(kid->op_type == OP_SCOPE
17614                  || (kid->op_type == OP_NULL && kid->op_targ == OP_LEAVE));
17615                 /* since OP_SORT doesn't have a handy op_other-style
17616                  * field that can point directly to the start of the code
17617                  * block, store it in the otherwise-unused op_next field
17618                  * of the top-level OP_NULL. This will be quicker at
17619                  * run-time, and it will also allow us to remove leading
17620                  * OP_NULLs by just messing with op_nexts without
17621                  * altering the basic op_first/op_sibling layout. */
17622                 kid = kLISTOP->op_first;
17623                 assert(
17624                       (kid->op_type == OP_NULL
17625                       && (  kid->op_targ == OP_NEXTSTATE
17626                          || kid->op_targ == OP_DBSTATE  ))
17627                     || kid->op_type == OP_STUB
17628                     || kid->op_type == OP_ENTER
17629                     || (PL_parser && PL_parser->error_count));
17630                 nullop->op_next = kid->op_next;
17631                 DEFER(nullop->op_next);
17632             }
17633
17634             /* check that RHS of sort is a single plain array */
17635             oright = cUNOPo->op_first;
17636             if (!oright || oright->op_type != OP_PUSHMARK)
17637                 break;
17638
17639             if (o->op_private & OPpSORT_INPLACE)
17640                 break;
17641
17642             /* reverse sort ... can be optimised.  */
17643             if (!OpHAS_SIBLING(cUNOPo)) {
17644                 /* Nothing follows us on the list. */
17645                 OP * const reverse = o->op_next;
17646
17647                 if (reverse->op_type == OP_REVERSE &&
17648                     (reverse->op_flags & OPf_WANT) == OPf_WANT_LIST) {
17649                     OP * const pushmark = cUNOPx(reverse)->op_first;
17650                     if (pushmark && (pushmark->op_type == OP_PUSHMARK)
17651                         && (OpSIBLING(cUNOPx(pushmark)) == o)) {
17652                         /* reverse -> pushmark -> sort */
17653                         o->op_private |= OPpSORT_REVERSE;
17654                         op_null(reverse);
17655                         pushmark->op_next = oright->op_next;
17656                         op_null(oright);
17657                     }
17658                 }
17659             }
17660
17661             break;
17662         }
17663
17664         case OP_REVERSE: {
17665             OP *ourmark, *theirmark, *ourlast, *iter, *expushmark, *rv2av;
17666             OP *gvop = NULL;
17667             LISTOP *enter, *exlist;
17668
17669             if (o->op_private & OPpSORT_INPLACE)
17670                 break;
17671
17672             enter = (LISTOP *) o->op_next;
17673             if (!enter)
17674                 break;
17675             if (enter->op_type == OP_NULL) {
17676                 enter = (LISTOP *) enter->op_next;
17677                 if (!enter)
17678                     break;
17679             }
17680             /* for $a (...) will have OP_GV then OP_RV2GV here.
17681                for (...) just has an OP_GV.  */
17682             if (enter->op_type == OP_GV) {
17683                 gvop = (OP *) enter;
17684                 enter = (LISTOP *) enter->op_next;
17685                 if (!enter)
17686                     break;
17687                 if (enter->op_type == OP_RV2GV) {
17688                   enter = (LISTOP *) enter->op_next;
17689                   if (!enter)
17690                     break;
17691                 }
17692             }
17693
17694             if (enter->op_type != OP_ENTERITER)
17695                 break;
17696
17697             iter = enter->op_next;
17698             if (!iter || iter->op_type != OP_ITER)
17699                 break;
17700
17701             expushmark = enter->op_first;
17702             if (!expushmark || expushmark->op_type != OP_NULL
17703                 || expushmark->op_targ != OP_PUSHMARK)
17704                 break;
17705
17706             exlist = (LISTOP *) OpSIBLING(expushmark);
17707             if (!exlist || exlist->op_type != OP_NULL
17708                 || exlist->op_targ != OP_LIST)
17709                 break;
17710
17711             if (exlist->op_last != o) {
17712                 /* Mmm. Was expecting to point back to this op.  */
17713                 break;
17714             }
17715             theirmark = exlist->op_first;
17716             if (!theirmark || theirmark->op_type != OP_PUSHMARK)
17717                 break;
17718
17719             if (OpSIBLING(theirmark) != o) {
17720                 /* There's something between the mark and the reverse, eg
17721                    for (1, reverse (...))
17722                    so no go.  */
17723                 break;
17724             }
17725
17726             ourmark = ((LISTOP *)o)->op_first;
17727             if (!ourmark || ourmark->op_type != OP_PUSHMARK)
17728                 break;
17729
17730             ourlast = ((LISTOP *)o)->op_last;
17731             if (!ourlast || ourlast->op_next != o)
17732                 break;
17733
17734             rv2av = OpSIBLING(ourmark);
17735             if (rv2av && rv2av->op_type == OP_RV2AV && !OpHAS_SIBLING(rv2av)
17736                 && rv2av->op_flags == (OPf_WANT_LIST | OPf_KIDS)) {
17737                 /* We're just reversing a single array.  */
17738                 rv2av->op_flags = OPf_WANT_SCALAR | OPf_KIDS | OPf_REF;
17739                 enter->op_flags |= OPf_STACKED;
17740             }
17741
17742             /* We don't have control over who points to theirmark, so sacrifice
17743                ours.  */
17744             theirmark->op_next = ourmark->op_next;
17745             theirmark->op_flags = ourmark->op_flags;
17746             ourlast->op_next = gvop ? gvop : (OP *) enter;
17747             op_null(ourmark);
17748             op_null(o);
17749             enter->op_private |= OPpITER_REVERSED;
17750             iter->op_private |= OPpITER_REVERSED;
17751
17752             oldoldop = NULL;
17753             oldop    = ourlast;
17754             o        = oldop->op_next;
17755             goto redo;
17756             NOT_REACHED; /* NOTREACHED */
17757             break;
17758         }
17759
17760         case OP_QR:
17761         case OP_MATCH:
17762             if (!(cPMOP->op_pmflags & PMf_ONCE)) {
17763                 assert (!cPMOP->op_pmstashstartu.op_pmreplstart);
17764             }
17765             break;
17766
17767         case OP_RUNCV:
17768             if (!(o->op_private & OPpOFFBYONE) && !CvCLONE(PL_compcv)
17769              && (!CvANON(PL_compcv) || (!PL_cv_has_eval && !PL_perldb)))
17770             {
17771                 SV *sv;
17772                 if (CvEVAL(PL_compcv)) sv = &PL_sv_undef;
17773                 else {
17774                     sv = newRV((SV *)PL_compcv);
17775                     sv_rvweaken(sv);
17776                     SvREADONLY_on(sv);
17777                 }
17778                 OpTYPE_set(o, OP_CONST);
17779                 o->op_flags |= OPf_SPECIAL;
17780                 cSVOPo->op_sv = sv;
17781             }
17782             break;
17783
17784         case OP_SASSIGN:
17785             if (OP_GIMME(o,0) == G_VOID
17786              || (  o->op_next->op_type == OP_LINESEQ
17787                 && (  o->op_next->op_next->op_type == OP_LEAVESUB
17788                    || (  o->op_next->op_next->op_type == OP_RETURN
17789                       && !CvLVALUE(PL_compcv)))))
17790             {
17791                 OP *right = cBINOP->op_first;
17792                 if (right) {
17793                     /*   sassign
17794                     *      RIGHT
17795                     *      substr
17796                     *         pushmark
17797                     *         arg1
17798                     *         arg2
17799                     *         ...
17800                     * becomes
17801                     *
17802                     *  ex-sassign
17803                     *     substr
17804                     *        pushmark
17805                     *        RIGHT
17806                     *        arg1
17807                     *        arg2
17808                     *        ...
17809                     */
17810                     OP *left = OpSIBLING(right);
17811                     if (left->op_type == OP_SUBSTR
17812                          && (left->op_private & 7) < 4) {
17813                         op_null(o);
17814                         /* cut out right */
17815                         op_sibling_splice(o, NULL, 1, NULL);
17816                         /* and insert it as second child of OP_SUBSTR */
17817                         op_sibling_splice(left, cBINOPx(left)->op_first, 0,
17818                                     right);
17819                         left->op_private |= OPpSUBSTR_REPL_FIRST;
17820                         left->op_flags =
17821                             (o->op_flags & ~OPf_WANT) | OPf_WANT_VOID;
17822                     }
17823                 }
17824             }
17825             break;
17826
17827         case OP_AASSIGN: {
17828             int l, r, lr, lscalars, rscalars;
17829
17830             /* handle common vars detection, e.g. ($a,$b) = ($b,$a).
17831                Note that we do this now rather than in newASSIGNOP(),
17832                since only by now are aliased lexicals flagged as such
17833
17834                See the essay "Common vars in list assignment" above for
17835                the full details of the rationale behind all the conditions
17836                below.
17837
17838                PL_generation sorcery:
17839                To detect whether there are common vars, the global var
17840                PL_generation is incremented for each assign op we scan.
17841                Then we run through all the lexical variables on the LHS,
17842                of the assignment, setting a spare slot in each of them to
17843                PL_generation.  Then we scan the RHS, and if any lexicals
17844                already have that value, we know we've got commonality.
17845                Also, if the generation number is already set to
17846                PERL_INT_MAX, then the variable is involved in aliasing, so
17847                we also have potential commonality in that case.
17848              */
17849
17850             PL_generation++;
17851             /* scan LHS */
17852             lscalars = 0;
17853             l = S_aassign_scan(aTHX_ cLISTOPo->op_last,  FALSE, &lscalars);
17854             /* scan RHS */
17855             rscalars = 0;
17856             r = S_aassign_scan(aTHX_ cLISTOPo->op_first, TRUE, &rscalars);
17857             lr = (l|r);
17858
17859
17860             /* After looking for things which are *always* safe, this main
17861              * if/else chain selects primarily based on the type of the
17862              * LHS, gradually working its way down from the more dangerous
17863              * to the more restrictive and thus safer cases */
17864
17865             if (   !l                      /* () = ....; */
17866                 || !r                      /* .... = (); */
17867                 || !(l & ~AAS_SAFE_SCALAR) /* (undef, pos()) = ...; */
17868                 || !(r & ~AAS_SAFE_SCALAR) /* ... = (1,2,length,undef); */
17869                 || (lscalars < 2)          /* ($x, undef) = ... */
17870             ) {
17871                 NOOP; /* always safe */
17872             }
17873             else if (l & AAS_DANGEROUS) {
17874                 /* always dangerous */
17875                 o->op_private |= OPpASSIGN_COMMON_SCALAR;
17876                 o->op_private |= OPpASSIGN_COMMON_AGG;
17877             }
17878             else if (l & (AAS_PKG_SCALAR|AAS_PKG_AGG)) {
17879                 /* package vars are always dangerous - too many
17880                  * aliasing possibilities */
17881                 if (l & AAS_PKG_SCALAR)
17882                     o->op_private |= OPpASSIGN_COMMON_SCALAR;
17883                 if (l & AAS_PKG_AGG)
17884                     o->op_private |= OPpASSIGN_COMMON_AGG;
17885             }
17886             else if (l & ( AAS_MY_SCALAR|AAS_MY_AGG
17887                           |AAS_LEX_SCALAR|AAS_LEX_AGG))
17888             {
17889                 /* LHS contains only lexicals and safe ops */
17890
17891                 if (l & (AAS_MY_AGG|AAS_LEX_AGG))
17892                     o->op_private |= OPpASSIGN_COMMON_AGG;
17893
17894                 if (l & (AAS_MY_SCALAR|AAS_LEX_SCALAR)) {
17895                     if (lr & AAS_LEX_SCALAR_COMM)
17896                         o->op_private |= OPpASSIGN_COMMON_SCALAR;
17897                     else if (   !(l & AAS_LEX_SCALAR)
17898                              && (r & AAS_DEFAV))
17899                     {
17900                         /* falsely mark
17901                          *    my (...) = @_
17902                          * as scalar-safe for performance reasons.
17903                          * (it will still have been marked _AGG if necessary */
17904                         NOOP;
17905                     }
17906                     else if (r  & (AAS_PKG_SCALAR|AAS_PKG_AGG|AAS_DANGEROUS))
17907                         /* if there are only lexicals on the LHS and no
17908                          * common ones on the RHS, then we assume that the
17909                          * only way those lexicals could also get
17910                          * on the RHS is via some sort of dereffing or
17911                          * closure, e.g.
17912                          *    $r = \$lex;
17913                          *    ($lex, $x) = (1, $$r)
17914                          * and in this case we assume the var must have
17915                          *  a bumped ref count. So if its ref count is 1,
17916                          *  it must only be on the LHS.
17917                          */
17918                         o->op_private |= OPpASSIGN_COMMON_RC1;
17919                 }
17920             }
17921
17922             /* ... = ($x)
17923              * may have to handle aggregate on LHS, but we can't
17924              * have common scalars. */
17925             if (rscalars < 2)
17926                 o->op_private &=
17927                         ~(OPpASSIGN_COMMON_SCALAR|OPpASSIGN_COMMON_RC1);
17928
17929             if ((o->op_flags & OPf_WANT) == OPf_WANT_SCALAR)
17930                 S_check_for_bool_cxt(o, 1, OPpASSIGN_TRUEBOOL, 0);
17931             break;
17932         }
17933
17934         case OP_REF:
17935             /* see if ref() is used in boolean context */
17936             if ((o->op_flags & OPf_WANT) == OPf_WANT_SCALAR)
17937                 S_check_for_bool_cxt(o, 1, OPpTRUEBOOL, OPpMAYBE_TRUEBOOL);
17938             break;
17939
17940         case OP_LENGTH:
17941             /* see if the op is used in known boolean context,
17942              * but not if OA_TARGLEX optimisation is enabled */
17943             if (   (o->op_flags & OPf_WANT) == OPf_WANT_SCALAR
17944                 && !(o->op_private & OPpTARGET_MY)
17945             )
17946                 S_check_for_bool_cxt(o, 1, OPpTRUEBOOL, 0);
17947             break;
17948
17949         case OP_POS:
17950             /* see if the op is used in known boolean context */
17951             if ((o->op_flags & OPf_WANT) == OPf_WANT_SCALAR)
17952                 S_check_for_bool_cxt(o, 1, OPpTRUEBOOL, 0);
17953             break;
17954
17955         case OP_CUSTOM: {
17956             Perl_cpeep_t cpeep =
17957                 XopENTRYCUSTOM(o, xop_peep);
17958             if (cpeep)
17959                 cpeep(aTHX_ o, oldop);
17960             break;
17961         }
17962
17963         }
17964         /* did we just null the current op? If so, re-process it to handle
17965          * eliding "empty" ops from the chain */
17966         if (o->op_type == OP_NULL && oldop && oldop->op_next == o) {
17967             o->op_opt = 0;
17968             o = oldop;
17969         }
17970         else {
17971             oldoldop = oldop;
17972             oldop = o;
17973         }
17974     }
17975     LEAVE;
17976 }
17977
17978 void
17979 Perl_peep(pTHX_ OP *o)
17980 {
17981     CALL_RPEEP(o);
17982 }
17983
17984 /*
17985 =for apidoc_section Custom Operators
17986
17987 =for apidoc Perl_custom_op_xop
17988 Return the XOP structure for a given custom op.  This macro should be
17989 considered internal to C<OP_NAME> and the other access macros: use them instead.
17990 This macro does call a function.  Prior
17991 to 5.19.6, this was implemented as a
17992 function.
17993
17994 =cut
17995 */
17996
17997
17998 /* use PERL_MAGIC_ext to call a function to free the xop structure when
17999  * freeing PL_custom_ops */
18000
18001 static int
18002 custom_op_register_free(pTHX_ SV *sv, MAGIC *mg)
18003 {
18004     XOP *xop;
18005
18006     PERL_UNUSED_ARG(mg);
18007     xop = INT2PTR(XOP *, SvIV(sv));
18008     Safefree(xop->xop_name);
18009     Safefree(xop->xop_desc);
18010     Safefree(xop);
18011     return 0;
18012 }
18013
18014
18015 static const MGVTBL custom_op_register_vtbl = {
18016     0,                          /* get */
18017     0,                          /* set */
18018     0,                          /* len */
18019     0,                          /* clear */
18020     custom_op_register_free,     /* free */
18021     0,                          /* copy */
18022     0,                          /* dup */
18023 #ifdef MGf_LOCAL
18024     0,                          /* local */
18025 #endif
18026 };
18027
18028
18029 XOPRETANY
18030 Perl_custom_op_get_field(pTHX_ const OP *o, const xop_flags_enum field)
18031 {
18032     SV *keysv;
18033     HE *he = NULL;
18034     XOP *xop;
18035
18036     static const XOP xop_null = { 0, 0, 0, 0, 0 };
18037
18038     PERL_ARGS_ASSERT_CUSTOM_OP_GET_FIELD;
18039     assert(o->op_type == OP_CUSTOM);
18040
18041     /* This is wrong. It assumes a function pointer can be cast to IV,
18042      * which isn't guaranteed, but this is what the old custom OP code
18043      * did. In principle it should be safer to Copy the bytes of the
18044      * pointer into a PV: since the new interface is hidden behind
18045      * functions, this can be changed later if necessary.  */
18046     /* Change custom_op_xop if this ever happens */
18047     keysv = sv_2mortal(newSViv(PTR2IV(o->op_ppaddr)));
18048
18049     if (PL_custom_ops)
18050         he = hv_fetch_ent(PL_custom_ops, keysv, 0, 0);
18051
18052     /* See if the op isn't registered, but its name *is* registered.
18053      * That implies someone is using the pre-5.14 API,where only name and
18054      * description could be registered. If so, fake up a real
18055      * registration.
18056      * We only check for an existing name, and assume no one will have
18057      * just registered a desc */
18058     if (!he && PL_custom_op_names &&
18059         (he = hv_fetch_ent(PL_custom_op_names, keysv, 0, 0))
18060     ) {
18061         const char *pv;
18062         STRLEN l;
18063
18064         /* XXX does all this need to be shared mem? */
18065         Newxz(xop, 1, XOP);
18066         pv = SvPV(HeVAL(he), l);
18067         XopENTRY_set(xop, xop_name, savepvn(pv, l));
18068         if (PL_custom_op_descs &&
18069             (he = hv_fetch_ent(PL_custom_op_descs, keysv, 0, 0))
18070         ) {
18071             pv = SvPV(HeVAL(he), l);
18072             XopENTRY_set(xop, xop_desc, savepvn(pv, l));
18073         }
18074         Perl_custom_op_register(aTHX_ o->op_ppaddr, xop);
18075         he = hv_fetch_ent(PL_custom_ops, keysv, 0, 0);
18076         /* add magic to the SV so that the xop struct (pointed to by
18077          * SvIV(sv)) is freed. Normally a static xop is registered, but
18078          * for this backcompat hack, we've alloced one */
18079         (void)sv_magicext(HeVAL(he), NULL, PERL_MAGIC_ext,
18080                 &custom_op_register_vtbl, NULL, 0);
18081
18082     }
18083     else {
18084         if (!he)
18085             xop = (XOP *)&xop_null;
18086         else
18087             xop = INT2PTR(XOP *, SvIV(HeVAL(he)));
18088     }
18089     {
18090         XOPRETANY any;
18091         if(field == XOPe_xop_ptr) {
18092             any.xop_ptr = xop;
18093         } else {
18094             const U32 flags = XopFLAGS(xop);
18095             if(flags & field) {
18096                 switch(field) {
18097                 case XOPe_xop_name:
18098                     any.xop_name = xop->xop_name;
18099                     break;
18100                 case XOPe_xop_desc:
18101                     any.xop_desc = xop->xop_desc;
18102                     break;
18103                 case XOPe_xop_class:
18104                     any.xop_class = xop->xop_class;
18105                     break;
18106                 case XOPe_xop_peep:
18107                     any.xop_peep = xop->xop_peep;
18108                     break;
18109                 default:
18110                     NOT_REACHED; /* NOTREACHED */
18111                     break;
18112                 }
18113             } else {
18114                 switch(field) {
18115                 case XOPe_xop_name:
18116                     any.xop_name = XOPd_xop_name;
18117                     break;
18118                 case XOPe_xop_desc:
18119                     any.xop_desc = XOPd_xop_desc;
18120                     break;
18121                 case XOPe_xop_class:
18122                     any.xop_class = XOPd_xop_class;
18123                     break;
18124                 case XOPe_xop_peep:
18125                     any.xop_peep = XOPd_xop_peep;
18126                     break;
18127                 default:
18128                     NOT_REACHED; /* NOTREACHED */
18129                     break;
18130                 }
18131             }
18132         }
18133         /* On some platforms (HP-UX, IA64) gcc emits a warning for this function:
18134          * op.c: In function 'Perl_custom_op_get_field':
18135          * op.c:...: warning: 'any.xop_name' may be used uninitialized in this function [-Wmaybe-uninitialized]
18136          * This is because on those platforms (with -DEBUGGING) NOT_REACHED
18137          * expands to assert(0), which expands to ((0) ? (void)0 :
18138          * __assert(...)), and gcc doesn't know that __assert can never return. */
18139         return any;
18140     }
18141 }
18142
18143 /*
18144 =for apidoc custom_op_register
18145 Register a custom op.  See L<perlguts/"Custom Operators">.
18146
18147 =cut
18148 */
18149
18150 void
18151 Perl_custom_op_register(pTHX_ Perl_ppaddr_t ppaddr, const XOP *xop)
18152 {
18153     SV *keysv;
18154
18155     PERL_ARGS_ASSERT_CUSTOM_OP_REGISTER;
18156
18157     /* see the comment in custom_op_xop */
18158     keysv = sv_2mortal(newSViv(PTR2IV(ppaddr)));
18159
18160     if (!PL_custom_ops)
18161         PL_custom_ops = newHV();
18162
18163     if (!hv_store_ent(PL_custom_ops, keysv, newSViv(PTR2IV(xop)), 0))
18164         Perl_croak(aTHX_ "panic: can't register custom OP %s", xop->xop_name);
18165 }
18166
18167 /*
18168
18169 =for apidoc core_prototype
18170
18171 This function assigns the prototype of the named core function to C<sv>, or
18172 to a new mortal SV if C<sv> is C<NULL>.  It returns the modified C<sv>, or
18173 C<NULL> if the core function has no prototype.  C<code> is a code as returned
18174 by C<keyword()>.  It must not be equal to 0.
18175
18176 =cut
18177 */
18178
18179 SV *
18180 Perl_core_prototype(pTHX_ SV *sv, const char *name, const int code,
18181                           int * const opnum)
18182 {
18183     int i = 0, n = 0, seen_question = 0, defgv = 0;
18184     I32 oa;
18185 #define MAX_ARGS_OP ((sizeof(I32) - 1) * 2)
18186     char str[ MAX_ARGS_OP * 2 + 2 ]; /* One ';', one '\0' */
18187     bool nullret = FALSE;
18188
18189     PERL_ARGS_ASSERT_CORE_PROTOTYPE;
18190
18191     assert (code);
18192
18193     if (!sv) sv = sv_newmortal();
18194
18195 #define retsetpvs(x,y) sv_setpvs(sv, x); if(opnum) *opnum=(y); return sv
18196
18197     switch (code < 0 ? -code : code) {
18198     case KEY_and   : case KEY_chop: case KEY_chomp:
18199     case KEY_cmp   : case KEY_defined: case KEY_delete: case KEY_exec  :
18200     case KEY_exists: case KEY_eq     : case KEY_ge    : case KEY_goto  :
18201     case KEY_grep  : case KEY_gt     : case KEY_last  : case KEY_le    :
18202     case KEY_lt    : case KEY_map    : case KEY_ne    : case KEY_next  :
18203     case KEY_or    : case KEY_print  : case KEY_printf: case KEY_qr    :
18204     case KEY_redo  : case KEY_require: case KEY_return: case KEY_say   :
18205     case KEY_select: case KEY_sort   : case KEY_split : case KEY_system:
18206     case KEY_x     : case KEY_xor    :
18207         if (!opnum) return NULL; nullret = TRUE; goto findopnum;
18208     case KEY_glob:    retsetpvs("_;", OP_GLOB);
18209     case KEY_keys:    retsetpvs("\\[%@]", OP_KEYS);
18210     case KEY_values:  retsetpvs("\\[%@]", OP_VALUES);
18211     case KEY_each:    retsetpvs("\\[%@]", OP_EACH);
18212     case KEY_pos:     retsetpvs(";\\[$*]", OP_POS);
18213     case KEY___FILE__: case KEY___LINE__: case KEY___PACKAGE__:
18214         retsetpvs("", 0);
18215     case KEY_evalbytes:
18216         name = "entereval"; break;
18217     case KEY_readpipe:
18218         name = "backtick";
18219     }
18220
18221 #undef retsetpvs
18222
18223   findopnum:
18224     while (i < MAXO) {  /* The slow way. */
18225         if (strEQ(name, PL_op_name[i])
18226             || strEQ(name, PL_op_desc[i]))
18227         {
18228             if (nullret) { assert(opnum); *opnum = i; return NULL; }
18229             goto found;
18230         }
18231         i++;
18232     }
18233     return NULL;
18234   found:
18235     defgv = PL_opargs[i] & OA_DEFGV;
18236     oa = PL_opargs[i] >> OASHIFT;
18237     while (oa) {
18238         if (oa & OA_OPTIONAL && !seen_question && (
18239               !defgv || (oa & (OA_OPTIONAL - 1)) == OA_FILEREF
18240         )) {
18241             seen_question = 1;
18242             str[n++] = ';';
18243         }
18244         if ((oa & (OA_OPTIONAL - 1)) >= OA_AVREF
18245             && (oa & (OA_OPTIONAL - 1)) <= OA_SCALARREF
18246             /* But globs are already references (kinda) */
18247             && (oa & (OA_OPTIONAL - 1)) != OA_FILEREF
18248         ) {
18249             str[n++] = '\\';
18250         }
18251         if ((oa & (OA_OPTIONAL - 1)) == OA_SCALARREF
18252          && !scalar_mod_type(NULL, i)) {
18253             str[n++] = '[';
18254             str[n++] = '$';
18255             str[n++] = '@';
18256             str[n++] = '%';
18257             if (i == OP_LOCK || i == OP_UNDEF) str[n++] = '&';
18258             str[n++] = '*';
18259             str[n++] = ']';
18260         }
18261         else str[n++] = ("?$@@%&*$")[oa & (OA_OPTIONAL - 1)];
18262         if (oa & OA_OPTIONAL && defgv && str[n-1] == '$') {
18263             str[n-1] = '_'; defgv = 0;
18264         }
18265         oa = oa >> 4;
18266     }
18267     if (code == -KEY_not || code == -KEY_getprotobynumber) str[n++] = ';';
18268     str[n++] = '\0';
18269     sv_setpvn(sv, str, n - 1);
18270     if (opnum) *opnum = i;
18271     return sv;
18272 }
18273
18274 OP *
18275 Perl_coresub_op(pTHX_ SV * const coreargssv, const int code,
18276                       const int opnum)
18277 {
18278     OP * const argop = (opnum == OP_SELECT && code) ? NULL :
18279                                         newSVOP(OP_COREARGS,0,coreargssv);
18280     OP *o;
18281
18282     PERL_ARGS_ASSERT_CORESUB_OP;
18283
18284     switch(opnum) {
18285     case 0:
18286         return op_append_elem(OP_LINESEQ,
18287                        argop,
18288                        newSLICEOP(0,
18289                                   newSVOP(OP_CONST, 0, newSViv(-code % 3)),
18290                                   newOP(OP_CALLER,0)
18291                        )
18292                );
18293     case OP_EACH:
18294     case OP_KEYS:
18295     case OP_VALUES:
18296         o = newUNOP(OP_AVHVSWITCH,0,argop);
18297         o->op_private = opnum-OP_EACH;
18298         return o;
18299     case OP_SELECT: /* which represents OP_SSELECT as well */
18300         if (code)
18301             return newCONDOP(
18302                          0,
18303                          newBINOP(OP_GT, 0,
18304                                   newAVREF(newGVOP(OP_GV, 0, PL_defgv)),
18305                                   newSVOP(OP_CONST, 0, newSVuv(1))
18306                                  ),
18307                          coresub_op(newSVuv((UV)OP_SSELECT), 0,
18308                                     OP_SSELECT),
18309                          coresub_op(coreargssv, 0, OP_SELECT)
18310                    );
18311         /* FALLTHROUGH */
18312     default:
18313         switch (PL_opargs[opnum] & OA_CLASS_MASK) {
18314         case OA_BASEOP:
18315             return op_append_elem(
18316                         OP_LINESEQ, argop,
18317                         newOP(opnum,
18318                               opnum == OP_WANTARRAY || opnum == OP_RUNCV
18319                                 ? OPpOFFBYONE << 8 : 0)
18320                    );
18321         case OA_BASEOP_OR_UNOP:
18322             if (opnum == OP_ENTEREVAL) {
18323                 o = newUNOP(OP_ENTEREVAL,OPpEVAL_COPHH<<8,argop);
18324                 if (code == -KEY_evalbytes) o->op_private |= OPpEVAL_BYTES;
18325             }
18326             else o = newUNOP(opnum,0,argop);
18327             if (opnum == OP_CALLER) o->op_private |= OPpOFFBYONE;
18328             else {
18329           onearg:
18330               if (is_handle_constructor(o, 1))
18331                 argop->op_private |= OPpCOREARGS_DEREF1;
18332               if (scalar_mod_type(NULL, opnum))
18333                 argop->op_private |= OPpCOREARGS_SCALARMOD;
18334             }
18335             return o;
18336         default:
18337             o = op_convert_list(opnum,OPf_SPECIAL*(opnum == OP_GLOB),argop);
18338             if (is_handle_constructor(o, 2))
18339                 argop->op_private |= OPpCOREARGS_DEREF2;
18340             if (opnum == OP_SUBSTR) {
18341                 o->op_private |= OPpMAYBE_LVSUB;
18342                 return o;
18343             }
18344             else goto onearg;
18345         }
18346     }
18347 }
18348
18349 void
18350 Perl_report_redefined_cv(pTHX_ const SV *name, const CV *old_cv,
18351                                SV * const *new_const_svp)
18352 {
18353     const char *hvname;
18354     bool is_const = !!CvCONST(old_cv);
18355     SV *old_const_sv = is_const ? cv_const_sv(old_cv) : NULL;
18356
18357     PERL_ARGS_ASSERT_REPORT_REDEFINED_CV;
18358
18359     if (is_const && new_const_svp && old_const_sv == *new_const_svp)
18360         return;
18361         /* They are 2 constant subroutines generated from
18362            the same constant. This probably means that
18363            they are really the "same" proxy subroutine
18364            instantiated in 2 places. Most likely this is
18365            when a constant is exported twice.  Don't warn.
18366         */
18367     if (
18368         (ckWARN(WARN_REDEFINE)
18369          && !(
18370                 CvGV(old_cv) && GvSTASH(CvGV(old_cv))
18371              && HvNAMELEN(GvSTASH(CvGV(old_cv))) == 7
18372              && (hvname = HvNAME(GvSTASH(CvGV(old_cv))),
18373                  strEQ(hvname, "autouse"))
18374              )
18375         )
18376      || (is_const
18377          && ckWARN_d(WARN_REDEFINE)
18378          && (!new_const_svp || sv_cmp(old_const_sv, *new_const_svp))
18379         )
18380     )
18381         Perl_warner(aTHX_ packWARN(WARN_REDEFINE),
18382                           is_const
18383                             ? "Constant subroutine %" SVf " redefined"
18384                             : "Subroutine %" SVf " redefined",
18385                           SVfARG(name));
18386 }
18387
18388 /*
18389 =for apidoc_section Hook manipulation
18390
18391 These functions provide convenient and thread-safe means of manipulating
18392 hook variables.
18393
18394 =cut
18395 */
18396
18397 /*
18398 =for apidoc wrap_op_checker
18399
18400 Puts a C function into the chain of check functions for a specified op
18401 type.  This is the preferred way to manipulate the L</PL_check> array.
18402 C<opcode> specifies which type of op is to be affected.  C<new_checker>
18403 is a pointer to the C function that is to be added to that opcode's
18404 check chain, and C<old_checker_p> points to the storage location where a
18405 pointer to the next function in the chain will be stored.  The value of
18406 C<new_checker> is written into the L</PL_check> array, while the value
18407 previously stored there is written to C<*old_checker_p>.
18408
18409 L</PL_check> is global to an entire process, and a module wishing to
18410 hook op checking may find itself invoked more than once per process,
18411 typically in different threads.  To handle that situation, this function
18412 is idempotent.  The location C<*old_checker_p> must initially (once
18413 per process) contain a null pointer.  A C variable of static duration
18414 (declared at file scope, typically also marked C<static> to give
18415 it internal linkage) will be implicitly initialised appropriately,
18416 if it does not have an explicit initialiser.  This function will only
18417 actually modify the check chain if it finds C<*old_checker_p> to be null.
18418 This function is also thread safe on the small scale.  It uses appropriate
18419 locking to avoid race conditions in accessing L</PL_check>.
18420
18421 When this function is called, the function referenced by C<new_checker>
18422 must be ready to be called, except for C<*old_checker_p> being unfilled.
18423 In a threading situation, C<new_checker> may be called immediately,
18424 even before this function has returned.  C<*old_checker_p> will always
18425 be appropriately set before C<new_checker> is called.  If C<new_checker>
18426 decides not to do anything special with an op that it is given (which
18427 is the usual case for most uses of op check hooking), it must chain the
18428 check function referenced by C<*old_checker_p>.
18429
18430 Taken all together, XS code to hook an op checker should typically look
18431 something like this:
18432
18433     static Perl_check_t nxck_frob;
18434     static OP *myck_frob(pTHX_ OP *op) {
18435         ...
18436         op = nxck_frob(aTHX_ op);
18437         ...
18438         return op;
18439     }
18440     BOOT:
18441         wrap_op_checker(OP_FROB, myck_frob, &nxck_frob);
18442
18443 If you want to influence compilation of calls to a specific subroutine,
18444 then use L</cv_set_call_checker_flags> rather than hooking checking of
18445 all C<entersub> ops.
18446
18447 =cut
18448 */
18449
18450 void
18451 Perl_wrap_op_checker(pTHX_ Optype opcode,
18452     Perl_check_t new_checker, Perl_check_t *old_checker_p)
18453 {
18454
18455     PERL_UNUSED_CONTEXT;
18456     PERL_ARGS_ASSERT_WRAP_OP_CHECKER;
18457     if (*old_checker_p) return;
18458     OP_CHECK_MUTEX_LOCK;
18459     if (!*old_checker_p) {
18460         *old_checker_p = PL_check[opcode];
18461         PL_check[opcode] = new_checker;
18462     }
18463     OP_CHECK_MUTEX_UNLOCK;
18464 }
18465
18466 #include "XSUB.h"
18467
18468 /* Efficient sub that returns a constant scalar value. */
18469 static void
18470 const_sv_xsub(pTHX_ CV* cv)
18471 {
18472     dXSARGS;
18473     SV *const sv = MUTABLE_SV(XSANY.any_ptr);
18474     PERL_UNUSED_ARG(items);
18475     if (!sv) {
18476         XSRETURN(0);
18477     }
18478     EXTEND(sp, 1);
18479     ST(0) = sv;
18480     XSRETURN(1);
18481 }
18482
18483 static void
18484 const_av_xsub(pTHX_ CV* cv)
18485 {
18486     dXSARGS;
18487     AV * const av = MUTABLE_AV(XSANY.any_ptr);
18488     SP -= items;
18489     assert(av);
18490 #ifndef DEBUGGING
18491     if (!av) {
18492         XSRETURN(0);
18493     }
18494 #endif
18495     if (SvRMAGICAL(av))
18496         Perl_croak(aTHX_ "Magical list constants are not supported");
18497     if (GIMME_V != G_ARRAY) {
18498         EXTEND(SP, 1);
18499         ST(0) = sv_2mortal(newSViv((IV)AvFILLp(av)+1));
18500         XSRETURN(1);
18501     }
18502     EXTEND(SP, AvFILLp(av)+1);
18503     Copy(AvARRAY(av), &ST(0), AvFILLp(av)+1, SV *);
18504     XSRETURN(AvFILLp(av)+1);
18505 }
18506
18507 /* Copy an existing cop->cop_warnings field.
18508  * If it's one of the standard addresses, just re-use the address.
18509  * This is the e implementation for the DUP_WARNINGS() macro
18510  */
18511
18512 STRLEN*
18513 Perl_dup_warnings(pTHX_ STRLEN* warnings)
18514 {
18515     Size_t size;
18516     STRLEN *new_warnings;
18517
18518     if (warnings == NULL || specialWARN(warnings))
18519         return warnings;
18520
18521     size = sizeof(*warnings) + *warnings;
18522
18523     new_warnings = (STRLEN*)PerlMemShared_malloc(size);
18524     Copy(warnings, new_warnings, size, char);
18525     return new_warnings;
18526 }
18527
18528 /*
18529  * ex: set ts=8 sts=4 sw=4 et:
18530  */