This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Also join the 'else if'
[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 /* make freed ops die if they're inadvertently executed */
471 #ifdef DEBUGGING
472 static OP *
473 S_pp_freed(pTHX)
474 {
475     DIE(aTHX_ "panic: freed op 0x%p called\n", PL_op);
476 }
477 #endif
478
479
480 /* Return the block of memory used by an op to the free list of
481  * the OP slab associated with that op.
482  */
483
484 void
485 Perl_Slab_Free(pTHX_ void *op)
486 {
487     OP * const o = (OP *)op;
488     OPSLAB *slab;
489
490     PERL_ARGS_ASSERT_SLAB_FREE;
491
492 #ifdef DEBUGGING
493     o->op_ppaddr = S_pp_freed;
494 #endif
495
496     if (!o->op_slabbed) {
497         if (!o->op_static)
498             PerlMemShared_free(op);
499         return;
500     }
501
502     slab = OpSLAB(o);
503     /* If this op is already freed, our refcount will get screwy. */
504     assert(o->op_type != OP_FREED);
505     o->op_type = OP_FREED;
506     link_freed_op(slab, o);
507     DEBUG_S_warn((aTHX_ "freeing    op at %p, slab %p, head slab %p",
508         (void*)o, (void *)OpMySLAB(o), (void*)slab));
509     OpslabREFCNT_dec_padok(slab);
510 }
511
512 void
513 Perl_opslab_free_nopad(pTHX_ OPSLAB *slab)
514 {
515     const bool havepad = !!PL_comppad;
516     PERL_ARGS_ASSERT_OPSLAB_FREE_NOPAD;
517     if (havepad) {
518         ENTER;
519         PAD_SAVE_SETNULLPAD();
520     }
521     opslab_free(slab);
522     if (havepad) LEAVE;
523 }
524
525 /* Free a chain of OP slabs. Should only be called after all ops contained
526  * in it have been freed. At this point, its reference count should be 1,
527  * because OpslabREFCNT_dec() skips doing rc-- when it detects that rc == 1,
528  * and just directly calls opslab_free().
529  * (Note that the reference count which PL_compcv held on the slab should
530  * have been removed once compilation of the sub was complete).
531  *
532  *
533  */
534
535 void
536 Perl_opslab_free(pTHX_ OPSLAB *slab)
537 {
538     OPSLAB *slab2;
539     PERL_ARGS_ASSERT_OPSLAB_FREE;
540     PERL_UNUSED_CONTEXT;
541     DEBUG_S_warn((aTHX_ "freeing slab %p", (void*)slab));
542     assert(slab->opslab_refcnt == 1);
543     PerlMemShared_free(slab->opslab_freed);
544     do {
545         slab2 = slab->opslab_next;
546 #ifdef DEBUGGING
547         slab->opslab_refcnt = ~(size_t)0;
548 #endif
549 #ifdef PERL_DEBUG_READONLY_OPS
550         DEBUG_m(PerlIO_printf(Perl_debug_log, "Deallocate slab at %p\n",
551                                                (void*)slab));
552         if (munmap(slab, OpSLABSizeBytes(slab->opslab_size))) {
553             perror("munmap failed");
554             abort();
555         }
556 #else
557         PerlMemShared_free(slab);
558 #endif
559         slab = slab2;
560     } while (slab);
561 }
562
563 /* like opslab_free(), but first calls op_free() on any ops in the slab
564  * not marked as OP_FREED
565  */
566
567 void
568 Perl_opslab_force_free(pTHX_ OPSLAB *slab)
569 {
570     OPSLAB *slab2;
571 #ifdef DEBUGGING
572     size_t savestack_count = 0;
573 #endif
574     PERL_ARGS_ASSERT_OPSLAB_FORCE_FREE;
575     slab2 = slab;
576     do {
577         OPSLOT *slot = OpSLOToff(slab2, slab2->opslab_free_space);
578         OPSLOT *end  = OpSLOToff(slab2, slab2->opslab_size);
579         for (; slot < end;
580                 slot = (OPSLOT*) ((I32**)slot + slot->opslot_size) )
581         {
582             if (slot->opslot_op.op_type != OP_FREED
583              && !(slot->opslot_op.op_savefree
584 #ifdef DEBUGGING
585                   && ++savestack_count
586 #endif
587                  )
588             ) {
589                 assert(slot->opslot_op.op_slabbed);
590                 op_free(&slot->opslot_op);
591                 if (slab->opslab_refcnt == 1) goto free;
592             }
593         }
594     } while ((slab2 = slab2->opslab_next));
595     /* > 1 because the CV still holds a reference count. */
596     if (slab->opslab_refcnt > 1) { /* still referenced by the savestack */
597 #ifdef DEBUGGING
598         assert(savestack_count == slab->opslab_refcnt-1);
599 #endif
600         /* Remove the CV’s reference count. */
601         slab->opslab_refcnt--;
602         return;
603     }
604    free:
605     opslab_free(slab);
606 }
607
608 #ifdef PERL_DEBUG_READONLY_OPS
609 OP *
610 Perl_op_refcnt_inc(pTHX_ OP *o)
611 {
612     if(o) {
613         OPSLAB *const slab = o->op_slabbed ? OpSLAB(o) : NULL;
614         if (slab && slab->opslab_readonly) {
615             Slab_to_rw(slab);
616             ++o->op_targ;
617             Slab_to_ro(slab);
618         } else {
619             ++o->op_targ;
620         }
621     }
622     return o;
623
624 }
625
626 PADOFFSET
627 Perl_op_refcnt_dec(pTHX_ OP *o)
628 {
629     PADOFFSET result;
630     OPSLAB *const slab = o->op_slabbed ? OpSLAB(o) : NULL;
631
632     PERL_ARGS_ASSERT_OP_REFCNT_DEC;
633
634     if (slab && slab->opslab_readonly) {
635         Slab_to_rw(slab);
636         result = --o->op_targ;
637         Slab_to_ro(slab);
638     } else {
639         result = --o->op_targ;
640     }
641     return result;
642 }
643 #endif
644 /*
645  * In the following definition, the ", (OP*)0" is just to make the compiler
646  * think the expression is of the right type: croak actually does a Siglongjmp.
647  */
648 #define CHECKOP(type,o) \
649     ((PL_op_mask && PL_op_mask[type])                           \
650      ? ( op_free((OP*)o),                                       \
651          Perl_croak(aTHX_ "'%s' trapped by operation mask", PL_op_desc[type]),  \
652          (OP*)0 )                                               \
653      : PL_check[type](aTHX_ (OP*)o))
654
655 #define RETURN_UNLIMITED_NUMBER (PERL_INT_MAX / 2)
656
657 #define OpTYPE_set(o,type) \
658     STMT_START {                                \
659         o->op_type = (OPCODE)type;              \
660         o->op_ppaddr = PL_ppaddr[type];         \
661     } STMT_END
662
663 STATIC OP *
664 S_no_fh_allowed(pTHX_ OP *o)
665 {
666     PERL_ARGS_ASSERT_NO_FH_ALLOWED;
667
668     yyerror(Perl_form(aTHX_ "Missing comma after first argument to %s function",
669                  OP_DESC(o)));
670     return o;
671 }
672
673 STATIC OP *
674 S_too_few_arguments_pv(pTHX_ OP *o, const char* name, U32 flags)
675 {
676     PERL_ARGS_ASSERT_TOO_FEW_ARGUMENTS_PV;
677     yyerror_pv(Perl_form(aTHX_ "Not enough arguments for %s", name), flags);
678     return o;
679 }
680
681 STATIC OP *
682 S_too_many_arguments_pv(pTHX_ OP *o, const char *name, U32 flags)
683 {
684     PERL_ARGS_ASSERT_TOO_MANY_ARGUMENTS_PV;
685
686     yyerror_pv(Perl_form(aTHX_ "Too many arguments for %s", name), flags);
687     return o;
688 }
689
690 STATIC void
691 S_bad_type_pv(pTHX_ I32 n, const char *t, const OP *o, const OP *kid)
692 {
693     PERL_ARGS_ASSERT_BAD_TYPE_PV;
694
695     yyerror_pv(Perl_form(aTHX_ "Type of arg %d to %s must be %s (not %s)",
696                  (int)n, PL_op_desc[(o)->op_type], t, OP_DESC(kid)), 0);
697 }
698
699 STATIC void
700 S_bad_type_gv(pTHX_ I32 n, GV *gv, const OP *kid, const char *t)
701 {
702     SV * const namesv = cv_name((CV *)gv, NULL, 0);
703     PERL_ARGS_ASSERT_BAD_TYPE_GV;
704
705     yyerror_pv(Perl_form(aTHX_ "Type of arg %d to %" SVf " must be %s (not %s)",
706                  (int)n, SVfARG(namesv), t, OP_DESC(kid)), SvUTF8(namesv));
707 }
708
709 STATIC void
710 S_no_bareword_allowed(pTHX_ OP *o)
711 {
712     PERL_ARGS_ASSERT_NO_BAREWORD_ALLOWED;
713
714     qerror(Perl_mess(aTHX_
715                      "Bareword \"%" SVf "\" not allowed while \"strict subs\" in use",
716                      SVfARG(cSVOPo_sv)));
717     o->op_private &= ~OPpCONST_STRICT; /* prevent warning twice about the same OP */
718 }
719
720 void
721 Perl_no_bareword_filehandle(pTHX_ const char *fhname) {
722     PERL_ARGS_ASSERT_NO_BAREWORD_FILEHANDLE;
723
724     if (strNE(fhname, "STDERR")
725         && strNE(fhname, "STDOUT")
726         && strNE(fhname, "STDIN")
727         && strNE(fhname, "_")
728         && strNE(fhname, "ARGV")
729         && strNE(fhname, "ARGVOUT")
730         && strNE(fhname, "DATA")) {
731         qerror(Perl_mess(aTHX_ "Bareword filehandle \"%s\" not allowed under 'no feature \"bareword_filehandles\"'", fhname));
732     }
733 }
734
735 /* "register" allocation */
736
737 PADOFFSET
738 Perl_allocmy(pTHX_ const char *const name, const STRLEN len, const U32 flags)
739 {
740     PADOFFSET off;
741     bool is_idfirst, is_default;
742     const bool is_our = (PL_parser->in_my == KEY_our);
743
744     PERL_ARGS_ASSERT_ALLOCMY;
745
746     if (flags & ~SVf_UTF8)
747         Perl_croak(aTHX_ "panic: allocmy illegal flag bits 0x%" UVxf,
748                    (UV)flags);
749
750     is_idfirst = flags & SVf_UTF8
751         ? isIDFIRST_utf8_safe((U8*)name + 1, name + len)
752         : isIDFIRST_A(name[1]);
753
754     /* $_, @_, etc. */
755     is_default = len == 2 && name[1] == '_';
756
757     /* complain about "my $<special_var>" etc etc */
758     if (!is_our && (!is_idfirst || is_default)) {
759         const char * const type =
760               PL_parser->in_my == KEY_sigvar ? "subroutine signature" :
761               PL_parser->in_my == KEY_state  ? "\"state\""     : "\"my\"";
762
763         if (!(flags & SVf_UTF8 && UTF8_IS_START(name[1]))
764          && isASCII(name[1])
765          && (!isPRINT(name[1]) || memCHRs("\t\n\r\f", name[1]))) {
766             /* diag_listed_as: Can't use global %s in %s */
767             yyerror(Perl_form(aTHX_ "Can't use global %c^%c%.*s in %s",
768                               name[0], toCTRL(name[1]),
769                               (int)(len - 2), name + 2,
770                               type));
771         } else {
772             yyerror_pv(Perl_form(aTHX_ "Can't use global %.*s in %s",
773                               (int) len, name,
774                               type), flags & SVf_UTF8);
775         }
776     }
777
778     /* allocate a spare slot and store the name in that slot */
779
780     off = pad_add_name_pvn(name, len,
781                        (is_our ? padadd_OUR :
782                         PL_parser->in_my == KEY_state ? padadd_STATE : 0),
783                     PL_parser->in_my_stash,
784                     (is_our
785                         /* $_ is always in main::, even with our */
786                         ? (PL_curstash && !memEQs(name,len,"$_")
787                             ? PL_curstash
788                             : PL_defstash)
789                         : NULL
790                     )
791     );
792     /* anon sub prototypes contains state vars should always be cloned,
793      * otherwise the state var would be shared between anon subs */
794
795     if (PL_parser->in_my == KEY_state && CvANON(PL_compcv))
796         CvCLONE_on(PL_compcv);
797
798     return off;
799 }
800
801 /*
802 =for apidoc_section $optree_manipulation
803
804 =for apidoc alloccopstash
805
806 Available only under threaded builds, this function allocates an entry in
807 C<PL_stashpad> for the stash passed to it.
808
809 =cut
810 */
811
812 #ifdef USE_ITHREADS
813 PADOFFSET
814 Perl_alloccopstash(pTHX_ HV *hv)
815 {
816     PADOFFSET off = 0, o = 1;
817     bool found_slot = FALSE;
818
819     PERL_ARGS_ASSERT_ALLOCCOPSTASH;
820
821     if (PL_stashpad[PL_stashpadix] == hv) return PL_stashpadix;
822
823     for (; o < PL_stashpadmax; ++o) {
824         if (PL_stashpad[o] == hv) return PL_stashpadix = o;
825         if (!PL_stashpad[o] || SvTYPE(PL_stashpad[o]) != SVt_PVHV)
826             found_slot = TRUE, off = o;
827     }
828     if (!found_slot) {
829         Renew(PL_stashpad, PL_stashpadmax + 10, HV *);
830         Zero(PL_stashpad + PL_stashpadmax, 10, HV *);
831         off = PL_stashpadmax;
832         PL_stashpadmax += 10;
833     }
834
835     PL_stashpad[PL_stashpadix = off] = hv;
836     return off;
837 }
838 #endif
839
840 /* free the body of an op without examining its contents.
841  * Always use this rather than FreeOp directly */
842
843 static void
844 S_op_destroy(pTHX_ OP *o)
845 {
846     FreeOp(o);
847 }
848
849 /* Destructor */
850
851 /*
852 =for apidoc op_free
853
854 Free an op and its children. Only use this when an op is no longer linked
855 to from any optree.
856
857 =cut
858 */
859
860 void
861 Perl_op_free(pTHX_ OP *o)
862 {
863     OPCODE type;
864     OP *top_op = o;
865     OP *next_op = o;
866     bool went_up = FALSE; /* whether we reached the current node by
867                             following the parent pointer from a child, and
868                             so have already seen this node */
869
870     if (!o || o->op_type == OP_FREED)
871         return;
872
873     if (o->op_private & OPpREFCOUNTED) {
874         /* if base of tree is refcounted, just decrement */
875         switch (o->op_type) {
876         case OP_LEAVESUB:
877         case OP_LEAVESUBLV:
878         case OP_LEAVEEVAL:
879         case OP_LEAVE:
880         case OP_SCOPE:
881         case OP_LEAVEWRITE:
882             {
883                 PADOFFSET refcnt;
884                 OP_REFCNT_LOCK;
885                 refcnt = OpREFCNT_dec(o);
886                 OP_REFCNT_UNLOCK;
887                 if (refcnt) {
888                     /* Need to find and remove any pattern match ops from
889                      * the list we maintain for reset().  */
890                     find_and_forget_pmops(o);
891                     return;
892                 }
893             }
894             break;
895         default:
896             break;
897         }
898     }
899
900     while (next_op) {
901         o = next_op;
902
903         /* free child ops before ourself, (then free ourself "on the
904          * way back up") */
905
906         if (!went_up && o->op_flags & OPf_KIDS) {
907             next_op = cUNOPo->op_first;
908             continue;
909         }
910
911         /* find the next node to visit, *then* free the current node
912          * (can't rely on o->op_* fields being valid after o has been
913          * freed) */
914
915         /* The next node to visit will be either the sibling, or the
916          * parent if no siblings left, or NULL if we've worked our way
917          * back up to the top node in the tree */
918         next_op = (o == top_op) ? NULL : o->op_sibparent;
919         went_up = cBOOL(!OpHAS_SIBLING(o)); /* parents are already visited */
920
921         /* Now process the current node */
922
923         /* Though ops may be freed twice, freeing the op after its slab is a
924            big no-no. */
925         assert(!o->op_slabbed || OpSLAB(o)->opslab_refcnt != ~(size_t)0);
926         /* During the forced freeing of ops after compilation failure, kidops
927            may be freed before their parents. */
928         if (!o || o->op_type == OP_FREED)
929             continue;
930
931         type = o->op_type;
932
933         /* an op should only ever acquire op_private flags that we know about.
934          * If this fails, you may need to fix something in regen/op_private.
935          * Don't bother testing if:
936          *   * the op_ppaddr doesn't match the op; someone may have
937          *     overridden the op and be doing strange things with it;
938          *   * we've errored, as op flags are often left in an
939          *     inconsistent state then. Note that an error when
940          *     compiling the main program leaves PL_parser NULL, so
941          *     we can't spot faults in the main code, only
942          *     evaled/required code;
943          *   * it's a banned op - we may be croaking before the op is
944          *     fully formed. - see CHECKOP. */
945 #ifdef DEBUGGING
946         if (   o->op_ppaddr == PL_ppaddr[type]
947             && PL_parser
948             && !PL_parser->error_count
949             && !(PL_op_mask && PL_op_mask[type])
950         )
951         {
952             assert(!(o->op_private & ~PL_op_private_valid[type]));
953         }
954 #endif
955
956
957         /* Call the op_free hook if it has been set. Do it now so that it's called
958          * at the right time for refcounted ops, but still before all of the kids
959          * are freed. */
960         CALL_OPFREEHOOK(o);
961
962         if (type == OP_NULL)
963             type = (OPCODE)o->op_targ;
964
965         if (o->op_slabbed)
966             Slab_to_rw(OpSLAB(o));
967
968         /* COP* is not cleared by op_clear() so that we may track line
969          * numbers etc even after null() */
970         if (type == OP_NEXTSTATE || type == OP_DBSTATE) {
971             cop_free((COP*)o);
972         }
973
974         op_clear(o);
975         FreeOp(o);
976         if (PL_op == o)
977             PL_op = NULL;
978     }
979 }
980
981
982 /* S_op_clear_gv(): free a GV attached to an OP */
983
984 STATIC
985 #ifdef USE_ITHREADS
986 void S_op_clear_gv(pTHX_ OP *o, PADOFFSET *ixp)
987 #else
988 void S_op_clear_gv(pTHX_ OP *o, SV**svp)
989 #endif
990 {
991
992     GV *gv = (o->op_type == OP_GV || o->op_type == OP_GVSV
993             || o->op_type == OP_MULTIDEREF)
994 #ifdef USE_ITHREADS
995                 && PL_curpad
996                 ? ((GV*)PAD_SVl(*ixp)) : NULL;
997 #else
998                 ? (GV*)(*svp) : NULL;
999 #endif
1000     /* It's possible during global destruction that the GV is freed
1001        before the optree. Whilst the SvREFCNT_inc is happy to bump from
1002        0 to 1 on a freed SV, the corresponding SvREFCNT_dec from 1 to 0
1003        will trigger an assertion failure, because the entry to sv_clear
1004        checks that the scalar is not already freed.  A check of for
1005        !SvIS_FREED(gv) turns out to be invalid, because during global
1006        destruction the reference count can be forced down to zero
1007        (with SVf_BREAK set).  In which case raising to 1 and then
1008        dropping to 0 triggers cleanup before it should happen.  I
1009        *think* that this might actually be a general, systematic,
1010        weakness of the whole idea of SVf_BREAK, in that code *is*
1011        allowed to raise and lower references during global destruction,
1012        so any *valid* code that happens to do this during global
1013        destruction might well trigger premature cleanup.  */
1014     bool still_valid = gv && SvREFCNT(gv);
1015
1016     if (still_valid)
1017         SvREFCNT_inc_simple_void(gv);
1018 #ifdef USE_ITHREADS
1019     if (*ixp > 0) {
1020         pad_swipe(*ixp, TRUE);
1021         *ixp = 0;
1022     }
1023 #else
1024     SvREFCNT_dec(*svp);
1025     *svp = NULL;
1026 #endif
1027     if (still_valid) {
1028         int try_downgrade = SvREFCNT(gv) == 2;
1029         SvREFCNT_dec_NN(gv);
1030         if (try_downgrade)
1031             gv_try_downgrade(gv);
1032     }
1033 }
1034
1035
1036 void
1037 Perl_op_clear(pTHX_ OP *o)
1038 {
1039
1040
1041     PERL_ARGS_ASSERT_OP_CLEAR;
1042
1043     switch (o->op_type) {
1044     case OP_NULL:       /* Was holding old type, if any. */
1045         /* FALLTHROUGH */
1046     case OP_ENTERTRY:
1047     case OP_ENTEREVAL:  /* Was holding hints. */
1048     case OP_ARGDEFELEM: /* Was holding signature index. */
1049         o->op_targ = 0;
1050         break;
1051     default:
1052         if (!(o->op_flags & OPf_REF) || !OP_IS_STAT(o->op_type))
1053             break;
1054         /* FALLTHROUGH */
1055     case OP_GVSV:
1056     case OP_GV:
1057     case OP_AELEMFAST:
1058 #ifdef USE_ITHREADS
1059             S_op_clear_gv(aTHX_ o, &(cPADOPx(o)->op_padix));
1060 #else
1061             S_op_clear_gv(aTHX_ o, &(cSVOPx(o)->op_sv));
1062 #endif
1063         break;
1064     case OP_METHOD_REDIR:
1065     case OP_METHOD_REDIR_SUPER:
1066 #ifdef USE_ITHREADS
1067         if (cMETHOPx(o)->op_rclass_targ) {
1068             pad_swipe(cMETHOPx(o)->op_rclass_targ, 1);
1069             cMETHOPx(o)->op_rclass_targ = 0;
1070         }
1071 #else
1072         SvREFCNT_dec(cMETHOPx(o)->op_rclass_sv);
1073         cMETHOPx(o)->op_rclass_sv = NULL;
1074 #endif
1075         /* FALLTHROUGH */
1076     case OP_METHOD_NAMED:
1077     case OP_METHOD_SUPER:
1078         SvREFCNT_dec(cMETHOPx(o)->op_u.op_meth_sv);
1079         cMETHOPx(o)->op_u.op_meth_sv = NULL;
1080 #ifdef USE_ITHREADS
1081         if (o->op_targ) {
1082             pad_swipe(o->op_targ, 1);
1083             o->op_targ = 0;
1084         }
1085 #endif
1086         break;
1087     case OP_CONST:
1088     case OP_HINTSEVAL:
1089         SvREFCNT_dec(cSVOPo->op_sv);
1090         cSVOPo->op_sv = NULL;
1091 #ifdef USE_ITHREADS
1092         /** Bug #15654
1093           Even if op_clear does a pad_free for the target of the op,
1094           pad_free doesn't actually remove the sv that exists in the pad;
1095           instead it lives on. This results in that it could be reused as
1096           a target later on when the pad was reallocated.
1097         **/
1098         if(o->op_targ) {
1099           pad_swipe(o->op_targ,1);
1100           o->op_targ = 0;
1101         }
1102 #endif
1103         break;
1104     case OP_DUMP:
1105     case OP_GOTO:
1106     case OP_NEXT:
1107     case OP_LAST:
1108     case OP_REDO:
1109         if (o->op_flags & (OPf_SPECIAL|OPf_STACKED|OPf_KIDS))
1110             break;
1111         /* FALLTHROUGH */
1112     case OP_TRANS:
1113     case OP_TRANSR:
1114         if (   (o->op_type == OP_TRANS || o->op_type == OP_TRANSR)
1115             && (o->op_private & OPpTRANS_USE_SVOP))
1116         {
1117 #ifdef USE_ITHREADS
1118             if (cPADOPo->op_padix > 0) {
1119                 pad_swipe(cPADOPo->op_padix, TRUE);
1120                 cPADOPo->op_padix = 0;
1121             }
1122 #else
1123             SvREFCNT_dec(cSVOPo->op_sv);
1124             cSVOPo->op_sv = NULL;
1125 #endif
1126         }
1127         else {
1128             PerlMemShared_free(cPVOPo->op_pv);
1129             cPVOPo->op_pv = NULL;
1130         }
1131         break;
1132     case OP_SUBST:
1133         op_free(cPMOPo->op_pmreplrootu.op_pmreplroot);
1134         goto clear_pmop;
1135
1136     case OP_SPLIT:
1137         if (     (o->op_private & OPpSPLIT_ASSIGN) /* @array  = split */
1138             && !(o->op_flags & OPf_STACKED))       /* @{expr} = split */
1139         {
1140             if (o->op_private & OPpSPLIT_LEX)
1141                 pad_free(cPMOPo->op_pmreplrootu.op_pmtargetoff);
1142             else
1143 #ifdef USE_ITHREADS
1144                 pad_swipe(cPMOPo->op_pmreplrootu.op_pmtargetoff, TRUE);
1145 #else
1146                 SvREFCNT_dec(MUTABLE_SV(cPMOPo->op_pmreplrootu.op_pmtargetgv));
1147 #endif
1148         }
1149         /* FALLTHROUGH */
1150     case OP_MATCH:
1151     case OP_QR:
1152     clear_pmop:
1153         if (!(cPMOPo->op_pmflags & PMf_CODELIST_PRIVATE))
1154             op_free(cPMOPo->op_code_list);
1155         cPMOPo->op_code_list = NULL;
1156         forget_pmop(cPMOPo);
1157         cPMOPo->op_pmreplrootu.op_pmreplroot = NULL;
1158         /* we use the same protection as the "SAFE" version of the PM_ macros
1159          * here since sv_clean_all might release some PMOPs
1160          * after PL_regex_padav has been cleared
1161          * and the clearing of PL_regex_padav needs to
1162          * happen before sv_clean_all
1163          */
1164 #ifdef USE_ITHREADS
1165         if(PL_regex_pad) {        /* We could be in destruction */
1166             const IV offset = (cPMOPo)->op_pmoffset;
1167             ReREFCNT_dec(PM_GETRE(cPMOPo));
1168             PL_regex_pad[offset] = &PL_sv_undef;
1169             sv_catpvn_nomg(PL_regex_pad[0], (const char *)&offset,
1170                            sizeof(offset));
1171         }
1172 #else
1173         ReREFCNT_dec(PM_GETRE(cPMOPo));
1174         PM_SETRE(cPMOPo, NULL);
1175 #endif
1176
1177         break;
1178
1179     case OP_ARGCHECK:
1180         PerlMemShared_free(cUNOP_AUXo->op_aux);
1181         break;
1182
1183     case OP_MULTICONCAT:
1184         {
1185             UNOP_AUX_item *aux = cUNOP_AUXo->op_aux;
1186             /* aux[PERL_MULTICONCAT_IX_PLAIN_PV] and/or
1187              * aux[PERL_MULTICONCAT_IX_UTF8_PV] point to plain and/or
1188              * utf8 shared strings */
1189             char *p1 = aux[PERL_MULTICONCAT_IX_PLAIN_PV].pv;
1190             char *p2 = aux[PERL_MULTICONCAT_IX_UTF8_PV].pv;
1191             if (p1)
1192                 PerlMemShared_free(p1);
1193             if (p2 && p1 != p2)
1194                 PerlMemShared_free(p2);
1195             PerlMemShared_free(aux);
1196         }
1197         break;
1198
1199     case OP_MULTIDEREF:
1200         {
1201             UNOP_AUX_item *items = cUNOP_AUXo->op_aux;
1202             UV actions = items->uv;
1203             bool last = 0;
1204             bool is_hash = FALSE;
1205
1206             while (!last) {
1207                 switch (actions & MDEREF_ACTION_MASK) {
1208
1209                 case MDEREF_reload:
1210                     actions = (++items)->uv;
1211                     continue;
1212
1213                 case MDEREF_HV_padhv_helem:
1214                     is_hash = TRUE;
1215                     /* FALLTHROUGH */
1216                 case MDEREF_AV_padav_aelem:
1217                     pad_free((++items)->pad_offset);
1218                     goto do_elem;
1219
1220                 case MDEREF_HV_gvhv_helem:
1221                     is_hash = TRUE;
1222                     /* FALLTHROUGH */
1223                 case MDEREF_AV_gvav_aelem:
1224 #ifdef USE_ITHREADS
1225                     S_op_clear_gv(aTHX_ o, &((++items)->pad_offset));
1226 #else
1227                     S_op_clear_gv(aTHX_ o, &((++items)->sv));
1228 #endif
1229                     goto do_elem;
1230
1231                 case MDEREF_HV_gvsv_vivify_rv2hv_helem:
1232                     is_hash = TRUE;
1233                     /* FALLTHROUGH */
1234                 case MDEREF_AV_gvsv_vivify_rv2av_aelem:
1235 #ifdef USE_ITHREADS
1236                     S_op_clear_gv(aTHX_ o, &((++items)->pad_offset));
1237 #else
1238                     S_op_clear_gv(aTHX_ o, &((++items)->sv));
1239 #endif
1240                     goto do_vivify_rv2xv_elem;
1241
1242                 case MDEREF_HV_padsv_vivify_rv2hv_helem:
1243                     is_hash = TRUE;
1244                     /* FALLTHROUGH */
1245                 case MDEREF_AV_padsv_vivify_rv2av_aelem:
1246                     pad_free((++items)->pad_offset);
1247                     goto do_vivify_rv2xv_elem;
1248
1249                 case MDEREF_HV_pop_rv2hv_helem:
1250                 case MDEREF_HV_vivify_rv2hv_helem:
1251                     is_hash = TRUE;
1252                     /* FALLTHROUGH */
1253                 do_vivify_rv2xv_elem:
1254                 case MDEREF_AV_pop_rv2av_aelem:
1255                 case MDEREF_AV_vivify_rv2av_aelem:
1256                 do_elem:
1257                     switch (actions & MDEREF_INDEX_MASK) {
1258                     case MDEREF_INDEX_none:
1259                         last = 1;
1260                         break;
1261                     case MDEREF_INDEX_const:
1262                         if (is_hash) {
1263 #ifdef USE_ITHREADS
1264                             /* see RT #15654 */
1265                             pad_swipe((++items)->pad_offset, 1);
1266 #else
1267                             SvREFCNT_dec((++items)->sv);
1268 #endif
1269                         }
1270                         else
1271                             items++;
1272                         break;
1273                     case MDEREF_INDEX_padsv:
1274                         pad_free((++items)->pad_offset);
1275                         break;
1276                     case MDEREF_INDEX_gvsv:
1277 #ifdef USE_ITHREADS
1278                         S_op_clear_gv(aTHX_ o, &((++items)->pad_offset));
1279 #else
1280                         S_op_clear_gv(aTHX_ o, &((++items)->sv));
1281 #endif
1282                         break;
1283                     }
1284
1285                     if (actions & MDEREF_FLAG_last)
1286                         last = 1;
1287                     is_hash = FALSE;
1288
1289                     break;
1290
1291                 default:
1292                     assert(0);
1293                     last = 1;
1294                     break;
1295
1296                 } /* switch */
1297
1298                 actions >>= MDEREF_SHIFT;
1299             } /* while */
1300
1301             /* start of malloc is at op_aux[-1], where the length is
1302              * stored */
1303             PerlMemShared_free(cUNOP_AUXo->op_aux - 1);
1304         }
1305         break;
1306     }
1307
1308     if (o->op_targ > 0) {
1309         pad_free(o->op_targ);
1310         o->op_targ = 0;
1311     }
1312 }
1313
1314 STATIC void
1315 S_cop_free(pTHX_ COP* cop)
1316 {
1317     PERL_ARGS_ASSERT_COP_FREE;
1318
1319     /* If called during global destruction PL_defstash might be NULL and there
1320        shouldn't be any code running that will trip over the bad cop address.
1321        This also avoids uselessly creating the AV after it's been destroyed.
1322     */
1323     if (cop->op_type == OP_DBSTATE && PL_phase != PERL_PHASE_DESTRUCT) {
1324         /* Remove the now invalid op from the line number information.
1325            This could cause a freed memory overwrite if the debugger tried to
1326            set a breakpoint on this line.
1327         */
1328         AV *av = CopFILEAVn(cop);
1329         if (av) {
1330             SV * const * const svp = av_fetch(av, CopLINE(cop), FALSE);
1331             if (svp && *svp != &PL_sv_undef && SvIVX(*svp) == PTR2IV(cop) ) {
1332                 (void)SvIOK_off(*svp);
1333                 SvIV_set(*svp, 0);
1334             }
1335         }
1336     }
1337     CopFILE_free(cop);
1338     if (! specialWARN(cop->cop_warnings))
1339         PerlMemShared_free(cop->cop_warnings);
1340     cophh_free(CopHINTHASH_get(cop));
1341     if (PL_curcop == cop)
1342        PL_curcop = NULL;
1343 }
1344
1345 STATIC void
1346 S_forget_pmop(pTHX_ PMOP *const o)
1347 {
1348     HV * const pmstash = PmopSTASH(o);
1349
1350     PERL_ARGS_ASSERT_FORGET_PMOP;
1351
1352     if (pmstash && !SvIS_FREED(pmstash) && SvMAGICAL(pmstash)) {
1353         MAGIC * const mg = mg_find((const SV *)pmstash, PERL_MAGIC_symtab);
1354         if (mg) {
1355             PMOP **const array = (PMOP**) mg->mg_ptr;
1356             U32 count = mg->mg_len / sizeof(PMOP**);
1357             U32 i = count;
1358
1359             while (i--) {
1360                 if (array[i] == o) {
1361                     /* Found it. Move the entry at the end to overwrite it.  */
1362                     array[i] = array[--count];
1363                     mg->mg_len = count * sizeof(PMOP**);
1364                     /* Could realloc smaller at this point always, but probably
1365                        not worth it. Probably worth free()ing if we're the
1366                        last.  */
1367                     if(!count) {
1368                         Safefree(mg->mg_ptr);
1369                         mg->mg_ptr = NULL;
1370                     }
1371                     break;
1372                 }
1373             }
1374         }
1375     }
1376     if (PL_curpm == o)
1377         PL_curpm = NULL;
1378 }
1379
1380
1381 STATIC void
1382 S_find_and_forget_pmops(pTHX_ OP *o)
1383 {
1384     OP* top_op = o;
1385
1386     PERL_ARGS_ASSERT_FIND_AND_FORGET_PMOPS;
1387
1388     while (1) {
1389         switch (o->op_type) {
1390         case OP_SUBST:
1391         case OP_SPLIT:
1392         case OP_MATCH:
1393         case OP_QR:
1394             forget_pmop((PMOP*)o);
1395         }
1396
1397         if (o->op_flags & OPf_KIDS) {
1398             o = cUNOPo->op_first;
1399             continue;
1400         }
1401
1402         while (1) {
1403             if (o == top_op)
1404                 return; /* at top; no parents/siblings to try */
1405             if (OpHAS_SIBLING(o)) {
1406                 o = o->op_sibparent; /* process next sibling */
1407                 break;
1408             }
1409             o = o->op_sibparent; /*try parent's next sibling */
1410         }
1411     }
1412 }
1413
1414
1415 /*
1416 =for apidoc op_null
1417
1418 Neutralizes an op when it is no longer needed, but is still linked to from
1419 other ops.
1420
1421 =cut
1422 */
1423
1424 void
1425 Perl_op_null(pTHX_ OP *o)
1426 {
1427
1428     PERL_ARGS_ASSERT_OP_NULL;
1429
1430     if (o->op_type == OP_NULL)
1431         return;
1432     op_clear(o);
1433     o->op_targ = o->op_type;
1434     OpTYPE_set(o, OP_NULL);
1435 }
1436
1437 /*
1438 =for apidoc op_refcnt_lock
1439
1440 Implements the C<OP_REFCNT_LOCK> macro which you should use instead.
1441
1442 =cut
1443 */
1444
1445 void
1446 Perl_op_refcnt_lock(pTHX)
1447   PERL_TSA_ACQUIRE(PL_op_mutex)
1448 {
1449     PERL_UNUSED_CONTEXT;
1450     OP_REFCNT_LOCK;
1451 }
1452
1453 /*
1454 =for apidoc op_refcnt_unlock
1455
1456 Implements the C<OP_REFCNT_UNLOCK> macro which you should use instead.
1457
1458 =cut
1459 */
1460
1461 void
1462 Perl_op_refcnt_unlock(pTHX)
1463   PERL_TSA_RELEASE(PL_op_mutex)
1464 {
1465     PERL_UNUSED_CONTEXT;
1466     OP_REFCNT_UNLOCK;
1467 }
1468
1469
1470 /*
1471 =for apidoc op_sibling_splice
1472
1473 A general function for editing the structure of an existing chain of
1474 op_sibling nodes.  By analogy with the perl-level C<splice()> function, allows
1475 you to delete zero or more sequential nodes, replacing them with zero or
1476 more different nodes.  Performs the necessary op_first/op_last
1477 housekeeping on the parent node and op_sibling manipulation on the
1478 children.  The last deleted node will be marked as the last node by
1479 updating the op_sibling/op_sibparent or op_moresib field as appropriate.
1480
1481 Note that op_next is not manipulated, and nodes are not freed; that is the
1482 responsibility of the caller.  It also won't create a new list op for an
1483 empty list etc; use higher-level functions like op_append_elem() for that.
1484
1485 C<parent> is the parent node of the sibling chain. It may passed as C<NULL> if
1486 the splicing doesn't affect the first or last op in the chain.
1487
1488 C<start> is the node preceding the first node to be spliced.  Node(s)
1489 following it will be deleted, and ops will be inserted after it.  If it is
1490 C<NULL>, the first node onwards is deleted, and nodes are inserted at the
1491 beginning.
1492
1493 C<del_count> is the number of nodes to delete.  If zero, no nodes are deleted.
1494 If -1 or greater than or equal to the number of remaining kids, all
1495 remaining kids are deleted.
1496
1497 C<insert> is the first of a chain of nodes to be inserted in place of the nodes.
1498 If C<NULL>, no nodes are inserted.
1499
1500 The head of the chain of deleted ops is returned, or C<NULL> if no ops were
1501 deleted.
1502
1503 For example:
1504
1505     action                    before      after         returns
1506     ------                    -----       -----         -------
1507
1508                               P           P
1509     splice(P, A, 2, X-Y-Z)    |           |             B-C
1510                               A-B-C-D     A-X-Y-Z-D
1511
1512                               P           P
1513     splice(P, NULL, 1, X-Y)   |           |             A
1514                               A-B-C-D     X-Y-B-C-D
1515
1516                               P           P
1517     splice(P, NULL, 3, NULL)  |           |             A-B-C
1518                               A-B-C-D     D
1519
1520                               P           P
1521     splice(P, B, 0, X-Y)      |           |             NULL
1522                               A-B-C-D     A-B-X-Y-C-D
1523
1524
1525 For lower-level direct manipulation of C<op_sibparent> and C<op_moresib>,
1526 see C<L</OpMORESIB_set>>, C<L</OpLASTSIB_set>>, C<L</OpMAYBESIB_set>>.
1527
1528 =cut
1529 */
1530
1531 OP *
1532 Perl_op_sibling_splice(OP *parent, OP *start, int del_count, OP* insert)
1533 {
1534     OP *first;
1535     OP *rest;
1536     OP *last_del = NULL;
1537     OP *last_ins = NULL;
1538
1539     if (start)
1540         first = OpSIBLING(start);
1541     else if (!parent)
1542         goto no_parent;
1543     else
1544         first = cLISTOPx(parent)->op_first;
1545
1546     assert(del_count >= -1);
1547
1548     if (del_count && first) {
1549         last_del = first;
1550         while (--del_count && OpHAS_SIBLING(last_del))
1551             last_del = OpSIBLING(last_del);
1552         rest = OpSIBLING(last_del);
1553         OpLASTSIB_set(last_del, NULL);
1554     }
1555     else
1556         rest = first;
1557
1558     if (insert) {
1559         last_ins = insert;
1560         while (OpHAS_SIBLING(last_ins))
1561             last_ins = OpSIBLING(last_ins);
1562         OpMAYBESIB_set(last_ins, rest, NULL);
1563     }
1564     else
1565         insert = rest;
1566
1567     if (start) {
1568         OpMAYBESIB_set(start, insert, NULL);
1569     }
1570     else {
1571         assert(parent);
1572         cLISTOPx(parent)->op_first = insert;
1573         if (insert)
1574             parent->op_flags |= OPf_KIDS;
1575         else
1576             parent->op_flags &= ~OPf_KIDS;
1577     }
1578
1579     if (!rest) {
1580         /* update op_last etc */
1581         U32 type;
1582         OP *lastop;
1583
1584         if (!parent)
1585             goto no_parent;
1586
1587         /* ought to use OP_CLASS(parent) here, but that can't handle
1588          * ex-foo OP_NULL ops. Also note that XopENTRYCUSTOM() can't
1589          * either */
1590         type = parent->op_type;
1591         if (type == OP_CUSTOM) {
1592             dTHX;
1593             type = XopENTRYCUSTOM(parent, xop_class);
1594         }
1595         else {
1596             if (type == OP_NULL)
1597                 type = parent->op_targ;
1598             type = PL_opargs[type] & OA_CLASS_MASK;
1599         }
1600
1601         lastop = last_ins ? last_ins : start ? start : NULL;
1602         if (   type == OA_BINOP
1603             || type == OA_LISTOP
1604             || type == OA_PMOP
1605             || type == OA_LOOP
1606         )
1607             cLISTOPx(parent)->op_last = lastop;
1608
1609         if (lastop)
1610             OpLASTSIB_set(lastop, parent);
1611     }
1612     return last_del ? first : NULL;
1613
1614   no_parent:
1615     Perl_croak_nocontext("panic: op_sibling_splice(): NULL parent");
1616 }
1617
1618 /*
1619 =for apidoc op_parent
1620
1621 Returns the parent OP of C<o>, if it has a parent. Returns C<NULL> otherwise.
1622
1623 =cut
1624 */
1625
1626 OP *
1627 Perl_op_parent(OP *o)
1628 {
1629     PERL_ARGS_ASSERT_OP_PARENT;
1630     while (OpHAS_SIBLING(o))
1631         o = OpSIBLING(o);
1632     return o->op_sibparent;
1633 }
1634
1635 /* replace the sibling following start with a new UNOP, which becomes
1636  * the parent of the original sibling; e.g.
1637  *
1638  *  op_sibling_newUNOP(P, A, unop-args...)
1639  *
1640  *  P              P
1641  *  |      becomes |
1642  *  A-B-C          A-U-C
1643  *                   |
1644  *                   B
1645  *
1646  * where U is the new UNOP.
1647  *
1648  * parent and start args are the same as for op_sibling_splice();
1649  * type and flags args are as newUNOP().
1650  *
1651  * Returns the new UNOP.
1652  */
1653
1654 STATIC OP *
1655 S_op_sibling_newUNOP(pTHX_ OP *parent, OP *start, I32 type, I32 flags)
1656 {
1657     OP *kid, *newop;
1658
1659     kid = op_sibling_splice(parent, start, 1, NULL);
1660     newop = newUNOP(type, flags, kid);
1661     op_sibling_splice(parent, start, 0, newop);
1662     return newop;
1663 }
1664
1665
1666 /* lowest-level newLOGOP-style function - just allocates and populates
1667  * the struct. Higher-level stuff should be done by S_new_logop() /
1668  * newLOGOP(). This function exists mainly to avoid op_first assignment
1669  * being spread throughout this file.
1670  */
1671
1672 LOGOP *
1673 Perl_alloc_LOGOP(pTHX_ I32 type, OP *first, OP* other)
1674 {
1675     LOGOP *logop;
1676     OP *kid = first;
1677     NewOp(1101, logop, 1, LOGOP);
1678     OpTYPE_set(logop, type);
1679     logop->op_first = first;
1680     logop->op_other = other;
1681     if (first)
1682         logop->op_flags = OPf_KIDS;
1683     while (kid && OpHAS_SIBLING(kid))
1684         kid = OpSIBLING(kid);
1685     if (kid)
1686         OpLASTSIB_set(kid, (OP*)logop);
1687     return logop;
1688 }
1689
1690
1691 /* Contextualizers */
1692
1693 /*
1694 =for apidoc op_contextualize
1695
1696 Applies a syntactic context to an op tree representing an expression.
1697 C<o> is the op tree, and C<context> must be C<G_SCALAR>, C<G_LIST>,
1698 or C<G_VOID> to specify the context to apply.  The modified op tree
1699 is returned.
1700
1701 =cut
1702 */
1703
1704 OP *
1705 Perl_op_contextualize(pTHX_ OP *o, I32 context)
1706 {
1707     PERL_ARGS_ASSERT_OP_CONTEXTUALIZE;
1708     switch (context) {
1709         case G_SCALAR: return scalar(o);
1710         case G_LIST:   return list(o);
1711         case G_VOID:   return scalarvoid(o);
1712         default:
1713             Perl_croak(aTHX_ "panic: op_contextualize bad context %ld",
1714                        (long) context);
1715     }
1716 }
1717
1718 /*
1719
1720 =for apidoc op_linklist
1721 This function is the implementation of the L</LINKLIST> macro.  It should
1722 not be called directly.
1723
1724 =cut
1725 */
1726
1727
1728 OP *
1729 Perl_op_linklist(pTHX_ OP *o)
1730 {
1731
1732     OP **prevp;
1733     OP *kid;
1734     OP * top_op = o;
1735
1736     PERL_ARGS_ASSERT_OP_LINKLIST;
1737
1738     while (1) {
1739         /* Descend down the tree looking for any unprocessed subtrees to
1740          * do first */
1741         if (!o->op_next) {
1742             if (o->op_flags & OPf_KIDS) {
1743                 o = cUNOPo->op_first;
1744                 continue;
1745             }
1746             o->op_next = o; /* leaf node; link to self initially */
1747         }
1748
1749         /* if we're at the top level, there either weren't any children
1750          * to process, or we've worked our way back to the top. */
1751         if (o == top_op)
1752             return o->op_next;
1753
1754         /* o is now processed. Next, process any sibling subtrees */
1755
1756         if (OpHAS_SIBLING(o)) {
1757             o = OpSIBLING(o);
1758             continue;
1759         }
1760
1761         /* Done all the subtrees at this level. Go back up a level and
1762          * link the parent in with all its (processed) children.
1763          */
1764
1765         o = o->op_sibparent;
1766         assert(!o->op_next);
1767         prevp = &(o->op_next);
1768         kid   = (o->op_flags & OPf_KIDS) ? cUNOPo->op_first : NULL;
1769         while (kid) {
1770             *prevp = kid->op_next;
1771             prevp = &(kid->op_next);
1772             kid = OpSIBLING(kid);
1773         }
1774         *prevp = o;
1775     }
1776 }
1777
1778
1779 static OP *
1780 S_scalarkids(pTHX_ OP *o)
1781 {
1782     if (o && o->op_flags & OPf_KIDS) {
1783         OP *kid;
1784         for (kid = cLISTOPo->op_first; kid; kid = OpSIBLING(kid))
1785             scalar(kid);
1786     }
1787     return o;
1788 }
1789
1790 STATIC OP *
1791 S_scalarboolean(pTHX_ OP *o)
1792 {
1793     PERL_ARGS_ASSERT_SCALARBOOLEAN;
1794
1795     if ((o->op_type == OP_SASSIGN && cBINOPo->op_first->op_type == OP_CONST &&
1796          !(cBINOPo->op_first->op_flags & OPf_SPECIAL)) ||
1797         (o->op_type == OP_NOT     && cUNOPo->op_first->op_type == OP_SASSIGN &&
1798          cBINOPx(cUNOPo->op_first)->op_first->op_type == OP_CONST &&
1799          !(cBINOPx(cUNOPo->op_first)->op_first->op_flags & OPf_SPECIAL))) {
1800         if (ckWARN(WARN_SYNTAX)) {
1801             const line_t oldline = CopLINE(PL_curcop);
1802
1803             if (PL_parser && PL_parser->copline != NOLINE) {
1804                 /* This ensures that warnings are reported at the first line
1805                    of the conditional, not the last.  */
1806                 CopLINE_set(PL_curcop, PL_parser->copline);
1807             }
1808             Perl_warner(aTHX_ packWARN(WARN_SYNTAX), "Found = in conditional, should be ==");
1809             CopLINE_set(PL_curcop, oldline);
1810         }
1811     }
1812     return scalar(o);
1813 }
1814
1815 static SV *
1816 S_op_varname_subscript(pTHX_ const OP *o, int subscript_type)
1817 {
1818     assert(o);
1819     assert(o->op_type == OP_PADAV || o->op_type == OP_RV2AV ||
1820            o->op_type == OP_PADHV || o->op_type == OP_RV2HV);
1821     {
1822         const char funny  = o->op_type == OP_PADAV
1823                          || o->op_type == OP_RV2AV ? '@' : '%';
1824         if (o->op_type == OP_RV2AV || o->op_type == OP_RV2HV) {
1825             GV *gv;
1826             if (cUNOPo->op_first->op_type != OP_GV
1827              || !(gv = cGVOPx_gv(cUNOPo->op_first)))
1828                 return NULL;
1829             return varname(gv, funny, 0, NULL, 0, subscript_type);
1830         }
1831         return
1832             varname(MUTABLE_GV(PL_compcv), funny, o->op_targ, NULL, 0, subscript_type);
1833     }
1834 }
1835
1836 static SV *
1837 S_op_varname(pTHX_ const OP *o)
1838 {
1839     return S_op_varname_subscript(aTHX_ o, 1);
1840 }
1841
1842 /*
1843
1844 Warns that an access of a single element from a named container variable in
1845 scalar context might not be what the programmer wanted. The container
1846 variable's (sigiled, full) name is given by C<name>, and the key to access
1847 it is given by the C<SVOP_sv> of the C<OP_CONST> op given by C<o>.
1848 C<is_hash> selects whether it prints using {KEY} or [KEY] brackets.
1849
1850 C<is_slice> selects between two different messages used in different places.
1851  */
1852 static void
1853 S_warn_elem_scalar_context(pTHX_ const OP *o, SV *name, bool is_hash, bool is_slice)
1854 {
1855     SV *keysv;
1856     const char *keypv = NULL;
1857
1858     const char lbrack = is_hash ? '{' : '[';
1859     const char rbrack = is_hash ? '}' : ']';
1860
1861     if (o->op_type == OP_CONST) {
1862         keysv = cSVOPo_sv;
1863         if (SvPOK(keysv)) {
1864             SV *sv = keysv;
1865             keysv = sv_newmortal();
1866             pv_pretty(keysv, SvPVX_const(sv), SvCUR(sv), 32, NULL, NULL,
1867                       PERL_PV_PRETTY_DUMP |PERL_PV_ESCAPE_UNI_DETECT);
1868         }
1869         else if (!SvOK(keysv))
1870             keypv = "undef";
1871     }
1872     else keypv = "...";
1873
1874     assert(SvPOK(name));
1875     sv_chop(name,SvPVX(name)+1);
1876
1877     const char *msg;
1878
1879     if (keypv) {
1880         msg = is_slice ?
1881             "Scalar value @%" SVf "%c%s%c better written as $%" SVf "%c%s%c" :
1882             "%%%" SVf "%c%s%c in scalar context better written as $%" SVf "%c%s%c";
1883         /* diag_listed_as: %%s[%s] in scalar context better written as $%s[%s] */
1884         /* diag_listed_as: Scalar value @%s[%s] better written as $%s[%s] */
1885         Perl_warner(aTHX_ packWARN(WARN_SYNTAX), msg,
1886                 SVfARG(name), lbrack, keypv, rbrack,
1887                 SVfARG(name), lbrack, keypv, rbrack);
1888     }
1889     else {
1890         msg = is_slice ?
1891             "Scalar value @%" SVf "%c%" SVf "%c better written as $%" SVf "%c%" SVf "%c" :
1892             "%%%" SVf "%c%" SVf "%c in scalar context better written as $%" SVf "%c%" SVf "%c";
1893         /* diag_listed_as: %%s[%s] in scalar context better written as $%s[%s] */
1894         /* diag_listed_as: Scalar value @%s[%s] better written as $%s[%s] */
1895         Perl_warner(aTHX_ packWARN(WARN_SYNTAX), msg,
1896                 SVfARG(name), lbrack, SVfARG(keysv), rbrack,
1897                 SVfARG(name), lbrack, SVfARG(keysv), rbrack);
1898     }
1899 }
1900
1901 static void
1902 S_scalar_slice_warning(pTHX_ const OP *o)
1903 {
1904     OP *kid;
1905     const bool is_hash = o->op_type == OP_HSLICE
1906                 || (o->op_type == OP_NULL && o->op_targ == OP_HSLICE);
1907     SV *name;
1908
1909     if (!(o->op_private & OPpSLICEWARNING))
1910         return;
1911     if (PL_parser && PL_parser->error_count)
1912         /* This warning can be nonsensical when there is a syntax error. */
1913         return;
1914
1915     kid = cLISTOPo->op_first;
1916     kid = OpSIBLING(kid); /* get past pushmark */
1917     /* weed out false positives: any ops that can return lists */
1918     switch (kid->op_type) {
1919     case OP_BACKTICK:
1920     case OP_GLOB:
1921     case OP_READLINE:
1922     case OP_MATCH:
1923     case OP_RV2AV:
1924     case OP_EACH:
1925     case OP_VALUES:
1926     case OP_KEYS:
1927     case OP_SPLIT:
1928     case OP_LIST:
1929     case OP_SORT:
1930     case OP_REVERSE:
1931     case OP_ENTERSUB:
1932     case OP_CALLER:
1933     case OP_LSTAT:
1934     case OP_STAT:
1935     case OP_READDIR:
1936     case OP_SYSTEM:
1937     case OP_TMS:
1938     case OP_LOCALTIME:
1939     case OP_GMTIME:
1940     case OP_ENTEREVAL:
1941         return;
1942     }
1943
1944     /* Don't warn if we have a nulled list either. */
1945     if (kid->op_type == OP_NULL && kid->op_targ == OP_LIST)
1946         return;
1947
1948     assert(OpSIBLING(kid));
1949     name = S_op_varname(aTHX_ OpSIBLING(kid));
1950     if (!name) /* XS module fiddling with the op tree */
1951         return;
1952     S_warn_elem_scalar_context(aTHX_ kid, name, is_hash, true);
1953 }
1954
1955
1956
1957 /* apply scalar context to the o subtree */
1958
1959 OP *
1960 Perl_scalar(pTHX_ OP *o)
1961 {
1962     OP * top_op = o;
1963
1964     while (1) {
1965         OP *next_kid = NULL; /* what op (if any) to process next */
1966         OP *kid;
1967
1968         /* assumes no premature commitment */
1969         if (!o || (PL_parser && PL_parser->error_count)
1970              || (o->op_flags & OPf_WANT)
1971              || o->op_type == OP_RETURN)
1972         {
1973             goto do_next;
1974         }
1975
1976         o->op_flags = (o->op_flags & ~OPf_WANT) | OPf_WANT_SCALAR;
1977
1978         switch (o->op_type) {
1979         case OP_REPEAT:
1980             scalar(cBINOPo->op_first);
1981             /* convert what initially looked like a list repeat into a
1982              * scalar repeat, e.g. $s = (1) x $n
1983              */
1984             if (o->op_private & OPpREPEAT_DOLIST) {
1985                 kid = cLISTOPx(cUNOPo->op_first)->op_first;
1986                 assert(kid->op_type == OP_PUSHMARK);
1987                 if (OpHAS_SIBLING(kid) && !OpHAS_SIBLING(OpSIBLING(kid))) {
1988                     op_null(cLISTOPx(cUNOPo->op_first)->op_first);
1989                     o->op_private &=~ OPpREPEAT_DOLIST;
1990                 }
1991             }
1992             break;
1993
1994         case OP_OR:
1995         case OP_AND:
1996         case OP_COND_EXPR:
1997             /* impose scalar context on everything except the condition */
1998             next_kid = OpSIBLING(cUNOPo->op_first);
1999             break;
2000
2001         default:
2002             if (o->op_flags & OPf_KIDS)
2003                 next_kid = cUNOPo->op_first; /* do all kids */
2004             break;
2005
2006         /* the children of these ops are usually a list of statements,
2007          * except the leaves, whose first child is a corresponding enter
2008          */
2009         case OP_SCOPE:
2010         case OP_LINESEQ:
2011         case OP_LIST:
2012             kid = cLISTOPo->op_first;
2013             goto do_kids;
2014         case OP_LEAVE:
2015         case OP_LEAVETRY:
2016             kid = cLISTOPo->op_first;
2017             scalar(kid);
2018             kid = OpSIBLING(kid);
2019         do_kids:
2020             while (kid) {
2021                 OP *sib = OpSIBLING(kid);
2022                 /* Apply void context to all kids except the last, which
2023                  * is scalar (ignoring a trailing ex-nextstate in determining
2024                  * if it's the last kid). E.g.
2025                  *      $scalar = do { void; void; scalar }
2026                  * Except that 'when's are always scalar, e.g.
2027                  *      $scalar = do { given(..) {
2028                     *                 when (..) { scalar }
2029                     *                 when (..) { scalar }
2030                     *                 ...
2031                     *                }}
2032                     */
2033                 if (!sib
2034                      || (  !OpHAS_SIBLING(sib)
2035                          && sib->op_type == OP_NULL
2036                          && (   sib->op_targ == OP_NEXTSTATE
2037                              || sib->op_targ == OP_DBSTATE  )
2038                         )
2039                 )
2040                 {
2041                     /* tail call optimise calling scalar() on the last kid */
2042                     next_kid = kid;
2043                     goto do_next;
2044                 }
2045                 else if (kid->op_type == OP_LEAVEWHEN)
2046                     scalar(kid);
2047                 else
2048                     scalarvoid(kid);
2049                 kid = sib;
2050             }
2051             NOT_REACHED; /* NOTREACHED */
2052             break;
2053
2054         case OP_SORT:
2055             Perl_ck_warner(aTHX_ packWARN(WARN_SCALAR), "Useless use of %s in scalar context", "sort");
2056             break;
2057
2058         case OP_KVHSLICE:
2059         case OP_KVASLICE:
2060         {
2061             /* Warn about scalar context */
2062             SV *name;
2063
2064             /* This warning can be nonsensical when there is a syntax error. */
2065             if (PL_parser && PL_parser->error_count)
2066                 break;
2067
2068             if (!ckWARN(WARN_SYNTAX)) break;
2069
2070             kid = cLISTOPo->op_first;
2071             kid = OpSIBLING(kid); /* get past pushmark */
2072             assert(OpSIBLING(kid));
2073             name = S_op_varname(aTHX_ OpSIBLING(kid));
2074             if (!name) /* XS module fiddling with the op tree */
2075                 break;
2076             S_warn_elem_scalar_context(aTHX_ kid, name, o->op_type == OP_KVHSLICE, false);
2077         }
2078         } /* switch */
2079
2080         /* If next_kid is set, someone in the code above wanted us to process
2081          * that kid and all its remaining siblings.  Otherwise, work our way
2082          * back up the tree */
2083       do_next:
2084         while (!next_kid) {
2085             if (o == top_op)
2086                 return top_op; /* at top; no parents/siblings to try */
2087             if (OpHAS_SIBLING(o))
2088                 next_kid = o->op_sibparent;
2089             else {
2090                 o = o->op_sibparent; /*try parent's next sibling */
2091                 switch (o->op_type) {
2092                 case OP_SCOPE:
2093                 case OP_LINESEQ:
2094                 case OP_LIST:
2095                 case OP_LEAVE:
2096                 case OP_LEAVETRY:
2097                     /* should really restore PL_curcop to its old value, but
2098                      * setting it to PL_compiling is better than do nothing */
2099                     PL_curcop = &PL_compiling;
2100                 }
2101             }
2102         }
2103         o = next_kid;
2104     } /* while */
2105 }
2106
2107
2108 /* apply void context to the optree arg */
2109
2110 OP *
2111 Perl_scalarvoid(pTHX_ OP *arg)
2112 {
2113     OP *kid;
2114     SV* sv;
2115     OP *o = arg;
2116
2117     PERL_ARGS_ASSERT_SCALARVOID;
2118
2119     while (1) {
2120         U8 want;
2121         SV *useless_sv = NULL;
2122         const char* useless = NULL;
2123         OP * next_kid = NULL;
2124
2125         if (o->op_type == OP_NEXTSTATE
2126             || o->op_type == OP_DBSTATE
2127             || (o->op_type == OP_NULL && (o->op_targ == OP_NEXTSTATE
2128                                           || o->op_targ == OP_DBSTATE)))
2129             PL_curcop = (COP*)o;                /* for warning below */
2130
2131         /* assumes no premature commitment */
2132         want = o->op_flags & OPf_WANT;
2133         if ((want && want != OPf_WANT_SCALAR)
2134             || (PL_parser && PL_parser->error_count)
2135             || o->op_type == OP_RETURN || o->op_type == OP_REQUIRE || o->op_type == OP_LEAVEWHEN)
2136         {
2137             goto get_next_op;
2138         }
2139
2140         if ((o->op_private & OPpTARGET_MY)
2141             && (PL_opargs[o->op_type] & OA_TARGLEX))/* OPp share the meaning */
2142         {
2143             /* newASSIGNOP has already applied scalar context, which we
2144                leave, as if this op is inside SASSIGN.  */
2145             goto get_next_op;
2146         }
2147
2148         o->op_flags = (o->op_flags & ~OPf_WANT) | OPf_WANT_VOID;
2149
2150         switch (o->op_type) {
2151         default:
2152             if (!(PL_opargs[o->op_type] & OA_FOLDCONST))
2153                 break;
2154             /* FALLTHROUGH */
2155         case OP_REPEAT:
2156             if (o->op_flags & OPf_STACKED)
2157                 break;
2158             if (o->op_type == OP_REPEAT)
2159                 scalar(cBINOPo->op_first);
2160             goto func_ops;
2161         case OP_CONCAT:
2162             if ((o->op_flags & OPf_STACKED) &&
2163                     !(o->op_private & OPpCONCAT_NESTED))
2164                 break;
2165             goto func_ops;
2166         case OP_SUBSTR:
2167             if (o->op_private == 4)
2168                 break;
2169             /* FALLTHROUGH */
2170         case OP_WANTARRAY:
2171         case OP_GV:
2172         case OP_SMARTMATCH:
2173         case OP_AV2ARYLEN:
2174         case OP_REF:
2175         case OP_REFGEN:
2176         case OP_SREFGEN:
2177         case OP_DEFINED:
2178         case OP_HEX:
2179         case OP_OCT:
2180         case OP_LENGTH:
2181         case OP_VEC:
2182         case OP_INDEX:
2183         case OP_RINDEX:
2184         case OP_SPRINTF:
2185         case OP_KVASLICE:
2186         case OP_KVHSLICE:
2187         case OP_UNPACK:
2188         case OP_PACK:
2189         case OP_JOIN:
2190         case OP_LSLICE:
2191         case OP_ANONLIST:
2192         case OP_ANONHASH:
2193         case OP_SORT:
2194         case OP_REVERSE:
2195         case OP_RANGE:
2196         case OP_FLIP:
2197         case OP_FLOP:
2198         case OP_CALLER:
2199         case OP_FILENO:
2200         case OP_EOF:
2201         case OP_TELL:
2202         case OP_GETSOCKNAME:
2203         case OP_GETPEERNAME:
2204         case OP_READLINK:
2205         case OP_TELLDIR:
2206         case OP_GETPPID:
2207         case OP_GETPGRP:
2208         case OP_GETPRIORITY:
2209         case OP_TIME:
2210         case OP_TMS:
2211         case OP_LOCALTIME:
2212         case OP_GMTIME:
2213         case OP_GHBYNAME:
2214         case OP_GHBYADDR:
2215         case OP_GHOSTENT:
2216         case OP_GNBYNAME:
2217         case OP_GNBYADDR:
2218         case OP_GNETENT:
2219         case OP_GPBYNAME:
2220         case OP_GPBYNUMBER:
2221         case OP_GPROTOENT:
2222         case OP_GSBYNAME:
2223         case OP_GSBYPORT:
2224         case OP_GSERVENT:
2225         case OP_GPWNAM:
2226         case OP_GPWUID:
2227         case OP_GGRNAM:
2228         case OP_GGRGID:
2229         case OP_GETLOGIN:
2230         case OP_PROTOTYPE:
2231         case OP_RUNCV:
2232         func_ops:
2233             useless = OP_DESC(o);
2234             break;
2235
2236         case OP_GVSV:
2237         case OP_PADSV:
2238         case OP_PADAV:
2239         case OP_PADHV:
2240         case OP_PADANY:
2241         case OP_AELEM:
2242         case OP_AELEMFAST:
2243         case OP_AELEMFAST_LEX:
2244         case OP_ASLICE:
2245         case OP_HELEM:
2246         case OP_HSLICE:
2247             if (!(o->op_private & (OPpLVAL_INTRO|OPpOUR_INTRO)))
2248                 /* Otherwise it's "Useless use of grep iterator" */
2249                 useless = OP_DESC(o);
2250             break;
2251
2252         case OP_SPLIT:
2253             if (!(o->op_private & OPpSPLIT_ASSIGN))
2254                 useless = OP_DESC(o);
2255             break;
2256
2257         case OP_NOT:
2258             kid = cUNOPo->op_first;
2259             if (kid->op_type != OP_MATCH && kid->op_type != OP_SUBST &&
2260                 kid->op_type != OP_TRANS && kid->op_type != OP_TRANSR) {
2261                 goto func_ops;
2262             }
2263             useless = "negative pattern binding (!~)";
2264             break;
2265
2266         case OP_SUBST:
2267             if (cPMOPo->op_pmflags & PMf_NONDESTRUCT)
2268                 useless = "non-destructive substitution (s///r)";
2269             break;
2270
2271         case OP_TRANSR:
2272             useless = "non-destructive transliteration (tr///r)";
2273             break;
2274
2275         case OP_RV2GV:
2276         case OP_RV2SV:
2277         case OP_RV2AV:
2278         case OP_RV2HV:
2279             if (!(o->op_private & (OPpLVAL_INTRO|OPpOUR_INTRO)) &&
2280                 (!OpHAS_SIBLING(o) || OpSIBLING(o)->op_type != OP_READLINE))
2281                 useless = "a variable";
2282             break;
2283
2284         case OP_CONST:
2285             sv = cSVOPo_sv;
2286             if (cSVOPo->op_private & OPpCONST_STRICT)
2287                 no_bareword_allowed(o);
2288             else {
2289                 if (ckWARN(WARN_VOID)) {
2290                     NV nv;
2291                     /* don't warn on optimised away booleans, eg
2292                      * use constant Foo, 5; Foo || print; */
2293                     if (cSVOPo->op_private & OPpCONST_SHORTCIRCUIT)
2294                         useless = NULL;
2295                     /* the constants 0 and 1 are permitted as they are
2296                        conventionally used as dummies in constructs like
2297                        1 while some_condition_with_side_effects;  */
2298                     else if (SvNIOK(sv) && ((nv = SvNV(sv)) == 0.0 || nv == 1.0))
2299                         useless = NULL;
2300                     else if (SvPOK(sv)) {
2301                         SV * const dsv = newSVpvs("");
2302                         useless_sv
2303                             = Perl_newSVpvf(aTHX_
2304                                             "a constant (%s)",
2305                                             pv_pretty(dsv, SvPVX_const(sv),
2306                                                       SvCUR(sv), 32, NULL, NULL,
2307                                                       PERL_PV_PRETTY_DUMP
2308                                                       | PERL_PV_ESCAPE_NOCLEAR
2309                                                       | PERL_PV_ESCAPE_UNI_DETECT));
2310                         SvREFCNT_dec_NN(dsv);
2311                     }
2312                     else if (SvOK(sv)) {
2313                         useless_sv = Perl_newSVpvf(aTHX_ "a constant (%" SVf ")", SVfARG(sv));
2314                     }
2315                     else
2316                         useless = "a constant (undef)";
2317                 }
2318             }
2319             op_null(o);         /* don't execute or even remember it */
2320             break;
2321
2322         case OP_POSTINC:
2323             OpTYPE_set(o, OP_PREINC);  /* pre-increment is faster */
2324             break;
2325
2326         case OP_POSTDEC:
2327             OpTYPE_set(o, OP_PREDEC);  /* pre-decrement is faster */
2328             break;
2329
2330         case OP_I_POSTINC:
2331             OpTYPE_set(o, OP_I_PREINC);        /* pre-increment is faster */
2332             break;
2333
2334         case OP_I_POSTDEC:
2335             OpTYPE_set(o, OP_I_PREDEC);        /* pre-decrement is faster */
2336             break;
2337
2338         case OP_SASSIGN: {
2339             OP *rv2gv;
2340             UNOP *refgen, *rv2cv;
2341             LISTOP *exlist;
2342
2343             if ((o->op_private & ~OPpASSIGN_BACKWARDS) != 2)
2344                 break;
2345
2346             rv2gv = ((BINOP *)o)->op_last;
2347             if (!rv2gv || rv2gv->op_type != OP_RV2GV)
2348                 break;
2349
2350             refgen = (UNOP *)((BINOP *)o)->op_first;
2351
2352             if (!refgen || (refgen->op_type != OP_REFGEN
2353                             && refgen->op_type != OP_SREFGEN))
2354                 break;
2355
2356             exlist = (LISTOP *)refgen->op_first;
2357             if (!exlist || exlist->op_type != OP_NULL
2358                 || exlist->op_targ != OP_LIST)
2359                 break;
2360
2361             if (exlist->op_first->op_type != OP_PUSHMARK
2362                 && exlist->op_first != exlist->op_last)
2363                 break;
2364
2365             rv2cv = (UNOP*)exlist->op_last;
2366
2367             if (rv2cv->op_type != OP_RV2CV)
2368                 break;
2369
2370             assert ((rv2gv->op_private & OPpDONT_INIT_GV) == 0);
2371             assert ((o->op_private & OPpASSIGN_CV_TO_GV) == 0);
2372             assert ((rv2cv->op_private & OPpMAY_RETURN_CONSTANT) == 0);
2373
2374             o->op_private |= OPpASSIGN_CV_TO_GV;
2375             rv2gv->op_private |= OPpDONT_INIT_GV;
2376             rv2cv->op_private |= OPpMAY_RETURN_CONSTANT;
2377
2378             break;
2379         }
2380
2381         case OP_AASSIGN: {
2382             inplace_aassign(o);
2383             break;
2384         }
2385
2386         case OP_OR:
2387         case OP_AND:
2388             kid = cLOGOPo->op_first;
2389             if (kid->op_type == OP_NOT
2390                 && (kid->op_flags & OPf_KIDS)) {
2391                 if (o->op_type == OP_AND) {
2392                     OpTYPE_set(o, OP_OR);
2393                 } else {
2394                     OpTYPE_set(o, OP_AND);
2395                 }
2396                 op_null(kid);
2397             }
2398             /* FALLTHROUGH */
2399
2400         case OP_DOR:
2401         case OP_COND_EXPR:
2402         case OP_ENTERGIVEN:
2403         case OP_ENTERWHEN:
2404             next_kid = OpSIBLING(cUNOPo->op_first);
2405         break;
2406
2407         case OP_NULL:
2408             if (o->op_flags & OPf_STACKED)
2409                 break;
2410             /* FALLTHROUGH */
2411         case OP_NEXTSTATE:
2412         case OP_DBSTATE:
2413         case OP_ENTERTRY:
2414         case OP_ENTER:
2415             if (!(o->op_flags & OPf_KIDS))
2416                 break;
2417             /* FALLTHROUGH */
2418         case OP_SCOPE:
2419         case OP_LEAVE:
2420         case OP_LEAVETRY:
2421         case OP_LEAVELOOP:
2422         case OP_LINESEQ:
2423         case OP_LEAVEGIVEN:
2424         case OP_LEAVEWHEN:
2425         kids:
2426             next_kid = cLISTOPo->op_first;
2427             break;
2428         case OP_LIST:
2429             /* If the first kid after pushmark is something that the padrange
2430                optimisation would reject, then null the list and the pushmark.
2431             */
2432             if ((kid = cLISTOPo->op_first)->op_type == OP_PUSHMARK
2433                 && (  !(kid = OpSIBLING(kid))
2434                       || (  kid->op_type != OP_PADSV
2435                             && kid->op_type != OP_PADAV
2436                             && kid->op_type != OP_PADHV)
2437                       || kid->op_private & ~OPpLVAL_INTRO
2438                       || !(kid = OpSIBLING(kid))
2439                       || (  kid->op_type != OP_PADSV
2440                             && kid->op_type != OP_PADAV
2441                             && kid->op_type != OP_PADHV)
2442                       || kid->op_private & ~OPpLVAL_INTRO)
2443             ) {
2444                 op_null(cUNOPo->op_first); /* NULL the pushmark */
2445                 op_null(o); /* NULL the list */
2446             }
2447             goto kids;
2448         case OP_ENTEREVAL:
2449             scalarkids(o);
2450             break;
2451         case OP_SCALAR:
2452             scalar(o);
2453             break;
2454         }
2455
2456         if (useless_sv) {
2457             /* mortalise it, in case warnings are fatal.  */
2458             Perl_ck_warner(aTHX_ packWARN(WARN_VOID),
2459                            "Useless use of %" SVf " in void context",
2460                            SVfARG(sv_2mortal(useless_sv)));
2461         }
2462         else if (useless) {
2463             Perl_ck_warner(aTHX_ packWARN(WARN_VOID),
2464                            "Useless use of %s in void context",
2465                            useless);
2466         }
2467
2468       get_next_op:
2469         /* if a kid hasn't been nominated to process, continue with the
2470          * next sibling, or if no siblings left, go back to the parent's
2471          * siblings and so on
2472          */
2473         while (!next_kid) {
2474             if (o == arg)
2475                 return arg; /* at top; no parents/siblings to try */
2476             if (OpHAS_SIBLING(o))
2477                 next_kid = o->op_sibparent;
2478             else
2479                 o = o->op_sibparent; /*try parent's next sibling */
2480         }
2481         o = next_kid;
2482     }
2483
2484     return arg;
2485 }
2486
2487
2488 static OP *
2489 S_listkids(pTHX_ OP *o)
2490 {
2491     if (o && o->op_flags & OPf_KIDS) {
2492         OP *kid;
2493         for (kid = cLISTOPo->op_first; kid; kid = OpSIBLING(kid))
2494             list(kid);
2495     }
2496     return o;
2497 }
2498
2499
2500 /* apply list context to the o subtree */
2501
2502 OP *
2503 Perl_list(pTHX_ OP *o)
2504 {
2505     OP * top_op = o;
2506
2507     while (1) {
2508         OP *next_kid = NULL; /* what op (if any) to process next */
2509
2510         OP *kid;
2511
2512         /* assumes no premature commitment */
2513         if (!o || (o->op_flags & OPf_WANT)
2514              || (PL_parser && PL_parser->error_count)
2515              || o->op_type == OP_RETURN)
2516         {
2517             goto do_next;
2518         }
2519
2520         if ((o->op_private & OPpTARGET_MY)
2521             && (PL_opargs[o->op_type] & OA_TARGLEX))/* OPp share the meaning */
2522         {
2523             goto do_next;                               /* As if inside SASSIGN */
2524         }
2525
2526         o->op_flags = (o->op_flags & ~OPf_WANT) | OPf_WANT_LIST;
2527
2528         switch (o->op_type) {
2529         case OP_REPEAT:
2530             if (o->op_private & OPpREPEAT_DOLIST
2531              && !(o->op_flags & OPf_STACKED))
2532             {
2533                 list(cBINOPo->op_first);
2534                 kid = cBINOPo->op_last;
2535                 /* optimise away (.....) x 1 */
2536                 if (kid->op_type == OP_CONST && SvIOK(kSVOP_sv)
2537                  && SvIVX(kSVOP_sv) == 1)
2538                 {
2539                     op_null(o); /* repeat */
2540                     op_null(cUNOPx(cBINOPo->op_first)->op_first);/* pushmark */
2541                     /* const (rhs): */
2542                     op_free(op_sibling_splice(o, cBINOPo->op_first, 1, NULL));
2543                 }
2544             }
2545             break;
2546
2547         case OP_OR:
2548         case OP_AND:
2549         case OP_COND_EXPR:
2550             /* impose list context on everything except the condition */
2551             next_kid = OpSIBLING(cUNOPo->op_first);
2552             break;
2553
2554         default:
2555             if (!(o->op_flags & OPf_KIDS))
2556                 break;
2557             /* possibly flatten 1..10 into a constant array */
2558             if (!o->op_next && cUNOPo->op_first->op_type == OP_FLOP) {
2559                 list(cBINOPo->op_first);
2560                 gen_constant_list(o);
2561                 goto do_next;
2562             }
2563             next_kid = cUNOPo->op_first; /* do all kids */
2564             break;
2565
2566         case OP_LIST:
2567             if (cLISTOPo->op_first->op_type == OP_PUSHMARK) {
2568                 op_null(cUNOPo->op_first); /* NULL the pushmark */
2569                 op_null(o); /* NULL the list */
2570             }
2571             if (o->op_flags & OPf_KIDS)
2572                 next_kid = cUNOPo->op_first; /* do all kids */
2573             break;
2574
2575         /* the children of these ops are usually a list of statements,
2576          * except the leaves, whose first child is a corresponding enter
2577          */
2578         case OP_SCOPE:
2579         case OP_LINESEQ:
2580             kid = cLISTOPo->op_first;
2581             goto do_kids;
2582         case OP_LEAVE:
2583         case OP_LEAVETRY:
2584             kid = cLISTOPo->op_first;
2585             list(kid);
2586             kid = OpSIBLING(kid);
2587         do_kids:
2588             while (kid) {
2589                 OP *sib = OpSIBLING(kid);
2590                 /* Apply void context to all kids except the last, which
2591                  * is list. E.g.
2592                  *      @a = do { void; void; list }
2593                  * Except that 'when's are always list context, e.g.
2594                  *      @a = do { given(..) {
2595                     *                 when (..) { list }
2596                     *                 when (..) { list }
2597                     *                 ...
2598                     *                }}
2599                     */
2600                 if (!sib) {
2601                     /* tail call optimise calling list() on the last kid */
2602                     next_kid = kid;
2603                     goto do_next;
2604                 }
2605                 else if (kid->op_type == OP_LEAVEWHEN)
2606                     list(kid);
2607                 else
2608                     scalarvoid(kid);
2609                 kid = sib;
2610             }
2611             NOT_REACHED; /* NOTREACHED */
2612             break;
2613
2614         }
2615
2616         /* If next_kid is set, someone in the code above wanted us to process
2617          * that kid and all its remaining siblings.  Otherwise, work our way
2618          * back up the tree */
2619       do_next:
2620         while (!next_kid) {
2621             if (o == top_op)
2622                 return top_op; /* at top; no parents/siblings to try */
2623             if (OpHAS_SIBLING(o))
2624                 next_kid = o->op_sibparent;
2625             else {
2626                 o = o->op_sibparent; /*try parent's next sibling */
2627                 switch (o->op_type) {
2628                 case OP_SCOPE:
2629                 case OP_LINESEQ:
2630                 case OP_LIST:
2631                 case OP_LEAVE:
2632                 case OP_LEAVETRY:
2633                     /* should really restore PL_curcop to its old value, but
2634                      * setting it to PL_compiling is better than do nothing */
2635                     PL_curcop = &PL_compiling;
2636                 }
2637             }
2638
2639
2640         }
2641         o = next_kid;
2642     } /* while */
2643 }
2644
2645 /* apply void context to non-final ops of a sequence */
2646
2647 static OP *
2648 S_voidnonfinal(pTHX_ OP *o)
2649 {
2650     if (o) {
2651         const OPCODE type = o->op_type;
2652
2653         if (type == OP_LINESEQ || type == OP_SCOPE ||
2654             type == OP_LEAVE || type == OP_LEAVETRY)
2655         {
2656             OP *kid = cLISTOPo->op_first, *sib;
2657             if(type == OP_LEAVE) {
2658                 /* Don't put the OP_ENTER in void context */
2659                 assert(kid->op_type == OP_ENTER);
2660                 kid = OpSIBLING(kid);
2661             }
2662             for (; kid; kid = sib) {
2663                 if ((sib = OpSIBLING(kid))
2664                  && (  OpHAS_SIBLING(sib) || sib->op_type != OP_NULL
2665                     || (  sib->op_targ != OP_NEXTSTATE
2666                        && sib->op_targ != OP_DBSTATE  )))
2667                 {
2668                     scalarvoid(kid);
2669                 }
2670             }
2671             PL_curcop = &PL_compiling;
2672         }
2673         o->op_flags &= ~OPf_PARENS;
2674         if (PL_hints & HINT_BLOCK_SCOPE)
2675             o->op_flags |= OPf_PARENS;
2676     }
2677     else
2678         o = newOP(OP_STUB, 0);
2679     return o;
2680 }
2681
2682 STATIC OP *
2683 S_modkids(pTHX_ OP *o, I32 type)
2684 {
2685     if (o && o->op_flags & OPf_KIDS) {
2686         OP *kid;
2687         for (kid = cLISTOPo->op_first; kid; kid = OpSIBLING(kid))
2688             op_lvalue(kid, type);
2689     }
2690     return o;
2691 }
2692
2693
2694 /* for a helem/hslice/kvslice, if its a fixed hash, croak on invalid
2695  * const fields. Also, convert CONST keys to HEK-in-SVs.
2696  * rop    is the op that retrieves the hash;
2697  * key_op is the first key
2698  * real   if false, only check (and possibly croak); don't update op
2699  */
2700
2701 STATIC void
2702 S_check_hash_fields_and_hekify(pTHX_ UNOP *rop, SVOP *key_op, int real)
2703 {
2704     PADNAME *lexname;
2705     GV **fields;
2706     bool check_fields;
2707
2708     /* find the padsv corresponding to $lex->{} or @{$lex}{} */
2709     if (rop) {
2710         if (rop->op_first->op_type == OP_PADSV)
2711             /* @$hash{qw(keys here)} */
2712             rop = (UNOP*)rop->op_first;
2713         else {
2714             /* @{$hash}{qw(keys here)} */
2715             if (rop->op_first->op_type == OP_SCOPE
2716                 && cLISTOPx(rop->op_first)->op_last->op_type == OP_PADSV)
2717                 {
2718                     rop = (UNOP*)cLISTOPx(rop->op_first)->op_last;
2719                 }
2720             else
2721                 rop = NULL;
2722         }
2723     }
2724
2725     lexname = NULL; /* just to silence compiler warnings */
2726     fields  = NULL; /* just to silence compiler warnings */
2727
2728     check_fields =
2729             rop
2730          && (lexname = padnamelist_fetch(PL_comppad_name, rop->op_targ),
2731              SvPAD_TYPED(lexname))
2732          && (fields = (GV**)hv_fetchs(PadnameTYPE(lexname), "FIELDS", FALSE))
2733          && isGV(*fields) && GvHV(*fields);
2734
2735     for (; key_op; key_op = (SVOP*)OpSIBLING(key_op)) {
2736         SV **svp, *sv;
2737         if (key_op->op_type != OP_CONST)
2738             continue;
2739         svp = cSVOPx_svp(key_op);
2740
2741         /* make sure it's not a bareword under strict subs */
2742         if (key_op->op_private & OPpCONST_BARE &&
2743             key_op->op_private & OPpCONST_STRICT)
2744         {
2745             no_bareword_allowed((OP*)key_op);
2746         }
2747
2748         /* Make the CONST have a shared SV */
2749         if (   !SvIsCOW_shared_hash(sv = *svp)
2750             && SvTYPE(sv) < SVt_PVMG
2751             && SvOK(sv)
2752             && !SvROK(sv)
2753             && real)
2754         {
2755             SSize_t keylen;
2756             const char * const key = SvPV_const(sv, *(STRLEN*)&keylen);
2757             SV *nsv = newSVpvn_share(key, SvUTF8(sv) ? -keylen : keylen, 0);
2758             SvREFCNT_dec_NN(sv);
2759             *svp = nsv;
2760         }
2761
2762         if (   check_fields
2763             && !hv_fetch_ent(GvHV(*fields), *svp, FALSE, 0))
2764         {
2765             Perl_croak(aTHX_ "No such class field \"%" SVf "\" "
2766                         "in variable %" PNf " of type %" HEKf,
2767                         SVfARG(*svp), PNfARG(lexname),
2768                         HEKfARG(HvNAME_HEK(PadnameTYPE(lexname))));
2769         }
2770     }
2771 }
2772
2773 /* info returned by S_sprintf_is_multiconcatable() */
2774
2775 struct sprintf_ismc_info {
2776     SSize_t nargs;    /* num of args to sprintf (not including the format) */
2777     char  *start;     /* start of raw format string */
2778     char  *end;       /* bytes after end of raw format string */
2779     STRLEN total_len; /* total length (in bytes) of format string, not
2780                          including '%s' and  half of '%%' */
2781     STRLEN variant;   /* number of bytes by which total_len_p would grow
2782                          if upgraded to utf8 */
2783     bool   utf8;      /* whether the format is utf8 */
2784 };
2785
2786
2787 /* is the OP_SPRINTF o suitable for converting into a multiconcat op?
2788  * i.e. its format argument is a const string with only '%s' and '%%'
2789  * formats, and the number of args is known, e.g.
2790  *    sprintf "a=%s f=%s", $a[0], scalar(f());
2791  * but not
2792  *    sprintf "i=%d a=%s f=%s", $i, @a, f();
2793  *
2794  * If successful, the sprintf_ismc_info struct pointed to by info will be
2795  * populated.
2796  */
2797
2798 STATIC bool
2799 S_sprintf_is_multiconcatable(pTHX_ OP *o,struct sprintf_ismc_info *info)
2800 {
2801     OP    *pm, *constop, *kid;
2802     SV    *sv;
2803     char  *s, *e, *p;
2804     SSize_t nargs, nformats;
2805     STRLEN cur, total_len, variant;
2806     bool   utf8;
2807
2808     /* if sprintf's behaviour changes, die here so that someone
2809      * can decide whether to enhance this function or skip optimising
2810      * under those new circumstances */
2811     assert(!(o->op_flags & OPf_STACKED));
2812     assert(!(PL_opargs[OP_SPRINTF] & OA_TARGLEX));
2813     assert(!(o->op_private & ~OPpARG4_MASK));
2814
2815     pm = cUNOPo->op_first;
2816     if (pm->op_type != OP_PUSHMARK) /* weird coreargs stuff */
2817         return FALSE;
2818     constop = OpSIBLING(pm);
2819     if (!constop || constop->op_type != OP_CONST)
2820         return FALSE;
2821     sv = cSVOPx_sv(constop);
2822     if (SvMAGICAL(sv) || !SvPOK(sv))
2823         return FALSE;
2824
2825     s = SvPV(sv, cur);
2826     e = s + cur;
2827
2828     /* Scan format for %% and %s and work out how many %s there are.
2829      * Abandon if other format types are found.
2830      */
2831
2832     nformats  = 0;
2833     total_len = 0;
2834     variant   = 0;
2835
2836     for (p = s; p < e; p++) {
2837         if (*p != '%') {
2838             total_len++;
2839             if (!UTF8_IS_INVARIANT(*p))
2840                 variant++;
2841             continue;
2842         }
2843         p++;
2844         if (p >= e)
2845             return FALSE; /* lone % at end gives "Invalid conversion" */
2846         if (*p == '%')
2847             total_len++;
2848         else if (*p == 's')
2849             nformats++;
2850         else
2851             return FALSE;
2852     }
2853
2854     if (!nformats || nformats > PERL_MULTICONCAT_MAXARG)
2855         return FALSE;
2856
2857     utf8 = cBOOL(SvUTF8(sv));
2858     if (utf8)
2859         variant = 0;
2860
2861     /* scan args; they must all be in scalar cxt */
2862
2863     nargs = 0;
2864     kid = OpSIBLING(constop);
2865
2866     while (kid) {
2867         if ((kid->op_flags & OPf_WANT) != OPf_WANT_SCALAR)
2868             return FALSE;
2869         nargs++;
2870         kid = OpSIBLING(kid);
2871     }
2872
2873     if (nargs != nformats)
2874         return FALSE; /* e.g. sprintf("%s%s", $a); */
2875
2876
2877     info->nargs      = nargs;
2878     info->start      = s;
2879     info->end        = e;
2880     info->total_len  = total_len;
2881     info->variant    = variant;
2882     info->utf8       = utf8;
2883
2884     return TRUE;
2885 }
2886
2887
2888
2889 /* S_maybe_multiconcat():
2890  *
2891  * given an OP_STRINGIFY, OP_SASSIGN, OP_CONCAT or OP_SPRINTF op, possibly
2892  * convert it (and its children) into an OP_MULTICONCAT. See the code
2893  * comments just before pp_multiconcat() for the full details of what
2894  * OP_MULTICONCAT supports.
2895  *
2896  * Basically we're looking for an optree with a chain of OP_CONCATS down
2897  * the LHS (or an OP_SPRINTF), with possibly an OP_SASSIGN, and/or
2898  * OP_STRINGIFY, and/or OP_CONCAT acting as '.=' at its head, e.g.
2899  *
2900  *      $x = "$a$b-$c"
2901  *
2902  *  looks like
2903  *
2904  *      SASSIGN
2905  *         |
2906  *      STRINGIFY   -- PADSV[$x]
2907  *         |
2908  *         |
2909  *      ex-PUSHMARK -- CONCAT/S
2910  *                        |
2911  *                     CONCAT/S  -- PADSV[$d]
2912  *                        |
2913  *                     CONCAT    -- CONST["-"]
2914  *                        |
2915  *                     PADSV[$a] -- PADSV[$b]
2916  *
2917  * Note that at this stage the OP_SASSIGN may have already been optimised
2918  * away with OPpTARGET_MY set on the OP_STRINGIFY or OP_CONCAT.
2919  */
2920
2921 STATIC void
2922 S_maybe_multiconcat(pTHX_ OP *o)
2923 {
2924     OP *lastkidop;   /* the right-most of any kids unshifted onto o */
2925     OP *topop;       /* the top-most op in the concat tree (often equals o,
2926                         unless there are assign/stringify ops above it */
2927     OP *parentop;    /* the parent op of topop (or itself if no parent) */
2928     OP *targmyop;    /* the op (if any) with the OPpTARGET_MY flag */
2929     OP *targetop;    /* the op corresponding to target=... or target.=... */
2930     OP *stringop;    /* the OP_STRINGIFY op, if any */
2931     OP *nextop;      /* used for recreating the op_next chain without consts */
2932     OP *kid;         /* general-purpose op pointer */
2933     UNOP_AUX_item *aux;
2934     UNOP_AUX_item *lenp;
2935     char *const_str, *p;
2936     struct sprintf_ismc_info sprintf_info;
2937
2938                      /* store info about each arg in args[];
2939                       * toparg is the highest used slot; argp is a general
2940                       * pointer to args[] slots */
2941     struct {
2942         void *p;      /* initially points to const sv (or null for op);
2943                          later, set to SvPV(constsv), with ... */
2944         STRLEN len;   /* ... len set to SvPV(..., len) */
2945     } *argp, *toparg, args[PERL_MULTICONCAT_MAXARG*2 + 1];
2946
2947     SSize_t nargs  = 0;
2948     SSize_t nconst = 0;
2949     SSize_t nadjconst  = 0; /* adjacent consts - may be demoted to args */
2950     STRLEN variant;
2951     bool utf8 = FALSE;
2952     bool kid_is_last = FALSE; /* most args will be the RHS kid of a concat op;
2953                                  the last-processed arg will the LHS of one,
2954                                  as args are processed in reverse order */
2955     U8   stacked_last = 0;   /* whether the last seen concat op was STACKED */
2956     STRLEN total_len  = 0;   /* sum of the lengths of the const segments */
2957     U8 flags          = 0;   /* what will become the op_flags and ... */
2958     U8 private_flags  = 0;   /* ... op_private of the multiconcat op */
2959     bool is_sprintf = FALSE; /* we're optimising an sprintf */
2960     bool is_targable  = FALSE; /* targetop is an OPpTARGET_MY candidate */
2961     bool prev_was_const = FALSE; /* previous arg was a const */
2962
2963     /* -----------------------------------------------------------------
2964      * Phase 1:
2965      *
2966      * Examine the optree non-destructively to determine whether it's
2967      * suitable to be converted into an OP_MULTICONCAT. Accumulate
2968      * information about the optree in args[].
2969      */
2970
2971     argp     = args;
2972     targmyop = NULL;
2973     targetop = NULL;
2974     stringop = NULL;
2975     topop    = o;
2976     parentop = o;
2977
2978     assert(   o->op_type == OP_SASSIGN
2979            || o->op_type == OP_CONCAT
2980            || o->op_type == OP_SPRINTF
2981            || o->op_type == OP_STRINGIFY);
2982
2983     Zero(&sprintf_info, 1, struct sprintf_ismc_info);
2984
2985     /* first see if, at the top of the tree, there is an assign,
2986      * append and/or stringify */
2987
2988     if (topop->op_type == OP_SASSIGN) {
2989         /* expr = ..... */
2990         if (o->op_ppaddr != PL_ppaddr[OP_SASSIGN])
2991             return;
2992         if (o->op_private & (OPpASSIGN_BACKWARDS|OPpASSIGN_CV_TO_GV))
2993             return;
2994         assert(!(o->op_private & ~OPpARG2_MASK)); /* barf on unknown flags */
2995
2996         parentop = topop;
2997         topop = cBINOPo->op_first;
2998         targetop = OpSIBLING(topop);
2999         if (!targetop) /* probably some sort of syntax error */
3000             return;
3001
3002         /* don't optimise away assign in 'local $foo = ....' */
3003         if (   (targetop->op_private & OPpLVAL_INTRO)
3004             /* these are the common ops which do 'local', but
3005              * not all */
3006             && (   targetop->op_type == OP_GVSV
3007                 || targetop->op_type == OP_RV2SV
3008                 || targetop->op_type == OP_AELEM
3009                 || targetop->op_type == OP_HELEM
3010                 )
3011         )
3012             return;
3013     }
3014     else if (   topop->op_type == OP_CONCAT
3015              && (topop->op_flags & OPf_STACKED)
3016              && (!(topop->op_private & OPpCONCAT_NESTED))
3017             )
3018     {
3019         /* expr .= ..... */
3020
3021         /* OPpTARGET_MY shouldn't be able to be set here. If it is,
3022          * decide what to do about it */
3023         assert(!(o->op_private & OPpTARGET_MY));
3024
3025         /* barf on unknown flags */
3026         assert(!(o->op_private & ~(OPpARG2_MASK|OPpTARGET_MY)));
3027         private_flags |= OPpMULTICONCAT_APPEND;
3028         targetop = cBINOPo->op_first;
3029         parentop = topop;
3030         topop    = OpSIBLING(targetop);
3031
3032         /* $x .= <FOO> gets optimised to rcatline instead */
3033         if (topop->op_type == OP_READLINE)
3034             return;
3035     }
3036
3037     if (targetop) {
3038         /* Can targetop (the LHS) if it's a padsv, be optimised
3039          * away and use OPpTARGET_MY instead?
3040          */
3041         if (    (targetop->op_type == OP_PADSV)
3042             && !(targetop->op_private & OPpDEREF)
3043             && !(targetop->op_private & OPpPAD_STATE)
3044                /* we don't support 'my $x .= ...' */
3045             && (   o->op_type == OP_SASSIGN
3046                 || !(targetop->op_private & OPpLVAL_INTRO))
3047         )
3048             is_targable = TRUE;
3049     }
3050
3051     if (topop->op_type == OP_STRINGIFY) {
3052         if (topop->op_ppaddr != PL_ppaddr[OP_STRINGIFY])
3053             return;
3054         stringop = topop;
3055
3056         /* barf on unknown flags */
3057         assert(!(o->op_private & ~(OPpARG4_MASK|OPpTARGET_MY)));
3058
3059         if ((topop->op_private & OPpTARGET_MY)) {
3060             if (o->op_type == OP_SASSIGN)
3061                 return; /* can't have two assigns */
3062             targmyop = topop;
3063         }
3064
3065         private_flags |= OPpMULTICONCAT_STRINGIFY;
3066         parentop = topop;
3067         topop = cBINOPx(topop)->op_first;
3068         assert(OP_TYPE_IS_OR_WAS_NN(topop, OP_PUSHMARK));
3069         topop = OpSIBLING(topop);
3070     }
3071
3072     if (topop->op_type == OP_SPRINTF) {
3073         if (topop->op_ppaddr != PL_ppaddr[OP_SPRINTF])
3074             return;
3075         if (S_sprintf_is_multiconcatable(aTHX_ topop, &sprintf_info)) {
3076             nargs     = sprintf_info.nargs;
3077             total_len = sprintf_info.total_len;
3078             variant   = sprintf_info.variant;
3079             utf8      = sprintf_info.utf8;
3080             is_sprintf = TRUE;
3081             private_flags |= OPpMULTICONCAT_FAKE;
3082             toparg = argp;
3083             /* we have an sprintf op rather than a concat optree.
3084              * Skip most of the code below which is associated with
3085              * processing that optree. We also skip phase 2, determining
3086              * whether its cost effective to optimise, since for sprintf,
3087              * multiconcat is *always* faster */
3088             goto create_aux;
3089         }
3090         /* note that even if the sprintf itself isn't multiconcatable,
3091          * the expression as a whole may be, e.g. in
3092          *    $x .= sprintf("%d",...)
3093          * the sprintf op will be left as-is, but the concat/S op may
3094          * be upgraded to multiconcat
3095          */
3096     }
3097     else if (topop->op_type == OP_CONCAT) {
3098         if (topop->op_ppaddr != PL_ppaddr[OP_CONCAT])
3099             return;
3100
3101         if ((topop->op_private & OPpTARGET_MY)) {
3102             if (o->op_type == OP_SASSIGN || targmyop)
3103                 return; /* can't have two assigns */
3104             targmyop = topop;
3105         }
3106     }
3107
3108     /* Is it safe to convert a sassign/stringify/concat op into
3109      * a multiconcat? */
3110     assert((PL_opargs[OP_SASSIGN]   & OA_CLASS_MASK) == OA_BINOP);
3111     assert((PL_opargs[OP_CONCAT]    & OA_CLASS_MASK) == OA_BINOP);
3112     assert((PL_opargs[OP_STRINGIFY] & OA_CLASS_MASK) == OA_LISTOP);
3113     assert((PL_opargs[OP_SPRINTF]   & OA_CLASS_MASK) == OA_LISTOP);
3114     STATIC_ASSERT_STMT(   STRUCT_OFFSET(BINOP,    op_last)
3115                        == STRUCT_OFFSET(UNOP_AUX, op_aux));
3116     STATIC_ASSERT_STMT(   STRUCT_OFFSET(LISTOP,   op_last)
3117                        == STRUCT_OFFSET(UNOP_AUX, op_aux));
3118
3119     /* Now scan the down the tree looking for a series of
3120      * CONCAT/OPf_STACKED ops on the LHS (with the last one not
3121      * stacked). For example this tree:
3122      *
3123      *     |
3124      *   CONCAT/STACKED
3125      *     |
3126      *   CONCAT/STACKED -- EXPR5
3127      *     |
3128      *   CONCAT/STACKED -- EXPR4
3129      *     |
3130      *   CONCAT -- EXPR3
3131      *     |
3132      *   EXPR1  -- EXPR2
3133      *
3134      * corresponds to an expression like
3135      *
3136      *   (EXPR1 . EXPR2 . EXPR3 . EXPR4 . EXPR5)
3137      *
3138      * Record info about each EXPR in args[]: in particular, whether it is
3139      * a stringifiable OP_CONST and if so what the const sv is.
3140      *
3141      * The reason why the last concat can't be STACKED is the difference
3142      * between
3143      *
3144      *    ((($a .= $a) .= $a) .= $a) .= $a
3145      *
3146      * and
3147      *    $a . $a . $a . $a . $a
3148      *
3149      * The main difference between the optrees for those two constructs
3150      * is the presence of the last STACKED. As well as modifying $a,
3151      * the former sees the changed $a between each concat, so if $s is
3152      * initially 'a', the first returns 'a' x 16, while the latter returns
3153      * 'a' x 5. And pp_multiconcat can't handle that kind of thing.
3154      */
3155
3156     kid = topop;
3157
3158     for (;;) {
3159         OP *argop;
3160         SV *sv;
3161         bool last = FALSE;
3162
3163         if (    kid->op_type == OP_CONCAT
3164             && !kid_is_last
3165         ) {
3166             OP *k1, *k2;
3167             k1 = cUNOPx(kid)->op_first;
3168             k2 = OpSIBLING(k1);
3169             /* shouldn't happen except maybe after compile err? */
3170             if (!k2)
3171                 return;
3172
3173             /* avoid turning (A . B . ($lex = C) ...)  into  (A . B . C ...) */
3174             if (kid->op_private & OPpTARGET_MY)
3175                 kid_is_last = TRUE;
3176
3177             stacked_last = (kid->op_flags & OPf_STACKED);
3178             if (!stacked_last)
3179                 kid_is_last = TRUE;
3180
3181             kid   = k1;
3182             argop = k2;
3183         }
3184         else {
3185             argop = kid;
3186             last = TRUE;
3187         }
3188
3189         if (   nargs + nadjconst  >  PERL_MULTICONCAT_MAXARG        - 2
3190             || (argp - args + 1)  > (PERL_MULTICONCAT_MAXARG*2 + 1) - 2)
3191         {
3192             /* At least two spare slots are needed to decompose both
3193              * concat args. If there are no slots left, continue to
3194              * examine the rest of the optree, but don't push new values
3195              * on args[]. If the optree as a whole is legal for conversion
3196              * (in particular that the last concat isn't STACKED), then
3197              * the first PERL_MULTICONCAT_MAXARG elements of the optree
3198              * can be converted into an OP_MULTICONCAT now, with the first
3199              * child of that op being the remainder of the optree -
3200              * which may itself later be converted to a multiconcat op
3201              * too.
3202              */
3203             if (last) {
3204                 /* the last arg is the rest of the optree */
3205                 argp++->p = NULL;
3206                 nargs++;
3207             }
3208         }
3209         else if (   argop->op_type == OP_CONST
3210             && ((sv = cSVOPx_sv(argop)))
3211             /* defer stringification until runtime of 'constant'
3212              * things that might stringify variantly, e.g. the radix
3213              * point of NVs, or overloaded RVs */
3214             && (SvPOK(sv) || SvIOK(sv))
3215             && (!SvGMAGICAL(sv))
3216         ) {
3217             if (argop->op_private & OPpCONST_STRICT)
3218                 no_bareword_allowed(argop);
3219             argp++->p = sv;
3220             utf8   |= cBOOL(SvUTF8(sv));
3221             nconst++;
3222             if (prev_was_const)
3223                 /* this const may be demoted back to a plain arg later;
3224                  * make sure we have enough arg slots left */
3225                 nadjconst++;
3226             prev_was_const = !prev_was_const;
3227         }
3228         else {
3229             argp++->p = NULL;
3230             nargs++;
3231             prev_was_const = FALSE;
3232         }
3233
3234         if (last)
3235             break;
3236     }
3237
3238     toparg = argp - 1;
3239
3240     if (stacked_last)
3241         return; /* we don't support ((A.=B).=C)...) */
3242
3243     /* look for two adjacent consts and don't fold them together:
3244      *     $o . "a" . "b"
3245      * should do
3246      *     $o->concat("a")->concat("b")
3247      * rather than
3248      *     $o->concat("ab")
3249      * (but $o .=  "a" . "b" should still fold)
3250      */
3251     {
3252         bool seen_nonconst = FALSE;
3253         for (argp = toparg; argp >= args; argp--) {
3254             if (argp->p == NULL) {
3255                 seen_nonconst = TRUE;
3256                 continue;
3257             }
3258             if (!seen_nonconst)
3259                 continue;
3260             if (argp[1].p) {
3261                 /* both previous and current arg were constants;
3262                  * leave the current OP_CONST as-is */
3263                 argp->p = NULL;
3264                 nconst--;
3265                 nargs++;
3266             }
3267         }
3268     }
3269
3270     /* -----------------------------------------------------------------
3271      * Phase 2:
3272      *
3273      * At this point we have determined that the optree *can* be converted
3274      * into a multiconcat. Having gathered all the evidence, we now decide
3275      * whether it *should*.
3276      */
3277
3278
3279     /* we need at least one concat action, e.g.:
3280      *
3281      *  Y . Z
3282      *  X = Y . Z
3283      *  X .= Y
3284      *
3285      * otherwise we could be doing something like $x = "foo", which
3286      * if treated as a concat, would fail to COW.
3287      */
3288     if (nargs + nconst + cBOOL(private_flags & OPpMULTICONCAT_APPEND) < 2)
3289         return;
3290
3291     /* Benchmarking seems to indicate that we gain if:
3292      * * we optimise at least two actions into a single multiconcat
3293      *    (e.g concat+concat, sassign+concat);
3294      * * or if we can eliminate at least 1 OP_CONST;
3295      * * or if we can eliminate a padsv via OPpTARGET_MY
3296      */
3297
3298     if (
3299            /* eliminated at least one OP_CONST */
3300            nconst >= 1
3301            /* eliminated an OP_SASSIGN */
3302         || o->op_type == OP_SASSIGN
3303            /* eliminated an OP_PADSV */
3304         || (!targmyop && is_targable)
3305     )
3306         /* definitely a net gain to optimise */
3307         goto optimise;
3308
3309     /* ... if not, what else? */
3310
3311     /* special-case '$lex1 = expr . $lex1' (where expr isn't lex1):
3312      * multiconcat is faster (due to not creating a temporary copy of
3313      * $lex1), whereas for a general $lex1 = $lex2 . $lex3, concat is
3314      * faster.
3315      */
3316     if (   nconst == 0
3317          && nargs == 2
3318          && targmyop
3319          && topop->op_type == OP_CONCAT
3320     ) {
3321         PADOFFSET t = targmyop->op_targ;
3322         OP *k1 = cBINOPx(topop)->op_first;
3323         OP *k2 = cBINOPx(topop)->op_last;
3324         if (   k2->op_type == OP_PADSV
3325             && k2->op_targ == t
3326             && (   k1->op_type != OP_PADSV
3327                 || k1->op_targ != t)
3328         )
3329             goto optimise;
3330     }
3331
3332     /* need at least two concats */
3333     if (nargs + nconst + cBOOL(private_flags & OPpMULTICONCAT_APPEND) < 3)
3334         return;
3335
3336
3337
3338     /* -----------------------------------------------------------------
3339      * Phase 3:
3340      *
3341      * At this point the optree has been verified as ok to be optimised
3342      * into an OP_MULTICONCAT. Now start changing things.
3343      */
3344
3345    optimise:
3346
3347     /* stringify all const args and determine utf8ness */
3348
3349     variant = 0;
3350     for (argp = args; argp <= toparg; argp++) {
3351         SV *sv = (SV*)argp->p;
3352         if (!sv)
3353             continue; /* not a const op */
3354         if (utf8 && !SvUTF8(sv))
3355             sv_utf8_upgrade_nomg(sv);
3356         argp->p = SvPV_nomg(sv, argp->len);
3357         total_len += argp->len;
3358
3359         /* see if any strings would grow if converted to utf8 */
3360         if (!utf8) {
3361             variant += variant_under_utf8_count((U8 *) argp->p,
3362                                                 (U8 *) argp->p + argp->len);
3363         }
3364     }
3365
3366     /* create and populate aux struct */
3367
3368   create_aux:
3369
3370     aux = (UNOP_AUX_item*)PerlMemShared_malloc(
3371                     sizeof(UNOP_AUX_item)
3372                     *  (
3373                            PERL_MULTICONCAT_HEADER_SIZE
3374                          + ((nargs + 1) * (variant ? 2 : 1))
3375                         )
3376                     );
3377     const_str = (char *)PerlMemShared_malloc(total_len ? total_len : 1);
3378
3379     /* Extract all the non-const expressions from the concat tree then
3380      * dispose of the old tree, e.g. convert the tree from this:
3381      *
3382      *  o => SASSIGN
3383      *         |
3384      *       STRINGIFY   -- TARGET
3385      *         |
3386      *       ex-PUSHMARK -- CONCAT
3387      *                        |
3388      *                      CONCAT -- EXPR5
3389      *                        |
3390      *                      CONCAT -- EXPR4
3391      *                        |
3392      *                      CONCAT -- EXPR3
3393      *                        |
3394      *                      EXPR1  -- EXPR2
3395      *
3396      *
3397      * to:
3398      *
3399      *  o => MULTICONCAT
3400      *         |
3401      *       ex-PUSHMARK -- EXPR1 -- EXPR2 -- EXPR3 -- EXPR4 -- EXPR5 -- TARGET
3402      *
3403      * except that if EXPRi is an OP_CONST, it's discarded.
3404      *
3405      * During the conversion process, EXPR ops are stripped from the tree
3406      * and unshifted onto o. Finally, any of o's remaining original
3407      * childen are discarded and o is converted into an OP_MULTICONCAT.
3408      *
3409      * In this middle of this, o may contain both: unshifted args on the
3410      * left, and some remaining original args on the right. lastkidop
3411      * is set to point to the right-most unshifted arg to delineate
3412      * between the two sets.
3413      */
3414
3415
3416     if (is_sprintf) {
3417         /* create a copy of the format with the %'s removed, and record
3418          * the sizes of the const string segments in the aux struct */
3419         char *q, *oldq;
3420         lenp = aux + PERL_MULTICONCAT_IX_LENGTHS;
3421
3422         p    = sprintf_info.start;
3423         q    = const_str;
3424         oldq = q;
3425         for (; p < sprintf_info.end; p++) {
3426             if (*p == '%') {
3427                 p++;
3428                 if (*p != '%') {
3429                     (lenp++)->ssize = q - oldq;
3430                     oldq = q;
3431                     continue;
3432                 }
3433             }
3434             *q++ = *p;
3435         }
3436         lenp->ssize = q - oldq;
3437         assert((STRLEN)(q - const_str) == total_len);
3438
3439         /* Attach all the args (i.e. the kids of the sprintf) to o (which
3440          * may or may not be topop) The pushmark and const ops need to be
3441          * kept in case they're an op_next entry point.
3442          */
3443         lastkidop = cLISTOPx(topop)->op_last;
3444         kid = cUNOPx(topop)->op_first; /* pushmark */
3445         op_null(kid);
3446         op_null(OpSIBLING(kid));       /* const */
3447         if (o != topop) {
3448             kid = op_sibling_splice(topop, NULL, -1, NULL); /* cut all args */
3449             op_sibling_splice(o, NULL, 0, kid); /* and attach to o */
3450             lastkidop->op_next = o;
3451         }
3452     }
3453     else {
3454         p = const_str;
3455         lenp = aux + PERL_MULTICONCAT_IX_LENGTHS;
3456
3457         lenp->ssize = -1;
3458
3459         /* Concatenate all const strings into const_str.
3460          * Note that args[] contains the RHS args in reverse order, so
3461          * we scan args[] from top to bottom to get constant strings
3462          * in L-R order
3463          */
3464         for (argp = toparg; argp >= args; argp--) {
3465             if (!argp->p)
3466                 /* not a const op */
3467                 (++lenp)->ssize = -1;
3468             else {
3469                 STRLEN l = argp->len;
3470                 Copy(argp->p, p, l, char);
3471                 p += l;
3472                 if (lenp->ssize == -1)
3473                     lenp->ssize = l;
3474                 else
3475                     lenp->ssize += l;
3476             }
3477         }
3478
3479         kid = topop;
3480         nextop = o;
3481         lastkidop = NULL;
3482
3483         for (argp = args; argp <= toparg; argp++) {
3484             /* only keep non-const args, except keep the first-in-next-chain
3485              * arg no matter what it is (but nulled if OP_CONST), because it
3486              * may be the entry point to this subtree from the previous
3487              * op_next.
3488              */
3489             bool last = (argp == toparg);
3490             OP *prev;
3491
3492             /* set prev to the sibling *before* the arg to be cut out,
3493              * e.g. when cutting EXPR:
3494              *
3495              *         |
3496              * kid=  CONCAT
3497              *         |
3498              * prev= CONCAT -- EXPR
3499              *         |
3500              */
3501             if (argp == args && kid->op_type != OP_CONCAT) {
3502                 /* in e.g. '$x .= f(1)' there's no RHS concat tree
3503                  * so the expression to be cut isn't kid->op_last but
3504                  * kid itself */
3505                 OP *o1, *o2;
3506                 /* find the op before kid */
3507                 o1 = NULL;
3508                 o2 = cUNOPx(parentop)->op_first;
3509                 while (o2 && o2 != kid) {
3510                     o1 = o2;
3511                     o2 = OpSIBLING(o2);
3512                 }
3513                 assert(o2 == kid);
3514                 prev = o1;
3515                 kid  = parentop;
3516             }
3517             else if (kid == o && lastkidop)
3518                 prev = last ? lastkidop : OpSIBLING(lastkidop);
3519             else
3520                 prev = last ? NULL : cUNOPx(kid)->op_first;
3521
3522             if (!argp->p || last) {
3523                 /* cut RH op */
3524                 OP *aop = op_sibling_splice(kid, prev, 1, NULL);
3525                 /* and unshift to front of o */
3526                 op_sibling_splice(o, NULL, 0, aop);
3527                 /* record the right-most op added to o: later we will
3528                  * free anything to the right of it */
3529                 if (!lastkidop)
3530                     lastkidop = aop;
3531                 aop->op_next = nextop;
3532                 if (last) {
3533                     if (argp->p)
3534                         /* null the const at start of op_next chain */
3535                         op_null(aop);
3536                 }
3537                 else if (prev)
3538                     nextop = prev->op_next;
3539             }
3540
3541             /* the last two arguments are both attached to the same concat op */
3542             if (argp < toparg - 1)
3543                 kid = prev;
3544         }
3545     }
3546
3547     /* Populate the aux struct */
3548
3549     aux[PERL_MULTICONCAT_IX_NARGS].ssize     = nargs;
3550     aux[PERL_MULTICONCAT_IX_PLAIN_PV].pv    = utf8 ? NULL : const_str;
3551     aux[PERL_MULTICONCAT_IX_PLAIN_LEN].ssize = utf8 ?    0 : total_len;
3552     aux[PERL_MULTICONCAT_IX_UTF8_PV].pv     = const_str;
3553     aux[PERL_MULTICONCAT_IX_UTF8_LEN].ssize  = total_len;
3554
3555     /* if variant > 0, calculate a variant const string and lengths where
3556      * the utf8 version of the string will take 'variant' more bytes than
3557      * the plain one. */
3558
3559     if (variant) {
3560         char              *p = const_str;
3561         STRLEN          ulen = total_len + variant;
3562         UNOP_AUX_item  *lens = aux + PERL_MULTICONCAT_IX_LENGTHS;
3563         UNOP_AUX_item *ulens = lens + (nargs + 1);
3564         char             *up = (char*)PerlMemShared_malloc(ulen);
3565         SSize_t            n;
3566
3567         aux[PERL_MULTICONCAT_IX_UTF8_PV].pv    = up;
3568         aux[PERL_MULTICONCAT_IX_UTF8_LEN].ssize = ulen;
3569
3570         for (n = 0; n < (nargs + 1); n++) {
3571             SSize_t i;
3572             char * orig_up = up;
3573             for (i = (lens++)->ssize; i > 0; i--) {
3574                 U8 c = *p++;
3575                 append_utf8_from_native_byte(c, (U8**)&up);
3576             }
3577             (ulens++)->ssize = (i < 0) ? i : up - orig_up;
3578         }
3579     }
3580
3581     if (stringop) {
3582         /* if there was a top(ish)-level OP_STRINGIFY, we need to keep
3583          * that op's first child - an ex-PUSHMARK - because the op_next of
3584          * the previous op may point to it (i.e. it's the entry point for
3585          * the o optree)
3586          */
3587         OP *pmop =
3588             (stringop == o)
3589                 ? op_sibling_splice(o, lastkidop, 1, NULL)
3590                 : op_sibling_splice(stringop, NULL, 1, NULL);
3591         assert(OP_TYPE_IS_OR_WAS_NN(pmop, OP_PUSHMARK));
3592         op_sibling_splice(o, NULL, 0, pmop);
3593         if (!lastkidop)
3594             lastkidop = pmop;
3595     }
3596
3597     /* Optimise
3598      *    target  = A.B.C...
3599      *    target .= A.B.C...
3600      */
3601
3602     if (targetop) {
3603         assert(!targmyop);
3604
3605         if (o->op_type == OP_SASSIGN) {
3606             /* Move the target subtree from being the last of o's children
3607              * to being the last of o's preserved children.
3608              * Note the difference between 'target = ...' and 'target .= ...':
3609              * for the former, target is executed last; for the latter,
3610              * first.
3611              */
3612             kid = OpSIBLING(lastkidop);
3613             op_sibling_splice(o, kid, 1, NULL); /* cut target op */
3614             op_sibling_splice(o, lastkidop, 0, targetop); /* and paste */
3615             lastkidop->op_next = kid->op_next;
3616             lastkidop = targetop;
3617         }
3618         else {
3619             /* Move the target subtree from being the first of o's
3620              * original children to being the first of *all* o's children.
3621              */
3622             if (lastkidop) {
3623                 op_sibling_splice(o, lastkidop, 1, NULL); /* cut target op */
3624                 op_sibling_splice(o, NULL, 0, targetop);  /* and paste*/
3625             }
3626             else {
3627                 /* if the RHS of .= doesn't contain a concat (e.g.
3628                  * $x .= "foo"), it gets missed by the "strip ops from the
3629                  * tree and add to o" loop earlier */
3630                 assert(topop->op_type != OP_CONCAT);
3631                 if (stringop) {
3632                     /* in e.g. $x .= "$y", move the $y expression
3633                      * from being a child of OP_STRINGIFY to being the
3634                      * second child of the OP_CONCAT
3635                      */
3636                     assert(cUNOPx(stringop)->op_first == topop);
3637                     op_sibling_splice(stringop, NULL, 1, NULL);
3638                     op_sibling_splice(o, cUNOPo->op_first, 0, topop);
3639                 }
3640                 assert(topop == OpSIBLING(cBINOPo->op_first));
3641                 if (toparg->p)
3642                     op_null(topop);
3643                 lastkidop = topop;
3644             }
3645         }
3646
3647         if (is_targable) {
3648             /* optimise
3649              *  my $lex  = A.B.C...
3650              *     $lex  = A.B.C...
3651              *     $lex .= A.B.C...
3652              * The original padsv op is kept but nulled in case it's the
3653              * entry point for the optree (which it will be for
3654              * '$lex .=  ... '
3655              */
3656             private_flags |= OPpTARGET_MY;
3657             private_flags |= (targetop->op_private & OPpLVAL_INTRO);
3658             o->op_targ = targetop->op_targ;
3659             targetop->op_targ = 0;
3660             op_null(targetop);
3661         }
3662         else
3663             flags |= OPf_STACKED;
3664     }
3665     else if (targmyop) {
3666         private_flags |= OPpTARGET_MY;
3667         if (o != targmyop) {
3668             o->op_targ = targmyop->op_targ;
3669             targmyop->op_targ = 0;
3670         }
3671     }
3672
3673     /* detach the emaciated husk of the sprintf/concat optree and free it */
3674     for (;;) {
3675         kid = op_sibling_splice(o, lastkidop, 1, NULL);
3676         if (!kid)
3677             break;
3678         op_free(kid);
3679     }
3680
3681     /* and convert o into a multiconcat */
3682
3683     o->op_flags        = (flags|OPf_KIDS|stacked_last
3684                          |(o->op_flags & (OPf_WANT|OPf_PARENS)));
3685     o->op_private      = private_flags;
3686     o->op_type         = OP_MULTICONCAT;
3687     o->op_ppaddr       = PL_ppaddr[OP_MULTICONCAT];
3688     cUNOP_AUXo->op_aux = aux;
3689 }
3690
3691
3692 /* do all the final processing on an optree (e.g. running the peephole
3693  * optimiser on it), then attach it to cv (if cv is non-null)
3694  */
3695
3696 static void
3697 S_process_optree(pTHX_ CV *cv, OP *optree, OP* start)
3698 {
3699     OP **startp;
3700
3701     /* XXX for some reason, evals, require and main optrees are
3702      * never attached to their CV; instead they just hang off
3703      * PL_main_root + PL_main_start or PL_eval_root + PL_eval_start
3704      * and get manually freed when appropriate */
3705     if (cv)
3706         startp = &CvSTART(cv);
3707     else
3708         startp = PL_in_eval? &PL_eval_start : &PL_main_start;
3709
3710     *startp = start;
3711     optree->op_private |= OPpREFCOUNTED;
3712     OpREFCNT_set(optree, 1);
3713     optimize_optree(optree);
3714     CALL_PEEP(*startp);
3715     finalize_optree(optree);
3716     S_prune_chain_head(startp);
3717
3718     if (cv) {
3719         /* now that optimizer has done its work, adjust pad values */
3720         pad_tidy(optree->op_type == OP_LEAVEWRITE ? padtidy_FORMAT
3721                  : CvCLONE(cv) ? padtidy_SUBCLONE : padtidy_SUB);
3722     }
3723 }
3724
3725
3726 /*
3727 =for apidoc optimize_optree
3728
3729 This function applies some optimisations to the optree in top-down order.
3730 It is called before the peephole optimizer, which processes ops in
3731 execution order. Note that finalize_optree() also does a top-down scan,
3732 but is called *after* the peephole optimizer.
3733
3734 =cut
3735 */
3736
3737 void
3738 Perl_optimize_optree(pTHX_ OP* o)
3739 {
3740     PERL_ARGS_ASSERT_OPTIMIZE_OPTREE;
3741
3742     ENTER;
3743     SAVEVPTR(PL_curcop);
3744
3745     optimize_op(o);
3746
3747     LEAVE;
3748 }
3749
3750
3751 #define warn_implicit_snail_cvsig(o)  S_warn_implicit_snail_cvsig(aTHX_ o)
3752 static void
3753 S_warn_implicit_snail_cvsig(pTHX_ OP *o)
3754 {
3755     CV *cv = PL_compcv;
3756     while(cv && CvEVAL(cv))
3757         cv = CvOUTSIDE(cv);
3758
3759     if(cv && CvSIGNATURE(cv))
3760         Perl_ck_warner_d(aTHX_ packWARN(WARN_EXPERIMENTAL__ARGS_ARRAY_WITH_SIGNATURES),
3761             "Implicit use of @_ in %s with signatured subroutine is experimental", OP_DESC(o));
3762 }
3763
3764 #define OP_ZOOM(o)  (OP_TYPE_IS(o, OP_NULL) ? cUNOPx(o)->op_first : (o))
3765
3766 /* helper for optimize_optree() which optimises one op then recurses
3767  * to optimise any children.
3768  */
3769
3770 STATIC void
3771 S_optimize_op(pTHX_ OP* o)
3772 {
3773     OP *top_op = o;
3774
3775     PERL_ARGS_ASSERT_OPTIMIZE_OP;
3776
3777     while (1) {
3778         OP * next_kid = NULL;
3779
3780         assert(o->op_type != OP_FREED);
3781
3782         switch (o->op_type) {
3783         case OP_NEXTSTATE:
3784         case OP_DBSTATE:
3785             PL_curcop = ((COP*)o);              /* for warnings */
3786             break;
3787
3788
3789         case OP_CONCAT:
3790         case OP_SASSIGN:
3791         case OP_STRINGIFY:
3792         case OP_SPRINTF:
3793             S_maybe_multiconcat(aTHX_ o);
3794             break;
3795
3796         case OP_SUBST:
3797             if (cPMOPo->op_pmreplrootu.op_pmreplroot) {
3798                 /* we can't assume that op_pmreplroot->op_sibparent == o
3799                  * and that it is thus possible to walk back up the tree
3800                  * past op_pmreplroot. So, although we try to avoid
3801                  * recursing through op trees, do it here. After all,
3802                  * there are unlikely to be many nested s///e's within
3803                  * the replacement part of a s///e.
3804                  */
3805                 optimize_op(cPMOPo->op_pmreplrootu.op_pmreplroot);
3806             }
3807             break;
3808
3809         case OP_RV2AV:
3810         {
3811             OP *first = (o->op_flags & OPf_KIDS) ? cUNOPo->op_first : NULL;
3812             CV *cv = PL_compcv;
3813             while(cv && CvEVAL(cv))
3814                 cv = CvOUTSIDE(cv);
3815
3816             if(cv && CvSIGNATURE(cv) &&
3817                     OP_TYPE_IS(first, OP_GV) && cGVOPx_gv(first) == PL_defgv) {
3818                 OP *parent = op_parent(o);
3819                 while(OP_TYPE_IS(parent, OP_NULL))
3820                     parent = op_parent(parent);
3821
3822                 Perl_ck_warner_d(aTHX_ packWARN(WARN_EXPERIMENTAL__ARGS_ARRAY_WITH_SIGNATURES),
3823                     "Use of @_ in %s with signatured subroutine is experimental", OP_DESC(parent));
3824             }
3825             break;
3826         }
3827
3828         case OP_SHIFT:
3829         case OP_POP:
3830             if(!CvUNIQUE(PL_compcv) && !(o->op_flags & OPf_KIDS))
3831                 warn_implicit_snail_cvsig(o);
3832             break;
3833
3834         case OP_ENTERSUB:
3835             if(!(o->op_flags & OPf_STACKED))
3836                 warn_implicit_snail_cvsig(o);
3837             break;
3838
3839         case OP_GOTO:
3840         {
3841             OP *first = (o->op_flags & OPf_KIDS) ? cUNOPo->op_first : NULL;
3842             OP *ffirst;
3843             if(OP_TYPE_IS(first, OP_SREFGEN) &&
3844                     (ffirst = OP_ZOOM(cUNOPx(first)->op_first)) &&
3845                     OP_TYPE_IS(ffirst, OP_RV2CV))
3846                 warn_implicit_snail_cvsig(o);
3847             break;
3848         }
3849
3850         default:
3851             break;
3852         }
3853
3854         if (o->op_flags & OPf_KIDS)
3855             next_kid = cUNOPo->op_first;
3856
3857         /* if a kid hasn't been nominated to process, continue with the
3858          * next sibling, or if no siblings left, go back to the parent's
3859          * siblings and so on
3860          */
3861         while (!next_kid) {
3862             if (o == top_op)
3863                 return; /* at top; no parents/siblings to try */
3864             if (OpHAS_SIBLING(o))
3865                 next_kid = o->op_sibparent;
3866             else
3867                 o = o->op_sibparent; /*try parent's next sibling */
3868         }
3869
3870       /* this label not yet used. Goto here if any code above sets
3871        * next-kid
3872        get_next_op:
3873        */
3874         o = next_kid;
3875     }
3876 }
3877
3878
3879 /*
3880 =for apidoc finalize_optree
3881
3882 This function finalizes the optree.  Should be called directly after
3883 the complete optree is built.  It does some additional
3884 checking which can't be done in the normal C<ck_>xxx functions and makes
3885 the tree thread-safe.
3886
3887 =cut
3888 */
3889 void
3890 Perl_finalize_optree(pTHX_ OP* o)
3891 {
3892     PERL_ARGS_ASSERT_FINALIZE_OPTREE;
3893
3894     ENTER;
3895     SAVEVPTR(PL_curcop);
3896
3897     finalize_op(o);
3898
3899     LEAVE;
3900 }
3901
3902 #ifdef USE_ITHREADS
3903 /* Relocate sv to the pad for thread safety.
3904  * Despite being a "constant", the SV is written to,
3905  * for reference counts, sv_upgrade() etc. */
3906 PERL_STATIC_INLINE void
3907 S_op_relocate_sv(pTHX_ SV** svp, PADOFFSET* targp)
3908 {
3909     PADOFFSET ix;
3910     PERL_ARGS_ASSERT_OP_RELOCATE_SV;
3911     if (!*svp) return;
3912     ix = pad_alloc(OP_CONST, SVf_READONLY);
3913     SvREFCNT_dec(PAD_SVl(ix));
3914     PAD_SETSV(ix, *svp);
3915     /* XXX I don't know how this isn't readonly already. */
3916     if (!SvIsCOW(PAD_SVl(ix))) SvREADONLY_on(PAD_SVl(ix));
3917     *svp = NULL;
3918     *targp = ix;
3919 }
3920 #endif
3921
3922 /*
3923 =for apidoc traverse_op_tree
3924
3925 Return the next op in a depth-first traversal of the op tree,
3926 returning NULL when the traversal is complete.
3927
3928 The initial call must supply the root of the tree as both top and o.
3929
3930 For now it's static, but it may be exposed to the API in the future.
3931
3932 =cut
3933 */
3934
3935 STATIC OP*
3936 S_traverse_op_tree(pTHX_ OP *top, OP *o) {
3937     OP *sib;
3938
3939     PERL_ARGS_ASSERT_TRAVERSE_OP_TREE;
3940
3941     if ((o->op_flags & OPf_KIDS) && cUNOPo->op_first) {
3942         return cUNOPo->op_first;
3943     }
3944     else if ((sib = OpSIBLING(o))) {
3945         return sib;
3946     }
3947     else {
3948         OP *parent = o->op_sibparent;
3949         assert(!(o->op_moresib));
3950         while (parent && parent != top) {
3951             OP *sib = OpSIBLING(parent);
3952             if (sib)
3953                 return sib;
3954             parent = parent->op_sibparent;
3955         }
3956
3957         return NULL;
3958     }
3959 }
3960
3961 STATIC void
3962 S_finalize_op(pTHX_ OP* o)
3963 {
3964     OP * const top = o;
3965     PERL_ARGS_ASSERT_FINALIZE_OP;
3966
3967     do {
3968         assert(o->op_type != OP_FREED);
3969
3970         switch (o->op_type) {
3971         case OP_NEXTSTATE:
3972         case OP_DBSTATE:
3973             PL_curcop = ((COP*)o);              /* for warnings */
3974             break;
3975         case OP_EXEC:
3976             if (OpHAS_SIBLING(o)) {
3977                 OP *sib = OpSIBLING(o);
3978                 if ((  sib->op_type == OP_NEXTSTATE || sib->op_type == OP_DBSTATE)
3979                     && ckWARN(WARN_EXEC)
3980                     && OpHAS_SIBLING(sib))
3981                 {
3982                     const OPCODE type = OpSIBLING(sib)->op_type;
3983                     if (type != OP_EXIT && type != OP_WARN && type != OP_DIE) {
3984                         const line_t oldline = CopLINE(PL_curcop);
3985                         CopLINE_set(PL_curcop, CopLINE((COP*)sib));
3986                         Perl_warner(aTHX_ packWARN(WARN_EXEC),
3987                             "Statement unlikely to be reached");
3988                         Perl_warner(aTHX_ packWARN(WARN_EXEC),
3989                             "\t(Maybe you meant system() when you said exec()?)\n");
3990                         CopLINE_set(PL_curcop, oldline);
3991                     }
3992                 }
3993             }
3994             break;
3995
3996         case OP_GV:
3997             if ((o->op_private & OPpEARLY_CV) && ckWARN(WARN_PROTOTYPE)) {
3998                 GV * const gv = cGVOPo_gv;
3999                 if (SvTYPE(gv) == SVt_PVGV && GvCV(gv) && SvPVX_const(GvCV(gv))) {
4000                     /* XXX could check prototype here instead of just carping */
4001                     SV * const sv = sv_newmortal();
4002                     gv_efullname3(sv, gv, NULL);
4003                     Perl_warner(aTHX_ packWARN(WARN_PROTOTYPE),
4004                                 "%" SVf "() called too early to check prototype",
4005                                 SVfARG(sv));
4006                 }
4007             }
4008             break;
4009
4010         case OP_CONST:
4011             if (cSVOPo->op_private & OPpCONST_STRICT)
4012                 no_bareword_allowed(o);
4013 #ifdef USE_ITHREADS
4014             /* FALLTHROUGH */
4015         case OP_HINTSEVAL:
4016             op_relocate_sv(&cSVOPo->op_sv, &o->op_targ);
4017 #endif
4018             break;
4019
4020 #ifdef USE_ITHREADS
4021             /* Relocate all the METHOP's SVs to the pad for thread safety. */
4022         case OP_METHOD_NAMED:
4023         case OP_METHOD_SUPER:
4024         case OP_METHOD_REDIR:
4025         case OP_METHOD_REDIR_SUPER:
4026             op_relocate_sv(&cMETHOPx(o)->op_u.op_meth_sv, &o->op_targ);
4027             break;
4028 #endif
4029
4030         case OP_HELEM: {
4031             UNOP *rop;
4032             SVOP *key_op;
4033             OP *kid;
4034
4035             if ((key_op = cSVOPx(((BINOP*)o)->op_last))->op_type != OP_CONST)
4036                 break;
4037
4038             rop = (UNOP*)((BINOP*)o)->op_first;
4039
4040             goto check_keys;
4041
4042             case OP_HSLICE:
4043                 S_scalar_slice_warning(aTHX_ o);
4044                 /* FALLTHROUGH */
4045
4046             case OP_KVHSLICE:
4047                 kid = OpSIBLING(cLISTOPo->op_first);
4048             if (/* I bet there's always a pushmark... */
4049                 OP_TYPE_ISNT_AND_WASNT_NN(kid, OP_LIST)
4050                 && OP_TYPE_ISNT_NN(kid, OP_CONST))
4051             {
4052                 break;
4053             }
4054
4055             key_op = (SVOP*)(kid->op_type == OP_CONST
4056                              ? kid
4057                              : OpSIBLING(kLISTOP->op_first));
4058
4059             rop = (UNOP*)((LISTOP*)o)->op_last;
4060
4061         check_keys:
4062             if (o->op_private & OPpLVAL_INTRO || rop->op_type != OP_RV2HV)
4063                 rop = NULL;
4064             S_check_hash_fields_and_hekify(aTHX_ rop, key_op, 1);
4065             break;
4066         }
4067         case OP_NULL:
4068             if (o->op_targ != OP_HSLICE && o->op_targ != OP_ASLICE)
4069                 break;
4070             /* FALLTHROUGH */
4071         case OP_ASLICE:
4072             S_scalar_slice_warning(aTHX_ o);
4073             break;
4074
4075         case OP_SUBST: {
4076             if (cPMOPo->op_pmreplrootu.op_pmreplroot)
4077                 finalize_op(cPMOPo->op_pmreplrootu.op_pmreplroot);
4078             break;
4079         }
4080         default:
4081             break;
4082         }
4083
4084 #ifdef DEBUGGING
4085         if (o->op_flags & OPf_KIDS) {
4086             OP *kid;
4087
4088             /* check that op_last points to the last sibling, and that
4089              * the last op_sibling/op_sibparent field points back to the
4090              * parent, and that the only ops with KIDS are those which are
4091              * entitled to them */
4092             U32 type = o->op_type;
4093             U32 family;
4094             bool has_last;
4095
4096             if (type == OP_NULL) {
4097                 type = o->op_targ;
4098                 /* ck_glob creates a null UNOP with ex-type GLOB
4099                  * (which is a list op. So pretend it wasn't a listop */
4100                 if (type == OP_GLOB)
4101                     type = OP_NULL;
4102             }
4103             family = PL_opargs[type] & OA_CLASS_MASK;
4104
4105             has_last = (   family == OA_BINOP
4106                         || family == OA_LISTOP
4107                         || family == OA_PMOP
4108                         || family == OA_LOOP
4109                        );
4110             assert(  has_last /* has op_first and op_last, or ...
4111                   ... has (or may have) op_first: */
4112                   || family == OA_UNOP
4113                   || family == OA_UNOP_AUX
4114                   || family == OA_LOGOP
4115                   || family == OA_BASEOP_OR_UNOP
4116                   || family == OA_FILESTATOP
4117                   || family == OA_LOOPEXOP
4118                   || family == OA_METHOP
4119                   || type == OP_CUSTOM
4120                   || type == OP_NULL /* new_logop does this */
4121                   );
4122
4123             for (kid = cUNOPo->op_first; kid; kid = OpSIBLING(kid)) {
4124                 if (!OpHAS_SIBLING(kid)) {
4125                     if (has_last)
4126                         assert(kid == cLISTOPo->op_last);
4127                     assert(kid->op_sibparent == o);
4128                 }
4129             }
4130         }
4131 #endif
4132     } while (( o = traverse_op_tree(top, o)) != NULL);
4133 }
4134
4135 static void
4136 S_mark_padname_lvalue(pTHX_ PADNAME *pn)
4137 {
4138     CV *cv = PL_compcv;
4139     PadnameLVALUE_on(pn);
4140     while (PadnameOUTER(pn) && PARENT_PAD_INDEX(pn)) {
4141         cv = CvOUTSIDE(cv);
4142         /* RT #127786: cv can be NULL due to an eval within the DB package
4143          * called from an anon sub - anon subs don't have CvOUTSIDE() set
4144          * unless they contain an eval, but calling eval within DB
4145          * pretends the eval was done in the caller's scope.
4146          */
4147         if (!cv)
4148             break;
4149         assert(CvPADLIST(cv));
4150         pn =
4151            PadlistNAMESARRAY(CvPADLIST(cv))[PARENT_PAD_INDEX(pn)];
4152         assert(PadnameLEN(pn));
4153         PadnameLVALUE_on(pn);
4154     }
4155 }
4156
4157 static bool
4158 S_vivifies(const OPCODE type)
4159 {
4160     switch(type) {
4161     case OP_RV2AV:     case   OP_ASLICE:
4162     case OP_RV2HV:     case OP_KVASLICE:
4163     case OP_RV2SV:     case   OP_HSLICE:
4164     case OP_AELEMFAST: case OP_KVHSLICE:
4165     case OP_HELEM:
4166     case OP_AELEM:
4167         return 1;
4168     }
4169     return 0;
4170 }
4171
4172
4173 /* apply lvalue reference (aliasing) context to the optree o.
4174  * E.g. in
4175  *     \($x,$y) = (...)
4176  * o would be the list ($x,$y) and type would be OP_AASSIGN.
4177  * It may descend and apply this to children too, for example in
4178  * \( $cond ? $x, $y) = (...)
4179  */
4180
4181 static void
4182 S_lvref(pTHX_ OP *o, I32 type)
4183 {
4184     OP *kid;
4185     OP * top_op = o;
4186
4187     while (1) {
4188         switch (o->op_type) {
4189         case OP_COND_EXPR:
4190             o = OpSIBLING(cUNOPo->op_first);
4191             continue;
4192
4193         case OP_PUSHMARK:
4194             goto do_next;
4195
4196         case OP_RV2AV:
4197             if (cUNOPo->op_first->op_type != OP_GV) goto badref;
4198             o->op_flags |= OPf_STACKED;
4199             if (o->op_flags & OPf_PARENS) {
4200                 if (o->op_private & OPpLVAL_INTRO) {
4201                      yyerror(Perl_form(aTHX_ "Can't modify reference to "
4202                           "localized parenthesized array in list assignment"));
4203                     goto do_next;
4204                 }
4205               slurpy:
4206                 OpTYPE_set(o, OP_LVAVREF);
4207                 o->op_private &= OPpLVAL_INTRO|OPpPAD_STATE;
4208                 o->op_flags |= OPf_MOD|OPf_REF;
4209                 goto do_next;
4210             }
4211             o->op_private |= OPpLVREF_AV;
4212             goto checkgv;
4213
4214         case OP_RV2CV:
4215             kid = cUNOPo->op_first;
4216             if (kid->op_type == OP_NULL)
4217                 kid = cUNOPx(OpSIBLING(kUNOP->op_first))
4218                     ->op_first;
4219             o->op_private = OPpLVREF_CV;
4220             if (kid->op_type == OP_GV)
4221                 o->op_flags |= OPf_STACKED;
4222             else if (kid->op_type == OP_PADCV) {
4223                 o->op_targ = kid->op_targ;
4224                 kid->op_targ = 0;
4225                 op_free(cUNOPo->op_first);
4226                 cUNOPo->op_first = NULL;
4227                 o->op_flags &=~ OPf_KIDS;
4228             }
4229             else goto badref;
4230             break;
4231
4232         case OP_RV2HV:
4233             if (o->op_flags & OPf_PARENS) {
4234               parenhash:
4235                 yyerror(Perl_form(aTHX_ "Can't modify reference to "
4236                                      "parenthesized hash in list assignment"));
4237                     goto do_next;
4238             }
4239             o->op_private |= OPpLVREF_HV;
4240             /* FALLTHROUGH */
4241         case OP_RV2SV:
4242           checkgv:
4243             if (cUNOPo->op_first->op_type != OP_GV) goto badref;
4244             o->op_flags |= OPf_STACKED;
4245             break;
4246
4247         case OP_PADHV:
4248             if (o->op_flags & OPf_PARENS) goto parenhash;
4249             o->op_private |= OPpLVREF_HV;
4250             /* FALLTHROUGH */
4251         case OP_PADSV:
4252             PAD_COMPNAME_GEN_set(o->op_targ, PERL_INT_MAX);
4253             break;
4254
4255         case OP_PADAV:
4256             PAD_COMPNAME_GEN_set(o->op_targ, PERL_INT_MAX);
4257             if (o->op_flags & OPf_PARENS) goto slurpy;
4258             o->op_private |= OPpLVREF_AV;
4259             break;
4260
4261         case OP_AELEM:
4262         case OP_HELEM:
4263             o->op_private |= OPpLVREF_ELEM;
4264             o->op_flags   |= OPf_STACKED;
4265             break;
4266
4267         case OP_ASLICE:
4268         case OP_HSLICE:
4269             OpTYPE_set(o, OP_LVREFSLICE);
4270             o->op_private &= OPpLVAL_INTRO;
4271             goto do_next;
4272
4273         case OP_NULL:
4274             if (o->op_flags & OPf_SPECIAL)              /* do BLOCK */
4275                 goto badref;
4276             else if (!(o->op_flags & OPf_KIDS))
4277                 goto do_next;
4278
4279             /* the code formerly only recursed into the first child of
4280              * a non ex-list OP_NULL. if we ever encounter such a null op with
4281              * more than one child, need to decide whether its ok to process
4282              * *all* its kids or not */
4283             assert(o->op_targ == OP_LIST
4284                     || !(OpHAS_SIBLING(cBINOPo->op_first)));
4285             /* FALLTHROUGH */
4286         case OP_LIST:
4287             o = cLISTOPo->op_first;
4288             continue;
4289
4290         case OP_STUB:
4291             if (o->op_flags & OPf_PARENS)
4292                 goto do_next;
4293             /* FALLTHROUGH */
4294         default:
4295           badref:
4296             /* diag_listed_as: Can't modify reference to %s in %s assignment */
4297             yyerror(Perl_form(aTHX_ "Can't modify reference to %s in %s",
4298                          o->op_type == OP_NULL && o->op_flags & OPf_SPECIAL
4299                           ? "do block"
4300                           : OP_DESC(o),
4301                          PL_op_desc[type]));
4302             goto do_next;
4303         }
4304
4305         OpTYPE_set(o, OP_LVREF);
4306         o->op_private &=
4307             OPpLVAL_INTRO|OPpLVREF_ELEM|OPpLVREF_TYPE|OPpPAD_STATE;
4308         if (type == OP_ENTERLOOP)
4309             o->op_private |= OPpLVREF_ITER;
4310
4311       do_next:
4312         while (1) {
4313             if (o == top_op)
4314                 return; /* at top; no parents/siblings to try */
4315             if (OpHAS_SIBLING(o)) {
4316                 o = o->op_sibparent;
4317                 break;
4318             }
4319             o = o->op_sibparent; /*try parent's next sibling */
4320         }
4321     } /* while */
4322 }
4323
4324
4325 PERL_STATIC_INLINE bool
4326 S_potential_mod_type(I32 type)
4327 {
4328     /* Types that only potentially result in modification.  */
4329     return type == OP_GREPSTART || type == OP_ENTERSUB
4330         || type == OP_REFGEN    || type == OP_LEAVESUBLV;
4331 }
4332
4333
4334 /*
4335 =for apidoc op_lvalue
4336
4337 Propagate lvalue ("modifiable") context to an op and its children.
4338 C<type> represents the context type, roughly based on the type of op that
4339 would do the modifying, although C<local()> is represented by C<OP_NULL>,
4340 because it has no op type of its own (it is signalled by a flag on
4341 the lvalue op).
4342
4343 This function detects things that can't be modified, such as C<$x+1>, and
4344 generates errors for them.  For example, C<$x+1 = 2> would cause it to be
4345 called with an op of type C<OP_ADD> and a C<type> argument of C<OP_SASSIGN>.
4346
4347 It also flags things that need to behave specially in an lvalue context,
4348 such as C<$$x = 5> which might have to vivify a reference in C<$x>.
4349
4350 =cut
4351
4352 Perl_op_lvalue_flags() is a non-API lower-level interface to
4353 op_lvalue().  The flags param has these bits:
4354     OP_LVALUE_NO_CROAK:  return rather than croaking on error
4355
4356 */
4357
4358 OP *
4359 Perl_op_lvalue_flags(pTHX_ OP *o, I32 type, U32 flags)
4360 {
4361     OP *top_op = o;
4362
4363     if (!o || (PL_parser && PL_parser->error_count))
4364         return o;
4365
4366     while (1) {
4367     OP *kid;
4368     /* -1 = error on localize, 0 = ignore localize, 1 = ok to localize */
4369     int localize = -1;
4370     OP *next_kid = NULL;
4371
4372     if ((o->op_private & OPpTARGET_MY)
4373         && (PL_opargs[o->op_type] & OA_TARGLEX))/* OPp share the meaning */
4374     {
4375         goto do_next;
4376     }
4377
4378     /* elements of a list might be in void context because the list is
4379        in scalar context or because they are attribute sub calls */
4380     if ((o->op_flags & OPf_WANT) == OPf_WANT_VOID)
4381         goto do_next;
4382
4383     if (type == OP_PRTF || type == OP_SPRINTF) type = OP_ENTERSUB;
4384
4385     switch (o->op_type) {
4386     case OP_UNDEF:
4387         if (type == OP_SASSIGN)
4388             goto nomod;
4389         PL_modcount++;
4390         goto do_next;
4391
4392     case OP_STUB:
4393         if ((o->op_flags & OPf_PARENS))
4394             break;
4395         goto nomod;
4396
4397     case OP_ENTERSUB:
4398         if ((type == OP_UNDEF || type == OP_REFGEN || type == OP_LOCK) &&
4399             !(o->op_flags & OPf_STACKED)) {
4400             OpTYPE_set(o, OP_RV2CV);            /* entersub => rv2cv */
4401             assert(cUNOPo->op_first->op_type == OP_NULL);
4402             op_null(((LISTOP*)cUNOPo->op_first)->op_first);/* disable pushmark */
4403             break;
4404         }
4405         else {                          /* lvalue subroutine call */
4406             o->op_private |= OPpLVAL_INTRO;
4407             PL_modcount = RETURN_UNLIMITED_NUMBER;
4408             if (S_potential_mod_type(type)) {
4409                 o->op_private |= OPpENTERSUB_INARGS;
4410                 break;
4411             }
4412             else {                      /* Compile-time error message: */
4413                 OP *kid = cUNOPo->op_first;
4414                 CV *cv;
4415                 GV *gv;
4416                 SV *namesv;
4417
4418                 if (kid->op_type != OP_PUSHMARK) {
4419                     if (kid->op_type != OP_NULL || kid->op_targ != OP_LIST)
4420                         Perl_croak(aTHX_
4421                                 "panic: unexpected lvalue entersub "
4422                                 "args: type/targ %ld:%" UVuf,
4423                                 (long)kid->op_type, (UV)kid->op_targ);
4424                     kid = kLISTOP->op_first;
4425                 }
4426                 while (OpHAS_SIBLING(kid))
4427                     kid = OpSIBLING(kid);
4428                 if (!(kid->op_type == OP_NULL && kid->op_targ == OP_RV2CV)) {
4429                     break;      /* Postpone until runtime */
4430                 }
4431
4432                 kid = kUNOP->op_first;
4433                 if (kid->op_type == OP_NULL && kid->op_targ == OP_RV2SV)
4434                     kid = kUNOP->op_first;
4435                 if (kid->op_type == OP_NULL)
4436                     Perl_croak(aTHX_
4437                                "panic: unexpected constant lvalue entersub "
4438                                "entry via type/targ %ld:%" UVuf,
4439                                (long)kid->op_type, (UV)kid->op_targ);
4440                 if (kid->op_type != OP_GV) {
4441                     break;
4442                 }
4443
4444                 gv = kGVOP_gv;
4445                 cv = isGV(gv)
4446                     ? GvCV(gv)
4447                     : SvROK(gv) && SvTYPE(SvRV(gv)) == SVt_PVCV
4448                         ? MUTABLE_CV(SvRV(gv))
4449                         : NULL;
4450                 if (!cv)
4451                     break;
4452                 if (CvLVALUE(cv))
4453                     break;
4454                 if (flags & OP_LVALUE_NO_CROAK)
4455                     return NULL;
4456
4457                 namesv = cv_name(cv, NULL, 0);
4458                 yyerror_pv(Perl_form(aTHX_ "Can't modify non-lvalue "
4459                                      "subroutine call of &%" SVf " in %s",
4460                                      SVfARG(namesv), PL_op_desc[type]),
4461                            SvUTF8(namesv));
4462                 goto do_next;
4463             }
4464         }
4465         /* FALLTHROUGH */
4466     default:
4467       nomod:
4468         if (flags & OP_LVALUE_NO_CROAK) return NULL;
4469         /* grep, foreach, subcalls, refgen */
4470         if (S_potential_mod_type(type))
4471             break;
4472         yyerror(Perl_form(aTHX_ "Can't modify %s in %s",
4473                      (o->op_type == OP_NULL && (o->op_flags & OPf_SPECIAL)
4474                       ? "do block"
4475                       : OP_DESC(o)),
4476                      type ? PL_op_desc[type] : "local"));
4477         goto do_next;
4478
4479     case OP_PREINC:
4480     case OP_PREDEC:
4481     case OP_POW:
4482     case OP_MULTIPLY:
4483     case OP_DIVIDE:
4484     case OP_MODULO:
4485     case OP_ADD:
4486     case OP_SUBTRACT:
4487     case OP_CONCAT:
4488     case OP_LEFT_SHIFT:
4489     case OP_RIGHT_SHIFT:
4490     case OP_BIT_AND:
4491     case OP_BIT_XOR:
4492     case OP_BIT_OR:
4493     case OP_I_MULTIPLY:
4494     case OP_I_DIVIDE:
4495     case OP_I_MODULO:
4496     case OP_I_ADD:
4497     case OP_I_SUBTRACT:
4498         if (!(o->op_flags & OPf_STACKED))
4499             goto nomod;
4500         PL_modcount++;
4501         break;
4502
4503     case OP_REPEAT:
4504         if (o->op_flags & OPf_STACKED) {
4505             PL_modcount++;
4506             break;
4507         }
4508         if (!(o->op_private & OPpREPEAT_DOLIST))
4509             goto nomod;
4510         else {
4511             const I32 mods = PL_modcount;
4512             /* we recurse rather than iterate here because we need to
4513              * calculate and use the delta applied to PL_modcount by the
4514              * first child. So in something like
4515              *     ($x, ($y) x 3) = split;
4516              * split knows that 4 elements are wanted
4517              */
4518             modkids(cBINOPo->op_first, type);
4519             if (type != OP_AASSIGN)
4520                 goto nomod;
4521             kid = cBINOPo->op_last;
4522             if (kid->op_type == OP_CONST && SvIOK(kSVOP_sv)) {
4523                 const IV iv = SvIV(kSVOP_sv);
4524                 if (PL_modcount != RETURN_UNLIMITED_NUMBER)
4525                     PL_modcount =
4526                         mods + (PL_modcount - mods) * (iv < 0 ? 0 : iv);
4527             }
4528             else
4529                 PL_modcount = RETURN_UNLIMITED_NUMBER;
4530         }
4531         break;
4532
4533     case OP_COND_EXPR:
4534         localize = 1;
4535         next_kid = OpSIBLING(cUNOPo->op_first);
4536         break;
4537
4538     case OP_RV2AV:
4539     case OP_RV2HV:
4540         if (type == OP_REFGEN && o->op_flags & OPf_PARENS) {
4541            PL_modcount = RETURN_UNLIMITED_NUMBER;
4542            /* Treat \(@foo) like ordinary list, but still mark it as modi-
4543               fiable since some contexts need to know.  */
4544            o->op_flags |= OPf_MOD;
4545            goto do_next;
4546         }
4547         /* FALLTHROUGH */
4548     case OP_RV2GV:
4549         if (scalar_mod_type(o, type))
4550             goto nomod;
4551         ref(cUNOPo->op_first, o->op_type);
4552         /* FALLTHROUGH */
4553     case OP_ASLICE:
4554     case OP_HSLICE:
4555         localize = 1;
4556         /* FALLTHROUGH */
4557     case OP_AASSIGN:
4558         /* Do not apply the lvsub flag for rv2[ah]v in scalar context.  */
4559         if (type == OP_LEAVESUBLV && (
4560                 (o->op_type != OP_RV2AV && o->op_type != OP_RV2HV)
4561              || (o->op_flags & OPf_WANT) != OPf_WANT_SCALAR
4562            ))
4563             o->op_private |= OPpMAYBE_LVSUB;
4564         /* FALLTHROUGH */
4565     case OP_NEXTSTATE:
4566     case OP_DBSTATE:
4567        PL_modcount = RETURN_UNLIMITED_NUMBER;
4568         break;
4569
4570     case OP_KVHSLICE:
4571     case OP_KVASLICE:
4572     case OP_AKEYS:
4573         if (type == OP_LEAVESUBLV)
4574             o->op_private |= OPpMAYBE_LVSUB;
4575         goto nomod;
4576
4577     case OP_AVHVSWITCH:
4578         if (type == OP_LEAVESUBLV
4579          && (o->op_private & OPpAVHVSWITCH_MASK) + OP_EACH == OP_KEYS)
4580             o->op_private |= OPpMAYBE_LVSUB;
4581         goto nomod;
4582
4583     case OP_AV2ARYLEN:
4584         PL_hints |= HINT_BLOCK_SCOPE;
4585         if (type == OP_LEAVESUBLV)
4586             o->op_private |= OPpMAYBE_LVSUB;
4587         PL_modcount++;
4588         break;
4589
4590     case OP_RV2SV:
4591         ref(cUNOPo->op_first, o->op_type);
4592         localize = 1;
4593         /* FALLTHROUGH */
4594     case OP_GV:
4595         PL_hints |= HINT_BLOCK_SCOPE;
4596         /* FALLTHROUGH */
4597     case OP_SASSIGN:
4598     case OP_ANDASSIGN:
4599     case OP_ORASSIGN:
4600     case OP_DORASSIGN:
4601         PL_modcount++;
4602         break;
4603
4604     case OP_AELEMFAST:
4605     case OP_AELEMFAST_LEX:
4606         localize = -1;
4607         PL_modcount++;
4608         break;
4609
4610     case OP_PADAV:
4611     case OP_PADHV:
4612        PL_modcount = RETURN_UNLIMITED_NUMBER;
4613         if (type == OP_REFGEN && o->op_flags & OPf_PARENS)
4614         {
4615            /* Treat \(@foo) like ordinary list, but still mark it as modi-
4616               fiable since some contexts need to know.  */
4617             o->op_flags |= OPf_MOD;
4618             goto do_next;
4619         }
4620         if (scalar_mod_type(o, type))
4621             goto nomod;
4622         if ((o->op_flags & OPf_WANT) != OPf_WANT_SCALAR
4623           && type == OP_LEAVESUBLV)
4624             o->op_private |= OPpMAYBE_LVSUB;
4625         /* FALLTHROUGH */
4626     case OP_PADSV:
4627         PL_modcount++;
4628         if (!type) /* local() */
4629             Perl_croak(aTHX_ "Can't localize lexical variable %" PNf,
4630                               PNfARG(PAD_COMPNAME(o->op_targ)));
4631         if (!(o->op_private & OPpLVAL_INTRO)
4632          || (  type != OP_SASSIGN && type != OP_AASSIGN
4633             && PadnameIsSTATE(PAD_COMPNAME_SV(o->op_targ))  ))
4634             S_mark_padname_lvalue(aTHX_ PAD_COMPNAME_SV(o->op_targ));
4635         break;
4636
4637     case OP_PUSHMARK:
4638         localize = 0;
4639         break;
4640
4641     case OP_KEYS:
4642         if (type != OP_LEAVESUBLV && !scalar_mod_type(NULL, type))
4643             goto nomod;
4644         goto lvalue_func;
4645     case OP_SUBSTR:
4646         if (o->op_private == 4) /* don't allow 4 arg substr as lvalue */
4647             goto nomod;
4648         /* FALLTHROUGH */
4649     case OP_POS:
4650     case OP_VEC:
4651       lvalue_func:
4652         if (type == OP_LEAVESUBLV)
4653             o->op_private |= OPpMAYBE_LVSUB;
4654         if (o->op_flags & OPf_KIDS && OpHAS_SIBLING(cBINOPo->op_first)) {
4655             /* we recurse rather than iterate here because the child
4656              * needs to be processed with a different 'type' parameter */
4657
4658             /* substr and vec */
4659             /* If this op is in merely potential (non-fatal) modifiable
4660                context, then apply OP_ENTERSUB context to
4661                the kid op (to avoid croaking).  Other-
4662                wise pass this op’s own type so the correct op is mentioned
4663                in error messages.  */
4664             op_lvalue(OpSIBLING(cBINOPo->op_first),
4665                       S_potential_mod_type(type)
4666                         ? (I32)OP_ENTERSUB
4667                         : o->op_type);
4668         }
4669         break;
4670
4671     case OP_AELEM:
4672     case OP_HELEM:
4673         ref(cBINOPo->op_first, o->op_type);
4674         if (type == OP_ENTERSUB &&
4675              !(o->op_private & (OPpLVAL_INTRO | OPpDEREF)))
4676             o->op_private |= OPpLVAL_DEFER;
4677         if (type == OP_LEAVESUBLV)
4678             o->op_private |= OPpMAYBE_LVSUB;
4679         localize = 1;
4680         PL_modcount++;
4681         break;
4682
4683     case OP_LEAVE:
4684     case OP_LEAVELOOP:
4685         o->op_private |= OPpLVALUE;
4686         /* FALLTHROUGH */
4687     case OP_SCOPE:
4688     case OP_ENTER:
4689     case OP_LINESEQ:
4690         localize = 0;
4691         if (o->op_flags & OPf_KIDS)
4692             next_kid = cLISTOPo->op_last;
4693         break;
4694
4695     case OP_NULL:
4696         localize = 0;
4697         if (o->op_flags & OPf_SPECIAL)          /* do BLOCK */
4698             goto nomod;
4699         else if (!(o->op_flags & OPf_KIDS))
4700             break;
4701
4702         if (o->op_targ != OP_LIST) {
4703             OP *sib = OpSIBLING(cLISTOPo->op_first);
4704             /* OP_TRANS and OP_TRANSR with argument have a weird optree
4705              * that looks like
4706              *
4707              *   null
4708              *      arg
4709              *      trans
4710              *
4711              * compared with things like OP_MATCH which have the argument
4712              * as a child:
4713              *
4714              *   match
4715              *      arg
4716              *
4717              * so handle specially to correctly get "Can't modify" croaks etc
4718              */
4719
4720             if (sib && (sib->op_type == OP_TRANS || sib->op_type == OP_TRANSR))
4721             {
4722                 /* this should trigger a "Can't modify transliteration" err */
4723                 op_lvalue(sib, type);
4724             }
4725             next_kid = cBINOPo->op_first;
4726             /* we assume OP_NULLs which aren't ex-list have no more than 2
4727              * children. If this assumption is wrong, increase the scan
4728              * limit below */
4729             assert(   !OpHAS_SIBLING(next_kid)
4730                    || !OpHAS_SIBLING(OpSIBLING(next_kid)));
4731             break;
4732         }
4733         /* FALLTHROUGH */
4734     case OP_LIST:
4735         localize = 0;
4736         next_kid = cLISTOPo->op_first;
4737         break;
4738
4739     case OP_COREARGS:
4740         goto do_next;
4741
4742     case OP_AND:
4743     case OP_OR:
4744         if (type == OP_LEAVESUBLV
4745          || !S_vivifies(cLOGOPo->op_first->op_type))
4746             next_kid = cLOGOPo->op_first;
4747         else if (type == OP_LEAVESUBLV
4748          || !S_vivifies(OpSIBLING(cLOGOPo->op_first)->op_type))
4749             next_kid = OpSIBLING(cLOGOPo->op_first);
4750         goto nomod;
4751
4752     case OP_SREFGEN:
4753         if (type == OP_NULL) { /* local */
4754           local_refgen:
4755             if (!FEATURE_MYREF_IS_ENABLED)
4756                 Perl_croak(aTHX_ "The experimental declared_refs "
4757                                  "feature is not enabled");
4758             Perl_ck_warner_d(aTHX_
4759                      packWARN(WARN_EXPERIMENTAL__DECLARED_REFS),
4760                     "Declaring references is experimental");
4761             next_kid = cUNOPo->op_first;
4762             goto do_next;
4763         }
4764         if (type != OP_AASSIGN && type != OP_SASSIGN
4765          && type != OP_ENTERLOOP)
4766             goto nomod;
4767         /* Don’t bother applying lvalue context to the ex-list.  */
4768         kid = cUNOPx(cUNOPo->op_first)->op_first;
4769         assert (!OpHAS_SIBLING(kid));
4770         goto kid_2lvref;
4771     case OP_REFGEN:
4772         if (type == OP_NULL) /* local */
4773             goto local_refgen;
4774         if (type != OP_AASSIGN) goto nomod;
4775         kid = cUNOPo->op_first;
4776       kid_2lvref:
4777         {
4778             const U8 ec = PL_parser ? PL_parser->error_count : 0;
4779             S_lvref(aTHX_ kid, type);
4780             if (!PL_parser || PL_parser->error_count == ec) {
4781                 if (!FEATURE_REFALIASING_IS_ENABLED)
4782                     Perl_croak(aTHX_
4783                        "Experimental aliasing via reference not enabled");
4784                 Perl_ck_warner_d(aTHX_
4785                                  packWARN(WARN_EXPERIMENTAL__REFALIASING),
4786                                 "Aliasing via reference is experimental");
4787             }
4788         }
4789         if (o->op_type == OP_REFGEN)
4790             op_null(cUNOPx(cUNOPo->op_first)->op_first); /* pushmark */
4791         op_null(o);
4792         goto do_next;
4793
4794     case OP_SPLIT:
4795         if ((o->op_private & OPpSPLIT_ASSIGN)) {
4796             /* This is actually @array = split.  */
4797             PL_modcount = RETURN_UNLIMITED_NUMBER;
4798             break;
4799         }
4800         goto nomod;
4801
4802     case OP_SCALAR:
4803         op_lvalue(cUNOPo->op_first, OP_ENTERSUB);
4804         goto nomod;
4805     }
4806
4807     /* [20011101.069 (#7861)] File test operators interpret OPf_REF to mean that
4808        their argument is a filehandle; thus \stat(".") should not set
4809        it. AMS 20011102 */
4810     if (type == OP_REFGEN && OP_IS_STAT(o->op_type))
4811         goto do_next;
4812
4813     if (type != OP_LEAVESUBLV)
4814         o->op_flags |= OPf_MOD;
4815
4816     if (type == OP_AASSIGN || type == OP_SASSIGN)
4817         o->op_flags |= OPf_SPECIAL
4818                       |(o->op_type == OP_ENTERSUB ? 0 : OPf_REF);
4819     else if (!type) { /* local() */
4820         switch (localize) {
4821         case 1:
4822             o->op_private |= OPpLVAL_INTRO;
4823             o->op_flags &= ~OPf_SPECIAL;
4824             PL_hints |= HINT_BLOCK_SCOPE;
4825             break;
4826         case 0:
4827             break;
4828         case -1:
4829             Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX),
4830                            "Useless localization of %s", OP_DESC(o));
4831         }
4832     }
4833     else if (type != OP_GREPSTART && type != OP_ENTERSUB
4834              && type != OP_LEAVESUBLV && o->op_type != OP_ENTERSUB)
4835         o->op_flags |= OPf_REF;
4836
4837   do_next:
4838     while (!next_kid) {
4839         if (o == top_op)
4840             return top_op; /* at top; no parents/siblings to try */
4841         if (OpHAS_SIBLING(o)) {
4842             next_kid = o->op_sibparent;
4843             if (!OpHAS_SIBLING(next_kid)) {
4844                 /* a few node types don't recurse into their second child */
4845                 OP *parent = next_kid->op_sibparent;
4846                 I32 ptype  = parent->op_type;
4847                 if (   (ptype == OP_NULL && parent->op_targ != OP_LIST)
4848                     || (   (ptype == OP_AND || ptype == OP_OR)
4849                         && (type != OP_LEAVESUBLV
4850                             && S_vivifies(next_kid->op_type))
4851                        )
4852                 )  {
4853                     /*try parent's next sibling */
4854                     o = parent;
4855                     next_kid =  NULL;
4856                 }
4857             }
4858         }
4859         else
4860             o = o->op_sibparent; /*try parent's next sibling */
4861
4862     }
4863     o = next_kid;
4864
4865     } /* while */
4866
4867 }
4868
4869
4870 STATIC bool
4871 S_scalar_mod_type(const OP *o, I32 type)
4872 {
4873     switch (type) {
4874     case OP_POS:
4875     case OP_SASSIGN:
4876         if (o && o->op_type == OP_RV2GV)
4877             return FALSE;
4878         /* FALLTHROUGH */
4879     case OP_PREINC:
4880     case OP_PREDEC:
4881     case OP_POSTINC:
4882     case OP_POSTDEC:
4883     case OP_I_PREINC:
4884     case OP_I_PREDEC:
4885     case OP_I_POSTINC:
4886     case OP_I_POSTDEC:
4887     case OP_POW:
4888     case OP_MULTIPLY:
4889     case OP_DIVIDE:
4890     case OP_MODULO:
4891     case OP_REPEAT:
4892     case OP_ADD:
4893     case OP_SUBTRACT:
4894     case OP_I_MULTIPLY:
4895     case OP_I_DIVIDE:
4896     case OP_I_MODULO:
4897     case OP_I_ADD:
4898     case OP_I_SUBTRACT:
4899     case OP_LEFT_SHIFT:
4900     case OP_RIGHT_SHIFT:
4901     case OP_BIT_AND:
4902     case OP_BIT_XOR:
4903     case OP_BIT_OR:
4904     case OP_NBIT_AND:
4905     case OP_NBIT_XOR:
4906     case OP_NBIT_OR:
4907     case OP_SBIT_AND:
4908     case OP_SBIT_XOR:
4909     case OP_SBIT_OR:
4910     case OP_CONCAT:
4911     case OP_SUBST:
4912     case OP_TRANS:
4913     case OP_TRANSR:
4914     case OP_READ:
4915     case OP_SYSREAD:
4916     case OP_RECV:
4917     case OP_ANDASSIGN:
4918     case OP_ORASSIGN:
4919     case OP_DORASSIGN:
4920     case OP_VEC:
4921     case OP_SUBSTR:
4922         return TRUE;
4923     default:
4924         return FALSE;
4925     }
4926 }
4927
4928 STATIC bool
4929 S_is_handle_constructor(const OP *o, I32 numargs)
4930 {
4931     PERL_ARGS_ASSERT_IS_HANDLE_CONSTRUCTOR;
4932
4933     switch (o->op_type) {
4934     case OP_PIPE_OP:
4935     case OP_SOCKPAIR:
4936         if (numargs == 2)
4937             return TRUE;
4938         /* FALLTHROUGH */
4939     case OP_SYSOPEN:
4940     case OP_OPEN:
4941     case OP_SELECT:             /* XXX c.f. SelectSaver.pm */
4942     case OP_SOCKET:
4943     case OP_OPEN_DIR:
4944     case OP_ACCEPT:
4945         if (numargs == 1)
4946             return TRUE;
4947         /* FALLTHROUGH */
4948     default:
4949         return FALSE;
4950     }
4951 }
4952
4953 static OP *
4954 S_refkids(pTHX_ OP *o, I32 type)
4955 {
4956     if (o && o->op_flags & OPf_KIDS) {
4957         OP *kid;
4958         for (kid = cLISTOPo->op_first; kid; kid = OpSIBLING(kid))
4959             ref(kid, type);
4960     }
4961     return o;
4962 }
4963
4964
4965 /* Apply reference (autovivification) context to the subtree at o.
4966  * For example in
4967  *     push @{expression}, ....;
4968  * o will be the head of 'expression' and type will be OP_RV2AV.
4969  * It marks the op o (or a suitable child) as autovivifying, e.g. by
4970  * setting  OPf_MOD.
4971  * For OP_RV2AV/OP_PADAV and OP_RV2HV/OP_PADHV sets OPf_REF too if
4972  * set_op_ref is true.
4973  *
4974  * Also calls scalar(o).
4975  */
4976
4977 OP *
4978 Perl_doref(pTHX_ OP *o, I32 type, bool set_op_ref)
4979 {
4980     OP * top_op = o;
4981
4982     PERL_ARGS_ASSERT_DOREF;
4983
4984     if (PL_parser && PL_parser->error_count)
4985         return o;
4986
4987     while (1) {
4988         switch (o->op_type) {
4989         case OP_ENTERSUB:
4990             if ((type == OP_EXISTS || type == OP_DEFINED) &&
4991                 !(o->op_flags & OPf_STACKED)) {
4992                 OpTYPE_set(o, OP_RV2CV);             /* entersub => rv2cv */
4993                 assert(cUNOPo->op_first->op_type == OP_NULL);
4994                 /* disable pushmark */
4995                 op_null(((LISTOP*)cUNOPo->op_first)->op_first);
4996                 o->op_flags |= OPf_SPECIAL;
4997             }
4998             else if (type == OP_RV2SV || type == OP_RV2AV || type == OP_RV2HV){
4999                 o->op_private |= (type == OP_RV2AV ? OPpDEREF_AV
5000                                   : type == OP_RV2HV ? OPpDEREF_HV
5001                                   : OPpDEREF_SV);
5002                 o->op_flags |= OPf_MOD;
5003             }
5004
5005             break;
5006
5007         case OP_COND_EXPR:
5008             o = OpSIBLING(cUNOPo->op_first);
5009             continue;
5010
5011         case OP_RV2SV:
5012             if (type == OP_DEFINED)
5013                 o->op_flags |= OPf_SPECIAL;             /* don't create GV */
5014             /* FALLTHROUGH */
5015         case OP_PADSV:
5016             if (type == OP_RV2SV || type == OP_RV2AV || type == OP_RV2HV) {
5017                 o->op_private |= (type == OP_RV2AV ? OPpDEREF_AV
5018                                   : type == OP_RV2HV ? OPpDEREF_HV
5019                                   : OPpDEREF_SV);
5020                 o->op_flags |= OPf_MOD;
5021             }
5022             if (o->op_flags & OPf_KIDS) {
5023                 type = o->op_type;
5024                 o = cUNOPo->op_first;
5025                 continue;
5026             }
5027             break;
5028
5029         case OP_RV2AV:
5030         case OP_RV2HV:
5031             if (set_op_ref)
5032                 o->op_flags |= OPf_REF;
5033             /* FALLTHROUGH */
5034         case OP_RV2GV:
5035             if (type == OP_DEFINED)
5036                 o->op_flags |= OPf_SPECIAL;             /* don't create GV */
5037             type = o->op_type;
5038             o = cUNOPo->op_first;
5039             continue;
5040
5041         case OP_PADAV:
5042         case OP_PADHV:
5043             if (set_op_ref)
5044                 o->op_flags |= OPf_REF;
5045             break;
5046
5047         case OP_SCALAR:
5048         case OP_NULL:
5049             if (!(o->op_flags & OPf_KIDS) || type == OP_DEFINED)
5050                 break;
5051              o = cBINOPo->op_first;
5052             continue;
5053
5054         case OP_AELEM:
5055         case OP_HELEM:
5056             if (type == OP_RV2SV || type == OP_RV2AV || type == OP_RV2HV) {
5057                 o->op_private |= (type == OP_RV2AV ? OPpDEREF_AV
5058                                   : type == OP_RV2HV ? OPpDEREF_HV
5059                                   : OPpDEREF_SV);
5060                 o->op_flags |= OPf_MOD;
5061             }
5062             type = o->op_type;
5063             o = cBINOPo->op_first;
5064             continue;;
5065
5066         case OP_SCOPE:
5067         case OP_LEAVE:
5068             set_op_ref = FALSE;
5069             /* FALLTHROUGH */
5070         case OP_ENTER:
5071         case OP_LIST:
5072             if (!(o->op_flags & OPf_KIDS))
5073                 break;
5074             o = cLISTOPo->op_last;
5075             continue;
5076
5077         default:
5078             break;
5079         } /* switch */
5080
5081         while (1) {
5082             if (o == top_op)
5083                 return scalar(top_op); /* at top; no parents/siblings to try */
5084             if (OpHAS_SIBLING(o)) {
5085                 o = o->op_sibparent;
5086                 /* Normally skip all siblings and go straight to the parent;
5087                  * the only op that requires two children to be processed
5088                  * is OP_COND_EXPR */
5089                 if (!OpHAS_SIBLING(o)
5090                         && o->op_sibparent->op_type == OP_COND_EXPR)
5091                     break;
5092                 continue;
5093             }
5094             o = o->op_sibparent; /*try parent's next sibling */
5095         }
5096     } /* while */
5097 }
5098
5099
5100 STATIC OP *
5101 S_dup_attrlist(pTHX_ OP *o)
5102 {
5103     OP *rop;
5104
5105     PERL_ARGS_ASSERT_DUP_ATTRLIST;
5106
5107     /* An attrlist is either a simple OP_CONST or an OP_LIST with kids,
5108      * where the first kid is OP_PUSHMARK and the remaining ones
5109      * are OP_CONST.  We need to push the OP_CONST values.
5110      */
5111     if (o->op_type == OP_CONST)
5112         rop = newSVOP(OP_CONST, o->op_flags, SvREFCNT_inc_NN(cSVOPo->op_sv));
5113     else {
5114         assert((o->op_type == OP_LIST) && (o->op_flags & OPf_KIDS));
5115         rop = NULL;
5116         for (o = cLISTOPo->op_first; o; o = OpSIBLING(o)) {
5117             if (o->op_type == OP_CONST)
5118                 rop = op_append_elem(OP_LIST, rop,
5119                                   newSVOP(OP_CONST, o->op_flags,
5120                                           SvREFCNT_inc_NN(cSVOPo->op_sv)));
5121         }
5122     }
5123     return rop;
5124 }
5125
5126 STATIC void
5127 S_apply_attrs(pTHX_ HV *stash, SV *target, OP *attrs)
5128 {
5129     PERL_ARGS_ASSERT_APPLY_ATTRS;
5130     {
5131         SV * const stashsv = newSVhek(HvNAME_HEK(stash));
5132
5133         /* fake up C<use attributes $pkg,$rv,@attrs> */
5134
5135 #define ATTRSMODULE "attributes"
5136 #define ATTRSMODULE_PM "attributes.pm"
5137
5138         Perl_load_module(
5139           aTHX_ PERL_LOADMOD_IMPORT_OPS,
5140           newSVpvs(ATTRSMODULE),
5141           NULL,
5142           op_prepend_elem(OP_LIST,
5143                           newSVOP(OP_CONST, 0, stashsv),
5144                           op_prepend_elem(OP_LIST,
5145                                           newSVOP(OP_CONST, 0,
5146                                                   newRV(target)),
5147                                           dup_attrlist(attrs))));
5148     }
5149 }
5150
5151 STATIC void
5152 S_apply_attrs_my(pTHX_ HV *stash, OP *target, OP *attrs, OP **imopsp)
5153 {
5154     OP *pack, *imop, *arg;
5155     SV *meth, *stashsv, **svp;
5156
5157     PERL_ARGS_ASSERT_APPLY_ATTRS_MY;
5158
5159     if (!attrs)
5160         return;
5161
5162     assert(target->op_type == OP_PADSV ||
5163            target->op_type == OP_PADHV ||
5164            target->op_type == OP_PADAV);
5165
5166     /* Ensure that attributes.pm is loaded. */
5167     /* Don't force the C<use> if we don't need it. */
5168     svp = hv_fetchs(GvHVn(PL_incgv), ATTRSMODULE_PM, FALSE);
5169     if (svp && *svp != &PL_sv_undef)
5170         NOOP;   /* already in %INC */
5171     else
5172         Perl_load_module(aTHX_ PERL_LOADMOD_NOIMPORT,
5173                                newSVpvs(ATTRSMODULE), NULL);
5174
5175     /* Need package name for method call. */
5176     pack = newSVOP(OP_CONST, 0, newSVpvs(ATTRSMODULE));
5177
5178     /* Build up the real arg-list. */
5179     stashsv = newSVhek(HvNAME_HEK(stash));
5180
5181     arg = newOP(OP_PADSV, 0);
5182     arg->op_targ = target->op_targ;
5183     arg = op_prepend_elem(OP_LIST,
5184                        newSVOP(OP_CONST, 0, stashsv),
5185                        op_prepend_elem(OP_LIST,
5186                                     newUNOP(OP_REFGEN, 0,
5187                                             arg),
5188                                     dup_attrlist(attrs)));
5189
5190     /* Fake up a method call to import */
5191     meth = newSVpvs_share("import");
5192     imop = op_convert_list(OP_ENTERSUB, OPf_STACKED|OPf_SPECIAL|OPf_WANT_VOID,
5193                    op_append_elem(OP_LIST,
5194                                op_prepend_elem(OP_LIST, pack, arg),
5195                                newMETHOP_named(OP_METHOD_NAMED, 0, meth)));
5196
5197     /* Combine the ops. */
5198     *imopsp = op_append_elem(OP_LIST, *imopsp, imop);
5199 }
5200
5201 /*
5202 =notfor apidoc apply_attrs_string
5203
5204 Attempts to apply a list of attributes specified by the C<attrstr> and
5205 C<len> arguments to the subroutine identified by the C<cv> argument which
5206 is expected to be associated with the package identified by the C<stashpv>
5207 argument (see L<attributes>).  It gets this wrong, though, in that it
5208 does not correctly identify the boundaries of the individual attribute
5209 specifications within C<attrstr>.  This is not really intended for the
5210 public API, but has to be listed here for systems such as AIX which
5211 need an explicit export list for symbols.  (It's called from XS code
5212 in support of the C<ATTRS:> keyword from F<xsubpp>.)  Patches to fix it
5213 to respect attribute syntax properly would be welcome.
5214
5215 =cut
5216 */
5217
5218 void
5219 Perl_apply_attrs_string(pTHX_ const char *stashpv, CV *cv,
5220                         const char *attrstr, STRLEN len)
5221 {
5222     OP *attrs = NULL;
5223
5224     PERL_ARGS_ASSERT_APPLY_ATTRS_STRING;
5225
5226     if (!len) {
5227         len = strlen(attrstr);
5228     }
5229
5230     while (len) {
5231         for (; isSPACE(*attrstr) && len; --len, ++attrstr) ;
5232         if (len) {
5233             const char * const sstr = attrstr;
5234             for (; !isSPACE(*attrstr) && len; --len, ++attrstr) ;
5235             attrs = op_append_elem(OP_LIST, attrs,
5236                                 newSVOP(OP_CONST, 0,
5237                                         newSVpvn(sstr, attrstr-sstr)));
5238         }
5239     }
5240
5241     Perl_load_module(aTHX_ PERL_LOADMOD_IMPORT_OPS,
5242                      newSVpvs(ATTRSMODULE),
5243                      NULL, op_prepend_elem(OP_LIST,
5244                                   newSVOP(OP_CONST, 0, newSVpv(stashpv,0)),
5245                                   op_prepend_elem(OP_LIST,
5246                                                newSVOP(OP_CONST, 0,
5247                                                        newRV(MUTABLE_SV(cv))),
5248                                                attrs)));
5249 }
5250
5251 STATIC void
5252 S_move_proto_attr(pTHX_ OP **proto, OP **attrs, const GV * name,
5253                         bool curstash)
5254 {
5255     OP *new_proto = NULL;
5256     STRLEN pvlen;
5257     char *pv;
5258     OP *o;
5259
5260     PERL_ARGS_ASSERT_MOVE_PROTO_ATTR;
5261
5262     if (!*attrs)
5263         return;
5264
5265     o = *attrs;
5266     if (o->op_type == OP_CONST) {
5267         pv = SvPV(cSVOPo_sv, pvlen);
5268         if (memBEGINs(pv, pvlen, "prototype(")) {
5269             SV * const tmpsv = newSVpvn_flags(pv + 10, pvlen - 11, SvUTF8(cSVOPo_sv));
5270             SV ** const tmpo = cSVOPx_svp(o);
5271             SvREFCNT_dec(cSVOPo_sv);
5272             *tmpo = tmpsv;
5273             new_proto = o;
5274             *attrs = NULL;
5275         }
5276     } else if (o->op_type == OP_LIST) {
5277         OP * lasto;
5278         assert(o->op_flags & OPf_KIDS);
5279         lasto = cLISTOPo->op_first;
5280         assert(lasto->op_type == OP_PUSHMARK);
5281         for (o = OpSIBLING(lasto); o; o = OpSIBLING(o)) {
5282             if (o->op_type == OP_CONST) {
5283                 pv = SvPV(cSVOPo_sv, pvlen);
5284                 if (memBEGINs(pv, pvlen, "prototype(")) {
5285                     SV * const tmpsv = newSVpvn_flags(pv + 10, pvlen - 11, SvUTF8(cSVOPo_sv));
5286                     SV ** const tmpo = cSVOPx_svp(o);
5287                     SvREFCNT_dec(cSVOPo_sv);
5288                     *tmpo = tmpsv;
5289                     if (new_proto && ckWARN(WARN_MISC)) {
5290                         STRLEN new_len;
5291                         const char * newp = SvPV(cSVOPo_sv, new_len);
5292                         Perl_warner(aTHX_ packWARN(WARN_MISC),
5293                             "Attribute prototype(%" UTF8f ") discards earlier prototype attribute in same sub",
5294                             UTF8fARG(SvUTF8(cSVOPo_sv), new_len, newp));
5295                         op_free(new_proto);
5296                     }
5297                     else if (new_proto)
5298                         op_free(new_proto);
5299                     new_proto = o;
5300                     /* excise new_proto from the list */
5301                     op_sibling_splice(*attrs, lasto, 1, NULL);
5302                     o = lasto;
5303                     continue;
5304                 }
5305             }
5306             lasto = o;
5307         }
5308         /* If the list is now just the PUSHMARK, scrap the whole thing; otherwise attributes.xs
5309            would get pulled in with no real need */
5310         if (!OpHAS_SIBLING(cLISTOPx(*attrs)->op_first)) {
5311             op_free(*attrs);
5312             *attrs = NULL;
5313         }
5314     }
5315
5316     if (new_proto) {
5317         SV *svname;
5318         if (isGV(name)) {
5319             svname = sv_newmortal();
5320             gv_efullname3(svname, name, NULL);
5321         }
5322         else if (SvPOK(name) && *SvPVX((SV *)name) == '&')
5323             svname = newSVpvn_flags(SvPVX((SV *)name)+1, SvCUR(name)-1, SvUTF8(name)|SVs_TEMP);
5324         else
5325             svname = (SV *)name;
5326         if (ckWARN(WARN_ILLEGALPROTO))
5327             (void)validate_proto(svname, cSVOPx_sv(new_proto), TRUE,
5328                                  curstash);
5329         if (*proto && ckWARN(WARN_PROTOTYPE)) {
5330             STRLEN old_len, new_len;
5331             const char * oldp = SvPV(cSVOPx_sv(*proto), old_len);
5332             const char * newp = SvPV(cSVOPx_sv(new_proto), new_len);
5333
5334             if (curstash && svname == (SV *)name
5335              && !memchr(SvPVX(svname), ':', SvCUR(svname))) {
5336                 svname = sv_2mortal(newSVsv(PL_curstname));
5337                 sv_catpvs(svname, "::");
5338                 sv_catsv(svname, (SV *)name);
5339             }
5340
5341             Perl_warner(aTHX_ packWARN(WARN_PROTOTYPE),
5342                 "Prototype '%" UTF8f "' overridden by attribute 'prototype(%" UTF8f ")'"
5343                 " in %" SVf,
5344                 UTF8fARG(SvUTF8(cSVOPx_sv(*proto)), old_len, oldp),
5345                 UTF8fARG(SvUTF8(cSVOPx_sv(new_proto)), new_len, newp),
5346                 SVfARG(svname));
5347         }
5348         if (*proto)
5349             op_free(*proto);
5350         *proto = new_proto;
5351     }
5352 }
5353
5354 static void
5355 S_cant_declare(pTHX_ OP *o)
5356 {
5357     if (o->op_type == OP_NULL
5358      && (o->op_flags & (OPf_SPECIAL|OPf_KIDS)) == OPf_KIDS)
5359         o = cUNOPo->op_first;
5360     yyerror(Perl_form(aTHX_ "Can't declare %s in \"%s\"",
5361                              o->op_type == OP_NULL
5362                                && o->op_flags & OPf_SPECIAL
5363                                  ? "do block"
5364                                  : OP_DESC(o),
5365                              PL_parser->in_my == KEY_our   ? "our"   :
5366                              PL_parser->in_my == KEY_state ? "state" :
5367                                                              "my"));
5368 }
5369
5370 STATIC OP *
5371 S_my_kid(pTHX_ OP *o, OP *attrs, OP **imopsp)
5372 {
5373     I32 type;
5374     const bool stately = PL_parser && PL_parser->in_my == KEY_state;
5375
5376     PERL_ARGS_ASSERT_MY_KID;
5377
5378     if (!o || (PL_parser && PL_parser->error_count))
5379         return o;
5380
5381     type = o->op_type;
5382
5383     if (OP_TYPE_IS_OR_WAS(o, OP_LIST)) {
5384         OP *kid;
5385         for (kid = cLISTOPo->op_first; kid; kid = OpSIBLING(kid))
5386             my_kid(kid, attrs, imopsp);
5387         return o;
5388     } else if (type == OP_UNDEF || type == OP_STUB) {
5389         return o;
5390     } else if (type == OP_RV2SV ||      /* "our" declaration */
5391                type == OP_RV2AV ||
5392                type == OP_RV2HV) {
5393         if (cUNOPo->op_first->op_type != OP_GV) { /* MJD 20011224 */
5394             S_cant_declare(aTHX_ o);
5395         } else if (attrs) {
5396             GV * const gv = cGVOPx_gv(cUNOPo->op_first);
5397             assert(PL_parser);
5398             PL_parser->in_my = FALSE;
5399             PL_parser->in_my_stash = NULL;
5400             apply_attrs(GvSTASH(gv),
5401                         (type == OP_RV2SV ? GvSVn(gv) :
5402                          type == OP_RV2AV ? MUTABLE_SV(GvAVn(gv)) :
5403                          type == OP_RV2HV ? MUTABLE_SV(GvHVn(gv)) : MUTABLE_SV(gv)),
5404                         attrs);
5405         }
5406         o->op_private |= OPpOUR_INTRO;
5407         return o;
5408     }
5409     else if (type == OP_REFGEN || type == OP_SREFGEN) {
5410         if (!FEATURE_MYREF_IS_ENABLED)
5411             Perl_croak(aTHX_ "The experimental declared_refs "
5412                              "feature is not enabled");
5413         Perl_ck_warner_d(aTHX_
5414              packWARN(WARN_EXPERIMENTAL__DECLARED_REFS),
5415             "Declaring references is experimental");
5416         /* Kid is a nulled OP_LIST, handled above.  */
5417         my_kid(cUNOPo->op_first, attrs, imopsp);
5418         return o;
5419     }
5420     else if (type != OP_PADSV &&
5421              type != OP_PADAV &&
5422              type != OP_PADHV &&
5423              type != OP_PUSHMARK)
5424     {
5425         S_cant_declare(aTHX_ o);
5426         return o;
5427     }
5428     else if (attrs && type != OP_PUSHMARK) {
5429         HV *stash;
5430
5431         assert(PL_parser);
5432         PL_parser->in_my = FALSE;
5433         PL_parser->in_my_stash = NULL;
5434
5435         /* check for C<my Dog $spot> when deciding package */
5436         stash = PAD_COMPNAME_TYPE(o->op_targ);
5437         if (!stash)
5438             stash = PL_curstash;
5439         apply_attrs_my(stash, o, attrs, imopsp);
5440     }
5441     o->op_flags |= OPf_MOD;
5442     o->op_private |= OPpLVAL_INTRO;
5443     if (stately)
5444         o->op_private |= OPpPAD_STATE;
5445     return o;
5446 }
5447
5448 OP *
5449 Perl_my_attrs(pTHX_ OP *o, OP *attrs)
5450 {
5451     OP *rops;
5452     int maybe_scalar = 0;
5453
5454     PERL_ARGS_ASSERT_MY_ATTRS;
5455
5456 /* [perl #17376]: this appears to be premature, and results in code such as
5457    C< our(%x); > executing in list mode rather than void mode */
5458 #if 0
5459     if (o->op_flags & OPf_PARENS)
5460         list(o);
5461     else
5462         maybe_scalar = 1;
5463 #else
5464     maybe_scalar = 1;
5465 #endif
5466     if (attrs)
5467         SAVEFREEOP(attrs);
5468     rops = NULL;
5469     o = my_kid(o, attrs, &rops);
5470     if (rops) {
5471         if (maybe_scalar && o->op_type == OP_PADSV) {
5472             o = scalar(op_append_list(OP_LIST, rops, o));
5473             o->op_private |= OPpLVAL_INTRO;
5474         }
5475         else {
5476             /* The listop in rops might have a pushmark at the beginning,
5477                which will mess up list assignment. */
5478             LISTOP * const lrops = (LISTOP *)rops; /* for brevity */
5479             if (rops->op_type == OP_LIST &&
5480                 lrops->op_first && lrops->op_first->op_type == OP_PUSHMARK)
5481             {
5482                 OP * const pushmark = lrops->op_first;
5483                 /* excise pushmark */
5484                 op_sibling_splice(rops, NULL, 1, NULL);
5485                 op_free(pushmark);
5486             }
5487             o = op_append_list(OP_LIST, o, rops);
5488         }
5489     }
5490     PL_parser->in_my = FALSE;
5491     PL_parser->in_my_stash = NULL;
5492     return o;
5493 }
5494
5495 OP *
5496 Perl_sawparens(pTHX_ OP *o)
5497 {
5498     PERL_UNUSED_CONTEXT;
5499     if (o)
5500         o->op_flags |= OPf_PARENS;
5501     return o;
5502 }
5503
5504 OP *
5505 Perl_bind_match(pTHX_ I32 type, OP *left, OP *right)
5506 {
5507     OP *o;
5508     bool ismatchop = 0;
5509     const OPCODE ltype = left->op_type;
5510     const OPCODE rtype = right->op_type;
5511
5512     PERL_ARGS_ASSERT_BIND_MATCH;
5513
5514     if ( (ltype == OP_RV2AV || ltype == OP_RV2HV || ltype == OP_PADAV
5515           || ltype == OP_PADHV) && ckWARN(WARN_MISC))
5516     {
5517       const char * const desc
5518           = PL_op_desc[(
5519                           rtype == OP_SUBST || rtype == OP_TRANS
5520                        || rtype == OP_TRANSR
5521                        )
5522                        ? (int)rtype : OP_MATCH];
5523       const bool isary = ltype == OP_RV2AV || ltype == OP_PADAV;
5524       SV * const name =
5525         S_op_varname(aTHX_ left);
5526       if (name)
5527         Perl_warner(aTHX_ packWARN(WARN_MISC),
5528              "Applying %s to %" SVf " will act on scalar(%" SVf ")",
5529              desc, SVfARG(name), SVfARG(name));
5530       else {
5531         const char * const sample = (isary
5532              ? "@array" : "%hash");
5533         Perl_warner(aTHX_ packWARN(WARN_MISC),
5534              "Applying %s to %s will act on scalar(%s)",
5535              desc, sample, sample);
5536       }
5537     }
5538
5539     if (rtype == OP_CONST &&
5540         cSVOPx(right)->op_private & OPpCONST_BARE &&
5541         cSVOPx(right)->op_private & OPpCONST_STRICT)
5542     {
5543         no_bareword_allowed(right);
5544     }
5545
5546     /* !~ doesn't make sense with /r, so error on it for now */
5547     if (rtype == OP_SUBST && (cPMOPx(right)->op_pmflags & PMf_NONDESTRUCT) &&
5548         type == OP_NOT)
5549         /* diag_listed_as: Using !~ with %s doesn't make sense */
5550         yyerror("Using !~ with s///r doesn't make sense");
5551     if (rtype == OP_TRANSR && type == OP_NOT)
5552         /* diag_listed_as: Using !~ with %s doesn't make sense */
5553         yyerror("Using !~ with tr///r doesn't make sense");
5554
5555     ismatchop = (rtype == OP_MATCH ||
5556                  rtype == OP_SUBST ||
5557                  rtype == OP_TRANS || rtype == OP_TRANSR)
5558              && !(right->op_flags & OPf_SPECIAL);
5559     if (ismatchop && right->op_private & OPpTARGET_MY) {
5560         right->op_targ = 0;
5561         right->op_private &= ~OPpTARGET_MY;
5562     }
5563     if (!(right->op_flags & OPf_STACKED) && !right->op_targ && ismatchop) {
5564         if (left->op_type == OP_PADSV
5565          && !(left->op_private & OPpLVAL_INTRO))
5566         {
5567             right->op_targ = left->op_targ;
5568             op_free(left);
5569             o = right;
5570         }
5571         else {
5572             right->op_flags |= OPf_STACKED;
5573             if (rtype != OP_MATCH && rtype != OP_TRANSR &&
5574             ! (rtype == OP_TRANS &&
5575                right->op_private & OPpTRANS_IDENTICAL) &&
5576             ! (rtype == OP_SUBST &&
5577                (cPMOPx(right)->op_pmflags & PMf_NONDESTRUCT)))
5578                 left = op_lvalue(left, rtype);
5579             if (right->op_type == OP_TRANS || right->op_type == OP_TRANSR)
5580                 o = newBINOP(OP_NULL, OPf_STACKED, scalar(left), right);
5581             else
5582                 o = op_prepend_elem(rtype, scalar(left), right);
5583         }
5584         if (type == OP_NOT)
5585             return newUNOP(OP_NOT, 0, scalar(o));
5586         return o;
5587     }
5588     else
5589         return bind_match(type, left,
5590                 pmruntime(newPMOP(OP_MATCH, 0), right, NULL, 0, 0));
5591 }
5592
5593 OP *
5594 Perl_invert(pTHX_ OP *o)
5595 {
5596     if (!o)
5597         return NULL;
5598     return newUNOP(OP_NOT, OPf_SPECIAL, scalar(o));
5599 }
5600
5601 OP *
5602 Perl_cmpchain_start(pTHX_ I32 type, OP *left, OP *right)
5603 {
5604     BINOP *bop;
5605     OP *op;
5606
5607     if (!left)
5608         left = newOP(OP_NULL, 0);
5609     if (!right)
5610         right = newOP(OP_NULL, 0);
5611     scalar(left);
5612     scalar(right);
5613     NewOp(0, bop, 1, BINOP);
5614     op = (OP*)bop;
5615     ASSUME((PL_opargs[type] & OA_CLASS_MASK) == OA_BINOP);
5616     OpTYPE_set(op, type);
5617     cBINOPx(op)->op_flags = OPf_KIDS;
5618     cBINOPx(op)->op_private = 2;
5619     cBINOPx(op)->op_first = left;
5620     cBINOPx(op)->op_last = right;
5621     OpMORESIB_set(left, right);
5622     OpLASTSIB_set(right, op);
5623     return op;
5624 }
5625
5626 OP *
5627 Perl_cmpchain_extend(pTHX_ I32 type, OP *ch, OP *right)
5628 {
5629     BINOP *bop;
5630     OP *op;
5631
5632     PERL_ARGS_ASSERT_CMPCHAIN_EXTEND;
5633     if (!right)
5634         right = newOP(OP_NULL, 0);
5635     scalar(right);
5636     NewOp(0, bop, 1, BINOP);
5637     op = (OP*)bop;
5638     ASSUME((PL_opargs[type] & OA_CLASS_MASK) == OA_BINOP);
5639     OpTYPE_set(op, type);
5640     if (ch->op_type != OP_NULL) {
5641         UNOP *lch;
5642         OP *nch, *cleft, *cright;
5643         NewOp(0, lch, 1, UNOP);
5644         nch = (OP*)lch;
5645         OpTYPE_set(nch, OP_NULL);
5646         nch->op_flags = OPf_KIDS;
5647         cleft = cBINOPx(ch)->op_first;
5648         cright = cBINOPx(ch)->op_last;
5649         cBINOPx(ch)->op_first = NULL;
5650         cBINOPx(ch)->op_last = NULL;
5651         cBINOPx(ch)->op_private = 0;
5652         cBINOPx(ch)->op_flags = 0;
5653         cUNOPx(nch)->op_first = cright;
5654         OpMORESIB_set(cright, ch);
5655         OpMORESIB_set(ch, cleft);
5656         OpLASTSIB_set(cleft, nch);
5657         ch = nch;
5658     }
5659     OpMORESIB_set(right, op);
5660     OpMORESIB_set(op, cUNOPx(ch)->op_first);
5661     cUNOPx(ch)->op_first = right;
5662     return ch;
5663 }
5664
5665 OP *
5666 Perl_cmpchain_finish(pTHX_ OP *ch)
5667 {
5668
5669     PERL_ARGS_ASSERT_CMPCHAIN_FINISH;
5670     if (ch->op_type != OP_NULL) {
5671         OPCODE cmpoptype = ch->op_type;
5672         ch = CHECKOP(cmpoptype, ch);
5673         if(!ch->op_next && ch->op_type == cmpoptype)
5674             ch = fold_constants(op_integerize(op_std_init(ch)));
5675         return ch;
5676     } else {
5677         OP *condop = NULL;
5678         OP *rightarg = cUNOPx(ch)->op_first;
5679         cUNOPx(ch)->op_first = OpSIBLING(rightarg);
5680         OpLASTSIB_set(rightarg, NULL);
5681         while (1) {
5682             OP *cmpop = cUNOPx(ch)->op_first;
5683             OP *leftarg = OpSIBLING(cmpop);
5684             OPCODE cmpoptype = cmpop->op_type;
5685             OP *nextrightarg;
5686             bool is_last;
5687             is_last = !(cUNOPx(ch)->op_first = OpSIBLING(leftarg));
5688             OpLASTSIB_set(cmpop, NULL);
5689             OpLASTSIB_set(leftarg, NULL);
5690             if (is_last) {
5691                 ch->op_flags = 0;
5692                 op_free(ch);
5693                 nextrightarg = NULL;
5694             } else {
5695                 nextrightarg = newUNOP(OP_CMPCHAIN_DUP, 0, leftarg);
5696                 leftarg = newOP(OP_NULL, 0);
5697             }
5698             cBINOPx(cmpop)->op_first = leftarg;
5699             cBINOPx(cmpop)->op_last = rightarg;
5700             OpMORESIB_set(leftarg, rightarg);
5701             OpLASTSIB_set(rightarg, cmpop);
5702             cmpop->op_flags = OPf_KIDS;
5703             cmpop->op_private = 2;
5704             cmpop = CHECKOP(cmpoptype, cmpop);
5705             if(!cmpop->op_next && cmpop->op_type == cmpoptype)
5706                 cmpop = op_integerize(op_std_init(cmpop));
5707             condop = condop ? newLOGOP(OP_CMPCHAIN_AND, 0, cmpop, condop) :
5708                         cmpop;
5709             if (!nextrightarg)
5710                 return condop;
5711             rightarg = nextrightarg;
5712         }
5713     }
5714 }
5715
5716 /*
5717 =for apidoc op_scope
5718
5719 Wraps up an op tree with some additional ops so that at runtime a dynamic
5720 scope will be created.  The original ops run in the new dynamic scope,
5721 and then, provided that they exit normally, the scope will be unwound.
5722 The additional ops used to create and unwind the dynamic scope will
5723 normally be an C<enter>/C<leave> pair, but a C<scope> op may be used
5724 instead if the ops are simple enough to not need the full dynamic scope
5725 structure.
5726
5727 =cut
5728 */
5729
5730 OP *
5731 Perl_op_scope(pTHX_ OP *o)
5732 {
5733     if (o) {
5734         if (o->op_flags & OPf_PARENS || PERLDB_NOOPT || TAINTING_get) {
5735             o = op_prepend_elem(OP_LINESEQ,
5736                     newOP(OP_ENTER, (o->op_flags & OPf_WANT)), o);
5737             OpTYPE_set(o, OP_LEAVE);
5738         }
5739         else if (o->op_type == OP_LINESEQ) {
5740             OP *kid;
5741             OpTYPE_set(o, OP_SCOPE);
5742             kid = ((LISTOP*)o)->op_first;
5743             if (kid->op_type == OP_NEXTSTATE || kid->op_type == OP_DBSTATE) {
5744                 op_null(kid);
5745
5746                 /* The following deals with things like 'do {1 for 1}' */
5747                 kid = OpSIBLING(kid);
5748                 if (kid &&
5749                     (kid->op_type == OP_NEXTSTATE || kid->op_type == OP_DBSTATE))
5750                     op_null(kid);
5751             }
5752         }
5753         else
5754             o = newLISTOP(OP_SCOPE, 0, o, NULL);
5755     }
5756     return o;
5757 }
5758
5759 OP *
5760 Perl_op_unscope(pTHX_ OP *o)
5761 {
5762     if (o && o->op_type == OP_LINESEQ) {
5763         OP *kid = cLISTOPo->op_first;
5764         for(; kid; kid = OpSIBLING(kid))
5765             if (kid->op_type == OP_NEXTSTATE || kid->op_type == OP_DBSTATE)
5766                 op_null(kid);
5767     }
5768     return o;
5769 }
5770
5771 /*
5772 =for apidoc block_start
5773
5774 Handles compile-time scope entry.
5775 Arranges for hints to be restored on block
5776 exit and also handles pad sequence numbers to make lexical variables scope
5777 right.  Returns a savestack index for use with C<block_end>.
5778
5779 =cut
5780 */
5781
5782 int
5783 Perl_block_start(pTHX_ int full)
5784 {
5785     const int retval = PL_savestack_ix;
5786
5787     PL_compiling.cop_seq = PL_cop_seqmax;
5788     COP_SEQMAX_INC;
5789     pad_block_start(full);
5790     SAVEHINTS();
5791     PL_hints &= ~HINT_BLOCK_SCOPE;
5792     SAVECOMPILEWARNINGS();
5793     PL_compiling.cop_warnings = DUP_WARNINGS(PL_compiling.cop_warnings);
5794     SAVEI32(PL_compiling.cop_seq);
5795     PL_compiling.cop_seq = 0;
5796
5797     CALL_BLOCK_HOOKS(bhk_start, full);
5798
5799     return retval;
5800 }
5801
5802 /*
5803 =for apidoc block_end
5804
5805 Handles compile-time scope exit.  C<floor>
5806 is the savestack index returned by
5807 C<block_start>, and C<seq> is the body of the block.  Returns the block,
5808 possibly modified.
5809
5810 =cut
5811 */
5812
5813 OP*
5814 Perl_block_end(pTHX_ I32 floor, OP *seq)
5815 {
5816     const int needblockscope = PL_hints & HINT_BLOCK_SCOPE;
5817     OP* retval = voidnonfinal(seq);
5818     OP *o;
5819
5820     /* XXX Is the null PL_parser check necessary here? */
5821     assert(PL_parser); /* Let’s find out under debugging builds.  */
5822     if (PL_parser && PL_parser->parsed_sub) {
5823         o = newSTATEOP(0, NULL, NULL);
5824         op_null(o);
5825         retval = op_append_elem(OP_LINESEQ, retval, o);
5826     }
5827
5828     CALL_BLOCK_HOOKS(bhk_pre_end, &retval);
5829
5830     LEAVE_SCOPE(floor);
5831     if (needblockscope)
5832         PL_hints |= HINT_BLOCK_SCOPE; /* propagate out */
5833     o = pad_leavemy();
5834
5835     if (o) {
5836         /* pad_leavemy has created a sequence of introcv ops for all my
5837            subs declared in the block.  We have to replicate that list with
5838            clonecv ops, to deal with this situation:
5839
5840                sub {
5841                    my sub s1;
5842                    my sub s2;
5843                    sub s1 { state sub foo { \&s2 } }
5844                }->()
5845
5846            Originally, I was going to have introcv clone the CV and turn
5847            off the stale flag.  Since &s1 is declared before &s2, the
5848            introcv op for &s1 is executed (on sub entry) before the one for
5849            &s2.  But the &foo sub inside &s1 (which is cloned when &s1 is
5850            cloned, since it is a state sub) closes over &s2 and expects
5851            to see it in its outer CV’s pad.  If the introcv op clones &s1,
5852            then &s2 is still marked stale.  Since &s1 is not active, and
5853            &foo closes over &s1’s implicit entry for &s2, we get a â€˜Varia-
5854            ble will not stay shared’ warning.  Because it is the same stub
5855            that will be used when the introcv op for &s2 is executed, clos-
5856            ing over it is safe.  Hence, we have to turn off the stale flag
5857            on all lexical subs in the block before we clone any of them.
5858            Hence, having introcv clone the sub cannot work.  So we create a
5859            list of ops like this:
5860
5861                lineseq
5862                   |
5863                   +-- introcv
5864                   |
5865                   +-- introcv
5866                   |
5867                   +-- introcv
5868                   |
5869                   .
5870                   .
5871                   .
5872                   |
5873                   +-- clonecv
5874                   |
5875                   +-- clonecv
5876                   |
5877                   +-- clonecv
5878                   |
5879                   .
5880                   .
5881                   .
5882          */
5883         OP *kid = o->op_flags & OPf_KIDS ? cLISTOPo->op_first : o;
5884         OP * const last = o->op_flags & OPf_KIDS ? cLISTOPo->op_last : o;
5885         for (;; kid = OpSIBLING(kid)) {
5886             OP *newkid = newOP(OP_CLONECV, 0);
5887             newkid->op_targ = kid->op_targ;
5888             o = op_append_elem(OP_LINESEQ, o, newkid);
5889             if (kid == last) break;
5890         }
5891         retval = op_prepend_elem(OP_LINESEQ, o, retval);
5892     }
5893
5894     CALL_BLOCK_HOOKS(bhk_post_end, &retval);
5895
5896     return retval;
5897 }
5898
5899 /*
5900 =for apidoc_section $scope
5901
5902 =for apidoc blockhook_register
5903
5904 Register a set of hooks to be called when the Perl lexical scope changes
5905 at compile time.  See L<perlguts/"Compile-time scope hooks">.
5906
5907 =cut
5908 */
5909
5910 void
5911 Perl_blockhook_register(pTHX_ BHK *hk)
5912 {
5913     PERL_ARGS_ASSERT_BLOCKHOOK_REGISTER;
5914
5915     Perl_av_create_and_push(aTHX_ &PL_blockhooks, newSViv(PTR2IV(hk)));
5916 }
5917
5918 void
5919 Perl_newPROG(pTHX_ OP *o)
5920 {
5921     OP *start;
5922
5923     PERL_ARGS_ASSERT_NEWPROG;
5924
5925     if (PL_in_eval) {
5926         PERL_CONTEXT *cx;
5927         I32 i;
5928         if (PL_eval_root)
5929                 return;
5930         PL_eval_root = newUNOP(OP_LEAVEEVAL,
5931                                ((PL_in_eval & EVAL_KEEPERR)
5932                                 ? OPf_SPECIAL : 0), o);
5933
5934         cx = CX_CUR();
5935         assert(CxTYPE(cx) == CXt_EVAL);
5936
5937         if ((cx->blk_gimme & G_WANT) == G_VOID)
5938             scalarvoid(PL_eval_root);
5939         else if ((cx->blk_gimme & G_WANT) == G_LIST)
5940             list(PL_eval_root);
5941         else
5942             scalar(PL_eval_root);
5943
5944         start = op_linklist(PL_eval_root);
5945         PL_eval_root->op_next = 0;
5946         i = PL_savestack_ix;
5947         SAVEFREEOP(o);
5948         ENTER;
5949         S_process_optree(aTHX_ NULL, PL_eval_root, start);
5950         LEAVE;
5951         PL_savestack_ix = i;
5952     }
5953     else {
5954         if (o->op_type == OP_STUB) {
5955             /* This block is entered if nothing is compiled for the main
5956                program. This will be the case for an genuinely empty main
5957                program, or one which only has BEGIN blocks etc, so already
5958                run and freed.
5959
5960                Historically (5.000) the guard above was !o. However, commit
5961                f8a08f7b8bd67b28 (Jun 2001), integrated to blead as
5962                c71fccf11fde0068, changed perly.y so that newPROG() is now
5963                called with the output of block_end(), which returns a new
5964                OP_STUB for the case of an empty optree. ByteLoader (and
5965                maybe other things) also take this path, because they set up
5966                PL_main_start and PL_main_root directly, without generating an
5967                optree.
5968
5969                If the parsing the main program aborts (due to parse errors,
5970                or due to BEGIN or similar calling exit), then newPROG()
5971                isn't even called, and hence this code path and its cleanups
5972                are skipped. This shouldn't make a make a difference:
5973                * a non-zero return from perl_parse is a failure, and
5974                  perl_destruct() should be called immediately.
5975                * however, if exit(0) is called during the parse, then
5976                  perl_parse() returns 0, and perl_run() is called. As
5977                  PL_main_start will be NULL, perl_run() will return
5978                  promptly, and the exit code will remain 0.
5979             */
5980
5981             PL_comppad_name = 0;
5982             PL_compcv = 0;
5983             S_op_destroy(aTHX_ o);
5984             return;
5985         }
5986         PL_main_root = op_scope(sawparens(scalarvoid(o)));
5987         PL_curcop = &PL_compiling;
5988         start = LINKLIST(PL_main_root);
5989         PL_main_root->op_next = 0;
5990         S_process_optree(aTHX_ NULL, PL_main_root, start);
5991         if (!PL_parser->error_count)
5992             /* on error, leave CV slabbed so that ops left lying around
5993              * will eb cleaned up. Else unslab */
5994             cv_forget_slab(PL_compcv);
5995         PL_compcv = 0;
5996
5997         /* Register with debugger */
5998         if (PERLDB_INTER) {
5999             CV * const cv = get_cvs("DB::postponed", 0);
6000             if (cv) {
6001                 dSP;
6002                 PUSHMARK(SP);
6003                 XPUSHs(MUTABLE_SV(CopFILEGV(&PL_compiling)));
6004                 PUTBACK;
6005                 call_sv(MUTABLE_SV(cv), G_DISCARD);
6006             }
6007         }
6008     }
6009 }
6010
6011 OP *
6012 Perl_localize(pTHX_ OP *o, I32 lex)
6013 {
6014     PERL_ARGS_ASSERT_LOCALIZE;
6015
6016     if (o->op_flags & OPf_PARENS)
6017 /* [perl #17376]: this appears to be premature, and results in code such as
6018    C< our(%x); > executing in list mode rather than void mode */
6019 #if 0
6020         list(o);
6021 #else
6022         NOOP;
6023 #endif
6024     else {
6025         if ( PL_parser->bufptr > PL_parser->oldbufptr
6026             && PL_parser->bufptr[-1] == ','
6027             && ckWARN(WARN_PARENTHESIS))
6028         {
6029             char *s = PL_parser->bufptr;
6030             bool sigil = FALSE;
6031
6032             /* some heuristics to detect a potential error */
6033             while (*s && (memCHRs(", \t\n", *s)))
6034                 s++;
6035
6036             while (1) {
6037                 if (*s && (memCHRs("@$%", *s) || (!lex && *s == '*'))
6038                        && *++s
6039                        && (isWORDCHAR(*s) || UTF8_IS_CONTINUED(*s))) {
6040                     s++;
6041                     sigil = TRUE;
6042                     while (*s && (isWORDCHAR(*s) || UTF8_IS_CONTINUED(*s)))
6043                         s++;
6044                     while (*s && (memCHRs(", \t\n", *s)))
6045                         s++;
6046                 }
6047                 else
6048                     break;
6049             }
6050             if (sigil && (*s == ';' || *s == '=')) {
6051                 Perl_warner(aTHX_ packWARN(WARN_PARENTHESIS),
6052                                 "Parentheses missing around \"%s\" list",
6053                                 lex
6054                                     ? (PL_parser->in_my == KEY_our
6055                                         ? "our"
6056                                         : PL_parser->in_my == KEY_state
6057                                             ? "state"
6058                                             : "my")
6059                                     : "local");
6060             }
6061         }
6062     }
6063     if (lex)
6064         o = my(o);
6065     else
6066         o = op_lvalue(o, OP_NULL);              /* a bit kludgey */
6067     PL_parser->in_my = FALSE;
6068     PL_parser->in_my_stash = NULL;
6069     return o;
6070 }
6071
6072 OP *
6073 Perl_jmaybe(pTHX_ OP *o)
6074 {
6075     PERL_ARGS_ASSERT_JMAYBE;
6076
6077     if (o->op_type == OP_LIST) {
6078         if (FEATURE_MULTIDIMENSIONAL_IS_ENABLED) {
6079             OP * const o2
6080                 = newSVREF(newGVOP(OP_GV, 0, gv_fetchpvs(";", GV_ADD|GV_NOTQUAL, SVt_PV)));
6081             o = op_convert_list(OP_JOIN, 0, op_prepend_elem(OP_LIST, o2, o));
6082         }
6083         else {
6084             /* If the user disables this, then a warning might not be enough to alert
6085                them to a possible change of behaviour here, so throw an exception.
6086             */
6087             yyerror("Multidimensional hash lookup is disabled");
6088         }
6089     }
6090     return o;
6091 }
6092
6093 PERL_STATIC_INLINE OP *
6094 S_op_std_init(pTHX_ OP *o)
6095 {
6096     I32 type = o->op_type;
6097
6098     PERL_ARGS_ASSERT_OP_STD_INIT;
6099
6100     if (PL_opargs[type] & OA_RETSCALAR)
6101         scalar(o);
6102     if (PL_opargs[type] & OA_TARGET && !o->op_targ)
6103         o->op_targ = pad_alloc(type, SVs_PADTMP);
6104
6105     return o;
6106 }
6107
6108 PERL_STATIC_INLINE OP *
6109 S_op_integerize(pTHX_ OP *o)
6110 {
6111     I32 type = o->op_type;
6112
6113     PERL_ARGS_ASSERT_OP_INTEGERIZE;
6114
6115     /* integerize op. */
6116     if ((PL_opargs[type] & OA_OTHERINT) && (PL_hints & HINT_INTEGER))
6117     {
6118         o->op_ppaddr = PL_ppaddr[++(o->op_type)];
6119     }
6120
6121     if (type == OP_NEGATE)
6122         /* XXX might want a ck_negate() for this */
6123         cUNOPo->op_first->op_private &= ~OPpCONST_STRICT;
6124
6125     return o;
6126 }
6127
6128 /* This function exists solely to provide a scope to limit
6129    setjmp/longjmp() messing with auto variables.  It cannot be inlined because
6130    it uses setjmp
6131  */
6132 STATIC int
6133 S_fold_constants_eval(pTHX) {
6134     int ret = 0;
6135     dJMPENV;
6136
6137     JMPENV_PUSH(ret);
6138
6139     if (ret == 0) {
6140         CALLRUNOPS(aTHX);
6141     }
6142
6143     JMPENV_POP;
6144
6145     return ret;
6146 }
6147
6148 static OP *
6149 S_fold_constants(pTHX_ OP *const o)
6150 {
6151     OP *curop;
6152     OP *newop;
6153     I32 type = o->op_type;
6154     bool is_stringify;
6155     SV *sv = NULL;
6156     int ret = 0;
6157     OP *old_next;
6158     SV * const oldwarnhook = PL_warnhook;
6159     SV * const olddiehook  = PL_diehook;
6160     COP not_compiling;
6161     U8 oldwarn = PL_dowarn;
6162     I32 old_cxix;
6163
6164     PERL_ARGS_ASSERT_FOLD_CONSTANTS;
6165
6166     if (!(PL_opargs[type] & OA_FOLDCONST))
6167         goto nope;
6168
6169     switch (type) {
6170     case OP_UCFIRST:
6171     case OP_LCFIRST:
6172     case OP_UC:
6173     case OP_LC:
6174     case OP_FC:
6175 #ifdef USE_LOCALE_CTYPE
6176         if (IN_LC_COMPILETIME(LC_CTYPE))
6177             goto nope;
6178 #endif
6179         break;
6180     case OP_SLT:
6181     case OP_SGT:
6182     case OP_SLE:
6183     case OP_SGE:
6184     case OP_SCMP:
6185 #ifdef USE_LOCALE_COLLATE
6186         if (IN_LC_COMPILETIME(LC_COLLATE))
6187             goto nope;
6188 #endif
6189         break;
6190     case OP_SPRINTF:
6191         /* XXX what about the numeric ops? */
6192 #ifdef USE_LOCALE_NUMERIC
6193         if (IN_LC_COMPILETIME(LC_NUMERIC))
6194             goto nope;
6195 #endif
6196         break;
6197     case OP_PACK:
6198         if (!OpHAS_SIBLING(cLISTOPo->op_first)
6199           || OpSIBLING(cLISTOPo->op_first)->op_type != OP_CONST)
6200             goto nope;
6201         {
6202             SV * const sv = cSVOPx_sv(OpSIBLING(cLISTOPo->op_first));
6203             if (!SvPOK(sv) || SvGMAGICAL(sv)) goto nope;
6204             {
6205                 const char *s = SvPVX_const(sv);
6206                 while (s < SvEND(sv)) {
6207                     if (isALPHA_FOLD_EQ(*s, 'p')) goto nope;
6208                     s++;
6209                 }
6210             }
6211         }
6212         break;
6213     case OP_REPEAT:
6214         if (o->op_private & OPpREPEAT_DOLIST) goto nope;
6215         break;
6216     case OP_SREFGEN:
6217         if (cUNOPx(cUNOPo->op_first)->op_first->op_type != OP_CONST
6218          || SvPADTMP(cSVOPx_sv(cUNOPx(cUNOPo->op_first)->op_first)))
6219             goto nope;
6220     }
6221
6222     if (PL_parser && PL_parser->error_count)
6223         goto nope;              /* Don't try to run w/ errors */
6224
6225     for (curop = LINKLIST(o); curop != o; curop = LINKLIST(curop)) {
6226         switch (curop->op_type) {
6227         case OP_CONST:
6228             if (   (curop->op_private & OPpCONST_BARE)
6229                 && (curop->op_private & OPpCONST_STRICT)) {
6230                 no_bareword_allowed(curop);
6231                 goto nope;
6232             }
6233             /* FALLTHROUGH */
6234         case OP_LIST:
6235         case OP_SCALAR:
6236         case OP_NULL:
6237         case OP_PUSHMARK:
6238             /* Foldable; move to next op in list */
6239             break;
6240
6241         default:
6242             /* No other op types are considered foldable */
6243             goto nope;
6244         }
6245     }
6246
6247     curop = LINKLIST(o);
6248     old_next = o->op_next;
6249     o->op_next = 0;
6250     PL_op = curop;
6251
6252     old_cxix = cxstack_ix;
6253     create_eval_scope(NULL, G_FAKINGEVAL);
6254
6255     /* Verify that we don't need to save it:  */
6256     assert(PL_curcop == &PL_compiling);
6257     StructCopy(&PL_compiling, &not_compiling, COP);
6258     PL_curcop = &not_compiling;
6259     /* The above ensures that we run with all the correct hints of the
6260        currently compiling COP, but that IN_PERL_RUNTIME is true. */
6261     assert(IN_PERL_RUNTIME);
6262     PL_warnhook = PERL_WARNHOOK_FATAL;
6263     PL_diehook  = NULL;
6264
6265     /* Effective $^W=1.  */
6266     if ( ! (PL_dowarn & G_WARN_ALL_MASK))
6267         PL_dowarn |= G_WARN_ON;
6268
6269     ret = S_fold_constants_eval(aTHX);
6270
6271     switch (ret) {
6272     case 0:
6273         sv = *(PL_stack_sp--);
6274         if (o->op_targ && sv == PAD_SV(o->op_targ)) {   /* grab pad temp? */
6275             pad_swipe(o->op_targ,  FALSE);
6276         }
6277         else if (SvTEMP(sv)) {                  /* grab mortal temp? */
6278             SvREFCNT_inc_simple_void(sv);
6279             SvTEMP_off(sv);
6280         }
6281         else { assert(SvIMMORTAL(sv)); }
6282         break;
6283     case 3:
6284         /* Something tried to die.  Abandon constant folding.  */
6285         /* Pretend the error never happened.  */
6286         CLEAR_ERRSV();
6287         o->op_next = old_next;
6288         break;
6289     default:
6290         /* Don't expect 1 (setjmp failed) or 2 (something called my_exit)  */
6291         PL_warnhook = oldwarnhook;
6292         PL_diehook  = olddiehook;
6293         /* XXX note that this croak may fail as we've already blown away
6294          * the stack - eg any nested evals */
6295         Perl_croak(aTHX_ "panic: fold_constants JMPENV_PUSH returned %d", ret);
6296     }
6297     PL_dowarn   = oldwarn;
6298     PL_warnhook = oldwarnhook;
6299     PL_diehook  = olddiehook;
6300     PL_curcop = &PL_compiling;
6301
6302     /* if we croaked, depending on how we croaked the eval scope
6303      * may or may not have already been popped */
6304     if (cxstack_ix > old_cxix) {
6305         assert(cxstack_ix == old_cxix + 1);
6306         assert(CxTYPE(CX_CUR()) == CXt_EVAL);
6307         delete_eval_scope();
6308     }
6309     if (ret)
6310         goto nope;
6311
6312     /* OP_STRINGIFY and constant folding are used to implement qq.
6313        Here the constant folding is an implementation detail that we
6314        want to hide.  If the stringify op is itself already marked
6315        folded, however, then it is actually a folded join.  */
6316     is_stringify = type == OP_STRINGIFY && !o->op_folded;
6317     op_free(o);
6318     assert(sv);
6319     if (is_stringify)
6320         SvPADTMP_off(sv);
6321     else if (!SvIMMORTAL(sv)) {
6322         SvPADTMP_on(sv);
6323         SvREADONLY_on(sv);
6324     }
6325     newop = newSVOP(OP_CONST, 0, MUTABLE_SV(sv));
6326     if (!is_stringify) newop->op_folded = 1;
6327     return newop;
6328
6329  nope:
6330     return o;
6331 }
6332
6333 /* convert a constant range in list context into an OP_RV2AV, OP_CONST pair;
6334  * the constant value being an AV holding the flattened range.
6335  */
6336
6337 static void
6338 S_gen_constant_list(pTHX_ OP *o)
6339 {
6340     OP *curop, *old_next;
6341     SV * const oldwarnhook = PL_warnhook;
6342     SV * const olddiehook  = PL_diehook;
6343     COP *old_curcop;
6344     U8 oldwarn = PL_dowarn;
6345     SV **svp;
6346     AV *av;
6347     I32 old_cxix;
6348     COP not_compiling;
6349     int ret = 0;
6350     dJMPENV;
6351     bool op_was_null;
6352
6353     list(o);
6354     if (PL_parser && PL_parser->error_count)
6355         return;         /* Don't attempt to run with errors */
6356
6357     curop = LINKLIST(o);
6358     old_next = o->op_next;
6359     o->op_next = 0;
6360     op_was_null = o->op_type == OP_NULL;
6361     if (op_was_null) /* b3698342565fb462291fba4b432cfcd05b6eb4e1 */
6362         o->op_type = OP_CUSTOM;
6363     CALL_PEEP(curop);
6364     if (op_was_null)
6365         o->op_type = OP_NULL;
6366     S_prune_chain_head(&curop);
6367     PL_op = curop;
6368
6369     old_cxix = cxstack_ix;
6370     create_eval_scope(NULL, G_FAKINGEVAL);
6371
6372     old_curcop = PL_curcop;
6373     StructCopy(old_curcop, &not_compiling, COP);
6374     PL_curcop = &not_compiling;
6375     /* The above ensures that we run with all the correct hints of the
6376        current COP, but that IN_PERL_RUNTIME is true. */
6377     assert(IN_PERL_RUNTIME);
6378     PL_warnhook = PERL_WARNHOOK_FATAL;
6379     PL_diehook  = NULL;
6380     JMPENV_PUSH(ret);
6381
6382     /* Effective $^W=1.  */
6383     if ( ! (PL_dowarn & G_WARN_ALL_MASK))
6384         PL_dowarn |= G_WARN_ON;
6385
6386     switch (ret) {
6387     case 0:
6388 #if defined DEBUGGING && !defined DEBUGGING_RE_ONLY
6389         PL_curstackinfo->si_stack_hwm = 0; /* stop valgrind complaining */
6390 #endif
6391         Perl_pp_pushmark(aTHX);
6392         CALLRUNOPS(aTHX);
6393         PL_op = curop;
6394         assert (!(curop->op_flags & OPf_SPECIAL));
6395         assert(curop->op_type == OP_RANGE);
6396         Perl_pp_anonlist(aTHX);
6397         break;
6398     case 3:
6399         CLEAR_ERRSV();
6400         o->op_next = old_next;
6401         break;
6402     default:
6403         JMPENV_POP;
6404         PL_warnhook = oldwarnhook;
6405         PL_diehook = olddiehook;
6406         Perl_croak(aTHX_ "panic: gen_constant_list JMPENV_PUSH returned %d",
6407             ret);
6408     }
6409
6410     JMPENV_POP;
6411     PL_dowarn = oldwarn;
6412     PL_warnhook = oldwarnhook;
6413     PL_diehook = olddiehook;
6414     PL_curcop = old_curcop;
6415
6416     if (cxstack_ix > old_cxix) {
6417         assert(cxstack_ix == old_cxix + 1);
6418         assert(CxTYPE(CX_CUR()) == CXt_EVAL);
6419         delete_eval_scope();
6420     }
6421     if (ret)
6422         return;
6423
6424     OpTYPE_set(o, OP_RV2AV);
6425     o->op_flags &= ~OPf_REF;    /* treat \(1..2) like an ordinary list */
6426     o->op_flags |= OPf_PARENS;  /* and flatten \(1..2,3) */
6427     o->op_opt = 0;              /* needs to be revisited in rpeep() */
6428     av = (AV *)SvREFCNT_inc_NN(*PL_stack_sp--);
6429
6430     /* replace subtree with an OP_CONST */
6431     curop = ((UNOP*)o)->op_first;
6432     op_sibling_splice(o, NULL, -1, newSVOP(OP_CONST, 0, (SV *)av));
6433     op_free(curop);
6434
6435     if (AvFILLp(av) != -1)
6436         for (svp = AvARRAY(av) + AvFILLp(av); svp >= AvARRAY(av); --svp)
6437         {
6438             SvPADTMP_on(*svp);
6439             SvREADONLY_on(*svp);
6440         }
6441     LINKLIST(o);
6442     list(o);
6443     return;
6444 }
6445
6446 /*
6447 =for apidoc_section $optree_manipulation
6448 */
6449
6450 /* List constructors */
6451
6452 /*
6453 =for apidoc op_append_elem
6454
6455 Append an item to the list of ops contained directly within a list-type
6456 op, returning the lengthened list.  C<first> is the list-type op,
6457 and C<last> is the op to append to the list.  C<optype> specifies the
6458 intended opcode for the list.  If C<first> is not already a list of the
6459 right type, it will be upgraded into one.  If either C<first> or C<last>
6460 is null, the other is returned unchanged.
6461
6462 =cut
6463 */
6464
6465 OP *
6466 Perl_op_append_elem(pTHX_ I32 type, OP *first, OP *last)
6467 {
6468     if (!first)
6469         return last;
6470
6471     if (!last)
6472         return first;
6473
6474     if (first->op_type != (unsigned)type
6475         || (type == OP_LIST && (first->op_flags & OPf_PARENS)))
6476     {
6477         return newLISTOP(type, 0, first, last);
6478     }
6479
6480     op_sibling_splice(first, ((LISTOP*)first)->op_last, 0, last);
6481     first->op_flags |= OPf_KIDS;
6482     return first;
6483 }
6484
6485 /*
6486 =for apidoc op_append_list
6487
6488 Concatenate the lists of ops contained directly within two list-type ops,
6489 returning the combined list.  C<first> and C<last> are the list-type ops
6490 to concatenate.  C<optype> specifies the intended opcode for the list.
6491 If either C<first> or C<last> is not already a list of the right type,
6492 it will be upgraded into one.  If either C<first> or C<last> is null,
6493 the other is returned unchanged.
6494
6495 =cut
6496 */
6497
6498 OP *
6499 Perl_op_append_list(pTHX_ I32 type, OP *first, OP *last)
6500 {
6501     if (!first)
6502         return last;
6503
6504     if (!last)
6505         return first;
6506
6507     if (first->op_type != (unsigned)type)
6508         return op_prepend_elem(type, first, last);
6509
6510     if (last->op_type != (unsigned)type)
6511         return op_append_elem(type, first, last);
6512
6513     OpMORESIB_set(((LISTOP*)first)->op_last, ((LISTOP*)last)->op_first);
6514     ((LISTOP*)first)->op_last = ((LISTOP*)last)->op_last;
6515     OpLASTSIB_set(((LISTOP*)first)->op_last, first);
6516     first->op_flags |= (last->op_flags & OPf_KIDS);
6517
6518     S_op_destroy(aTHX_ last);
6519
6520     return first;
6521 }
6522
6523 /*
6524 =for apidoc op_prepend_elem
6525
6526 Prepend an item to the list of ops contained directly within a list-type
6527 op, returning the lengthened list.  C<first> is the op to prepend to the
6528 list, and C<last> is the list-type op.  C<optype> specifies the intended
6529 opcode for the list.  If C<last> is not already a list of the right type,
6530 it will be upgraded into one.  If either C<first> or C<last> is null,
6531 the other is returned unchanged.
6532
6533 =cut
6534 */
6535
6536 OP *
6537 Perl_op_prepend_elem(pTHX_ I32 type, OP *first, OP *last)
6538 {
6539     if (!first)
6540         return last;
6541
6542     if (!last)
6543         return first;
6544
6545     if (last->op_type == (unsigned)type) {
6546         if (type == OP_LIST) {  /* already a PUSHMARK there */
6547             /* insert 'first' after pushmark */
6548             op_sibling_splice(last, cLISTOPx(last)->op_first, 0, first);
6549             if (!(first->op_flags & OPf_PARENS))
6550                 last->op_flags &= ~OPf_PARENS;
6551         }
6552         else
6553             op_sibling_splice(last, NULL, 0, first);
6554         last->op_flags |= OPf_KIDS;
6555         return last;
6556     }
6557
6558     return newLISTOP(type, 0, first, last);
6559 }
6560
6561 /*
6562 =for apidoc op_convert_list
6563
6564 Converts C<o> into a list op if it is not one already, and then converts it
6565 into the specified C<type>, calling its check function, allocating a target if
6566 it needs one, and folding constants.
6567
6568 A list-type op is usually constructed one kid at a time via C<newLISTOP>,
6569 C<op_prepend_elem> and C<op_append_elem>.  Then finally it is passed to
6570 C<op_convert_list> to make it the right type.
6571
6572 =cut
6573 */
6574
6575 OP *
6576 Perl_op_convert_list(pTHX_ I32 type, I32 flags, OP *o)
6577 {
6578     if (type < 0) type = -type, flags |= OPf_SPECIAL;
6579     if (!o || o->op_type != OP_LIST)
6580         o = force_list(o, FALSE);
6581     else
6582     {
6583         o->op_flags &= ~OPf_WANT;
6584         o->op_private &= ~OPpLVAL_INTRO;
6585     }
6586
6587     if (!(PL_opargs[type] & OA_MARK))
6588         op_null(cLISTOPo->op_first);
6589     else {
6590         OP * const kid2 = OpSIBLING(cLISTOPo->op_first);
6591         if (kid2 && kid2->op_type == OP_COREARGS) {
6592             op_null(cLISTOPo->op_first);
6593             kid2->op_private |= OPpCOREARGS_PUSHMARK;
6594         }
6595     }
6596
6597     if (type != OP_SPLIT)
6598         /* At this point o is a LISTOP, but OP_SPLIT is a PMOP; let
6599          * ck_split() create a real PMOP and leave the op's type as listop
6600          * for now. Otherwise op_free() etc will crash.
6601          */
6602         OpTYPE_set(o, type);
6603
6604     o->op_flags |= flags;
6605     if (flags & OPf_FOLDED)
6606         o->op_folded = 1;
6607
6608     o = CHECKOP(type, o);
6609     if (o->op_type != (unsigned)type)
6610         return o;
6611
6612     return fold_constants(op_integerize(op_std_init(o)));
6613 }
6614
6615 /* Constructors */
6616
6617
6618 /*
6619 =for apidoc_section $optree_construction
6620
6621 =for apidoc newNULLLIST
6622
6623 Constructs, checks, and returns a new C<stub> op, which represents an
6624 empty list expression.
6625
6626 =cut
6627 */
6628
6629 OP *
6630 Perl_newNULLLIST(pTHX)
6631 {
6632     return newOP(OP_STUB, 0);
6633 }
6634
6635 /* promote o and any siblings to be a list if its not already; i.e.
6636  *
6637  *  o - A - B
6638  *
6639  * becomes
6640  *
6641  *  list
6642  *    |
6643  *  pushmark - o - A - B
6644  *
6645  * If nullit it true, the list op is nulled.
6646  */
6647
6648 static OP *
6649 S_force_list(pTHX_ OP *o, bool nullit)
6650 {
6651     if (!o || o->op_type != OP_LIST) {
6652         OP *rest = NULL;
6653         if (o) {
6654             /* manually detach any siblings then add them back later */
6655             rest = OpSIBLING(o);
6656             OpLASTSIB_set(o, NULL);
6657         }
6658         o = newLISTOP(OP_LIST, 0, o, NULL);
6659         if (rest)
6660             op_sibling_splice(o, cLISTOPo->op_last, 0, rest);
6661     }
6662     if (nullit)
6663         op_null(o);
6664     return o;
6665 }
6666
6667 /*
6668 =for apidoc newLISTOP
6669
6670 Constructs, checks, and returns an op of any list type.  C<type> is
6671 the opcode.  C<flags> gives the eight bits of C<op_flags>, except that
6672 C<OPf_KIDS> will be set automatically if required.  C<first> and C<last>
6673 supply up to two ops to be direct children of the list op; they are
6674 consumed by this function and become part of the constructed op tree.
6675
6676 For most list operators, the check function expects all the kid ops to be
6677 present already, so calling C<newLISTOP(OP_JOIN, ...)> (e.g.) is not
6678 appropriate.  What you want to do in that case is create an op of type
6679 C<OP_LIST>, append more children to it, and then call L</op_convert_list>.
6680 See L</op_convert_list> for more information.
6681
6682
6683 =cut
6684 */
6685
6686 OP *
6687 Perl_newLISTOP(pTHX_ I32 type, I32 flags, OP *first, OP *last)
6688 {
6689     LISTOP *listop;
6690     /* Note that allocating an OP_PUSHMARK can die under Safe.pm if
6691      * pushmark is banned. So do it now while existing ops are in a
6692      * consistent state, in case they suddenly get freed */
6693     OP* const pushop = type == OP_LIST ? newOP(OP_PUSHMARK, 0) : NULL;
6694
6695     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_LISTOP
6696         || type == OP_CUSTOM);
6697
6698     NewOp(1101, listop, 1, LISTOP);
6699     OpTYPE_set(listop, type);
6700     if (first || last)
6701         flags |= OPf_KIDS;
6702     listop->op_flags = (U8)flags;
6703
6704     if (!last && first)
6705         last = first;
6706     else if (!first && last)
6707         first = last;
6708     else if (first)
6709         OpMORESIB_set(first, last);
6710     listop->op_first = first;
6711     listop->op_last = last;
6712
6713     if (pushop) {
6714         OpMORESIB_set(pushop, first);
6715         listop->op_first = pushop;
6716         listop->op_flags |= OPf_KIDS;
6717         if (!last)
6718             listop->op_last = pushop;
6719     }
6720     if (listop->op_last)
6721         OpLASTSIB_set(listop->op_last, (OP*)listop);
6722
6723     return CHECKOP(type, listop);
6724 }
6725
6726 /*
6727 =for apidoc newOP
6728
6729 Constructs, checks, and returns an op of any base type (any type that
6730 has no extra fields).  C<type> is the opcode.  C<flags> gives the
6731 eight bits of C<op_flags>, and, shifted up eight bits, the eight bits
6732 of C<op_private>.
6733
6734 =cut
6735 */
6736
6737 OP *
6738 Perl_newOP(pTHX_ I32 type, I32 flags)
6739 {
6740     OP *o;
6741
6742     if (type == -OP_ENTEREVAL) {
6743         type = OP_ENTEREVAL;
6744         flags |= OPpEVAL_BYTES<<8;
6745     }
6746
6747     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_BASEOP
6748         || (PL_opargs[type] & OA_CLASS_MASK) == OA_BASEOP_OR_UNOP
6749         || (PL_opargs[type] & OA_CLASS_MASK) == OA_FILESTATOP
6750         || (PL_opargs[type] & OA_CLASS_MASK) == OA_LOOPEXOP);
6751
6752     NewOp(1101, o, 1, OP);
6753     OpTYPE_set(o, type);
6754     o->op_flags = (U8)flags;
6755
6756     o->op_next = o;
6757     o->op_private = (U8)(0 | (flags >> 8));
6758     if (PL_opargs[type] & OA_RETSCALAR)
6759         scalar(o);
6760     if (PL_opargs[type] & OA_TARGET)
6761         o->op_targ = pad_alloc(type, SVs_PADTMP);
6762     return CHECKOP(type, o);
6763 }
6764
6765 /*
6766 =for apidoc newUNOP
6767
6768 Constructs, checks, and returns an op of any unary type.  C<type> is
6769 the opcode.  C<flags> gives the eight bits of C<op_flags>, except that
6770 C<OPf_KIDS> will be set automatically if required, and, shifted up eight
6771 bits, the eight bits of C<op_private>, except that the bit with value 1
6772 is automatically set.  C<first> supplies an optional op to be the direct
6773 child of the unary op; it is consumed by this function and become part
6774 of the constructed op tree.
6775
6776 =for apidoc Amnh||OPf_KIDS
6777
6778 =cut
6779 */
6780
6781 OP *
6782 Perl_newUNOP(pTHX_ I32 type, I32 flags, OP *first)
6783 {
6784     UNOP *unop;
6785
6786     if (type == -OP_ENTEREVAL) {
6787         type = OP_ENTEREVAL;
6788         flags |= OPpEVAL_BYTES<<8;
6789     }
6790
6791     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_UNOP
6792         || (PL_opargs[type] & OA_CLASS_MASK) == OA_BASEOP_OR_UNOP
6793         || (PL_opargs[type] & OA_CLASS_MASK) == OA_FILESTATOP
6794         || (PL_opargs[type] & OA_CLASS_MASK) == OA_LOOPEXOP
6795         || type == OP_SASSIGN
6796         || type == OP_ENTERTRY
6797         || type == OP_ENTERTRYCATCH
6798         || type == OP_CUSTOM
6799         || type == OP_NULL );
6800
6801     if (!first)
6802         first = newOP(OP_STUB, 0);
6803     if (PL_opargs[type] & OA_MARK)
6804         first = force_list(first, TRUE);
6805
6806     NewOp(1101, unop, 1, UNOP);
6807     OpTYPE_set(unop, type);
6808     unop->op_first = first;
6809     unop->op_flags = (U8)(flags | OPf_KIDS);
6810     unop->op_private = (U8)(1 | (flags >> 8));
6811
6812     if (!OpHAS_SIBLING(first)) /* true unless weird syntax error */
6813         OpLASTSIB_set(first, (OP*)unop);
6814
6815     unop = (UNOP*) CHECKOP(type, unop);
6816     if (unop->op_next)
6817         return (OP*)unop;
6818
6819     return fold_constants(op_integerize(op_std_init((OP *) unop)));
6820 }
6821
6822 /*
6823 =for apidoc newUNOP_AUX
6824
6825 Similar to C<newUNOP>, but creates an C<UNOP_AUX> struct instead, with C<op_aux>
6826 initialised to C<aux>
6827
6828 =cut
6829 */
6830
6831 OP *
6832 Perl_newUNOP_AUX(pTHX_ I32 type, I32 flags, OP *first, UNOP_AUX_item *aux)
6833 {
6834     UNOP_AUX *unop;
6835
6836     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_UNOP_AUX
6837         || type == OP_CUSTOM);
6838
6839     NewOp(1101, unop, 1, UNOP_AUX);
6840     unop->op_type = (OPCODE)type;
6841     unop->op_ppaddr = PL_ppaddr[type];
6842     unop->op_first = first;
6843     unop->op_flags = (U8)(flags | (first ? OPf_KIDS : 0));
6844     unop->op_private = (U8)((first ? 1 : 0) | (flags >> 8));
6845     unop->op_aux = aux;
6846
6847     if (first && !OpHAS_SIBLING(first)) /* true unless weird syntax error */
6848         OpLASTSIB_set(first, (OP*)unop);
6849
6850     unop = (UNOP_AUX*) CHECKOP(type, unop);
6851
6852     return op_std_init((OP *) unop);
6853 }
6854
6855 /*
6856 =for apidoc newMETHOP
6857
6858 Constructs, checks, and returns an op of method type with a method name
6859 evaluated at runtime.  C<type> is the opcode.  C<flags> gives the eight
6860 bits of C<op_flags>, except that C<OPf_KIDS> will be set automatically,
6861 and, shifted up eight bits, the eight bits of C<op_private>, except that
6862 the bit with value 1 is automatically set.  C<dynamic_meth> supplies an
6863 op which evaluates method name; it is consumed by this function and
6864 become part of the constructed op tree.
6865 Supported optypes: C<OP_METHOD>.
6866
6867 =cut
6868 */
6869
6870 static OP*
6871 S_newMETHOP_internal(pTHX_ I32 type, I32 flags, OP* dynamic_meth, SV* const_meth) {
6872     METHOP *methop;
6873
6874     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_METHOP
6875         || type == OP_CUSTOM);
6876
6877     NewOp(1101, methop, 1, METHOP);
6878     if (dynamic_meth) {
6879         if (PL_opargs[type] & OA_MARK) dynamic_meth = force_list(dynamic_meth, TRUE);
6880         methop->op_flags = (U8)(flags | OPf_KIDS);
6881         methop->op_u.op_first = dynamic_meth;
6882         methop->op_private = (U8)(1 | (flags >> 8));
6883
6884         if (!OpHAS_SIBLING(dynamic_meth))
6885             OpLASTSIB_set(dynamic_meth, (OP*)methop);
6886     }
6887     else {
6888         assert(const_meth);
6889         methop->op_flags = (U8)(flags & ~OPf_KIDS);
6890         methop->op_u.op_meth_sv = const_meth;
6891         methop->op_private = (U8)(0 | (flags >> 8));
6892         methop->op_next = (OP*)methop;
6893     }
6894
6895 #ifdef USE_ITHREADS
6896     methop->op_rclass_targ = 0;
6897 #else
6898     methop->op_rclass_sv = NULL;
6899 #endif
6900
6901     OpTYPE_set(methop, type);
6902     return CHECKOP(type, methop);
6903 }
6904
6905 OP *
6906 Perl_newMETHOP (pTHX_ I32 type, I32 flags, OP* dynamic_meth) {
6907     PERL_ARGS_ASSERT_NEWMETHOP;
6908     return newMETHOP_internal(type, flags, dynamic_meth, NULL);
6909 }
6910
6911 /*
6912 =for apidoc newMETHOP_named
6913
6914 Constructs, checks, and returns an op of method type with a constant
6915 method name.  C<type> is the opcode.  C<flags> gives the eight bits of
6916 C<op_flags>, and, shifted up eight bits, the eight bits of
6917 C<op_private>.  C<const_meth> supplies a constant method name;
6918 it must be a shared COW string.
6919 Supported optypes: C<OP_METHOD_NAMED>.
6920
6921 =cut
6922 */
6923
6924 OP *
6925 Perl_newMETHOP_named (pTHX_ I32 type, I32 flags, SV* const_meth) {
6926     PERL_ARGS_ASSERT_NEWMETHOP_NAMED;
6927     return newMETHOP_internal(type, flags, NULL, const_meth);
6928 }
6929
6930 /*
6931 =for apidoc newBINOP
6932
6933 Constructs, checks, and returns an op of any binary type.  C<type>
6934 is the opcode.  C<flags> gives the eight bits of C<op_flags>, except
6935 that C<OPf_KIDS> will be set automatically, and, shifted up eight bits,
6936 the eight bits of C<op_private>, except that the bit with value 1 or
6937 2 is automatically set as required.  C<first> and C<last> supply up to
6938 two ops to be the direct children of the binary op; they are consumed
6939 by this function and become part of the constructed op tree.
6940
6941 =cut
6942 */
6943
6944 OP *
6945 Perl_newBINOP(pTHX_ I32 type, I32 flags, OP *first, OP *last)
6946 {
6947     BINOP *binop;
6948
6949     ASSUME((PL_opargs[type] & OA_CLASS_MASK) == OA_BINOP
6950         || type == OP_NULL || type == OP_CUSTOM);
6951
6952     NewOp(1101, binop, 1, BINOP);
6953
6954     if (!first)
6955         first = newOP(OP_NULL, 0);
6956
6957     OpTYPE_set(binop, type);
6958     binop->op_first = first;
6959     binop->op_flags = (U8)(flags | OPf_KIDS);
6960     if (!last) {
6961         last = first;
6962         binop->op_private = (U8)(1 | (flags >> 8));
6963     }
6964     else {
6965         binop->op_private = (U8)(2 | (flags >> 8));
6966         OpMORESIB_set(first, last);
6967     }
6968
6969     if (!OpHAS_SIBLING(last)) /* true unless weird syntax error */
6970         OpLASTSIB_set(last, (OP*)binop);
6971
6972     binop->op_last = OpSIBLING(binop->op_first);
6973     if (binop->op_last)
6974         OpLASTSIB_set(binop->op_last, (OP*)binop);
6975
6976     binop = (BINOP*)CHECKOP(type, binop);
6977     if (binop->op_next || binop->op_type != (OPCODE)type)
6978         return (OP*)binop;
6979
6980     return fold_constants(op_integerize(op_std_init((OP *)binop)));
6981 }
6982
6983 void
6984 Perl_invmap_dump(pTHX_ SV* invlist, UV *map)
6985 {
6986     const char indent[] = "    ";
6987
6988     UV len = _invlist_len(invlist);
6989     UV * array = invlist_array(invlist);
6990     UV i;
6991
6992     PERL_ARGS_ASSERT_INVMAP_DUMP;
6993
6994     for (i = 0; i < len; i++) {
6995         UV start = array[i];
6996         UV end   = (i + 1 < len) ? array[i+1] - 1 : IV_MAX;
6997
6998         PerlIO_printf(Perl_debug_log, "%s[%" UVuf "] 0x%04" UVXf, indent, i, start);
6999         if (end == IV_MAX) {
7000             PerlIO_printf(Perl_debug_log, " .. INFTY");
7001         }
7002         else if (end != start) {
7003             PerlIO_printf(Perl_debug_log, " .. 0x%04" UVXf, end);
7004         }
7005         else {
7006             PerlIO_printf(Perl_debug_log, "            ");
7007         }
7008
7009         PerlIO_printf(Perl_debug_log, "\t");
7010
7011         if (map[i] == TR_UNLISTED) {
7012             PerlIO_printf(Perl_debug_log, "TR_UNLISTED\n");
7013         }
7014         else if (map[i] == TR_SPECIAL_HANDLING) {
7015             PerlIO_printf(Perl_debug_log, "TR_SPECIAL_HANDLING\n");
7016         }
7017         else {
7018             PerlIO_printf(Perl_debug_log, "0x%04" UVXf "\n", map[i]);
7019         }
7020     }
7021 }
7022
7023 /* Given an OP_TRANS / OP_TRANSR op o, plus OP_CONST ops expr and repl
7024  * containing the search and replacement strings, assemble into
7025  * a translation table attached as o->op_pv.
7026  * Free expr and repl.
7027  * It expects the toker to have already set the
7028  *   OPpTRANS_COMPLEMENT
7029  *   OPpTRANS_SQUASH
7030  *   OPpTRANS_DELETE
7031  * flags as appropriate; this function may add
7032  *   OPpTRANS_USE_SVOP
7033  *   OPpTRANS_CAN_FORCE_UTF8
7034  *   OPpTRANS_IDENTICAL
7035  *   OPpTRANS_GROWS
7036  * flags
7037  */
7038
7039 static OP *
7040 S_pmtrans(pTHX_ OP *o, OP *expr, OP *repl)
7041 {
7042     /* This function compiles a tr///, from data gathered from toke.c, into a
7043      * form suitable for use by do_trans() in doop.c at runtime.
7044      *
7045      * It first normalizes the data, while discarding extraneous inputs; then
7046      * writes out the compiled data.  The normalization allows for complete
7047      * analysis, and avoids some false negatives and positives earlier versions
7048      * of this code had.
7049      *
7050      * The normalization form is an inversion map (described below in detail).
7051      * This is essentially the compiled form for tr///'s that require UTF-8,
7052      * and its easy to use it to write the 257-byte table for tr///'s that
7053      * don't need UTF-8.  That table is identical to what's been in use for
7054      * many perl versions, except that it doesn't handle some edge cases that
7055      * it used to, involving code points above 255.  The UTF-8 form now handles
7056      * these.  (This could be changed with extra coding should it shown to be
7057      * desirable.)
7058      *
7059      * If the complement (/c) option is specified, the lhs string (tstr) is
7060      * parsed into an inversion list.  Complementing these is trivial.  Then a
7061      * complemented tstr is built from that, and used thenceforth.  This hides
7062      * the fact that it was complemented from almost all successive code.
7063      *
7064      * One of the important characteristics to know about the input is whether
7065      * the transliteration may be done in place, or does a temporary need to be
7066      * allocated, then copied.  If the replacement for every character in every
7067      * possible string takes up no more bytes than the character it
7068      * replaces, then it can be edited in place.  Otherwise the replacement
7069      * could overwrite a byte we are about to read, depending on the strings
7070      * being processed.  The comments and variable names here refer to this as
7071      * "growing".  Some inputs won't grow, and might even shrink under /d, but
7072      * some inputs could grow, so we have to assume any given one might grow.
7073      * On very long inputs, the temporary could eat up a lot of memory, so we
7074      * want to avoid it if possible.  For non-UTF-8 inputs, everything is
7075      * single-byte, so can be edited in place, unless there is something in the
7076      * pattern that could force it into UTF-8.  The inversion map makes it
7077      * feasible to determine this.  Previous versions of this code pretty much
7078      * punted on determining if UTF-8 could be edited in place.  Now, this code
7079      * is rigorous in making that determination.
7080      *
7081      * Another characteristic we need to know is whether the lhs and rhs are
7082      * identical.  If so, and no other flags are present, the only effect of
7083      * the tr/// is to count the characters present in the input that are
7084      * mentioned in the lhs string.  The implementation of that is easier and
7085      * runs faster than the more general case.  Normalizing here allows for
7086      * accurate determination of this.  Previously there were false negatives
7087      * possible.
7088      *
7089      * Instead of 'transliterated', the comments here use 'unmapped' for the
7090      * characters that are left unchanged by the operation; otherwise they are
7091      * 'mapped'
7092      *
7093      * The lhs of the tr/// is here referred to as the t side.
7094      * The rhs of the tr/// is here referred to as the r side.
7095      */
7096
7097     SV * const tstr = ((SVOP*)expr)->op_sv;
7098     SV * const rstr = ((SVOP*)repl)->op_sv;
7099     STRLEN tlen;
7100     STRLEN rlen;
7101     const U8 * t0 = (U8*)SvPV_const(tstr, tlen);
7102     const U8 * r0 = (U8*)SvPV_const(rstr, rlen);
7103     const U8 * t = t0;
7104     const U8 * r = r0;
7105     UV t_count = 0, r_count = 0;  /* Number of characters in search and
7106                                          replacement lists */
7107
7108     /* khw thinks some of the private flags for this op are quaintly named.
7109      * OPpTRANS_GROWS for example is TRUE if the replacement for some lhs
7110      * character when represented in UTF-8 is longer than the original
7111      * character's UTF-8 representation */
7112     const bool complement = cBOOL(o->op_private & OPpTRANS_COMPLEMENT);
7113     const bool squash     = cBOOL(o->op_private & OPpTRANS_SQUASH);
7114     const bool del        = cBOOL(o->op_private & OPpTRANS_DELETE);
7115
7116     /* Set to true if there is some character < 256 in the lhs that maps to
7117      * above 255.  If so, a non-UTF-8 match string can be forced into being in
7118      * UTF-8 by a tr/// operation. */
7119     bool can_force_utf8 = FALSE;
7120
7121     /* What is the maximum expansion factor in UTF-8 transliterations.  If a
7122      * 2-byte UTF-8 encoded character is to be replaced by a 3-byte one, its
7123      * expansion factor is 1.5.  This number is used at runtime to calculate
7124      * how much space to allocate for non-inplace transliterations.  Without
7125      * this number, the worst case is 14, which is extremely unlikely to happen
7126      * in real life, and could require significant memory overhead. */
7127     NV max_expansion = 1.;
7128
7129     UV t_range_count, r_range_count, min_range_count;
7130     UV* t_array;
7131     SV* t_invlist;
7132     UV* r_map;
7133     UV r_cp = 0, t_cp = 0;
7134     UV t_cp_end = (UV) -1;
7135     UV r_cp_end;
7136     Size_t len;
7137     AV* invmap;
7138     UV final_map = TR_UNLISTED;    /* The final character in the replacement
7139                                       list, updated as we go along.  Initialize
7140                                       to something illegal */
7141
7142     bool rstr_utf8 = cBOOL(SvUTF8(rstr));
7143     bool tstr_utf8 = cBOOL(SvUTF8(tstr));
7144
7145     const U8* tend = t + tlen;
7146     const U8* rend = r + rlen;
7147
7148     SV * inverted_tstr = NULL;
7149
7150     Size_t i;
7151     unsigned int pass2;
7152
7153     /* This routine implements detection of a transliteration having a longer
7154      * UTF-8 representation than its source, by partitioning all the possible
7155      * code points of the platform into equivalence classes of the same UTF-8
7156      * byte length in the first pass.  As it constructs the mappings, it carves
7157      * these up into smaller chunks, but doesn't merge any together.  This
7158      * makes it easy to find the instances it's looking for.  A second pass is
7159      * done after this has been determined which merges things together to
7160      * shrink the table for runtime.  The table below is used for both ASCII
7161      * and EBCDIC platforms.  On EBCDIC, the byte length is not monotonically
7162      * increasing for code points below 256.  To correct for that, the macro
7163      * CP_ADJUST defined below converts those code points to ASCII in the first
7164      * pass, and we use the ASCII partition values.  That works because the
7165      * growth factor will be unaffected, which is all that is calculated during
7166      * the first pass. */
7167     UV PL_partition_by_byte_length[] = {
7168         0,
7169         0x80,   /* Below this is 1 byte representations */
7170         (32 * (1UL << (    UTF_ACCUMULATION_SHIFT))),   /* 2 bytes below this */
7171         (16 * (1UL << (2 * UTF_ACCUMULATION_SHIFT))),   /* 3 bytes below this */
7172         ( 8 * (1UL << (3 * UTF_ACCUMULATION_SHIFT))),   /* 4 bytes below this */
7173         ( 4 * (1UL << (4 * UTF_ACCUMULATION_SHIFT))),   /* 5 bytes below this */
7174         ( 2 * (1UL << (5 * UTF_ACCUMULATION_SHIFT)))    /* 6 bytes below this */
7175
7176 #  ifdef UV_IS_QUAD
7177                                                     ,
7178         ( ((UV) 1U << (6 * UTF_ACCUMULATION_SHIFT)))    /* 7 bytes below this */
7179 #  endif
7180
7181     };
7182
7183     PERL_ARGS_ASSERT_PMTRANS;
7184
7185     PL_hints |= HINT_BLOCK_SCOPE;
7186
7187     /* If /c, the search list is sorted and complemented.  This is now done by
7188      * creating an inversion list from it, and then trivially inverting that.
7189      * The previous implementation used qsort, but creating the list
7190      * automatically keeps it sorted as we go along */
7191     if (complement) {
7192         UV start, end;
7193         SV * inverted_tlist = _new_invlist(tlen);
7194         Size_t temp_len;
7195
7196         DEBUG_y(PerlIO_printf(Perl_debug_log,
7197                     "%s: %d: tstr before inversion=\n%s\n",
7198                     __FILE__, __LINE__, _byte_dump_string(t, tend - t, 0)));
7199
7200         while (t < tend) {
7201
7202             /* Non-utf8 strings don't have ranges, so each character is listed
7203              * out */
7204             if (! tstr_utf8) {
7205                 inverted_tlist = add_cp_to_invlist(inverted_tlist, *t);
7206                 t++;
7207             }
7208             else {  /* But UTF-8 strings have been parsed in toke.c to have
7209                  * ranges if appropriate. */
7210                 UV t_cp;
7211                 Size_t t_char_len;
7212
7213                 /* Get the first character */
7214                 t_cp = valid_utf8_to_uvchr(t, &t_char_len);
7215                 t += t_char_len;
7216
7217                 /* If the next byte indicates that this wasn't the first
7218                  * element of a range, the range is just this one */
7219                 if (t >= tend || *t != RANGE_INDICATOR) {
7220                     inverted_tlist = add_cp_to_invlist(inverted_tlist, t_cp);
7221                 }
7222                 else { /* Otherwise, ignore the indicator byte, and get the
7223                           final element, and add the whole range */
7224                     t++;
7225                     t_cp_end = valid_utf8_to_uvchr(t, &t_char_len);
7226                     t += t_char_len;
7227
7228                     inverted_tlist = _add_range_to_invlist(inverted_tlist,
7229                                                       t_cp, t_cp_end);
7230                 }
7231             }
7232         } /* End of parse through tstr */
7233
7234         /* The inversion list is done; now invert it */
7235         _invlist_invert(inverted_tlist);
7236
7237         /* Now go through the inverted list and create a new tstr for the rest
7238          * of the routine to use.  Since the UTF-8 version can have ranges, and
7239          * can be much more compact than the non-UTF-8 version, we create the
7240          * string in UTF-8 even if not necessary.  (This is just an intermediate
7241          * value that gets thrown away anyway.) */
7242         invlist_iterinit(inverted_tlist);
7243         inverted_tstr = newSVpvs("");
7244         while (invlist_iternext(inverted_tlist, &start, &end)) {
7245             U8 temp[UTF8_MAXBYTES];
7246             U8 * temp_end_pos;
7247
7248             /* IV_MAX keeps things from going out of bounds */
7249             start = MIN(IV_MAX, start);
7250             end   = MIN(IV_MAX, end);
7251
7252             temp_end_pos = uvchr_to_utf8(temp, start);
7253             sv_catpvn(inverted_tstr, (char *) temp, temp_end_pos - temp);
7254
7255             if (start != end) {
7256                 Perl_sv_catpvf(aTHX_ inverted_tstr, "%c", RANGE_INDICATOR);
7257                 temp_end_pos = uvchr_to_utf8(temp, end);
7258                 sv_catpvn(inverted_tstr, (char *) temp, temp_end_pos - temp);
7259             }
7260         }
7261
7262         /* Set up so the remainder of the routine uses this complement, instead
7263          * of the actual input */
7264         t0 = t = (U8*)SvPV_const(inverted_tstr, temp_len);
7265         tend = t0 + temp_len;
7266         tstr_utf8 = TRUE;
7267
7268         SvREFCNT_dec_NN(inverted_tlist);
7269     }
7270
7271     /* For non-/d, an empty rhs means to use the lhs */
7272     if (rlen == 0 && ! del) {
7273         r0 = t0;
7274         rend = tend;
7275         rstr_utf8  = tstr_utf8;
7276     }
7277
7278     t_invlist = _new_invlist(1);
7279
7280     /* Initialize to a single range */
7281     t_invlist = _add_range_to_invlist(t_invlist, 0, UV_MAX);
7282
7283     /* For the first pass, the lhs is partitioned such that the
7284      * number of UTF-8 bytes required to represent a code point in each
7285      * partition is the same as the number for any other code point in
7286      * that partion.  We copy the pre-compiled partion. */
7287     len = C_ARRAY_LENGTH(PL_partition_by_byte_length);
7288     invlist_extend(t_invlist, len);
7289     t_array = invlist_array(t_invlist);
7290     Copy(PL_partition_by_byte_length, t_array, len, UV);
7291     invlist_set_len(t_invlist, len, *(get_invlist_offset_addr(t_invlist)));
7292     Newx(r_map, len + 1, UV);
7293
7294     /* Parse the (potentially adjusted) input, creating the inversion map.
7295      * This is done in two passes.  The first pass is to determine if the
7296      * transliteration can be done in place.  The inversion map it creates
7297      * could be used, but generally would be larger and slower to run than the
7298      * output of the second pass, which starts with a more compact table and
7299      * allows more ranges to be merged */
7300     for (pass2 = 0; pass2 < 2; pass2++) {
7301         if (pass2) {
7302             /* Initialize to a single range */
7303             t_invlist = _add_range_to_invlist(t_invlist, 0, UV_MAX);
7304
7305             /* In the second pass, we just have the single range */
7306             len = 1;
7307             t_array = invlist_array(t_invlist);
7308         }
7309
7310 /* As noted earlier, we convert EBCDIC code points to Unicode in the first pass
7311  * so as to get the well-behaved length 1 vs length 2 boundary.  Only code
7312  * points below 256 differ between the two character sets in this regard.  For
7313  * these, we also can't have any ranges, as they have to be individually
7314  * converted. */
7315 #ifdef EBCDIC
7316 #  define CP_ADJUST(x)          ((pass2) ? (x) : NATIVE_TO_UNI(x))
7317 #  define FORCE_RANGE_LEN_1(x)  ((pass2) ? 0 : ((x) < 256))
7318 #  define CP_SKIP(x)            ((pass2) ? UVCHR_SKIP(x) : OFFUNISKIP(x))
7319 #else
7320 #  define CP_ADJUST(x)          (x)
7321 #  define FORCE_RANGE_LEN_1(x)  0
7322 #  define CP_SKIP(x)            UVCHR_SKIP(x)
7323 #endif
7324
7325         /* And the mapping of each of the ranges is initialized.  Initially,
7326          * everything is TR_UNLISTED. */
7327         for (i = 0; i < len; i++) {
7328             r_map[i] = TR_UNLISTED;
7329         }
7330
7331         t = t0;
7332         t_count = 0;
7333         r = r0;
7334         r_count = 0;
7335         t_range_count = r_range_count = 0;
7336
7337         DEBUG_y(PerlIO_printf(Perl_debug_log, "%s: %d:\ntstr=%s\n",
7338                     __FILE__, __LINE__, _byte_dump_string(t, tend - t, 0)));
7339         DEBUG_y(PerlIO_printf(Perl_debug_log, "rstr=%s\n",
7340                                         _byte_dump_string(r, rend - r, 0)));
7341         DEBUG_y(PerlIO_printf(Perl_debug_log, "/c=%d; /s=%d; /d=%d\n",
7342                                                   complement, squash, del));
7343         DEBUG_y(invmap_dump(t_invlist, r_map));
7344
7345         /* Now go through the search list constructing an inversion map.  The
7346          * input is not necessarily in any particular order.  Making it an
7347          * inversion map orders it, potentially simplifying, and makes it easy
7348          * to deal with at run time.  This is the only place in core that
7349          * generates an inversion map; if others were introduced, it might be
7350          * better to create general purpose routines to handle them.
7351          * (Inversion maps are created in perl in other places.)
7352          *
7353          * An inversion map consists of two parallel arrays.  One is
7354          * essentially an inversion list: an ordered list of code points such
7355          * that each element gives the first code point of a range of
7356          * consecutive code points that map to the element in the other array
7357          * that has the same index as this one (in other words, the
7358          * corresponding element).  Thus the range extends up to (but not
7359          * including) the code point given by the next higher element.  In a
7360          * true inversion map, the corresponding element in the other array
7361          * gives the mapping of the first code point in the range, with the
7362          * understanding that the next higher code point in the inversion
7363          * list's range will map to the next higher code point in the map.
7364          *
7365          * So if at element [i], let's say we have:
7366          *
7367          *     t_invlist  r_map
7368          * [i]    A         a
7369          *
7370          * This means that A => a, B => b, C => c....  Let's say that the
7371          * situation is such that:
7372          *
7373          * [i+1]  L        -1
7374          *
7375          * This means the sequence that started at [i] stops at K => k.  This
7376          * illustrates that you need to look at the next element to find where
7377          * a sequence stops.  Except, the highest element in the inversion list
7378          * begins a range that is understood to extend to the platform's
7379          * infinity.
7380          *
7381          * This routine modifies traditional inversion maps to reserve two
7382          * mappings:
7383          *
7384          *  TR_UNLISTED (or -1) indicates that no code point in the range
7385          *      is listed in the tr/// searchlist.  At runtime, these are
7386          *      always passed through unchanged.  In the inversion map, all
7387          *      points in the range are mapped to -1, instead of increasing,
7388          *      like the 'L' in the example above.
7389          *
7390          *      We start the parse with every code point mapped to this, and as
7391          *      we parse and find ones that are listed in the search list, we
7392          *      carve out ranges as we go along that override that.
7393          *
7394          *  TR_SPECIAL_HANDLING (or -2) indicates that every code point in the
7395          *      range needs special handling.  Again, all code points in the
7396          *      range are mapped to -2, instead of increasing.
7397          *
7398          *      Under /d this value means the code point should be deleted from
7399          *      the transliteration when encountered.
7400          *
7401          *      Otherwise, it marks that every code point in the range is to
7402          *      map to the final character in the replacement list.  This
7403          *      happens only when the replacement list is shorter than the
7404          *      search one, so there are things in the search list that have no
7405          *      correspondence in the replacement list.  For example, in
7406          *      tr/a-z/A/, 'A' is the final value, and the inversion map
7407          *      generated for this would be like this:
7408          *          \0  =>  -1
7409          *          a   =>   A
7410          *          b-z =>  -2
7411          *          z+1 =>  -1
7412          *      'A' appears once, then the remainder of the range maps to -2.
7413          *      The use of -2 isn't strictly necessary, as an inversion map is
7414          *      capable of representing this situation, but not nearly so
7415          *      compactly, and this is actually quite commonly encountered.
7416          *      Indeed, the original design of this code used a full inversion
7417          *      map for this.  But things like
7418          *          tr/\0-\x{FFFF}/A/
7419          *      generated huge data structures, slowly, and the execution was
7420          *      also slow.  So the current scheme was implemented.
7421          *
7422          *  So, if the next element in our example is:
7423          *
7424          * [i+2]  Q        q
7425          *
7426          * Then all of L, M, N, O, and P map to TR_UNLISTED.  If the next
7427          * elements are
7428          *
7429          * [i+3]  R        z
7430          * [i+4]  S       TR_UNLISTED
7431          *
7432          * Then Q => q; R => z; and S => TR_UNLISTED.  If [i+4] (the 'S') is
7433          * the final element in the arrays, every code point from S to infinity
7434          * maps to TR_UNLISTED.
7435          *
7436          */
7437                            /* Finish up range started in what otherwise would
7438                             * have been the final iteration */
7439         while (t < tend || t_range_count > 0) {
7440             bool adjacent_to_range_above = FALSE;
7441             bool adjacent_to_range_below = FALSE;
7442
7443             bool merge_with_range_above = FALSE;
7444             bool merge_with_range_below = FALSE;
7445
7446             UV span, invmap_range_length_remaining;
7447             SSize_t j;
7448             Size_t i;
7449
7450             /* If we are in the middle of processing a range in the 'target'
7451              * side, the previous iteration has set us up.  Otherwise, look at
7452              * the next character in the search list */
7453             if (t_range_count <= 0) {
7454                 if (! tstr_utf8) {
7455
7456                     /* Here, not in the middle of a range, and not UTF-8.  The
7457                      * next code point is the single byte where we're at */
7458                     t_cp = CP_ADJUST(*t);
7459                     t_range_count = 1;
7460                     t++;
7461                 }
7462                 else {
7463                     Size_t t_char_len;
7464
7465                     /* Here, not in the middle of a range, and is UTF-8.  The
7466                      * next code point is the next UTF-8 char in the input.  We
7467                      * know the input is valid, because the toker constructed
7468                      * it */
7469                     t_cp = CP_ADJUST(valid_utf8_to_uvchr(t, &t_char_len));
7470                     t += t_char_len;
7471
7472                     /* UTF-8 strings (only) have been parsed in toke.c to have
7473                      * ranges.  See if the next byte indicates that this was
7474                      * the first element of a range.  If so, get the final
7475                      * element and calculate the range size.  If not, the range
7476                      * size is 1 */
7477                     if (   t < tend && *t == RANGE_INDICATOR
7478                         && ! FORCE_RANGE_LEN_1(t_cp))
7479                     {
7480                         t++;
7481                         t_range_count = valid_utf8_to_uvchr(t, &t_char_len)
7482                                       - t_cp + 1;
7483                         t += t_char_len;
7484                     }
7485                     else {
7486                         t_range_count = 1;
7487                     }
7488                 }
7489
7490                 /* Count the total number of listed code points * */
7491                 t_count += t_range_count;
7492             }
7493
7494             /* Similarly, get the next character in the replacement list */
7495             if (r_range_count <= 0) {
7496                 if (r >= rend) {
7497
7498                     /* But if we've exhausted the rhs, there is nothing to map
7499                      * to, except the special handling one, and we make the
7500                      * range the same size as the lhs one. */
7501                     r_cp = TR_SPECIAL_HANDLING;
7502                     r_range_count = t_range_count;
7503
7504                     if (! del) {
7505                         DEBUG_yv(PerlIO_printf(Perl_debug_log,
7506                                         "final_map =%" UVXf "\n", final_map));
7507                     }
7508                 }
7509                 else {
7510                     if (! rstr_utf8) {
7511                         r_cp = CP_ADJUST(*r);
7512                         r_range_count = 1;
7513                         r++;
7514                     }
7515                     else {
7516                         Size_t r_char_len;
7517
7518                         r_cp = CP_ADJUST(valid_utf8_to_uvchr(r, &r_char_len));
7519                         r += r_char_len;
7520                         if (   r < rend && *r == RANGE_INDICATOR
7521                             && ! FORCE_RANGE_LEN_1(r_cp))
7522                         {
7523                             r++;
7524                             r_range_count = valid_utf8_to_uvchr(r,
7525                                                     &r_char_len) - r_cp + 1;
7526                             r += r_char_len;
7527                         }
7528                         else {
7529                             r_range_count = 1;
7530                         }
7531                     }
7532
7533                     if (r_cp == TR_SPECIAL_HANDLING) {
7534                         r_range_count = t_range_count;
7535                     }
7536
7537                     /* This is the final character so far */
7538                     final_map = r_cp + r_range_count - 1;
7539
7540                     r_count += r_range_count;
7541                 }
7542             }
7543
7544             /* Here, we have the next things ready in both sides.  They are
7545              * potentially ranges.  We try to process as big a chunk as
7546              * possible at once, but the lhs and rhs must be synchronized, so
7547              * things like tr/A-Z/a-ij-z/ will need to be processed in 2 chunks
7548              * */
7549             min_range_count = MIN(t_range_count, r_range_count);
7550
7551             /* Search the inversion list for the entry that contains the input
7552              * code point <cp>.  The inversion map was initialized to cover the
7553              * entire range of possible inputs, so this should not fail.  So
7554              * the return value is the index into the list's array of the range
7555              * that contains <cp>, that is, 'i' such that array[i] <= cp <
7556              * array[i+1] */
7557             j = _invlist_search(t_invlist, t_cp);
7558             assert(j >= 0);
7559             i = j;
7560
7561             /* Here, the data structure might look like:
7562              *
7563              * index    t   r     Meaning
7564              * [i-1]    J   j   # J-L => j-l
7565              * [i]      M  -1   # M => default; as do N, O, P, Q
7566              * [i+1]    R   x   # R => x, S => x+1, T => x+2
7567              * [i+2]    U   y   # U => y, V => y+1, ...
7568              * ...
7569              * [-1]     Z  -1   # Z => default; as do Z+1, ... infinity
7570              *
7571              * where 'x' and 'y' above are not to be taken literally.
7572              *
7573              * The maximum chunk we can handle in this loop iteration, is the
7574              * smallest of the three components: the lhs 't_', the rhs 'r_',
7575              * and the remainder of the range in element [i].  (In pass 1, that
7576              * range will have everything in it be of the same class; we can't
7577              * cross into another class.)  'min_range_count' already contains
7578              * the smallest of the first two values.  The final one is
7579              * irrelevant if the map is to the special indicator */
7580
7581             invmap_range_length_remaining = (i + 1 < len)
7582                                             ? t_array[i+1] - t_cp
7583                                             : IV_MAX - t_cp;
7584             span = MAX(1, MIN(min_range_count, invmap_range_length_remaining));
7585
7586             /* The end point of this chunk is where we are, plus the span, but
7587              * never larger than the platform's infinity */
7588             t_cp_end = MIN(IV_MAX, t_cp + span - 1);
7589
7590             if (r_cp == TR_SPECIAL_HANDLING) {
7591
7592                 /* If unmatched lhs code points map to the final map, use that
7593                  * value.  This being set to TR_SPECIAL_HANDLING indicates that
7594                  * we don't have a final map: unmatched lhs code points are
7595                  * simply deleted */
7596                 r_cp_end = (del) ? TR_SPECIAL_HANDLING : final_map;
7597             }
7598             else {
7599                 r_cp_end = MIN(IV_MAX, r_cp + span - 1);
7600
7601                 /* If something on the lhs is below 256, and something on the
7602                  * rhs is above, there is a potential mapping here across that
7603                  * boundary.  Indeed the only way there isn't is if both sides
7604                  * start at the same point.  That means they both cross at the
7605                  * same time.  But otherwise one crosses before the other */
7606                 if (t_cp < 256 && r_cp_end > 255 && r_cp != t_cp) {
7607                     can_force_utf8 = TRUE;
7608                 }
7609             }
7610
7611             /* If a character appears in the search list more than once, the
7612              * 2nd and succeeding occurrences are ignored, so only do this
7613              * range if haven't already processed this character.  (The range
7614              * has been set up so that all members in it will be of the same
7615              * ilk) */
7616             if (r_map[i] == TR_UNLISTED) {
7617                 DEBUG_yv(PerlIO_printf(Perl_debug_log,
7618                     "Processing %" UVxf "-%" UVxf " => %" UVxf "-%" UVxf "\n",
7619                     t_cp, t_cp_end, r_cp, r_cp_end));
7620
7621                 /* This is the first definition for this chunk, hence is valid
7622                  * and needs to be processed.  Here and in the comments below,
7623                  * we use the above sample data.  The t_cp chunk must be any
7624                  * contiguous subset of M, N, O, P, and/or Q.
7625                  *
7626                  * In the first pass, calculate if there is any possible input
7627                  * string that has a character whose transliteration will be
7628                  * longer than it.  If none, the transliteration may be done
7629                  * in-place, as it can't write over a so-far unread byte.
7630                  * Otherwise, a copy must first be made.  This could be
7631                  * expensive for long inputs.
7632                  *
7633                  * In the first pass, the t_invlist has been partitioned so
7634                  * that all elements in any single range have the same number
7635                  * of bytes in their UTF-8 representations.  And the r space is
7636                  * either a single byte, or a range of strictly monotonically
7637                  * increasing code points.  So the final element in the range
7638                  * will be represented by no fewer bytes than the initial one.
7639                  * That means that if the final code point in the t range has
7640                  * at least as many bytes as the final code point in the r,
7641                  * then all code points in the t range have at least as many
7642                  * bytes as their corresponding r range element.  But if that's
7643                  * not true, the transliteration of at least the final code
7644                  * point grows in length.  As an example, suppose we had
7645                  *      tr/\x{fff0}-\x{fff1}/\x{ffff}-\x{10000}/
7646                  * The UTF-8 for all but 10000 occupies 3 bytes on ASCII
7647                  * platforms.  We have deliberately set up the data structure
7648                  * so that any range in the lhs gets split into chunks for
7649                  * processing, such that every code point in a chunk has the
7650                  * same number of UTF-8 bytes.  We only have to check the final
7651                  * code point in the rhs against any code point in the lhs. */
7652                 if ( ! pass2
7653                     && r_cp_end != TR_SPECIAL_HANDLING
7654                     && CP_SKIP(t_cp_end) < CP_SKIP(r_cp_end))
7655                 {
7656                     /* Here, we will need to make a copy of the input string
7657                      * before doing the transliteration.  The worst possible
7658                      * case is an expansion ratio of 14:1. This is rare, and
7659                      * we'd rather allocate only the necessary amount of extra
7660                      * memory for that copy.  We can calculate the worst case
7661                      * for this particular transliteration is by keeping track
7662                      * of the expansion factor for each range.
7663                      *
7664                      * Consider tr/\xCB/\X{E000}/.  The maximum expansion
7665                      * factor is 1 byte going to 3 if the target string is not
7666                      * UTF-8, but 2 bytes going to 3 if it is in UTF-8.  We
7667                      * could pass two different values so doop could choose
7668                      * based on the UTF-8ness of the target.  But khw thinks
7669                      * (perhaps wrongly) that is overkill.  It is used only to
7670                      * make sure we malloc enough space.
7671                      *
7672                      * If no target string can force the result to be UTF-8,
7673                      * then we don't have to worry about the case of the target
7674                      * string not being UTF-8 */
7675                     NV t_size = (can_force_utf8 && t_cp < 256)
7676                                 ? 1
7677                                 : CP_SKIP(t_cp_end);
7678                     NV ratio = CP_SKIP(r_cp_end) / t_size;
7679
7680                     o->op_private |= OPpTRANS_GROWS;
7681
7682                     /* Now that we know it grows, we can keep track of the
7683                      * largest ratio */
7684                     if (ratio > max_expansion) {
7685                         max_expansion = ratio;
7686                         DEBUG_y(PerlIO_printf(Perl_debug_log,
7687                                         "New expansion factor: %" NVgf "\n",
7688                                         max_expansion));
7689                     }
7690                 }
7691
7692                 /* The very first range is marked as adjacent to the
7693                  * non-existent range below it, as it causes things to "just
7694                  * work" (TradeMark)
7695                  *
7696                  * If the lowest code point in this chunk is M, it adjoins the
7697                  * J-L range */
7698                 if (t_cp == t_array[i]) {
7699                     adjacent_to_range_below = TRUE;
7700
7701                     /* And if the map has the same offset from the beginning of
7702                      * the range as does this new code point (or both are for
7703                      * TR_SPECIAL_HANDLING), this chunk can be completely
7704                      * merged with the range below.  EXCEPT, in the first pass,
7705                      * we don't merge ranges whose UTF-8 byte representations
7706                      * have different lengths, so that we can more easily
7707                      * detect if a replacement is longer than the source, that
7708                      * is if it 'grows'.  But in the 2nd pass, there's no
7709                      * reason to not merge */
7710                     if (   (i > 0 && (   pass2
7711                                       || CP_SKIP(t_array[i-1])
7712                                                             == CP_SKIP(t_cp)))
7713                         && (   (   r_cp == TR_SPECIAL_HANDLING
7714                                 && r_map[i-1] == TR_SPECIAL_HANDLING)
7715                             || (   r_cp != TR_SPECIAL_HANDLING
7716                                 && r_cp - r_map[i-1] == t_cp - t_array[i-1])))
7717                     {
7718                         merge_with_range_below = TRUE;
7719                     }
7720                 }
7721
7722                 /* Similarly, if the highest code point in this chunk is 'Q',
7723                  * it adjoins the range above, and if the map is suitable, can
7724                  * be merged with it */
7725                 if (    t_cp_end >= IV_MAX - 1
7726                     || (   i + 1 < len
7727                         && t_cp_end + 1 == t_array[i+1]))
7728                 {
7729                     adjacent_to_range_above = TRUE;
7730                     if (i + 1 < len)
7731                     if (    (   pass2
7732                              || CP_SKIP(t_cp) == CP_SKIP(t_array[i+1]))
7733                         && (   (   r_cp == TR_SPECIAL_HANDLING
7734                                 && r_map[i+1] == (UV) TR_SPECIAL_HANDLING)
7735                             || (   r_cp != TR_SPECIAL_HANDLING
7736                                 && r_cp_end == r_map[i+1] - 1)))
7737                     {
7738                         merge_with_range_above = TRUE;
7739                     }
7740                 }
7741
7742                 if (merge_with_range_below && merge_with_range_above) {
7743
7744                     /* Here the new chunk looks like M => m, ... Q => q; and
7745                      * the range above is like R => r, ....  Thus, the [i-1]
7746                      * and [i+1] ranges should be seamlessly melded so the
7747                      * result looks like
7748                      *
7749                      * [i-1]    J   j   # J-T => j-t
7750                      * [i]      U   y   # U => y, V => y+1, ...
7751                      * ...
7752                      * [-1]     Z  -1   # Z => default; as do Z+1, ... infinity
7753                      */
7754                     Move(t_array + i + 2, t_array + i, len - i - 2, UV);
7755                     Move(r_map   + i + 2, r_map   + i, len - i - 2, UV);
7756                     len -= 2;
7757                     invlist_set_len(t_invlist,
7758                                     len,
7759                                     *(get_invlist_offset_addr(t_invlist)));
7760                 }
7761                 else if (merge_with_range_below) {
7762
7763                     /* Here the new chunk looks like M => m, .... But either
7764                      * (or both) it doesn't extend all the way up through Q; or
7765                      * the range above doesn't start with R => r. */
7766                     if (! adjacent_to_range_above) {
7767
7768                         /* In the first case, let's say the new chunk extends
7769                          * through O.  We then want:
7770                          *
7771                          * [i-1]    J   j   # J-O => j-o
7772                          * [i]      P  -1   # P => -1, Q => -1
7773                          * [i+1]    R   x   # R => x, S => x+1, T => x+2
7774                          * [i+2]    U   y   # U => y, V => y+1, ...
7775                          * ...
7776                          * [-1]     Z  -1   # Z => default; as do Z+1, ...
7777                          *                                            infinity
7778                          */
7779                         t_array[i] = t_cp_end + 1;
7780                         r_map[i] = TR_UNLISTED;
7781                     }
7782                     else { /* Adjoins the range above, but can't merge with it
7783                               (because 'x' is not the next map after q) */
7784                         /*
7785                          * [i-1]    J   j   # J-Q => j-q
7786                          * [i]      R   x   # R => x, S => x+1, T => x+2
7787                          * [i+1]    U   y   # U => y, V => y+1, ...
7788                          * ...
7789                          * [-1]     Z  -1   # Z => default; as do Z+1, ...
7790                          *                                          infinity
7791                          */
7792
7793                         Move(t_array + i + 1, t_array + i, len - i - 1, UV);
7794                         Move(r_map + i + 1, r_map + i, len - i - 1, UV);
7795                         len--;
7796                         invlist_set_len(t_invlist, len,
7797                                         *(get_invlist_offset_addr(t_invlist)));
7798                     }
7799                 }
7800                 else if (merge_with_range_above) {
7801
7802                     /* Here the new chunk ends with Q => q, and the range above
7803                      * must start with R => r, so the two can be merged. But
7804                      * either (or both) the new chunk doesn't extend all the
7805                      * way down to M; or the mapping of the final code point
7806                      * range below isn't m */
7807                     if (! adjacent_to_range_below) {
7808
7809                         /* In the first case, let's assume the new chunk starts
7810                          * with P => p.  Then, because it's merge-able with the
7811                          * range above, that range must be R => r.  We want:
7812                          *
7813                          * [i-1]    J   j   # J-L => j-l
7814                          * [i]      M  -1   # M => -1, N => -1
7815                          * [i+1]    P   p   # P-T => p-t
7816                          * [i+2]    U   y   # U => y, V => y+1, ...
7817                          * ...
7818                          * [-1]     Z  -1   # Z => default; as do Z+1, ...
7819                          *                                          infinity
7820                          */
7821                         t_array[i+1] = t_cp;
7822                         r_map[i+1] = r_cp;
7823                     }
7824                     else { /* Adjoins the range below, but can't merge with it
7825                             */
7826                         /*
7827                          * [i-1]    J   j   # J-L => j-l
7828                          * [i]      M   x   # M-T => x-5 .. x+2
7829                          * [i+1]    U   y   # U => y, V => y+1, ...
7830                          * ...
7831                          * [-1]     Z  -1   # Z => default; as do Z+1, ...
7832                          *                                          infinity
7833                          */
7834                         Move(t_array + i + 1, t_array + i, len - i - 1, UV);
7835                         Move(r_map   + i + 1, r_map   + i, len - i - 1, UV);
7836                         len--;
7837                         t_array[i] = t_cp;
7838                         r_map[i] = r_cp;
7839                         invlist_set_len(t_invlist, len,
7840                                         *(get_invlist_offset_addr(t_invlist)));
7841                     }
7842                 }
7843                 else if (adjacent_to_range_below && adjacent_to_range_above) {
7844                     /* The new chunk completely fills the gap between the
7845                      * ranges on either side, but can't merge with either of
7846                      * them.
7847                      *
7848                      * [i-1]    J   j   # J-L => j-l
7849                      * [i]      M   z   # M => z, N => z+1 ... Q => z+4
7850                      * [i+1]    R   x   # R => x, S => x+1, T => x+2
7851                      * [i+2]    U   y   # U => y, V => y+1, ...
7852                      * ...
7853                      * [-1]     Z  -1   # Z => default; as do Z+1, ... infinity
7854                      */
7855                     r_map[i] = r_cp;
7856                 }
7857                 else if (adjacent_to_range_below) {
7858                     /* The new chunk adjoins the range below, but not the range
7859                      * above, and can't merge.  Let's assume the chunk ends at
7860                      * O.
7861                      *
7862                      * [i-1]    J   j   # J-L => j-l
7863                      * [i]      M   z   # M => z, N => z+1, O => z+2
7864                      * [i+1]    P   -1  # P => -1, Q => -1
7865                      * [i+2]    R   x   # R => x, S => x+1, T => x+2
7866                      * [i+3]    U   y   # U => y, V => y+1, ...
7867                      * ...
7868                      * [-w]     Z  -1   # Z => default; as do Z+1, ... infinity
7869                      */
7870                     invlist_extend(t_invlist, len + 1);
7871                     t_array = invlist_array(t_invlist);
7872                     Renew(r_map, len + 1, UV);
7873
7874                     Move(t_array + i + 1, t_array + i + 2, len - i - 1, UV);
7875                     Move(r_map + i + 1,   r_map   + i + 2, len - i - 1, UV);
7876                     r_map[i] = r_cp;
7877                     t_array[i+1] = t_cp_end + 1;
7878                     r_map[i+1] = TR_UNLISTED;
7879                     len++;
7880                     invlist_set_len(t_invlist, len,
7881                                     *(get_invlist_offset_addr(t_invlist)));
7882                 }
7883                 else if (adjacent_to_range_above) {
7884                     /* The new chunk adjoins the range above, but not the range
7885                      * below, and can't merge.  Let's assume the new chunk
7886                      * starts at O
7887                      *
7888                      * [i-1]    J   j   # J-L => j-l
7889                      * [i]      M  -1   # M => default, N => default
7890                      * [i+1]    O   z   # O => z, P => z+1, Q => z+2
7891                      * [i+2]    R   x   # R => x, S => x+1, T => x+2
7892                      * [i+3]    U   y   # U => y, V => y+1, ...
7893                      * ...
7894                      * [-1]     Z  -1   # Z => default; as do Z+1, ... infinity
7895                      */
7896                     invlist_extend(t_invlist, len + 1);
7897                     t_array = invlist_array(t_invlist);
7898                     Renew(r_map, len + 1, UV);
7899
7900                     Move(t_array + i + 1, t_array + i + 2, len - i - 1, UV);
7901                     Move(r_map   + i + 1, r_map   + i + 2, len - i - 1, UV);
7902                     t_array[i+1] = t_cp;
7903                     r_map[i+1] = r_cp;
7904                     len++;
7905                     invlist_set_len(t_invlist, len,
7906                                     *(get_invlist_offset_addr(t_invlist)));
7907                 }
7908                 else {
7909                     /* The new chunk adjoins neither the range above, nor the
7910                      * range below.  Lets assume it is N..P => n..p
7911                      *
7912                      * [i-1]    J   j   # J-L => j-l
7913                      * [i]      M  -1   # M => default
7914                      * [i+1]    N   n   # N..P => n..p
7915                      * [i+2]    Q  -1   # Q => default
7916                      * [i+3]    R   x   # R => x, S => x+1, T => x+2
7917                      * [i+4]    U   y   # U => y, V => y+1, ...
7918                      * ...
7919                      * [-1]     Z  -1   # Z => default; as do Z+1, ... infinity
7920                      */
7921
7922                     DEBUG_yv(PerlIO_printf(Perl_debug_log,
7923                                         "Before fixing up: len=%d, i=%d\n",
7924                                         (int) len, (int) i));
7925                     DEBUG_yv(invmap_dump(t_invlist, r_map));
7926
7927                     invlist_extend(t_invlist, len + 2);
7928                     t_array = invlist_array(t_invlist);
7929                     Renew(r_map, len + 2, UV);
7930
7931                     Move(t_array + i + 1,
7932                          t_array + i + 2 + 1, len - i - (2 - 1), UV);
7933                     Move(r_map   + i + 1,
7934                          r_map   + i + 2 + 1, len - i - (2 - 1), UV);
7935
7936                     len += 2;
7937                     invlist_set_len(t_invlist, len,
7938                                     *(get_invlist_offset_addr(t_invlist)));
7939
7940                     t_array[i+1] = t_cp;
7941                     r_map[i+1] = r_cp;
7942
7943                     t_array[i+2] = t_cp_end + 1;
7944                     r_map[i+2] = TR_UNLISTED;
7945                 }
7946                 DEBUG_yv(PerlIO_printf(Perl_debug_log,
7947                           "After iteration: span=%" UVuf ", t_range_count=%"
7948                           UVuf " r_range_count=%" UVuf "\n",
7949                           span, t_range_count, r_range_count));
7950                 DEBUG_yv(invmap_dump(t_invlist, r_map));
7951             } /* End of this chunk needs to be processed */
7952
7953             /* Done with this chunk. */
7954             t_cp += span;
7955             if (t_cp >= IV_MAX) {
7956                 break;
7957             }
7958             t_range_count -= span;
7959             if (r_cp != TR_SPECIAL_HANDLING) {
7960                 r_cp += span;
7961                 r_range_count -= span;
7962             }
7963             else {
7964                 r_range_count = 0;
7965             }
7966
7967         } /* End of loop through the search list */
7968
7969         /* We don't need an exact count, but we do need to know if there is
7970          * anything left over in the replacement list.  So, just assume it's
7971          * one byte per character */
7972         if (rend > r) {
7973             r_count++;
7974         }
7975     } /* End of passes */
7976
7977     SvREFCNT_dec(inverted_tstr);
7978
7979     DEBUG_y(PerlIO_printf(Perl_debug_log, "After everything: \n"));
7980     DEBUG_y(invmap_dump(t_invlist, r_map));
7981
7982     /* We now have normalized the input into an inversion map.
7983      *
7984      * See if the lhs and rhs are equivalent.  If so, this tr/// is a no-op
7985      * except for the count, and streamlined runtime code can be used */
7986     if (!del && !squash) {
7987
7988         /* They are identical if they point to same address, or if everything
7989          * maps to UNLISTED or to itself.  This catches things that not looking
7990          * at the normalized inversion map doesn't catch, like tr/aa/ab/ or
7991          * tr/\x{100}-\x{104}/\x{100}-\x{102}\x{103}-\x{104}  */
7992         if (r0 != t0) {
7993             for (i = 0; i < len; i++) {
7994                 if (r_map[i] != TR_UNLISTED && r_map[i] != t_array[i]) {
7995                     goto done_identical_check;
7996                 }
7997             }
7998         }
7999
8000         /* Here have gone through entire list, and didn't find any
8001          * non-identical mappings */
8002         o->op_private |= OPpTRANS_IDENTICAL;
8003
8004       done_identical_check: ;
8005     }
8006
8007     t_array = invlist_array(t_invlist);
8008
8009     /* If has components above 255, we generally need to use the inversion map
8010      * implementation */
8011     if (   can_force_utf8
8012         || (   len > 0
8013             && t_array[len-1] > 255
8014                  /* If the final range is 0x100-INFINITY and is a special
8015                   * mapping, the table implementation can handle it */
8016             && ! (   t_array[len-1] == 256
8017                   && (   r_map[len-1] == TR_UNLISTED
8018                       || r_map[len-1] == TR_SPECIAL_HANDLING))))
8019     {
8020         SV* r_map_sv;
8021         SV* temp_sv;
8022
8023         /* A UTF-8 op is generated, indicated by this flag.  This op is an
8024          * sv_op */
8025         o->op_private |= OPpTRANS_USE_SVOP;
8026
8027         if (can_force_utf8) {
8028             o->op_private |= OPpTRANS_CAN_FORCE_UTF8;
8029         }
8030
8031         /* The inversion map is pushed; first the list. */
8032         invmap = MUTABLE_AV(newAV());
8033
8034         SvREADONLY_on(t_invlist);
8035         av_push(invmap, t_invlist);
8036
8037         /* 2nd is the mapping */
8038         r_map_sv = newSVpvn((char *) r_map, len * sizeof(UV));
8039         SvREADONLY_on(r_map_sv);
8040         av_push(invmap, r_map_sv);
8041
8042         /* 3rd is the max possible expansion factor */
8043         temp_sv = newSVnv(max_expansion);
8044         SvREADONLY_on(temp_sv);
8045         av_push(invmap, temp_sv);
8046
8047         /* Characters that are in the search list, but not in the replacement
8048          * list are mapped to the final character in the replacement list */
8049         if (! del && r_count < t_count) {
8050             temp_sv = newSVuv(final_map);
8051             SvREADONLY_on(temp_sv);
8052             av_push(invmap, temp_sv);
8053         }
8054
8055 #ifdef USE_ITHREADS
8056         cPADOPo->op_padix = pad_alloc(OP_TRANS, SVf_READONLY);
8057         SvREFCNT_dec(PAD_SVl(cPADOPo->op_padix));
8058         PAD_SETSV(cPADOPo->op_padix, (SV *) invmap);
8059         SvPADTMP_on(invmap);
8060         SvREADONLY_on(invmap);
8061 #else
8062         cSVOPo->op_sv = (SV *) invmap;
8063 #endif
8064
8065     }
8066     else {
8067         OPtrans_map *tbl;
8068         unsigned short i;
8069
8070         /* The OPtrans_map struct already contains one slot; hence the -1. */
8071         SSize_t struct_size = sizeof(OPtrans_map)
8072                             + (256 - 1 + 1)*sizeof(short);
8073
8074         /* Non-utf8 case: set o->op_pv to point to a simple 256+ entry lookup
8075         * table. Entries with the value TR_UNMAPPED indicate chars not to be
8076         * translated, while TR_DELETE indicates a search char without a
8077         * corresponding replacement char under /d.
8078         *
8079         * In addition, an extra slot at the end is used to store the final
8080         * repeating char, or TR_R_EMPTY under an empty replacement list, or
8081         * TR_DELETE under /d; which makes the runtime code easier.
8082         */
8083
8084         /* Indicate this is an op_pv */
8085         o->op_private &= ~OPpTRANS_USE_SVOP;
8086
8087         tbl = (OPtrans_map*)PerlMemShared_calloc(struct_size, 1);
8088         tbl->size = 256;
8089         cPVOPo->op_pv = (char*)tbl;
8090
8091         for (i = 0; i < len; i++) {
8092             STATIC_ASSERT_DECL(TR_SPECIAL_HANDLING == TR_DELETE);
8093             short upper = i >= len - 1 ? 256 : (short) t_array[i+1];
8094             short to = (short) r_map[i];
8095             short j;
8096             bool do_increment = TRUE;
8097
8098             /* Any code points above our limit should be irrelevant */
8099             if (t_array[i] >= tbl->size) break;
8100
8101             /* Set up the map */
8102             if (to == (short) TR_SPECIAL_HANDLING && ! del) {
8103                 to = (short) final_map;
8104                 do_increment = FALSE;
8105             }
8106             else if (to < 0) {
8107                 do_increment = FALSE;
8108             }
8109
8110             /* Create a map for everything in this range.  The value increases
8111              * except for the special cases */
8112             for (j = (short) t_array[i]; j < upper; j++) {
8113                 tbl->map[j] = to;
8114                 if (do_increment) to++;
8115             }
8116         }
8117
8118         tbl->map[tbl->size] = del
8119                               ? (short) TR_DELETE
8120                               : (short) rlen
8121                                 ? (short) final_map
8122                                 : (short) TR_R_EMPTY;
8123         DEBUG_y(PerlIO_printf(Perl_debug_log,"%s: %d\n", __FILE__, __LINE__));
8124         for (i = 0; i < tbl->size; i++) {
8125             if (tbl->map[i] < 0) {
8126                 DEBUG_y(PerlIO_printf(Perl_debug_log," %02x=>%d",
8127                                                 (unsigned) i, tbl->map[i]));
8128             }
8129             else {
8130                 DEBUG_y(PerlIO_printf(Perl_debug_log," %02x=>%02x",
8131                                                 (unsigned) i, tbl->map[i]));
8132             }
8133             if ((i+1) % 8 == 0 || i + 1 == (short) tbl->size) {
8134                 DEBUG_y(PerlIO_printf(Perl_debug_log,"\n"));
8135             }
8136         }
8137         DEBUG_y(PerlIO_printf(Perl_debug_log,"Final map 0x%x=>%02x\n",
8138                                 (unsigned) tbl->size, tbl->map[tbl->size]));
8139
8140         SvREFCNT_dec(t_invlist);
8141
8142 #if 0   /* code that added excess above-255 chars at the end of the table, in
8143            case we ever want to not use the inversion map implementation for
8144            this */
8145
8146         ASSUME(j <= rlen);
8147         excess = rlen - j;
8148
8149         if (excess) {
8150             /* More replacement chars than search chars:
8151              * store excess replacement chars at end of main table.
8152              */
8153
8154             struct_size += excess;
8155             tbl = (OPtrans_map*)PerlMemShared_realloc(tbl,
8156                         struct_size + excess * sizeof(short));
8157             tbl->size += excess;
8158             cPVOPo->op_pv = (char*)tbl;
8159
8160             for (i = 0; i < excess; i++)
8161                 tbl->map[i + 256] = r[j+i];
8162         }
8163         else {
8164             /* no more replacement chars than search chars */
8165         }
8166 #endif
8167
8168     }
8169
8170     DEBUG_y(PerlIO_printf(Perl_debug_log,
8171             "/d=%d, /s=%d, /c=%d, identical=%d, grows=%d,"
8172             " use_svop=%d, can_force_utf8=%d,\nexpansion=%" NVgf "\n",
8173             del, squash, complement,
8174             cBOOL(o->op_private & OPpTRANS_IDENTICAL),
8175             cBOOL(o->op_private & OPpTRANS_USE_SVOP),
8176             cBOOL(o->op_private & OPpTRANS_GROWS),
8177             cBOOL(o->op_private & OPpTRANS_CAN_FORCE_UTF8),
8178             max_expansion));
8179
8180     Safefree(r_map);
8181
8182     if(del && rlen != 0 && r_count == t_count) {
8183         Perl_ck_warner(aTHX_ packWARN(WARN_MISC), "Useless use of /d modifier in transliteration operator");
8184     } else if(r_count > t_count) {
8185         Perl_ck_warner(aTHX_ packWARN(WARN_MISC), "Replacement list is longer than search list");
8186     }
8187
8188     op_free(expr);
8189     op_free(repl);
8190
8191     return o;
8192 }
8193
8194
8195 /*
8196 =for apidoc newPMOP
8197
8198 Constructs, checks, and returns an op of any pattern matching type.
8199 C<type> is the opcode.  C<flags> gives the eight bits of C<op_flags>
8200 and, shifted up eight bits, the eight bits of C<op_private>.
8201
8202 =cut
8203 */
8204
8205 OP *
8206 Perl_newPMOP(pTHX_ I32 type, I32 flags)
8207 {
8208     PMOP *pmop;
8209
8210     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_PMOP
8211         || type == OP_CUSTOM);
8212
8213     NewOp(1101, pmop, 1, PMOP);
8214     OpTYPE_set(pmop, type);
8215     pmop->op_flags = (U8)flags;
8216     pmop->op_private = (U8)(0 | (flags >> 8));
8217     if (PL_opargs[type] & OA_RETSCALAR)
8218         scalar((OP *)pmop);
8219
8220     if (PL_hints & HINT_RE_TAINT)
8221         pmop->op_pmflags |= PMf_RETAINT;
8222 #ifdef USE_LOCALE_CTYPE
8223     if (IN_LC_COMPILETIME(LC_CTYPE)) {
8224         set_regex_charset(&(pmop->op_pmflags), REGEX_LOCALE_CHARSET);
8225     }
8226     else
8227 #endif
8228          if (IN_UNI_8_BIT) {
8229         set_regex_charset(&(pmop->op_pmflags), REGEX_UNICODE_CHARSET);
8230     }
8231     if (PL_hints & HINT_RE_FLAGS) {
8232         SV *reflags = Perl_refcounted_he_fetch_pvn(aTHX_
8233          PL_compiling.cop_hints_hash, STR_WITH_LEN("reflags"), 0, 0
8234         );
8235         if (reflags && SvOK(reflags)) pmop->op_pmflags |= SvIV(reflags);
8236         reflags = Perl_refcounted_he_fetch_pvn(aTHX_
8237          PL_compiling.cop_hints_hash, STR_WITH_LEN("reflags_charset"), 0, 0
8238         );
8239         if (reflags && SvOK(reflags)) {
8240             set_regex_charset(&(pmop->op_pmflags), (regex_charset)SvIV(reflags));
8241         }
8242     }
8243
8244
8245 #ifdef USE_ITHREADS
8246     assert(SvPOK(PL_regex_pad[0]));
8247     if (SvCUR(PL_regex_pad[0])) {
8248         /* Pop off the "packed" IV from the end.  */
8249         SV *const repointer_list = PL_regex_pad[0];
8250         const char *p = SvEND(repointer_list) - sizeof(IV);
8251         const IV offset = *((IV*)p);
8252
8253         assert(SvCUR(repointer_list) % sizeof(IV) == 0);
8254
8255         SvEND_set(repointer_list, p);
8256
8257         pmop->op_pmoffset = offset;
8258         /* This slot should be free, so assert this:  */
8259         assert(PL_regex_pad[offset] == &PL_sv_undef);
8260     } else {
8261         SV * const repointer = &PL_sv_undef;
8262         av_push(PL_regex_padav, repointer);
8263         pmop->op_pmoffset = av_top_index(PL_regex_padav);
8264         PL_regex_pad = AvARRAY(PL_regex_padav);
8265     }
8266 #endif
8267
8268     return CHECKOP(type, pmop);
8269 }
8270
8271 static void
8272 S_set_haseval(pTHX)
8273 {
8274     PADOFFSET i = 1;
8275     PL_cv_has_eval = 1;
8276     /* Any pad names in scope are potentially lvalues.  */
8277     for (; i < PadnamelistMAXNAMED(PL_comppad_name); i++) {
8278         PADNAME *pn = PAD_COMPNAME_SV(i);
8279         if (!pn || !PadnameLEN(pn))
8280             continue;
8281         if (PadnameOUTER(pn) || PadnameIN_SCOPE(pn, PL_cop_seqmax))
8282             S_mark_padname_lvalue(aTHX_ pn);
8283     }
8284 }
8285
8286 /* Given some sort of match op o, and an expression expr containing a
8287  * pattern, either compile expr into a regex and attach it to o (if it's
8288  * constant), or convert expr into a runtime regcomp op sequence (if it's
8289  * not)
8290  *
8291  * Flags currently has 2 bits of meaning:
8292  * 1: isreg indicates that the pattern is part of a regex construct, eg
8293  *      $x =~ /pattern/ or split /pattern/, as opposed to $x =~ $pattern or
8294  *      split "pattern", which aren't. In the former case, expr will be a list
8295  *      if the pattern contains more than one term (eg /a$b/).
8296  * 2: The pattern is for a split.
8297  *
8298  * When the pattern has been compiled within a new anon CV (for
8299  * qr/(?{...})/ ), then floor indicates the savestack level just before
8300  * the new sub was created
8301  *
8302  * tr/// is also handled.
8303  */
8304
8305 OP *
8306 Perl_pmruntime(pTHX_ OP *o, OP *expr, OP *repl, UV flags, I32 floor)
8307 {
8308     PMOP *pm;
8309     LOGOP *rcop;
8310     I32 repl_has_vars = 0;
8311     bool is_trans = (o->op_type == OP_TRANS || o->op_type == OP_TRANSR);
8312     bool is_compiletime;
8313     bool has_code;
8314     bool isreg    = cBOOL(flags & 1);
8315     bool is_split = cBOOL(flags & 2);
8316
8317     PERL_ARGS_ASSERT_PMRUNTIME;
8318
8319     if (is_trans) {
8320         return pmtrans(o, expr, repl);
8321     }
8322
8323     /* find whether we have any runtime or code elements;
8324      * at the same time, temporarily set the op_next of each DO block;
8325      * then when we LINKLIST, this will cause the DO blocks to be excluded
8326      * from the op_next chain (and from having LINKLIST recursively
8327      * applied to them). We fix up the DOs specially later */
8328
8329     is_compiletime = 1;
8330     has_code = 0;
8331     if (expr->op_type == OP_LIST) {
8332         OP *child;
8333         for (child = cLISTOPx(expr)->op_first; child; child = OpSIBLING(child)) {
8334             if (child->op_type == OP_NULL && (child->op_flags & OPf_SPECIAL)) {
8335                 has_code = 1;
8336                 assert(!child->op_next);
8337                 if (UNLIKELY(!OpHAS_SIBLING(child))) {
8338                     assert(PL_parser && PL_parser->error_count);
8339                     /* This can happen with qr/ (?{(^{})/.  Just fake up
8340                        the op we were expecting to see, to avoid crashing
8341                        elsewhere.  */
8342                     op_sibling_splice(expr, child, 0,
8343                               newSVOP(OP_CONST, 0, &PL_sv_no));
8344                 }
8345                 child->op_next = OpSIBLING(child);
8346             }
8347             else if (child->op_type != OP_CONST && child->op_type != OP_PUSHMARK)
8348             is_compiletime = 0;
8349         }
8350     }
8351     else if (expr->op_type != OP_CONST)
8352         is_compiletime = 0;
8353
8354     LINKLIST(expr);
8355
8356     /* fix up DO blocks; treat each one as a separate little sub;
8357      * also, mark any arrays as LIST/REF */
8358
8359     if (expr->op_type == OP_LIST) {
8360         OP *child;
8361         for (child = cLISTOPx(expr)->op_first; child; child = OpSIBLING(child)) {
8362
8363             if (child->op_type == OP_PADAV || child->op_type == OP_RV2AV) {
8364                 assert( !(child->op_flags  & OPf_WANT));
8365                 /* push the array rather than its contents. The regex
8366                  * engine will retrieve and join the elements later */
8367                 child->op_flags |= (OPf_WANT_LIST | OPf_REF);
8368                 continue;
8369             }
8370
8371             if (!(child->op_type == OP_NULL && (child->op_flags & OPf_SPECIAL)))
8372                 continue;
8373             child->op_next = NULL; /* undo temporary hack from above */
8374             scalar(child);
8375             LINKLIST(child);
8376             if (cLISTOPx(child)->op_first->op_type == OP_LEAVE) {
8377                 LISTOP *leaveop = cLISTOPx(cLISTOPx(child)->op_first);
8378                 /* skip ENTER */
8379                 assert(leaveop->op_first->op_type == OP_ENTER);
8380                 assert(OpHAS_SIBLING(leaveop->op_first));
8381                 child->op_next = OpSIBLING(leaveop->op_first);
8382                 /* skip leave */
8383                 assert(leaveop->op_flags & OPf_KIDS);
8384                 assert(leaveop->op_last->op_next == (OP*)leaveop);
8385                 leaveop->op_next = NULL; /* stop on last op */
8386                 op_null((OP*)leaveop);
8387             }
8388             else {
8389                 /* skip SCOPE */
8390                 OP *scope = cLISTOPx(child)->op_first;
8391                 assert(scope->op_type == OP_SCOPE);
8392                 assert(scope->op_flags & OPf_KIDS);
8393                 scope->op_next = NULL; /* stop on last op */
8394                 op_null(scope);
8395             }
8396
8397             /* XXX optimize_optree() must be called on o before
8398              * CALL_PEEP(), as currently S_maybe_multiconcat() can't
8399              * currently cope with a peephole-optimised optree.
8400              * Calling optimize_optree() here ensures that condition
8401              * is met, but may mean optimize_optree() is applied
8402              * to the same optree later (where hopefully it won't do any
8403              * harm as it can't convert an op to multiconcat if it's
8404              * already been converted */
8405             optimize_optree(child);
8406
8407             /* have to peep the DOs individually as we've removed it from
8408              * the op_next chain */
8409             CALL_PEEP(child);
8410             S_prune_chain_head(&(child->op_next));
8411             if (is_compiletime)
8412                 /* runtime finalizes as part of finalizing whole tree */
8413                 finalize_optree(child);
8414         }
8415     }
8416     else if (expr->op_type == OP_PADAV || expr->op_type == OP_RV2AV) {
8417         assert( !(expr->op_flags  & OPf_WANT));
8418         /* push the array rather than its contents. The regex
8419          * engine will retrieve and join the elements later */
8420         expr->op_flags |= (OPf_WANT_LIST | OPf_REF);
8421     }
8422
8423     PL_hints |= HINT_BLOCK_SCOPE;
8424     pm = (PMOP*)o;
8425     assert(floor==0 || (pm->op_pmflags & PMf_HAS_CV));
8426
8427     if (is_compiletime) {
8428         U32 rx_flags = pm->op_pmflags & RXf_PMf_COMPILETIME;
8429         regexp_engine const *eng = current_re_engine();
8430
8431         if (is_split) {
8432             /* make engine handle split ' ' specially */
8433             pm->op_pmflags |= PMf_SPLIT;
8434             rx_flags |= RXf_SPLIT;
8435         }
8436
8437         if (!has_code || !eng->op_comp) {
8438             /* compile-time simple constant pattern */
8439
8440             if ((pm->op_pmflags & PMf_HAS_CV) && !has_code) {
8441                 /* whoops! we guessed that a qr// had a code block, but we
8442                  * were wrong (e.g. /[(?{}]/ ). Throw away the PL_compcv
8443                  * that isn't required now. Note that we have to be pretty
8444                  * confident that nothing used that CV's pad while the
8445                  * regex was parsed, except maybe op targets for \Q etc.
8446                  * If there were any op targets, though, they should have
8447                  * been stolen by constant folding.
8448                  */
8449 #ifdef DEBUGGING
8450                 SSize_t i = 0;
8451                 assert(PadnamelistMAXNAMED(PL_comppad_name) == 0);
8452                 while (++i <= AvFILLp(PL_comppad)) {
8453 #  ifdef USE_PAD_RESET
8454                     /* under USE_PAD_RESET, pad swipe replaces a swiped
8455                      * folded constant with a fresh padtmp */
8456                     assert(!PL_curpad[i] || SvPADTMP(PL_curpad[i]));
8457 #  else
8458                     assert(!PL_curpad[i]);
8459 #  endif
8460                 }
8461 #endif
8462                 /* This LEAVE_SCOPE will restore PL_compcv to point to the
8463                  * outer CV (the one whose slab holds the pm op). The
8464                  * inner CV (which holds expr) will be freed later, once
8465                  * all the entries on the parse stack have been popped on
8466                  * return from this function. Which is why its safe to
8467                  * call op_free(expr) below.
8468                  */
8469                 LEAVE_SCOPE(floor);
8470                 pm->op_pmflags &= ~PMf_HAS_CV;
8471             }
8472
8473             /* Skip compiling if parser found an error for this pattern */
8474             if (pm->op_pmflags & PMf_HAS_ERROR) {
8475                 return o;
8476             }
8477
8478             PM_SETRE(pm,
8479                 eng->op_comp
8480                     ? eng->op_comp(aTHX_ NULL, 0, expr, eng, NULL, NULL,
8481                                         rx_flags, pm->op_pmflags)
8482                     : Perl_re_op_compile(aTHX_ NULL, 0, expr, eng, NULL, NULL,
8483                                         rx_flags, pm->op_pmflags)
8484             );
8485             op_free(expr);
8486         }
8487         else {
8488             /* compile-time pattern that includes literal code blocks */
8489
8490             REGEXP* re;
8491
8492             /* Skip compiling if parser found an error for this pattern */
8493             if (pm->op_pmflags & PMf_HAS_ERROR) {
8494                 return o;
8495             }
8496
8497             re = eng->op_comp(aTHX_ NULL, 0, expr, eng, NULL, NULL,
8498                         rx_flags,
8499                         (pm->op_pmflags |
8500                             ((PL_hints & HINT_RE_EVAL) ? PMf_USE_RE_EVAL : 0))
8501                     );
8502             PM_SETRE(pm, re);
8503             if (pm->op_pmflags & PMf_HAS_CV) {
8504                 CV *cv;
8505                 /* this QR op (and the anon sub we embed it in) is never
8506                  * actually executed. It's just a placeholder where we can
8507                  * squirrel away expr in op_code_list without the peephole
8508                  * optimiser etc processing it for a second time */
8509                 OP *qr = newPMOP(OP_QR, 0);
8510                 ((PMOP*)qr)->op_code_list = expr;
8511
8512                 /* handle the implicit sub{} wrapped round the qr/(?{..})/ */
8513                 SvREFCNT_inc_simple_void(PL_compcv);
8514                 cv = newATTRSUB(floor, 0, NULL, NULL, qr);
8515                 ReANY(re)->qr_anoncv = cv;
8516
8517                 /* attach the anon CV to the pad so that
8518                  * pad_fixup_inner_anons() can find it */
8519                 (void)pad_add_anon(cv, o->op_type);
8520                 SvREFCNT_inc_simple_void(cv);
8521             }
8522             else {
8523                 pm->op_code_list = expr;
8524             }
8525         }
8526     }
8527     else {
8528         /* runtime pattern: build chain of regcomp etc ops */
8529         bool reglist;
8530         PADOFFSET cv_targ = 0;
8531
8532         reglist = isreg && expr->op_type == OP_LIST;
8533         if (reglist)
8534             op_null(expr);
8535
8536         if (has_code) {
8537             pm->op_code_list = expr;
8538             /* don't free op_code_list; its ops are embedded elsewhere too */
8539             pm->op_pmflags |= PMf_CODELIST_PRIVATE;
8540         }
8541
8542         if (is_split)
8543             /* make engine handle split ' ' specially */
8544             pm->op_pmflags |= PMf_SPLIT;
8545
8546         /* the OP_REGCMAYBE is a placeholder in the non-threaded case
8547          * to allow its op_next to be pointed past the regcomp and
8548          * preceding stacking ops;
8549          * OP_REGCRESET is there to reset taint before executing the
8550          * stacking ops */
8551         if (pm->op_pmflags & PMf_KEEP || TAINTING_get)
8552             expr = newUNOP((TAINTING_get ? OP_REGCRESET : OP_REGCMAYBE),0,expr);
8553
8554         if (pm->op_pmflags & PMf_HAS_CV) {
8555             /* we have a runtime qr with literal code. This means
8556              * that the qr// has been wrapped in a new CV, which
8557              * means that runtime consts, vars etc will have been compiled
8558              * against a new pad. So... we need to execute those ops
8559              * within the environment of the new CV. So wrap them in a call
8560              * to a new anon sub. i.e. for
8561              *
8562              *     qr/a$b(?{...})/,
8563              *
8564              * we build an anon sub that looks like
8565              *
8566              *     sub { "a", $b, '(?{...})' }
8567              *
8568              * and call it, passing the returned list to regcomp.
8569              * Or to put it another way, the list of ops that get executed
8570              * are:
8571              *
8572              *     normal              PMf_HAS_CV
8573              *     ------              -------------------
8574              *                         pushmark (for regcomp)
8575              *                         pushmark (for entersub)
8576              *                         anoncode
8577              *                         srefgen
8578              *                         entersub
8579              *     regcreset                  regcreset
8580              *     pushmark                   pushmark
8581              *     const("a")                 const("a")
8582              *     gvsv(b)                    gvsv(b)
8583              *     const("(?{...})")          const("(?{...})")
8584              *                                leavesub
8585              *     regcomp             regcomp
8586              */
8587
8588             SvREFCNT_inc_simple_void(PL_compcv);
8589             CvLVALUE_on(PL_compcv);
8590             /* these lines are just an unrolled newANONATTRSUB */
8591             expr = newSVOP(OP_ANONCODE, 0,
8592                     MUTABLE_SV(newATTRSUB(floor, 0, NULL, NULL, expr)));
8593             cv_targ = expr->op_targ;
8594             expr = newUNOP(OP_REFGEN, 0, expr);
8595
8596             expr = list(force_list(newUNOP(OP_ENTERSUB, 0, scalar(expr)), TRUE));
8597         }
8598
8599         rcop = alloc_LOGOP(OP_REGCOMP, scalar(expr), o);
8600         rcop->op_flags |=  ((PL_hints & HINT_RE_EVAL) ? OPf_SPECIAL : 0)
8601                            | (reglist ? OPf_STACKED : 0);
8602         rcop->op_targ = cv_targ;
8603
8604         /* /$x/ may cause an eval, since $x might be qr/(?{..})/  */
8605         if (PL_hints & HINT_RE_EVAL)
8606             S_set_haseval(aTHX);
8607
8608         /* establish postfix order */
8609         if (expr->op_type == OP_REGCRESET || expr->op_type == OP_REGCMAYBE) {
8610             LINKLIST(expr);
8611             rcop->op_next = expr;
8612             ((UNOP*)expr)->op_first->op_next = (OP*)rcop;
8613         }
8614         else {
8615             rcop->op_next = LINKLIST(expr);
8616             expr->op_next = (OP*)rcop;
8617         }
8618
8619         op_prepend_elem(o->op_type, scalar((OP*)rcop), o);
8620     }
8621
8622     if (repl) {
8623         OP *curop = repl;
8624         bool konst;
8625         /* If we are looking at s//.../e with a single statement, get past
8626            the implicit do{}. */
8627         if (curop->op_type == OP_NULL && curop->op_flags & OPf_KIDS
8628              && cUNOPx(curop)->op_first->op_type == OP_SCOPE
8629              && cUNOPx(curop)->op_first->op_flags & OPf_KIDS)
8630          {
8631             OP *sib;
8632             OP *kid = cUNOPx(cUNOPx(curop)->op_first)->op_first;
8633             if (kid->op_type == OP_NULL && (sib = OpSIBLING(kid))
8634              && !OpHAS_SIBLING(sib))
8635                 curop = sib;
8636         }
8637         if (curop->op_type == OP_CONST)
8638             konst = TRUE;
8639         else if (( (curop->op_type == OP_RV2SV ||
8640                     curop->op_type == OP_RV2AV ||
8641                     curop->op_type == OP_RV2HV ||
8642                     curop->op_type == OP_RV2GV)
8643                    && cUNOPx(curop)->op_first
8644                    && cUNOPx(curop)->op_first->op_type == OP_GV )
8645                 || curop->op_type == OP_PADSV
8646                 || curop->op_type == OP_PADAV
8647                 || curop->op_type == OP_PADHV
8648                 || curop->op_type == OP_PADANY) {
8649             repl_has_vars = 1;
8650             konst = TRUE;
8651         }
8652         else konst = FALSE;
8653         if (konst
8654             && !(repl_has_vars
8655                  && (!PM_GETRE(pm)
8656                      || !RX_PRELEN(PM_GETRE(pm))
8657                      || RX_EXTFLAGS(PM_GETRE(pm)) & RXf_EVAL_SEEN)))
8658         {
8659             pm->op_pmflags |= PMf_CONST;        /* const for long enough */
8660             op_prepend_elem(o->op_type, scalar(repl), o);
8661         }
8662         else {
8663             rcop = alloc_LOGOP(OP_SUBSTCONT, scalar(repl), o);
8664             rcop->op_private = 1;
8665
8666             /* establish postfix order */
8667             rcop->op_next = LINKLIST(repl);
8668             repl->op_next = (OP*)rcop;
8669
8670             pm->op_pmreplrootu.op_pmreplroot = scalar((OP*)rcop);
8671             assert(!(pm->op_pmflags & PMf_ONCE));
8672             pm->op_pmstashstartu.op_pmreplstart = LINKLIST(rcop);
8673             rcop->op_next = 0;
8674         }
8675     }
8676
8677     return (OP*)pm;
8678 }
8679
8680 /*
8681 =for apidoc newSVOP
8682
8683 Constructs, checks, and returns an op of any type that involves an
8684 embedded SV.  C<type> is the opcode.  C<flags> gives the eight bits
8685 of C<op_flags>.  C<sv> gives the SV to embed in the op; this function
8686 takes ownership of one reference to it.
8687
8688 =cut
8689 */
8690
8691 OP *
8692 Perl_newSVOP(pTHX_ I32 type, I32 flags, SV *sv)
8693 {
8694     SVOP *svop;
8695
8696     PERL_ARGS_ASSERT_NEWSVOP;
8697
8698     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_SVOP
8699         || (PL_opargs[type] & OA_CLASS_MASK) == OA_PVOP_OR_SVOP
8700         || (PL_opargs[type] & OA_CLASS_MASK) == OA_FILESTATOP
8701         || type == OP_CUSTOM);
8702
8703     NewOp(1101, svop, 1, SVOP);
8704     OpTYPE_set(svop, type);
8705     svop->op_sv = sv;
8706     svop->op_next = (OP*)svop;
8707     svop->op_flags = (U8)flags;
8708     svop->op_private = (U8)(0 | (flags >> 8));
8709     if (PL_opargs[type] & OA_RETSCALAR)
8710         scalar((OP*)svop);
8711     if (PL_opargs[type] & OA_TARGET)
8712         svop->op_targ = pad_alloc(type, SVs_PADTMP);
8713     return CHECKOP(type, svop);
8714 }
8715
8716 /*
8717 =for apidoc newDEFSVOP
8718
8719 Constructs and returns an op to access C<$_>.
8720
8721 =cut
8722 */
8723
8724 OP *
8725 Perl_newDEFSVOP(pTHX)
8726 {
8727         return newSVREF(newGVOP(OP_GV, 0, PL_defgv));
8728 }
8729
8730 #ifdef USE_ITHREADS
8731
8732 /*
8733 =for apidoc newPADOP
8734
8735 Constructs, checks, and returns an op of any type that involves a
8736 reference to a pad element.  C<type> is the opcode.  C<flags> gives the
8737 eight bits of C<op_flags>.  A pad slot is automatically allocated, and
8738 is populated with C<sv>; this function takes ownership of one reference
8739 to it.
8740
8741 This function only exists if Perl has been compiled to use ithreads.
8742
8743 =cut
8744 */
8745
8746 OP *
8747 Perl_newPADOP(pTHX_ I32 type, I32 flags, SV *sv)
8748 {
8749     PADOP *padop;
8750
8751     PERL_ARGS_ASSERT_NEWPADOP;
8752
8753     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_SVOP
8754         || (PL_opargs[type] & OA_CLASS_MASK) == OA_PVOP_OR_SVOP
8755         || (PL_opargs[type] & OA_CLASS_MASK) == OA_FILESTATOP
8756         || type == OP_CUSTOM);
8757
8758     NewOp(1101, padop, 1, PADOP);
8759     OpTYPE_set(padop, type);
8760     padop->op_padix =
8761         pad_alloc(type, isGV(sv) ? SVf_READONLY : SVs_PADTMP);
8762     SvREFCNT_dec(PAD_SVl(padop->op_padix));
8763     PAD_SETSV(padop->op_padix, sv);
8764     assert(sv);
8765     padop->op_next = (OP*)padop;
8766     padop->op_flags = (U8)flags;
8767     if (PL_opargs[type] & OA_RETSCALAR)
8768         scalar((OP*)padop);
8769     if (PL_opargs[type] & OA_TARGET)
8770         padop->op_targ = pad_alloc(type, SVs_PADTMP);
8771     return CHECKOP(type, padop);
8772 }
8773
8774 #endif /* USE_ITHREADS */
8775
8776 /*
8777 =for apidoc newGVOP
8778
8779 Constructs, checks, and returns an op of any type that involves an
8780 embedded reference to a GV.  C<type> is the opcode.  C<flags> gives the
8781 eight bits of C<op_flags>.  C<gv> identifies the GV that the op should
8782 reference; calling this function does not transfer ownership of any
8783 reference to it.
8784
8785 =cut
8786 */
8787
8788 OP *
8789 Perl_newGVOP(pTHX_ I32 type, I32 flags, GV *gv)
8790 {
8791     PERL_ARGS_ASSERT_NEWGVOP;
8792
8793 #ifdef USE_ITHREADS
8794     return newPADOP(type, flags, SvREFCNT_inc_simple_NN(gv));
8795 #else
8796     return newSVOP(type, flags, SvREFCNT_inc_simple_NN(gv));
8797 #endif
8798 }
8799
8800 /*
8801 =for apidoc newPVOP
8802
8803 Constructs, checks, and returns an op of any type that involves an
8804 embedded C-level pointer (PV).  C<type> is the opcode.  C<flags> gives
8805 the eight bits of C<op_flags>.  C<pv> supplies the C-level pointer.
8806 Depending on the op type, the memory referenced by C<pv> may be freed
8807 when the op is destroyed.  If the op is of a freeing type, C<pv> must
8808 have been allocated using C<PerlMemShared_malloc>.
8809
8810 =cut
8811 */
8812
8813 OP *
8814 Perl_newPVOP(pTHX_ I32 type, I32 flags, char *pv)
8815 {
8816     const bool utf8 = cBOOL(flags & SVf_UTF8);
8817     PVOP *pvop;
8818
8819     flags &= ~SVf_UTF8;
8820
8821     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_PVOP_OR_SVOP
8822         || type == OP_RUNCV || type == OP_CUSTOM
8823         || (PL_opargs[type] & OA_CLASS_MASK) == OA_LOOPEXOP);
8824
8825     NewOp(1101, pvop, 1, PVOP);
8826     OpTYPE_set(pvop, type);
8827     pvop->op_pv = pv;
8828     pvop->op_next = (OP*)pvop;
8829     pvop->op_flags = (U8)flags;
8830     pvop->op_private = utf8 ? OPpPV_IS_UTF8 : 0;
8831     if (PL_opargs[type] & OA_RETSCALAR)
8832         scalar((OP*)pvop);
8833     if (PL_opargs[type] & OA_TARGET)
8834         pvop->op_targ = pad_alloc(type, SVs_PADTMP);
8835     return CHECKOP(type, pvop);
8836 }
8837
8838 void
8839 Perl_package(pTHX_ OP *o)
8840 {
8841     SV *const sv = cSVOPo->op_sv;
8842
8843     PERL_ARGS_ASSERT_PACKAGE;
8844
8845     SAVEGENERICSV(PL_curstash);
8846     save_item(PL_curstname);
8847
8848     PL_curstash = (HV *)SvREFCNT_inc(gv_stashsv(sv, GV_ADD));
8849
8850     sv_setsv(PL_curstname, sv);
8851
8852     PL_hints |= HINT_BLOCK_SCOPE;
8853     PL_parser->copline = NOLINE;
8854
8855     op_free(o);
8856 }
8857
8858 void
8859 Perl_package_version( pTHX_ OP *v )
8860 {
8861     U32 savehints = PL_hints;
8862     PERL_ARGS_ASSERT_PACKAGE_VERSION;
8863     PL_hints &= ~HINT_STRICT_VARS;
8864     sv_setsv( GvSV(gv_fetchpvs("VERSION", GV_ADDMULTI, SVt_PV)), cSVOPx(v)->op_sv );
8865     PL_hints = savehints;
8866     op_free(v);
8867 }
8868
8869 /* Extract the first two components of a "version" object as two 8bit integers
8870  * and return them packed into a single U16 in the format of PL_prevailing_version.
8871  * This function only ever has to cope with version objects already known
8872  * bounded by the current perl version, so we know its components will fit
8873  * (Up until we reach perl version 5.256 anyway) */
8874 static U16 S_extract_shortver(pTHX_ SV *sv)
8875 {
8876     SV *rv;
8877     if(!SvRV(sv) || !SvOBJECT(rv = SvRV(sv)) || !sv_derived_from(sv, "version"))
8878         return 0;
8879
8880     AV *av = MUTABLE_AV(SvRV(*hv_fetchs(MUTABLE_HV(rv), "version", 0)));
8881
8882     U16 shortver = 0;
8883
8884     IV major = av_count(av) > 0 ? SvIV(*av_fetch(av, 0, false)) : 0;
8885     if(major > 255)
8886         shortver |= 255 << 8;
8887     else
8888         shortver |= major << 8;
8889
8890     IV minor = av_count(av) > 1 ? SvIV(*av_fetch(av, 1, false)) : 0;
8891     if(minor > 255)
8892         shortver |= 255;
8893     else
8894         shortver |= minor;
8895
8896     return shortver;
8897 }
8898 #define SHORTVER(maj,min) ((maj << 8) | min)
8899
8900 void
8901 Perl_utilize(pTHX_ int aver, I32 floor, OP *version, OP *idop, OP *arg)
8902 {
8903     OP *pack;
8904     OP *imop;
8905     OP *veop;
8906     SV *use_version = NULL;
8907
8908     PERL_ARGS_ASSERT_UTILIZE;
8909
8910     if (idop->op_type != OP_CONST)
8911         Perl_croak(aTHX_ "Module name must be constant");
8912
8913     veop = NULL;
8914
8915     if (version) {
8916         SV * const vesv = ((SVOP*)version)->op_sv;
8917
8918         if (!arg && !SvNIOKp(vesv)) {
8919             arg = version;
8920         }
8921         else {
8922             OP *pack;
8923             SV *meth;
8924
8925             if (version->op_type != OP_CONST || !SvNIOKp(vesv))
8926                 Perl_croak(aTHX_ "Version number must be a constant number");
8927
8928             /* Make copy of idop so we don't free it twice */
8929             pack = newSVOP(OP_CONST, 0, newSVsv(((SVOP*)idop)->op_sv));
8930
8931             /* Fake up a method call to VERSION */
8932             meth = newSVpvs_share("VERSION");
8933             veop = op_convert_list(OP_ENTERSUB, OPf_STACKED|OPf_SPECIAL,
8934                             op_append_elem(OP_LIST,
8935                                         op_prepend_elem(OP_LIST, pack, version),
8936                                         newMETHOP_named(OP_METHOD_NAMED, 0, meth)));
8937         }
8938     }
8939
8940     /* Fake up an import/unimport */
8941     if (arg && arg->op_type == OP_STUB) {
8942         imop = arg;             /* no import on explicit () */
8943     }
8944     else if (SvNIOKp(((SVOP*)idop)->op_sv)) {
8945         imop = NULL;            /* use 5.0; */
8946         if (aver)
8947             use_version = ((SVOP*)idop)->op_sv;
8948         else
8949             idop->op_private |= OPpCONST_NOVER;
8950     }
8951     else {
8952         SV *meth;
8953
8954         /* Make copy of idop so we don't free it twice */
8955         pack = newSVOP(OP_CONST, 0, newSVsv(((SVOP*)idop)->op_sv));
8956
8957         /* Fake up a method call to import/unimport */
8958         meth = aver
8959             ? newSVpvs_share("import") : newSVpvs_share("unimport");
8960         imop = op_convert_list(OP_ENTERSUB, OPf_STACKED|OPf_SPECIAL,
8961                        op_append_elem(OP_LIST,
8962                                    op_prepend_elem(OP_LIST, pack, arg),
8963                                    newMETHOP_named(OP_METHOD_NAMED, 0, meth)
8964                        ));
8965     }
8966
8967     /* Fake up the BEGIN {}, which does its thing immediately. */
8968     newATTRSUB(floor,
8969         newSVOP(OP_CONST, 0, newSVpvs_share("BEGIN")),
8970         NULL,
8971         NULL,
8972         op_append_elem(OP_LINESEQ,
8973             op_append_elem(OP_LINESEQ,
8974                 newSTATEOP(0, NULL, newUNOP(OP_REQUIRE, 0, idop)),
8975                 newSTATEOP(0, NULL, veop)),
8976             newSTATEOP(0, NULL, imop) ));
8977
8978     if (use_version) {
8979         /* Enable the
8980          * feature bundle that corresponds to the required version. */
8981         use_version = sv_2mortal(new_version(use_version));
8982         S_enable_feature_bundle(aTHX_ use_version);
8983
8984         U16 shortver = S_extract_shortver(aTHX_ use_version);
8985
8986         /* If a version >= 5.11.0 is requested, strictures are on by default! */
8987         if (shortver >= SHORTVER(5, 11)) {
8988             if (!(PL_hints & HINT_EXPLICIT_STRICT_REFS))
8989                 PL_hints |= HINT_STRICT_REFS;
8990             if (!(PL_hints & HINT_EXPLICIT_STRICT_SUBS))
8991                 PL_hints |= HINT_STRICT_SUBS;
8992             if (!(PL_hints & HINT_EXPLICIT_STRICT_VARS))
8993                 PL_hints |= HINT_STRICT_VARS;
8994
8995             if (shortver >= SHORTVER(5, 35))
8996                 free_and_set_cop_warnings(&PL_compiling, pWARN_ALL);
8997         }
8998         /* otherwise they are off */
8999         else {
9000             if(PL_prevailing_version >= SHORTVER(5, 11))
9001                 deprecate_fatal_in("5.40",
9002                     "Downgrading a use VERSION declaration to below v5.11");
9003
9004             if (!(PL_hints & HINT_EXPLICIT_STRICT_REFS))
9005                 PL_hints &= ~HINT_STRICT_REFS;
9006             if (!(PL_hints & HINT_EXPLICIT_STRICT_SUBS))
9007                 PL_hints &= ~HINT_STRICT_SUBS;
9008             if (!(PL_hints & HINT_EXPLICIT_STRICT_VARS))
9009                 PL_hints &= ~HINT_STRICT_VARS;
9010         }
9011
9012         PL_prevailing_version = shortver;
9013     }
9014
9015     /* The "did you use incorrect case?" warning used to be here.
9016      * The problem is that on case-insensitive filesystems one
9017      * might get false positives for "use" (and "require"):
9018      * "use Strict" or "require CARP" will work.  This causes
9019      * portability problems for the script: in case-strict
9020      * filesystems the script will stop working.
9021      *
9022      * The "incorrect case" warning checked whether "use Foo"
9023      * imported "Foo" to your namespace, but that is wrong, too:
9024      * there is no requirement nor promise in the language that
9025      * a Foo.pm should or would contain anything in package "Foo".
9026      *
9027      * There is very little Configure-wise that can be done, either:
9028      * the case-sensitivity of the build filesystem of Perl does not
9029      * help in guessing the case-sensitivity of the runtime environment.
9030      */
9031
9032     PL_hints |= HINT_BLOCK_SCOPE;
9033     PL_parser->copline = NOLINE;
9034     COP_SEQMAX_INC; /* Purely for B::*'s benefit */
9035 }
9036
9037 /*
9038 =for apidoc_section $embedding
9039
9040 =for apidoc      load_module
9041 =for apidoc_item load_module_nocontext
9042
9043 These load the module whose name is pointed to by the string part of C<name>.
9044 Note that the actual module name, not its filename, should be given.
9045 Eg, "Foo::Bar" instead of "Foo/Bar.pm". ver, if specified and not NULL,
9046 provides version semantics similar to C<use Foo::Bar VERSION>. The optional
9047 trailing arguments can be used to specify arguments to the module's C<import()>
9048 method, similar to C<use Foo::Bar VERSION LIST>; their precise handling depends
9049 on the flags. The flags argument is a bitwise-ORed collection of any of
9050 C<PERL_LOADMOD_DENY>, C<PERL_LOADMOD_NOIMPORT>, or C<PERL_LOADMOD_IMPORT_OPS>
9051 (or 0 for no flags).
9052
9053 If C<PERL_LOADMOD_NOIMPORT> is set, the module is loaded as if with an empty
9054 import list, as in C<use Foo::Bar ()>; this is the only circumstance in which
9055 the trailing optional arguments may be omitted entirely. Otherwise, if
9056 C<PERL_LOADMOD_IMPORT_OPS> is set, the trailing arguments must consist of
9057 exactly one C<OP*>, containing the op tree that produces the relevant import
9058 arguments. Otherwise, the trailing arguments must all be C<SV*> values that
9059 will be used as import arguments; and the list must be terminated with C<(SV*)
9060 NULL>. If neither C<PERL_LOADMOD_NOIMPORT> nor C<PERL_LOADMOD_IMPORT_OPS> is
9061 set, the trailing C<NULL> pointer is needed even if no import arguments are
9062 desired. The reference count for each specified C<SV*> argument is
9063 decremented. In addition, the C<name> argument is modified.
9064
9065 If C<PERL_LOADMOD_DENY> is set, the module is loaded as if with C<no> rather
9066 than C<use>.
9067
9068 C<load_module> and C<load_module_nocontext> have the same apparent signature,
9069 but the former hides the fact that it is accessing a thread context parameter.
9070 So use the latter when you get a compilation error about C<pTHX>.
9071
9072 =for apidoc Amnh||PERL_LOADMOD_DENY
9073 =for apidoc Amnh||PERL_LOADMOD_NOIMPORT
9074 =for apidoc Amnh||PERL_LOADMOD_IMPORT_OPS
9075
9076 =for apidoc vload_module
9077 Like C<L</load_module>> but the arguments are an encapsulated argument list.
9078
9079 =cut */
9080
9081 void
9082 Perl_load_module(pTHX_ U32 flags, SV *name, SV *ver, ...)
9083 {
9084     va_list args;
9085
9086     PERL_ARGS_ASSERT_LOAD_MODULE;
9087
9088     va_start(args, ver);
9089     vload_module(flags, name, ver, &args);
9090     va_end(args);
9091 }
9092
9093 #ifdef MULTIPLICITY
9094 void
9095 Perl_load_module_nocontext(U32 flags, SV *name, SV *ver, ...)
9096 {
9097     dTHX;
9098     va_list args;
9099     PERL_ARGS_ASSERT_LOAD_MODULE_NOCONTEXT;
9100     va_start(args, ver);
9101     vload_module(flags, name, ver, &args);
9102     va_end(args);
9103 }
9104 #endif
9105
9106 void
9107 Perl_vload_module(pTHX_ U32 flags, SV *name, SV *ver, va_list *args)
9108 {
9109     OP *veop, *imop;
9110     OP * modname;
9111     I32 floor;
9112
9113     PERL_ARGS_ASSERT_VLOAD_MODULE;
9114
9115     /* utilize() fakes up a BEGIN { require ..; import ... }, so make sure
9116      * that it has a PL_parser to play with while doing that, and also
9117      * that it doesn't mess with any existing parser, by creating a tmp
9118      * new parser with lex_start(). This won't actually be used for much,
9119      * since pp_require() will create another parser for the real work.
9120      * The ENTER/LEAVE pair protect callers from any side effects of use.
9121      *
9122      * start_subparse() creates a new PL_compcv. This means that any ops
9123      * allocated below will be allocated from that CV's op slab, and so
9124      * will be automatically freed if the utilise() fails
9125      */
9126
9127     ENTER;
9128     SAVEVPTR(PL_curcop);
9129     lex_start(NULL, NULL, LEX_START_SAME_FILTER);
9130     floor = start_subparse(FALSE, 0);
9131
9132     modname = newSVOP(OP_CONST, 0, name);
9133     modname->op_private |= OPpCONST_BARE;
9134     if (ver) {
9135         veop = newSVOP(OP_CONST, 0, ver);
9136     }
9137     else
9138         veop = NULL;
9139     if (flags & PERL_LOADMOD_NOIMPORT) {
9140         imop = sawparens(newNULLLIST());
9141     }
9142     else if (flags & PERL_LOADMOD_IMPORT_OPS) {
9143         imop = va_arg(*args, OP*);
9144     }
9145     else {
9146         SV *sv;
9147         imop = NULL;
9148         sv = va_arg(*args, SV*);
9149         while (sv) {
9150             imop = op_append_elem(OP_LIST, imop, newSVOP(OP_CONST, 0, sv));
9151             sv = va_arg(*args, SV*);
9152         }
9153     }
9154
9155     utilize(!(flags & PERL_LOADMOD_DENY), floor, veop, modname, imop);
9156     LEAVE;
9157 }
9158
9159 PERL_STATIC_INLINE OP *
9160 S_new_entersubop(pTHX_ GV *gv, OP *arg)
9161 {
9162     return newUNOP(OP_ENTERSUB, OPf_STACKED,
9163                    newLISTOP(OP_LIST, 0, arg,
9164                              newUNOP(OP_RV2CV, 0,
9165                                      newGVOP(OP_GV, 0, gv))));
9166 }
9167
9168 OP *
9169 Perl_dofile(pTHX_ OP *term, I32 force_builtin)
9170 {
9171     OP *doop;
9172     GV *gv;
9173
9174     PERL_ARGS_ASSERT_DOFILE;
9175
9176     if (!force_builtin && (gv = gv_override("do", 2))) {
9177         doop = S_new_entersubop(aTHX_ gv, term);
9178     }
9179     else {
9180         doop = newUNOP(OP_DOFILE, 0, scalar(term));
9181     }
9182     return doop;
9183 }
9184
9185 /*
9186 =for apidoc_section $optree_construction
9187
9188 =for apidoc newSLICEOP
9189
9190 Constructs, checks, and returns an C<lslice> (list slice) op.  C<flags>
9191 gives the eight bits of C<op_flags>, except that C<OPf_KIDS> will
9192 be set automatically, and, shifted up eight bits, the eight bits of
9193 C<op_private>, except that the bit with value 1 or 2 is automatically
9194 set as required.  C<listval> and C<subscript> supply the parameters of
9195 the slice; they are consumed by this function and become part of the
9196 constructed op tree.
9197
9198 =cut
9199 */
9200
9201 OP *
9202 Perl_newSLICEOP(pTHX_ I32 flags, OP *subscript, OP *listval)
9203 {
9204     return newBINOP(OP_LSLICE, flags,
9205             list(force_list(subscript, TRUE)),
9206             list(force_list(listval,   TRUE)));
9207 }
9208
9209 #define ASSIGN_SCALAR 0
9210 #define ASSIGN_LIST   1
9211 #define ASSIGN_REF    2
9212
9213 /* given the optree o on the LHS of an assignment, determine whether its:
9214  *  ASSIGN_SCALAR   $x  = ...
9215  *  ASSIGN_LIST    ($x) = ...
9216  *  ASSIGN_REF     \$x  = ...
9217  */
9218
9219 STATIC I32
9220 S_assignment_type(pTHX_ const OP *o)
9221 {
9222     unsigned type;
9223     U8 flags;
9224     U8 ret;
9225
9226     if (!o)
9227         return ASSIGN_LIST;
9228
9229     if (o->op_type == OP_SREFGEN)
9230     {
9231         OP * const kid = cUNOPx(cUNOPo->op_first)->op_first;
9232         type = kid->op_type;
9233         flags = o->op_flags | kid->op_flags;
9234         if (!(flags & OPf_PARENS)
9235           && (kid->op_type == OP_RV2AV || kid->op_type == OP_PADAV ||
9236               kid->op_type == OP_RV2HV || kid->op_type == OP_PADHV ))
9237             return ASSIGN_REF;
9238         ret = ASSIGN_REF;
9239     } else {
9240         if ((o->op_type == OP_NULL) && (o->op_flags & OPf_KIDS))
9241             o = cUNOPo->op_first;
9242         flags = o->op_flags;
9243         type = o->op_type;
9244         ret = ASSIGN_SCALAR;
9245     }
9246
9247     if (type == OP_COND_EXPR) {
9248         OP * const sib = OpSIBLING(cLOGOPo->op_first);
9249         const I32 t = assignment_type(sib);
9250         const I32 f = assignment_type(OpSIBLING(sib));
9251
9252         if (t == ASSIGN_LIST && f == ASSIGN_LIST)
9253             return ASSIGN_LIST;
9254         if ((t == ASSIGN_LIST) ^ (f == ASSIGN_LIST))
9255             yyerror("Assignment to both a list and a scalar");
9256         return ASSIGN_SCALAR;
9257     }
9258
9259     if (type == OP_LIST &&
9260         (flags & OPf_WANT) == OPf_WANT_SCALAR &&
9261         o->op_private & OPpLVAL_INTRO)
9262         return ret;
9263
9264     if (type == OP_LIST || flags & OPf_PARENS ||
9265         type == OP_RV2AV || type == OP_RV2HV ||
9266         type == OP_ASLICE || type == OP_HSLICE ||
9267         type == OP_KVASLICE || type == OP_KVHSLICE || type == OP_REFGEN)
9268         return ASSIGN_LIST;
9269
9270     if (type == OP_PADAV || type == OP_PADHV)
9271         return ASSIGN_LIST;
9272
9273     if (type == OP_RV2SV)
9274         return ret;
9275
9276     return ret;
9277 }
9278
9279 static OP *
9280 S_newONCEOP(pTHX_ OP *initop, OP *padop)
9281 {
9282     const PADOFFSET target = padop->op_targ;
9283     OP *const other = newOP(OP_PADSV,
9284                             padop->op_flags
9285                             | ((padop->op_private & ~OPpLVAL_INTRO) << 8));
9286     OP *const first = newOP(OP_NULL, 0);
9287     OP *const nullop = newCONDOP(0, first, initop, other);
9288     /* XXX targlex disabled for now; see ticket #124160
9289         newCONDOP(0, first, S_maybe_targlex(aTHX_ initop), other);
9290      */
9291     OP *const condop = first->op_next;
9292
9293     OpTYPE_set(condop, OP_ONCE);
9294     other->op_targ = target;
9295     nullop->op_flags |= OPf_WANT_SCALAR;
9296
9297     /* Store the initializedness of state vars in a separate
9298        pad entry.  */
9299     condop->op_targ =
9300       pad_add_name_pvn("$",1,padadd_NO_DUP_CHECK|padadd_STATE,0,0);
9301     /* hijacking PADSTALE for uninitialized state variables */
9302     SvPADSTALE_on(PAD_SVl(condop->op_targ));
9303
9304     return nullop;
9305 }
9306
9307 /*
9308 =for apidoc newASSIGNOP
9309
9310 Constructs, checks, and returns an assignment op.  C<left> and C<right>
9311 supply the parameters of the assignment; they are consumed by this
9312 function and become part of the constructed op tree.
9313
9314 If C<optype> is C<OP_ANDASSIGN>, C<OP_ORASSIGN>, or C<OP_DORASSIGN>, then
9315 a suitable conditional optree is constructed.  If C<optype> is the opcode
9316 of a binary operator, such as C<OP_BIT_OR>, then an op is constructed that
9317 performs the binary operation and assigns the result to the left argument.
9318 Either way, if C<optype> is non-zero then C<flags> has no effect.
9319
9320 If C<optype> is zero, then a plain scalar or list assignment is
9321 constructed.  Which type of assignment it is is automatically determined.
9322 C<flags> gives the eight bits of C<op_flags>, except that C<OPf_KIDS>
9323 will be set automatically, and, shifted up eight bits, the eight bits
9324 of C<op_private>, except that the bit with value 1 or 2 is automatically
9325 set as required.
9326
9327 =cut
9328 */
9329
9330 OP *
9331 Perl_newASSIGNOP(pTHX_ I32 flags, OP *left, I32 optype, OP *right)
9332 {
9333     OP *o;
9334     I32 assign_type;
9335
9336     switch (optype) {
9337         case 0: break;
9338         case OP_ANDASSIGN:
9339         case OP_ORASSIGN:
9340         case OP_DORASSIGN:
9341             right = scalar(right);
9342             return newLOGOP(optype, 0,
9343                 op_lvalue(scalar(left), optype),
9344                 newBINOP(OP_SASSIGN, OPpASSIGN_BACKWARDS<<8, right, right));
9345         default:
9346             return newBINOP(optype, OPf_STACKED,
9347                 op_lvalue(scalar(left), optype), scalar(right));
9348     }
9349
9350     if ((assign_type = assignment_type(left)) == ASSIGN_LIST) {
9351         OP *state_var_op = NULL;
9352         static const char no_list_state[] = "Initialization of state variables"
9353             " in list currently forbidden";
9354         OP *curop;
9355
9356         if (left->op_type == OP_ASLICE || left->op_type == OP_HSLICE)
9357             left->op_private &= ~ OPpSLICEWARNING;
9358
9359         PL_modcount = 0;
9360         left = op_lvalue(left, OP_AASSIGN);
9361         curop = list(force_list(left, TRUE));
9362         o = newBINOP(OP_AASSIGN, flags, list(force_list(right, TRUE)), curop);
9363         o->op_private = (U8)(0 | (flags >> 8));
9364
9365         if (OP_TYPE_IS_OR_WAS(left, OP_LIST))
9366         {
9367             OP *lop = ((LISTOP*)left)->op_first, *vop, *eop;
9368             if (!(left->op_flags & OPf_PARENS) &&
9369                     lop->op_type == OP_PUSHMARK &&
9370                     (vop = OpSIBLING(lop)) &&
9371                     (vop->op_type == OP_PADAV || vop->op_type == OP_PADHV) &&
9372                     !(vop->op_flags & OPf_PARENS) &&
9373                     (vop->op_private & (OPpLVAL_INTRO|OPpPAD_STATE)) ==
9374                         (OPpLVAL_INTRO|OPpPAD_STATE) &&
9375                     (eop = OpSIBLING(vop)) &&
9376                     eop->op_type == OP_ENTERSUB &&
9377                     !OpHAS_SIBLING(eop)) {
9378                 state_var_op = vop;
9379             } else {
9380                 while (lop) {
9381                     if ((lop->op_type == OP_PADSV ||
9382                          lop->op_type == OP_PADAV ||
9383                          lop->op_type == OP_PADHV ||
9384                          lop->op_type == OP_PADANY)
9385                       && (lop->op_private & OPpPAD_STATE)
9386                     )
9387                         yyerror(no_list_state);
9388                     lop = OpSIBLING(lop);
9389                 }
9390             }
9391         }
9392         else if (  (left->op_private & OPpLVAL_INTRO)
9393                 && (left->op_private & OPpPAD_STATE)
9394                 && (   left->op_type == OP_PADSV
9395                     || left->op_type == OP_PADAV
9396                     || left->op_type == OP_PADHV
9397                     || left->op_type == OP_PADANY)
9398         ) {
9399                 /* All single variable list context state assignments, hence
9400                    state ($a) = ...
9401                    (state $a) = ...
9402                    state @a = ...
9403                    state (@a) = ...
9404                    (state @a) = ...
9405                    state %a = ...
9406                    state (%a) = ...
9407                    (state %a) = ...
9408                 */
9409                 if (left->op_flags & OPf_PARENS)
9410                     yyerror(no_list_state);
9411                 else
9412                     state_var_op = left;
9413         }
9414
9415         /* optimise @a = split(...) into:
9416         * @{expr}:              split(..., @{expr}) (where @a is not flattened)
9417         * @a, my @a, local @a:  split(...)          (where @a is attached to
9418         *                                            the split op itself)
9419         */
9420
9421         if (   right
9422             && right->op_type == OP_SPLIT
9423             /* don't do twice, e.g. @b = (@a = split) */
9424             && !(right->op_private & OPpSPLIT_ASSIGN))
9425         {
9426             OP *gvop = NULL;
9427
9428             if (   (  left->op_type == OP_RV2AV
9429                    && (gvop=((UNOP*)left)->op_first)->op_type==OP_GV)
9430                 || left->op_type == OP_PADAV)
9431             {
9432                 /* @pkg or @lex or local @pkg' or 'my @lex' */
9433                 OP *tmpop;
9434                 if (gvop) {
9435 #ifdef USE_ITHREADS
9436                     ((PMOP*)right)->op_pmreplrootu.op_pmtargetoff
9437                         = cPADOPx(gvop)->op_padix;
9438                     cPADOPx(gvop)->op_padix = 0;        /* steal it */
9439 #else
9440                     ((PMOP*)right)->op_pmreplrootu.op_pmtargetgv
9441                         = MUTABLE_GV(cSVOPx(gvop)->op_sv);
9442                     cSVOPx(gvop)->op_sv = NULL; /* steal it */
9443 #endif
9444                     right->op_private |=
9445                         left->op_private & OPpOUR_INTRO;
9446                 }
9447                 else {
9448                     ((PMOP*)right)->op_pmreplrootu.op_pmtargetoff = left->op_targ;
9449                     left->op_targ = 0;  /* steal it */
9450                     right->op_private |= OPpSPLIT_LEX;
9451                 }
9452                 right->op_private |= left->op_private & OPpLVAL_INTRO;
9453
9454               detach_split:
9455                 tmpop = cUNOPo->op_first;       /* to list (nulled) */
9456                 tmpop = ((UNOP*)tmpop)->op_first; /* to pushmark */
9457                 assert(OpSIBLING(tmpop) == right);
9458                 assert(!OpHAS_SIBLING(right));
9459                 /* detach the split subtreee from the o tree,
9460                  * then free the residual o tree */
9461                 op_sibling_splice(cUNOPo->op_first, tmpop, 1, NULL);
9462                 op_free(o);                     /* blow off assign */
9463                 right->op_private |= OPpSPLIT_ASSIGN;
9464                 right->op_flags &= ~OPf_WANT;
9465                         /* "I don't know and I don't care." */
9466                 return right;
9467             }
9468             else if (left->op_type == OP_RV2AV) {
9469                 /* @{expr} */
9470
9471                 OP *pushop = cUNOPx(cBINOPo->op_last)->op_first;
9472                 assert(OpSIBLING(pushop) == left);
9473                 /* Detach the array ...  */
9474                 op_sibling_splice(cBINOPo->op_last, pushop, 1, NULL);
9475                 /* ... and attach it to the split.  */
9476                 op_sibling_splice(right, cLISTOPx(right)->op_last,
9477                                   0, left);
9478                 right->op_flags |= OPf_STACKED;
9479                 /* Detach split and expunge aassign as above.  */
9480                 goto detach_split;
9481             }
9482             else if (PL_modcount < RETURN_UNLIMITED_NUMBER &&
9483                     ((LISTOP*)right)->op_last->op_type == OP_CONST)
9484             {
9485                 /* convert split(...,0) to split(..., PL_modcount+1) */
9486                 SV ** const svp =
9487                     &((SVOP*)((LISTOP*)right)->op_last)->op_sv;
9488                 SV * const sv = *svp;
9489                 if (SvIOK(sv) && SvIVX(sv) == 0)
9490                 {
9491                   if (right->op_private & OPpSPLIT_IMPLIM) {
9492                     /* our own SV, created in ck_split */
9493                     SvREADONLY_off(sv);
9494                     sv_setiv(sv, PL_modcount+1);
9495                   }
9496                   else {
9497                     /* SV may belong to someone else */
9498                     SvREFCNT_dec(sv);
9499                     *svp = newSViv(PL_modcount+1);
9500                   }
9501                 }
9502             }
9503         }
9504
9505         if (state_var_op)
9506             o = S_newONCEOP(aTHX_ o, state_var_op);
9507         return o;
9508     }
9509     if (assign_type == ASSIGN_REF)
9510         return newBINOP(OP_REFASSIGN, flags, scalar(right), left);
9511     if (!right)
9512         right = newOP(OP_UNDEF, 0);
9513     if (right->op_type == OP_READLINE) {
9514         right->op_flags |= OPf_STACKED;
9515         return newBINOP(OP_NULL, flags, op_lvalue(scalar(left), OP_SASSIGN),
9516                 scalar(right));
9517     }
9518     else {
9519         o = newBINOP(OP_SASSIGN, flags,
9520             scalar(right), op_lvalue(scalar(left), OP_SASSIGN) );
9521     }
9522     return o;
9523 }
9524
9525 /*
9526 =for apidoc newSTATEOP
9527
9528 Constructs a state op (COP).  The state op is normally a C<nextstate> op,
9529 but will be a C<dbstate> op if debugging is enabled for currently-compiled
9530 code.  The state op is populated from C<PL_curcop> (or C<PL_compiling>).
9531 If C<label> is non-null, it supplies the name of a label to attach to
9532 the state op; this function takes ownership of the memory pointed at by
9533 C<label>, and will free it.  C<flags> gives the eight bits of C<op_flags>
9534 for the state op.
9535
9536 If C<o> is null, the state op is returned.  Otherwise the state op is
9537 combined with C<o> into a C<lineseq> list op, which is returned.  C<o>
9538 is consumed by this function and becomes part of the returned op tree.
9539
9540 =cut
9541 */
9542
9543 OP *
9544 Perl_newSTATEOP(pTHX_ I32 flags, char *label, OP *o)
9545 {
9546     const U32 seq = intro_my();
9547     const U32 utf8 = flags & SVf_UTF8;
9548     COP *cop;
9549
9550     assert(PL_parser);
9551     PL_parser->parsed_sub = 0;
9552
9553     flags &= ~SVf_UTF8;
9554
9555     NewOp(1101, cop, 1, COP);
9556     if (PERLDB_LINE && CopLINE(PL_curcop) && PL_curstash != PL_debstash) {
9557         OpTYPE_set(cop, OP_DBSTATE);
9558     }
9559     else {
9560         OpTYPE_set(cop, OP_NEXTSTATE);
9561     }
9562     cop->op_flags = (U8)flags;
9563     CopHINTS_set(cop, PL_hints);
9564 #ifdef VMS
9565     if (VMSISH_HUSHED) cop->op_private |= OPpHUSH_VMSISH;
9566 #endif
9567     cop->op_next = (OP*)cop;
9568
9569     cop->cop_seq = seq;
9570     cop->cop_warnings = DUP_WARNINGS(PL_curcop->cop_warnings);
9571     CopHINTHASH_set(cop, cophh_copy(CopHINTHASH_get(PL_curcop)));
9572     if (label) {
9573         Perl_cop_store_label(aTHX_ cop, label, strlen(label), utf8);
9574
9575         PL_hints |= HINT_BLOCK_SCOPE;
9576         /* It seems that we need to defer freeing this pointer, as other parts
9577            of the grammar end up wanting to copy it after this op has been
9578            created. */
9579         SAVEFREEPV(label);
9580     }
9581
9582     if (PL_parser->preambling != NOLINE) {
9583         CopLINE_set(cop, PL_parser->preambling);
9584         PL_parser->copline = NOLINE;
9585     }
9586     else if (PL_parser->copline == NOLINE)
9587         CopLINE_set(cop, CopLINE(PL_curcop));
9588     else {
9589         CopLINE_set(cop, PL_parser->copline);
9590         PL_parser->copline = NOLINE;
9591     }
9592 #ifdef USE_ITHREADS
9593     CopFILE_set(cop, CopFILE(PL_curcop));       /* XXX share in a pvtable? */
9594 #else
9595     CopFILEGV_set(cop, CopFILEGV(PL_curcop));
9596 #endif
9597     CopSTASH_set(cop, PL_curstash);
9598
9599     if (cop->op_type == OP_DBSTATE) {
9600         /* this line can have a breakpoint - store the cop in IV */
9601         AV *av = CopFILEAVx(PL_curcop);
9602         if (av) {
9603             SV * const * const svp = av_fetch(av, CopLINE(cop), FALSE);
9604             if (svp && *svp != &PL_sv_undef ) {
9605                 (void)SvIOK_on(*svp);
9606                 SvIV_set(*svp, PTR2IV(cop));
9607             }
9608         }
9609     }
9610
9611     if (flags & OPf_SPECIAL)
9612         op_null((OP*)cop);
9613     return op_prepend_elem(OP_LINESEQ, (OP*)cop, o);
9614 }
9615
9616 /*
9617 =for apidoc newLOGOP
9618
9619 Constructs, checks, and returns a logical (flow control) op.  C<type>
9620 is the opcode.  C<flags> gives the eight bits of C<op_flags>, except
9621 that C<OPf_KIDS> will be set automatically, and, shifted up eight bits,
9622 the eight bits of C<op_private>, except that the bit with value 1 is
9623 automatically set.  C<first> supplies the expression controlling the
9624 flow, and C<other> supplies the side (alternate) chain of ops; they are
9625 consumed by this function and become part of the constructed op tree.
9626
9627 =cut
9628 */
9629
9630 OP *
9631 Perl_newLOGOP(pTHX_ I32 type, I32 flags, OP *first, OP *other)
9632 {
9633     PERL_ARGS_ASSERT_NEWLOGOP;
9634
9635     return new_logop(type, flags, &first, &other);
9636 }
9637
9638
9639 /* See if the optree o contains a single OP_CONST (plus possibly
9640  * surrounding enter/nextstate/null etc). If so, return it, else return
9641  * NULL.
9642  */
9643
9644 STATIC OP *
9645 S_search_const(pTHX_ OP *o)
9646 {
9647     PERL_ARGS_ASSERT_SEARCH_CONST;
9648
9649   redo:
9650     switch (o->op_type) {
9651         case OP_CONST:
9652             return o;
9653         case OP_NULL:
9654             if (o->op_flags & OPf_KIDS) {
9655                 o = cUNOPo->op_first;
9656                 goto redo;
9657             }
9658             break;
9659         case OP_LEAVE:
9660         case OP_SCOPE:
9661         case OP_LINESEQ:
9662         {
9663             OP *kid;
9664             if (!(o->op_flags & OPf_KIDS))
9665                 return NULL;
9666             kid = cLISTOPo->op_first;
9667
9668             do {
9669                 switch (kid->op_type) {
9670                     case OP_ENTER:
9671                     case OP_NULL:
9672                     case OP_NEXTSTATE:
9673                         kid = OpSIBLING(kid);
9674                         break;
9675                     default:
9676                         if (kid != cLISTOPo->op_last)
9677                             return NULL;
9678                         goto last;
9679                 }
9680             } while (kid);
9681
9682             if (!kid)
9683                 kid = cLISTOPo->op_last;
9684           last:
9685              o = kid;
9686              goto redo;
9687         }
9688     }
9689
9690     return NULL;
9691 }
9692
9693
9694 STATIC OP *
9695 S_new_logop(pTHX_ I32 type, I32 flags, OP** firstp, OP** otherp)
9696 {
9697     LOGOP *logop;
9698     OP *o;
9699     OP *first;
9700     OP *other;
9701     OP *cstop = NULL;
9702     int prepend_not = 0;
9703
9704     PERL_ARGS_ASSERT_NEW_LOGOP;
9705
9706     first = *firstp;
9707     other = *otherp;
9708
9709     /* [perl #59802]: Warn about things like "return $a or $b", which
9710        is parsed as "(return $a) or $b" rather than "return ($a or
9711        $b)".  NB: This also applies to xor, which is why we do it
9712        here.
9713      */
9714     switch (first->op_type) {
9715     case OP_NEXT:
9716     case OP_LAST:
9717     case OP_REDO:
9718         /* XXX: Perhaps we should emit a stronger warning for these.
9719            Even with the high-precedence operator they don't seem to do
9720            anything sensible.
9721
9722            But until we do, fall through here.
9723          */
9724     case OP_RETURN:
9725     case OP_EXIT:
9726     case OP_DIE:
9727     case OP_GOTO:
9728         /* XXX: Currently we allow people to "shoot themselves in the
9729            foot" by explicitly writing "(return $a) or $b".
9730
9731            Warn unless we are looking at the result from folding or if
9732            the programmer explicitly grouped the operators like this.
9733            The former can occur with e.g.
9734
9735                 use constant FEATURE => ( $] >= ... );
9736                 sub { not FEATURE and return or do_stuff(); }
9737          */
9738         if (!first->op_folded && !(first->op_flags & OPf_PARENS))
9739             Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX),
9740                            "Possible precedence issue with control flow operator");
9741         /* XXX: Should we optimze this to "return $a;" (i.e. remove
9742            the "or $b" part)?
9743         */
9744         break;
9745     }
9746
9747     if (type == OP_XOR)         /* Not short circuit, but here by precedence. */
9748         return newBINOP(type, flags, scalar(first), scalar(other));
9749
9750     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_LOGOP
9751         || type == OP_CUSTOM);
9752
9753     scalarboolean(first);
9754
9755     /* search for a constant op that could let us fold the test */
9756     if ((cstop = search_const(first))) {
9757         if (cstop->op_private & OPpCONST_STRICT)
9758             no_bareword_allowed(cstop);
9759         else if ((cstop->op_private & OPpCONST_BARE))
9760                 Perl_ck_warner(aTHX_ packWARN(WARN_BAREWORD), "Bareword found in conditional");
9761         if ((type == OP_AND &&  SvTRUE(((SVOP*)cstop)->op_sv)) ||
9762             (type == OP_OR  && !SvTRUE(((SVOP*)cstop)->op_sv)) ||
9763             (type == OP_DOR && !SvOK(((SVOP*)cstop)->op_sv))) {
9764             /* Elide the (constant) lhs, since it can't affect the outcome */
9765             *firstp = NULL;
9766             if (other->op_type == OP_CONST)
9767                 other->op_private |= OPpCONST_SHORTCIRCUIT;
9768             op_free(first);
9769             if (other->op_type == OP_LEAVE)
9770                 other = newUNOP(OP_NULL, OPf_SPECIAL, other);
9771             else if (other->op_type == OP_MATCH
9772                   || other->op_type == OP_SUBST
9773                   || other->op_type == OP_TRANSR
9774                   || other->op_type == OP_TRANS)
9775                 /* Mark the op as being unbindable with =~ */
9776                 other->op_flags |= OPf_SPECIAL;
9777
9778             other->op_folded = 1;
9779             return other;
9780         }
9781         else {
9782             /* Elide the rhs, since the outcome is entirely determined by
9783              * the (constant) lhs */
9784
9785             /* check for C<my $x if 0>, or C<my($x,$y) if 0> */
9786             const OP *o2 = other;
9787             if ( ! (o2->op_type == OP_LIST
9788                     && (( o2 = cUNOPx(o2)->op_first))
9789                     && o2->op_type == OP_PUSHMARK
9790                     && (( o2 = OpSIBLING(o2))) )
9791             )
9792                 o2 = other;
9793             if ((o2->op_type == OP_PADSV || o2->op_type == OP_PADAV
9794                         || o2->op_type == OP_PADHV)
9795                 && o2->op_private & OPpLVAL_INTRO
9796                 && !(o2->op_private & OPpPAD_STATE))
9797             {
9798         Perl_croak(aTHX_ "This use of my() in false conditional is "
9799                           "no longer allowed");
9800             }
9801
9802             *otherp = NULL;
9803             if (cstop->op_type == OP_CONST)
9804                 cstop->op_private |= OPpCONST_SHORTCIRCUIT;
9805             op_free(other);
9806             return first;
9807         }
9808     }
9809     else if ((first->op_flags & OPf_KIDS) && type != OP_DOR
9810         && ckWARN(WARN_MISC)) /* [#24076] Don't warn for <FH> err FOO. */
9811     {
9812         const OP * const k1 = ((UNOP*)first)->op_first;
9813         const OP * const k2 = OpSIBLING(k1);
9814         OPCODE warnop = 0;
9815         switch (first->op_type)
9816         {
9817         case OP_NULL:
9818             if (k2 && k2->op_type == OP_READLINE
9819                   && (k2->op_flags & OPf_STACKED)
9820                   && ((k1->op_flags & OPf_WANT) == OPf_WANT_SCALAR))
9821             {
9822                 warnop = k2->op_type;
9823             }
9824             break;
9825
9826         case OP_SASSIGN:
9827             if (k1->op_type == OP_READDIR
9828                   || k1->op_type == OP_GLOB
9829                   || (k1->op_type == OP_NULL && k1->op_targ == OP_GLOB)
9830                  || k1->op_type == OP_EACH
9831                  || k1->op_type == OP_AEACH)
9832             {
9833                 warnop = ((k1->op_type == OP_NULL)
9834                           ? (OPCODE)k1->op_targ : k1->op_type);
9835             }
9836             break;
9837         }
9838         if (warnop) {
9839             const line_t oldline = CopLINE(PL_curcop);
9840             /* This ensures that warnings are reported at the first line
9841                of the construction, not the last.  */
9842             CopLINE_set(PL_curcop, PL_parser->copline);
9843             Perl_warner(aTHX_ packWARN(WARN_MISC),
9844                  "Value of %s%s can be \"0\"; test with defined()",
9845                  PL_op_desc[warnop],
9846                  ((warnop == OP_READLINE || warnop == OP_GLOB)
9847                   ? " construct" : "() operator"));
9848             CopLINE_set(PL_curcop, oldline);
9849         }
9850     }
9851
9852     /* optimize AND and OR ops that have NOTs as children */
9853     if (first->op_type == OP_NOT
9854         && (first->op_flags & OPf_KIDS)
9855         && ((first->op_flags & OPf_SPECIAL) /* unless ($x) { } */
9856             || (other->op_type == OP_NOT))  /* if (!$x && !$y) { } */
9857         ) {
9858         if (type == OP_AND || type == OP_OR) {
9859             if (type == OP_AND)
9860                 type = OP_OR;
9861             else
9862                 type = OP_AND;
9863             op_null(first);
9864             if (other->op_type == OP_NOT) { /* !a AND|OR !b => !(a OR|AND b) */
9865                 op_null(other);
9866                 prepend_not = 1; /* prepend a NOT op later */
9867             }
9868         }
9869     }
9870
9871     logop = alloc_LOGOP(type, first, LINKLIST(other));
9872     logop->op_flags |= (U8)flags;
9873     logop->op_private = (U8)(1 | (flags >> 8));
9874
9875     /* establish postfix order */
9876     logop->op_next = LINKLIST(first);
9877     first->op_next = (OP*)logop;
9878     assert(!OpHAS_SIBLING(first));
9879     op_sibling_splice((OP*)logop, first, 0, other);
9880
9881     CHECKOP(type,logop);
9882
9883     o = newUNOP(prepend_not ? OP_NOT : OP_NULL,
9884                 PL_opargs[type] & OA_RETSCALAR ? OPf_WANT_SCALAR : 0,
9885                 (OP*)logop);
9886     other->op_next = o;
9887
9888     return o;
9889 }
9890
9891 /*
9892 =for apidoc newCONDOP
9893
9894 Constructs, checks, and returns a conditional-expression (C<cond_expr>)
9895 op.  C<flags> gives the eight bits of C<op_flags>, except that C<OPf_KIDS>
9896 will be set automatically, and, shifted up eight bits, the eight bits of
9897 C<op_private>, except that the bit with value 1 is automatically set.
9898 C<first> supplies the expression selecting between the two branches,
9899 and C<trueop> and C<falseop> supply the branches; they are consumed by
9900 this function and become part of the constructed op tree.
9901
9902 =cut
9903 */
9904
9905 OP *
9906 Perl_newCONDOP(pTHX_ I32 flags, OP *first, OP *trueop, OP *falseop)
9907 {
9908     LOGOP *logop;
9909     OP *start;
9910     OP *o;
9911     OP *cstop;
9912
9913     PERL_ARGS_ASSERT_NEWCONDOP;
9914
9915     if (!falseop)
9916         return newLOGOP(OP_AND, 0, first, trueop);
9917     if (!trueop)
9918         return newLOGOP(OP_OR, 0, first, falseop);
9919
9920     scalarboolean(first);
9921     if ((cstop = search_const(first))) {
9922         /* Left or right arm of the conditional?  */
9923         const bool left = SvTRUE(((SVOP*)cstop)->op_sv);
9924         OP *live = left ? trueop : falseop;
9925         OP *const dead = left ? falseop : trueop;
9926         if (cstop->op_private & OPpCONST_BARE &&
9927             cstop->op_private & OPpCONST_STRICT) {
9928             no_bareword_allowed(cstop);
9929         }
9930         op_free(first);
9931         op_free(dead);
9932         if (live->op_type == OP_LEAVE)
9933             live = newUNOP(OP_NULL, OPf_SPECIAL, live);
9934         else if (live->op_type == OP_MATCH || live->op_type == OP_SUBST
9935               || live->op_type == OP_TRANS || live->op_type == OP_TRANSR)
9936             /* Mark the op as being unbindable with =~ */
9937             live->op_flags |= OPf_SPECIAL;
9938         live->op_folded = 1;
9939         return live;
9940     }
9941     logop = alloc_LOGOP(OP_COND_EXPR, first, LINKLIST(trueop));
9942     logop->op_flags |= (U8)flags;
9943     logop->op_private = (U8)(1 | (flags >> 8));
9944     logop->op_next = LINKLIST(falseop);
9945
9946     CHECKOP(OP_COND_EXPR, /* that's logop->op_type */
9947             logop);
9948
9949     /* establish postfix order */
9950     start = LINKLIST(first);
9951     first->op_next = (OP*)logop;
9952
9953     /* make first, trueop, falseop siblings */
9954     op_sibling_splice((OP*)logop, first,  0, trueop);
9955     op_sibling_splice((OP*)logop, trueop, 0, falseop);
9956
9957     o = newUNOP(OP_NULL, 0, (OP*)logop);
9958
9959     trueop->op_next = falseop->op_next = o;
9960
9961     o->op_next = start;
9962     return o;
9963 }
9964
9965 /*
9966 =for apidoc newTRYCATCHOP
9967
9968 Constructs and returns a conditional execution statement that implements
9969 the C<try>/C<catch> semantics.  First the op tree in C<tryblock> is executed,
9970 inside a context that traps exceptions.  If an exception occurs then the
9971 optree in C<catchblock> is executed, with the trapped exception set into the
9972 lexical variable given by C<catchvar> (which must be an op of type
9973 C<OP_PADSV>).  All the optrees are consumed by this function and become part
9974 of the returned op tree.
9975
9976 The C<flags> argument is currently ignored.
9977
9978 =cut
9979  */
9980
9981 OP *
9982 Perl_newTRYCATCHOP(pTHX_ I32 flags, OP *tryblock, OP *catchvar, OP *catchblock)
9983 {
9984     OP *o, *catchop;
9985
9986     PERL_ARGS_ASSERT_NEWTRYCATCHOP;
9987     assert(catchvar->op_type == OP_PADSV);
9988
9989     PERL_UNUSED_ARG(flags);
9990
9991     /* The returned optree is shaped as:
9992      *   LISTOP leavetrycatch
9993      *       LOGOP entertrycatch
9994      *       LISTOP poptry
9995      *           $tryblock here
9996      *       LOGOP catch
9997      *           $catchblock here
9998      */
9999
10000     if(tryblock->op_type != OP_LINESEQ)
10001         tryblock = op_convert_list(OP_LINESEQ, 0, tryblock);
10002     OpTYPE_set(tryblock, OP_POPTRY);
10003
10004     /* Manually construct a naked LOGOP.
10005      * Normally if we call newLOGOP the returned value is a UNOP(OP_NULL)
10006      * containing the LOGOP we wanted as its op_first */
10007     catchop = (OP *)alloc_LOGOP(OP_CATCH, newOP(OP_NULL, 0), catchblock);
10008     OpMORESIB_set(cUNOPx(catchop)->op_first, catchblock);
10009     OpLASTSIB_set(catchblock, catchop);
10010
10011     /* Inject the catchvar's pad offset into the OP_CATCH targ */
10012     cLOGOPx(catchop)->op_targ = catchvar->op_targ;
10013     op_free(catchvar);
10014
10015     /* Build the optree structure */
10016     o = newLISTOP(OP_LIST, 0, tryblock, catchop);
10017     o = op_convert_list(OP_ENTERTRYCATCH, 0, o);
10018
10019     return o;
10020 }
10021
10022 /*
10023 =for apidoc newRANGE
10024
10025 Constructs and returns a C<range> op, with subordinate C<flip> and
10026 C<flop> ops.  C<flags> gives the eight bits of C<op_flags> for the
10027 C<flip> op and, shifted up eight bits, the eight bits of C<op_private>
10028 for both the C<flip> and C<range> ops, except that the bit with value
10029 1 is automatically set.  C<left> and C<right> supply the expressions
10030 controlling the endpoints of the range; they are consumed by this function
10031 and become part of the constructed op tree.
10032
10033 =cut
10034 */
10035
10036 OP *
10037 Perl_newRANGE(pTHX_ I32 flags, OP *left, OP *right)
10038 {
10039     LOGOP *range;
10040     OP *flip;
10041     OP *flop;
10042     OP *leftstart;
10043     OP *o;
10044
10045     PERL_ARGS_ASSERT_NEWRANGE;
10046
10047     range = alloc_LOGOP(OP_RANGE, left, LINKLIST(right));
10048     range->op_flags = OPf_KIDS;
10049     leftstart = LINKLIST(left);
10050     range->op_private = (U8)(1 | (flags >> 8));
10051
10052     /* make left and right siblings */
10053     op_sibling_splice((OP*)range, left, 0, right);
10054
10055     range->op_next = (OP*)range;
10056     flip = newUNOP(OP_FLIP, flags, (OP*)range);
10057     flop = newUNOP(OP_FLOP, 0, flip);
10058     o = newUNOP(OP_NULL, 0, flop);
10059     LINKLIST(flop);
10060     range->op_next = leftstart;
10061
10062     left->op_next = flip;
10063     right->op_next = flop;
10064
10065     range->op_targ =
10066         pad_add_name_pvn("$", 1, padadd_NO_DUP_CHECK|padadd_STATE, 0, 0);
10067     sv_upgrade(PAD_SV(range->op_targ), SVt_PVNV);
10068     flip->op_targ =
10069         pad_add_name_pvn("$", 1, padadd_NO_DUP_CHECK|padadd_STATE, 0, 0);;
10070     sv_upgrade(PAD_SV(flip->op_targ), SVt_PVNV);
10071     SvPADTMP_on(PAD_SV(flip->op_targ));
10072
10073     flip->op_private =  left->op_type == OP_CONST ? OPpFLIP_LINENUM : 0;
10074     flop->op_private = right->op_type == OP_CONST ? OPpFLIP_LINENUM : 0;
10075
10076     /* check barewords before they might be optimized aways */
10077     if (flip->op_private && cSVOPx(left)->op_private & OPpCONST_STRICT)
10078         no_bareword_allowed(left);
10079     if (flop->op_private && cSVOPx(right)->op_private & OPpCONST_STRICT)
10080         no_bareword_allowed(right);
10081
10082     flip->op_next = o;
10083     if (!flip->op_private || !flop->op_private)
10084         LINKLIST(o);            /* blow off optimizer unless constant */
10085
10086     return o;
10087 }
10088
10089 /*
10090 =for apidoc newLOOPOP
10091
10092 Constructs, checks, and returns an op tree expressing a loop.  This is
10093 only a loop in the control flow through the op tree; it does not have
10094 the heavyweight loop structure that allows exiting the loop by C<last>
10095 and suchlike.  C<flags> gives the eight bits of C<op_flags> for the
10096 top-level op, except that some bits will be set automatically as required.
10097 C<expr> supplies the expression controlling loop iteration, and C<block>
10098 supplies the body of the loop; they are consumed by this function and
10099 become part of the constructed op tree.  C<debuggable> is currently
10100 unused and should always be 1.
10101
10102 =cut
10103 */
10104
10105 OP *
10106 Perl_newLOOPOP(pTHX_ I32 flags, I32 debuggable, OP *expr, OP *block)
10107 {
10108     OP* listop;
10109     OP* o;
10110     const bool once = block && block->op_flags & OPf_SPECIAL &&
10111                       block->op_type == OP_NULL;
10112
10113     PERL_UNUSED_ARG(debuggable);
10114
10115     if (expr) {
10116         if (once && (
10117               (expr->op_type == OP_CONST && !SvTRUE(((SVOP*)expr)->op_sv))
10118            || (  expr->op_type == OP_NOT
10119               && cUNOPx(expr)->op_first->op_type == OP_CONST
10120               && SvTRUE(cSVOPx_sv(cUNOPx(expr)->op_first))
10121               )
10122            ))
10123             /* Return the block now, so that S_new_logop does not try to
10124                fold it away. */
10125         {
10126             op_free(expr);
10127             return block;       /* do {} while 0 does once */
10128         }
10129
10130         if (expr->op_type == OP_READLINE
10131             || expr->op_type == OP_READDIR
10132             || expr->op_type == OP_GLOB
10133             || expr->op_type == OP_EACH || expr->op_type == OP_AEACH
10134             || (expr->op_type == OP_NULL && expr->op_targ == OP_GLOB)) {
10135             expr = newUNOP(OP_DEFINED, 0,
10136                 newASSIGNOP(0, newDEFSVOP(), 0, expr) );
10137         } else if (expr->op_flags & OPf_KIDS) {
10138             const OP * const k1 = ((UNOP*)expr)->op_first;
10139             const OP * const k2 = k1 ? OpSIBLING(k1) : NULL;
10140             switch (expr->op_type) {
10141               case OP_NULL:
10142                 if (k2 && (k2->op_type == OP_READLINE || k2->op_type == OP_READDIR)
10143                       && (k2->op_flags & OPf_STACKED)
10144                       && ((k1->op_flags & OPf_WANT) == OPf_WANT_SCALAR))
10145                     expr = newUNOP(OP_DEFINED, 0, expr);
10146                 break;
10147
10148               case OP_SASSIGN:
10149                 if (k1 && (k1->op_type == OP_READDIR
10150                       || k1->op_type == OP_GLOB
10151                       || (k1->op_type == OP_NULL && k1->op_targ == OP_GLOB)
10152                      || k1->op_type == OP_EACH
10153                      || k1->op_type == OP_AEACH))
10154                     expr = newUNOP(OP_DEFINED, 0, expr);
10155                 break;
10156             }
10157         }
10158     }
10159
10160     /* if block is null, the next op_append_elem() would put UNSTACK, a scalar
10161      * op, in listop. This is wrong. [perl #27024] */
10162     if (!block)
10163         block = newOP(OP_NULL, 0);
10164     listop = op_append_elem(OP_LINESEQ, block, newOP(OP_UNSTACK, 0));
10165     o = new_logop(OP_AND, 0, &expr, &listop);
10166
10167     if (once) {
10168         ASSUME(listop);
10169     }
10170
10171     if (listop)
10172         ((LISTOP*)listop)->op_last->op_next = LINKLIST(o);
10173
10174     if (once && o != listop)
10175     {
10176         assert(cUNOPo->op_first->op_type == OP_AND
10177             || cUNOPo->op_first->op_type == OP_OR);
10178         o->op_next = ((LOGOP*)cUNOPo->op_first)->op_other;
10179     }
10180
10181     if (o == listop)
10182         o = newUNOP(OP_NULL, 0, o);     /* or do {} while 1 loses outer block */
10183
10184     o->op_flags |= flags;
10185     o = op_scope(o);
10186     o->op_flags |= OPf_SPECIAL; /* suppress cx_popblock() curpm restoration*/
10187     return o;
10188 }
10189
10190 /*
10191 =for apidoc newWHILEOP
10192
10193 Constructs, checks, and returns an op tree expressing a C<while> loop.
10194 This is a heavyweight loop, with structure that allows exiting the loop
10195 by C<last> and suchlike.
10196
10197 C<loop> is an optional preconstructed C<enterloop> op to use in the
10198 loop; if it is null then a suitable op will be constructed automatically.
10199 C<expr> supplies the loop's controlling expression.  C<block> supplies the
10200 main body of the loop, and C<cont> optionally supplies a C<continue> block
10201 that operates as a second half of the body.  All of these optree inputs
10202 are consumed by this function and become part of the constructed op tree.
10203
10204 C<flags> gives the eight bits of C<op_flags> for the C<leaveloop>
10205 op and, shifted up eight bits, the eight bits of C<op_private> for
10206 the C<leaveloop> op, except that (in both cases) some bits will be set
10207 automatically.  C<debuggable> is currently unused and should always be 1.
10208 C<has_my> can be supplied as true to force the
10209 loop body to be enclosed in its own scope.
10210
10211 =cut
10212 */
10213
10214 OP *
10215 Perl_newWHILEOP(pTHX_ I32 flags, I32 debuggable, LOOP *loop,
10216         OP *expr, OP *block, OP *cont, I32 has_my)
10217 {
10218     OP *redo;
10219     OP *next = NULL;
10220     OP *listop;
10221     OP *o;
10222     U8 loopflags = 0;
10223
10224     PERL_UNUSED_ARG(debuggable);
10225
10226     if (expr) {
10227         if (expr->op_type == OP_READLINE
10228          || expr->op_type == OP_READDIR
10229          || expr->op_type == OP_GLOB
10230          || expr->op_type == OP_EACH || expr->op_type == OP_AEACH
10231                      || (expr->op_type == OP_NULL && expr->op_targ == OP_GLOB)) {
10232             expr = newUNOP(OP_DEFINED, 0,
10233                 newASSIGNOP(0, newDEFSVOP(), 0, expr) );
10234         } else if (expr->op_flags & OPf_KIDS) {
10235             const OP * const k1 = ((UNOP*)expr)->op_first;
10236             const OP * const k2 = (k1) ? OpSIBLING(k1) : NULL;
10237             switch (expr->op_type) {
10238               case OP_NULL:
10239                 if (k2 && (k2->op_type == OP_READLINE || k2->op_type == OP_READDIR)
10240                       && (k2->op_flags & OPf_STACKED)
10241                       && ((k1->op_flags & OPf_WANT) == OPf_WANT_SCALAR))
10242                     expr = newUNOP(OP_DEFINED, 0, expr);
10243                 break;
10244
10245               case OP_SASSIGN:
10246                 if (k1 && (k1->op_type == OP_READDIR
10247                       || k1->op_type == OP_GLOB
10248                       || (k1->op_type == OP_NULL && k1->op_targ == OP_GLOB)
10249                      || k1->op_type == OP_EACH
10250                      || k1->op_type == OP_AEACH))
10251                     expr = newUNOP(OP_DEFINED, 0, expr);
10252                 break;
10253             }
10254         }
10255     }
10256
10257     if (!block)
10258         block = newOP(OP_NULL, 0);
10259     else if (cont || has_my) {
10260         block = op_scope(block);
10261     }
10262
10263     if (cont) {
10264         next = LINKLIST(cont);
10265     }
10266     if (expr) {
10267         OP * const unstack = newOP(OP_UNSTACK, 0);
10268         if (!next)
10269             next = unstack;
10270         cont = op_append_elem(OP_LINESEQ, cont, unstack);
10271     }
10272
10273     assert(block);
10274     listop = op_append_list(OP_LINESEQ, block, cont);
10275     assert(listop);
10276     redo = LINKLIST(listop);
10277
10278     if (expr) {
10279         scalar(listop);
10280         o = new_logop(OP_AND, 0, &expr, &listop);
10281         if (o == expr && o->op_type == OP_CONST && !SvTRUE(cSVOPo->op_sv)) {
10282             op_free((OP*)loop);
10283             return expr;                /* listop already freed by new_logop */
10284         }
10285         if (listop)
10286             ((LISTOP*)listop)->op_last->op_next =
10287                 (o == listop ? redo : LINKLIST(o));
10288     }
10289     else
10290         o = listop;
10291
10292     if (!loop) {
10293         NewOp(1101,loop,1,LOOP);
10294         OpTYPE_set(loop, OP_ENTERLOOP);
10295         loop->op_private = 0;
10296         loop->op_next = (OP*)loop;
10297     }
10298
10299     o = newBINOP(OP_LEAVELOOP, 0, (OP*)loop, o);
10300
10301     loop->op_redoop = redo;
10302     loop->op_lastop = o;
10303     o->op_private |= loopflags;
10304
10305     if (next)
10306         loop->op_nextop = next;
10307     else
10308         loop->op_nextop = o;
10309
10310     o->op_flags |= flags;
10311     o->op_private |= (flags >> 8);
10312     return o;
10313 }
10314
10315 /*
10316 =for apidoc newFOROP
10317
10318 Constructs, checks, and returns an op tree expressing a C<foreach>
10319 loop (iteration through a list of values).  This is a heavyweight loop,
10320 with structure that allows exiting the loop by C<last> and suchlike.
10321
10322 C<sv> optionally supplies the variable(s) that will be aliased to each
10323 item in turn; if null, it defaults to C<$_>.
10324 C<expr> supplies the list of values to iterate over.  C<block> supplies
10325 the main body of the loop, and C<cont> optionally supplies a C<continue>
10326 block that operates as a second half of the body.  All of these optree
10327 inputs are consumed by this function and become part of the constructed
10328 op tree.
10329
10330 C<flags> gives the eight bits of C<op_flags> for the C<leaveloop>
10331 op and, shifted up eight bits, the eight bits of C<op_private> for
10332 the C<leaveloop> op, except that (in both cases) some bits will be set
10333 automatically.
10334
10335 =cut
10336 */
10337
10338 OP *
10339 Perl_newFOROP(pTHX_ I32 flags, OP *sv, OP *expr, OP *block, OP *cont)
10340 {
10341     LOOP *loop;
10342     OP *iter;
10343     PADOFFSET padoff = 0;
10344     PADOFFSET how_many_more = 0;
10345     I32 iterflags = 0;
10346     I32 iterpflags = 0;
10347     bool parens = 0;
10348
10349     PERL_ARGS_ASSERT_NEWFOROP;
10350
10351     if (sv) {
10352         if (sv->op_type == OP_RV2SV) {  /* symbol table variable */
10353             iterpflags = sv->op_private & OPpOUR_INTRO; /* for our $x () */
10354             OpTYPE_set(sv, OP_RV2GV);
10355
10356             /* The op_type check is needed to prevent a possible segfault
10357              * if the loop variable is undeclared and 'strict vars' is in
10358              * effect. This is illegal but is nonetheless parsed, so we
10359              * may reach this point with an OP_CONST where we're expecting
10360              * an OP_GV.
10361              */
10362             if (cUNOPx(sv)->op_first->op_type == OP_GV
10363              && cGVOPx_gv(cUNOPx(sv)->op_first) == PL_defgv)
10364                 iterpflags |= OPpITER_DEF;
10365         }
10366         else if (sv->op_type == OP_PADSV) { /* private variable */
10367             if (sv->op_flags & OPf_PARENS) {
10368                 /* handle degenerate 1-var form of "for my ($x, ...)" */
10369                 sv->op_private |= OPpLVAL_INTRO;
10370                 parens = 1;
10371             }
10372             iterpflags = sv->op_private & OPpLVAL_INTRO; /* for my $x () */
10373             padoff = sv->op_targ;
10374             sv->op_targ = 0;
10375             op_free(sv);
10376             sv = NULL;
10377             PAD_COMPNAME_GEN_set(padoff, PERL_INT_MAX);
10378         }
10379         else if (sv->op_type == OP_NULL && sv->op_targ == OP_SREFGEN)
10380             NOOP;
10381         else if (sv->op_type == OP_LIST) {
10382             LISTOP *list = (LISTOP *) sv;
10383             OP *pushmark = list->op_first;
10384             OP *first_padsv;
10385             UNOP *padsv;
10386             PADOFFSET i;
10387
10388             iterpflags = OPpLVAL_INTRO; /* for my ($k, $v) () */
10389             parens = 1;
10390
10391             if (!pushmark || pushmark->op_type != OP_PUSHMARK) {
10392                 Perl_croak(aTHX_ "panic: newFORLOOP, found %s, expecting pushmark",
10393                            pushmark ? PL_op_desc[pushmark->op_type] : "NULL");
10394             }
10395             first_padsv = OpSIBLING(pushmark);
10396             if (!first_padsv || first_padsv->op_type != OP_PADSV) {
10397                 Perl_croak(aTHX_ "panic: newFORLOOP, found %s, expecting padsv",
10398                            first_padsv ? PL_op_desc[first_padsv->op_type] : "NULL");
10399             }
10400             padoff = first_padsv->op_targ;
10401
10402             /* There should be at least one more PADSV to find, and the ops
10403                should have consecutive values in targ: */
10404             padsv = (UNOP *) OpSIBLING(first_padsv);
10405             do {
10406                 if (!padsv || padsv->op_type != OP_PADSV) {
10407                     Perl_croak(aTHX_ "panic: newFORLOOP, found %s at %zd, expecting padsv",
10408                                padsv ? PL_op_desc[padsv->op_type] : "NULL",
10409                                how_many_more);
10410                 }
10411                 ++how_many_more;
10412                 if (padsv->op_targ != padoff + how_many_more) {
10413                     Perl_croak(aTHX_ "panic: newFORLOOP, padsv at %zd targ is %zd, not %zd",
10414                                how_many_more, padsv->op_targ, padoff + how_many_more);
10415                 }
10416
10417                 padsv = (UNOP *) OpSIBLING(padsv);
10418             } while (padsv);
10419
10420             /* OK, this optree has the shape that we expected. So now *we*
10421                "claim" the Pad slots: */
10422             first_padsv->op_targ = 0;
10423             PAD_COMPNAME_GEN_set(padoff, PERL_INT_MAX);
10424
10425             i = padoff;
10426
10427             padsv = (UNOP *) OpSIBLING(first_padsv);
10428             do {
10429                 ++i;
10430                 padsv->op_targ = 0;
10431                 PAD_COMPNAME_GEN_set(i, PERL_INT_MAX);
10432
10433                 padsv = (UNOP *) OpSIBLING(padsv);
10434             } while (padsv);
10435
10436             op_free(sv);
10437             sv = NULL;
10438         }
10439         else
10440             Perl_croak(aTHX_ "Can't use %s for loop variable", PL_op_desc[sv->op_type]);
10441         if (padoff) {
10442             PADNAME * const pn = PAD_COMPNAME(padoff);
10443             const char * const name = PadnamePV(pn);
10444
10445             if (PadnameLEN(pn) == 2 && name[0] == '$' && name[1] == '_')
10446                 iterpflags |= OPpITER_DEF;
10447         }
10448     }
10449     else {
10450         sv = newGVOP(OP_GV, 0, PL_defgv);
10451         iterpflags |= OPpITER_DEF;
10452     }
10453
10454     if (expr->op_type == OP_RV2AV || expr->op_type == OP_PADAV) {
10455         expr = op_lvalue(force_list(scalar(ref(expr, OP_ITER)), TRUE), OP_GREPSTART);
10456         iterflags |= OPf_STACKED;
10457     }
10458     else if (expr->op_type == OP_NULL &&
10459              (expr->op_flags & OPf_KIDS) &&
10460              ((BINOP*)expr)->op_first->op_type == OP_FLOP)
10461     {
10462         /* Basically turn for($x..$y) into the same as for($x,$y), but we
10463          * set the STACKED flag to indicate that these values are to be
10464          * treated as min/max values by 'pp_enteriter'.
10465          */
10466         const UNOP* const flip = (UNOP*)((UNOP*)((BINOP*)expr)->op_first)->op_first;
10467         LOGOP* const range = (LOGOP*) flip->op_first;
10468         OP* const left  = range->op_first;
10469         OP* const right = OpSIBLING(left);
10470         LISTOP* listop;
10471
10472         range->op_flags &= ~OPf_KIDS;
10473         /* detach range's children */
10474         op_sibling_splice((OP*)range, NULL, -1, NULL);
10475
10476         listop = (LISTOP*)newLISTOP(OP_LIST, 0, left, right);
10477         listop->op_first->op_next = range->op_next;
10478         left->op_next = range->op_other;
10479         right->op_next = (OP*)listop;
10480         listop->op_next = listop->op_first;
10481
10482         op_free(expr);
10483         expr = (OP*)(listop);
10484         op_null(expr);
10485         iterflags |= OPf_STACKED;
10486     }
10487     else {
10488         expr = op_lvalue(force_list(expr, TRUE), OP_GREPSTART);
10489     }
10490
10491     loop = (LOOP*)op_convert_list(OP_ENTERITER, iterflags,
10492                                   op_append_elem(OP_LIST, list(expr),
10493                                                  scalar(sv)));
10494     assert(!loop->op_next);
10495     /* for my  $x () sets OPpLVAL_INTRO;
10496      * for our $x () sets OPpOUR_INTRO */
10497     loop->op_private = (U8)iterpflags;
10498
10499     /* upgrade loop from a LISTOP to a LOOPOP;
10500      * keep it in-place if there's space */
10501     if (loop->op_slabbed
10502         &&    OpSLOT(loop)->opslot_size
10503             < SIZE_TO_PSIZE(sizeof(LOOP) + OPSLOT_HEADER))
10504     {
10505         /* no space; allocate new op */
10506         LOOP *tmp;
10507         NewOp(1234,tmp,1,LOOP);
10508         Copy(loop,tmp,1,LISTOP);
10509         assert(loop->op_last->op_sibparent == (OP*)loop);
10510         OpLASTSIB_set(loop->op_last, (OP*)tmp); /*point back to new parent */
10511         S_op_destroy(aTHX_ (OP*)loop);
10512         loop = tmp;
10513     }
10514     else if (!loop->op_slabbed)
10515     {
10516         /* loop was malloc()ed */
10517         loop = (LOOP*)PerlMemShared_realloc(loop, sizeof(LOOP));
10518         OpLASTSIB_set(loop->op_last, (OP*)loop);
10519     }
10520     loop->op_targ = padoff;
10521     if (parens)
10522         /* hint to deparser that this:  for my (...) ... */
10523         loop->op_flags |= OPf_PARENS;
10524     iter = newOP(OP_ITER, 0);
10525     iter->op_targ = how_many_more;
10526     return newWHILEOP(flags, 1, loop, iter, block, cont, 0);
10527 }
10528
10529 /*
10530 =for apidoc newLOOPEX
10531
10532 Constructs, checks, and returns a loop-exiting op (such as C<goto>
10533 or C<last>).  C<type> is the opcode.  C<label> supplies the parameter
10534 determining the target of the op; it is consumed by this function and
10535 becomes part of the constructed op tree.
10536
10537 =cut
10538 */
10539
10540 OP*
10541 Perl_newLOOPEX(pTHX_ I32 type, OP *label)
10542 {
10543     OP *o = NULL;
10544
10545     PERL_ARGS_ASSERT_NEWLOOPEX;
10546
10547     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_LOOPEXOP
10548         || type == OP_CUSTOM);
10549
10550     if (type != OP_GOTO) {
10551         /* "last()" means "last" */
10552         if (label->op_type == OP_STUB && (label->op_flags & OPf_PARENS)) {
10553             o = newOP(type, OPf_SPECIAL);
10554         }
10555     }
10556     else {
10557         /* Check whether it's going to be a goto &function */
10558         if (label->op_type == OP_ENTERSUB
10559                 && !(label->op_flags & OPf_STACKED))
10560             label = newUNOP(OP_REFGEN, 0, op_lvalue(label, OP_REFGEN));
10561     }
10562
10563     /* Check for a constant argument */
10564     if (label->op_type == OP_CONST) {
10565             SV * const sv = ((SVOP *)label)->op_sv;
10566             STRLEN l;
10567             const char *s = SvPV_const(sv,l);
10568             if (l == strlen(s)) {
10569                 o = newPVOP(type,
10570                             SvUTF8(((SVOP*)label)->op_sv),
10571                             savesharedpv(
10572                                 SvPV_nolen_const(((SVOP*)label)->op_sv)));
10573             }
10574     }
10575
10576     /* If we have already created an op, we do not need the label. */
10577     if (o)
10578                 op_free(label);
10579     else o = newUNOP(type, OPf_STACKED, label);
10580
10581     PL_hints |= HINT_BLOCK_SCOPE;
10582     return o;
10583 }
10584
10585 /* if the condition is a literal array or hash
10586    (or @{ ... } etc), make a reference to it.
10587  */
10588 STATIC OP *
10589 S_ref_array_or_hash(pTHX_ OP *cond)
10590 {
10591     if (cond
10592     && (cond->op_type == OP_RV2AV
10593     ||  cond->op_type == OP_PADAV
10594     ||  cond->op_type == OP_RV2HV
10595     ||  cond->op_type == OP_PADHV))
10596
10597         return newUNOP(OP_REFGEN, 0, op_lvalue(cond, OP_REFGEN));
10598
10599     else if(cond
10600     && (cond->op_type == OP_ASLICE
10601     ||  cond->op_type == OP_KVASLICE
10602     ||  cond->op_type == OP_HSLICE
10603     ||  cond->op_type == OP_KVHSLICE)) {
10604
10605         /* anonlist now needs a list from this op, was previously used in
10606          * scalar context */
10607         cond->op_flags &= ~(OPf_WANT_SCALAR | OPf_REF);
10608         cond->op_flags |= OPf_WANT_LIST;
10609
10610         return newANONLIST(op_lvalue(cond, OP_ANONLIST));
10611     }
10612
10613     else
10614         return cond;
10615 }
10616
10617 /* These construct the optree fragments representing given()
10618    and when() blocks.
10619
10620    entergiven and enterwhen are LOGOPs; the op_other pointer
10621    points up to the associated leave op. We need this so we
10622    can put it in the context and make break/continue work.
10623    (Also, of course, pp_enterwhen will jump straight to
10624    op_other if the match fails.)
10625  */
10626
10627 STATIC OP *
10628 S_newGIVWHENOP(pTHX_ OP *cond, OP *block,
10629                    I32 enter_opcode, I32 leave_opcode,
10630                    PADOFFSET entertarg)
10631 {
10632     LOGOP *enterop;
10633     OP *o;
10634
10635     PERL_ARGS_ASSERT_NEWGIVWHENOP;
10636     PERL_UNUSED_ARG(entertarg); /* used to indicate targ of lexical $_ */
10637
10638     enterop = alloc_LOGOP(enter_opcode, block, NULL);
10639     enterop->op_targ = 0;
10640     enterop->op_private = 0;
10641
10642     o = newUNOP(leave_opcode, 0, (OP *) enterop);
10643
10644     if (cond) {
10645         /* prepend cond if we have one */
10646         op_sibling_splice((OP*)enterop, NULL, 0, scalar(cond));
10647
10648         o->op_next = LINKLIST(cond);
10649         cond->op_next = (OP *) enterop;
10650     }
10651     else {
10652         /* This is a default {} block */
10653         enterop->op_flags |= OPf_SPECIAL;
10654         o      ->op_flags |= OPf_SPECIAL;
10655
10656         o->op_next = (OP *) enterop;
10657     }
10658
10659     CHECKOP(enter_opcode, enterop); /* Currently does nothing, since
10660                                        entergiven and enterwhen both
10661                                        use ck_null() */
10662
10663     enterop->op_next = LINKLIST(block);
10664     block->op_next = enterop->op_other = o;
10665
10666     return o;
10667 }
10668
10669
10670 /* For the purposes of 'when(implied_smartmatch)'
10671  *              versus 'when(boolean_expression)',
10672  * does this look like a boolean operation? For these purposes
10673    a boolean operation is:
10674      - a subroutine call [*]
10675      - a logical connective
10676      - a comparison operator
10677      - a filetest operator, with the exception of -s -M -A -C
10678      - defined(), exists() or eof()
10679      - /$re/ or $foo =~ /$re/
10680
10681    [*] possibly surprising
10682  */
10683 STATIC bool
10684 S_looks_like_bool(pTHX_ const OP *o)
10685 {
10686     PERL_ARGS_ASSERT_LOOKS_LIKE_BOOL;
10687
10688     switch(o->op_type) {
10689         case OP_OR:
10690         case OP_DOR:
10691             return looks_like_bool(cLOGOPo->op_first);
10692
10693         case OP_AND:
10694         {
10695             OP* sibl = OpSIBLING(cLOGOPo->op_first);
10696             ASSUME(sibl);
10697             return (
10698                 looks_like_bool(cLOGOPo->op_first)
10699              && looks_like_bool(sibl));
10700         }
10701
10702         case OP_NULL:
10703         case OP_SCALAR:
10704             return (
10705                 o->op_flags & OPf_KIDS
10706             && looks_like_bool(cUNOPo->op_first));
10707
10708         case OP_ENTERSUB:
10709
10710         case OP_NOT:    case OP_XOR:
10711
10712         case OP_EQ:     case OP_NE:     case OP_LT:
10713         case OP_GT:     case OP_LE:     case OP_GE:
10714
10715         case OP_I_EQ:   case OP_I_NE:   case OP_I_LT:
10716         case OP_I_GT:   case OP_I_LE:   case OP_I_GE:
10717
10718         case OP_SEQ:    case OP_SNE:    case OP_SLT:
10719         case OP_SGT:    case OP_SLE:    case OP_SGE:
10720
10721         case OP_SMARTMATCH:
10722
10723         case OP_FTRREAD:  case OP_FTRWRITE: case OP_FTREXEC:
10724         case OP_FTEREAD:  case OP_FTEWRITE: case OP_FTEEXEC:
10725         case OP_FTIS:     case OP_FTEOWNED: case OP_FTROWNED:
10726         case OP_FTZERO:   case OP_FTSOCK:   case OP_FTCHR:
10727         case OP_FTBLK:    case OP_FTFILE:   case OP_FTDIR:
10728         case OP_FTPIPE:   case OP_FTLINK:   case OP_FTSUID:
10729         case OP_FTSGID:   case OP_FTSVTX:   case OP_FTTTY:
10730         case OP_FTTEXT:   case OP_FTBINARY:
10731
10732         case OP_DEFINED: case OP_EXISTS:
10733         case OP_MATCH:   case OP_EOF:
10734
10735         case OP_FLOP:
10736
10737             return TRUE;
10738
10739         case OP_INDEX:
10740         case OP_RINDEX:
10741             /* optimised-away (index() != -1) or similar comparison */
10742             if (o->op_private & OPpTRUEBOOL)
10743                 return TRUE;
10744             return FALSE;
10745
10746         case OP_CONST:
10747             /* Detect comparisons that have been optimized away */
10748             if (cSVOPo->op_sv == &PL_sv_yes
10749             ||  cSVOPo->op_sv == &PL_sv_no)
10750
10751                 return TRUE;
10752             else
10753                 return FALSE;
10754         /* FALLTHROUGH */
10755         default:
10756             return FALSE;
10757     }
10758 }
10759
10760
10761 /*
10762 =for apidoc newGIVENOP
10763
10764 Constructs, checks, and returns an op tree expressing a C<given> block.
10765 C<cond> supplies the expression to whose value C<$_> will be locally
10766 aliased, and C<block> supplies the body of the C<given> construct; they
10767 are consumed by this function and become part of the constructed op tree.
10768 C<defsv_off> must be zero (it used to identity the pad slot of lexical $_).
10769
10770 =cut
10771 */
10772
10773 OP *
10774 Perl_newGIVENOP(pTHX_ OP *cond, OP *block, PADOFFSET defsv_off)
10775 {
10776     PERL_ARGS_ASSERT_NEWGIVENOP;
10777     PERL_UNUSED_ARG(defsv_off);
10778
10779     assert(!defsv_off);
10780     return newGIVWHENOP(
10781         ref_array_or_hash(cond),
10782         block,
10783         OP_ENTERGIVEN, OP_LEAVEGIVEN,
10784         0);
10785 }
10786
10787 /*
10788 =for apidoc newWHENOP
10789
10790 Constructs, checks, and returns an op tree expressing a C<when> block.
10791 C<cond> supplies the test expression, and C<block> supplies the block
10792 that will be executed if the test evaluates to true; they are consumed
10793 by this function and become part of the constructed op tree.  C<cond>
10794 will be interpreted DWIMically, often as a comparison against C<$_>,
10795 and may be null to generate a C<default> block.
10796
10797 =cut
10798 */
10799
10800 OP *
10801 Perl_newWHENOP(pTHX_ OP *cond, OP *block)
10802 {
10803     const bool cond_llb = (!cond || looks_like_bool(cond));
10804     OP *cond_op;
10805
10806     PERL_ARGS_ASSERT_NEWWHENOP;
10807
10808     if (cond_llb)
10809         cond_op = cond;
10810     else {
10811         cond_op = newBINOP(OP_SMARTMATCH, OPf_SPECIAL,
10812                 newDEFSVOP(),
10813                 scalar(ref_array_or_hash(cond)));
10814     }
10815
10816     return newGIVWHENOP(cond_op, block, OP_ENTERWHEN, OP_LEAVEWHEN, 0);
10817 }
10818
10819 /*
10820 =for apidoc newDEFEROP
10821
10822 Constructs and returns a deferred-block statement that implements the
10823 C<defer> semantics.  The C<block> optree is consumed by this function and
10824 becomes part of the returned optree.
10825
10826 The C<flags> argument carries additional flags to set on the returned op,
10827 including the C<op_private> field.
10828
10829 =cut
10830  */
10831
10832 OP *
10833 Perl_newDEFEROP(pTHX_ I32 flags, OP *block)
10834 {
10835     OP *o, *start, *blockfirst;
10836
10837     PERL_ARGS_ASSERT_NEWDEFEROP;
10838
10839     start = LINKLIST(block);
10840
10841     /* Hide the block inside an OP_NULL with no exection */
10842     block = newUNOP(OP_NULL, 0, block);
10843     block->op_next = block;
10844
10845     o = (OP *)alloc_LOGOP(OP_PUSHDEFER, block, start);
10846     o->op_flags |= OPf_WANT_VOID | (U8)(flags);
10847     o->op_private = (U8)(flags >> 8);
10848
10849     /* Terminate the block */
10850     blockfirst = cUNOPx(block)->op_first;
10851     assert(blockfirst->op_type == OP_SCOPE || blockfirst->op_type == OP_LEAVE);
10852     blockfirst->op_next = NULL;
10853
10854     return o;
10855 }
10856
10857 /*
10858 =for apidoc op_wrap_finally
10859
10860 Wraps the given C<block> optree fragment in its own scoped block, arranging
10861 for the C<finally> optree fragment to be invoked when leaving that block for
10862 any reason. Both optree fragments are consumed and the combined result is
10863 returned.
10864
10865 =cut
10866 */
10867
10868 OP *
10869 Perl_op_wrap_finally(pTHX_ OP *block, OP *finally)
10870 {
10871     PERL_ARGS_ASSERT_OP_WRAP_FINALLY;
10872
10873     /* TODO: If block is already an ENTER/LEAVE-wrapped line sequence we can
10874      * just splice the DEFEROP in at the top, for efficiency.
10875      */
10876
10877     OP *o = newLISTOP(OP_LINESEQ, 0, newDEFEROP((OPpDEFER_FINALLY << 8), finally), block);
10878     o = op_prepend_elem(OP_LINESEQ, newOP(OP_ENTER, 0), o);
10879     OpTYPE_set(o, OP_LEAVE);
10880
10881     return o;
10882 }
10883
10884 /* must not conflict with SVf_UTF8 */
10885 #define CV_CKPROTO_CURSTASH     0x1
10886
10887 void
10888 Perl_cv_ckproto_len_flags(pTHX_ const CV *cv, const GV *gv, const char *p,
10889                     const STRLEN len, const U32 flags)
10890 {
10891     SV *name = NULL, *msg;
10892     const char * cvp = SvROK(cv)
10893                         ? SvTYPE(SvRV_const(cv)) == SVt_PVCV
10894                            ? (cv = (const CV *)SvRV_const(cv), CvPROTO(cv))
10895                            : ""
10896                         : CvPROTO(cv);
10897     STRLEN clen = CvPROTOLEN(cv), plen = len;
10898
10899     PERL_ARGS_ASSERT_CV_CKPROTO_LEN_FLAGS;
10900
10901     if (p == NULL && cvp == NULL)
10902         return;
10903
10904     if (!ckWARN_d(WARN_PROTOTYPE))
10905         return;
10906
10907     if (p && cvp) {
10908         p = S_strip_spaces(aTHX_ p, &plen);
10909         cvp = S_strip_spaces(aTHX_ cvp, &clen);
10910         if ((flags & SVf_UTF8) == SvUTF8(cv)) {
10911             if (plen == clen && memEQ(cvp, p, plen))
10912                 return;
10913         } else {
10914             if (flags & SVf_UTF8) {
10915                 if (bytes_cmp_utf8((const U8 *)cvp, clen, (const U8 *)p, plen) == 0)
10916                     return;
10917             }
10918             else {
10919                 if (bytes_cmp_utf8((const U8 *)p, plen, (const U8 *)cvp, clen) == 0)
10920                     return;
10921             }
10922         }
10923     }
10924
10925     msg = sv_newmortal();
10926
10927     if (gv)
10928     {
10929         if (isGV(gv))
10930             gv_efullname3(name = sv_newmortal(), gv, NULL);
10931         else if (SvPOK(gv) && *SvPVX((SV *)gv) == '&')
10932             name = newSVpvn_flags(SvPVX((SV *)gv)+1, SvCUR(gv)-1, SvUTF8(gv)|SVs_TEMP);
10933         else if (flags & CV_CKPROTO_CURSTASH || SvROK(gv)) {
10934             name = sv_2mortal(newSVhek(HvNAME_HEK(PL_curstash)));
10935             sv_catpvs(name, "::");
10936             if (SvROK(gv)) {
10937                 assert (SvTYPE(SvRV_const(gv)) == SVt_PVCV);
10938                 assert (CvNAMED(SvRV_const(gv)));
10939                 sv_cathek(name, CvNAME_HEK(MUTABLE_CV(SvRV_const(gv))));
10940             }
10941             else sv_catsv(name, (SV *)gv);
10942         }
10943         else name = (SV *)gv;
10944     }
10945     sv_setpvs(msg, "Prototype mismatch:");
10946     if (name)
10947         Perl_sv_catpvf(aTHX_ msg, " sub %" SVf, SVfARG(name));
10948     if (cvp)
10949         Perl_sv_catpvf(aTHX_ msg, " (%" UTF8f ")",
10950             UTF8fARG(SvUTF8(cv),clen,cvp)
10951         );
10952     else
10953         sv_catpvs(msg, ": none");
10954     sv_catpvs(msg, " vs ");
10955     if (p)
10956         Perl_sv_catpvf(aTHX_ msg, "(%" UTF8f ")", UTF8fARG(flags & SVf_UTF8,len,p));
10957     else
10958         sv_catpvs(msg, "none");
10959     Perl_warner(aTHX_ packWARN(WARN_PROTOTYPE), "%" SVf, SVfARG(msg));
10960 }
10961
10962 static void const_sv_xsub(pTHX_ CV* cv);
10963 static void const_av_xsub(pTHX_ CV* cv);
10964
10965 /*
10966
10967 =for apidoc_section $optree_manipulation
10968
10969 =for apidoc cv_const_sv
10970
10971 If C<cv> is a constant sub eligible for inlining, returns the constant
10972 value returned by the sub.  Otherwise, returns C<NULL>.
10973
10974 Constant subs can be created with C<newCONSTSUB> or as described in
10975 L<perlsub/"Constant Functions">.
10976
10977 =cut
10978 */
10979 SV *
10980 Perl_cv_const_sv(const CV *const cv)
10981 {
10982     SV *sv;
10983     if (!cv)
10984         return NULL;
10985     if (!(SvTYPE(cv) == SVt_PVCV || SvTYPE(cv) == SVt_PVFM))
10986         return NULL;
10987     sv = CvCONST(cv) ? MUTABLE_SV(CvXSUBANY(cv).any_ptr) : NULL;
10988     if (sv && SvTYPE(sv) == SVt_PVAV) return NULL;
10989     return sv;
10990 }
10991
10992 SV *
10993 Perl_cv_const_sv_or_av(const CV * const cv)
10994 {
10995     if (!cv)
10996         return NULL;
10997     if (SvROK(cv)) return SvRV((SV *)cv);
10998     assert (SvTYPE(cv) == SVt_PVCV || SvTYPE(cv) == SVt_PVFM);
10999     return CvCONST(cv) ? MUTABLE_SV(CvXSUBANY(cv).any_ptr) : NULL;
11000 }
11001
11002 /* op_const_sv:  examine an optree to determine whether it's in-lineable.
11003  * Can be called in 2 ways:
11004  *
11005  * !allow_lex
11006  *      look for a single OP_CONST with attached value: return the value
11007  *
11008  * allow_lex && !CvCONST(cv);
11009  *
11010  *      examine the clone prototype, and if contains only a single
11011  *      OP_CONST, return the value; or if it contains a single PADSV ref-
11012  *      erencing an outer lexical, turn on CvCONST to indicate the CV is
11013  *      a candidate for "constizing" at clone time, and return NULL.
11014  */
11015
11016 static SV *
11017 S_op_const_sv(pTHX_ const OP *o, CV *cv, bool allow_lex)
11018 {
11019     SV *sv = NULL;
11020     bool padsv = FALSE;
11021
11022     assert(o);
11023     assert(cv);
11024
11025     for (; o; o = o->op_next) {
11026         const OPCODE type = o->op_type;
11027
11028         if (type == OP_NEXTSTATE || type == OP_LINESEQ
11029              || type == OP_NULL
11030              || type == OP_PUSHMARK)
11031                 continue;
11032         if (type == OP_DBSTATE)
11033                 continue;
11034         if (type == OP_LEAVESUB)
11035             break;
11036         if (sv)
11037             return NULL;
11038         if (type == OP_CONST && cSVOPo->op_sv)
11039             sv = cSVOPo->op_sv;
11040         else if (type == OP_UNDEF && !o->op_private) {
11041             sv = newSV_type(SVt_NULL);
11042             SAVEFREESV(sv);
11043         }
11044         else if (allow_lex && type == OP_PADSV) {
11045                 if (PAD_COMPNAME_FLAGS(o->op_targ) & PADNAMEt_OUTER)
11046                 {
11047                     sv = &PL_sv_undef; /* an arbitrary non-null value */
11048                     padsv = TRUE;
11049                 }
11050                 else
11051                     return NULL;
11052         }
11053         else {
11054             return NULL;
11055         }
11056     }
11057     if (padsv) {
11058         CvCONST_on(cv);
11059         return NULL;
11060     }
11061     return sv;
11062 }
11063
11064 static void
11065 S_already_defined(pTHX_ CV *const cv, OP * const block, OP * const o,
11066                         PADNAME * const name, SV ** const const_svp)
11067 {
11068     assert (cv);
11069     assert (o || name);
11070     assert (const_svp);
11071     if (!block) {
11072         if (CvFLAGS(PL_compcv)) {
11073             /* might have had built-in attrs applied */
11074             const bool pureperl = !CvISXSUB(cv) && CvROOT(cv);
11075             if (CvLVALUE(PL_compcv) && ! CvLVALUE(cv) && pureperl
11076              && ckWARN(WARN_MISC))
11077             {
11078                 /* protect against fatal warnings leaking compcv */
11079                 SAVEFREESV(PL_compcv);
11080                 Perl_warner(aTHX_ packWARN(WARN_MISC), "lvalue attribute ignored after the subroutine has been defined");
11081                 SvREFCNT_inc_simple_void_NN(PL_compcv);
11082             }
11083             CvFLAGS(cv) |=
11084                 (CvFLAGS(PL_compcv) & CVf_BUILTIN_ATTRS
11085                   & ~(CVf_LVALUE * pureperl));
11086         }
11087         return;
11088     }
11089
11090     /* redundant check for speed: */
11091     if (CvCONST(cv) || ckWARN(WARN_REDEFINE)) {
11092         const line_t oldline = CopLINE(PL_curcop);
11093         SV *namesv = o
11094             ? cSVOPo->op_sv
11095             : newSVpvn_flags( PadnamePV(name)+1,PadnameLEN(name)-1,
11096                (PadnameUTF8(name)) ? SVf_UTF8|SVs_TEMP : SVs_TEMP
11097               );
11098         if (PL_parser && PL_parser->copline != NOLINE)
11099             /* This ensures that warnings are reported at the first
11100                line of a redefinition, not the last.  */
11101             CopLINE_set(PL_curcop, PL_parser->copline);
11102         /* protect against fatal warnings leaking compcv */
11103         SAVEFREESV(PL_compcv);
11104         report_redefined_cv(namesv, cv, const_svp);
11105         SvREFCNT_inc_simple_void_NN(PL_compcv);
11106         CopLINE_set(PL_curcop, oldline);
11107     }
11108     SAVEFREESV(cv);
11109     return;
11110 }
11111
11112 CV *
11113 Perl_newMYSUB(pTHX_ I32 floor, OP *o, OP *proto, OP *attrs, OP *block)
11114 {
11115     CV **spot;
11116     SV **svspot;
11117     const char *ps;
11118     STRLEN ps_len = 0; /* init it to avoid false uninit warning from icc */
11119     U32 ps_utf8 = 0;
11120     CV *cv = NULL;
11121     CV *compcv = PL_compcv;
11122     SV *const_sv;
11123     PADNAME *name;
11124     PADOFFSET pax = o->op_targ;
11125     CV *outcv = CvOUTSIDE(PL_compcv);
11126     CV *clonee = NULL;
11127     HEK *hek = NULL;
11128     bool reusable = FALSE;
11129     OP *start = NULL;
11130 #ifdef PERL_DEBUG_READONLY_OPS
11131     OPSLAB *slab = NULL;
11132 #endif
11133
11134     PERL_ARGS_ASSERT_NEWMYSUB;
11135
11136     PL_hints |= HINT_BLOCK_SCOPE;
11137
11138     /* Find the pad slot for storing the new sub.
11139        We cannot use PL_comppad, as it is the pad owned by the new sub.  We
11140        need to look in CvOUTSIDE and find the pad belonging to the enclos-
11141        ing sub.  And then we need to dig deeper if this is a lexical from
11142        outside, as in:
11143            my sub foo; sub { sub foo { } }
11144      */
11145   redo:
11146     name = PadlistNAMESARRAY(CvPADLIST(outcv))[pax];
11147     if (PadnameOUTER(name) && PARENT_PAD_INDEX(name)) {
11148         pax = PARENT_PAD_INDEX(name);
11149         outcv = CvOUTSIDE(outcv);
11150         assert(outcv);
11151         goto redo;
11152     }
11153     svspot =
11154         &PadARRAY(PadlistARRAY(CvPADLIST(outcv))
11155                         [CvDEPTH(outcv) ? CvDEPTH(outcv) : 1])[pax];
11156     spot = (CV **)svspot;
11157
11158     if (!(PL_parser && PL_parser->error_count))
11159         move_proto_attr(&proto, &attrs, (GV *)PadnameSV(name), 0);
11160
11161     if (proto) {
11162         assert(proto->op_type == OP_CONST);
11163         ps = SvPV_const(((SVOP*)proto)->op_sv, ps_len);
11164         ps_utf8 = SvUTF8(((SVOP*)proto)->op_sv);
11165     }
11166     else
11167         ps = NULL;
11168
11169     if (proto)
11170         SAVEFREEOP(proto);
11171     if (attrs)
11172         SAVEFREEOP(attrs);
11173
11174     if (PL_parser && PL_parser->error_count) {
11175         op_free(block);
11176         SvREFCNT_dec(PL_compcv);
11177         PL_compcv = 0;
11178         goto done;
11179     }
11180
11181     if (CvDEPTH(outcv) && CvCLONE(compcv)) {
11182         cv = *spot;
11183         svspot = (SV **)(spot = &clonee);
11184     }
11185     else if (PadnameIsSTATE(name) || CvDEPTH(outcv))
11186         cv = *spot;
11187     else {
11188         assert (SvTYPE(*spot) == SVt_PVCV);
11189         if (CvNAMED(*spot))
11190             hek = CvNAME_HEK(*spot);
11191         else {
11192             U32 hash;
11193             PERL_HASH(hash, PadnamePV(name)+1, PadnameLEN(name)-1);
11194             CvNAME_HEK_set(*spot, hek =
11195                 share_hek(
11196                     PadnamePV(name)+1,
11197                     (PadnameLEN(name)-1) * (PadnameUTF8(name) ? -1 : 1),
11198                     hash
11199                 )
11200             );
11201             CvLEXICAL_on(*spot);
11202         }
11203         cv = PadnamePROTOCV(name);
11204         svspot = (SV **)(spot = &PadnamePROTOCV(name));
11205     }
11206
11207     if (block) {
11208         /* This makes sub {}; work as expected.  */
11209         if (block->op_type == OP_STUB) {
11210             const line_t l = PL_parser->copline;
11211             op_free(block);
11212             block = newSTATEOP(0, NULL, 0);
11213             PL_parser->copline = l;
11214         }
11215         block = CvLVALUE(compcv)
11216              || (cv && CvLVALUE(cv) && !CvROOT(cv) && !CvXSUB(cv))
11217                    ? newUNOP(OP_LEAVESUBLV, 0,
11218                              op_lvalue(voidnonfinal(block), OP_LEAVESUBLV))
11219                    : newUNOP(OP_LEAVESUB, 0, voidnonfinal(block));
11220         start = LINKLIST(block);
11221         block->op_next = 0;
11222         if (ps && !*ps && !attrs && !CvLVALUE(compcv))
11223             const_sv = S_op_const_sv(aTHX_ start, compcv, FALSE);
11224         else
11225             const_sv = NULL;
11226     }
11227     else
11228         const_sv = NULL;
11229
11230     if (cv) {
11231         const bool exists = CvROOT(cv) || CvXSUB(cv);
11232
11233         /* if the subroutine doesn't exist and wasn't pre-declared
11234          * with a prototype, assume it will be AUTOLOADed,
11235          * skipping the prototype check
11236          */
11237         if (exists || SvPOK(cv))
11238             cv_ckproto_len_flags(cv, (GV *)PadnameSV(name), ps, ps_len,
11239                                  ps_utf8);
11240         /* already defined? */
11241         if (exists) {
11242             S_already_defined(aTHX_ cv, block, NULL, name, &const_sv);
11243             if (block)
11244                 cv = NULL;
11245             else {
11246                 if (attrs)
11247                     goto attrs;
11248                 /* just a "sub foo;" when &foo is already defined */
11249                 SAVEFREESV(compcv);
11250                 goto done;
11251             }
11252         }
11253         else if (CvDEPTH(outcv) && CvCLONE(compcv)) {
11254             cv = NULL;
11255             reusable = TRUE;
11256         }
11257     }
11258
11259     if (const_sv) {
11260         SvREFCNT_inc_simple_void_NN(const_sv);
11261         SvFLAGS(const_sv) |= SVs_PADTMP;
11262         if (cv) {
11263             assert(!CvROOT(cv) && !CvCONST(cv));
11264             cv_forget_slab(cv);
11265         }
11266         else {
11267             cv = MUTABLE_CV(newSV_type(SVt_PVCV));
11268             CvFILE_set_from_cop(cv, PL_curcop);
11269             CvSTASH_set(cv, PL_curstash);
11270             *spot = cv;
11271         }
11272         SvPVCLEAR(MUTABLE_SV(cv));  /* prototype is "" */
11273         CvXSUBANY(cv).any_ptr = const_sv;
11274         CvXSUB(cv) = const_sv_xsub;
11275         CvCONST_on(cv);
11276         CvISXSUB_on(cv);
11277         PoisonPADLIST(cv);
11278         CvFLAGS(cv) |= CvMETHOD(compcv);
11279         op_free(block);
11280         SvREFCNT_dec(compcv);
11281         PL_compcv = NULL;
11282         goto setname;
11283     }
11284
11285     /* Checking whether outcv is CvOUTSIDE(compcv) is not sufficient to
11286        determine whether this sub definition is in the same scope as its
11287        declaration.  If this sub definition is inside an inner named pack-
11288        age sub (my sub foo; sub bar { sub foo { ... } }), outcv points to
11289        the package sub.  So check PadnameOUTER(name) too.
11290      */
11291     if (outcv == CvOUTSIDE(compcv) && !PadnameOUTER(name)) {
11292         assert(!CvWEAKOUTSIDE(compcv));
11293         SvREFCNT_dec(CvOUTSIDE(compcv));
11294         CvWEAKOUTSIDE_on(compcv);
11295     }
11296     /* XXX else do we have a circular reference? */
11297
11298     if (cv) {   /* must reuse cv in case stub is referenced elsewhere */
11299         /* transfer PL_compcv to cv */
11300         if (block) {
11301             bool free_file = CvFILE(cv) && CvDYNFILE(cv);
11302             cv_flags_t preserved_flags =
11303                 CvFLAGS(cv) & (CVf_BUILTIN_ATTRS|CVf_NAMED);
11304             PADLIST *const temp_padl = CvPADLIST(cv);
11305             CV *const temp_cv = CvOUTSIDE(cv);
11306             const cv_flags_t other_flags =
11307                 CvFLAGS(cv) & (CVf_SLABBED|CVf_WEAKOUTSIDE);
11308             OP * const cvstart = CvSTART(cv);
11309
11310             SvPOK_off(cv);
11311             CvFLAGS(cv) =
11312                 CvFLAGS(compcv) | preserved_flags;
11313             CvOUTSIDE(cv) = CvOUTSIDE(compcv);
11314             CvOUTSIDE_SEQ(cv) = CvOUTSIDE_SEQ(compcv);
11315             CvPADLIST_set(cv, CvPADLIST(compcv));
11316             CvOUTSIDE(compcv) = temp_cv;
11317             CvPADLIST_set(compcv, temp_padl);
11318             CvSTART(cv) = CvSTART(compcv);
11319             CvSTART(compcv) = cvstart;
11320             CvFLAGS(compcv) &= ~(CVf_SLABBED|CVf_WEAKOUTSIDE);
11321             CvFLAGS(compcv) |= other_flags;
11322
11323             if (free_file) {
11324                 Safefree(CvFILE(cv));
11325                 CvFILE(cv) = NULL;
11326             }
11327
11328             /* inner references to compcv must be fixed up ... */
11329             pad_fixup_inner_anons(CvPADLIST(cv), compcv, cv);
11330             if (PERLDB_INTER)/* Advice debugger on the new sub. */
11331                 ++PL_sub_generation;
11332         }
11333         else {
11334             /* Might have had built-in attributes applied -- propagate them. */
11335             CvFLAGS(cv) |= (CvFLAGS(compcv) & CVf_BUILTIN_ATTRS);
11336         }
11337         /* ... before we throw it away */
11338         SvREFCNT_dec(compcv);
11339         PL_compcv = compcv = cv;
11340     }
11341     else {
11342         cv = compcv;
11343         *spot = cv;
11344     }
11345
11346   setname:
11347     CvLEXICAL_on(cv);
11348     if (!CvNAME_HEK(cv)) {
11349         if (hek) (void)share_hek_hek(hek);
11350         else {
11351             U32 hash;
11352             PERL_HASH(hash, PadnamePV(name)+1, PadnameLEN(name)-1);
11353             hek = share_hek(PadnamePV(name)+1,
11354                       (PadnameLEN(name)-1) * (PadnameUTF8(name) ? -1 : 1),
11355                       hash);
11356         }
11357         CvNAME_HEK_set(cv, hek);
11358     }
11359
11360     if (const_sv)
11361         goto clone;
11362
11363     if (CvFILE(cv) && CvDYNFILE(cv))
11364         Safefree(CvFILE(cv));
11365     CvFILE_set_from_cop(cv, PL_curcop);
11366     CvSTASH_set(cv, PL_curstash);
11367
11368     if (ps) {
11369         sv_setpvn(MUTABLE_SV(cv), ps, ps_len);
11370         if (ps_utf8)
11371             SvUTF8_on(MUTABLE_SV(cv));
11372     }
11373
11374     if (block) {
11375         /* If we assign an optree to a PVCV, then we've defined a
11376          * subroutine that the debugger could be able to set a breakpoint
11377          * in, so signal to pp_entereval that it should not throw away any
11378          * saved lines at scope exit.  */
11379
11380         PL_breakable_sub_gen++;
11381         CvROOT(cv) = block;
11382         /* The cv no longer needs to hold a refcount on the slab, as CvROOT
11383            itself has a refcount. */
11384         CvSLABBED_off(cv);
11385         OpslabREFCNT_dec_padok((OPSLAB *)CvSTART(cv));
11386 #ifdef PERL_DEBUG_READONLY_OPS
11387         slab = (OPSLAB *)CvSTART(cv);
11388 #endif
11389         S_process_optree(aTHX_ cv, block, start);
11390     }
11391
11392   attrs:
11393     if (attrs) {
11394         /* Need to do a C<use attributes $stash_of_cv,\&cv,@attrs>. */
11395         apply_attrs(PL_curstash, MUTABLE_SV(cv), attrs);
11396     }
11397
11398     if (block) {
11399         if (PERLDB_SUBLINE && PL_curstash != PL_debstash) {
11400             SV * const tmpstr = sv_newmortal();
11401             GV * const db_postponed = gv_fetchpvs("DB::postponed",
11402                                                   GV_ADDMULTI, SVt_PVHV);
11403             HV *hv;
11404             SV * const sv = Perl_newSVpvf(aTHX_ "%s:%ld-%ld",
11405                                           CopFILE(PL_curcop),
11406                                           (long)PL_subline,
11407                                           (long)CopLINE(PL_curcop));
11408             if (HvNAME_HEK(PL_curstash)) {
11409                 sv_sethek(tmpstr, HvNAME_HEK(PL_curstash));
11410                 sv_catpvs(tmpstr, "::");
11411             }
11412             else
11413                 sv_setpvs(tmpstr, "__ANON__::");
11414
11415             sv_catpvn_flags(tmpstr, PadnamePV(name)+1, PadnameLEN(name)-1,
11416                             PadnameUTF8(name) ? SV_CATUTF8 : SV_CATBYTES);
11417             (void)hv_store_ent(GvHV(PL_DBsub), tmpstr, sv, 0);
11418             hv = GvHVn(db_postponed);
11419             if (HvTOTALKEYS(hv) > 0 && hv_exists_ent(hv, tmpstr, 0)) {
11420                 CV * const pcv = GvCV(db_postponed);
11421                 if (pcv) {
11422                     dSP;
11423                     PUSHMARK(SP);
11424                     XPUSHs(tmpstr);
11425                     PUTBACK;
11426                     call_sv(MUTABLE_SV(pcv), G_DISCARD);
11427                 }
11428             }
11429         }
11430     }
11431
11432   clone:
11433     if (clonee) {
11434         assert(CvDEPTH(outcv));
11435         spot = (CV **)
11436             &PadARRAY(PadlistARRAY(CvPADLIST(outcv))[CvDEPTH(outcv)])[pax];
11437         if (reusable)
11438             cv_clone_into(clonee, *spot);
11439         else *spot = cv_clone(clonee);
11440         SvREFCNT_dec_NN(clonee);
11441         cv = *spot;
11442     }
11443
11444     if (CvDEPTH(outcv) && !reusable && PadnameIsSTATE(name)) {
11445         PADOFFSET depth = CvDEPTH(outcv);
11446         while (--depth) {
11447             SV *oldcv;
11448             svspot = &PadARRAY(PadlistARRAY(CvPADLIST(outcv))[depth])[pax];
11449             oldcv = *svspot;
11450             *svspot = SvREFCNT_inc_simple_NN(cv);
11451             SvREFCNT_dec(oldcv);
11452         }
11453     }
11454
11455   done:
11456     if (PL_parser)
11457         PL_parser->copline = NOLINE;
11458     LEAVE_SCOPE(floor);
11459 #ifdef PERL_DEBUG_READONLY_OPS
11460     if (slab)
11461         Slab_to_ro(slab);
11462 #endif
11463     op_free(o);
11464     return cv;
11465 }
11466
11467 /*
11468 =for apidoc newATTRSUB_x
11469
11470 Construct a Perl subroutine, also performing some surrounding jobs.
11471
11472 This function is expected to be called in a Perl compilation context,
11473 and some aspects of the subroutine are taken from global variables
11474 associated with compilation.  In particular, C<PL_compcv> represents
11475 the subroutine that is currently being compiled.  It must be non-null
11476 when this function is called, and some aspects of the subroutine being
11477 constructed are taken from it.  The constructed subroutine may actually
11478 be a reuse of the C<PL_compcv> object, but will not necessarily be so.
11479
11480 If C<block> is null then the subroutine will have no body, and for the
11481 time being it will be an error to call it.  This represents a forward
11482 subroutine declaration such as S<C<sub foo ($$);>>.  If C<block> is
11483 non-null then it provides the Perl code of the subroutine body, which
11484 will be executed when the subroutine is called.  This body includes
11485 any argument unwrapping code resulting from a subroutine signature or
11486 similar.  The pad use of the code must correspond to the pad attached
11487 to C<PL_compcv>.  The code is not expected to include a C<leavesub> or
11488 C<leavesublv> op; this function will add such an op.  C<block> is consumed
11489 by this function and will become part of the constructed subroutine.
11490
11491 C<proto> specifies the subroutine's prototype, unless one is supplied
11492 as an attribute (see below).  If C<proto> is null, then the subroutine
11493 will not have a prototype.  If C<proto> is non-null, it must point to a
11494 C<const> op whose value is a string, and the subroutine will have that
11495 string as its prototype.  If a prototype is supplied as an attribute, the
11496 attribute takes precedence over C<proto>, but in that case C<proto> should
11497 preferably be null.  In any case, C<proto> is consumed by this function.
11498
11499 C<attrs> supplies attributes to be applied the subroutine.  A handful of
11500 attributes take effect by built-in means, being applied to C<PL_compcv>
11501 immediately when seen.  Other attributes are collected up and attached
11502 to the subroutine by this route.  C<attrs> may be null to supply no
11503 attributes, or point to a C<const> op for a single attribute, or point
11504 to a C<list> op whose children apart from the C<pushmark> are C<const>
11505 ops for one or more attributes.  Each C<const> op must be a string,
11506 giving the attribute name optionally followed by parenthesised arguments,
11507 in the manner in which attributes appear in Perl source.  The attributes
11508 will be applied to the sub by this function.  C<attrs> is consumed by
11509 this function.
11510
11511 If C<o_is_gv> is false and C<o> is null, then the subroutine will
11512 be anonymous.  If C<o_is_gv> is false and C<o> is non-null, then C<o>
11513 must point to a C<const> OP, which will be consumed by this function,
11514 and its string value supplies a name for the subroutine.  The name may
11515 be qualified or unqualified, and if it is unqualified then a default
11516 stash will be selected in some manner.  If C<o_is_gv> is true, then C<o>
11517 doesn't point to an C<OP> at all, but is instead a cast pointer to a C<GV>
11518 by which the subroutine will be named.
11519
11520 If there is already a subroutine of the specified name, then the new
11521 sub will either replace the existing one in the glob or be merged with
11522 the existing one.  A warning may be generated about redefinition.
11523
11524 If the subroutine has one of a few special names, such as C<BEGIN> or
11525 C<END>, then it will be claimed by the appropriate queue for automatic
11526 running of phase-related subroutines.  In this case the relevant glob will
11527 be left not containing any subroutine, even if it did contain one before.
11528 In the case of C<BEGIN>, the subroutine will be executed and the reference
11529 to it disposed of before this function returns.
11530
11531 The function returns a pointer to the constructed subroutine.  If the sub
11532 is anonymous then ownership of one counted reference to the subroutine
11533 is transferred to the caller.  If the sub is named then the caller does
11534 not get ownership of a reference.  In most such cases, where the sub
11535 has a non-phase name, the sub will be alive at the point it is returned
11536 by virtue of being contained in the glob that names it.  A phase-named
11537 subroutine will usually be alive by virtue of the reference owned by the
11538 phase's automatic run queue.  But a C<BEGIN> subroutine, having already
11539 been executed, will quite likely have been destroyed already by the
11540 time this function returns, making it erroneous for the caller to make
11541 any use of the returned pointer.  It is the caller's responsibility to
11542 ensure that it knows which of these situations applies.
11543
11544 =for apidoc newATTRSUB
11545 Construct a Perl subroutine, also performing some surrounding jobs.
11546
11547 This is the same as L<perlintern/C<newATTRSUB_x>> with its C<o_is_gv> parameter set to
11548 FALSE.  This means that if C<o> is null, the new sub will be anonymous; otherwise
11549 the name will be derived from C<o> in the way described (as with all other
11550 details) in L<perlintern/C<newATTRSUB_x>>.
11551
11552 =for apidoc newSUB
11553 Like C<L</newATTRSUB>>, but without attributes.
11554
11555 =cut
11556 */
11557
11558 /* _x = extended */
11559 CV *
11560 Perl_newATTRSUB_x(pTHX_ I32 floor, OP *o, OP *proto, OP *attrs,
11561                             OP *block, bool o_is_gv)
11562 {
11563     GV *gv;
11564     const char *ps;
11565     STRLEN ps_len = 0; /* init it to avoid false uninit warning from icc */
11566     U32 ps_utf8 = 0;
11567     CV *cv = NULL;     /* the previous CV with this name, if any */
11568     SV *const_sv;
11569     const bool ec = PL_parser && PL_parser->error_count;
11570     /* If the subroutine has no body, no attributes, and no builtin attributes
11571        then it's just a sub declaration, and we may be able to get away with
11572        storing with a placeholder scalar in the symbol table, rather than a
11573        full CV.  If anything is present then it will take a full CV to
11574        store it.  */
11575     const I32 gv_fetch_flags
11576         = ec ? GV_NOADD_NOINIT :
11577         (block || attrs || (CvFLAGS(PL_compcv) & CVf_BUILTIN_ATTRS))
11578         ? GV_ADDMULTI : GV_ADDMULTI | GV_NOINIT;
11579     STRLEN namlen = 0;
11580     const char * const name =
11581          o ? SvPV_const(o_is_gv ? (SV *)o : cSVOPo->op_sv, namlen) : NULL;
11582     bool has_name;
11583     bool name_is_utf8 = o && !o_is_gv && SvUTF8(cSVOPo->op_sv);
11584     bool evanescent = FALSE;
11585     OP *start = NULL;
11586 #ifdef PERL_DEBUG_READONLY_OPS
11587     OPSLAB *slab = NULL;
11588 #endif
11589
11590     if (o_is_gv) {
11591         gv = (GV*)o;
11592         o = NULL;
11593         has_name = TRUE;
11594     } else if (name) {
11595         /* Try to optimise and avoid creating a GV.  Instead, the CV’s name
11596            hek and CvSTASH pointer together can imply the GV.  If the name
11597            contains a package name, then GvSTASH(CvGV(cv)) may differ from
11598            CvSTASH, so forego the optimisation if we find any.
11599            Also, we may be called from load_module at run time, so
11600            PL_curstash (which sets CvSTASH) may not point to the stash the
11601            sub is stored in.  */
11602         /* XXX This optimization is currently disabled for packages other
11603                than main, since there was too much CPAN breakage.  */
11604         const I32 flags =
11605            ec ? GV_NOADD_NOINIT
11606               :   (IN_PERL_RUNTIME && PL_curstash != CopSTASH(PL_curcop))
11607                || PL_curstash != PL_defstash
11608                || memchr(name, ':', namlen) || memchr(name, '\'', namlen)
11609                     ? gv_fetch_flags
11610                     : GV_ADDMULTI | GV_NOINIT | GV_NOTQUAL;
11611         gv = gv_fetchsv(cSVOPo->op_sv, flags, SVt_PVCV);
11612         has_name = TRUE;
11613     } else if (PERLDB_NAMEANON && CopLINE(PL_curcop)) {
11614         SV * const sv = sv_newmortal();
11615         Perl_sv_setpvf(aTHX_ sv, "%s[%s:%" IVdf "]",
11616                        PL_curstash ? "__ANON__" : "__ANON__::__ANON__",
11617                        CopFILE(PL_curcop), (IV)CopLINE(PL_curcop));
11618         gv = gv_fetchsv(sv, gv_fetch_flags, SVt_PVCV);
11619         has_name = TRUE;
11620     } else if (PL_curstash) {
11621         gv = gv_fetchpvs("__ANON__", gv_fetch_flags, SVt_PVCV);
11622         has_name = FALSE;
11623     } else {
11624         gv = gv_fetchpvs("__ANON__::__ANON__", gv_fetch_flags, SVt_PVCV);
11625         has_name = FALSE;
11626     }
11627
11628     if (!ec) {
11629         if (isGV(gv)) {
11630             move_proto_attr(&proto, &attrs, gv, 0);
11631         } else {
11632             assert(cSVOPo);
11633             move_proto_attr(&proto, &attrs, (GV *)cSVOPo->op_sv, 1);
11634         }
11635     }
11636
11637     if (proto) {
11638         assert(proto->op_type == OP_CONST);
11639         ps = SvPV_const(((SVOP*)proto)->op_sv, ps_len);
11640         ps_utf8 = SvUTF8(((SVOP*)proto)->op_sv);
11641     }
11642     else
11643         ps = NULL;
11644
11645     if (o)
11646         SAVEFREEOP(o);
11647     if (proto)
11648         SAVEFREEOP(proto);
11649     if (attrs)
11650         SAVEFREEOP(attrs);
11651
11652     if (ec) {
11653         op_free(block);
11654
11655         if (name)
11656             SvREFCNT_dec(PL_compcv);
11657         else
11658             cv = PL_compcv;
11659
11660         PL_compcv = 0;
11661         if (name && block) {
11662             const char *s = (char *) my_memrchr(name, ':', namlen);
11663             s = s ? s+1 : name;
11664             if (strEQ(s, "BEGIN")) {
11665                 if (PL_in_eval & EVAL_KEEPERR)
11666                     Perl_croak_nocontext("BEGIN not safe after errors--compilation aborted");
11667                 else {
11668                     SV * const errsv = ERRSV;
11669                     /* force display of errors found but not reported */
11670                     sv_catpvs(errsv, "BEGIN not safe after errors--compilation aborted");
11671                     Perl_croak_nocontext("%" SVf, SVfARG(errsv));
11672                 }
11673             }
11674         }
11675         goto done;
11676     }
11677
11678     if (!block && SvTYPE(gv) != SVt_PVGV) {
11679         /* If we are not defining a new sub and the existing one is not a
11680            full GV + CV... */
11681         if (attrs || (CvFLAGS(PL_compcv) & CVf_BUILTIN_ATTRS)) {
11682             /* We are applying attributes to an existing sub, so we need it
11683                upgraded if it is a constant.  */
11684             if (SvROK(gv) && SvTYPE(SvRV(gv)) != SVt_PVCV)
11685                 gv_init_pvn(gv, PL_curstash, name, namlen,
11686                             SVf_UTF8 * name_is_utf8);
11687         }
11688         else {                  /* Maybe prototype now, and had at maximum
11689                                    a prototype or const/sub ref before.  */
11690             if (SvTYPE(gv) > SVt_NULL) {
11691                 cv_ckproto_len_flags((const CV *)gv,
11692                                     o ? (const GV *)cSVOPo->op_sv : NULL, ps,
11693                                     ps_len, ps_utf8);
11694             }
11695
11696             if (!SvROK(gv)) {
11697                 if (ps) {
11698                     sv_setpvn(MUTABLE_SV(gv), ps, ps_len);
11699                     if (ps_utf8)
11700                         SvUTF8_on(MUTABLE_SV(gv));
11701                 }
11702                 else
11703                     sv_setiv(MUTABLE_SV(gv), -1);
11704             }
11705
11706             SvREFCNT_dec(PL_compcv);
11707             cv = PL_compcv = NULL;
11708             goto done;
11709         }
11710     }
11711
11712     cv = (!name || (isGV(gv) && GvCVGEN(gv)))
11713         ? NULL
11714         : isGV(gv)
11715             ? GvCV(gv)
11716             : SvROK(gv) && SvTYPE(SvRV(gv)) == SVt_PVCV
11717                 ? (CV *)SvRV(gv)
11718                 : NULL;
11719
11720     if (block) {
11721         assert(PL_parser);
11722         /* This makes sub {}; work as expected.  */
11723         if (block->op_type == OP_STUB) {
11724             const line_t l = PL_parser->copline;
11725             op_free(block);
11726             block = newSTATEOP(0, NULL, 0);
11727             PL_parser->copline = l;
11728         }
11729         block = CvLVALUE(PL_compcv)
11730              || (cv && CvLVALUE(cv) && !CvROOT(cv) && !CvXSUB(cv)
11731                     && (!isGV(gv) || !GvASSUMECV(gv)))
11732                    ? newUNOP(OP_LEAVESUBLV, 0,
11733                              op_lvalue(voidnonfinal(block), OP_LEAVESUBLV))
11734                    : newUNOP(OP_LEAVESUB, 0, voidnonfinal(block));
11735         start = LINKLIST(block);
11736         block->op_next = 0;
11737         if (ps && !*ps && !attrs && !CvLVALUE(PL_compcv))
11738             const_sv =
11739                 S_op_const_sv(aTHX_ start, PL_compcv,
11740                                         cBOOL(CvCLONE(PL_compcv)));
11741         else
11742             const_sv = NULL;
11743     }
11744     else
11745         const_sv = NULL;
11746
11747     if (SvPOK(gv) || (SvROK(gv) && SvTYPE(SvRV(gv)) != SVt_PVCV)) {
11748         cv_ckproto_len_flags((const CV *)gv,
11749                              o ? (const GV *)cSVOPo->op_sv : NULL, ps,
11750                              ps_len, ps_utf8|CV_CKPROTO_CURSTASH);
11751         if (SvROK(gv)) {
11752             /* All the other code for sub redefinition warnings expects the
11753                clobbered sub to be a CV.  Instead of making all those code
11754                paths more complex, just inline the RV version here.  */
11755             const line_t oldline = CopLINE(PL_curcop);
11756             assert(IN_PERL_COMPILETIME);
11757             if (PL_parser && PL_parser->copline != NOLINE)
11758                 /* This ensures that warnings are reported at the first
11759                    line of a redefinition, not the last.  */
11760                 CopLINE_set(PL_curcop, PL_parser->copline);
11761             /* protect against fatal warnings leaking compcv */
11762             SAVEFREESV(PL_compcv);
11763
11764             if (ckWARN(WARN_REDEFINE)
11765              || (  ckWARN_d(WARN_REDEFINE)
11766                 && (  !const_sv || SvRV(gv) == const_sv
11767                    || sv_cmp(SvRV(gv), const_sv)  ))) {
11768                 assert(cSVOPo);
11769                 Perl_warner(aTHX_ packWARN(WARN_REDEFINE),
11770                           "Constant subroutine %" SVf " redefined",
11771                           SVfARG(cSVOPo->op_sv));
11772             }
11773
11774             SvREFCNT_inc_simple_void_NN(PL_compcv);
11775             CopLINE_set(PL_curcop, oldline);
11776             SvREFCNT_dec(SvRV(gv));
11777         }
11778     }
11779
11780     if (cv) {
11781         const bool exists = CvROOT(cv) || CvXSUB(cv);
11782
11783         /* if the subroutine doesn't exist and wasn't pre-declared
11784          * with a prototype, assume it will be AUTOLOADed,
11785          * skipping the prototype check
11786          */
11787         if (exists || SvPOK(cv))
11788             cv_ckproto_len_flags(cv, gv, ps, ps_len, ps_utf8);
11789         /* already defined (or promised)? */
11790         if (exists || (isGV(gv) && GvASSUMECV(gv))) {
11791             S_already_defined(aTHX_ cv, block, o, NULL, &const_sv);
11792             if (block)
11793                 cv = NULL;
11794             else {
11795                 if (attrs)
11796                     goto attrs;
11797                 /* just a "sub foo;" when &foo is already defined */
11798                 SAVEFREESV(PL_compcv);
11799                 goto done;
11800             }
11801         }
11802     }
11803
11804     if (const_sv) {
11805         SvREFCNT_inc_simple_void_NN(const_sv);
11806         SvFLAGS(const_sv) |= SVs_PADTMP;
11807         if (cv) {
11808             assert(!CvROOT(cv) && !CvCONST(cv));
11809             cv_forget_slab(cv);
11810             SvPVCLEAR(MUTABLE_SV(cv));  /* prototype is "" */
11811             CvXSUBANY(cv).any_ptr = const_sv;
11812             CvXSUB(cv) = const_sv_xsub;
11813             CvCONST_on(cv);
11814             CvISXSUB_on(cv);
11815             PoisonPADLIST(cv);
11816             CvFLAGS(cv) |= CvMETHOD(PL_compcv);
11817         }
11818         else {
11819             if (isGV(gv) || CvMETHOD(PL_compcv)) {
11820                 if (name && isGV(gv))
11821                     GvCV_set(gv, NULL);
11822                 cv = newCONSTSUB_flags(
11823                     NULL, name, namlen, name_is_utf8 ? SVf_UTF8 : 0,
11824                     const_sv
11825                 );
11826                 assert(cv);
11827                 assert(SvREFCNT((SV*)cv) != 0);
11828                 CvFLAGS(cv) |= CvMETHOD(PL_compcv);
11829             }
11830             else {
11831                 if (!SvROK(gv)) {
11832                     SV_CHECK_THINKFIRST_COW_DROP((SV *)gv);
11833                     prepare_SV_for_RV((SV *)gv);
11834                     SvOK_off((SV *)gv);
11835                     SvROK_on(gv);
11836                 }
11837                 SvRV_set(gv, const_sv);
11838             }
11839         }
11840         op_free(block);
11841         SvREFCNT_dec(PL_compcv);
11842         PL_compcv = NULL;
11843         goto done;
11844     }
11845
11846     /* don't copy new BEGIN CV to old BEGIN CV - RT #129099 */
11847     if (name && cv && *name == 'B' && strEQ(name, "BEGIN"))
11848         cv = NULL;
11849
11850     if (cv) {                           /* must reuse cv if autoloaded */
11851         /* transfer PL_compcv to cv */
11852         if (block) {
11853             bool free_file = CvFILE(cv) && CvDYNFILE(cv);
11854             cv_flags_t existing_builtin_attrs = CvFLAGS(cv) & CVf_BUILTIN_ATTRS;
11855             PADLIST *const temp_av = CvPADLIST(cv);
11856             CV *const temp_cv = CvOUTSIDE(cv);
11857             const cv_flags_t other_flags =
11858                 CvFLAGS(cv) & (CVf_SLABBED|CVf_WEAKOUTSIDE);
11859             OP * const cvstart = CvSTART(cv);
11860
11861             if (isGV(gv)) {
11862                 CvGV_set(cv,gv);
11863                 assert(!CvCVGV_RC(cv));
11864                 assert(CvGV(cv) == gv);
11865             }
11866             else {
11867                 U32 hash;
11868                 PERL_HASH(hash, name, namlen);
11869                 CvNAME_HEK_set(cv,
11870                                share_hek(name,
11871                                          name_is_utf8
11872                                             ? -(SSize_t)namlen
11873                                             :  (SSize_t)namlen,
11874                                          hash));
11875             }
11876
11877             SvPOK_off(cv);
11878             CvFLAGS(cv) = CvFLAGS(PL_compcv) | existing_builtin_attrs
11879                                              | CvNAMED(cv);
11880             CvOUTSIDE(cv) = CvOUTSIDE(PL_compcv);
11881             CvOUTSIDE_SEQ(cv) = CvOUTSIDE_SEQ(PL_compcv);
11882             CvPADLIST_set(cv,CvPADLIST(PL_compcv));
11883             CvOUTSIDE(PL_compcv) = temp_cv;
11884             CvPADLIST_set(PL_compcv, temp_av);
11885             CvSTART(cv) = CvSTART(PL_compcv);
11886             CvSTART(PL_compcv) = cvstart;
11887             CvFLAGS(PL_compcv) &= ~(CVf_SLABBED|CVf_WEAKOUTSIDE);
11888             CvFLAGS(PL_compcv) |= other_flags;
11889
11890             if (free_file) {
11891                 Safefree(CvFILE(cv));
11892             }
11893             CvFILE_set_from_cop(cv, PL_curcop);
11894             CvSTASH_set(cv, PL_curstash);
11895
11896             /* inner references to PL_compcv must be fixed up ... */
11897             pad_fixup_inner_anons(CvPADLIST(cv), PL_compcv, cv);
11898             if (PERLDB_INTER)/* Advice debugger on the new sub. */
11899                 ++PL_sub_generation;
11900         }
11901         else {
11902             /* Might have had built-in attributes applied -- propagate them. */
11903             CvFLAGS(cv) |= (CvFLAGS(PL_compcv) & CVf_BUILTIN_ATTRS);
11904         }
11905         /* ... before we throw it away */
11906         SvREFCNT_dec(PL_compcv);
11907         PL_compcv = cv;
11908     }
11909     else {
11910         cv = PL_compcv;
11911         if (name && isGV(gv)) {
11912             GvCV_set(gv, cv);
11913             GvCVGEN(gv) = 0;
11914             if (HvENAME_HEK(GvSTASH(gv)))
11915                 /* sub Foo::bar { (shift)+1 } */
11916                 gv_method_changed(gv);
11917         }
11918         else if (name) {
11919             if (!SvROK(gv)) {
11920                 SV_CHECK_THINKFIRST_COW_DROP((SV *)gv);
11921                 prepare_SV_for_RV((SV *)gv);
11922                 SvOK_off((SV *)gv);
11923                 SvROK_on(gv);
11924             }
11925             SvRV_set(gv, (SV *)cv);
11926             if (HvENAME_HEK(PL_curstash))
11927                 mro_method_changed_in(PL_curstash);
11928         }
11929     }
11930     assert(cv);
11931     assert(SvREFCNT((SV*)cv) != 0);
11932
11933     if (!CvHASGV(cv)) {
11934         if (isGV(gv))
11935             CvGV_set(cv, gv);
11936         else {
11937             U32 hash;
11938             PERL_HASH(hash, name, namlen);
11939             CvNAME_HEK_set(cv, share_hek(name,
11940                                          name_is_utf8
11941                                             ? -(SSize_t)namlen
11942                                             :  (SSize_t)namlen,
11943                                          hash));
11944         }
11945         CvFILE_set_from_cop(cv, PL_curcop);
11946         CvSTASH_set(cv, PL_curstash);
11947     }
11948
11949     if (ps) {
11950         sv_setpvn(MUTABLE_SV(cv), ps, ps_len);
11951         if ( ps_utf8 )
11952             SvUTF8_on(MUTABLE_SV(cv));
11953     }
11954
11955     if (block) {
11956         /* If we assign an optree to a PVCV, then we've defined a
11957          * subroutine that the debugger could be able to set a breakpoint
11958          * in, so signal to pp_entereval that it should not throw away any
11959          * saved lines at scope exit.  */
11960
11961         PL_breakable_sub_gen++;
11962         CvROOT(cv) = block;
11963         /* The cv no longer needs to hold a refcount on the slab, as CvROOT
11964            itself has a refcount. */
11965         CvSLABBED_off(cv);
11966         OpslabREFCNT_dec_padok((OPSLAB *)CvSTART(cv));
11967 #ifdef PERL_DEBUG_READONLY_OPS
11968         slab = (OPSLAB *)CvSTART(cv);
11969 #endif
11970         S_process_optree(aTHX_ cv, block, start);
11971     }
11972
11973   attrs:
11974     if (attrs) {
11975         /* Need to do a C<use attributes $stash_of_cv,\&cv,@attrs>. */
11976         HV *stash = name && !CvNAMED(cv) && GvSTASH(CvGV(cv))
11977                         ? GvSTASH(CvGV(cv))
11978                         : PL_curstash;
11979         if (!name)
11980             SAVEFREESV(cv);
11981         apply_attrs(stash, MUTABLE_SV(cv), attrs);
11982         if (!name)
11983             SvREFCNT_inc_simple_void_NN(cv);
11984     }
11985
11986     if (block && has_name) {
11987         if (PERLDB_SUBLINE && PL_curstash != PL_debstash) {
11988             SV * const tmpstr = cv_name(cv,NULL,0);
11989             GV * const db_postponed = gv_fetchpvs("DB::postponed",
11990                                                   GV_ADDMULTI, SVt_PVHV);
11991             HV *hv;
11992             SV * const sv = Perl_newSVpvf(aTHX_ "%s:%ld-%ld",
11993                                           CopFILE(PL_curcop),
11994                                           (long)PL_subline,
11995                                           (long)CopLINE(PL_curcop));
11996             (void)hv_store_ent(GvHV(PL_DBsub), tmpstr, sv, 0);
11997             hv = GvHVn(db_postponed);
11998             if (HvTOTALKEYS(hv) > 0 && hv_exists_ent(hv, tmpstr, 0)) {
11999                 CV * const pcv = GvCV(db_postponed);
12000                 if (pcv) {
12001                     dSP;
12002                     PUSHMARK(SP);
12003                     XPUSHs(tmpstr);
12004                     PUTBACK;
12005                     call_sv(MUTABLE_SV(pcv), G_DISCARD);
12006                 }
12007             }
12008         }
12009
12010         if (name) {
12011             if (PL_parser && PL_parser->error_count)
12012                 clear_special_blocks(name, gv, cv);
12013             else
12014                 evanescent =
12015                     process_special_blocks(floor, name, gv, cv);
12016         }
12017     }
12018     assert(cv);
12019
12020   done:
12021     assert(!cv || evanescent || SvREFCNT((SV*)cv) != 0);
12022     if (PL_parser)
12023         PL_parser->copline = NOLINE;
12024     LEAVE_SCOPE(floor);
12025
12026     assert(!cv || evanescent || SvREFCNT((SV*)cv) != 0);
12027     if (!evanescent) {
12028 #ifdef PERL_DEBUG_READONLY_OPS
12029     if (slab)
12030         Slab_to_ro(slab);
12031 #endif
12032     if (cv && name && block && CvOUTSIDE(cv) && !CvEVAL(CvOUTSIDE(cv)))
12033         pad_add_weakref(cv);
12034     }
12035     return cv;
12036 }
12037
12038 STATIC void
12039 S_clear_special_blocks(pTHX_ const char *const fullname,
12040                        GV *const gv, CV *const cv) {
12041     const char *colon;
12042     const char *name;
12043
12044     PERL_ARGS_ASSERT_CLEAR_SPECIAL_BLOCKS;
12045
12046     colon = strrchr(fullname,':');
12047     name = colon ? colon + 1 : fullname;
12048
12049     if ((*name == 'B' && strEQ(name, "BEGIN"))
12050         || (*name == 'E' && strEQ(name, "END"))
12051         || (*name == 'U' && strEQ(name, "UNITCHECK"))
12052         || (*name == 'C' && strEQ(name, "CHECK"))
12053         || (*name == 'I' && strEQ(name, "INIT"))) {
12054         if (!isGV(gv)) {
12055             (void)CvGV(cv);
12056             assert(isGV(gv));
12057         }
12058         GvCV_set(gv, NULL);
12059         SvREFCNT_dec_NN(MUTABLE_SV(cv));
12060     }
12061 }
12062
12063 /* Returns true if the sub has been freed.  */
12064 STATIC bool
12065 S_process_special_blocks(pTHX_ I32 floor, const char *const fullname,
12066                          GV *const gv,
12067                          CV *const cv)
12068 {
12069     const char *const colon = strrchr(fullname,':');
12070     const char *const name = colon ? colon + 1 : fullname;
12071
12072     PERL_ARGS_ASSERT_PROCESS_SPECIAL_BLOCKS;
12073
12074     if (*name == 'B') {
12075         if (strEQ(name, "BEGIN")) {
12076             const I32 oldscope = PL_scopestack_ix;
12077             dSP;
12078             (void)CvGV(cv);
12079             if (floor) LEAVE_SCOPE(floor);
12080             ENTER;
12081
12082             SAVEVPTR(PL_curcop);
12083             if (PL_curcop == &PL_compiling) {
12084                 /* Avoid pushing the "global" &PL_compiling onto the
12085                  * context stack. For example, a stack trace inside
12086                  * nested use's would show all calls coming from whoever
12087                  * most recently updated PL_compiling.cop_file and
12088                  * cop_line.  So instead, temporarily set PL_curcop to a
12089                  * private copy of &PL_compiling. PL_curcop will soon be
12090                  * set to point back to &PL_compiling anyway but only
12091                  * after the temp value has been pushed onto the context
12092                  * stack as blk_oldcop.
12093                  * This is slightly hacky, but necessary. Note also
12094                  * that in the brief window before PL_curcop is set back
12095                  * to PL_compiling, IN_PERL_COMPILETIME/IN_PERL_RUNTIME
12096                  * will give the wrong answer.
12097                  */
12098                 PL_curcop = (COP*)newSTATEOP(PL_compiling.op_flags, NULL, NULL);
12099                 CopLINE_set(PL_curcop, CopLINE(&PL_compiling));
12100                 SAVEFREEOP(PL_curcop);
12101             }
12102
12103             PUSHSTACKi(PERLSI_REQUIRE);
12104             SAVECOPFILE(&PL_compiling);
12105             SAVECOPLINE(&PL_compiling);
12106
12107             DEBUG_x( dump_sub(gv) );
12108             Perl_av_create_and_push(aTHX_ &PL_beginav, MUTABLE_SV(cv));
12109             GvCV_set(gv,0);             /* cv has been hijacked */
12110             call_list(oldscope, PL_beginav);
12111
12112             POPSTACK;
12113             LEAVE;
12114             return !PL_savebegin;
12115         }
12116         else
12117             return FALSE;
12118     } else {
12119         if (*name == 'E') {
12120             if (strEQ(name, "END")) {
12121                 DEBUG_x( dump_sub(gv) );
12122                 Perl_av_create_and_unshift_one(aTHX_ &PL_endav, MUTABLE_SV(cv));
12123             } else
12124                 return FALSE;
12125         } else if (*name == 'U') {
12126             if (strEQ(name, "UNITCHECK")) {
12127                 /* It's never too late to run a unitcheck block */
12128                 Perl_av_create_and_unshift_one(aTHX_ &PL_unitcheckav, MUTABLE_SV(cv));
12129             }
12130             else
12131                 return FALSE;
12132         } else if (*name == 'C') {
12133             if (strEQ(name, "CHECK")) {
12134                 if (PL_main_start)
12135                     /* diag_listed_as: Too late to run %s block */
12136                     Perl_ck_warner(aTHX_ packWARN(WARN_VOID),
12137                                    "Too late to run CHECK block");
12138                 Perl_av_create_and_unshift_one(aTHX_ &PL_checkav, MUTABLE_SV(cv));
12139             }
12140             else
12141                 return FALSE;
12142         } else if (*name == 'I') {
12143             if (strEQ(name, "INIT")) {
12144                 if (PL_main_start)
12145                     /* diag_listed_as: Too late to run %s block */
12146                     Perl_ck_warner(aTHX_ packWARN(WARN_VOID),
12147                                    "Too late to run INIT block");
12148                 Perl_av_create_and_push(aTHX_ &PL_initav, MUTABLE_SV(cv));
12149             }
12150             else
12151                 return FALSE;
12152         } else
12153             return FALSE;
12154         DEBUG_x( dump_sub(gv) );
12155         (void)CvGV(cv);
12156         GvCV_set(gv,0);         /* cv has been hijacked */
12157         return FALSE;
12158     }
12159 }
12160
12161 /*
12162 =for apidoc newCONSTSUB
12163
12164 Behaves like L</newCONSTSUB_flags>, except that C<name> is nul-terminated
12165 rather than of counted length, and no flags are set.  (This means that
12166 C<name> is always interpreted as Latin-1.)
12167
12168 =cut
12169 */
12170
12171 CV *
12172 Perl_newCONSTSUB(pTHX_ HV *stash, const char *name, SV *sv)
12173 {
12174     return newCONSTSUB_flags(stash, name, name ? strlen(name) : 0, 0, sv);
12175 }
12176
12177 /*
12178 =for apidoc newCONSTSUB_flags
12179
12180 Construct a constant subroutine, also performing some surrounding
12181 jobs.  A scalar constant-valued subroutine is eligible for inlining
12182 at compile-time, and in Perl code can be created by S<C<sub FOO () {
12183 123 }>>.  Other kinds of constant subroutine have other treatment.
12184
12185 The subroutine will have an empty prototype and will ignore any arguments
12186 when called.  Its constant behaviour is determined by C<sv>.  If C<sv>
12187 is null, the subroutine will yield an empty list.  If C<sv> points to a
12188 scalar, the subroutine will always yield that scalar.  If C<sv> points
12189 to an array, the subroutine will always yield a list of the elements of
12190 that array in list context, or the number of elements in the array in
12191 scalar context.  This function takes ownership of one counted reference
12192 to the scalar or array, and will arrange for the object to live as long
12193 as the subroutine does.  If C<sv> points to a scalar then the inlining
12194 assumes that the value of the scalar will never change, so the caller
12195 must ensure that the scalar is not subsequently written to.  If C<sv>
12196 points to an array then no such assumption is made, so it is ostensibly
12197 safe to mutate the array or its elements, but whether this is really
12198 supported has not been determined.
12199
12200 The subroutine will have C<CvFILE> set according to C<PL_curcop>.
12201 Other aspects of the subroutine will be left in their default state.
12202 The caller is free to mutate the subroutine beyond its initial state
12203 after this function has returned.
12204
12205 If C<name> is null then the subroutine will be anonymous, with its
12206 C<CvGV> referring to an C<__ANON__> glob.  If C<name> is non-null then the
12207 subroutine will be named accordingly, referenced by the appropriate glob.
12208 C<name> is a string of length C<len> bytes giving a sigilless symbol
12209 name, in UTF-8 if C<flags> has the C<SVf_UTF8> bit set and in Latin-1
12210 otherwise.  The name may be either qualified or unqualified.  If the
12211 name is unqualified then it defaults to being in the stash specified by
12212 C<stash> if that is non-null, or to C<PL_curstash> if C<stash> is null.
12213 The symbol is always added to the stash if necessary, with C<GV_ADDMULTI>
12214 semantics.
12215
12216 C<flags> should not have bits set other than C<SVf_UTF8>.
12217
12218 If there is already a subroutine of the specified name, then the new sub
12219 will replace the existing one in the glob.  A warning may be generated
12220 about the redefinition.
12221
12222 If the subroutine has one of a few special names, such as C<BEGIN> or
12223 C<END>, then it will be claimed by the appropriate queue for automatic
12224 running of phase-related subroutines.  In this case the relevant glob will
12225 be left not containing any subroutine, even if it did contain one before.
12226 Execution of the subroutine will likely be a no-op, unless C<sv> was
12227 a tied array or the caller modified the subroutine in some interesting
12228 way before it was executed.  In the case of C<BEGIN>, the treatment is
12229 buggy: the sub will be executed when only half built, and may be deleted
12230 prematurely, possibly causing a crash.
12231
12232 The function returns a pointer to the constructed subroutine.  If the sub
12233 is anonymous then ownership of one counted reference to the subroutine
12234 is transferred to the caller.  If the sub is named then the caller does
12235 not get ownership of a reference.  In most such cases, where the sub
12236 has a non-phase name, the sub will be alive at the point it is returned
12237 by virtue of being contained in the glob that names it.  A phase-named
12238 subroutine will usually be alive by virtue of the reference owned by
12239 the phase's automatic run queue.  A C<BEGIN> subroutine may have been
12240 destroyed already by the time this function returns, but currently bugs
12241 occur in that case before the caller gets control.  It is the caller's
12242 responsibility to ensure that it knows which of these situations applies.
12243
12244 =cut
12245 */
12246
12247 CV *
12248 Perl_newCONSTSUB_flags(pTHX_ HV *stash, const char *name, STRLEN len,
12249                              U32 flags, SV *sv)
12250 {
12251     CV* cv;
12252     const char *const file = CopFILE(PL_curcop);
12253
12254     ENTER;
12255
12256     if (IN_PERL_RUNTIME) {
12257         /* at runtime, it's not safe to manipulate PL_curcop: it may be
12258          * an op shared between threads. Use a non-shared COP for our
12259          * dirty work */
12260          SAVEVPTR(PL_curcop);
12261          SAVECOMPILEWARNINGS();
12262          PL_compiling.cop_warnings = DUP_WARNINGS(PL_curcop->cop_warnings);
12263          PL_curcop = &PL_compiling;
12264     }
12265     SAVECOPLINE(PL_curcop);
12266     CopLINE_set(PL_curcop, PL_parser ? PL_parser->copline : NOLINE);
12267
12268     SAVEHINTS();
12269     PL_hints &= ~HINT_BLOCK_SCOPE;
12270
12271     if (stash) {
12272         SAVEGENERICSV(PL_curstash);
12273         PL_curstash = (HV *)SvREFCNT_inc_simple_NN(stash);
12274     }
12275
12276     /* Protect sv against leakage caused by fatal warnings. */
12277     if (sv) SAVEFREESV(sv);
12278
12279     /* file becomes the CvFILE. For an XS, it's usually static storage,
12280        and so doesn't get free()d.  (It's expected to be from the C pre-
12281        processor __FILE__ directive). But we need a dynamically allocated one,
12282        and we need it to get freed.  */
12283     cv = newXS_len_flags(name, len,
12284                          sv && SvTYPE(sv) == SVt_PVAV
12285                              ? const_av_xsub
12286                              : const_sv_xsub,
12287                          file ? file : "", "",
12288                          &sv, XS_DYNAMIC_FILENAME | flags);
12289     assert(cv);
12290     assert(SvREFCNT((SV*)cv) != 0);
12291     CvXSUBANY(cv).any_ptr = SvREFCNT_inc_simple(sv);
12292     CvCONST_on(cv);
12293
12294     LEAVE;
12295
12296     return cv;
12297 }
12298
12299 /*
12300 =for apidoc newXS
12301
12302 Used by C<xsubpp> to hook up XSUBs as Perl subs.  C<filename> needs to be
12303 static storage, as it is used directly as CvFILE(), without a copy being made.
12304
12305 =cut
12306 */
12307
12308 CV *
12309 Perl_newXS(pTHX_ const char *name, XSUBADDR_t subaddr, const char *filename)
12310 {
12311     PERL_ARGS_ASSERT_NEWXS;
12312     return newXS_len_flags(
12313         name, name ? strlen(name) : 0, subaddr, filename, NULL, NULL, 0
12314     );
12315 }
12316
12317 CV *
12318 Perl_newXS_flags(pTHX_ const char *name, XSUBADDR_t subaddr,
12319                  const char *const filename, const char *const proto,
12320                  U32 flags)
12321 {
12322     PERL_ARGS_ASSERT_NEWXS_FLAGS;
12323     return newXS_len_flags(
12324        name, name ? strlen(name) : 0, subaddr, filename, proto, NULL, flags
12325     );
12326 }
12327
12328 CV *
12329 Perl_newXS_deffile(pTHX_ const char *name, XSUBADDR_t subaddr)
12330 {
12331     PERL_ARGS_ASSERT_NEWXS_DEFFILE;
12332     return newXS_len_flags(
12333         name, strlen(name), subaddr, NULL, NULL, NULL, 0
12334     );
12335 }
12336
12337 /*
12338 =for apidoc newXS_len_flags
12339
12340 Construct an XS subroutine, also performing some surrounding jobs.
12341
12342 The subroutine will have the entry point C<subaddr>.  It will have
12343 the prototype specified by the nul-terminated string C<proto>, or
12344 no prototype if C<proto> is null.  The prototype string is copied;
12345 the caller can mutate the supplied string afterwards.  If C<filename>
12346 is non-null, it must be a nul-terminated filename, and the subroutine
12347 will have its C<CvFILE> set accordingly.  By default C<CvFILE> is set to
12348 point directly to the supplied string, which must be static.  If C<flags>
12349 has the C<XS_DYNAMIC_FILENAME> bit set, then a copy of the string will
12350 be taken instead.
12351
12352 Other aspects of the subroutine will be left in their default state.
12353 If anything else needs to be done to the subroutine for it to function
12354 correctly, it is the caller's responsibility to do that after this
12355 function has constructed it.  However, beware of the subroutine
12356 potentially being destroyed before this function returns, as described
12357 below.
12358
12359 If C<name> is null then the subroutine will be anonymous, with its
12360 C<CvGV> referring to an C<__ANON__> glob.  If C<name> is non-null then the
12361 subroutine will be named accordingly, referenced by the appropriate glob.
12362 C<name> is a string of length C<len> bytes giving a sigilless symbol name,
12363 in UTF-8 if C<flags> has the C<SVf_UTF8> bit set and in Latin-1 otherwise.
12364 The name may be either qualified or unqualified, with the stash defaulting
12365 in the same manner as for C<gv_fetchpvn_flags>.  C<flags> may contain
12366 flag bits understood by C<gv_fetchpvn_flags> with the same meaning as
12367 they have there, such as C<GV_ADDWARN>.  The symbol is always added to
12368 the stash if necessary, with C<GV_ADDMULTI> semantics.
12369
12370 If there is already a subroutine of the specified name, then the new sub
12371 will replace the existing one in the glob.  A warning may be generated
12372 about the redefinition.  If the old subroutine was C<CvCONST> then the
12373 decision about whether to warn is influenced by an expectation about
12374 whether the new subroutine will become a constant of similar value.
12375 That expectation is determined by C<const_svp>.  (Note that the call to
12376 this function doesn't make the new subroutine C<CvCONST> in any case;
12377 that is left to the caller.)  If C<const_svp> is null then it indicates
12378 that the new subroutine will not become a constant.  If C<const_svp>
12379 is non-null then it indicates that the new subroutine will become a
12380 constant, and it points to an C<SV*> that provides the constant value
12381 that the subroutine will have.
12382
12383 If the subroutine has one of a few special names, such as C<BEGIN> or
12384 C<END>, then it will be claimed by the appropriate queue for automatic
12385 running of phase-related subroutines.  In this case the relevant glob will
12386 be left not containing any subroutine, even if it did contain one before.
12387 In the case of C<BEGIN>, the subroutine will be executed and the reference
12388 to it disposed of before this function returns, and also before its
12389 prototype is set.  If a C<BEGIN> subroutine would not be sufficiently
12390 constructed by this function to be ready for execution then the caller
12391 must prevent this happening by giving the subroutine a different name.
12392
12393 The function returns a pointer to the constructed subroutine.  If the sub
12394 is anonymous then ownership of one counted reference to the subroutine
12395 is transferred to the caller.  If the sub is named then the caller does
12396 not get ownership of a reference.  In most such cases, where the sub
12397 has a non-phase name, the sub will be alive at the point it is returned
12398 by virtue of being contained in the glob that names it.  A phase-named
12399 subroutine will usually be alive by virtue of the reference owned by the
12400 phase's automatic run queue.  But a C<BEGIN> subroutine, having already
12401 been executed, will quite likely have been destroyed already by the
12402 time this function returns, making it erroneous for the caller to make
12403 any use of the returned pointer.  It is the caller's responsibility to
12404 ensure that it knows which of these situations applies.
12405
12406 =cut
12407 */
12408
12409 CV *
12410 Perl_newXS_len_flags(pTHX_ const char *name, STRLEN len,
12411                            XSUBADDR_t subaddr, const char *const filename,
12412                            const char *const proto, SV **const_svp,
12413                            U32 flags)
12414 {
12415     CV *cv;
12416     bool interleave = FALSE;
12417     bool evanescent = FALSE;
12418
12419     PERL_ARGS_ASSERT_NEWXS_LEN_FLAGS;
12420
12421     {
12422         GV * const gv = gv_fetchpvn(
12423                             name ? name : PL_curstash ? "__ANON__" : "__ANON__::__ANON__",
12424                             name ? len : PL_curstash ? sizeof("__ANON__") - 1:
12425                                 sizeof("__ANON__::__ANON__") - 1,
12426                             GV_ADDMULTI | flags, SVt_PVCV);
12427
12428         if ((cv = (name ? GvCV(gv) : NULL))) {
12429             if (GvCVGEN(gv)) {
12430                 /* just a cached method */
12431                 SvREFCNT_dec(cv);
12432                 cv = NULL;
12433             }
12434             else if (CvROOT(cv) || CvXSUB(cv) || GvASSUMECV(gv)) {
12435                 /* already defined (or promised) */
12436                 /* Redundant check that allows us to avoid creating an SV
12437                    most of the time: */
12438                 if (CvCONST(cv) || ckWARN(WARN_REDEFINE)) {
12439                     report_redefined_cv(newSVpvn_flags(
12440                                          name,len,(flags&SVf_UTF8)|SVs_TEMP
12441                                         ),
12442                                         cv, const_svp);
12443                 }
12444                 interleave = TRUE;
12445                 ENTER;
12446                 SAVEFREESV(cv);
12447                 cv = NULL;
12448             }
12449         }
12450
12451         if (cv)                         /* must reuse cv if autoloaded */
12452             cv_undef(cv);
12453         else {
12454             cv = MUTABLE_CV(newSV_type(SVt_PVCV));
12455             if (name) {
12456                 GvCV_set(gv,cv);
12457                 GvCVGEN(gv) = 0;
12458                 if (HvENAME_HEK(GvSTASH(gv)))
12459                     gv_method_changed(gv); /* newXS */
12460             }
12461         }
12462         assert(cv);
12463         assert(SvREFCNT((SV*)cv) != 0);
12464
12465         CvGV_set(cv, gv);
12466         if(filename) {
12467             /* XSUBs can't be perl lang/perl5db.pl debugged
12468             if (PERLDB_LINE_OR_SAVESRC)
12469                 (void)gv_fetchfile(filename); */
12470             assert(!CvDYNFILE(cv)); /* cv_undef should have turned it off */
12471             if (flags & XS_DYNAMIC_FILENAME) {
12472                 CvDYNFILE_on(cv);
12473                 CvFILE(cv) = savepv(filename);
12474             } else {
12475             /* NOTE: not copied, as it is expected to be an external constant string */
12476                 CvFILE(cv) = (char *)filename;
12477             }
12478         } else {
12479             assert((flags & XS_DYNAMIC_FILENAME) == 0 && PL_xsubfilename);
12480             CvFILE(cv) = (char*)PL_xsubfilename;
12481         }
12482         CvISXSUB_on(cv);
12483         CvXSUB(cv) = subaddr;
12484 #ifndef MULTIPLICITY
12485         CvHSCXT(cv) = &PL_stack_sp;
12486 #else
12487         PoisonPADLIST(cv);
12488 #endif
12489
12490         if (name)
12491             evanescent = process_special_blocks(0, name, gv, cv);
12492         else
12493             CvANON_on(cv);
12494     } /* <- not a conditional branch */
12495
12496     assert(cv);
12497     assert(evanescent || SvREFCNT((SV*)cv) != 0);
12498
12499     if (!evanescent) sv_setpv(MUTABLE_SV(cv), proto);
12500     if (interleave) LEAVE;
12501     assert(evanescent || SvREFCNT((SV*)cv) != 0);
12502     return cv;
12503 }
12504
12505 /* Add a stub CV to a typeglob.
12506  * This is the implementation of a forward declaration, 'sub foo';'
12507  */
12508
12509 CV *
12510 Perl_newSTUB(pTHX_ GV *gv, bool fake)
12511 {
12512     CV *cv = MUTABLE_CV(newSV_type(SVt_PVCV));
12513     GV *cvgv;
12514     PERL_ARGS_ASSERT_NEWSTUB;
12515     assert(!GvCVu(gv));
12516     GvCV_set(gv, cv);
12517     GvCVGEN(gv) = 0;
12518     if (!fake && GvSTASH(gv) && HvENAME_HEK(GvSTASH(gv)))
12519         gv_method_changed(gv);
12520     if (SvFAKE(gv)) {
12521         cvgv = gv_fetchsv((SV *)gv, GV_ADDMULTI, SVt_PVCV);
12522         SvFAKE_off(cvgv);
12523     }
12524     else cvgv = gv;
12525     CvGV_set(cv, cvgv);
12526     CvFILE_set_from_cop(cv, PL_curcop);
12527     CvSTASH_set(cv, PL_curstash);
12528     GvMULTI_on(gv);
12529     return cv;
12530 }
12531
12532 void
12533 Perl_newFORM(pTHX_ I32 floor, OP *o, OP *block)
12534 {
12535     CV *cv;
12536     GV *gv;
12537     OP *root;
12538     OP *start;
12539
12540     if (PL_parser && PL_parser->error_count) {
12541         op_free(block);
12542         goto finish;
12543     }
12544
12545     gv = o
12546         ? gv_fetchsv(cSVOPo->op_sv, GV_ADD, SVt_PVFM)
12547         : gv_fetchpvs("STDOUT", GV_ADD|GV_NOTQUAL, SVt_PVFM);
12548
12549     GvMULTI_on(gv);
12550     if ((cv = GvFORM(gv))) {
12551         if (ckWARN(WARN_REDEFINE)) {
12552             const line_t oldline = CopLINE(PL_curcop);
12553             if (PL_parser && PL_parser->copline != NOLINE)
12554                 CopLINE_set(PL_curcop, PL_parser->copline);
12555             if (o) {
12556                 Perl_warner(aTHX_ packWARN(WARN_REDEFINE),
12557                             "Format %" SVf " redefined", SVfARG(cSVOPo->op_sv));
12558             } else {
12559                 /* diag_listed_as: Format %s redefined */
12560                 Perl_warner(aTHX_ packWARN(WARN_REDEFINE),
12561                             "Format STDOUT redefined");
12562             }
12563             CopLINE_set(PL_curcop, oldline);
12564         }
12565         SvREFCNT_dec(cv);
12566     }
12567     cv = PL_compcv;
12568     GvFORM(gv) = (CV *)SvREFCNT_inc_simple_NN(cv);
12569     CvGV_set(cv, gv);
12570     CvFILE_set_from_cop(cv, PL_curcop);
12571
12572
12573     root = newUNOP(OP_LEAVEWRITE, 0, voidnonfinal(block));
12574     CvROOT(cv) = root;
12575     start = LINKLIST(root);
12576     root->op_next = 0;
12577     S_process_optree(aTHX_ cv, root, start);
12578     cv_forget_slab(cv);
12579
12580   finish:
12581     op_free(o);
12582     if (PL_parser)
12583         PL_parser->copline = NOLINE;
12584     LEAVE_SCOPE(floor);
12585     PL_compiling.cop_seq = 0;
12586 }
12587
12588 OP *
12589 Perl_newANONLIST(pTHX_ OP *o)
12590 {
12591     return op_convert_list(OP_ANONLIST, OPf_SPECIAL, o);
12592 }
12593
12594 OP *
12595 Perl_newANONHASH(pTHX_ OP *o)
12596 {
12597     return op_convert_list(OP_ANONHASH, OPf_SPECIAL, o);
12598 }
12599
12600 OP *
12601 Perl_newANONSUB(pTHX_ I32 floor, OP *proto, OP *block)
12602 {
12603     return newANONATTRSUB(floor, proto, NULL, block);
12604 }
12605
12606 OP *
12607 Perl_newANONATTRSUB(pTHX_ I32 floor, OP *proto, OP *attrs, OP *block)
12608 {
12609     SV * const cv = MUTABLE_SV(newATTRSUB(floor, 0, proto, attrs, block));
12610     OP * anoncode =
12611         newSVOP(OP_ANONCODE, 0,
12612                 cv);
12613     if (CvANONCONST(cv))
12614         anoncode = newUNOP(OP_ANONCONST, 0,
12615                            op_convert_list(OP_ENTERSUB,
12616                                            OPf_STACKED|OPf_WANT_SCALAR,
12617                                            anoncode));
12618     return newUNOP(OP_REFGEN, 0, anoncode);
12619 }
12620
12621 OP *
12622 Perl_oopsAV(pTHX_ OP *o)
12623 {
12624
12625     PERL_ARGS_ASSERT_OOPSAV;
12626
12627     switch (o->op_type) {
12628     case OP_PADSV:
12629     case OP_PADHV:
12630         OpTYPE_set(o, OP_PADAV);
12631         return ref(o, OP_RV2AV);
12632
12633     case OP_RV2SV:
12634     case OP_RV2HV:
12635         OpTYPE_set(o, OP_RV2AV);
12636         ref(o, OP_RV2AV);
12637         break;
12638
12639     default:
12640         Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL), "oops: oopsAV");
12641         break;
12642     }
12643     return o;
12644 }
12645
12646 OP *
12647 Perl_oopsHV(pTHX_ OP *o)
12648 {
12649
12650     PERL_ARGS_ASSERT_OOPSHV;
12651
12652     switch (o->op_type) {
12653     case OP_PADSV:
12654     case OP_PADAV:
12655         OpTYPE_set(o, OP_PADHV);
12656         return ref(o, OP_RV2HV);
12657
12658     case OP_RV2SV:
12659     case OP_RV2AV:
12660         OpTYPE_set(o, OP_RV2HV);
12661         /* rv2hv steals the bottom bit for its own uses */
12662         o->op_private &= ~OPpARG1_MASK;
12663         ref(o, OP_RV2HV);
12664         break;
12665
12666     default:
12667         Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL), "oops: oopsHV");
12668         break;
12669     }
12670     return o;
12671 }
12672
12673 OP *
12674 Perl_newAVREF(pTHX_ OP *o)
12675 {
12676
12677     PERL_ARGS_ASSERT_NEWAVREF;
12678
12679     if (o->op_type == OP_PADANY) {
12680         OpTYPE_set(o, OP_PADAV);
12681         return o;
12682     }
12683     else if ((o->op_type == OP_RV2AV || o->op_type == OP_PADAV)) {
12684         Perl_croak(aTHX_ "Can't use an array as a reference");
12685     }
12686     return newUNOP(OP_RV2AV, 0, scalar(o));
12687 }
12688
12689 OP *
12690 Perl_newGVREF(pTHX_ I32 type, OP *o)
12691 {
12692     if (type == OP_MAPSTART || type == OP_GREPSTART || type == OP_SORT)
12693         return newUNOP(OP_NULL, 0, o);
12694     return ref(newUNOP(OP_RV2GV, OPf_REF, o), type);
12695 }
12696
12697 OP *
12698 Perl_newHVREF(pTHX_ OP *o)
12699 {
12700
12701     PERL_ARGS_ASSERT_NEWHVREF;
12702
12703     if (o->op_type == OP_PADANY) {
12704         OpTYPE_set(o, OP_PADHV);
12705         return o;
12706     }
12707     else if ((o->op_type == OP_RV2HV || o->op_type == OP_PADHV)) {
12708         Perl_croak(aTHX_ "Can't use a hash as a reference");
12709     }
12710     return newUNOP(OP_RV2HV, 0, scalar(o));
12711 }
12712
12713 OP *
12714 Perl_newCVREF(pTHX_ I32 flags, OP *o)
12715 {
12716     if (o->op_type == OP_PADANY) {
12717         OpTYPE_set(o, OP_PADCV);
12718     }
12719     return newUNOP(OP_RV2CV, flags, scalar(o));
12720 }
12721
12722 OP *
12723 Perl_newSVREF(pTHX_ OP *o)
12724 {
12725
12726     PERL_ARGS_ASSERT_NEWSVREF;
12727
12728     if (o->op_type == OP_PADANY) {
12729         OpTYPE_set(o, OP_PADSV);
12730         scalar(o);
12731         return o;
12732     }
12733     return newUNOP(OP_RV2SV, 0, scalar(o));
12734 }
12735
12736 /* Check routines. See the comments at the top of this file for details
12737  * on when these are called */
12738
12739 OP *
12740 Perl_ck_anoncode(pTHX_ OP *o)
12741 {
12742     PERL_ARGS_ASSERT_CK_ANONCODE;
12743
12744     cSVOPo->op_targ = pad_add_anon((CV*)cSVOPo->op_sv, o->op_type);
12745     cSVOPo->op_sv = NULL;
12746     return o;
12747 }
12748
12749 static void
12750 S_io_hints(pTHX_ OP *o)
12751 {
12752 #if O_BINARY != 0 || O_TEXT != 0
12753     HV * const table =
12754         PL_hints & HINT_LOCALIZE_HH ? GvHV(PL_hintgv) : NULL;;
12755     if (table) {
12756         SV **svp = hv_fetchs(table, "open_IN", FALSE);
12757         if (svp && *svp) {
12758             STRLEN len = 0;
12759             const char *d = SvPV_const(*svp, len);
12760             const I32 mode = mode_from_discipline(d, len);
12761             /* bit-and:ing with zero O_BINARY or O_TEXT would be useless. */
12762 #  if O_BINARY != 0
12763             if (mode & O_BINARY)
12764                 o->op_private |= OPpOPEN_IN_RAW;
12765 #  endif
12766 #  if O_TEXT != 0
12767             if (mode & O_TEXT)
12768                 o->op_private |= OPpOPEN_IN_CRLF;
12769 #  endif
12770         }
12771
12772         svp = hv_fetchs(table, "open_OUT", FALSE);
12773         if (svp && *svp) {
12774             STRLEN len = 0;
12775             const char *d = SvPV_const(*svp, len);
12776             const I32 mode = mode_from_discipline(d, len);
12777             /* bit-and:ing with zero O_BINARY or O_TEXT would be useless. */
12778 #  if O_BINARY != 0
12779             if (mode & O_BINARY)
12780                 o->op_private |= OPpOPEN_OUT_RAW;
12781 #  endif
12782 #  if O_TEXT != 0
12783             if (mode & O_TEXT)
12784                 o->op_private |= OPpOPEN_OUT_CRLF;
12785 #  endif
12786         }
12787     }
12788 #else
12789     PERL_UNUSED_CONTEXT;
12790     PERL_UNUSED_ARG(o);
12791 #endif
12792 }
12793
12794 OP *
12795 Perl_ck_backtick(pTHX_ OP *o)
12796 {
12797     GV *gv;
12798     OP *newop = NULL;
12799     OP *sibl;
12800     PERL_ARGS_ASSERT_CK_BACKTICK;
12801     o = ck_fun(o);
12802     /* qx and `` have a null pushmark; CORE::readpipe has only one kid. */
12803     if (o->op_flags & OPf_KIDS && (sibl = OpSIBLING(cUNOPo->op_first))
12804      && (gv = gv_override("readpipe",8)))
12805     {
12806         /* detach rest of siblings from o and its first child */
12807         op_sibling_splice(o, cUNOPo->op_first, -1, NULL);
12808         newop = S_new_entersubop(aTHX_ gv, sibl);
12809     }
12810     else if (!(o->op_flags & OPf_KIDS))
12811         newop = newUNOP(OP_BACKTICK, 0, newDEFSVOP());
12812     if (newop) {
12813         op_free(o);
12814         return newop;
12815     }
12816     S_io_hints(aTHX_ o);
12817     return o;
12818 }
12819
12820 OP *
12821 Perl_ck_bitop(pTHX_ OP *o)
12822 {
12823     PERL_ARGS_ASSERT_CK_BITOP;
12824
12825     /* get rid of arg count and indicate if in the scope of 'use integer' */
12826     o->op_private = (PL_hints & HINT_INTEGER) ? OPpUSEINT : 0;
12827
12828     if (!(o->op_flags & OPf_STACKED) /* Not an assignment */
12829             && OP_IS_INFIX_BIT(o->op_type))
12830     {
12831         const OP * const left = cBINOPo->op_first;
12832         const OP * const right = OpSIBLING(left);
12833         if ((OP_IS_NUMCOMPARE(left->op_type) &&
12834                 (left->op_flags & OPf_PARENS) == 0) ||
12835             (OP_IS_NUMCOMPARE(right->op_type) &&
12836                 (right->op_flags & OPf_PARENS) == 0))
12837             Perl_ck_warner(aTHX_ packWARN(WARN_PRECEDENCE),
12838                           "Possible precedence problem on bitwise %s operator",
12839                            o->op_type ==  OP_BIT_OR
12840                          ||o->op_type == OP_NBIT_OR  ? "|"
12841                         :  o->op_type ==  OP_BIT_AND
12842                          ||o->op_type == OP_NBIT_AND ? "&"
12843                         :  o->op_type ==  OP_BIT_XOR
12844                          ||o->op_type == OP_NBIT_XOR ? "^"
12845                         :  o->op_type == OP_SBIT_OR  ? "|."
12846                         :  o->op_type == OP_SBIT_AND ? "&." : "^."
12847                            );
12848     }
12849     return o;
12850 }
12851
12852 PERL_STATIC_INLINE bool
12853 is_dollar_bracket(pTHX_ const OP * const o)
12854 {
12855     const OP *kid;
12856     PERL_UNUSED_CONTEXT;
12857     return o->op_type == OP_RV2SV && o->op_flags & OPf_KIDS
12858         && (kid = cUNOPx(o)->op_first)
12859         && kid->op_type == OP_GV
12860         && strEQ(GvNAME(cGVOPx_gv(kid)), "[");
12861 }
12862
12863 /* for lt, gt, le, ge, eq, ne and their i_ variants */
12864
12865 OP *
12866 Perl_ck_cmp(pTHX_ OP *o)
12867 {
12868     bool is_eq;
12869     bool neg;
12870     bool reverse;
12871     bool iv0;
12872     OP *indexop, *constop, *start;
12873     SV *sv;
12874     IV iv;
12875
12876     PERL_ARGS_ASSERT_CK_CMP;
12877
12878     is_eq = (   o->op_type == OP_EQ
12879              || o->op_type == OP_NE
12880              || o->op_type == OP_I_EQ
12881              || o->op_type == OP_I_NE);
12882
12883     if (!is_eq && ckWARN(WARN_SYNTAX)) {
12884         const OP *kid = cUNOPo->op_first;
12885         if (kid &&
12886             (
12887                 (   is_dollar_bracket(aTHX_ kid)
12888                  && OpSIBLING(kid) && OpSIBLING(kid)->op_type == OP_CONST
12889                 )
12890              || (   kid->op_type == OP_CONST
12891                  && (kid = OpSIBLING(kid)) && is_dollar_bracket(aTHX_ kid)
12892                 )
12893            )
12894         )
12895             Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
12896                         "$[ used in %s (did you mean $] ?)", OP_DESC(o));
12897     }
12898
12899     /* convert (index(...) == -1) and variations into
12900      *   (r)index/BOOL(,NEG)
12901      */
12902
12903     reverse = FALSE;
12904
12905     indexop = cUNOPo->op_first;
12906     constop = OpSIBLING(indexop);
12907     start = NULL;
12908     if (indexop->op_type == OP_CONST) {
12909         constop = indexop;
12910         indexop = OpSIBLING(constop);
12911         start = constop;
12912         reverse = TRUE;
12913     }
12914
12915     if (indexop->op_type != OP_INDEX && indexop->op_type != OP_RINDEX)
12916         return o;
12917
12918     /* ($lex = index(....)) == -1 */
12919     if (indexop->op_private & OPpTARGET_MY)
12920         return o;
12921
12922     if (constop->op_type != OP_CONST)
12923         return o;
12924
12925     sv = cSVOPx_sv(constop);
12926     if (!(sv && SvIOK_notUV(sv)))
12927         return o;
12928
12929     iv = SvIVX(sv);
12930     if (iv != -1 && iv != 0)
12931         return o;
12932     iv0 = (iv == 0);
12933
12934     if (o->op_type == OP_LT || o->op_type == OP_I_LT) {
12935         if (!(iv0 ^ reverse))
12936             return o;
12937         neg = iv0;
12938     }
12939     else if (o->op_type == OP_LE || o->op_type == OP_I_LE) {
12940         if (iv0 ^ reverse)
12941             return o;
12942         neg = !iv0;
12943     }
12944     else if (o->op_type == OP_GE || o->op_type == OP_I_GE) {
12945         if (!(iv0 ^ reverse))
12946             return o;
12947         neg = !iv0;
12948     }
12949     else if (o->op_type == OP_GT || o->op_type == OP_I_GT) {
12950         if (iv0 ^ reverse)
12951             return o;
12952         neg = iv0;
12953     }
12954     else if (o->op_type == OP_EQ || o->op_type == OP_I_EQ) {
12955         if (iv0)
12956             return o;
12957         neg = TRUE;
12958     }
12959     else {
12960         assert(o->op_type == OP_NE || o->op_type == OP_I_NE);
12961         if (iv0)
12962             return o;
12963         neg = FALSE;
12964     }
12965
12966     indexop->op_flags &= ~OPf_PARENS;
12967     indexop->op_flags |= (o->op_flags & OPf_PARENS);
12968     indexop->op_private |= OPpTRUEBOOL;
12969     if (neg)
12970         indexop->op_private |= OPpINDEX_BOOLNEG;
12971     /* cut out the index op and free the eq,const ops */
12972     (void)op_sibling_splice(o, start, 1, NULL);
12973     op_free(o);
12974
12975     return indexop;
12976 }
12977
12978
12979 OP *
12980 Perl_ck_concat(pTHX_ OP *o)
12981 {
12982     const OP * const kid = cUNOPo->op_first;
12983
12984     PERL_ARGS_ASSERT_CK_CONCAT;
12985     PERL_UNUSED_CONTEXT;
12986
12987     /* reuse the padtmp returned by the concat child */
12988     if (kid->op_type == OP_CONCAT && !(kid->op_private & OPpTARGET_MY) &&
12989             !(kUNOP->op_first->op_flags & OPf_MOD))
12990     {
12991         o->op_flags |= OPf_STACKED;
12992         o->op_private |= OPpCONCAT_NESTED;
12993     }
12994     return o;
12995 }
12996
12997 OP *
12998 Perl_ck_spair(pTHX_ OP *o)
12999 {
13000
13001     PERL_ARGS_ASSERT_CK_SPAIR;
13002
13003     if (o->op_flags & OPf_KIDS) {
13004         OP* newop;
13005         OP* kid;
13006         OP* kidkid;
13007         const OPCODE type = o->op_type;
13008         o = modkids(ck_fun(o), type);
13009         kid    = cUNOPo->op_first;
13010         kidkid = kUNOP->op_first;
13011         newop = OpSIBLING(kidkid);
13012         if (newop) {
13013             const OPCODE type = newop->op_type;
13014             if (OpHAS_SIBLING(newop))
13015                 return o;
13016             if (o->op_type == OP_REFGEN
13017              && (  type == OP_RV2CV
13018                 || (  !(newop->op_flags & OPf_PARENS)
13019                    && (  type == OP_RV2AV || type == OP_PADAV
13020                       || type == OP_RV2HV || type == OP_PADHV))))
13021                 NOOP; /* OK (allow srefgen for \@a and \%h) */
13022             else if (OP_GIMME(newop,0) != G_SCALAR)
13023                 return o;
13024         }
13025         /* excise first sibling */
13026         op_sibling_splice(kid, NULL, 1, NULL);
13027         op_free(kidkid);
13028     }
13029     /* transforms OP_REFGEN into OP_SREFGEN, OP_CHOP into OP_SCHOP,
13030      * and OP_CHOMP into OP_SCHOMP */
13031     o->op_ppaddr = PL_ppaddr[++o->op_type];
13032     return ck_fun(o);
13033 }
13034
13035 OP *
13036 Perl_ck_delete(pTHX_ OP *o)
13037 {
13038     PERL_ARGS_ASSERT_CK_DELETE;
13039
13040     o = ck_fun(o);
13041     o->op_private = 0;
13042     if (o->op_flags & OPf_KIDS) {
13043         OP * const kid = cUNOPo->op_first;
13044         switch (kid->op_type) {
13045         case OP_ASLICE:
13046             o->op_flags |= OPf_SPECIAL;
13047             /* FALLTHROUGH */
13048         case OP_HSLICE:
13049             o->op_private |= OPpSLICE;
13050             break;
13051         case OP_AELEM:
13052             o->op_flags |= OPf_SPECIAL;
13053             /* FALLTHROUGH */
13054         case OP_HELEM:
13055             break;
13056         case OP_KVASLICE:
13057             o->op_flags |= OPf_SPECIAL;
13058             /* FALLTHROUGH */
13059         case OP_KVHSLICE:
13060             o->op_private |= OPpKVSLICE;
13061             break;
13062         default:
13063             Perl_croak(aTHX_ "delete argument is not a HASH or ARRAY "
13064                              "element or slice");
13065         }
13066         if (kid->op_private & OPpLVAL_INTRO)
13067             o->op_private |= OPpLVAL_INTRO;
13068         op_null(kid);
13069     }
13070     return o;
13071 }
13072
13073 OP *
13074 Perl_ck_eof(pTHX_ OP *o)
13075 {
13076     PERL_ARGS_ASSERT_CK_EOF;
13077
13078     if (o->op_flags & OPf_KIDS) {
13079         OP *kid;
13080         if (cLISTOPo->op_first->op_type == OP_STUB) {
13081             OP * const newop
13082                 = newUNOP(o->op_type, OPf_SPECIAL, newGVOP(OP_GV, 0, PL_argvgv));
13083             op_free(o);
13084             o = newop;
13085         }
13086         o = ck_fun(o);
13087         kid = cLISTOPo->op_first;
13088         if (kid->op_type == OP_RV2GV)
13089             kid->op_private |= OPpALLOW_FAKE;
13090     }
13091     return o;
13092 }
13093
13094
13095 OP *
13096 Perl_ck_eval(pTHX_ OP *o)
13097 {
13098
13099     PERL_ARGS_ASSERT_CK_EVAL;
13100
13101     PL_hints |= HINT_BLOCK_SCOPE;
13102     if (o->op_flags & OPf_KIDS) {
13103         SVOP * const kid = (SVOP*)cUNOPo->op_first;
13104         assert(kid);
13105
13106         if (o->op_type == OP_ENTERTRY) {
13107             LOGOP *enter;
13108
13109             /* cut whole sibling chain free from o */
13110             op_sibling_splice(o, NULL, -1, NULL);
13111             op_free(o);
13112
13113             enter = alloc_LOGOP(OP_ENTERTRY, NULL, NULL);
13114
13115             /* establish postfix order */
13116             enter->op_next = (OP*)enter;
13117
13118             o = op_prepend_elem(OP_LINESEQ, (OP*)enter, (OP*)kid);
13119             OpTYPE_set(o, OP_LEAVETRY);
13120             enter->op_other = o;
13121             return o;
13122         }
13123         else {
13124             scalar((OP*)kid);
13125             S_set_haseval(aTHX);
13126         }
13127     }
13128     else {
13129         const U8 priv = o->op_private;
13130         op_free(o);
13131         /* the newUNOP will recursively call ck_eval(), which will handle
13132          * all the stuff at the end of this function, like adding
13133          * OP_HINTSEVAL
13134          */
13135         return newUNOP(OP_ENTEREVAL, priv <<8, newDEFSVOP());
13136     }
13137     o->op_targ = (PADOFFSET)PL_hints;
13138     if (o->op_private & OPpEVAL_BYTES) o->op_targ &= ~HINT_UTF8;
13139     if ((PL_hints & HINT_LOCALIZE_HH) != 0
13140      && !(o->op_private & OPpEVAL_COPHH) && GvHV(PL_hintgv)) {
13141         /* Store a copy of %^H that pp_entereval can pick up. */
13142         HV *hh = hv_copy_hints_hv(GvHV(PL_hintgv));
13143         OP *hhop;
13144         STOREFEATUREBITSHH(hh);
13145         hhop = newSVOP(OP_HINTSEVAL, 0, MUTABLE_SV(hh));
13146         /* append hhop to only child  */
13147         op_sibling_splice(o, cUNOPo->op_first, 0, hhop);
13148
13149         o->op_private |= OPpEVAL_HAS_HH;
13150     }
13151     if (!(o->op_private & OPpEVAL_BYTES)
13152          && FEATURE_UNIEVAL_IS_ENABLED)
13153             o->op_private |= OPpEVAL_UNICODE;
13154     return o;
13155 }
13156
13157 OP *
13158 Perl_ck_trycatch(pTHX_ OP *o)
13159 {
13160     LOGOP *enter;
13161     OP *to_free = NULL;
13162     OP *trykid, *catchkid;
13163     OP *catchroot, *catchstart;
13164
13165     PERL_ARGS_ASSERT_CK_TRYCATCH;
13166
13167     trykid = cUNOPo->op_first;
13168     if(trykid->op_type == OP_NULL || trykid->op_type == OP_PUSHMARK) {
13169         to_free = trykid;
13170         trykid = OpSIBLING(trykid);
13171     }
13172     catchkid = OpSIBLING(trykid);
13173
13174     assert(trykid->op_type == OP_POPTRY);
13175     assert(catchkid->op_type == OP_CATCH);
13176
13177     /* cut whole sibling chain free from o */
13178     op_sibling_splice(o, NULL, -1, NULL);
13179     if(to_free)
13180         op_free(to_free);
13181     op_free(o);
13182
13183     enter = alloc_LOGOP(OP_ENTERTRYCATCH, NULL, NULL);
13184
13185     /* establish postfix order */
13186     enter->op_next = (OP*)enter;
13187
13188     o = op_prepend_elem(OP_LINESEQ, (OP*)enter, trykid);
13189     op_append_elem(OP_LINESEQ, (OP*)o, catchkid);
13190
13191     OpTYPE_set(o, OP_LEAVETRYCATCH);
13192
13193     /* The returned optree is actually threaded up slightly nonobviously in
13194      * terms of its ->op_next pointers.
13195      *
13196      * This way, if the tryblock dies, its retop points at the OP_CATCH, but
13197      * if it does not then its leavetry skips over that and continues
13198      * execution past it.
13199      */
13200
13201     /* First, link up the actual body of the catch block */
13202     catchroot = OpSIBLING(cUNOPx(catchkid)->op_first);
13203     catchstart = LINKLIST(catchroot);
13204     cLOGOPx(catchkid)->op_other = catchstart;
13205
13206     o->op_next = LINKLIST(o);
13207
13208     /* die within try block should jump to the catch */
13209     enter->op_other = catchkid;
13210
13211     /* after try block that doesn't die, just skip straight to leavetrycatch */
13212     trykid->op_next = o;
13213
13214     /* after catch block, skip back up to the leavetrycatch */
13215     catchroot->op_next = o;
13216
13217     return o;
13218 }
13219
13220 OP *
13221 Perl_ck_exec(pTHX_ OP *o)
13222 {
13223     PERL_ARGS_ASSERT_CK_EXEC;
13224
13225     if (o->op_flags & OPf_STACKED) {
13226         OP *kid;
13227         o = ck_fun(o);
13228         kid = OpSIBLING(cUNOPo->op_first);
13229         if (kid->op_type == OP_RV2GV)
13230             op_null(kid);
13231     }
13232     else
13233         o = listkids(o);
13234     return o;
13235 }
13236
13237 OP *
13238 Perl_ck_exists(pTHX_ OP *o)
13239 {
13240     PERL_ARGS_ASSERT_CK_EXISTS;
13241
13242     o = ck_fun(o);
13243     if (o->op_flags & OPf_KIDS) {
13244         OP * const kid = cUNOPo->op_first;
13245         if (kid->op_type == OP_ENTERSUB) {
13246             (void) ref(kid, o->op_type);
13247             if (kid->op_type != OP_RV2CV
13248                         && !(PL_parser && PL_parser->error_count))
13249                 Perl_croak(aTHX_
13250                           "exists argument is not a subroutine name");
13251             o->op_private |= OPpEXISTS_SUB;
13252         }
13253         else if (kid->op_type == OP_AELEM)
13254             o->op_flags |= OPf_SPECIAL;
13255         else if (kid->op_type != OP_HELEM)
13256             Perl_croak(aTHX_ "exists argument is not a HASH or ARRAY "
13257                              "element or a subroutine");
13258         op_null(kid);
13259     }
13260     return o;
13261 }
13262
13263 OP *
13264 Perl_ck_rvconst(pTHX_ OP *o)
13265 {
13266     SVOP * const kid = (SVOP*)cUNOPo->op_first;
13267
13268     PERL_ARGS_ASSERT_CK_RVCONST;
13269
13270     if (o->op_type == OP_RV2HV)
13271         /* rv2hv steals the bottom bit for its own uses */
13272         o->op_private &= ~OPpARG1_MASK;
13273
13274     o->op_private |= (PL_hints & HINT_STRICT_REFS);
13275
13276     if (kid->op_type == OP_CONST) {
13277         int iscv;
13278         GV *gv;
13279         SV * const kidsv = kid->op_sv;
13280
13281         /* Is it a constant from cv_const_sv()? */
13282         if ((SvROK(kidsv) || isGV_with_GP(kidsv)) && SvREADONLY(kidsv)) {
13283             return o;
13284         }
13285         if (SvTYPE(kidsv) == SVt_PVAV) return o;
13286         if ((o->op_private & HINT_STRICT_REFS) && (kid->op_private & OPpCONST_BARE)) {
13287             const char *badthing;
13288             switch (o->op_type) {
13289             case OP_RV2SV:
13290                 badthing = "a SCALAR";
13291                 break;
13292             case OP_RV2AV:
13293                 badthing = "an ARRAY";
13294                 break;
13295             case OP_RV2HV:
13296                 badthing = "a HASH";
13297                 break;
13298             default:
13299                 badthing = NULL;
13300                 break;
13301             }
13302             if (badthing)
13303                 Perl_croak(aTHX_
13304                            "Can't use bareword (\"%" SVf "\") as %s ref while \"strict refs\" in use",
13305                            SVfARG(kidsv), badthing);
13306         }
13307         /*
13308          * This is a little tricky.  We only want to add the symbol if we
13309          * didn't add it in the lexer.  Otherwise we get duplicate strict
13310          * warnings.  But if we didn't add it in the lexer, we must at
13311          * least pretend like we wanted to add it even if it existed before,
13312          * or we get possible typo warnings.  OPpCONST_ENTERED says
13313          * whether the lexer already added THIS instance of this symbol.
13314          */
13315         iscv = o->op_type == OP_RV2CV ? GV_NOEXPAND|GV_ADDMULTI : 0;
13316         gv = gv_fetchsv(kidsv,
13317                 o->op_type == OP_RV2CV
13318                         && o->op_private & OPpMAY_RETURN_CONSTANT
13319                     ? GV_NOEXPAND
13320                     : iscv | !(kid->op_private & OPpCONST_ENTERED),
13321                 iscv
13322                     ? SVt_PVCV
13323                     : o->op_type == OP_RV2SV
13324                         ? SVt_PV
13325                         : o->op_type == OP_RV2AV
13326                             ? SVt_PVAV
13327                             : o->op_type == OP_RV2HV
13328                                 ? SVt_PVHV
13329                                 : SVt_PVGV);
13330         if (gv) {
13331             if (!isGV(gv)) {
13332                 assert(iscv);
13333                 assert(SvROK(gv));
13334                 if (!(o->op_private & OPpMAY_RETURN_CONSTANT)
13335                   && SvTYPE(SvRV(gv)) != SVt_PVCV)
13336                     gv_fetchsv(kidsv, GV_ADDMULTI, SVt_PVCV);
13337             }
13338             OpTYPE_set(kid, OP_GV);
13339             SvREFCNT_dec(kid->op_sv);
13340 #ifdef USE_ITHREADS
13341             /* XXX hack: dependence on sizeof(PADOP) <= sizeof(SVOP) */
13342             STATIC_ASSERT_STMT(sizeof(PADOP) <= sizeof(SVOP));
13343             kPADOP->op_padix = pad_alloc(OP_GV, SVf_READONLY);
13344             SvREFCNT_dec(PAD_SVl(kPADOP->op_padix));
13345             PAD_SETSV(kPADOP->op_padix, MUTABLE_SV(SvREFCNT_inc_simple_NN(gv)));
13346 #else
13347             kid->op_sv = SvREFCNT_inc_simple_NN(gv);
13348 #endif
13349             kid->op_private = 0;
13350             /* FAKE globs in the symbol table cause weird bugs (#77810) */
13351             SvFAKE_off(gv);
13352         }
13353     }
13354     return o;
13355 }
13356
13357 OP *
13358 Perl_ck_ftst(pTHX_ OP *o)
13359 {
13360     const I32 type = o->op_type;
13361
13362     PERL_ARGS_ASSERT_CK_FTST;
13363
13364     if (o->op_flags & OPf_REF) {
13365         NOOP;
13366     }
13367     else if (o->op_flags & OPf_KIDS && cUNOPo->op_first->op_type != OP_STUB) {
13368         SVOP * const kid = (SVOP*)cUNOPo->op_first;
13369         const OPCODE kidtype = kid->op_type;
13370
13371         if (kidtype == OP_CONST && (kid->op_private & OPpCONST_BARE)
13372          && !kid->op_folded) {
13373             OP * const newop = newGVOP(type, OPf_REF,
13374                 gv_fetchsv(kid->op_sv, GV_ADD, SVt_PVIO));
13375             op_free(o);
13376             return newop;
13377         }
13378
13379         if ((kidtype == OP_RV2AV || kidtype == OP_PADAV) && ckWARN(WARN_SYNTAX)) {
13380             SV *name = S_op_varname_subscript(aTHX_ (OP*)kid, 2);
13381             if (name) {
13382                 /* diag_listed_as: Array passed to stat will be coerced to a scalar%s */
13383                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX), "%s (did you want stat %" SVf "?)",
13384                             array_passed_to_stat, name);
13385             }
13386             else {
13387                 /* diag_listed_as: Array passed to stat will be coerced to a scalar%s */
13388                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX), "%s", array_passed_to_stat);
13389             }
13390        }
13391         scalar((OP *) kid);
13392         if ((PL_hints & HINT_FILETEST_ACCESS) && OP_IS_FILETEST_ACCESS(o->op_type))
13393             o->op_private |= OPpFT_ACCESS;
13394         if (OP_IS_FILETEST(type)
13395             && OP_IS_FILETEST(kidtype)
13396         ) {
13397             o->op_private |= OPpFT_STACKED;
13398             kid->op_private |= OPpFT_STACKING;
13399             if (kidtype == OP_FTTTY && (
13400                    !(kid->op_private & OPpFT_STACKED)
13401                 || kid->op_private & OPpFT_AFTER_t
13402                ))
13403                 o->op_private |= OPpFT_AFTER_t;
13404         }
13405     }
13406     else {
13407         op_free(o);
13408         if (type == OP_FTTTY)
13409             o = newGVOP(type, OPf_REF, PL_stdingv);
13410         else
13411             o = newUNOP(type, 0, newDEFSVOP());
13412     }
13413     return o;
13414 }
13415
13416 OP *
13417 Perl_ck_fun(pTHX_ OP *o)
13418 {
13419     const int type = o->op_type;
13420     I32 oa = PL_opargs[type] >> OASHIFT;
13421
13422     PERL_ARGS_ASSERT_CK_FUN;
13423
13424     if (o->op_flags & OPf_STACKED) {
13425         if ((oa & OA_OPTIONAL) && (oa >> 4) && !((oa >> 4) & OA_OPTIONAL))
13426             oa &= ~OA_OPTIONAL;
13427         else
13428             return no_fh_allowed(o);
13429     }
13430
13431     if (o->op_flags & OPf_KIDS) {
13432         OP *prev_kid = NULL;
13433         OP *kid = cLISTOPo->op_first;
13434         I32 numargs = 0;
13435         bool seen_optional = FALSE;
13436
13437         if (kid->op_type == OP_PUSHMARK ||
13438             (kid->op_type == OP_NULL && kid->op_targ == OP_PUSHMARK))
13439         {
13440             prev_kid = kid;
13441             kid = OpSIBLING(kid);
13442         }
13443         if (kid && kid->op_type == OP_COREARGS) {
13444             bool optional = FALSE;
13445             while (oa) {
13446                 numargs++;
13447                 if (oa & OA_OPTIONAL) optional = TRUE;
13448                 oa = oa >> 4;
13449             }
13450             if (optional) o->op_private |= numargs;
13451             return o;
13452         }
13453
13454         while (oa) {
13455             if (oa & OA_OPTIONAL || (oa & 7) == OA_LIST) {
13456                 if (!kid && !seen_optional && PL_opargs[type] & OA_DEFGV) {
13457                     kid = newDEFSVOP();
13458                     /* append kid to chain */
13459                     op_sibling_splice(o, prev_kid, 0, kid);
13460                 }
13461                 seen_optional = TRUE;
13462             }
13463             if (!kid) break;
13464
13465             numargs++;
13466             switch (oa & 7) {
13467             case OA_SCALAR:
13468                 /* list seen where single (scalar) arg expected? */
13469                 if (numargs == 1 && !(oa >> 4)
13470                     && kid->op_type == OP_LIST && type != OP_SCALAR)
13471                 {
13472                     return too_many_arguments_pv(o,PL_op_desc[type], 0);
13473                 }
13474                 if (type != OP_DELETE) scalar(kid);
13475                 break;
13476             case OA_LIST:
13477                 if (oa < 16) {
13478                     kid = 0;
13479                     continue;
13480                 }
13481                 else
13482                     list(kid);
13483                 break;
13484             case OA_AVREF:
13485                 if ((type == OP_PUSH || type == OP_UNSHIFT)
13486                     && !OpHAS_SIBLING(kid))
13487                     Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX),
13488                                    "Useless use of %s with no values",
13489                                    PL_op_desc[type]);
13490
13491                 if (kid->op_type == OP_CONST
13492                       && (  !SvROK(cSVOPx_sv(kid))
13493                          || SvTYPE(SvRV(cSVOPx_sv(kid))) != SVt_PVAV  )
13494                         )
13495                     bad_type_pv(numargs, "array", o, kid);
13496                 else if (kid->op_type == OP_RV2HV || kid->op_type == OP_PADHV
13497                          || kid->op_type == OP_RV2GV) {
13498                     bad_type_pv(1, "array", o, kid);
13499                 }
13500                 else if (kid->op_type != OP_RV2AV && kid->op_type != OP_PADAV) {
13501                     yyerror_pv(Perl_form(aTHX_ "Experimental %s on scalar is now forbidden",
13502                                          PL_op_desc[type]), 0);
13503                 }
13504                 else {
13505                     op_lvalue(kid, type);
13506                 }
13507                 break;
13508             case OA_HVREF:
13509                 if (kid->op_type != OP_RV2HV && kid->op_type != OP_PADHV)
13510                     bad_type_pv(numargs, "hash", o, kid);
13511                 op_lvalue(kid, type);
13512                 break;
13513             case OA_CVREF:
13514                 {
13515                     /* replace kid with newop in chain */
13516                     OP * const newop =
13517                         S_op_sibling_newUNOP(aTHX_ o, prev_kid, OP_NULL, 0);
13518                     newop->op_next = newop;
13519                     kid = newop;
13520                 }
13521                 break;
13522             case OA_FILEREF:
13523                 if (kid->op_type != OP_GV && kid->op_type != OP_RV2GV) {
13524                     if (kid->op_type == OP_CONST &&
13525                         (kid->op_private & OPpCONST_BARE))
13526                     {
13527                         OP * const newop = newGVOP(OP_GV, 0,
13528                             gv_fetchsv(((SVOP*)kid)->op_sv, GV_ADD, SVt_PVIO));
13529                         /* a first argument is handled by toke.c, ideally we'd
13530                          just check here but several ops don't use ck_fun() */
13531                         if (!FEATURE_BAREWORD_FILEHANDLES_IS_ENABLED && numargs > 1) {
13532                             no_bareword_filehandle(SvPVX(cSVOPx_sv((SVOP*)kid)));
13533                         }
13534                         /* replace kid with newop in chain */
13535                         op_sibling_splice(o, prev_kid, 1, newop);
13536                         op_free(kid);
13537                         kid = newop;
13538                     }
13539                     else if (kid->op_type == OP_READLINE) {
13540                         /* neophyte patrol: open(<FH>), close(<FH>) etc. */
13541                         bad_type_pv(numargs, "HANDLE", o, kid);
13542                     }
13543                     else {
13544                         I32 flags = OPf_SPECIAL;
13545                         I32 priv = 0;
13546                         PADOFFSET targ = 0;
13547
13548                         /* is this op a FH constructor? */
13549                         if (is_handle_constructor(o,numargs)) {
13550                             const char *name = NULL;
13551                             STRLEN len = 0;
13552                             U32 name_utf8 = 0;
13553                             bool want_dollar = TRUE;
13554
13555                             flags = 0;
13556                             /* Set a flag to tell rv2gv to vivify
13557                              * need to "prove" flag does not mean something
13558                              * else already - NI-S 1999/05/07
13559                              */
13560                             priv = OPpDEREF;
13561                             if (kid->op_type == OP_PADSV) {
13562                                 PADNAME * const pn
13563                                     = PAD_COMPNAME_SV(kid->op_targ);
13564                                 name = PadnamePV (pn);
13565                                 len  = PadnameLEN(pn);
13566                                 name_utf8 = PadnameUTF8(pn);
13567                             }
13568                             else if (kid->op_type == OP_RV2SV
13569                                      && kUNOP->op_first->op_type == OP_GV)
13570                             {
13571                                 GV * const gv = cGVOPx_gv(kUNOP->op_first);
13572                                 name = GvNAME(gv);
13573                                 len = GvNAMELEN(gv);
13574                                 name_utf8 = GvNAMEUTF8(gv) ? SVf_UTF8 : 0;
13575                             }
13576                             else if (kid->op_type == OP_AELEM
13577                                      || kid->op_type == OP_HELEM)
13578                             {
13579                                  OP *firstop;
13580                                  OP *op = ((BINOP*)kid)->op_first;
13581                                  name = NULL;
13582                                  if (op) {
13583                                       SV *tmpstr = NULL;
13584                                       const char * const a =
13585                                            kid->op_type == OP_AELEM ?
13586                                            "[]" : "{}";
13587                                       if (((op->op_type == OP_RV2AV) ||
13588                                            (op->op_type == OP_RV2HV)) &&
13589                                           (firstop = ((UNOP*)op)->op_first) &&
13590                                           (firstop->op_type == OP_GV)) {
13591                                            /* packagevar $a[] or $h{} */
13592                                            GV * const gv = cGVOPx_gv(firstop);
13593                                            if (gv)
13594                                                 tmpstr =
13595                                                      Perl_newSVpvf(aTHX_
13596                                                                    "%s%c...%c",
13597                                                                    GvNAME(gv),
13598                                                                    a[0], a[1]);
13599                                       }
13600                                       else if (op->op_type == OP_PADAV
13601                                                || op->op_type == OP_PADHV) {
13602                                            /* lexicalvar $a[] or $h{} */
13603                                            const char * const padname =
13604                                                 PAD_COMPNAME_PV(op->op_targ);
13605                                            if (padname)
13606                                                 tmpstr =
13607                                                      Perl_newSVpvf(aTHX_
13608                                                                    "%s%c...%c",
13609                                                                    padname + 1,
13610                                                                    a[0], a[1]);
13611                                       }
13612                                       if (tmpstr) {
13613                                            name = SvPV_const(tmpstr, len);
13614                                            name_utf8 = SvUTF8(tmpstr);
13615                                            sv_2mortal(tmpstr);
13616                                       }
13617                                  }
13618                                  if (!name) {
13619                                       name = "__ANONIO__";
13620                                       len = 10;
13621                                       want_dollar = FALSE;
13622                                  }
13623                                  op_lvalue(kid, type);
13624                             }
13625                             if (name) {
13626                                 SV *namesv;
13627                                 targ = pad_alloc(OP_RV2GV, SVf_READONLY);
13628                                 namesv = PAD_SVl(targ);
13629                                 if (want_dollar && *name != '$')
13630                                     sv_setpvs(namesv, "$");
13631                                 else
13632                                     SvPVCLEAR(namesv);
13633                                 sv_catpvn(namesv, name, len);
13634                                 if ( name_utf8 ) SvUTF8_on(namesv);
13635                             }
13636                         }
13637                         scalar(kid);
13638                         kid = S_op_sibling_newUNOP(aTHX_ o, prev_kid,
13639                                     OP_RV2GV, flags);
13640                         kid->op_targ = targ;
13641                         kid->op_private |= priv;
13642                     }
13643                 }
13644                 scalar(kid);
13645                 break;
13646             case OA_SCALARREF:
13647                 if ((type == OP_UNDEF || type == OP_POS)
13648                     && numargs == 1 && !(oa >> 4)
13649                     && kid->op_type == OP_LIST)
13650                     return too_many_arguments_pv(o,PL_op_desc[type], 0);
13651                 op_lvalue(scalar(kid), type);
13652                 break;
13653             }
13654             oa >>= 4;
13655             prev_kid = kid;
13656             kid = OpSIBLING(kid);
13657         }
13658         /* FIXME - should the numargs or-ing move after the too many
13659          * arguments check? */
13660         o->op_private |= numargs;
13661         if (kid)
13662             return too_many_arguments_pv(o,OP_DESC(o), 0);
13663         listkids(o);
13664     }
13665     else if (PL_opargs[type] & OA_DEFGV) {
13666         /* Ordering of these two is important to keep f_map.t passing.  */
13667         op_free(o);
13668         return newUNOP(type, 0, newDEFSVOP());
13669     }
13670
13671     if (oa) {
13672         while (oa & OA_OPTIONAL)
13673             oa >>= 4;
13674         if (oa && oa != OA_LIST)
13675             return too_few_arguments_pv(o,OP_DESC(o), 0);
13676     }
13677     return o;
13678 }
13679
13680 OP *
13681 Perl_ck_glob(pTHX_ OP *o)
13682 {
13683     GV *gv;
13684
13685     PERL_ARGS_ASSERT_CK_GLOB;
13686
13687     o = ck_fun(o);
13688     if ((o->op_flags & OPf_KIDS) && !OpHAS_SIBLING(cLISTOPo->op_first))
13689         op_append_elem(OP_GLOB, o, newDEFSVOP()); /* glob() => glob($_) */
13690
13691     if (!(o->op_flags & OPf_SPECIAL) && (gv = gv_override("glob", 4)))
13692     {
13693         /* convert
13694          *     glob
13695          *       \ null - const(wildcard)
13696          * into
13697          *     null
13698          *       \ enter
13699          *            \ list
13700          *                 \ mark - glob - rv2cv
13701          *                             |        \ gv(CORE::GLOBAL::glob)
13702          *                             |
13703          *                              \ null - const(wildcard)
13704          */
13705         o->op_flags |= OPf_SPECIAL;
13706         o->op_targ = pad_alloc(OP_GLOB, SVs_PADTMP);
13707         o = S_new_entersubop(aTHX_ gv, o);
13708         o = newUNOP(OP_NULL, 0, o);
13709         o->op_targ = OP_GLOB; /* hint at what it used to be: eg in newWHILEOP */
13710         return o;
13711     }
13712     else o->op_flags &= ~OPf_SPECIAL;
13713 #if !defined(PERL_EXTERNAL_GLOB)
13714     if (!PL_globhook) {
13715         ENTER;
13716         Perl_load_module(aTHX_ PERL_LOADMOD_NOIMPORT,
13717                                newSVpvs("File::Glob"), NULL, NULL, NULL);
13718         LEAVE;
13719     }
13720 #endif /* !PERL_EXTERNAL_GLOB */
13721     gv = (GV *)newSV_type(SVt_NULL);
13722     gv_init(gv, 0, "", 0, 0);
13723     gv_IOadd(gv);
13724     op_append_elem(OP_GLOB, o, newGVOP(OP_GV, 0, gv));
13725     SvREFCNT_dec_NN(gv); /* newGVOP increased it */
13726     scalarkids(o);
13727     return o;
13728 }
13729
13730 OP *
13731 Perl_ck_grep(pTHX_ OP *o)
13732 {
13733     LOGOP *gwop;
13734     OP *kid;
13735     const OPCODE type = o->op_type == OP_GREPSTART ? OP_GREPWHILE : OP_MAPWHILE;
13736
13737     PERL_ARGS_ASSERT_CK_GREP;
13738
13739     /* don't allocate gwop here, as we may leak it if PL_parser->error_count > 0 */
13740
13741     if (o->op_flags & OPf_STACKED) {
13742         kid = cUNOPx(OpSIBLING(cLISTOPo->op_first))->op_first;
13743         if (kid->op_type != OP_SCOPE && kid->op_type != OP_LEAVE)
13744             return no_fh_allowed(o);
13745         o->op_flags &= ~OPf_STACKED;
13746     }
13747     kid = OpSIBLING(cLISTOPo->op_first);
13748     if (type == OP_MAPWHILE)
13749         list(kid);
13750     else
13751         scalar(kid);
13752     o = ck_fun(o);
13753     if (PL_parser && PL_parser->error_count)
13754         return o;
13755     kid = OpSIBLING(cLISTOPo->op_first);
13756     if (kid->op_type != OP_NULL)
13757         Perl_croak(aTHX_ "panic: ck_grep, type=%u", (unsigned) kid->op_type);
13758     kid = kUNOP->op_first;
13759
13760     gwop = alloc_LOGOP(type, o, LINKLIST(kid));
13761     kid->op_next = (OP*)gwop;
13762     o->op_private = gwop->op_private = 0;
13763     gwop->op_targ = pad_alloc(type, SVs_PADTMP);
13764
13765     kid = OpSIBLING(cLISTOPo->op_first);
13766     for (kid = OpSIBLING(kid); kid; kid = OpSIBLING(kid))
13767         op_lvalue(kid, OP_GREPSTART);
13768
13769     return (OP*)gwop;
13770 }
13771
13772 OP *
13773 Perl_ck_index(pTHX_ OP *o)
13774 {
13775     PERL_ARGS_ASSERT_CK_INDEX;
13776
13777     if (o->op_flags & OPf_KIDS) {
13778         OP *kid = OpSIBLING(cLISTOPo->op_first);        /* get past pushmark */
13779         if (kid)
13780             kid = OpSIBLING(kid);                       /* get past "big" */
13781         if (kid && kid->op_type == OP_CONST) {
13782             const bool save_taint = TAINT_get;
13783             SV *sv = kSVOP->op_sv;
13784             if (   (!SvPOK(sv) || SvNIOKp(sv) || isREGEXP(sv))
13785                 && SvOK(sv) && !SvROK(sv))
13786             {
13787                 sv = newSV_type(SVt_NULL);
13788                 sv_copypv(sv, kSVOP->op_sv);
13789                 SvREFCNT_dec_NN(kSVOP->op_sv);
13790                 kSVOP->op_sv = sv;
13791             }
13792             if (SvOK(sv)) fbm_compile(sv, 0);
13793             TAINT_set(save_taint);
13794 #ifdef NO_TAINT_SUPPORT
13795             PERL_UNUSED_VAR(save_taint);
13796 #endif
13797         }
13798     }
13799     return ck_fun(o);
13800 }
13801
13802 OP *
13803 Perl_ck_lfun(pTHX_ OP *o)
13804 {
13805     const OPCODE type = o->op_type;
13806
13807     PERL_ARGS_ASSERT_CK_LFUN;
13808
13809     return modkids(ck_fun(o), type);
13810 }
13811
13812 OP *
13813 Perl_ck_defined(pTHX_ OP *o)            /* 19990527 MJD */
13814 {
13815     PERL_ARGS_ASSERT_CK_DEFINED;
13816
13817     if ((o->op_flags & OPf_KIDS)) {
13818         switch (cUNOPo->op_first->op_type) {
13819         case OP_RV2AV:
13820         case OP_PADAV:
13821             Perl_croak(aTHX_ "Can't use 'defined(@array)'"
13822                              " (Maybe you should just omit the defined()?)");
13823             NOT_REACHED; /* NOTREACHED */
13824             break;
13825         case OP_RV2HV:
13826         case OP_PADHV:
13827             Perl_croak(aTHX_ "Can't use 'defined(%%hash)'"
13828                              " (Maybe you should just omit the defined()?)");
13829             NOT_REACHED; /* NOTREACHED */
13830             break;
13831         default:
13832             /* no warning */
13833             break;
13834         }
13835     }
13836     return ck_rfun(o);
13837 }
13838
13839 OP *
13840 Perl_ck_readline(pTHX_ OP *o)
13841 {
13842     PERL_ARGS_ASSERT_CK_READLINE;
13843
13844     if (o->op_flags & OPf_KIDS) {
13845          OP *kid = cLISTOPo->op_first;
13846          if (kid->op_type == OP_RV2GV) kid->op_private |= OPpALLOW_FAKE;
13847          scalar(kid);
13848     }
13849     else {
13850         OP * const newop
13851             = newUNOP(OP_READLINE, 0, newGVOP(OP_GV, 0, PL_argvgv));
13852         op_free(o);
13853         return newop;
13854     }
13855     return o;
13856 }
13857
13858 OP *
13859 Perl_ck_rfun(pTHX_ OP *o)
13860 {
13861     const OPCODE type = o->op_type;
13862
13863     PERL_ARGS_ASSERT_CK_RFUN;
13864
13865     return refkids(ck_fun(o), type);
13866 }
13867
13868 OP *
13869 Perl_ck_listiob(pTHX_ OP *o)
13870 {
13871     OP *kid;
13872
13873     PERL_ARGS_ASSERT_CK_LISTIOB;
13874
13875     kid = cLISTOPo->op_first;
13876     if (!kid) {
13877         o = force_list(o, TRUE);
13878         kid = cLISTOPo->op_first;
13879     }
13880     if (kid->op_type == OP_PUSHMARK)
13881         kid = OpSIBLING(kid);
13882     if (kid && o->op_flags & OPf_STACKED)
13883         kid = OpSIBLING(kid);
13884     else if (kid && !OpHAS_SIBLING(kid)) {              /* print HANDLE; */
13885         if (kid->op_type == OP_CONST && kid->op_private & OPpCONST_BARE
13886          && !kid->op_folded) {
13887             o->op_flags |= OPf_STACKED; /* make it a filehandle */
13888             scalar(kid);
13889             /* replace old const op with new OP_RV2GV parent */
13890             kid = S_op_sibling_newUNOP(aTHX_ o, cLISTOPo->op_first,
13891                                         OP_RV2GV, OPf_REF);
13892             kid = OpSIBLING(kid);
13893         }
13894     }
13895
13896     if (!kid)
13897         op_append_elem(o->op_type, o, newDEFSVOP());
13898
13899     if (o->op_type == OP_PRTF) return modkids(listkids(o), OP_PRTF);
13900     return listkids(o);
13901 }
13902
13903 OP *
13904 Perl_ck_smartmatch(pTHX_ OP *o)
13905 {
13906     PERL_ARGS_ASSERT_CK_SMARTMATCH;
13907     if (0 == (o->op_flags & OPf_SPECIAL)) {
13908         OP *first  = cBINOPo->op_first;
13909         OP *second = OpSIBLING(first);
13910
13911         /* Implicitly take a reference to an array or hash */
13912
13913         /* remove the original two siblings, then add back the
13914          * (possibly different) first and second sibs.
13915          */
13916         op_sibling_splice(o, NULL, 1, NULL);
13917         op_sibling_splice(o, NULL, 1, NULL);
13918         first  = ref_array_or_hash(first);
13919         second = ref_array_or_hash(second);
13920         op_sibling_splice(o, NULL, 0, second);
13921         op_sibling_splice(o, NULL, 0, first);
13922
13923         /* Implicitly take a reference to a regular expression */
13924         if (first->op_type == OP_MATCH && !(first->op_flags & OPf_STACKED)) {
13925             OpTYPE_set(first, OP_QR);
13926         }
13927         if (second->op_type == OP_MATCH && !(second->op_flags & OPf_STACKED)) {
13928             OpTYPE_set(second, OP_QR);
13929         }
13930     }
13931
13932     return o;
13933 }
13934
13935
13936 static OP *
13937 S_maybe_targlex(pTHX_ OP *o)
13938 {
13939     OP * const kid = cLISTOPo->op_first;
13940     /* has a disposable target? */
13941     if ((PL_opargs[kid->op_type] & OA_TARGLEX)
13942         && !(kid->op_flags & OPf_STACKED)
13943         /* Cannot steal the second time! */
13944         && !(kid->op_private & OPpTARGET_MY)
13945         )
13946     {
13947         OP * const kkid = OpSIBLING(kid);
13948
13949         /* Can just relocate the target. */
13950         if (kkid && kkid->op_type == OP_PADSV
13951             && (!(kkid->op_private & OPpLVAL_INTRO)
13952                || kkid->op_private & OPpPAD_STATE))
13953         {
13954             kid->op_targ = kkid->op_targ;
13955             kkid->op_targ = 0;
13956             /* Now we do not need PADSV and SASSIGN.
13957              * Detach kid and free the rest. */
13958             op_sibling_splice(o, NULL, 1, NULL);
13959             op_free(o);
13960             kid->op_private |= OPpTARGET_MY;    /* Used for context settings */
13961             return kid;
13962         }
13963     }
13964     return o;
13965 }
13966
13967 OP *
13968 Perl_ck_sassign(pTHX_ OP *o)
13969 {
13970     OP * const kid = cBINOPo->op_first;
13971
13972     PERL_ARGS_ASSERT_CK_SASSIGN;
13973
13974     if (OpHAS_SIBLING(kid)) {
13975         OP *kkid = OpSIBLING(kid);
13976         /* For state variable assignment with attributes, kkid is a list op
13977            whose op_last is a padsv. */
13978         if ((kkid->op_type == OP_PADSV ||
13979              (OP_TYPE_IS_OR_WAS(kkid, OP_LIST) &&
13980               (kkid = cLISTOPx(kkid)->op_last)->op_type == OP_PADSV
13981              )
13982             )
13983                 && (kkid->op_private & (OPpLVAL_INTRO|OPpPAD_STATE))
13984                     == (OPpLVAL_INTRO|OPpPAD_STATE)) {
13985             return S_newONCEOP(aTHX_ o, kkid);
13986         }
13987     }
13988     return S_maybe_targlex(aTHX_ o);
13989 }
13990
13991
13992 OP *
13993 Perl_ck_match(pTHX_ OP *o)
13994 {
13995     PERL_UNUSED_CONTEXT;
13996     PERL_ARGS_ASSERT_CK_MATCH;
13997
13998     return o;
13999 }
14000
14001 OP *
14002 Perl_ck_method(pTHX_ OP *o)
14003 {
14004     SV *sv, *methsv, *rclass;
14005     const char* method;
14006     char* compatptr;
14007     int utf8;
14008     STRLEN len, nsplit = 0, i;
14009     OP* new_op;
14010     OP * const kid = cUNOPo->op_first;
14011
14012     PERL_ARGS_ASSERT_CK_METHOD;
14013     if (kid->op_type != OP_CONST) return o;
14014
14015     sv = kSVOP->op_sv;
14016
14017     /* replace ' with :: */
14018     while ((compatptr = (char *) memchr(SvPVX(sv), '\'',
14019                                         SvEND(sv) - SvPVX(sv) )))
14020     {
14021         *compatptr = ':';
14022         sv_insert(sv, compatptr - SvPVX_const(sv), 0, ":", 1);
14023     }
14024
14025     method = SvPVX_const(sv);
14026     len = SvCUR(sv);
14027     utf8 = SvUTF8(sv) ? -1 : 1;
14028
14029     for (i = len - 1; i > 0; --i) if (method[i] == ':') {
14030         nsplit = i+1;
14031         break;
14032     }
14033
14034     methsv = newSVpvn_share(method+nsplit, utf8*(len - nsplit), 0);
14035
14036     if (!nsplit) { /* $proto->method() */
14037         op_free(o);
14038         return newMETHOP_named(OP_METHOD_NAMED, 0, methsv);
14039     }
14040
14041     if (memEQs(method, nsplit, "SUPER::")) { /* $proto->SUPER::method() */
14042         op_free(o);
14043         return newMETHOP_named(OP_METHOD_SUPER, 0, methsv);
14044     }
14045
14046     /* $proto->MyClass::method() and $proto->MyClass::SUPER::method() */
14047     if (nsplit >= 9 && strBEGINs(method+nsplit-9, "::SUPER::")) {
14048         rclass = newSVpvn_share(method, utf8*(nsplit-9), 0);
14049         new_op = newMETHOP_named(OP_METHOD_REDIR_SUPER, 0, methsv);
14050     } else {
14051         rclass = newSVpvn_share(method, utf8*(nsplit-2), 0);
14052         new_op = newMETHOP_named(OP_METHOD_REDIR, 0, methsv);
14053     }
14054 #ifdef USE_ITHREADS
14055     op_relocate_sv(&rclass, &cMETHOPx(new_op)->op_rclass_targ);
14056 #else
14057     cMETHOPx(new_op)->op_rclass_sv = rclass;
14058 #endif
14059     op_free(o);
14060     return new_op;
14061 }
14062
14063 OP *
14064 Perl_ck_null(pTHX_ OP *o)
14065 {
14066     PERL_ARGS_ASSERT_CK_NULL;
14067     PERL_UNUSED_CONTEXT;
14068     return o;
14069 }
14070
14071 OP *
14072 Perl_ck_open(pTHX_ OP *o)
14073 {
14074     PERL_ARGS_ASSERT_CK_OPEN;
14075
14076     S_io_hints(aTHX_ o);
14077     {
14078          /* In case of three-arg dup open remove strictness
14079           * from the last arg if it is a bareword. */
14080          OP * const first = cLISTOPx(o)->op_first; /* The pushmark. */
14081          OP * const last  = cLISTOPx(o)->op_last;  /* The bareword. */
14082          OP *oa;
14083          const char *mode;
14084
14085          if ((last->op_type == OP_CONST) &&             /* The bareword. */
14086              (last->op_private & OPpCONST_BARE) &&
14087              (last->op_private & OPpCONST_STRICT) &&
14088              (oa = OpSIBLING(first)) &&         /* The fh. */
14089              (oa = OpSIBLING(oa)) &&                    /* The mode. */
14090              (oa->op_type == OP_CONST) &&
14091              SvPOK(((SVOP*)oa)->op_sv) &&
14092              (mode = SvPVX_const(((SVOP*)oa)->op_sv)) &&
14093              mode[0] == '>' && mode[1] == '&' &&        /* A dup open. */
14094              (last == OpSIBLING(oa)))                   /* The bareword. */
14095               last->op_private &= ~OPpCONST_STRICT;
14096     }
14097     return ck_fun(o);
14098 }
14099
14100 OP *
14101 Perl_ck_prototype(pTHX_ OP *o)
14102 {
14103     PERL_ARGS_ASSERT_CK_PROTOTYPE;
14104     if (!(o->op_flags & OPf_KIDS)) {
14105         op_free(o);
14106         return newUNOP(OP_PROTOTYPE, 0, newDEFSVOP());
14107     }
14108     return o;
14109 }
14110
14111 OP *
14112 Perl_ck_refassign(pTHX_ OP *o)
14113 {
14114     OP * const right = cLISTOPo->op_first;
14115     OP * const left = OpSIBLING(right);
14116     OP *varop = cUNOPx(cUNOPx(left)->op_first)->op_first;
14117     bool stacked = 0;
14118
14119     PERL_ARGS_ASSERT_CK_REFASSIGN;
14120     assert (left);
14121     assert (left->op_type == OP_SREFGEN);
14122
14123     o->op_private = 0;
14124     /* we use OPpPAD_STATE in refassign to mean either of those things,
14125      * and the code assumes the two flags occupy the same bit position
14126      * in the various ops below */
14127     assert(OPpPAD_STATE == OPpOUR_INTRO);
14128
14129     switch (varop->op_type) {
14130     case OP_PADAV:
14131         o->op_private |= OPpLVREF_AV;
14132         goto settarg;
14133     case OP_PADHV:
14134         o->op_private |= OPpLVREF_HV;
14135         /* FALLTHROUGH */
14136     case OP_PADSV:
14137       settarg:
14138         o->op_private |= (varop->op_private & (OPpLVAL_INTRO|OPpPAD_STATE));
14139         o->op_targ = varop->op_targ;
14140         varop->op_targ = 0;
14141         PAD_COMPNAME_GEN_set(o->op_targ, PERL_INT_MAX);
14142         break;
14143
14144     case OP_RV2AV:
14145         o->op_private |= OPpLVREF_AV;
14146         goto checkgv;
14147         NOT_REACHED; /* NOTREACHED */
14148     case OP_RV2HV:
14149         o->op_private |= OPpLVREF_HV;
14150         /* FALLTHROUGH */
14151     case OP_RV2SV:
14152       checkgv:
14153         o->op_private |= (varop->op_private & (OPpLVAL_INTRO|OPpOUR_INTRO));
14154         if (cUNOPx(varop)->op_first->op_type != OP_GV) goto bad;
14155       detach_and_stack:
14156         /* Point varop to its GV kid, detached.  */
14157         varop = op_sibling_splice(varop, NULL, -1, NULL);
14158         stacked = TRUE;
14159         break;
14160     case OP_RV2CV: {
14161         OP * const kidparent =
14162             OpSIBLING(cUNOPx(cUNOPx(varop)->op_first)->op_first);
14163         OP * const kid = cUNOPx(kidparent)->op_first;
14164         o->op_private |= OPpLVREF_CV;
14165         if (kid->op_type == OP_GV) {
14166             SV *sv = (SV*)cGVOPx_gv(kid);
14167             varop = kidparent;
14168             if (SvROK(sv) && SvTYPE(SvRV(sv)) == SVt_PVCV) {
14169                 /* a CVREF here confuses pp_refassign, so make sure
14170                    it gets a GV */
14171                 CV *const cv = (CV*)SvRV(sv);
14172                 SV *name_sv = sv_2mortal(newSVhek(CvNAME_HEK(cv)));
14173                 (void)gv_init_sv((GV*)sv, CvSTASH(cv), name_sv, 0);
14174                 assert(SvTYPE(sv) == SVt_PVGV);
14175             }
14176             goto detach_and_stack;
14177         }
14178         if (kid->op_type != OP_PADCV)   goto bad;
14179         o->op_targ = kid->op_targ;
14180         kid->op_targ = 0;
14181         break;
14182     }
14183     case OP_AELEM:
14184     case OP_HELEM:
14185         o->op_private |= (varop->op_private & OPpLVAL_INTRO);
14186         o->op_private |= OPpLVREF_ELEM;
14187         op_null(varop);
14188         stacked = TRUE;
14189         /* Detach varop.  */
14190         op_sibling_splice(cUNOPx(left)->op_first, NULL, -1, NULL);
14191         break;
14192     default:
14193       bad:
14194         /* diag_listed_as: Can't modify reference to %s in %s assignment */
14195         yyerror(Perl_form(aTHX_ "Can't modify reference to %s in scalar "
14196                                 "assignment",
14197                                  OP_DESC(varop)));
14198         return o;
14199     }
14200     if (!FEATURE_REFALIASING_IS_ENABLED)
14201         Perl_croak(aTHX_
14202                   "Experimental aliasing via reference not enabled");
14203     Perl_ck_warner_d(aTHX_
14204                      packWARN(WARN_EXPERIMENTAL__REFALIASING),
14205                     "Aliasing via reference is experimental");
14206     if (stacked) {
14207         o->op_flags |= OPf_STACKED;
14208         op_sibling_splice(o, right, 1, varop);
14209     }
14210     else {
14211         o->op_flags &=~ OPf_STACKED;
14212         op_sibling_splice(o, right, 1, NULL);
14213     }
14214     op_free(left);
14215     return o;
14216 }
14217
14218 OP *
14219 Perl_ck_repeat(pTHX_ OP *o)
14220 {
14221     PERL_ARGS_ASSERT_CK_REPEAT;
14222
14223     if (cBINOPo->op_first->op_flags & OPf_PARENS) {
14224         OP* kids;
14225         o->op_private |= OPpREPEAT_DOLIST;
14226         kids = op_sibling_splice(o, NULL, 1, NULL); /* detach first kid */
14227         kids = force_list(kids, TRUE); /* promote it to a list */
14228         op_sibling_splice(o, NULL, 0, kids); /* and add back */
14229     }
14230     else
14231         scalar(o);
14232     return o;
14233 }
14234
14235 OP *
14236 Perl_ck_require(pTHX_ OP *o)
14237 {
14238     GV* gv;
14239
14240     PERL_ARGS_ASSERT_CK_REQUIRE;
14241
14242     if (o->op_flags & OPf_KIDS) {       /* Shall we supply missing .pm? */
14243         SVOP * const kid = (SVOP*)cUNOPo->op_first;
14244         U32 hash;
14245         char *s;
14246         STRLEN len;
14247         if (kid->op_type == OP_CONST) {
14248           SV * const sv = kid->op_sv;
14249           U32 const was_readonly = SvREADONLY(sv);
14250           if (kid->op_private & OPpCONST_BARE) {
14251             const char *end;
14252             HEK *hek;
14253
14254             if (was_readonly) {
14255                 SvREADONLY_off(sv);
14256             }
14257
14258             if (SvIsCOW(sv)) sv_force_normal_flags(sv, 0);
14259
14260             s = SvPVX(sv);
14261             len = SvCUR(sv);
14262             end = s + len;
14263             /* treat ::foo::bar as foo::bar */
14264             if (len >= 2 && s[0] == ':' && s[1] == ':')
14265                 DIE(aTHX_ "Bareword in require must not start with a double-colon: \"%s\"\n", s);
14266             if (s == end)
14267                 DIE(aTHX_ "Bareword in require maps to empty filename");
14268
14269             for (; s < end; s++) {
14270                 if (*s == ':' && s[1] == ':') {
14271                     *s = '/';
14272                     Move(s+2, s+1, end - s - 1, char);
14273                     --end;
14274                 }
14275             }
14276             SvEND_set(sv, end);
14277             sv_catpvs(sv, ".pm");
14278             PERL_HASH(hash, SvPVX(sv), SvCUR(sv));
14279             hek = share_hek(SvPVX(sv),
14280                             (SSize_t)SvCUR(sv) * (SvUTF8(sv) ? -1 : 1),
14281                             hash);
14282             sv_sethek(sv, hek);
14283             unshare_hek(hek);
14284             SvFLAGS(sv) |= was_readonly;
14285           }
14286           else if (SvPOK(sv) && !SvNIOK(sv) && !SvGMAGICAL(sv)
14287                 && !SvVOK(sv)) {
14288             s = SvPV(sv, len);
14289             if (SvREFCNT(sv) > 1) {
14290                 kid->op_sv = newSVpvn_share(
14291                     s, SvUTF8(sv) ? -(SSize_t)len : (SSize_t)len, 0);
14292                 SvREFCNT_dec_NN(sv);
14293             }
14294             else {
14295                 HEK *hek;
14296                 if (was_readonly) SvREADONLY_off(sv);
14297                 PERL_HASH(hash, s, len);
14298                 hek = share_hek(s,
14299                                 SvUTF8(sv) ? -(SSize_t)len : (SSize_t)len,
14300                                 hash);
14301                 sv_sethek(sv, hek);
14302                 unshare_hek(hek);
14303                 SvFLAGS(sv) |= was_readonly;
14304             }
14305           }
14306         }
14307     }
14308
14309     if (!(o->op_flags & OPf_SPECIAL) /* Wasn't written as CORE::require */
14310         /* handle override, if any */
14311      && (gv = gv_override("require", 7))) {
14312         OP *kid, *newop;
14313         if (o->op_flags & OPf_KIDS) {
14314             kid = cUNOPo->op_first;
14315             op_sibling_splice(o, NULL, -1, NULL);
14316         }
14317         else {
14318             kid = newDEFSVOP();
14319         }
14320         op_free(o);
14321         newop = S_new_entersubop(aTHX_ gv, kid);
14322         return newop;
14323     }
14324
14325     return ck_fun(o);
14326 }
14327
14328 OP *
14329 Perl_ck_return(pTHX_ OP *o)
14330 {
14331     OP *kid;
14332
14333     PERL_ARGS_ASSERT_CK_RETURN;
14334
14335     kid = OpSIBLING(cLISTOPo->op_first);
14336     if (PL_compcv && CvLVALUE(PL_compcv)) {
14337         for (; kid; kid = OpSIBLING(kid))
14338             op_lvalue(kid, OP_LEAVESUBLV);
14339     }
14340
14341     return o;
14342 }
14343
14344 OP *
14345 Perl_ck_select(pTHX_ OP *o)
14346 {
14347     OP* kid;
14348
14349     PERL_ARGS_ASSERT_CK_SELECT;
14350
14351     if (o->op_flags & OPf_KIDS) {
14352         kid = OpSIBLING(cLISTOPo->op_first);     /* get past pushmark */
14353         if (kid && OpHAS_SIBLING(kid)) {
14354             OpTYPE_set(o, OP_SSELECT);
14355             o = ck_fun(o);
14356             return fold_constants(op_integerize(op_std_init(o)));
14357         }
14358     }
14359     o = ck_fun(o);
14360     kid = OpSIBLING(cLISTOPo->op_first);    /* get past pushmark */
14361     if (kid && kid->op_type == OP_RV2GV)
14362         kid->op_private &= ~HINT_STRICT_REFS;
14363     return o;
14364 }
14365
14366 OP *
14367 Perl_ck_shift(pTHX_ OP *o)
14368 {
14369     const I32 type = o->op_type;
14370
14371     PERL_ARGS_ASSERT_CK_SHIFT;
14372
14373     if (!(o->op_flags & OPf_KIDS)) {
14374         OP *argop;
14375
14376         if (!CvUNIQUE(PL_compcv)) {
14377             o->op_flags |= OPf_SPECIAL;
14378             return o;
14379         }
14380
14381         argop = newUNOP(OP_RV2AV, 0, scalar(newGVOP(OP_GV, 0, PL_argvgv)));
14382         op_free(o);
14383         return newUNOP(type, 0, scalar(argop));
14384     }
14385     return scalar(ck_fun(o));
14386 }
14387
14388 OP *
14389 Perl_ck_sort(pTHX_ OP *o)
14390 {
14391     OP *firstkid;
14392     OP *kid;
14393     U8 stacked;
14394
14395     PERL_ARGS_ASSERT_CK_SORT;
14396
14397     if (o->op_flags & OPf_STACKED)
14398         simplify_sort(o);
14399     firstkid = OpSIBLING(cLISTOPo->op_first);           /* get past pushmark */
14400
14401     if (!firstkid)
14402         return too_few_arguments_pv(o,OP_DESC(o), 0);
14403
14404     if ((stacked = o->op_flags & OPf_STACKED)) {        /* may have been cleared */
14405         OP *kid = cUNOPx(firstkid)->op_first;           /* get past null */
14406
14407         /* if the first arg is a code block, process it and mark sort as
14408          * OPf_SPECIAL */
14409         if (kid->op_type == OP_SCOPE || kid->op_type == OP_LEAVE) {
14410             LINKLIST(kid);
14411             if (kid->op_type == OP_LEAVE)
14412                     op_null(kid);                       /* wipe out leave */
14413             /* Prevent execution from escaping out of the sort block. */
14414             kid->op_next = 0;
14415
14416             /* provide scalar context for comparison function/block */
14417             kid = scalar(firstkid);
14418             kid->op_next = kid;
14419             o->op_flags |= OPf_SPECIAL;
14420         }
14421         else if (kid->op_type == OP_CONST
14422               && kid->op_private & OPpCONST_BARE) {
14423             char tmpbuf[256];
14424             STRLEN len;
14425             PADOFFSET off;
14426             const char * const name = SvPV(kSVOP_sv, len);
14427             *tmpbuf = '&';
14428             assert (len < 256);
14429             Copy(name, tmpbuf+1, len, char);
14430             off = pad_findmy_pvn(tmpbuf, len+1, 0);
14431             if (off != NOT_IN_PAD) {
14432                 if (PAD_COMPNAME_FLAGS_isOUR(off)) {
14433                     SV * const fq =
14434                         newSVhek(HvNAME_HEK(PAD_COMPNAME_OURSTASH(off)));
14435                     sv_catpvs(fq, "::");
14436                     sv_catsv(fq, kSVOP_sv);
14437                     SvREFCNT_dec_NN(kSVOP_sv);
14438                     kSVOP->op_sv = fq;
14439                 }
14440                 else {
14441                     OP * const padop = newOP(OP_PADCV, 0);
14442                     padop->op_targ = off;
14443                     /* replace the const op with the pad op */
14444                     op_sibling_splice(firstkid, NULL, 1, padop);
14445                     op_free(kid);
14446                 }
14447             }
14448         }
14449
14450         firstkid = OpSIBLING(firstkid);
14451     }
14452
14453     for (kid = firstkid; kid; kid = OpSIBLING(kid)) {
14454         /* provide list context for arguments */
14455         list(kid);
14456         if (stacked)
14457             op_lvalue(kid, OP_GREPSTART);
14458     }
14459
14460     return o;
14461 }
14462
14463 /* for sort { X } ..., where X is one of
14464  *   $a <=> $b, $b <=> $a, $a cmp $b, $b cmp $a
14465  * elide the second child of the sort (the one containing X),
14466  * and set these flags as appropriate
14467         OPpSORT_NUMERIC;
14468         OPpSORT_INTEGER;
14469         OPpSORT_DESCEND;
14470  * Also, check and warn on lexical $a, $b.
14471  */
14472
14473 STATIC void
14474 S_simplify_sort(pTHX_ OP *o)
14475 {
14476     OP *kid = OpSIBLING(cLISTOPo->op_first);    /* get past pushmark */
14477     OP *k;
14478     int descending;
14479     GV *gv;
14480     const char *gvname;
14481     bool have_scopeop;
14482
14483     PERL_ARGS_ASSERT_SIMPLIFY_SORT;
14484
14485     kid = kUNOP->op_first;                              /* get past null */
14486     if (!(have_scopeop = kid->op_type == OP_SCOPE)
14487      && kid->op_type != OP_LEAVE)
14488         return;
14489     kid = kLISTOP->op_last;                             /* get past scope */
14490     switch(kid->op_type) {
14491         case OP_NCMP:
14492         case OP_I_NCMP:
14493         case OP_SCMP:
14494             if (!have_scopeop) goto padkids;
14495             break;
14496         default:
14497             return;
14498     }
14499     k = kid;                                            /* remember this node*/
14500     if (kBINOP->op_first->op_type != OP_RV2SV
14501      || kBINOP->op_last ->op_type != OP_RV2SV)
14502     {
14503         /*
14504            Warn about my($a) or my($b) in a sort block, *if* $a or $b is
14505            then used in a comparison.  This catches most, but not
14506            all cases.  For instance, it catches
14507                sort { my($a); $a <=> $b }
14508            but not
14509                sort { my($a); $a < $b ? -1 : $a == $b ? 0 : 1; }
14510            (although why you'd do that is anyone's guess).
14511         */
14512
14513        padkids:
14514         if (!ckWARN(WARN_SYNTAX)) return;
14515         kid = kBINOP->op_first;
14516         do {
14517             if (kid->op_type == OP_PADSV) {
14518                 PADNAME * const name = PAD_COMPNAME(kid->op_targ);
14519                 if (PadnameLEN(name) == 2 && *PadnamePV(name) == '$'
14520                  && (  PadnamePV(name)[1] == 'a'
14521                     || PadnamePV(name)[1] == 'b'  ))
14522                     /* diag_listed_as: "my %s" used in sort comparison */
14523                     Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
14524                                      "\"%s %s\" used in sort comparison",
14525                                       PadnameIsSTATE(name)
14526                                         ? "state"
14527                                         : "my",
14528                                       PadnamePV(name));
14529             }
14530         } while ((kid = OpSIBLING(kid)));
14531         return;
14532     }
14533     kid = kBINOP->op_first;                             /* get past cmp */
14534     if (kUNOP->op_first->op_type != OP_GV)
14535         return;
14536     kid = kUNOP->op_first;                              /* get past rv2sv */
14537     gv = kGVOP_gv;
14538     if (GvSTASH(gv) != PL_curstash)
14539         return;
14540     gvname = GvNAME(gv);
14541     if (*gvname == 'a' && gvname[1] == '\0')
14542         descending = 0;
14543     else if (*gvname == 'b' && gvname[1] == '\0')
14544         descending = 1;
14545     else
14546         return;
14547
14548     kid = k;                                            /* back to cmp */
14549     /* already checked above that it is rv2sv */
14550     kid = kBINOP->op_last;                              /* down to 2nd arg */
14551     if (kUNOP->op_first->op_type != OP_GV)
14552         return;
14553     kid = kUNOP->op_first;                              /* get past rv2sv */
14554     gv = kGVOP_gv;
14555     if (GvSTASH(gv) != PL_curstash)
14556         return;
14557     gvname = GvNAME(gv);
14558     if ( descending
14559          ? !(*gvname == 'a' && gvname[1] == '\0')
14560          : !(*gvname == 'b' && gvname[1] == '\0'))
14561         return;
14562     o->op_flags &= ~(OPf_STACKED | OPf_SPECIAL);
14563     if (descending)
14564         o->op_private |= OPpSORT_DESCEND;
14565     if (k->op_type == OP_NCMP)
14566         o->op_private |= OPpSORT_NUMERIC;
14567     if (k->op_type == OP_I_NCMP)
14568         o->op_private |= OPpSORT_NUMERIC | OPpSORT_INTEGER;
14569     kid = OpSIBLING(cLISTOPo->op_first);
14570     /* cut out and delete old block (second sibling) */
14571     op_sibling_splice(o, cLISTOPo->op_first, 1, NULL);
14572     op_free(kid);
14573 }
14574
14575 OP *
14576 Perl_ck_split(pTHX_ OP *o)
14577 {
14578     OP *kid;
14579     OP *sibs;
14580
14581     PERL_ARGS_ASSERT_CK_SPLIT;
14582
14583     assert(o->op_type == OP_LIST);
14584
14585     if (o->op_flags & OPf_STACKED)
14586         return no_fh_allowed(o);
14587
14588     kid = cLISTOPo->op_first;
14589     /* delete leading NULL node, then add a CONST if no other nodes */
14590     assert(kid->op_type == OP_NULL);
14591     op_sibling_splice(o, NULL, 1,
14592         OpHAS_SIBLING(kid) ? NULL : newSVOP(OP_CONST, 0, newSVpvs(" ")));
14593     op_free(kid);
14594     kid = cLISTOPo->op_first;
14595
14596     if (kid->op_type != OP_MATCH || kid->op_flags & OPf_STACKED) {
14597         /* remove match expression, and replace with new optree with
14598          * a match op at its head */
14599         op_sibling_splice(o, NULL, 1, NULL);
14600         /* pmruntime will handle split " " behavior with flag==2 */
14601         kid = pmruntime(newPMOP(OP_MATCH, 0), kid, NULL, 2, 0);
14602         op_sibling_splice(o, NULL, 0, kid);
14603     }
14604
14605     assert(kid->op_type == OP_MATCH || kid->op_type == OP_SPLIT);
14606
14607     if (((PMOP *)kid)->op_pmflags & PMf_GLOBAL) {
14608       Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP),
14609                      "Use of /g modifier is meaningless in split");
14610     }
14611
14612     /* eliminate the split op, and move the match op (plus any children)
14613      * into its place, then convert the match op into a split op. i.e.
14614      *
14615      *  SPLIT                    MATCH                 SPLIT(ex-MATCH)
14616      *    |                        |                     |
14617      *  MATCH - A - B - C   =>     R - A - B - C   =>    R - A - B - C
14618      *    |                        |                     |
14619      *    R                        X - Y                 X - Y
14620      *    |
14621      *    X - Y
14622      *
14623      * (R, if it exists, will be a regcomp op)
14624      */
14625
14626     op_sibling_splice(o, NULL, 1, NULL); /* detach match op from o */
14627     sibs = op_sibling_splice(o, NULL, -1, NULL); /* detach any other sibs */
14628     op_sibling_splice(kid, cLISTOPx(kid)->op_last, 0, sibs); /* and reattach */
14629     OpTYPE_set(kid, OP_SPLIT);
14630     kid->op_flags   = (o->op_flags | (kid->op_flags & OPf_KIDS));
14631     kid->op_private = o->op_private;
14632     op_free(o);
14633     o = kid;
14634     kid = sibs; /* kid is now the string arg of the split */
14635
14636     if (!kid) {
14637         kid = newDEFSVOP();
14638         op_append_elem(OP_SPLIT, o, kid);
14639     }
14640     scalar(kid);
14641
14642     kid = OpSIBLING(kid);
14643     if (!kid) {
14644         kid = newSVOP(OP_CONST, 0, newSViv(0));
14645         op_append_elem(OP_SPLIT, o, kid);
14646         o->op_private |= OPpSPLIT_IMPLIM;
14647     }
14648     scalar(kid);
14649
14650     if (OpHAS_SIBLING(kid))
14651         return too_many_arguments_pv(o,OP_DESC(o), 0);
14652
14653     return o;
14654 }
14655
14656 OP *
14657 Perl_ck_stringify(pTHX_ OP *o)
14658 {
14659     OP * const kid = OpSIBLING(cUNOPo->op_first);
14660     PERL_ARGS_ASSERT_CK_STRINGIFY;
14661     if ((   kid->op_type == OP_JOIN || kid->op_type == OP_QUOTEMETA
14662          || kid->op_type == OP_LC   || kid->op_type == OP_LCFIRST
14663          || kid->op_type == OP_UC   || kid->op_type == OP_UCFIRST)
14664         && !OpHAS_SIBLING(kid)) /* syntax errs can leave extra children */
14665     {
14666         op_sibling_splice(o, cUNOPo->op_first, -1, NULL);
14667         op_free(o);
14668         return kid;
14669     }
14670     return ck_fun(o);
14671 }
14672
14673 OP *
14674 Perl_ck_join(pTHX_ OP *o)
14675 {
14676     OP * const kid = OpSIBLING(cLISTOPo->op_first);
14677
14678     PERL_ARGS_ASSERT_CK_JOIN;
14679
14680     if (kid && kid->op_type == OP_MATCH) {
14681         if (ckWARN(WARN_SYNTAX)) {
14682             const REGEXP *re = PM_GETRE(kPMOP);
14683             const SV *msg = re
14684                     ? newSVpvn_flags( RX_PRECOMP_const(re), RX_PRELEN(re),
14685                                             SVs_TEMP | ( RX_UTF8(re) ? SVf_UTF8 : 0 ) )
14686                     : newSVpvs_flags( "STRING", SVs_TEMP );
14687             Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
14688                         "/%" SVf "/ should probably be written as \"%" SVf "\"",
14689                         SVfARG(msg), SVfARG(msg));
14690         }
14691     }
14692     if (kid
14693      && (kid->op_type == OP_CONST /* an innocent, unsuspicious separator */
14694         || (kid->op_type == OP_PADSV && !(kid->op_private & OPpLVAL_INTRO))
14695         || (  kid->op_type==OP_RV2SV && kUNOP->op_first->op_type == OP_GV
14696            && !(kid->op_private & (OPpLVAL_INTRO|OPpOUR_INTRO)))))
14697     {
14698         const OP * const bairn = OpSIBLING(kid); /* the list */
14699         if (bairn && !OpHAS_SIBLING(bairn) /* single-item list */
14700          && OP_GIMME(bairn,0) == G_SCALAR)
14701         {
14702             OP * const ret = op_convert_list(OP_STRINGIFY, OPf_FOLDED,
14703                                      op_sibling_splice(o, kid, 1, NULL));
14704             op_free(o);
14705             return ret;
14706         }
14707     }
14708
14709     return ck_fun(o);
14710 }
14711
14712 /*
14713 =for apidoc rv2cv_op_cv
14714
14715 Examines an op, which is expected to identify a subroutine at runtime,
14716 and attempts to determine at compile time which subroutine it identifies.
14717 This is normally used during Perl compilation to determine whether
14718 a prototype can be applied to a function call.  C<cvop> is the op
14719 being considered, normally an C<rv2cv> op.  A pointer to the identified
14720 subroutine is returned, if it could be determined statically, and a null
14721 pointer is returned if it was not possible to determine statically.
14722
14723 Currently, the subroutine can be identified statically if the RV that the
14724 C<rv2cv> is to operate on is provided by a suitable C<gv> or C<const> op.
14725 A C<gv> op is suitable if the GV's CV slot is populated.  A C<const> op is
14726 suitable if the constant value must be an RV pointing to a CV.  Details of
14727 this process may change in future versions of Perl.  If the C<rv2cv> op
14728 has the C<OPpENTERSUB_AMPER> flag set then no attempt is made to identify
14729 the subroutine statically: this flag is used to suppress compile-time
14730 magic on a subroutine call, forcing it to use default runtime behaviour.
14731
14732 If C<flags> has the bit C<RV2CVOPCV_MARK_EARLY> set, then the handling
14733 of a GV reference is modified.  If a GV was examined and its CV slot was
14734 found to be empty, then the C<gv> op has the C<OPpEARLY_CV> flag set.
14735 If the op is not optimised away, and the CV slot is later populated with
14736 a subroutine having a prototype, that flag eventually triggers the warning
14737 "called too early to check prototype".
14738
14739 If C<flags> has the bit C<RV2CVOPCV_RETURN_NAME_GV> set, then instead
14740 of returning a pointer to the subroutine it returns a pointer to the
14741 GV giving the most appropriate name for the subroutine in this context.
14742 Normally this is just the C<CvGV> of the subroutine, but for an anonymous
14743 (C<CvANON>) subroutine that is referenced through a GV it will be the
14744 referencing GV.  The resulting C<GV*> is cast to C<CV*> to be returned.
14745 A null pointer is returned as usual if there is no statically-determinable
14746 subroutine.
14747
14748 =for apidoc Amnh||OPpEARLY_CV
14749 =for apidoc Amnh||OPpENTERSUB_AMPER
14750 =for apidoc Amnh||RV2CVOPCV_MARK_EARLY
14751 =for apidoc Amnh||RV2CVOPCV_RETURN_NAME_GV
14752
14753 =cut
14754 */
14755
14756 /* shared by toke.c:yylex */
14757 CV *
14758 Perl_find_lexical_cv(pTHX_ PADOFFSET off)
14759 {
14760     PADNAME *name = PAD_COMPNAME(off);
14761     CV *compcv = PL_compcv;
14762     while (PadnameOUTER(name)) {
14763         assert(PARENT_PAD_INDEX(name));
14764         compcv = CvOUTSIDE(compcv);
14765         name = PadlistNAMESARRAY(CvPADLIST(compcv))
14766                 [off = PARENT_PAD_INDEX(name)];
14767     }
14768     assert(!PadnameIsOUR(name));
14769     if (!PadnameIsSTATE(name) && PadnamePROTOCV(name)) {
14770         return PadnamePROTOCV(name);
14771     }
14772     return (CV *)AvARRAY(PadlistARRAY(CvPADLIST(compcv))[1])[off];
14773 }
14774
14775 CV *
14776 Perl_rv2cv_op_cv(pTHX_ OP *cvop, U32 flags)
14777 {
14778     OP *rvop;
14779     CV *cv;
14780     GV *gv;
14781     PERL_ARGS_ASSERT_RV2CV_OP_CV;
14782     if (flags & ~RV2CVOPCV_FLAG_MASK)
14783         Perl_croak(aTHX_ "panic: rv2cv_op_cv bad flags %x", (unsigned)flags);
14784     if (cvop->op_type != OP_RV2CV)
14785         return NULL;
14786     if (cvop->op_private & OPpENTERSUB_AMPER)
14787         return NULL;
14788     if (!(cvop->op_flags & OPf_KIDS))
14789         return NULL;
14790     rvop = cUNOPx(cvop)->op_first;
14791     switch (rvop->op_type) {
14792         case OP_GV: {
14793             gv = cGVOPx_gv(rvop);
14794             if (!isGV(gv)) {
14795                 if (SvROK(gv) && SvTYPE(SvRV(gv)) == SVt_PVCV) {
14796                     cv = MUTABLE_CV(SvRV(gv));
14797                     gv = NULL;
14798                     break;
14799                 }
14800                 if (flags & RV2CVOPCV_RETURN_STUB)
14801                     return (CV *)gv;
14802                 else return NULL;
14803             }
14804             cv = GvCVu(gv);
14805             if (!cv) {
14806                 if (flags & RV2CVOPCV_MARK_EARLY)
14807                     rvop->op_private |= OPpEARLY_CV;
14808                 return NULL;
14809             }
14810         } break;
14811         case OP_CONST: {
14812             SV *rv = cSVOPx_sv(rvop);
14813             if (!SvROK(rv))
14814                 return NULL;
14815             cv = (CV*)SvRV(rv);
14816             gv = NULL;
14817         } break;
14818         case OP_PADCV: {
14819             cv = find_lexical_cv(rvop->op_targ);
14820             gv = NULL;
14821         } break;
14822         default: {
14823             return NULL;
14824         } NOT_REACHED; /* NOTREACHED */
14825     }
14826     if (SvTYPE((SV*)cv) != SVt_PVCV)
14827         return NULL;
14828     if (flags & RV2CVOPCV_RETURN_NAME_GV) {
14829         if ((!CvANON(cv) && !CvLEXICAL(cv)) || !gv)
14830             gv = CvGV(cv);
14831         return (CV*)gv;
14832     }
14833     else if (flags & RV2CVOPCV_MAYBE_NAME_GV) {
14834         if (CvLEXICAL(cv) || CvNAMED(cv))
14835             return NULL;
14836         if (!CvANON(cv) || !gv)
14837             gv = CvGV(cv);
14838         return (CV*)gv;
14839
14840     } else {
14841         return cv;
14842     }
14843 }
14844
14845 /*
14846 =for apidoc ck_entersub_args_list
14847
14848 Performs the default fixup of the arguments part of an C<entersub>
14849 op tree.  This consists of applying list context to each of the
14850 argument ops.  This is the standard treatment used on a call marked
14851 with C<&>, or a method call, or a call through a subroutine reference,
14852 or any other call where the callee can't be identified at compile time,
14853 or a call where the callee has no prototype.
14854
14855 =cut
14856 */
14857
14858 OP *
14859 Perl_ck_entersub_args_list(pTHX_ OP *entersubop)
14860 {
14861     OP *aop;
14862
14863     PERL_ARGS_ASSERT_CK_ENTERSUB_ARGS_LIST;
14864
14865     aop = cUNOPx(entersubop)->op_first;
14866     if (!OpHAS_SIBLING(aop))
14867         aop = cUNOPx(aop)->op_first;
14868     for (aop = OpSIBLING(aop); OpHAS_SIBLING(aop); aop = OpSIBLING(aop)) {
14869         /* skip the extra attributes->import() call implicitly added in
14870          * something like foo(my $x : bar)
14871          */
14872         if (   aop->op_type == OP_ENTERSUB
14873             && (aop->op_flags & OPf_WANT) == OPf_WANT_VOID
14874         )
14875             continue;
14876         list(aop);
14877         op_lvalue(aop, OP_ENTERSUB);
14878     }
14879     return entersubop;
14880 }
14881
14882 /*
14883 =for apidoc ck_entersub_args_proto
14884
14885 Performs the fixup of the arguments part of an C<entersub> op tree
14886 based on a subroutine prototype.  This makes various modifications to
14887 the argument ops, from applying context up to inserting C<refgen> ops,
14888 and checking the number and syntactic types of arguments, as directed by
14889 the prototype.  This is the standard treatment used on a subroutine call,
14890 not marked with C<&>, where the callee can be identified at compile time
14891 and has a prototype.
14892
14893 C<protosv> supplies the subroutine prototype to be applied to the call.
14894 It may be a normal defined scalar, of which the string value will be used.
14895 Alternatively, for convenience, it may be a subroutine object (a C<CV*>
14896 that has been cast to C<SV*>) which has a prototype.  The prototype
14897 supplied, in whichever form, does not need to match the actual callee
14898 referenced by the op tree.
14899
14900 If the argument ops disagree with the prototype, for example by having
14901 an unacceptable number of arguments, a valid op tree is returned anyway.
14902 The error is reflected in the parser state, normally resulting in a single
14903 exception at the top level of parsing which covers all the compilation
14904 errors that occurred.  In the error message, the callee is referred to
14905 by the name defined by the C<namegv> parameter.
14906
14907 =cut
14908 */
14909
14910 OP *
14911 Perl_ck_entersub_args_proto(pTHX_ OP *entersubop, GV *namegv, SV *protosv)
14912 {
14913     STRLEN proto_len;
14914     const char *proto, *proto_end;
14915     OP *aop, *prev, *cvop, *parent;
14916     int optional = 0;
14917     I32 arg = 0;
14918     I32 contextclass = 0;
14919     const char *e = NULL;
14920     PERL_ARGS_ASSERT_CK_ENTERSUB_ARGS_PROTO;
14921     if (SvTYPE(protosv) == SVt_PVCV ? !SvPOK(protosv) : !SvOK(protosv))
14922         Perl_croak(aTHX_ "panic: ck_entersub_args_proto CV with no proto, "
14923                    "flags=%lx", (unsigned long) SvFLAGS(protosv));
14924     if (SvTYPE(protosv) == SVt_PVCV)
14925          proto = CvPROTO(protosv), proto_len = CvPROTOLEN(protosv);
14926     else proto = SvPV(protosv, proto_len);
14927     proto = S_strip_spaces(aTHX_ proto, &proto_len);
14928     proto_end = proto + proto_len;
14929     parent = entersubop;
14930     aop = cUNOPx(entersubop)->op_first;
14931     if (!OpHAS_SIBLING(aop)) {
14932         parent = aop;
14933         aop = cUNOPx(aop)->op_first;
14934     }
14935     prev = aop;
14936     aop = OpSIBLING(aop);
14937     for (cvop = aop; OpHAS_SIBLING(cvop); cvop = OpSIBLING(cvop)) ;
14938     while (aop != cvop) {
14939         OP* o3 = aop;
14940
14941         if (proto >= proto_end)
14942         {
14943             SV * const namesv = cv_name((CV *)namegv, NULL, 0);
14944             yyerror_pv(Perl_form(aTHX_ "Too many arguments for %" SVf,
14945                                         SVfARG(namesv)), SvUTF8(namesv));
14946             return entersubop;
14947         }
14948
14949         switch (*proto) {
14950             case ';':
14951                 optional = 1;
14952                 proto++;
14953                 continue;
14954             case '_':
14955                 /* _ must be at the end */
14956                 if (proto[1] && !memCHRs(";@%", proto[1]))
14957                     goto oops;
14958                 /* FALLTHROUGH */
14959             case '$':
14960                 proto++;
14961                 arg++;
14962                 scalar(aop);
14963                 break;
14964             case '%':
14965             case '@':
14966                 list(aop);
14967                 arg++;
14968                 break;
14969             case '&':
14970                 proto++;
14971                 arg++;
14972                 if (    o3->op_type != OP_UNDEF
14973                     && (o3->op_type != OP_SREFGEN
14974                         || (  cUNOPx(cUNOPx(o3)->op_first)->op_first->op_type
14975                                 != OP_ANONCODE
14976                             && cUNOPx(cUNOPx(o3)->op_first)->op_first->op_type
14977                                 != OP_RV2CV)))
14978                     bad_type_gv(arg, namegv, o3,
14979                             arg == 1 ? "block or sub {}" : "sub {}");
14980                 break;
14981             case '*':
14982                 /* '*' allows any scalar type, including bareword */
14983                 proto++;
14984                 arg++;
14985                 if (o3->op_type == OP_RV2GV)
14986                     goto wrapref;       /* autoconvert GLOB -> GLOBref */
14987                 else if (o3->op_type == OP_CONST)
14988                     o3->op_private &= ~OPpCONST_STRICT;
14989                 scalar(aop);
14990                 break;
14991             case '+':
14992                 proto++;
14993                 arg++;
14994                 if (o3->op_type == OP_RV2AV ||
14995                     o3->op_type == OP_PADAV ||
14996                     o3->op_type == OP_RV2HV ||
14997                     o3->op_type == OP_PADHV
14998                 ) {
14999                     goto wrapref;
15000                 }
15001                 scalar(aop);
15002                 break;
15003             case '[': case ']':
15004                 goto oops;
15005
15006             case '\\':
15007                 proto++;
15008                 arg++;
15009             again:
15010                 switch (*proto++) {
15011                     case '[':
15012                         if (contextclass++ == 0) {
15013                             e = (char *) memchr(proto, ']', proto_end - proto);
15014                             if (!e || e == proto)
15015                                 goto oops;
15016                         }
15017                         else
15018                             goto oops;
15019                         goto again;
15020
15021                     case ']':
15022                         if (contextclass) {
15023                             const char *p = proto;
15024                             const char *const end = proto;
15025                             contextclass = 0;
15026                             while (*--p != '[')
15027                                 /* \[$] accepts any scalar lvalue */
15028                                 if (*p == '$'
15029                                  && Perl_op_lvalue_flags(aTHX_
15030                                      scalar(o3),
15031                                      OP_READ, /* not entersub */
15032                                      OP_LVALUE_NO_CROAK
15033                                     )) goto wrapref;
15034                             bad_type_gv(arg, namegv, o3,
15035                                     Perl_form(aTHX_ "one of %.*s",(int)(end - p), p));
15036                         } else
15037                             goto oops;
15038                         break;
15039                     case '*':
15040                         if (o3->op_type == OP_RV2GV)
15041                             goto wrapref;
15042                         if (!contextclass)
15043                             bad_type_gv(arg, namegv, o3, "symbol");
15044                         break;
15045                     case '&':
15046                         if (o3->op_type == OP_ENTERSUB
15047                          && !(o3->op_flags & OPf_STACKED))
15048                             goto wrapref;
15049                         if (!contextclass)
15050                             bad_type_gv(arg, namegv, o3, "subroutine");
15051                         break;
15052                     case '$':
15053                         if (o3->op_type == OP_RV2SV ||
15054                                 o3->op_type == OP_PADSV ||
15055                                 o3->op_type == OP_HELEM ||
15056                                 o3->op_type == OP_AELEM)
15057                             goto wrapref;
15058                         if (!contextclass) {
15059                             /* \$ accepts any scalar lvalue */
15060                             if (Perl_op_lvalue_flags(aTHX_
15061                                     scalar(o3),
15062                                     OP_READ,  /* not entersub */
15063                                     OP_LVALUE_NO_CROAK
15064                                )) goto wrapref;
15065                             bad_type_gv(arg, namegv, o3, "scalar");
15066                         }
15067                         break;
15068                     case '@':
15069                         if (o3->op_type == OP_RV2AV ||
15070                                 o3->op_type == OP_PADAV)
15071                         {
15072                             o3->op_flags &=~ OPf_PARENS;
15073                             goto wrapref;
15074                         }
15075                         if (!contextclass)
15076                             bad_type_gv(arg, namegv, o3, "array");
15077                         break;
15078                     case '%':
15079                         if (o3->op_type == OP_RV2HV ||
15080                                 o3->op_type == OP_PADHV)
15081                         {
15082                             o3->op_flags &=~ OPf_PARENS;
15083                             goto wrapref;
15084                         }
15085                         if (!contextclass)
15086                             bad_type_gv(arg, namegv, o3, "hash");
15087                         break;
15088                     wrapref:
15089                             aop = S_op_sibling_newUNOP(aTHX_ parent, prev,
15090                                                 OP_REFGEN, 0);
15091                         if (contextclass && e) {
15092                             proto = e + 1;
15093                             contextclass = 0;
15094                         }
15095                         break;
15096                     default: goto oops;
15097                 }
15098                 if (contextclass)
15099                     goto again;
15100                 break;
15101             case ' ':
15102                 proto++;
15103                 continue;
15104             default:
15105             oops: {
15106                 Perl_croak(aTHX_ "Malformed prototype for %" SVf ": %" SVf,
15107                                   SVfARG(cv_name((CV *)namegv, NULL, 0)),
15108                                   SVfARG(protosv));
15109             }
15110         }
15111
15112         op_lvalue(aop, OP_ENTERSUB);
15113         prev = aop;
15114         aop = OpSIBLING(aop);
15115     }
15116     if (aop == cvop && *proto == '_') {
15117         /* generate an access to $_ */
15118         op_sibling_splice(parent, prev, 0, newDEFSVOP());
15119     }
15120     if (!optional && proto_end > proto &&
15121         (*proto != '@' && *proto != '%' && *proto != ';' && *proto != '_'))
15122     {
15123         SV * const namesv = cv_name((CV *)namegv, NULL, 0);
15124         yyerror_pv(Perl_form(aTHX_ "Not enough arguments for %" SVf,
15125                                     SVfARG(namesv)), SvUTF8(namesv));
15126     }
15127     return entersubop;
15128 }
15129
15130 /*
15131 =for apidoc ck_entersub_args_proto_or_list
15132
15133 Performs the fixup of the arguments part of an C<entersub> op tree either
15134 based on a subroutine prototype or using default list-context processing.
15135 This is the standard treatment used on a subroutine call, not marked
15136 with C<&>, where the callee can be identified at compile time.
15137
15138 C<protosv> supplies the subroutine prototype to be applied to the call,
15139 or indicates that there is no prototype.  It may be a normal scalar,
15140 in which case if it is defined then the string value will be used
15141 as a prototype, and if it is undefined then there is no prototype.
15142 Alternatively, for convenience, it may be a subroutine object (a C<CV*>
15143 that has been cast to C<SV*>), of which the prototype will be used if it
15144 has one.  The prototype (or lack thereof) supplied, in whichever form,
15145 does not need to match the actual callee referenced by the op tree.
15146
15147 If the argument ops disagree with the prototype, for example by having
15148 an unacceptable number of arguments, a valid op tree is returned anyway.
15149 The error is reflected in the parser state, normally resulting in a single
15150 exception at the top level of parsing which covers all the compilation
15151 errors that occurred.  In the error message, the callee is referred to
15152 by the name defined by the C<namegv> parameter.
15153
15154 =cut
15155 */
15156
15157 OP *
15158 Perl_ck_entersub_args_proto_or_list(pTHX_ OP *entersubop,
15159         GV *namegv, SV *protosv)
15160 {
15161     PERL_ARGS_ASSERT_CK_ENTERSUB_ARGS_PROTO_OR_LIST;
15162     if (SvTYPE(protosv) == SVt_PVCV ? SvPOK(protosv) : SvOK(protosv))
15163         return ck_entersub_args_proto(entersubop, namegv, protosv);
15164     else
15165         return ck_entersub_args_list(entersubop);
15166 }
15167
15168 OP *
15169 Perl_ck_entersub_args_core(pTHX_ OP *entersubop, GV *namegv, SV *protosv)
15170 {
15171     IV cvflags = SvIVX(protosv);
15172     int opnum = cvflags & 0xffff;
15173     OP *aop = cUNOPx(entersubop)->op_first;
15174
15175     PERL_ARGS_ASSERT_CK_ENTERSUB_ARGS_CORE;
15176
15177     if (!opnum) {
15178         OP *cvop;
15179         if (!OpHAS_SIBLING(aop))
15180             aop = cUNOPx(aop)->op_first;
15181         aop = OpSIBLING(aop);
15182         for (cvop = aop; OpSIBLING(cvop); cvop = OpSIBLING(cvop)) ;
15183         if (aop != cvop) {
15184             SV *namesv = cv_name((CV *)namegv, NULL, CV_NAME_NOTQUAL);
15185             yyerror_pv(Perl_form(aTHX_ "Too many arguments for %" SVf,
15186                 SVfARG(namesv)), SvUTF8(namesv));
15187         }
15188
15189         op_free(entersubop);
15190         switch(cvflags >> 16) {
15191         case 'F': return newSVOP(OP_CONST, 0,
15192                                         newSVpv(CopFILE(PL_curcop),0));
15193         case 'L': return newSVOP(
15194                            OP_CONST, 0,
15195                            Perl_newSVpvf(aTHX_
15196                              "%" IVdf, (IV)CopLINE(PL_curcop)
15197                            )
15198                          );
15199         case 'P': return newSVOP(OP_CONST, 0,
15200                                    (PL_curstash
15201                                      ? newSVhek(HvNAME_HEK(PL_curstash))
15202                                      : &PL_sv_undef
15203                                    )
15204                                 );
15205         }
15206         NOT_REACHED; /* NOTREACHED */
15207     }
15208     else {
15209         OP *prev, *cvop, *first, *parent;
15210         U32 flags = 0;
15211
15212         parent = entersubop;
15213         if (!OpHAS_SIBLING(aop)) {
15214             parent = aop;
15215             aop = cUNOPx(aop)->op_first;
15216         }
15217
15218         first = prev = aop;
15219         aop = OpSIBLING(aop);
15220         /* find last sibling */
15221         for (cvop = aop;
15222              OpHAS_SIBLING(cvop);
15223              prev = cvop, cvop = OpSIBLING(cvop))
15224             ;
15225         if (!(cvop->op_private & OPpENTERSUB_NOPAREN)
15226             /* Usually, OPf_SPECIAL on an op with no args means that it had
15227              * parens, but these have their own meaning for that flag: */
15228             && opnum != OP_VALUES && opnum != OP_KEYS && opnum != OP_EACH
15229             && opnum != OP_DELETE && opnum != OP_EXISTS)
15230                 flags |= OPf_SPECIAL;
15231         /* excise cvop from end of sibling chain */
15232         op_sibling_splice(parent, prev, 1, NULL);
15233         op_free(cvop);
15234         if (aop == cvop) aop = NULL;
15235
15236         /* detach remaining siblings from the first sibling, then
15237          * dispose of original optree */
15238
15239         if (aop)
15240             op_sibling_splice(parent, first, -1, NULL);
15241         op_free(entersubop);
15242
15243         if (cvflags == (OP_ENTEREVAL | (1<<16)))
15244             flags |= OPpEVAL_BYTES <<8;
15245
15246         switch (PL_opargs[opnum] & OA_CLASS_MASK) {
15247         case OA_UNOP:
15248         case OA_BASEOP_OR_UNOP:
15249         case OA_FILESTATOP:
15250             if (!aop)
15251                 return newOP(opnum,flags);       /* zero args */
15252             if (aop == prev)
15253                 return newUNOP(opnum,flags,aop); /* one arg */
15254             /* too many args */
15255             /* FALLTHROUGH */
15256         case OA_BASEOP:
15257             if (aop) {
15258                 SV *namesv;
15259                 OP *nextop;
15260
15261                 namesv = cv_name((CV *)namegv, NULL, CV_NAME_NOTQUAL);
15262                 yyerror_pv(Perl_form(aTHX_ "Too many arguments for %" SVf,
15263                     SVfARG(namesv)), SvUTF8(namesv));
15264                 while (aop) {
15265                     nextop = OpSIBLING(aop);
15266                     op_free(aop);
15267                     aop = nextop;
15268                 }
15269
15270             }
15271             return opnum == OP_RUNCV
15272                 ? newPVOP(OP_RUNCV,0,NULL)
15273                 : newOP(opnum,0);
15274         default:
15275             return op_convert_list(opnum,0,aop);
15276         }
15277     }
15278     NOT_REACHED; /* NOTREACHED */
15279     return entersubop;
15280 }
15281
15282 /*
15283 =for apidoc cv_get_call_checker_flags
15284
15285 Retrieves the function that will be used to fix up a call to C<cv>.
15286 Specifically, the function is applied to an C<entersub> op tree for a
15287 subroutine call, not marked with C<&>, where the callee can be identified
15288 at compile time as C<cv>.
15289
15290 The C-level function pointer is returned in C<*ckfun_p>, an SV argument
15291 for it is returned in C<*ckobj_p>, and control flags are returned in
15292 C<*ckflags_p>.  The function is intended to be called in this manner:
15293
15294  entersubop = (*ckfun_p)(aTHX_ entersubop, namegv, (*ckobj_p));
15295
15296 In this call, C<entersubop> is a pointer to the C<entersub> op,
15297 which may be replaced by the check function, and C<namegv> supplies
15298 the name that should be used by the check function to refer
15299 to the callee of the C<entersub> op if it needs to emit any diagnostics.
15300 It is permitted to apply the check function in non-standard situations,
15301 such as to a call to a different subroutine or to a method call.
15302
15303 C<namegv> may not actually be a GV.  If the C<CALL_CHECKER_REQUIRE_GV>
15304 bit is clear in C<*ckflags_p>, it is permitted to pass a CV or other SV
15305 instead, anything that can be used as the first argument to L</cv_name>.
15306 If the C<CALL_CHECKER_REQUIRE_GV> bit is set in C<*ckflags_p> then the
15307 check function requires C<namegv> to be a genuine GV.
15308
15309 By default, the check function is
15310 L<Perl_ck_entersub_args_proto_or_list|/ck_entersub_args_proto_or_list>,
15311 the SV parameter is C<cv> itself, and the C<CALL_CHECKER_REQUIRE_GV>
15312 flag is clear.  This implements standard prototype processing.  It can
15313 be changed, for a particular subroutine, by L</cv_set_call_checker_flags>.
15314
15315 If the C<CALL_CHECKER_REQUIRE_GV> bit is set in C<gflags> then it
15316 indicates that the caller only knows about the genuine GV version of
15317 C<namegv>, and accordingly the corresponding bit will always be set in
15318 C<*ckflags_p>, regardless of the check function's recorded requirements.
15319 If the C<CALL_CHECKER_REQUIRE_GV> bit is clear in C<gflags> then it
15320 indicates the caller knows about the possibility of passing something
15321 other than a GV as C<namegv>, and accordingly the corresponding bit may
15322 be either set or clear in C<*ckflags_p>, indicating the check function's
15323 recorded requirements.
15324
15325 C<gflags> is a bitset passed into C<cv_get_call_checker_flags>, in which
15326 only the C<CALL_CHECKER_REQUIRE_GV> bit currently has a defined meaning
15327 (for which see above).  All other bits should be clear.
15328
15329 =for apidoc Amnh||CALL_CHECKER_REQUIRE_GV
15330
15331 =for apidoc cv_get_call_checker
15332
15333 The original form of L</cv_get_call_checker_flags>, which does not return
15334 checker flags.  When using a checker function returned by this function,
15335 it is only safe to call it with a genuine GV as its C<namegv> argument.
15336
15337 =cut
15338 */
15339
15340 void
15341 Perl_cv_get_call_checker_flags(pTHX_ CV *cv, U32 gflags,
15342         Perl_call_checker *ckfun_p, SV **ckobj_p, U32 *ckflags_p)
15343 {
15344     MAGIC *callmg;
15345     PERL_ARGS_ASSERT_CV_GET_CALL_CHECKER_FLAGS;
15346     PERL_UNUSED_CONTEXT;
15347     callmg = SvMAGICAL((SV*)cv) ? mg_find((SV*)cv, PERL_MAGIC_checkcall) : NULL;
15348     if (callmg) {
15349         *ckfun_p = DPTR2FPTR(Perl_call_checker, callmg->mg_ptr);
15350         *ckobj_p = callmg->mg_obj;
15351         *ckflags_p = (callmg->mg_flags | gflags) & MGf_REQUIRE_GV;
15352     } else {
15353         *ckfun_p = Perl_ck_entersub_args_proto_or_list;
15354         *ckobj_p = (SV*)cv;
15355         *ckflags_p = gflags & MGf_REQUIRE_GV;
15356     }
15357 }
15358
15359 void
15360 Perl_cv_get_call_checker(pTHX_ CV *cv, Perl_call_checker *ckfun_p, SV **ckobj_p)
15361 {
15362     U32 ckflags;
15363     PERL_ARGS_ASSERT_CV_GET_CALL_CHECKER;
15364     PERL_UNUSED_CONTEXT;
15365     cv_get_call_checker_flags(cv, CALL_CHECKER_REQUIRE_GV, ckfun_p, ckobj_p,
15366         &ckflags);
15367 }
15368
15369 /*
15370 =for apidoc cv_set_call_checker_flags
15371
15372 Sets the function that will be used to fix up a call to C<cv>.
15373 Specifically, the function is applied to an C<entersub> op tree for a
15374 subroutine call, not marked with C<&>, where the callee can be identified
15375 at compile time as C<cv>.
15376
15377 The C-level function pointer is supplied in C<ckfun>, an SV argument for
15378 it is supplied in C<ckobj>, and control flags are supplied in C<ckflags>.
15379 The function should be defined like this:
15380
15381     STATIC OP * ckfun(pTHX_ OP *op, GV *namegv, SV *ckobj)
15382
15383 It is intended to be called in this manner:
15384
15385     entersubop = ckfun(aTHX_ entersubop, namegv, ckobj);
15386
15387 In this call, C<entersubop> is a pointer to the C<entersub> op,
15388 which may be replaced by the check function, and C<namegv> supplies
15389 the name that should be used by the check function to refer
15390 to the callee of the C<entersub> op if it needs to emit any diagnostics.
15391 It is permitted to apply the check function in non-standard situations,
15392 such as to a call to a different subroutine or to a method call.
15393
15394 C<namegv> may not actually be a GV.  For efficiency, perl may pass a
15395 CV or other SV instead.  Whatever is passed can be used as the first
15396 argument to L</cv_name>.  You can force perl to pass a GV by including
15397 C<CALL_CHECKER_REQUIRE_GV> in the C<ckflags>.
15398
15399 C<ckflags> is a bitset, in which only the C<CALL_CHECKER_REQUIRE_GV>
15400 bit currently has a defined meaning (for which see above).  All other
15401 bits should be clear.
15402
15403 The current setting for a particular CV can be retrieved by
15404 L</cv_get_call_checker_flags>.
15405
15406 =for apidoc cv_set_call_checker
15407
15408 The original form of L</cv_set_call_checker_flags>, which passes it the
15409 C<CALL_CHECKER_REQUIRE_GV> flag for backward-compatibility.  The effect
15410 of that flag setting is that the check function is guaranteed to get a
15411 genuine GV as its C<namegv> argument.
15412
15413 =cut
15414 */
15415
15416 void
15417 Perl_cv_set_call_checker(pTHX_ CV *cv, Perl_call_checker ckfun, SV *ckobj)
15418 {
15419     PERL_ARGS_ASSERT_CV_SET_CALL_CHECKER;
15420     cv_set_call_checker_flags(cv, ckfun, ckobj, CALL_CHECKER_REQUIRE_GV);
15421 }
15422
15423 void
15424 Perl_cv_set_call_checker_flags(pTHX_ CV *cv, Perl_call_checker ckfun,
15425                                      SV *ckobj, U32 ckflags)
15426 {
15427     PERL_ARGS_ASSERT_CV_SET_CALL_CHECKER_FLAGS;
15428     if (ckfun == Perl_ck_entersub_args_proto_or_list && ckobj == (SV*)cv) {
15429         if (SvMAGICAL((SV*)cv))
15430             mg_free_type((SV*)cv, PERL_MAGIC_checkcall);
15431     } else {
15432         MAGIC *callmg;
15433         sv_magic((SV*)cv, &PL_sv_undef, PERL_MAGIC_checkcall, NULL, 0);
15434         callmg = mg_find((SV*)cv, PERL_MAGIC_checkcall);
15435         assert(callmg);
15436         if (callmg->mg_flags & MGf_REFCOUNTED) {
15437             SvREFCNT_dec(callmg->mg_obj);
15438             callmg->mg_flags &= ~MGf_REFCOUNTED;
15439         }
15440         callmg->mg_ptr = FPTR2DPTR(char *, ckfun);
15441         callmg->mg_obj = ckobj;
15442         if (ckobj != (SV*)cv) {
15443             SvREFCNT_inc_simple_void_NN(ckobj);
15444             callmg->mg_flags |= MGf_REFCOUNTED;
15445         }
15446         callmg->mg_flags = (callmg->mg_flags &~ MGf_REQUIRE_GV)
15447                          | (U8)(ckflags & MGf_REQUIRE_GV) | MGf_COPY;
15448     }
15449 }
15450
15451 static void
15452 S_entersub_alloc_targ(pTHX_ OP * const o)
15453 {
15454     o->op_targ = pad_alloc(OP_ENTERSUB, SVs_PADTMP);
15455     o->op_private |= OPpENTERSUB_HASTARG;
15456 }
15457
15458 OP *
15459 Perl_ck_subr(pTHX_ OP *o)
15460 {
15461     OP *aop, *cvop;
15462     CV *cv;
15463     GV *namegv;
15464     SV **const_class = NULL;
15465
15466     PERL_ARGS_ASSERT_CK_SUBR;
15467
15468     aop = cUNOPx(o)->op_first;
15469     if (!OpHAS_SIBLING(aop))
15470         aop = cUNOPx(aop)->op_first;
15471     aop = OpSIBLING(aop);
15472     for (cvop = aop; OpHAS_SIBLING(cvop); cvop = OpSIBLING(cvop)) ;
15473     cv = rv2cv_op_cv(cvop, RV2CVOPCV_MARK_EARLY);
15474     namegv = cv ? (GV*)rv2cv_op_cv(cvop, RV2CVOPCV_MAYBE_NAME_GV) : NULL;
15475
15476     o->op_private &= ~1;
15477     o->op_private |= (PL_hints & HINT_STRICT_REFS);
15478     if (PERLDB_SUB && PL_curstash != PL_debstash)
15479         o->op_private |= OPpENTERSUB_DB;
15480     switch (cvop->op_type) {
15481         case OP_RV2CV:
15482             o->op_private |= (cvop->op_private & OPpENTERSUB_AMPER);
15483             op_null(cvop);
15484             break;
15485         case OP_METHOD:
15486         case OP_METHOD_NAMED:
15487         case OP_METHOD_SUPER:
15488         case OP_METHOD_REDIR:
15489         case OP_METHOD_REDIR_SUPER:
15490             o->op_flags |= OPf_REF;
15491             if (aop->op_type == OP_CONST) {
15492                 aop->op_private &= ~OPpCONST_STRICT;
15493                 const_class = &cSVOPx(aop)->op_sv;
15494             }
15495             else if (aop->op_type == OP_LIST) {
15496                 OP * const sib = OpSIBLING(((UNOP*)aop)->op_first);
15497                 if (sib && sib->op_type == OP_CONST) {
15498                     sib->op_private &= ~OPpCONST_STRICT;
15499                     const_class = &cSVOPx(sib)->op_sv;
15500                 }
15501             }
15502             /* make class name a shared cow string to speedup method calls */
15503             /* constant string might be replaced with object, f.e. bigint */
15504             if (const_class && SvPOK(*const_class)) {
15505                 STRLEN len;
15506                 const char* str = SvPV(*const_class, len);
15507                 if (len) {
15508                     SV* const shared = newSVpvn_share(
15509                         str, SvUTF8(*const_class)
15510                                     ? -(SSize_t)len : (SSize_t)len,
15511                         0
15512                     );
15513                     if (SvREADONLY(*const_class))
15514                         SvREADONLY_on(shared);
15515                     SvREFCNT_dec(*const_class);
15516                     *const_class = shared;
15517                 }
15518             }
15519             break;
15520     }
15521
15522     if (!cv) {
15523         S_entersub_alloc_targ(aTHX_ o);
15524         return ck_entersub_args_list(o);
15525     } else {
15526         Perl_call_checker ckfun;
15527         SV *ckobj;
15528         U32 ckflags;
15529         cv_get_call_checker_flags(cv, 0, &ckfun, &ckobj, &ckflags);
15530         if (CvISXSUB(cv) || !CvROOT(cv))
15531             S_entersub_alloc_targ(aTHX_ o);
15532         if (!namegv) {
15533             /* The original call checker API guarantees that a GV will
15534                be provided with the right name.  So, if the old API was
15535                used (or the REQUIRE_GV flag was passed), we have to reify
15536                the CV’s GV, unless this is an anonymous sub.  This is not
15537                ideal for lexical subs, as its stringification will include
15538                the package.  But it is the best we can do.  */
15539             if (ckflags & CALL_CHECKER_REQUIRE_GV) {
15540                 if (!CvANON(cv) && (!CvNAMED(cv) || CvNAME_HEK(cv)))
15541                     namegv = CvGV(cv);
15542             }
15543             else namegv = MUTABLE_GV(cv);
15544             /* After a syntax error in a lexical sub, the cv that
15545                rv2cv_op_cv returns may be a nameless stub. */
15546             if (!namegv) return ck_entersub_args_list(o);
15547
15548         }
15549         return ckfun(aTHX_ o, namegv, ckobj);
15550     }
15551 }
15552
15553 OP *
15554 Perl_ck_svconst(pTHX_ OP *o)
15555 {
15556     SV * const sv = cSVOPo->op_sv;
15557     PERL_ARGS_ASSERT_CK_SVCONST;
15558     PERL_UNUSED_CONTEXT;
15559 #ifdef PERL_COPY_ON_WRITE
15560     /* Since the read-only flag may be used to protect a string buffer, we
15561        cannot do copy-on-write with existing read-only scalars that are not
15562        already copy-on-write scalars.  To allow $_ = "hello" to do COW with
15563        that constant, mark the constant as COWable here, if it is not
15564        already read-only. */
15565     if (!SvREADONLY(sv) && !SvIsCOW(sv) && SvCANCOW(sv)) {
15566         SvIsCOW_on(sv);
15567         CowREFCNT(sv) = 0;
15568 # ifdef PERL_DEBUG_READONLY_COW
15569         sv_buf_to_ro(sv);
15570 # endif
15571     }
15572 #endif
15573     SvREADONLY_on(sv);
15574     return o;
15575 }
15576
15577 OP *
15578 Perl_ck_trunc(pTHX_ OP *o)
15579 {
15580     PERL_ARGS_ASSERT_CK_TRUNC;
15581
15582     if (o->op_flags & OPf_KIDS) {
15583         SVOP *kid = (SVOP*)cUNOPo->op_first;
15584
15585         if (kid->op_type == OP_NULL)
15586             kid = (SVOP*)OpSIBLING(kid);
15587         if (kid && kid->op_type == OP_CONST &&
15588             (kid->op_private & OPpCONST_BARE) &&
15589             !kid->op_folded)
15590         {
15591             o->op_flags |= OPf_SPECIAL;
15592             kid->op_private &= ~OPpCONST_STRICT;
15593             if (!FEATURE_BAREWORD_FILEHANDLES_IS_ENABLED) {
15594                 no_bareword_filehandle(SvPVX(cSVOPx_sv(kid)));
15595             }
15596         }
15597     }
15598     return ck_fun(o);
15599 }
15600
15601 OP *
15602 Perl_ck_substr(pTHX_ OP *o)
15603 {
15604     PERL_ARGS_ASSERT_CK_SUBSTR;
15605
15606     o = ck_fun(o);
15607     if ((o->op_flags & OPf_KIDS) && (o->op_private == 4)) {
15608         OP *kid = cLISTOPo->op_first;
15609
15610         if (kid->op_type == OP_NULL)
15611             kid = OpSIBLING(kid);
15612         if (kid)
15613             /* Historically, substr(delete $foo{bar},...) has been allowed
15614                with 4-arg substr.  Keep it working by applying entersub
15615                lvalue context.  */
15616             op_lvalue(kid, OP_ENTERSUB);
15617
15618     }
15619     return o;
15620 }
15621
15622 OP *
15623 Perl_ck_tell(pTHX_ OP *o)
15624 {
15625     PERL_ARGS_ASSERT_CK_TELL;
15626     o = ck_fun(o);
15627     if (o->op_flags & OPf_KIDS) {
15628      OP *kid = cLISTOPo->op_first;
15629      if (kid->op_type == OP_NULL && OpHAS_SIBLING(kid)) kid = OpSIBLING(kid);
15630      if (kid->op_type == OP_RV2GV) kid->op_private |= OPpALLOW_FAKE;
15631     }
15632     return o;
15633 }
15634
15635 PERL_STATIC_INLINE OP *
15636 S_last_non_null_kid(OP *o) {
15637     OP *last = NULL;
15638     if (cUNOPo->op_flags & OPf_KIDS) {
15639         OP *k = cLISTOPo->op_first;
15640         while (k) {
15641             if (k->op_type != OP_NULL) {
15642                 last = k;
15643             }
15644             k = OpSIBLING(k);
15645         }
15646     }
15647
15648     return last;
15649 }
15650
15651 OP *
15652 Perl_ck_each(pTHX_ OP *o)
15653 {
15654     OP *kid = o->op_flags & OPf_KIDS ? cUNOPo->op_first : NULL;
15655     const unsigned orig_type  = o->op_type;
15656
15657     PERL_ARGS_ASSERT_CK_EACH;
15658
15659     if (kid) {
15660         switch (kid->op_type) {
15661             case OP_PADHV:
15662                 break;
15663
15664             case OP_RV2HV:
15665                 /* Catch out an anonhash here, since the behaviour might be
15666                  * confusing.
15667                  *
15668                  * The typical tree is:
15669                  *
15670                  *     rv2hv
15671                  *         scope
15672                  *             null
15673                  *             anonhash
15674                  *
15675                  * If the contents of the block is more complex you might get:
15676                  *
15677                  *     rv2hv
15678                  *         leave
15679                  *             enter
15680                  *             ...
15681                  *             anonhash
15682                  *
15683                  * Similarly for the anonlist version below.
15684                  */
15685                 if (orig_type == OP_EACH &&
15686                     ckWARN(WARN_SYNTAX) &&
15687                     (cUNOPx(kid)->op_flags & OPf_KIDS) &&
15688                     ( cUNOPx(kid)->op_first->op_type == OP_SCOPE ||
15689                       cUNOPx(kid)->op_first->op_type == OP_LEAVE) &&
15690                     (cUNOPx(kid)->op_first->op_flags & OPf_KIDS)) {
15691                     /* look for last non-null kid, since we might have:
15692                        each %{ some code ; +{ anon hash } }
15693                     */
15694                     OP *k = S_last_non_null_kid(cUNOPx(kid)->op_first);
15695                     if (k && k->op_type == OP_ANONHASH) {
15696                         /* diag_listed_as: each on anonymous %s will always start from the beginning */
15697                         Perl_warner(aTHX_ packWARN(WARN_SYNTAX), "each on anonymous hash will always start from the beginning");
15698                     }
15699                 }
15700                 break;
15701             case OP_RV2AV:
15702                 if (orig_type == OP_EACH &&
15703                     ckWARN(WARN_SYNTAX) &&
15704                     (cUNOPx(kid)->op_flags & OPf_KIDS) &&
15705                     (cUNOPx(kid)->op_first->op_type == OP_SCOPE ||
15706                      cUNOPx(kid)->op_first->op_type == OP_LEAVE) &&
15707                     (cUNOPx(kid)->op_first->op_flags & OPf_KIDS)) {
15708                     OP *k = S_last_non_null_kid(cUNOPx(kid)->op_first);
15709                     if (k && k->op_type == OP_ANONLIST) {
15710                         /* diag_listed_as: each on anonymous %s will always start from the beginning */
15711                         Perl_warner(aTHX_ packWARN(WARN_SYNTAX), "each on anonymous array will always start from the beginning");
15712                     }
15713                 }
15714                 /* FALLTHROUGH */
15715             case OP_PADAV:
15716                 OpTYPE_set(o, orig_type == OP_EACH ? OP_AEACH
15717                             : orig_type == OP_KEYS ? OP_AKEYS
15718                             :                        OP_AVALUES);
15719                 break;
15720             case OP_CONST:
15721                 if (kid->op_private == OPpCONST_BARE
15722                  || !SvROK(cSVOPx_sv(kid))
15723                  || (  SvTYPE(SvRV(cSVOPx_sv(kid))) != SVt_PVAV
15724                     && SvTYPE(SvRV(cSVOPx_sv(kid))) != SVt_PVHV  )
15725                    )
15726                     goto bad;
15727                 /* FALLTHROUGH */
15728             default:
15729                 qerror(Perl_mess(aTHX_
15730                     "Experimental %s on scalar is now forbidden",
15731                      PL_op_desc[orig_type]));
15732                bad:
15733                 bad_type_pv(1, "hash or array", o, kid);
15734                 return o;
15735         }
15736     }
15737     return ck_fun(o);
15738 }
15739
15740 OP *
15741 Perl_ck_length(pTHX_ OP *o)
15742 {
15743     PERL_ARGS_ASSERT_CK_LENGTH;
15744
15745     o = ck_fun(o);
15746
15747     if (ckWARN(WARN_SYNTAX)) {
15748         const OP *kid = o->op_flags & OPf_KIDS ? cLISTOPo->op_first : NULL;
15749
15750         if (kid) {
15751             SV *name = NULL;
15752             const bool hash = kid->op_type == OP_PADHV
15753                            || kid->op_type == OP_RV2HV;
15754             switch (kid->op_type) {
15755                 case OP_PADHV:
15756                 case OP_PADAV:
15757                 case OP_RV2HV:
15758                 case OP_RV2AV:
15759                     name = S_op_varname(aTHX_ kid);
15760                     break;
15761                 default:
15762                     return o;
15763             }
15764             if (name)
15765                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
15766                     "length() used on %" SVf " (did you mean \"scalar(%s%" SVf
15767                     ")\"?)",
15768                     SVfARG(name), hash ? "keys " : "", SVfARG(name)
15769                 );
15770             else if (hash)
15771      /* diag_listed_as: length() used on %s (did you mean "scalar(%s)"?) */
15772                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
15773                     "length() used on %%hash (did you mean \"scalar(keys %%hash)\"?)");
15774             else
15775      /* diag_listed_as: length() used on %s (did you mean "scalar(%s)"?) */
15776                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
15777                     "length() used on @array (did you mean \"scalar(@array)\"?)");
15778         }
15779     }
15780
15781     return o;
15782 }
15783
15784
15785 OP *
15786 Perl_ck_isa(pTHX_ OP *o)
15787 {
15788     OP *classop = cBINOPo->op_last;
15789
15790     PERL_ARGS_ASSERT_CK_ISA;
15791
15792     /* Convert barename into PV */
15793     if(classop->op_type == OP_CONST && classop->op_private & OPpCONST_BARE) {
15794         /* TODO: Optionally convert package to raw HV here */
15795         classop->op_private &= ~(OPpCONST_BARE|OPpCONST_STRICT);
15796     }
15797
15798     return o;
15799 }
15800
15801
15802 /*
15803    ---------------------------------------------------------
15804
15805    Common vars in list assignment
15806
15807    There now follows some enums and static functions for detecting
15808    common variables in list assignments. Here is a little essay I wrote
15809    for myself when trying to get my head around this. DAPM.
15810
15811    ----
15812
15813    First some random observations:
15814
15815    * If a lexical var is an alias of something else, e.g.
15816        for my $x ($lex, $pkg, $a[0]) {...}
15817      then the act of aliasing will increase the reference count of the SV
15818
15819    * If a package var is an alias of something else, it may still have a
15820      reference count of 1, depending on how the alias was created, e.g.
15821      in *a = *b, $a may have a refcount of 1 since the GP is shared
15822      with a single GvSV pointer to the SV. So If it's an alias of another
15823      package var, then RC may be 1; if it's an alias of another scalar, e.g.
15824      a lexical var or an array element, then it will have RC > 1.
15825
15826    * There are many ways to create a package alias; ultimately, XS code
15827      may quite legally do GvSV(gv) = SvREFCNT_inc(sv) for example, so
15828      run-time tracing mechanisms are unlikely to be able to catch all cases.
15829
15830    * When the LHS is all my declarations, the same vars can't appear directly
15831      on the RHS, but they can indirectly via closures, aliasing and lvalue
15832      subs. But those techniques all involve an increase in the lexical
15833      scalar's ref count.
15834
15835    * When the LHS is all lexical vars (but not necessarily my declarations),
15836      it is possible for the same lexicals to appear directly on the RHS, and
15837      without an increased ref count, since the stack isn't refcounted.
15838      This case can be detected at compile time by scanning for common lex
15839      vars with PL_generation.
15840
15841    * lvalue subs defeat common var detection, but they do at least
15842      return vars with a temporary ref count increment. Also, you can't
15843      tell at compile time whether a sub call is lvalue.
15844
15845
15846    So...
15847
15848    A: There are a few circumstances where there definitely can't be any
15849      commonality:
15850
15851        LHS empty:  () = (...);
15852        RHS empty:  (....) = ();
15853        RHS contains only constants or other 'can't possibly be shared'
15854            elements (e.g. ops that return PADTMPs):  (...) = (1,2, length)
15855            i.e. they only contain ops not marked as dangerous, whose children
15856            are also not dangerous;
15857        LHS ditto;
15858        LHS contains a single scalar element: e.g. ($x) = (....); because
15859            after $x has been modified, it won't be used again on the RHS;
15860        RHS contains a single element with no aggregate on LHS: e.g.
15861            ($a,$b,$c)  = ($x); again, once $a has been modified, its value
15862            won't be used again.
15863
15864    B: If LHS are all 'my' lexical var declarations (or safe ops, which
15865      we can ignore):
15866
15867        my ($a, $b, @c) = ...;
15868
15869        Due to closure and goto tricks, these vars may already have content.
15870        For the same reason, an element on the RHS may be a lexical or package
15871        alias of one of the vars on the left, or share common elements, for
15872        example:
15873
15874            my ($x,$y) = f(); # $x and $y on both sides
15875            sub f : lvalue { ($x,$y) = (1,2); $y, $x }
15876
15877        and
15878
15879            my $ra = f();
15880            my @a = @$ra;  # elements of @a on both sides
15881            sub f { @a = 1..4; \@a }
15882
15883
15884        First, just consider scalar vars on LHS:
15885
15886            RHS is safe only if (A), or in addition,
15887                * contains only lexical *scalar* vars, where neither side's
15888                  lexicals have been flagged as aliases
15889
15890            If RHS is not safe, then it's always legal to check LHS vars for
15891            RC==1, since the only RHS aliases will always be associated
15892            with an RC bump.
15893
15894            Note that in particular, RHS is not safe if:
15895
15896                * it contains package scalar vars; e.g.:
15897
15898                    f();
15899                    my ($x, $y) = (2, $x_alias);
15900                    sub f { $x = 1; *x_alias = \$x; }
15901
15902                * It contains other general elements, such as flattened or
15903                * spliced or single array or hash elements, e.g.
15904
15905                    f();
15906                    my ($x,$y) = @a; # or $a[0] or @a{@b} etc
15907
15908                    sub f {
15909                        ($x, $y) = (1,2);
15910                        use feature 'refaliasing';
15911                        \($a[0], $a[1]) = \($y,$x);
15912                    }
15913
15914                  It doesn't matter if the array/hash is lexical or package.
15915
15916                * it contains a function call that happens to be an lvalue
15917                  sub which returns one or more of the above, e.g.
15918
15919                    f();
15920                    my ($x,$y) = f();
15921
15922                    sub f : lvalue {
15923                        ($x, $y) = (1,2);
15924                        *x1 = \$x;
15925                        $y, $x1;
15926                    }
15927
15928                    (so a sub call on the RHS should be treated the same
15929                    as having a package var on the RHS).
15930
15931                * any other "dangerous" thing, such an op or built-in that
15932                  returns one of the above, e.g. pp_preinc
15933
15934
15935            If RHS is not safe, what we can do however is at compile time flag
15936            that the LHS are all my declarations, and at run time check whether
15937            all the LHS have RC == 1, and if so skip the full scan.
15938
15939        Now consider array and hash vars on LHS: e.g. my (...,@a) = ...;
15940
15941            Here the issue is whether there can be elements of @a on the RHS
15942            which will get prematurely freed when @a is cleared prior to
15943            assignment. This is only a problem if the aliasing mechanism
15944            is one which doesn't increase the refcount - only if RC == 1
15945            will the RHS element be prematurely freed.
15946
15947            Because the array/hash is being INTROed, it or its elements
15948            can't directly appear on the RHS:
15949
15950                my (@a) = ($a[0], @a, etc) # NOT POSSIBLE
15951
15952            but can indirectly, e.g.:
15953
15954                my $r = f();
15955                my (@a) = @$r;
15956                sub f { @a = 1..3; \@a }
15957
15958            So if the RHS isn't safe as defined by (A), we must always
15959            mortalise and bump the ref count of any remaining RHS elements
15960            when assigning to a non-empty LHS aggregate.
15961
15962            Lexical scalars on the RHS aren't safe if they've been involved in
15963            aliasing, e.g.
15964
15965                use feature 'refaliasing';
15966
15967                f();
15968                \(my $lex) = \$pkg;
15969                my @a = ($lex,3); # equivalent to ($a[0],3)
15970
15971                sub f {
15972                    @a = (1,2);
15973                    \$pkg = \$a[0];
15974                }
15975
15976            Similarly with lexical arrays and hashes on the RHS:
15977
15978                f();
15979                my @b;
15980                my @a = (@b);
15981
15982                sub f {
15983                    @a = (1,2);
15984                    \$b[0] = \$a[1];
15985                    \$b[1] = \$a[0];
15986                }
15987
15988
15989
15990    C: As (B), but in addition the LHS may contain non-intro lexicals, e.g.
15991        my $a; ($a, my $b) = (....);
15992
15993        The difference between (B) and (C) is that it is now physically
15994        possible for the LHS vars to appear on the RHS too, where they
15995        are not reference counted; but in this case, the compile-time
15996        PL_generation sweep will detect such common vars.
15997
15998        So the rules for (C) differ from (B) in that if common vars are
15999        detected, the runtime "test RC==1" optimisation can no longer be used,
16000        and a full mark and sweep is required
16001
16002    D: As (C), but in addition the LHS may contain package vars.
16003
16004        Since package vars can be aliased without a corresponding refcount
16005        increase, all bets are off. It's only safe if (A). E.g.
16006
16007            my ($x, $y) = (1,2);
16008
16009            for $x_alias ($x) {
16010                ($x_alias, $y) = (3, $x); # whoops
16011            }
16012
16013        Ditto for LHS aggregate package vars.
16014
16015    E: Any other dangerous ops on LHS, e.g.
16016            (f(), $a[0], @$r) = (...);
16017
16018        this is similar to (E) in that all bets are off. In addition, it's
16019        impossible to determine at compile time whether the LHS
16020        contains a scalar or an aggregate, e.g.
16021
16022            sub f : lvalue { @a }
16023            (f()) = 1..3;
16024
16025 * ---------------------------------------------------------
16026 */
16027
16028
16029 /* A set of bit flags returned by S_aassign_scan(). Each flag indicates
16030  * that at least one of the things flagged was seen.
16031  */
16032
16033 enum {
16034     AAS_MY_SCALAR       = 0x001, /* my $scalar */
16035     AAS_MY_AGG          = 0x002, /* aggregate: my @array or my %hash */
16036     AAS_LEX_SCALAR      = 0x004, /* $lexical */
16037     AAS_LEX_AGG         = 0x008, /* @lexical or %lexical aggregate */
16038     AAS_LEX_SCALAR_COMM = 0x010, /* $lexical seen on both sides */
16039     AAS_PKG_SCALAR      = 0x020, /* $scalar (where $scalar is pkg var) */
16040     AAS_PKG_AGG         = 0x040, /* package @array or %hash aggregate */
16041     AAS_DANGEROUS       = 0x080, /* an op (other than the above)
16042                                          that's flagged OA_DANGEROUS */
16043     AAS_SAFE_SCALAR     = 0x100, /* produces at least one scalar SV that's
16044                                         not in any of the categories above */
16045     AAS_DEFAV           = 0x200  /* contains just a single '@_' on RHS */
16046 };
16047
16048
16049
16050 /* helper function for S_aassign_scan().
16051  * check a PAD-related op for commonality and/or set its generation number.
16052  * Returns a boolean indicating whether its shared */
16053
16054 static bool
16055 S_aassign_padcheck(pTHX_ OP* o, bool rhs)
16056 {
16057     if (PAD_COMPNAME_GEN(o->op_targ) == PERL_INT_MAX)
16058         /* lexical used in aliasing */
16059         return TRUE;
16060
16061     if (rhs)
16062         return cBOOL(PAD_COMPNAME_GEN(o->op_targ) == (STRLEN)PL_generation);
16063     else
16064         PAD_COMPNAME_GEN_set(o->op_targ, PL_generation);
16065
16066     return FALSE;
16067 }
16068
16069
16070 /*
16071   Helper function for OPpASSIGN_COMMON* detection in rpeep().
16072   It scans the left or right hand subtree of the aassign op, and returns a
16073   set of flags indicating what sorts of things it found there.
16074   'rhs' indicates whether we're scanning the LHS or RHS. If the former, we
16075   set PL_generation on lexical vars; if the latter, we see if
16076   PL_generation matches.
16077   'scalars_p' is a pointer to a counter of the number of scalar SVs seen.
16078   This fn will increment it by the number seen. It's not intended to
16079   be an accurate count (especially as many ops can push a variable
16080   number of SVs onto the stack); rather it's used as to test whether there
16081   can be at most 1 SV pushed; so it's only meanings are "0, 1, many".
16082 */
16083
16084 static int
16085 S_aassign_scan(pTHX_ OP* o, bool rhs, int *scalars_p)
16086 {
16087     OP *top_op           = o;
16088     OP *effective_top_op = o;
16089     int all_flags = 0;
16090
16091     while (1) {
16092     bool top = o == effective_top_op;
16093     int flags = 0;
16094     OP* next_kid = NULL;
16095
16096     /* first, look for a solitary @_ on the RHS */
16097     if (   rhs
16098         && top
16099         && (o->op_flags & OPf_KIDS)
16100         && OP_TYPE_IS_OR_WAS(o, OP_LIST)
16101     ) {
16102         OP *kid = cUNOPo->op_first;
16103         if (   (   kid->op_type == OP_PUSHMARK
16104                 || kid->op_type == OP_PADRANGE) /* ex-pushmark */
16105             && ((kid = OpSIBLING(kid)))
16106             && !OpHAS_SIBLING(kid)
16107             && kid->op_type == OP_RV2AV
16108             && !(kid->op_flags & OPf_REF)
16109             && !(kid->op_private & (OPpLVAL_INTRO|OPpMAYBE_LVSUB))
16110             && ((kid->op_flags & OPf_WANT) == OPf_WANT_LIST)
16111             && ((kid = cUNOPx(kid)->op_first))
16112             && kid->op_type == OP_GV
16113             && cGVOPx_gv(kid) == PL_defgv
16114         )
16115             flags = AAS_DEFAV;
16116     }
16117
16118     switch (o->op_type) {
16119     case OP_GVSV:
16120         (*scalars_p)++;
16121         all_flags |= AAS_PKG_SCALAR;
16122         goto do_next;
16123
16124     case OP_PADAV:
16125     case OP_PADHV:
16126         (*scalars_p) += 2;
16127         /* if !top, could be e.g. @a[0,1] */
16128         all_flags |=  (top && (o->op_flags & OPf_REF))
16129                         ? ((o->op_private & OPpLVAL_INTRO)
16130                             ? AAS_MY_AGG : AAS_LEX_AGG)
16131                         : AAS_DANGEROUS;
16132         goto do_next;
16133
16134     case OP_PADSV:
16135         {
16136             int comm = S_aassign_padcheck(aTHX_ o, rhs)
16137                         ?  AAS_LEX_SCALAR_COMM : 0;
16138             (*scalars_p)++;
16139             all_flags |= (o->op_private & OPpLVAL_INTRO)
16140                 ? (AAS_MY_SCALAR|comm) : (AAS_LEX_SCALAR|comm);
16141             goto do_next;
16142
16143         }
16144
16145     case OP_RV2AV:
16146     case OP_RV2HV:
16147         (*scalars_p) += 2;
16148         if (cUNOPx(o)->op_first->op_type != OP_GV)
16149             all_flags |= AAS_DANGEROUS; /* @{expr}, %{expr} */
16150         /* @pkg, %pkg */
16151         /* if !top, could be e.g. @a[0,1] */
16152         else if (top && (o->op_flags & OPf_REF))
16153             all_flags |= AAS_PKG_AGG;
16154         else
16155             all_flags |= AAS_DANGEROUS;
16156         goto do_next;
16157
16158     case OP_RV2SV:
16159         (*scalars_p)++;
16160         if (cUNOPx(o)->op_first->op_type != OP_GV) {
16161             (*scalars_p) += 2;
16162             all_flags |= AAS_DANGEROUS; /* ${expr} */
16163         }
16164         else
16165             all_flags |= AAS_PKG_SCALAR; /* $pkg */
16166         goto do_next;
16167
16168     case OP_SPLIT:
16169         if (o->op_private & OPpSPLIT_ASSIGN) {
16170             /* the assign in @a = split() has been optimised away
16171              * and the @a attached directly to the split op
16172              * Treat the array as appearing on the RHS, i.e.
16173              *    ... = (@a = split)
16174              * is treated like
16175              *    ... = @a;
16176              */
16177
16178             if (o->op_flags & OPf_STACKED) {
16179                 /* @{expr} = split() - the array expression is tacked
16180                  * on as an extra child to split - process kid */
16181                 next_kid = cLISTOPo->op_last;
16182                 goto do_next;
16183             }
16184
16185             /* ... else array is directly attached to split op */
16186             (*scalars_p) += 2;
16187             all_flags |= (PL_op->op_private & OPpSPLIT_LEX)
16188                             ? ((o->op_private & OPpLVAL_INTRO)
16189                                 ? AAS_MY_AGG : AAS_LEX_AGG)
16190                             : AAS_PKG_AGG;
16191             goto do_next;
16192         }
16193         (*scalars_p)++;
16194         /* other args of split can't be returned */
16195         all_flags |= AAS_SAFE_SCALAR;
16196         goto do_next;
16197
16198     case OP_UNDEF:
16199         /* undef on LHS following a var is significant, e.g.
16200          *    my $x = 1;
16201          *    @a = (($x, undef) = (2 => $x));
16202          *    # @a shoul be (2,1) not (2,2)
16203          *
16204          * undef on RHS counts as a scalar:
16205          *   ($x, $y)    = (undef, $x); # 2 scalars on RHS: unsafe
16206          */
16207         if ((!rhs && *scalars_p) || rhs)
16208             (*scalars_p)++;
16209         flags = AAS_SAFE_SCALAR;
16210         break;
16211
16212     case OP_PUSHMARK:
16213     case OP_STUB:
16214         /* these are all no-ops; they don't push a potentially common SV
16215          * onto the stack, so they are neither AAS_DANGEROUS nor
16216          * AAS_SAFE_SCALAR */
16217         goto do_next;
16218
16219     case OP_PADRANGE: /* Ignore padrange; checking its siblings is enough */
16220         break;
16221
16222     case OP_NULL:
16223     case OP_LIST:
16224         /* these do nothing, but may have children */
16225         break;
16226
16227     default:
16228         if (PL_opargs[o->op_type] & OA_DANGEROUS) {
16229             (*scalars_p) += 2;
16230             flags = AAS_DANGEROUS;
16231             break;
16232         }
16233
16234         if (   (PL_opargs[o->op_type] & OA_TARGLEX)
16235             && (o->op_private & OPpTARGET_MY))
16236         {
16237             (*scalars_p)++;
16238             all_flags |= S_aassign_padcheck(aTHX_ o, rhs)
16239                             ? AAS_LEX_SCALAR_COMM : AAS_LEX_SCALAR;
16240             goto do_next;
16241         }
16242
16243         /* if its an unrecognised, non-dangerous op, assume that it
16244          * is the cause of at least one safe scalar */
16245         (*scalars_p)++;
16246         flags = AAS_SAFE_SCALAR;
16247         break;
16248     }
16249
16250     all_flags |= flags;
16251
16252     /* by default, process all kids next
16253      * XXX this assumes that all other ops are "transparent" - i.e. that
16254      * they can return some of their children. While this true for e.g.
16255      * sort and grep, it's not true for e.g. map. We really need a
16256      * 'transparent' flag added to regen/opcodes
16257      */
16258     if (o->op_flags & OPf_KIDS) {
16259         next_kid = cUNOPo->op_first;
16260         /* these ops do nothing but may have children; but their
16261          * children should also be treated as top-level */
16262         if (   o == effective_top_op
16263             && (o->op_type == OP_NULL || o->op_type == OP_LIST)
16264         )
16265             effective_top_op = next_kid;
16266     }
16267
16268
16269     /* If next_kid is set, someone in the code above wanted us to process
16270      * that kid and all its remaining siblings.  Otherwise, work our way
16271      * back up the tree */
16272   do_next:
16273     while (!next_kid) {
16274         if (o == top_op)
16275             return all_flags; /* at top; no parents/siblings to try */
16276         if (OpHAS_SIBLING(o)) {
16277             next_kid = o->op_sibparent;
16278             if (o == effective_top_op)
16279                 effective_top_op = next_kid;
16280         }
16281         else if (o == effective_top_op)
16282             effective_top_op = o->op_sibparent;
16283         o = o->op_sibparent; /* try parent's next sibling */
16284     }
16285     o = next_kid;
16286     } /* while */
16287
16288 }
16289
16290
16291 /* Check for in place reverse and sort assignments like "@a = reverse @a"
16292    and modify the optree to make them work inplace */
16293
16294 STATIC void
16295 S_inplace_aassign(pTHX_ OP *o) {
16296
16297     OP *modop, *modop_pushmark;
16298     OP *oright;
16299     OP *oleft, *oleft_pushmark;
16300
16301     PERL_ARGS_ASSERT_INPLACE_AASSIGN;
16302
16303     assert((o->op_flags & OPf_WANT) == OPf_WANT_VOID);
16304
16305     assert(cUNOPo->op_first->op_type == OP_NULL);
16306     modop_pushmark = cUNOPx(cUNOPo->op_first)->op_first;
16307     assert(modop_pushmark->op_type == OP_PUSHMARK);
16308     modop = OpSIBLING(modop_pushmark);
16309
16310     if (modop->op_type != OP_SORT && modop->op_type != OP_REVERSE)
16311         return;
16312
16313     /* no other operation except sort/reverse */
16314     if (OpHAS_SIBLING(modop))
16315         return;
16316
16317     assert(cUNOPx(modop)->op_first->op_type == OP_PUSHMARK);
16318     if (!(oright = OpSIBLING(cUNOPx(modop)->op_first))) return;
16319
16320     if (modop->op_flags & OPf_STACKED) {
16321         /* skip sort subroutine/block */
16322         assert(oright->op_type == OP_NULL);
16323         oright = OpSIBLING(oright);
16324     }
16325
16326     assert(OpSIBLING(cUNOPo->op_first)->op_type == OP_NULL);
16327     oleft_pushmark = cUNOPx(OpSIBLING(cUNOPo->op_first))->op_first;
16328     assert(oleft_pushmark->op_type == OP_PUSHMARK);
16329     oleft = OpSIBLING(oleft_pushmark);
16330
16331     /* Check the lhs is an array */
16332     if (!oleft ||
16333         (oleft->op_type != OP_RV2AV && oleft->op_type != OP_PADAV)
16334         || OpHAS_SIBLING(oleft)
16335         || (oleft->op_private & OPpLVAL_INTRO)
16336     )
16337         return;
16338
16339     /* Only one thing on the rhs */
16340     if (OpHAS_SIBLING(oright))
16341         return;
16342
16343     /* check the array is the same on both sides */
16344     if (oleft->op_type == OP_RV2AV) {
16345         if (oright->op_type != OP_RV2AV
16346             || !cUNOPx(oright)->op_first
16347             || cUNOPx(oright)->op_first->op_type != OP_GV
16348             || cUNOPx(oleft )->op_first->op_type != OP_GV
16349             || cGVOPx_gv(cUNOPx(oleft)->op_first) !=
16350                cGVOPx_gv(cUNOPx(oright)->op_first)
16351         )
16352             return;
16353     }
16354     else if (oright->op_type != OP_PADAV
16355         || oright->op_targ != oleft->op_targ
16356     )
16357         return;
16358
16359     /* This actually is an inplace assignment */
16360
16361     modop->op_private |= OPpSORT_INPLACE;
16362
16363     /* transfer MODishness etc from LHS arg to RHS arg */
16364     oright->op_flags = oleft->op_flags;
16365
16366     /* remove the aassign op and the lhs */
16367     op_null(o);
16368     op_null(oleft_pushmark);
16369     if (oleft->op_type == OP_RV2AV && cUNOPx(oleft)->op_first)
16370         op_null(cUNOPx(oleft)->op_first);
16371     op_null(oleft);
16372 }
16373
16374
16375
16376 /* S_maybe_multideref(): given an op_next chain of ops beginning at 'start'
16377  * that potentially represent a series of one or more aggregate derefs
16378  * (such as $a->[1]{$key}), examine the chain, and if appropriate, convert
16379  * the whole chain to a single OP_MULTIDEREF op (maybe with a few
16380  * additional ops left in too).
16381  *
16382  * The caller will have already verified that the first few ops in the
16383  * chain following 'start' indicate a multideref candidate, and will have
16384  * set 'orig_o' to the point further on in the chain where the first index
16385  * expression (if any) begins.  'orig_action' specifies what type of
16386  * beginning has already been determined by the ops between start..orig_o
16387  * (e.g.  $lex_ary[], $pkg_ary->{}, expr->[], etc).
16388  *
16389  * 'hints' contains any hints flags that need adding (currently just
16390  * OPpHINT_STRICT_REFS) as found in any rv2av/hv skipped by the caller.
16391  */
16392
16393 STATIC void
16394 S_maybe_multideref(pTHX_ OP *start, OP *orig_o, UV orig_action, U8 hints)
16395 {
16396     int pass;
16397     UNOP_AUX_item *arg_buf = NULL;
16398     bool reset_start_targ  = FALSE; /* start->op_targ needs zeroing */
16399     int index_skip         = -1;    /* don't output index arg on this action */
16400
16401     /* similar to regex compiling, do two passes; the first pass
16402      * determines whether the op chain is convertible and calculates the
16403      * buffer size; the second pass populates the buffer and makes any
16404      * changes necessary to ops (such as moving consts to the pad on
16405      * threaded builds).
16406      *
16407      * NB: for things like Coverity, note that both passes take the same
16408      * path through the logic tree (except for 'if (pass)' bits), since
16409      * both passes are following the same op_next chain; and in
16410      * particular, if it would return early on the second pass, it would
16411      * already have returned early on the first pass.
16412      */
16413     for (pass = 0; pass < 2; pass++) {
16414         OP *o                = orig_o;
16415         UV action            = orig_action;
16416         OP *first_elem_op    = NULL;  /* first seen aelem/helem */
16417         OP *top_op           = NULL;  /* highest [ah]elem/exists/del/rv2[ah]v */
16418         int action_count     = 0;     /* number of actions seen so far */
16419         int action_ix        = 0;     /* action_count % (actions per IV) */
16420         bool next_is_hash    = FALSE; /* is the next lookup to be a hash? */
16421         bool is_last         = FALSE; /* no more derefs to follow */
16422         bool maybe_aelemfast = FALSE; /* we can replace with aelemfast? */
16423         UV action_word       = 0;     /* all actions so far */
16424         UNOP_AUX_item *arg     = arg_buf;
16425         UNOP_AUX_item *action_ptr = arg_buf;
16426
16427         arg++; /* reserve slot for first action word */
16428
16429         switch (action) {
16430         case MDEREF_HV_gvsv_vivify_rv2hv_helem:
16431         case MDEREF_HV_gvhv_helem:
16432             next_is_hash = TRUE;
16433             /* FALLTHROUGH */
16434         case MDEREF_AV_gvsv_vivify_rv2av_aelem:
16435         case MDEREF_AV_gvav_aelem:
16436             if (pass) {
16437 #ifdef USE_ITHREADS
16438                 arg->pad_offset = cPADOPx(start)->op_padix;
16439                 /* stop it being swiped when nulled */
16440                 cPADOPx(start)->op_padix = 0;
16441 #else
16442                 arg->sv = cSVOPx(start)->op_sv;
16443                 cSVOPx(start)->op_sv = NULL;
16444 #endif
16445             }
16446             arg++;
16447             break;
16448
16449         case MDEREF_HV_padhv_helem:
16450         case MDEREF_HV_padsv_vivify_rv2hv_helem:
16451             next_is_hash = TRUE;
16452             /* FALLTHROUGH */
16453         case MDEREF_AV_padav_aelem:
16454         case MDEREF_AV_padsv_vivify_rv2av_aelem:
16455             if (pass) {
16456                 arg->pad_offset = start->op_targ;
16457                 /* we skip setting op_targ = 0 for now, since the intact
16458                  * OP_PADXV is needed by S_check_hash_fields_and_hekify */
16459                 reset_start_targ = TRUE;
16460             }
16461             arg++;
16462             break;
16463
16464         case MDEREF_HV_pop_rv2hv_helem:
16465             next_is_hash = TRUE;
16466             /* FALLTHROUGH */
16467         case MDEREF_AV_pop_rv2av_aelem:
16468             break;
16469
16470         default:
16471             NOT_REACHED; /* NOTREACHED */
16472             return;
16473         }
16474
16475         while (!is_last) {
16476             /* look for another (rv2av/hv; get index;
16477              * aelem/helem/exists/delele) sequence */
16478
16479             OP *kid;
16480             bool is_deref;
16481             bool ok;
16482             UV index_type = MDEREF_INDEX_none;
16483
16484             if (action_count) {
16485                 /* if this is not the first lookup, consume the rv2av/hv  */
16486
16487                 /* for N levels of aggregate lookup, we normally expect
16488                  * that the first N-1 [ah]elem ops will be flagged as
16489                  * /DEREF (so they autovivifiy if necessary), and the last
16490                  * lookup op not to be.
16491                  * For other things (like @{$h{k1}{k2}}) extra scope or
16492                  * leave ops can appear, so abandon the effort in that
16493                  * case */
16494                 if (o->op_type != OP_RV2AV && o->op_type != OP_RV2HV)
16495                     return;
16496
16497                 /* rv2av or rv2hv sKR/1 */
16498
16499                 ASSUME(!(o->op_flags & ~(OPf_WANT|OPf_KIDS|OPf_PARENS
16500                                             |OPf_REF|OPf_MOD|OPf_SPECIAL)));
16501                 if (o->op_flags != (OPf_WANT_SCALAR|OPf_KIDS|OPf_REF))
16502                     return;
16503
16504                 /* at this point, we wouldn't expect any of these
16505                  * possible private flags:
16506                  * OPpMAYBE_LVSUB, OPpOUR_INTRO, OPpLVAL_INTRO
16507                  * OPpTRUEBOOL, OPpMAYBE_TRUEBOOL (rv2hv only)
16508                  */
16509                 ASSUME(!(o->op_private &
16510                     ~(OPpHINT_STRICT_REFS|OPpARG1_MASK|OPpSLICEWARNING)));
16511
16512                 hints = (o->op_private & OPpHINT_STRICT_REFS);
16513
16514                 /* make sure the type of the previous /DEREF matches the
16515                  * type of the next lookup */
16516                 ASSUME(o->op_type == (next_is_hash ? OP_RV2HV : OP_RV2AV));
16517                 top_op = o;
16518
16519                 action = next_is_hash
16520                             ? MDEREF_HV_vivify_rv2hv_helem
16521                             : MDEREF_AV_vivify_rv2av_aelem;
16522                 o = o->op_next;
16523             }
16524
16525             /* if this is the second pass, and we're at the depth where
16526              * previously we encountered a non-simple index expression,
16527              * stop processing the index at this point */
16528             if (action_count != index_skip) {
16529
16530                 /* look for one or more simple ops that return an array
16531                  * index or hash key */
16532
16533                 switch (o->op_type) {
16534                 case OP_PADSV:
16535                     /* it may be a lexical var index */
16536                     ASSUME(!(o->op_flags & ~(OPf_WANT|OPf_PARENS
16537                                             |OPf_REF|OPf_MOD|OPf_SPECIAL)));
16538                     ASSUME(!(o->op_private &
16539                             ~(OPpPAD_STATE|OPpDEREF|OPpLVAL_INTRO)));
16540
16541                     if (   OP_GIMME(o,0) == G_SCALAR
16542                         && !(o->op_flags & (OPf_REF|OPf_MOD))
16543                         && o->op_private == 0)
16544                     {
16545                         if (pass)
16546                             arg->pad_offset = o->op_targ;
16547                         arg++;
16548                         index_type = MDEREF_INDEX_padsv;
16549                         o = o->op_next;
16550                     }
16551                     break;
16552
16553                 case OP_CONST:
16554                     if (next_is_hash) {
16555                         /* it's a constant hash index */
16556                         if (!(SvFLAGS(cSVOPo_sv) & (SVf_IOK|SVf_NOK|SVf_POK)))
16557                             /* "use constant foo => FOO; $h{+foo}" for
16558                              * some weird FOO, can leave you with constants
16559                              * that aren't simple strings. It's not worth
16560                              * the extra hassle for those edge cases */
16561                             break;
16562
16563                         {
16564                             UNOP *rop = NULL;
16565                             OP * helem_op = o->op_next;
16566
16567                             ASSUME(   helem_op->op_type == OP_HELEM
16568                                    || helem_op->op_type == OP_NULL
16569                                    || pass == 0);
16570                             if (helem_op->op_type == OP_HELEM) {
16571                                 rop = (UNOP*)(((BINOP*)helem_op)->op_first);
16572                                 if (   helem_op->op_private & OPpLVAL_INTRO
16573                                     || rop->op_type != OP_RV2HV
16574                                 )
16575                                     rop = NULL;
16576                             }
16577                             /* on first pass just check; on second pass
16578                              * hekify */
16579                             S_check_hash_fields_and_hekify(aTHX_ rop, cSVOPo,
16580                                                             pass);
16581                         }
16582
16583                         if (pass) {
16584 #ifdef USE_ITHREADS
16585                             /* Relocate sv to the pad for thread safety */
16586                             op_relocate_sv(&cSVOPo->op_sv, &o->op_targ);
16587                             arg->pad_offset = o->op_targ;
16588                             o->op_targ = 0;
16589 #else
16590                             arg->sv = cSVOPx_sv(o);
16591 #endif
16592                         }
16593                     }
16594                     else {
16595                         /* it's a constant array index */
16596                         IV iv;
16597                         SV *ix_sv = cSVOPo->op_sv;
16598                         if (!SvIOK(ix_sv))
16599                             break;
16600                         iv = SvIV(ix_sv);
16601
16602                         if (   action_count == 0
16603                             && iv >= -128
16604                             && iv <= 127
16605                             && (   action == MDEREF_AV_padav_aelem
16606                                 || action == MDEREF_AV_gvav_aelem)
16607                         )
16608                             maybe_aelemfast = TRUE;
16609
16610                         if (pass) {
16611                             arg->iv = iv;
16612                             SvREFCNT_dec_NN(cSVOPo->op_sv);
16613                         }
16614                     }
16615                     if (pass)
16616                         /* we've taken ownership of the SV */
16617                         cSVOPo->op_sv = NULL;
16618                     arg++;
16619                     index_type = MDEREF_INDEX_const;
16620                     o = o->op_next;
16621                     break;
16622
16623                 case OP_GV:
16624                     /* it may be a package var index */
16625
16626                     ASSUME(!(o->op_flags & ~(OPf_WANT|OPf_PARENS|OPf_SPECIAL)));
16627                     ASSUME(!(o->op_private & ~(OPpEARLY_CV)));
16628                     if (  (o->op_flags & ~(OPf_PARENS|OPf_SPECIAL)) != OPf_WANT_SCALAR
16629                         || o->op_private != 0
16630                     )
16631                         break;
16632
16633                     kid = o->op_next;
16634                     if (kid->op_type != OP_RV2SV)
16635                         break;
16636
16637                     ASSUME(!(kid->op_flags &
16638                             ~(OPf_WANT|OPf_KIDS|OPf_MOD|OPf_REF
16639                              |OPf_SPECIAL|OPf_PARENS)));
16640                     ASSUME(!(kid->op_private &
16641                                     ~(OPpARG1_MASK
16642                                      |OPpHINT_STRICT_REFS|OPpOUR_INTRO
16643                                      |OPpDEREF|OPpLVAL_INTRO)));
16644                     if(   (kid->op_flags &~ OPf_PARENS)
16645                             != (OPf_WANT_SCALAR|OPf_KIDS)
16646                        || (kid->op_private & ~(OPpARG1_MASK|HINT_STRICT_REFS))
16647                     )
16648                         break;
16649
16650                     if (pass) {
16651 #ifdef USE_ITHREADS
16652                         arg->pad_offset = cPADOPx(o)->op_padix;
16653                         /* stop it being swiped when nulled */
16654                         cPADOPx(o)->op_padix = 0;
16655 #else
16656                         arg->sv = cSVOPx(o)->op_sv;
16657                         cSVOPo->op_sv = NULL;
16658 #endif
16659                     }
16660                     arg++;
16661                     index_type = MDEREF_INDEX_gvsv;
16662                     o = kid->op_next;
16663                     break;
16664
16665                 } /* switch */
16666             } /* action_count != index_skip */
16667
16668             action |= index_type;
16669
16670
16671             /* at this point we have either:
16672              *   * detected what looks like a simple index expression,
16673              *     and expect the next op to be an [ah]elem, or
16674              *     an nulled  [ah]elem followed by a delete or exists;
16675              *  * found a more complex expression, so something other
16676              *    than the above follows.
16677              */
16678
16679             /* possibly an optimised away [ah]elem (where op_next is
16680              * exists or delete) */
16681             if (o->op_type == OP_NULL)
16682                 o = o->op_next;
16683
16684             /* at this point we're looking for an OP_AELEM, OP_HELEM,
16685              * OP_EXISTS or OP_DELETE */
16686
16687             /* if a custom array/hash access checker is in scope,
16688              * abandon optimisation attempt */
16689             if (  (o->op_type == OP_AELEM || o->op_type == OP_HELEM)
16690                && PL_check[o->op_type] != Perl_ck_null)
16691                 return;
16692             /* similarly for customised exists and delete */
16693             if (  (o->op_type == OP_EXISTS)
16694                && PL_check[o->op_type] != Perl_ck_exists)
16695                 return;
16696             if (  (o->op_type == OP_DELETE)
16697                && PL_check[o->op_type] != Perl_ck_delete)
16698                 return;
16699
16700             if (   o->op_type != OP_AELEM
16701                 || (o->op_private &
16702                       (OPpLVAL_INTRO|OPpLVAL_DEFER|OPpDEREF|OPpMAYBE_LVSUB))
16703                 )
16704                 maybe_aelemfast = FALSE;
16705
16706             /* look for aelem/helem/exists/delete. If it's not the last elem
16707              * lookup, it *must* have OPpDEREF_AV/HV, but not many other
16708              * flags; if it's the last, then it mustn't have
16709              * OPpDEREF_AV/HV, but may have lots of other flags, like
16710              * OPpLVAL_INTRO etc
16711              */
16712
16713             if (   index_type == MDEREF_INDEX_none
16714                 || (   o->op_type != OP_AELEM  && o->op_type != OP_HELEM
16715                     && o->op_type != OP_EXISTS && o->op_type != OP_DELETE)
16716             )
16717                 ok = FALSE;
16718             else {
16719                 /* we have aelem/helem/exists/delete with valid simple index */
16720
16721                 is_deref =    (o->op_type == OP_AELEM || o->op_type == OP_HELEM)
16722                            && (   (o->op_private & OPpDEREF) == OPpDEREF_AV
16723                                || (o->op_private & OPpDEREF) == OPpDEREF_HV);
16724
16725                 /* This doesn't make much sense but is legal:
16726                  *    @{ local $x[0][0] } = 1
16727                  * Since scope exit will undo the autovivification,
16728                  * don't bother in the first place. The OP_LEAVE
16729                  * assertion is in case there are other cases of both
16730                  * OPpLVAL_INTRO and OPpDEREF which don't include a scope
16731                  * exit that would undo the local - in which case this
16732                  * block of code would need rethinking.
16733                  */
16734                 if (is_deref && (o->op_private & OPpLVAL_INTRO)) {
16735 #ifdef DEBUGGING
16736                     OP *n = o->op_next;
16737                     while (n && (  n->op_type == OP_NULL
16738                                 || n->op_type == OP_LIST
16739                                 || n->op_type == OP_SCALAR))
16740                         n = n->op_next;
16741                     assert(n && n->op_type == OP_LEAVE);
16742 #endif
16743                     o->op_private &= ~OPpDEREF;
16744                     is_deref = FALSE;
16745                 }
16746
16747                 if (is_deref) {
16748                     ASSUME(!(o->op_flags &
16749                                  ~(OPf_WANT|OPf_KIDS|OPf_MOD|OPf_PARENS)));
16750                     ASSUME(!(o->op_private & ~(OPpARG2_MASK|OPpDEREF)));
16751
16752                     ok =    (o->op_flags &~ OPf_PARENS)
16753                                == (OPf_WANT_SCALAR|OPf_KIDS|OPf_MOD)
16754                          && !(o->op_private & ~(OPpDEREF|OPpARG2_MASK));
16755                 }
16756                 else if (o->op_type == OP_EXISTS) {
16757                     ASSUME(!(o->op_flags & ~(OPf_WANT|OPf_KIDS|OPf_PARENS
16758                                 |OPf_REF|OPf_MOD|OPf_SPECIAL)));
16759                     ASSUME(!(o->op_private & ~(OPpARG1_MASK|OPpEXISTS_SUB)));
16760                     ok =  !(o->op_private & ~OPpARG1_MASK);
16761                 }
16762                 else if (o->op_type == OP_DELETE) {
16763                     ASSUME(!(o->op_flags & ~(OPf_WANT|OPf_KIDS|OPf_PARENS
16764                                 |OPf_REF|OPf_MOD|OPf_SPECIAL)));
16765                     ASSUME(!(o->op_private &
16766                                     ~(OPpARG1_MASK|OPpSLICE|OPpLVAL_INTRO)));
16767                     /* don't handle slices or 'local delete'; the latter
16768                      * is fairly rare, and has a complex runtime */
16769                     ok =  !(o->op_private & ~OPpARG1_MASK);
16770                     if (OP_TYPE_IS_OR_WAS(cUNOPo->op_first, OP_AELEM))
16771                         /* skip handling run-tome error */
16772                         ok = (ok && cBOOL(o->op_flags & OPf_SPECIAL));
16773                 }
16774                 else {
16775                     ASSUME(o->op_type == OP_AELEM || o->op_type == OP_HELEM);
16776                     ASSUME(!(o->op_flags & ~(OPf_WANT|OPf_KIDS|OPf_MOD
16777                                             |OPf_PARENS|OPf_REF|OPf_SPECIAL)));
16778                     ASSUME(!(o->op_private & ~(OPpARG2_MASK|OPpMAYBE_LVSUB
16779                                     |OPpLVAL_DEFER|OPpDEREF|OPpLVAL_INTRO)));
16780                     ok = (o->op_private & OPpDEREF) != OPpDEREF_SV;
16781                 }
16782             }
16783
16784             if (ok) {
16785                 if (!first_elem_op)
16786                     first_elem_op = o;
16787                 top_op = o;
16788                 if (is_deref) {
16789                     next_is_hash = cBOOL((o->op_private & OPpDEREF) == OPpDEREF_HV);
16790                     o = o->op_next;
16791                 }
16792                 else {
16793                     is_last = TRUE;
16794                     action |= MDEREF_FLAG_last;
16795                 }
16796             }
16797             else {
16798                 /* at this point we have something that started
16799                  * promisingly enough (with rv2av or whatever), but failed
16800                  * to find a simple index followed by an
16801                  * aelem/helem/exists/delete. If this is the first action,
16802                  * give up; but if we've already seen at least one
16803                  * aelem/helem, then keep them and add a new action with
16804                  * MDEREF_INDEX_none, which causes it to do the vivify
16805                  * from the end of the previous lookup, and do the deref,
16806                  * but stop at that point. So $a[0][expr] will do one
16807                  * av_fetch, vivify and deref, then continue executing at
16808                  * expr */
16809                 if (!action_count)
16810                     return;
16811                 is_last = TRUE;
16812                 index_skip = action_count;
16813                 action |= MDEREF_FLAG_last;
16814                 if (index_type != MDEREF_INDEX_none)
16815                     arg--;
16816             }
16817
16818             action_word |= (action << (action_ix * MDEREF_SHIFT));
16819             action_ix++;
16820             action_count++;
16821             /* if there's no space for the next action, reserve a new slot
16822              * for it *before* we start adding args for that action */
16823             if ((action_ix + 1) * MDEREF_SHIFT > UVSIZE*8) {
16824                 if (pass)
16825                     action_ptr->uv = action_word;
16826                 action_word = 0;
16827                 action_ptr = arg;
16828                 arg++;
16829                 action_ix = 0;
16830             }
16831         } /* while !is_last */
16832
16833         /* success! */
16834
16835         if (!action_ix)
16836             /* slot reserved for next action word not now needed */
16837             arg--;
16838         else if (pass)
16839             action_ptr->uv = action_word;
16840
16841         if (pass) {
16842             OP *mderef;
16843             OP *p, *q;
16844
16845             mderef = newUNOP_AUX(OP_MULTIDEREF, 0, NULL, arg_buf);
16846             if (index_skip == -1) {
16847                 mderef->op_flags = o->op_flags
16848                         & (OPf_WANT|OPf_MOD|(next_is_hash ? OPf_SPECIAL : 0));
16849                 if (o->op_type == OP_EXISTS)
16850                     mderef->op_private = OPpMULTIDEREF_EXISTS;
16851                 else if (o->op_type == OP_DELETE)
16852                     mderef->op_private = OPpMULTIDEREF_DELETE;
16853                 else
16854                     mderef->op_private = o->op_private
16855                         & (OPpMAYBE_LVSUB|OPpLVAL_DEFER|OPpLVAL_INTRO);
16856             }
16857             /* accumulate strictness from every level (although I don't think
16858              * they can actually vary) */
16859             mderef->op_private |= hints;
16860
16861             /* integrate the new multideref op into the optree and the
16862              * op_next chain.
16863              *
16864              * In general an op like aelem or helem has two child
16865              * sub-trees: the aggregate expression (a_expr) and the
16866              * index expression (i_expr):
16867              *
16868              *     aelem
16869              *       |
16870              *     a_expr - i_expr
16871              *
16872              * The a_expr returns an AV or HV, while the i-expr returns an
16873              * index. In general a multideref replaces most or all of a
16874              * multi-level tree, e.g.
16875              *
16876              *     exists
16877              *       |
16878              *     ex-aelem
16879              *       |
16880              *     rv2av  - i_expr1
16881              *       |
16882              *     helem
16883              *       |
16884              *     rv2hv  - i_expr2
16885              *       |
16886              *     aelem
16887              *       |
16888              *     a_expr - i_expr3
16889              *
16890              * With multideref, all the i_exprs will be simple vars or
16891              * constants, except that i_expr1 may be arbitrary in the case
16892              * of MDEREF_INDEX_none.
16893              *
16894              * The bottom-most a_expr will be either:
16895              *   1) a simple var (so padXv or gv+rv2Xv);
16896              *   2) a simple scalar var dereferenced (e.g. $r->[0]):
16897              *      so a simple var with an extra rv2Xv;
16898              *   3) or an arbitrary expression.
16899              *
16900              * 'start', the first op in the execution chain, will point to
16901              *   1),2): the padXv or gv op;
16902              *   3):    the rv2Xv which forms the last op in the a_expr
16903              *          execution chain, and the top-most op in the a_expr
16904              *          subtree.
16905              *
16906              * For all cases, the 'start' node is no longer required,
16907              * but we can't free it since one or more external nodes
16908              * may point to it. E.g. consider
16909              *     $h{foo} = $a ? $b : $c
16910              * Here, both the op_next and op_other branches of the
16911              * cond_expr point to the gv[*h] of the hash expression, so
16912              * we can't free the 'start' op.
16913              *
16914              * For expr->[...], we need to save the subtree containing the
16915              * expression; for the other cases, we just need to save the
16916              * start node.
16917              * So in all cases, we null the start op and keep it around by
16918              * making it the child of the multideref op; for the expr->
16919              * case, the expr will be a subtree of the start node.
16920              *
16921              * So in the simple 1,2 case the  optree above changes to
16922              *
16923              *     ex-exists
16924              *       |
16925              *     multideref
16926              *       |
16927              *     ex-gv (or ex-padxv)
16928              *
16929              *  with the op_next chain being
16930              *
16931              *  -> ex-gv -> multideref -> op-following-ex-exists ->
16932              *
16933              *  In the 3 case, we have
16934              *
16935              *     ex-exists
16936              *       |
16937              *     multideref
16938              *       |
16939              *     ex-rv2xv
16940              *       |
16941              *    rest-of-a_expr
16942              *      subtree
16943              *
16944              *  and
16945              *
16946              *  -> rest-of-a_expr subtree ->
16947              *    ex-rv2xv -> multideref -> op-following-ex-exists ->
16948              *
16949              *
16950              * Where the last i_expr is non-simple (i.e. MDEREF_INDEX_none,
16951              * e.g. $a[0]{foo}[$x+1], the next rv2xv is nulled and the
16952              * multideref attached as the child, e.g.
16953              *
16954              *     exists
16955              *       |
16956              *     ex-aelem
16957              *       |
16958              *     ex-rv2av  - i_expr1
16959              *       |
16960              *     multideref
16961              *       |
16962              *     ex-whatever
16963              *
16964              */
16965
16966             /* if we free this op, don't free the pad entry */
16967             if (reset_start_targ)
16968                 start->op_targ = 0;
16969
16970
16971             /* Cut the bit we need to save out of the tree and attach to
16972              * the multideref op, then free the rest of the tree */
16973
16974             /* find parent of node to be detached (for use by splice) */
16975             p = first_elem_op;
16976             if (   orig_action == MDEREF_AV_pop_rv2av_aelem
16977                 || orig_action == MDEREF_HV_pop_rv2hv_helem)
16978             {
16979                 /* there is an arbitrary expression preceding us, e.g.
16980                  * expr->[..]? so we need to save the 'expr' subtree */
16981                 if (p->op_type == OP_EXISTS || p->op_type == OP_DELETE)
16982                     p = cUNOPx(p)->op_first;
16983                 ASSUME(   start->op_type == OP_RV2AV
16984                        || start->op_type == OP_RV2HV);
16985             }
16986             else {
16987                 /* either a padXv or rv2Xv+gv, maybe with an ex-Xelem
16988                  * above for exists/delete. */
16989                 while (   (p->op_flags & OPf_KIDS)
16990                        && cUNOPx(p)->op_first != start
16991                 )
16992                     p = cUNOPx(p)->op_first;
16993             }
16994             ASSUME(cUNOPx(p)->op_first == start);
16995
16996             /* detach from main tree, and re-attach under the multideref */
16997             op_sibling_splice(mderef, NULL, 0,
16998                     op_sibling_splice(p, NULL, 1, NULL));
16999             op_null(start);
17000
17001             start->op_next = mderef;
17002
17003             mderef->op_next = index_skip == -1 ? o->op_next : o;
17004
17005             /* excise and free the original tree, and replace with
17006              * the multideref op */
17007             p = op_sibling_splice(top_op, NULL, -1, mderef);
17008             while (p) {
17009                 q = OpSIBLING(p);
17010                 op_free(p);
17011                 p = q;
17012             }
17013             op_null(top_op);
17014         }
17015         else {
17016             Size_t size = arg - arg_buf;
17017
17018             if (maybe_aelemfast && action_count == 1)
17019                 return;
17020
17021             arg_buf = (UNOP_AUX_item*)PerlMemShared_malloc(
17022                                 sizeof(UNOP_AUX_item) * (size + 1));
17023             /* for dumping etc: store the length in a hidden first slot;
17024              * we set the op_aux pointer to the second slot */
17025             arg_buf->uv = size;
17026             arg_buf++;
17027         }
17028     } /* for (pass = ...) */
17029 }
17030
17031 /* See if the ops following o are such that o will always be executed in
17032  * boolean context: that is, the SV which o pushes onto the stack will
17033  * only ever be consumed by later ops via SvTRUE(sv) or similar.
17034  * If so, set a suitable private flag on o. Normally this will be
17035  * bool_flag; but see below why maybe_flag is needed too.
17036  *
17037  * Typically the two flags you pass will be the generic OPpTRUEBOOL and
17038  * OPpMAYBE_TRUEBOOL, buts it's possible that for some ops those bits may
17039  * already be taken, so you'll have to give that op two different flags.
17040  *
17041  * More explanation of 'maybe_flag' and 'safe_and' parameters.
17042  * The binary logical ops &&, ||, // (plus 'if' and 'unless' which use
17043  * those underlying ops) short-circuit, which means that rather than
17044  * necessarily returning a truth value, they may return the LH argument,
17045  * which may not be boolean. For example in $x = (keys %h || -1), keys
17046  * should return a key count rather than a boolean, even though its
17047  * sort-of being used in boolean context.
17048  *
17049  * So we only consider such logical ops to provide boolean context to
17050  * their LH argument if they themselves are in void or boolean context.
17051  * However, sometimes the context isn't known until run-time. In this
17052  * case the op is marked with the maybe_flag flag it.
17053  *
17054  * Consider the following.
17055  *
17056  *     sub f { ....;  if (%h) { .... } }
17057  *
17058  * This is actually compiled as
17059  *
17060  *     sub f { ....;  %h && do { .... } }
17061  *
17062  * Here we won't know until runtime whether the final statement (and hence
17063  * the &&) is in void context and so is safe to return a boolean value.
17064  * So mark o with maybe_flag rather than the bool_flag.
17065  * Note that there is cost associated with determining context at runtime
17066  * (e.g. a call to block_gimme()), so it may not be worth setting (at
17067  * compile time) and testing (at runtime) maybe_flag if the scalar verses
17068  * boolean costs savings are marginal.
17069  *
17070  * However, we can do slightly better with && (compared to || and //):
17071  * this op only returns its LH argument when that argument is false. In
17072  * this case, as long as the op promises to return a false value which is
17073  * valid in both boolean and scalar contexts, we can mark an op consumed
17074  * by && with bool_flag rather than maybe_flag.
17075  * For example as long as pp_padhv and pp_rv2hv return &PL_sv_zero rather
17076  * than &PL_sv_no for a false result in boolean context, then it's safe. An
17077  * op which promises to handle this case is indicated by setting safe_and
17078  * to true.
17079  */
17080
17081 static void
17082 S_check_for_bool_cxt(OP*o, bool safe_and, U8 bool_flag, U8 maybe_flag)
17083 {
17084     OP *lop;
17085     U8 flag = 0;
17086
17087     assert((o->op_flags & OPf_WANT) == OPf_WANT_SCALAR);
17088
17089     /* OPpTARGET_MY and boolean context probably don't mix well.
17090      * If someone finds a valid use case, maybe add an extra flag to this
17091      * function which indicates its safe to do so for this op? */
17092     assert(!(   (PL_opargs[o->op_type] & OA_TARGLEX)
17093              && (o->op_private & OPpTARGET_MY)));
17094
17095     lop = o->op_next;
17096
17097     while (lop) {
17098         switch (lop->op_type) {
17099         case OP_NULL:
17100         case OP_SCALAR:
17101             break;
17102
17103         /* these two consume the stack argument in the scalar case,
17104          * and treat it as a boolean in the non linenumber case */
17105         case OP_FLIP:
17106         case OP_FLOP:
17107             if (   ((lop->op_flags & OPf_WANT) == OPf_WANT_LIST)
17108                 || (lop->op_private & OPpFLIP_LINENUM))
17109             {
17110                 lop = NULL;
17111                 break;
17112             }
17113             /* FALLTHROUGH */
17114         /* these never leave the original value on the stack */
17115         case OP_NOT:
17116         case OP_XOR:
17117         case OP_COND_EXPR:
17118         case OP_GREPWHILE:
17119             flag = bool_flag;
17120             lop = NULL;
17121             break;
17122
17123         /* OR DOR and AND evaluate their arg as a boolean, but then may
17124          * leave the original scalar value on the stack when following the
17125          * op_next route. If not in void context, we need to ensure
17126          * that whatever follows consumes the arg only in boolean context
17127          * too.
17128          */
17129         case OP_AND:
17130             if (safe_and) {
17131                 flag = bool_flag;
17132                 lop = NULL;
17133                 break;
17134             }
17135             /* FALLTHROUGH */
17136         case OP_OR:
17137         case OP_DOR:
17138             if ((lop->op_flags & OPf_WANT) == OPf_WANT_VOID) {
17139                 flag = bool_flag;
17140                 lop = NULL;
17141             }
17142             else if (!(lop->op_flags & OPf_WANT)) {
17143                 /* unknown context - decide at runtime */
17144                 flag = maybe_flag;
17145                 lop = NULL;
17146             }
17147             break;
17148
17149         default:
17150             lop = NULL;
17151             break;
17152         }
17153
17154         if (lop)
17155             lop = lop->op_next;
17156     }
17157
17158     o->op_private |= flag;
17159 }
17160
17161
17162
17163 /* mechanism for deferring recursion in rpeep() */
17164
17165 #define MAX_DEFERRED 4
17166
17167 #define DEFER(o) \
17168   STMT_START { \
17169     if (defer_ix == (MAX_DEFERRED-1)) { \
17170         OP **defer = defer_queue[defer_base]; \
17171         CALL_RPEEP(*defer); \
17172         S_prune_chain_head(defer); \
17173         defer_base = (defer_base + 1) % MAX_DEFERRED; \
17174         defer_ix--; \
17175     } \
17176     defer_queue[(defer_base + ++defer_ix) % MAX_DEFERRED] = &(o); \
17177   } STMT_END
17178
17179 #define IS_AND_OP(o)   (o->op_type == OP_AND)
17180 #define IS_OR_OP(o)    (o->op_type == OP_OR)
17181
17182
17183 /* A peephole optimizer.  We visit the ops in the order they're to execute.
17184  * See the comments at the top of this file for more details about when
17185  * peep() is called */
17186
17187 void
17188 Perl_rpeep(pTHX_ OP *o)
17189 {
17190     OP* oldop = NULL;
17191     OP* oldoldop = NULL;
17192     OP** defer_queue[MAX_DEFERRED]; /* small queue of deferred branches */
17193     int defer_base = 0;
17194     int defer_ix = -1;
17195
17196     if (!o || o->op_opt)
17197         return;
17198
17199     assert(o->op_type != OP_FREED);
17200
17201     ENTER;
17202     SAVEOP();
17203     SAVEVPTR(PL_curcop);
17204     for (;; o = o->op_next) {
17205         if (o && o->op_opt)
17206             o = NULL;
17207         if (!o) {
17208             while (defer_ix >= 0) {
17209                 OP **defer =
17210                         defer_queue[(defer_base + defer_ix--) % MAX_DEFERRED];
17211                 CALL_RPEEP(*defer);
17212                 S_prune_chain_head(defer);
17213             }
17214             break;
17215         }
17216
17217       redo:
17218
17219         /* oldoldop -> oldop -> o should be a chain of 3 adjacent ops */
17220         assert(!oldoldop || oldoldop->op_next == oldop);
17221         assert(!oldop    || oldop->op_next    == o);
17222
17223         /* By default, this op has now been optimised. A couple of cases below
17224            clear this again.  */
17225         o->op_opt = 1;
17226         PL_op = o;
17227
17228         /* look for a series of 1 or more aggregate derefs, e.g.
17229          *   $a[1]{foo}[$i]{$k}
17230          * and replace with a single OP_MULTIDEREF op.
17231          * Each index must be either a const, or a simple variable,
17232          *
17233          * First, look for likely combinations of starting ops,
17234          * corresponding to (global and lexical variants of)
17235          *     $a[...]   $h{...}
17236          *     $r->[...] $r->{...}
17237          *     (preceding expression)->[...]
17238          *     (preceding expression)->{...}
17239          * and if so, call maybe_multideref() to do a full inspection
17240          * of the op chain and if appropriate, replace with an
17241          * OP_MULTIDEREF
17242          */
17243         {
17244             UV action;
17245             OP *o2 = o;
17246             U8 hints = 0;
17247
17248             switch (o2->op_type) {
17249             case OP_GV:
17250                 /* $pkg[..]   :   gv[*pkg]
17251                  * $pkg->[...]:   gv[*pkg]; rv2sv sKM/DREFAV */
17252
17253                 /* Fail if there are new op flag combinations that we're
17254                  * not aware of, rather than:
17255                  *  * silently failing to optimise, or
17256                  *  * silently optimising the flag away.
17257                  * If this ASSUME starts failing, examine what new flag
17258                  * has been added to the op, and decide whether the
17259                  * optimisation should still occur with that flag, then
17260                  * update the code accordingly. This applies to all the
17261                  * other ASSUMEs in the block of code too.
17262                  */
17263                 ASSUME(!(o2->op_flags &
17264                             ~(OPf_WANT|OPf_MOD|OPf_PARENS|OPf_SPECIAL)));
17265                 ASSUME(!(o2->op_private & ~OPpEARLY_CV));
17266
17267                 o2 = o2->op_next;
17268
17269                 if (o2->op_type == OP_RV2AV) {
17270                     action = MDEREF_AV_gvav_aelem;
17271                     goto do_deref;
17272                 }
17273
17274                 if (o2->op_type == OP_RV2HV) {
17275                     action = MDEREF_HV_gvhv_helem;
17276                     goto do_deref;
17277                 }
17278
17279                 if (o2->op_type != OP_RV2SV)
17280                     break;
17281
17282                 /* at this point we've seen gv,rv2sv, so the only valid
17283                  * construct left is $pkg->[] or $pkg->{} */
17284
17285                 ASSUME(!(o2->op_flags & OPf_STACKED));
17286                 if ((o2->op_flags & (OPf_WANT|OPf_REF|OPf_MOD|OPf_SPECIAL))
17287                             != (OPf_WANT_SCALAR|OPf_MOD))
17288                     break;
17289
17290                 ASSUME(!(o2->op_private & ~(OPpARG1_MASK|HINT_STRICT_REFS
17291                                     |OPpOUR_INTRO|OPpDEREF|OPpLVAL_INTRO)));
17292                 if (o2->op_private & (OPpOUR_INTRO|OPpLVAL_INTRO))
17293                     break;
17294                 if (   (o2->op_private & OPpDEREF) != OPpDEREF_AV
17295                     && (o2->op_private & OPpDEREF) != OPpDEREF_HV)
17296                     break;
17297
17298                 o2 = o2->op_next;
17299                 if (o2->op_type == OP_RV2AV) {
17300                     action = MDEREF_AV_gvsv_vivify_rv2av_aelem;
17301                     goto do_deref;
17302                 }
17303                 if (o2->op_type == OP_RV2HV) {
17304                     action = MDEREF_HV_gvsv_vivify_rv2hv_helem;
17305                     goto do_deref;
17306                 }
17307                 break;
17308
17309             case OP_PADSV:
17310                 /* $lex->[...]: padsv[$lex] sM/DREFAV */
17311
17312                 ASSUME(!(o2->op_flags &
17313                     ~(OPf_WANT|OPf_PARENS|OPf_REF|OPf_MOD|OPf_SPECIAL)));
17314                 if ((o2->op_flags &
17315                         (OPf_WANT|OPf_REF|OPf_MOD|OPf_SPECIAL))
17316                      != (OPf_WANT_SCALAR|OPf_MOD))
17317                     break;
17318
17319                 ASSUME(!(o2->op_private &
17320                                 ~(OPpPAD_STATE|OPpDEREF|OPpLVAL_INTRO)));
17321                 /* skip if state or intro, or not a deref */
17322                 if (      o2->op_private != OPpDEREF_AV
17323                        && o2->op_private != OPpDEREF_HV)
17324                     break;
17325
17326                 o2 = o2->op_next;
17327                 if (o2->op_type == OP_RV2AV) {
17328                     action = MDEREF_AV_padsv_vivify_rv2av_aelem;
17329                     goto do_deref;
17330                 }
17331                 if (o2->op_type == OP_RV2HV) {
17332                     action = MDEREF_HV_padsv_vivify_rv2hv_helem;
17333                     goto do_deref;
17334                 }
17335                 break;
17336
17337             case OP_PADAV:
17338             case OP_PADHV:
17339                 /*    $lex[..]:  padav[@lex:1,2] sR *
17340                  * or $lex{..}:  padhv[%lex:1,2] sR */
17341                 ASSUME(!(o2->op_flags & ~(OPf_WANT|OPf_MOD|OPf_PARENS|
17342                                             OPf_REF|OPf_SPECIAL)));
17343                 if ((o2->op_flags &
17344                         (OPf_WANT|OPf_REF|OPf_MOD|OPf_SPECIAL))
17345                      != (OPf_WANT_SCALAR|OPf_REF))
17346                     break;
17347                 if (o2->op_flags != (OPf_WANT_SCALAR|OPf_REF))
17348                     break;
17349                 /* OPf_PARENS isn't currently used in this case;
17350                  * if that changes, let us know! */
17351                 ASSUME(!(o2->op_flags & OPf_PARENS));
17352
17353                 /* at this point, we wouldn't expect any of the remaining
17354                  * possible private flags:
17355                  * OPpPAD_STATE, OPpLVAL_INTRO, OPpTRUEBOOL,
17356                  * OPpMAYBE_TRUEBOOL, OPpMAYBE_LVSUB
17357                  *
17358                  * OPpSLICEWARNING shouldn't affect runtime
17359                  */
17360                 ASSUME(!(o2->op_private & ~(OPpSLICEWARNING)));
17361
17362                 action = o2->op_type == OP_PADAV
17363                             ? MDEREF_AV_padav_aelem
17364                             : MDEREF_HV_padhv_helem;
17365                 o2 = o2->op_next;
17366                 S_maybe_multideref(aTHX_ o, o2, action, 0);
17367                 break;
17368
17369
17370             case OP_RV2AV:
17371             case OP_RV2HV:
17372                 action = o2->op_type == OP_RV2AV
17373                             ? MDEREF_AV_pop_rv2av_aelem
17374                             : MDEREF_HV_pop_rv2hv_helem;
17375                 /* FALLTHROUGH */
17376             do_deref:
17377                 /* (expr)->[...]:  rv2av sKR/1;
17378                  * (expr)->{...}:  rv2hv sKR/1; */
17379
17380                 ASSUME(o2->op_type == OP_RV2AV || o2->op_type == OP_RV2HV);
17381
17382                 ASSUME(!(o2->op_flags & ~(OPf_WANT|OPf_KIDS|OPf_PARENS
17383                                 |OPf_REF|OPf_MOD|OPf_STACKED|OPf_SPECIAL)));
17384                 if (o2->op_flags != (OPf_WANT_SCALAR|OPf_KIDS|OPf_REF))
17385                     break;
17386
17387                 /* at this point, we wouldn't expect any of these
17388                  * possible private flags:
17389                  * OPpMAYBE_LVSUB, OPpLVAL_INTRO
17390                  * OPpTRUEBOOL, OPpMAYBE_TRUEBOOL, (rv2hv only)
17391                  */
17392                 ASSUME(!(o2->op_private &
17393                     ~(OPpHINT_STRICT_REFS|OPpARG1_MASK|OPpSLICEWARNING
17394                      |OPpOUR_INTRO)));
17395                 hints |= (o2->op_private & OPpHINT_STRICT_REFS);
17396
17397                 o2 = o2->op_next;
17398
17399                 S_maybe_multideref(aTHX_ o, o2, action, hints);
17400                 break;
17401
17402             default:
17403                 break;
17404             }
17405         }
17406
17407
17408         switch (o->op_type) {
17409         case OP_DBSTATE:
17410             PL_curcop = ((COP*)o);              /* for warnings */
17411             break;
17412         case OP_NEXTSTATE:
17413             PL_curcop = ((COP*)o);              /* for warnings */
17414
17415             /* Optimise a "return ..." at the end of a sub to just be "...".
17416              * This saves 2 ops. Before:
17417              * 1  <;> nextstate(main 1 -e:1) v ->2
17418              * 4  <@> return K ->5
17419              * 2    <0> pushmark s ->3
17420              * -    <1> ex-rv2sv sK/1 ->4
17421              * 3      <#> gvsv[*cat] s ->4
17422              *
17423              * After:
17424              * -  <@> return K ->-
17425              * -    <0> pushmark s ->2
17426              * -    <1> ex-rv2sv sK/1 ->-
17427              * 2      <$> gvsv(*cat) s ->3
17428              */
17429             {
17430                 OP *next = o->op_next;
17431                 OP *sibling = OpSIBLING(o);
17432                 if (   OP_TYPE_IS(next, OP_PUSHMARK)
17433                     && OP_TYPE_IS(sibling, OP_RETURN)
17434                     && OP_TYPE_IS(sibling->op_next, OP_LINESEQ)
17435                     && ( OP_TYPE_IS(sibling->op_next->op_next, OP_LEAVESUB)
17436                        ||OP_TYPE_IS(sibling->op_next->op_next,
17437                                     OP_LEAVESUBLV))
17438                     && cUNOPx(sibling)->op_first == next
17439                     && OpHAS_SIBLING(next) && OpSIBLING(next)->op_next
17440                     && next->op_next
17441                 ) {
17442                     /* Look through the PUSHMARK's siblings for one that
17443                      * points to the RETURN */
17444                     OP *top = OpSIBLING(next);
17445                     while (top && top->op_next) {
17446                         if (top->op_next == sibling) {
17447                             top->op_next = sibling->op_next;
17448                             o->op_next = next->op_next;
17449                             break;
17450                         }
17451                         top = OpSIBLING(top);
17452                     }
17453                 }
17454             }
17455
17456             /* Optimise 'my $x; my $y;' into 'my ($x, $y);'
17457              *
17458              * This latter form is then suitable for conversion into padrange
17459              * later on. Convert:
17460              *
17461              *   nextstate1 -> padop1 -> nextstate2 -> padop2 -> nextstate3
17462              *
17463              * into:
17464              *
17465              *   nextstate1 ->     listop     -> nextstate3
17466              *                 /            \
17467              *         pushmark -> padop1 -> padop2
17468              */
17469             if (o->op_next && (
17470                     o->op_next->op_type == OP_PADSV
17471                  || o->op_next->op_type == OP_PADAV
17472                  || o->op_next->op_type == OP_PADHV
17473                 )
17474                 && !(o->op_next->op_private & ~OPpLVAL_INTRO)
17475                 && o->op_next->op_next && o->op_next->op_next->op_type == OP_NEXTSTATE
17476                 && o->op_next->op_next->op_next && (
17477                     o->op_next->op_next->op_next->op_type == OP_PADSV
17478                  || o->op_next->op_next->op_next->op_type == OP_PADAV
17479                  || o->op_next->op_next->op_next->op_type == OP_PADHV
17480                 )
17481                 && !(o->op_next->op_next->op_next->op_private & ~OPpLVAL_INTRO)
17482                 && o->op_next->op_next->op_next->op_next && o->op_next->op_next->op_next->op_next->op_type == OP_NEXTSTATE
17483                 && (!CopLABEL((COP*)o)) /* Don't mess with labels */
17484                 && (!CopLABEL((COP*)o->op_next->op_next)) /* ... */
17485             ) {
17486                 OP *pad1, *ns2, *pad2, *ns3, *newop, *newpm;
17487
17488                 pad1 =    o->op_next;
17489                 ns2  = pad1->op_next;
17490                 pad2 =  ns2->op_next;
17491                 ns3  = pad2->op_next;
17492
17493                 /* we assume here that the op_next chain is the same as
17494                  * the op_sibling chain */
17495                 assert(OpSIBLING(o)    == pad1);
17496                 assert(OpSIBLING(pad1) == ns2);
17497                 assert(OpSIBLING(ns2)  == pad2);
17498                 assert(OpSIBLING(pad2) == ns3);
17499
17500                 /* excise and delete ns2 */
17501                 op_sibling_splice(NULL, pad1, 1, NULL);
17502                 op_free(ns2);
17503
17504                 /* excise pad1 and pad2 */
17505                 op_sibling_splice(NULL, o, 2, NULL);
17506
17507                 /* create new listop, with children consisting of:
17508                  * a new pushmark, pad1, pad2. */
17509                 newop = newLISTOP(OP_LIST, 0, pad1, pad2);
17510                 newop->op_flags |= OPf_PARENS;
17511                 newop->op_flags = (newop->op_flags & ~OPf_WANT) | OPf_WANT_VOID;
17512
17513                 /* insert newop between o and ns3 */
17514                 op_sibling_splice(NULL, o, 0, newop);
17515
17516                 /*fixup op_next chain */
17517                 newpm = cUNOPx(newop)->op_first; /* pushmark */
17518                 o    ->op_next = newpm;
17519                 newpm->op_next = pad1;
17520                 pad1 ->op_next = pad2;
17521                 pad2 ->op_next = newop; /* listop */
17522                 newop->op_next = ns3;
17523
17524                 /* Ensure pushmark has this flag if padops do */
17525                 if (pad1->op_flags & OPf_MOD && pad2->op_flags & OPf_MOD) {
17526                     newpm->op_flags |= OPf_MOD;
17527                 }
17528
17529                 break;
17530             }
17531
17532             /* Two NEXTSTATEs in a row serve no purpose. Except if they happen
17533                to carry two labels. For now, take the easier option, and skip
17534                this optimisation if the first NEXTSTATE has a label.  */
17535             if (!CopLABEL((COP*)o) && !PERLDB_NOOPT) {
17536                 OP *nextop = o->op_next;
17537                 while (nextop) {
17538                     switch (nextop->op_type) {
17539                         case OP_NULL:
17540                         case OP_SCALAR:
17541                         case OP_LINESEQ:
17542                         case OP_SCOPE:
17543                             nextop = nextop->op_next;
17544                             continue;
17545                     }
17546                     break;
17547                 }
17548
17549                 if (nextop && (nextop->op_type == OP_NEXTSTATE)) {
17550                     op_null(o);
17551                     if (oldop)
17552                         oldop->op_next = nextop;
17553                     o = nextop;
17554                     /* Skip (old)oldop assignment since the current oldop's
17555                        op_next already points to the next op.  */
17556                     goto redo;
17557                 }
17558             }
17559             break;
17560
17561         case OP_CONCAT:
17562             if (o->op_next && o->op_next->op_type == OP_STRINGIFY) {
17563                 if (o->op_next->op_private & OPpTARGET_MY) {
17564                     if (o->op_flags & OPf_STACKED) /* chained concats */
17565                         break; /* ignore_optimization */
17566                     else {
17567                         /* assert(PL_opargs[o->op_type] & OA_TARGLEX); */
17568                         o->op_targ = o->op_next->op_targ;
17569                         o->op_next->op_targ = 0;
17570                         o->op_private |= OPpTARGET_MY;
17571                     }
17572                 }
17573                 op_null(o->op_next);
17574             }
17575             break;
17576         case OP_STUB:
17577             if ((o->op_flags & OPf_WANT) != OPf_WANT_LIST) {
17578                 break; /* Scalar stub must produce undef.  List stub is noop */
17579             }
17580             goto nothin;
17581         case OP_NULL:
17582             if (o->op_targ == OP_NEXTSTATE
17583                 || o->op_targ == OP_DBSTATE)
17584             {
17585                 PL_curcop = ((COP*)o);
17586             }
17587             /* XXX: We avoid setting op_seq here to prevent later calls
17588                to rpeep() from mistakenly concluding that optimisation
17589                has already occurred. This doesn't fix the real problem,
17590                though (See 20010220.007 (#5874)). AMS 20010719 */
17591             /* op_seq functionality is now replaced by op_opt */
17592             o->op_opt = 0;
17593             /* FALLTHROUGH */
17594         case OP_SCALAR:
17595         case OP_LINESEQ:
17596         case OP_SCOPE:
17597         nothin:
17598             if (oldop) {
17599                 oldop->op_next = o->op_next;
17600                 o->op_opt = 0;
17601                 continue;
17602             }
17603             break;
17604
17605         case OP_PUSHMARK:
17606
17607             /* Given
17608                  5 repeat/DOLIST
17609                  3   ex-list
17610                  1     pushmark
17611                  2     scalar or const
17612                  4   const[0]
17613                convert repeat into a stub with no kids.
17614              */
17615             if (o->op_next->op_type == OP_CONST
17616              || (  o->op_next->op_type == OP_PADSV
17617                 && !(o->op_next->op_private & OPpLVAL_INTRO))
17618              || (  o->op_next->op_type == OP_GV
17619                 && o->op_next->op_next->op_type == OP_RV2SV
17620                 && !(o->op_next->op_next->op_private
17621                         & (OPpLVAL_INTRO|OPpOUR_INTRO))))
17622             {
17623                 const OP *kid = o->op_next->op_next;
17624                 if (o->op_next->op_type == OP_GV)
17625                    kid = kid->op_next;
17626                 /* kid is now the ex-list.  */
17627                 if (kid->op_type == OP_NULL
17628                  && (kid = kid->op_next)->op_type == OP_CONST
17629                     /* kid is now the repeat count.  */
17630                  && kid->op_next->op_type == OP_REPEAT
17631                  && kid->op_next->op_private & OPpREPEAT_DOLIST
17632                  && (kid->op_next->op_flags & OPf_WANT) == OPf_WANT_LIST
17633                  && SvIOK(kSVOP_sv) && SvIVX(kSVOP_sv) == 0
17634                  && oldop)
17635                 {
17636                     o = kid->op_next; /* repeat */
17637                     oldop->op_next = o;
17638                     op_free(cBINOPo->op_first);
17639                     op_free(cBINOPo->op_last );
17640                     o->op_flags &=~ OPf_KIDS;
17641                     /* stub is a baseop; repeat is a binop */
17642                     STATIC_ASSERT_STMT(sizeof(OP) <= sizeof(BINOP));
17643                     OpTYPE_set(o, OP_STUB);
17644                     o->op_private = 0;
17645                     break;
17646                 }
17647             }
17648
17649             /* Convert a series of PAD ops for my vars plus support into a
17650              * single padrange op. Basically
17651              *
17652              *    pushmark -> pad[ahs]v -> pad[ahs]?v -> ... -> (list) -> rest
17653              *
17654              * becomes, depending on circumstances, one of
17655              *
17656              *    padrange  ----------------------------------> (list) -> rest
17657              *    padrange  --------------------------------------------> rest
17658              *
17659              * where all the pad indexes are sequential and of the same type
17660              * (INTRO or not).
17661              * We convert the pushmark into a padrange op, then skip
17662              * any other pad ops, and possibly some trailing ops.
17663              * Note that we don't null() the skipped ops, to make it
17664              * easier for Deparse to undo this optimisation (and none of
17665              * the skipped ops are holding any resourses). It also makes
17666              * it easier for find_uninit_var(), as it can just ignore
17667              * padrange, and examine the original pad ops.
17668              */
17669         {
17670             OP *p;
17671             OP *followop = NULL; /* the op that will follow the padrange op */
17672             U8 count = 0;
17673             U8 intro = 0;
17674             PADOFFSET base = 0; /* init only to stop compiler whining */
17675             bool gvoid = 0;     /* init only to stop compiler whining */
17676             bool defav = 0;  /* seen (...) = @_ */
17677             bool reuse = 0;  /* reuse an existing padrange op */
17678
17679             /* look for a pushmark -> gv[_] -> rv2av */
17680
17681             {
17682                 OP *rv2av, *q;
17683                 p = o->op_next;
17684                 if (   p->op_type == OP_GV
17685                     && cGVOPx_gv(p) == PL_defgv
17686                     && (rv2av = p->op_next)
17687                     && rv2av->op_type == OP_RV2AV
17688                     && !(rv2av->op_flags & OPf_REF)
17689                     && !(rv2av->op_private & (OPpLVAL_INTRO|OPpMAYBE_LVSUB))
17690                     && ((rv2av->op_flags & OPf_WANT) == OPf_WANT_LIST)
17691                 ) {
17692                     q = rv2av->op_next;
17693                     if (q->op_type == OP_NULL)
17694                         q = q->op_next;
17695                     if (q->op_type == OP_PUSHMARK) {
17696                         defav = 1;
17697                         p = q;
17698                     }
17699                 }
17700             }
17701             if (!defav) {
17702                 p = o;
17703             }
17704
17705             /* scan for PAD ops */
17706
17707             for (p = p->op_next; p; p = p->op_next) {
17708                 if (p->op_type == OP_NULL)
17709                     continue;
17710
17711                 if ((     p->op_type != OP_PADSV
17712                        && p->op_type != OP_PADAV
17713                        && p->op_type != OP_PADHV
17714                     )
17715                       /* any private flag other than INTRO? e.g. STATE */
17716                    || (p->op_private & ~OPpLVAL_INTRO)
17717                 )
17718                     break;
17719
17720                 /* let $a[N] potentially be optimised into AELEMFAST_LEX
17721                  * instead */
17722                 if (   p->op_type == OP_PADAV
17723                     && p->op_next
17724                     && p->op_next->op_type == OP_CONST
17725                     && p->op_next->op_next
17726                     && p->op_next->op_next->op_type == OP_AELEM
17727                 )
17728                     break;
17729
17730                 /* for 1st padop, note what type it is and the range
17731                  * start; for the others, check that it's the same type
17732                  * and that the targs are contiguous */
17733                 if (count == 0) {
17734                     intro = (p->op_private & OPpLVAL_INTRO);
17735                     base = p->op_targ;
17736                     gvoid = OP_GIMME(p,0) == G_VOID;
17737                 }
17738                 else {
17739                     if ((p->op_private & OPpLVAL_INTRO) != intro)
17740                         break;
17741                     /* Note that you'd normally  expect targs to be
17742                      * contiguous in my($a,$b,$c), but that's not the case
17743                      * when external modules start doing things, e.g.
17744                      * Function::Parameters */
17745                     if (p->op_targ != base + count)
17746                         break;
17747                     assert(p->op_targ == base + count);
17748                     /* Either all the padops or none of the padops should
17749                        be in void context.  Since we only do the optimisa-
17750                        tion for av/hv when the aggregate itself is pushed
17751                        on to the stack (one item), there is no need to dis-
17752                        tinguish list from scalar context.  */
17753                     if (gvoid != (OP_GIMME(p,0) == G_VOID))
17754                         break;
17755                 }
17756
17757                 /* for AV, HV, only when we're not flattening */
17758                 if (   p->op_type != OP_PADSV
17759                     && !gvoid
17760                     && !(p->op_flags & OPf_REF)
17761                 )
17762                     break;
17763
17764                 if (count >= OPpPADRANGE_COUNTMASK)
17765                     break;
17766
17767                 /* there's a biggest base we can fit into a
17768                  * SAVEt_CLEARPADRANGE in pp_padrange.
17769                  * (The sizeof() stuff will be constant-folded, and is
17770                  * intended to avoid getting "comparison is always false"
17771                  * compiler warnings. See the comments above
17772                  * MEM_WRAP_CHECK for more explanation on why we do this
17773                  * in a weird way to avoid compiler warnings.)
17774                  */
17775                 if (   intro
17776                     && (8*sizeof(base) >
17777                         8*sizeof(UV)-OPpPADRANGE_COUNTSHIFT-SAVE_TIGHT_SHIFT
17778                         ? (Size_t)base
17779                         : (UV_MAX >> (OPpPADRANGE_COUNTSHIFT+SAVE_TIGHT_SHIFT))
17780                         ) >
17781                         (UV_MAX >> (OPpPADRANGE_COUNTSHIFT+SAVE_TIGHT_SHIFT))
17782                 )
17783                     break;
17784
17785                 /* Success! We've got another valid pad op to optimise away */
17786                 count++;
17787                 followop = p->op_next;
17788             }
17789
17790             if (count < 1 || (count == 1 && !defav))
17791                 break;
17792
17793             /* pp_padrange in specifically compile-time void context
17794              * skips pushing a mark and lexicals; in all other contexts
17795              * (including unknown till runtime) it pushes a mark and the
17796              * lexicals. We must be very careful then, that the ops we
17797              * optimise away would have exactly the same effect as the
17798              * padrange.
17799              * In particular in void context, we can only optimise to
17800              * a padrange if we see the complete sequence
17801              *     pushmark, pad*v, ...., list
17802              * which has the net effect of leaving the markstack as it
17803              * was.  Not pushing onto the stack (whereas padsv does touch
17804              * the stack) makes no difference in void context.
17805              */
17806             assert(followop);
17807             if (gvoid) {
17808                 if (followop->op_type == OP_LIST
17809                         && OP_GIMME(followop,0) == G_VOID
17810                    )
17811                 {
17812                     followop = followop->op_next; /* skip OP_LIST */
17813
17814                     /* consolidate two successive my(...);'s */
17815
17816                     if (   oldoldop
17817                         && oldoldop->op_type == OP_PADRANGE
17818                         && (oldoldop->op_flags & OPf_WANT) == OPf_WANT_VOID
17819                         && (oldoldop->op_private & OPpLVAL_INTRO) == intro
17820                         && !(oldoldop->op_flags & OPf_SPECIAL)
17821                     ) {
17822                         U8 old_count;
17823                         assert(oldoldop->op_next == oldop);
17824                         assert(   oldop->op_type == OP_NEXTSTATE
17825                                || oldop->op_type == OP_DBSTATE);
17826                         assert(oldop->op_next == o);
17827
17828                         old_count
17829                             = (oldoldop->op_private & OPpPADRANGE_COUNTMASK);
17830
17831                        /* Do not assume pad offsets for $c and $d are con-
17832                           tiguous in
17833                             my ($a,$b,$c);
17834                             my ($d,$e,$f);
17835                         */
17836                         if (  oldoldop->op_targ + old_count == base
17837                            && old_count < OPpPADRANGE_COUNTMASK - count) {
17838                             base = oldoldop->op_targ;
17839                             count += old_count;
17840                             reuse = 1;
17841                         }
17842                     }
17843
17844                     /* if there's any immediately following singleton
17845                      * my var's; then swallow them and the associated
17846                      * nextstates; i.e.
17847                      *    my ($a,$b); my $c; my $d;
17848                      * is treated as
17849                      *    my ($a,$b,$c,$d);
17850                      */
17851
17852                     while (    ((p = followop->op_next))
17853                             && (  p->op_type == OP_PADSV
17854                                || p->op_type == OP_PADAV
17855                                || p->op_type == OP_PADHV)
17856                             && (p->op_flags & OPf_WANT) == OPf_WANT_VOID
17857                             && (p->op_private & OPpLVAL_INTRO) == intro
17858                             && !(p->op_private & ~OPpLVAL_INTRO)
17859                             && p->op_next
17860                             && (   p->op_next->op_type == OP_NEXTSTATE
17861                                 || p->op_next->op_type == OP_DBSTATE)
17862                             && count < OPpPADRANGE_COUNTMASK
17863                             && base + count == p->op_targ
17864                     ) {
17865                         count++;
17866                         followop = p->op_next;
17867                     }
17868                 }
17869                 else
17870                     break;
17871             }
17872
17873             if (reuse) {
17874                 assert(oldoldop->op_type == OP_PADRANGE);
17875                 oldoldop->op_next = followop;
17876                 oldoldop->op_private = (intro | count);
17877                 o = oldoldop;
17878                 oldop = NULL;
17879                 oldoldop = NULL;
17880             }
17881             else {
17882                 /* Convert the pushmark into a padrange.
17883                  * To make Deparse easier, we guarantee that a padrange was
17884                  * *always* formerly a pushmark */
17885                 assert(o->op_type == OP_PUSHMARK);
17886                 o->op_next = followop;
17887                 OpTYPE_set(o, OP_PADRANGE);
17888                 o->op_targ = base;
17889                 /* bit 7: INTRO; bit 6..0: count */
17890                 o->op_private = (intro | count);
17891                 o->op_flags = ((o->op_flags & ~(OPf_WANT|OPf_SPECIAL))
17892                               | gvoid * OPf_WANT_VOID
17893                               | (defav ? OPf_SPECIAL : 0));
17894             }
17895             break;
17896         }
17897
17898         case OP_RV2AV:
17899             if ((o->op_flags & OPf_WANT) == OPf_WANT_SCALAR)
17900                 S_check_for_bool_cxt(o, 1, OPpTRUEBOOL, 0);
17901             break;
17902
17903         case OP_RV2HV:
17904         case OP_PADHV:
17905             /*'keys %h' in void or scalar context: skip the OP_KEYS
17906              * and perform the functionality directly in the RV2HV/PADHV
17907              * op
17908              */
17909             if (o->op_flags & OPf_REF) {
17910                 OP *k = o->op_next;
17911                 U8 want = (k->op_flags & OPf_WANT);
17912                 if (   k
17913                     && k->op_type == OP_KEYS
17914                     && (   want == OPf_WANT_VOID
17915                         || want == OPf_WANT_SCALAR)
17916                     && !(k->op_private & OPpMAYBE_LVSUB)
17917                     && !(k->op_flags & OPf_MOD)
17918                 ) {
17919                     o->op_next     = k->op_next;
17920                     o->op_flags   &= ~(OPf_REF|OPf_WANT);
17921                     o->op_flags   |= want;
17922                     o->op_private |= (o->op_type == OP_PADHV ?
17923                                       OPpPADHV_ISKEYS : OPpRV2HV_ISKEYS);
17924                     /* for keys(%lex), hold onto the OP_KEYS's targ
17925                      * since padhv doesn't have its own targ to return
17926                      * an int with */
17927                     if (!(o->op_type ==OP_PADHV && want == OPf_WANT_SCALAR))
17928                         op_null(k);
17929                 }
17930             }
17931
17932             /* see if %h is used in boolean context */
17933             if ((o->op_flags & OPf_WANT) == OPf_WANT_SCALAR)
17934                 S_check_for_bool_cxt(o, 1, OPpTRUEBOOL, OPpMAYBE_TRUEBOOL);
17935
17936
17937             if (o->op_type != OP_PADHV)
17938                 break;
17939             /* FALLTHROUGH */
17940         case OP_PADAV:
17941             if (   o->op_type == OP_PADAV
17942                 && (o->op_flags & OPf_WANT) == OPf_WANT_SCALAR
17943             )
17944                 S_check_for_bool_cxt(o, 1, OPpTRUEBOOL, 0);
17945             /* FALLTHROUGH */
17946         case OP_PADSV:
17947             /* Skip over state($x) in void context.  */
17948             if (oldop && o->op_private == (OPpPAD_STATE|OPpLVAL_INTRO)
17949              && (o->op_flags & OPf_WANT) == OPf_WANT_VOID)
17950             {
17951                 oldop->op_next = o->op_next;
17952                 goto redo_nextstate;
17953             }
17954             if (o->op_type != OP_PADAV)
17955                 break;
17956             /* FALLTHROUGH */
17957         case OP_GV:
17958             if (o->op_type == OP_PADAV || o->op_next->op_type == OP_RV2AV) {
17959                 OP* const pop = (o->op_type == OP_PADAV) ?
17960                             o->op_next : o->op_next->op_next;
17961                 IV i;
17962                 if (pop && pop->op_type == OP_CONST &&
17963                     ((PL_op = pop->op_next)) &&
17964                     pop->op_next->op_type == OP_AELEM &&
17965                     !(pop->op_next->op_private &
17966                       (OPpLVAL_INTRO|OPpLVAL_DEFER|OPpDEREF|OPpMAYBE_LVSUB)) &&
17967                     (i = SvIV(((SVOP*)pop)->op_sv)) >= -128 && i <= 127)
17968                 {
17969                     GV *gv;
17970                     if (cSVOPx(pop)->op_private & OPpCONST_STRICT)
17971                         no_bareword_allowed(pop);
17972                     if (o->op_type == OP_GV)
17973                         op_null(o->op_next);
17974                     op_null(pop->op_next);
17975                     op_null(pop);
17976                     o->op_flags |= pop->op_next->op_flags & OPf_MOD;
17977                     o->op_next = pop->op_next->op_next;
17978                     o->op_ppaddr = PL_ppaddr[OP_AELEMFAST];
17979                     o->op_private = (U8)i;
17980                     if (o->op_type == OP_GV) {
17981                         gv = cGVOPo_gv;
17982                         GvAVn(gv);
17983                         o->op_type = OP_AELEMFAST;
17984                     }
17985                     else
17986                         o->op_type = OP_AELEMFAST_LEX;
17987                 }
17988                 if (o->op_type != OP_GV)
17989                     break;
17990             }
17991
17992             /* Remove $foo from the op_next chain in void context.  */
17993             if (oldop
17994              && (  o->op_next->op_type == OP_RV2SV
17995                 || o->op_next->op_type == OP_RV2AV
17996                 || o->op_next->op_type == OP_RV2HV  )
17997              && (o->op_next->op_flags & OPf_WANT) == OPf_WANT_VOID
17998              && !(o->op_next->op_private & OPpLVAL_INTRO))
17999             {
18000                 oldop->op_next = o->op_next->op_next;
18001                 /* Reprocess the previous op if it is a nextstate, to
18002                    allow double-nextstate optimisation.  */
18003               redo_nextstate:
18004                 if (oldop->op_type == OP_NEXTSTATE) {
18005                     oldop->op_opt = 0;
18006                     o = oldop;
18007                     oldop = oldoldop;
18008                     oldoldop = NULL;
18009                     goto redo;
18010                 }
18011                 o = oldop->op_next;
18012                 goto redo;
18013             }
18014             else if (o->op_next->op_type == OP_RV2SV) {
18015                 if (!(o->op_next->op_private & OPpDEREF)) {
18016                     op_null(o->op_next);
18017                     o->op_private |= o->op_next->op_private & (OPpLVAL_INTRO
18018                                                                | OPpOUR_INTRO);
18019                     o->op_next = o->op_next->op_next;
18020                     OpTYPE_set(o, OP_GVSV);
18021                 }
18022             }
18023             else if (o->op_next->op_type == OP_READLINE
18024                     && o->op_next->op_next->op_type == OP_CONCAT
18025                     && (o->op_next->op_next->op_flags & OPf_STACKED))
18026             {
18027                 /* Turn "$a .= <FH>" into an OP_RCATLINE. AMS 20010917 */
18028                 OpTYPE_set(o, OP_RCATLINE);
18029                 o->op_flags |= OPf_STACKED;
18030                 op_null(o->op_next->op_next);
18031                 op_null(o->op_next);
18032             }
18033
18034             break;
18035
18036         case OP_NOT:
18037             break;
18038
18039         case OP_AND:
18040         case OP_OR:
18041         case OP_DOR:
18042         case OP_CMPCHAIN_AND:
18043         case OP_PUSHDEFER:
18044             while (cLOGOP->op_other->op_type == OP_NULL)
18045                 cLOGOP->op_other = cLOGOP->op_other->op_next;
18046             while (o->op_next && (   o->op_type == o->op_next->op_type
18047                                   || o->op_next->op_type == OP_NULL))
18048                 o->op_next = o->op_next->op_next;
18049
18050             /* If we're an OR and our next is an AND in void context, we'll
18051                follow its op_other on short circuit, same for reverse.
18052                We can't do this with OP_DOR since if it's true, its return
18053                value is the underlying value which must be evaluated
18054                by the next op. */
18055             if (o->op_next &&
18056                 (
18057                     (IS_AND_OP(o) && IS_OR_OP(o->op_next))
18058                  || (IS_OR_OP(o) && IS_AND_OP(o->op_next))
18059                 )
18060                 && (o->op_next->op_flags & OPf_WANT) == OPf_WANT_VOID
18061             ) {
18062                 o->op_next = ((LOGOP*)o->op_next)->op_other;
18063             }
18064             DEFER(cLOGOP->op_other);
18065             o->op_opt = 1;
18066             break;
18067
18068         case OP_GREPWHILE:
18069             if ((o->op_flags & OPf_WANT) == OPf_WANT_SCALAR)
18070                 S_check_for_bool_cxt(o, 1, OPpTRUEBOOL, 0);
18071             /* FALLTHROUGH */
18072         case OP_COND_EXPR:
18073         case OP_MAPWHILE:
18074         case OP_ANDASSIGN:
18075         case OP_ORASSIGN:
18076         case OP_DORASSIGN:
18077         case OP_RANGE:
18078         case OP_ONCE:
18079         case OP_ARGDEFELEM:
18080             while (cLOGOP->op_other->op_type == OP_NULL)
18081                 cLOGOP->op_other = cLOGOP->op_other->op_next;
18082             DEFER(cLOGOP->op_other);
18083             break;
18084
18085         case OP_ENTERLOOP:
18086         case OP_ENTERITER:
18087             while (cLOOP->op_redoop->op_type == OP_NULL)
18088                 cLOOP->op_redoop = cLOOP->op_redoop->op_next;
18089             while (cLOOP->op_nextop->op_type == OP_NULL)
18090                 cLOOP->op_nextop = cLOOP->op_nextop->op_next;
18091             while (cLOOP->op_lastop->op_type == OP_NULL)
18092                 cLOOP->op_lastop = cLOOP->op_lastop->op_next;
18093             /* a while(1) loop doesn't have an op_next that escapes the
18094              * loop, so we have to explicitly follow the op_lastop to
18095              * process the rest of the code */
18096             DEFER(cLOOP->op_lastop);
18097             break;
18098
18099         case OP_ENTERTRY:
18100             assert(cLOGOPo->op_other->op_type == OP_LEAVETRY);
18101             DEFER(cLOGOPo->op_other);
18102             break;
18103
18104         case OP_ENTERTRYCATCH:
18105             assert(cLOGOPo->op_other->op_type == OP_CATCH);
18106             /* catch body is the ->op_other of the OP_CATCH */
18107             DEFER(cLOGOPx(cLOGOPo->op_other)->op_other);
18108             break;
18109
18110         case OP_SUBST:
18111             if ((o->op_flags & OPf_WANT) == OPf_WANT_SCALAR)
18112                 S_check_for_bool_cxt(o, 1, OPpTRUEBOOL, 0);
18113             assert(!(cPMOP->op_pmflags & PMf_ONCE));
18114             while (cPMOP->op_pmstashstartu.op_pmreplstart &&
18115                    cPMOP->op_pmstashstartu.op_pmreplstart->op_type == OP_NULL)
18116                 cPMOP->op_pmstashstartu.op_pmreplstart
18117                     = cPMOP->op_pmstashstartu.op_pmreplstart->op_next;
18118             DEFER(cPMOP->op_pmstashstartu.op_pmreplstart);
18119             break;
18120
18121         case OP_SORT: {
18122             OP *oright;
18123
18124             if (o->op_flags & OPf_SPECIAL) {
18125                 /* first arg is a code block */
18126                 OP * const nullop = OpSIBLING(cLISTOP->op_first);
18127                 OP * kid          = cUNOPx(nullop)->op_first;
18128
18129                 assert(nullop->op_type == OP_NULL);
18130                 assert(kid->op_type == OP_SCOPE
18131                  || (kid->op_type == OP_NULL && kid->op_targ == OP_LEAVE));
18132                 /* since OP_SORT doesn't have a handy op_other-style
18133                  * field that can point directly to the start of the code
18134                  * block, store it in the otherwise-unused op_next field
18135                  * of the top-level OP_NULL. This will be quicker at
18136                  * run-time, and it will also allow us to remove leading
18137                  * OP_NULLs by just messing with op_nexts without
18138                  * altering the basic op_first/op_sibling layout. */
18139                 kid = kLISTOP->op_first;
18140                 assert(
18141                       (kid->op_type == OP_NULL
18142                       && (  kid->op_targ == OP_NEXTSTATE
18143                          || kid->op_targ == OP_DBSTATE  ))
18144                     || kid->op_type == OP_STUB
18145                     || kid->op_type == OP_ENTER
18146                     || (PL_parser && PL_parser->error_count));
18147                 nullop->op_next = kid->op_next;
18148                 DEFER(nullop->op_next);
18149             }
18150
18151             /* check that RHS of sort is a single plain array */
18152             oright = cUNOPo->op_first;
18153             if (!oright || oright->op_type != OP_PUSHMARK)
18154                 break;
18155
18156             if (o->op_private & OPpSORT_INPLACE)
18157                 break;
18158
18159             /* reverse sort ... can be optimised.  */
18160             if (!OpHAS_SIBLING(cUNOPo)) {
18161                 /* Nothing follows us on the list. */
18162                 OP * const reverse = o->op_next;
18163
18164                 if (reverse->op_type == OP_REVERSE &&
18165                     (reverse->op_flags & OPf_WANT) == OPf_WANT_LIST) {
18166                     OP * const pushmark = cUNOPx(reverse)->op_first;
18167                     if (pushmark && (pushmark->op_type == OP_PUSHMARK)
18168                         && (OpSIBLING(cUNOPx(pushmark)) == o)) {
18169                         /* reverse -> pushmark -> sort */
18170                         o->op_private |= OPpSORT_REVERSE;
18171                         op_null(reverse);
18172                         pushmark->op_next = oright->op_next;
18173                         op_null(oright);
18174                     }
18175                 }
18176             }
18177
18178             break;
18179         }
18180
18181         case OP_REVERSE: {
18182             OP *ourmark, *theirmark, *ourlast, *iter, *expushmark, *rv2av;
18183             OP *gvop = NULL;
18184             LISTOP *enter, *exlist;
18185
18186             if (o->op_private & OPpSORT_INPLACE)
18187                 break;
18188
18189             enter = (LISTOP *) o->op_next;
18190             if (!enter)
18191                 break;
18192             if (enter->op_type == OP_NULL) {
18193                 enter = (LISTOP *) enter->op_next;
18194                 if (!enter)
18195                     break;
18196             }
18197             /* for $a (...) will have OP_GV then OP_RV2GV here.
18198                for (...) just has an OP_GV.  */
18199             if (enter->op_type == OP_GV) {
18200                 gvop = (OP *) enter;
18201                 enter = (LISTOP *) enter->op_next;
18202                 if (!enter)
18203                     break;
18204                 if (enter->op_type == OP_RV2GV) {
18205                   enter = (LISTOP *) enter->op_next;
18206                   if (!enter)
18207                     break;
18208                 }
18209             }
18210
18211             if (enter->op_type != OP_ENTERITER)
18212                 break;
18213
18214             iter = enter->op_next;
18215             if (!iter || iter->op_type != OP_ITER)
18216                 break;
18217
18218             expushmark = enter->op_first;
18219             if (!expushmark || expushmark->op_type != OP_NULL
18220                 || expushmark->op_targ != OP_PUSHMARK)
18221                 break;
18222
18223             exlist = (LISTOP *) OpSIBLING(expushmark);
18224             if (!exlist || exlist->op_type != OP_NULL
18225                 || exlist->op_targ != OP_LIST)
18226                 break;
18227
18228             if (exlist->op_last != o) {
18229                 /* Mmm. Was expecting to point back to this op.  */
18230                 break;
18231             }
18232             theirmark = exlist->op_first;
18233             if (!theirmark || theirmark->op_type != OP_PUSHMARK)
18234                 break;
18235
18236             if (OpSIBLING(theirmark) != o) {
18237                 /* There's something between the mark and the reverse, eg
18238                    for (1, reverse (...))
18239                    so no go.  */
18240                 break;
18241             }
18242
18243             ourmark = ((LISTOP *)o)->op_first;
18244             if (!ourmark || ourmark->op_type != OP_PUSHMARK)
18245                 break;
18246
18247             ourlast = ((LISTOP *)o)->op_last;
18248             if (!ourlast || ourlast->op_next != o)
18249                 break;
18250
18251             rv2av = OpSIBLING(ourmark);
18252             if (rv2av && rv2av->op_type == OP_RV2AV && !OpHAS_SIBLING(rv2av)
18253                 && rv2av->op_flags == (OPf_WANT_LIST | OPf_KIDS)) {
18254                 /* We're just reversing a single array.  */
18255                 rv2av->op_flags = OPf_WANT_SCALAR | OPf_KIDS | OPf_REF;
18256                 enter->op_flags |= OPf_STACKED;
18257             }
18258
18259             /* We don't have control over who points to theirmark, so sacrifice
18260                ours.  */
18261             theirmark->op_next = ourmark->op_next;
18262             theirmark->op_flags = ourmark->op_flags;
18263             ourlast->op_next = gvop ? gvop : (OP *) enter;
18264             op_null(ourmark);
18265             op_null(o);
18266             enter->op_private |= OPpITER_REVERSED;
18267             iter->op_private |= OPpITER_REVERSED;
18268
18269             oldoldop = NULL;
18270             oldop    = ourlast;
18271             o        = oldop->op_next;
18272             goto redo;
18273             NOT_REACHED; /* NOTREACHED */
18274             break;
18275         }
18276
18277         case OP_QR:
18278         case OP_MATCH:
18279             if (!(cPMOP->op_pmflags & PMf_ONCE)) {
18280                 assert (!cPMOP->op_pmstashstartu.op_pmreplstart);
18281             }
18282             break;
18283
18284         case OP_RUNCV:
18285             if (!(o->op_private & OPpOFFBYONE) && !CvCLONE(PL_compcv)
18286              && (!CvANON(PL_compcv) || (!PL_cv_has_eval && !PL_perldb)))
18287             {
18288                 SV *sv;
18289                 if (CvEVAL(PL_compcv)) sv = &PL_sv_undef;
18290                 else {
18291                     sv = newRV((SV *)PL_compcv);
18292                     sv_rvweaken(sv);
18293                     SvREADONLY_on(sv);
18294                 }
18295                 OpTYPE_set(o, OP_CONST);
18296                 o->op_flags |= OPf_SPECIAL;
18297                 cSVOPo->op_sv = sv;
18298             }
18299             break;
18300
18301         case OP_SASSIGN:
18302             if (OP_GIMME(o,0) == G_VOID
18303              || (  o->op_next->op_type == OP_LINESEQ
18304                 && (  o->op_next->op_next->op_type == OP_LEAVESUB
18305                    || (  o->op_next->op_next->op_type == OP_RETURN
18306                       && !CvLVALUE(PL_compcv)))))
18307             {
18308                 OP *right = cBINOP->op_first;
18309                 if (right) {
18310                     /*   sassign
18311                     *      RIGHT
18312                     *      substr
18313                     *         pushmark
18314                     *         arg1
18315                     *         arg2
18316                     *         ...
18317                     * becomes
18318                     *
18319                     *  ex-sassign
18320                     *     substr
18321                     *        pushmark
18322                     *        RIGHT
18323                     *        arg1
18324                     *        arg2
18325                     *        ...
18326                     */
18327                     OP *left = OpSIBLING(right);
18328                     if (left->op_type == OP_SUBSTR
18329                          && (left->op_private & 7) < 4) {
18330                         op_null(o);
18331                         /* cut out right */
18332                         op_sibling_splice(o, NULL, 1, NULL);
18333                         /* and insert it as second child of OP_SUBSTR */
18334                         op_sibling_splice(left, cBINOPx(left)->op_first, 0,
18335                                     right);
18336                         left->op_private |= OPpSUBSTR_REPL_FIRST;
18337                         left->op_flags =
18338                             (o->op_flags & ~OPf_WANT) | OPf_WANT_VOID;
18339                     }
18340                 }
18341             }
18342             break;
18343
18344         case OP_AASSIGN: {
18345             int l, r, lr, lscalars, rscalars;
18346
18347             /* handle common vars detection, e.g. ($a,$b) = ($b,$a).
18348                Note that we do this now rather than in newASSIGNOP(),
18349                since only by now are aliased lexicals flagged as such
18350
18351                See the essay "Common vars in list assignment" above for
18352                the full details of the rationale behind all the conditions
18353                below.
18354
18355                PL_generation sorcery:
18356                To detect whether there are common vars, the global var
18357                PL_generation is incremented for each assign op we scan.
18358                Then we run through all the lexical variables on the LHS,
18359                of the assignment, setting a spare slot in each of them to
18360                PL_generation.  Then we scan the RHS, and if any lexicals
18361                already have that value, we know we've got commonality.
18362                Also, if the generation number is already set to
18363                PERL_INT_MAX, then the variable is involved in aliasing, so
18364                we also have potential commonality in that case.
18365              */
18366
18367             PL_generation++;
18368             /* scan LHS */
18369             lscalars = 0;
18370             l = S_aassign_scan(aTHX_ cLISTOPo->op_last,  FALSE, &lscalars);
18371             /* scan RHS */
18372             rscalars = 0;
18373             r = S_aassign_scan(aTHX_ cLISTOPo->op_first, TRUE, &rscalars);
18374             lr = (l|r);
18375
18376
18377             /* After looking for things which are *always* safe, this main
18378              * if/else chain selects primarily based on the type of the
18379              * LHS, gradually working its way down from the more dangerous
18380              * to the more restrictive and thus safer cases */
18381
18382             if (   !l                      /* () = ....; */
18383                 || !r                      /* .... = (); */
18384                 || !(l & ~AAS_SAFE_SCALAR) /* (undef, pos()) = ...; */
18385                 || !(r & ~AAS_SAFE_SCALAR) /* ... = (1,2,length,undef); */
18386                 || (lscalars < 2)          /* (undef, $x) = ... */
18387             ) {
18388                 NOOP; /* always safe */
18389             }
18390             else if (l & AAS_DANGEROUS) {
18391                 /* always dangerous */
18392                 o->op_private |= OPpASSIGN_COMMON_SCALAR;
18393                 o->op_private |= OPpASSIGN_COMMON_AGG;
18394             }
18395             else if (l & (AAS_PKG_SCALAR|AAS_PKG_AGG)) {
18396                 /* package vars are always dangerous - too many
18397                  * aliasing possibilities */
18398                 if (l & AAS_PKG_SCALAR)
18399                     o->op_private |= OPpASSIGN_COMMON_SCALAR;
18400                 if (l & AAS_PKG_AGG)
18401                     o->op_private |= OPpASSIGN_COMMON_AGG;
18402             }
18403             else if (l & ( AAS_MY_SCALAR|AAS_MY_AGG
18404                           |AAS_LEX_SCALAR|AAS_LEX_AGG))
18405             {
18406                 /* LHS contains only lexicals and safe ops */
18407
18408                 if (l & (AAS_MY_AGG|AAS_LEX_AGG))
18409                     o->op_private |= OPpASSIGN_COMMON_AGG;
18410
18411                 if (l & (AAS_MY_SCALAR|AAS_LEX_SCALAR)) {
18412                     if (lr & AAS_LEX_SCALAR_COMM)
18413                         o->op_private |= OPpASSIGN_COMMON_SCALAR;
18414                     else if (   !(l & AAS_LEX_SCALAR)
18415                              && (r & AAS_DEFAV))
18416                     {
18417                         /* falsely mark
18418                          *    my (...) = @_
18419                          * as scalar-safe for performance reasons.
18420                          * (it will still have been marked _AGG if necessary */
18421                         NOOP;
18422                     }
18423                     else if (r  & (AAS_PKG_SCALAR|AAS_PKG_AGG|AAS_DANGEROUS))
18424                         /* if there are only lexicals on the LHS and no
18425                          * common ones on the RHS, then we assume that the
18426                          * only way those lexicals could also get
18427                          * on the RHS is via some sort of dereffing or
18428                          * closure, e.g.
18429                          *    $r = \$lex;
18430                          *    ($lex, $x) = (1, $$r)
18431                          * and in this case we assume the var must have
18432                          *  a bumped ref count. So if its ref count is 1,
18433                          *  it must only be on the LHS.
18434                          */
18435                         o->op_private |= OPpASSIGN_COMMON_RC1;
18436                 }
18437             }
18438
18439             /* ... = ($x)
18440              * may have to handle aggregate on LHS, but we can't
18441              * have common scalars. */
18442             if (rscalars < 2)
18443                 o->op_private &=
18444                         ~(OPpASSIGN_COMMON_SCALAR|OPpASSIGN_COMMON_RC1);
18445
18446             if ((o->op_flags & OPf_WANT) == OPf_WANT_SCALAR)
18447                 S_check_for_bool_cxt(o, 1, OPpASSIGN_TRUEBOOL, 0);
18448             break;
18449         }
18450
18451         case OP_REF:
18452         case OP_BLESSED:
18453             /* if the op is used in boolean context, set the TRUEBOOL flag
18454              * which enables an optimisation at runtime which avoids creating
18455              * a stack temporary for known-true package names */
18456             if ((o->op_flags & OPf_WANT) == OPf_WANT_SCALAR)
18457                 S_check_for_bool_cxt(o, 1, OPpTRUEBOOL, OPpMAYBE_TRUEBOOL);
18458             break;
18459
18460         case OP_LENGTH:
18461             /* see if the op is used in known boolean context,
18462              * but not if OA_TARGLEX optimisation is enabled */
18463             if (   (o->op_flags & OPf_WANT) == OPf_WANT_SCALAR
18464                 && !(o->op_private & OPpTARGET_MY)
18465             )
18466                 S_check_for_bool_cxt(o, 1, OPpTRUEBOOL, 0);
18467             break;
18468
18469         case OP_POS:
18470             /* see if the op is used in known boolean context */
18471             if ((o->op_flags & OPf_WANT) == OPf_WANT_SCALAR)
18472                 S_check_for_bool_cxt(o, 1, OPpTRUEBOOL, 0);
18473             break;
18474
18475         case OP_CUSTOM: {
18476             Perl_cpeep_t cpeep =
18477                 XopENTRYCUSTOM(o, xop_peep);
18478             if (cpeep)
18479                 cpeep(aTHX_ o, oldop);
18480             break;
18481         }
18482
18483         }
18484         /* did we just null the current op? If so, re-process it to handle
18485          * eliding "empty" ops from the chain */
18486         if (o->op_type == OP_NULL && oldop && oldop->op_next == o) {
18487             o->op_opt = 0;
18488             o = oldop;
18489         }
18490         else {
18491             oldoldop = oldop;
18492             oldop = o;
18493         }
18494     }
18495     LEAVE;
18496 }
18497
18498 void
18499 Perl_peep(pTHX_ OP *o)
18500 {
18501     CALL_RPEEP(o);
18502 }
18503
18504 /*
18505 =for apidoc_section $custom
18506
18507 =for apidoc Perl_custom_op_xop
18508 Return the XOP structure for a given custom op.  This macro should be
18509 considered internal to C<OP_NAME> and the other access macros: use them instead.
18510 This macro does call a function.  Prior
18511 to 5.19.6, this was implemented as a
18512 function.
18513
18514 =cut
18515 */
18516
18517
18518 /* use PERL_MAGIC_ext to call a function to free the xop structure when
18519  * freeing PL_custom_ops */
18520
18521 static int
18522 custom_op_register_free(pTHX_ SV *sv, MAGIC *mg)
18523 {
18524     XOP *xop;
18525
18526     PERL_UNUSED_ARG(mg);
18527     xop = INT2PTR(XOP *, SvIV(sv));
18528     Safefree(xop->xop_name);
18529     Safefree(xop->xop_desc);
18530     Safefree(xop);
18531     return 0;
18532 }
18533
18534
18535 static const MGVTBL custom_op_register_vtbl = {
18536     0,                          /* get */
18537     0,                          /* set */
18538     0,                          /* len */
18539     0,                          /* clear */
18540     custom_op_register_free,     /* free */
18541     0,                          /* copy */
18542     0,                          /* dup */
18543 #ifdef MGf_LOCAL
18544     0,                          /* local */
18545 #endif
18546 };
18547
18548
18549 XOPRETANY
18550 Perl_custom_op_get_field(pTHX_ const OP *o, const xop_flags_enum field)
18551 {
18552     SV *keysv;
18553     HE *he = NULL;
18554     XOP *xop;
18555
18556     static const XOP xop_null = { 0, 0, 0, 0, 0 };
18557
18558     PERL_ARGS_ASSERT_CUSTOM_OP_GET_FIELD;
18559     assert(o->op_type == OP_CUSTOM);
18560
18561     /* This is wrong. It assumes a function pointer can be cast to IV,
18562      * which isn't guaranteed, but this is what the old custom OP code
18563      * did. In principle it should be safer to Copy the bytes of the
18564      * pointer into a PV: since the new interface is hidden behind
18565      * functions, this can be changed later if necessary.  */
18566     /* Change custom_op_xop if this ever happens */
18567     keysv = sv_2mortal(newSViv(PTR2IV(o->op_ppaddr)));
18568
18569     if (PL_custom_ops)
18570         he = hv_fetch_ent(PL_custom_ops, keysv, 0, 0);
18571
18572     /* See if the op isn't registered, but its name *is* registered.
18573      * That implies someone is using the pre-5.14 API,where only name and
18574      * description could be registered. If so, fake up a real
18575      * registration.
18576      * We only check for an existing name, and assume no one will have
18577      * just registered a desc */
18578     if (!he && PL_custom_op_names &&
18579         (he = hv_fetch_ent(PL_custom_op_names, keysv, 0, 0))
18580     ) {
18581         const char *pv;
18582         STRLEN l;
18583
18584         /* XXX does all this need to be shared mem? */
18585         Newxz(xop, 1, XOP);
18586         pv = SvPV(HeVAL(he), l);
18587         XopENTRY_set(xop, xop_name, savepvn(pv, l));
18588         if (PL_custom_op_descs &&
18589             (he = hv_fetch_ent(PL_custom_op_descs, keysv, 0, 0))
18590         ) {
18591             pv = SvPV(HeVAL(he), l);
18592             XopENTRY_set(xop, xop_desc, savepvn(pv, l));
18593         }
18594         Perl_custom_op_register(aTHX_ o->op_ppaddr, xop);
18595         he = hv_fetch_ent(PL_custom_ops, keysv, 0, 0);
18596         /* add magic to the SV so that the xop struct (pointed to by
18597          * SvIV(sv)) is freed. Normally a static xop is registered, but
18598          * for this backcompat hack, we've alloced one */
18599         (void)sv_magicext(HeVAL(he), NULL, PERL_MAGIC_ext,
18600                 &custom_op_register_vtbl, NULL, 0);
18601
18602     }
18603     else {
18604         if (!he)
18605             xop = (XOP *)&xop_null;
18606         else
18607             xop = INT2PTR(XOP *, SvIV(HeVAL(he)));
18608     }
18609
18610     {
18611         XOPRETANY any;
18612         if(field == XOPe_xop_ptr) {
18613             any.xop_ptr = xop;
18614         } else {
18615             const U32 flags = XopFLAGS(xop);
18616             if(flags & field) {
18617                 switch(field) {
18618                 case XOPe_xop_name:
18619                     any.xop_name = xop->xop_name;
18620                     break;
18621                 case XOPe_xop_desc:
18622                     any.xop_desc = xop->xop_desc;
18623                     break;
18624                 case XOPe_xop_class:
18625                     any.xop_class = xop->xop_class;
18626                     break;
18627                 case XOPe_xop_peep:
18628                     any.xop_peep = xop->xop_peep;
18629                     break;
18630                 default:
18631                   field_panic:
18632                     Perl_croak(aTHX_
18633                         "panic: custom_op_get_field(): invalid field %d\n",
18634                         (int)field);
18635                     break;
18636                 }
18637             } else {
18638                 switch(field) {
18639                 case XOPe_xop_name:
18640                     any.xop_name = XOPd_xop_name;
18641                     break;
18642                 case XOPe_xop_desc:
18643                     any.xop_desc = XOPd_xop_desc;
18644                     break;
18645                 case XOPe_xop_class:
18646                     any.xop_class = XOPd_xop_class;
18647                     break;
18648                 case XOPe_xop_peep:
18649                     any.xop_peep = XOPd_xop_peep;
18650                     break;
18651                 default:
18652                     goto field_panic;
18653                     break;
18654                 }
18655             }
18656         }
18657         return any;
18658     }
18659 }
18660
18661 /*
18662 =for apidoc custom_op_register
18663 Register a custom op.  See L<perlguts/"Custom Operators">.
18664
18665 =cut
18666 */
18667
18668 void
18669 Perl_custom_op_register(pTHX_ Perl_ppaddr_t ppaddr, const XOP *xop)
18670 {
18671     SV *keysv;
18672
18673     PERL_ARGS_ASSERT_CUSTOM_OP_REGISTER;
18674
18675     /* see the comment in custom_op_xop */
18676     keysv = sv_2mortal(newSViv(PTR2IV(ppaddr)));
18677
18678     if (!PL_custom_ops)
18679         PL_custom_ops = newHV();
18680
18681     if (!hv_store_ent(PL_custom_ops, keysv, newSViv(PTR2IV(xop)), 0))
18682         Perl_croak(aTHX_ "panic: can't register custom OP %s", xop->xop_name);
18683 }
18684
18685 /*
18686
18687 =for apidoc core_prototype
18688
18689 This function assigns the prototype of the named core function to C<sv>, or
18690 to a new mortal SV if C<sv> is C<NULL>.  It returns the modified C<sv>, or
18691 C<NULL> if the core function has no prototype.  C<code> is a code as returned
18692 by C<keyword()>.  It must not be equal to 0.
18693
18694 =cut
18695 */
18696
18697 SV *
18698 Perl_core_prototype(pTHX_ SV *sv, const char *name, const int code,
18699                           int * const opnum)
18700 {
18701     int i = 0, n = 0, seen_question = 0, defgv = 0;
18702     I32 oa;
18703 #define MAX_ARGS_OP ((sizeof(I32) - 1) * 2)
18704     char str[ MAX_ARGS_OP * 2 + 2 ]; /* One ';', one '\0' */
18705     bool nullret = FALSE;
18706
18707     PERL_ARGS_ASSERT_CORE_PROTOTYPE;
18708
18709     assert (code);
18710
18711     if (!sv) sv = sv_newmortal();
18712
18713 #define retsetpvs(x,y) sv_setpvs(sv, x); if(opnum) *opnum=(y); return sv
18714
18715     switch (code < 0 ? -code : code) {
18716     case KEY_and   : case KEY_chop: case KEY_chomp:
18717     case KEY_cmp   : case KEY_defined: case KEY_delete: case KEY_exec  :
18718     case KEY_exists: case KEY_eq     : case KEY_ge    : case KEY_goto  :
18719     case KEY_grep  : case KEY_gt     : case KEY_last  : case KEY_le    :
18720     case KEY_lt    : case KEY_map    : case KEY_ne    : case KEY_next  :
18721     case KEY_or    : case KEY_print  : case KEY_printf: case KEY_qr    :
18722     case KEY_redo  : case KEY_require: case KEY_return: case KEY_say   :
18723     case KEY_select: case KEY_sort   : case KEY_split : case KEY_system:
18724     case KEY_x     : case KEY_xor    :
18725         if (!opnum) return NULL; nullret = TRUE; goto findopnum;
18726     case KEY_glob:    retsetpvs("_;", OP_GLOB);
18727     case KEY_keys:    retsetpvs("\\[%@]", OP_KEYS);
18728     case KEY_values:  retsetpvs("\\[%@]", OP_VALUES);
18729     case KEY_each:    retsetpvs("\\[%@]", OP_EACH);
18730     case KEY_pos:     retsetpvs(";\\[$*]", OP_POS);
18731     case KEY___FILE__: case KEY___LINE__: case KEY___PACKAGE__:
18732         retsetpvs("", 0);
18733     case KEY_evalbytes:
18734         name = "entereval"; break;
18735     case KEY_readpipe:
18736         name = "backtick";
18737     }
18738
18739 #undef retsetpvs
18740
18741   findopnum:
18742     while (i < MAXO) {  /* The slow way. */
18743         if (strEQ(name, PL_op_name[i])
18744             || strEQ(name, PL_op_desc[i]))
18745         {
18746             if (nullret) { assert(opnum); *opnum = i; return NULL; }
18747             goto found;
18748         }
18749         i++;
18750     }
18751     return NULL;
18752   found:
18753     defgv = PL_opargs[i] & OA_DEFGV;
18754     oa = PL_opargs[i] >> OASHIFT;
18755     while (oa) {
18756         if (oa & OA_OPTIONAL && !seen_question && (
18757               !defgv || (oa & (OA_OPTIONAL - 1)) == OA_FILEREF
18758         )) {
18759             seen_question = 1;
18760             str[n++] = ';';
18761         }
18762         if ((oa & (OA_OPTIONAL - 1)) >= OA_AVREF
18763             && (oa & (OA_OPTIONAL - 1)) <= OA_SCALARREF
18764             /* But globs are already references (kinda) */
18765             && (oa & (OA_OPTIONAL - 1)) != OA_FILEREF
18766         ) {
18767             str[n++] = '\\';
18768         }
18769         if ((oa & (OA_OPTIONAL - 1)) == OA_SCALARREF
18770          && !scalar_mod_type(NULL, i)) {
18771             str[n++] = '[';
18772             str[n++] = '$';
18773             str[n++] = '@';
18774             str[n++] = '%';
18775             if (i == OP_LOCK || i == OP_UNDEF) str[n++] = '&';
18776             str[n++] = '*';
18777             str[n++] = ']';
18778         }
18779         else str[n++] = ("?$@@%&*$")[oa & (OA_OPTIONAL - 1)];
18780         if (oa & OA_OPTIONAL && defgv && str[n-1] == '$') {
18781             str[n-1] = '_'; defgv = 0;
18782         }
18783         oa = oa >> 4;
18784     }
18785     if (code == -KEY_not || code == -KEY_getprotobynumber) str[n++] = ';';
18786     str[n++] = '\0';
18787     sv_setpvn(sv, str, n - 1);
18788     if (opnum) *opnum = i;
18789     return sv;
18790 }
18791
18792 OP *
18793 Perl_coresub_op(pTHX_ SV * const coreargssv, const int code,
18794                       const int opnum)
18795 {
18796     OP * const argop = (opnum == OP_SELECT && code) ? NULL :
18797                                         newSVOP(OP_COREARGS,0,coreargssv);
18798     OP *o;
18799
18800     PERL_ARGS_ASSERT_CORESUB_OP;
18801
18802     switch(opnum) {
18803     case 0:
18804         return op_append_elem(OP_LINESEQ,
18805                        argop,
18806                        newSLICEOP(0,
18807                                   newSVOP(OP_CONST, 0, newSViv(-code % 3)),
18808                                   newOP(OP_CALLER,0)
18809                        )
18810                );
18811     case OP_EACH:
18812     case OP_KEYS:
18813     case OP_VALUES:
18814         o = newUNOP(OP_AVHVSWITCH,0,argop);
18815         o->op_private = opnum-OP_EACH;
18816         return o;
18817     case OP_SELECT: /* which represents OP_SSELECT as well */
18818         if (code)
18819             return newCONDOP(
18820                          0,
18821                          newBINOP(OP_GT, 0,
18822                                   newAVREF(newGVOP(OP_GV, 0, PL_defgv)),
18823                                   newSVOP(OP_CONST, 0, newSVuv(1))
18824                                  ),
18825                          coresub_op(newSVuv((UV)OP_SSELECT), 0,
18826                                     OP_SSELECT),
18827                          coresub_op(coreargssv, 0, OP_SELECT)
18828                    );
18829         /* FALLTHROUGH */
18830     default:
18831         switch (PL_opargs[opnum] & OA_CLASS_MASK) {
18832         case OA_BASEOP:
18833             return op_append_elem(
18834                         OP_LINESEQ, argop,
18835                         newOP(opnum,
18836                               opnum == OP_WANTARRAY || opnum == OP_RUNCV
18837                                 ? OPpOFFBYONE << 8 : 0)
18838                    );
18839         case OA_BASEOP_OR_UNOP:
18840             if (opnum == OP_ENTEREVAL) {
18841                 o = newUNOP(OP_ENTEREVAL,OPpEVAL_COPHH<<8,argop);
18842                 if (code == -KEY_evalbytes) o->op_private |= OPpEVAL_BYTES;
18843             }
18844             else o = newUNOP(opnum,0,argop);
18845             if (opnum == OP_CALLER) o->op_private |= OPpOFFBYONE;
18846             else {
18847           onearg:
18848               if (is_handle_constructor(o, 1))
18849                 argop->op_private |= OPpCOREARGS_DEREF1;
18850               if (scalar_mod_type(NULL, opnum))
18851                 argop->op_private |= OPpCOREARGS_SCALARMOD;
18852             }
18853             return o;
18854         default:
18855             o = op_convert_list(opnum,OPf_SPECIAL*(opnum == OP_GLOB),argop);
18856             if (is_handle_constructor(o, 2))
18857                 argop->op_private |= OPpCOREARGS_DEREF2;
18858             if (opnum == OP_SUBSTR) {
18859                 o->op_private |= OPpMAYBE_LVSUB;
18860                 return o;
18861             }
18862             else goto onearg;
18863         }
18864     }
18865 }
18866
18867 void
18868 Perl_report_redefined_cv(pTHX_ const SV *name, const CV *old_cv,
18869                                SV * const *new_const_svp)
18870 {
18871     const char *hvname;
18872     bool is_const = !!CvCONST(old_cv);
18873     SV *old_const_sv = is_const ? cv_const_sv(old_cv) : NULL;
18874
18875     PERL_ARGS_ASSERT_REPORT_REDEFINED_CV;
18876
18877     if (is_const && new_const_svp && old_const_sv == *new_const_svp)
18878         return;
18879         /* They are 2 constant subroutines generated from
18880            the same constant. This probably means that
18881            they are really the "same" proxy subroutine
18882            instantiated in 2 places. Most likely this is
18883            when a constant is exported twice.  Don't warn.
18884         */
18885     if (
18886         (ckWARN(WARN_REDEFINE)
18887          && !(
18888                 CvGV(old_cv) && GvSTASH(CvGV(old_cv))
18889              && HvNAMELEN(GvSTASH(CvGV(old_cv))) == 7
18890              && (hvname = HvNAME(GvSTASH(CvGV(old_cv))),
18891                  strEQ(hvname, "autouse"))
18892              )
18893         )
18894      || (is_const
18895          && ckWARN_d(WARN_REDEFINE)
18896          && (!new_const_svp || sv_cmp(old_const_sv, *new_const_svp))
18897         )
18898     )
18899         Perl_warner(aTHX_ packWARN(WARN_REDEFINE),
18900                           is_const
18901                             ? "Constant subroutine %" SVf " redefined"
18902                             : "Subroutine %" SVf " redefined",
18903                           SVfARG(name));
18904 }
18905
18906 /*
18907 =for apidoc_section $hook
18908
18909 These functions provide convenient and thread-safe means of manipulating
18910 hook variables.
18911
18912 =cut
18913 */
18914
18915 /*
18916 =for apidoc wrap_op_checker
18917
18918 Puts a C function into the chain of check functions for a specified op
18919 type.  This is the preferred way to manipulate the L</PL_check> array.
18920 C<opcode> specifies which type of op is to be affected.  C<new_checker>
18921 is a pointer to the C function that is to be added to that opcode's
18922 check chain, and C<old_checker_p> points to the storage location where a
18923 pointer to the next function in the chain will be stored.  The value of
18924 C<new_checker> is written into the L</PL_check> array, while the value
18925 previously stored there is written to C<*old_checker_p>.
18926
18927 L</PL_check> is global to an entire process, and a module wishing to
18928 hook op checking may find itself invoked more than once per process,
18929 typically in different threads.  To handle that situation, this function
18930 is idempotent.  The location C<*old_checker_p> must initially (once
18931 per process) contain a null pointer.  A C variable of static duration
18932 (declared at file scope, typically also marked C<static> to give
18933 it internal linkage) will be implicitly initialised appropriately,
18934 if it does not have an explicit initialiser.  This function will only
18935 actually modify the check chain if it finds C<*old_checker_p> to be null.
18936 This function is also thread safe on the small scale.  It uses appropriate
18937 locking to avoid race conditions in accessing L</PL_check>.
18938
18939 When this function is called, the function referenced by C<new_checker>
18940 must be ready to be called, except for C<*old_checker_p> being unfilled.
18941 In a threading situation, C<new_checker> may be called immediately,
18942 even before this function has returned.  C<*old_checker_p> will always
18943 be appropriately set before C<new_checker> is called.  If C<new_checker>
18944 decides not to do anything special with an op that it is given (which
18945 is the usual case for most uses of op check hooking), it must chain the
18946 check function referenced by C<*old_checker_p>.
18947
18948 Taken all together, XS code to hook an op checker should typically look
18949 something like this:
18950
18951     static Perl_check_t nxck_frob;
18952     static OP *myck_frob(pTHX_ OP *op) {
18953         ...
18954         op = nxck_frob(aTHX_ op);
18955         ...
18956         return op;
18957     }
18958     BOOT:
18959         wrap_op_checker(OP_FROB, myck_frob, &nxck_frob);
18960
18961 If you want to influence compilation of calls to a specific subroutine,
18962 then use L</cv_set_call_checker_flags> rather than hooking checking of
18963 all C<entersub> ops.
18964
18965 =cut
18966 */
18967
18968 void
18969 Perl_wrap_op_checker(pTHX_ Optype opcode,
18970     Perl_check_t new_checker, Perl_check_t *old_checker_p)
18971 {
18972
18973     PERL_UNUSED_CONTEXT;
18974     PERL_ARGS_ASSERT_WRAP_OP_CHECKER;
18975     if (*old_checker_p) return;
18976     OP_CHECK_MUTEX_LOCK;
18977     if (!*old_checker_p) {
18978         *old_checker_p = PL_check[opcode];
18979         PL_check[opcode] = new_checker;
18980     }
18981     OP_CHECK_MUTEX_UNLOCK;
18982 }
18983
18984 #include "XSUB.h"
18985
18986 /* Efficient sub that returns a constant scalar value. */
18987 static void
18988 const_sv_xsub(pTHX_ CV* cv)
18989 {
18990     dXSARGS;
18991     SV *const sv = MUTABLE_SV(XSANY.any_ptr);
18992     PERL_UNUSED_ARG(items);
18993     if (!sv) {
18994         XSRETURN(0);
18995     }
18996     EXTEND(sp, 1);
18997     ST(0) = sv;
18998     XSRETURN(1);
18999 }
19000
19001 static void
19002 const_av_xsub(pTHX_ CV* cv)
19003 {
19004     dXSARGS;
19005     AV * const av = MUTABLE_AV(XSANY.any_ptr);
19006     SP -= items;
19007     assert(av);
19008 #ifndef DEBUGGING
19009     if (!av) {
19010         XSRETURN(0);
19011     }
19012 #endif
19013     if (SvRMAGICAL(av))
19014         Perl_croak(aTHX_ "Magical list constants are not supported");
19015     if (GIMME_V != G_LIST) {
19016         EXTEND(SP, 1);
19017         ST(0) = sv_2mortal(newSViv((IV)AvFILLp(av)+1));
19018         XSRETURN(1);
19019     }
19020     EXTEND(SP, AvFILLp(av)+1);
19021     Copy(AvARRAY(av), &ST(0), AvFILLp(av)+1, SV *);
19022     XSRETURN(AvFILLp(av)+1);
19023 }
19024
19025 /* Copy an existing cop->cop_warnings field.
19026  * If it's one of the standard addresses, just re-use the address.
19027  * This is the e implementation for the DUP_WARNINGS() macro
19028  */
19029
19030 STRLEN*
19031 Perl_dup_warnings(pTHX_ STRLEN* warnings)
19032 {
19033     Size_t size;
19034     STRLEN *new_warnings;
19035
19036     if (warnings == NULL || specialWARN(warnings))
19037         return warnings;
19038
19039     size = sizeof(*warnings) + *warnings;
19040
19041     new_warnings = (STRLEN*)PerlMemShared_malloc(size);
19042     Copy(warnings, new_warnings, size, char);
19043     return new_warnings;
19044 }
19045
19046 /*
19047  * ex: set ts=8 sts=4 sw=4 et:
19048  */