This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
document the new flags behaviour and why
[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 void
1438 Perl_op_refcnt_lock(pTHX)
1439   PERL_TSA_ACQUIRE(PL_op_mutex)
1440 {
1441     PERL_UNUSED_CONTEXT;
1442     OP_REFCNT_LOCK;
1443 }
1444
1445 void
1446 Perl_op_refcnt_unlock(pTHX)
1447   PERL_TSA_RELEASE(PL_op_mutex)
1448 {
1449     PERL_UNUSED_CONTEXT;
1450     OP_REFCNT_UNLOCK;
1451 }
1452
1453
1454 /*
1455 =for apidoc op_sibling_splice
1456
1457 A general function for editing the structure of an existing chain of
1458 op_sibling nodes.  By analogy with the perl-level C<splice()> function, allows
1459 you to delete zero or more sequential nodes, replacing them with zero or
1460 more different nodes.  Performs the necessary op_first/op_last
1461 housekeeping on the parent node and op_sibling manipulation on the
1462 children.  The last deleted node will be marked as the last node by
1463 updating the op_sibling/op_sibparent or op_moresib field as appropriate.
1464
1465 Note that op_next is not manipulated, and nodes are not freed; that is the
1466 responsibility of the caller.  It also won't create a new list op for an
1467 empty list etc; use higher-level functions like op_append_elem() for that.
1468
1469 C<parent> is the parent node of the sibling chain. It may passed as C<NULL> if
1470 the splicing doesn't affect the first or last op in the chain.
1471
1472 C<start> is the node preceding the first node to be spliced.  Node(s)
1473 following it will be deleted, and ops will be inserted after it.  If it is
1474 C<NULL>, the first node onwards is deleted, and nodes are inserted at the
1475 beginning.
1476
1477 C<del_count> is the number of nodes to delete.  If zero, no nodes are deleted.
1478 If -1 or greater than or equal to the number of remaining kids, all
1479 remaining kids are deleted.
1480
1481 C<insert> is the first of a chain of nodes to be inserted in place of the nodes.
1482 If C<NULL>, no nodes are inserted.
1483
1484 The head of the chain of deleted ops is returned, or C<NULL> if no ops were
1485 deleted.
1486
1487 For example:
1488
1489     action                    before      after         returns
1490     ------                    -----       -----         -------
1491
1492                               P           P
1493     splice(P, A, 2, X-Y-Z)    |           |             B-C
1494                               A-B-C-D     A-X-Y-Z-D
1495
1496                               P           P
1497     splice(P, NULL, 1, X-Y)   |           |             A
1498                               A-B-C-D     X-Y-B-C-D
1499
1500                               P           P
1501     splice(P, NULL, 3, NULL)  |           |             A-B-C
1502                               A-B-C-D     D
1503
1504                               P           P
1505     splice(P, B, 0, X-Y)      |           |             NULL
1506                               A-B-C-D     A-B-X-Y-C-D
1507
1508
1509 For lower-level direct manipulation of C<op_sibparent> and C<op_moresib>,
1510 see C<L</OpMORESIB_set>>, C<L</OpLASTSIB_set>>, C<L</OpMAYBESIB_set>>.
1511
1512 =cut
1513 */
1514
1515 OP *
1516 Perl_op_sibling_splice(OP *parent, OP *start, int del_count, OP* insert)
1517 {
1518     OP *first;
1519     OP *rest;
1520     OP *last_del = NULL;
1521     OP *last_ins = NULL;
1522
1523     if (start)
1524         first = OpSIBLING(start);
1525     else if (!parent)
1526         goto no_parent;
1527     else
1528         first = cLISTOPx(parent)->op_first;
1529
1530     assert(del_count >= -1);
1531
1532     if (del_count && first) {
1533         last_del = first;
1534         while (--del_count && OpHAS_SIBLING(last_del))
1535             last_del = OpSIBLING(last_del);
1536         rest = OpSIBLING(last_del);
1537         OpLASTSIB_set(last_del, NULL);
1538     }
1539     else
1540         rest = first;
1541
1542     if (insert) {
1543         last_ins = insert;
1544         while (OpHAS_SIBLING(last_ins))
1545             last_ins = OpSIBLING(last_ins);
1546         OpMAYBESIB_set(last_ins, rest, NULL);
1547     }
1548     else
1549         insert = rest;
1550
1551     if (start) {
1552         OpMAYBESIB_set(start, insert, NULL);
1553     }
1554     else {
1555         assert(parent);
1556         cLISTOPx(parent)->op_first = insert;
1557         if (insert)
1558             parent->op_flags |= OPf_KIDS;
1559         else
1560             parent->op_flags &= ~OPf_KIDS;
1561     }
1562
1563     if (!rest) {
1564         /* update op_last etc */
1565         U32 type;
1566         OP *lastop;
1567
1568         if (!parent)
1569             goto no_parent;
1570
1571         /* ought to use OP_CLASS(parent) here, but that can't handle
1572          * ex-foo OP_NULL ops. Also note that XopENTRYCUSTOM() can't
1573          * either */
1574         type = parent->op_type;
1575         if (type == OP_CUSTOM) {
1576             dTHX;
1577             type = XopENTRYCUSTOM(parent, xop_class);
1578         }
1579         else {
1580             if (type == OP_NULL)
1581                 type = parent->op_targ;
1582             type = PL_opargs[type] & OA_CLASS_MASK;
1583         }
1584
1585         lastop = last_ins ? last_ins : start ? start : NULL;
1586         if (   type == OA_BINOP
1587             || type == OA_LISTOP
1588             || type == OA_PMOP
1589             || type == OA_LOOP
1590         )
1591             cLISTOPx(parent)->op_last = lastop;
1592
1593         if (lastop)
1594             OpLASTSIB_set(lastop, parent);
1595     }
1596     return last_del ? first : NULL;
1597
1598   no_parent:
1599     Perl_croak_nocontext("panic: op_sibling_splice(): NULL parent");
1600 }
1601
1602 /*
1603 =for apidoc op_parent
1604
1605 Returns the parent OP of C<o>, if it has a parent. Returns C<NULL> otherwise.
1606
1607 =cut
1608 */
1609
1610 OP *
1611 Perl_op_parent(OP *o)
1612 {
1613     PERL_ARGS_ASSERT_OP_PARENT;
1614     while (OpHAS_SIBLING(o))
1615         o = OpSIBLING(o);
1616     return o->op_sibparent;
1617 }
1618
1619 /* replace the sibling following start with a new UNOP, which becomes
1620  * the parent of the original sibling; e.g.
1621  *
1622  *  op_sibling_newUNOP(P, A, unop-args...)
1623  *
1624  *  P              P
1625  *  |      becomes |
1626  *  A-B-C          A-U-C
1627  *                   |
1628  *                   B
1629  *
1630  * where U is the new UNOP.
1631  *
1632  * parent and start args are the same as for op_sibling_splice();
1633  * type and flags args are as newUNOP().
1634  *
1635  * Returns the new UNOP.
1636  */
1637
1638 STATIC OP *
1639 S_op_sibling_newUNOP(pTHX_ OP *parent, OP *start, I32 type, I32 flags)
1640 {
1641     OP *kid, *newop;
1642
1643     kid = op_sibling_splice(parent, start, 1, NULL);
1644     newop = newUNOP(type, flags, kid);
1645     op_sibling_splice(parent, start, 0, newop);
1646     return newop;
1647 }
1648
1649
1650 /* lowest-level newLOGOP-style function - just allocates and populates
1651  * the struct. Higher-level stuff should be done by S_new_logop() /
1652  * newLOGOP(). This function exists mainly to avoid op_first assignment
1653  * being spread throughout this file.
1654  */
1655
1656 LOGOP *
1657 Perl_alloc_LOGOP(pTHX_ I32 type, OP *first, OP* other)
1658 {
1659     LOGOP *logop;
1660     OP *kid = first;
1661     NewOp(1101, logop, 1, LOGOP);
1662     OpTYPE_set(logop, type);
1663     logop->op_first = first;
1664     logop->op_other = other;
1665     if (first)
1666         logop->op_flags = OPf_KIDS;
1667     while (kid && OpHAS_SIBLING(kid))
1668         kid = OpSIBLING(kid);
1669     if (kid)
1670         OpLASTSIB_set(kid, (OP*)logop);
1671     return logop;
1672 }
1673
1674
1675 /* Contextualizers */
1676
1677 /*
1678 =for apidoc op_contextualize
1679
1680 Applies a syntactic context to an op tree representing an expression.
1681 C<o> is the op tree, and C<context> must be C<G_SCALAR>, C<G_LIST>,
1682 or C<G_VOID> to specify the context to apply.  The modified op tree
1683 is returned.
1684
1685 =cut
1686 */
1687
1688 OP *
1689 Perl_op_contextualize(pTHX_ OP *o, I32 context)
1690 {
1691     PERL_ARGS_ASSERT_OP_CONTEXTUALIZE;
1692     switch (context) {
1693         case G_SCALAR: return scalar(o);
1694         case G_LIST:   return list(o);
1695         case G_VOID:   return scalarvoid(o);
1696         default:
1697             Perl_croak(aTHX_ "panic: op_contextualize bad context %ld",
1698                        (long) context);
1699     }
1700 }
1701
1702 /*
1703
1704 =for apidoc op_linklist
1705 This function is the implementation of the L</LINKLIST> macro.  It should
1706 not be called directly.
1707
1708 =cut
1709 */
1710
1711
1712 OP *
1713 Perl_op_linklist(pTHX_ OP *o)
1714 {
1715
1716     OP **prevp;
1717     OP *kid;
1718     OP * top_op = o;
1719
1720     PERL_ARGS_ASSERT_OP_LINKLIST;
1721
1722     while (1) {
1723         /* Descend down the tree looking for any unprocessed subtrees to
1724          * do first */
1725         if (!o->op_next) {
1726             if (o->op_flags & OPf_KIDS) {
1727                 o = cUNOPo->op_first;
1728                 continue;
1729             }
1730             o->op_next = o; /* leaf node; link to self initially */
1731         }
1732
1733         /* if we're at the top level, there either weren't any children
1734          * to process, or we've worked our way back to the top. */
1735         if (o == top_op)
1736             return o->op_next;
1737
1738         /* o is now processed. Next, process any sibling subtrees */
1739
1740         if (OpHAS_SIBLING(o)) {
1741             o = OpSIBLING(o);
1742             continue;
1743         }
1744
1745         /* Done all the subtrees at this level. Go back up a level and
1746          * link the parent in with all its (processed) children.
1747          */
1748
1749         o = o->op_sibparent;
1750         assert(!o->op_next);
1751         prevp = &(o->op_next);
1752         kid   = (o->op_flags & OPf_KIDS) ? cUNOPo->op_first : NULL;
1753         while (kid) {
1754             *prevp = kid->op_next;
1755             prevp = &(kid->op_next);
1756             kid = OpSIBLING(kid);
1757         }
1758         *prevp = o;
1759     }
1760 }
1761
1762
1763 static OP *
1764 S_scalarkids(pTHX_ OP *o)
1765 {
1766     if (o && o->op_flags & OPf_KIDS) {
1767         OP *kid;
1768         for (kid = cLISTOPo->op_first; kid; kid = OpSIBLING(kid))
1769             scalar(kid);
1770     }
1771     return o;
1772 }
1773
1774 STATIC OP *
1775 S_scalarboolean(pTHX_ OP *o)
1776 {
1777     PERL_ARGS_ASSERT_SCALARBOOLEAN;
1778
1779     if ((o->op_type == OP_SASSIGN && cBINOPo->op_first->op_type == OP_CONST &&
1780          !(cBINOPo->op_first->op_flags & OPf_SPECIAL)) ||
1781         (o->op_type == OP_NOT     && cUNOPo->op_first->op_type == OP_SASSIGN &&
1782          cBINOPx(cUNOPo->op_first)->op_first->op_type == OP_CONST &&
1783          !(cBINOPx(cUNOPo->op_first)->op_first->op_flags & OPf_SPECIAL))) {
1784         if (ckWARN(WARN_SYNTAX)) {
1785             const line_t oldline = CopLINE(PL_curcop);
1786
1787             if (PL_parser && PL_parser->copline != NOLINE) {
1788                 /* This ensures that warnings are reported at the first line
1789                    of the conditional, not the last.  */
1790                 CopLINE_set(PL_curcop, PL_parser->copline);
1791             }
1792             Perl_warner(aTHX_ packWARN(WARN_SYNTAX), "Found = in conditional, should be ==");
1793             CopLINE_set(PL_curcop, oldline);
1794         }
1795     }
1796     return scalar(o);
1797 }
1798
1799 static SV *
1800 S_op_varname_subscript(pTHX_ const OP *o, int subscript_type)
1801 {
1802     assert(o);
1803     assert(o->op_type == OP_PADAV || o->op_type == OP_RV2AV ||
1804            o->op_type == OP_PADHV || o->op_type == OP_RV2HV);
1805     {
1806         const char funny  = o->op_type == OP_PADAV
1807                          || o->op_type == OP_RV2AV ? '@' : '%';
1808         if (o->op_type == OP_RV2AV || o->op_type == OP_RV2HV) {
1809             GV *gv;
1810             if (cUNOPo->op_first->op_type != OP_GV
1811              || !(gv = cGVOPx_gv(cUNOPo->op_first)))
1812                 return NULL;
1813             return varname(gv, funny, 0, NULL, 0, subscript_type);
1814         }
1815         return
1816             varname(MUTABLE_GV(PL_compcv), funny, o->op_targ, NULL, 0, subscript_type);
1817     }
1818 }
1819
1820 static SV *
1821 S_op_varname(pTHX_ const OP *o)
1822 {
1823     return S_op_varname_subscript(aTHX_ o, 1);
1824 }
1825
1826 static void
1827 S_op_pretty(pTHX_ const OP *o, SV **retsv, const char **retpv)
1828 { /* or not so pretty :-) */
1829     if (o->op_type == OP_CONST) {
1830         *retsv = cSVOPo_sv;
1831         if (SvPOK(*retsv)) {
1832             SV *sv = *retsv;
1833             *retsv = sv_newmortal();
1834             pv_pretty(*retsv, SvPVX_const(sv), SvCUR(sv), 32, NULL, NULL,
1835                       PERL_PV_PRETTY_DUMP |PERL_PV_ESCAPE_UNI_DETECT);
1836         }
1837         else if (!SvOK(*retsv))
1838             *retpv = "undef";
1839     }
1840     else *retpv = "...";
1841 }
1842
1843 static void
1844 S_scalar_slice_warning(pTHX_ const OP *o)
1845 {
1846     OP *kid;
1847     const bool h = o->op_type == OP_HSLICE
1848                 || (o->op_type == OP_NULL && o->op_targ == OP_HSLICE);
1849     const char lbrack =
1850         h ? '{' : '[';
1851     const char rbrack =
1852         h ? '}' : ']';
1853     SV *name;
1854     SV *keysv = NULL; /* just to silence compiler warnings */
1855     const char *key = NULL;
1856
1857     if (!(o->op_private & OPpSLICEWARNING))
1858         return;
1859     if (PL_parser && PL_parser->error_count)
1860         /* This warning can be nonsensical when there is a syntax error. */
1861         return;
1862
1863     kid = cLISTOPo->op_first;
1864     kid = OpSIBLING(kid); /* get past pushmark */
1865     /* weed out false positives: any ops that can return lists */
1866     switch (kid->op_type) {
1867     case OP_BACKTICK:
1868     case OP_GLOB:
1869     case OP_READLINE:
1870     case OP_MATCH:
1871     case OP_RV2AV:
1872     case OP_EACH:
1873     case OP_VALUES:
1874     case OP_KEYS:
1875     case OP_SPLIT:
1876     case OP_LIST:
1877     case OP_SORT:
1878     case OP_REVERSE:
1879     case OP_ENTERSUB:
1880     case OP_CALLER:
1881     case OP_LSTAT:
1882     case OP_STAT:
1883     case OP_READDIR:
1884     case OP_SYSTEM:
1885     case OP_TMS:
1886     case OP_LOCALTIME:
1887     case OP_GMTIME:
1888     case OP_ENTEREVAL:
1889         return;
1890     }
1891
1892     /* Don't warn if we have a nulled list either. */
1893     if (kid->op_type == OP_NULL && kid->op_targ == OP_LIST)
1894         return;
1895
1896     assert(OpSIBLING(kid));
1897     name = S_op_varname(aTHX_ OpSIBLING(kid));
1898     if (!name) /* XS module fiddling with the op tree */
1899         return;
1900     S_op_pretty(aTHX_ kid, &keysv, &key);
1901     assert(SvPOK(name));
1902     sv_chop(name,SvPVX(name)+1);
1903     if (key)
1904        /* diag_listed_as: Scalar value @%s[%s] better written as $%s[%s] */
1905         Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
1906                    "Scalar value @%" SVf "%c%s%c better written as $%" SVf
1907                    "%c%s%c",
1908                     SVfARG(name), lbrack, key, rbrack, SVfARG(name),
1909                     lbrack, key, rbrack);
1910     else
1911        /* diag_listed_as: Scalar value @%s[%s] better written as $%s[%s] */
1912         Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
1913                    "Scalar value @%" SVf "%c%" SVf "%c better written as $%"
1914                     SVf "%c%" SVf "%c",
1915                     SVfARG(name), lbrack, SVfARG(keysv), rbrack,
1916                     SVfARG(name), lbrack, SVfARG(keysv), rbrack);
1917 }
1918
1919
1920
1921 /* apply scalar context to the o subtree */
1922
1923 OP *
1924 Perl_scalar(pTHX_ OP *o)
1925 {
1926     OP * top_op = o;
1927
1928     while (1) {
1929         OP *next_kid = NULL; /* what op (if any) to process next */
1930         OP *kid;
1931
1932         /* assumes no premature commitment */
1933         if (!o || (PL_parser && PL_parser->error_count)
1934              || (o->op_flags & OPf_WANT)
1935              || o->op_type == OP_RETURN)
1936         {
1937             goto do_next;
1938         }
1939
1940         o->op_flags = (o->op_flags & ~OPf_WANT) | OPf_WANT_SCALAR;
1941
1942         switch (o->op_type) {
1943         case OP_REPEAT:
1944             scalar(cBINOPo->op_first);
1945             /* convert what initially looked like a list repeat into a
1946              * scalar repeat, e.g. $s = (1) x $n
1947              */
1948             if (o->op_private & OPpREPEAT_DOLIST) {
1949                 kid = cLISTOPx(cUNOPo->op_first)->op_first;
1950                 assert(kid->op_type == OP_PUSHMARK);
1951                 if (OpHAS_SIBLING(kid) && !OpHAS_SIBLING(OpSIBLING(kid))) {
1952                     op_null(cLISTOPx(cUNOPo->op_first)->op_first);
1953                     o->op_private &=~ OPpREPEAT_DOLIST;
1954                 }
1955             }
1956             break;
1957
1958         case OP_OR:
1959         case OP_AND:
1960         case OP_COND_EXPR:
1961             /* impose scalar context on everything except the condition */
1962             next_kid = OpSIBLING(cUNOPo->op_first);
1963             break;
1964
1965         default:
1966             if (o->op_flags & OPf_KIDS)
1967                 next_kid = cUNOPo->op_first; /* do all kids */
1968             break;
1969
1970         /* the children of these ops are usually a list of statements,
1971          * except the leaves, whose first child is a corresponding enter
1972          */
1973         case OP_SCOPE:
1974         case OP_LINESEQ:
1975         case OP_LIST:
1976             kid = cLISTOPo->op_first;
1977             goto do_kids;
1978         case OP_LEAVE:
1979         case OP_LEAVETRY:
1980             kid = cLISTOPo->op_first;
1981             scalar(kid);
1982             kid = OpSIBLING(kid);
1983         do_kids:
1984             while (kid) {
1985                 OP *sib = OpSIBLING(kid);
1986                 /* Apply void context to all kids except the last, which
1987                  * is scalar (ignoring a trailing ex-nextstate in determining
1988                  * if it's the last kid). E.g.
1989                  *      $scalar = do { void; void; scalar }
1990                  * Except that 'when's are always scalar, e.g.
1991                  *      $scalar = do { given(..) {
1992                     *                 when (..) { scalar }
1993                     *                 when (..) { scalar }
1994                     *                 ...
1995                     *                }}
1996                     */
1997                 if (!sib
1998                      || (  !OpHAS_SIBLING(sib)
1999                          && sib->op_type == OP_NULL
2000                          && (   sib->op_targ == OP_NEXTSTATE
2001                              || sib->op_targ == OP_DBSTATE  )
2002                         )
2003                 )
2004                 {
2005                     /* tail call optimise calling scalar() on the last kid */
2006                     next_kid = kid;
2007                     goto do_next;
2008                 }
2009                 else if (kid->op_type == OP_LEAVEWHEN)
2010                     scalar(kid);
2011                 else
2012                     scalarvoid(kid);
2013                 kid = sib;
2014             }
2015             NOT_REACHED; /* NOTREACHED */
2016             break;
2017
2018         case OP_SORT:
2019             Perl_ck_warner(aTHX_ packWARN(WARN_VOID), "Useless use of sort in scalar context");
2020             break;
2021
2022         case OP_KVHSLICE:
2023         case OP_KVASLICE:
2024         {
2025             /* Warn about scalar context */
2026             const char lbrack = o->op_type == OP_KVHSLICE ? '{' : '[';
2027             const char rbrack = o->op_type == OP_KVHSLICE ? '}' : ']';
2028             SV *name;
2029             SV *keysv;
2030             const char *key = NULL;
2031
2032             /* This warning can be nonsensical when there is a syntax error. */
2033             if (PL_parser && PL_parser->error_count)
2034                 break;
2035
2036             if (!ckWARN(WARN_SYNTAX)) break;
2037
2038             kid = cLISTOPo->op_first;
2039             kid = OpSIBLING(kid); /* get past pushmark */
2040             assert(OpSIBLING(kid));
2041             name = S_op_varname(aTHX_ OpSIBLING(kid));
2042             if (!name) /* XS module fiddling with the op tree */
2043                 break;
2044             S_op_pretty(aTHX_ kid, &keysv, &key);
2045             assert(SvPOK(name));
2046             sv_chop(name,SvPVX(name)+1);
2047             if (key)
2048       /* diag_listed_as: %%s[%s] in scalar context better written as $%s[%s] */
2049                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
2050                            "%%%" SVf "%c%s%c in scalar context better written "
2051                            "as $%" SVf "%c%s%c",
2052                             SVfARG(name), lbrack, key, rbrack, SVfARG(name),
2053                             lbrack, key, rbrack);
2054             else
2055       /* diag_listed_as: %%s[%s] in scalar context better written as $%s[%s] */
2056                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
2057                            "%%%" SVf "%c%" SVf "%c in scalar context better "
2058                            "written as $%" SVf "%c%" SVf "%c",
2059                             SVfARG(name), lbrack, SVfARG(keysv), rbrack,
2060                             SVfARG(name), lbrack, SVfARG(keysv), rbrack);
2061         }
2062         } /* switch */
2063
2064         /* If next_kid is set, someone in the code above wanted us to process
2065          * that kid and all its remaining siblings.  Otherwise, work our way
2066          * back up the tree */
2067       do_next:
2068         while (!next_kid) {
2069             if (o == top_op)
2070                 return top_op; /* at top; no parents/siblings to try */
2071             if (OpHAS_SIBLING(o))
2072                 next_kid = o->op_sibparent;
2073             else {
2074                 o = o->op_sibparent; /*try parent's next sibling */
2075                 switch (o->op_type) {
2076                 case OP_SCOPE:
2077                 case OP_LINESEQ:
2078                 case OP_LIST:
2079                 case OP_LEAVE:
2080                 case OP_LEAVETRY:
2081                     /* should really restore PL_curcop to its old value, but
2082                      * setting it to PL_compiling is better than do nothing */
2083                     PL_curcop = &PL_compiling;
2084                 }
2085             }
2086         }
2087         o = next_kid;
2088     } /* while */
2089 }
2090
2091
2092 /* apply void context to the optree arg */
2093
2094 OP *
2095 Perl_scalarvoid(pTHX_ OP *arg)
2096 {
2097     OP *kid;
2098     SV* sv;
2099     OP *o = arg;
2100
2101     PERL_ARGS_ASSERT_SCALARVOID;
2102
2103     while (1) {
2104         U8 want;
2105         SV *useless_sv = NULL;
2106         const char* useless = NULL;
2107         OP * next_kid = NULL;
2108
2109         if (o->op_type == OP_NEXTSTATE
2110             || o->op_type == OP_DBSTATE
2111             || (o->op_type == OP_NULL && (o->op_targ == OP_NEXTSTATE
2112                                           || o->op_targ == OP_DBSTATE)))
2113             PL_curcop = (COP*)o;                /* for warning below */
2114
2115         /* assumes no premature commitment */
2116         want = o->op_flags & OPf_WANT;
2117         if ((want && want != OPf_WANT_SCALAR)
2118             || (PL_parser && PL_parser->error_count)
2119             || o->op_type == OP_RETURN || o->op_type == OP_REQUIRE || o->op_type == OP_LEAVEWHEN)
2120         {
2121             goto get_next_op;
2122         }
2123
2124         if ((o->op_private & OPpTARGET_MY)
2125             && (PL_opargs[o->op_type] & OA_TARGLEX))/* OPp share the meaning */
2126         {
2127             /* newASSIGNOP has already applied scalar context, which we
2128                leave, as if this op is inside SASSIGN.  */
2129             goto get_next_op;
2130         }
2131
2132         o->op_flags = (o->op_flags & ~OPf_WANT) | OPf_WANT_VOID;
2133
2134         switch (o->op_type) {
2135         default:
2136             if (!(PL_opargs[o->op_type] & OA_FOLDCONST))
2137                 break;
2138             /* FALLTHROUGH */
2139         case OP_REPEAT:
2140             if (o->op_flags & OPf_STACKED)
2141                 break;
2142             if (o->op_type == OP_REPEAT)
2143                 scalar(cBINOPo->op_first);
2144             goto func_ops;
2145         case OP_CONCAT:
2146             if ((o->op_flags & OPf_STACKED) &&
2147                     !(o->op_private & OPpCONCAT_NESTED))
2148                 break;
2149             goto func_ops;
2150         case OP_SUBSTR:
2151             if (o->op_private == 4)
2152                 break;
2153             /* FALLTHROUGH */
2154         case OP_WANTARRAY:
2155         case OP_GV:
2156         case OP_SMARTMATCH:
2157         case OP_AV2ARYLEN:
2158         case OP_REF:
2159         case OP_REFGEN:
2160         case OP_SREFGEN:
2161         case OP_DEFINED:
2162         case OP_HEX:
2163         case OP_OCT:
2164         case OP_LENGTH:
2165         case OP_VEC:
2166         case OP_INDEX:
2167         case OP_RINDEX:
2168         case OP_SPRINTF:
2169         case OP_KVASLICE:
2170         case OP_KVHSLICE:
2171         case OP_UNPACK:
2172         case OP_PACK:
2173         case OP_JOIN:
2174         case OP_LSLICE:
2175         case OP_ANONLIST:
2176         case OP_ANONHASH:
2177         case OP_SORT:
2178         case OP_REVERSE:
2179         case OP_RANGE:
2180         case OP_FLIP:
2181         case OP_FLOP:
2182         case OP_CALLER:
2183         case OP_FILENO:
2184         case OP_EOF:
2185         case OP_TELL:
2186         case OP_GETSOCKNAME:
2187         case OP_GETPEERNAME:
2188         case OP_READLINK:
2189         case OP_TELLDIR:
2190         case OP_GETPPID:
2191         case OP_GETPGRP:
2192         case OP_GETPRIORITY:
2193         case OP_TIME:
2194         case OP_TMS:
2195         case OP_LOCALTIME:
2196         case OP_GMTIME:
2197         case OP_GHBYNAME:
2198         case OP_GHBYADDR:
2199         case OP_GHOSTENT:
2200         case OP_GNBYNAME:
2201         case OP_GNBYADDR:
2202         case OP_GNETENT:
2203         case OP_GPBYNAME:
2204         case OP_GPBYNUMBER:
2205         case OP_GPROTOENT:
2206         case OP_GSBYNAME:
2207         case OP_GSBYPORT:
2208         case OP_GSERVENT:
2209         case OP_GPWNAM:
2210         case OP_GPWUID:
2211         case OP_GGRNAM:
2212         case OP_GGRGID:
2213         case OP_GETLOGIN:
2214         case OP_PROTOTYPE:
2215         case OP_RUNCV:
2216         func_ops:
2217             useless = OP_DESC(o);
2218             break;
2219
2220         case OP_GVSV:
2221         case OP_PADSV:
2222         case OP_PADAV:
2223         case OP_PADHV:
2224         case OP_PADANY:
2225         case OP_AELEM:
2226         case OP_AELEMFAST:
2227         case OP_AELEMFAST_LEX:
2228         case OP_ASLICE:
2229         case OP_HELEM:
2230         case OP_HSLICE:
2231             if (!(o->op_private & (OPpLVAL_INTRO|OPpOUR_INTRO)))
2232                 /* Otherwise it's "Useless use of grep iterator" */
2233                 useless = OP_DESC(o);
2234             break;
2235
2236         case OP_SPLIT:
2237             if (!(o->op_private & OPpSPLIT_ASSIGN))
2238                 useless = OP_DESC(o);
2239             break;
2240
2241         case OP_NOT:
2242             kid = cUNOPo->op_first;
2243             if (kid->op_type != OP_MATCH && kid->op_type != OP_SUBST &&
2244                 kid->op_type != OP_TRANS && kid->op_type != OP_TRANSR) {
2245                 goto func_ops;
2246             }
2247             useless = "negative pattern binding (!~)";
2248             break;
2249
2250         case OP_SUBST:
2251             if (cPMOPo->op_pmflags & PMf_NONDESTRUCT)
2252                 useless = "non-destructive substitution (s///r)";
2253             break;
2254
2255         case OP_TRANSR:
2256             useless = "non-destructive transliteration (tr///r)";
2257             break;
2258
2259         case OP_RV2GV:
2260         case OP_RV2SV:
2261         case OP_RV2AV:
2262         case OP_RV2HV:
2263             if (!(o->op_private & (OPpLVAL_INTRO|OPpOUR_INTRO)) &&
2264                 (!OpHAS_SIBLING(o) || OpSIBLING(o)->op_type != OP_READLINE))
2265                 useless = "a variable";
2266             break;
2267
2268         case OP_CONST:
2269             sv = cSVOPo_sv;
2270             if (cSVOPo->op_private & OPpCONST_STRICT)
2271                 no_bareword_allowed(o);
2272             else {
2273                 if (ckWARN(WARN_VOID)) {
2274                     NV nv;
2275                     /* don't warn on optimised away booleans, eg
2276                      * use constant Foo, 5; Foo || print; */
2277                     if (cSVOPo->op_private & OPpCONST_SHORTCIRCUIT)
2278                         useless = NULL;
2279                     /* the constants 0 and 1 are permitted as they are
2280                        conventionally used as dummies in constructs like
2281                        1 while some_condition_with_side_effects;  */
2282                     else if (SvNIOK(sv) && ((nv = SvNV(sv)) == 0.0 || nv == 1.0))
2283                         useless = NULL;
2284                     else if (SvPOK(sv)) {
2285                         SV * const dsv = newSVpvs("");
2286                         useless_sv
2287                             = Perl_newSVpvf(aTHX_
2288                                             "a constant (%s)",
2289                                             pv_pretty(dsv, SvPVX_const(sv),
2290                                                       SvCUR(sv), 32, NULL, NULL,
2291                                                       PERL_PV_PRETTY_DUMP
2292                                                       | PERL_PV_ESCAPE_NOCLEAR
2293                                                       | PERL_PV_ESCAPE_UNI_DETECT));
2294                         SvREFCNT_dec_NN(dsv);
2295                     }
2296                     else if (SvOK(sv)) {
2297                         useless_sv = Perl_newSVpvf(aTHX_ "a constant (%" SVf ")", SVfARG(sv));
2298                     }
2299                     else
2300                         useless = "a constant (undef)";
2301                 }
2302             }
2303             op_null(o);         /* don't execute or even remember it */
2304             break;
2305
2306         case OP_POSTINC:
2307             OpTYPE_set(o, OP_PREINC);  /* pre-increment is faster */
2308             break;
2309
2310         case OP_POSTDEC:
2311             OpTYPE_set(o, OP_PREDEC);  /* pre-decrement is faster */
2312             break;
2313
2314         case OP_I_POSTINC:
2315             OpTYPE_set(o, OP_I_PREINC);        /* pre-increment is faster */
2316             break;
2317
2318         case OP_I_POSTDEC:
2319             OpTYPE_set(o, OP_I_PREDEC);        /* pre-decrement is faster */
2320             break;
2321
2322         case OP_SASSIGN: {
2323             OP *rv2gv;
2324             UNOP *refgen, *rv2cv;
2325             LISTOP *exlist;
2326
2327             if ((o->op_private & ~OPpASSIGN_BACKWARDS) != 2)
2328                 break;
2329
2330             rv2gv = ((BINOP *)o)->op_last;
2331             if (!rv2gv || rv2gv->op_type != OP_RV2GV)
2332                 break;
2333
2334             refgen = (UNOP *)((BINOP *)o)->op_first;
2335
2336             if (!refgen || (refgen->op_type != OP_REFGEN
2337                             && refgen->op_type != OP_SREFGEN))
2338                 break;
2339
2340             exlist = (LISTOP *)refgen->op_first;
2341             if (!exlist || exlist->op_type != OP_NULL
2342                 || exlist->op_targ != OP_LIST)
2343                 break;
2344
2345             if (exlist->op_first->op_type != OP_PUSHMARK
2346                 && exlist->op_first != exlist->op_last)
2347                 break;
2348
2349             rv2cv = (UNOP*)exlist->op_last;
2350
2351             if (rv2cv->op_type != OP_RV2CV)
2352                 break;
2353
2354             assert ((rv2gv->op_private & OPpDONT_INIT_GV) == 0);
2355             assert ((o->op_private & OPpASSIGN_CV_TO_GV) == 0);
2356             assert ((rv2cv->op_private & OPpMAY_RETURN_CONSTANT) == 0);
2357
2358             o->op_private |= OPpASSIGN_CV_TO_GV;
2359             rv2gv->op_private |= OPpDONT_INIT_GV;
2360             rv2cv->op_private |= OPpMAY_RETURN_CONSTANT;
2361
2362             break;
2363         }
2364
2365         case OP_AASSIGN: {
2366             inplace_aassign(o);
2367             break;
2368         }
2369
2370         case OP_OR:
2371         case OP_AND:
2372             kid = cLOGOPo->op_first;
2373             if (kid->op_type == OP_NOT
2374                 && (kid->op_flags & OPf_KIDS)) {
2375                 if (o->op_type == OP_AND) {
2376                     OpTYPE_set(o, OP_OR);
2377                 } else {
2378                     OpTYPE_set(o, OP_AND);
2379                 }
2380                 op_null(kid);
2381             }
2382             /* FALLTHROUGH */
2383
2384         case OP_DOR:
2385         case OP_COND_EXPR:
2386         case OP_ENTERGIVEN:
2387         case OP_ENTERWHEN:
2388             next_kid = OpSIBLING(cUNOPo->op_first);
2389         break;
2390
2391         case OP_NULL:
2392             if (o->op_flags & OPf_STACKED)
2393                 break;
2394             /* FALLTHROUGH */
2395         case OP_NEXTSTATE:
2396         case OP_DBSTATE:
2397         case OP_ENTERTRY:
2398         case OP_ENTER:
2399             if (!(o->op_flags & OPf_KIDS))
2400                 break;
2401             /* FALLTHROUGH */
2402         case OP_SCOPE:
2403         case OP_LEAVE:
2404         case OP_LEAVETRY:
2405         case OP_LEAVELOOP:
2406         case OP_LINESEQ:
2407         case OP_LEAVEGIVEN:
2408         case OP_LEAVEWHEN:
2409         kids:
2410             next_kid = cLISTOPo->op_first;
2411             break;
2412         case OP_LIST:
2413             /* If the first kid after pushmark is something that the padrange
2414                optimisation would reject, then null the list and the pushmark.
2415             */
2416             if ((kid = cLISTOPo->op_first)->op_type == OP_PUSHMARK
2417                 && (  !(kid = OpSIBLING(kid))
2418                       || (  kid->op_type != OP_PADSV
2419                             && kid->op_type != OP_PADAV
2420                             && kid->op_type != OP_PADHV)
2421                       || kid->op_private & ~OPpLVAL_INTRO
2422                       || !(kid = OpSIBLING(kid))
2423                       || (  kid->op_type != OP_PADSV
2424                             && kid->op_type != OP_PADAV
2425                             && kid->op_type != OP_PADHV)
2426                       || kid->op_private & ~OPpLVAL_INTRO)
2427             ) {
2428                 op_null(cUNOPo->op_first); /* NULL the pushmark */
2429                 op_null(o); /* NULL the list */
2430             }
2431             goto kids;
2432         case OP_ENTEREVAL:
2433             scalarkids(o);
2434             break;
2435         case OP_SCALAR:
2436             scalar(o);
2437             break;
2438         }
2439
2440         if (useless_sv) {
2441             /* mortalise it, in case warnings are fatal.  */
2442             Perl_ck_warner(aTHX_ packWARN(WARN_VOID),
2443                            "Useless use of %" SVf " in void context",
2444                            SVfARG(sv_2mortal(useless_sv)));
2445         }
2446         else if (useless) {
2447             Perl_ck_warner(aTHX_ packWARN(WARN_VOID),
2448                            "Useless use of %s in void context",
2449                            useless);
2450         }
2451
2452       get_next_op:
2453         /* if a kid hasn't been nominated to process, continue with the
2454          * next sibling, or if no siblings left, go back to the parent's
2455          * siblings and so on
2456          */
2457         while (!next_kid) {
2458             if (o == arg)
2459                 return arg; /* at top; no parents/siblings to try */
2460             if (OpHAS_SIBLING(o))
2461                 next_kid = o->op_sibparent;
2462             else
2463                 o = o->op_sibparent; /*try parent's next sibling */
2464         }
2465         o = next_kid;
2466     }
2467
2468     return arg;
2469 }
2470
2471
2472 static OP *
2473 S_listkids(pTHX_ OP *o)
2474 {
2475     if (o && o->op_flags & OPf_KIDS) {
2476         OP *kid;
2477         for (kid = cLISTOPo->op_first; kid; kid = OpSIBLING(kid))
2478             list(kid);
2479     }
2480     return o;
2481 }
2482
2483
2484 /* apply list context to the o subtree */
2485
2486 OP *
2487 Perl_list(pTHX_ OP *o)
2488 {
2489     OP * top_op = o;
2490
2491     while (1) {
2492         OP *next_kid = NULL; /* what op (if any) to process next */
2493
2494         OP *kid;
2495
2496         /* assumes no premature commitment */
2497         if (!o || (o->op_flags & OPf_WANT)
2498              || (PL_parser && PL_parser->error_count)
2499              || o->op_type == OP_RETURN)
2500         {
2501             goto do_next;
2502         }
2503
2504         if ((o->op_private & OPpTARGET_MY)
2505             && (PL_opargs[o->op_type] & OA_TARGLEX))/* OPp share the meaning */
2506         {
2507             goto do_next;                               /* As if inside SASSIGN */
2508         }
2509
2510         o->op_flags = (o->op_flags & ~OPf_WANT) | OPf_WANT_LIST;
2511
2512         switch (o->op_type) {
2513         case OP_REPEAT:
2514             if (o->op_private & OPpREPEAT_DOLIST
2515              && !(o->op_flags & OPf_STACKED))
2516             {
2517                 list(cBINOPo->op_first);
2518                 kid = cBINOPo->op_last;
2519                 /* optimise away (.....) x 1 */
2520                 if (kid->op_type == OP_CONST && SvIOK(kSVOP_sv)
2521                  && SvIVX(kSVOP_sv) == 1)
2522                 {
2523                     op_null(o); /* repeat */
2524                     op_null(cUNOPx(cBINOPo->op_first)->op_first);/* pushmark */
2525                     /* const (rhs): */
2526                     op_free(op_sibling_splice(o, cBINOPo->op_first, 1, NULL));
2527                 }
2528             }
2529             break;
2530
2531         case OP_OR:
2532         case OP_AND:
2533         case OP_COND_EXPR:
2534             /* impose list context on everything except the condition */
2535             next_kid = OpSIBLING(cUNOPo->op_first);
2536             break;
2537
2538         default:
2539             if (!(o->op_flags & OPf_KIDS))
2540                 break;
2541             /* possibly flatten 1..10 into a constant array */
2542             if (!o->op_next && cUNOPo->op_first->op_type == OP_FLOP) {
2543                 list(cBINOPo->op_first);
2544                 gen_constant_list(o);
2545                 goto do_next;
2546             }
2547             next_kid = cUNOPo->op_first; /* do all kids */
2548             break;
2549
2550         case OP_LIST:
2551             if (cLISTOPo->op_first->op_type == OP_PUSHMARK) {
2552                 op_null(cUNOPo->op_first); /* NULL the pushmark */
2553                 op_null(o); /* NULL the list */
2554             }
2555             if (o->op_flags & OPf_KIDS)
2556                 next_kid = cUNOPo->op_first; /* do all kids */
2557             break;
2558
2559         /* the children of these ops are usually a list of statements,
2560          * except the leaves, whose first child is a corresponding enter
2561          */
2562         case OP_SCOPE:
2563         case OP_LINESEQ:
2564             kid = cLISTOPo->op_first;
2565             goto do_kids;
2566         case OP_LEAVE:
2567         case OP_LEAVETRY:
2568             kid = cLISTOPo->op_first;
2569             list(kid);
2570             kid = OpSIBLING(kid);
2571         do_kids:
2572             while (kid) {
2573                 OP *sib = OpSIBLING(kid);
2574                 /* Apply void context to all kids except the last, which
2575                  * is list. E.g.
2576                  *      @a = do { void; void; list }
2577                  * Except that 'when's are always list context, e.g.
2578                  *      @a = do { given(..) {
2579                     *                 when (..) { list }
2580                     *                 when (..) { list }
2581                     *                 ...
2582                     *                }}
2583                     */
2584                 if (!sib) {
2585                     /* tail call optimise calling list() on the last kid */
2586                     next_kid = kid;
2587                     goto do_next;
2588                 }
2589                 else if (kid->op_type == OP_LEAVEWHEN)
2590                     list(kid);
2591                 else
2592                     scalarvoid(kid);
2593                 kid = sib;
2594             }
2595             NOT_REACHED; /* NOTREACHED */
2596             break;
2597
2598         }
2599
2600         /* If next_kid is set, someone in the code above wanted us to process
2601          * that kid and all its remaining siblings.  Otherwise, work our way
2602          * back up the tree */
2603       do_next:
2604         while (!next_kid) {
2605             if (o == top_op)
2606                 return top_op; /* at top; no parents/siblings to try */
2607             if (OpHAS_SIBLING(o))
2608                 next_kid = o->op_sibparent;
2609             else {
2610                 o = o->op_sibparent; /*try parent's next sibling */
2611                 switch (o->op_type) {
2612                 case OP_SCOPE:
2613                 case OP_LINESEQ:
2614                 case OP_LIST:
2615                 case OP_LEAVE:
2616                 case OP_LEAVETRY:
2617                     /* should really restore PL_curcop to its old value, but
2618                      * setting it to PL_compiling is better than do nothing */
2619                     PL_curcop = &PL_compiling;
2620                 }
2621             }
2622
2623
2624         }
2625         o = next_kid;
2626     } /* while */
2627 }
2628
2629 /* apply void context to non-final ops of a sequence */
2630
2631 static OP *
2632 S_voidnonfinal(pTHX_ OP *o)
2633 {
2634     if (o) {
2635         const OPCODE type = o->op_type;
2636
2637         if (type == OP_LINESEQ || type == OP_SCOPE ||
2638             type == OP_LEAVE || type == OP_LEAVETRY)
2639         {
2640             OP *kid = cLISTOPo->op_first, *sib;
2641             if(type == OP_LEAVE) {
2642                 /* Don't put the OP_ENTER in void context */
2643                 assert(kid->op_type == OP_ENTER);
2644                 kid = OpSIBLING(kid);
2645             }
2646             for (; kid; kid = sib) {
2647                 if ((sib = OpSIBLING(kid))
2648                  && (  OpHAS_SIBLING(sib) || sib->op_type != OP_NULL
2649                     || (  sib->op_targ != OP_NEXTSTATE
2650                        && sib->op_targ != OP_DBSTATE  )))
2651                 {
2652                     scalarvoid(kid);
2653                 }
2654             }
2655             PL_curcop = &PL_compiling;
2656         }
2657         o->op_flags &= ~OPf_PARENS;
2658         if (PL_hints & HINT_BLOCK_SCOPE)
2659             o->op_flags |= OPf_PARENS;
2660     }
2661     else
2662         o = newOP(OP_STUB, 0);
2663     return o;
2664 }
2665
2666 STATIC OP *
2667 S_modkids(pTHX_ OP *o, I32 type)
2668 {
2669     if (o && o->op_flags & OPf_KIDS) {
2670         OP *kid;
2671         for (kid = cLISTOPo->op_first; kid; kid = OpSIBLING(kid))
2672             op_lvalue(kid, type);
2673     }
2674     return o;
2675 }
2676
2677
2678 /* for a helem/hslice/kvslice, if its a fixed hash, croak on invalid
2679  * const fields. Also, convert CONST keys to HEK-in-SVs.
2680  * rop    is the op that retrieves the hash;
2681  * key_op is the first key
2682  * real   if false, only check (and possibly croak); don't update op
2683  */
2684
2685 STATIC void
2686 S_check_hash_fields_and_hekify(pTHX_ UNOP *rop, SVOP *key_op, int real)
2687 {
2688     PADNAME *lexname;
2689     GV **fields;
2690     bool check_fields;
2691
2692     /* find the padsv corresponding to $lex->{} or @{$lex}{} */
2693     if (rop) {
2694         if (rop->op_first->op_type == OP_PADSV)
2695             /* @$hash{qw(keys here)} */
2696             rop = (UNOP*)rop->op_first;
2697         else {
2698             /* @{$hash}{qw(keys here)} */
2699             if (rop->op_first->op_type == OP_SCOPE
2700                 && cLISTOPx(rop->op_first)->op_last->op_type == OP_PADSV)
2701                 {
2702                     rop = (UNOP*)cLISTOPx(rop->op_first)->op_last;
2703                 }
2704             else
2705                 rop = NULL;
2706         }
2707     }
2708
2709     lexname = NULL; /* just to silence compiler warnings */
2710     fields  = NULL; /* just to silence compiler warnings */
2711
2712     check_fields =
2713             rop
2714          && (lexname = padnamelist_fetch(PL_comppad_name, rop->op_targ),
2715              SvPAD_TYPED(lexname))
2716          && (fields = (GV**)hv_fetchs(PadnameTYPE(lexname), "FIELDS", FALSE))
2717          && isGV(*fields) && GvHV(*fields);
2718
2719     for (; key_op; key_op = (SVOP*)OpSIBLING(key_op)) {
2720         SV **svp, *sv;
2721         if (key_op->op_type != OP_CONST)
2722             continue;
2723         svp = cSVOPx_svp(key_op);
2724
2725         /* make sure it's not a bareword under strict subs */
2726         if (key_op->op_private & OPpCONST_BARE &&
2727             key_op->op_private & OPpCONST_STRICT)
2728         {
2729             no_bareword_allowed((OP*)key_op);
2730         }
2731
2732         /* Make the CONST have a shared SV */
2733         if (   !SvIsCOW_shared_hash(sv = *svp)
2734             && SvTYPE(sv) < SVt_PVMG
2735             && SvOK(sv)
2736             && !SvROK(sv)
2737             && real)
2738         {
2739             SSize_t keylen;
2740             const char * const key = SvPV_const(sv, *(STRLEN*)&keylen);
2741             SV *nsv = newSVpvn_share(key, SvUTF8(sv) ? -keylen : keylen, 0);
2742             SvREFCNT_dec_NN(sv);
2743             *svp = nsv;
2744         }
2745
2746         if (   check_fields
2747             && !hv_fetch_ent(GvHV(*fields), *svp, FALSE, 0))
2748         {
2749             Perl_croak(aTHX_ "No such class field \"%" SVf "\" "
2750                         "in variable %" PNf " of type %" HEKf,
2751                         SVfARG(*svp), PNfARG(lexname),
2752                         HEKfARG(HvNAME_HEK(PadnameTYPE(lexname))));
2753         }
2754     }
2755 }
2756
2757 /* info returned by S_sprintf_is_multiconcatable() */
2758
2759 struct sprintf_ismc_info {
2760     SSize_t nargs;    /* num of args to sprintf (not including the format) */
2761     char  *start;     /* start of raw format string */
2762     char  *end;       /* bytes after end of raw format string */
2763     STRLEN total_len; /* total length (in bytes) of format string, not
2764                          including '%s' and  half of '%%' */
2765     STRLEN variant;   /* number of bytes by which total_len_p would grow
2766                          if upgraded to utf8 */
2767     bool   utf8;      /* whether the format is utf8 */
2768 };
2769
2770
2771 /* is the OP_SPRINTF o suitable for converting into a multiconcat op?
2772  * i.e. its format argument is a const string with only '%s' and '%%'
2773  * formats, and the number of args is known, e.g.
2774  *    sprintf "a=%s f=%s", $a[0], scalar(f());
2775  * but not
2776  *    sprintf "i=%d a=%s f=%s", $i, @a, f();
2777  *
2778  * If successful, the sprintf_ismc_info struct pointed to by info will be
2779  * populated.
2780  */
2781
2782 STATIC bool
2783 S_sprintf_is_multiconcatable(pTHX_ OP *o,struct sprintf_ismc_info *info)
2784 {
2785     OP    *pm, *constop, *kid;
2786     SV    *sv;
2787     char  *s, *e, *p;
2788     SSize_t nargs, nformats;
2789     STRLEN cur, total_len, variant;
2790     bool   utf8;
2791
2792     /* if sprintf's behaviour changes, die here so that someone
2793      * can decide whether to enhance this function or skip optimising
2794      * under those new circumstances */
2795     assert(!(o->op_flags & OPf_STACKED));
2796     assert(!(PL_opargs[OP_SPRINTF] & OA_TARGLEX));
2797     assert(!(o->op_private & ~OPpARG4_MASK));
2798
2799     pm = cUNOPo->op_first;
2800     if (pm->op_type != OP_PUSHMARK) /* weird coreargs stuff */
2801         return FALSE;
2802     constop = OpSIBLING(pm);
2803     if (!constop || constop->op_type != OP_CONST)
2804         return FALSE;
2805     sv = cSVOPx_sv(constop);
2806     if (SvMAGICAL(sv) || !SvPOK(sv))
2807         return FALSE;
2808
2809     s = SvPV(sv, cur);
2810     e = s + cur;
2811
2812     /* Scan format for %% and %s and work out how many %s there are.
2813      * Abandon if other format types are found.
2814      */
2815
2816     nformats  = 0;
2817     total_len = 0;
2818     variant   = 0;
2819
2820     for (p = s; p < e; p++) {
2821         if (*p != '%') {
2822             total_len++;
2823             if (!UTF8_IS_INVARIANT(*p))
2824                 variant++;
2825             continue;
2826         }
2827         p++;
2828         if (p >= e)
2829             return FALSE; /* lone % at end gives "Invalid conversion" */
2830         if (*p == '%')
2831             total_len++;
2832         else if (*p == 's')
2833             nformats++;
2834         else
2835             return FALSE;
2836     }
2837
2838     if (!nformats || nformats > PERL_MULTICONCAT_MAXARG)
2839         return FALSE;
2840
2841     utf8 = cBOOL(SvUTF8(sv));
2842     if (utf8)
2843         variant = 0;
2844
2845     /* scan args; they must all be in scalar cxt */
2846
2847     nargs = 0;
2848     kid = OpSIBLING(constop);
2849
2850     while (kid) {
2851         if ((kid->op_flags & OPf_WANT) != OPf_WANT_SCALAR)
2852             return FALSE;
2853         nargs++;
2854         kid = OpSIBLING(kid);
2855     }
2856
2857     if (nargs != nformats)
2858         return FALSE; /* e.g. sprintf("%s%s", $a); */
2859
2860
2861     info->nargs      = nargs;
2862     info->start      = s;
2863     info->end        = e;
2864     info->total_len  = total_len;
2865     info->variant    = variant;
2866     info->utf8       = utf8;
2867
2868     return TRUE;
2869 }
2870
2871
2872
2873 /* S_maybe_multiconcat():
2874  *
2875  * given an OP_STRINGIFY, OP_SASSIGN, OP_CONCAT or OP_SPRINTF op, possibly
2876  * convert it (and its children) into an OP_MULTICONCAT. See the code
2877  * comments just before pp_multiconcat() for the full details of what
2878  * OP_MULTICONCAT supports.
2879  *
2880  * Basically we're looking for an optree with a chain of OP_CONCATS down
2881  * the LHS (or an OP_SPRINTF), with possibly an OP_SASSIGN, and/or
2882  * OP_STRINGIFY, and/or OP_CONCAT acting as '.=' at its head, e.g.
2883  *
2884  *      $x = "$a$b-$c"
2885  *
2886  *  looks like
2887  *
2888  *      SASSIGN
2889  *         |
2890  *      STRINGIFY   -- PADSV[$x]
2891  *         |
2892  *         |
2893  *      ex-PUSHMARK -- CONCAT/S
2894  *                        |
2895  *                     CONCAT/S  -- PADSV[$d]
2896  *                        |
2897  *                     CONCAT    -- CONST["-"]
2898  *                        |
2899  *                     PADSV[$a] -- PADSV[$b]
2900  *
2901  * Note that at this stage the OP_SASSIGN may have already been optimised
2902  * away with OPpTARGET_MY set on the OP_STRINGIFY or OP_CONCAT.
2903  */
2904
2905 STATIC void
2906 S_maybe_multiconcat(pTHX_ OP *o)
2907 {
2908     OP *lastkidop;   /* the right-most of any kids unshifted onto o */
2909     OP *topop;       /* the top-most op in the concat tree (often equals o,
2910                         unless there are assign/stringify ops above it */
2911     OP *parentop;    /* the parent op of topop (or itself if no parent) */
2912     OP *targmyop;    /* the op (if any) with the OPpTARGET_MY flag */
2913     OP *targetop;    /* the op corresponding to target=... or target.=... */
2914     OP *stringop;    /* the OP_STRINGIFY op, if any */
2915     OP *nextop;      /* used for recreating the op_next chain without consts */
2916     OP *kid;         /* general-purpose op pointer */
2917     UNOP_AUX_item *aux;
2918     UNOP_AUX_item *lenp;
2919     char *const_str, *p;
2920     struct sprintf_ismc_info sprintf_info;
2921
2922                      /* store info about each arg in args[];
2923                       * toparg is the highest used slot; argp is a general
2924                       * pointer to args[] slots */
2925     struct {
2926         void *p;      /* initially points to const sv (or null for op);
2927                          later, set to SvPV(constsv), with ... */
2928         STRLEN len;   /* ... len set to SvPV(..., len) */
2929     } *argp, *toparg, args[PERL_MULTICONCAT_MAXARG*2 + 1];
2930
2931     SSize_t nargs  = 0;
2932     SSize_t nconst = 0;
2933     SSize_t nadjconst  = 0; /* adjacent consts - may be demoted to args */
2934     STRLEN variant;
2935     bool utf8 = FALSE;
2936     bool kid_is_last = FALSE; /* most args will be the RHS kid of a concat op;
2937                                  the last-processed arg will the LHS of one,
2938                                  as args are processed in reverse order */
2939     U8   stacked_last = 0;   /* whether the last seen concat op was STACKED */
2940     STRLEN total_len  = 0;   /* sum of the lengths of the const segments */
2941     U8 flags          = 0;   /* what will become the op_flags and ... */
2942     U8 private_flags  = 0;   /* ... op_private of the multiconcat op */
2943     bool is_sprintf = FALSE; /* we're optimising an sprintf */
2944     bool is_targable  = FALSE; /* targetop is an OPpTARGET_MY candidate */
2945     bool prev_was_const = FALSE; /* previous arg was a const */
2946
2947     /* -----------------------------------------------------------------
2948      * Phase 1:
2949      *
2950      * Examine the optree non-destructively to determine whether it's
2951      * suitable to be converted into an OP_MULTICONCAT. Accumulate
2952      * information about the optree in args[].
2953      */
2954
2955     argp     = args;
2956     targmyop = NULL;
2957     targetop = NULL;
2958     stringop = NULL;
2959     topop    = o;
2960     parentop = o;
2961
2962     assert(   o->op_type == OP_SASSIGN
2963            || o->op_type == OP_CONCAT
2964            || o->op_type == OP_SPRINTF
2965            || o->op_type == OP_STRINGIFY);
2966
2967     Zero(&sprintf_info, 1, struct sprintf_ismc_info);
2968
2969     /* first see if, at the top of the tree, there is an assign,
2970      * append and/or stringify */
2971
2972     if (topop->op_type == OP_SASSIGN) {
2973         /* expr = ..... */
2974         if (o->op_ppaddr != PL_ppaddr[OP_SASSIGN])
2975             return;
2976         if (o->op_private & (OPpASSIGN_BACKWARDS|OPpASSIGN_CV_TO_GV))
2977             return;
2978         assert(!(o->op_private & ~OPpARG2_MASK)); /* barf on unknown flags */
2979
2980         parentop = topop;
2981         topop = cBINOPo->op_first;
2982         targetop = OpSIBLING(topop);
2983         if (!targetop) /* probably some sort of syntax error */
2984             return;
2985
2986         /* don't optimise away assign in 'local $foo = ....' */
2987         if (   (targetop->op_private & OPpLVAL_INTRO)
2988             /* these are the common ops which do 'local', but
2989              * not all */
2990             && (   targetop->op_type == OP_GVSV
2991                 || targetop->op_type == OP_RV2SV
2992                 || targetop->op_type == OP_AELEM
2993                 || targetop->op_type == OP_HELEM
2994                 )
2995         )
2996             return;
2997     }
2998     else if (   topop->op_type == OP_CONCAT
2999              && (topop->op_flags & OPf_STACKED)
3000              && (!(topop->op_private & OPpCONCAT_NESTED))
3001             )
3002     {
3003         /* expr .= ..... */
3004
3005         /* OPpTARGET_MY shouldn't be able to be set here. If it is,
3006          * decide what to do about it */
3007         assert(!(o->op_private & OPpTARGET_MY));
3008
3009         /* barf on unknown flags */
3010         assert(!(o->op_private & ~(OPpARG2_MASK|OPpTARGET_MY)));
3011         private_flags |= OPpMULTICONCAT_APPEND;
3012         targetop = cBINOPo->op_first;
3013         parentop = topop;
3014         topop    = OpSIBLING(targetop);
3015
3016         /* $x .= <FOO> gets optimised to rcatline instead */
3017         if (topop->op_type == OP_READLINE)
3018             return;
3019     }
3020
3021     if (targetop) {
3022         /* Can targetop (the LHS) if it's a padsv, be optimised
3023          * away and use OPpTARGET_MY instead?
3024          */
3025         if (    (targetop->op_type == OP_PADSV)
3026             && !(targetop->op_private & OPpDEREF)
3027             && !(targetop->op_private & OPpPAD_STATE)
3028                /* we don't support 'my $x .= ...' */
3029             && (   o->op_type == OP_SASSIGN
3030                 || !(targetop->op_private & OPpLVAL_INTRO))
3031         )
3032             is_targable = TRUE;
3033     }
3034
3035     if (topop->op_type == OP_STRINGIFY) {
3036         if (topop->op_ppaddr != PL_ppaddr[OP_STRINGIFY])
3037             return;
3038         stringop = topop;
3039
3040         /* barf on unknown flags */
3041         assert(!(o->op_private & ~(OPpARG4_MASK|OPpTARGET_MY)));
3042
3043         if ((topop->op_private & OPpTARGET_MY)) {
3044             if (o->op_type == OP_SASSIGN)
3045                 return; /* can't have two assigns */
3046             targmyop = topop;
3047         }
3048
3049         private_flags |= OPpMULTICONCAT_STRINGIFY;
3050         parentop = topop;
3051         topop = cBINOPx(topop)->op_first;
3052         assert(OP_TYPE_IS_OR_WAS_NN(topop, OP_PUSHMARK));
3053         topop = OpSIBLING(topop);
3054     }
3055
3056     if (topop->op_type == OP_SPRINTF) {
3057         if (topop->op_ppaddr != PL_ppaddr[OP_SPRINTF])
3058             return;
3059         if (S_sprintf_is_multiconcatable(aTHX_ topop, &sprintf_info)) {
3060             nargs     = sprintf_info.nargs;
3061             total_len = sprintf_info.total_len;
3062             variant   = sprintf_info.variant;
3063             utf8      = sprintf_info.utf8;
3064             is_sprintf = TRUE;
3065             private_flags |= OPpMULTICONCAT_FAKE;
3066             toparg = argp;
3067             /* we have an sprintf op rather than a concat optree.
3068              * Skip most of the code below which is associated with
3069              * processing that optree. We also skip phase 2, determining
3070              * whether its cost effective to optimise, since for sprintf,
3071              * multiconcat is *always* faster */
3072             goto create_aux;
3073         }
3074         /* note that even if the sprintf itself isn't multiconcatable,
3075          * the expression as a whole may be, e.g. in
3076          *    $x .= sprintf("%d",...)
3077          * the sprintf op will be left as-is, but the concat/S op may
3078          * be upgraded to multiconcat
3079          */
3080     }
3081     else if (topop->op_type == OP_CONCAT) {
3082         if (topop->op_ppaddr != PL_ppaddr[OP_CONCAT])
3083             return;
3084
3085         if ((topop->op_private & OPpTARGET_MY)) {
3086             if (o->op_type == OP_SASSIGN || targmyop)
3087                 return; /* can't have two assigns */
3088             targmyop = topop;
3089         }
3090     }
3091
3092     /* Is it safe to convert a sassign/stringify/concat op into
3093      * a multiconcat? */
3094     assert((PL_opargs[OP_SASSIGN]   & OA_CLASS_MASK) == OA_BINOP);
3095     assert((PL_opargs[OP_CONCAT]    & OA_CLASS_MASK) == OA_BINOP);
3096     assert((PL_opargs[OP_STRINGIFY] & OA_CLASS_MASK) == OA_LISTOP);
3097     assert((PL_opargs[OP_SPRINTF]   & OA_CLASS_MASK) == OA_LISTOP);
3098     STATIC_ASSERT_STMT(   STRUCT_OFFSET(BINOP,    op_last)
3099                        == STRUCT_OFFSET(UNOP_AUX, op_aux));
3100     STATIC_ASSERT_STMT(   STRUCT_OFFSET(LISTOP,   op_last)
3101                        == STRUCT_OFFSET(UNOP_AUX, op_aux));
3102
3103     /* Now scan the down the tree looking for a series of
3104      * CONCAT/OPf_STACKED ops on the LHS (with the last one not
3105      * stacked). For example this tree:
3106      *
3107      *     |
3108      *   CONCAT/STACKED
3109      *     |
3110      *   CONCAT/STACKED -- EXPR5
3111      *     |
3112      *   CONCAT/STACKED -- EXPR4
3113      *     |
3114      *   CONCAT -- EXPR3
3115      *     |
3116      *   EXPR1  -- EXPR2
3117      *
3118      * corresponds to an expression like
3119      *
3120      *   (EXPR1 . EXPR2 . EXPR3 . EXPR4 . EXPR5)
3121      *
3122      * Record info about each EXPR in args[]: in particular, whether it is
3123      * a stringifiable OP_CONST and if so what the const sv is.
3124      *
3125      * The reason why the last concat can't be STACKED is the difference
3126      * between
3127      *
3128      *    ((($a .= $a) .= $a) .= $a) .= $a
3129      *
3130      * and
3131      *    $a . $a . $a . $a . $a
3132      *
3133      * The main difference between the optrees for those two constructs
3134      * is the presence of the last STACKED. As well as modifying $a,
3135      * the former sees the changed $a between each concat, so if $s is
3136      * initially 'a', the first returns 'a' x 16, while the latter returns
3137      * 'a' x 5. And pp_multiconcat can't handle that kind of thing.
3138      */
3139
3140     kid = topop;
3141
3142     for (;;) {
3143         OP *argop;
3144         SV *sv;
3145         bool last = FALSE;
3146
3147         if (    kid->op_type == OP_CONCAT
3148             && !kid_is_last
3149         ) {
3150             OP *k1, *k2;
3151             k1 = cUNOPx(kid)->op_first;
3152             k2 = OpSIBLING(k1);
3153             /* shouldn't happen except maybe after compile err? */
3154             if (!k2)
3155                 return;
3156
3157             /* avoid turning (A . B . ($lex = C) ...)  into  (A . B . C ...) */
3158             if (kid->op_private & OPpTARGET_MY)
3159                 kid_is_last = TRUE;
3160
3161             stacked_last = (kid->op_flags & OPf_STACKED);
3162             if (!stacked_last)
3163                 kid_is_last = TRUE;
3164
3165             kid   = k1;
3166             argop = k2;
3167         }
3168         else {
3169             argop = kid;
3170             last = TRUE;
3171         }
3172
3173         if (   nargs + nadjconst  >  PERL_MULTICONCAT_MAXARG        - 2
3174             || (argp - args + 1)  > (PERL_MULTICONCAT_MAXARG*2 + 1) - 2)
3175         {
3176             /* At least two spare slots are needed to decompose both
3177              * concat args. If there are no slots left, continue to
3178              * examine the rest of the optree, but don't push new values
3179              * on args[]. If the optree as a whole is legal for conversion
3180              * (in particular that the last concat isn't STACKED), then
3181              * the first PERL_MULTICONCAT_MAXARG elements of the optree
3182              * can be converted into an OP_MULTICONCAT now, with the first
3183              * child of that op being the remainder of the optree -
3184              * which may itself later be converted to a multiconcat op
3185              * too.
3186              */
3187             if (last) {
3188                 /* the last arg is the rest of the optree */
3189                 argp++->p = NULL;
3190                 nargs++;
3191             }
3192         }
3193         else if (   argop->op_type == OP_CONST
3194             && ((sv = cSVOPx_sv(argop)))
3195             /* defer stringification until runtime of 'constant'
3196              * things that might stringify variantly, e.g. the radix
3197              * point of NVs, or overloaded RVs */
3198             && (SvPOK(sv) || SvIOK(sv))
3199             && (!SvGMAGICAL(sv))
3200         ) {
3201             if (argop->op_private & OPpCONST_STRICT)
3202                 no_bareword_allowed(argop);
3203             argp++->p = sv;
3204             utf8   |= cBOOL(SvUTF8(sv));
3205             nconst++;
3206             if (prev_was_const)
3207                 /* this const may be demoted back to a plain arg later;
3208                  * make sure we have enough arg slots left */
3209                 nadjconst++;
3210             prev_was_const = !prev_was_const;
3211         }
3212         else {
3213             argp++->p = NULL;
3214             nargs++;
3215             prev_was_const = FALSE;
3216         }
3217
3218         if (last)
3219             break;
3220     }
3221
3222     toparg = argp - 1;
3223
3224     if (stacked_last)
3225         return; /* we don't support ((A.=B).=C)...) */
3226
3227     /* look for two adjacent consts and don't fold them together:
3228      *     $o . "a" . "b"
3229      * should do
3230      *     $o->concat("a")->concat("b")
3231      * rather than
3232      *     $o->concat("ab")
3233      * (but $o .=  "a" . "b" should still fold)
3234      */
3235     {
3236         bool seen_nonconst = FALSE;
3237         for (argp = toparg; argp >= args; argp--) {
3238             if (argp->p == NULL) {
3239                 seen_nonconst = TRUE;
3240                 continue;
3241             }
3242             if (!seen_nonconst)
3243                 continue;
3244             if (argp[1].p) {
3245                 /* both previous and current arg were constants;
3246                  * leave the current OP_CONST as-is */
3247                 argp->p = NULL;
3248                 nconst--;
3249                 nargs++;
3250             }
3251         }
3252     }
3253
3254     /* -----------------------------------------------------------------
3255      * Phase 2:
3256      *
3257      * At this point we have determined that the optree *can* be converted
3258      * into a multiconcat. Having gathered all the evidence, we now decide
3259      * whether it *should*.
3260      */
3261
3262
3263     /* we need at least one concat action, e.g.:
3264      *
3265      *  Y . Z
3266      *  X = Y . Z
3267      *  X .= Y
3268      *
3269      * otherwise we could be doing something like $x = "foo", which
3270      * if treated as a concat, would fail to COW.
3271      */
3272     if (nargs + nconst + cBOOL(private_flags & OPpMULTICONCAT_APPEND) < 2)
3273         return;
3274
3275     /* Benchmarking seems to indicate that we gain if:
3276      * * we optimise at least two actions into a single multiconcat
3277      *    (e.g concat+concat, sassign+concat);
3278      * * or if we can eliminate at least 1 OP_CONST;
3279      * * or if we can eliminate a padsv via OPpTARGET_MY
3280      */
3281
3282     if (
3283            /* eliminated at least one OP_CONST */
3284            nconst >= 1
3285            /* eliminated an OP_SASSIGN */
3286         || o->op_type == OP_SASSIGN
3287            /* eliminated an OP_PADSV */
3288         || (!targmyop && is_targable)
3289     )
3290         /* definitely a net gain to optimise */
3291         goto optimise;
3292
3293     /* ... if not, what else? */
3294
3295     /* special-case '$lex1 = expr . $lex1' (where expr isn't lex1):
3296      * multiconcat is faster (due to not creating a temporary copy of
3297      * $lex1), whereas for a general $lex1 = $lex2 . $lex3, concat is
3298      * faster.
3299      */
3300     if (   nconst == 0
3301          && nargs == 2
3302          && targmyop
3303          && topop->op_type == OP_CONCAT
3304     ) {
3305         PADOFFSET t = targmyop->op_targ;
3306         OP *k1 = cBINOPx(topop)->op_first;
3307         OP *k2 = cBINOPx(topop)->op_last;
3308         if (   k2->op_type == OP_PADSV
3309             && k2->op_targ == t
3310             && (   k1->op_type != OP_PADSV
3311                 || k1->op_targ != t)
3312         )
3313             goto optimise;
3314     }
3315
3316     /* need at least two concats */
3317     if (nargs + nconst + cBOOL(private_flags & OPpMULTICONCAT_APPEND) < 3)
3318         return;
3319
3320
3321
3322     /* -----------------------------------------------------------------
3323      * Phase 3:
3324      *
3325      * At this point the optree has been verified as ok to be optimised
3326      * into an OP_MULTICONCAT. Now start changing things.
3327      */
3328
3329    optimise:
3330
3331     /* stringify all const args and determine utf8ness */
3332
3333     variant = 0;
3334     for (argp = args; argp <= toparg; argp++) {
3335         SV *sv = (SV*)argp->p;
3336         if (!sv)
3337             continue; /* not a const op */
3338         if (utf8 && !SvUTF8(sv))
3339             sv_utf8_upgrade_nomg(sv);
3340         argp->p = SvPV_nomg(sv, argp->len);
3341         total_len += argp->len;
3342
3343         /* see if any strings would grow if converted to utf8 */
3344         if (!utf8) {
3345             variant += variant_under_utf8_count((U8 *) argp->p,
3346                                                 (U8 *) argp->p + argp->len);
3347         }
3348     }
3349
3350     /* create and populate aux struct */
3351
3352   create_aux:
3353
3354     aux = (UNOP_AUX_item*)PerlMemShared_malloc(
3355                     sizeof(UNOP_AUX_item)
3356                     *  (
3357                            PERL_MULTICONCAT_HEADER_SIZE
3358                          + ((nargs + 1) * (variant ? 2 : 1))
3359                         )
3360                     );
3361     const_str = (char *)PerlMemShared_malloc(total_len ? total_len : 1);
3362
3363     /* Extract all the non-const expressions from the concat tree then
3364      * dispose of the old tree, e.g. convert the tree from this:
3365      *
3366      *  o => SASSIGN
3367      *         |
3368      *       STRINGIFY   -- TARGET
3369      *         |
3370      *       ex-PUSHMARK -- CONCAT
3371      *                        |
3372      *                      CONCAT -- EXPR5
3373      *                        |
3374      *                      CONCAT -- EXPR4
3375      *                        |
3376      *                      CONCAT -- EXPR3
3377      *                        |
3378      *                      EXPR1  -- EXPR2
3379      *
3380      *
3381      * to:
3382      *
3383      *  o => MULTICONCAT
3384      *         |
3385      *       ex-PUSHMARK -- EXPR1 -- EXPR2 -- EXPR3 -- EXPR4 -- EXPR5 -- TARGET
3386      *
3387      * except that if EXPRi is an OP_CONST, it's discarded.
3388      *
3389      * During the conversion process, EXPR ops are stripped from the tree
3390      * and unshifted onto o. Finally, any of o's remaining original
3391      * childen are discarded and o is converted into an OP_MULTICONCAT.
3392      *
3393      * In this middle of this, o may contain both: unshifted args on the
3394      * left, and some remaining original args on the right. lastkidop
3395      * is set to point to the right-most unshifted arg to delineate
3396      * between the two sets.
3397      */
3398
3399
3400     if (is_sprintf) {
3401         /* create a copy of the format with the %'s removed, and record
3402          * the sizes of the const string segments in the aux struct */
3403         char *q, *oldq;
3404         lenp = aux + PERL_MULTICONCAT_IX_LENGTHS;
3405
3406         p    = sprintf_info.start;
3407         q    = const_str;
3408         oldq = q;
3409         for (; p < sprintf_info.end; p++) {
3410             if (*p == '%') {
3411                 p++;
3412                 if (*p != '%') {
3413                     (lenp++)->ssize = q - oldq;
3414                     oldq = q;
3415                     continue;
3416                 }
3417             }
3418             *q++ = *p;
3419         }
3420         lenp->ssize = q - oldq;
3421         assert((STRLEN)(q - const_str) == total_len);
3422
3423         /* Attach all the args (i.e. the kids of the sprintf) to o (which
3424          * may or may not be topop) The pushmark and const ops need to be
3425          * kept in case they're an op_next entry point.
3426          */
3427         lastkidop = cLISTOPx(topop)->op_last;
3428         kid = cUNOPx(topop)->op_first; /* pushmark */
3429         op_null(kid);
3430         op_null(OpSIBLING(kid));       /* const */
3431         if (o != topop) {
3432             kid = op_sibling_splice(topop, NULL, -1, NULL); /* cut all args */
3433             op_sibling_splice(o, NULL, 0, kid); /* and attach to o */
3434             lastkidop->op_next = o;
3435         }
3436     }
3437     else {
3438         p = const_str;
3439         lenp = aux + PERL_MULTICONCAT_IX_LENGTHS;
3440
3441         lenp->ssize = -1;
3442
3443         /* Concatenate all const strings into const_str.
3444          * Note that args[] contains the RHS args in reverse order, so
3445          * we scan args[] from top to bottom to get constant strings
3446          * in L-R order
3447          */
3448         for (argp = toparg; argp >= args; argp--) {
3449             if (!argp->p)
3450                 /* not a const op */
3451                 (++lenp)->ssize = -1;
3452             else {
3453                 STRLEN l = argp->len;
3454                 Copy(argp->p, p, l, char);
3455                 p += l;
3456                 if (lenp->ssize == -1)
3457                     lenp->ssize = l;
3458                 else
3459                     lenp->ssize += l;
3460             }
3461         }
3462
3463         kid = topop;
3464         nextop = o;
3465         lastkidop = NULL;
3466
3467         for (argp = args; argp <= toparg; argp++) {
3468             /* only keep non-const args, except keep the first-in-next-chain
3469              * arg no matter what it is (but nulled if OP_CONST), because it
3470              * may be the entry point to this subtree from the previous
3471              * op_next.
3472              */
3473             bool last = (argp == toparg);
3474             OP *prev;
3475
3476             /* set prev to the sibling *before* the arg to be cut out,
3477              * e.g. when cutting EXPR:
3478              *
3479              *         |
3480              * kid=  CONCAT
3481              *         |
3482              * prev= CONCAT -- EXPR
3483              *         |
3484              */
3485             if (argp == args && kid->op_type != OP_CONCAT) {
3486                 /* in e.g. '$x .= f(1)' there's no RHS concat tree
3487                  * so the expression to be cut isn't kid->op_last but
3488                  * kid itself */
3489                 OP *o1, *o2;
3490                 /* find the op before kid */
3491                 o1 = NULL;
3492                 o2 = cUNOPx(parentop)->op_first;
3493                 while (o2 && o2 != kid) {
3494                     o1 = o2;
3495                     o2 = OpSIBLING(o2);
3496                 }
3497                 assert(o2 == kid);
3498                 prev = o1;
3499                 kid  = parentop;
3500             }
3501             else if (kid == o && lastkidop)
3502                 prev = last ? lastkidop : OpSIBLING(lastkidop);
3503             else
3504                 prev = last ? NULL : cUNOPx(kid)->op_first;
3505
3506             if (!argp->p || last) {
3507                 /* cut RH op */
3508                 OP *aop = op_sibling_splice(kid, prev, 1, NULL);
3509                 /* and unshift to front of o */
3510                 op_sibling_splice(o, NULL, 0, aop);
3511                 /* record the right-most op added to o: later we will
3512                  * free anything to the right of it */
3513                 if (!lastkidop)
3514                     lastkidop = aop;
3515                 aop->op_next = nextop;
3516                 if (last) {
3517                     if (argp->p)
3518                         /* null the const at start of op_next chain */
3519                         op_null(aop);
3520                 }
3521                 else if (prev)
3522                     nextop = prev->op_next;
3523             }
3524
3525             /* the last two arguments are both attached to the same concat op */
3526             if (argp < toparg - 1)
3527                 kid = prev;
3528         }
3529     }
3530
3531     /* Populate the aux struct */
3532
3533     aux[PERL_MULTICONCAT_IX_NARGS].ssize     = nargs;
3534     aux[PERL_MULTICONCAT_IX_PLAIN_PV].pv    = utf8 ? NULL : const_str;
3535     aux[PERL_MULTICONCAT_IX_PLAIN_LEN].ssize = utf8 ?    0 : total_len;
3536     aux[PERL_MULTICONCAT_IX_UTF8_PV].pv     = const_str;
3537     aux[PERL_MULTICONCAT_IX_UTF8_LEN].ssize  = total_len;
3538
3539     /* if variant > 0, calculate a variant const string and lengths where
3540      * the utf8 version of the string will take 'variant' more bytes than
3541      * the plain one. */
3542
3543     if (variant) {
3544         char              *p = const_str;
3545         STRLEN          ulen = total_len + variant;
3546         UNOP_AUX_item  *lens = aux + PERL_MULTICONCAT_IX_LENGTHS;
3547         UNOP_AUX_item *ulens = lens + (nargs + 1);
3548         char             *up = (char*)PerlMemShared_malloc(ulen);
3549         SSize_t            n;
3550
3551         aux[PERL_MULTICONCAT_IX_UTF8_PV].pv    = up;
3552         aux[PERL_MULTICONCAT_IX_UTF8_LEN].ssize = ulen;
3553
3554         for (n = 0; n < (nargs + 1); n++) {
3555             SSize_t i;
3556             char * orig_up = up;
3557             for (i = (lens++)->ssize; i > 0; i--) {
3558                 U8 c = *p++;
3559                 append_utf8_from_native_byte(c, (U8**)&up);
3560             }
3561             (ulens++)->ssize = (i < 0) ? i : up - orig_up;
3562         }
3563     }
3564
3565     if (stringop) {
3566         /* if there was a top(ish)-level OP_STRINGIFY, we need to keep
3567          * that op's first child - an ex-PUSHMARK - because the op_next of
3568          * the previous op may point to it (i.e. it's the entry point for
3569          * the o optree)
3570          */
3571         OP *pmop =
3572             (stringop == o)
3573                 ? op_sibling_splice(o, lastkidop, 1, NULL)
3574                 : op_sibling_splice(stringop, NULL, 1, NULL);
3575         assert(OP_TYPE_IS_OR_WAS_NN(pmop, OP_PUSHMARK));
3576         op_sibling_splice(o, NULL, 0, pmop);
3577         if (!lastkidop)
3578             lastkidop = pmop;
3579     }
3580
3581     /* Optimise
3582      *    target  = A.B.C...
3583      *    target .= A.B.C...
3584      */
3585
3586     if (targetop) {
3587         assert(!targmyop);
3588
3589         if (o->op_type == OP_SASSIGN) {
3590             /* Move the target subtree from being the last of o's children
3591              * to being the last of o's preserved children.
3592              * Note the difference between 'target = ...' and 'target .= ...':
3593              * for the former, target is executed last; for the latter,
3594              * first.
3595              */
3596             kid = OpSIBLING(lastkidop);
3597             op_sibling_splice(o, kid, 1, NULL); /* cut target op */
3598             op_sibling_splice(o, lastkidop, 0, targetop); /* and paste */
3599             lastkidop->op_next = kid->op_next;
3600             lastkidop = targetop;
3601         }
3602         else {
3603             /* Move the target subtree from being the first of o's
3604              * original children to being the first of *all* o's children.
3605              */
3606             if (lastkidop) {
3607                 op_sibling_splice(o, lastkidop, 1, NULL); /* cut target op */
3608                 op_sibling_splice(o, NULL, 0, targetop);  /* and paste*/
3609             }
3610             else {
3611                 /* if the RHS of .= doesn't contain a concat (e.g.
3612                  * $x .= "foo"), it gets missed by the "strip ops from the
3613                  * tree and add to o" loop earlier */
3614                 assert(topop->op_type != OP_CONCAT);
3615                 if (stringop) {
3616                     /* in e.g. $x .= "$y", move the $y expression
3617                      * from being a child of OP_STRINGIFY to being the
3618                      * second child of the OP_CONCAT
3619                      */
3620                     assert(cUNOPx(stringop)->op_first == topop);
3621                     op_sibling_splice(stringop, NULL, 1, NULL);
3622                     op_sibling_splice(o, cUNOPo->op_first, 0, topop);
3623                 }
3624                 assert(topop == OpSIBLING(cBINOPo->op_first));
3625                 if (toparg->p)
3626                     op_null(topop);
3627                 lastkidop = topop;
3628             }
3629         }
3630
3631         if (is_targable) {
3632             /* optimise
3633              *  my $lex  = A.B.C...
3634              *     $lex  = A.B.C...
3635              *     $lex .= A.B.C...
3636              * The original padsv op is kept but nulled in case it's the
3637              * entry point for the optree (which it will be for
3638              * '$lex .=  ... '
3639              */
3640             private_flags |= OPpTARGET_MY;
3641             private_flags |= (targetop->op_private & OPpLVAL_INTRO);
3642             o->op_targ = targetop->op_targ;
3643             targetop->op_targ = 0;
3644             op_null(targetop);
3645         }
3646         else
3647             flags |= OPf_STACKED;
3648     }
3649     else if (targmyop) {
3650         private_flags |= OPpTARGET_MY;
3651         if (o != targmyop) {
3652             o->op_targ = targmyop->op_targ;
3653             targmyop->op_targ = 0;
3654         }
3655     }
3656
3657     /* detach the emaciated husk of the sprintf/concat optree and free it */
3658     for (;;) {
3659         kid = op_sibling_splice(o, lastkidop, 1, NULL);
3660         if (!kid)
3661             break;
3662         op_free(kid);
3663     }
3664
3665     /* and convert o into a multiconcat */
3666
3667     o->op_flags        = (flags|OPf_KIDS|stacked_last
3668                          |(o->op_flags & (OPf_WANT|OPf_PARENS)));
3669     o->op_private      = private_flags;
3670     o->op_type         = OP_MULTICONCAT;
3671     o->op_ppaddr       = PL_ppaddr[OP_MULTICONCAT];
3672     cUNOP_AUXo->op_aux = aux;
3673 }
3674
3675
3676 /* do all the final processing on an optree (e.g. running the peephole
3677  * optimiser on it), then attach it to cv (if cv is non-null)
3678  */
3679
3680 static void
3681 S_process_optree(pTHX_ CV *cv, OP *optree, OP* start)
3682 {
3683     OP **startp;
3684
3685     /* XXX for some reason, evals, require and main optrees are
3686      * never attached to their CV; instead they just hang off
3687      * PL_main_root + PL_main_start or PL_eval_root + PL_eval_start
3688      * and get manually freed when appropriate */
3689     if (cv)
3690         startp = &CvSTART(cv);
3691     else
3692         startp = PL_in_eval? &PL_eval_start : &PL_main_start;
3693
3694     *startp = start;
3695     optree->op_private |= OPpREFCOUNTED;
3696     OpREFCNT_set(optree, 1);
3697     optimize_optree(optree);
3698     CALL_PEEP(*startp);
3699     finalize_optree(optree);
3700     S_prune_chain_head(startp);
3701
3702     if (cv) {
3703         /* now that optimizer has done its work, adjust pad values */
3704         pad_tidy(optree->op_type == OP_LEAVEWRITE ? padtidy_FORMAT
3705                  : CvCLONE(cv) ? padtidy_SUBCLONE : padtidy_SUB);
3706     }
3707 }
3708
3709
3710 /*
3711 =for apidoc optimize_optree
3712
3713 This function applies some optimisations to the optree in top-down order.
3714 It is called before the peephole optimizer, which processes ops in
3715 execution order. Note that finalize_optree() also does a top-down scan,
3716 but is called *after* the peephole optimizer.
3717
3718 =cut
3719 */
3720
3721 void
3722 Perl_optimize_optree(pTHX_ OP* o)
3723 {
3724     PERL_ARGS_ASSERT_OPTIMIZE_OPTREE;
3725
3726     ENTER;
3727     SAVEVPTR(PL_curcop);
3728
3729     optimize_op(o);
3730
3731     LEAVE;
3732 }
3733
3734
3735 #define warn_implicit_snail_cvsig(o)  S_warn_implicit_snail_cvsig(aTHX_ o)
3736 static void
3737 S_warn_implicit_snail_cvsig(pTHX_ OP *o)
3738 {
3739     CV *cv = PL_compcv;
3740     while(cv && CvEVAL(cv))
3741         cv = CvOUTSIDE(cv);
3742
3743     if(cv && CvSIGNATURE(cv))
3744         Perl_ck_warner_d(aTHX_ packWARN(WARN_EXPERIMENTAL__ARGS_ARRAY_WITH_SIGNATURES),
3745             "Implicit use of @_ in %s with signatured subroutine is experimental", OP_DESC(o));
3746 }
3747
3748 #define OP_ZOOM(o)  (OP_TYPE_IS(o, OP_NULL) ? cUNOPx(o)->op_first : (o))
3749
3750 /* helper for optimize_optree() which optimises one op then recurses
3751  * to optimise any children.
3752  */
3753
3754 STATIC void
3755 S_optimize_op(pTHX_ OP* o)
3756 {
3757     OP *top_op = o;
3758
3759     PERL_ARGS_ASSERT_OPTIMIZE_OP;
3760
3761     while (1) {
3762         OP * next_kid = NULL;
3763
3764         assert(o->op_type != OP_FREED);
3765
3766         switch (o->op_type) {
3767         case OP_NEXTSTATE:
3768         case OP_DBSTATE:
3769             PL_curcop = ((COP*)o);              /* for warnings */
3770             break;
3771
3772
3773         case OP_CONCAT:
3774         case OP_SASSIGN:
3775         case OP_STRINGIFY:
3776         case OP_SPRINTF:
3777             S_maybe_multiconcat(aTHX_ o);
3778             break;
3779
3780         case OP_SUBST:
3781             if (cPMOPo->op_pmreplrootu.op_pmreplroot) {
3782                 /* we can't assume that op_pmreplroot->op_sibparent == o
3783                  * and that it is thus possible to walk back up the tree
3784                  * past op_pmreplroot. So, although we try to avoid
3785                  * recursing through op trees, do it here. After all,
3786                  * there are unlikely to be many nested s///e's within
3787                  * the replacement part of a s///e.
3788                  */
3789                 optimize_op(cPMOPo->op_pmreplrootu.op_pmreplroot);
3790             }
3791             break;
3792
3793         case OP_RV2AV:
3794         {
3795             OP *first = (o->op_flags & OPf_KIDS) ? cUNOPo->op_first : NULL;
3796             CV *cv = PL_compcv;
3797             while(cv && CvEVAL(cv))
3798                 cv = CvOUTSIDE(cv);
3799
3800             if(cv && CvSIGNATURE(cv) &&
3801                     OP_TYPE_IS(first, OP_GV) && cGVOPx_gv(first) == PL_defgv) {
3802                 OP *parent = op_parent(o);
3803                 while(OP_TYPE_IS(parent, OP_NULL))
3804                     parent = op_parent(parent);
3805
3806                 Perl_ck_warner_d(aTHX_ packWARN(WARN_EXPERIMENTAL__ARGS_ARRAY_WITH_SIGNATURES),
3807                     "Use of @_ in %s with signatured subroutine is experimental", OP_DESC(parent));
3808             }
3809             break;
3810         }
3811
3812         case OP_SHIFT:
3813         case OP_POP:
3814             if(!CvUNIQUE(PL_compcv) && !(o->op_flags & OPf_KIDS))
3815                 warn_implicit_snail_cvsig(o);
3816             break;
3817
3818         case OP_ENTERSUB:
3819             if(!(o->op_flags & OPf_STACKED))
3820                 warn_implicit_snail_cvsig(o);
3821             break;
3822
3823         case OP_GOTO:
3824         {
3825             OP *first = (o->op_flags & OPf_KIDS) ? cUNOPo->op_first : NULL;
3826             OP *ffirst;
3827             if(OP_TYPE_IS(first, OP_SREFGEN) &&
3828                     (ffirst = OP_ZOOM(cUNOPx(first)->op_first)) &&
3829                     OP_TYPE_IS(ffirst, OP_RV2CV))
3830                 warn_implicit_snail_cvsig(o);
3831             break;
3832         }
3833
3834         default:
3835             break;
3836         }
3837
3838         if (o->op_flags & OPf_KIDS)
3839             next_kid = cUNOPo->op_first;
3840
3841         /* if a kid hasn't been nominated to process, continue with the
3842          * next sibling, or if no siblings left, go back to the parent's
3843          * siblings and so on
3844          */
3845         while (!next_kid) {
3846             if (o == top_op)
3847                 return; /* at top; no parents/siblings to try */
3848             if (OpHAS_SIBLING(o))
3849                 next_kid = o->op_sibparent;
3850             else
3851                 o = o->op_sibparent; /*try parent's next sibling */
3852         }
3853
3854       /* this label not yet used. Goto here if any code above sets
3855        * next-kid
3856        get_next_op:
3857        */
3858         o = next_kid;
3859     }
3860 }
3861
3862
3863 /*
3864 =for apidoc finalize_optree
3865
3866 This function finalizes the optree.  Should be called directly after
3867 the complete optree is built.  It does some additional
3868 checking which can't be done in the normal C<ck_>xxx functions and makes
3869 the tree thread-safe.
3870
3871 =cut
3872 */
3873 void
3874 Perl_finalize_optree(pTHX_ OP* o)
3875 {
3876     PERL_ARGS_ASSERT_FINALIZE_OPTREE;
3877
3878     ENTER;
3879     SAVEVPTR(PL_curcop);
3880
3881     finalize_op(o);
3882
3883     LEAVE;
3884 }
3885
3886 #ifdef USE_ITHREADS
3887 /* Relocate sv to the pad for thread safety.
3888  * Despite being a "constant", the SV is written to,
3889  * for reference counts, sv_upgrade() etc. */
3890 PERL_STATIC_INLINE void
3891 S_op_relocate_sv(pTHX_ SV** svp, PADOFFSET* targp)
3892 {
3893     PADOFFSET ix;
3894     PERL_ARGS_ASSERT_OP_RELOCATE_SV;
3895     if (!*svp) return;
3896     ix = pad_alloc(OP_CONST, SVf_READONLY);
3897     SvREFCNT_dec(PAD_SVl(ix));
3898     PAD_SETSV(ix, *svp);
3899     /* XXX I don't know how this isn't readonly already. */
3900     if (!SvIsCOW(PAD_SVl(ix))) SvREADONLY_on(PAD_SVl(ix));
3901     *svp = NULL;
3902     *targp = ix;
3903 }
3904 #endif
3905
3906 /*
3907 =for apidoc traverse_op_tree
3908
3909 Return the next op in a depth-first traversal of the op tree,
3910 returning NULL when the traversal is complete.
3911
3912 The initial call must supply the root of the tree as both top and o.
3913
3914 For now it's static, but it may be exposed to the API in the future.
3915
3916 =cut
3917 */
3918
3919 STATIC OP*
3920 S_traverse_op_tree(pTHX_ OP *top, OP *o) {
3921     OP *sib;
3922
3923     PERL_ARGS_ASSERT_TRAVERSE_OP_TREE;
3924
3925     if ((o->op_flags & OPf_KIDS) && cUNOPo->op_first) {
3926         return cUNOPo->op_first;
3927     }
3928     else if ((sib = OpSIBLING(o))) {
3929         return sib;
3930     }
3931     else {
3932         OP *parent = o->op_sibparent;
3933         assert(!(o->op_moresib));
3934         while (parent && parent != top) {
3935             OP *sib = OpSIBLING(parent);
3936             if (sib)
3937                 return sib;
3938             parent = parent->op_sibparent;
3939         }
3940
3941         return NULL;
3942     }
3943 }
3944
3945 STATIC void
3946 S_finalize_op(pTHX_ OP* o)
3947 {
3948     OP * const top = o;
3949     PERL_ARGS_ASSERT_FINALIZE_OP;
3950
3951     do {
3952         assert(o->op_type != OP_FREED);
3953
3954         switch (o->op_type) {
3955         case OP_NEXTSTATE:
3956         case OP_DBSTATE:
3957             PL_curcop = ((COP*)o);              /* for warnings */
3958             break;
3959         case OP_EXEC:
3960             if (OpHAS_SIBLING(o)) {
3961                 OP *sib = OpSIBLING(o);
3962                 if ((  sib->op_type == OP_NEXTSTATE || sib->op_type == OP_DBSTATE)
3963                     && ckWARN(WARN_EXEC)
3964                     && OpHAS_SIBLING(sib))
3965                 {
3966                     const OPCODE type = OpSIBLING(sib)->op_type;
3967                     if (type != OP_EXIT && type != OP_WARN && type != OP_DIE) {
3968                         const line_t oldline = CopLINE(PL_curcop);
3969                         CopLINE_set(PL_curcop, CopLINE((COP*)sib));
3970                         Perl_warner(aTHX_ packWARN(WARN_EXEC),
3971                             "Statement unlikely to be reached");
3972                         Perl_warner(aTHX_ packWARN(WARN_EXEC),
3973                             "\t(Maybe you meant system() when you said exec()?)\n");
3974                         CopLINE_set(PL_curcop, oldline);
3975                     }
3976                 }
3977             }
3978             break;
3979
3980         case OP_GV:
3981             if ((o->op_private & OPpEARLY_CV) && ckWARN(WARN_PROTOTYPE)) {
3982                 GV * const gv = cGVOPo_gv;
3983                 if (SvTYPE(gv) == SVt_PVGV && GvCV(gv) && SvPVX_const(GvCV(gv))) {
3984                     /* XXX could check prototype here instead of just carping */
3985                     SV * const sv = sv_newmortal();
3986                     gv_efullname3(sv, gv, NULL);
3987                     Perl_warner(aTHX_ packWARN(WARN_PROTOTYPE),
3988                                 "%" SVf "() called too early to check prototype",
3989                                 SVfARG(sv));
3990                 }
3991             }
3992             break;
3993
3994         case OP_CONST:
3995             if (cSVOPo->op_private & OPpCONST_STRICT)
3996                 no_bareword_allowed(o);
3997 #ifdef USE_ITHREADS
3998             /* FALLTHROUGH */
3999         case OP_HINTSEVAL:
4000             op_relocate_sv(&cSVOPo->op_sv, &o->op_targ);
4001 #endif
4002             break;
4003
4004 #ifdef USE_ITHREADS
4005             /* Relocate all the METHOP's SVs to the pad for thread safety. */
4006         case OP_METHOD_NAMED:
4007         case OP_METHOD_SUPER:
4008         case OP_METHOD_REDIR:
4009         case OP_METHOD_REDIR_SUPER:
4010             op_relocate_sv(&cMETHOPx(o)->op_u.op_meth_sv, &o->op_targ);
4011             break;
4012 #endif
4013
4014         case OP_HELEM: {
4015             UNOP *rop;
4016             SVOP *key_op;
4017             OP *kid;
4018
4019             if ((key_op = cSVOPx(((BINOP*)o)->op_last))->op_type != OP_CONST)
4020                 break;
4021
4022             rop = (UNOP*)((BINOP*)o)->op_first;
4023
4024             goto check_keys;
4025
4026             case OP_HSLICE:
4027                 S_scalar_slice_warning(aTHX_ o);
4028                 /* FALLTHROUGH */
4029
4030             case OP_KVHSLICE:
4031                 kid = OpSIBLING(cLISTOPo->op_first);
4032             if (/* I bet there's always a pushmark... */
4033                 OP_TYPE_ISNT_AND_WASNT_NN(kid, OP_LIST)
4034                 && OP_TYPE_ISNT_NN(kid, OP_CONST))
4035             {
4036                 break;
4037             }
4038
4039             key_op = (SVOP*)(kid->op_type == OP_CONST
4040                              ? kid
4041                              : OpSIBLING(kLISTOP->op_first));
4042
4043             rop = (UNOP*)((LISTOP*)o)->op_last;
4044
4045         check_keys:
4046             if (o->op_private & OPpLVAL_INTRO || rop->op_type != OP_RV2HV)
4047                 rop = NULL;
4048             S_check_hash_fields_and_hekify(aTHX_ rop, key_op, 1);
4049             break;
4050         }
4051         case OP_NULL:
4052             if (o->op_targ != OP_HSLICE && o->op_targ != OP_ASLICE)
4053                 break;
4054             /* FALLTHROUGH */
4055         case OP_ASLICE:
4056             S_scalar_slice_warning(aTHX_ o);
4057             break;
4058
4059         case OP_SUBST: {
4060             if (cPMOPo->op_pmreplrootu.op_pmreplroot)
4061                 finalize_op(cPMOPo->op_pmreplrootu.op_pmreplroot);
4062             break;
4063         }
4064         default:
4065             break;
4066         }
4067
4068 #ifdef DEBUGGING
4069         if (o->op_flags & OPf_KIDS) {
4070             OP *kid;
4071
4072             /* check that op_last points to the last sibling, and that
4073              * the last op_sibling/op_sibparent field points back to the
4074              * parent, and that the only ops with KIDS are those which are
4075              * entitled to them */
4076             U32 type = o->op_type;
4077             U32 family;
4078             bool has_last;
4079
4080             if (type == OP_NULL) {
4081                 type = o->op_targ;
4082                 /* ck_glob creates a null UNOP with ex-type GLOB
4083                  * (which is a list op. So pretend it wasn't a listop */
4084                 if (type == OP_GLOB)
4085                     type = OP_NULL;
4086             }
4087             family = PL_opargs[type] & OA_CLASS_MASK;
4088
4089             has_last = (   family == OA_BINOP
4090                         || family == OA_LISTOP
4091                         || family == OA_PMOP
4092                         || family == OA_LOOP
4093                        );
4094             assert(  has_last /* has op_first and op_last, or ...
4095                   ... has (or may have) op_first: */
4096                   || family == OA_UNOP
4097                   || family == OA_UNOP_AUX
4098                   || family == OA_LOGOP
4099                   || family == OA_BASEOP_OR_UNOP
4100                   || family == OA_FILESTATOP
4101                   || family == OA_LOOPEXOP
4102                   || family == OA_METHOP
4103                   || type == OP_CUSTOM
4104                   || type == OP_NULL /* new_logop does this */
4105                   );
4106
4107             for (kid = cUNOPo->op_first; kid; kid = OpSIBLING(kid)) {
4108                 if (!OpHAS_SIBLING(kid)) {
4109                     if (has_last)
4110                         assert(kid == cLISTOPo->op_last);
4111                     assert(kid->op_sibparent == o);
4112                 }
4113             }
4114         }
4115 #endif
4116     } while (( o = traverse_op_tree(top, o)) != NULL);
4117 }
4118
4119 static void
4120 S_mark_padname_lvalue(pTHX_ PADNAME *pn)
4121 {
4122     CV *cv = PL_compcv;
4123     PadnameLVALUE_on(pn);
4124     while (PadnameOUTER(pn) && PARENT_PAD_INDEX(pn)) {
4125         cv = CvOUTSIDE(cv);
4126         /* RT #127786: cv can be NULL due to an eval within the DB package
4127          * called from an anon sub - anon subs don't have CvOUTSIDE() set
4128          * unless they contain an eval, but calling eval within DB
4129          * pretends the eval was done in the caller's scope.
4130          */
4131         if (!cv)
4132             break;
4133         assert(CvPADLIST(cv));
4134         pn =
4135            PadlistNAMESARRAY(CvPADLIST(cv))[PARENT_PAD_INDEX(pn)];
4136         assert(PadnameLEN(pn));
4137         PadnameLVALUE_on(pn);
4138     }
4139 }
4140
4141 static bool
4142 S_vivifies(const OPCODE type)
4143 {
4144     switch(type) {
4145     case OP_RV2AV:     case   OP_ASLICE:
4146     case OP_RV2HV:     case OP_KVASLICE:
4147     case OP_RV2SV:     case   OP_HSLICE:
4148     case OP_AELEMFAST: case OP_KVHSLICE:
4149     case OP_HELEM:
4150     case OP_AELEM:
4151         return 1;
4152     }
4153     return 0;
4154 }
4155
4156
4157 /* apply lvalue reference (aliasing) context to the optree o.
4158  * E.g. in
4159  *     \($x,$y) = (...)
4160  * o would be the list ($x,$y) and type would be OP_AASSIGN.
4161  * It may descend and apply this to children too, for example in
4162  * \( $cond ? $x, $y) = (...)
4163  */
4164
4165 static void
4166 S_lvref(pTHX_ OP *o, I32 type)
4167 {
4168     OP *kid;
4169     OP * top_op = o;
4170
4171     while (1) {
4172         switch (o->op_type) {
4173         case OP_COND_EXPR:
4174             o = OpSIBLING(cUNOPo->op_first);
4175             continue;
4176
4177         case OP_PUSHMARK:
4178             goto do_next;
4179
4180         case OP_RV2AV:
4181             if (cUNOPo->op_first->op_type != OP_GV) goto badref;
4182             o->op_flags |= OPf_STACKED;
4183             if (o->op_flags & OPf_PARENS) {
4184                 if (o->op_private & OPpLVAL_INTRO) {
4185                      yyerror(Perl_form(aTHX_ "Can't modify reference to "
4186                           "localized parenthesized array in list assignment"));
4187                     goto do_next;
4188                 }
4189               slurpy:
4190                 OpTYPE_set(o, OP_LVAVREF);
4191                 o->op_private &= OPpLVAL_INTRO|OPpPAD_STATE;
4192                 o->op_flags |= OPf_MOD|OPf_REF;
4193                 goto do_next;
4194             }
4195             o->op_private |= OPpLVREF_AV;
4196             goto checkgv;
4197
4198         case OP_RV2CV:
4199             kid = cUNOPo->op_first;
4200             if (kid->op_type == OP_NULL)
4201                 kid = cUNOPx(OpSIBLING(kUNOP->op_first))
4202                     ->op_first;
4203             o->op_private = OPpLVREF_CV;
4204             if (kid->op_type == OP_GV)
4205                 o->op_flags |= OPf_STACKED;
4206             else if (kid->op_type == OP_PADCV) {
4207                 o->op_targ = kid->op_targ;
4208                 kid->op_targ = 0;
4209                 op_free(cUNOPo->op_first);
4210                 cUNOPo->op_first = NULL;
4211                 o->op_flags &=~ OPf_KIDS;
4212             }
4213             else goto badref;
4214             break;
4215
4216         case OP_RV2HV:
4217             if (o->op_flags & OPf_PARENS) {
4218               parenhash:
4219                 yyerror(Perl_form(aTHX_ "Can't modify reference to "
4220                                      "parenthesized hash in list assignment"));
4221                     goto do_next;
4222             }
4223             o->op_private |= OPpLVREF_HV;
4224             /* FALLTHROUGH */
4225         case OP_RV2SV:
4226           checkgv:
4227             if (cUNOPo->op_first->op_type != OP_GV) goto badref;
4228             o->op_flags |= OPf_STACKED;
4229             break;
4230
4231         case OP_PADHV:
4232             if (o->op_flags & OPf_PARENS) goto parenhash;
4233             o->op_private |= OPpLVREF_HV;
4234             /* FALLTHROUGH */
4235         case OP_PADSV:
4236             PAD_COMPNAME_GEN_set(o->op_targ, PERL_INT_MAX);
4237             break;
4238
4239         case OP_PADAV:
4240             PAD_COMPNAME_GEN_set(o->op_targ, PERL_INT_MAX);
4241             if (o->op_flags & OPf_PARENS) goto slurpy;
4242             o->op_private |= OPpLVREF_AV;
4243             break;
4244
4245         case OP_AELEM:
4246         case OP_HELEM:
4247             o->op_private |= OPpLVREF_ELEM;
4248             o->op_flags   |= OPf_STACKED;
4249             break;
4250
4251         case OP_ASLICE:
4252         case OP_HSLICE:
4253             OpTYPE_set(o, OP_LVREFSLICE);
4254             o->op_private &= OPpLVAL_INTRO;
4255             goto do_next;
4256
4257         case OP_NULL:
4258             if (o->op_flags & OPf_SPECIAL)              /* do BLOCK */
4259                 goto badref;
4260             else if (!(o->op_flags & OPf_KIDS))
4261                 goto do_next;
4262
4263             /* the code formerly only recursed into the first child of
4264              * a non ex-list OP_NULL. if we ever encounter such a null op with
4265              * more than one child, need to decide whether its ok to process
4266              * *all* its kids or not */
4267             assert(o->op_targ == OP_LIST
4268                     || !(OpHAS_SIBLING(cBINOPo->op_first)));
4269             /* FALLTHROUGH */
4270         case OP_LIST:
4271             o = cLISTOPo->op_first;
4272             continue;
4273
4274         case OP_STUB:
4275             if (o->op_flags & OPf_PARENS)
4276                 goto do_next;
4277             /* FALLTHROUGH */
4278         default:
4279           badref:
4280             /* diag_listed_as: Can't modify reference to %s in %s assignment */
4281             yyerror(Perl_form(aTHX_ "Can't modify reference to %s in %s",
4282                          o->op_type == OP_NULL && o->op_flags & OPf_SPECIAL
4283                           ? "do block"
4284                           : OP_DESC(o),
4285                          PL_op_desc[type]));
4286             goto do_next;
4287         }
4288
4289         OpTYPE_set(o, OP_LVREF);
4290         o->op_private &=
4291             OPpLVAL_INTRO|OPpLVREF_ELEM|OPpLVREF_TYPE|OPpPAD_STATE;
4292         if (type == OP_ENTERLOOP)
4293             o->op_private |= OPpLVREF_ITER;
4294
4295       do_next:
4296         while (1) {
4297             if (o == top_op)
4298                 return; /* at top; no parents/siblings to try */
4299             if (OpHAS_SIBLING(o)) {
4300                 o = o->op_sibparent;
4301                 break;
4302             }
4303             o = o->op_sibparent; /*try parent's next sibling */
4304         }
4305     } /* while */
4306 }
4307
4308
4309 PERL_STATIC_INLINE bool
4310 S_potential_mod_type(I32 type)
4311 {
4312     /* Types that only potentially result in modification.  */
4313     return type == OP_GREPSTART || type == OP_ENTERSUB
4314         || type == OP_REFGEN    || type == OP_LEAVESUBLV;
4315 }
4316
4317
4318 /*
4319 =for apidoc op_lvalue
4320
4321 Propagate lvalue ("modifiable") context to an op and its children.
4322 C<type> represents the context type, roughly based on the type of op that
4323 would do the modifying, although C<local()> is represented by C<OP_NULL>,
4324 because it has no op type of its own (it is signalled by a flag on
4325 the lvalue op).
4326
4327 This function detects things that can't be modified, such as C<$x+1>, and
4328 generates errors for them.  For example, C<$x+1 = 2> would cause it to be
4329 called with an op of type C<OP_ADD> and a C<type> argument of C<OP_SASSIGN>.
4330
4331 It also flags things that need to behave specially in an lvalue context,
4332 such as C<$$x = 5> which might have to vivify a reference in C<$x>.
4333
4334 =cut
4335
4336 Perl_op_lvalue_flags() is a non-API lower-level interface to
4337 op_lvalue().  The flags param has these bits:
4338     OP_LVALUE_NO_CROAK:  return rather than croaking on error
4339
4340 */
4341
4342 OP *
4343 Perl_op_lvalue_flags(pTHX_ OP *o, I32 type, U32 flags)
4344 {
4345     OP *top_op = o;
4346
4347     if (!o || (PL_parser && PL_parser->error_count))
4348         return o;
4349
4350     while (1) {
4351     OP *kid;
4352     /* -1 = error on localize, 0 = ignore localize, 1 = ok to localize */
4353     int localize = -1;
4354     OP *next_kid = NULL;
4355
4356     if ((o->op_private & OPpTARGET_MY)
4357         && (PL_opargs[o->op_type] & OA_TARGLEX))/* OPp share the meaning */
4358     {
4359         goto do_next;
4360     }
4361
4362     /* elements of a list might be in void context because the list is
4363        in scalar context or because they are attribute sub calls */
4364     if ((o->op_flags & OPf_WANT) == OPf_WANT_VOID)
4365         goto do_next;
4366
4367     if (type == OP_PRTF || type == OP_SPRINTF) type = OP_ENTERSUB;
4368
4369     switch (o->op_type) {
4370     case OP_UNDEF:
4371         if (type == OP_SASSIGN)
4372             goto nomod;
4373         PL_modcount++;
4374         goto do_next;
4375
4376     case OP_STUB:
4377         if ((o->op_flags & OPf_PARENS))
4378             break;
4379         goto nomod;
4380
4381     case OP_ENTERSUB:
4382         if ((type == OP_UNDEF || type == OP_REFGEN || type == OP_LOCK) &&
4383             !(o->op_flags & OPf_STACKED)) {
4384             OpTYPE_set(o, OP_RV2CV);            /* entersub => rv2cv */
4385             assert(cUNOPo->op_first->op_type == OP_NULL);
4386             op_null(((LISTOP*)cUNOPo->op_first)->op_first);/* disable pushmark */
4387             break;
4388         }
4389         else {                          /* lvalue subroutine call */
4390             o->op_private |= OPpLVAL_INTRO;
4391             PL_modcount = RETURN_UNLIMITED_NUMBER;
4392             if (S_potential_mod_type(type)) {
4393                 o->op_private |= OPpENTERSUB_INARGS;
4394                 break;
4395             }
4396             else {                      /* Compile-time error message: */
4397                 OP *kid = cUNOPo->op_first;
4398                 CV *cv;
4399                 GV *gv;
4400                 SV *namesv;
4401
4402                 if (kid->op_type != OP_PUSHMARK) {
4403                     if (kid->op_type != OP_NULL || kid->op_targ != OP_LIST)
4404                         Perl_croak(aTHX_
4405                                 "panic: unexpected lvalue entersub "
4406                                 "args: type/targ %ld:%" UVuf,
4407                                 (long)kid->op_type, (UV)kid->op_targ);
4408                     kid = kLISTOP->op_first;
4409                 }
4410                 while (OpHAS_SIBLING(kid))
4411                     kid = OpSIBLING(kid);
4412                 if (!(kid->op_type == OP_NULL && kid->op_targ == OP_RV2CV)) {
4413                     break;      /* Postpone until runtime */
4414                 }
4415
4416                 kid = kUNOP->op_first;
4417                 if (kid->op_type == OP_NULL && kid->op_targ == OP_RV2SV)
4418                     kid = kUNOP->op_first;
4419                 if (kid->op_type == OP_NULL)
4420                     Perl_croak(aTHX_
4421                                "panic: unexpected constant lvalue entersub "
4422                                "entry via type/targ %ld:%" UVuf,
4423                                (long)kid->op_type, (UV)kid->op_targ);
4424                 if (kid->op_type != OP_GV) {
4425                     break;
4426                 }
4427
4428                 gv = kGVOP_gv;
4429                 cv = isGV(gv)
4430                     ? GvCV(gv)
4431                     : SvROK(gv) && SvTYPE(SvRV(gv)) == SVt_PVCV
4432                         ? MUTABLE_CV(SvRV(gv))
4433                         : NULL;
4434                 if (!cv)
4435                     break;
4436                 if (CvLVALUE(cv))
4437                     break;
4438                 if (flags & OP_LVALUE_NO_CROAK)
4439                     return NULL;
4440
4441                 namesv = cv_name(cv, NULL, 0);
4442                 yyerror_pv(Perl_form(aTHX_ "Can't modify non-lvalue "
4443                                      "subroutine call of &%" SVf " in %s",
4444                                      SVfARG(namesv), PL_op_desc[type]),
4445                            SvUTF8(namesv));
4446                 goto do_next;
4447             }
4448         }
4449         /* FALLTHROUGH */
4450     default:
4451       nomod:
4452         if (flags & OP_LVALUE_NO_CROAK) return NULL;
4453         /* grep, foreach, subcalls, refgen */
4454         if (S_potential_mod_type(type))
4455             break;
4456         yyerror(Perl_form(aTHX_ "Can't modify %s in %s",
4457                      (o->op_type == OP_NULL && (o->op_flags & OPf_SPECIAL)
4458                       ? "do block"
4459                       : OP_DESC(o)),
4460                      type ? PL_op_desc[type] : "local"));
4461         goto do_next;
4462
4463     case OP_PREINC:
4464     case OP_PREDEC:
4465     case OP_POW:
4466     case OP_MULTIPLY:
4467     case OP_DIVIDE:
4468     case OP_MODULO:
4469     case OP_ADD:
4470     case OP_SUBTRACT:
4471     case OP_CONCAT:
4472     case OP_LEFT_SHIFT:
4473     case OP_RIGHT_SHIFT:
4474     case OP_BIT_AND:
4475     case OP_BIT_XOR:
4476     case OP_BIT_OR:
4477     case OP_I_MULTIPLY:
4478     case OP_I_DIVIDE:
4479     case OP_I_MODULO:
4480     case OP_I_ADD:
4481     case OP_I_SUBTRACT:
4482         if (!(o->op_flags & OPf_STACKED))
4483             goto nomod;
4484         PL_modcount++;
4485         break;
4486
4487     case OP_REPEAT:
4488         if (o->op_flags & OPf_STACKED) {
4489             PL_modcount++;
4490             break;
4491         }
4492         if (!(o->op_private & OPpREPEAT_DOLIST))
4493             goto nomod;
4494         else {
4495             const I32 mods = PL_modcount;
4496             /* we recurse rather than iterate here because we need to
4497              * calculate and use the delta applied to PL_modcount by the
4498              * first child. So in something like
4499              *     ($x, ($y) x 3) = split;
4500              * split knows that 4 elements are wanted
4501              */
4502             modkids(cBINOPo->op_first, type);
4503             if (type != OP_AASSIGN)
4504                 goto nomod;
4505             kid = cBINOPo->op_last;
4506             if (kid->op_type == OP_CONST && SvIOK(kSVOP_sv)) {
4507                 const IV iv = SvIV(kSVOP_sv);
4508                 if (PL_modcount != RETURN_UNLIMITED_NUMBER)
4509                     PL_modcount =
4510                         mods + (PL_modcount - mods) * (iv < 0 ? 0 : iv);
4511             }
4512             else
4513                 PL_modcount = RETURN_UNLIMITED_NUMBER;
4514         }
4515         break;
4516
4517     case OP_COND_EXPR:
4518         localize = 1;
4519         next_kid = OpSIBLING(cUNOPo->op_first);
4520         break;
4521
4522     case OP_RV2AV:
4523     case OP_RV2HV:
4524         if (type == OP_REFGEN && o->op_flags & OPf_PARENS) {
4525            PL_modcount = RETURN_UNLIMITED_NUMBER;
4526            /* Treat \(@foo) like ordinary list, but still mark it as modi-
4527               fiable since some contexts need to know.  */
4528            o->op_flags |= OPf_MOD;
4529            goto do_next;
4530         }
4531         /* FALLTHROUGH */
4532     case OP_RV2GV:
4533         if (scalar_mod_type(o, type))
4534             goto nomod;
4535         ref(cUNOPo->op_first, o->op_type);
4536         /* FALLTHROUGH */
4537     case OP_ASLICE:
4538     case OP_HSLICE:
4539         localize = 1;
4540         /* FALLTHROUGH */
4541     case OP_AASSIGN:
4542         /* Do not apply the lvsub flag for rv2[ah]v in scalar context.  */
4543         if (type == OP_LEAVESUBLV && (
4544                 (o->op_type != OP_RV2AV && o->op_type != OP_RV2HV)
4545              || (o->op_flags & OPf_WANT) != OPf_WANT_SCALAR
4546            ))
4547             o->op_private |= OPpMAYBE_LVSUB;
4548         /* FALLTHROUGH */
4549     case OP_NEXTSTATE:
4550     case OP_DBSTATE:
4551        PL_modcount = RETURN_UNLIMITED_NUMBER;
4552         break;
4553
4554     case OP_KVHSLICE:
4555     case OP_KVASLICE:
4556     case OP_AKEYS:
4557         if (type == OP_LEAVESUBLV)
4558             o->op_private |= OPpMAYBE_LVSUB;
4559         goto nomod;
4560
4561     case OP_AVHVSWITCH:
4562         if (type == OP_LEAVESUBLV
4563          && (o->op_private & OPpAVHVSWITCH_MASK) + OP_EACH == OP_KEYS)
4564             o->op_private |= OPpMAYBE_LVSUB;
4565         goto nomod;
4566
4567     case OP_AV2ARYLEN:
4568         PL_hints |= HINT_BLOCK_SCOPE;
4569         if (type == OP_LEAVESUBLV)
4570             o->op_private |= OPpMAYBE_LVSUB;
4571         PL_modcount++;
4572         break;
4573
4574     case OP_RV2SV:
4575         ref(cUNOPo->op_first, o->op_type);
4576         localize = 1;
4577         /* FALLTHROUGH */
4578     case OP_GV:
4579         PL_hints |= HINT_BLOCK_SCOPE;
4580         /* FALLTHROUGH */
4581     case OP_SASSIGN:
4582     case OP_ANDASSIGN:
4583     case OP_ORASSIGN:
4584     case OP_DORASSIGN:
4585         PL_modcount++;
4586         break;
4587
4588     case OP_AELEMFAST:
4589     case OP_AELEMFAST_LEX:
4590         localize = -1;
4591         PL_modcount++;
4592         break;
4593
4594     case OP_PADAV:
4595     case OP_PADHV:
4596        PL_modcount = RETURN_UNLIMITED_NUMBER;
4597         if (type == OP_REFGEN && o->op_flags & OPf_PARENS)
4598         {
4599            /* Treat \(@foo) like ordinary list, but still mark it as modi-
4600               fiable since some contexts need to know.  */
4601             o->op_flags |= OPf_MOD;
4602             goto do_next;
4603         }
4604         if (scalar_mod_type(o, type))
4605             goto nomod;
4606         if ((o->op_flags & OPf_WANT) != OPf_WANT_SCALAR
4607           && type == OP_LEAVESUBLV)
4608             o->op_private |= OPpMAYBE_LVSUB;
4609         /* FALLTHROUGH */
4610     case OP_PADSV:
4611         PL_modcount++;
4612         if (!type) /* local() */
4613             Perl_croak(aTHX_ "Can't localize lexical variable %" PNf,
4614                               PNfARG(PAD_COMPNAME(o->op_targ)));
4615         if (!(o->op_private & OPpLVAL_INTRO)
4616          || (  type != OP_SASSIGN && type != OP_AASSIGN
4617             && PadnameIsSTATE(PAD_COMPNAME_SV(o->op_targ))  ))
4618             S_mark_padname_lvalue(aTHX_ PAD_COMPNAME_SV(o->op_targ));
4619         break;
4620
4621     case OP_PUSHMARK:
4622         localize = 0;
4623         break;
4624
4625     case OP_KEYS:
4626         if (type != OP_LEAVESUBLV && !scalar_mod_type(NULL, type))
4627             goto nomod;
4628         goto lvalue_func;
4629     case OP_SUBSTR:
4630         if (o->op_private == 4) /* don't allow 4 arg substr as lvalue */
4631             goto nomod;
4632         /* FALLTHROUGH */
4633     case OP_POS:
4634     case OP_VEC:
4635       lvalue_func:
4636         if (type == OP_LEAVESUBLV)
4637             o->op_private |= OPpMAYBE_LVSUB;
4638         if (o->op_flags & OPf_KIDS && OpHAS_SIBLING(cBINOPo->op_first)) {
4639             /* we recurse rather than iterate here because the child
4640              * needs to be processed with a different 'type' parameter */
4641
4642             /* substr and vec */
4643             /* If this op is in merely potential (non-fatal) modifiable
4644                context, then apply OP_ENTERSUB context to
4645                the kid op (to avoid croaking).  Other-
4646                wise pass this op’s own type so the correct op is mentioned
4647                in error messages.  */
4648             op_lvalue(OpSIBLING(cBINOPo->op_first),
4649                       S_potential_mod_type(type)
4650                         ? (I32)OP_ENTERSUB
4651                         : o->op_type);
4652         }
4653         break;
4654
4655     case OP_AELEM:
4656     case OP_HELEM:
4657         ref(cBINOPo->op_first, o->op_type);
4658         if (type == OP_ENTERSUB &&
4659              !(o->op_private & (OPpLVAL_INTRO | OPpDEREF)))
4660             o->op_private |= OPpLVAL_DEFER;
4661         if (type == OP_LEAVESUBLV)
4662             o->op_private |= OPpMAYBE_LVSUB;
4663         localize = 1;
4664         PL_modcount++;
4665         break;
4666
4667     case OP_LEAVE:
4668     case OP_LEAVELOOP:
4669         o->op_private |= OPpLVALUE;
4670         /* FALLTHROUGH */
4671     case OP_SCOPE:
4672     case OP_ENTER:
4673     case OP_LINESEQ:
4674         localize = 0;
4675         if (o->op_flags & OPf_KIDS)
4676             next_kid = cLISTOPo->op_last;
4677         break;
4678
4679     case OP_NULL:
4680         localize = 0;
4681         if (o->op_flags & OPf_SPECIAL)          /* do BLOCK */
4682             goto nomod;
4683         else if (!(o->op_flags & OPf_KIDS))
4684             break;
4685
4686         if (o->op_targ != OP_LIST) {
4687             OP *sib = OpSIBLING(cLISTOPo->op_first);
4688             /* OP_TRANS and OP_TRANSR with argument have a weird optree
4689              * that looks like
4690              *
4691              *   null
4692              *      arg
4693              *      trans
4694              *
4695              * compared with things like OP_MATCH which have the argument
4696              * as a child:
4697              *
4698              *   match
4699              *      arg
4700              *
4701              * so handle specially to correctly get "Can't modify" croaks etc
4702              */
4703
4704             if (sib && (sib->op_type == OP_TRANS || sib->op_type == OP_TRANSR))
4705             {
4706                 /* this should trigger a "Can't modify transliteration" err */
4707                 op_lvalue(sib, type);
4708             }
4709             next_kid = cBINOPo->op_first;
4710             /* we assume OP_NULLs which aren't ex-list have no more than 2
4711              * children. If this assumption is wrong, increase the scan
4712              * limit below */
4713             assert(   !OpHAS_SIBLING(next_kid)
4714                    || !OpHAS_SIBLING(OpSIBLING(next_kid)));
4715             break;
4716         }
4717         /* FALLTHROUGH */
4718     case OP_LIST:
4719         localize = 0;
4720         next_kid = cLISTOPo->op_first;
4721         break;
4722
4723     case OP_COREARGS:
4724         goto do_next;
4725
4726     case OP_AND:
4727     case OP_OR:
4728         if (type == OP_LEAVESUBLV
4729          || !S_vivifies(cLOGOPo->op_first->op_type))
4730             next_kid = cLOGOPo->op_first;
4731         else if (type == OP_LEAVESUBLV
4732          || !S_vivifies(OpSIBLING(cLOGOPo->op_first)->op_type))
4733             next_kid = OpSIBLING(cLOGOPo->op_first);
4734         goto nomod;
4735
4736     case OP_SREFGEN:
4737         if (type == OP_NULL) { /* local */
4738           local_refgen:
4739             if (!FEATURE_MYREF_IS_ENABLED)
4740                 Perl_croak(aTHX_ "The experimental declared_refs "
4741                                  "feature is not enabled");
4742             Perl_ck_warner_d(aTHX_
4743                      packWARN(WARN_EXPERIMENTAL__DECLARED_REFS),
4744                     "Declaring references is experimental");
4745             next_kid = cUNOPo->op_first;
4746             goto do_next;
4747         }
4748         if (type != OP_AASSIGN && type != OP_SASSIGN
4749          && type != OP_ENTERLOOP)
4750             goto nomod;
4751         /* Don’t bother applying lvalue context to the ex-list.  */
4752         kid = cUNOPx(cUNOPo->op_first)->op_first;
4753         assert (!OpHAS_SIBLING(kid));
4754         goto kid_2lvref;
4755     case OP_REFGEN:
4756         if (type == OP_NULL) /* local */
4757             goto local_refgen;
4758         if (type != OP_AASSIGN) goto nomod;
4759         kid = cUNOPo->op_first;
4760       kid_2lvref:
4761         {
4762             const U8 ec = PL_parser ? PL_parser->error_count : 0;
4763             S_lvref(aTHX_ kid, type);
4764             if (!PL_parser || PL_parser->error_count == ec) {
4765                 if (!FEATURE_REFALIASING_IS_ENABLED)
4766                     Perl_croak(aTHX_
4767                        "Experimental aliasing via reference not enabled");
4768                 Perl_ck_warner_d(aTHX_
4769                                  packWARN(WARN_EXPERIMENTAL__REFALIASING),
4770                                 "Aliasing via reference is experimental");
4771             }
4772         }
4773         if (o->op_type == OP_REFGEN)
4774             op_null(cUNOPx(cUNOPo->op_first)->op_first); /* pushmark */
4775         op_null(o);
4776         goto do_next;
4777
4778     case OP_SPLIT:
4779         if ((o->op_private & OPpSPLIT_ASSIGN)) {
4780             /* This is actually @array = split.  */
4781             PL_modcount = RETURN_UNLIMITED_NUMBER;
4782             break;
4783         }
4784         goto nomod;
4785
4786     case OP_SCALAR:
4787         op_lvalue(cUNOPo->op_first, OP_ENTERSUB);
4788         goto nomod;
4789     }
4790
4791     /* [20011101.069 (#7861)] File test operators interpret OPf_REF to mean that
4792        their argument is a filehandle; thus \stat(".") should not set
4793        it. AMS 20011102 */
4794     if (type == OP_REFGEN && OP_IS_STAT(o->op_type))
4795         goto do_next;
4796
4797     if (type != OP_LEAVESUBLV)
4798         o->op_flags |= OPf_MOD;
4799
4800     if (type == OP_AASSIGN || type == OP_SASSIGN)
4801         o->op_flags |= OPf_SPECIAL
4802                       |(o->op_type == OP_ENTERSUB ? 0 : OPf_REF);
4803     else if (!type) { /* local() */
4804         switch (localize) {
4805         case 1:
4806             o->op_private |= OPpLVAL_INTRO;
4807             o->op_flags &= ~OPf_SPECIAL;
4808             PL_hints |= HINT_BLOCK_SCOPE;
4809             break;
4810         case 0:
4811             break;
4812         case -1:
4813             Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX),
4814                            "Useless localization of %s", OP_DESC(o));
4815         }
4816     }
4817     else if (type != OP_GREPSTART && type != OP_ENTERSUB
4818              && type != OP_LEAVESUBLV && o->op_type != OP_ENTERSUB)
4819         o->op_flags |= OPf_REF;
4820
4821   do_next:
4822     while (!next_kid) {
4823         if (o == top_op)
4824             return top_op; /* at top; no parents/siblings to try */
4825         if (OpHAS_SIBLING(o)) {
4826             next_kid = o->op_sibparent;
4827             if (!OpHAS_SIBLING(next_kid)) {
4828                 /* a few node types don't recurse into their second child */
4829                 OP *parent = next_kid->op_sibparent;
4830                 I32 ptype  = parent->op_type;
4831                 if (   (ptype == OP_NULL && parent->op_targ != OP_LIST)
4832                     || (   (ptype == OP_AND || ptype == OP_OR)
4833                         && (type != OP_LEAVESUBLV
4834                             && S_vivifies(next_kid->op_type))
4835                        )
4836                 )  {
4837                     /*try parent's next sibling */
4838                     o = parent;
4839                     next_kid =  NULL;
4840                 }
4841             }
4842         }
4843         else
4844             o = o->op_sibparent; /*try parent's next sibling */
4845
4846     }
4847     o = next_kid;
4848
4849     } /* while */
4850
4851 }
4852
4853
4854 STATIC bool
4855 S_scalar_mod_type(const OP *o, I32 type)
4856 {
4857     switch (type) {
4858     case OP_POS:
4859     case OP_SASSIGN:
4860         if (o && o->op_type == OP_RV2GV)
4861             return FALSE;
4862         /* FALLTHROUGH */
4863     case OP_PREINC:
4864     case OP_PREDEC:
4865     case OP_POSTINC:
4866     case OP_POSTDEC:
4867     case OP_I_PREINC:
4868     case OP_I_PREDEC:
4869     case OP_I_POSTINC:
4870     case OP_I_POSTDEC:
4871     case OP_POW:
4872     case OP_MULTIPLY:
4873     case OP_DIVIDE:
4874     case OP_MODULO:
4875     case OP_REPEAT:
4876     case OP_ADD:
4877     case OP_SUBTRACT:
4878     case OP_I_MULTIPLY:
4879     case OP_I_DIVIDE:
4880     case OP_I_MODULO:
4881     case OP_I_ADD:
4882     case OP_I_SUBTRACT:
4883     case OP_LEFT_SHIFT:
4884     case OP_RIGHT_SHIFT:
4885     case OP_BIT_AND:
4886     case OP_BIT_XOR:
4887     case OP_BIT_OR:
4888     case OP_NBIT_AND:
4889     case OP_NBIT_XOR:
4890     case OP_NBIT_OR:
4891     case OP_SBIT_AND:
4892     case OP_SBIT_XOR:
4893     case OP_SBIT_OR:
4894     case OP_CONCAT:
4895     case OP_SUBST:
4896     case OP_TRANS:
4897     case OP_TRANSR:
4898     case OP_READ:
4899     case OP_SYSREAD:
4900     case OP_RECV:
4901     case OP_ANDASSIGN:
4902     case OP_ORASSIGN:
4903     case OP_DORASSIGN:
4904     case OP_VEC:
4905     case OP_SUBSTR:
4906         return TRUE;
4907     default:
4908         return FALSE;
4909     }
4910 }
4911
4912 STATIC bool
4913 S_is_handle_constructor(const OP *o, I32 numargs)
4914 {
4915     PERL_ARGS_ASSERT_IS_HANDLE_CONSTRUCTOR;
4916
4917     switch (o->op_type) {
4918     case OP_PIPE_OP:
4919     case OP_SOCKPAIR:
4920         if (numargs == 2)
4921             return TRUE;
4922         /* FALLTHROUGH */
4923     case OP_SYSOPEN:
4924     case OP_OPEN:
4925     case OP_SELECT:             /* XXX c.f. SelectSaver.pm */
4926     case OP_SOCKET:
4927     case OP_OPEN_DIR:
4928     case OP_ACCEPT:
4929         if (numargs == 1)
4930             return TRUE;
4931         /* FALLTHROUGH */
4932     default:
4933         return FALSE;
4934     }
4935 }
4936
4937 static OP *
4938 S_refkids(pTHX_ OP *o, I32 type)
4939 {
4940     if (o && o->op_flags & OPf_KIDS) {
4941         OP *kid;
4942         for (kid = cLISTOPo->op_first; kid; kid = OpSIBLING(kid))
4943             ref(kid, type);
4944     }
4945     return o;
4946 }
4947
4948
4949 /* Apply reference (autovivification) context to the subtree at o.
4950  * For example in
4951  *     push @{expression}, ....;
4952  * o will be the head of 'expression' and type will be OP_RV2AV.
4953  * It marks the op o (or a suitable child) as autovivifying, e.g. by
4954  * setting  OPf_MOD.
4955  * For OP_RV2AV/OP_PADAV and OP_RV2HV/OP_PADHV sets OPf_REF too if
4956  * set_op_ref is true.
4957  *
4958  * Also calls scalar(o).
4959  */
4960
4961 OP *
4962 Perl_doref(pTHX_ OP *o, I32 type, bool set_op_ref)
4963 {
4964     OP * top_op = o;
4965
4966     PERL_ARGS_ASSERT_DOREF;
4967
4968     if (PL_parser && PL_parser->error_count)
4969         return o;
4970
4971     while (1) {
4972         switch (o->op_type) {
4973         case OP_ENTERSUB:
4974             if ((type == OP_EXISTS || type == OP_DEFINED) &&
4975                 !(o->op_flags & OPf_STACKED)) {
4976                 OpTYPE_set(o, OP_RV2CV);             /* entersub => rv2cv */
4977                 assert(cUNOPo->op_first->op_type == OP_NULL);
4978                 /* disable pushmark */
4979                 op_null(((LISTOP*)cUNOPo->op_first)->op_first);
4980                 o->op_flags |= OPf_SPECIAL;
4981             }
4982             else if (type == OP_RV2SV || type == OP_RV2AV || type == OP_RV2HV){
4983                 o->op_private |= (type == OP_RV2AV ? OPpDEREF_AV
4984                                   : type == OP_RV2HV ? OPpDEREF_HV
4985                                   : OPpDEREF_SV);
4986                 o->op_flags |= OPf_MOD;
4987             }
4988
4989             break;
4990
4991         case OP_COND_EXPR:
4992             o = OpSIBLING(cUNOPo->op_first);
4993             continue;
4994
4995         case OP_RV2SV:
4996             if (type == OP_DEFINED)
4997                 o->op_flags |= OPf_SPECIAL;             /* don't create GV */
4998             /* FALLTHROUGH */
4999         case OP_PADSV:
5000             if (type == OP_RV2SV || type == OP_RV2AV || type == OP_RV2HV) {
5001                 o->op_private |= (type == OP_RV2AV ? OPpDEREF_AV
5002                                   : type == OP_RV2HV ? OPpDEREF_HV
5003                                   : OPpDEREF_SV);
5004                 o->op_flags |= OPf_MOD;
5005             }
5006             if (o->op_flags & OPf_KIDS) {
5007                 type = o->op_type;
5008                 o = cUNOPo->op_first;
5009                 continue;
5010             }
5011             break;
5012
5013         case OP_RV2AV:
5014         case OP_RV2HV:
5015             if (set_op_ref)
5016                 o->op_flags |= OPf_REF;
5017             /* FALLTHROUGH */
5018         case OP_RV2GV:
5019             if (type == OP_DEFINED)
5020                 o->op_flags |= OPf_SPECIAL;             /* don't create GV */
5021             type = o->op_type;
5022             o = cUNOPo->op_first;
5023             continue;
5024
5025         case OP_PADAV:
5026         case OP_PADHV:
5027             if (set_op_ref)
5028                 o->op_flags |= OPf_REF;
5029             break;
5030
5031         case OP_SCALAR:
5032         case OP_NULL:
5033             if (!(o->op_flags & OPf_KIDS) || type == OP_DEFINED)
5034                 break;
5035              o = cBINOPo->op_first;
5036             continue;
5037
5038         case OP_AELEM:
5039         case OP_HELEM:
5040             if (type == OP_RV2SV || type == OP_RV2AV || type == OP_RV2HV) {
5041                 o->op_private |= (type == OP_RV2AV ? OPpDEREF_AV
5042                                   : type == OP_RV2HV ? OPpDEREF_HV
5043                                   : OPpDEREF_SV);
5044                 o->op_flags |= OPf_MOD;
5045             }
5046             type = o->op_type;
5047             o = cBINOPo->op_first;
5048             continue;;
5049
5050         case OP_SCOPE:
5051         case OP_LEAVE:
5052             set_op_ref = FALSE;
5053             /* FALLTHROUGH */
5054         case OP_ENTER:
5055         case OP_LIST:
5056             if (!(o->op_flags & OPf_KIDS))
5057                 break;
5058             o = cLISTOPo->op_last;
5059             continue;
5060
5061         default:
5062             break;
5063         } /* switch */
5064
5065         while (1) {
5066             if (o == top_op)
5067                 return scalar(top_op); /* at top; no parents/siblings to try */
5068             if (OpHAS_SIBLING(o)) {
5069                 o = o->op_sibparent;
5070                 /* Normally skip all siblings and go straight to the parent;
5071                  * the only op that requires two children to be processed
5072                  * is OP_COND_EXPR */
5073                 if (!OpHAS_SIBLING(o)
5074                         && o->op_sibparent->op_type == OP_COND_EXPR)
5075                     break;
5076                 continue;
5077             }
5078             o = o->op_sibparent; /*try parent's next sibling */
5079         }
5080     } /* while */
5081 }
5082
5083
5084 STATIC OP *
5085 S_dup_attrlist(pTHX_ OP *o)
5086 {
5087     OP *rop;
5088
5089     PERL_ARGS_ASSERT_DUP_ATTRLIST;
5090
5091     /* An attrlist is either a simple OP_CONST or an OP_LIST with kids,
5092      * where the first kid is OP_PUSHMARK and the remaining ones
5093      * are OP_CONST.  We need to push the OP_CONST values.
5094      */
5095     if (o->op_type == OP_CONST)
5096         rop = newSVOP(OP_CONST, o->op_flags, SvREFCNT_inc_NN(cSVOPo->op_sv));
5097     else {
5098         assert((o->op_type == OP_LIST) && (o->op_flags & OPf_KIDS));
5099         rop = NULL;
5100         for (o = cLISTOPo->op_first; o; o = OpSIBLING(o)) {
5101             if (o->op_type == OP_CONST)
5102                 rop = op_append_elem(OP_LIST, rop,
5103                                   newSVOP(OP_CONST, o->op_flags,
5104                                           SvREFCNT_inc_NN(cSVOPo->op_sv)));
5105         }
5106     }
5107     return rop;
5108 }
5109
5110 STATIC void
5111 S_apply_attrs(pTHX_ HV *stash, SV *target, OP *attrs)
5112 {
5113     PERL_ARGS_ASSERT_APPLY_ATTRS;
5114     {
5115         SV * const stashsv = newSVhek(HvNAME_HEK(stash));
5116
5117         /* fake up C<use attributes $pkg,$rv,@attrs> */
5118
5119 #define ATTRSMODULE "attributes"
5120 #define ATTRSMODULE_PM "attributes.pm"
5121
5122         Perl_load_module(
5123           aTHX_ PERL_LOADMOD_IMPORT_OPS,
5124           newSVpvs(ATTRSMODULE),
5125           NULL,
5126           op_prepend_elem(OP_LIST,
5127                           newSVOP(OP_CONST, 0, stashsv),
5128                           op_prepend_elem(OP_LIST,
5129                                           newSVOP(OP_CONST, 0,
5130                                                   newRV(target)),
5131                                           dup_attrlist(attrs))));
5132     }
5133 }
5134
5135 STATIC void
5136 S_apply_attrs_my(pTHX_ HV *stash, OP *target, OP *attrs, OP **imopsp)
5137 {
5138     OP *pack, *imop, *arg;
5139     SV *meth, *stashsv, **svp;
5140
5141     PERL_ARGS_ASSERT_APPLY_ATTRS_MY;
5142
5143     if (!attrs)
5144         return;
5145
5146     assert(target->op_type == OP_PADSV ||
5147            target->op_type == OP_PADHV ||
5148            target->op_type == OP_PADAV);
5149
5150     /* Ensure that attributes.pm is loaded. */
5151     /* Don't force the C<use> if we don't need it. */
5152     svp = hv_fetchs(GvHVn(PL_incgv), ATTRSMODULE_PM, FALSE);
5153     if (svp && *svp != &PL_sv_undef)
5154         NOOP;   /* already in %INC */
5155     else
5156         Perl_load_module(aTHX_ PERL_LOADMOD_NOIMPORT,
5157                                newSVpvs(ATTRSMODULE), NULL);
5158
5159     /* Need package name for method call. */
5160     pack = newSVOP(OP_CONST, 0, newSVpvs(ATTRSMODULE));
5161
5162     /* Build up the real arg-list. */
5163     stashsv = newSVhek(HvNAME_HEK(stash));
5164
5165     arg = newOP(OP_PADSV, 0);
5166     arg->op_targ = target->op_targ;
5167     arg = op_prepend_elem(OP_LIST,
5168                        newSVOP(OP_CONST, 0, stashsv),
5169                        op_prepend_elem(OP_LIST,
5170                                     newUNOP(OP_REFGEN, 0,
5171                                             arg),
5172                                     dup_attrlist(attrs)));
5173
5174     /* Fake up a method call to import */
5175     meth = newSVpvs_share("import");
5176     imop = op_convert_list(OP_ENTERSUB, OPf_STACKED|OPf_SPECIAL|OPf_WANT_VOID,
5177                    op_append_elem(OP_LIST,
5178                                op_prepend_elem(OP_LIST, pack, arg),
5179                                newMETHOP_named(OP_METHOD_NAMED, 0, meth)));
5180
5181     /* Combine the ops. */
5182     *imopsp = op_append_elem(OP_LIST, *imopsp, imop);
5183 }
5184
5185 /*
5186 =notfor apidoc apply_attrs_string
5187
5188 Attempts to apply a list of attributes specified by the C<attrstr> and
5189 C<len> arguments to the subroutine identified by the C<cv> argument which
5190 is expected to be associated with the package identified by the C<stashpv>
5191 argument (see L<attributes>).  It gets this wrong, though, in that it
5192 does not correctly identify the boundaries of the individual attribute
5193 specifications within C<attrstr>.  This is not really intended for the
5194 public API, but has to be listed here for systems such as AIX which
5195 need an explicit export list for symbols.  (It's called from XS code
5196 in support of the C<ATTRS:> keyword from F<xsubpp>.)  Patches to fix it
5197 to respect attribute syntax properly would be welcome.
5198
5199 =cut
5200 */
5201
5202 void
5203 Perl_apply_attrs_string(pTHX_ const char *stashpv, CV *cv,
5204                         const char *attrstr, STRLEN len)
5205 {
5206     OP *attrs = NULL;
5207
5208     PERL_ARGS_ASSERT_APPLY_ATTRS_STRING;
5209
5210     if (!len) {
5211         len = strlen(attrstr);
5212     }
5213
5214     while (len) {
5215         for (; isSPACE(*attrstr) && len; --len, ++attrstr) ;
5216         if (len) {
5217             const char * const sstr = attrstr;
5218             for (; !isSPACE(*attrstr) && len; --len, ++attrstr) ;
5219             attrs = op_append_elem(OP_LIST, attrs,
5220                                 newSVOP(OP_CONST, 0,
5221                                         newSVpvn(sstr, attrstr-sstr)));
5222         }
5223     }
5224
5225     Perl_load_module(aTHX_ PERL_LOADMOD_IMPORT_OPS,
5226                      newSVpvs(ATTRSMODULE),
5227                      NULL, op_prepend_elem(OP_LIST,
5228                                   newSVOP(OP_CONST, 0, newSVpv(stashpv,0)),
5229                                   op_prepend_elem(OP_LIST,
5230                                                newSVOP(OP_CONST, 0,
5231                                                        newRV(MUTABLE_SV(cv))),
5232                                                attrs)));
5233 }
5234
5235 STATIC void
5236 S_move_proto_attr(pTHX_ OP **proto, OP **attrs, const GV * name,
5237                         bool curstash)
5238 {
5239     OP *new_proto = NULL;
5240     STRLEN pvlen;
5241     char *pv;
5242     OP *o;
5243
5244     PERL_ARGS_ASSERT_MOVE_PROTO_ATTR;
5245
5246     if (!*attrs)
5247         return;
5248
5249     o = *attrs;
5250     if (o->op_type == OP_CONST) {
5251         pv = SvPV(cSVOPo_sv, pvlen);
5252         if (memBEGINs(pv, pvlen, "prototype(")) {
5253             SV * const tmpsv = newSVpvn_flags(pv + 10, pvlen - 11, SvUTF8(cSVOPo_sv));
5254             SV ** const tmpo = cSVOPx_svp(o);
5255             SvREFCNT_dec(cSVOPo_sv);
5256             *tmpo = tmpsv;
5257             new_proto = o;
5258             *attrs = NULL;
5259         }
5260     } else if (o->op_type == OP_LIST) {
5261         OP * lasto;
5262         assert(o->op_flags & OPf_KIDS);
5263         lasto = cLISTOPo->op_first;
5264         assert(lasto->op_type == OP_PUSHMARK);
5265         for (o = OpSIBLING(lasto); o; o = OpSIBLING(o)) {
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                     if (new_proto && ckWARN(WARN_MISC)) {
5274                         STRLEN new_len;
5275                         const char * newp = SvPV(cSVOPo_sv, new_len);
5276                         Perl_warner(aTHX_ packWARN(WARN_MISC),
5277                             "Attribute prototype(%" UTF8f ") discards earlier prototype attribute in same sub",
5278                             UTF8fARG(SvUTF8(cSVOPo_sv), new_len, newp));
5279                         op_free(new_proto);
5280                     }
5281                     else if (new_proto)
5282                         op_free(new_proto);
5283                     new_proto = o;
5284                     /* excise new_proto from the list */
5285                     op_sibling_splice(*attrs, lasto, 1, NULL);
5286                     o = lasto;
5287                     continue;
5288                 }
5289             }
5290             lasto = o;
5291         }
5292         /* If the list is now just the PUSHMARK, scrap the whole thing; otherwise attributes.xs
5293            would get pulled in with no real need */
5294         if (!OpHAS_SIBLING(cLISTOPx(*attrs)->op_first)) {
5295             op_free(*attrs);
5296             *attrs = NULL;
5297         }
5298     }
5299
5300     if (new_proto) {
5301         SV *svname;
5302         if (isGV(name)) {
5303             svname = sv_newmortal();
5304             gv_efullname3(svname, name, NULL);
5305         }
5306         else if (SvPOK(name) && *SvPVX((SV *)name) == '&')
5307             svname = newSVpvn_flags(SvPVX((SV *)name)+1, SvCUR(name)-1, SvUTF8(name)|SVs_TEMP);
5308         else
5309             svname = (SV *)name;
5310         if (ckWARN(WARN_ILLEGALPROTO))
5311             (void)validate_proto(svname, cSVOPx_sv(new_proto), TRUE,
5312                                  curstash);
5313         if (*proto && ckWARN(WARN_PROTOTYPE)) {
5314             STRLEN old_len, new_len;
5315             const char * oldp = SvPV(cSVOPx_sv(*proto), old_len);
5316             const char * newp = SvPV(cSVOPx_sv(new_proto), new_len);
5317
5318             if (curstash && svname == (SV *)name
5319              && !memchr(SvPVX(svname), ':', SvCUR(svname))) {
5320                 svname = sv_2mortal(newSVsv(PL_curstname));
5321                 sv_catpvs(svname, "::");
5322                 sv_catsv(svname, (SV *)name);
5323             }
5324
5325             Perl_warner(aTHX_ packWARN(WARN_PROTOTYPE),
5326                 "Prototype '%" UTF8f "' overridden by attribute 'prototype(%" UTF8f ")'"
5327                 " in %" SVf,
5328                 UTF8fARG(SvUTF8(cSVOPx_sv(*proto)), old_len, oldp),
5329                 UTF8fARG(SvUTF8(cSVOPx_sv(new_proto)), new_len, newp),
5330                 SVfARG(svname));
5331         }
5332         if (*proto)
5333             op_free(*proto);
5334         *proto = new_proto;
5335     }
5336 }
5337
5338 static void
5339 S_cant_declare(pTHX_ OP *o)
5340 {
5341     if (o->op_type == OP_NULL
5342      && (o->op_flags & (OPf_SPECIAL|OPf_KIDS)) == OPf_KIDS)
5343         o = cUNOPo->op_first;
5344     yyerror(Perl_form(aTHX_ "Can't declare %s in \"%s\"",
5345                              o->op_type == OP_NULL
5346                                && o->op_flags & OPf_SPECIAL
5347                                  ? "do block"
5348                                  : OP_DESC(o),
5349                              PL_parser->in_my == KEY_our   ? "our"   :
5350                              PL_parser->in_my == KEY_state ? "state" :
5351                                                              "my"));
5352 }
5353
5354 STATIC OP *
5355 S_my_kid(pTHX_ OP *o, OP *attrs, OP **imopsp)
5356 {
5357     I32 type;
5358     const bool stately = PL_parser && PL_parser->in_my == KEY_state;
5359
5360     PERL_ARGS_ASSERT_MY_KID;
5361
5362     if (!o || (PL_parser && PL_parser->error_count))
5363         return o;
5364
5365     type = o->op_type;
5366
5367     if (OP_TYPE_IS_OR_WAS(o, OP_LIST)) {
5368         OP *kid;
5369         for (kid = cLISTOPo->op_first; kid; kid = OpSIBLING(kid))
5370             my_kid(kid, attrs, imopsp);
5371         return o;
5372     } else if (type == OP_UNDEF || type == OP_STUB) {
5373         return o;
5374     } else if (type == OP_RV2SV ||      /* "our" declaration */
5375                type == OP_RV2AV ||
5376                type == OP_RV2HV) {
5377         if (cUNOPo->op_first->op_type != OP_GV) { /* MJD 20011224 */
5378             S_cant_declare(aTHX_ o);
5379         } else if (attrs) {
5380             GV * const gv = cGVOPx_gv(cUNOPo->op_first);
5381             assert(PL_parser);
5382             PL_parser->in_my = FALSE;
5383             PL_parser->in_my_stash = NULL;
5384             apply_attrs(GvSTASH(gv),
5385                         (type == OP_RV2SV ? GvSVn(gv) :
5386                          type == OP_RV2AV ? MUTABLE_SV(GvAVn(gv)) :
5387                          type == OP_RV2HV ? MUTABLE_SV(GvHVn(gv)) : MUTABLE_SV(gv)),
5388                         attrs);
5389         }
5390         o->op_private |= OPpOUR_INTRO;
5391         return o;
5392     }
5393     else if (type == OP_REFGEN || type == OP_SREFGEN) {
5394         if (!FEATURE_MYREF_IS_ENABLED)
5395             Perl_croak(aTHX_ "The experimental declared_refs "
5396                              "feature is not enabled");
5397         Perl_ck_warner_d(aTHX_
5398              packWARN(WARN_EXPERIMENTAL__DECLARED_REFS),
5399             "Declaring references is experimental");
5400         /* Kid is a nulled OP_LIST, handled above.  */
5401         my_kid(cUNOPo->op_first, attrs, imopsp);
5402         return o;
5403     }
5404     else if (type != OP_PADSV &&
5405              type != OP_PADAV &&
5406              type != OP_PADHV &&
5407              type != OP_PUSHMARK)
5408     {
5409         S_cant_declare(aTHX_ o);
5410         return o;
5411     }
5412     else if (attrs && type != OP_PUSHMARK) {
5413         HV *stash;
5414
5415         assert(PL_parser);
5416         PL_parser->in_my = FALSE;
5417         PL_parser->in_my_stash = NULL;
5418
5419         /* check for C<my Dog $spot> when deciding package */
5420         stash = PAD_COMPNAME_TYPE(o->op_targ);
5421         if (!stash)
5422             stash = PL_curstash;
5423         apply_attrs_my(stash, o, attrs, imopsp);
5424     }
5425     o->op_flags |= OPf_MOD;
5426     o->op_private |= OPpLVAL_INTRO;
5427     if (stately)
5428         o->op_private |= OPpPAD_STATE;
5429     return o;
5430 }
5431
5432 OP *
5433 Perl_my_attrs(pTHX_ OP *o, OP *attrs)
5434 {
5435     OP *rops;
5436     int maybe_scalar = 0;
5437
5438     PERL_ARGS_ASSERT_MY_ATTRS;
5439
5440 /* [perl #17376]: this appears to be premature, and results in code such as
5441    C< our(%x); > executing in list mode rather than void mode */
5442 #if 0
5443     if (o->op_flags & OPf_PARENS)
5444         list(o);
5445     else
5446         maybe_scalar = 1;
5447 #else
5448     maybe_scalar = 1;
5449 #endif
5450     if (attrs)
5451         SAVEFREEOP(attrs);
5452     rops = NULL;
5453     o = my_kid(o, attrs, &rops);
5454     if (rops) {
5455         if (maybe_scalar && o->op_type == OP_PADSV) {
5456             o = scalar(op_append_list(OP_LIST, rops, o));
5457             o->op_private |= OPpLVAL_INTRO;
5458         }
5459         else {
5460             /* The listop in rops might have a pushmark at the beginning,
5461                which will mess up list assignment. */
5462             LISTOP * const lrops = (LISTOP *)rops; /* for brevity */
5463             if (rops->op_type == OP_LIST &&
5464                 lrops->op_first && lrops->op_first->op_type == OP_PUSHMARK)
5465             {
5466                 OP * const pushmark = lrops->op_first;
5467                 /* excise pushmark */
5468                 op_sibling_splice(rops, NULL, 1, NULL);
5469                 op_free(pushmark);
5470             }
5471             o = op_append_list(OP_LIST, o, rops);
5472         }
5473     }
5474     PL_parser->in_my = FALSE;
5475     PL_parser->in_my_stash = NULL;
5476     return o;
5477 }
5478
5479 OP *
5480 Perl_sawparens(pTHX_ OP *o)
5481 {
5482     PERL_UNUSED_CONTEXT;
5483     if (o)
5484         o->op_flags |= OPf_PARENS;
5485     return o;
5486 }
5487
5488 OP *
5489 Perl_bind_match(pTHX_ I32 type, OP *left, OP *right)
5490 {
5491     OP *o;
5492     bool ismatchop = 0;
5493     const OPCODE ltype = left->op_type;
5494     const OPCODE rtype = right->op_type;
5495
5496     PERL_ARGS_ASSERT_BIND_MATCH;
5497
5498     if ( (ltype == OP_RV2AV || ltype == OP_RV2HV || ltype == OP_PADAV
5499           || ltype == OP_PADHV) && ckWARN(WARN_MISC))
5500     {
5501       const char * const desc
5502           = PL_op_desc[(
5503                           rtype == OP_SUBST || rtype == OP_TRANS
5504                        || rtype == OP_TRANSR
5505                        )
5506                        ? (int)rtype : OP_MATCH];
5507       const bool isary = ltype == OP_RV2AV || ltype == OP_PADAV;
5508       SV * const name =
5509         S_op_varname(aTHX_ left);
5510       if (name)
5511         Perl_warner(aTHX_ packWARN(WARN_MISC),
5512              "Applying %s to %" SVf " will act on scalar(%" SVf ")",
5513              desc, SVfARG(name), SVfARG(name));
5514       else {
5515         const char * const sample = (isary
5516              ? "@array" : "%hash");
5517         Perl_warner(aTHX_ packWARN(WARN_MISC),
5518              "Applying %s to %s will act on scalar(%s)",
5519              desc, sample, sample);
5520       }
5521     }
5522
5523     if (rtype == OP_CONST &&
5524         cSVOPx(right)->op_private & OPpCONST_BARE &&
5525         cSVOPx(right)->op_private & OPpCONST_STRICT)
5526     {
5527         no_bareword_allowed(right);
5528     }
5529
5530     /* !~ doesn't make sense with /r, so error on it for now */
5531     if (rtype == OP_SUBST && (cPMOPx(right)->op_pmflags & PMf_NONDESTRUCT) &&
5532         type == OP_NOT)
5533         /* diag_listed_as: Using !~ with %s doesn't make sense */
5534         yyerror("Using !~ with s///r doesn't make sense");
5535     if (rtype == OP_TRANSR && type == OP_NOT)
5536         /* diag_listed_as: Using !~ with %s doesn't make sense */
5537         yyerror("Using !~ with tr///r doesn't make sense");
5538
5539     ismatchop = (rtype == OP_MATCH ||
5540                  rtype == OP_SUBST ||
5541                  rtype == OP_TRANS || rtype == OP_TRANSR)
5542              && !(right->op_flags & OPf_SPECIAL);
5543     if (ismatchop && right->op_private & OPpTARGET_MY) {
5544         right->op_targ = 0;
5545         right->op_private &= ~OPpTARGET_MY;
5546     }
5547     if (!(right->op_flags & OPf_STACKED) && !right->op_targ && ismatchop) {
5548         if (left->op_type == OP_PADSV
5549          && !(left->op_private & OPpLVAL_INTRO))
5550         {
5551             right->op_targ = left->op_targ;
5552             op_free(left);
5553             o = right;
5554         }
5555         else {
5556             right->op_flags |= OPf_STACKED;
5557             if (rtype != OP_MATCH && rtype != OP_TRANSR &&
5558             ! (rtype == OP_TRANS &&
5559                right->op_private & OPpTRANS_IDENTICAL) &&
5560             ! (rtype == OP_SUBST &&
5561                (cPMOPx(right)->op_pmflags & PMf_NONDESTRUCT)))
5562                 left = op_lvalue(left, rtype);
5563             if (right->op_type == OP_TRANS || right->op_type == OP_TRANSR)
5564                 o = newBINOP(OP_NULL, OPf_STACKED, scalar(left), right);
5565             else
5566                 o = op_prepend_elem(rtype, scalar(left), right);
5567         }
5568         if (type == OP_NOT)
5569             return newUNOP(OP_NOT, 0, scalar(o));
5570         return o;
5571     }
5572     else
5573         return bind_match(type, left,
5574                 pmruntime(newPMOP(OP_MATCH, 0), right, NULL, 0, 0));
5575 }
5576
5577 OP *
5578 Perl_invert(pTHX_ OP *o)
5579 {
5580     if (!o)
5581         return NULL;
5582     return newUNOP(OP_NOT, OPf_SPECIAL, scalar(o));
5583 }
5584
5585 OP *
5586 Perl_cmpchain_start(pTHX_ I32 type, OP *left, OP *right)
5587 {
5588     BINOP *bop;
5589     OP *op;
5590
5591     if (!left)
5592         left = newOP(OP_NULL, 0);
5593     if (!right)
5594         right = newOP(OP_NULL, 0);
5595     scalar(left);
5596     scalar(right);
5597     NewOp(0, bop, 1, BINOP);
5598     op = (OP*)bop;
5599     ASSUME((PL_opargs[type] & OA_CLASS_MASK) == OA_BINOP);
5600     OpTYPE_set(op, type);
5601     cBINOPx(op)->op_flags = OPf_KIDS;
5602     cBINOPx(op)->op_private = 2;
5603     cBINOPx(op)->op_first = left;
5604     cBINOPx(op)->op_last = right;
5605     OpMORESIB_set(left, right);
5606     OpLASTSIB_set(right, op);
5607     return op;
5608 }
5609
5610 OP *
5611 Perl_cmpchain_extend(pTHX_ I32 type, OP *ch, OP *right)
5612 {
5613     BINOP *bop;
5614     OP *op;
5615
5616     PERL_ARGS_ASSERT_CMPCHAIN_EXTEND;
5617     if (!right)
5618         right = newOP(OP_NULL, 0);
5619     scalar(right);
5620     NewOp(0, bop, 1, BINOP);
5621     op = (OP*)bop;
5622     ASSUME((PL_opargs[type] & OA_CLASS_MASK) == OA_BINOP);
5623     OpTYPE_set(op, type);
5624     if (ch->op_type != OP_NULL) {
5625         UNOP *lch;
5626         OP *nch, *cleft, *cright;
5627         NewOp(0, lch, 1, UNOP);
5628         nch = (OP*)lch;
5629         OpTYPE_set(nch, OP_NULL);
5630         nch->op_flags = OPf_KIDS;
5631         cleft = cBINOPx(ch)->op_first;
5632         cright = cBINOPx(ch)->op_last;
5633         cBINOPx(ch)->op_first = NULL;
5634         cBINOPx(ch)->op_last = NULL;
5635         cBINOPx(ch)->op_private = 0;
5636         cBINOPx(ch)->op_flags = 0;
5637         cUNOPx(nch)->op_first = cright;
5638         OpMORESIB_set(cright, ch);
5639         OpMORESIB_set(ch, cleft);
5640         OpLASTSIB_set(cleft, nch);
5641         ch = nch;
5642     }
5643     OpMORESIB_set(right, op);
5644     OpMORESIB_set(op, cUNOPx(ch)->op_first);
5645     cUNOPx(ch)->op_first = right;
5646     return ch;
5647 }
5648
5649 OP *
5650 Perl_cmpchain_finish(pTHX_ OP *ch)
5651 {
5652
5653     PERL_ARGS_ASSERT_CMPCHAIN_FINISH;
5654     if (ch->op_type != OP_NULL) {
5655         OPCODE cmpoptype = ch->op_type;
5656         ch = CHECKOP(cmpoptype, ch);
5657         if(!ch->op_next && ch->op_type == cmpoptype)
5658             ch = fold_constants(op_integerize(op_std_init(ch)));
5659         return ch;
5660     } else {
5661         OP *condop = NULL;
5662         OP *rightarg = cUNOPx(ch)->op_first;
5663         cUNOPx(ch)->op_first = OpSIBLING(rightarg);
5664         OpLASTSIB_set(rightarg, NULL);
5665         while (1) {
5666             OP *cmpop = cUNOPx(ch)->op_first;
5667             OP *leftarg = OpSIBLING(cmpop);
5668             OPCODE cmpoptype = cmpop->op_type;
5669             OP *nextrightarg;
5670             bool is_last;
5671             is_last = !(cUNOPx(ch)->op_first = OpSIBLING(leftarg));
5672             OpLASTSIB_set(cmpop, NULL);
5673             OpLASTSIB_set(leftarg, NULL);
5674             if (is_last) {
5675                 ch->op_flags = 0;
5676                 op_free(ch);
5677                 nextrightarg = NULL;
5678             } else {
5679                 nextrightarg = newUNOP(OP_CMPCHAIN_DUP, 0, leftarg);
5680                 leftarg = newOP(OP_NULL, 0);
5681             }
5682             cBINOPx(cmpop)->op_first = leftarg;
5683             cBINOPx(cmpop)->op_last = rightarg;
5684             OpMORESIB_set(leftarg, rightarg);
5685             OpLASTSIB_set(rightarg, cmpop);
5686             cmpop->op_flags = OPf_KIDS;
5687             cmpop->op_private = 2;
5688             cmpop = CHECKOP(cmpoptype, cmpop);
5689             if(!cmpop->op_next && cmpop->op_type == cmpoptype)
5690                 cmpop = op_integerize(op_std_init(cmpop));
5691             condop = condop ? newLOGOP(OP_CMPCHAIN_AND, 0, cmpop, condop) :
5692                         cmpop;
5693             if (!nextrightarg)
5694                 return condop;
5695             rightarg = nextrightarg;
5696         }
5697     }
5698 }
5699
5700 /*
5701 =for apidoc op_scope
5702
5703 Wraps up an op tree with some additional ops so that at runtime a dynamic
5704 scope will be created.  The original ops run in the new dynamic scope,
5705 and then, provided that they exit normally, the scope will be unwound.
5706 The additional ops used to create and unwind the dynamic scope will
5707 normally be an C<enter>/C<leave> pair, but a C<scope> op may be used
5708 instead if the ops are simple enough to not need the full dynamic scope
5709 structure.
5710
5711 =cut
5712 */
5713
5714 OP *
5715 Perl_op_scope(pTHX_ OP *o)
5716 {
5717     if (o) {
5718         if (o->op_flags & OPf_PARENS || PERLDB_NOOPT || TAINTING_get) {
5719             o = op_prepend_elem(OP_LINESEQ,
5720                     newOP(OP_ENTER, (o->op_flags & OPf_WANT)), o);
5721             OpTYPE_set(o, OP_LEAVE);
5722         }
5723         else if (o->op_type == OP_LINESEQ) {
5724             OP *kid;
5725             OpTYPE_set(o, OP_SCOPE);
5726             kid = ((LISTOP*)o)->op_first;
5727             if (kid->op_type == OP_NEXTSTATE || kid->op_type == OP_DBSTATE) {
5728                 op_null(kid);
5729
5730                 /* The following deals with things like 'do {1 for 1}' */
5731                 kid = OpSIBLING(kid);
5732                 if (kid &&
5733                     (kid->op_type == OP_NEXTSTATE || kid->op_type == OP_DBSTATE))
5734                     op_null(kid);
5735             }
5736         }
5737         else
5738             o = newLISTOP(OP_SCOPE, 0, o, NULL);
5739     }
5740     return o;
5741 }
5742
5743 OP *
5744 Perl_op_unscope(pTHX_ OP *o)
5745 {
5746     if (o && o->op_type == OP_LINESEQ) {
5747         OP *kid = cLISTOPo->op_first;
5748         for(; kid; kid = OpSIBLING(kid))
5749             if (kid->op_type == OP_NEXTSTATE || kid->op_type == OP_DBSTATE)
5750                 op_null(kid);
5751     }
5752     return o;
5753 }
5754
5755 /*
5756 =for apidoc block_start
5757
5758 Handles compile-time scope entry.
5759 Arranges for hints to be restored on block
5760 exit and also handles pad sequence numbers to make lexical variables scope
5761 right.  Returns a savestack index for use with C<block_end>.
5762
5763 =cut
5764 */
5765
5766 int
5767 Perl_block_start(pTHX_ int full)
5768 {
5769     const int retval = PL_savestack_ix;
5770
5771     PL_compiling.cop_seq = PL_cop_seqmax;
5772     COP_SEQMAX_INC;
5773     pad_block_start(full);
5774     SAVEHINTS();
5775     PL_hints &= ~HINT_BLOCK_SCOPE;
5776     SAVECOMPILEWARNINGS();
5777     PL_compiling.cop_warnings = DUP_WARNINGS(PL_compiling.cop_warnings);
5778     SAVEI32(PL_compiling.cop_seq);
5779     PL_compiling.cop_seq = 0;
5780
5781     CALL_BLOCK_HOOKS(bhk_start, full);
5782
5783     return retval;
5784 }
5785
5786 /*
5787 =for apidoc block_end
5788
5789 Handles compile-time scope exit.  C<floor>
5790 is the savestack index returned by
5791 C<block_start>, and C<seq> is the body of the block.  Returns the block,
5792 possibly modified.
5793
5794 =cut
5795 */
5796
5797 OP*
5798 Perl_block_end(pTHX_ I32 floor, OP *seq)
5799 {
5800     const int needblockscope = PL_hints & HINT_BLOCK_SCOPE;
5801     OP* retval = voidnonfinal(seq);
5802     OP *o;
5803
5804     /* XXX Is the null PL_parser check necessary here? */
5805     assert(PL_parser); /* Let’s find out under debugging builds.  */
5806     if (PL_parser && PL_parser->parsed_sub) {
5807         o = newSTATEOP(0, NULL, NULL);
5808         op_null(o);
5809         retval = op_append_elem(OP_LINESEQ, retval, o);
5810     }
5811
5812     CALL_BLOCK_HOOKS(bhk_pre_end, &retval);
5813
5814     LEAVE_SCOPE(floor);
5815     if (needblockscope)
5816         PL_hints |= HINT_BLOCK_SCOPE; /* propagate out */
5817     o = pad_leavemy();
5818
5819     if (o) {
5820         /* pad_leavemy has created a sequence of introcv ops for all my
5821            subs declared in the block.  We have to replicate that list with
5822            clonecv ops, to deal with this situation:
5823
5824                sub {
5825                    my sub s1;
5826                    my sub s2;
5827                    sub s1 { state sub foo { \&s2 } }
5828                }->()
5829
5830            Originally, I was going to have introcv clone the CV and turn
5831            off the stale flag.  Since &s1 is declared before &s2, the
5832            introcv op for &s1 is executed (on sub entry) before the one for
5833            &s2.  But the &foo sub inside &s1 (which is cloned when &s1 is
5834            cloned, since it is a state sub) closes over &s2 and expects
5835            to see it in its outer CV’s pad.  If the introcv op clones &s1,
5836            then &s2 is still marked stale.  Since &s1 is not active, and
5837            &foo closes over &s1’s implicit entry for &s2, we get a â€˜Varia-
5838            ble will not stay shared’ warning.  Because it is the same stub
5839            that will be used when the introcv op for &s2 is executed, clos-
5840            ing over it is safe.  Hence, we have to turn off the stale flag
5841            on all lexical subs in the block before we clone any of them.
5842            Hence, having introcv clone the sub cannot work.  So we create a
5843            list of ops like this:
5844
5845                lineseq
5846                   |
5847                   +-- introcv
5848                   |
5849                   +-- introcv
5850                   |
5851                   +-- introcv
5852                   |
5853                   .
5854                   .
5855                   .
5856                   |
5857                   +-- clonecv
5858                   |
5859                   +-- clonecv
5860                   |
5861                   +-- clonecv
5862                   |
5863                   .
5864                   .
5865                   .
5866          */
5867         OP *kid = o->op_flags & OPf_KIDS ? cLISTOPo->op_first : o;
5868         OP * const last = o->op_flags & OPf_KIDS ? cLISTOPo->op_last : o;
5869         for (;; kid = OpSIBLING(kid)) {
5870             OP *newkid = newOP(OP_CLONECV, 0);
5871             newkid->op_targ = kid->op_targ;
5872             o = op_append_elem(OP_LINESEQ, o, newkid);
5873             if (kid == last) break;
5874         }
5875         retval = op_prepend_elem(OP_LINESEQ, o, retval);
5876     }
5877
5878     CALL_BLOCK_HOOKS(bhk_post_end, &retval);
5879
5880     return retval;
5881 }
5882
5883 /*
5884 =for apidoc_section $scope
5885
5886 =for apidoc blockhook_register
5887
5888 Register a set of hooks to be called when the Perl lexical scope changes
5889 at compile time.  See L<perlguts/"Compile-time scope hooks">.
5890
5891 =cut
5892 */
5893
5894 void
5895 Perl_blockhook_register(pTHX_ BHK *hk)
5896 {
5897     PERL_ARGS_ASSERT_BLOCKHOOK_REGISTER;
5898
5899     Perl_av_create_and_push(aTHX_ &PL_blockhooks, newSViv(PTR2IV(hk)));
5900 }
5901
5902 void
5903 Perl_newPROG(pTHX_ OP *o)
5904 {
5905     OP *start;
5906
5907     PERL_ARGS_ASSERT_NEWPROG;
5908
5909     if (PL_in_eval) {
5910         PERL_CONTEXT *cx;
5911         I32 i;
5912         if (PL_eval_root)
5913                 return;
5914         PL_eval_root = newUNOP(OP_LEAVEEVAL,
5915                                ((PL_in_eval & EVAL_KEEPERR)
5916                                 ? OPf_SPECIAL : 0), o);
5917
5918         cx = CX_CUR();
5919         assert(CxTYPE(cx) == CXt_EVAL);
5920
5921         if ((cx->blk_gimme & G_WANT) == G_VOID)
5922             scalarvoid(PL_eval_root);
5923         else if ((cx->blk_gimme & G_WANT) == G_LIST)
5924             list(PL_eval_root);
5925         else
5926             scalar(PL_eval_root);
5927
5928         start = op_linklist(PL_eval_root);
5929         PL_eval_root->op_next = 0;
5930         i = PL_savestack_ix;
5931         SAVEFREEOP(o);
5932         ENTER;
5933         S_process_optree(aTHX_ NULL, PL_eval_root, start);
5934         LEAVE;
5935         PL_savestack_ix = i;
5936     }
5937     else {
5938         if (o->op_type == OP_STUB) {
5939             /* This block is entered if nothing is compiled for the main
5940                program. This will be the case for an genuinely empty main
5941                program, or one which only has BEGIN blocks etc, so already
5942                run and freed.
5943
5944                Historically (5.000) the guard above was !o. However, commit
5945                f8a08f7b8bd67b28 (Jun 2001), integrated to blead as
5946                c71fccf11fde0068, changed perly.y so that newPROG() is now
5947                called with the output of block_end(), which returns a new
5948                OP_STUB for the case of an empty optree. ByteLoader (and
5949                maybe other things) also take this path, because they set up
5950                PL_main_start and PL_main_root directly, without generating an
5951                optree.
5952
5953                If the parsing the main program aborts (due to parse errors,
5954                or due to BEGIN or similar calling exit), then newPROG()
5955                isn't even called, and hence this code path and its cleanups
5956                are skipped. This shouldn't make a make a difference:
5957                * a non-zero return from perl_parse is a failure, and
5958                  perl_destruct() should be called immediately.
5959                * however, if exit(0) is called during the parse, then
5960                  perl_parse() returns 0, and perl_run() is called. As
5961                  PL_main_start will be NULL, perl_run() will return
5962                  promptly, and the exit code will remain 0.
5963             */
5964
5965             PL_comppad_name = 0;
5966             PL_compcv = 0;
5967             S_op_destroy(aTHX_ o);
5968             return;
5969         }
5970         PL_main_root = op_scope(sawparens(scalarvoid(o)));
5971         PL_curcop = &PL_compiling;
5972         start = LINKLIST(PL_main_root);
5973         PL_main_root->op_next = 0;
5974         S_process_optree(aTHX_ NULL, PL_main_root, start);
5975         if (!PL_parser->error_count)
5976             /* on error, leave CV slabbed so that ops left lying around
5977              * will eb cleaned up. Else unslab */
5978             cv_forget_slab(PL_compcv);
5979         PL_compcv = 0;
5980
5981         /* Register with debugger */
5982         if (PERLDB_INTER) {
5983             CV * const cv = get_cvs("DB::postponed", 0);
5984             if (cv) {
5985                 dSP;
5986                 PUSHMARK(SP);
5987                 XPUSHs(MUTABLE_SV(CopFILEGV(&PL_compiling)));
5988                 PUTBACK;
5989                 call_sv(MUTABLE_SV(cv), G_DISCARD);
5990             }
5991         }
5992     }
5993 }
5994
5995 OP *
5996 Perl_localize(pTHX_ OP *o, I32 lex)
5997 {
5998     PERL_ARGS_ASSERT_LOCALIZE;
5999
6000     if (o->op_flags & OPf_PARENS)
6001 /* [perl #17376]: this appears to be premature, and results in code such as
6002    C< our(%x); > executing in list mode rather than void mode */
6003 #if 0
6004         list(o);
6005 #else
6006         NOOP;
6007 #endif
6008     else {
6009         if ( PL_parser->bufptr > PL_parser->oldbufptr
6010             && PL_parser->bufptr[-1] == ','
6011             && ckWARN(WARN_PARENTHESIS))
6012         {
6013             char *s = PL_parser->bufptr;
6014             bool sigil = FALSE;
6015
6016             /* some heuristics to detect a potential error */
6017             while (*s && (memCHRs(", \t\n", *s)))
6018                 s++;
6019
6020             while (1) {
6021                 if (*s && (memCHRs("@$%", *s) || (!lex && *s == '*'))
6022                        && *++s
6023                        && (isWORDCHAR(*s) || UTF8_IS_CONTINUED(*s))) {
6024                     s++;
6025                     sigil = TRUE;
6026                     while (*s && (isWORDCHAR(*s) || UTF8_IS_CONTINUED(*s)))
6027                         s++;
6028                     while (*s && (memCHRs(", \t\n", *s)))
6029                         s++;
6030                 }
6031                 else
6032                     break;
6033             }
6034             if (sigil && (*s == ';' || *s == '=')) {
6035                 Perl_warner(aTHX_ packWARN(WARN_PARENTHESIS),
6036                                 "Parentheses missing around \"%s\" list",
6037                                 lex
6038                                     ? (PL_parser->in_my == KEY_our
6039                                         ? "our"
6040                                         : PL_parser->in_my == KEY_state
6041                                             ? "state"
6042                                             : "my")
6043                                     : "local");
6044             }
6045         }
6046     }
6047     if (lex)
6048         o = my(o);
6049     else
6050         o = op_lvalue(o, OP_NULL);              /* a bit kludgey */
6051     PL_parser->in_my = FALSE;
6052     PL_parser->in_my_stash = NULL;
6053     return o;
6054 }
6055
6056 OP *
6057 Perl_jmaybe(pTHX_ OP *o)
6058 {
6059     PERL_ARGS_ASSERT_JMAYBE;
6060
6061     if (o->op_type == OP_LIST) {
6062         if (FEATURE_MULTIDIMENSIONAL_IS_ENABLED) {
6063             OP * const o2
6064                 = newSVREF(newGVOP(OP_GV, 0, gv_fetchpvs(";", GV_ADD|GV_NOTQUAL, SVt_PV)));
6065             o = op_convert_list(OP_JOIN, 0, op_prepend_elem(OP_LIST, o2, o));
6066         }
6067         else {
6068             /* If the user disables this, then a warning might not be enough to alert
6069                them to a possible change of behaviour here, so throw an exception.
6070             */
6071             yyerror("Multidimensional hash lookup is disabled");
6072         }
6073     }
6074     return o;
6075 }
6076
6077 PERL_STATIC_INLINE OP *
6078 S_op_std_init(pTHX_ OP *o)
6079 {
6080     I32 type = o->op_type;
6081
6082     PERL_ARGS_ASSERT_OP_STD_INIT;
6083
6084     if (PL_opargs[type] & OA_RETSCALAR)
6085         scalar(o);
6086     if (PL_opargs[type] & OA_TARGET && !o->op_targ)
6087         o->op_targ = pad_alloc(type, SVs_PADTMP);
6088
6089     return o;
6090 }
6091
6092 PERL_STATIC_INLINE OP *
6093 S_op_integerize(pTHX_ OP *o)
6094 {
6095     I32 type = o->op_type;
6096
6097     PERL_ARGS_ASSERT_OP_INTEGERIZE;
6098
6099     /* integerize op. */
6100     if ((PL_opargs[type] & OA_OTHERINT) && (PL_hints & HINT_INTEGER))
6101     {
6102         o->op_ppaddr = PL_ppaddr[++(o->op_type)];
6103     }
6104
6105     if (type == OP_NEGATE)
6106         /* XXX might want a ck_negate() for this */
6107         cUNOPo->op_first->op_private &= ~OPpCONST_STRICT;
6108
6109     return o;
6110 }
6111
6112 /* This function exists solely to provide a scope to limit
6113    setjmp/longjmp() messing with auto variables.  It cannot be inlined because
6114    it uses setjmp
6115  */
6116 STATIC int
6117 S_fold_constants_eval(pTHX) {
6118     int ret = 0;
6119     dJMPENV;
6120
6121     JMPENV_PUSH(ret);
6122
6123     if (ret == 0) {
6124         CALLRUNOPS(aTHX);
6125     }
6126
6127     JMPENV_POP;
6128
6129     return ret;
6130 }
6131
6132 static OP *
6133 S_fold_constants(pTHX_ OP *const o)
6134 {
6135     OP *curop;
6136     OP *newop;
6137     I32 type = o->op_type;
6138     bool is_stringify;
6139     SV *sv = NULL;
6140     int ret = 0;
6141     OP *old_next;
6142     SV * const oldwarnhook = PL_warnhook;
6143     SV * const olddiehook  = PL_diehook;
6144     COP not_compiling;
6145     U8 oldwarn = PL_dowarn;
6146     I32 old_cxix;
6147
6148     PERL_ARGS_ASSERT_FOLD_CONSTANTS;
6149
6150     if (!(PL_opargs[type] & OA_FOLDCONST))
6151         goto nope;
6152
6153     switch (type) {
6154     case OP_UCFIRST:
6155     case OP_LCFIRST:
6156     case OP_UC:
6157     case OP_LC:
6158     case OP_FC:
6159 #ifdef USE_LOCALE_CTYPE
6160         if (IN_LC_COMPILETIME(LC_CTYPE))
6161             goto nope;
6162 #endif
6163         break;
6164     case OP_SLT:
6165     case OP_SGT:
6166     case OP_SLE:
6167     case OP_SGE:
6168     case OP_SCMP:
6169 #ifdef USE_LOCALE_COLLATE
6170         if (IN_LC_COMPILETIME(LC_COLLATE))
6171             goto nope;
6172 #endif
6173         break;
6174     case OP_SPRINTF:
6175         /* XXX what about the numeric ops? */
6176 #ifdef USE_LOCALE_NUMERIC
6177         if (IN_LC_COMPILETIME(LC_NUMERIC))
6178             goto nope;
6179 #endif
6180         break;
6181     case OP_PACK:
6182         if (!OpHAS_SIBLING(cLISTOPo->op_first)
6183           || OpSIBLING(cLISTOPo->op_first)->op_type != OP_CONST)
6184             goto nope;
6185         {
6186             SV * const sv = cSVOPx_sv(OpSIBLING(cLISTOPo->op_first));
6187             if (!SvPOK(sv) || SvGMAGICAL(sv)) goto nope;
6188             {
6189                 const char *s = SvPVX_const(sv);
6190                 while (s < SvEND(sv)) {
6191                     if (isALPHA_FOLD_EQ(*s, 'p')) goto nope;
6192                     s++;
6193                 }
6194             }
6195         }
6196         break;
6197     case OP_REPEAT:
6198         if (o->op_private & OPpREPEAT_DOLIST) goto nope;
6199         break;
6200     case OP_SREFGEN:
6201         if (cUNOPx(cUNOPo->op_first)->op_first->op_type != OP_CONST
6202          || SvPADTMP(cSVOPx_sv(cUNOPx(cUNOPo->op_first)->op_first)))
6203             goto nope;
6204     }
6205
6206     if (PL_parser && PL_parser->error_count)
6207         goto nope;              /* Don't try to run w/ errors */
6208
6209     for (curop = LINKLIST(o); curop != o; curop = LINKLIST(curop)) {
6210         switch (curop->op_type) {
6211         case OP_CONST:
6212             if (   (curop->op_private & OPpCONST_BARE)
6213                 && (curop->op_private & OPpCONST_STRICT)) {
6214                 no_bareword_allowed(curop);
6215                 goto nope;
6216             }
6217             /* FALLTHROUGH */
6218         case OP_LIST:
6219         case OP_SCALAR:
6220         case OP_NULL:
6221         case OP_PUSHMARK:
6222             /* Foldable; move to next op in list */
6223             break;
6224
6225         default:
6226             /* No other op types are considered foldable */
6227             goto nope;
6228         }
6229     }
6230
6231     curop = LINKLIST(o);
6232     old_next = o->op_next;
6233     o->op_next = 0;
6234     PL_op = curop;
6235
6236     old_cxix = cxstack_ix;
6237     create_eval_scope(NULL, G_FAKINGEVAL);
6238
6239     /* Verify that we don't need to save it:  */
6240     assert(PL_curcop == &PL_compiling);
6241     StructCopy(&PL_compiling, &not_compiling, COP);
6242     PL_curcop = &not_compiling;
6243     /* The above ensures that we run with all the correct hints of the
6244        currently compiling COP, but that IN_PERL_RUNTIME is true. */
6245     assert(IN_PERL_RUNTIME);
6246     PL_warnhook = PERL_WARNHOOK_FATAL;
6247     PL_diehook  = NULL;
6248
6249     /* Effective $^W=1.  */
6250     if ( ! (PL_dowarn & G_WARN_ALL_MASK))
6251         PL_dowarn |= G_WARN_ON;
6252
6253     ret = S_fold_constants_eval(aTHX);
6254
6255     switch (ret) {
6256     case 0:
6257         sv = *(PL_stack_sp--);
6258         if (o->op_targ && sv == PAD_SV(o->op_targ)) {   /* grab pad temp? */
6259             pad_swipe(o->op_targ,  FALSE);
6260         }
6261         else if (SvTEMP(sv)) {                  /* grab mortal temp? */
6262             SvREFCNT_inc_simple_void(sv);
6263             SvTEMP_off(sv);
6264         }
6265         else { assert(SvIMMORTAL(sv)); }
6266         break;
6267     case 3:
6268         /* Something tried to die.  Abandon constant folding.  */
6269         /* Pretend the error never happened.  */
6270         CLEAR_ERRSV();
6271         o->op_next = old_next;
6272         break;
6273     default:
6274         /* Don't expect 1 (setjmp failed) or 2 (something called my_exit)  */
6275         PL_warnhook = oldwarnhook;
6276         PL_diehook  = olddiehook;
6277         /* XXX note that this croak may fail as we've already blown away
6278          * the stack - eg any nested evals */
6279         Perl_croak(aTHX_ "panic: fold_constants JMPENV_PUSH returned %d", ret);
6280     }
6281     PL_dowarn   = oldwarn;
6282     PL_warnhook = oldwarnhook;
6283     PL_diehook  = olddiehook;
6284     PL_curcop = &PL_compiling;
6285
6286     /* if we croaked, depending on how we croaked the eval scope
6287      * may or may not have already been popped */
6288     if (cxstack_ix > old_cxix) {
6289         assert(cxstack_ix == old_cxix + 1);
6290         assert(CxTYPE(CX_CUR()) == CXt_EVAL);
6291         delete_eval_scope();
6292     }
6293     if (ret)
6294         goto nope;
6295
6296     /* OP_STRINGIFY and constant folding are used to implement qq.
6297        Here the constant folding is an implementation detail that we
6298        want to hide.  If the stringify op is itself already marked
6299        folded, however, then it is actually a folded join.  */
6300     is_stringify = type == OP_STRINGIFY && !o->op_folded;
6301     op_free(o);
6302     assert(sv);
6303     if (is_stringify)
6304         SvPADTMP_off(sv);
6305     else if (!SvIMMORTAL(sv)) {
6306         SvPADTMP_on(sv);
6307         SvREADONLY_on(sv);
6308     }
6309     newop = newSVOP(OP_CONST, 0, MUTABLE_SV(sv));
6310     if (!is_stringify) newop->op_folded = 1;
6311     return newop;
6312
6313  nope:
6314     return o;
6315 }
6316
6317 /* convert a constant range in list context into an OP_RV2AV, OP_CONST pair;
6318  * the constant value being an AV holding the flattened range.
6319  */
6320
6321 static void
6322 S_gen_constant_list(pTHX_ OP *o)
6323 {
6324     OP *curop, *old_next;
6325     SV * const oldwarnhook = PL_warnhook;
6326     SV * const olddiehook  = PL_diehook;
6327     COP *old_curcop;
6328     U8 oldwarn = PL_dowarn;
6329     SV **svp;
6330     AV *av;
6331     I32 old_cxix;
6332     COP not_compiling;
6333     int ret = 0;
6334     dJMPENV;
6335     bool op_was_null;
6336
6337     list(o);
6338     if (PL_parser && PL_parser->error_count)
6339         return;         /* Don't attempt to run with errors */
6340
6341     curop = LINKLIST(o);
6342     old_next = o->op_next;
6343     o->op_next = 0;
6344     op_was_null = o->op_type == OP_NULL;
6345     if (op_was_null) /* b3698342565fb462291fba4b432cfcd05b6eb4e1 */
6346         o->op_type = OP_CUSTOM;
6347     CALL_PEEP(curop);
6348     if (op_was_null)
6349         o->op_type = OP_NULL;
6350     S_prune_chain_head(&curop);
6351     PL_op = curop;
6352
6353     old_cxix = cxstack_ix;
6354     create_eval_scope(NULL, G_FAKINGEVAL);
6355
6356     old_curcop = PL_curcop;
6357     StructCopy(old_curcop, &not_compiling, COP);
6358     PL_curcop = &not_compiling;
6359     /* The above ensures that we run with all the correct hints of the
6360        current COP, but that IN_PERL_RUNTIME is true. */
6361     assert(IN_PERL_RUNTIME);
6362     PL_warnhook = PERL_WARNHOOK_FATAL;
6363     PL_diehook  = NULL;
6364     JMPENV_PUSH(ret);
6365
6366     /* Effective $^W=1.  */
6367     if ( ! (PL_dowarn & G_WARN_ALL_MASK))
6368         PL_dowarn |= G_WARN_ON;
6369
6370     switch (ret) {
6371     case 0:
6372 #if defined DEBUGGING && !defined DEBUGGING_RE_ONLY
6373         PL_curstackinfo->si_stack_hwm = 0; /* stop valgrind complaining */
6374 #endif
6375         Perl_pp_pushmark(aTHX);
6376         CALLRUNOPS(aTHX);
6377         PL_op = curop;
6378         assert (!(curop->op_flags & OPf_SPECIAL));
6379         assert(curop->op_type == OP_RANGE);
6380         Perl_pp_anonlist(aTHX);
6381         break;
6382     case 3:
6383         CLEAR_ERRSV();
6384         o->op_next = old_next;
6385         break;
6386     default:
6387         JMPENV_POP;
6388         PL_warnhook = oldwarnhook;
6389         PL_diehook = olddiehook;
6390         Perl_croak(aTHX_ "panic: gen_constant_list JMPENV_PUSH returned %d",
6391             ret);
6392     }
6393
6394     JMPENV_POP;
6395     PL_dowarn = oldwarn;
6396     PL_warnhook = oldwarnhook;
6397     PL_diehook = olddiehook;
6398     PL_curcop = old_curcop;
6399
6400     if (cxstack_ix > old_cxix) {
6401         assert(cxstack_ix == old_cxix + 1);
6402         assert(CxTYPE(CX_CUR()) == CXt_EVAL);
6403         delete_eval_scope();
6404     }
6405     if (ret)
6406         return;
6407
6408     OpTYPE_set(o, OP_RV2AV);
6409     o->op_flags &= ~OPf_REF;    /* treat \(1..2) like an ordinary list */
6410     o->op_flags |= OPf_PARENS;  /* and flatten \(1..2,3) */
6411     o->op_opt = 0;              /* needs to be revisited in rpeep() */
6412     av = (AV *)SvREFCNT_inc_NN(*PL_stack_sp--);
6413
6414     /* replace subtree with an OP_CONST */
6415     curop = ((UNOP*)o)->op_first;
6416     op_sibling_splice(o, NULL, -1, newSVOP(OP_CONST, 0, (SV *)av));
6417     op_free(curop);
6418
6419     if (AvFILLp(av) != -1)
6420         for (svp = AvARRAY(av) + AvFILLp(av); svp >= AvARRAY(av); --svp)
6421         {
6422             SvPADTMP_on(*svp);
6423             SvREADONLY_on(*svp);
6424         }
6425     LINKLIST(o);
6426     list(o);
6427     return;
6428 }
6429
6430 /*
6431 =for apidoc_section $optree_manipulation
6432 */
6433
6434 /* List constructors */
6435
6436 /*
6437 =for apidoc op_append_elem
6438
6439 Append an item to the list of ops contained directly within a list-type
6440 op, returning the lengthened list.  C<first> is the list-type op,
6441 and C<last> is the op to append to the list.  C<optype> specifies the
6442 intended opcode for the list.  If C<first> is not already a list of the
6443 right type, it will be upgraded into one.  If either C<first> or C<last>
6444 is null, the other is returned unchanged.
6445
6446 =cut
6447 */
6448
6449 OP *
6450 Perl_op_append_elem(pTHX_ I32 type, OP *first, OP *last)
6451 {
6452     if (!first)
6453         return last;
6454
6455     if (!last)
6456         return first;
6457
6458     if (first->op_type != (unsigned)type
6459         || (type == OP_LIST && (first->op_flags & OPf_PARENS)))
6460     {
6461         return newLISTOP(type, 0, first, last);
6462     }
6463
6464     op_sibling_splice(first, ((LISTOP*)first)->op_last, 0, last);
6465     first->op_flags |= OPf_KIDS;
6466     return first;
6467 }
6468
6469 /*
6470 =for apidoc op_append_list
6471
6472 Concatenate the lists of ops contained directly within two list-type ops,
6473 returning the combined list.  C<first> and C<last> are the list-type ops
6474 to concatenate.  C<optype> specifies the intended opcode for the list.
6475 If either C<first> or C<last> is not already a list of the right type,
6476 it will be upgraded into one.  If either C<first> or C<last> is null,
6477 the other is returned unchanged.
6478
6479 =cut
6480 */
6481
6482 OP *
6483 Perl_op_append_list(pTHX_ I32 type, OP *first, OP *last)
6484 {
6485     if (!first)
6486         return last;
6487
6488     if (!last)
6489         return first;
6490
6491     if (first->op_type != (unsigned)type)
6492         return op_prepend_elem(type, first, last);
6493
6494     if (last->op_type != (unsigned)type)
6495         return op_append_elem(type, first, last);
6496
6497     OpMORESIB_set(((LISTOP*)first)->op_last, ((LISTOP*)last)->op_first);
6498     ((LISTOP*)first)->op_last = ((LISTOP*)last)->op_last;
6499     OpLASTSIB_set(((LISTOP*)first)->op_last, first);
6500     first->op_flags |= (last->op_flags & OPf_KIDS);
6501
6502     S_op_destroy(aTHX_ last);
6503
6504     return first;
6505 }
6506
6507 /*
6508 =for apidoc op_prepend_elem
6509
6510 Prepend an item to the list of ops contained directly within a list-type
6511 op, returning the lengthened list.  C<first> is the op to prepend to the
6512 list, and C<last> is the list-type op.  C<optype> specifies the intended
6513 opcode for the list.  If C<last> is not already a list of the right type,
6514 it will be upgraded into one.  If either C<first> or C<last> is null,
6515 the other is returned unchanged.
6516
6517 =cut
6518 */
6519
6520 OP *
6521 Perl_op_prepend_elem(pTHX_ I32 type, OP *first, OP *last)
6522 {
6523     if (!first)
6524         return last;
6525
6526     if (!last)
6527         return first;
6528
6529     if (last->op_type == (unsigned)type) {
6530         if (type == OP_LIST) {  /* already a PUSHMARK there */
6531             /* insert 'first' after pushmark */
6532             op_sibling_splice(last, cLISTOPx(last)->op_first, 0, first);
6533             if (!(first->op_flags & OPf_PARENS))
6534                 last->op_flags &= ~OPf_PARENS;
6535         }
6536         else
6537             op_sibling_splice(last, NULL, 0, first);
6538         last->op_flags |= OPf_KIDS;
6539         return last;
6540     }
6541
6542     return newLISTOP(type, 0, first, last);
6543 }
6544
6545 /*
6546 =for apidoc op_convert_list
6547
6548 Converts C<o> into a list op if it is not one already, and then converts it
6549 into the specified C<type>, calling its check function, allocating a target if
6550 it needs one, and folding constants.
6551
6552 A list-type op is usually constructed one kid at a time via C<newLISTOP>,
6553 C<op_prepend_elem> and C<op_append_elem>.  Then finally it is passed to
6554 C<op_convert_list> to make it the right type.
6555
6556 =cut
6557 */
6558
6559 OP *
6560 Perl_op_convert_list(pTHX_ I32 type, I32 flags, OP *o)
6561 {
6562     if (type < 0) type = -type, flags |= OPf_SPECIAL;
6563     if (!o || o->op_type != OP_LIST)
6564         o = force_list(o, FALSE);
6565     else
6566     {
6567         o->op_flags &= ~OPf_WANT;
6568         o->op_private &= ~OPpLVAL_INTRO;
6569     }
6570
6571     if (!(PL_opargs[type] & OA_MARK))
6572         op_null(cLISTOPo->op_first);
6573     else {
6574         OP * const kid2 = OpSIBLING(cLISTOPo->op_first);
6575         if (kid2 && kid2->op_type == OP_COREARGS) {
6576             op_null(cLISTOPo->op_first);
6577             kid2->op_private |= OPpCOREARGS_PUSHMARK;
6578         }
6579     }
6580
6581     if (type != OP_SPLIT)
6582         /* At this point o is a LISTOP, but OP_SPLIT is a PMOP; let
6583          * ck_split() create a real PMOP and leave the op's type as listop
6584          * for now. Otherwise op_free() etc will crash.
6585          */
6586         OpTYPE_set(o, type);
6587
6588     o->op_flags |= flags;
6589     if (flags & OPf_FOLDED)
6590         o->op_folded = 1;
6591
6592     o = CHECKOP(type, o);
6593     if (o->op_type != (unsigned)type)
6594         return o;
6595
6596     return fold_constants(op_integerize(op_std_init(o)));
6597 }
6598
6599 /* Constructors */
6600
6601
6602 /*
6603 =for apidoc_section $optree_construction
6604
6605 =for apidoc newNULLLIST
6606
6607 Constructs, checks, and returns a new C<stub> op, which represents an
6608 empty list expression.
6609
6610 =cut
6611 */
6612
6613 OP *
6614 Perl_newNULLLIST(pTHX)
6615 {
6616     return newOP(OP_STUB, 0);
6617 }
6618
6619 /* promote o and any siblings to be a list if its not already; i.e.
6620  *
6621  *  o - A - B
6622  *
6623  * becomes
6624  *
6625  *  list
6626  *    |
6627  *  pushmark - o - A - B
6628  *
6629  * If nullit it true, the list op is nulled.
6630  */
6631
6632 static OP *
6633 S_force_list(pTHX_ OP *o, bool nullit)
6634 {
6635     if (!o || o->op_type != OP_LIST) {
6636         OP *rest = NULL;
6637         if (o) {
6638             /* manually detach any siblings then add them back later */
6639             rest = OpSIBLING(o);
6640             OpLASTSIB_set(o, NULL);
6641         }
6642         o = newLISTOP(OP_LIST, 0, o, NULL);
6643         if (rest)
6644             op_sibling_splice(o, cLISTOPo->op_last, 0, rest);
6645     }
6646     if (nullit)
6647         op_null(o);
6648     return o;
6649 }
6650
6651 /*
6652 =for apidoc newLISTOP
6653
6654 Constructs, checks, and returns an op of any list type.  C<type> is
6655 the opcode.  C<flags> gives the eight bits of C<op_flags>, except that
6656 C<OPf_KIDS> will be set automatically if required.  C<first> and C<last>
6657 supply up to two ops to be direct children of the list op; they are
6658 consumed by this function and become part of the constructed op tree.
6659
6660 For most list operators, the check function expects all the kid ops to be
6661 present already, so calling C<newLISTOP(OP_JOIN, ...)> (e.g.) is not
6662 appropriate.  What you want to do in that case is create an op of type
6663 C<OP_LIST>, append more children to it, and then call L</op_convert_list>.
6664 See L</op_convert_list> for more information.
6665
6666
6667 =cut
6668 */
6669
6670 OP *
6671 Perl_newLISTOP(pTHX_ I32 type, I32 flags, OP *first, OP *last)
6672 {
6673     LISTOP *listop;
6674     /* Note that allocating an OP_PUSHMARK can die under Safe.pm if
6675      * pushmark is banned. So do it now while existing ops are in a
6676      * consistent state, in case they suddenly get freed */
6677     OP* const pushop = type == OP_LIST ? newOP(OP_PUSHMARK, 0) : NULL;
6678
6679     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_LISTOP
6680         || type == OP_CUSTOM);
6681
6682     NewOp(1101, listop, 1, LISTOP);
6683     OpTYPE_set(listop, type);
6684     if (first || last)
6685         flags |= OPf_KIDS;
6686     listop->op_flags = (U8)flags;
6687
6688     if (!last && first)
6689         last = first;
6690     else if (!first && last)
6691         first = last;
6692     else if (first)
6693         OpMORESIB_set(first, last);
6694     listop->op_first = first;
6695     listop->op_last = last;
6696
6697     if (pushop) {
6698         OpMORESIB_set(pushop, first);
6699         listop->op_first = pushop;
6700         listop->op_flags |= OPf_KIDS;
6701         if (!last)
6702             listop->op_last = pushop;
6703     }
6704     if (listop->op_last)
6705         OpLASTSIB_set(listop->op_last, (OP*)listop);
6706
6707     return CHECKOP(type, listop);
6708 }
6709
6710 /*
6711 =for apidoc newOP
6712
6713 Constructs, checks, and returns an op of any base type (any type that
6714 has no extra fields).  C<type> is the opcode.  C<flags> gives the
6715 eight bits of C<op_flags>, and, shifted up eight bits, the eight bits
6716 of C<op_private>.
6717
6718 =cut
6719 */
6720
6721 OP *
6722 Perl_newOP(pTHX_ I32 type, I32 flags)
6723 {
6724     OP *o;
6725
6726     if (type == -OP_ENTEREVAL) {
6727         type = OP_ENTEREVAL;
6728         flags |= OPpEVAL_BYTES<<8;
6729     }
6730
6731     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_BASEOP
6732         || (PL_opargs[type] & OA_CLASS_MASK) == OA_BASEOP_OR_UNOP
6733         || (PL_opargs[type] & OA_CLASS_MASK) == OA_FILESTATOP
6734         || (PL_opargs[type] & OA_CLASS_MASK) == OA_LOOPEXOP);
6735
6736     NewOp(1101, o, 1, OP);
6737     OpTYPE_set(o, type);
6738     o->op_flags = (U8)flags;
6739
6740     o->op_next = o;
6741     o->op_private = (U8)(0 | (flags >> 8));
6742     if (PL_opargs[type] & OA_RETSCALAR)
6743         scalar(o);
6744     if (PL_opargs[type] & OA_TARGET)
6745         o->op_targ = pad_alloc(type, SVs_PADTMP);
6746     return CHECKOP(type, o);
6747 }
6748
6749 /*
6750 =for apidoc newUNOP
6751
6752 Constructs, checks, and returns an op of any unary type.  C<type> is
6753 the opcode.  C<flags> gives the eight bits of C<op_flags>, except that
6754 C<OPf_KIDS> will be set automatically if required, and, shifted up eight
6755 bits, the eight bits of C<op_private>, except that the bit with value 1
6756 is automatically set.  C<first> supplies an optional op to be the direct
6757 child of the unary op; it is consumed by this function and become part
6758 of the constructed op tree.
6759
6760 =for apidoc Amnh||OPf_KIDS
6761
6762 =cut
6763 */
6764
6765 OP *
6766 Perl_newUNOP(pTHX_ I32 type, I32 flags, OP *first)
6767 {
6768     UNOP *unop;
6769
6770     if (type == -OP_ENTEREVAL) {
6771         type = OP_ENTEREVAL;
6772         flags |= OPpEVAL_BYTES<<8;
6773     }
6774
6775     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_UNOP
6776         || (PL_opargs[type] & OA_CLASS_MASK) == OA_BASEOP_OR_UNOP
6777         || (PL_opargs[type] & OA_CLASS_MASK) == OA_FILESTATOP
6778         || (PL_opargs[type] & OA_CLASS_MASK) == OA_LOOPEXOP
6779         || type == OP_SASSIGN
6780         || type == OP_ENTERTRY
6781         || type == OP_ENTERTRYCATCH
6782         || type == OP_CUSTOM
6783         || type == OP_NULL );
6784
6785     if (!first)
6786         first = newOP(OP_STUB, 0);
6787     if (PL_opargs[type] & OA_MARK)
6788         first = force_list(first, TRUE);
6789
6790     NewOp(1101, unop, 1, UNOP);
6791     OpTYPE_set(unop, type);
6792     unop->op_first = first;
6793     unop->op_flags = (U8)(flags | OPf_KIDS);
6794     unop->op_private = (U8)(1 | (flags >> 8));
6795
6796     if (!OpHAS_SIBLING(first)) /* true unless weird syntax error */
6797         OpLASTSIB_set(first, (OP*)unop);
6798
6799     unop = (UNOP*) CHECKOP(type, unop);
6800     if (unop->op_next)
6801         return (OP*)unop;
6802
6803     return fold_constants(op_integerize(op_std_init((OP *) unop)));
6804 }
6805
6806 /*
6807 =for apidoc newUNOP_AUX
6808
6809 Similar to C<newUNOP>, but creates an C<UNOP_AUX> struct instead, with C<op_aux>
6810 initialised to C<aux>
6811
6812 =cut
6813 */
6814
6815 OP *
6816 Perl_newUNOP_AUX(pTHX_ I32 type, I32 flags, OP *first, UNOP_AUX_item *aux)
6817 {
6818     UNOP_AUX *unop;
6819
6820     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_UNOP_AUX
6821         || type == OP_CUSTOM);
6822
6823     NewOp(1101, unop, 1, UNOP_AUX);
6824     unop->op_type = (OPCODE)type;
6825     unop->op_ppaddr = PL_ppaddr[type];
6826     unop->op_first = first;
6827     unop->op_flags = (U8)(flags | (first ? OPf_KIDS : 0));
6828     unop->op_private = (U8)((first ? 1 : 0) | (flags >> 8));
6829     unop->op_aux = aux;
6830
6831     if (first && !OpHAS_SIBLING(first)) /* true unless weird syntax error */
6832         OpLASTSIB_set(first, (OP*)unop);
6833
6834     unop = (UNOP_AUX*) CHECKOP(type, unop);
6835
6836     return op_std_init((OP *) unop);
6837 }
6838
6839 /*
6840 =for apidoc newMETHOP
6841
6842 Constructs, checks, and returns an op of method type with a method name
6843 evaluated at runtime.  C<type> is the opcode.  C<flags> gives the eight
6844 bits of C<op_flags>, except that C<OPf_KIDS> will be set automatically,
6845 and, shifted up eight bits, the eight bits of C<op_private>, except that
6846 the bit with value 1 is automatically set.  C<dynamic_meth> supplies an
6847 op which evaluates method name; it is consumed by this function and
6848 become part of the constructed op tree.
6849 Supported optypes: C<OP_METHOD>.
6850
6851 =cut
6852 */
6853
6854 static OP*
6855 S_newMETHOP_internal(pTHX_ I32 type, I32 flags, OP* dynamic_meth, SV* const_meth) {
6856     METHOP *methop;
6857
6858     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_METHOP
6859         || type == OP_CUSTOM);
6860
6861     NewOp(1101, methop, 1, METHOP);
6862     if (dynamic_meth) {
6863         if (PL_opargs[type] & OA_MARK) dynamic_meth = force_list(dynamic_meth, TRUE);
6864         methop->op_flags = (U8)(flags | OPf_KIDS);
6865         methop->op_u.op_first = dynamic_meth;
6866         methop->op_private = (U8)(1 | (flags >> 8));
6867
6868         if (!OpHAS_SIBLING(dynamic_meth))
6869             OpLASTSIB_set(dynamic_meth, (OP*)methop);
6870     }
6871     else {
6872         assert(const_meth);
6873         methop->op_flags = (U8)(flags & ~OPf_KIDS);
6874         methop->op_u.op_meth_sv = const_meth;
6875         methop->op_private = (U8)(0 | (flags >> 8));
6876         methop->op_next = (OP*)methop;
6877     }
6878
6879 #ifdef USE_ITHREADS
6880     methop->op_rclass_targ = 0;
6881 #else
6882     methop->op_rclass_sv = NULL;
6883 #endif
6884
6885     OpTYPE_set(methop, type);
6886     return CHECKOP(type, methop);
6887 }
6888
6889 OP *
6890 Perl_newMETHOP (pTHX_ I32 type, I32 flags, OP* dynamic_meth) {
6891     PERL_ARGS_ASSERT_NEWMETHOP;
6892     return newMETHOP_internal(type, flags, dynamic_meth, NULL);
6893 }
6894
6895 /*
6896 =for apidoc newMETHOP_named
6897
6898 Constructs, checks, and returns an op of method type with a constant
6899 method name.  C<type> is the opcode.  C<flags> gives the eight bits of
6900 C<op_flags>, and, shifted up eight bits, the eight bits of
6901 C<op_private>.  C<const_meth> supplies a constant method name;
6902 it must be a shared COW string.
6903 Supported optypes: C<OP_METHOD_NAMED>.
6904
6905 =cut
6906 */
6907
6908 OP *
6909 Perl_newMETHOP_named (pTHX_ I32 type, I32 flags, SV* const_meth) {
6910     PERL_ARGS_ASSERT_NEWMETHOP_NAMED;
6911     return newMETHOP_internal(type, flags, NULL, const_meth);
6912 }
6913
6914 /*
6915 =for apidoc newBINOP
6916
6917 Constructs, checks, and returns an op of any binary type.  C<type>
6918 is the opcode.  C<flags> gives the eight bits of C<op_flags>, except
6919 that C<OPf_KIDS> will be set automatically, and, shifted up eight bits,
6920 the eight bits of C<op_private>, except that the bit with value 1 or
6921 2 is automatically set as required.  C<first> and C<last> supply up to
6922 two ops to be the direct children of the binary op; they are consumed
6923 by this function and become part of the constructed op tree.
6924
6925 =cut
6926 */
6927
6928 OP *
6929 Perl_newBINOP(pTHX_ I32 type, I32 flags, OP *first, OP *last)
6930 {
6931     BINOP *binop;
6932
6933     ASSUME((PL_opargs[type] & OA_CLASS_MASK) == OA_BINOP
6934         || type == OP_NULL || type == OP_CUSTOM);
6935
6936     NewOp(1101, binop, 1, BINOP);
6937
6938     if (!first)
6939         first = newOP(OP_NULL, 0);
6940
6941     OpTYPE_set(binop, type);
6942     binop->op_first = first;
6943     binop->op_flags = (U8)(flags | OPf_KIDS);
6944     if (!last) {
6945         last = first;
6946         binop->op_private = (U8)(1 | (flags >> 8));
6947     }
6948     else {
6949         binop->op_private = (U8)(2 | (flags >> 8));
6950         OpMORESIB_set(first, last);
6951     }
6952
6953     if (!OpHAS_SIBLING(last)) /* true unless weird syntax error */
6954         OpLASTSIB_set(last, (OP*)binop);
6955
6956     binop->op_last = OpSIBLING(binop->op_first);
6957     if (binop->op_last)
6958         OpLASTSIB_set(binop->op_last, (OP*)binop);
6959
6960     binop = (BINOP*)CHECKOP(type, binop);
6961     if (binop->op_next || binop->op_type != (OPCODE)type)
6962         return (OP*)binop;
6963
6964     return fold_constants(op_integerize(op_std_init((OP *)binop)));
6965 }
6966
6967 void
6968 Perl_invmap_dump(pTHX_ SV* invlist, UV *map)
6969 {
6970     const char indent[] = "    ";
6971
6972     UV len = _invlist_len(invlist);
6973     UV * array = invlist_array(invlist);
6974     UV i;
6975
6976     PERL_ARGS_ASSERT_INVMAP_DUMP;
6977
6978     for (i = 0; i < len; i++) {
6979         UV start = array[i];
6980         UV end   = (i + 1 < len) ? array[i+1] - 1 : IV_MAX;
6981
6982         PerlIO_printf(Perl_debug_log, "%s[%" UVuf "] 0x%04" UVXf, indent, i, start);
6983         if (end == IV_MAX) {
6984             PerlIO_printf(Perl_debug_log, " .. INFTY");
6985         }
6986         else if (end != start) {
6987             PerlIO_printf(Perl_debug_log, " .. 0x%04" UVXf, end);
6988         }
6989         else {
6990             PerlIO_printf(Perl_debug_log, "            ");
6991         }
6992
6993         PerlIO_printf(Perl_debug_log, "\t");
6994
6995         if (map[i] == TR_UNLISTED) {
6996             PerlIO_printf(Perl_debug_log, "TR_UNLISTED\n");
6997         }
6998         else if (map[i] == TR_SPECIAL_HANDLING) {
6999             PerlIO_printf(Perl_debug_log, "TR_SPECIAL_HANDLING\n");
7000         }
7001         else {
7002             PerlIO_printf(Perl_debug_log, "0x%04" UVXf "\n", map[i]);
7003         }
7004     }
7005 }
7006
7007 /* Given an OP_TRANS / OP_TRANSR op o, plus OP_CONST ops expr and repl
7008  * containing the search and replacement strings, assemble into
7009  * a translation table attached as o->op_pv.
7010  * Free expr and repl.
7011  * It expects the toker to have already set the
7012  *   OPpTRANS_COMPLEMENT
7013  *   OPpTRANS_SQUASH
7014  *   OPpTRANS_DELETE
7015  * flags as appropriate; this function may add
7016  *   OPpTRANS_USE_SVOP
7017  *   OPpTRANS_CAN_FORCE_UTF8
7018  *   OPpTRANS_IDENTICAL
7019  *   OPpTRANS_GROWS
7020  * flags
7021  */
7022
7023 static OP *
7024 S_pmtrans(pTHX_ OP *o, OP *expr, OP *repl)
7025 {
7026     /* This function compiles a tr///, from data gathered from toke.c, into a
7027      * form suitable for use by do_trans() in doop.c at runtime.
7028      *
7029      * It first normalizes the data, while discarding extraneous inputs; then
7030      * writes out the compiled data.  The normalization allows for complete
7031      * analysis, and avoids some false negatives and positives earlier versions
7032      * of this code had.
7033      *
7034      * The normalization form is an inversion map (described below in detail).
7035      * This is essentially the compiled form for tr///'s that require UTF-8,
7036      * and its easy to use it to write the 257-byte table for tr///'s that
7037      * don't need UTF-8.  That table is identical to what's been in use for
7038      * many perl versions, except that it doesn't handle some edge cases that
7039      * it used to, involving code points above 255.  The UTF-8 form now handles
7040      * these.  (This could be changed with extra coding should it shown to be
7041      * desirable.)
7042      *
7043      * If the complement (/c) option is specified, the lhs string (tstr) is
7044      * parsed into an inversion list.  Complementing these is trivial.  Then a
7045      * complemented tstr is built from that, and used thenceforth.  This hides
7046      * the fact that it was complemented from almost all successive code.
7047      *
7048      * One of the important characteristics to know about the input is whether
7049      * the transliteration may be done in place, or does a temporary need to be
7050      * allocated, then copied.  If the replacement for every character in every
7051      * possible string takes up no more bytes than the character it
7052      * replaces, then it can be edited in place.  Otherwise the replacement
7053      * could overwrite a byte we are about to read, depending on the strings
7054      * being processed.  The comments and variable names here refer to this as
7055      * "growing".  Some inputs won't grow, and might even shrink under /d, but
7056      * some inputs could grow, so we have to assume any given one might grow.
7057      * On very long inputs, the temporary could eat up a lot of memory, so we
7058      * want to avoid it if possible.  For non-UTF-8 inputs, everything is
7059      * single-byte, so can be edited in place, unless there is something in the
7060      * pattern that could force it into UTF-8.  The inversion map makes it
7061      * feasible to determine this.  Previous versions of this code pretty much
7062      * punted on determining if UTF-8 could be edited in place.  Now, this code
7063      * is rigorous in making that determination.
7064      *
7065      * Another characteristic we need to know is whether the lhs and rhs are
7066      * identical.  If so, and no other flags are present, the only effect of
7067      * the tr/// is to count the characters present in the input that are
7068      * mentioned in the lhs string.  The implementation of that is easier and
7069      * runs faster than the more general case.  Normalizing here allows for
7070      * accurate determination of this.  Previously there were false negatives
7071      * possible.
7072      *
7073      * Instead of 'transliterated', the comments here use 'unmapped' for the
7074      * characters that are left unchanged by the operation; otherwise they are
7075      * 'mapped'
7076      *
7077      * The lhs of the tr/// is here referred to as the t side.
7078      * The rhs of the tr/// is here referred to as the r side.
7079      */
7080
7081     SV * const tstr = ((SVOP*)expr)->op_sv;
7082     SV * const rstr = ((SVOP*)repl)->op_sv;
7083     STRLEN tlen;
7084     STRLEN rlen;
7085     const U8 * t0 = (U8*)SvPV_const(tstr, tlen);
7086     const U8 * r0 = (U8*)SvPV_const(rstr, rlen);
7087     const U8 * t = t0;
7088     const U8 * r = r0;
7089     UV t_count = 0, r_count = 0;  /* Number of characters in search and
7090                                          replacement lists */
7091
7092     /* khw thinks some of the private flags for this op are quaintly named.
7093      * OPpTRANS_GROWS for example is TRUE if the replacement for some lhs
7094      * character when represented in UTF-8 is longer than the original
7095      * character's UTF-8 representation */
7096     const bool complement = cBOOL(o->op_private & OPpTRANS_COMPLEMENT);
7097     const bool squash     = cBOOL(o->op_private & OPpTRANS_SQUASH);
7098     const bool del        = cBOOL(o->op_private & OPpTRANS_DELETE);
7099
7100     /* Set to true if there is some character < 256 in the lhs that maps to
7101      * above 255.  If so, a non-UTF-8 match string can be forced into being in
7102      * UTF-8 by a tr/// operation. */
7103     bool can_force_utf8 = FALSE;
7104
7105     /* What is the maximum expansion factor in UTF-8 transliterations.  If a
7106      * 2-byte UTF-8 encoded character is to be replaced by a 3-byte one, its
7107      * expansion factor is 1.5.  This number is used at runtime to calculate
7108      * how much space to allocate for non-inplace transliterations.  Without
7109      * this number, the worst case is 14, which is extremely unlikely to happen
7110      * in real life, and could require significant memory overhead. */
7111     NV max_expansion = 1.;
7112
7113     UV t_range_count, r_range_count, min_range_count;
7114     UV* t_array;
7115     SV* t_invlist;
7116     UV* r_map;
7117     UV r_cp = 0, t_cp = 0;
7118     UV t_cp_end = (UV) -1;
7119     UV r_cp_end;
7120     Size_t len;
7121     AV* invmap;
7122     UV final_map = TR_UNLISTED;    /* The final character in the replacement
7123                                       list, updated as we go along.  Initialize
7124                                       to something illegal */
7125
7126     bool rstr_utf8 = cBOOL(SvUTF8(rstr));
7127     bool tstr_utf8 = cBOOL(SvUTF8(tstr));
7128
7129     const U8* tend = t + tlen;
7130     const U8* rend = r + rlen;
7131
7132     SV * inverted_tstr = NULL;
7133
7134     Size_t i;
7135     unsigned int pass2;
7136
7137     /* This routine implements detection of a transliteration having a longer
7138      * UTF-8 representation than its source, by partitioning all the possible
7139      * code points of the platform into equivalence classes of the same UTF-8
7140      * byte length in the first pass.  As it constructs the mappings, it carves
7141      * these up into smaller chunks, but doesn't merge any together.  This
7142      * makes it easy to find the instances it's looking for.  A second pass is
7143      * done after this has been determined which merges things together to
7144      * shrink the table for runtime.  The table below is used for both ASCII
7145      * and EBCDIC platforms.  On EBCDIC, the byte length is not monotonically
7146      * increasing for code points below 256.  To correct for that, the macro
7147      * CP_ADJUST defined below converts those code points to ASCII in the first
7148      * pass, and we use the ASCII partition values.  That works because the
7149      * growth factor will be unaffected, which is all that is calculated during
7150      * the first pass. */
7151     UV PL_partition_by_byte_length[] = {
7152         0,
7153         0x80,   /* Below this is 1 byte representations */
7154         (32 * (1UL << (    UTF_ACCUMULATION_SHIFT))),   /* 2 bytes below this */
7155         (16 * (1UL << (2 * UTF_ACCUMULATION_SHIFT))),   /* 3 bytes below this */
7156         ( 8 * (1UL << (3 * UTF_ACCUMULATION_SHIFT))),   /* 4 bytes below this */
7157         ( 4 * (1UL << (4 * UTF_ACCUMULATION_SHIFT))),   /* 5 bytes below this */
7158         ( 2 * (1UL << (5 * UTF_ACCUMULATION_SHIFT)))    /* 6 bytes below this */
7159
7160 #  ifdef UV_IS_QUAD
7161                                                     ,
7162         ( ((UV) 1U << (6 * UTF_ACCUMULATION_SHIFT)))    /* 7 bytes below this */
7163 #  endif
7164
7165     };
7166
7167     PERL_ARGS_ASSERT_PMTRANS;
7168
7169     PL_hints |= HINT_BLOCK_SCOPE;
7170
7171     /* If /c, the search list is sorted and complemented.  This is now done by
7172      * creating an inversion list from it, and then trivially inverting that.
7173      * The previous implementation used qsort, but creating the list
7174      * automatically keeps it sorted as we go along */
7175     if (complement) {
7176         UV start, end;
7177         SV * inverted_tlist = _new_invlist(tlen);
7178         Size_t temp_len;
7179
7180         DEBUG_y(PerlIO_printf(Perl_debug_log,
7181                     "%s: %d: tstr before inversion=\n%s\n",
7182                     __FILE__, __LINE__, _byte_dump_string(t, tend - t, 0)));
7183
7184         while (t < tend) {
7185
7186             /* Non-utf8 strings don't have ranges, so each character is listed
7187              * out */
7188             if (! tstr_utf8) {
7189                 inverted_tlist = add_cp_to_invlist(inverted_tlist, *t);
7190                 t++;
7191             }
7192             else {  /* But UTF-8 strings have been parsed in toke.c to have
7193                  * ranges if appropriate. */
7194                 UV t_cp;
7195                 Size_t t_char_len;
7196
7197                 /* Get the first character */
7198                 t_cp = valid_utf8_to_uvchr(t, &t_char_len);
7199                 t += t_char_len;
7200
7201                 /* If the next byte indicates that this wasn't the first
7202                  * element of a range, the range is just this one */
7203                 if (t >= tend || *t != RANGE_INDICATOR) {
7204                     inverted_tlist = add_cp_to_invlist(inverted_tlist, t_cp);
7205                 }
7206                 else { /* Otherwise, ignore the indicator byte, and get the
7207                           final element, and add the whole range */
7208                     t++;
7209                     t_cp_end = valid_utf8_to_uvchr(t, &t_char_len);
7210                     t += t_char_len;
7211
7212                     inverted_tlist = _add_range_to_invlist(inverted_tlist,
7213                                                       t_cp, t_cp_end);
7214                 }
7215             }
7216         } /* End of parse through tstr */
7217
7218         /* The inversion list is done; now invert it */
7219         _invlist_invert(inverted_tlist);
7220
7221         /* Now go through the inverted list and create a new tstr for the rest
7222          * of the routine to use.  Since the UTF-8 version can have ranges, and
7223          * can be much more compact than the non-UTF-8 version, we create the
7224          * string in UTF-8 even if not necessary.  (This is just an intermediate
7225          * value that gets thrown away anyway.) */
7226         invlist_iterinit(inverted_tlist);
7227         inverted_tstr = newSVpvs("");
7228         while (invlist_iternext(inverted_tlist, &start, &end)) {
7229             U8 temp[UTF8_MAXBYTES];
7230             U8 * temp_end_pos;
7231
7232             /* IV_MAX keeps things from going out of bounds */
7233             start = MIN(IV_MAX, start);
7234             end   = MIN(IV_MAX, end);
7235
7236             temp_end_pos = uvchr_to_utf8(temp, start);
7237             sv_catpvn(inverted_tstr, (char *) temp, temp_end_pos - temp);
7238
7239             if (start != end) {
7240                 Perl_sv_catpvf(aTHX_ inverted_tstr, "%c", RANGE_INDICATOR);
7241                 temp_end_pos = uvchr_to_utf8(temp, end);
7242                 sv_catpvn(inverted_tstr, (char *) temp, temp_end_pos - temp);
7243             }
7244         }
7245
7246         /* Set up so the remainder of the routine uses this complement, instead
7247          * of the actual input */
7248         t0 = t = (U8*)SvPV_const(inverted_tstr, temp_len);
7249         tend = t0 + temp_len;
7250         tstr_utf8 = TRUE;
7251
7252         SvREFCNT_dec_NN(inverted_tlist);
7253     }
7254
7255     /* For non-/d, an empty rhs means to use the lhs */
7256     if (rlen == 0 && ! del) {
7257         r0 = t0;
7258         rend = tend;
7259         rstr_utf8  = tstr_utf8;
7260     }
7261
7262     t_invlist = _new_invlist(1);
7263
7264     /* Initialize to a single range */
7265     t_invlist = _add_range_to_invlist(t_invlist, 0, UV_MAX);
7266
7267     /* For the first pass, the lhs is partitioned such that the
7268      * number of UTF-8 bytes required to represent a code point in each
7269      * partition is the same as the number for any other code point in
7270      * that partion.  We copy the pre-compiled partion. */
7271     len = C_ARRAY_LENGTH(PL_partition_by_byte_length);
7272     invlist_extend(t_invlist, len);
7273     t_array = invlist_array(t_invlist);
7274     Copy(PL_partition_by_byte_length, t_array, len, UV);
7275     invlist_set_len(t_invlist, len, *(get_invlist_offset_addr(t_invlist)));
7276     Newx(r_map, len + 1, UV);
7277
7278     /* Parse the (potentially adjusted) input, creating the inversion map.
7279      * This is done in two passes.  The first pass is to determine if the
7280      * transliteration can be done in place.  The inversion map it creates
7281      * could be used, but generally would be larger and slower to run than the
7282      * output of the second pass, which starts with a more compact table and
7283      * allows more ranges to be merged */
7284     for (pass2 = 0; pass2 < 2; pass2++) {
7285         if (pass2) {
7286             /* Initialize to a single range */
7287             t_invlist = _add_range_to_invlist(t_invlist, 0, UV_MAX);
7288
7289             /* In the second pass, we just have the single range */
7290             len = 1;
7291             t_array = invlist_array(t_invlist);
7292         }
7293
7294 /* As noted earlier, we convert EBCDIC code points to Unicode in the first pass
7295  * so as to get the well-behaved length 1 vs length 2 boundary.  Only code
7296  * points below 256 differ between the two character sets in this regard.  For
7297  * these, we also can't have any ranges, as they have to be individually
7298  * converted. */
7299 #ifdef EBCDIC
7300 #  define CP_ADJUST(x)          ((pass2) ? (x) : NATIVE_TO_UNI(x))
7301 #  define FORCE_RANGE_LEN_1(x)  ((pass2) ? 0 : ((x) < 256))
7302 #  define CP_SKIP(x)            ((pass2) ? UVCHR_SKIP(x) : OFFUNISKIP(x))
7303 #else
7304 #  define CP_ADJUST(x)          (x)
7305 #  define FORCE_RANGE_LEN_1(x)  0
7306 #  define CP_SKIP(x)            UVCHR_SKIP(x)
7307 #endif
7308
7309         /* And the mapping of each of the ranges is initialized.  Initially,
7310          * everything is TR_UNLISTED. */
7311         for (i = 0; i < len; i++) {
7312             r_map[i] = TR_UNLISTED;
7313         }
7314
7315         t = t0;
7316         t_count = 0;
7317         r = r0;
7318         r_count = 0;
7319         t_range_count = r_range_count = 0;
7320
7321         DEBUG_y(PerlIO_printf(Perl_debug_log, "%s: %d:\ntstr=%s\n",
7322                     __FILE__, __LINE__, _byte_dump_string(t, tend - t, 0)));
7323         DEBUG_y(PerlIO_printf(Perl_debug_log, "rstr=%s\n",
7324                                         _byte_dump_string(r, rend - r, 0)));
7325         DEBUG_y(PerlIO_printf(Perl_debug_log, "/c=%d; /s=%d; /d=%d\n",
7326                                                   complement, squash, del));
7327         DEBUG_y(invmap_dump(t_invlist, r_map));
7328
7329         /* Now go through the search list constructing an inversion map.  The
7330          * input is not necessarily in any particular order.  Making it an
7331          * inversion map orders it, potentially simplifying, and makes it easy
7332          * to deal with at run time.  This is the only place in core that
7333          * generates an inversion map; if others were introduced, it might be
7334          * better to create general purpose routines to handle them.
7335          * (Inversion maps are created in perl in other places.)
7336          *
7337          * An inversion map consists of two parallel arrays.  One is
7338          * essentially an inversion list: an ordered list of code points such
7339          * that each element gives the first code point of a range of
7340          * consecutive code points that map to the element in the other array
7341          * that has the same index as this one (in other words, the
7342          * corresponding element).  Thus the range extends up to (but not
7343          * including) the code point given by the next higher element.  In a
7344          * true inversion map, the corresponding element in the other array
7345          * gives the mapping of the first code point in the range, with the
7346          * understanding that the next higher code point in the inversion
7347          * list's range will map to the next higher code point in the map.
7348          *
7349          * So if at element [i], let's say we have:
7350          *
7351          *     t_invlist  r_map
7352          * [i]    A         a
7353          *
7354          * This means that A => a, B => b, C => c....  Let's say that the
7355          * situation is such that:
7356          *
7357          * [i+1]  L        -1
7358          *
7359          * This means the sequence that started at [i] stops at K => k.  This
7360          * illustrates that you need to look at the next element to find where
7361          * a sequence stops.  Except, the highest element in the inversion list
7362          * begins a range that is understood to extend to the platform's
7363          * infinity.
7364          *
7365          * This routine modifies traditional inversion maps to reserve two
7366          * mappings:
7367          *
7368          *  TR_UNLISTED (or -1) indicates that no code point in the range
7369          *      is listed in the tr/// searchlist.  At runtime, these are
7370          *      always passed through unchanged.  In the inversion map, all
7371          *      points in the range are mapped to -1, instead of increasing,
7372          *      like the 'L' in the example above.
7373          *
7374          *      We start the parse with every code point mapped to this, and as
7375          *      we parse and find ones that are listed in the search list, we
7376          *      carve out ranges as we go along that override that.
7377          *
7378          *  TR_SPECIAL_HANDLING (or -2) indicates that every code point in the
7379          *      range needs special handling.  Again, all code points in the
7380          *      range are mapped to -2, instead of increasing.
7381          *
7382          *      Under /d this value means the code point should be deleted from
7383          *      the transliteration when encountered.
7384          *
7385          *      Otherwise, it marks that every code point in the range is to
7386          *      map to the final character in the replacement list.  This
7387          *      happens only when the replacement list is shorter than the
7388          *      search one, so there are things in the search list that have no
7389          *      correspondence in the replacement list.  For example, in
7390          *      tr/a-z/A/, 'A' is the final value, and the inversion map
7391          *      generated for this would be like this:
7392          *          \0  =>  -1
7393          *          a   =>   A
7394          *          b-z =>  -2
7395          *          z+1 =>  -1
7396          *      'A' appears once, then the remainder of the range maps to -2.
7397          *      The use of -2 isn't strictly necessary, as an inversion map is
7398          *      capable of representing this situation, but not nearly so
7399          *      compactly, and this is actually quite commonly encountered.
7400          *      Indeed, the original design of this code used a full inversion
7401          *      map for this.  But things like
7402          *          tr/\0-\x{FFFF}/A/
7403          *      generated huge data structures, slowly, and the execution was
7404          *      also slow.  So the current scheme was implemented.
7405          *
7406          *  So, if the next element in our example is:
7407          *
7408          * [i+2]  Q        q
7409          *
7410          * Then all of L, M, N, O, and P map to TR_UNLISTED.  If the next
7411          * elements are
7412          *
7413          * [i+3]  R        z
7414          * [i+4]  S       TR_UNLISTED
7415          *
7416          * Then Q => q; R => z; and S => TR_UNLISTED.  If [i+4] (the 'S') is
7417          * the final element in the arrays, every code point from S to infinity
7418          * maps to TR_UNLISTED.
7419          *
7420          */
7421                            /* Finish up range started in what otherwise would
7422                             * have been the final iteration */
7423         while (t < tend || t_range_count > 0) {
7424             bool adjacent_to_range_above = FALSE;
7425             bool adjacent_to_range_below = FALSE;
7426
7427             bool merge_with_range_above = FALSE;
7428             bool merge_with_range_below = FALSE;
7429
7430             UV span, invmap_range_length_remaining;
7431             SSize_t j;
7432             Size_t i;
7433
7434             /* If we are in the middle of processing a range in the 'target'
7435              * side, the previous iteration has set us up.  Otherwise, look at
7436              * the next character in the search list */
7437             if (t_range_count <= 0) {
7438                 if (! tstr_utf8) {
7439
7440                     /* Here, not in the middle of a range, and not UTF-8.  The
7441                      * next code point is the single byte where we're at */
7442                     t_cp = CP_ADJUST(*t);
7443                     t_range_count = 1;
7444                     t++;
7445                 }
7446                 else {
7447                     Size_t t_char_len;
7448
7449                     /* Here, not in the middle of a range, and is UTF-8.  The
7450                      * next code point is the next UTF-8 char in the input.  We
7451                      * know the input is valid, because the toker constructed
7452                      * it */
7453                     t_cp = CP_ADJUST(valid_utf8_to_uvchr(t, &t_char_len));
7454                     t += t_char_len;
7455
7456                     /* UTF-8 strings (only) have been parsed in toke.c to have
7457                      * ranges.  See if the next byte indicates that this was
7458                      * the first element of a range.  If so, get the final
7459                      * element and calculate the range size.  If not, the range
7460                      * size is 1 */
7461                     if (   t < tend && *t == RANGE_INDICATOR
7462                         && ! FORCE_RANGE_LEN_1(t_cp))
7463                     {
7464                         t++;
7465                         t_range_count = valid_utf8_to_uvchr(t, &t_char_len)
7466                                       - t_cp + 1;
7467                         t += t_char_len;
7468                     }
7469                     else {
7470                         t_range_count = 1;
7471                     }
7472                 }
7473
7474                 /* Count the total number of listed code points * */
7475                 t_count += t_range_count;
7476             }
7477
7478             /* Similarly, get the next character in the replacement list */
7479             if (r_range_count <= 0) {
7480                 if (r >= rend) {
7481
7482                     /* But if we've exhausted the rhs, there is nothing to map
7483                      * to, except the special handling one, and we make the
7484                      * range the same size as the lhs one. */
7485                     r_cp = TR_SPECIAL_HANDLING;
7486                     r_range_count = t_range_count;
7487
7488                     if (! del) {
7489                         DEBUG_yv(PerlIO_printf(Perl_debug_log,
7490                                         "final_map =%" UVXf "\n", final_map));
7491                     }
7492                 }
7493                 else {
7494                     if (! rstr_utf8) {
7495                         r_cp = CP_ADJUST(*r);
7496                         r_range_count = 1;
7497                         r++;
7498                     }
7499                     else {
7500                         Size_t r_char_len;
7501
7502                         r_cp = CP_ADJUST(valid_utf8_to_uvchr(r, &r_char_len));
7503                         r += r_char_len;
7504                         if (   r < rend && *r == RANGE_INDICATOR
7505                             && ! FORCE_RANGE_LEN_1(r_cp))
7506                         {
7507                             r++;
7508                             r_range_count = valid_utf8_to_uvchr(r,
7509                                                     &r_char_len) - r_cp + 1;
7510                             r += r_char_len;
7511                         }
7512                         else {
7513                             r_range_count = 1;
7514                         }
7515                     }
7516
7517                     if (r_cp == TR_SPECIAL_HANDLING) {
7518                         r_range_count = t_range_count;
7519                     }
7520
7521                     /* This is the final character so far */
7522                     final_map = r_cp + r_range_count - 1;
7523
7524                     r_count += r_range_count;
7525                 }
7526             }
7527
7528             /* Here, we have the next things ready in both sides.  They are
7529              * potentially ranges.  We try to process as big a chunk as
7530              * possible at once, but the lhs and rhs must be synchronized, so
7531              * things like tr/A-Z/a-ij-z/ will need to be processed in 2 chunks
7532              * */
7533             min_range_count = MIN(t_range_count, r_range_count);
7534
7535             /* Search the inversion list for the entry that contains the input
7536              * code point <cp>.  The inversion map was initialized to cover the
7537              * entire range of possible inputs, so this should not fail.  So
7538              * the return value is the index into the list's array of the range
7539              * that contains <cp>, that is, 'i' such that array[i] <= cp <
7540              * array[i+1] */
7541             j = _invlist_search(t_invlist, t_cp);
7542             assert(j >= 0);
7543             i = j;
7544
7545             /* Here, the data structure might look like:
7546              *
7547              * index    t   r     Meaning
7548              * [i-1]    J   j   # J-L => j-l
7549              * [i]      M  -1   # M => default; as do N, O, P, Q
7550              * [i+1]    R   x   # R => x, S => x+1, T => x+2
7551              * [i+2]    U   y   # U => y, V => y+1, ...
7552              * ...
7553              * [-1]     Z  -1   # Z => default; as do Z+1, ... infinity
7554              *
7555              * where 'x' and 'y' above are not to be taken literally.
7556              *
7557              * The maximum chunk we can handle in this loop iteration, is the
7558              * smallest of the three components: the lhs 't_', the rhs 'r_',
7559              * and the remainder of the range in element [i].  (In pass 1, that
7560              * range will have everything in it be of the same class; we can't
7561              * cross into another class.)  'min_range_count' already contains
7562              * the smallest of the first two values.  The final one is
7563              * irrelevant if the map is to the special indicator */
7564
7565             invmap_range_length_remaining = (i + 1 < len)
7566                                             ? t_array[i+1] - t_cp
7567                                             : IV_MAX - t_cp;
7568             span = MAX(1, MIN(min_range_count, invmap_range_length_remaining));
7569
7570             /* The end point of this chunk is where we are, plus the span, but
7571              * never larger than the platform's infinity */
7572             t_cp_end = MIN(IV_MAX, t_cp + span - 1);
7573
7574             if (r_cp == TR_SPECIAL_HANDLING) {
7575
7576                 /* If unmatched lhs code points map to the final map, use that
7577                  * value.  This being set to TR_SPECIAL_HANDLING indicates that
7578                  * we don't have a final map: unmatched lhs code points are
7579                  * simply deleted */
7580                 r_cp_end = (del) ? TR_SPECIAL_HANDLING : final_map;
7581             }
7582             else {
7583                 r_cp_end = MIN(IV_MAX, r_cp + span - 1);
7584
7585                 /* If something on the lhs is below 256, and something on the
7586                  * rhs is above, there is a potential mapping here across that
7587                  * boundary.  Indeed the only way there isn't is if both sides
7588                  * start at the same point.  That means they both cross at the
7589                  * same time.  But otherwise one crosses before the other */
7590                 if (t_cp < 256 && r_cp_end > 255 && r_cp != t_cp) {
7591                     can_force_utf8 = TRUE;
7592                 }
7593             }
7594
7595             /* If a character appears in the search list more than once, the
7596              * 2nd and succeeding occurrences are ignored, so only do this
7597              * range if haven't already processed this character.  (The range
7598              * has been set up so that all members in it will be of the same
7599              * ilk) */
7600             if (r_map[i] == TR_UNLISTED) {
7601                 DEBUG_yv(PerlIO_printf(Perl_debug_log,
7602                     "Processing %" UVxf "-%" UVxf " => %" UVxf "-%" UVxf "\n",
7603                     t_cp, t_cp_end, r_cp, r_cp_end));
7604
7605                 /* This is the first definition for this chunk, hence is valid
7606                  * and needs to be processed.  Here and in the comments below,
7607                  * we use the above sample data.  The t_cp chunk must be any
7608                  * contiguous subset of M, N, O, P, and/or Q.
7609                  *
7610                  * In the first pass, calculate if there is any possible input
7611                  * string that has a character whose transliteration will be
7612                  * longer than it.  If none, the transliteration may be done
7613                  * in-place, as it can't write over a so-far unread byte.
7614                  * Otherwise, a copy must first be made.  This could be
7615                  * expensive for long inputs.
7616                  *
7617                  * In the first pass, the t_invlist has been partitioned so
7618                  * that all elements in any single range have the same number
7619                  * of bytes in their UTF-8 representations.  And the r space is
7620                  * either a single byte, or a range of strictly monotonically
7621                  * increasing code points.  So the final element in the range
7622                  * will be represented by no fewer bytes than the initial one.
7623                  * That means that if the final code point in the t range has
7624                  * at least as many bytes as the final code point in the r,
7625                  * then all code points in the t range have at least as many
7626                  * bytes as their corresponding r range element.  But if that's
7627                  * not true, the transliteration of at least the final code
7628                  * point grows in length.  As an example, suppose we had
7629                  *      tr/\x{fff0}-\x{fff1}/\x{ffff}-\x{10000}/
7630                  * The UTF-8 for all but 10000 occupies 3 bytes on ASCII
7631                  * platforms.  We have deliberately set up the data structure
7632                  * so that any range in the lhs gets split into chunks for
7633                  * processing, such that every code point in a chunk has the
7634                  * same number of UTF-8 bytes.  We only have to check the final
7635                  * code point in the rhs against any code point in the lhs. */
7636                 if ( ! pass2
7637                     && r_cp_end != TR_SPECIAL_HANDLING
7638                     && CP_SKIP(t_cp_end) < CP_SKIP(r_cp_end))
7639                 {
7640                     /* Here, we will need to make a copy of the input string
7641                      * before doing the transliteration.  The worst possible
7642                      * case is an expansion ratio of 14:1. This is rare, and
7643                      * we'd rather allocate only the necessary amount of extra
7644                      * memory for that copy.  We can calculate the worst case
7645                      * for this particular transliteration is by keeping track
7646                      * of the expansion factor for each range.
7647                      *
7648                      * Consider tr/\xCB/\X{E000}/.  The maximum expansion
7649                      * factor is 1 byte going to 3 if the target string is not
7650                      * UTF-8, but 2 bytes going to 3 if it is in UTF-8.  We
7651                      * could pass two different values so doop could choose
7652                      * based on the UTF-8ness of the target.  But khw thinks
7653                      * (perhaps wrongly) that is overkill.  It is used only to
7654                      * make sure we malloc enough space.
7655                      *
7656                      * If no target string can force the result to be UTF-8,
7657                      * then we don't have to worry about the case of the target
7658                      * string not being UTF-8 */
7659                     NV t_size = (can_force_utf8 && t_cp < 256)
7660                                 ? 1
7661                                 : CP_SKIP(t_cp_end);
7662                     NV ratio = CP_SKIP(r_cp_end) / t_size;
7663
7664                     o->op_private |= OPpTRANS_GROWS;
7665
7666                     /* Now that we know it grows, we can keep track of the
7667                      * largest ratio */
7668                     if (ratio > max_expansion) {
7669                         max_expansion = ratio;
7670                         DEBUG_y(PerlIO_printf(Perl_debug_log,
7671                                         "New expansion factor: %" NVgf "\n",
7672                                         max_expansion));
7673                     }
7674                 }
7675
7676                 /* The very first range is marked as adjacent to the
7677                  * non-existent range below it, as it causes things to "just
7678                  * work" (TradeMark)
7679                  *
7680                  * If the lowest code point in this chunk is M, it adjoins the
7681                  * J-L range */
7682                 if (t_cp == t_array[i]) {
7683                     adjacent_to_range_below = TRUE;
7684
7685                     /* And if the map has the same offset from the beginning of
7686                      * the range as does this new code point (or both are for
7687                      * TR_SPECIAL_HANDLING), this chunk can be completely
7688                      * merged with the range below.  EXCEPT, in the first pass,
7689                      * we don't merge ranges whose UTF-8 byte representations
7690                      * have different lengths, so that we can more easily
7691                      * detect if a replacement is longer than the source, that
7692                      * is if it 'grows'.  But in the 2nd pass, there's no
7693                      * reason to not merge */
7694                     if (   (i > 0 && (   pass2
7695                                       || CP_SKIP(t_array[i-1])
7696                                                             == CP_SKIP(t_cp)))
7697                         && (   (   r_cp == TR_SPECIAL_HANDLING
7698                                 && r_map[i-1] == TR_SPECIAL_HANDLING)
7699                             || (   r_cp != TR_SPECIAL_HANDLING
7700                                 && r_cp - r_map[i-1] == t_cp - t_array[i-1])))
7701                     {
7702                         merge_with_range_below = TRUE;
7703                     }
7704                 }
7705
7706                 /* Similarly, if the highest code point in this chunk is 'Q',
7707                  * it adjoins the range above, and if the map is suitable, can
7708                  * be merged with it */
7709                 if (    t_cp_end >= IV_MAX - 1
7710                     || (   i + 1 < len
7711                         && t_cp_end + 1 == t_array[i+1]))
7712                 {
7713                     adjacent_to_range_above = TRUE;
7714                     if (i + 1 < len)
7715                     if (    (   pass2
7716                              || CP_SKIP(t_cp) == CP_SKIP(t_array[i+1]))
7717                         && (   (   r_cp == TR_SPECIAL_HANDLING
7718                                 && r_map[i+1] == (UV) TR_SPECIAL_HANDLING)
7719                             || (   r_cp != TR_SPECIAL_HANDLING
7720                                 && r_cp_end == r_map[i+1] - 1)))
7721                     {
7722                         merge_with_range_above = TRUE;
7723                     }
7724                 }
7725
7726                 if (merge_with_range_below && merge_with_range_above) {
7727
7728                     /* Here the new chunk looks like M => m, ... Q => q; and
7729                      * the range above is like R => r, ....  Thus, the [i-1]
7730                      * and [i+1] ranges should be seamlessly melded so the
7731                      * result looks like
7732                      *
7733                      * [i-1]    J   j   # J-T => j-t
7734                      * [i]      U   y   # U => y, V => y+1, ...
7735                      * ...
7736                      * [-1]     Z  -1   # Z => default; as do Z+1, ... infinity
7737                      */
7738                     Move(t_array + i + 2, t_array + i, len - i - 2, UV);
7739                     Move(r_map   + i + 2, r_map   + i, len - i - 2, UV);
7740                     len -= 2;
7741                     invlist_set_len(t_invlist,
7742                                     len,
7743                                     *(get_invlist_offset_addr(t_invlist)));
7744                 }
7745                 else if (merge_with_range_below) {
7746
7747                     /* Here the new chunk looks like M => m, .... But either
7748                      * (or both) it doesn't extend all the way up through Q; or
7749                      * the range above doesn't start with R => r. */
7750                     if (! adjacent_to_range_above) {
7751
7752                         /* In the first case, let's say the new chunk extends
7753                          * through O.  We then want:
7754                          *
7755                          * [i-1]    J   j   # J-O => j-o
7756                          * [i]      P  -1   # P => -1, Q => -1
7757                          * [i+1]    R   x   # R => x, S => x+1, T => x+2
7758                          * [i+2]    U   y   # U => y, V => y+1, ...
7759                          * ...
7760                          * [-1]     Z  -1   # Z => default; as do Z+1, ...
7761                          *                                            infinity
7762                          */
7763                         t_array[i] = t_cp_end + 1;
7764                         r_map[i] = TR_UNLISTED;
7765                     }
7766                     else { /* Adjoins the range above, but can't merge with it
7767                               (because 'x' is not the next map after q) */
7768                         /*
7769                          * [i-1]    J   j   # J-Q => j-q
7770                          * [i]      R   x   # R => x, S => x+1, T => x+2
7771                          * [i+1]    U   y   # U => y, V => y+1, ...
7772                          * ...
7773                          * [-1]     Z  -1   # Z => default; as do Z+1, ...
7774                          *                                          infinity
7775                          */
7776
7777                         Move(t_array + i + 1, t_array + i, len - i - 1, UV);
7778                         Move(r_map + i + 1, r_map + i, len - i - 1, UV);
7779                         len--;
7780                         invlist_set_len(t_invlist, len,
7781                                         *(get_invlist_offset_addr(t_invlist)));
7782                     }
7783                 }
7784                 else if (merge_with_range_above) {
7785
7786                     /* Here the new chunk ends with Q => q, and the range above
7787                      * must start with R => r, so the two can be merged. But
7788                      * either (or both) the new chunk doesn't extend all the
7789                      * way down to M; or the mapping of the final code point
7790                      * range below isn't m */
7791                     if (! adjacent_to_range_below) {
7792
7793                         /* In the first case, let's assume the new chunk starts
7794                          * with P => p.  Then, because it's merge-able with the
7795                          * range above, that range must be R => r.  We want:
7796                          *
7797                          * [i-1]    J   j   # J-L => j-l
7798                          * [i]      M  -1   # M => -1, N => -1
7799                          * [i+1]    P   p   # P-T => p-t
7800                          * [i+2]    U   y   # U => y, V => y+1, ...
7801                          * ...
7802                          * [-1]     Z  -1   # Z => default; as do Z+1, ...
7803                          *                                          infinity
7804                          */
7805                         t_array[i+1] = t_cp;
7806                         r_map[i+1] = r_cp;
7807                     }
7808                     else { /* Adjoins the range below, but can't merge with it
7809                             */
7810                         /*
7811                          * [i-1]    J   j   # J-L => j-l
7812                          * [i]      M   x   # M-T => x-5 .. x+2
7813                          * [i+1]    U   y   # U => y, V => y+1, ...
7814                          * ...
7815                          * [-1]     Z  -1   # Z => default; as do Z+1, ...
7816                          *                                          infinity
7817                          */
7818                         Move(t_array + i + 1, t_array + i, len - i - 1, UV);
7819                         Move(r_map   + i + 1, r_map   + i, len - i - 1, UV);
7820                         len--;
7821                         t_array[i] = t_cp;
7822                         r_map[i] = r_cp;
7823                         invlist_set_len(t_invlist, len,
7824                                         *(get_invlist_offset_addr(t_invlist)));
7825                     }
7826                 }
7827                 else if (adjacent_to_range_below && adjacent_to_range_above) {
7828                     /* The new chunk completely fills the gap between the
7829                      * ranges on either side, but can't merge with either of
7830                      * them.
7831                      *
7832                      * [i-1]    J   j   # J-L => j-l
7833                      * [i]      M   z   # M => z, N => z+1 ... Q => z+4
7834                      * [i+1]    R   x   # R => x, S => x+1, T => x+2
7835                      * [i+2]    U   y   # U => y, V => y+1, ...
7836                      * ...
7837                      * [-1]     Z  -1   # Z => default; as do Z+1, ... infinity
7838                      */
7839                     r_map[i] = r_cp;
7840                 }
7841                 else if (adjacent_to_range_below) {
7842                     /* The new chunk adjoins the range below, but not the range
7843                      * above, and can't merge.  Let's assume the chunk ends at
7844                      * O.
7845                      *
7846                      * [i-1]    J   j   # J-L => j-l
7847                      * [i]      M   z   # M => z, N => z+1, O => z+2
7848                      * [i+1]    P   -1  # P => -1, Q => -1
7849                      * [i+2]    R   x   # R => x, S => x+1, T => x+2
7850                      * [i+3]    U   y   # U => y, V => y+1, ...
7851                      * ...
7852                      * [-w]     Z  -1   # Z => default; as do Z+1, ... infinity
7853                      */
7854                     invlist_extend(t_invlist, len + 1);
7855                     t_array = invlist_array(t_invlist);
7856                     Renew(r_map, len + 1, UV);
7857
7858                     Move(t_array + i + 1, t_array + i + 2, len - i - 1, UV);
7859                     Move(r_map + i + 1,   r_map   + i + 2, len - i - 1, UV);
7860                     r_map[i] = r_cp;
7861                     t_array[i+1] = t_cp_end + 1;
7862                     r_map[i+1] = TR_UNLISTED;
7863                     len++;
7864                     invlist_set_len(t_invlist, len,
7865                                     *(get_invlist_offset_addr(t_invlist)));
7866                 }
7867                 else if (adjacent_to_range_above) {
7868                     /* The new chunk adjoins the range above, but not the range
7869                      * below, and can't merge.  Let's assume the new chunk
7870                      * starts at O
7871                      *
7872                      * [i-1]    J   j   # J-L => j-l
7873                      * [i]      M  -1   # M => default, N => default
7874                      * [i+1]    O   z   # O => z, P => z+1, Q => z+2
7875                      * [i+2]    R   x   # R => x, S => x+1, T => x+2
7876                      * [i+3]    U   y   # U => y, V => y+1, ...
7877                      * ...
7878                      * [-1]     Z  -1   # Z => default; as do Z+1, ... infinity
7879                      */
7880                     invlist_extend(t_invlist, len + 1);
7881                     t_array = invlist_array(t_invlist);
7882                     Renew(r_map, len + 1, UV);
7883
7884                     Move(t_array + i + 1, t_array + i + 2, len - i - 1, UV);
7885                     Move(r_map   + i + 1, r_map   + i + 2, len - i - 1, UV);
7886                     t_array[i+1] = t_cp;
7887                     r_map[i+1] = r_cp;
7888                     len++;
7889                     invlist_set_len(t_invlist, len,
7890                                     *(get_invlist_offset_addr(t_invlist)));
7891                 }
7892                 else {
7893                     /* The new chunk adjoins neither the range above, nor the
7894                      * range below.  Lets assume it is N..P => n..p
7895                      *
7896                      * [i-1]    J   j   # J-L => j-l
7897                      * [i]      M  -1   # M => default
7898                      * [i+1]    N   n   # N..P => n..p
7899                      * [i+2]    Q  -1   # Q => default
7900                      * [i+3]    R   x   # R => x, S => x+1, T => x+2
7901                      * [i+4]    U   y   # U => y, V => y+1, ...
7902                      * ...
7903                      * [-1]     Z  -1   # Z => default; as do Z+1, ... infinity
7904                      */
7905
7906                     DEBUG_yv(PerlIO_printf(Perl_debug_log,
7907                                         "Before fixing up: len=%d, i=%d\n",
7908                                         (int) len, (int) i));
7909                     DEBUG_yv(invmap_dump(t_invlist, r_map));
7910
7911                     invlist_extend(t_invlist, len + 2);
7912                     t_array = invlist_array(t_invlist);
7913                     Renew(r_map, len + 2, UV);
7914
7915                     Move(t_array + i + 1,
7916                          t_array + i + 2 + 1, len - i - (2 - 1), UV);
7917                     Move(r_map   + i + 1,
7918                          r_map   + i + 2 + 1, len - i - (2 - 1), UV);
7919
7920                     len += 2;
7921                     invlist_set_len(t_invlist, len,
7922                                     *(get_invlist_offset_addr(t_invlist)));
7923
7924                     t_array[i+1] = t_cp;
7925                     r_map[i+1] = r_cp;
7926
7927                     t_array[i+2] = t_cp_end + 1;
7928                     r_map[i+2] = TR_UNLISTED;
7929                 }
7930                 DEBUG_yv(PerlIO_printf(Perl_debug_log,
7931                           "After iteration: span=%" UVuf ", t_range_count=%"
7932                           UVuf " r_range_count=%" UVuf "\n",
7933                           span, t_range_count, r_range_count));
7934                 DEBUG_yv(invmap_dump(t_invlist, r_map));
7935             } /* End of this chunk needs to be processed */
7936
7937             /* Done with this chunk. */
7938             t_cp += span;
7939             if (t_cp >= IV_MAX) {
7940                 break;
7941             }
7942             t_range_count -= span;
7943             if (r_cp != TR_SPECIAL_HANDLING) {
7944                 r_cp += span;
7945                 r_range_count -= span;
7946             }
7947             else {
7948                 r_range_count = 0;
7949             }
7950
7951         } /* End of loop through the search list */
7952
7953         /* We don't need an exact count, but we do need to know if there is
7954          * anything left over in the replacement list.  So, just assume it's
7955          * one byte per character */
7956         if (rend > r) {
7957             r_count++;
7958         }
7959     } /* End of passes */
7960
7961     SvREFCNT_dec(inverted_tstr);
7962
7963     DEBUG_y(PerlIO_printf(Perl_debug_log, "After everything: \n"));
7964     DEBUG_y(invmap_dump(t_invlist, r_map));
7965
7966     /* We now have normalized the input into an inversion map.
7967      *
7968      * See if the lhs and rhs are equivalent.  If so, this tr/// is a no-op
7969      * except for the count, and streamlined runtime code can be used */
7970     if (!del && !squash) {
7971
7972         /* They are identical if they point to same address, or if everything
7973          * maps to UNLISTED or to itself.  This catches things that not looking
7974          * at the normalized inversion map doesn't catch, like tr/aa/ab/ or
7975          * tr/\x{100}-\x{104}/\x{100}-\x{102}\x{103}-\x{104}  */
7976         if (r0 != t0) {
7977             for (i = 0; i < len; i++) {
7978                 if (r_map[i] != TR_UNLISTED && r_map[i] != t_array[i]) {
7979                     goto done_identical_check;
7980                 }
7981             }
7982         }
7983
7984         /* Here have gone through entire list, and didn't find any
7985          * non-identical mappings */
7986         o->op_private |= OPpTRANS_IDENTICAL;
7987
7988       done_identical_check: ;
7989     }
7990
7991     t_array = invlist_array(t_invlist);
7992
7993     /* If has components above 255, we generally need to use the inversion map
7994      * implementation */
7995     if (   can_force_utf8
7996         || (   len > 0
7997             && t_array[len-1] > 255
7998                  /* If the final range is 0x100-INFINITY and is a special
7999                   * mapping, the table implementation can handle it */
8000             && ! (   t_array[len-1] == 256
8001                   && (   r_map[len-1] == TR_UNLISTED
8002                       || r_map[len-1] == TR_SPECIAL_HANDLING))))
8003     {
8004         SV* r_map_sv;
8005
8006         /* A UTF-8 op is generated, indicated by this flag.  This op is an
8007          * sv_op */
8008         o->op_private |= OPpTRANS_USE_SVOP;
8009
8010         if (can_force_utf8) {
8011             o->op_private |= OPpTRANS_CAN_FORCE_UTF8;
8012         }
8013
8014         /* The inversion map is pushed; first the list. */
8015         invmap = MUTABLE_AV(newAV());
8016         av_push(invmap, t_invlist);
8017
8018         /* 2nd is the mapping */
8019         r_map_sv = newSVpvn((char *) r_map, len * sizeof(UV));
8020         av_push(invmap, r_map_sv);
8021
8022         /* 3rd is the max possible expansion factor */
8023         av_push(invmap, newSVnv(max_expansion));
8024
8025         /* Characters that are in the search list, but not in the replacement
8026          * list are mapped to the final character in the replacement list */
8027         if (! del && r_count < t_count) {
8028             av_push(invmap, newSVuv(final_map));
8029         }
8030
8031 #ifdef USE_ITHREADS
8032         cPADOPo->op_padix = pad_alloc(OP_TRANS, SVf_READONLY);
8033         SvREFCNT_dec(PAD_SVl(cPADOPo->op_padix));
8034         PAD_SETSV(cPADOPo->op_padix, (SV *) invmap);
8035         SvPADTMP_on(invmap);
8036         SvREADONLY_on(invmap);
8037 #else
8038         cSVOPo->op_sv = (SV *) invmap;
8039 #endif
8040
8041     }
8042     else {
8043         OPtrans_map *tbl;
8044         unsigned short i;
8045
8046         /* The OPtrans_map struct already contains one slot; hence the -1. */
8047         SSize_t struct_size = sizeof(OPtrans_map)
8048                             + (256 - 1 + 1)*sizeof(short);
8049
8050         /* Non-utf8 case: set o->op_pv to point to a simple 256+ entry lookup
8051         * table. Entries with the value TR_UNMAPPED indicate chars not to be
8052         * translated, while TR_DELETE indicates a search char without a
8053         * corresponding replacement char under /d.
8054         *
8055         * In addition, an extra slot at the end is used to store the final
8056         * repeating char, or TR_R_EMPTY under an empty replacement list, or
8057         * TR_DELETE under /d; which makes the runtime code easier.
8058         */
8059
8060         /* Indicate this is an op_pv */
8061         o->op_private &= ~OPpTRANS_USE_SVOP;
8062
8063         tbl = (OPtrans_map*)PerlMemShared_calloc(struct_size, 1);
8064         tbl->size = 256;
8065         cPVOPo->op_pv = (char*)tbl;
8066
8067         for (i = 0; i < len; i++) {
8068             STATIC_ASSERT_DECL(TR_SPECIAL_HANDLING == TR_DELETE);
8069             short upper = i >= len - 1 ? 256 : (short) t_array[i+1];
8070             short to = (short) r_map[i];
8071             short j;
8072             bool do_increment = TRUE;
8073
8074             /* Any code points above our limit should be irrelevant */
8075             if (t_array[i] >= tbl->size) break;
8076
8077             /* Set up the map */
8078             if (to == (short) TR_SPECIAL_HANDLING && ! del) {
8079                 to = (short) final_map;
8080                 do_increment = FALSE;
8081             }
8082             else if (to < 0) {
8083                 do_increment = FALSE;
8084             }
8085
8086             /* Create a map for everything in this range.  The value increases
8087              * except for the special cases */
8088             for (j = (short) t_array[i]; j < upper; j++) {
8089                 tbl->map[j] = to;
8090                 if (do_increment) to++;
8091             }
8092         }
8093
8094         tbl->map[tbl->size] = del
8095                               ? (short) TR_DELETE
8096                               : (short) rlen
8097                                 ? (short) final_map
8098                                 : (short) TR_R_EMPTY;
8099         DEBUG_y(PerlIO_printf(Perl_debug_log,"%s: %d\n", __FILE__, __LINE__));
8100         for (i = 0; i < tbl->size; i++) {
8101             if (tbl->map[i] < 0) {
8102                 DEBUG_y(PerlIO_printf(Perl_debug_log," %02x=>%d",
8103                                                 (unsigned) i, tbl->map[i]));
8104             }
8105             else {
8106                 DEBUG_y(PerlIO_printf(Perl_debug_log," %02x=>%02x",
8107                                                 (unsigned) i, tbl->map[i]));
8108             }
8109             if ((i+1) % 8 == 0 || i + 1 == (short) tbl->size) {
8110                 DEBUG_y(PerlIO_printf(Perl_debug_log,"\n"));
8111             }
8112         }
8113         DEBUG_y(PerlIO_printf(Perl_debug_log,"Final map 0x%x=>%02x\n",
8114                                 (unsigned) tbl->size, tbl->map[tbl->size]));
8115
8116         SvREFCNT_dec(t_invlist);
8117
8118 #if 0   /* code that added excess above-255 chars at the end of the table, in
8119            case we ever want to not use the inversion map implementation for
8120            this */
8121
8122         ASSUME(j <= rlen);
8123         excess = rlen - j;
8124
8125         if (excess) {
8126             /* More replacement chars than search chars:
8127              * store excess replacement chars at end of main table.
8128              */
8129
8130             struct_size += excess;
8131             tbl = (OPtrans_map*)PerlMemShared_realloc(tbl,
8132                         struct_size + excess * sizeof(short));
8133             tbl->size += excess;
8134             cPVOPo->op_pv = (char*)tbl;
8135
8136             for (i = 0; i < excess; i++)
8137                 tbl->map[i + 256] = r[j+i];
8138         }
8139         else {
8140             /* no more replacement chars than search chars */
8141         }
8142 #endif
8143
8144     }
8145
8146     DEBUG_y(PerlIO_printf(Perl_debug_log,
8147             "/d=%d, /s=%d, /c=%d, identical=%d, grows=%d,"
8148             " use_svop=%d, can_force_utf8=%d,\nexpansion=%" NVgf "\n",
8149             del, squash, complement,
8150             cBOOL(o->op_private & OPpTRANS_IDENTICAL),
8151             cBOOL(o->op_private & OPpTRANS_USE_SVOP),
8152             cBOOL(o->op_private & OPpTRANS_GROWS),
8153             cBOOL(o->op_private & OPpTRANS_CAN_FORCE_UTF8),
8154             max_expansion));
8155
8156     Safefree(r_map);
8157
8158     if(del && rlen != 0 && r_count == t_count) {
8159         Perl_ck_warner(aTHX_ packWARN(WARN_MISC), "Useless use of /d modifier in transliteration operator");
8160     } else if(r_count > t_count) {
8161         Perl_ck_warner(aTHX_ packWARN(WARN_MISC), "Replacement list is longer than search list");
8162     }
8163
8164     op_free(expr);
8165     op_free(repl);
8166
8167     return o;
8168 }
8169
8170
8171 /*
8172 =for apidoc newPMOP
8173
8174 Constructs, checks, and returns an op of any pattern matching type.
8175 C<type> is the opcode.  C<flags> gives the eight bits of C<op_flags>
8176 and, shifted up eight bits, the eight bits of C<op_private>.
8177
8178 =cut
8179 */
8180
8181 OP *
8182 Perl_newPMOP(pTHX_ I32 type, I32 flags)
8183 {
8184     PMOP *pmop;
8185
8186     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_PMOP
8187         || type == OP_CUSTOM);
8188
8189     NewOp(1101, pmop, 1, PMOP);
8190     OpTYPE_set(pmop, type);
8191     pmop->op_flags = (U8)flags;
8192     pmop->op_private = (U8)(0 | (flags >> 8));
8193     if (PL_opargs[type] & OA_RETSCALAR)
8194         scalar((OP *)pmop);
8195
8196     if (PL_hints & HINT_RE_TAINT)
8197         pmop->op_pmflags |= PMf_RETAINT;
8198 #ifdef USE_LOCALE_CTYPE
8199     if (IN_LC_COMPILETIME(LC_CTYPE)) {
8200         set_regex_charset(&(pmop->op_pmflags), REGEX_LOCALE_CHARSET);
8201     }
8202     else
8203 #endif
8204          if (IN_UNI_8_BIT) {
8205         set_regex_charset(&(pmop->op_pmflags), REGEX_UNICODE_CHARSET);
8206     }
8207     if (PL_hints & HINT_RE_FLAGS) {
8208         SV *reflags = Perl_refcounted_he_fetch_pvn(aTHX_
8209          PL_compiling.cop_hints_hash, STR_WITH_LEN("reflags"), 0, 0
8210         );
8211         if (reflags && SvOK(reflags)) pmop->op_pmflags |= SvIV(reflags);
8212         reflags = Perl_refcounted_he_fetch_pvn(aTHX_
8213          PL_compiling.cop_hints_hash, STR_WITH_LEN("reflags_charset"), 0, 0
8214         );
8215         if (reflags && SvOK(reflags)) {
8216             set_regex_charset(&(pmop->op_pmflags), (regex_charset)SvIV(reflags));
8217         }
8218     }
8219
8220
8221 #ifdef USE_ITHREADS
8222     assert(SvPOK(PL_regex_pad[0]));
8223     if (SvCUR(PL_regex_pad[0])) {
8224         /* Pop off the "packed" IV from the end.  */
8225         SV *const repointer_list = PL_regex_pad[0];
8226         const char *p = SvEND(repointer_list) - sizeof(IV);
8227         const IV offset = *((IV*)p);
8228
8229         assert(SvCUR(repointer_list) % sizeof(IV) == 0);
8230
8231         SvEND_set(repointer_list, p);
8232
8233         pmop->op_pmoffset = offset;
8234         /* This slot should be free, so assert this:  */
8235         assert(PL_regex_pad[offset] == &PL_sv_undef);
8236     } else {
8237         SV * const repointer = &PL_sv_undef;
8238         av_push(PL_regex_padav, repointer);
8239         pmop->op_pmoffset = av_top_index(PL_regex_padav);
8240         PL_regex_pad = AvARRAY(PL_regex_padav);
8241     }
8242 #endif
8243
8244     return CHECKOP(type, pmop);
8245 }
8246
8247 static void
8248 S_set_haseval(pTHX)
8249 {
8250     PADOFFSET i = 1;
8251     PL_cv_has_eval = 1;
8252     /* Any pad names in scope are potentially lvalues.  */
8253     for (; i < PadnamelistMAXNAMED(PL_comppad_name); i++) {
8254         PADNAME *pn = PAD_COMPNAME_SV(i);
8255         if (!pn || !PadnameLEN(pn))
8256             continue;
8257         if (PadnameOUTER(pn) || PadnameIN_SCOPE(pn, PL_cop_seqmax))
8258             S_mark_padname_lvalue(aTHX_ pn);
8259     }
8260 }
8261
8262 /* Given some sort of match op o, and an expression expr containing a
8263  * pattern, either compile expr into a regex and attach it to o (if it's
8264  * constant), or convert expr into a runtime regcomp op sequence (if it's
8265  * not)
8266  *
8267  * Flags currently has 2 bits of meaning:
8268  * 1: isreg indicates that the pattern is part of a regex construct, eg
8269  *      $x =~ /pattern/ or split /pattern/, as opposed to $x =~ $pattern or
8270  *      split "pattern", which aren't. In the former case, expr will be a list
8271  *      if the pattern contains more than one term (eg /a$b/).
8272  * 2: The pattern is for a split.
8273  *
8274  * When the pattern has been compiled within a new anon CV (for
8275  * qr/(?{...})/ ), then floor indicates the savestack level just before
8276  * the new sub was created
8277  *
8278  * tr/// is also handled.
8279  */
8280
8281 OP *
8282 Perl_pmruntime(pTHX_ OP *o, OP *expr, OP *repl, UV flags, I32 floor)
8283 {
8284     PMOP *pm;
8285     LOGOP *rcop;
8286     I32 repl_has_vars = 0;
8287     bool is_trans = (o->op_type == OP_TRANS || o->op_type == OP_TRANSR);
8288     bool is_compiletime;
8289     bool has_code;
8290     bool isreg    = cBOOL(flags & 1);
8291     bool is_split = cBOOL(flags & 2);
8292
8293     PERL_ARGS_ASSERT_PMRUNTIME;
8294
8295     if (is_trans) {
8296         return pmtrans(o, expr, repl);
8297     }
8298
8299     /* find whether we have any runtime or code elements;
8300      * at the same time, temporarily set the op_next of each DO block;
8301      * then when we LINKLIST, this will cause the DO blocks to be excluded
8302      * from the op_next chain (and from having LINKLIST recursively
8303      * applied to them). We fix up the DOs specially later */
8304
8305     is_compiletime = 1;
8306     has_code = 0;
8307     if (expr->op_type == OP_LIST) {
8308         OP *child;
8309         for (child = cLISTOPx(expr)->op_first; child; child = OpSIBLING(child)) {
8310             if (child->op_type == OP_NULL && (child->op_flags & OPf_SPECIAL)) {
8311                 has_code = 1;
8312                 assert(!child->op_next);
8313                 if (UNLIKELY(!OpHAS_SIBLING(child))) {
8314                     assert(PL_parser && PL_parser->error_count);
8315                     /* This can happen with qr/ (?{(^{})/.  Just fake up
8316                        the op we were expecting to see, to avoid crashing
8317                        elsewhere.  */
8318                     op_sibling_splice(expr, child, 0,
8319                               newSVOP(OP_CONST, 0, &PL_sv_no));
8320                 }
8321                 child->op_next = OpSIBLING(child);
8322             }
8323             else if (child->op_type != OP_CONST && child->op_type != OP_PUSHMARK)
8324             is_compiletime = 0;
8325         }
8326     }
8327     else if (expr->op_type != OP_CONST)
8328         is_compiletime = 0;
8329
8330     LINKLIST(expr);
8331
8332     /* fix up DO blocks; treat each one as a separate little sub;
8333      * also, mark any arrays as LIST/REF */
8334
8335     if (expr->op_type == OP_LIST) {
8336         OP *child;
8337         for (child = cLISTOPx(expr)->op_first; child; child = OpSIBLING(child)) {
8338
8339             if (child->op_type == OP_PADAV || child->op_type == OP_RV2AV) {
8340                 assert( !(child->op_flags  & OPf_WANT));
8341                 /* push the array rather than its contents. The regex
8342                  * engine will retrieve and join the elements later */
8343                 child->op_flags |= (OPf_WANT_LIST | OPf_REF);
8344                 continue;
8345             }
8346
8347             if (!(child->op_type == OP_NULL && (child->op_flags & OPf_SPECIAL)))
8348                 continue;
8349             child->op_next = NULL; /* undo temporary hack from above */
8350             scalar(child);
8351             LINKLIST(child);
8352             if (cLISTOPx(child)->op_first->op_type == OP_LEAVE) {
8353                 LISTOP *leaveop = cLISTOPx(cLISTOPx(child)->op_first);
8354                 /* skip ENTER */
8355                 assert(leaveop->op_first->op_type == OP_ENTER);
8356                 assert(OpHAS_SIBLING(leaveop->op_first));
8357                 child->op_next = OpSIBLING(leaveop->op_first);
8358                 /* skip leave */
8359                 assert(leaveop->op_flags & OPf_KIDS);
8360                 assert(leaveop->op_last->op_next == (OP*)leaveop);
8361                 leaveop->op_next = NULL; /* stop on last op */
8362                 op_null((OP*)leaveop);
8363             }
8364             else {
8365                 /* skip SCOPE */
8366                 OP *scope = cLISTOPx(child)->op_first;
8367                 assert(scope->op_type == OP_SCOPE);
8368                 assert(scope->op_flags & OPf_KIDS);
8369                 scope->op_next = NULL; /* stop on last op */
8370                 op_null(scope);
8371             }
8372
8373             /* XXX optimize_optree() must be called on o before
8374              * CALL_PEEP(), as currently S_maybe_multiconcat() can't
8375              * currently cope with a peephole-optimised optree.
8376              * Calling optimize_optree() here ensures that condition
8377              * is met, but may mean optimize_optree() is applied
8378              * to the same optree later (where hopefully it won't do any
8379              * harm as it can't convert an op to multiconcat if it's
8380              * already been converted */
8381             optimize_optree(child);
8382
8383             /* have to peep the DOs individually as we've removed it from
8384              * the op_next chain */
8385             CALL_PEEP(child);
8386             S_prune_chain_head(&(child->op_next));
8387             if (is_compiletime)
8388                 /* runtime finalizes as part of finalizing whole tree */
8389                 finalize_optree(child);
8390         }
8391     }
8392     else if (expr->op_type == OP_PADAV || expr->op_type == OP_RV2AV) {
8393         assert( !(expr->op_flags  & OPf_WANT));
8394         /* push the array rather than its contents. The regex
8395          * engine will retrieve and join the elements later */
8396         expr->op_flags |= (OPf_WANT_LIST | OPf_REF);
8397     }
8398
8399     PL_hints |= HINT_BLOCK_SCOPE;
8400     pm = (PMOP*)o;
8401     assert(floor==0 || (pm->op_pmflags & PMf_HAS_CV));
8402
8403     if (is_compiletime) {
8404         U32 rx_flags = pm->op_pmflags & RXf_PMf_COMPILETIME;
8405         regexp_engine const *eng = current_re_engine();
8406
8407         if (is_split) {
8408             /* make engine handle split ' ' specially */
8409             pm->op_pmflags |= PMf_SPLIT;
8410             rx_flags |= RXf_SPLIT;
8411         }
8412
8413         if (!has_code || !eng->op_comp) {
8414             /* compile-time simple constant pattern */
8415
8416             if ((pm->op_pmflags & PMf_HAS_CV) && !has_code) {
8417                 /* whoops! we guessed that a qr// had a code block, but we
8418                  * were wrong (e.g. /[(?{}]/ ). Throw away the PL_compcv
8419                  * that isn't required now. Note that we have to be pretty
8420                  * confident that nothing used that CV's pad while the
8421                  * regex was parsed, except maybe op targets for \Q etc.
8422                  * If there were any op targets, though, they should have
8423                  * been stolen by constant folding.
8424                  */
8425 #ifdef DEBUGGING
8426                 SSize_t i = 0;
8427                 assert(PadnamelistMAXNAMED(PL_comppad_name) == 0);
8428                 while (++i <= AvFILLp(PL_comppad)) {
8429 #  ifdef USE_PAD_RESET
8430                     /* under USE_PAD_RESET, pad swipe replaces a swiped
8431                      * folded constant with a fresh padtmp */
8432                     assert(!PL_curpad[i] || SvPADTMP(PL_curpad[i]));
8433 #  else
8434                     assert(!PL_curpad[i]);
8435 #  endif
8436                 }
8437 #endif
8438                 /* This LEAVE_SCOPE will restore PL_compcv to point to the
8439                  * outer CV (the one whose slab holds the pm op). The
8440                  * inner CV (which holds expr) will be freed later, once
8441                  * all the entries on the parse stack have been popped on
8442                  * return from this function. Which is why its safe to
8443                  * call op_free(expr) below.
8444                  */
8445                 LEAVE_SCOPE(floor);
8446                 pm->op_pmflags &= ~PMf_HAS_CV;
8447             }
8448
8449             /* Skip compiling if parser found an error for this pattern */
8450             if (pm->op_pmflags & PMf_HAS_ERROR) {
8451                 return o;
8452             }
8453
8454             PM_SETRE(pm,
8455                 eng->op_comp
8456                     ? eng->op_comp(aTHX_ NULL, 0, expr, eng, NULL, NULL,
8457                                         rx_flags, pm->op_pmflags)
8458                     : Perl_re_op_compile(aTHX_ NULL, 0, expr, eng, NULL, NULL,
8459                                         rx_flags, pm->op_pmflags)
8460             );
8461             op_free(expr);
8462         }
8463         else {
8464             /* compile-time pattern that includes literal code blocks */
8465
8466             REGEXP* re;
8467
8468             /* Skip compiling if parser found an error for this pattern */
8469             if (pm->op_pmflags & PMf_HAS_ERROR) {
8470                 return o;
8471             }
8472
8473             re = eng->op_comp(aTHX_ NULL, 0, expr, eng, NULL, NULL,
8474                         rx_flags,
8475                         (pm->op_pmflags |
8476                             ((PL_hints & HINT_RE_EVAL) ? PMf_USE_RE_EVAL : 0))
8477                     );
8478             PM_SETRE(pm, re);
8479             if (pm->op_pmflags & PMf_HAS_CV) {
8480                 CV *cv;
8481                 /* this QR op (and the anon sub we embed it in) is never
8482                  * actually executed. It's just a placeholder where we can
8483                  * squirrel away expr in op_code_list without the peephole
8484                  * optimiser etc processing it for a second time */
8485                 OP *qr = newPMOP(OP_QR, 0);
8486                 ((PMOP*)qr)->op_code_list = expr;
8487
8488                 /* handle the implicit sub{} wrapped round the qr/(?{..})/ */
8489                 SvREFCNT_inc_simple_void(PL_compcv);
8490                 cv = newATTRSUB(floor, 0, NULL, NULL, qr);
8491                 ReANY(re)->qr_anoncv = cv;
8492
8493                 /* attach the anon CV to the pad so that
8494                  * pad_fixup_inner_anons() can find it */
8495                 (void)pad_add_anon(cv, o->op_type);
8496                 SvREFCNT_inc_simple_void(cv);
8497             }
8498             else {
8499                 pm->op_code_list = expr;
8500             }
8501         }
8502     }
8503     else {
8504         /* runtime pattern: build chain of regcomp etc ops */
8505         bool reglist;
8506         PADOFFSET cv_targ = 0;
8507
8508         reglist = isreg && expr->op_type == OP_LIST;
8509         if (reglist)
8510             op_null(expr);
8511
8512         if (has_code) {
8513             pm->op_code_list = expr;
8514             /* don't free op_code_list; its ops are embedded elsewhere too */
8515             pm->op_pmflags |= PMf_CODELIST_PRIVATE;
8516         }
8517
8518         if (is_split)
8519             /* make engine handle split ' ' specially */
8520             pm->op_pmflags |= PMf_SPLIT;
8521
8522         /* the OP_REGCMAYBE is a placeholder in the non-threaded case
8523          * to allow its op_next to be pointed past the regcomp and
8524          * preceding stacking ops;
8525          * OP_REGCRESET is there to reset taint before executing the
8526          * stacking ops */
8527         if (pm->op_pmflags & PMf_KEEP || TAINTING_get)
8528             expr = newUNOP((TAINTING_get ? OP_REGCRESET : OP_REGCMAYBE),0,expr);
8529
8530         if (pm->op_pmflags & PMf_HAS_CV) {
8531             /* we have a runtime qr with literal code. This means
8532              * that the qr// has been wrapped in a new CV, which
8533              * means that runtime consts, vars etc will have been compiled
8534              * against a new pad. So... we need to execute those ops
8535              * within the environment of the new CV. So wrap them in a call
8536              * to a new anon sub. i.e. for
8537              *
8538              *     qr/a$b(?{...})/,
8539              *
8540              * we build an anon sub that looks like
8541              *
8542              *     sub { "a", $b, '(?{...})' }
8543              *
8544              * and call it, passing the returned list to regcomp.
8545              * Or to put it another way, the list of ops that get executed
8546              * are:
8547              *
8548              *     normal              PMf_HAS_CV
8549              *     ------              -------------------
8550              *                         pushmark (for regcomp)
8551              *                         pushmark (for entersub)
8552              *                         anoncode
8553              *                         srefgen
8554              *                         entersub
8555              *     regcreset                  regcreset
8556              *     pushmark                   pushmark
8557              *     const("a")                 const("a")
8558              *     gvsv(b)                    gvsv(b)
8559              *     const("(?{...})")          const("(?{...})")
8560              *                                leavesub
8561              *     regcomp             regcomp
8562              */
8563
8564             SvREFCNT_inc_simple_void(PL_compcv);
8565             CvLVALUE_on(PL_compcv);
8566             /* these lines are just an unrolled newANONATTRSUB */
8567             expr = newSVOP(OP_ANONCODE, 0,
8568                     MUTABLE_SV(newATTRSUB(floor, 0, NULL, NULL, expr)));
8569             cv_targ = expr->op_targ;
8570             expr = newUNOP(OP_REFGEN, 0, expr);
8571
8572             expr = list(force_list(newUNOP(OP_ENTERSUB, 0, scalar(expr)), TRUE));
8573         }
8574
8575         rcop = alloc_LOGOP(OP_REGCOMP, scalar(expr), o);
8576         rcop->op_flags |=  ((PL_hints & HINT_RE_EVAL) ? OPf_SPECIAL : 0)
8577                            | (reglist ? OPf_STACKED : 0);
8578         rcop->op_targ = cv_targ;
8579
8580         /* /$x/ may cause an eval, since $x might be qr/(?{..})/  */
8581         if (PL_hints & HINT_RE_EVAL)
8582             S_set_haseval(aTHX);
8583
8584         /* establish postfix order */
8585         if (expr->op_type == OP_REGCRESET || expr->op_type == OP_REGCMAYBE) {
8586             LINKLIST(expr);
8587             rcop->op_next = expr;
8588             ((UNOP*)expr)->op_first->op_next = (OP*)rcop;
8589         }
8590         else {
8591             rcop->op_next = LINKLIST(expr);
8592             expr->op_next = (OP*)rcop;
8593         }
8594
8595         op_prepend_elem(o->op_type, scalar((OP*)rcop), o);
8596     }
8597
8598     if (repl) {
8599         OP *curop = repl;
8600         bool konst;
8601         /* If we are looking at s//.../e with a single statement, get past
8602            the implicit do{}. */
8603         if (curop->op_type == OP_NULL && curop->op_flags & OPf_KIDS
8604              && cUNOPx(curop)->op_first->op_type == OP_SCOPE
8605              && cUNOPx(curop)->op_first->op_flags & OPf_KIDS)
8606          {
8607             OP *sib;
8608             OP *kid = cUNOPx(cUNOPx(curop)->op_first)->op_first;
8609             if (kid->op_type == OP_NULL && (sib = OpSIBLING(kid))
8610              && !OpHAS_SIBLING(sib))
8611                 curop = sib;
8612         }
8613         if (curop->op_type == OP_CONST)
8614             konst = TRUE;
8615         else if (( (curop->op_type == OP_RV2SV ||
8616                     curop->op_type == OP_RV2AV ||
8617                     curop->op_type == OP_RV2HV ||
8618                     curop->op_type == OP_RV2GV)
8619                    && cUNOPx(curop)->op_first
8620                    && cUNOPx(curop)->op_first->op_type == OP_GV )
8621                 || curop->op_type == OP_PADSV
8622                 || curop->op_type == OP_PADAV
8623                 || curop->op_type == OP_PADHV
8624                 || curop->op_type == OP_PADANY) {
8625             repl_has_vars = 1;
8626             konst = TRUE;
8627         }
8628         else konst = FALSE;
8629         if (konst
8630             && !(repl_has_vars
8631                  && (!PM_GETRE(pm)
8632                      || !RX_PRELEN(PM_GETRE(pm))
8633                      || RX_EXTFLAGS(PM_GETRE(pm)) & RXf_EVAL_SEEN)))
8634         {
8635             pm->op_pmflags |= PMf_CONST;        /* const for long enough */
8636             op_prepend_elem(o->op_type, scalar(repl), o);
8637         }
8638         else {
8639             rcop = alloc_LOGOP(OP_SUBSTCONT, scalar(repl), o);
8640             rcop->op_private = 1;
8641
8642             /* establish postfix order */
8643             rcop->op_next = LINKLIST(repl);
8644             repl->op_next = (OP*)rcop;
8645
8646             pm->op_pmreplrootu.op_pmreplroot = scalar((OP*)rcop);
8647             assert(!(pm->op_pmflags & PMf_ONCE));
8648             pm->op_pmstashstartu.op_pmreplstart = LINKLIST(rcop);
8649             rcop->op_next = 0;
8650         }
8651     }
8652
8653     return (OP*)pm;
8654 }
8655
8656 /*
8657 =for apidoc newSVOP
8658
8659 Constructs, checks, and returns an op of any type that involves an
8660 embedded SV.  C<type> is the opcode.  C<flags> gives the eight bits
8661 of C<op_flags>.  C<sv> gives the SV to embed in the op; this function
8662 takes ownership of one reference to it.
8663
8664 =cut
8665 */
8666
8667 OP *
8668 Perl_newSVOP(pTHX_ I32 type, I32 flags, SV *sv)
8669 {
8670     SVOP *svop;
8671
8672     PERL_ARGS_ASSERT_NEWSVOP;
8673
8674     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_SVOP
8675         || (PL_opargs[type] & OA_CLASS_MASK) == OA_PVOP_OR_SVOP
8676         || (PL_opargs[type] & OA_CLASS_MASK) == OA_FILESTATOP
8677         || type == OP_CUSTOM);
8678
8679     NewOp(1101, svop, 1, SVOP);
8680     OpTYPE_set(svop, type);
8681     svop->op_sv = sv;
8682     svop->op_next = (OP*)svop;
8683     svop->op_flags = (U8)flags;
8684     svop->op_private = (U8)(0 | (flags >> 8));
8685     if (PL_opargs[type] & OA_RETSCALAR)
8686         scalar((OP*)svop);
8687     if (PL_opargs[type] & OA_TARGET)
8688         svop->op_targ = pad_alloc(type, SVs_PADTMP);
8689     return CHECKOP(type, svop);
8690 }
8691
8692 /*
8693 =for apidoc newDEFSVOP
8694
8695 Constructs and returns an op to access C<$_>.
8696
8697 =cut
8698 */
8699
8700 OP *
8701 Perl_newDEFSVOP(pTHX)
8702 {
8703         return newSVREF(newGVOP(OP_GV, 0, PL_defgv));
8704 }
8705
8706 #ifdef USE_ITHREADS
8707
8708 /*
8709 =for apidoc newPADOP
8710
8711 Constructs, checks, and returns an op of any type that involves a
8712 reference to a pad element.  C<type> is the opcode.  C<flags> gives the
8713 eight bits of C<op_flags>.  A pad slot is automatically allocated, and
8714 is populated with C<sv>; this function takes ownership of one reference
8715 to it.
8716
8717 This function only exists if Perl has been compiled to use ithreads.
8718
8719 =cut
8720 */
8721
8722 OP *
8723 Perl_newPADOP(pTHX_ I32 type, I32 flags, SV *sv)
8724 {
8725     PADOP *padop;
8726
8727     PERL_ARGS_ASSERT_NEWPADOP;
8728
8729     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_SVOP
8730         || (PL_opargs[type] & OA_CLASS_MASK) == OA_PVOP_OR_SVOP
8731         || (PL_opargs[type] & OA_CLASS_MASK) == OA_FILESTATOP
8732         || type == OP_CUSTOM);
8733
8734     NewOp(1101, padop, 1, PADOP);
8735     OpTYPE_set(padop, type);
8736     padop->op_padix =
8737         pad_alloc(type, isGV(sv) ? SVf_READONLY : SVs_PADTMP);
8738     SvREFCNT_dec(PAD_SVl(padop->op_padix));
8739     PAD_SETSV(padop->op_padix, sv);
8740     assert(sv);
8741     padop->op_next = (OP*)padop;
8742     padop->op_flags = (U8)flags;
8743     if (PL_opargs[type] & OA_RETSCALAR)
8744         scalar((OP*)padop);
8745     if (PL_opargs[type] & OA_TARGET)
8746         padop->op_targ = pad_alloc(type, SVs_PADTMP);
8747     return CHECKOP(type, padop);
8748 }
8749
8750 #endif /* USE_ITHREADS */
8751
8752 /*
8753 =for apidoc newGVOP
8754
8755 Constructs, checks, and returns an op of any type that involves an
8756 embedded reference to a GV.  C<type> is the opcode.  C<flags> gives the
8757 eight bits of C<op_flags>.  C<gv> identifies the GV that the op should
8758 reference; calling this function does not transfer ownership of any
8759 reference to it.
8760
8761 =cut
8762 */
8763
8764 OP *
8765 Perl_newGVOP(pTHX_ I32 type, I32 flags, GV *gv)
8766 {
8767     PERL_ARGS_ASSERT_NEWGVOP;
8768
8769 #ifdef USE_ITHREADS
8770     return newPADOP(type, flags, SvREFCNT_inc_simple_NN(gv));
8771 #else
8772     return newSVOP(type, flags, SvREFCNT_inc_simple_NN(gv));
8773 #endif
8774 }
8775
8776 /*
8777 =for apidoc newPVOP
8778
8779 Constructs, checks, and returns an op of any type that involves an
8780 embedded C-level pointer (PV).  C<type> is the opcode.  C<flags> gives
8781 the eight bits of C<op_flags>.  C<pv> supplies the C-level pointer.
8782 Depending on the op type, the memory referenced by C<pv> may be freed
8783 when the op is destroyed.  If the op is of a freeing type, C<pv> must
8784 have been allocated using C<PerlMemShared_malloc>.
8785
8786 =cut
8787 */
8788
8789 OP *
8790 Perl_newPVOP(pTHX_ I32 type, I32 flags, char *pv)
8791 {
8792     const bool utf8 = cBOOL(flags & SVf_UTF8);
8793     PVOP *pvop;
8794
8795     flags &= ~SVf_UTF8;
8796
8797     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_PVOP_OR_SVOP
8798         || type == OP_RUNCV || type == OP_CUSTOM
8799         || (PL_opargs[type] & OA_CLASS_MASK) == OA_LOOPEXOP);
8800
8801     NewOp(1101, pvop, 1, PVOP);
8802     OpTYPE_set(pvop, type);
8803     pvop->op_pv = pv;
8804     pvop->op_next = (OP*)pvop;
8805     pvop->op_flags = (U8)flags;
8806     pvop->op_private = utf8 ? OPpPV_IS_UTF8 : 0;
8807     if (PL_opargs[type] & OA_RETSCALAR)
8808         scalar((OP*)pvop);
8809     if (PL_opargs[type] & OA_TARGET)
8810         pvop->op_targ = pad_alloc(type, SVs_PADTMP);
8811     return CHECKOP(type, pvop);
8812 }
8813
8814 void
8815 Perl_package(pTHX_ OP *o)
8816 {
8817     SV *const sv = cSVOPo->op_sv;
8818
8819     PERL_ARGS_ASSERT_PACKAGE;
8820
8821     SAVEGENERICSV(PL_curstash);
8822     save_item(PL_curstname);
8823
8824     PL_curstash = (HV *)SvREFCNT_inc(gv_stashsv(sv, GV_ADD));
8825
8826     sv_setsv(PL_curstname, sv);
8827
8828     PL_hints |= HINT_BLOCK_SCOPE;
8829     PL_parser->copline = NOLINE;
8830
8831     op_free(o);
8832 }
8833
8834 void
8835 Perl_package_version( pTHX_ OP *v )
8836 {
8837     U32 savehints = PL_hints;
8838     PERL_ARGS_ASSERT_PACKAGE_VERSION;
8839     PL_hints &= ~HINT_STRICT_VARS;
8840     sv_setsv( GvSV(gv_fetchpvs("VERSION", GV_ADDMULTI, SVt_PV)), cSVOPx(v)->op_sv );
8841     PL_hints = savehints;
8842     op_free(v);
8843 }
8844
8845 /* Extract the first two components of a "version" object as two 8bit integers
8846  * and return them packed into a single U16 in the format of PL_prevailing_version.
8847  * This function only ever has to cope with version objects already known
8848  * bounded by the current perl version, so we know its components will fit
8849  * (Up until we reach perl version 5.256 anyway) */
8850 static U16 S_extract_shortver(pTHX_ SV *sv)
8851 {
8852     SV *rv;
8853     if(!SvRV(sv) || !SvOBJECT(rv = SvRV(sv)) || !sv_derived_from(sv, "version"))
8854         return 0;
8855
8856     AV *av = MUTABLE_AV(SvRV(*hv_fetchs(MUTABLE_HV(rv), "version", 0)));
8857
8858     U16 shortver = 0;
8859
8860     IV major = av_count(av) > 0 ? SvIV(*av_fetch(av, 0, false)) : 0;
8861     if(major > 255)
8862         shortver |= 255 << 8;
8863     else
8864         shortver |= major << 8;
8865
8866     IV minor = av_count(av) > 1 ? SvIV(*av_fetch(av, 1, false)) : 0;
8867     if(minor > 255)
8868         shortver |= 255;
8869     else
8870         shortver |= minor;
8871
8872     return shortver;
8873 }
8874 #define SHORTVER(maj,min) ((maj << 8) | min)
8875
8876 void
8877 Perl_utilize(pTHX_ int aver, I32 floor, OP *version, OP *idop, OP *arg)
8878 {
8879     OP *pack;
8880     OP *imop;
8881     OP *veop;
8882     SV *use_version = NULL;
8883
8884     PERL_ARGS_ASSERT_UTILIZE;
8885
8886     if (idop->op_type != OP_CONST)
8887         Perl_croak(aTHX_ "Module name must be constant");
8888
8889     veop = NULL;
8890
8891     if (version) {
8892         SV * const vesv = ((SVOP*)version)->op_sv;
8893
8894         if (!arg && !SvNIOKp(vesv)) {
8895             arg = version;
8896         }
8897         else {
8898             OP *pack;
8899             SV *meth;
8900
8901             if (version->op_type != OP_CONST || !SvNIOKp(vesv))
8902                 Perl_croak(aTHX_ "Version number must be a constant number");
8903
8904             /* Make copy of idop so we don't free it twice */
8905             pack = newSVOP(OP_CONST, 0, newSVsv(((SVOP*)idop)->op_sv));
8906
8907             /* Fake up a method call to VERSION */
8908             meth = newSVpvs_share("VERSION");
8909             veop = op_convert_list(OP_ENTERSUB, OPf_STACKED|OPf_SPECIAL,
8910                             op_append_elem(OP_LIST,
8911                                         op_prepend_elem(OP_LIST, pack, version),
8912                                         newMETHOP_named(OP_METHOD_NAMED, 0, meth)));
8913         }
8914     }
8915
8916     /* Fake up an import/unimport */
8917     if (arg && arg->op_type == OP_STUB) {
8918         imop = arg;             /* no import on explicit () */
8919     }
8920     else if (SvNIOKp(((SVOP*)idop)->op_sv)) {
8921         imop = NULL;            /* use 5.0; */
8922         if (aver)
8923             use_version = ((SVOP*)idop)->op_sv;
8924         else
8925             idop->op_private |= OPpCONST_NOVER;
8926     }
8927     else {
8928         SV *meth;
8929
8930         /* Make copy of idop so we don't free it twice */
8931         pack = newSVOP(OP_CONST, 0, newSVsv(((SVOP*)idop)->op_sv));
8932
8933         /* Fake up a method call to import/unimport */
8934         meth = aver
8935             ? newSVpvs_share("import") : newSVpvs_share("unimport");
8936         imop = op_convert_list(OP_ENTERSUB, OPf_STACKED|OPf_SPECIAL,
8937                        op_append_elem(OP_LIST,
8938                                    op_prepend_elem(OP_LIST, pack, arg),
8939                                    newMETHOP_named(OP_METHOD_NAMED, 0, meth)
8940                        ));
8941     }
8942
8943     /* Fake up the BEGIN {}, which does its thing immediately. */
8944     newATTRSUB(floor,
8945         newSVOP(OP_CONST, 0, newSVpvs_share("BEGIN")),
8946         NULL,
8947         NULL,
8948         op_append_elem(OP_LINESEQ,
8949             op_append_elem(OP_LINESEQ,
8950                 newSTATEOP(0, NULL, newUNOP(OP_REQUIRE, 0, idop)),
8951                 newSTATEOP(0, NULL, veop)),
8952             newSTATEOP(0, NULL, imop) ));
8953
8954     if (use_version) {
8955         /* Enable the
8956          * feature bundle that corresponds to the required version. */
8957         use_version = sv_2mortal(new_version(use_version));
8958         S_enable_feature_bundle(aTHX_ use_version);
8959
8960         U16 shortver = S_extract_shortver(aTHX_ use_version);
8961
8962         /* If a version >= 5.11.0 is requested, strictures are on by default! */
8963         if (shortver >= SHORTVER(5, 11)) {
8964             if (!(PL_hints & HINT_EXPLICIT_STRICT_REFS))
8965                 PL_hints |= HINT_STRICT_REFS;
8966             if (!(PL_hints & HINT_EXPLICIT_STRICT_SUBS))
8967                 PL_hints |= HINT_STRICT_SUBS;
8968             if (!(PL_hints & HINT_EXPLICIT_STRICT_VARS))
8969                 PL_hints |= HINT_STRICT_VARS;
8970
8971             if (shortver >= SHORTVER(5, 35))
8972                 free_and_set_cop_warnings(&PL_compiling, pWARN_ALL);
8973         }
8974         /* otherwise they are off */
8975         else {
8976             if(PL_prevailing_version >= SHORTVER(5, 11))
8977                 deprecate_fatal_in("5.40",
8978                     "Downgrading a use VERSION declaration to below v5.11");
8979
8980             if (!(PL_hints & HINT_EXPLICIT_STRICT_REFS))
8981                 PL_hints &= ~HINT_STRICT_REFS;
8982             if (!(PL_hints & HINT_EXPLICIT_STRICT_SUBS))
8983                 PL_hints &= ~HINT_STRICT_SUBS;
8984             if (!(PL_hints & HINT_EXPLICIT_STRICT_VARS))
8985                 PL_hints &= ~HINT_STRICT_VARS;
8986         }
8987
8988         PL_prevailing_version = shortver;
8989     }
8990
8991     /* The "did you use incorrect case?" warning used to be here.
8992      * The problem is that on case-insensitive filesystems one
8993      * might get false positives for "use" (and "require"):
8994      * "use Strict" or "require CARP" will work.  This causes
8995      * portability problems for the script: in case-strict
8996      * filesystems the script will stop working.
8997      *
8998      * The "incorrect case" warning checked whether "use Foo"
8999      * imported "Foo" to your namespace, but that is wrong, too:
9000      * there is no requirement nor promise in the language that
9001      * a Foo.pm should or would contain anything in package "Foo".
9002      *
9003      * There is very little Configure-wise that can be done, either:
9004      * the case-sensitivity of the build filesystem of Perl does not
9005      * help in guessing the case-sensitivity of the runtime environment.
9006      */
9007
9008     PL_hints |= HINT_BLOCK_SCOPE;
9009     PL_parser->copline = NOLINE;
9010     COP_SEQMAX_INC; /* Purely for B::*'s benefit */
9011 }
9012
9013 /*
9014 =for apidoc_section $embedding
9015
9016 =for apidoc load_module
9017
9018 Loads the module whose name is pointed to by the string part of C<name>.
9019 Note that the actual module name, not its filename, should be given.
9020 Eg, "Foo::Bar" instead of "Foo/Bar.pm". ver, if specified and not NULL,
9021 provides version semantics similar to C<use Foo::Bar VERSION>. The optional
9022 trailing arguments can be used to specify arguments to the module's C<import()>
9023 method, similar to C<use Foo::Bar VERSION LIST>; their precise handling depends
9024 on the flags. The flags argument is a bitwise-ORed collection of any of
9025 C<PERL_LOADMOD_DENY>, C<PERL_LOADMOD_NOIMPORT>, or C<PERL_LOADMOD_IMPORT_OPS>
9026 (or 0 for no flags).
9027
9028 If C<PERL_LOADMOD_NOIMPORT> is set, the module is loaded as if with an empty
9029 import list, as in C<use Foo::Bar ()>; this is the only circumstance in which
9030 the trailing optional arguments may be omitted entirely. Otherwise, if
9031 C<PERL_LOADMOD_IMPORT_OPS> is set, the trailing arguments must consist of
9032 exactly one C<OP*>, containing the op tree that produces the relevant import
9033 arguments. Otherwise, the trailing arguments must all be C<SV*> values that
9034 will be used as import arguments; and the list must be terminated with C<(SV*)
9035 NULL>. If neither C<PERL_LOADMOD_NOIMPORT> nor C<PERL_LOADMOD_IMPORT_OPS> is
9036 set, the trailing C<NULL> pointer is needed even if no import arguments are
9037 desired. The reference count for each specified C<SV*> argument is
9038 decremented. In addition, the C<name> argument is modified.
9039
9040 If C<PERL_LOADMOD_DENY> is set, the module is loaded as if with C<no> rather
9041 than C<use>.
9042
9043 =for apidoc Amnh||PERL_LOADMOD_DENY
9044 =for apidoc Amnh||PERL_LOADMOD_NOIMPORT
9045 =for apidoc Amnh||PERL_LOADMOD_IMPORT_OPS
9046
9047 =for apidoc vload_module
9048 Like C<L</load_module>> but the arguments are an encapsulated argument list.
9049
9050 =for apidoc load_module_nocontext
9051 Like C<L</load_module>> but does not take a thread context (C<aTHX>) parameter,
9052 so is used in situations where the caller doesn't already have the thread
9053 context.
9054
9055 =cut */
9056
9057 void
9058 Perl_load_module(pTHX_ U32 flags, SV *name, SV *ver, ...)
9059 {
9060     va_list args;
9061
9062     PERL_ARGS_ASSERT_LOAD_MODULE;
9063
9064     va_start(args, ver);
9065     vload_module(flags, name, ver, &args);
9066     va_end(args);
9067 }
9068
9069 #ifdef MULTIPLICITY
9070 void
9071 Perl_load_module_nocontext(U32 flags, SV *name, SV *ver, ...)
9072 {
9073     dTHX;
9074     va_list args;
9075     PERL_ARGS_ASSERT_LOAD_MODULE_NOCONTEXT;
9076     va_start(args, ver);
9077     vload_module(flags, name, ver, &args);
9078     va_end(args);
9079 }
9080 #endif
9081
9082 void
9083 Perl_vload_module(pTHX_ U32 flags, SV *name, SV *ver, va_list *args)
9084 {
9085     OP *veop, *imop;
9086     OP * modname;
9087     I32 floor;
9088
9089     PERL_ARGS_ASSERT_VLOAD_MODULE;
9090
9091     /* utilize() fakes up a BEGIN { require ..; import ... }, so make sure
9092      * that it has a PL_parser to play with while doing that, and also
9093      * that it doesn't mess with any existing parser, by creating a tmp
9094      * new parser with lex_start(). This won't actually be used for much,
9095      * since pp_require() will create another parser for the real work.
9096      * The ENTER/LEAVE pair protect callers from any side effects of use.
9097      *
9098      * start_subparse() creates a new PL_compcv. This means that any ops
9099      * allocated below will be allocated from that CV's op slab, and so
9100      * will be automatically freed if the utilise() fails
9101      */
9102
9103     ENTER;
9104     SAVEVPTR(PL_curcop);
9105     lex_start(NULL, NULL, LEX_START_SAME_FILTER);
9106     floor = start_subparse(FALSE, 0);
9107
9108     modname = newSVOP(OP_CONST, 0, name);
9109     modname->op_private |= OPpCONST_BARE;
9110     if (ver) {
9111         veop = newSVOP(OP_CONST, 0, ver);
9112     }
9113     else
9114         veop = NULL;
9115     if (flags & PERL_LOADMOD_NOIMPORT) {
9116         imop = sawparens(newNULLLIST());
9117     }
9118     else if (flags & PERL_LOADMOD_IMPORT_OPS) {
9119         imop = va_arg(*args, OP*);
9120     }
9121     else {
9122         SV *sv;
9123         imop = NULL;
9124         sv = va_arg(*args, SV*);
9125         while (sv) {
9126             imop = op_append_elem(OP_LIST, imop, newSVOP(OP_CONST, 0, sv));
9127             sv = va_arg(*args, SV*);
9128         }
9129     }
9130
9131     utilize(!(flags & PERL_LOADMOD_DENY), floor, veop, modname, imop);
9132     LEAVE;
9133 }
9134
9135 PERL_STATIC_INLINE OP *
9136 S_new_entersubop(pTHX_ GV *gv, OP *arg)
9137 {
9138     return newUNOP(OP_ENTERSUB, OPf_STACKED,
9139                    newLISTOP(OP_LIST, 0, arg,
9140                              newUNOP(OP_RV2CV, 0,
9141                                      newGVOP(OP_GV, 0, gv))));
9142 }
9143
9144 OP *
9145 Perl_dofile(pTHX_ OP *term, I32 force_builtin)
9146 {
9147     OP *doop;
9148     GV *gv;
9149
9150     PERL_ARGS_ASSERT_DOFILE;
9151
9152     if (!force_builtin && (gv = gv_override("do", 2))) {
9153         doop = S_new_entersubop(aTHX_ gv, term);
9154     }
9155     else {
9156         doop = newUNOP(OP_DOFILE, 0, scalar(term));
9157     }
9158     return doop;
9159 }
9160
9161 /*
9162 =for apidoc_section $optree_construction
9163
9164 =for apidoc newSLICEOP
9165
9166 Constructs, checks, and returns an C<lslice> (list slice) op.  C<flags>
9167 gives the eight bits of C<op_flags>, except that C<OPf_KIDS> will
9168 be set automatically, and, shifted up eight bits, the eight bits of
9169 C<op_private>, except that the bit with value 1 or 2 is automatically
9170 set as required.  C<listval> and C<subscript> supply the parameters of
9171 the slice; they are consumed by this function and become part of the
9172 constructed op tree.
9173
9174 =cut
9175 */
9176
9177 OP *
9178 Perl_newSLICEOP(pTHX_ I32 flags, OP *subscript, OP *listval)
9179 {
9180     return newBINOP(OP_LSLICE, flags,
9181             list(force_list(subscript, TRUE)),
9182             list(force_list(listval,   TRUE)));
9183 }
9184
9185 #define ASSIGN_SCALAR 0
9186 #define ASSIGN_LIST   1
9187 #define ASSIGN_REF    2
9188
9189 /* given the optree o on the LHS of an assignment, determine whether its:
9190  *  ASSIGN_SCALAR   $x  = ...
9191  *  ASSIGN_LIST    ($x) = ...
9192  *  ASSIGN_REF     \$x  = ...
9193  */
9194
9195 STATIC I32
9196 S_assignment_type(pTHX_ const OP *o)
9197 {
9198     unsigned type;
9199     U8 flags;
9200     U8 ret;
9201
9202     if (!o)
9203         return ASSIGN_LIST;
9204
9205     if (o->op_type == OP_SREFGEN)
9206     {
9207         OP * const kid = cUNOPx(cUNOPo->op_first)->op_first;
9208         type = kid->op_type;
9209         flags = o->op_flags | kid->op_flags;
9210         if (!(flags & OPf_PARENS)
9211           && (kid->op_type == OP_RV2AV || kid->op_type == OP_PADAV ||
9212               kid->op_type == OP_RV2HV || kid->op_type == OP_PADHV ))
9213             return ASSIGN_REF;
9214         ret = ASSIGN_REF;
9215     } else {
9216         if ((o->op_type == OP_NULL) && (o->op_flags & OPf_KIDS))
9217             o = cUNOPo->op_first;
9218         flags = o->op_flags;
9219         type = o->op_type;
9220         ret = ASSIGN_SCALAR;
9221     }
9222
9223     if (type == OP_COND_EXPR) {
9224         OP * const sib = OpSIBLING(cLOGOPo->op_first);
9225         const I32 t = assignment_type(sib);
9226         const I32 f = assignment_type(OpSIBLING(sib));
9227
9228         if (t == ASSIGN_LIST && f == ASSIGN_LIST)
9229             return ASSIGN_LIST;
9230         if ((t == ASSIGN_LIST) ^ (f == ASSIGN_LIST))
9231             yyerror("Assignment to both a list and a scalar");
9232         return ASSIGN_SCALAR;
9233     }
9234
9235     if (type == OP_LIST &&
9236         (flags & OPf_WANT) == OPf_WANT_SCALAR &&
9237         o->op_private & OPpLVAL_INTRO)
9238         return ret;
9239
9240     if (type == OP_LIST || flags & OPf_PARENS ||
9241         type == OP_RV2AV || type == OP_RV2HV ||
9242         type == OP_ASLICE || type == OP_HSLICE ||
9243         type == OP_KVASLICE || type == OP_KVHSLICE || type == OP_REFGEN)
9244         return ASSIGN_LIST;
9245
9246     if (type == OP_PADAV || type == OP_PADHV)
9247         return ASSIGN_LIST;
9248
9249     if (type == OP_RV2SV)
9250         return ret;
9251
9252     return ret;
9253 }
9254
9255 static OP *
9256 S_newONCEOP(pTHX_ OP *initop, OP *padop)
9257 {
9258     const PADOFFSET target = padop->op_targ;
9259     OP *const other = newOP(OP_PADSV,
9260                             padop->op_flags
9261                             | ((padop->op_private & ~OPpLVAL_INTRO) << 8));
9262     OP *const first = newOP(OP_NULL, 0);
9263     OP *const nullop = newCONDOP(0, first, initop, other);
9264     /* XXX targlex disabled for now; see ticket #124160
9265         newCONDOP(0, first, S_maybe_targlex(aTHX_ initop), other);
9266      */
9267     OP *const condop = first->op_next;
9268
9269     OpTYPE_set(condop, OP_ONCE);
9270     other->op_targ = target;
9271     nullop->op_flags |= OPf_WANT_SCALAR;
9272
9273     /* Store the initializedness of state vars in a separate
9274        pad entry.  */
9275     condop->op_targ =
9276       pad_add_name_pvn("$",1,padadd_NO_DUP_CHECK|padadd_STATE,0,0);
9277     /* hijacking PADSTALE for uninitialized state variables */
9278     SvPADSTALE_on(PAD_SVl(condop->op_targ));
9279
9280     return nullop;
9281 }
9282
9283 /*
9284 =for apidoc newASSIGNOP
9285
9286 Constructs, checks, and returns an assignment op.  C<left> and C<right>
9287 supply the parameters of the assignment; they are consumed by this
9288 function and become part of the constructed op tree.
9289
9290 If C<optype> is C<OP_ANDASSIGN>, C<OP_ORASSIGN>, or C<OP_DORASSIGN>, then
9291 a suitable conditional optree is constructed.  If C<optype> is the opcode
9292 of a binary operator, such as C<OP_BIT_OR>, then an op is constructed that
9293 performs the binary operation and assigns the result to the left argument.
9294 Either way, if C<optype> is non-zero then C<flags> has no effect.
9295
9296 If C<optype> is zero, then a plain scalar or list assignment is
9297 constructed.  Which type of assignment it is is automatically determined.
9298 C<flags> gives the eight bits of C<op_flags>, except that C<OPf_KIDS>
9299 will be set automatically, and, shifted up eight bits, the eight bits
9300 of C<op_private>, except that the bit with value 1 or 2 is automatically
9301 set as required.
9302
9303 =cut
9304 */
9305
9306 OP *
9307 Perl_newASSIGNOP(pTHX_ I32 flags, OP *left, I32 optype, OP *right)
9308 {
9309     OP *o;
9310     I32 assign_type;
9311
9312     switch (optype) {
9313         case 0: break;
9314         case OP_ANDASSIGN:
9315         case OP_ORASSIGN:
9316         case OP_DORASSIGN:
9317             right = scalar(right);
9318             return newLOGOP(optype, 0,
9319                 op_lvalue(scalar(left), optype),
9320                 newBINOP(OP_SASSIGN, OPpASSIGN_BACKWARDS<<8, right, right));
9321         default:
9322             return newBINOP(optype, OPf_STACKED,
9323                 op_lvalue(scalar(left), optype), scalar(right));
9324     }
9325
9326     if ((assign_type = assignment_type(left)) == ASSIGN_LIST) {
9327         OP *state_var_op = NULL;
9328         static const char no_list_state[] = "Initialization of state variables"
9329             " in list currently forbidden";
9330         OP *curop;
9331
9332         if (left->op_type == OP_ASLICE || left->op_type == OP_HSLICE)
9333             left->op_private &= ~ OPpSLICEWARNING;
9334
9335         PL_modcount = 0;
9336         left = op_lvalue(left, OP_AASSIGN);
9337         curop = list(force_list(left, TRUE));
9338         o = newBINOP(OP_AASSIGN, flags, list(force_list(right, TRUE)), curop);
9339         o->op_private = (U8)(0 | (flags >> 8));
9340
9341         if (OP_TYPE_IS_OR_WAS(left, OP_LIST))
9342         {
9343             OP *lop = ((LISTOP*)left)->op_first, *vop, *eop;
9344             if (!(left->op_flags & OPf_PARENS) &&
9345                     lop->op_type == OP_PUSHMARK &&
9346                     (vop = OpSIBLING(lop)) &&
9347                     (vop->op_type == OP_PADAV || vop->op_type == OP_PADHV) &&
9348                     !(vop->op_flags & OPf_PARENS) &&
9349                     (vop->op_private & (OPpLVAL_INTRO|OPpPAD_STATE)) ==
9350                         (OPpLVAL_INTRO|OPpPAD_STATE) &&
9351                     (eop = OpSIBLING(vop)) &&
9352                     eop->op_type == OP_ENTERSUB &&
9353                     !OpHAS_SIBLING(eop)) {
9354                 state_var_op = vop;
9355             } else {
9356                 while (lop) {
9357                     if ((lop->op_type == OP_PADSV ||
9358                          lop->op_type == OP_PADAV ||
9359                          lop->op_type == OP_PADHV ||
9360                          lop->op_type == OP_PADANY)
9361                       && (lop->op_private & OPpPAD_STATE)
9362                     )
9363                         yyerror(no_list_state);
9364                     lop = OpSIBLING(lop);
9365                 }
9366             }
9367         }
9368         else if (  (left->op_private & OPpLVAL_INTRO)
9369                 && (left->op_private & OPpPAD_STATE)
9370                 && (   left->op_type == OP_PADSV
9371                     || left->op_type == OP_PADAV
9372                     || left->op_type == OP_PADHV
9373                     || left->op_type == OP_PADANY)
9374         ) {
9375                 /* All single variable list context state assignments, hence
9376                    state ($a) = ...
9377                    (state $a) = ...
9378                    state @a = ...
9379                    state (@a) = ...
9380                    (state @a) = ...
9381                    state %a = ...
9382                    state (%a) = ...
9383                    (state %a) = ...
9384                 */
9385                 if (left->op_flags & OPf_PARENS)
9386                     yyerror(no_list_state);
9387                 else
9388                     state_var_op = left;
9389         }
9390
9391         /* optimise @a = split(...) into:
9392         * @{expr}:              split(..., @{expr}) (where @a is not flattened)
9393         * @a, my @a, local @a:  split(...)          (where @a is attached to
9394         *                                            the split op itself)
9395         */
9396
9397         if (   right
9398             && right->op_type == OP_SPLIT
9399             /* don't do twice, e.g. @b = (@a = split) */
9400             && !(right->op_private & OPpSPLIT_ASSIGN))
9401         {
9402             OP *gvop = NULL;
9403
9404             if (   (  left->op_type == OP_RV2AV
9405                    && (gvop=((UNOP*)left)->op_first)->op_type==OP_GV)
9406                 || left->op_type == OP_PADAV)
9407             {
9408                 /* @pkg or @lex or local @pkg' or 'my @lex' */
9409                 OP *tmpop;
9410                 if (gvop) {
9411 #ifdef USE_ITHREADS
9412                     ((PMOP*)right)->op_pmreplrootu.op_pmtargetoff
9413                         = cPADOPx(gvop)->op_padix;
9414                     cPADOPx(gvop)->op_padix = 0;        /* steal it */
9415 #else
9416                     ((PMOP*)right)->op_pmreplrootu.op_pmtargetgv
9417                         = MUTABLE_GV(cSVOPx(gvop)->op_sv);
9418                     cSVOPx(gvop)->op_sv = NULL; /* steal it */
9419 #endif
9420                     right->op_private |=
9421                         left->op_private & OPpOUR_INTRO;
9422                 }
9423                 else {
9424                     ((PMOP*)right)->op_pmreplrootu.op_pmtargetoff = left->op_targ;
9425                     left->op_targ = 0;  /* steal it */
9426                     right->op_private |= OPpSPLIT_LEX;
9427                 }
9428                 right->op_private |= left->op_private & OPpLVAL_INTRO;
9429
9430               detach_split:
9431                 tmpop = cUNOPo->op_first;       /* to list (nulled) */
9432                 tmpop = ((UNOP*)tmpop)->op_first; /* to pushmark */
9433                 assert(OpSIBLING(tmpop) == right);
9434                 assert(!OpHAS_SIBLING(right));
9435                 /* detach the split subtreee from the o tree,
9436                  * then free the residual o tree */
9437                 op_sibling_splice(cUNOPo->op_first, tmpop, 1, NULL);
9438                 op_free(o);                     /* blow off assign */
9439                 right->op_private |= OPpSPLIT_ASSIGN;
9440                 right->op_flags &= ~OPf_WANT;
9441                         /* "I don't know and I don't care." */
9442                 return right;
9443             }
9444             else if (left->op_type == OP_RV2AV) {
9445                 /* @{expr} */
9446
9447                 OP *pushop = cUNOPx(cBINOPo->op_last)->op_first;
9448                 assert(OpSIBLING(pushop) == left);
9449                 /* Detach the array ...  */
9450                 op_sibling_splice(cBINOPo->op_last, pushop, 1, NULL);
9451                 /* ... and attach it to the split.  */
9452                 op_sibling_splice(right, cLISTOPx(right)->op_last,
9453                                   0, left);
9454                 right->op_flags |= OPf_STACKED;
9455                 /* Detach split and expunge aassign as above.  */
9456                 goto detach_split;
9457             }
9458             else if (PL_modcount < RETURN_UNLIMITED_NUMBER &&
9459                     ((LISTOP*)right)->op_last->op_type == OP_CONST)
9460             {
9461                 /* convert split(...,0) to split(..., PL_modcount+1) */
9462                 SV ** const svp =
9463                     &((SVOP*)((LISTOP*)right)->op_last)->op_sv;
9464                 SV * const sv = *svp;
9465                 if (SvIOK(sv) && SvIVX(sv) == 0)
9466                 {
9467                   if (right->op_private & OPpSPLIT_IMPLIM) {
9468                     /* our own SV, created in ck_split */
9469                     SvREADONLY_off(sv);
9470                     sv_setiv(sv, PL_modcount+1);
9471                   }
9472                   else {
9473                     /* SV may belong to someone else */
9474                     SvREFCNT_dec(sv);
9475                     *svp = newSViv(PL_modcount+1);
9476                   }
9477                 }
9478             }
9479         }
9480
9481         if (state_var_op)
9482             o = S_newONCEOP(aTHX_ o, state_var_op);
9483         return o;
9484     }
9485     if (assign_type == ASSIGN_REF)
9486         return newBINOP(OP_REFASSIGN, flags, scalar(right), left);
9487     if (!right)
9488         right = newOP(OP_UNDEF, 0);
9489     if (right->op_type == OP_READLINE) {
9490         right->op_flags |= OPf_STACKED;
9491         return newBINOP(OP_NULL, flags, op_lvalue(scalar(left), OP_SASSIGN),
9492                 scalar(right));
9493     }
9494     else {
9495         o = newBINOP(OP_SASSIGN, flags,
9496             scalar(right), op_lvalue(scalar(left), OP_SASSIGN) );
9497     }
9498     return o;
9499 }
9500
9501 /*
9502 =for apidoc newSTATEOP
9503
9504 Constructs a state op (COP).  The state op is normally a C<nextstate> op,
9505 but will be a C<dbstate> op if debugging is enabled for currently-compiled
9506 code.  The state op is populated from C<PL_curcop> (or C<PL_compiling>).
9507 If C<label> is non-null, it supplies the name of a label to attach to
9508 the state op; this function takes ownership of the memory pointed at by
9509 C<label>, and will free it.  C<flags> gives the eight bits of C<op_flags>
9510 for the state op.
9511
9512 If C<o> is null, the state op is returned.  Otherwise the state op is
9513 combined with C<o> into a C<lineseq> list op, which is returned.  C<o>
9514 is consumed by this function and becomes part of the returned op tree.
9515
9516 =cut
9517 */
9518
9519 OP *
9520 Perl_newSTATEOP(pTHX_ I32 flags, char *label, OP *o)
9521 {
9522     const U32 seq = intro_my();
9523     const U32 utf8 = flags & SVf_UTF8;
9524     COP *cop;
9525
9526     PL_parser->parsed_sub = 0;
9527
9528     flags &= ~SVf_UTF8;
9529
9530     NewOp(1101, cop, 1, COP);
9531     if (PERLDB_LINE && CopLINE(PL_curcop) && PL_curstash != PL_debstash) {
9532         OpTYPE_set(cop, OP_DBSTATE);
9533     }
9534     else {
9535         OpTYPE_set(cop, OP_NEXTSTATE);
9536     }
9537     cop->op_flags = (U8)flags;
9538     CopHINTS_set(cop, PL_hints);
9539 #ifdef VMS
9540     if (VMSISH_HUSHED) cop->op_private |= OPpHUSH_VMSISH;
9541 #endif
9542     cop->op_next = (OP*)cop;
9543
9544     cop->cop_seq = seq;
9545     cop->cop_warnings = DUP_WARNINGS(PL_curcop->cop_warnings);
9546     CopHINTHASH_set(cop, cophh_copy(CopHINTHASH_get(PL_curcop)));
9547     if (label) {
9548         Perl_cop_store_label(aTHX_ cop, label, strlen(label), utf8);
9549
9550         PL_hints |= HINT_BLOCK_SCOPE;
9551         /* It seems that we need to defer freeing this pointer, as other parts
9552            of the grammar end up wanting to copy it after this op has been
9553            created. */
9554         SAVEFREEPV(label);
9555     }
9556
9557     if (PL_parser->preambling != NOLINE) {
9558         CopLINE_set(cop, PL_parser->preambling);
9559         PL_parser->copline = NOLINE;
9560     }
9561     else if (PL_parser->copline == NOLINE)
9562         CopLINE_set(cop, CopLINE(PL_curcop));
9563     else {
9564         CopLINE_set(cop, PL_parser->copline);
9565         PL_parser->copline = NOLINE;
9566     }
9567 #ifdef USE_ITHREADS
9568     CopFILE_set(cop, CopFILE(PL_curcop));       /* XXX share in a pvtable? */
9569 #else
9570     CopFILEGV_set(cop, CopFILEGV(PL_curcop));
9571 #endif
9572     CopSTASH_set(cop, PL_curstash);
9573
9574     if (cop->op_type == OP_DBSTATE) {
9575         /* this line can have a breakpoint - store the cop in IV */
9576         AV *av = CopFILEAVx(PL_curcop);
9577         if (av) {
9578             SV * const * const svp = av_fetch(av, CopLINE(cop), FALSE);
9579             if (svp && *svp != &PL_sv_undef ) {
9580                 (void)SvIOK_on(*svp);
9581                 SvIV_set(*svp, PTR2IV(cop));
9582             }
9583         }
9584     }
9585
9586     if (flags & OPf_SPECIAL)
9587         op_null((OP*)cop);
9588     return op_prepend_elem(OP_LINESEQ, (OP*)cop, o);
9589 }
9590
9591 /*
9592 =for apidoc newLOGOP
9593
9594 Constructs, checks, and returns a logical (flow control) op.  C<type>
9595 is the opcode.  C<flags> gives the eight bits of C<op_flags>, except
9596 that C<OPf_KIDS> will be set automatically, and, shifted up eight bits,
9597 the eight bits of C<op_private>, except that the bit with value 1 is
9598 automatically set.  C<first> supplies the expression controlling the
9599 flow, and C<other> supplies the side (alternate) chain of ops; they are
9600 consumed by this function and become part of the constructed op tree.
9601
9602 =cut
9603 */
9604
9605 OP *
9606 Perl_newLOGOP(pTHX_ I32 type, I32 flags, OP *first, OP *other)
9607 {
9608     PERL_ARGS_ASSERT_NEWLOGOP;
9609
9610     return new_logop(type, flags, &first, &other);
9611 }
9612
9613
9614 /* See if the optree o contains a single OP_CONST (plus possibly
9615  * surrounding enter/nextstate/null etc). If so, return it, else return
9616  * NULL.
9617  */
9618
9619 STATIC OP *
9620 S_search_const(pTHX_ OP *o)
9621 {
9622     PERL_ARGS_ASSERT_SEARCH_CONST;
9623
9624   redo:
9625     switch (o->op_type) {
9626         case OP_CONST:
9627             return o;
9628         case OP_NULL:
9629             if (o->op_flags & OPf_KIDS) {
9630                 o = cUNOPo->op_first;
9631                 goto redo;
9632             }
9633             break;
9634         case OP_LEAVE:
9635         case OP_SCOPE:
9636         case OP_LINESEQ:
9637         {
9638             OP *kid;
9639             if (!(o->op_flags & OPf_KIDS))
9640                 return NULL;
9641             kid = cLISTOPo->op_first;
9642
9643             do {
9644                 switch (kid->op_type) {
9645                     case OP_ENTER:
9646                     case OP_NULL:
9647                     case OP_NEXTSTATE:
9648                         kid = OpSIBLING(kid);
9649                         break;
9650                     default:
9651                         if (kid != cLISTOPo->op_last)
9652                             return NULL;
9653                         goto last;
9654                 }
9655             } while (kid);
9656
9657             if (!kid)
9658                 kid = cLISTOPo->op_last;
9659           last:
9660              o = kid;
9661              goto redo;
9662         }
9663     }
9664
9665     return NULL;
9666 }
9667
9668
9669 STATIC OP *
9670 S_new_logop(pTHX_ I32 type, I32 flags, OP** firstp, OP** otherp)
9671 {
9672     LOGOP *logop;
9673     OP *o;
9674     OP *first;
9675     OP *other;
9676     OP *cstop = NULL;
9677     int prepend_not = 0;
9678
9679     PERL_ARGS_ASSERT_NEW_LOGOP;
9680
9681     first = *firstp;
9682     other = *otherp;
9683
9684     /* [perl #59802]: Warn about things like "return $a or $b", which
9685        is parsed as "(return $a) or $b" rather than "return ($a or
9686        $b)".  NB: This also applies to xor, which is why we do it
9687        here.
9688      */
9689     switch (first->op_type) {
9690     case OP_NEXT:
9691     case OP_LAST:
9692     case OP_REDO:
9693         /* XXX: Perhaps we should emit a stronger warning for these.
9694            Even with the high-precedence operator they don't seem to do
9695            anything sensible.
9696
9697            But until we do, fall through here.
9698          */
9699     case OP_RETURN:
9700     case OP_EXIT:
9701     case OP_DIE:
9702     case OP_GOTO:
9703         /* XXX: Currently we allow people to "shoot themselves in the
9704            foot" by explicitly writing "(return $a) or $b".
9705
9706            Warn unless we are looking at the result from folding or if
9707            the programmer explicitly grouped the operators like this.
9708            The former can occur with e.g.
9709
9710                 use constant FEATURE => ( $] >= ... );
9711                 sub { not FEATURE and return or do_stuff(); }
9712          */
9713         if (!first->op_folded && !(first->op_flags & OPf_PARENS))
9714             Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX),
9715                            "Possible precedence issue with control flow operator");
9716         /* XXX: Should we optimze this to "return $a;" (i.e. remove
9717            the "or $b" part)?
9718         */
9719         break;
9720     }
9721
9722     if (type == OP_XOR)         /* Not short circuit, but here by precedence. */
9723         return newBINOP(type, flags, scalar(first), scalar(other));
9724
9725     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_LOGOP
9726         || type == OP_CUSTOM);
9727
9728     scalarboolean(first);
9729
9730     /* search for a constant op that could let us fold the test */
9731     if ((cstop = search_const(first))) {
9732         if (cstop->op_private & OPpCONST_STRICT)
9733             no_bareword_allowed(cstop);
9734         else if ((cstop->op_private & OPpCONST_BARE))
9735                 Perl_ck_warner(aTHX_ packWARN(WARN_BAREWORD), "Bareword found in conditional");
9736         if ((type == OP_AND &&  SvTRUE(((SVOP*)cstop)->op_sv)) ||
9737             (type == OP_OR  && !SvTRUE(((SVOP*)cstop)->op_sv)) ||
9738             (type == OP_DOR && !SvOK(((SVOP*)cstop)->op_sv))) {
9739             /* Elide the (constant) lhs, since it can't affect the outcome */
9740             *firstp = NULL;
9741             if (other->op_type == OP_CONST)
9742                 other->op_private |= OPpCONST_SHORTCIRCUIT;
9743             op_free(first);
9744             if (other->op_type == OP_LEAVE)
9745                 other = newUNOP(OP_NULL, OPf_SPECIAL, other);
9746             else if (other->op_type == OP_MATCH
9747                   || other->op_type == OP_SUBST
9748                   || other->op_type == OP_TRANSR
9749                   || other->op_type == OP_TRANS)
9750                 /* Mark the op as being unbindable with =~ */
9751                 other->op_flags |= OPf_SPECIAL;
9752
9753             other->op_folded = 1;
9754             return other;
9755         }
9756         else {
9757             /* Elide the rhs, since the outcome is entirely determined by
9758              * the (constant) lhs */
9759
9760             /* check for C<my $x if 0>, or C<my($x,$y) if 0> */
9761             const OP *o2 = other;
9762             if ( ! (o2->op_type == OP_LIST
9763                     && (( o2 = cUNOPx(o2)->op_first))
9764                     && o2->op_type == OP_PUSHMARK
9765                     && (( o2 = OpSIBLING(o2))) )
9766             )
9767                 o2 = other;
9768             if ((o2->op_type == OP_PADSV || o2->op_type == OP_PADAV
9769                         || o2->op_type == OP_PADHV)
9770                 && o2->op_private & OPpLVAL_INTRO
9771                 && !(o2->op_private & OPpPAD_STATE))
9772             {
9773         Perl_croak(aTHX_ "This use of my() in false conditional is "
9774                           "no longer allowed");
9775             }
9776
9777             *otherp = NULL;
9778             if (cstop->op_type == OP_CONST)
9779                 cstop->op_private |= OPpCONST_SHORTCIRCUIT;
9780             op_free(other);
9781             return first;
9782         }
9783     }
9784     else if ((first->op_flags & OPf_KIDS) && type != OP_DOR
9785         && ckWARN(WARN_MISC)) /* [#24076] Don't warn for <FH> err FOO. */
9786     {
9787         const OP * const k1 = ((UNOP*)first)->op_first;
9788         const OP * const k2 = OpSIBLING(k1);
9789         OPCODE warnop = 0;
9790         switch (first->op_type)
9791         {
9792         case OP_NULL:
9793             if (k2 && k2->op_type == OP_READLINE
9794                   && (k2->op_flags & OPf_STACKED)
9795                   && ((k1->op_flags & OPf_WANT) == OPf_WANT_SCALAR))
9796             {
9797                 warnop = k2->op_type;
9798             }
9799             break;
9800
9801         case OP_SASSIGN:
9802             if (k1->op_type == OP_READDIR
9803                   || k1->op_type == OP_GLOB
9804                   || (k1->op_type == OP_NULL && k1->op_targ == OP_GLOB)
9805                  || k1->op_type == OP_EACH
9806                  || k1->op_type == OP_AEACH)
9807             {
9808                 warnop = ((k1->op_type == OP_NULL)
9809                           ? (OPCODE)k1->op_targ : k1->op_type);
9810             }
9811             break;
9812         }
9813         if (warnop) {
9814             const line_t oldline = CopLINE(PL_curcop);
9815             /* This ensures that warnings are reported at the first line
9816                of the construction, not the last.  */
9817             CopLINE_set(PL_curcop, PL_parser->copline);
9818             Perl_warner(aTHX_ packWARN(WARN_MISC),
9819                  "Value of %s%s can be \"0\"; test with defined()",
9820                  PL_op_desc[warnop],
9821                  ((warnop == OP_READLINE || warnop == OP_GLOB)
9822                   ? " construct" : "() operator"));
9823             CopLINE_set(PL_curcop, oldline);
9824         }
9825     }
9826
9827     /* optimize AND and OR ops that have NOTs as children */
9828     if (first->op_type == OP_NOT
9829         && (first->op_flags & OPf_KIDS)
9830         && ((first->op_flags & OPf_SPECIAL) /* unless ($x) { } */
9831             || (other->op_type == OP_NOT))  /* if (!$x && !$y) { } */
9832         ) {
9833         if (type == OP_AND || type == OP_OR) {
9834             if (type == OP_AND)
9835                 type = OP_OR;
9836             else
9837                 type = OP_AND;
9838             op_null(first);
9839             if (other->op_type == OP_NOT) { /* !a AND|OR !b => !(a OR|AND b) */
9840                 op_null(other);
9841                 prepend_not = 1; /* prepend a NOT op later */
9842             }
9843         }
9844     }
9845
9846     logop = alloc_LOGOP(type, first, LINKLIST(other));
9847     logop->op_flags |= (U8)flags;
9848     logop->op_private = (U8)(1 | (flags >> 8));
9849
9850     /* establish postfix order */
9851     logop->op_next = LINKLIST(first);
9852     first->op_next = (OP*)logop;
9853     assert(!OpHAS_SIBLING(first));
9854     op_sibling_splice((OP*)logop, first, 0, other);
9855
9856     CHECKOP(type,logop);
9857
9858     o = newUNOP(prepend_not ? OP_NOT : OP_NULL,
9859                 PL_opargs[type] & OA_RETSCALAR ? OPf_WANT_SCALAR : 0,
9860                 (OP*)logop);
9861     other->op_next = o;
9862
9863     return o;
9864 }
9865
9866 /*
9867 =for apidoc newCONDOP
9868
9869 Constructs, checks, and returns a conditional-expression (C<cond_expr>)
9870 op.  C<flags> gives the eight bits of C<op_flags>, except that C<OPf_KIDS>
9871 will be set automatically, and, shifted up eight bits, the eight bits of
9872 C<op_private>, except that the bit with value 1 is automatically set.
9873 C<first> supplies the expression selecting between the two branches,
9874 and C<trueop> and C<falseop> supply the branches; they are consumed by
9875 this function and become part of the constructed op tree.
9876
9877 =cut
9878 */
9879
9880 OP *
9881 Perl_newCONDOP(pTHX_ I32 flags, OP *first, OP *trueop, OP *falseop)
9882 {
9883     LOGOP *logop;
9884     OP *start;
9885     OP *o;
9886     OP *cstop;
9887
9888     PERL_ARGS_ASSERT_NEWCONDOP;
9889
9890     if (!falseop)
9891         return newLOGOP(OP_AND, 0, first, trueop);
9892     if (!trueop)
9893         return newLOGOP(OP_OR, 0, first, falseop);
9894
9895     scalarboolean(first);
9896     if ((cstop = search_const(first))) {
9897         /* Left or right arm of the conditional?  */
9898         const bool left = SvTRUE(((SVOP*)cstop)->op_sv);
9899         OP *live = left ? trueop : falseop;
9900         OP *const dead = left ? falseop : trueop;
9901         if (cstop->op_private & OPpCONST_BARE &&
9902             cstop->op_private & OPpCONST_STRICT) {
9903             no_bareword_allowed(cstop);
9904         }
9905         op_free(first);
9906         op_free(dead);
9907         if (live->op_type == OP_LEAVE)
9908             live = newUNOP(OP_NULL, OPf_SPECIAL, live);
9909         else if (live->op_type == OP_MATCH || live->op_type == OP_SUBST
9910               || live->op_type == OP_TRANS || live->op_type == OP_TRANSR)
9911             /* Mark the op as being unbindable with =~ */
9912             live->op_flags |= OPf_SPECIAL;
9913         live->op_folded = 1;
9914         return live;
9915     }
9916     logop = alloc_LOGOP(OP_COND_EXPR, first, LINKLIST(trueop));
9917     logop->op_flags |= (U8)flags;
9918     logop->op_private = (U8)(1 | (flags >> 8));
9919     logop->op_next = LINKLIST(falseop);
9920
9921     CHECKOP(OP_COND_EXPR, /* that's logop->op_type */
9922             logop);
9923
9924     /* establish postfix order */
9925     start = LINKLIST(first);
9926     first->op_next = (OP*)logop;
9927
9928     /* make first, trueop, falseop siblings */
9929     op_sibling_splice((OP*)logop, first,  0, trueop);
9930     op_sibling_splice((OP*)logop, trueop, 0, falseop);
9931
9932     o = newUNOP(OP_NULL, 0, (OP*)logop);
9933
9934     trueop->op_next = falseop->op_next = o;
9935
9936     o->op_next = start;
9937     return o;
9938 }
9939
9940 /*
9941 =for apidoc newTRYCATCHOP
9942
9943 Constructs and returns a conditional execution statement that implements
9944 the C<try>/C<catch> semantics.  First the op tree in C<tryblock> is executed,
9945 inside a context that traps exceptions.  If an exception occurs then the
9946 optree in C<catchblock> is executed, with the trapped exception set into the
9947 lexical variable given by C<catchvar> (which must be an op of type
9948 C<OP_PADSV>).  All the optrees are consumed by this function and become part
9949 of the returned op tree.
9950
9951 The C<flags> argument is currently ignored.
9952
9953 =cut
9954  */
9955
9956 OP *
9957 Perl_newTRYCATCHOP(pTHX_ I32 flags, OP *tryblock, OP *catchvar, OP *catchblock)
9958 {
9959     OP *o, *catchop;
9960
9961     PERL_ARGS_ASSERT_NEWTRYCATCHOP;
9962     assert(catchvar->op_type == OP_PADSV);
9963
9964     PERL_UNUSED_ARG(flags);
9965
9966     /* The returned optree is shaped as:
9967      *   LISTOP leavetrycatch
9968      *       LOGOP entertrycatch
9969      *       LISTOP poptry
9970      *           $tryblock here
9971      *       LOGOP catch
9972      *           $catchblock here
9973      */
9974
9975     if(tryblock->op_type != OP_LINESEQ)
9976         tryblock = op_convert_list(OP_LINESEQ, 0, tryblock);
9977     OpTYPE_set(tryblock, OP_POPTRY);
9978
9979     /* Manually construct a naked LOGOP.
9980      * Normally if we call newLOGOP the returned value is a UNOP(OP_NULL)
9981      * containing the LOGOP we wanted as its op_first */
9982     catchop = (OP *)alloc_LOGOP(OP_CATCH, newOP(OP_NULL, 0), catchblock);
9983     OpMORESIB_set(cUNOPx(catchop)->op_first, catchblock);
9984     OpLASTSIB_set(catchblock, catchop);
9985
9986     /* Inject the catchvar's pad offset into the OP_CATCH targ */
9987     cLOGOPx(catchop)->op_targ = catchvar->op_targ;
9988     op_free(catchvar);
9989
9990     /* Build the optree structure */
9991     o = newLISTOP(OP_LIST, 0, tryblock, catchop);
9992     o = op_convert_list(OP_ENTERTRYCATCH, 0, o);
9993
9994     return o;
9995 }
9996
9997 /*
9998 =for apidoc newRANGE
9999
10000 Constructs and returns a C<range> op, with subordinate C<flip> and
10001 C<flop> ops.  C<flags> gives the eight bits of C<op_flags> for the
10002 C<flip> op and, shifted up eight bits, the eight bits of C<op_private>
10003 for both the C<flip> and C<range> ops, except that the bit with value
10004 1 is automatically set.  C<left> and C<right> supply the expressions
10005 controlling the endpoints of the range; they are consumed by this function
10006 and become part of the constructed op tree.
10007
10008 =cut
10009 */
10010
10011 OP *
10012 Perl_newRANGE(pTHX_ I32 flags, OP *left, OP *right)
10013 {
10014     LOGOP *range;
10015     OP *flip;
10016     OP *flop;
10017     OP *leftstart;
10018     OP *o;
10019
10020     PERL_ARGS_ASSERT_NEWRANGE;
10021
10022     range = alloc_LOGOP(OP_RANGE, left, LINKLIST(right));
10023     range->op_flags = OPf_KIDS;
10024     leftstart = LINKLIST(left);
10025     range->op_private = (U8)(1 | (flags >> 8));
10026
10027     /* make left and right siblings */
10028     op_sibling_splice((OP*)range, left, 0, right);
10029
10030     range->op_next = (OP*)range;
10031     flip = newUNOP(OP_FLIP, flags, (OP*)range);
10032     flop = newUNOP(OP_FLOP, 0, flip);
10033     o = newUNOP(OP_NULL, 0, flop);
10034     LINKLIST(flop);
10035     range->op_next = leftstart;
10036
10037     left->op_next = flip;
10038     right->op_next = flop;
10039
10040     range->op_targ =
10041         pad_add_name_pvn("$", 1, padadd_NO_DUP_CHECK|padadd_STATE, 0, 0);
10042     sv_upgrade(PAD_SV(range->op_targ), SVt_PVNV);
10043     flip->op_targ =
10044         pad_add_name_pvn("$", 1, padadd_NO_DUP_CHECK|padadd_STATE, 0, 0);;
10045     sv_upgrade(PAD_SV(flip->op_targ), SVt_PVNV);
10046     SvPADTMP_on(PAD_SV(flip->op_targ));
10047
10048     flip->op_private =  left->op_type == OP_CONST ? OPpFLIP_LINENUM : 0;
10049     flop->op_private = right->op_type == OP_CONST ? OPpFLIP_LINENUM : 0;
10050
10051     /* check barewords before they might be optimized aways */
10052     if (flip->op_private && cSVOPx(left)->op_private & OPpCONST_STRICT)
10053         no_bareword_allowed(left);
10054     if (flop->op_private && cSVOPx(right)->op_private & OPpCONST_STRICT)
10055         no_bareword_allowed(right);
10056
10057     flip->op_next = o;
10058     if (!flip->op_private || !flop->op_private)
10059         LINKLIST(o);            /* blow off optimizer unless constant */
10060
10061     return o;
10062 }
10063
10064 /*
10065 =for apidoc newLOOPOP
10066
10067 Constructs, checks, and returns an op tree expressing a loop.  This is
10068 only a loop in the control flow through the op tree; it does not have
10069 the heavyweight loop structure that allows exiting the loop by C<last>
10070 and suchlike.  C<flags> gives the eight bits of C<op_flags> for the
10071 top-level op, except that some bits will be set automatically as required.
10072 C<expr> supplies the expression controlling loop iteration, and C<block>
10073 supplies the body of the loop; they are consumed by this function and
10074 become part of the constructed op tree.  C<debuggable> is currently
10075 unused and should always be 1.
10076
10077 =cut
10078 */
10079
10080 OP *
10081 Perl_newLOOPOP(pTHX_ I32 flags, I32 debuggable, OP *expr, OP *block)
10082 {
10083     OP* listop;
10084     OP* o;
10085     const bool once = block && block->op_flags & OPf_SPECIAL &&
10086                       block->op_type == OP_NULL;
10087
10088     PERL_UNUSED_ARG(debuggable);
10089
10090     if (expr) {
10091         if (once && (
10092               (expr->op_type == OP_CONST && !SvTRUE(((SVOP*)expr)->op_sv))
10093            || (  expr->op_type == OP_NOT
10094               && cUNOPx(expr)->op_first->op_type == OP_CONST
10095               && SvTRUE(cSVOPx_sv(cUNOPx(expr)->op_first))
10096               )
10097            ))
10098             /* Return the block now, so that S_new_logop does not try to
10099                fold it away. */
10100         {
10101             op_free(expr);
10102             return block;       /* do {} while 0 does once */
10103         }
10104
10105         if (expr->op_type == OP_READLINE
10106             || expr->op_type == OP_READDIR
10107             || expr->op_type == OP_GLOB
10108             || expr->op_type == OP_EACH || expr->op_type == OP_AEACH
10109             || (expr->op_type == OP_NULL && expr->op_targ == OP_GLOB)) {
10110             expr = newUNOP(OP_DEFINED, 0,
10111                 newASSIGNOP(0, newDEFSVOP(), 0, expr) );
10112         } else if (expr->op_flags & OPf_KIDS) {
10113             const OP * const k1 = ((UNOP*)expr)->op_first;
10114             const OP * const k2 = k1 ? OpSIBLING(k1) : NULL;
10115             switch (expr->op_type) {
10116               case OP_NULL:
10117                 if (k2 && (k2->op_type == OP_READLINE || k2->op_type == OP_READDIR)
10118                       && (k2->op_flags & OPf_STACKED)
10119                       && ((k1->op_flags & OPf_WANT) == OPf_WANT_SCALAR))
10120                     expr = newUNOP(OP_DEFINED, 0, expr);
10121                 break;
10122
10123               case OP_SASSIGN:
10124                 if (k1 && (k1->op_type == OP_READDIR
10125                       || k1->op_type == OP_GLOB
10126                       || (k1->op_type == OP_NULL && k1->op_targ == OP_GLOB)
10127                      || k1->op_type == OP_EACH
10128                      || k1->op_type == OP_AEACH))
10129                     expr = newUNOP(OP_DEFINED, 0, expr);
10130                 break;
10131             }
10132         }
10133     }
10134
10135     /* if block is null, the next op_append_elem() would put UNSTACK, a scalar
10136      * op, in listop. This is wrong. [perl #27024] */
10137     if (!block)
10138         block = newOP(OP_NULL, 0);
10139     listop = op_append_elem(OP_LINESEQ, block, newOP(OP_UNSTACK, 0));
10140     o = new_logop(OP_AND, 0, &expr, &listop);
10141
10142     if (once) {
10143         ASSUME(listop);
10144     }
10145
10146     if (listop)
10147         ((LISTOP*)listop)->op_last->op_next = LINKLIST(o);
10148
10149     if (once && o != listop)
10150     {
10151         assert(cUNOPo->op_first->op_type == OP_AND
10152             || cUNOPo->op_first->op_type == OP_OR);
10153         o->op_next = ((LOGOP*)cUNOPo->op_first)->op_other;
10154     }
10155
10156     if (o == listop)
10157         o = newUNOP(OP_NULL, 0, o);     /* or do {} while 1 loses outer block */
10158
10159     o->op_flags |= flags;
10160     o = op_scope(o);
10161     o->op_flags |= OPf_SPECIAL; /* suppress cx_popblock() curpm restoration*/
10162     return o;
10163 }
10164
10165 /*
10166 =for apidoc newWHILEOP
10167
10168 Constructs, checks, and returns an op tree expressing a C<while> loop.
10169 This is a heavyweight loop, with structure that allows exiting the loop
10170 by C<last> and suchlike.
10171
10172 C<loop> is an optional preconstructed C<enterloop> op to use in the
10173 loop; if it is null then a suitable op will be constructed automatically.
10174 C<expr> supplies the loop's controlling expression.  C<block> supplies the
10175 main body of the loop, and C<cont> optionally supplies a C<continue> block
10176 that operates as a second half of the body.  All of these optree inputs
10177 are consumed by this function and become part of the constructed op tree.
10178
10179 C<flags> gives the eight bits of C<op_flags> for the C<leaveloop>
10180 op and, shifted up eight bits, the eight bits of C<op_private> for
10181 the C<leaveloop> op, except that (in both cases) some bits will be set
10182 automatically.  C<debuggable> is currently unused and should always be 1.
10183 C<has_my> can be supplied as true to force the
10184 loop body to be enclosed in its own scope.
10185
10186 =cut
10187 */
10188
10189 OP *
10190 Perl_newWHILEOP(pTHX_ I32 flags, I32 debuggable, LOOP *loop,
10191         OP *expr, OP *block, OP *cont, I32 has_my)
10192 {
10193     OP *redo;
10194     OP *next = NULL;
10195     OP *listop;
10196     OP *o;
10197     U8 loopflags = 0;
10198
10199     PERL_UNUSED_ARG(debuggable);
10200
10201     if (expr) {
10202         if (expr->op_type == OP_READLINE
10203          || expr->op_type == OP_READDIR
10204          || expr->op_type == OP_GLOB
10205          || expr->op_type == OP_EACH || expr->op_type == OP_AEACH
10206                      || (expr->op_type == OP_NULL && expr->op_targ == OP_GLOB)) {
10207             expr = newUNOP(OP_DEFINED, 0,
10208                 newASSIGNOP(0, newDEFSVOP(), 0, expr) );
10209         } else if (expr->op_flags & OPf_KIDS) {
10210             const OP * const k1 = ((UNOP*)expr)->op_first;
10211             const OP * const k2 = (k1) ? OpSIBLING(k1) : NULL;
10212             switch (expr->op_type) {
10213               case OP_NULL:
10214                 if (k2 && (k2->op_type == OP_READLINE || k2->op_type == OP_READDIR)
10215                       && (k2->op_flags & OPf_STACKED)
10216                       && ((k1->op_flags & OPf_WANT) == OPf_WANT_SCALAR))
10217                     expr = newUNOP(OP_DEFINED, 0, expr);
10218                 break;
10219
10220               case OP_SASSIGN:
10221                 if (k1 && (k1->op_type == OP_READDIR
10222                       || k1->op_type == OP_GLOB
10223                       || (k1->op_type == OP_NULL && k1->op_targ == OP_GLOB)
10224                      || k1->op_type == OP_EACH
10225                      || k1->op_type == OP_AEACH))
10226                     expr = newUNOP(OP_DEFINED, 0, expr);
10227                 break;
10228             }
10229         }
10230     }
10231
10232     if (!block)
10233         block = newOP(OP_NULL, 0);
10234     else if (cont || has_my) {
10235         block = op_scope(block);
10236     }
10237
10238     if (cont) {
10239         next = LINKLIST(cont);
10240     }
10241     if (expr) {
10242         OP * const unstack = newOP(OP_UNSTACK, 0);
10243         if (!next)
10244             next = unstack;
10245         cont = op_append_elem(OP_LINESEQ, cont, unstack);
10246     }
10247
10248     assert(block);
10249     listop = op_append_list(OP_LINESEQ, block, cont);
10250     assert(listop);
10251     redo = LINKLIST(listop);
10252
10253     if (expr) {
10254         scalar(listop);
10255         o = new_logop(OP_AND, 0, &expr, &listop);
10256         if (o == expr && o->op_type == OP_CONST && !SvTRUE(cSVOPo->op_sv)) {
10257             op_free((OP*)loop);
10258             return expr;                /* listop already freed by new_logop */
10259         }
10260         if (listop)
10261             ((LISTOP*)listop)->op_last->op_next =
10262                 (o == listop ? redo : LINKLIST(o));
10263     }
10264     else
10265         o = listop;
10266
10267     if (!loop) {
10268         NewOp(1101,loop,1,LOOP);
10269         OpTYPE_set(loop, OP_ENTERLOOP);
10270         loop->op_private = 0;
10271         loop->op_next = (OP*)loop;
10272     }
10273
10274     o = newBINOP(OP_LEAVELOOP, 0, (OP*)loop, o);
10275
10276     loop->op_redoop = redo;
10277     loop->op_lastop = o;
10278     o->op_private |= loopflags;
10279
10280     if (next)
10281         loop->op_nextop = next;
10282     else
10283         loop->op_nextop = o;
10284
10285     o->op_flags |= flags;
10286     o->op_private |= (flags >> 8);
10287     return o;
10288 }
10289
10290 /*
10291 =for apidoc newFOROP
10292
10293 Constructs, checks, and returns an op tree expressing a C<foreach>
10294 loop (iteration through a list of values).  This is a heavyweight loop,
10295 with structure that allows exiting the loop by C<last> and suchlike.
10296
10297 C<sv> optionally supplies the variable(s) that will be aliased to each
10298 item in turn; if null, it defaults to C<$_>.
10299 C<expr> supplies the list of values to iterate over.  C<block> supplies
10300 the main body of the loop, and C<cont> optionally supplies a C<continue>
10301 block that operates as a second half of the body.  All of these optree
10302 inputs are consumed by this function and become part of the constructed
10303 op tree.
10304
10305 C<flags> gives the eight bits of C<op_flags> for the C<leaveloop>
10306 op and, shifted up eight bits, the eight bits of C<op_private> for
10307 the C<leaveloop> op, except that (in both cases) some bits will be set
10308 automatically.
10309
10310 =cut
10311 */
10312
10313 OP *
10314 Perl_newFOROP(pTHX_ I32 flags, OP *sv, OP *expr, OP *block, OP *cont)
10315 {
10316     LOOP *loop;
10317     OP *iter;
10318     PADOFFSET padoff = 0;
10319     PADOFFSET how_many_more = 0;
10320     I32 iterflags = 0;
10321     I32 iterpflags = 0;
10322
10323     PERL_ARGS_ASSERT_NEWFOROP;
10324
10325     if (sv) {
10326         if (sv->op_type == OP_RV2SV) {  /* symbol table variable */
10327             iterpflags = sv->op_private & OPpOUR_INTRO; /* for our $x () */
10328             OpTYPE_set(sv, OP_RV2GV);
10329
10330             /* The op_type check is needed to prevent a possible segfault
10331              * if the loop variable is undeclared and 'strict vars' is in
10332              * effect. This is illegal but is nonetheless parsed, so we
10333              * may reach this point with an OP_CONST where we're expecting
10334              * an OP_GV.
10335              */
10336             if (cUNOPx(sv)->op_first->op_type == OP_GV
10337              && cGVOPx_gv(cUNOPx(sv)->op_first) == PL_defgv)
10338                 iterpflags |= OPpITER_DEF;
10339         }
10340         else if (sv->op_type == OP_PADSV) { /* private variable */
10341             iterpflags = sv->op_private & OPpLVAL_INTRO; /* for my $x () */
10342             padoff = sv->op_targ;
10343             sv->op_targ = 0;
10344             op_free(sv);
10345             sv = NULL;
10346             PAD_COMPNAME_GEN_set(padoff, PERL_INT_MAX);
10347         }
10348         else if (sv->op_type == OP_NULL && sv->op_targ == OP_SREFGEN)
10349             NOOP;
10350         else if (sv->op_type == OP_LIST) {
10351             LISTOP *list = (LISTOP *) sv;
10352             OP *pushmark = list->op_first;
10353             OP *first_padsv;
10354             UNOP *padsv;
10355             PADOFFSET i;
10356
10357             iterpflags = OPpLVAL_INTRO; /* for my ($k, $v) () */
10358
10359             if (!pushmark || pushmark->op_type != OP_PUSHMARK) {
10360                 Perl_croak(aTHX_ "panic: newFORLOOP, found %s, expecting pushmark",
10361                            pushmark ? PL_op_desc[pushmark->op_type] : "NULL");
10362             }
10363             first_padsv = OpSIBLING(pushmark);
10364             if (!first_padsv || first_padsv->op_type != OP_PADSV) {
10365                 Perl_croak(aTHX_ "panic: newFORLOOP, found %s, expecting padsv",
10366                            first_padsv ? PL_op_desc[first_padsv->op_type] : "NULL");
10367             }
10368             padoff = first_padsv->op_targ;
10369
10370             /* There should be at least one more PADSV to find, and the ops
10371                should have consecutive values in targ: */
10372             padsv = (UNOP *) OpSIBLING(first_padsv);
10373             do {
10374                 if (!padsv || padsv->op_type != OP_PADSV) {
10375                     Perl_croak(aTHX_ "panic: newFORLOOP, found %s at %zd, expecting padsv",
10376                                padsv ? PL_op_desc[padsv->op_type] : "NULL",
10377                                how_many_more);
10378                 }
10379                 ++how_many_more;
10380                 if (padsv->op_targ != padoff + how_many_more) {
10381                     Perl_croak(aTHX_ "panic: newFORLOOP, padsv at %zd targ is %zd, not %zd",
10382                                how_many_more, padsv->op_targ, padoff + how_many_more);
10383                 }
10384
10385                 padsv = (UNOP *) OpSIBLING(padsv);
10386             } while (padsv);
10387
10388             /* OK, this optree has the shape that we expected. So now *we*
10389                "claim" the Pad slots: */
10390             first_padsv->op_targ = 0;
10391             PAD_COMPNAME_GEN_set(padoff, PERL_INT_MAX);
10392
10393             i = padoff;
10394
10395             padsv = (UNOP *) OpSIBLING(first_padsv);
10396             do {
10397                 ++i;
10398                 padsv->op_targ = 0;
10399                 PAD_COMPNAME_GEN_set(i, PERL_INT_MAX);
10400
10401                 padsv = (UNOP *) OpSIBLING(padsv);
10402             } while (padsv);
10403
10404             op_free(sv);
10405             sv = NULL;
10406         }
10407         else
10408             Perl_croak(aTHX_ "Can't use %s for loop variable", PL_op_desc[sv->op_type]);
10409         if (padoff) {
10410             PADNAME * const pn = PAD_COMPNAME(padoff);
10411             const char * const name = PadnamePV(pn);
10412
10413             if (PadnameLEN(pn) == 2 && name[0] == '$' && name[1] == '_')
10414                 iterpflags |= OPpITER_DEF;
10415         }
10416     }
10417     else {
10418         sv = newGVOP(OP_GV, 0, PL_defgv);
10419         iterpflags |= OPpITER_DEF;
10420     }
10421
10422     if (expr->op_type == OP_RV2AV || expr->op_type == OP_PADAV) {
10423         expr = op_lvalue(force_list(scalar(ref(expr, OP_ITER)), TRUE), OP_GREPSTART);
10424         iterflags |= OPf_STACKED;
10425     }
10426     else if (expr->op_type == OP_NULL &&
10427              (expr->op_flags & OPf_KIDS) &&
10428              ((BINOP*)expr)->op_first->op_type == OP_FLOP)
10429     {
10430         /* Basically turn for($x..$y) into the same as for($x,$y), but we
10431          * set the STACKED flag to indicate that these values are to be
10432          * treated as min/max values by 'pp_enteriter'.
10433          */
10434         const UNOP* const flip = (UNOP*)((UNOP*)((BINOP*)expr)->op_first)->op_first;
10435         LOGOP* const range = (LOGOP*) flip->op_first;
10436         OP* const left  = range->op_first;
10437         OP* const right = OpSIBLING(left);
10438         LISTOP* listop;
10439
10440         range->op_flags &= ~OPf_KIDS;
10441         /* detach range's children */
10442         op_sibling_splice((OP*)range, NULL, -1, NULL);
10443
10444         listop = (LISTOP*)newLISTOP(OP_LIST, 0, left, right);
10445         listop->op_first->op_next = range->op_next;
10446         left->op_next = range->op_other;
10447         right->op_next = (OP*)listop;
10448         listop->op_next = listop->op_first;
10449
10450         op_free(expr);
10451         expr = (OP*)(listop);
10452         op_null(expr);
10453         iterflags |= OPf_STACKED;
10454     }
10455     else {
10456         expr = op_lvalue(force_list(expr, TRUE), OP_GREPSTART);
10457     }
10458
10459     loop = (LOOP*)op_convert_list(OP_ENTERITER, iterflags,
10460                                   op_append_elem(OP_LIST, list(expr),
10461                                                  scalar(sv)));
10462     assert(!loop->op_next);
10463     /* for my  $x () sets OPpLVAL_INTRO;
10464      * for our $x () sets OPpOUR_INTRO */
10465     loop->op_private = (U8)iterpflags;
10466
10467     /* upgrade loop from a LISTOP to a LOOPOP;
10468      * keep it in-place if there's space */
10469     if (loop->op_slabbed
10470         &&    OpSLOT(loop)->opslot_size
10471             < SIZE_TO_PSIZE(sizeof(LOOP) + OPSLOT_HEADER))
10472     {
10473         /* no space; allocate new op */
10474         LOOP *tmp;
10475         NewOp(1234,tmp,1,LOOP);
10476         Copy(loop,tmp,1,LISTOP);
10477         assert(loop->op_last->op_sibparent == (OP*)loop);
10478         OpLASTSIB_set(loop->op_last, (OP*)tmp); /*point back to new parent */
10479         S_op_destroy(aTHX_ (OP*)loop);
10480         loop = tmp;
10481     }
10482     else if (!loop->op_slabbed)
10483     {
10484         /* loop was malloc()ed */
10485         loop = (LOOP*)PerlMemShared_realloc(loop, sizeof(LOOP));
10486         OpLASTSIB_set(loop->op_last, (OP*)loop);
10487     }
10488     loop->op_targ = padoff;
10489     iter = newOP(OP_ITER, 0);
10490     iter->op_targ = how_many_more;
10491     return newWHILEOP(flags, 1, loop, iter, block, cont, 0);
10492 }
10493
10494 /*
10495 =for apidoc newLOOPEX
10496
10497 Constructs, checks, and returns a loop-exiting op (such as C<goto>
10498 or C<last>).  C<type> is the opcode.  C<label> supplies the parameter
10499 determining the target of the op; it is consumed by this function and
10500 becomes part of the constructed op tree.
10501
10502 =cut
10503 */
10504
10505 OP*
10506 Perl_newLOOPEX(pTHX_ I32 type, OP *label)
10507 {
10508     OP *o = NULL;
10509
10510     PERL_ARGS_ASSERT_NEWLOOPEX;
10511
10512     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_LOOPEXOP
10513         || type == OP_CUSTOM);
10514
10515     if (type != OP_GOTO) {
10516         /* "last()" means "last" */
10517         if (label->op_type == OP_STUB && (label->op_flags & OPf_PARENS)) {
10518             o = newOP(type, OPf_SPECIAL);
10519         }
10520     }
10521     else {
10522         /* Check whether it's going to be a goto &function */
10523         if (label->op_type == OP_ENTERSUB
10524                 && !(label->op_flags & OPf_STACKED))
10525             label = newUNOP(OP_REFGEN, 0, op_lvalue(label, OP_REFGEN));
10526     }
10527
10528     /* Check for a constant argument */
10529     if (label->op_type == OP_CONST) {
10530             SV * const sv = ((SVOP *)label)->op_sv;
10531             STRLEN l;
10532             const char *s = SvPV_const(sv,l);
10533             if (l == strlen(s)) {
10534                 o = newPVOP(type,
10535                             SvUTF8(((SVOP*)label)->op_sv),
10536                             savesharedpv(
10537                                 SvPV_nolen_const(((SVOP*)label)->op_sv)));
10538             }
10539     }
10540
10541     /* If we have already created an op, we do not need the label. */
10542     if (o)
10543                 op_free(label);
10544     else o = newUNOP(type, OPf_STACKED, label);
10545
10546     PL_hints |= HINT_BLOCK_SCOPE;
10547     return o;
10548 }
10549
10550 /* if the condition is a literal array or hash
10551    (or @{ ... } etc), make a reference to it.
10552  */
10553 STATIC OP *
10554 S_ref_array_or_hash(pTHX_ OP *cond)
10555 {
10556     if (cond
10557     && (cond->op_type == OP_RV2AV
10558     ||  cond->op_type == OP_PADAV
10559     ||  cond->op_type == OP_RV2HV
10560     ||  cond->op_type == OP_PADHV))
10561
10562         return newUNOP(OP_REFGEN, 0, op_lvalue(cond, OP_REFGEN));
10563
10564     else if(cond
10565     && (cond->op_type == OP_ASLICE
10566     ||  cond->op_type == OP_KVASLICE
10567     ||  cond->op_type == OP_HSLICE
10568     ||  cond->op_type == OP_KVHSLICE)) {
10569
10570         /* anonlist now needs a list from this op, was previously used in
10571          * scalar context */
10572         cond->op_flags &= ~(OPf_WANT_SCALAR | OPf_REF);
10573         cond->op_flags |= OPf_WANT_LIST;
10574
10575         return newANONLIST(op_lvalue(cond, OP_ANONLIST));
10576     }
10577
10578     else
10579         return cond;
10580 }
10581
10582 /* These construct the optree fragments representing given()
10583    and when() blocks.
10584
10585    entergiven and enterwhen are LOGOPs; the op_other pointer
10586    points up to the associated leave op. We need this so we
10587    can put it in the context and make break/continue work.
10588    (Also, of course, pp_enterwhen will jump straight to
10589    op_other if the match fails.)
10590  */
10591
10592 STATIC OP *
10593 S_newGIVWHENOP(pTHX_ OP *cond, OP *block,
10594                    I32 enter_opcode, I32 leave_opcode,
10595                    PADOFFSET entertarg)
10596 {
10597     LOGOP *enterop;
10598     OP *o;
10599
10600     PERL_ARGS_ASSERT_NEWGIVWHENOP;
10601     PERL_UNUSED_ARG(entertarg); /* used to indicate targ of lexical $_ */
10602
10603     enterop = alloc_LOGOP(enter_opcode, block, NULL);
10604     enterop->op_targ = 0;
10605     enterop->op_private = 0;
10606
10607     o = newUNOP(leave_opcode, 0, (OP *) enterop);
10608
10609     if (cond) {
10610         /* prepend cond if we have one */
10611         op_sibling_splice((OP*)enterop, NULL, 0, scalar(cond));
10612
10613         o->op_next = LINKLIST(cond);
10614         cond->op_next = (OP *) enterop;
10615     }
10616     else {
10617         /* This is a default {} block */
10618         enterop->op_flags |= OPf_SPECIAL;
10619         o      ->op_flags |= OPf_SPECIAL;
10620
10621         o->op_next = (OP *) enterop;
10622     }
10623
10624     CHECKOP(enter_opcode, enterop); /* Currently does nothing, since
10625                                        entergiven and enterwhen both
10626                                        use ck_null() */
10627
10628     enterop->op_next = LINKLIST(block);
10629     block->op_next = enterop->op_other = o;
10630
10631     return o;
10632 }
10633
10634
10635 /* For the purposes of 'when(implied_smartmatch)'
10636  *              versus 'when(boolean_expression)',
10637  * does this look like a boolean operation? For these purposes
10638    a boolean operation is:
10639      - a subroutine call [*]
10640      - a logical connective
10641      - a comparison operator
10642      - a filetest operator, with the exception of -s -M -A -C
10643      - defined(), exists() or eof()
10644      - /$re/ or $foo =~ /$re/
10645
10646    [*] possibly surprising
10647  */
10648 STATIC bool
10649 S_looks_like_bool(pTHX_ const OP *o)
10650 {
10651     PERL_ARGS_ASSERT_LOOKS_LIKE_BOOL;
10652
10653     switch(o->op_type) {
10654         case OP_OR:
10655         case OP_DOR:
10656             return looks_like_bool(cLOGOPo->op_first);
10657
10658         case OP_AND:
10659         {
10660             OP* sibl = OpSIBLING(cLOGOPo->op_first);
10661             ASSUME(sibl);
10662             return (
10663                 looks_like_bool(cLOGOPo->op_first)
10664              && looks_like_bool(sibl));
10665         }
10666
10667         case OP_NULL:
10668         case OP_SCALAR:
10669             return (
10670                 o->op_flags & OPf_KIDS
10671             && looks_like_bool(cUNOPo->op_first));
10672
10673         case OP_ENTERSUB:
10674
10675         case OP_NOT:    case OP_XOR:
10676
10677         case OP_EQ:     case OP_NE:     case OP_LT:
10678         case OP_GT:     case OP_LE:     case OP_GE:
10679
10680         case OP_I_EQ:   case OP_I_NE:   case OP_I_LT:
10681         case OP_I_GT:   case OP_I_LE:   case OP_I_GE:
10682
10683         case OP_SEQ:    case OP_SNE:    case OP_SLT:
10684         case OP_SGT:    case OP_SLE:    case OP_SGE:
10685
10686         case OP_SMARTMATCH:
10687
10688         case OP_FTRREAD:  case OP_FTRWRITE: case OP_FTREXEC:
10689         case OP_FTEREAD:  case OP_FTEWRITE: case OP_FTEEXEC:
10690         case OP_FTIS:     case OP_FTEOWNED: case OP_FTROWNED:
10691         case OP_FTZERO:   case OP_FTSOCK:   case OP_FTCHR:
10692         case OP_FTBLK:    case OP_FTFILE:   case OP_FTDIR:
10693         case OP_FTPIPE:   case OP_FTLINK:   case OP_FTSUID:
10694         case OP_FTSGID:   case OP_FTSVTX:   case OP_FTTTY:
10695         case OP_FTTEXT:   case OP_FTBINARY:
10696
10697         case OP_DEFINED: case OP_EXISTS:
10698         case OP_MATCH:   case OP_EOF:
10699
10700         case OP_FLOP:
10701
10702             return TRUE;
10703
10704         case OP_INDEX:
10705         case OP_RINDEX:
10706             /* optimised-away (index() != -1) or similar comparison */
10707             if (o->op_private & OPpTRUEBOOL)
10708                 return TRUE;
10709             return FALSE;
10710
10711         case OP_CONST:
10712             /* Detect comparisons that have been optimized away */
10713             if (cSVOPo->op_sv == &PL_sv_yes
10714             ||  cSVOPo->op_sv == &PL_sv_no)
10715
10716                 return TRUE;
10717             else
10718                 return FALSE;
10719         /* FALLTHROUGH */
10720         default:
10721             return FALSE;
10722     }
10723 }
10724
10725
10726 /*
10727 =for apidoc newGIVENOP
10728
10729 Constructs, checks, and returns an op tree expressing a C<given> block.
10730 C<cond> supplies the expression to whose value C<$_> will be locally
10731 aliased, and C<block> supplies the body of the C<given> construct; they
10732 are consumed by this function and become part of the constructed op tree.
10733 C<defsv_off> must be zero (it used to identity the pad slot of lexical $_).
10734
10735 =cut
10736 */
10737
10738 OP *
10739 Perl_newGIVENOP(pTHX_ OP *cond, OP *block, PADOFFSET defsv_off)
10740 {
10741     PERL_ARGS_ASSERT_NEWGIVENOP;
10742     PERL_UNUSED_ARG(defsv_off);
10743
10744     assert(!defsv_off);
10745     return newGIVWHENOP(
10746         ref_array_or_hash(cond),
10747         block,
10748         OP_ENTERGIVEN, OP_LEAVEGIVEN,
10749         0);
10750 }
10751
10752 /*
10753 =for apidoc newWHENOP
10754
10755 Constructs, checks, and returns an op tree expressing a C<when> block.
10756 C<cond> supplies the test expression, and C<block> supplies the block
10757 that will be executed if the test evaluates to true; they are consumed
10758 by this function and become part of the constructed op tree.  C<cond>
10759 will be interpreted DWIMically, often as a comparison against C<$_>,
10760 and may be null to generate a C<default> block.
10761
10762 =cut
10763 */
10764
10765 OP *
10766 Perl_newWHENOP(pTHX_ OP *cond, OP *block)
10767 {
10768     const bool cond_llb = (!cond || looks_like_bool(cond));
10769     OP *cond_op;
10770
10771     PERL_ARGS_ASSERT_NEWWHENOP;
10772
10773     if (cond_llb)
10774         cond_op = cond;
10775     else {
10776         cond_op = newBINOP(OP_SMARTMATCH, OPf_SPECIAL,
10777                 newDEFSVOP(),
10778                 scalar(ref_array_or_hash(cond)));
10779     }
10780
10781     return newGIVWHENOP(cond_op, block, OP_ENTERWHEN, OP_LEAVEWHEN, 0);
10782 }
10783
10784 /*
10785 =for apidoc newDEFEROP
10786
10787 Constructs and returns a deferred-block statement that implements the
10788 C<defer> semantics.  The C<block> optree is consumed by this function and
10789 becomes part of the returned optree.
10790
10791 The C<flags> argument carries additional flags to set on the returned op,
10792 including the C<op_private> field.
10793
10794 =cut
10795  */
10796
10797 OP *
10798 Perl_newDEFEROP(pTHX_ I32 flags, OP *block)
10799 {
10800     OP *o, *start, *blockfirst;
10801
10802     PERL_ARGS_ASSERT_NEWDEFEROP;
10803
10804     start = LINKLIST(block);
10805
10806     /* Hide the block inside an OP_NULL with no exection */
10807     block = newUNOP(OP_NULL, 0, block);
10808     block->op_next = block;
10809
10810     o = (OP *)alloc_LOGOP(OP_PUSHDEFER, block, start);
10811     o->op_flags |= OPf_WANT_VOID | (U8)(flags);
10812     o->op_private = (U8)(flags >> 8);
10813
10814     /* Terminate the block */
10815     blockfirst = cUNOPx(block)->op_first;
10816     assert(blockfirst->op_type == OP_SCOPE || blockfirst->op_type == OP_LEAVE);
10817     blockfirst->op_next = NULL;
10818
10819     return o;
10820 }
10821
10822 /*
10823 =for apidoc op_wrap_finally
10824
10825 Wraps the given C<block> optree fragment in its own scoped block, arranging
10826 for the C<finally> optree fragment to be invoked when leaving that block for
10827 any reason. Both optree fragments are consumed and the combined result is
10828 returned.
10829
10830 =cut
10831 */
10832
10833 OP *
10834 Perl_op_wrap_finally(pTHX_ OP *block, OP *finally)
10835 {
10836     PERL_ARGS_ASSERT_OP_WRAP_FINALLY;
10837
10838     /* TODO: If block is already an ENTER/LEAVE-wrapped line sequence we can
10839      * just splice the DEFEROP in at the top, for efficiency.
10840      */
10841
10842     OP *o = newLISTOP(OP_LINESEQ, 0, newDEFEROP((OPpDEFER_FINALLY << 8), finally), block);
10843     o = op_prepend_elem(OP_LINESEQ, newOP(OP_ENTER, 0), o);
10844     OpTYPE_set(o, OP_LEAVE);
10845
10846     return o;
10847 }
10848
10849 /* must not conflict with SVf_UTF8 */
10850 #define CV_CKPROTO_CURSTASH     0x1
10851
10852 void
10853 Perl_cv_ckproto_len_flags(pTHX_ const CV *cv, const GV *gv, const char *p,
10854                     const STRLEN len, const U32 flags)
10855 {
10856     SV *name = NULL, *msg;
10857     const char * cvp = SvROK(cv)
10858                         ? SvTYPE(SvRV_const(cv)) == SVt_PVCV
10859                            ? (cv = (const CV *)SvRV_const(cv), CvPROTO(cv))
10860                            : ""
10861                         : CvPROTO(cv);
10862     STRLEN clen = CvPROTOLEN(cv), plen = len;
10863
10864     PERL_ARGS_ASSERT_CV_CKPROTO_LEN_FLAGS;
10865
10866     if (p == NULL && cvp == NULL)
10867         return;
10868
10869     if (!ckWARN_d(WARN_PROTOTYPE))
10870         return;
10871
10872     if (p && cvp) {
10873         p = S_strip_spaces(aTHX_ p, &plen);
10874         cvp = S_strip_spaces(aTHX_ cvp, &clen);
10875         if ((flags & SVf_UTF8) == SvUTF8(cv)) {
10876             if (plen == clen && memEQ(cvp, p, plen))
10877                 return;
10878         } else {
10879             if (flags & SVf_UTF8) {
10880                 if (bytes_cmp_utf8((const U8 *)cvp, clen, (const U8 *)p, plen) == 0)
10881                     return;
10882             }
10883             else {
10884                 if (bytes_cmp_utf8((const U8 *)p, plen, (const U8 *)cvp, clen) == 0)
10885                     return;
10886             }
10887         }
10888     }
10889
10890     msg = sv_newmortal();
10891
10892     if (gv)
10893     {
10894         if (isGV(gv))
10895             gv_efullname3(name = sv_newmortal(), gv, NULL);
10896         else if (SvPOK(gv) && *SvPVX((SV *)gv) == '&')
10897             name = newSVpvn_flags(SvPVX((SV *)gv)+1, SvCUR(gv)-1, SvUTF8(gv)|SVs_TEMP);
10898         else if (flags & CV_CKPROTO_CURSTASH || SvROK(gv)) {
10899             name = sv_2mortal(newSVhek(HvNAME_HEK(PL_curstash)));
10900             sv_catpvs(name, "::");
10901             if (SvROK(gv)) {
10902                 assert (SvTYPE(SvRV_const(gv)) == SVt_PVCV);
10903                 assert (CvNAMED(SvRV_const(gv)));
10904                 sv_cathek(name, CvNAME_HEK(MUTABLE_CV(SvRV_const(gv))));
10905             }
10906             else sv_catsv(name, (SV *)gv);
10907         }
10908         else name = (SV *)gv;
10909     }
10910     sv_setpvs(msg, "Prototype mismatch:");
10911     if (name)
10912         Perl_sv_catpvf(aTHX_ msg, " sub %" SVf, SVfARG(name));
10913     if (cvp)
10914         Perl_sv_catpvf(aTHX_ msg, " (%" UTF8f ")",
10915             UTF8fARG(SvUTF8(cv),clen,cvp)
10916         );
10917     else
10918         sv_catpvs(msg, ": none");
10919     sv_catpvs(msg, " vs ");
10920     if (p)
10921         Perl_sv_catpvf(aTHX_ msg, "(%" UTF8f ")", UTF8fARG(flags & SVf_UTF8,len,p));
10922     else
10923         sv_catpvs(msg, "none");
10924     Perl_warner(aTHX_ packWARN(WARN_PROTOTYPE), "%" SVf, SVfARG(msg));
10925 }
10926
10927 static void const_sv_xsub(pTHX_ CV* cv);
10928 static void const_av_xsub(pTHX_ CV* cv);
10929
10930 /*
10931
10932 =for apidoc_section $optree_manipulation
10933
10934 =for apidoc cv_const_sv
10935
10936 If C<cv> is a constant sub eligible for inlining, returns the constant
10937 value returned by the sub.  Otherwise, returns C<NULL>.
10938
10939 Constant subs can be created with C<newCONSTSUB> or as described in
10940 L<perlsub/"Constant Functions">.
10941
10942 =cut
10943 */
10944 SV *
10945 Perl_cv_const_sv(const CV *const cv)
10946 {
10947     SV *sv;
10948     if (!cv)
10949         return NULL;
10950     if (!(SvTYPE(cv) == SVt_PVCV || SvTYPE(cv) == SVt_PVFM))
10951         return NULL;
10952     sv = CvCONST(cv) ? MUTABLE_SV(CvXSUBANY(cv).any_ptr) : NULL;
10953     if (sv && SvTYPE(sv) == SVt_PVAV) return NULL;
10954     return sv;
10955 }
10956
10957 SV *
10958 Perl_cv_const_sv_or_av(const CV * const cv)
10959 {
10960     if (!cv)
10961         return NULL;
10962     if (SvROK(cv)) return SvRV((SV *)cv);
10963     assert (SvTYPE(cv) == SVt_PVCV || SvTYPE(cv) == SVt_PVFM);
10964     return CvCONST(cv) ? MUTABLE_SV(CvXSUBANY(cv).any_ptr) : NULL;
10965 }
10966
10967 /* op_const_sv:  examine an optree to determine whether it's in-lineable.
10968  * Can be called in 2 ways:
10969  *
10970  * !allow_lex
10971  *      look for a single OP_CONST with attached value: return the value
10972  *
10973  * allow_lex && !CvCONST(cv);
10974  *
10975  *      examine the clone prototype, and if contains only a single
10976  *      OP_CONST, return the value; or if it contains a single PADSV ref-
10977  *      erencing an outer lexical, turn on CvCONST to indicate the CV is
10978  *      a candidate for "constizing" at clone time, and return NULL.
10979  */
10980
10981 static SV *
10982 S_op_const_sv(pTHX_ const OP *o, CV *cv, bool allow_lex)
10983 {
10984     SV *sv = NULL;
10985     bool padsv = FALSE;
10986
10987     assert(o);
10988     assert(cv);
10989
10990     for (; o; o = o->op_next) {
10991         const OPCODE type = o->op_type;
10992
10993         if (type == OP_NEXTSTATE || type == OP_LINESEQ
10994              || type == OP_NULL
10995              || type == OP_PUSHMARK)
10996                 continue;
10997         if (type == OP_DBSTATE)
10998                 continue;
10999         if (type == OP_LEAVESUB)
11000             break;
11001         if (sv)
11002             return NULL;
11003         if (type == OP_CONST && cSVOPo->op_sv)
11004             sv = cSVOPo->op_sv;
11005         else if (type == OP_UNDEF && !o->op_private) {
11006             sv = newSV(0);
11007             SAVEFREESV(sv);
11008         }
11009         else if (allow_lex && type == OP_PADSV) {
11010                 if (PAD_COMPNAME_FLAGS(o->op_targ) & PADNAMEt_OUTER)
11011                 {
11012                     sv = &PL_sv_undef; /* an arbitrary non-null value */
11013                     padsv = TRUE;
11014                 }
11015                 else
11016                     return NULL;
11017         }
11018         else {
11019             return NULL;
11020         }
11021     }
11022     if (padsv) {
11023         CvCONST_on(cv);
11024         return NULL;
11025     }
11026     return sv;
11027 }
11028
11029 static void
11030 S_already_defined(pTHX_ CV *const cv, OP * const block, OP * const o,
11031                         PADNAME * const name, SV ** const const_svp)
11032 {
11033     assert (cv);
11034     assert (o || name);
11035     assert (const_svp);
11036     if (!block) {
11037         if (CvFLAGS(PL_compcv)) {
11038             /* might have had built-in attrs applied */
11039             const bool pureperl = !CvISXSUB(cv) && CvROOT(cv);
11040             if (CvLVALUE(PL_compcv) && ! CvLVALUE(cv) && pureperl
11041              && ckWARN(WARN_MISC))
11042             {
11043                 /* protect against fatal warnings leaking compcv */
11044                 SAVEFREESV(PL_compcv);
11045                 Perl_warner(aTHX_ packWARN(WARN_MISC), "lvalue attribute ignored after the subroutine has been defined");
11046                 SvREFCNT_inc_simple_void_NN(PL_compcv);
11047             }
11048             CvFLAGS(cv) |=
11049                 (CvFLAGS(PL_compcv) & CVf_BUILTIN_ATTRS
11050                   & ~(CVf_LVALUE * pureperl));
11051         }
11052         return;
11053     }
11054
11055     /* redundant check for speed: */
11056     if (CvCONST(cv) || ckWARN(WARN_REDEFINE)) {
11057         const line_t oldline = CopLINE(PL_curcop);
11058         SV *namesv = o
11059             ? cSVOPo->op_sv
11060             : newSVpvn_flags( PadnamePV(name)+1,PadnameLEN(name)-1,
11061                (PadnameUTF8(name)) ? SVf_UTF8|SVs_TEMP : SVs_TEMP
11062               );
11063         if (PL_parser && PL_parser->copline != NOLINE)
11064             /* This ensures that warnings are reported at the first
11065                line of a redefinition, not the last.  */
11066             CopLINE_set(PL_curcop, PL_parser->copline);
11067         /* protect against fatal warnings leaking compcv */
11068         SAVEFREESV(PL_compcv);
11069         report_redefined_cv(namesv, cv, const_svp);
11070         SvREFCNT_inc_simple_void_NN(PL_compcv);
11071         CopLINE_set(PL_curcop, oldline);
11072     }
11073     SAVEFREESV(cv);
11074     return;
11075 }
11076
11077 CV *
11078 Perl_newMYSUB(pTHX_ I32 floor, OP *o, OP *proto, OP *attrs, OP *block)
11079 {
11080     CV **spot;
11081     SV **svspot;
11082     const char *ps;
11083     STRLEN ps_len = 0; /* init it to avoid false uninit warning from icc */
11084     U32 ps_utf8 = 0;
11085     CV *cv = NULL;
11086     CV *compcv = PL_compcv;
11087     SV *const_sv;
11088     PADNAME *name;
11089     PADOFFSET pax = o->op_targ;
11090     CV *outcv = CvOUTSIDE(PL_compcv);
11091     CV *clonee = NULL;
11092     HEK *hek = NULL;
11093     bool reusable = FALSE;
11094     OP *start = NULL;
11095 #ifdef PERL_DEBUG_READONLY_OPS
11096     OPSLAB *slab = NULL;
11097 #endif
11098
11099     PERL_ARGS_ASSERT_NEWMYSUB;
11100
11101     PL_hints |= HINT_BLOCK_SCOPE;
11102
11103     /* Find the pad slot for storing the new sub.
11104        We cannot use PL_comppad, as it is the pad owned by the new sub.  We
11105        need to look in CvOUTSIDE and find the pad belonging to the enclos-
11106        ing sub.  And then we need to dig deeper if this is a lexical from
11107        outside, as in:
11108            my sub foo; sub { sub foo { } }
11109      */
11110   redo:
11111     name = PadlistNAMESARRAY(CvPADLIST(outcv))[pax];
11112     if (PadnameOUTER(name) && PARENT_PAD_INDEX(name)) {
11113         pax = PARENT_PAD_INDEX(name);
11114         outcv = CvOUTSIDE(outcv);
11115         assert(outcv);
11116         goto redo;
11117     }
11118     svspot =
11119         &PadARRAY(PadlistARRAY(CvPADLIST(outcv))
11120                         [CvDEPTH(outcv) ? CvDEPTH(outcv) : 1])[pax];
11121     spot = (CV **)svspot;
11122
11123     if (!(PL_parser && PL_parser->error_count))
11124         move_proto_attr(&proto, &attrs, (GV *)PadnameSV(name), 0);
11125
11126     if (proto) {
11127         assert(proto->op_type == OP_CONST);
11128         ps = SvPV_const(((SVOP*)proto)->op_sv, ps_len);
11129         ps_utf8 = SvUTF8(((SVOP*)proto)->op_sv);
11130     }
11131     else
11132         ps = NULL;
11133
11134     if (proto)
11135         SAVEFREEOP(proto);
11136     if (attrs)
11137         SAVEFREEOP(attrs);
11138
11139     if (PL_parser && PL_parser->error_count) {
11140         op_free(block);
11141         SvREFCNT_dec(PL_compcv);
11142         PL_compcv = 0;
11143         goto done;
11144     }
11145
11146     if (CvDEPTH(outcv) && CvCLONE(compcv)) {
11147         cv = *spot;
11148         svspot = (SV **)(spot = &clonee);
11149     }
11150     else if (PadnameIsSTATE(name) || CvDEPTH(outcv))
11151         cv = *spot;
11152     else {
11153         assert (SvTYPE(*spot) == SVt_PVCV);
11154         if (CvNAMED(*spot))
11155             hek = CvNAME_HEK(*spot);
11156         else {
11157             U32 hash;
11158             PERL_HASH(hash, PadnamePV(name)+1, PadnameLEN(name)-1);
11159             CvNAME_HEK_set(*spot, hek =
11160                 share_hek(
11161                     PadnamePV(name)+1,
11162                     (PadnameLEN(name)-1) * (PadnameUTF8(name) ? -1 : 1),
11163                     hash
11164                 )
11165             );
11166             CvLEXICAL_on(*spot);
11167         }
11168         cv = PadnamePROTOCV(name);
11169         svspot = (SV **)(spot = &PadnamePROTOCV(name));
11170     }
11171
11172     if (block) {
11173         /* This makes sub {}; work as expected.  */
11174         if (block->op_type == OP_STUB) {
11175             const line_t l = PL_parser->copline;
11176             op_free(block);
11177             block = newSTATEOP(0, NULL, 0);
11178             PL_parser->copline = l;
11179         }
11180         block = CvLVALUE(compcv)
11181              || (cv && CvLVALUE(cv) && !CvROOT(cv) && !CvXSUB(cv))
11182                    ? newUNOP(OP_LEAVESUBLV, 0,
11183                              op_lvalue(voidnonfinal(block), OP_LEAVESUBLV))
11184                    : newUNOP(OP_LEAVESUB, 0, voidnonfinal(block));
11185         start = LINKLIST(block);
11186         block->op_next = 0;
11187         if (ps && !*ps && !attrs && !CvLVALUE(compcv))
11188             const_sv = S_op_const_sv(aTHX_ start, compcv, FALSE);
11189         else
11190             const_sv = NULL;
11191     }
11192     else
11193         const_sv = NULL;
11194
11195     if (cv) {
11196         const bool exists = CvROOT(cv) || CvXSUB(cv);
11197
11198         /* if the subroutine doesn't exist and wasn't pre-declared
11199          * with a prototype, assume it will be AUTOLOADed,
11200          * skipping the prototype check
11201          */
11202         if (exists || SvPOK(cv))
11203             cv_ckproto_len_flags(cv, (GV *)PadnameSV(name), ps, ps_len,
11204                                  ps_utf8);
11205         /* already defined? */
11206         if (exists) {
11207             S_already_defined(aTHX_ cv, block, NULL, name, &const_sv);
11208             if (block)
11209                 cv = NULL;
11210             else {
11211                 if (attrs)
11212                     goto attrs;
11213                 /* just a "sub foo;" when &foo is already defined */
11214                 SAVEFREESV(compcv);
11215                 goto done;
11216             }
11217         }
11218         else if (CvDEPTH(outcv) && CvCLONE(compcv)) {
11219             cv = NULL;
11220             reusable = TRUE;
11221         }
11222     }
11223
11224     if (const_sv) {
11225         SvREFCNT_inc_simple_void_NN(const_sv);
11226         SvFLAGS(const_sv) |= SVs_PADTMP;
11227         if (cv) {
11228             assert(!CvROOT(cv) && !CvCONST(cv));
11229             cv_forget_slab(cv);
11230         }
11231         else {
11232             cv = MUTABLE_CV(newSV_type(SVt_PVCV));
11233             CvFILE_set_from_cop(cv, PL_curcop);
11234             CvSTASH_set(cv, PL_curstash);
11235             *spot = cv;
11236         }
11237         SvPVCLEAR(MUTABLE_SV(cv));  /* prototype is "" */
11238         CvXSUBANY(cv).any_ptr = const_sv;
11239         CvXSUB(cv) = const_sv_xsub;
11240         CvCONST_on(cv);
11241         CvISXSUB_on(cv);
11242         PoisonPADLIST(cv);
11243         CvFLAGS(cv) |= CvMETHOD(compcv);
11244         op_free(block);
11245         SvREFCNT_dec(compcv);
11246         PL_compcv = NULL;
11247         goto setname;
11248     }
11249
11250     /* Checking whether outcv is CvOUTSIDE(compcv) is not sufficient to
11251        determine whether this sub definition is in the same scope as its
11252        declaration.  If this sub definition is inside an inner named pack-
11253        age sub (my sub foo; sub bar { sub foo { ... } }), outcv points to
11254        the package sub.  So check PadnameOUTER(name) too.
11255      */
11256     if (outcv == CvOUTSIDE(compcv) && !PadnameOUTER(name)) {
11257         assert(!CvWEAKOUTSIDE(compcv));
11258         SvREFCNT_dec(CvOUTSIDE(compcv));
11259         CvWEAKOUTSIDE_on(compcv);
11260     }
11261     /* XXX else do we have a circular reference? */
11262
11263     if (cv) {   /* must reuse cv in case stub is referenced elsewhere */
11264         /* transfer PL_compcv to cv */
11265         if (block) {
11266             bool free_file = CvFILE(cv) && CvDYNFILE(cv);
11267             cv_flags_t preserved_flags =
11268                 CvFLAGS(cv) & (CVf_BUILTIN_ATTRS|CVf_NAMED);
11269             PADLIST *const temp_padl = CvPADLIST(cv);
11270             CV *const temp_cv = CvOUTSIDE(cv);
11271             const cv_flags_t other_flags =
11272                 CvFLAGS(cv) & (CVf_SLABBED|CVf_WEAKOUTSIDE);
11273             OP * const cvstart = CvSTART(cv);
11274
11275             SvPOK_off(cv);
11276             CvFLAGS(cv) =
11277                 CvFLAGS(compcv) | preserved_flags;
11278             CvOUTSIDE(cv) = CvOUTSIDE(compcv);
11279             CvOUTSIDE_SEQ(cv) = CvOUTSIDE_SEQ(compcv);
11280             CvPADLIST_set(cv, CvPADLIST(compcv));
11281             CvOUTSIDE(compcv) = temp_cv;
11282             CvPADLIST_set(compcv, temp_padl);
11283             CvSTART(cv) = CvSTART(compcv);
11284             CvSTART(compcv) = cvstart;
11285             CvFLAGS(compcv) &= ~(CVf_SLABBED|CVf_WEAKOUTSIDE);
11286             CvFLAGS(compcv) |= other_flags;
11287
11288             if (free_file) {
11289                 Safefree(CvFILE(cv));
11290                 CvFILE(cv) = NULL;
11291             }
11292
11293             /* inner references to compcv must be fixed up ... */
11294             pad_fixup_inner_anons(CvPADLIST(cv), compcv, cv);
11295             if (PERLDB_INTER)/* Advice debugger on the new sub. */
11296                 ++PL_sub_generation;
11297         }
11298         else {
11299             /* Might have had built-in attributes applied -- propagate them. */
11300             CvFLAGS(cv) |= (CvFLAGS(compcv) & CVf_BUILTIN_ATTRS);
11301         }
11302         /* ... before we throw it away */
11303         SvREFCNT_dec(compcv);
11304         PL_compcv = compcv = cv;
11305     }
11306     else {
11307         cv = compcv;
11308         *spot = cv;
11309     }
11310
11311   setname:
11312     CvLEXICAL_on(cv);
11313     if (!CvNAME_HEK(cv)) {
11314         if (hek) (void)share_hek_hek(hek);
11315         else {
11316             U32 hash;
11317             PERL_HASH(hash, PadnamePV(name)+1, PadnameLEN(name)-1);
11318             hek = share_hek(PadnamePV(name)+1,
11319                       (PadnameLEN(name)-1) * (PadnameUTF8(name) ? -1 : 1),
11320                       hash);
11321         }
11322         CvNAME_HEK_set(cv, hek);
11323     }
11324
11325     if (const_sv)
11326         goto clone;
11327
11328     if (CvFILE(cv) && CvDYNFILE(cv))
11329         Safefree(CvFILE(cv));
11330     CvFILE_set_from_cop(cv, PL_curcop);
11331     CvSTASH_set(cv, PL_curstash);
11332
11333     if (ps) {
11334         sv_setpvn(MUTABLE_SV(cv), ps, ps_len);
11335         if (ps_utf8)
11336             SvUTF8_on(MUTABLE_SV(cv));
11337     }
11338
11339     if (block) {
11340         /* If we assign an optree to a PVCV, then we've defined a
11341          * subroutine that the debugger could be able to set a breakpoint
11342          * in, so signal to pp_entereval that it should not throw away any
11343          * saved lines at scope exit.  */
11344
11345         PL_breakable_sub_gen++;
11346         CvROOT(cv) = block;
11347         /* The cv no longer needs to hold a refcount on the slab, as CvROOT
11348            itself has a refcount. */
11349         CvSLABBED_off(cv);
11350         OpslabREFCNT_dec_padok((OPSLAB *)CvSTART(cv));
11351 #ifdef PERL_DEBUG_READONLY_OPS
11352         slab = (OPSLAB *)CvSTART(cv);
11353 #endif
11354         S_process_optree(aTHX_ cv, block, start);
11355     }
11356
11357   attrs:
11358     if (attrs) {
11359         /* Need to do a C<use attributes $stash_of_cv,\&cv,@attrs>. */
11360         apply_attrs(PL_curstash, MUTABLE_SV(cv), attrs);
11361     }
11362
11363     if (block) {
11364         if (PERLDB_SUBLINE && PL_curstash != PL_debstash) {
11365             SV * const tmpstr = sv_newmortal();
11366             GV * const db_postponed = gv_fetchpvs("DB::postponed",
11367                                                   GV_ADDMULTI, SVt_PVHV);
11368             HV *hv;
11369             SV * const sv = Perl_newSVpvf(aTHX_ "%s:%ld-%ld",
11370                                           CopFILE(PL_curcop),
11371                                           (long)PL_subline,
11372                                           (long)CopLINE(PL_curcop));
11373             if (HvNAME_HEK(PL_curstash)) {
11374                 sv_sethek(tmpstr, HvNAME_HEK(PL_curstash));
11375                 sv_catpvs(tmpstr, "::");
11376             }
11377             else
11378                 sv_setpvs(tmpstr, "__ANON__::");
11379
11380             sv_catpvn_flags(tmpstr, PadnamePV(name)+1, PadnameLEN(name)-1,
11381                             PadnameUTF8(name) ? SV_CATUTF8 : SV_CATBYTES);
11382             (void)hv_store_ent(GvHV(PL_DBsub), tmpstr, sv, 0);
11383             hv = GvHVn(db_postponed);
11384             if (HvTOTALKEYS(hv) > 0 && hv_exists_ent(hv, tmpstr, 0)) {
11385                 CV * const pcv = GvCV(db_postponed);
11386                 if (pcv) {
11387                     dSP;
11388                     PUSHMARK(SP);
11389                     XPUSHs(tmpstr);
11390                     PUTBACK;
11391                     call_sv(MUTABLE_SV(pcv), G_DISCARD);
11392                 }
11393             }
11394         }
11395     }
11396
11397   clone:
11398     if (clonee) {
11399         assert(CvDEPTH(outcv));
11400         spot = (CV **)
11401             &PadARRAY(PadlistARRAY(CvPADLIST(outcv))[CvDEPTH(outcv)])[pax];
11402         if (reusable)
11403             cv_clone_into(clonee, *spot);
11404         else *spot = cv_clone(clonee);
11405         SvREFCNT_dec_NN(clonee);
11406         cv = *spot;
11407     }
11408
11409     if (CvDEPTH(outcv) && !reusable && PadnameIsSTATE(name)) {
11410         PADOFFSET depth = CvDEPTH(outcv);
11411         while (--depth) {
11412             SV *oldcv;
11413             svspot = &PadARRAY(PadlistARRAY(CvPADLIST(outcv))[depth])[pax];
11414             oldcv = *svspot;
11415             *svspot = SvREFCNT_inc_simple_NN(cv);
11416             SvREFCNT_dec(oldcv);
11417         }
11418     }
11419
11420   done:
11421     if (PL_parser)
11422         PL_parser->copline = NOLINE;
11423     LEAVE_SCOPE(floor);
11424 #ifdef PERL_DEBUG_READONLY_OPS
11425     if (slab)
11426         Slab_to_ro(slab);
11427 #endif
11428     op_free(o);
11429     return cv;
11430 }
11431
11432 /*
11433 =for apidoc newATTRSUB_x
11434
11435 Construct a Perl subroutine, also performing some surrounding jobs.
11436
11437 This function is expected to be called in a Perl compilation context,
11438 and some aspects of the subroutine are taken from global variables
11439 associated with compilation.  In particular, C<PL_compcv> represents
11440 the subroutine that is currently being compiled.  It must be non-null
11441 when this function is called, and some aspects of the subroutine being
11442 constructed are taken from it.  The constructed subroutine may actually
11443 be a reuse of the C<PL_compcv> object, but will not necessarily be so.
11444
11445 If C<block> is null then the subroutine will have no body, and for the
11446 time being it will be an error to call it.  This represents a forward
11447 subroutine declaration such as S<C<sub foo ($$);>>.  If C<block> is
11448 non-null then it provides the Perl code of the subroutine body, which
11449 will be executed when the subroutine is called.  This body includes
11450 any argument unwrapping code resulting from a subroutine signature or
11451 similar.  The pad use of the code must correspond to the pad attached
11452 to C<PL_compcv>.  The code is not expected to include a C<leavesub> or
11453 C<leavesublv> op; this function will add such an op.  C<block> is consumed
11454 by this function and will become part of the constructed subroutine.
11455
11456 C<proto> specifies the subroutine's prototype, unless one is supplied
11457 as an attribute (see below).  If C<proto> is null, then the subroutine
11458 will not have a prototype.  If C<proto> is non-null, it must point to a
11459 C<const> op whose value is a string, and the subroutine will have that
11460 string as its prototype.  If a prototype is supplied as an attribute, the
11461 attribute takes precedence over C<proto>, but in that case C<proto> should
11462 preferably be null.  In any case, C<proto> is consumed by this function.
11463
11464 C<attrs> supplies attributes to be applied the subroutine.  A handful of
11465 attributes take effect by built-in means, being applied to C<PL_compcv>
11466 immediately when seen.  Other attributes are collected up and attached
11467 to the subroutine by this route.  C<attrs> may be null to supply no
11468 attributes, or point to a C<const> op for a single attribute, or point
11469 to a C<list> op whose children apart from the C<pushmark> are C<const>
11470 ops for one or more attributes.  Each C<const> op must be a string,
11471 giving the attribute name optionally followed by parenthesised arguments,
11472 in the manner in which attributes appear in Perl source.  The attributes
11473 will be applied to the sub by this function.  C<attrs> is consumed by
11474 this function.
11475
11476 If C<o_is_gv> is false and C<o> is null, then the subroutine will
11477 be anonymous.  If C<o_is_gv> is false and C<o> is non-null, then C<o>
11478 must point to a C<const> OP, which will be consumed by this function,
11479 and its string value supplies a name for the subroutine.  The name may
11480 be qualified or unqualified, and if it is unqualified then a default
11481 stash will be selected in some manner.  If C<o_is_gv> is true, then C<o>
11482 doesn't point to an C<OP> at all, but is instead a cast pointer to a C<GV>
11483 by which the subroutine will be named.
11484
11485 If there is already a subroutine of the specified name, then the new
11486 sub will either replace the existing one in the glob or be merged with
11487 the existing one.  A warning may be generated about redefinition.
11488
11489 If the subroutine has one of a few special names, such as C<BEGIN> or
11490 C<END>, then it will be claimed by the appropriate queue for automatic
11491 running of phase-related subroutines.  In this case the relevant glob will
11492 be left not containing any subroutine, even if it did contain one before.
11493 In the case of C<BEGIN>, the subroutine will be executed and the reference
11494 to it disposed of before this function returns.
11495
11496 The function returns a pointer to the constructed subroutine.  If the sub
11497 is anonymous then ownership of one counted reference to the subroutine
11498 is transferred to the caller.  If the sub is named then the caller does
11499 not get ownership of a reference.  In most such cases, where the sub
11500 has a non-phase name, the sub will be alive at the point it is returned
11501 by virtue of being contained in the glob that names it.  A phase-named
11502 subroutine will usually be alive by virtue of the reference owned by the
11503 phase's automatic run queue.  But a C<BEGIN> subroutine, having already
11504 been executed, will quite likely have been destroyed already by the
11505 time this function returns, making it erroneous for the caller to make
11506 any use of the returned pointer.  It is the caller's responsibility to
11507 ensure that it knows which of these situations applies.
11508
11509 =for apidoc newATTRSUB
11510 Construct a Perl subroutine, also performing some surrounding jobs.
11511
11512 This is the same as L<perlintern/C<newATTRSUB_x>> with its C<o_is_gv> parameter set to
11513 FALSE.  This means that if C<o> is null, the new sub will be anonymous; otherwise
11514 the name will be derived from C<o> in the way described (as with all other
11515 details) in L<perlintern/C<newATTRSUB_x>>.
11516
11517 =for apidoc newSUB
11518 Like C<L</newATTRSUB>>, but without attributes.
11519
11520 =cut
11521 */
11522
11523 /* _x = extended */
11524 CV *
11525 Perl_newATTRSUB_x(pTHX_ I32 floor, OP *o, OP *proto, OP *attrs,
11526                             OP *block, bool o_is_gv)
11527 {
11528     GV *gv;
11529     const char *ps;
11530     STRLEN ps_len = 0; /* init it to avoid false uninit warning from icc */
11531     U32 ps_utf8 = 0;
11532     CV *cv = NULL;     /* the previous CV with this name, if any */
11533     SV *const_sv;
11534     const bool ec = PL_parser && PL_parser->error_count;
11535     /* If the subroutine has no body, no attributes, and no builtin attributes
11536        then it's just a sub declaration, and we may be able to get away with
11537        storing with a placeholder scalar in the symbol table, rather than a
11538        full CV.  If anything is present then it will take a full CV to
11539        store it.  */
11540     const I32 gv_fetch_flags
11541         = ec ? GV_NOADD_NOINIT :
11542         (block || attrs || (CvFLAGS(PL_compcv) & CVf_BUILTIN_ATTRS))
11543         ? GV_ADDMULTI : GV_ADDMULTI | GV_NOINIT;
11544     STRLEN namlen = 0;
11545     const char * const name =
11546          o ? SvPV_const(o_is_gv ? (SV *)o : cSVOPo->op_sv, namlen) : NULL;
11547     bool has_name;
11548     bool name_is_utf8 = o && !o_is_gv && SvUTF8(cSVOPo->op_sv);
11549     bool evanescent = FALSE;
11550     OP *start = NULL;
11551 #ifdef PERL_DEBUG_READONLY_OPS
11552     OPSLAB *slab = NULL;
11553 #endif
11554
11555     if (o_is_gv) {
11556         gv = (GV*)o;
11557         o = NULL;
11558         has_name = TRUE;
11559     } else if (name) {
11560         /* Try to optimise and avoid creating a GV.  Instead, the CV’s name
11561            hek and CvSTASH pointer together can imply the GV.  If the name
11562            contains a package name, then GvSTASH(CvGV(cv)) may differ from
11563            CvSTASH, so forego the optimisation if we find any.
11564            Also, we may be called from load_module at run time, so
11565            PL_curstash (which sets CvSTASH) may not point to the stash the
11566            sub is stored in.  */
11567         /* XXX This optimization is currently disabled for packages other
11568                than main, since there was too much CPAN breakage.  */
11569         const I32 flags =
11570            ec ? GV_NOADD_NOINIT
11571               :   (IN_PERL_RUNTIME && PL_curstash != CopSTASH(PL_curcop))
11572                || PL_curstash != PL_defstash
11573                || memchr(name, ':', namlen) || memchr(name, '\'', namlen)
11574                     ? gv_fetch_flags
11575                     : GV_ADDMULTI | GV_NOINIT | GV_NOTQUAL;
11576         gv = gv_fetchsv(cSVOPo->op_sv, flags, SVt_PVCV);
11577         has_name = TRUE;
11578     } else if (PERLDB_NAMEANON && CopLINE(PL_curcop)) {
11579         SV * const sv = sv_newmortal();
11580         Perl_sv_setpvf(aTHX_ sv, "%s[%s:%" IVdf "]",
11581                        PL_curstash ? "__ANON__" : "__ANON__::__ANON__",
11582                        CopFILE(PL_curcop), (IV)CopLINE(PL_curcop));
11583         gv = gv_fetchsv(sv, gv_fetch_flags, SVt_PVCV);
11584         has_name = TRUE;
11585     } else if (PL_curstash) {
11586         gv = gv_fetchpvs("__ANON__", gv_fetch_flags, SVt_PVCV);
11587         has_name = FALSE;
11588     } else {
11589         gv = gv_fetchpvs("__ANON__::__ANON__", gv_fetch_flags, SVt_PVCV);
11590         has_name = FALSE;
11591     }
11592
11593     if (!ec) {
11594         if (isGV(gv)) {
11595             move_proto_attr(&proto, &attrs, gv, 0);
11596         } else {
11597             assert(cSVOPo);
11598             move_proto_attr(&proto, &attrs, (GV *)cSVOPo->op_sv, 1);
11599         }
11600     }
11601
11602     if (proto) {
11603         assert(proto->op_type == OP_CONST);
11604         ps = SvPV_const(((SVOP*)proto)->op_sv, ps_len);
11605         ps_utf8 = SvUTF8(((SVOP*)proto)->op_sv);
11606     }
11607     else
11608         ps = NULL;
11609
11610     if (o)
11611         SAVEFREEOP(o);
11612     if (proto)
11613         SAVEFREEOP(proto);
11614     if (attrs)
11615         SAVEFREEOP(attrs);
11616
11617     if (ec) {
11618         op_free(block);
11619
11620         if (name)
11621             SvREFCNT_dec(PL_compcv);
11622         else
11623             cv = PL_compcv;
11624
11625         PL_compcv = 0;
11626         if (name && block) {
11627             const char *s = (char *) my_memrchr(name, ':', namlen);
11628             s = s ? s+1 : name;
11629             if (strEQ(s, "BEGIN")) {
11630                 if (PL_in_eval & EVAL_KEEPERR)
11631                     Perl_croak_nocontext("BEGIN not safe after errors--compilation aborted");
11632                 else {
11633                     SV * const errsv = ERRSV;
11634                     /* force display of errors found but not reported */
11635                     sv_catpvs(errsv, "BEGIN not safe after errors--compilation aborted");
11636                     Perl_croak_nocontext("%" SVf, SVfARG(errsv));
11637                 }
11638             }
11639         }
11640         goto done;
11641     }
11642
11643     if (!block && SvTYPE(gv) != SVt_PVGV) {
11644         /* If we are not defining a new sub and the existing one is not a
11645            full GV + CV... */
11646         if (attrs || (CvFLAGS(PL_compcv) & CVf_BUILTIN_ATTRS)) {
11647             /* We are applying attributes to an existing sub, so we need it
11648                upgraded if it is a constant.  */
11649             if (SvROK(gv) && SvTYPE(SvRV(gv)) != SVt_PVCV)
11650                 gv_init_pvn(gv, PL_curstash, name, namlen,
11651                             SVf_UTF8 * name_is_utf8);
11652         }
11653         else {                  /* Maybe prototype now, and had at maximum
11654                                    a prototype or const/sub ref before.  */
11655             if (SvTYPE(gv) > SVt_NULL) {
11656                 cv_ckproto_len_flags((const CV *)gv,
11657                                     o ? (const GV *)cSVOPo->op_sv : NULL, ps,
11658                                     ps_len, ps_utf8);
11659             }
11660
11661             if (!SvROK(gv)) {
11662                 if (ps) {
11663                     sv_setpvn(MUTABLE_SV(gv), ps, ps_len);
11664                     if (ps_utf8)
11665                         SvUTF8_on(MUTABLE_SV(gv));
11666                 }
11667                 else
11668                     sv_setiv(MUTABLE_SV(gv), -1);
11669             }
11670
11671             SvREFCNT_dec(PL_compcv);
11672             cv = PL_compcv = NULL;
11673             goto done;
11674         }
11675     }
11676
11677     cv = (!name || (isGV(gv) && GvCVGEN(gv)))
11678         ? NULL
11679         : isGV(gv)
11680             ? GvCV(gv)
11681             : SvROK(gv) && SvTYPE(SvRV(gv)) == SVt_PVCV
11682                 ? (CV *)SvRV(gv)
11683                 : NULL;
11684
11685     if (block) {
11686         assert(PL_parser);
11687         /* This makes sub {}; work as expected.  */
11688         if (block->op_type == OP_STUB) {
11689             const line_t l = PL_parser->copline;
11690             op_free(block);
11691             block = newSTATEOP(0, NULL, 0);
11692             PL_parser->copline = l;
11693         }
11694         block = CvLVALUE(PL_compcv)
11695              || (cv && CvLVALUE(cv) && !CvROOT(cv) && !CvXSUB(cv)
11696                     && (!isGV(gv) || !GvASSUMECV(gv)))
11697                    ? newUNOP(OP_LEAVESUBLV, 0,
11698                              op_lvalue(voidnonfinal(block), OP_LEAVESUBLV))
11699                    : newUNOP(OP_LEAVESUB, 0, voidnonfinal(block));
11700         start = LINKLIST(block);
11701         block->op_next = 0;
11702         if (ps && !*ps && !attrs && !CvLVALUE(PL_compcv))
11703             const_sv =
11704                 S_op_const_sv(aTHX_ start, PL_compcv,
11705                                         cBOOL(CvCLONE(PL_compcv)));
11706         else
11707             const_sv = NULL;
11708     }
11709     else
11710         const_sv = NULL;
11711
11712     if (SvPOK(gv) || (SvROK(gv) && SvTYPE(SvRV(gv)) != SVt_PVCV)) {
11713         cv_ckproto_len_flags((const CV *)gv,
11714                              o ? (const GV *)cSVOPo->op_sv : NULL, ps,
11715                              ps_len, ps_utf8|CV_CKPROTO_CURSTASH);
11716         if (SvROK(gv)) {
11717             /* All the other code for sub redefinition warnings expects the
11718                clobbered sub to be a CV.  Instead of making all those code
11719                paths more complex, just inline the RV version here.  */
11720             const line_t oldline = CopLINE(PL_curcop);
11721             assert(IN_PERL_COMPILETIME);
11722             if (PL_parser && PL_parser->copline != NOLINE)
11723                 /* This ensures that warnings are reported at the first
11724                    line of a redefinition, not the last.  */
11725                 CopLINE_set(PL_curcop, PL_parser->copline);
11726             /* protect against fatal warnings leaking compcv */
11727             SAVEFREESV(PL_compcv);
11728
11729             if (ckWARN(WARN_REDEFINE)
11730              || (  ckWARN_d(WARN_REDEFINE)
11731                 && (  !const_sv || SvRV(gv) == const_sv
11732                    || sv_cmp(SvRV(gv), const_sv)  ))) {
11733                 assert(cSVOPo);
11734                 Perl_warner(aTHX_ packWARN(WARN_REDEFINE),
11735                           "Constant subroutine %" SVf " redefined",
11736                           SVfARG(cSVOPo->op_sv));
11737             }
11738
11739             SvREFCNT_inc_simple_void_NN(PL_compcv);
11740             CopLINE_set(PL_curcop, oldline);
11741             SvREFCNT_dec(SvRV(gv));
11742         }
11743     }
11744
11745     if (cv) {
11746         const bool exists = CvROOT(cv) || CvXSUB(cv);
11747
11748         /* if the subroutine doesn't exist and wasn't pre-declared
11749          * with a prototype, assume it will be AUTOLOADed,
11750          * skipping the prototype check
11751          */
11752         if (exists || SvPOK(cv))
11753             cv_ckproto_len_flags(cv, gv, ps, ps_len, ps_utf8);
11754         /* already defined (or promised)? */
11755         if (exists || (isGV(gv) && GvASSUMECV(gv))) {
11756             S_already_defined(aTHX_ cv, block, o, NULL, &const_sv);
11757             if (block)
11758                 cv = NULL;
11759             else {
11760                 if (attrs)
11761                     goto attrs;
11762                 /* just a "sub foo;" when &foo is already defined */
11763                 SAVEFREESV(PL_compcv);
11764                 goto done;
11765             }
11766         }
11767     }
11768
11769     if (const_sv) {
11770         SvREFCNT_inc_simple_void_NN(const_sv);
11771         SvFLAGS(const_sv) |= SVs_PADTMP;
11772         if (cv) {
11773             assert(!CvROOT(cv) && !CvCONST(cv));
11774             cv_forget_slab(cv);
11775             SvPVCLEAR(MUTABLE_SV(cv));  /* prototype is "" */
11776             CvXSUBANY(cv).any_ptr = const_sv;
11777             CvXSUB(cv) = const_sv_xsub;
11778             CvCONST_on(cv);
11779             CvISXSUB_on(cv);
11780             PoisonPADLIST(cv);
11781             CvFLAGS(cv) |= CvMETHOD(PL_compcv);
11782         }
11783         else {
11784             if (isGV(gv) || CvMETHOD(PL_compcv)) {
11785                 if (name && isGV(gv))
11786                     GvCV_set(gv, NULL);
11787                 cv = newCONSTSUB_flags(
11788                     NULL, name, namlen, name_is_utf8 ? SVf_UTF8 : 0,
11789                     const_sv
11790                 );
11791                 assert(cv);
11792                 assert(SvREFCNT((SV*)cv) != 0);
11793                 CvFLAGS(cv) |= CvMETHOD(PL_compcv);
11794             }
11795             else {
11796                 if (!SvROK(gv)) {
11797                     SV_CHECK_THINKFIRST_COW_DROP((SV *)gv);
11798                     prepare_SV_for_RV((SV *)gv);
11799                     SvOK_off((SV *)gv);
11800                     SvROK_on(gv);
11801                 }
11802                 SvRV_set(gv, const_sv);
11803             }
11804         }
11805         op_free(block);
11806         SvREFCNT_dec(PL_compcv);
11807         PL_compcv = NULL;
11808         goto done;
11809     }
11810
11811     /* don't copy new BEGIN CV to old BEGIN CV - RT #129099 */
11812     if (name && cv && *name == 'B' && strEQ(name, "BEGIN"))
11813         cv = NULL;
11814
11815     if (cv) {                           /* must reuse cv if autoloaded */
11816         /* transfer PL_compcv to cv */
11817         if (block) {
11818             bool free_file = CvFILE(cv) && CvDYNFILE(cv);
11819             cv_flags_t existing_builtin_attrs = CvFLAGS(cv) & CVf_BUILTIN_ATTRS;
11820             PADLIST *const temp_av = CvPADLIST(cv);
11821             CV *const temp_cv = CvOUTSIDE(cv);
11822             const cv_flags_t other_flags =
11823                 CvFLAGS(cv) & (CVf_SLABBED|CVf_WEAKOUTSIDE);
11824             OP * const cvstart = CvSTART(cv);
11825
11826             if (isGV(gv)) {
11827                 CvGV_set(cv,gv);
11828                 assert(!CvCVGV_RC(cv));
11829                 assert(CvGV(cv) == gv);
11830             }
11831             else {
11832                 U32 hash;
11833                 PERL_HASH(hash, name, namlen);
11834                 CvNAME_HEK_set(cv,
11835                                share_hek(name,
11836                                          name_is_utf8
11837                                             ? -(SSize_t)namlen
11838                                             :  (SSize_t)namlen,
11839                                          hash));
11840             }
11841
11842             SvPOK_off(cv);
11843             CvFLAGS(cv) = CvFLAGS(PL_compcv) | existing_builtin_attrs
11844                                              | CvNAMED(cv);
11845             CvOUTSIDE(cv) = CvOUTSIDE(PL_compcv);
11846             CvOUTSIDE_SEQ(cv) = CvOUTSIDE_SEQ(PL_compcv);
11847             CvPADLIST_set(cv,CvPADLIST(PL_compcv));
11848             CvOUTSIDE(PL_compcv) = temp_cv;
11849             CvPADLIST_set(PL_compcv, temp_av);
11850             CvSTART(cv) = CvSTART(PL_compcv);
11851             CvSTART(PL_compcv) = cvstart;
11852             CvFLAGS(PL_compcv) &= ~(CVf_SLABBED|CVf_WEAKOUTSIDE);
11853             CvFLAGS(PL_compcv) |= other_flags;
11854
11855             if (free_file) {
11856                 Safefree(CvFILE(cv));
11857             }
11858             CvFILE_set_from_cop(cv, PL_curcop);
11859             CvSTASH_set(cv, PL_curstash);
11860
11861             /* inner references to PL_compcv must be fixed up ... */
11862             pad_fixup_inner_anons(CvPADLIST(cv), PL_compcv, cv);
11863             if (PERLDB_INTER)/* Advice debugger on the new sub. */
11864                 ++PL_sub_generation;
11865         }
11866         else {
11867             /* Might have had built-in attributes applied -- propagate them. */
11868             CvFLAGS(cv) |= (CvFLAGS(PL_compcv) & CVf_BUILTIN_ATTRS);
11869         }
11870         /* ... before we throw it away */
11871         SvREFCNT_dec(PL_compcv);
11872         PL_compcv = cv;
11873     }
11874     else {
11875         cv = PL_compcv;
11876         if (name && isGV(gv)) {
11877             GvCV_set(gv, cv);
11878             GvCVGEN(gv) = 0;
11879             if (HvENAME_HEK(GvSTASH(gv)))
11880                 /* sub Foo::bar { (shift)+1 } */
11881                 gv_method_changed(gv);
11882         }
11883         else if (name) {
11884             if (!SvROK(gv)) {
11885                 SV_CHECK_THINKFIRST_COW_DROP((SV *)gv);
11886                 prepare_SV_for_RV((SV *)gv);
11887                 SvOK_off((SV *)gv);
11888                 SvROK_on(gv);
11889             }
11890             SvRV_set(gv, (SV *)cv);
11891             if (HvENAME_HEK(PL_curstash))
11892                 mro_method_changed_in(PL_curstash);
11893         }
11894     }
11895     assert(cv);
11896     assert(SvREFCNT((SV*)cv) != 0);
11897
11898     if (!CvHASGV(cv)) {
11899         if (isGV(gv))
11900             CvGV_set(cv, gv);
11901         else {
11902             U32 hash;
11903             PERL_HASH(hash, name, namlen);
11904             CvNAME_HEK_set(cv, share_hek(name,
11905                                          name_is_utf8
11906                                             ? -(SSize_t)namlen
11907                                             :  (SSize_t)namlen,
11908                                          hash));
11909         }
11910         CvFILE_set_from_cop(cv, PL_curcop);
11911         CvSTASH_set(cv, PL_curstash);
11912     }
11913
11914     if (ps) {
11915         sv_setpvn(MUTABLE_SV(cv), ps, ps_len);
11916         if ( ps_utf8 )
11917             SvUTF8_on(MUTABLE_SV(cv));
11918     }
11919
11920     if (block) {
11921         /* If we assign an optree to a PVCV, then we've defined a
11922          * subroutine that the debugger could be able to set a breakpoint
11923          * in, so signal to pp_entereval that it should not throw away any
11924          * saved lines at scope exit.  */
11925
11926         PL_breakable_sub_gen++;
11927         CvROOT(cv) = block;
11928         /* The cv no longer needs to hold a refcount on the slab, as CvROOT
11929            itself has a refcount. */
11930         CvSLABBED_off(cv);
11931         OpslabREFCNT_dec_padok((OPSLAB *)CvSTART(cv));
11932 #ifdef PERL_DEBUG_READONLY_OPS
11933         slab = (OPSLAB *)CvSTART(cv);
11934 #endif
11935         S_process_optree(aTHX_ cv, block, start);
11936     }
11937
11938   attrs:
11939     if (attrs) {
11940         /* Need to do a C<use attributes $stash_of_cv,\&cv,@attrs>. */
11941         HV *stash = name && !CvNAMED(cv) && GvSTASH(CvGV(cv))
11942                         ? GvSTASH(CvGV(cv))
11943                         : PL_curstash;
11944         if (!name)
11945             SAVEFREESV(cv);
11946         apply_attrs(stash, MUTABLE_SV(cv), attrs);
11947         if (!name)
11948             SvREFCNT_inc_simple_void_NN(cv);
11949     }
11950
11951     if (block && has_name) {
11952         if (PERLDB_SUBLINE && PL_curstash != PL_debstash) {
11953             SV * const tmpstr = cv_name(cv,NULL,0);
11954             GV * const db_postponed = gv_fetchpvs("DB::postponed",
11955                                                   GV_ADDMULTI, SVt_PVHV);
11956             HV *hv;
11957             SV * const sv = Perl_newSVpvf(aTHX_ "%s:%ld-%ld",
11958                                           CopFILE(PL_curcop),
11959                                           (long)PL_subline,
11960                                           (long)CopLINE(PL_curcop));
11961             (void)hv_store_ent(GvHV(PL_DBsub), tmpstr, sv, 0);
11962             hv = GvHVn(db_postponed);
11963             if (HvTOTALKEYS(hv) > 0 && hv_exists_ent(hv, tmpstr, 0)) {
11964                 CV * const pcv = GvCV(db_postponed);
11965                 if (pcv) {
11966                     dSP;
11967                     PUSHMARK(SP);
11968                     XPUSHs(tmpstr);
11969                     PUTBACK;
11970                     call_sv(MUTABLE_SV(pcv), G_DISCARD);
11971                 }
11972             }
11973         }
11974
11975         if (name) {
11976             if (PL_parser && PL_parser->error_count)
11977                 clear_special_blocks(name, gv, cv);
11978             else
11979                 evanescent =
11980                     process_special_blocks(floor, name, gv, cv);
11981         }
11982     }
11983     assert(cv);
11984
11985   done:
11986     assert(!cv || evanescent || SvREFCNT((SV*)cv) != 0);
11987     if (PL_parser)
11988         PL_parser->copline = NOLINE;
11989     LEAVE_SCOPE(floor);
11990
11991     assert(!cv || evanescent || SvREFCNT((SV*)cv) != 0);
11992     if (!evanescent) {
11993 #ifdef PERL_DEBUG_READONLY_OPS
11994     if (slab)
11995         Slab_to_ro(slab);
11996 #endif
11997     if (cv && name && block && CvOUTSIDE(cv) && !CvEVAL(CvOUTSIDE(cv)))
11998         pad_add_weakref(cv);
11999     }
12000     return cv;
12001 }
12002
12003 STATIC void
12004 S_clear_special_blocks(pTHX_ const char *const fullname,
12005                        GV *const gv, CV *const cv) {
12006     const char *colon;
12007     const char *name;
12008
12009     PERL_ARGS_ASSERT_CLEAR_SPECIAL_BLOCKS;
12010
12011     colon = strrchr(fullname,':');
12012     name = colon ? colon + 1 : fullname;
12013
12014     if ((*name == 'B' && strEQ(name, "BEGIN"))
12015         || (*name == 'E' && strEQ(name, "END"))
12016         || (*name == 'U' && strEQ(name, "UNITCHECK"))
12017         || (*name == 'C' && strEQ(name, "CHECK"))
12018         || (*name == 'I' && strEQ(name, "INIT"))) {
12019         if (!isGV(gv)) {
12020             (void)CvGV(cv);
12021             assert(isGV(gv));
12022         }
12023         GvCV_set(gv, NULL);
12024         SvREFCNT_dec_NN(MUTABLE_SV(cv));
12025     }
12026 }
12027
12028 /* Returns true if the sub has been freed.  */
12029 STATIC bool
12030 S_process_special_blocks(pTHX_ I32 floor, const char *const fullname,
12031                          GV *const gv,
12032                          CV *const cv)
12033 {
12034     const char *const colon = strrchr(fullname,':');
12035     const char *const name = colon ? colon + 1 : fullname;
12036
12037     PERL_ARGS_ASSERT_PROCESS_SPECIAL_BLOCKS;
12038
12039     if (*name == 'B') {
12040         if (strEQ(name, "BEGIN")) {
12041             const I32 oldscope = PL_scopestack_ix;
12042             dSP;
12043             (void)CvGV(cv);
12044             if (floor) LEAVE_SCOPE(floor);
12045             ENTER;
12046
12047             SAVEVPTR(PL_curcop);
12048             if (PL_curcop == &PL_compiling) {
12049                 /* Avoid pushing the "global" &PL_compiling onto the
12050                  * context stack. For example, a stack trace inside
12051                  * nested use's would show all calls coming from whoever
12052                  * most recently updated PL_compiling.cop_file and
12053                  * cop_line.  So instead, temporarily set PL_curcop to a
12054                  * private copy of &PL_compiling. PL_curcop will soon be
12055                  * set to point back to &PL_compiling anyway but only
12056                  * after the temp value has been pushed onto the context
12057                  * stack as blk_oldcop.
12058                  * This is slightly hacky, but necessary. Note also
12059                  * that in the brief window before PL_curcop is set back
12060                  * to PL_compiling, IN_PERL_COMPILETIME/IN_PERL_RUNTIME
12061                  * will give the wrong answer.
12062                  */
12063                 PL_curcop = (COP*)newSTATEOP(PL_compiling.op_flags, NULL, NULL);
12064                 CopLINE_set(PL_curcop, CopLINE(&PL_compiling));
12065                 SAVEFREEOP(PL_curcop);
12066             }
12067
12068             PUSHSTACKi(PERLSI_REQUIRE);
12069             SAVECOPFILE(&PL_compiling);
12070             SAVECOPLINE(&PL_compiling);
12071
12072             DEBUG_x( dump_sub(gv) );
12073             Perl_av_create_and_push(aTHX_ &PL_beginav, MUTABLE_SV(cv));
12074             GvCV_set(gv,0);             /* cv has been hijacked */
12075             call_list(oldscope, PL_beginav);
12076
12077             POPSTACK;
12078             LEAVE;
12079             return !PL_savebegin;
12080         }
12081         else
12082             return FALSE;
12083     } else {
12084         if (*name == 'E') {
12085             if (strEQ(name, "END")) {
12086                 DEBUG_x( dump_sub(gv) );
12087                 Perl_av_create_and_unshift_one(aTHX_ &PL_endav, MUTABLE_SV(cv));
12088             } else
12089                 return FALSE;
12090         } else if (*name == 'U') {
12091             if (strEQ(name, "UNITCHECK")) {
12092                 /* It's never too late to run a unitcheck block */
12093                 Perl_av_create_and_unshift_one(aTHX_ &PL_unitcheckav, MUTABLE_SV(cv));
12094             }
12095             else
12096                 return FALSE;
12097         } else if (*name == 'C') {
12098             if (strEQ(name, "CHECK")) {
12099                 if (PL_main_start)
12100                     /* diag_listed_as: Too late to run %s block */
12101                     Perl_ck_warner(aTHX_ packWARN(WARN_VOID),
12102                                    "Too late to run CHECK block");
12103                 Perl_av_create_and_unshift_one(aTHX_ &PL_checkav, MUTABLE_SV(cv));
12104             }
12105             else
12106                 return FALSE;
12107         } else if (*name == 'I') {
12108             if (strEQ(name, "INIT")) {
12109                 if (PL_main_start)
12110                     /* diag_listed_as: Too late to run %s block */
12111                     Perl_ck_warner(aTHX_ packWARN(WARN_VOID),
12112                                    "Too late to run INIT block");
12113                 Perl_av_create_and_push(aTHX_ &PL_initav, MUTABLE_SV(cv));
12114             }
12115             else
12116                 return FALSE;
12117         } else
12118             return FALSE;
12119         DEBUG_x( dump_sub(gv) );
12120         (void)CvGV(cv);
12121         GvCV_set(gv,0);         /* cv has been hijacked */
12122         return FALSE;
12123     }
12124 }
12125
12126 /*
12127 =for apidoc newCONSTSUB
12128
12129 Behaves like L</newCONSTSUB_flags>, except that C<name> is nul-terminated
12130 rather than of counted length, and no flags are set.  (This means that
12131 C<name> is always interpreted as Latin-1.)
12132
12133 =cut
12134 */
12135
12136 CV *
12137 Perl_newCONSTSUB(pTHX_ HV *stash, const char *name, SV *sv)
12138 {
12139     return newCONSTSUB_flags(stash, name, name ? strlen(name) : 0, 0, sv);
12140 }
12141
12142 /*
12143 =for apidoc newCONSTSUB_flags
12144
12145 Construct a constant subroutine, also performing some surrounding
12146 jobs.  A scalar constant-valued subroutine is eligible for inlining
12147 at compile-time, and in Perl code can be created by S<C<sub FOO () {
12148 123 }>>.  Other kinds of constant subroutine have other treatment.
12149
12150 The subroutine will have an empty prototype and will ignore any arguments
12151 when called.  Its constant behaviour is determined by C<sv>.  If C<sv>
12152 is null, the subroutine will yield an empty list.  If C<sv> points to a
12153 scalar, the subroutine will always yield that scalar.  If C<sv> points
12154 to an array, the subroutine will always yield a list of the elements of
12155 that array in list context, or the number of elements in the array in
12156 scalar context.  This function takes ownership of one counted reference
12157 to the scalar or array, and will arrange for the object to live as long
12158 as the subroutine does.  If C<sv> points to a scalar then the inlining
12159 assumes that the value of the scalar will never change, so the caller
12160 must ensure that the scalar is not subsequently written to.  If C<sv>
12161 points to an array then no such assumption is made, so it is ostensibly
12162 safe to mutate the array or its elements, but whether this is really
12163 supported has not been determined.
12164
12165 The subroutine will have C<CvFILE> set according to C<PL_curcop>.
12166 Other aspects of the subroutine will be left in their default state.
12167 The caller is free to mutate the subroutine beyond its initial state
12168 after this function has returned.
12169
12170 If C<name> is null then the subroutine will be anonymous, with its
12171 C<CvGV> referring to an C<__ANON__> glob.  If C<name> is non-null then the
12172 subroutine will be named accordingly, referenced by the appropriate glob.
12173 C<name> is a string of length C<len> bytes giving a sigilless symbol
12174 name, in UTF-8 if C<flags> has the C<SVf_UTF8> bit set and in Latin-1
12175 otherwise.  The name may be either qualified or unqualified.  If the
12176 name is unqualified then it defaults to being in the stash specified by
12177 C<stash> if that is non-null, or to C<PL_curstash> if C<stash> is null.
12178 The symbol is always added to the stash if necessary, with C<GV_ADDMULTI>
12179 semantics.
12180
12181 C<flags> should not have bits set other than C<SVf_UTF8>.
12182
12183 If there is already a subroutine of the specified name, then the new sub
12184 will replace the existing one in the glob.  A warning may be generated
12185 about the redefinition.
12186
12187 If the subroutine has one of a few special names, such as C<BEGIN> or
12188 C<END>, then it will be claimed by the appropriate queue for automatic
12189 running of phase-related subroutines.  In this case the relevant glob will
12190 be left not containing any subroutine, even if it did contain one before.
12191 Execution of the subroutine will likely be a no-op, unless C<sv> was
12192 a tied array or the caller modified the subroutine in some interesting
12193 way before it was executed.  In the case of C<BEGIN>, the treatment is
12194 buggy: the sub will be executed when only half built, and may be deleted
12195 prematurely, possibly causing a crash.
12196
12197 The function returns a pointer to the constructed subroutine.  If the sub
12198 is anonymous then ownership of one counted reference to the subroutine
12199 is transferred to the caller.  If the sub is named then the caller does
12200 not get ownership of a reference.  In most such cases, where the sub
12201 has a non-phase name, the sub will be alive at the point it is returned
12202 by virtue of being contained in the glob that names it.  A phase-named
12203 subroutine will usually be alive by virtue of the reference owned by
12204 the phase's automatic run queue.  A C<BEGIN> subroutine may have been
12205 destroyed already by the time this function returns, but currently bugs
12206 occur in that case before the caller gets control.  It is the caller's
12207 responsibility to ensure that it knows which of these situations applies.
12208
12209 =cut
12210 */
12211
12212 CV *
12213 Perl_newCONSTSUB_flags(pTHX_ HV *stash, const char *name, STRLEN len,
12214                              U32 flags, SV *sv)
12215 {
12216     CV* cv;
12217     const char *const file = CopFILE(PL_curcop);
12218
12219     ENTER;
12220
12221     if (IN_PERL_RUNTIME) {
12222         /* at runtime, it's not safe to manipulate PL_curcop: it may be
12223          * an op shared between threads. Use a non-shared COP for our
12224          * dirty work */
12225          SAVEVPTR(PL_curcop);
12226          SAVECOMPILEWARNINGS();
12227          PL_compiling.cop_warnings = DUP_WARNINGS(PL_curcop->cop_warnings);
12228          PL_curcop = &PL_compiling;
12229     }
12230     SAVECOPLINE(PL_curcop);
12231     CopLINE_set(PL_curcop, PL_parser ? PL_parser->copline : NOLINE);
12232
12233     SAVEHINTS();
12234     PL_hints &= ~HINT_BLOCK_SCOPE;
12235
12236     if (stash) {
12237         SAVEGENERICSV(PL_curstash);
12238         PL_curstash = (HV *)SvREFCNT_inc_simple_NN(stash);
12239     }
12240
12241     /* Protect sv against leakage caused by fatal warnings. */
12242     if (sv) SAVEFREESV(sv);
12243
12244     /* file becomes the CvFILE. For an XS, it's usually static storage,
12245        and so doesn't get free()d.  (It's expected to be from the C pre-
12246        processor __FILE__ directive). But we need a dynamically allocated one,
12247        and we need it to get freed.  */
12248     cv = newXS_len_flags(name, len,
12249                          sv && SvTYPE(sv) == SVt_PVAV
12250                              ? const_av_xsub
12251                              : const_sv_xsub,
12252                          file ? file : "", "",
12253                          &sv, XS_DYNAMIC_FILENAME | flags);
12254     assert(cv);
12255     assert(SvREFCNT((SV*)cv) != 0);
12256     CvXSUBANY(cv).any_ptr = SvREFCNT_inc_simple(sv);
12257     CvCONST_on(cv);
12258
12259     LEAVE;
12260
12261     return cv;
12262 }
12263
12264 /*
12265 =for apidoc newXS
12266
12267 Used by C<xsubpp> to hook up XSUBs as Perl subs.  C<filename> needs to be
12268 static storage, as it is used directly as CvFILE(), without a copy being made.
12269
12270 =cut
12271 */
12272
12273 CV *
12274 Perl_newXS(pTHX_ const char *name, XSUBADDR_t subaddr, const char *filename)
12275 {
12276     PERL_ARGS_ASSERT_NEWXS;
12277     return newXS_len_flags(
12278         name, name ? strlen(name) : 0, subaddr, filename, NULL, NULL, 0
12279     );
12280 }
12281
12282 CV *
12283 Perl_newXS_flags(pTHX_ const char *name, XSUBADDR_t subaddr,
12284                  const char *const filename, const char *const proto,
12285                  U32 flags)
12286 {
12287     PERL_ARGS_ASSERT_NEWXS_FLAGS;
12288     return newXS_len_flags(
12289        name, name ? strlen(name) : 0, subaddr, filename, proto, NULL, flags
12290     );
12291 }
12292
12293 CV *
12294 Perl_newXS_deffile(pTHX_ const char *name, XSUBADDR_t subaddr)
12295 {
12296     PERL_ARGS_ASSERT_NEWXS_DEFFILE;
12297     return newXS_len_flags(
12298         name, strlen(name), subaddr, NULL, NULL, NULL, 0
12299     );
12300 }
12301
12302 /*
12303 =for apidoc newXS_len_flags
12304
12305 Construct an XS subroutine, also performing some surrounding jobs.
12306
12307 The subroutine will have the entry point C<subaddr>.  It will have
12308 the prototype specified by the nul-terminated string C<proto>, or
12309 no prototype if C<proto> is null.  The prototype string is copied;
12310 the caller can mutate the supplied string afterwards.  If C<filename>
12311 is non-null, it must be a nul-terminated filename, and the subroutine
12312 will have its C<CvFILE> set accordingly.  By default C<CvFILE> is set to
12313 point directly to the supplied string, which must be static.  If C<flags>
12314 has the C<XS_DYNAMIC_FILENAME> bit set, then a copy of the string will
12315 be taken instead.
12316
12317 Other aspects of the subroutine will be left in their default state.
12318 If anything else needs to be done to the subroutine for it to function
12319 correctly, it is the caller's responsibility to do that after this
12320 function has constructed it.  However, beware of the subroutine
12321 potentially being destroyed before this function returns, as described
12322 below.
12323
12324 If C<name> is null then the subroutine will be anonymous, with its
12325 C<CvGV> referring to an C<__ANON__> glob.  If C<name> is non-null then the
12326 subroutine will be named accordingly, referenced by the appropriate glob.
12327 C<name> is a string of length C<len> bytes giving a sigilless symbol name,
12328 in UTF-8 if C<flags> has the C<SVf_UTF8> bit set and in Latin-1 otherwise.
12329 The name may be either qualified or unqualified, with the stash defaulting
12330 in the same manner as for C<gv_fetchpvn_flags>.  C<flags> may contain
12331 flag bits understood by C<gv_fetchpvn_flags> with the same meaning as
12332 they have there, such as C<GV_ADDWARN>.  The symbol is always added to
12333 the stash if necessary, with C<GV_ADDMULTI> semantics.
12334
12335 If there is already a subroutine of the specified name, then the new sub
12336 will replace the existing one in the glob.  A warning may be generated
12337 about the redefinition.  If the old subroutine was C<CvCONST> then the
12338 decision about whether to warn is influenced by an expectation about
12339 whether the new subroutine will become a constant of similar value.
12340 That expectation is determined by C<const_svp>.  (Note that the call to
12341 this function doesn't make the new subroutine C<CvCONST> in any case;
12342 that is left to the caller.)  If C<const_svp> is null then it indicates
12343 that the new subroutine will not become a constant.  If C<const_svp>
12344 is non-null then it indicates that the new subroutine will become a
12345 constant, and it points to an C<SV*> that provides the constant value
12346 that the subroutine will have.
12347
12348 If the subroutine has one of a few special names, such as C<BEGIN> or
12349 C<END>, then it will be claimed by the appropriate queue for automatic
12350 running of phase-related subroutines.  In this case the relevant glob will
12351 be left not containing any subroutine, even if it did contain one before.
12352 In the case of C<BEGIN>, the subroutine will be executed and the reference
12353 to it disposed of before this function returns, and also before its
12354 prototype is set.  If a C<BEGIN> subroutine would not be sufficiently
12355 constructed by this function to be ready for execution then the caller
12356 must prevent this happening by giving the subroutine a different name.
12357
12358 The function returns a pointer to the constructed subroutine.  If the sub
12359 is anonymous then ownership of one counted reference to the subroutine
12360 is transferred to the caller.  If the sub is named then the caller does
12361 not get ownership of a reference.  In most such cases, where the sub
12362 has a non-phase name, the sub will be alive at the point it is returned
12363 by virtue of being contained in the glob that names it.  A phase-named
12364 subroutine will usually be alive by virtue of the reference owned by the
12365 phase's automatic run queue.  But a C<BEGIN> subroutine, having already
12366 been executed, will quite likely have been destroyed already by the
12367 time this function returns, making it erroneous for the caller to make
12368 any use of the returned pointer.  It is the caller's responsibility to
12369 ensure that it knows which of these situations applies.
12370
12371 =cut
12372 */
12373
12374 CV *
12375 Perl_newXS_len_flags(pTHX_ const char *name, STRLEN len,
12376                            XSUBADDR_t subaddr, const char *const filename,
12377                            const char *const proto, SV **const_svp,
12378                            U32 flags)
12379 {
12380     CV *cv;
12381     bool interleave = FALSE;
12382     bool evanescent = FALSE;
12383
12384     PERL_ARGS_ASSERT_NEWXS_LEN_FLAGS;
12385
12386     {
12387         GV * const gv = gv_fetchpvn(
12388                             name ? name : PL_curstash ? "__ANON__" : "__ANON__::__ANON__",
12389                             name ? len : PL_curstash ? sizeof("__ANON__") - 1:
12390                                 sizeof("__ANON__::__ANON__") - 1,
12391                             GV_ADDMULTI | flags, SVt_PVCV);
12392
12393         if ((cv = (name ? GvCV(gv) : NULL))) {
12394             if (GvCVGEN(gv)) {
12395                 /* just a cached method */
12396                 SvREFCNT_dec(cv);
12397                 cv = NULL;
12398             }
12399             else if (CvROOT(cv) || CvXSUB(cv) || GvASSUMECV(gv)) {
12400                 /* already defined (or promised) */
12401                 /* Redundant check that allows us to avoid creating an SV
12402                    most of the time: */
12403                 if (CvCONST(cv) || ckWARN(WARN_REDEFINE)) {
12404                     report_redefined_cv(newSVpvn_flags(
12405                                          name,len,(flags&SVf_UTF8)|SVs_TEMP
12406                                         ),
12407                                         cv, const_svp);
12408                 }
12409                 interleave = TRUE;
12410                 ENTER;
12411                 SAVEFREESV(cv);
12412                 cv = NULL;
12413             }
12414         }
12415
12416         if (cv)                         /* must reuse cv if autoloaded */
12417             cv_undef(cv);
12418         else {
12419             cv = MUTABLE_CV(newSV_type(SVt_PVCV));
12420             if (name) {
12421                 GvCV_set(gv,cv);
12422                 GvCVGEN(gv) = 0;
12423                 if (HvENAME_HEK(GvSTASH(gv)))
12424                     gv_method_changed(gv); /* newXS */
12425             }
12426         }
12427         assert(cv);
12428         assert(SvREFCNT((SV*)cv) != 0);
12429
12430         CvGV_set(cv, gv);
12431         if(filename) {
12432             /* XSUBs can't be perl lang/perl5db.pl debugged
12433             if (PERLDB_LINE_OR_SAVESRC)
12434                 (void)gv_fetchfile(filename); */
12435             assert(!CvDYNFILE(cv)); /* cv_undef should have turned it off */
12436             if (flags & XS_DYNAMIC_FILENAME) {
12437                 CvDYNFILE_on(cv);
12438                 CvFILE(cv) = savepv(filename);
12439             } else {
12440             /* NOTE: not copied, as it is expected to be an external constant string */
12441                 CvFILE(cv) = (char *)filename;
12442             }
12443         } else {
12444             assert((flags & XS_DYNAMIC_FILENAME) == 0 && PL_xsubfilename);
12445             CvFILE(cv) = (char*)PL_xsubfilename;
12446         }
12447         CvISXSUB_on(cv);
12448         CvXSUB(cv) = subaddr;
12449 #ifndef MULTIPLICITY
12450         CvHSCXT(cv) = &PL_stack_sp;
12451 #else
12452         PoisonPADLIST(cv);
12453 #endif
12454
12455         if (name)
12456             evanescent = process_special_blocks(0, name, gv, cv);
12457         else
12458             CvANON_on(cv);
12459     } /* <- not a conditional branch */
12460
12461     assert(cv);
12462     assert(evanescent || SvREFCNT((SV*)cv) != 0);
12463
12464     if (!evanescent) sv_setpv(MUTABLE_SV(cv), proto);
12465     if (interleave) LEAVE;
12466     assert(evanescent || SvREFCNT((SV*)cv) != 0);
12467     return cv;
12468 }
12469
12470 /* Add a stub CV to a typeglob.
12471  * This is the implementation of a forward declaration, 'sub foo';'
12472  */
12473
12474 CV *
12475 Perl_newSTUB(pTHX_ GV *gv, bool fake)
12476 {
12477     CV *cv = MUTABLE_CV(newSV_type(SVt_PVCV));
12478     GV *cvgv;
12479     PERL_ARGS_ASSERT_NEWSTUB;
12480     assert(!GvCVu(gv));
12481     GvCV_set(gv, cv);
12482     GvCVGEN(gv) = 0;
12483     if (!fake && GvSTASH(gv) && HvENAME_HEK(GvSTASH(gv)))
12484         gv_method_changed(gv);
12485     if (SvFAKE(gv)) {
12486         cvgv = gv_fetchsv((SV *)gv, GV_ADDMULTI, SVt_PVCV);
12487         SvFAKE_off(cvgv);
12488     }
12489     else cvgv = gv;
12490     CvGV_set(cv, cvgv);
12491     CvFILE_set_from_cop(cv, PL_curcop);
12492     CvSTASH_set(cv, PL_curstash);
12493     GvMULTI_on(gv);
12494     return cv;
12495 }
12496
12497 void
12498 Perl_newFORM(pTHX_ I32 floor, OP *o, OP *block)
12499 {
12500     CV *cv;
12501     GV *gv;
12502     OP *root;
12503     OP *start;
12504
12505     if (PL_parser && PL_parser->error_count) {
12506         op_free(block);
12507         goto finish;
12508     }
12509
12510     gv = o
12511         ? gv_fetchsv(cSVOPo->op_sv, GV_ADD, SVt_PVFM)
12512         : gv_fetchpvs("STDOUT", GV_ADD|GV_NOTQUAL, SVt_PVFM);
12513
12514     GvMULTI_on(gv);
12515     if ((cv = GvFORM(gv))) {
12516         if (ckWARN(WARN_REDEFINE)) {
12517             const line_t oldline = CopLINE(PL_curcop);
12518             if (PL_parser && PL_parser->copline != NOLINE)
12519                 CopLINE_set(PL_curcop, PL_parser->copline);
12520             if (o) {
12521                 Perl_warner(aTHX_ packWARN(WARN_REDEFINE),
12522                             "Format %" SVf " redefined", SVfARG(cSVOPo->op_sv));
12523             } else {
12524                 /* diag_listed_as: Format %s redefined */
12525                 Perl_warner(aTHX_ packWARN(WARN_REDEFINE),
12526                             "Format STDOUT redefined");
12527             }
12528             CopLINE_set(PL_curcop, oldline);
12529         }
12530         SvREFCNT_dec(cv);
12531     }
12532     cv = PL_compcv;
12533     GvFORM(gv) = (CV *)SvREFCNT_inc_simple_NN(cv);
12534     CvGV_set(cv, gv);
12535     CvFILE_set_from_cop(cv, PL_curcop);
12536
12537
12538     root = newUNOP(OP_LEAVEWRITE, 0, voidnonfinal(block));
12539     CvROOT(cv) = root;
12540     start = LINKLIST(root);
12541     root->op_next = 0;
12542     S_process_optree(aTHX_ cv, root, start);
12543     cv_forget_slab(cv);
12544
12545   finish:
12546     op_free(o);
12547     if (PL_parser)
12548         PL_parser->copline = NOLINE;
12549     LEAVE_SCOPE(floor);
12550     PL_compiling.cop_seq = 0;
12551 }
12552
12553 OP *
12554 Perl_newANONLIST(pTHX_ OP *o)
12555 {
12556     return op_convert_list(OP_ANONLIST, OPf_SPECIAL, o);
12557 }
12558
12559 OP *
12560 Perl_newANONHASH(pTHX_ OP *o)
12561 {
12562     return op_convert_list(OP_ANONHASH, OPf_SPECIAL, o);
12563 }
12564
12565 OP *
12566 Perl_newANONSUB(pTHX_ I32 floor, OP *proto, OP *block)
12567 {
12568     return newANONATTRSUB(floor, proto, NULL, block);
12569 }
12570
12571 OP *
12572 Perl_newANONATTRSUB(pTHX_ I32 floor, OP *proto, OP *attrs, OP *block)
12573 {
12574     SV * const cv = MUTABLE_SV(newATTRSUB(floor, 0, proto, attrs, block));
12575     OP * anoncode =
12576         newSVOP(OP_ANONCODE, 0,
12577                 cv);
12578     if (CvANONCONST(cv))
12579         anoncode = newUNOP(OP_ANONCONST, 0,
12580                            op_convert_list(OP_ENTERSUB,
12581                                            OPf_STACKED|OPf_WANT_SCALAR,
12582                                            anoncode));
12583     return newUNOP(OP_REFGEN, 0, anoncode);
12584 }
12585
12586 OP *
12587 Perl_oopsAV(pTHX_ OP *o)
12588 {
12589
12590     PERL_ARGS_ASSERT_OOPSAV;
12591
12592     switch (o->op_type) {
12593     case OP_PADSV:
12594     case OP_PADHV:
12595         OpTYPE_set(o, OP_PADAV);
12596         return ref(o, OP_RV2AV);
12597
12598     case OP_RV2SV:
12599     case OP_RV2HV:
12600         OpTYPE_set(o, OP_RV2AV);
12601         ref(o, OP_RV2AV);
12602         break;
12603
12604     default:
12605         Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL), "oops: oopsAV");
12606         break;
12607     }
12608     return o;
12609 }
12610
12611 OP *
12612 Perl_oopsHV(pTHX_ OP *o)
12613 {
12614
12615     PERL_ARGS_ASSERT_OOPSHV;
12616
12617     switch (o->op_type) {
12618     case OP_PADSV:
12619     case OP_PADAV:
12620         OpTYPE_set(o, OP_PADHV);
12621         return ref(o, OP_RV2HV);
12622
12623     case OP_RV2SV:
12624     case OP_RV2AV:
12625         OpTYPE_set(o, OP_RV2HV);
12626         /* rv2hv steals the bottom bit for its own uses */
12627         o->op_private &= ~OPpARG1_MASK;
12628         ref(o, OP_RV2HV);
12629         break;
12630
12631     default:
12632         Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL), "oops: oopsHV");
12633         break;
12634     }
12635     return o;
12636 }
12637
12638 OP *
12639 Perl_newAVREF(pTHX_ OP *o)
12640 {
12641
12642     PERL_ARGS_ASSERT_NEWAVREF;
12643
12644     if (o->op_type == OP_PADANY) {
12645         OpTYPE_set(o, OP_PADAV);
12646         return o;
12647     }
12648     else if ((o->op_type == OP_RV2AV || o->op_type == OP_PADAV)) {
12649         Perl_croak(aTHX_ "Can't use an array as a reference");
12650     }
12651     return newUNOP(OP_RV2AV, 0, scalar(o));
12652 }
12653
12654 OP *
12655 Perl_newGVREF(pTHX_ I32 type, OP *o)
12656 {
12657     if (type == OP_MAPSTART || type == OP_GREPSTART || type == OP_SORT)
12658         return newUNOP(OP_NULL, 0, o);
12659     return ref(newUNOP(OP_RV2GV, OPf_REF, o), type);
12660 }
12661
12662 OP *
12663 Perl_newHVREF(pTHX_ OP *o)
12664 {
12665
12666     PERL_ARGS_ASSERT_NEWHVREF;
12667
12668     if (o->op_type == OP_PADANY) {
12669         OpTYPE_set(o, OP_PADHV);
12670         return o;
12671     }
12672     else if ((o->op_type == OP_RV2HV || o->op_type == OP_PADHV)) {
12673         Perl_croak(aTHX_ "Can't use a hash as a reference");
12674     }
12675     return newUNOP(OP_RV2HV, 0, scalar(o));
12676 }
12677
12678 OP *
12679 Perl_newCVREF(pTHX_ I32 flags, OP *o)
12680 {
12681     if (o->op_type == OP_PADANY) {
12682         OpTYPE_set(o, OP_PADCV);
12683     }
12684     return newUNOP(OP_RV2CV, flags, scalar(o));
12685 }
12686
12687 OP *
12688 Perl_newSVREF(pTHX_ OP *o)
12689 {
12690
12691     PERL_ARGS_ASSERT_NEWSVREF;
12692
12693     if (o->op_type == OP_PADANY) {
12694         OpTYPE_set(o, OP_PADSV);
12695         scalar(o);
12696         return o;
12697     }
12698     return newUNOP(OP_RV2SV, 0, scalar(o));
12699 }
12700
12701 /* Check routines. See the comments at the top of this file for details
12702  * on when these are called */
12703
12704 OP *
12705 Perl_ck_anoncode(pTHX_ OP *o)
12706 {
12707     PERL_ARGS_ASSERT_CK_ANONCODE;
12708
12709     cSVOPo->op_targ = pad_add_anon((CV*)cSVOPo->op_sv, o->op_type);
12710     cSVOPo->op_sv = NULL;
12711     return o;
12712 }
12713
12714 static void
12715 S_io_hints(pTHX_ OP *o)
12716 {
12717 #if O_BINARY != 0 || O_TEXT != 0
12718     HV * const table =
12719         PL_hints & HINT_LOCALIZE_HH ? GvHV(PL_hintgv) : NULL;;
12720     if (table) {
12721         SV **svp = hv_fetchs(table, "open_IN", FALSE);
12722         if (svp && *svp) {
12723             STRLEN len = 0;
12724             const char *d = SvPV_const(*svp, len);
12725             const I32 mode = mode_from_discipline(d, len);
12726             /* bit-and:ing with zero O_BINARY or O_TEXT would be useless. */
12727 #  if O_BINARY != 0
12728             if (mode & O_BINARY)
12729                 o->op_private |= OPpOPEN_IN_RAW;
12730 #  endif
12731 #  if O_TEXT != 0
12732             if (mode & O_TEXT)
12733                 o->op_private |= OPpOPEN_IN_CRLF;
12734 #  endif
12735         }
12736
12737         svp = hv_fetchs(table, "open_OUT", FALSE);
12738         if (svp && *svp) {
12739             STRLEN len = 0;
12740             const char *d = SvPV_const(*svp, len);
12741             const I32 mode = mode_from_discipline(d, len);
12742             /* bit-and:ing with zero O_BINARY or O_TEXT would be useless. */
12743 #  if O_BINARY != 0
12744             if (mode & O_BINARY)
12745                 o->op_private |= OPpOPEN_OUT_RAW;
12746 #  endif
12747 #  if O_TEXT != 0
12748             if (mode & O_TEXT)
12749                 o->op_private |= OPpOPEN_OUT_CRLF;
12750 #  endif
12751         }
12752     }
12753 #else
12754     PERL_UNUSED_CONTEXT;
12755     PERL_UNUSED_ARG(o);
12756 #endif
12757 }
12758
12759 OP *
12760 Perl_ck_backtick(pTHX_ OP *o)
12761 {
12762     GV *gv;
12763     OP *newop = NULL;
12764     OP *sibl;
12765     PERL_ARGS_ASSERT_CK_BACKTICK;
12766     o = ck_fun(o);
12767     /* qx and `` have a null pushmark; CORE::readpipe has only one kid. */
12768     if (o->op_flags & OPf_KIDS && (sibl = OpSIBLING(cUNOPo->op_first))
12769      && (gv = gv_override("readpipe",8)))
12770     {
12771         /* detach rest of siblings from o and its first child */
12772         op_sibling_splice(o, cUNOPo->op_first, -1, NULL);
12773         newop = S_new_entersubop(aTHX_ gv, sibl);
12774     }
12775     else if (!(o->op_flags & OPf_KIDS))
12776         newop = newUNOP(OP_BACKTICK, 0, newDEFSVOP());
12777     if (newop) {
12778         op_free(o);
12779         return newop;
12780     }
12781     S_io_hints(aTHX_ o);
12782     return o;
12783 }
12784
12785 OP *
12786 Perl_ck_bitop(pTHX_ OP *o)
12787 {
12788     PERL_ARGS_ASSERT_CK_BITOP;
12789
12790     /* get rid of arg count and indicate if in the scope of 'use integer' */
12791     o->op_private = (PL_hints & HINT_INTEGER) ? OPpUSEINT : 0;
12792
12793     if (!(o->op_flags & OPf_STACKED) /* Not an assignment */
12794             && OP_IS_INFIX_BIT(o->op_type))
12795     {
12796         const OP * const left = cBINOPo->op_first;
12797         const OP * const right = OpSIBLING(left);
12798         if ((OP_IS_NUMCOMPARE(left->op_type) &&
12799                 (left->op_flags & OPf_PARENS) == 0) ||
12800             (OP_IS_NUMCOMPARE(right->op_type) &&
12801                 (right->op_flags & OPf_PARENS) == 0))
12802             Perl_ck_warner(aTHX_ packWARN(WARN_PRECEDENCE),
12803                           "Possible precedence problem on bitwise %s operator",
12804                            o->op_type ==  OP_BIT_OR
12805                          ||o->op_type == OP_NBIT_OR  ? "|"
12806                         :  o->op_type ==  OP_BIT_AND
12807                          ||o->op_type == OP_NBIT_AND ? "&"
12808                         :  o->op_type ==  OP_BIT_XOR
12809                          ||o->op_type == OP_NBIT_XOR ? "^"
12810                         :  o->op_type == OP_SBIT_OR  ? "|."
12811                         :  o->op_type == OP_SBIT_AND ? "&." : "^."
12812                            );
12813     }
12814     return o;
12815 }
12816
12817 PERL_STATIC_INLINE bool
12818 is_dollar_bracket(pTHX_ const OP * const o)
12819 {
12820     const OP *kid;
12821     PERL_UNUSED_CONTEXT;
12822     return o->op_type == OP_RV2SV && o->op_flags & OPf_KIDS
12823         && (kid = cUNOPx(o)->op_first)
12824         && kid->op_type == OP_GV
12825         && strEQ(GvNAME(cGVOPx_gv(kid)), "[");
12826 }
12827
12828 /* for lt, gt, le, ge, eq, ne and their i_ variants */
12829
12830 OP *
12831 Perl_ck_cmp(pTHX_ OP *o)
12832 {
12833     bool is_eq;
12834     bool neg;
12835     bool reverse;
12836     bool iv0;
12837     OP *indexop, *constop, *start;
12838     SV *sv;
12839     IV iv;
12840
12841     PERL_ARGS_ASSERT_CK_CMP;
12842
12843     is_eq = (   o->op_type == OP_EQ
12844              || o->op_type == OP_NE
12845              || o->op_type == OP_I_EQ
12846              || o->op_type == OP_I_NE);
12847
12848     if (!is_eq && ckWARN(WARN_SYNTAX)) {
12849         const OP *kid = cUNOPo->op_first;
12850         if (kid &&
12851             (
12852                 (   is_dollar_bracket(aTHX_ kid)
12853                  && OpSIBLING(kid) && OpSIBLING(kid)->op_type == OP_CONST
12854                 )
12855              || (   kid->op_type == OP_CONST
12856                  && (kid = OpSIBLING(kid)) && is_dollar_bracket(aTHX_ kid)
12857                 )
12858            )
12859         )
12860             Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
12861                         "$[ used in %s (did you mean $] ?)", OP_DESC(o));
12862     }
12863
12864     /* convert (index(...) == -1) and variations into
12865      *   (r)index/BOOL(,NEG)
12866      */
12867
12868     reverse = FALSE;
12869
12870     indexop = cUNOPo->op_first;
12871     constop = OpSIBLING(indexop);
12872     start = NULL;
12873     if (indexop->op_type == OP_CONST) {
12874         constop = indexop;
12875         indexop = OpSIBLING(constop);
12876         start = constop;
12877         reverse = TRUE;
12878     }
12879
12880     if (indexop->op_type != OP_INDEX && indexop->op_type != OP_RINDEX)
12881         return o;
12882
12883     /* ($lex = index(....)) == -1 */
12884     if (indexop->op_private & OPpTARGET_MY)
12885         return o;
12886
12887     if (constop->op_type != OP_CONST)
12888         return o;
12889
12890     sv = cSVOPx_sv(constop);
12891     if (!(sv && SvIOK_notUV(sv)))
12892         return o;
12893
12894     iv = SvIVX(sv);
12895     if (iv != -1 && iv != 0)
12896         return o;
12897     iv0 = (iv == 0);
12898
12899     if (o->op_type == OP_LT || o->op_type == OP_I_LT) {
12900         if (!(iv0 ^ reverse))
12901             return o;
12902         neg = iv0;
12903     }
12904     else if (o->op_type == OP_LE || o->op_type == OP_I_LE) {
12905         if (iv0 ^ reverse)
12906             return o;
12907         neg = !iv0;
12908     }
12909     else if (o->op_type == OP_GE || o->op_type == OP_I_GE) {
12910         if (!(iv0 ^ reverse))
12911             return o;
12912         neg = !iv0;
12913     }
12914     else if (o->op_type == OP_GT || o->op_type == OP_I_GT) {
12915         if (iv0 ^ reverse)
12916             return o;
12917         neg = iv0;
12918     }
12919     else if (o->op_type == OP_EQ || o->op_type == OP_I_EQ) {
12920         if (iv0)
12921             return o;
12922         neg = TRUE;
12923     }
12924     else {
12925         assert(o->op_type == OP_NE || o->op_type == OP_I_NE);
12926         if (iv0)
12927             return o;
12928         neg = FALSE;
12929     }
12930
12931     indexop->op_flags &= ~OPf_PARENS;
12932     indexop->op_flags |= (o->op_flags & OPf_PARENS);
12933     indexop->op_private |= OPpTRUEBOOL;
12934     if (neg)
12935         indexop->op_private |= OPpINDEX_BOOLNEG;
12936     /* cut out the index op and free the eq,const ops */
12937     (void)op_sibling_splice(o, start, 1, NULL);
12938     op_free(o);
12939
12940     return indexop;
12941 }
12942
12943
12944 OP *
12945 Perl_ck_concat(pTHX_ OP *o)
12946 {
12947     const OP * const kid = cUNOPo->op_first;
12948
12949     PERL_ARGS_ASSERT_CK_CONCAT;
12950     PERL_UNUSED_CONTEXT;
12951
12952     /* reuse the padtmp returned by the concat child */
12953     if (kid->op_type == OP_CONCAT && !(kid->op_private & OPpTARGET_MY) &&
12954             !(kUNOP->op_first->op_flags & OPf_MOD))
12955     {
12956         o->op_flags |= OPf_STACKED;
12957         o->op_private |= OPpCONCAT_NESTED;
12958     }
12959     return o;
12960 }
12961
12962 OP *
12963 Perl_ck_spair(pTHX_ OP *o)
12964 {
12965
12966     PERL_ARGS_ASSERT_CK_SPAIR;
12967
12968     if (o->op_flags & OPf_KIDS) {
12969         OP* newop;
12970         OP* kid;
12971         OP* kidkid;
12972         const OPCODE type = o->op_type;
12973         o = modkids(ck_fun(o), type);
12974         kid    = cUNOPo->op_first;
12975         kidkid = kUNOP->op_first;
12976         newop = OpSIBLING(kidkid);
12977         if (newop) {
12978             const OPCODE type = newop->op_type;
12979             if (OpHAS_SIBLING(newop))
12980                 return o;
12981             if (o->op_type == OP_REFGEN
12982              && (  type == OP_RV2CV
12983                 || (  !(newop->op_flags & OPf_PARENS)
12984                    && (  type == OP_RV2AV || type == OP_PADAV
12985                       || type == OP_RV2HV || type == OP_PADHV))))
12986                 NOOP; /* OK (allow srefgen for \@a and \%h) */
12987             else if (OP_GIMME(newop,0) != G_SCALAR)
12988                 return o;
12989         }
12990         /* excise first sibling */
12991         op_sibling_splice(kid, NULL, 1, NULL);
12992         op_free(kidkid);
12993     }
12994     /* transforms OP_REFGEN into OP_SREFGEN, OP_CHOP into OP_SCHOP,
12995      * and OP_CHOMP into OP_SCHOMP */
12996     o->op_ppaddr = PL_ppaddr[++o->op_type];
12997     return ck_fun(o);
12998 }
12999
13000 OP *
13001 Perl_ck_delete(pTHX_ OP *o)
13002 {
13003     PERL_ARGS_ASSERT_CK_DELETE;
13004
13005     o = ck_fun(o);
13006     o->op_private = 0;
13007     if (o->op_flags & OPf_KIDS) {
13008         OP * const kid = cUNOPo->op_first;
13009         switch (kid->op_type) {
13010         case OP_ASLICE:
13011             o->op_flags |= OPf_SPECIAL;
13012             /* FALLTHROUGH */
13013         case OP_HSLICE:
13014             o->op_private |= OPpSLICE;
13015             break;
13016         case OP_AELEM:
13017             o->op_flags |= OPf_SPECIAL;
13018             /* FALLTHROUGH */
13019         case OP_HELEM:
13020             break;
13021         case OP_KVASLICE:
13022             o->op_flags |= OPf_SPECIAL;
13023             /* FALLTHROUGH */
13024         case OP_KVHSLICE:
13025             o->op_private |= OPpKVSLICE;
13026             break;
13027         default:
13028             Perl_croak(aTHX_ "delete argument is not a HASH or ARRAY "
13029                              "element or slice");
13030         }
13031         if (kid->op_private & OPpLVAL_INTRO)
13032             o->op_private |= OPpLVAL_INTRO;
13033         op_null(kid);
13034     }
13035     return o;
13036 }
13037
13038 OP *
13039 Perl_ck_eof(pTHX_ OP *o)
13040 {
13041     PERL_ARGS_ASSERT_CK_EOF;
13042
13043     if (o->op_flags & OPf_KIDS) {
13044         OP *kid;
13045         if (cLISTOPo->op_first->op_type == OP_STUB) {
13046             OP * const newop
13047                 = newUNOP(o->op_type, OPf_SPECIAL, newGVOP(OP_GV, 0, PL_argvgv));
13048             op_free(o);
13049             o = newop;
13050         }
13051         o = ck_fun(o);
13052         kid = cLISTOPo->op_first;
13053         if (kid->op_type == OP_RV2GV)
13054             kid->op_private |= OPpALLOW_FAKE;
13055     }
13056     return o;
13057 }
13058
13059
13060 OP *
13061 Perl_ck_eval(pTHX_ OP *o)
13062 {
13063
13064     PERL_ARGS_ASSERT_CK_EVAL;
13065
13066     PL_hints |= HINT_BLOCK_SCOPE;
13067     if (o->op_flags & OPf_KIDS) {
13068         SVOP * const kid = (SVOP*)cUNOPo->op_first;
13069         assert(kid);
13070
13071         if (o->op_type == OP_ENTERTRY) {
13072             LOGOP *enter;
13073
13074             /* cut whole sibling chain free from o */
13075             op_sibling_splice(o, NULL, -1, NULL);
13076             op_free(o);
13077
13078             enter = alloc_LOGOP(OP_ENTERTRY, NULL, NULL);
13079
13080             /* establish postfix order */
13081             enter->op_next = (OP*)enter;
13082
13083             o = op_prepend_elem(OP_LINESEQ, (OP*)enter, (OP*)kid);
13084             OpTYPE_set(o, OP_LEAVETRY);
13085             enter->op_other = o;
13086             return o;
13087         }
13088         else {
13089             scalar((OP*)kid);
13090             S_set_haseval(aTHX);
13091         }
13092     }
13093     else {
13094         const U8 priv = o->op_private;
13095         op_free(o);
13096         /* the newUNOP will recursively call ck_eval(), which will handle
13097          * all the stuff at the end of this function, like adding
13098          * OP_HINTSEVAL
13099          */
13100         return newUNOP(OP_ENTEREVAL, priv <<8, newDEFSVOP());
13101     }
13102     o->op_targ = (PADOFFSET)PL_hints;
13103     if (o->op_private & OPpEVAL_BYTES) o->op_targ &= ~HINT_UTF8;
13104     if ((PL_hints & HINT_LOCALIZE_HH) != 0
13105      && !(o->op_private & OPpEVAL_COPHH) && GvHV(PL_hintgv)) {
13106         /* Store a copy of %^H that pp_entereval can pick up. */
13107         HV *hh = hv_copy_hints_hv(GvHV(PL_hintgv));
13108         OP *hhop;
13109         STOREFEATUREBITSHH(hh);
13110         hhop = newSVOP(OP_HINTSEVAL, 0, MUTABLE_SV(hh));
13111         /* append hhop to only child  */
13112         op_sibling_splice(o, cUNOPo->op_first, 0, hhop);
13113
13114         o->op_private |= OPpEVAL_HAS_HH;
13115     }
13116     if (!(o->op_private & OPpEVAL_BYTES)
13117          && FEATURE_UNIEVAL_IS_ENABLED)
13118             o->op_private |= OPpEVAL_UNICODE;
13119     return o;
13120 }
13121
13122 OP *
13123 Perl_ck_trycatch(pTHX_ OP *o)
13124 {
13125     LOGOP *enter;
13126     OP *to_free = NULL;
13127     OP *trykid, *catchkid;
13128     OP *catchroot, *catchstart;
13129
13130     PERL_ARGS_ASSERT_CK_TRYCATCH;
13131
13132     trykid = cUNOPo->op_first;
13133     if(trykid->op_type == OP_NULL || trykid->op_type == OP_PUSHMARK) {
13134         to_free = trykid;
13135         trykid = OpSIBLING(trykid);
13136     }
13137     catchkid = OpSIBLING(trykid);
13138
13139     assert(trykid->op_type == OP_POPTRY);
13140     assert(catchkid->op_type == OP_CATCH);
13141
13142     /* cut whole sibling chain free from o */
13143     op_sibling_splice(o, NULL, -1, NULL);
13144     if(to_free)
13145         op_free(to_free);
13146     op_free(o);
13147
13148     enter = alloc_LOGOP(OP_ENTERTRYCATCH, NULL, NULL);
13149
13150     /* establish postfix order */
13151     enter->op_next = (OP*)enter;
13152
13153     o = op_prepend_elem(OP_LINESEQ, (OP*)enter, trykid);
13154     op_append_elem(OP_LINESEQ, (OP*)o, catchkid);
13155
13156     OpTYPE_set(o, OP_LEAVETRYCATCH);
13157
13158     /* The returned optree is actually threaded up slightly nonobviously in
13159      * terms of its ->op_next pointers.
13160      *
13161      * This way, if the tryblock dies, its retop points at the OP_CATCH, but
13162      * if it does not then its leavetry skips over that and continues
13163      * execution past it.
13164      */
13165
13166     /* First, link up the actual body of the catch block */
13167     catchroot = OpSIBLING(cUNOPx(catchkid)->op_first);
13168     catchstart = LINKLIST(catchroot);
13169     cLOGOPx(catchkid)->op_other = catchstart;
13170
13171     o->op_next = LINKLIST(o);
13172
13173     /* die within try block should jump to the catch */
13174     enter->op_other = catchkid;
13175
13176     /* after try block that doesn't die, just skip straight to leavetrycatch */
13177     trykid->op_next = o;
13178
13179     /* after catch block, skip back up to the leavetrycatch */
13180     catchroot->op_next = o;
13181
13182     return o;
13183 }
13184
13185 OP *
13186 Perl_ck_exec(pTHX_ OP *o)
13187 {
13188     PERL_ARGS_ASSERT_CK_EXEC;
13189
13190     if (o->op_flags & OPf_STACKED) {
13191         OP *kid;
13192         o = ck_fun(o);
13193         kid = OpSIBLING(cUNOPo->op_first);
13194         if (kid->op_type == OP_RV2GV)
13195             op_null(kid);
13196     }
13197     else
13198         o = listkids(o);
13199     return o;
13200 }
13201
13202 OP *
13203 Perl_ck_exists(pTHX_ OP *o)
13204 {
13205     PERL_ARGS_ASSERT_CK_EXISTS;
13206
13207     o = ck_fun(o);
13208     if (o->op_flags & OPf_KIDS) {
13209         OP * const kid = cUNOPo->op_first;
13210         if (kid->op_type == OP_ENTERSUB) {
13211             (void) ref(kid, o->op_type);
13212             if (kid->op_type != OP_RV2CV
13213                         && !(PL_parser && PL_parser->error_count))
13214                 Perl_croak(aTHX_
13215                           "exists argument is not a subroutine name");
13216             o->op_private |= OPpEXISTS_SUB;
13217         }
13218         else if (kid->op_type == OP_AELEM)
13219             o->op_flags |= OPf_SPECIAL;
13220         else if (kid->op_type != OP_HELEM)
13221             Perl_croak(aTHX_ "exists argument is not a HASH or ARRAY "
13222                              "element or a subroutine");
13223         op_null(kid);
13224     }
13225     return o;
13226 }
13227
13228 OP *
13229 Perl_ck_rvconst(pTHX_ OP *o)
13230 {
13231     SVOP * const kid = (SVOP*)cUNOPo->op_first;
13232
13233     PERL_ARGS_ASSERT_CK_RVCONST;
13234
13235     if (o->op_type == OP_RV2HV)
13236         /* rv2hv steals the bottom bit for its own uses */
13237         o->op_private &= ~OPpARG1_MASK;
13238
13239     o->op_private |= (PL_hints & HINT_STRICT_REFS);
13240
13241     if (kid->op_type == OP_CONST) {
13242         int iscv;
13243         GV *gv;
13244         SV * const kidsv = kid->op_sv;
13245
13246         /* Is it a constant from cv_const_sv()? */
13247         if ((SvROK(kidsv) || isGV_with_GP(kidsv)) && SvREADONLY(kidsv)) {
13248             return o;
13249         }
13250         if (SvTYPE(kidsv) == SVt_PVAV) return o;
13251         if ((o->op_private & HINT_STRICT_REFS) && (kid->op_private & OPpCONST_BARE)) {
13252             const char *badthing;
13253             switch (o->op_type) {
13254             case OP_RV2SV:
13255                 badthing = "a SCALAR";
13256                 break;
13257             case OP_RV2AV:
13258                 badthing = "an ARRAY";
13259                 break;
13260             case OP_RV2HV:
13261                 badthing = "a HASH";
13262                 break;
13263             default:
13264                 badthing = NULL;
13265                 break;
13266             }
13267             if (badthing)
13268                 Perl_croak(aTHX_
13269                            "Can't use bareword (\"%" SVf "\") as %s ref while \"strict refs\" in use",
13270                            SVfARG(kidsv), badthing);
13271         }
13272         /*
13273          * This is a little tricky.  We only want to add the symbol if we
13274          * didn't add it in the lexer.  Otherwise we get duplicate strict
13275          * warnings.  But if we didn't add it in the lexer, we must at
13276          * least pretend like we wanted to add it even if it existed before,
13277          * or we get possible typo warnings.  OPpCONST_ENTERED says
13278          * whether the lexer already added THIS instance of this symbol.
13279          */
13280         iscv = o->op_type == OP_RV2CV ? GV_NOEXPAND|GV_ADDMULTI : 0;
13281         gv = gv_fetchsv(kidsv,
13282                 o->op_type == OP_RV2CV
13283                         && o->op_private & OPpMAY_RETURN_CONSTANT
13284                     ? GV_NOEXPAND
13285                     : iscv | !(kid->op_private & OPpCONST_ENTERED),
13286                 iscv
13287                     ? SVt_PVCV
13288                     : o->op_type == OP_RV2SV
13289                         ? SVt_PV
13290                         : o->op_type == OP_RV2AV
13291                             ? SVt_PVAV
13292                             : o->op_type == OP_RV2HV
13293                                 ? SVt_PVHV
13294                                 : SVt_PVGV);
13295         if (gv) {
13296             if (!isGV(gv)) {
13297                 assert(iscv);
13298                 assert(SvROK(gv));
13299                 if (!(o->op_private & OPpMAY_RETURN_CONSTANT)
13300                   && SvTYPE(SvRV(gv)) != SVt_PVCV)
13301                     gv_fetchsv(kidsv, GV_ADDMULTI, SVt_PVCV);
13302             }
13303             OpTYPE_set(kid, OP_GV);
13304             SvREFCNT_dec(kid->op_sv);
13305 #ifdef USE_ITHREADS
13306             /* XXX hack: dependence on sizeof(PADOP) <= sizeof(SVOP) */
13307             STATIC_ASSERT_STMT(sizeof(PADOP) <= sizeof(SVOP));
13308             kPADOP->op_padix = pad_alloc(OP_GV, SVf_READONLY);
13309             SvREFCNT_dec(PAD_SVl(kPADOP->op_padix));
13310             PAD_SETSV(kPADOP->op_padix, MUTABLE_SV(SvREFCNT_inc_simple_NN(gv)));
13311 #else
13312             kid->op_sv = SvREFCNT_inc_simple_NN(gv);
13313 #endif
13314             kid->op_private = 0;
13315             /* FAKE globs in the symbol table cause weird bugs (#77810) */
13316             SvFAKE_off(gv);
13317         }
13318     }
13319     return o;
13320 }
13321
13322 OP *
13323 Perl_ck_ftst(pTHX_ OP *o)
13324 {
13325     const I32 type = o->op_type;
13326
13327     PERL_ARGS_ASSERT_CK_FTST;
13328
13329     if (o->op_flags & OPf_REF) {
13330         NOOP;
13331     }
13332     else if (o->op_flags & OPf_KIDS && cUNOPo->op_first->op_type != OP_STUB) {
13333         SVOP * const kid = (SVOP*)cUNOPo->op_first;
13334         const OPCODE kidtype = kid->op_type;
13335
13336         if (kidtype == OP_CONST && (kid->op_private & OPpCONST_BARE)
13337          && !kid->op_folded) {
13338             OP * const newop = newGVOP(type, OPf_REF,
13339                 gv_fetchsv(kid->op_sv, GV_ADD, SVt_PVIO));
13340             op_free(o);
13341             return newop;
13342         }
13343
13344         if ((kidtype == OP_RV2AV || kidtype == OP_PADAV) && ckWARN(WARN_SYNTAX)) {
13345             SV *name = S_op_varname_subscript(aTHX_ (OP*)kid, 2);
13346             if (name) {
13347                 /* diag_listed_as: Array passed to stat will be coerced to a scalar%s */
13348                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX), "%s (did you want stat %" SVf "?)",
13349                             array_passed_to_stat, name);
13350             }
13351             else {
13352                 /* diag_listed_as: Array passed to stat will be coerced to a scalar%s */
13353                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX), "%s", array_passed_to_stat);
13354             }
13355        }
13356         scalar((OP *) kid);
13357         if ((PL_hints & HINT_FILETEST_ACCESS) && OP_IS_FILETEST_ACCESS(o->op_type))
13358             o->op_private |= OPpFT_ACCESS;
13359         if (OP_IS_FILETEST(type)
13360             && OP_IS_FILETEST(kidtype)
13361         ) {
13362             o->op_private |= OPpFT_STACKED;
13363             kid->op_private |= OPpFT_STACKING;
13364             if (kidtype == OP_FTTTY && (
13365                    !(kid->op_private & OPpFT_STACKED)
13366                 || kid->op_private & OPpFT_AFTER_t
13367                ))
13368                 o->op_private |= OPpFT_AFTER_t;
13369         }
13370     }
13371     else {
13372         op_free(o);
13373         if (type == OP_FTTTY)
13374             o = newGVOP(type, OPf_REF, PL_stdingv);
13375         else
13376             o = newUNOP(type, 0, newDEFSVOP());
13377     }
13378     return o;
13379 }
13380
13381 OP *
13382 Perl_ck_fun(pTHX_ OP *o)
13383 {
13384     const int type = o->op_type;
13385     I32 oa = PL_opargs[type] >> OASHIFT;
13386
13387     PERL_ARGS_ASSERT_CK_FUN;
13388
13389     if (o->op_flags & OPf_STACKED) {
13390         if ((oa & OA_OPTIONAL) && (oa >> 4) && !((oa >> 4) & OA_OPTIONAL))
13391             oa &= ~OA_OPTIONAL;
13392         else
13393             return no_fh_allowed(o);
13394     }
13395
13396     if (o->op_flags & OPf_KIDS) {
13397         OP *prev_kid = NULL;
13398         OP *kid = cLISTOPo->op_first;
13399         I32 numargs = 0;
13400         bool seen_optional = FALSE;
13401
13402         if (kid->op_type == OP_PUSHMARK ||
13403             (kid->op_type == OP_NULL && kid->op_targ == OP_PUSHMARK))
13404         {
13405             prev_kid = kid;
13406             kid = OpSIBLING(kid);
13407         }
13408         if (kid && kid->op_type == OP_COREARGS) {
13409             bool optional = FALSE;
13410             while (oa) {
13411                 numargs++;
13412                 if (oa & OA_OPTIONAL) optional = TRUE;
13413                 oa = oa >> 4;
13414             }
13415             if (optional) o->op_private |= numargs;
13416             return o;
13417         }
13418
13419         while (oa) {
13420             if (oa & OA_OPTIONAL || (oa & 7) == OA_LIST) {
13421                 if (!kid && !seen_optional && PL_opargs[type] & OA_DEFGV) {
13422                     kid = newDEFSVOP();
13423                     /* append kid to chain */
13424                     op_sibling_splice(o, prev_kid, 0, kid);
13425                 }
13426                 seen_optional = TRUE;
13427             }
13428             if (!kid) break;
13429
13430             numargs++;
13431             switch (oa & 7) {
13432             case OA_SCALAR:
13433                 /* list seen where single (scalar) arg expected? */
13434                 if (numargs == 1 && !(oa >> 4)
13435                     && kid->op_type == OP_LIST && type != OP_SCALAR)
13436                 {
13437                     return too_many_arguments_pv(o,PL_op_desc[type], 0);
13438                 }
13439                 if (type != OP_DELETE) scalar(kid);
13440                 break;
13441             case OA_LIST:
13442                 if (oa < 16) {
13443                     kid = 0;
13444                     continue;
13445                 }
13446                 else
13447                     list(kid);
13448                 break;
13449             case OA_AVREF:
13450                 if ((type == OP_PUSH || type == OP_UNSHIFT)
13451                     && !OpHAS_SIBLING(kid))
13452                     Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX),
13453                                    "Useless use of %s with no values",
13454                                    PL_op_desc[type]);
13455
13456                 if (kid->op_type == OP_CONST
13457                       && (  !SvROK(cSVOPx_sv(kid))
13458                          || SvTYPE(SvRV(cSVOPx_sv(kid))) != SVt_PVAV  )
13459                         )
13460                     bad_type_pv(numargs, "array", o, kid);
13461                 else if (kid->op_type == OP_RV2HV || kid->op_type == OP_PADHV
13462                          || kid->op_type == OP_RV2GV) {
13463                     bad_type_pv(1, "array", o, kid);
13464                 }
13465                 else if (kid->op_type != OP_RV2AV && kid->op_type != OP_PADAV) {
13466                     yyerror_pv(Perl_form(aTHX_ "Experimental %s on scalar is now forbidden",
13467                                          PL_op_desc[type]), 0);
13468                 }
13469                 else {
13470                     op_lvalue(kid, type);
13471                 }
13472                 break;
13473             case OA_HVREF:
13474                 if (kid->op_type != OP_RV2HV && kid->op_type != OP_PADHV)
13475                     bad_type_pv(numargs, "hash", o, kid);
13476                 op_lvalue(kid, type);
13477                 break;
13478             case OA_CVREF:
13479                 {
13480                     /* replace kid with newop in chain */
13481                     OP * const newop =
13482                         S_op_sibling_newUNOP(aTHX_ o, prev_kid, OP_NULL, 0);
13483                     newop->op_next = newop;
13484                     kid = newop;
13485                 }
13486                 break;
13487             case OA_FILEREF:
13488                 if (kid->op_type != OP_GV && kid->op_type != OP_RV2GV) {
13489                     if (kid->op_type == OP_CONST &&
13490                         (kid->op_private & OPpCONST_BARE))
13491                     {
13492                         OP * const newop = newGVOP(OP_GV, 0,
13493                             gv_fetchsv(((SVOP*)kid)->op_sv, GV_ADD, SVt_PVIO));
13494                         /* a first argument is handled by toke.c, ideally we'd
13495                          just check here but several ops don't use ck_fun() */
13496                         if (!FEATURE_BAREWORD_FILEHANDLES_IS_ENABLED && numargs > 1) {
13497                             no_bareword_filehandle(SvPVX(cSVOPx_sv((SVOP*)kid)));
13498                         }
13499                         /* replace kid with newop in chain */
13500                         op_sibling_splice(o, prev_kid, 1, newop);
13501                         op_free(kid);
13502                         kid = newop;
13503                     }
13504                     else if (kid->op_type == OP_READLINE) {
13505                         /* neophyte patrol: open(<FH>), close(<FH>) etc. */
13506                         bad_type_pv(numargs, "HANDLE", o, kid);
13507                     }
13508                     else {
13509                         I32 flags = OPf_SPECIAL;
13510                         I32 priv = 0;
13511                         PADOFFSET targ = 0;
13512
13513                         /* is this op a FH constructor? */
13514                         if (is_handle_constructor(o,numargs)) {
13515                             const char *name = NULL;
13516                             STRLEN len = 0;
13517                             U32 name_utf8 = 0;
13518                             bool want_dollar = TRUE;
13519
13520                             flags = 0;
13521                             /* Set a flag to tell rv2gv to vivify
13522                              * need to "prove" flag does not mean something
13523                              * else already - NI-S 1999/05/07
13524                              */
13525                             priv = OPpDEREF;
13526                             if (kid->op_type == OP_PADSV) {
13527                                 PADNAME * const pn
13528                                     = PAD_COMPNAME_SV(kid->op_targ);
13529                                 name = PadnamePV (pn);
13530                                 len  = PadnameLEN(pn);
13531                                 name_utf8 = PadnameUTF8(pn);
13532                             }
13533                             else if (kid->op_type == OP_RV2SV
13534                                      && kUNOP->op_first->op_type == OP_GV)
13535                             {
13536                                 GV * const gv = cGVOPx_gv(kUNOP->op_first);
13537                                 name = GvNAME(gv);
13538                                 len = GvNAMELEN(gv);
13539                                 name_utf8 = GvNAMEUTF8(gv) ? SVf_UTF8 : 0;
13540                             }
13541                             else if (kid->op_type == OP_AELEM
13542                                      || kid->op_type == OP_HELEM)
13543                             {
13544                                  OP *firstop;
13545                                  OP *op = ((BINOP*)kid)->op_first;
13546                                  name = NULL;
13547                                  if (op) {
13548                                       SV *tmpstr = NULL;
13549                                       const char * const a =
13550                                            kid->op_type == OP_AELEM ?
13551                                            "[]" : "{}";
13552                                       if (((op->op_type == OP_RV2AV) ||
13553                                            (op->op_type == OP_RV2HV)) &&
13554                                           (firstop = ((UNOP*)op)->op_first) &&
13555                                           (firstop->op_type == OP_GV)) {
13556                                            /* packagevar $a[] or $h{} */
13557                                            GV * const gv = cGVOPx_gv(firstop);
13558                                            if (gv)
13559                                                 tmpstr =
13560                                                      Perl_newSVpvf(aTHX_
13561                                                                    "%s%c...%c",
13562                                                                    GvNAME(gv),
13563                                                                    a[0], a[1]);
13564                                       }
13565                                       else if (op->op_type == OP_PADAV
13566                                                || op->op_type == OP_PADHV) {
13567                                            /* lexicalvar $a[] or $h{} */
13568                                            const char * const padname =
13569                                                 PAD_COMPNAME_PV(op->op_targ);
13570                                            if (padname)
13571                                                 tmpstr =
13572                                                      Perl_newSVpvf(aTHX_
13573                                                                    "%s%c...%c",
13574                                                                    padname + 1,
13575                                                                    a[0], a[1]);
13576                                       }
13577                                       if (tmpstr) {
13578                                            name = SvPV_const(tmpstr, len);
13579                                            name_utf8 = SvUTF8(tmpstr);
13580                                            sv_2mortal(tmpstr);
13581                                       }
13582                                  }
13583                                  if (!name) {
13584                                       name = "__ANONIO__";
13585                                       len = 10;
13586                                       want_dollar = FALSE;
13587                                  }
13588                                  op_lvalue(kid, type);
13589                             }
13590                             if (name) {
13591                                 SV *namesv;
13592                                 targ = pad_alloc(OP_RV2GV, SVf_READONLY);
13593                                 namesv = PAD_SVl(targ);
13594                                 if (want_dollar && *name != '$')
13595                                     sv_setpvs(namesv, "$");
13596                                 else
13597                                     SvPVCLEAR(namesv);
13598                                 sv_catpvn(namesv, name, len);
13599                                 if ( name_utf8 ) SvUTF8_on(namesv);
13600                             }
13601                         }
13602                         scalar(kid);
13603                         kid = S_op_sibling_newUNOP(aTHX_ o, prev_kid,
13604                                     OP_RV2GV, flags);
13605                         kid->op_targ = targ;
13606                         kid->op_private |= priv;
13607                     }
13608                 }
13609                 scalar(kid);
13610                 break;
13611             case OA_SCALARREF:
13612                 if ((type == OP_UNDEF || type == OP_POS)
13613                     && numargs == 1 && !(oa >> 4)
13614                     && kid->op_type == OP_LIST)
13615                     return too_many_arguments_pv(o,PL_op_desc[type], 0);
13616                 op_lvalue(scalar(kid), type);
13617                 break;
13618             }
13619             oa >>= 4;
13620             prev_kid = kid;
13621             kid = OpSIBLING(kid);
13622         }
13623         /* FIXME - should the numargs or-ing move after the too many
13624          * arguments check? */
13625         o->op_private |= numargs;
13626         if (kid)
13627             return too_many_arguments_pv(o,OP_DESC(o), 0);
13628         listkids(o);
13629     }
13630     else if (PL_opargs[type] & OA_DEFGV) {
13631         /* Ordering of these two is important to keep f_map.t passing.  */
13632         op_free(o);
13633         return newUNOP(type, 0, newDEFSVOP());
13634     }
13635
13636     if (oa) {
13637         while (oa & OA_OPTIONAL)
13638             oa >>= 4;
13639         if (oa && oa != OA_LIST)
13640             return too_few_arguments_pv(o,OP_DESC(o), 0);
13641     }
13642     return o;
13643 }
13644
13645 OP *
13646 Perl_ck_glob(pTHX_ OP *o)
13647 {
13648     GV *gv;
13649
13650     PERL_ARGS_ASSERT_CK_GLOB;
13651
13652     o = ck_fun(o);
13653     if ((o->op_flags & OPf_KIDS) && !OpHAS_SIBLING(cLISTOPo->op_first))
13654         op_append_elem(OP_GLOB, o, newDEFSVOP()); /* glob() => glob($_) */
13655
13656     if (!(o->op_flags & OPf_SPECIAL) && (gv = gv_override("glob", 4)))
13657     {
13658         /* convert
13659          *     glob
13660          *       \ null - const(wildcard)
13661          * into
13662          *     null
13663          *       \ enter
13664          *            \ list
13665          *                 \ mark - glob - rv2cv
13666          *                             |        \ gv(CORE::GLOBAL::glob)
13667          *                             |
13668          *                              \ null - const(wildcard)
13669          */
13670         o->op_flags |= OPf_SPECIAL;
13671         o->op_targ = pad_alloc(OP_GLOB, SVs_PADTMP);
13672         o = S_new_entersubop(aTHX_ gv, o);
13673         o = newUNOP(OP_NULL, 0, o);
13674         o->op_targ = OP_GLOB; /* hint at what it used to be: eg in newWHILEOP */
13675         return o;
13676     }
13677     else o->op_flags &= ~OPf_SPECIAL;
13678 #if !defined(PERL_EXTERNAL_GLOB)
13679     if (!PL_globhook) {
13680         ENTER;
13681         Perl_load_module(aTHX_ PERL_LOADMOD_NOIMPORT,
13682                                newSVpvs("File::Glob"), NULL, NULL, NULL);
13683         LEAVE;
13684     }
13685 #endif /* !PERL_EXTERNAL_GLOB */
13686     gv = (GV *)newSV(0);
13687     gv_init(gv, 0, "", 0, 0);
13688     gv_IOadd(gv);
13689     op_append_elem(OP_GLOB, o, newGVOP(OP_GV, 0, gv));
13690     SvREFCNT_dec_NN(gv); /* newGVOP increased it */
13691     scalarkids(o);
13692     return o;
13693 }
13694
13695 OP *
13696 Perl_ck_grep(pTHX_ OP *o)
13697 {
13698     LOGOP *gwop;
13699     OP *kid;
13700     const OPCODE type = o->op_type == OP_GREPSTART ? OP_GREPWHILE : OP_MAPWHILE;
13701
13702     PERL_ARGS_ASSERT_CK_GREP;
13703
13704     /* don't allocate gwop here, as we may leak it if PL_parser->error_count > 0 */
13705
13706     if (o->op_flags & OPf_STACKED) {
13707         kid = cUNOPx(OpSIBLING(cLISTOPo->op_first))->op_first;
13708         if (kid->op_type != OP_SCOPE && kid->op_type != OP_LEAVE)
13709             return no_fh_allowed(o);
13710         o->op_flags &= ~OPf_STACKED;
13711     }
13712     kid = OpSIBLING(cLISTOPo->op_first);
13713     if (type == OP_MAPWHILE)
13714         list(kid);
13715     else
13716         scalar(kid);
13717     o = ck_fun(o);
13718     if (PL_parser && PL_parser->error_count)
13719         return o;
13720     kid = OpSIBLING(cLISTOPo->op_first);
13721     if (kid->op_type != OP_NULL)
13722         Perl_croak(aTHX_ "panic: ck_grep, type=%u", (unsigned) kid->op_type);
13723     kid = kUNOP->op_first;
13724
13725     gwop = alloc_LOGOP(type, o, LINKLIST(kid));
13726     kid->op_next = (OP*)gwop;
13727     o->op_private = gwop->op_private = 0;
13728     gwop->op_targ = pad_alloc(type, SVs_PADTMP);
13729
13730     kid = OpSIBLING(cLISTOPo->op_first);
13731     for (kid = OpSIBLING(kid); kid; kid = OpSIBLING(kid))
13732         op_lvalue(kid, OP_GREPSTART);
13733
13734     return (OP*)gwop;
13735 }
13736
13737 OP *
13738 Perl_ck_index(pTHX_ OP *o)
13739 {
13740     PERL_ARGS_ASSERT_CK_INDEX;
13741
13742     if (o->op_flags & OPf_KIDS) {
13743         OP *kid = OpSIBLING(cLISTOPo->op_first);        /* get past pushmark */
13744         if (kid)
13745             kid = OpSIBLING(kid);                       /* get past "big" */
13746         if (kid && kid->op_type == OP_CONST) {
13747             const bool save_taint = TAINT_get;
13748             SV *sv = kSVOP->op_sv;
13749             if (   (!SvPOK(sv) || SvNIOKp(sv) || isREGEXP(sv))
13750                 && SvOK(sv) && !SvROK(sv))
13751             {
13752                 sv = newSV(0);
13753                 sv_copypv(sv, kSVOP->op_sv);
13754                 SvREFCNT_dec_NN(kSVOP->op_sv);
13755                 kSVOP->op_sv = sv;
13756             }
13757             if (SvOK(sv)) fbm_compile(sv, 0);
13758             TAINT_set(save_taint);
13759 #ifdef NO_TAINT_SUPPORT
13760             PERL_UNUSED_VAR(save_taint);
13761 #endif
13762         }
13763     }
13764     return ck_fun(o);
13765 }
13766
13767 OP *
13768 Perl_ck_lfun(pTHX_ OP *o)
13769 {
13770     const OPCODE type = o->op_type;
13771
13772     PERL_ARGS_ASSERT_CK_LFUN;
13773
13774     return modkids(ck_fun(o), type);
13775 }
13776
13777 OP *
13778 Perl_ck_defined(pTHX_ OP *o)            /* 19990527 MJD */
13779 {
13780     PERL_ARGS_ASSERT_CK_DEFINED;
13781
13782     if ((o->op_flags & OPf_KIDS)) {
13783         switch (cUNOPo->op_first->op_type) {
13784         case OP_RV2AV:
13785         case OP_PADAV:
13786             Perl_croak(aTHX_ "Can't use 'defined(@array)'"
13787                              " (Maybe you should just omit the defined()?)");
13788             NOT_REACHED; /* NOTREACHED */
13789             break;
13790         case OP_RV2HV:
13791         case OP_PADHV:
13792             Perl_croak(aTHX_ "Can't use 'defined(%%hash)'"
13793                              " (Maybe you should just omit the defined()?)");
13794             NOT_REACHED; /* NOTREACHED */
13795             break;
13796         default:
13797             /* no warning */
13798             break;
13799         }
13800     }
13801     return ck_rfun(o);
13802 }
13803
13804 OP *
13805 Perl_ck_readline(pTHX_ OP *o)
13806 {
13807     PERL_ARGS_ASSERT_CK_READLINE;
13808
13809     if (o->op_flags & OPf_KIDS) {
13810          OP *kid = cLISTOPo->op_first;
13811          if (kid->op_type == OP_RV2GV) kid->op_private |= OPpALLOW_FAKE;
13812          scalar(kid);
13813     }
13814     else {
13815         OP * const newop
13816             = newUNOP(OP_READLINE, 0, newGVOP(OP_GV, 0, PL_argvgv));
13817         op_free(o);
13818         return newop;
13819     }
13820     return o;
13821 }
13822
13823 OP *
13824 Perl_ck_rfun(pTHX_ OP *o)
13825 {
13826     const OPCODE type = o->op_type;
13827
13828     PERL_ARGS_ASSERT_CK_RFUN;
13829
13830     return refkids(ck_fun(o), type);
13831 }
13832
13833 OP *
13834 Perl_ck_listiob(pTHX_ OP *o)
13835 {
13836     OP *kid;
13837
13838     PERL_ARGS_ASSERT_CK_LISTIOB;
13839
13840     kid = cLISTOPo->op_first;
13841     if (!kid) {
13842         o = force_list(o, TRUE);
13843         kid = cLISTOPo->op_first;
13844     }
13845     if (kid->op_type == OP_PUSHMARK)
13846         kid = OpSIBLING(kid);
13847     if (kid && o->op_flags & OPf_STACKED)
13848         kid = OpSIBLING(kid);
13849     else if (kid && !OpHAS_SIBLING(kid)) {              /* print HANDLE; */
13850         if (kid->op_type == OP_CONST && kid->op_private & OPpCONST_BARE
13851          && !kid->op_folded) {
13852             o->op_flags |= OPf_STACKED; /* make it a filehandle */
13853             scalar(kid);
13854             /* replace old const op with new OP_RV2GV parent */
13855             kid = S_op_sibling_newUNOP(aTHX_ o, cLISTOPo->op_first,
13856                                         OP_RV2GV, OPf_REF);
13857             kid = OpSIBLING(kid);
13858         }
13859     }
13860
13861     if (!kid)
13862         op_append_elem(o->op_type, o, newDEFSVOP());
13863
13864     if (o->op_type == OP_PRTF) return modkids(listkids(o), OP_PRTF);
13865     return listkids(o);
13866 }
13867
13868 OP *
13869 Perl_ck_smartmatch(pTHX_ OP *o)
13870 {
13871     PERL_ARGS_ASSERT_CK_SMARTMATCH;
13872     if (0 == (o->op_flags & OPf_SPECIAL)) {
13873         OP *first  = cBINOPo->op_first;
13874         OP *second = OpSIBLING(first);
13875
13876         /* Implicitly take a reference to an array or hash */
13877
13878         /* remove the original two siblings, then add back the
13879          * (possibly different) first and second sibs.
13880          */
13881         op_sibling_splice(o, NULL, 1, NULL);
13882         op_sibling_splice(o, NULL, 1, NULL);
13883         first  = ref_array_or_hash(first);
13884         second = ref_array_or_hash(second);
13885         op_sibling_splice(o, NULL, 0, second);
13886         op_sibling_splice(o, NULL, 0, first);
13887
13888         /* Implicitly take a reference to a regular expression */
13889         if (first->op_type == OP_MATCH && !(first->op_flags & OPf_STACKED)) {
13890             OpTYPE_set(first, OP_QR);
13891         }
13892         if (second->op_type == OP_MATCH && !(second->op_flags & OPf_STACKED)) {
13893             OpTYPE_set(second, OP_QR);
13894         }
13895     }
13896
13897     return o;
13898 }
13899
13900
13901 static OP *
13902 S_maybe_targlex(pTHX_ OP *o)
13903 {
13904     OP * const kid = cLISTOPo->op_first;
13905     /* has a disposable target? */
13906     if ((PL_opargs[kid->op_type] & OA_TARGLEX)
13907         && !(kid->op_flags & OPf_STACKED)
13908         /* Cannot steal the second time! */
13909         && !(kid->op_private & OPpTARGET_MY)
13910         )
13911     {
13912         OP * const kkid = OpSIBLING(kid);
13913
13914         /* Can just relocate the target. */
13915         if (kkid && kkid->op_type == OP_PADSV
13916             && (!(kkid->op_private & OPpLVAL_INTRO)
13917                || kkid->op_private & OPpPAD_STATE))
13918         {
13919             kid->op_targ = kkid->op_targ;
13920             kkid->op_targ = 0;
13921             /* Now we do not need PADSV and SASSIGN.
13922              * Detach kid and free the rest. */
13923             op_sibling_splice(o, NULL, 1, NULL);
13924             op_free(o);
13925             kid->op_private |= OPpTARGET_MY;    /* Used for context settings */
13926             return kid;
13927         }
13928     }
13929     return o;
13930 }
13931
13932 OP *
13933 Perl_ck_sassign(pTHX_ OP *o)
13934 {
13935     OP * const kid = cBINOPo->op_first;
13936
13937     PERL_ARGS_ASSERT_CK_SASSIGN;
13938
13939     if (OpHAS_SIBLING(kid)) {
13940         OP *kkid = OpSIBLING(kid);
13941         /* For state variable assignment with attributes, kkid is a list op
13942            whose op_last is a padsv. */
13943         if ((kkid->op_type == OP_PADSV ||
13944              (OP_TYPE_IS_OR_WAS(kkid, OP_LIST) &&
13945               (kkid = cLISTOPx(kkid)->op_last)->op_type == OP_PADSV
13946              )
13947             )
13948                 && (kkid->op_private & (OPpLVAL_INTRO|OPpPAD_STATE))
13949                     == (OPpLVAL_INTRO|OPpPAD_STATE)) {
13950             return S_newONCEOP(aTHX_ o, kkid);
13951         }
13952     }
13953     return S_maybe_targlex(aTHX_ o);
13954 }
13955
13956
13957 OP *
13958 Perl_ck_match(pTHX_ OP *o)
13959 {
13960     PERL_UNUSED_CONTEXT;
13961     PERL_ARGS_ASSERT_CK_MATCH;
13962
13963     return o;
13964 }
13965
13966 OP *
13967 Perl_ck_method(pTHX_ OP *o)
13968 {
13969     SV *sv, *methsv, *rclass;
13970     const char* method;
13971     char* compatptr;
13972     int utf8;
13973     STRLEN len, nsplit = 0, i;
13974     OP* new_op;
13975     OP * const kid = cUNOPo->op_first;
13976
13977     PERL_ARGS_ASSERT_CK_METHOD;
13978     if (kid->op_type != OP_CONST) return o;
13979
13980     sv = kSVOP->op_sv;
13981
13982     /* replace ' with :: */
13983     while ((compatptr = (char *) memchr(SvPVX(sv), '\'',
13984                                         SvEND(sv) - SvPVX(sv) )))
13985     {
13986         *compatptr = ':';
13987         sv_insert(sv, compatptr - SvPVX_const(sv), 0, ":", 1);
13988     }
13989
13990     method = SvPVX_const(sv);
13991     len = SvCUR(sv);
13992     utf8 = SvUTF8(sv) ? -1 : 1;
13993
13994     for (i = len - 1; i > 0; --i) if (method[i] == ':') {
13995         nsplit = i+1;
13996         break;
13997     }
13998
13999     methsv = newSVpvn_share(method+nsplit, utf8*(len - nsplit), 0);
14000
14001     if (!nsplit) { /* $proto->method() */
14002         op_free(o);
14003         return newMETHOP_named(OP_METHOD_NAMED, 0, methsv);
14004     }
14005
14006     if (memEQs(method, nsplit, "SUPER::")) { /* $proto->SUPER::method() */
14007         op_free(o);
14008         return newMETHOP_named(OP_METHOD_SUPER, 0, methsv);
14009     }
14010
14011     /* $proto->MyClass::method() and $proto->MyClass::SUPER::method() */
14012     if (nsplit >= 9 && strBEGINs(method+nsplit-9, "::SUPER::")) {
14013         rclass = newSVpvn_share(method, utf8*(nsplit-9), 0);
14014         new_op = newMETHOP_named(OP_METHOD_REDIR_SUPER, 0, methsv);
14015     } else {
14016         rclass = newSVpvn_share(method, utf8*(nsplit-2), 0);
14017         new_op = newMETHOP_named(OP_METHOD_REDIR, 0, methsv);
14018     }
14019 #ifdef USE_ITHREADS
14020     op_relocate_sv(&rclass, &cMETHOPx(new_op)->op_rclass_targ);
14021 #else
14022     cMETHOPx(new_op)->op_rclass_sv = rclass;
14023 #endif
14024     op_free(o);
14025     return new_op;
14026 }
14027
14028 OP *
14029 Perl_ck_null(pTHX_ OP *o)
14030 {
14031     PERL_ARGS_ASSERT_CK_NULL;
14032     PERL_UNUSED_CONTEXT;
14033     return o;
14034 }
14035
14036 OP *
14037 Perl_ck_open(pTHX_ OP *o)
14038 {
14039     PERL_ARGS_ASSERT_CK_OPEN;
14040
14041     S_io_hints(aTHX_ o);
14042     {
14043          /* In case of three-arg dup open remove strictness
14044           * from the last arg if it is a bareword. */
14045          OP * const first = cLISTOPx(o)->op_first; /* The pushmark. */
14046          OP * const last  = cLISTOPx(o)->op_last;  /* The bareword. */
14047          OP *oa;
14048          const char *mode;
14049
14050          if ((last->op_type == OP_CONST) &&             /* The bareword. */
14051              (last->op_private & OPpCONST_BARE) &&
14052              (last->op_private & OPpCONST_STRICT) &&
14053              (oa = OpSIBLING(first)) &&         /* The fh. */
14054              (oa = OpSIBLING(oa)) &&                    /* The mode. */
14055              (oa->op_type == OP_CONST) &&
14056              SvPOK(((SVOP*)oa)->op_sv) &&
14057              (mode = SvPVX_const(((SVOP*)oa)->op_sv)) &&
14058              mode[0] == '>' && mode[1] == '&' &&        /* A dup open. */
14059              (last == OpSIBLING(oa)))                   /* The bareword. */
14060               last->op_private &= ~OPpCONST_STRICT;
14061     }
14062     return ck_fun(o);
14063 }
14064
14065 OP *
14066 Perl_ck_prototype(pTHX_ OP *o)
14067 {
14068     PERL_ARGS_ASSERT_CK_PROTOTYPE;
14069     if (!(o->op_flags & OPf_KIDS)) {
14070         op_free(o);
14071         return newUNOP(OP_PROTOTYPE, 0, newDEFSVOP());
14072     }
14073     return o;
14074 }
14075
14076 OP *
14077 Perl_ck_refassign(pTHX_ OP *o)
14078 {
14079     OP * const right = cLISTOPo->op_first;
14080     OP * const left = OpSIBLING(right);
14081     OP *varop = cUNOPx(cUNOPx(left)->op_first)->op_first;
14082     bool stacked = 0;
14083
14084     PERL_ARGS_ASSERT_CK_REFASSIGN;
14085     assert (left);
14086     assert (left->op_type == OP_SREFGEN);
14087
14088     o->op_private = 0;
14089     /* we use OPpPAD_STATE in refassign to mean either of those things,
14090      * and the code assumes the two flags occupy the same bit position
14091      * in the various ops below */
14092     assert(OPpPAD_STATE == OPpOUR_INTRO);
14093
14094     switch (varop->op_type) {
14095     case OP_PADAV:
14096         o->op_private |= OPpLVREF_AV;
14097         goto settarg;
14098     case OP_PADHV:
14099         o->op_private |= OPpLVREF_HV;
14100         /* FALLTHROUGH */
14101     case OP_PADSV:
14102       settarg:
14103         o->op_private |= (varop->op_private & (OPpLVAL_INTRO|OPpPAD_STATE));
14104         o->op_targ = varop->op_targ;
14105         varop->op_targ = 0;
14106         PAD_COMPNAME_GEN_set(o->op_targ, PERL_INT_MAX);
14107         break;
14108
14109     case OP_RV2AV:
14110         o->op_private |= OPpLVREF_AV;
14111         goto checkgv;
14112         NOT_REACHED; /* NOTREACHED */
14113     case OP_RV2HV:
14114         o->op_private |= OPpLVREF_HV;
14115         /* FALLTHROUGH */
14116     case OP_RV2SV:
14117       checkgv:
14118         o->op_private |= (varop->op_private & (OPpLVAL_INTRO|OPpOUR_INTRO));
14119         if (cUNOPx(varop)->op_first->op_type != OP_GV) goto bad;
14120       detach_and_stack:
14121         /* Point varop to its GV kid, detached.  */
14122         varop = op_sibling_splice(varop, NULL, -1, NULL);
14123         stacked = TRUE;
14124         break;
14125     case OP_RV2CV: {
14126         OP * const kidparent =
14127             OpSIBLING(cUNOPx(cUNOPx(varop)->op_first)->op_first);
14128         OP * const kid = cUNOPx(kidparent)->op_first;
14129         o->op_private |= OPpLVREF_CV;
14130         if (kid->op_type == OP_GV) {
14131             SV *sv = (SV*)cGVOPx_gv(kid);
14132             varop = kidparent;
14133             if (SvROK(sv) && SvTYPE(SvRV(sv)) == SVt_PVCV) {
14134                 /* a CVREF here confuses pp_refassign, so make sure
14135                    it gets a GV */
14136                 CV *const cv = (CV*)SvRV(sv);
14137                 SV *name_sv = sv_2mortal(newSVhek(CvNAME_HEK(cv)));
14138                 (void)gv_init_sv((GV*)sv, CvSTASH(cv), name_sv, 0);
14139                 assert(SvTYPE(sv) == SVt_PVGV);
14140             }
14141             goto detach_and_stack;
14142         }
14143         if (kid->op_type != OP_PADCV)   goto bad;
14144         o->op_targ = kid->op_targ;
14145         kid->op_targ = 0;
14146         break;
14147     }
14148     case OP_AELEM:
14149     case OP_HELEM:
14150         o->op_private |= (varop->op_private & OPpLVAL_INTRO);
14151         o->op_private |= OPpLVREF_ELEM;
14152         op_null(varop);
14153         stacked = TRUE;
14154         /* Detach varop.  */
14155         op_sibling_splice(cUNOPx(left)->op_first, NULL, -1, NULL);
14156         break;
14157     default:
14158       bad:
14159         /* diag_listed_as: Can't modify reference to %s in %s assignment */
14160         yyerror(Perl_form(aTHX_ "Can't modify reference to %s in scalar "
14161                                 "assignment",
14162                                  OP_DESC(varop)));
14163         return o;
14164     }
14165     if (!FEATURE_REFALIASING_IS_ENABLED)
14166         Perl_croak(aTHX_
14167                   "Experimental aliasing via reference not enabled");
14168     Perl_ck_warner_d(aTHX_
14169                      packWARN(WARN_EXPERIMENTAL__REFALIASING),
14170                     "Aliasing via reference is experimental");
14171     if (stacked) {
14172         o->op_flags |= OPf_STACKED;
14173         op_sibling_splice(o, right, 1, varop);
14174     }
14175     else {
14176         o->op_flags &=~ OPf_STACKED;
14177         op_sibling_splice(o, right, 1, NULL);
14178     }
14179     op_free(left);
14180     return o;
14181 }
14182
14183 OP *
14184 Perl_ck_repeat(pTHX_ OP *o)
14185 {
14186     PERL_ARGS_ASSERT_CK_REPEAT;
14187
14188     if (cBINOPo->op_first->op_flags & OPf_PARENS) {
14189         OP* kids;
14190         o->op_private |= OPpREPEAT_DOLIST;
14191         kids = op_sibling_splice(o, NULL, 1, NULL); /* detach first kid */
14192         kids = force_list(kids, TRUE); /* promote it to a list */
14193         op_sibling_splice(o, NULL, 0, kids); /* and add back */
14194     }
14195     else
14196         scalar(o);
14197     return o;
14198 }
14199
14200 OP *
14201 Perl_ck_require(pTHX_ OP *o)
14202 {
14203     GV* gv;
14204
14205     PERL_ARGS_ASSERT_CK_REQUIRE;
14206
14207     if (o->op_flags & OPf_KIDS) {       /* Shall we supply missing .pm? */
14208         SVOP * const kid = (SVOP*)cUNOPo->op_first;
14209         U32 hash;
14210         char *s;
14211         STRLEN len;
14212         if (kid->op_type == OP_CONST) {
14213           SV * const sv = kid->op_sv;
14214           U32 const was_readonly = SvREADONLY(sv);
14215           if (kid->op_private & OPpCONST_BARE) {
14216             const char *end;
14217             HEK *hek;
14218
14219             if (was_readonly) {
14220                 SvREADONLY_off(sv);
14221             }
14222
14223             if (SvIsCOW(sv)) sv_force_normal_flags(sv, 0);
14224
14225             s = SvPVX(sv);
14226             len = SvCUR(sv);
14227             end = s + len;
14228             /* treat ::foo::bar as foo::bar */
14229             if (len >= 2 && s[0] == ':' && s[1] == ':')
14230                 DIE(aTHX_ "Bareword in require must not start with a double-colon: \"%s\"\n", s);
14231             if (s == end)
14232                 DIE(aTHX_ "Bareword in require maps to empty filename");
14233
14234             for (; s < end; s++) {
14235                 if (*s == ':' && s[1] == ':') {
14236                     *s = '/';
14237                     Move(s+2, s+1, end - s - 1, char);
14238                     --end;
14239                 }
14240             }
14241             SvEND_set(sv, end);
14242             sv_catpvs(sv, ".pm");
14243             PERL_HASH(hash, SvPVX(sv), SvCUR(sv));
14244             hek = share_hek(SvPVX(sv),
14245                             (SSize_t)SvCUR(sv) * (SvUTF8(sv) ? -1 : 1),
14246                             hash);
14247             sv_sethek(sv, hek);
14248             unshare_hek(hek);
14249             SvFLAGS(sv) |= was_readonly;
14250           }
14251           else if (SvPOK(sv) && !SvNIOK(sv) && !SvGMAGICAL(sv)
14252                 && !SvVOK(sv)) {
14253             s = SvPV(sv, len);
14254             if (SvREFCNT(sv) > 1) {
14255                 kid->op_sv = newSVpvn_share(
14256                     s, SvUTF8(sv) ? -(SSize_t)len : (SSize_t)len, 0);
14257                 SvREFCNT_dec_NN(sv);
14258             }
14259             else {
14260                 HEK *hek;
14261                 if (was_readonly) SvREADONLY_off(sv);
14262                 PERL_HASH(hash, s, len);
14263                 hek = share_hek(s,
14264                                 SvUTF8(sv) ? -(SSize_t)len : (SSize_t)len,
14265                                 hash);
14266                 sv_sethek(sv, hek);
14267                 unshare_hek(hek);
14268                 SvFLAGS(sv) |= was_readonly;
14269             }
14270           }
14271         }
14272     }
14273
14274     if (!(o->op_flags & OPf_SPECIAL) /* Wasn't written as CORE::require */
14275         /* handle override, if any */
14276      && (gv = gv_override("require", 7))) {
14277         OP *kid, *newop;
14278         if (o->op_flags & OPf_KIDS) {
14279             kid = cUNOPo->op_first;
14280             op_sibling_splice(o, NULL, -1, NULL);
14281         }
14282         else {
14283             kid = newDEFSVOP();
14284         }
14285         op_free(o);
14286         newop = S_new_entersubop(aTHX_ gv, kid);
14287         return newop;
14288     }
14289
14290     return ck_fun(o);
14291 }
14292
14293 OP *
14294 Perl_ck_return(pTHX_ OP *o)
14295 {
14296     OP *kid;
14297
14298     PERL_ARGS_ASSERT_CK_RETURN;
14299
14300     kid = OpSIBLING(cLISTOPo->op_first);
14301     if (PL_compcv && CvLVALUE(PL_compcv)) {
14302         for (; kid; kid = OpSIBLING(kid))
14303             op_lvalue(kid, OP_LEAVESUBLV);
14304     }
14305
14306     return o;
14307 }
14308
14309 OP *
14310 Perl_ck_select(pTHX_ OP *o)
14311 {
14312     OP* kid;
14313
14314     PERL_ARGS_ASSERT_CK_SELECT;
14315
14316     if (o->op_flags & OPf_KIDS) {
14317         kid = OpSIBLING(cLISTOPo->op_first);     /* get past pushmark */
14318         if (kid && OpHAS_SIBLING(kid)) {
14319             OpTYPE_set(o, OP_SSELECT);
14320             o = ck_fun(o);
14321             return fold_constants(op_integerize(op_std_init(o)));
14322         }
14323     }
14324     o = ck_fun(o);
14325     kid = OpSIBLING(cLISTOPo->op_first);    /* get past pushmark */
14326     if (kid && kid->op_type == OP_RV2GV)
14327         kid->op_private &= ~HINT_STRICT_REFS;
14328     return o;
14329 }
14330
14331 OP *
14332 Perl_ck_shift(pTHX_ OP *o)
14333 {
14334     const I32 type = o->op_type;
14335
14336     PERL_ARGS_ASSERT_CK_SHIFT;
14337
14338     if (!(o->op_flags & OPf_KIDS)) {
14339         OP *argop;
14340
14341         if (!CvUNIQUE(PL_compcv)) {
14342             o->op_flags |= OPf_SPECIAL;
14343             return o;
14344         }
14345
14346         argop = newUNOP(OP_RV2AV, 0, scalar(newGVOP(OP_GV, 0, PL_argvgv)));
14347         op_free(o);
14348         return newUNOP(type, 0, scalar(argop));
14349     }
14350     return scalar(ck_fun(o));
14351 }
14352
14353 OP *
14354 Perl_ck_sort(pTHX_ OP *o)
14355 {
14356     OP *firstkid;
14357     OP *kid;
14358     U8 stacked;
14359
14360     PERL_ARGS_ASSERT_CK_SORT;
14361
14362     if (o->op_flags & OPf_STACKED)
14363         simplify_sort(o);
14364     firstkid = OpSIBLING(cLISTOPo->op_first);           /* get past pushmark */
14365
14366     if (!firstkid)
14367         return too_few_arguments_pv(o,OP_DESC(o), 0);
14368
14369     if ((stacked = o->op_flags & OPf_STACKED)) {        /* may have been cleared */
14370         OP *kid = cUNOPx(firstkid)->op_first;           /* get past null */
14371
14372         /* if the first arg is a code block, process it and mark sort as
14373          * OPf_SPECIAL */
14374         if (kid->op_type == OP_SCOPE || kid->op_type == OP_LEAVE) {
14375             LINKLIST(kid);
14376             if (kid->op_type == OP_LEAVE)
14377                     op_null(kid);                       /* wipe out leave */
14378             /* Prevent execution from escaping out of the sort block. */
14379             kid->op_next = 0;
14380
14381             /* provide scalar context for comparison function/block */
14382             kid = scalar(firstkid);
14383             kid->op_next = kid;
14384             o->op_flags |= OPf_SPECIAL;
14385         }
14386         else if (kid->op_type == OP_CONST
14387               && kid->op_private & OPpCONST_BARE) {
14388             char tmpbuf[256];
14389             STRLEN len;
14390             PADOFFSET off;
14391             const char * const name = SvPV(kSVOP_sv, len);
14392             *tmpbuf = '&';
14393             assert (len < 256);
14394             Copy(name, tmpbuf+1, len, char);
14395             off = pad_findmy_pvn(tmpbuf, len+1, 0);
14396             if (off != NOT_IN_PAD) {
14397                 if (PAD_COMPNAME_FLAGS_isOUR(off)) {
14398                     SV * const fq =
14399                         newSVhek(HvNAME_HEK(PAD_COMPNAME_OURSTASH(off)));
14400                     sv_catpvs(fq, "::");
14401                     sv_catsv(fq, kSVOP_sv);
14402                     SvREFCNT_dec_NN(kSVOP_sv);
14403                     kSVOP->op_sv = fq;
14404                 }
14405                 else {
14406                     OP * const padop = newOP(OP_PADCV, 0);
14407                     padop->op_targ = off;
14408                     /* replace the const op with the pad op */
14409                     op_sibling_splice(firstkid, NULL, 1, padop);
14410                     op_free(kid);
14411                 }
14412             }
14413         }
14414
14415         firstkid = OpSIBLING(firstkid);
14416     }
14417
14418     for (kid = firstkid; kid; kid = OpSIBLING(kid)) {
14419         /* provide list context for arguments */
14420         list(kid);
14421         if (stacked)
14422             op_lvalue(kid, OP_GREPSTART);
14423     }
14424
14425     return o;
14426 }
14427
14428 /* for sort { X } ..., where X is one of
14429  *   $a <=> $b, $b <=> $a, $a cmp $b, $b cmp $a
14430  * elide the second child of the sort (the one containing X),
14431  * and set these flags as appropriate
14432         OPpSORT_NUMERIC;
14433         OPpSORT_INTEGER;
14434         OPpSORT_DESCEND;
14435  * Also, check and warn on lexical $a, $b.
14436  */
14437
14438 STATIC void
14439 S_simplify_sort(pTHX_ OP *o)
14440 {
14441     OP *kid = OpSIBLING(cLISTOPo->op_first);    /* get past pushmark */
14442     OP *k;
14443     int descending;
14444     GV *gv;
14445     const char *gvname;
14446     bool have_scopeop;
14447
14448     PERL_ARGS_ASSERT_SIMPLIFY_SORT;
14449
14450     kid = kUNOP->op_first;                              /* get past null */
14451     if (!(have_scopeop = kid->op_type == OP_SCOPE)
14452      && kid->op_type != OP_LEAVE)
14453         return;
14454     kid = kLISTOP->op_last;                             /* get past scope */
14455     switch(kid->op_type) {
14456         case OP_NCMP:
14457         case OP_I_NCMP:
14458         case OP_SCMP:
14459             if (!have_scopeop) goto padkids;
14460             break;
14461         default:
14462             return;
14463     }
14464     k = kid;                                            /* remember this node*/
14465     if (kBINOP->op_first->op_type != OP_RV2SV
14466      || kBINOP->op_last ->op_type != OP_RV2SV)
14467     {
14468         /*
14469            Warn about my($a) or my($b) in a sort block, *if* $a or $b is
14470            then used in a comparison.  This catches most, but not
14471            all cases.  For instance, it catches
14472                sort { my($a); $a <=> $b }
14473            but not
14474                sort { my($a); $a < $b ? -1 : $a == $b ? 0 : 1; }
14475            (although why you'd do that is anyone's guess).
14476         */
14477
14478        padkids:
14479         if (!ckWARN(WARN_SYNTAX)) return;
14480         kid = kBINOP->op_first;
14481         do {
14482             if (kid->op_type == OP_PADSV) {
14483                 PADNAME * const name = PAD_COMPNAME(kid->op_targ);
14484                 if (PadnameLEN(name) == 2 && *PadnamePV(name) == '$'
14485                  && (  PadnamePV(name)[1] == 'a'
14486                     || PadnamePV(name)[1] == 'b'  ))
14487                     /* diag_listed_as: "my %s" used in sort comparison */
14488                     Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
14489                                      "\"%s %s\" used in sort comparison",
14490                                       PadnameIsSTATE(name)
14491                                         ? "state"
14492                                         : "my",
14493                                       PadnamePV(name));
14494             }
14495         } while ((kid = OpSIBLING(kid)));
14496         return;
14497     }
14498     kid = kBINOP->op_first;                             /* get past cmp */
14499     if (kUNOP->op_first->op_type != OP_GV)
14500         return;
14501     kid = kUNOP->op_first;                              /* get past rv2sv */
14502     gv = kGVOP_gv;
14503     if (GvSTASH(gv) != PL_curstash)
14504         return;
14505     gvname = GvNAME(gv);
14506     if (*gvname == 'a' && gvname[1] == '\0')
14507         descending = 0;
14508     else if (*gvname == 'b' && gvname[1] == '\0')
14509         descending = 1;
14510     else
14511         return;
14512
14513     kid = k;                                            /* back to cmp */
14514     /* already checked above that it is rv2sv */
14515     kid = kBINOP->op_last;                              /* down to 2nd arg */
14516     if (kUNOP->op_first->op_type != OP_GV)
14517         return;
14518     kid = kUNOP->op_first;                              /* get past rv2sv */
14519     gv = kGVOP_gv;
14520     if (GvSTASH(gv) != PL_curstash)
14521         return;
14522     gvname = GvNAME(gv);
14523     if ( descending
14524          ? !(*gvname == 'a' && gvname[1] == '\0')
14525          : !(*gvname == 'b' && gvname[1] == '\0'))
14526         return;
14527     o->op_flags &= ~(OPf_STACKED | OPf_SPECIAL);
14528     if (descending)
14529         o->op_private |= OPpSORT_DESCEND;
14530     if (k->op_type == OP_NCMP)
14531         o->op_private |= OPpSORT_NUMERIC;
14532     if (k->op_type == OP_I_NCMP)
14533         o->op_private |= OPpSORT_NUMERIC | OPpSORT_INTEGER;
14534     kid = OpSIBLING(cLISTOPo->op_first);
14535     /* cut out and delete old block (second sibling) */
14536     op_sibling_splice(o, cLISTOPo->op_first, 1, NULL);
14537     op_free(kid);
14538 }
14539
14540 OP *
14541 Perl_ck_split(pTHX_ OP *o)
14542 {
14543     OP *kid;
14544     OP *sibs;
14545
14546     PERL_ARGS_ASSERT_CK_SPLIT;
14547
14548     assert(o->op_type == OP_LIST);
14549
14550     if (o->op_flags & OPf_STACKED)
14551         return no_fh_allowed(o);
14552
14553     kid = cLISTOPo->op_first;
14554     /* delete leading NULL node, then add a CONST if no other nodes */
14555     assert(kid->op_type == OP_NULL);
14556     op_sibling_splice(o, NULL, 1,
14557         OpHAS_SIBLING(kid) ? NULL : newSVOP(OP_CONST, 0, newSVpvs(" ")));
14558     op_free(kid);
14559     kid = cLISTOPo->op_first;
14560
14561     if (kid->op_type != OP_MATCH || kid->op_flags & OPf_STACKED) {
14562         /* remove match expression, and replace with new optree with
14563          * a match op at its head */
14564         op_sibling_splice(o, NULL, 1, NULL);
14565         /* pmruntime will handle split " " behavior with flag==2 */
14566         kid = pmruntime(newPMOP(OP_MATCH, 0), kid, NULL, 2, 0);
14567         op_sibling_splice(o, NULL, 0, kid);
14568     }
14569
14570     assert(kid->op_type == OP_MATCH || kid->op_type == OP_SPLIT);
14571
14572     if (((PMOP *)kid)->op_pmflags & PMf_GLOBAL) {
14573       Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP),
14574                      "Use of /g modifier is meaningless in split");
14575     }
14576
14577     /* eliminate the split op, and move the match op (plus any children)
14578      * into its place, then convert the match op into a split op. i.e.
14579      *
14580      *  SPLIT                    MATCH                 SPLIT(ex-MATCH)
14581      *    |                        |                     |
14582      *  MATCH - A - B - C   =>     R - A - B - C   =>    R - A - B - C
14583      *    |                        |                     |
14584      *    R                        X - Y                 X - Y
14585      *    |
14586      *    X - Y
14587      *
14588      * (R, if it exists, will be a regcomp op)
14589      */
14590
14591     op_sibling_splice(o, NULL, 1, NULL); /* detach match op from o */
14592     sibs = op_sibling_splice(o, NULL, -1, NULL); /* detach any other sibs */
14593     op_sibling_splice(kid, cLISTOPx(kid)->op_last, 0, sibs); /* and reattach */
14594     OpTYPE_set(kid, OP_SPLIT);
14595     kid->op_flags   = (o->op_flags | (kid->op_flags & OPf_KIDS));
14596     kid->op_private = o->op_private;
14597     op_free(o);
14598     o = kid;
14599     kid = sibs; /* kid is now the string arg of the split */
14600
14601     if (!kid) {
14602         kid = newDEFSVOP();
14603         op_append_elem(OP_SPLIT, o, kid);
14604     }
14605     scalar(kid);
14606
14607     kid = OpSIBLING(kid);
14608     if (!kid) {
14609         kid = newSVOP(OP_CONST, 0, newSViv(0));
14610         op_append_elem(OP_SPLIT, o, kid);
14611         o->op_private |= OPpSPLIT_IMPLIM;
14612     }
14613     scalar(kid);
14614
14615     if (OpHAS_SIBLING(kid))
14616         return too_many_arguments_pv(o,OP_DESC(o), 0);
14617
14618     return o;
14619 }
14620
14621 OP *
14622 Perl_ck_stringify(pTHX_ OP *o)
14623 {
14624     OP * const kid = OpSIBLING(cUNOPo->op_first);
14625     PERL_ARGS_ASSERT_CK_STRINGIFY;
14626     if ((   kid->op_type == OP_JOIN || kid->op_type == OP_QUOTEMETA
14627          || kid->op_type == OP_LC   || kid->op_type == OP_LCFIRST
14628          || kid->op_type == OP_UC   || kid->op_type == OP_UCFIRST)
14629         && !OpHAS_SIBLING(kid)) /* syntax errs can leave extra children */
14630     {
14631         op_sibling_splice(o, cUNOPo->op_first, -1, NULL);
14632         op_free(o);
14633         return kid;
14634     }
14635     return ck_fun(o);
14636 }
14637
14638 OP *
14639 Perl_ck_join(pTHX_ OP *o)
14640 {
14641     OP * const kid = OpSIBLING(cLISTOPo->op_first);
14642
14643     PERL_ARGS_ASSERT_CK_JOIN;
14644
14645     if (kid && kid->op_type == OP_MATCH) {
14646         if (ckWARN(WARN_SYNTAX)) {
14647             const REGEXP *re = PM_GETRE(kPMOP);
14648             const SV *msg = re
14649                     ? newSVpvn_flags( RX_PRECOMP_const(re), RX_PRELEN(re),
14650                                             SVs_TEMP | ( RX_UTF8(re) ? SVf_UTF8 : 0 ) )
14651                     : newSVpvs_flags( "STRING", SVs_TEMP );
14652             Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
14653                         "/%" SVf "/ should probably be written as \"%" SVf "\"",
14654                         SVfARG(msg), SVfARG(msg));
14655         }
14656     }
14657     if (kid
14658      && (kid->op_type == OP_CONST /* an innocent, unsuspicious separator */
14659         || (kid->op_type == OP_PADSV && !(kid->op_private & OPpLVAL_INTRO))
14660         || (  kid->op_type==OP_RV2SV && kUNOP->op_first->op_type == OP_GV
14661            && !(kid->op_private & (OPpLVAL_INTRO|OPpOUR_INTRO)))))
14662     {
14663         const OP * const bairn = OpSIBLING(kid); /* the list */
14664         if (bairn && !OpHAS_SIBLING(bairn) /* single-item list */
14665          && OP_GIMME(bairn,0) == G_SCALAR)
14666         {
14667             OP * const ret = op_convert_list(OP_STRINGIFY, OPf_FOLDED,
14668                                      op_sibling_splice(o, kid, 1, NULL));
14669             op_free(o);
14670             return ret;
14671         }
14672     }
14673
14674     return ck_fun(o);
14675 }
14676
14677 /*
14678 =for apidoc rv2cv_op_cv
14679
14680 Examines an op, which is expected to identify a subroutine at runtime,
14681 and attempts to determine at compile time which subroutine it identifies.
14682 This is normally used during Perl compilation to determine whether
14683 a prototype can be applied to a function call.  C<cvop> is the op
14684 being considered, normally an C<rv2cv> op.  A pointer to the identified
14685 subroutine is returned, if it could be determined statically, and a null
14686 pointer is returned if it was not possible to determine statically.
14687
14688 Currently, the subroutine can be identified statically if the RV that the
14689 C<rv2cv> is to operate on is provided by a suitable C<gv> or C<const> op.
14690 A C<gv> op is suitable if the GV's CV slot is populated.  A C<const> op is
14691 suitable if the constant value must be an RV pointing to a CV.  Details of
14692 this process may change in future versions of Perl.  If the C<rv2cv> op
14693 has the C<OPpENTERSUB_AMPER> flag set then no attempt is made to identify
14694 the subroutine statically: this flag is used to suppress compile-time
14695 magic on a subroutine call, forcing it to use default runtime behaviour.
14696
14697 If C<flags> has the bit C<RV2CVOPCV_MARK_EARLY> set, then the handling
14698 of a GV reference is modified.  If a GV was examined and its CV slot was
14699 found to be empty, then the C<gv> op has the C<OPpEARLY_CV> flag set.
14700 If the op is not optimised away, and the CV slot is later populated with
14701 a subroutine having a prototype, that flag eventually triggers the warning
14702 "called too early to check prototype".
14703
14704 If C<flags> has the bit C<RV2CVOPCV_RETURN_NAME_GV> set, then instead
14705 of returning a pointer to the subroutine it returns a pointer to the
14706 GV giving the most appropriate name for the subroutine in this context.
14707 Normally this is just the C<CvGV> of the subroutine, but for an anonymous
14708 (C<CvANON>) subroutine that is referenced through a GV it will be the
14709 referencing GV.  The resulting C<GV*> is cast to C<CV*> to be returned.
14710 A null pointer is returned as usual if there is no statically-determinable
14711 subroutine.
14712
14713 =for apidoc Amnh||OPpEARLY_CV
14714 =for apidoc Amnh||OPpENTERSUB_AMPER
14715 =for apidoc Amnh||RV2CVOPCV_MARK_EARLY
14716 =for apidoc Amnh||RV2CVOPCV_RETURN_NAME_GV
14717
14718 =cut
14719 */
14720
14721 /* shared by toke.c:yylex */
14722 CV *
14723 Perl_find_lexical_cv(pTHX_ PADOFFSET off)
14724 {
14725     PADNAME *name = PAD_COMPNAME(off);
14726     CV *compcv = PL_compcv;
14727     while (PadnameOUTER(name)) {
14728         assert(PARENT_PAD_INDEX(name));
14729         compcv = CvOUTSIDE(compcv);
14730         name = PadlistNAMESARRAY(CvPADLIST(compcv))
14731                 [off = PARENT_PAD_INDEX(name)];
14732     }
14733     assert(!PadnameIsOUR(name));
14734     if (!PadnameIsSTATE(name) && PadnamePROTOCV(name)) {
14735         return PadnamePROTOCV(name);
14736     }
14737     return (CV *)AvARRAY(PadlistARRAY(CvPADLIST(compcv))[1])[off];
14738 }
14739
14740 CV *
14741 Perl_rv2cv_op_cv(pTHX_ OP *cvop, U32 flags)
14742 {
14743     OP *rvop;
14744     CV *cv;
14745     GV *gv;
14746     PERL_ARGS_ASSERT_RV2CV_OP_CV;
14747     if (flags & ~RV2CVOPCV_FLAG_MASK)
14748         Perl_croak(aTHX_ "panic: rv2cv_op_cv bad flags %x", (unsigned)flags);
14749     if (cvop->op_type != OP_RV2CV)
14750         return NULL;
14751     if (cvop->op_private & OPpENTERSUB_AMPER)
14752         return NULL;
14753     if (!(cvop->op_flags & OPf_KIDS))
14754         return NULL;
14755     rvop = cUNOPx(cvop)->op_first;
14756     switch (rvop->op_type) {
14757         case OP_GV: {
14758             gv = cGVOPx_gv(rvop);
14759             if (!isGV(gv)) {
14760                 if (SvROK(gv) && SvTYPE(SvRV(gv)) == SVt_PVCV) {
14761                     cv = MUTABLE_CV(SvRV(gv));
14762                     gv = NULL;
14763                     break;
14764                 }
14765                 if (flags & RV2CVOPCV_RETURN_STUB)
14766                     return (CV *)gv;
14767                 else return NULL;
14768             }
14769             cv = GvCVu(gv);
14770             if (!cv) {
14771                 if (flags & RV2CVOPCV_MARK_EARLY)
14772                     rvop->op_private |= OPpEARLY_CV;
14773                 return NULL;
14774             }
14775         } break;
14776         case OP_CONST: {
14777             SV *rv = cSVOPx_sv(rvop);
14778             if (!SvROK(rv))
14779                 return NULL;
14780             cv = (CV*)SvRV(rv);
14781             gv = NULL;
14782         } break;
14783         case OP_PADCV: {
14784             cv = find_lexical_cv(rvop->op_targ);
14785             gv = NULL;
14786         } break;
14787         default: {
14788             return NULL;
14789         } NOT_REACHED; /* NOTREACHED */
14790     }
14791     if (SvTYPE((SV*)cv) != SVt_PVCV)
14792         return NULL;
14793     if (flags & RV2CVOPCV_RETURN_NAME_GV) {
14794         if ((!CvANON(cv) && !CvLEXICAL(cv)) || !gv)
14795             gv = CvGV(cv);
14796         return (CV*)gv;
14797     }
14798     else if (flags & RV2CVOPCV_MAYBE_NAME_GV) {
14799         if (CvLEXICAL(cv) || CvNAMED(cv))
14800             return NULL;
14801         if (!CvANON(cv) || !gv)
14802             gv = CvGV(cv);
14803         return (CV*)gv;
14804
14805     } else {
14806         return cv;
14807     }
14808 }
14809
14810 /*
14811 =for apidoc ck_entersub_args_list
14812
14813 Performs the default fixup of the arguments part of an C<entersub>
14814 op tree.  This consists of applying list context to each of the
14815 argument ops.  This is the standard treatment used on a call marked
14816 with C<&>, or a method call, or a call through a subroutine reference,
14817 or any other call where the callee can't be identified at compile time,
14818 or a call where the callee has no prototype.
14819
14820 =cut
14821 */
14822
14823 OP *
14824 Perl_ck_entersub_args_list(pTHX_ OP *entersubop)
14825 {
14826     OP *aop;
14827
14828     PERL_ARGS_ASSERT_CK_ENTERSUB_ARGS_LIST;
14829
14830     aop = cUNOPx(entersubop)->op_first;
14831     if (!OpHAS_SIBLING(aop))
14832         aop = cUNOPx(aop)->op_first;
14833     for (aop = OpSIBLING(aop); OpHAS_SIBLING(aop); aop = OpSIBLING(aop)) {
14834         /* skip the extra attributes->import() call implicitly added in
14835          * something like foo(my $x : bar)
14836          */
14837         if (   aop->op_type == OP_ENTERSUB
14838             && (aop->op_flags & OPf_WANT) == OPf_WANT_VOID
14839         )
14840             continue;
14841         list(aop);
14842         op_lvalue(aop, OP_ENTERSUB);
14843     }
14844     return entersubop;
14845 }
14846
14847 /*
14848 =for apidoc ck_entersub_args_proto
14849
14850 Performs the fixup of the arguments part of an C<entersub> op tree
14851 based on a subroutine prototype.  This makes various modifications to
14852 the argument ops, from applying context up to inserting C<refgen> ops,
14853 and checking the number and syntactic types of arguments, as directed by
14854 the prototype.  This is the standard treatment used on a subroutine call,
14855 not marked with C<&>, where the callee can be identified at compile time
14856 and has a prototype.
14857
14858 C<protosv> supplies the subroutine prototype to be applied to the call.
14859 It may be a normal defined scalar, of which the string value will be used.
14860 Alternatively, for convenience, it may be a subroutine object (a C<CV*>
14861 that has been cast to C<SV*>) which has a prototype.  The prototype
14862 supplied, in whichever form, does not need to match the actual callee
14863 referenced by the op tree.
14864
14865 If the argument ops disagree with the prototype, for example by having
14866 an unacceptable number of arguments, a valid op tree is returned anyway.
14867 The error is reflected in the parser state, normally resulting in a single
14868 exception at the top level of parsing which covers all the compilation
14869 errors that occurred.  In the error message, the callee is referred to
14870 by the name defined by the C<namegv> parameter.
14871
14872 =cut
14873 */
14874
14875 OP *
14876 Perl_ck_entersub_args_proto(pTHX_ OP *entersubop, GV *namegv, SV *protosv)
14877 {
14878     STRLEN proto_len;
14879     const char *proto, *proto_end;
14880     OP *aop, *prev, *cvop, *parent;
14881     int optional = 0;
14882     I32 arg = 0;
14883     I32 contextclass = 0;
14884     const char *e = NULL;
14885     PERL_ARGS_ASSERT_CK_ENTERSUB_ARGS_PROTO;
14886     if (SvTYPE(protosv) == SVt_PVCV ? !SvPOK(protosv) : !SvOK(protosv))
14887         Perl_croak(aTHX_ "panic: ck_entersub_args_proto CV with no proto, "
14888                    "flags=%lx", (unsigned long) SvFLAGS(protosv));
14889     if (SvTYPE(protosv) == SVt_PVCV)
14890          proto = CvPROTO(protosv), proto_len = CvPROTOLEN(protosv);
14891     else proto = SvPV(protosv, proto_len);
14892     proto = S_strip_spaces(aTHX_ proto, &proto_len);
14893     proto_end = proto + proto_len;
14894     parent = entersubop;
14895     aop = cUNOPx(entersubop)->op_first;
14896     if (!OpHAS_SIBLING(aop)) {
14897         parent = aop;
14898         aop = cUNOPx(aop)->op_first;
14899     }
14900     prev = aop;
14901     aop = OpSIBLING(aop);
14902     for (cvop = aop; OpHAS_SIBLING(cvop); cvop = OpSIBLING(cvop)) ;
14903     while (aop != cvop) {
14904         OP* o3 = aop;
14905
14906         if (proto >= proto_end)
14907         {
14908             SV * const namesv = cv_name((CV *)namegv, NULL, 0);
14909             yyerror_pv(Perl_form(aTHX_ "Too many arguments for %" SVf,
14910                                         SVfARG(namesv)), SvUTF8(namesv));
14911             return entersubop;
14912         }
14913
14914         switch (*proto) {
14915             case ';':
14916                 optional = 1;
14917                 proto++;
14918                 continue;
14919             case '_':
14920                 /* _ must be at the end */
14921                 if (proto[1] && !memCHRs(";@%", proto[1]))
14922                     goto oops;
14923                 /* FALLTHROUGH */
14924             case '$':
14925                 proto++;
14926                 arg++;
14927                 scalar(aop);
14928                 break;
14929             case '%':
14930             case '@':
14931                 list(aop);
14932                 arg++;
14933                 break;
14934             case '&':
14935                 proto++;
14936                 arg++;
14937                 if (    o3->op_type != OP_UNDEF
14938                     && (o3->op_type != OP_SREFGEN
14939                         || (  cUNOPx(cUNOPx(o3)->op_first)->op_first->op_type
14940                                 != OP_ANONCODE
14941                             && cUNOPx(cUNOPx(o3)->op_first)->op_first->op_type
14942                                 != OP_RV2CV)))
14943                     bad_type_gv(arg, namegv, o3,
14944                             arg == 1 ? "block or sub {}" : "sub {}");
14945                 break;
14946             case '*':
14947                 /* '*' allows any scalar type, including bareword */
14948                 proto++;
14949                 arg++;
14950                 if (o3->op_type == OP_RV2GV)
14951                     goto wrapref;       /* autoconvert GLOB -> GLOBref */
14952                 else if (o3->op_type == OP_CONST)
14953                     o3->op_private &= ~OPpCONST_STRICT;
14954                 scalar(aop);
14955                 break;
14956             case '+':
14957                 proto++;
14958                 arg++;
14959                 if (o3->op_type == OP_RV2AV ||
14960                     o3->op_type == OP_PADAV ||
14961                     o3->op_type == OP_RV2HV ||
14962                     o3->op_type == OP_PADHV
14963                 ) {
14964                     goto wrapref;
14965                 }
14966                 scalar(aop);
14967                 break;
14968             case '[': case ']':
14969                 goto oops;
14970
14971             case '\\':
14972                 proto++;
14973                 arg++;
14974             again:
14975                 switch (*proto++) {
14976                     case '[':
14977                         if (contextclass++ == 0) {
14978                             e = (char *) memchr(proto, ']', proto_end - proto);
14979                             if (!e || e == proto)
14980                                 goto oops;
14981                         }
14982                         else
14983                             goto oops;
14984                         goto again;
14985
14986                     case ']':
14987                         if (contextclass) {
14988                             const char *p = proto;
14989                             const char *const end = proto;
14990                             contextclass = 0;
14991                             while (*--p != '[')
14992                                 /* \[$] accepts any scalar lvalue */
14993                                 if (*p == '$'
14994                                  && Perl_op_lvalue_flags(aTHX_
14995                                      scalar(o3),
14996                                      OP_READ, /* not entersub */
14997                                      OP_LVALUE_NO_CROAK
14998                                     )) goto wrapref;
14999                             bad_type_gv(arg, namegv, o3,
15000                                     Perl_form(aTHX_ "one of %.*s",(int)(end - p), p));
15001                         } else
15002                             goto oops;
15003                         break;
15004                     case '*':
15005                         if (o3->op_type == OP_RV2GV)
15006                             goto wrapref;
15007                         if (!contextclass)
15008                             bad_type_gv(arg, namegv, o3, "symbol");
15009                         break;
15010                     case '&':
15011                         if (o3->op_type == OP_ENTERSUB
15012                          && !(o3->op_flags & OPf_STACKED))
15013                             goto wrapref;
15014                         if (!contextclass)
15015                             bad_type_gv(arg, namegv, o3, "subroutine");
15016                         break;
15017                     case '$':
15018                         if (o3->op_type == OP_RV2SV ||
15019                                 o3->op_type == OP_PADSV ||
15020                                 o3->op_type == OP_HELEM ||
15021                                 o3->op_type == OP_AELEM)
15022                             goto wrapref;
15023                         if (!contextclass) {
15024                             /* \$ accepts any scalar lvalue */
15025                             if (Perl_op_lvalue_flags(aTHX_
15026                                     scalar(o3),
15027                                     OP_READ,  /* not entersub */
15028                                     OP_LVALUE_NO_CROAK
15029                                )) goto wrapref;
15030                             bad_type_gv(arg, namegv, o3, "scalar");
15031                         }
15032                         break;
15033                     case '@':
15034                         if (o3->op_type == OP_RV2AV ||
15035                                 o3->op_type == OP_PADAV)
15036                         {
15037                             o3->op_flags &=~ OPf_PARENS;
15038                             goto wrapref;
15039                         }
15040                         if (!contextclass)
15041                             bad_type_gv(arg, namegv, o3, "array");
15042                         break;
15043                     case '%':
15044                         if (o3->op_type == OP_RV2HV ||
15045                                 o3->op_type == OP_PADHV)
15046                         {
15047                             o3->op_flags &=~ OPf_PARENS;
15048                             goto wrapref;
15049                         }
15050                         if (!contextclass)
15051                             bad_type_gv(arg, namegv, o3, "hash");
15052                         break;
15053                     wrapref:
15054                             aop = S_op_sibling_newUNOP(aTHX_ parent, prev,
15055                                                 OP_REFGEN, 0);
15056                         if (contextclass && e) {
15057                             proto = e + 1;
15058                             contextclass = 0;
15059                         }
15060                         break;
15061                     default: goto oops;
15062                 }
15063                 if (contextclass)
15064                     goto again;
15065                 break;
15066             case ' ':
15067                 proto++;
15068                 continue;
15069             default:
15070             oops: {
15071                 Perl_croak(aTHX_ "Malformed prototype for %" SVf ": %" SVf,
15072                                   SVfARG(cv_name((CV *)namegv, NULL, 0)),
15073                                   SVfARG(protosv));
15074             }
15075         }
15076
15077         op_lvalue(aop, OP_ENTERSUB);
15078         prev = aop;
15079         aop = OpSIBLING(aop);
15080     }
15081     if (aop == cvop && *proto == '_') {
15082         /* generate an access to $_ */
15083         op_sibling_splice(parent, prev, 0, newDEFSVOP());
15084     }
15085     if (!optional && proto_end > proto &&
15086         (*proto != '@' && *proto != '%' && *proto != ';' && *proto != '_'))
15087     {
15088         SV * const namesv = cv_name((CV *)namegv, NULL, 0);
15089         yyerror_pv(Perl_form(aTHX_ "Not enough arguments for %" SVf,
15090                                     SVfARG(namesv)), SvUTF8(namesv));
15091     }
15092     return entersubop;
15093 }
15094
15095 /*
15096 =for apidoc ck_entersub_args_proto_or_list
15097
15098 Performs the fixup of the arguments part of an C<entersub> op tree either
15099 based on a subroutine prototype or using default list-context processing.
15100 This is the standard treatment used on a subroutine call, not marked
15101 with C<&>, where the callee can be identified at compile time.
15102
15103 C<protosv> supplies the subroutine prototype to be applied to the call,
15104 or indicates that there is no prototype.  It may be a normal scalar,
15105 in which case if it is defined then the string value will be used
15106 as a prototype, and if it is undefined then there is no prototype.
15107 Alternatively, for convenience, it may be a subroutine object (a C<CV*>
15108 that has been cast to C<SV*>), of which the prototype will be used if it
15109 has one.  The prototype (or lack thereof) supplied, in whichever form,
15110 does not need to match the actual callee referenced by the op tree.
15111
15112 If the argument ops disagree with the prototype, for example by having
15113 an unacceptable number of arguments, a valid op tree is returned anyway.
15114 The error is reflected in the parser state, normally resulting in a single
15115 exception at the top level of parsing which covers all the compilation
15116 errors that occurred.  In the error message, the callee is referred to
15117 by the name defined by the C<namegv> parameter.
15118
15119 =cut
15120 */
15121
15122 OP *
15123 Perl_ck_entersub_args_proto_or_list(pTHX_ OP *entersubop,
15124         GV *namegv, SV *protosv)
15125 {
15126     PERL_ARGS_ASSERT_CK_ENTERSUB_ARGS_PROTO_OR_LIST;
15127     if (SvTYPE(protosv) == SVt_PVCV ? SvPOK(protosv) : SvOK(protosv))
15128         return ck_entersub_args_proto(entersubop, namegv, protosv);
15129     else
15130         return ck_entersub_args_list(entersubop);
15131 }
15132
15133 OP *
15134 Perl_ck_entersub_args_core(pTHX_ OP *entersubop, GV *namegv, SV *protosv)
15135 {
15136     IV cvflags = SvIVX(protosv);
15137     int opnum = cvflags & 0xffff;
15138     OP *aop = cUNOPx(entersubop)->op_first;
15139
15140     PERL_ARGS_ASSERT_CK_ENTERSUB_ARGS_CORE;
15141
15142     if (!opnum) {
15143         OP *cvop;
15144         if (!OpHAS_SIBLING(aop))
15145             aop = cUNOPx(aop)->op_first;
15146         aop = OpSIBLING(aop);
15147         for (cvop = aop; OpSIBLING(cvop); cvop = OpSIBLING(cvop)) ;
15148         if (aop != cvop) {
15149             SV *namesv = cv_name((CV *)namegv, NULL, CV_NAME_NOTQUAL);
15150             yyerror_pv(Perl_form(aTHX_ "Too many arguments for %" SVf,
15151                 SVfARG(namesv)), SvUTF8(namesv));
15152         }
15153
15154         op_free(entersubop);
15155         switch(cvflags >> 16) {
15156         case 'F': return newSVOP(OP_CONST, 0,
15157                                         newSVpv(CopFILE(PL_curcop),0));
15158         case 'L': return newSVOP(
15159                            OP_CONST, 0,
15160                            Perl_newSVpvf(aTHX_
15161                              "%" IVdf, (IV)CopLINE(PL_curcop)
15162                            )
15163                          );
15164         case 'P': return newSVOP(OP_CONST, 0,
15165                                    (PL_curstash
15166                                      ? newSVhek(HvNAME_HEK(PL_curstash))
15167                                      : &PL_sv_undef
15168                                    )
15169                                 );
15170         }
15171         NOT_REACHED; /* NOTREACHED */
15172     }
15173     else {
15174         OP *prev, *cvop, *first, *parent;
15175         U32 flags = 0;
15176
15177         parent = entersubop;
15178         if (!OpHAS_SIBLING(aop)) {
15179             parent = aop;
15180             aop = cUNOPx(aop)->op_first;
15181         }
15182
15183         first = prev = aop;
15184         aop = OpSIBLING(aop);
15185         /* find last sibling */
15186         for (cvop = aop;
15187              OpHAS_SIBLING(cvop);
15188              prev = cvop, cvop = OpSIBLING(cvop))
15189             ;
15190         if (!(cvop->op_private & OPpENTERSUB_NOPAREN)
15191             /* Usually, OPf_SPECIAL on an op with no args means that it had
15192              * parens, but these have their own meaning for that flag: */
15193             && opnum != OP_VALUES && opnum != OP_KEYS && opnum != OP_EACH
15194             && opnum != OP_DELETE && opnum != OP_EXISTS)
15195                 flags |= OPf_SPECIAL;
15196         /* excise cvop from end of sibling chain */
15197         op_sibling_splice(parent, prev, 1, NULL);
15198         op_free(cvop);
15199         if (aop == cvop) aop = NULL;
15200
15201         /* detach remaining siblings from the first sibling, then
15202          * dispose of original optree */
15203
15204         if (aop)
15205             op_sibling_splice(parent, first, -1, NULL);
15206         op_free(entersubop);
15207
15208         if (cvflags == (OP_ENTEREVAL | (1<<16)))
15209             flags |= OPpEVAL_BYTES <<8;
15210
15211         switch (PL_opargs[opnum] & OA_CLASS_MASK) {
15212         case OA_UNOP:
15213         case OA_BASEOP_OR_UNOP:
15214         case OA_FILESTATOP:
15215             if (!aop)
15216                 return newOP(opnum,flags);       /* zero args */
15217             if (aop == prev)
15218                 return newUNOP(opnum,flags,aop); /* one arg */
15219             /* too many args */
15220             /* FALLTHROUGH */
15221         case OA_BASEOP:
15222             if (aop) {
15223                 SV *namesv;
15224                 OP *nextop;
15225
15226                 namesv = cv_name((CV *)namegv, NULL, CV_NAME_NOTQUAL);
15227                 yyerror_pv(Perl_form(aTHX_ "Too many arguments for %" SVf,
15228                     SVfARG(namesv)), SvUTF8(namesv));
15229                 while (aop) {
15230                     nextop = OpSIBLING(aop);
15231                     op_free(aop);
15232                     aop = nextop;
15233                 }
15234
15235             }
15236             return opnum == OP_RUNCV
15237                 ? newPVOP(OP_RUNCV,0,NULL)
15238                 : newOP(opnum,0);
15239         default:
15240             return op_convert_list(opnum,0,aop);
15241         }
15242     }
15243     NOT_REACHED; /* NOTREACHED */
15244     return entersubop;
15245 }
15246
15247 /*
15248 =for apidoc cv_get_call_checker_flags
15249
15250 Retrieves the function that will be used to fix up a call to C<cv>.
15251 Specifically, the function is applied to an C<entersub> op tree for a
15252 subroutine call, not marked with C<&>, where the callee can be identified
15253 at compile time as C<cv>.
15254
15255 The C-level function pointer is returned in C<*ckfun_p>, an SV argument
15256 for it is returned in C<*ckobj_p>, and control flags are returned in
15257 C<*ckflags_p>.  The function is intended to be called in this manner:
15258
15259  entersubop = (*ckfun_p)(aTHX_ entersubop, namegv, (*ckobj_p));
15260
15261 In this call, C<entersubop> is a pointer to the C<entersub> op,
15262 which may be replaced by the check function, and C<namegv> supplies
15263 the name that should be used by the check function to refer
15264 to the callee of the C<entersub> op if it needs to emit any diagnostics.
15265 It is permitted to apply the check function in non-standard situations,
15266 such as to a call to a different subroutine or to a method call.
15267
15268 C<namegv> may not actually be a GV.  If the C<CALL_CHECKER_REQUIRE_GV>
15269 bit is clear in C<*ckflags_p>, it is permitted to pass a CV or other SV
15270 instead, anything that can be used as the first argument to L</cv_name>.
15271 If the C<CALL_CHECKER_REQUIRE_GV> bit is set in C<*ckflags_p> then the
15272 check function requires C<namegv> to be a genuine GV.
15273
15274 By default, the check function is
15275 L<Perl_ck_entersub_args_proto_or_list|/ck_entersub_args_proto_or_list>,
15276 the SV parameter is C<cv> itself, and the C<CALL_CHECKER_REQUIRE_GV>
15277 flag is clear.  This implements standard prototype processing.  It can
15278 be changed, for a particular subroutine, by L</cv_set_call_checker_flags>.
15279
15280 If the C<CALL_CHECKER_REQUIRE_GV> bit is set in C<gflags> then it
15281 indicates that the caller only knows about the genuine GV version of
15282 C<namegv>, and accordingly the corresponding bit will always be set in
15283 C<*ckflags_p>, regardless of the check function's recorded requirements.
15284 If the C<CALL_CHECKER_REQUIRE_GV> bit is clear in C<gflags> then it
15285 indicates the caller knows about the possibility of passing something
15286 other than a GV as C<namegv>, and accordingly the corresponding bit may
15287 be either set or clear in C<*ckflags_p>, indicating the check function's
15288 recorded requirements.
15289
15290 C<gflags> is a bitset passed into C<cv_get_call_checker_flags>, in which
15291 only the C<CALL_CHECKER_REQUIRE_GV> bit currently has a defined meaning
15292 (for which see above).  All other bits should be clear.
15293
15294 =for apidoc Amnh||CALL_CHECKER_REQUIRE_GV
15295
15296 =for apidoc cv_get_call_checker
15297
15298 The original form of L</cv_get_call_checker_flags>, which does not return
15299 checker flags.  When using a checker function returned by this function,
15300 it is only safe to call it with a genuine GV as its C<namegv> argument.
15301
15302 =cut
15303 */
15304
15305 void
15306 Perl_cv_get_call_checker_flags(pTHX_ CV *cv, U32 gflags,
15307         Perl_call_checker *ckfun_p, SV **ckobj_p, U32 *ckflags_p)
15308 {
15309     MAGIC *callmg;
15310     PERL_ARGS_ASSERT_CV_GET_CALL_CHECKER_FLAGS;
15311     PERL_UNUSED_CONTEXT;
15312     callmg = SvMAGICAL((SV*)cv) ? mg_find((SV*)cv, PERL_MAGIC_checkcall) : NULL;
15313     if (callmg) {
15314         *ckfun_p = DPTR2FPTR(Perl_call_checker, callmg->mg_ptr);
15315         *ckobj_p = callmg->mg_obj;
15316         *ckflags_p = (callmg->mg_flags | gflags) & MGf_REQUIRE_GV;
15317     } else {
15318         *ckfun_p = Perl_ck_entersub_args_proto_or_list;
15319         *ckobj_p = (SV*)cv;
15320         *ckflags_p = gflags & MGf_REQUIRE_GV;
15321     }
15322 }
15323
15324 void
15325 Perl_cv_get_call_checker(pTHX_ CV *cv, Perl_call_checker *ckfun_p, SV **ckobj_p)
15326 {
15327     U32 ckflags;
15328     PERL_ARGS_ASSERT_CV_GET_CALL_CHECKER;
15329     PERL_UNUSED_CONTEXT;
15330     cv_get_call_checker_flags(cv, CALL_CHECKER_REQUIRE_GV, ckfun_p, ckobj_p,
15331         &ckflags);
15332 }
15333
15334 /*
15335 =for apidoc cv_set_call_checker_flags
15336
15337 Sets the function that will be used to fix up a call to C<cv>.
15338 Specifically, the function is applied to an C<entersub> op tree for a
15339 subroutine call, not marked with C<&>, where the callee can be identified
15340 at compile time as C<cv>.
15341
15342 The C-level function pointer is supplied in C<ckfun>, an SV argument for
15343 it is supplied in C<ckobj>, and control flags are supplied in C<ckflags>.
15344 The function should be defined like this:
15345
15346     STATIC OP * ckfun(pTHX_ OP *op, GV *namegv, SV *ckobj)
15347
15348 It is intended to be called in this manner:
15349
15350     entersubop = ckfun(aTHX_ entersubop, namegv, ckobj);
15351
15352 In this call, C<entersubop> is a pointer to the C<entersub> op,
15353 which may be replaced by the check function, and C<namegv> supplies
15354 the name that should be used by the check function to refer
15355 to the callee of the C<entersub> op if it needs to emit any diagnostics.
15356 It is permitted to apply the check function in non-standard situations,
15357 such as to a call to a different subroutine or to a method call.
15358
15359 C<namegv> may not actually be a GV.  For efficiency, perl may pass a
15360 CV or other SV instead.  Whatever is passed can be used as the first
15361 argument to L</cv_name>.  You can force perl to pass a GV by including
15362 C<CALL_CHECKER_REQUIRE_GV> in the C<ckflags>.
15363
15364 C<ckflags> is a bitset, in which only the C<CALL_CHECKER_REQUIRE_GV>
15365 bit currently has a defined meaning (for which see above).  All other
15366 bits should be clear.
15367
15368 The current setting for a particular CV can be retrieved by
15369 L</cv_get_call_checker_flags>.
15370
15371 =for apidoc cv_set_call_checker
15372
15373 The original form of L</cv_set_call_checker_flags>, which passes it the
15374 C<CALL_CHECKER_REQUIRE_GV> flag for backward-compatibility.  The effect
15375 of that flag setting is that the check function is guaranteed to get a
15376 genuine GV as its C<namegv> argument.
15377
15378 =cut
15379 */
15380
15381 void
15382 Perl_cv_set_call_checker(pTHX_ CV *cv, Perl_call_checker ckfun, SV *ckobj)
15383 {
15384     PERL_ARGS_ASSERT_CV_SET_CALL_CHECKER;
15385     cv_set_call_checker_flags(cv, ckfun, ckobj, CALL_CHECKER_REQUIRE_GV);
15386 }
15387
15388 void
15389 Perl_cv_set_call_checker_flags(pTHX_ CV *cv, Perl_call_checker ckfun,
15390                                      SV *ckobj, U32 ckflags)
15391 {
15392     PERL_ARGS_ASSERT_CV_SET_CALL_CHECKER_FLAGS;
15393     if (ckfun == Perl_ck_entersub_args_proto_or_list && ckobj == (SV*)cv) {
15394         if (SvMAGICAL((SV*)cv))
15395             mg_free_type((SV*)cv, PERL_MAGIC_checkcall);
15396     } else {
15397         MAGIC *callmg;
15398         sv_magic((SV*)cv, &PL_sv_undef, PERL_MAGIC_checkcall, NULL, 0);
15399         callmg = mg_find((SV*)cv, PERL_MAGIC_checkcall);
15400         assert(callmg);
15401         if (callmg->mg_flags & MGf_REFCOUNTED) {
15402             SvREFCNT_dec(callmg->mg_obj);
15403             callmg->mg_flags &= ~MGf_REFCOUNTED;
15404         }
15405         callmg->mg_ptr = FPTR2DPTR(char *, ckfun);
15406         callmg->mg_obj = ckobj;
15407         if (ckobj != (SV*)cv) {
15408             SvREFCNT_inc_simple_void_NN(ckobj);
15409             callmg->mg_flags |= MGf_REFCOUNTED;
15410         }
15411         callmg->mg_flags = (callmg->mg_flags &~ MGf_REQUIRE_GV)
15412                          | (U8)(ckflags & MGf_REQUIRE_GV) | MGf_COPY;
15413     }
15414 }
15415
15416 static void
15417 S_entersub_alloc_targ(pTHX_ OP * const o)
15418 {
15419     o->op_targ = pad_alloc(OP_ENTERSUB, SVs_PADTMP);
15420     o->op_private |= OPpENTERSUB_HASTARG;
15421 }
15422
15423 OP *
15424 Perl_ck_subr(pTHX_ OP *o)
15425 {
15426     OP *aop, *cvop;
15427     CV *cv;
15428     GV *namegv;
15429     SV **const_class = NULL;
15430
15431     PERL_ARGS_ASSERT_CK_SUBR;
15432
15433     aop = cUNOPx(o)->op_first;
15434     if (!OpHAS_SIBLING(aop))
15435         aop = cUNOPx(aop)->op_first;
15436     aop = OpSIBLING(aop);
15437     for (cvop = aop; OpHAS_SIBLING(cvop); cvop = OpSIBLING(cvop)) ;
15438     cv = rv2cv_op_cv(cvop, RV2CVOPCV_MARK_EARLY);
15439     namegv = cv ? (GV*)rv2cv_op_cv(cvop, RV2CVOPCV_MAYBE_NAME_GV) : NULL;
15440
15441     o->op_private &= ~1;
15442     o->op_private |= (PL_hints & HINT_STRICT_REFS);
15443     if (PERLDB_SUB && PL_curstash != PL_debstash)
15444         o->op_private |= OPpENTERSUB_DB;
15445     switch (cvop->op_type) {
15446         case OP_RV2CV:
15447             o->op_private |= (cvop->op_private & OPpENTERSUB_AMPER);
15448             op_null(cvop);
15449             break;
15450         case OP_METHOD:
15451         case OP_METHOD_NAMED:
15452         case OP_METHOD_SUPER:
15453         case OP_METHOD_REDIR:
15454         case OP_METHOD_REDIR_SUPER:
15455             o->op_flags |= OPf_REF;
15456             if (aop->op_type == OP_CONST) {
15457                 aop->op_private &= ~OPpCONST_STRICT;
15458                 const_class = &cSVOPx(aop)->op_sv;
15459             }
15460             else if (aop->op_type == OP_LIST) {
15461                 OP * const sib = OpSIBLING(((UNOP*)aop)->op_first);
15462                 if (sib && sib->op_type == OP_CONST) {
15463                     sib->op_private &= ~OPpCONST_STRICT;
15464                     const_class = &cSVOPx(sib)->op_sv;
15465                 }
15466             }
15467             /* make class name a shared cow string to speedup method calls */
15468             /* constant string might be replaced with object, f.e. bigint */
15469             if (const_class && SvPOK(*const_class)) {
15470                 STRLEN len;
15471                 const char* str = SvPV(*const_class, len);
15472                 if (len) {
15473                     SV* const shared = newSVpvn_share(
15474                         str, SvUTF8(*const_class)
15475                                     ? -(SSize_t)len : (SSize_t)len,
15476                         0
15477                     );
15478                     if (SvREADONLY(*const_class))
15479                         SvREADONLY_on(shared);
15480                     SvREFCNT_dec(*const_class);
15481                     *const_class = shared;
15482                 }
15483             }
15484             break;
15485     }
15486
15487     if (!cv) {
15488         S_entersub_alloc_targ(aTHX_ o);
15489         return ck_entersub_args_list(o);
15490     } else {
15491         Perl_call_checker ckfun;
15492         SV *ckobj;
15493         U32 ckflags;
15494         cv_get_call_checker_flags(cv, 0, &ckfun, &ckobj, &ckflags);
15495         if (CvISXSUB(cv) || !CvROOT(cv))
15496             S_entersub_alloc_targ(aTHX_ o);
15497         if (!namegv) {
15498             /* The original call checker API guarantees that a GV will
15499                be provided with the right name.  So, if the old API was
15500                used (or the REQUIRE_GV flag was passed), we have to reify
15501                the CV’s GV, unless this is an anonymous sub.  This is not
15502                ideal for lexical subs, as its stringification will include
15503                the package.  But it is the best we can do.  */
15504             if (ckflags & CALL_CHECKER_REQUIRE_GV) {
15505                 if (!CvANON(cv) && (!CvNAMED(cv) || CvNAME_HEK(cv)))
15506                     namegv = CvGV(cv);
15507             }
15508             else namegv = MUTABLE_GV(cv);
15509             /* After a syntax error in a lexical sub, the cv that
15510                rv2cv_op_cv returns may be a nameless stub. */
15511             if (!namegv) return ck_entersub_args_list(o);
15512
15513         }
15514         return ckfun(aTHX_ o, namegv, ckobj);
15515     }
15516 }
15517
15518 OP *
15519 Perl_ck_svconst(pTHX_ OP *o)
15520 {
15521     SV * const sv = cSVOPo->op_sv;
15522     PERL_ARGS_ASSERT_CK_SVCONST;
15523     PERL_UNUSED_CONTEXT;
15524 #ifdef PERL_COPY_ON_WRITE
15525     /* Since the read-only flag may be used to protect a string buffer, we
15526        cannot do copy-on-write with existing read-only scalars that are not
15527        already copy-on-write scalars.  To allow $_ = "hello" to do COW with
15528        that constant, mark the constant as COWable here, if it is not
15529        already read-only. */
15530     if (!SvREADONLY(sv) && !SvIsCOW(sv) && SvCANCOW(sv)) {
15531         SvIsCOW_on(sv);
15532         CowREFCNT(sv) = 0;
15533 # ifdef PERL_DEBUG_READONLY_COW
15534         sv_buf_to_ro(sv);
15535 # endif
15536     }
15537 #endif
15538     SvREADONLY_on(sv);
15539     return o;
15540 }
15541
15542 OP *
15543 Perl_ck_trunc(pTHX_ OP *o)
15544 {
15545     PERL_ARGS_ASSERT_CK_TRUNC;
15546
15547     if (o->op_flags & OPf_KIDS) {
15548         SVOP *kid = (SVOP*)cUNOPo->op_first;
15549
15550         if (kid->op_type == OP_NULL)
15551             kid = (SVOP*)OpSIBLING(kid);
15552         if (kid && kid->op_type == OP_CONST &&
15553             (kid->op_private & OPpCONST_BARE) &&
15554             !kid->op_folded)
15555         {
15556             o->op_flags |= OPf_SPECIAL;
15557             kid->op_private &= ~OPpCONST_STRICT;
15558             if (!FEATURE_BAREWORD_FILEHANDLES_IS_ENABLED) {
15559                 no_bareword_filehandle(SvPVX(cSVOPx_sv(kid)));
15560             }
15561         }
15562     }
15563     return ck_fun(o);
15564 }
15565
15566 OP *
15567 Perl_ck_substr(pTHX_ OP *o)
15568 {
15569     PERL_ARGS_ASSERT_CK_SUBSTR;
15570
15571     o = ck_fun(o);
15572     if ((o->op_flags & OPf_KIDS) && (o->op_private == 4)) {
15573         OP *kid = cLISTOPo->op_first;
15574
15575         if (kid->op_type == OP_NULL)
15576             kid = OpSIBLING(kid);
15577         if (kid)
15578             /* Historically, substr(delete $foo{bar},...) has been allowed
15579                with 4-arg substr.  Keep it working by applying entersub
15580                lvalue context.  */
15581             op_lvalue(kid, OP_ENTERSUB);
15582
15583     }
15584     return o;
15585 }
15586
15587 OP *
15588 Perl_ck_tell(pTHX_ OP *o)
15589 {
15590     PERL_ARGS_ASSERT_CK_TELL;
15591     o = ck_fun(o);
15592     if (o->op_flags & OPf_KIDS) {
15593      OP *kid = cLISTOPo->op_first;
15594      if (kid->op_type == OP_NULL && OpHAS_SIBLING(kid)) kid = OpSIBLING(kid);
15595      if (kid->op_type == OP_RV2GV) kid->op_private |= OPpALLOW_FAKE;
15596     }
15597     return o;
15598 }
15599
15600 PERL_STATIC_INLINE OP *
15601 S_last_non_null_kid(OP *o) {
15602     OP *last = NULL;
15603     if (cUNOPo->op_flags & OPf_KIDS) {
15604         OP *k = cLISTOPo->op_first;
15605         while (k) {
15606             if (k->op_type != OP_NULL) {
15607                 last = k;
15608             }
15609             k = OpSIBLING(k);
15610         }
15611     }
15612
15613     return last;
15614 }
15615
15616 OP *
15617 Perl_ck_each(pTHX_ OP *o)
15618 {
15619     OP *kid = o->op_flags & OPf_KIDS ? cUNOPo->op_first : NULL;
15620     const unsigned orig_type  = o->op_type;
15621
15622     PERL_ARGS_ASSERT_CK_EACH;
15623
15624     if (kid) {
15625         switch (kid->op_type) {
15626             case OP_PADHV:
15627                 break;
15628
15629             case OP_RV2HV:
15630                 /* Catch out an anonhash here, since the behaviour might be
15631                  * confusing.
15632                  *
15633                  * The typical tree is:
15634                  *
15635                  *     rv2hv
15636                  *         scope
15637                  *             null
15638                  *             anonhash
15639                  *
15640                  * If the contents of the block is more complex you might get:
15641                  *
15642                  *     rv2hv
15643                  *         leave
15644                  *             enter
15645                  *             ...
15646                  *             anonhash
15647                  *
15648                  * Similarly for the anonlist version below.
15649                  */
15650                 if (orig_type == OP_EACH &&
15651                     ckWARN(WARN_SYNTAX) &&
15652                     (cUNOPx(kid)->op_flags & OPf_KIDS) &&
15653                     ( cUNOPx(kid)->op_first->op_type == OP_SCOPE ||
15654                       cUNOPx(kid)->op_first->op_type == OP_LEAVE) &&
15655                     (cUNOPx(kid)->op_first->op_flags & OPf_KIDS)) {
15656                     /* look for last non-null kid, since we might have:
15657                        each %{ some code ; +{ anon hash } }
15658                     */
15659                     OP *k = S_last_non_null_kid(cUNOPx(kid)->op_first);
15660                     if (k && k->op_type == OP_ANONHASH) {
15661                         /* diag_listed_as: each on anonymous %s will always start from the beginning */
15662                         Perl_warner(aTHX_ packWARN(WARN_SYNTAX), "each on anonymous hash will always start from the beginning");
15663                     }
15664                 }
15665                 break;
15666             case OP_RV2AV:
15667                 if (orig_type == OP_EACH &&
15668                     ckWARN(WARN_SYNTAX) &&
15669                     (cUNOPx(kid)->op_flags & OPf_KIDS) &&
15670                     (cUNOPx(kid)->op_first->op_type == OP_SCOPE ||
15671                      cUNOPx(kid)->op_first->op_type == OP_LEAVE) &&
15672                     (cUNOPx(kid)->op_first->op_flags & OPf_KIDS)) {
15673                     OP *k = S_last_non_null_kid(cUNOPx(kid)->op_first);
15674                     if (k && k->op_type == OP_ANONLIST) {
15675                         /* diag_listed_as: each on anonymous %s will always start from the beginning */
15676                         Perl_warner(aTHX_ packWARN(WARN_SYNTAX), "each on anonymous array will always start from the beginning");
15677                     }
15678                 }
15679                 /* FALLTHROUGH */
15680             case OP_PADAV:
15681                 OpTYPE_set(o, orig_type == OP_EACH ? OP_AEACH
15682                             : orig_type == OP_KEYS ? OP_AKEYS
15683                             :                        OP_AVALUES);
15684                 break;
15685             case OP_CONST:
15686                 if (kid->op_private == OPpCONST_BARE
15687                  || !SvROK(cSVOPx_sv(kid))
15688                  || (  SvTYPE(SvRV(cSVOPx_sv(kid))) != SVt_PVAV
15689                     && SvTYPE(SvRV(cSVOPx_sv(kid))) != SVt_PVHV  )
15690                    )
15691                     goto bad;
15692                 /* FALLTHROUGH */
15693             default:
15694                 qerror(Perl_mess(aTHX_
15695                     "Experimental %s on scalar is now forbidden",
15696                      PL_op_desc[orig_type]));
15697                bad:
15698                 bad_type_pv(1, "hash or array", o, kid);
15699                 return o;
15700         }
15701     }
15702     return ck_fun(o);
15703 }
15704
15705 OP *
15706 Perl_ck_length(pTHX_ OP *o)
15707 {
15708     PERL_ARGS_ASSERT_CK_LENGTH;
15709
15710     o = ck_fun(o);
15711
15712     if (ckWARN(WARN_SYNTAX)) {
15713         const OP *kid = o->op_flags & OPf_KIDS ? cLISTOPo->op_first : NULL;
15714
15715         if (kid) {
15716             SV *name = NULL;
15717             const bool hash = kid->op_type == OP_PADHV
15718                            || kid->op_type == OP_RV2HV;
15719             switch (kid->op_type) {
15720                 case OP_PADHV:
15721                 case OP_PADAV:
15722                 case OP_RV2HV:
15723                 case OP_RV2AV:
15724                     name = S_op_varname(aTHX_ kid);
15725                     break;
15726                 default:
15727                     return o;
15728             }
15729             if (name)
15730                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
15731                     "length() used on %" SVf " (did you mean \"scalar(%s%" SVf
15732                     ")\"?)",
15733                     SVfARG(name), hash ? "keys " : "", SVfARG(name)
15734                 );
15735             else if (hash)
15736      /* diag_listed_as: length() used on %s (did you mean "scalar(%s)"?) */
15737                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
15738                     "length() used on %%hash (did you mean \"scalar(keys %%hash)\"?)");
15739             else
15740      /* diag_listed_as: length() used on %s (did you mean "scalar(%s)"?) */
15741                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
15742                     "length() used on @array (did you mean \"scalar(@array)\"?)");
15743         }
15744     }
15745
15746     return o;
15747 }
15748
15749
15750 OP *
15751 Perl_ck_isa(pTHX_ OP *o)
15752 {
15753     OP *classop = cBINOPo->op_last;
15754
15755     PERL_ARGS_ASSERT_CK_ISA;
15756
15757     /* Convert barename into PV */
15758     if(classop->op_type == OP_CONST && classop->op_private & OPpCONST_BARE) {
15759         /* TODO: Optionally convert package to raw HV here */
15760         classop->op_private &= ~(OPpCONST_BARE|OPpCONST_STRICT);
15761     }
15762
15763     return o;
15764 }
15765
15766
15767 /*
15768    ---------------------------------------------------------
15769
15770    Common vars in list assignment
15771
15772    There now follows some enums and static functions for detecting
15773    common variables in list assignments. Here is a little essay I wrote
15774    for myself when trying to get my head around this. DAPM.
15775
15776    ----
15777
15778    First some random observations:
15779
15780    * If a lexical var is an alias of something else, e.g.
15781        for my $x ($lex, $pkg, $a[0]) {...}
15782      then the act of aliasing will increase the reference count of the SV
15783
15784    * If a package var is an alias of something else, it may still have a
15785      reference count of 1, depending on how the alias was created, e.g.
15786      in *a = *b, $a may have a refcount of 1 since the GP is shared
15787      with a single GvSV pointer to the SV. So If it's an alias of another
15788      package var, then RC may be 1; if it's an alias of another scalar, e.g.
15789      a lexical var or an array element, then it will have RC > 1.
15790
15791    * There are many ways to create a package alias; ultimately, XS code
15792      may quite legally do GvSV(gv) = SvREFCNT_inc(sv) for example, so
15793      run-time tracing mechanisms are unlikely to be able to catch all cases.
15794
15795    * When the LHS is all my declarations, the same vars can't appear directly
15796      on the RHS, but they can indirectly via closures, aliasing and lvalue
15797      subs. But those techniques all involve an increase in the lexical
15798      scalar's ref count.
15799
15800    * When the LHS is all lexical vars (but not necessarily my declarations),
15801      it is possible for the same lexicals to appear directly on the RHS, and
15802      without an increased ref count, since the stack isn't refcounted.
15803      This case can be detected at compile time by scanning for common lex
15804      vars with PL_generation.
15805
15806    * lvalue subs defeat common var detection, but they do at least
15807      return vars with a temporary ref count increment. Also, you can't
15808      tell at compile time whether a sub call is lvalue.
15809
15810
15811    So...
15812
15813    A: There are a few circumstances where there definitely can't be any
15814      commonality:
15815
15816        LHS empty:  () = (...);
15817        RHS empty:  (....) = ();
15818        RHS contains only constants or other 'can't possibly be shared'
15819            elements (e.g. ops that return PADTMPs):  (...) = (1,2, length)
15820            i.e. they only contain ops not marked as dangerous, whose children
15821            are also not dangerous;
15822        LHS ditto;
15823        LHS contains a single scalar element: e.g. ($x) = (....); because
15824            after $x has been modified, it won't be used again on the RHS;
15825        RHS contains a single element with no aggregate on LHS: e.g.
15826            ($a,$b,$c)  = ($x); again, once $a has been modified, its value
15827            won't be used again.
15828
15829    B: If LHS are all 'my' lexical var declarations (or safe ops, which
15830      we can ignore):
15831
15832        my ($a, $b, @c) = ...;
15833
15834        Due to closure and goto tricks, these vars may already have content.
15835        For the same reason, an element on the RHS may be a lexical or package
15836        alias of one of the vars on the left, or share common elements, for
15837        example:
15838
15839            my ($x,$y) = f(); # $x and $y on both sides
15840            sub f : lvalue { ($x,$y) = (1,2); $y, $x }
15841
15842        and
15843
15844            my $ra = f();
15845            my @a = @$ra;  # elements of @a on both sides
15846            sub f { @a = 1..4; \@a }
15847
15848
15849        First, just consider scalar vars on LHS:
15850
15851            RHS is safe only if (A), or in addition,
15852                * contains only lexical *scalar* vars, where neither side's
15853                  lexicals have been flagged as aliases
15854
15855            If RHS is not safe, then it's always legal to check LHS vars for
15856            RC==1, since the only RHS aliases will always be associated
15857            with an RC bump.
15858
15859            Note that in particular, RHS is not safe if:
15860
15861                * it contains package scalar vars; e.g.:
15862
15863                    f();
15864                    my ($x, $y) = (2, $x_alias);
15865                    sub f { $x = 1; *x_alias = \$x; }
15866
15867                * It contains other general elements, such as flattened or
15868                * spliced or single array or hash elements, e.g.
15869
15870                    f();
15871                    my ($x,$y) = @a; # or $a[0] or @a{@b} etc
15872
15873                    sub f {
15874                        ($x, $y) = (1,2);
15875                        use feature 'refaliasing';
15876                        \($a[0], $a[1]) = \($y,$x);
15877                    }
15878
15879                  It doesn't matter if the array/hash is lexical or package.
15880
15881                * it contains a function call that happens to be an lvalue
15882                  sub which returns one or more of the above, e.g.
15883
15884                    f();
15885                    my ($x,$y) = f();
15886
15887                    sub f : lvalue {
15888                        ($x, $y) = (1,2);
15889                        *x1 = \$x;
15890                        $y, $x1;
15891                    }
15892
15893                    (so a sub call on the RHS should be treated the same
15894                    as having a package var on the RHS).
15895
15896                * any other "dangerous" thing, such an op or built-in that
15897                  returns one of the above, e.g. pp_preinc
15898
15899
15900            If RHS is not safe, what we can do however is at compile time flag
15901            that the LHS are all my declarations, and at run time check whether
15902            all the LHS have RC == 1, and if so skip the full scan.
15903
15904        Now consider array and hash vars on LHS: e.g. my (...,@a) = ...;
15905
15906            Here the issue is whether there can be elements of @a on the RHS
15907            which will get prematurely freed when @a is cleared prior to
15908            assignment. This is only a problem if the aliasing mechanism
15909            is one which doesn't increase the refcount - only if RC == 1
15910            will the RHS element be prematurely freed.
15911
15912            Because the array/hash is being INTROed, it or its elements
15913            can't directly appear on the RHS:
15914
15915                my (@a) = ($a[0], @a, etc) # NOT POSSIBLE
15916
15917            but can indirectly, e.g.:
15918
15919                my $r = f();
15920                my (@a) = @$r;
15921                sub f { @a = 1..3; \@a }
15922
15923            So if the RHS isn't safe as defined by (A), we must always
15924            mortalise and bump the ref count of any remaining RHS elements
15925            when assigning to a non-empty LHS aggregate.
15926
15927            Lexical scalars on the RHS aren't safe if they've been involved in
15928            aliasing, e.g.
15929
15930                use feature 'refaliasing';
15931
15932                f();
15933                \(my $lex) = \$pkg;
15934                my @a = ($lex,3); # equivalent to ($a[0],3)
15935
15936                sub f {
15937                    @a = (1,2);
15938                    \$pkg = \$a[0];
15939                }
15940
15941            Similarly with lexical arrays and hashes on the RHS:
15942
15943                f();
15944                my @b;
15945                my @a = (@b);
15946
15947                sub f {
15948                    @a = (1,2);
15949                    \$b[0] = \$a[1];
15950                    \$b[1] = \$a[0];
15951                }
15952
15953
15954
15955    C: As (B), but in addition the LHS may contain non-intro lexicals, e.g.
15956        my $a; ($a, my $b) = (....);
15957
15958        The difference between (B) and (C) is that it is now physically
15959        possible for the LHS vars to appear on the RHS too, where they
15960        are not reference counted; but in this case, the compile-time
15961        PL_generation sweep will detect such common vars.
15962
15963        So the rules for (C) differ from (B) in that if common vars are
15964        detected, the runtime "test RC==1" optimisation can no longer be used,
15965        and a full mark and sweep is required
15966
15967    D: As (C), but in addition the LHS may contain package vars.
15968
15969        Since package vars can be aliased without a corresponding refcount
15970        increase, all bets are off. It's only safe if (A). E.g.
15971
15972            my ($x, $y) = (1,2);
15973
15974            for $x_alias ($x) {
15975                ($x_alias, $y) = (3, $x); # whoops
15976            }
15977
15978        Ditto for LHS aggregate package vars.
15979
15980    E: Any other dangerous ops on LHS, e.g.
15981            (f(), $a[0], @$r) = (...);
15982
15983        this is similar to (E) in that all bets are off. In addition, it's
15984        impossible to determine at compile time whether the LHS
15985        contains a scalar or an aggregate, e.g.
15986
15987            sub f : lvalue { @a }
15988            (f()) = 1..3;
15989
15990 * ---------------------------------------------------------
15991 */
15992
15993
15994 /* A set of bit flags returned by S_aassign_scan(). Each flag indicates
15995  * that at least one of the things flagged was seen.
15996  */
15997
15998 enum {
15999     AAS_MY_SCALAR       = 0x001, /* my $scalar */
16000     AAS_MY_AGG          = 0x002, /* aggregate: my @array or my %hash */
16001     AAS_LEX_SCALAR      = 0x004, /* $lexical */
16002     AAS_LEX_AGG         = 0x008, /* @lexical or %lexical aggregate */
16003     AAS_LEX_SCALAR_COMM = 0x010, /* $lexical seen on both sides */
16004     AAS_PKG_SCALAR      = 0x020, /* $scalar (where $scalar is pkg var) */
16005     AAS_PKG_AGG         = 0x040, /* package @array or %hash aggregate */
16006     AAS_DANGEROUS       = 0x080, /* an op (other than the above)
16007                                          that's flagged OA_DANGEROUS */
16008     AAS_SAFE_SCALAR     = 0x100, /* produces at least one scalar SV that's
16009                                         not in any of the categories above */
16010     AAS_DEFAV           = 0x200  /* contains just a single '@_' on RHS */
16011 };
16012
16013
16014
16015 /* helper function for S_aassign_scan().
16016  * check a PAD-related op for commonality and/or set its generation number.
16017  * Returns a boolean indicating whether its shared */
16018
16019 static bool
16020 S_aassign_padcheck(pTHX_ OP* o, bool rhs)
16021 {
16022     if (PAD_COMPNAME_GEN(o->op_targ) == PERL_INT_MAX)
16023         /* lexical used in aliasing */
16024         return TRUE;
16025
16026     if (rhs)
16027         return cBOOL(PAD_COMPNAME_GEN(o->op_targ) == (STRLEN)PL_generation);
16028     else
16029         PAD_COMPNAME_GEN_set(o->op_targ, PL_generation);
16030
16031     return FALSE;
16032 }
16033
16034
16035 /*
16036   Helper function for OPpASSIGN_COMMON* detection in rpeep().
16037   It scans the left or right hand subtree of the aassign op, and returns a
16038   set of flags indicating what sorts of things it found there.
16039   'rhs' indicates whether we're scanning the LHS or RHS. If the former, we
16040   set PL_generation on lexical vars; if the latter, we see if
16041   PL_generation matches.
16042   'scalars_p' is a pointer to a counter of the number of scalar SVs seen.
16043   This fn will increment it by the number seen. It's not intended to
16044   be an accurate count (especially as many ops can push a variable
16045   number of SVs onto the stack); rather it's used as to test whether there
16046   can be at most 1 SV pushed; so it's only meanings are "0, 1, many".
16047 */
16048
16049 static int
16050 S_aassign_scan(pTHX_ OP* o, bool rhs, int *scalars_p)
16051 {
16052     OP *top_op           = o;
16053     OP *effective_top_op = o;
16054     int all_flags = 0;
16055
16056     while (1) {
16057     bool top = o == effective_top_op;
16058     int flags = 0;
16059     OP* next_kid = NULL;
16060
16061     /* first, look for a solitary @_ on the RHS */
16062     if (   rhs
16063         && top
16064         && (o->op_flags & OPf_KIDS)
16065         && OP_TYPE_IS_OR_WAS(o, OP_LIST)
16066     ) {
16067         OP *kid = cUNOPo->op_first;
16068         if (   (   kid->op_type == OP_PUSHMARK
16069                 || kid->op_type == OP_PADRANGE) /* ex-pushmark */
16070             && ((kid = OpSIBLING(kid)))
16071             && !OpHAS_SIBLING(kid)
16072             && kid->op_type == OP_RV2AV
16073             && !(kid->op_flags & OPf_REF)
16074             && !(kid->op_private & (OPpLVAL_INTRO|OPpMAYBE_LVSUB))
16075             && ((kid->op_flags & OPf_WANT) == OPf_WANT_LIST)
16076             && ((kid = cUNOPx(kid)->op_first))
16077             && kid->op_type == OP_GV
16078             && cGVOPx_gv(kid) == PL_defgv
16079         )
16080             flags = AAS_DEFAV;
16081     }
16082
16083     switch (o->op_type) {
16084     case OP_GVSV:
16085         (*scalars_p)++;
16086         all_flags |= AAS_PKG_SCALAR;
16087         goto do_next;
16088
16089     case OP_PADAV:
16090     case OP_PADHV:
16091         (*scalars_p) += 2;
16092         /* if !top, could be e.g. @a[0,1] */
16093         all_flags |=  (top && (o->op_flags & OPf_REF))
16094                         ? ((o->op_private & OPpLVAL_INTRO)
16095                             ? AAS_MY_AGG : AAS_LEX_AGG)
16096                         : AAS_DANGEROUS;
16097         goto do_next;
16098
16099     case OP_PADSV:
16100         {
16101             int comm = S_aassign_padcheck(aTHX_ o, rhs)
16102                         ?  AAS_LEX_SCALAR_COMM : 0;
16103             (*scalars_p)++;
16104             all_flags |= (o->op_private & OPpLVAL_INTRO)
16105                 ? (AAS_MY_SCALAR|comm) : (AAS_LEX_SCALAR|comm);
16106             goto do_next;
16107
16108         }
16109
16110     case OP_RV2AV:
16111     case OP_RV2HV:
16112         (*scalars_p) += 2;
16113         if (cUNOPx(o)->op_first->op_type != OP_GV)
16114             all_flags |= AAS_DANGEROUS; /* @{expr}, %{expr} */
16115         /* @pkg, %pkg */
16116         /* if !top, could be e.g. @a[0,1] */
16117         else if (top && (o->op_flags & OPf_REF))
16118             all_flags |= AAS_PKG_AGG;
16119         else
16120             all_flags |= AAS_DANGEROUS;
16121         goto do_next;
16122
16123     case OP_RV2SV:
16124         (*scalars_p)++;
16125         if (cUNOPx(o)->op_first->op_type != OP_GV) {
16126             (*scalars_p) += 2;
16127             all_flags |= AAS_DANGEROUS; /* ${expr} */
16128         }
16129         else
16130             all_flags |= AAS_PKG_SCALAR; /* $pkg */
16131         goto do_next;
16132
16133     case OP_SPLIT:
16134         if (o->op_private & OPpSPLIT_ASSIGN) {
16135             /* the assign in @a = split() has been optimised away
16136              * and the @a attached directly to the split op
16137              * Treat the array as appearing on the RHS, i.e.
16138              *    ... = (@a = split)
16139              * is treated like
16140              *    ... = @a;
16141              */
16142
16143             if (o->op_flags & OPf_STACKED) {
16144                 /* @{expr} = split() - the array expression is tacked
16145                  * on as an extra child to split - process kid */
16146                 next_kid = cLISTOPo->op_last;
16147                 goto do_next;
16148             }
16149
16150             /* ... else array is directly attached to split op */
16151             (*scalars_p) += 2;
16152             all_flags |= (PL_op->op_private & OPpSPLIT_LEX)
16153                             ? ((o->op_private & OPpLVAL_INTRO)
16154                                 ? AAS_MY_AGG : AAS_LEX_AGG)
16155                             : AAS_PKG_AGG;
16156             goto do_next;
16157         }
16158         (*scalars_p)++;
16159         /* other args of split can't be returned */
16160         all_flags |= AAS_SAFE_SCALAR;
16161         goto do_next;
16162
16163     case OP_UNDEF:
16164         /* undef on LHS following a var is significant, e.g.
16165          *    my $x = 1;
16166          *    @a = (($x, undef) = (2 => $x));
16167          *    # @a shoul be (2,1) not (2,2)
16168          *
16169          * undef on RHS counts as a scalar:
16170          *   ($x, $y)    = (undef, $x); # 2 scalars on RHS: unsafe
16171          */
16172         if ((!rhs && *scalars_p) || rhs)
16173             (*scalars_p)++;
16174         flags = AAS_SAFE_SCALAR;
16175         break;
16176
16177     case OP_PUSHMARK:
16178     case OP_STUB:
16179         /* these are all no-ops; they don't push a potentially common SV
16180          * onto the stack, so they are neither AAS_DANGEROUS nor
16181          * AAS_SAFE_SCALAR */
16182         goto do_next;
16183
16184     case OP_PADRANGE: /* Ignore padrange; checking its siblings is enough */
16185         break;
16186
16187     case OP_NULL:
16188     case OP_LIST:
16189         /* these do nothing, but may have children */
16190         break;
16191
16192     default:
16193         if (PL_opargs[o->op_type] & OA_DANGEROUS) {
16194             (*scalars_p) += 2;
16195             flags = AAS_DANGEROUS;
16196             break;
16197         }
16198
16199         if (   (PL_opargs[o->op_type] & OA_TARGLEX)
16200             && (o->op_private & OPpTARGET_MY))
16201         {
16202             (*scalars_p)++;
16203             all_flags |= S_aassign_padcheck(aTHX_ o, rhs)
16204                             ? AAS_LEX_SCALAR_COMM : AAS_LEX_SCALAR;
16205             goto do_next;
16206         }
16207
16208         /* if its an unrecognised, non-dangerous op, assume that it
16209          * is the cause of at least one safe scalar */
16210         (*scalars_p)++;
16211         flags = AAS_SAFE_SCALAR;
16212         break;
16213     }
16214
16215     all_flags |= flags;
16216
16217     /* by default, process all kids next
16218      * XXX this assumes that all other ops are "transparent" - i.e. that
16219      * they can return some of their children. While this true for e.g.
16220      * sort and grep, it's not true for e.g. map. We really need a
16221      * 'transparent' flag added to regen/opcodes
16222      */
16223     if (o->op_flags & OPf_KIDS) {
16224         next_kid = cUNOPo->op_first;
16225         /* these ops do nothing but may have children; but their
16226          * children should also be treated as top-level */
16227         if (   o == effective_top_op
16228             && (o->op_type == OP_NULL || o->op_type == OP_LIST)
16229         )
16230             effective_top_op = next_kid;
16231     }
16232
16233
16234     /* If next_kid is set, someone in the code above wanted us to process
16235      * that kid and all its remaining siblings.  Otherwise, work our way
16236      * back up the tree */
16237   do_next:
16238     while (!next_kid) {
16239         if (o == top_op)
16240             return all_flags; /* at top; no parents/siblings to try */
16241         if (OpHAS_SIBLING(o)) {
16242             next_kid = o->op_sibparent;
16243             if (o == effective_top_op)
16244                 effective_top_op = next_kid;
16245         }
16246         else
16247             if (o == effective_top_op)
16248                 effective_top_op = o->op_sibparent;
16249             o = o->op_sibparent; /* try parent's next sibling */
16250
16251     }
16252     o = next_kid;
16253     } /* while */
16254
16255 }
16256
16257
16258 /* Check for in place reverse and sort assignments like "@a = reverse @a"
16259    and modify the optree to make them work inplace */
16260
16261 STATIC void
16262 S_inplace_aassign(pTHX_ OP *o) {
16263
16264     OP *modop, *modop_pushmark;
16265     OP *oright;
16266     OP *oleft, *oleft_pushmark;
16267
16268     PERL_ARGS_ASSERT_INPLACE_AASSIGN;
16269
16270     assert((o->op_flags & OPf_WANT) == OPf_WANT_VOID);
16271
16272     assert(cUNOPo->op_first->op_type == OP_NULL);
16273     modop_pushmark = cUNOPx(cUNOPo->op_first)->op_first;
16274     assert(modop_pushmark->op_type == OP_PUSHMARK);
16275     modop = OpSIBLING(modop_pushmark);
16276
16277     if (modop->op_type != OP_SORT && modop->op_type != OP_REVERSE)
16278         return;
16279
16280     /* no other operation except sort/reverse */
16281     if (OpHAS_SIBLING(modop))
16282         return;
16283
16284     assert(cUNOPx(modop)->op_first->op_type == OP_PUSHMARK);
16285     if (!(oright = OpSIBLING(cUNOPx(modop)->op_first))) return;
16286
16287     if (modop->op_flags & OPf_STACKED) {
16288         /* skip sort subroutine/block */
16289         assert(oright->op_type == OP_NULL);
16290         oright = OpSIBLING(oright);
16291     }
16292
16293     assert(OpSIBLING(cUNOPo->op_first)->op_type == OP_NULL);
16294     oleft_pushmark = cUNOPx(OpSIBLING(cUNOPo->op_first))->op_first;
16295     assert(oleft_pushmark->op_type == OP_PUSHMARK);
16296     oleft = OpSIBLING(oleft_pushmark);
16297
16298     /* Check the lhs is an array */
16299     if (!oleft ||
16300         (oleft->op_type != OP_RV2AV && oleft->op_type != OP_PADAV)
16301         || OpHAS_SIBLING(oleft)
16302         || (oleft->op_private & OPpLVAL_INTRO)
16303     )
16304         return;
16305
16306     /* Only one thing on the rhs */
16307     if (OpHAS_SIBLING(oright))
16308         return;
16309
16310     /* check the array is the same on both sides */
16311     if (oleft->op_type == OP_RV2AV) {
16312         if (oright->op_type != OP_RV2AV
16313             || !cUNOPx(oright)->op_first
16314             || cUNOPx(oright)->op_first->op_type != OP_GV
16315             || cUNOPx(oleft )->op_first->op_type != OP_GV
16316             || cGVOPx_gv(cUNOPx(oleft)->op_first) !=
16317                cGVOPx_gv(cUNOPx(oright)->op_first)
16318         )
16319             return;
16320     }
16321     else if (oright->op_type != OP_PADAV
16322         || oright->op_targ != oleft->op_targ
16323     )
16324         return;
16325
16326     /* This actually is an inplace assignment */
16327
16328     modop->op_private |= OPpSORT_INPLACE;
16329
16330     /* transfer MODishness etc from LHS arg to RHS arg */
16331     oright->op_flags = oleft->op_flags;
16332
16333     /* remove the aassign op and the lhs */
16334     op_null(o);
16335     op_null(oleft_pushmark);
16336     if (oleft->op_type == OP_RV2AV && cUNOPx(oleft)->op_first)
16337         op_null(cUNOPx(oleft)->op_first);
16338     op_null(oleft);
16339 }
16340
16341
16342
16343 /* S_maybe_multideref(): given an op_next chain of ops beginning at 'start'
16344  * that potentially represent a series of one or more aggregate derefs
16345  * (such as $a->[1]{$key}), examine the chain, and if appropriate, convert
16346  * the whole chain to a single OP_MULTIDEREF op (maybe with a few
16347  * additional ops left in too).
16348  *
16349  * The caller will have already verified that the first few ops in the
16350  * chain following 'start' indicate a multideref candidate, and will have
16351  * set 'orig_o' to the point further on in the chain where the first index
16352  * expression (if any) begins.  'orig_action' specifies what type of
16353  * beginning has already been determined by the ops between start..orig_o
16354  * (e.g.  $lex_ary[], $pkg_ary->{}, expr->[], etc).
16355  *
16356  * 'hints' contains any hints flags that need adding (currently just
16357  * OPpHINT_STRICT_REFS) as found in any rv2av/hv skipped by the caller.
16358  */
16359
16360 STATIC void
16361 S_maybe_multideref(pTHX_ OP *start, OP *orig_o, UV orig_action, U8 hints)
16362 {
16363     int pass;
16364     UNOP_AUX_item *arg_buf = NULL;
16365     bool reset_start_targ  = FALSE; /* start->op_targ needs zeroing */
16366     int index_skip         = -1;    /* don't output index arg on this action */
16367
16368     /* similar to regex compiling, do two passes; the first pass
16369      * determines whether the op chain is convertible and calculates the
16370      * buffer size; the second pass populates the buffer and makes any
16371      * changes necessary to ops (such as moving consts to the pad on
16372      * threaded builds).
16373      *
16374      * NB: for things like Coverity, note that both passes take the same
16375      * path through the logic tree (except for 'if (pass)' bits), since
16376      * both passes are following the same op_next chain; and in
16377      * particular, if it would return early on the second pass, it would
16378      * already have returned early on the first pass.
16379      */
16380     for (pass = 0; pass < 2; pass++) {
16381         OP *o                = orig_o;
16382         UV action            = orig_action;
16383         OP *first_elem_op    = NULL;  /* first seen aelem/helem */
16384         OP *top_op           = NULL;  /* highest [ah]elem/exists/del/rv2[ah]v */
16385         int action_count     = 0;     /* number of actions seen so far */
16386         int action_ix        = 0;     /* action_count % (actions per IV) */
16387         bool next_is_hash    = FALSE; /* is the next lookup to be a hash? */
16388         bool is_last         = FALSE; /* no more derefs to follow */
16389         bool maybe_aelemfast = FALSE; /* we can replace with aelemfast? */
16390         UV action_word       = 0;     /* all actions so far */
16391         UNOP_AUX_item *arg     = arg_buf;
16392         UNOP_AUX_item *action_ptr = arg_buf;
16393
16394         arg++; /* reserve slot for first action word */
16395
16396         switch (action) {
16397         case MDEREF_HV_gvsv_vivify_rv2hv_helem:
16398         case MDEREF_HV_gvhv_helem:
16399             next_is_hash = TRUE;
16400             /* FALLTHROUGH */
16401         case MDEREF_AV_gvsv_vivify_rv2av_aelem:
16402         case MDEREF_AV_gvav_aelem:
16403             if (pass) {
16404 #ifdef USE_ITHREADS
16405                 arg->pad_offset = cPADOPx(start)->op_padix;
16406                 /* stop it being swiped when nulled */
16407                 cPADOPx(start)->op_padix = 0;
16408 #else
16409                 arg->sv = cSVOPx(start)->op_sv;
16410                 cSVOPx(start)->op_sv = NULL;
16411 #endif
16412             }
16413             arg++;
16414             break;
16415
16416         case MDEREF_HV_padhv_helem:
16417         case MDEREF_HV_padsv_vivify_rv2hv_helem:
16418             next_is_hash = TRUE;
16419             /* FALLTHROUGH */
16420         case MDEREF_AV_padav_aelem:
16421         case MDEREF_AV_padsv_vivify_rv2av_aelem:
16422             if (pass) {
16423                 arg->pad_offset = start->op_targ;
16424                 /* we skip setting op_targ = 0 for now, since the intact
16425                  * OP_PADXV is needed by S_check_hash_fields_and_hekify */
16426                 reset_start_targ = TRUE;
16427             }
16428             arg++;
16429             break;
16430
16431         case MDEREF_HV_pop_rv2hv_helem:
16432             next_is_hash = TRUE;
16433             /* FALLTHROUGH */
16434         case MDEREF_AV_pop_rv2av_aelem:
16435             break;
16436
16437         default:
16438             NOT_REACHED; /* NOTREACHED */
16439             return;
16440         }
16441
16442         while (!is_last) {
16443             /* look for another (rv2av/hv; get index;
16444              * aelem/helem/exists/delele) sequence */
16445
16446             OP *kid;
16447             bool is_deref;
16448             bool ok;
16449             UV index_type = MDEREF_INDEX_none;
16450
16451             if (action_count) {
16452                 /* if this is not the first lookup, consume the rv2av/hv  */
16453
16454                 /* for N levels of aggregate lookup, we normally expect
16455                  * that the first N-1 [ah]elem ops will be flagged as
16456                  * /DEREF (so they autovivifiy if necessary), and the last
16457                  * lookup op not to be.
16458                  * For other things (like @{$h{k1}{k2}}) extra scope or
16459                  * leave ops can appear, so abandon the effort in that
16460                  * case */
16461                 if (o->op_type != OP_RV2AV && o->op_type != OP_RV2HV)
16462                     return;
16463
16464                 /* rv2av or rv2hv sKR/1 */
16465
16466                 ASSUME(!(o->op_flags & ~(OPf_WANT|OPf_KIDS|OPf_PARENS
16467                                             |OPf_REF|OPf_MOD|OPf_SPECIAL)));
16468                 if (o->op_flags != (OPf_WANT_SCALAR|OPf_KIDS|OPf_REF))
16469                     return;
16470
16471                 /* at this point, we wouldn't expect any of these
16472                  * possible private flags:
16473                  * OPpMAYBE_LVSUB, OPpOUR_INTRO, OPpLVAL_INTRO
16474                  * OPpTRUEBOOL, OPpMAYBE_TRUEBOOL (rv2hv only)
16475                  */
16476                 ASSUME(!(o->op_private &
16477                     ~(OPpHINT_STRICT_REFS|OPpARG1_MASK|OPpSLICEWARNING)));
16478
16479                 hints = (o->op_private & OPpHINT_STRICT_REFS);
16480
16481                 /* make sure the type of the previous /DEREF matches the
16482                  * type of the next lookup */
16483                 ASSUME(o->op_type == (next_is_hash ? OP_RV2HV : OP_RV2AV));
16484                 top_op = o;
16485
16486                 action = next_is_hash
16487                             ? MDEREF_HV_vivify_rv2hv_helem
16488                             : MDEREF_AV_vivify_rv2av_aelem;
16489                 o = o->op_next;
16490             }
16491
16492             /* if this is the second pass, and we're at the depth where
16493              * previously we encountered a non-simple index expression,
16494              * stop processing the index at this point */
16495             if (action_count != index_skip) {
16496
16497                 /* look for one or more simple ops that return an array
16498                  * index or hash key */
16499
16500                 switch (o->op_type) {
16501                 case OP_PADSV:
16502                     /* it may be a lexical var index */
16503                     ASSUME(!(o->op_flags & ~(OPf_WANT|OPf_PARENS
16504                                             |OPf_REF|OPf_MOD|OPf_SPECIAL)));
16505                     ASSUME(!(o->op_private &
16506                             ~(OPpPAD_STATE|OPpDEREF|OPpLVAL_INTRO)));
16507
16508                     if (   OP_GIMME(o,0) == G_SCALAR
16509                         && !(o->op_flags & (OPf_REF|OPf_MOD))
16510                         && o->op_private == 0)
16511                     {
16512                         if (pass)
16513                             arg->pad_offset = o->op_targ;
16514                         arg++;
16515                         index_type = MDEREF_INDEX_padsv;
16516                         o = o->op_next;
16517                     }
16518                     break;
16519
16520                 case OP_CONST:
16521                     if (next_is_hash) {
16522                         /* it's a constant hash index */
16523                         if (!(SvFLAGS(cSVOPo_sv) & (SVf_IOK|SVf_NOK|SVf_POK)))
16524                             /* "use constant foo => FOO; $h{+foo}" for
16525                              * some weird FOO, can leave you with constants
16526                              * that aren't simple strings. It's not worth
16527                              * the extra hassle for those edge cases */
16528                             break;
16529
16530                         {
16531                             UNOP *rop = NULL;
16532                             OP * helem_op = o->op_next;
16533
16534                             ASSUME(   helem_op->op_type == OP_HELEM
16535                                    || helem_op->op_type == OP_NULL
16536                                    || pass == 0);
16537                             if (helem_op->op_type == OP_HELEM) {
16538                                 rop = (UNOP*)(((BINOP*)helem_op)->op_first);
16539                                 if (   helem_op->op_private & OPpLVAL_INTRO
16540                                     || rop->op_type != OP_RV2HV
16541                                 )
16542                                     rop = NULL;
16543                             }
16544                             /* on first pass just check; on second pass
16545                              * hekify */
16546                             S_check_hash_fields_and_hekify(aTHX_ rop, cSVOPo,
16547                                                             pass);
16548                         }
16549
16550                         if (pass) {
16551 #ifdef USE_ITHREADS
16552                             /* Relocate sv to the pad for thread safety */
16553                             op_relocate_sv(&cSVOPo->op_sv, &o->op_targ);
16554                             arg->pad_offset = o->op_targ;
16555                             o->op_targ = 0;
16556 #else
16557                             arg->sv = cSVOPx_sv(o);
16558 #endif
16559                         }
16560                     }
16561                     else {
16562                         /* it's a constant array index */
16563                         IV iv;
16564                         SV *ix_sv = cSVOPo->op_sv;
16565                         if (!SvIOK(ix_sv))
16566                             break;
16567                         iv = SvIV(ix_sv);
16568
16569                         if (   action_count == 0
16570                             && iv >= -128
16571                             && iv <= 127
16572                             && (   action == MDEREF_AV_padav_aelem
16573                                 || action == MDEREF_AV_gvav_aelem)
16574                         )
16575                             maybe_aelemfast = TRUE;
16576
16577                         if (pass) {
16578                             arg->iv = iv;
16579                             SvREFCNT_dec_NN(cSVOPo->op_sv);
16580                         }
16581                     }
16582                     if (pass)
16583                         /* we've taken ownership of the SV */
16584                         cSVOPo->op_sv = NULL;
16585                     arg++;
16586                     index_type = MDEREF_INDEX_const;
16587                     o = o->op_next;
16588                     break;
16589
16590                 case OP_GV:
16591                     /* it may be a package var index */
16592
16593                     ASSUME(!(o->op_flags & ~(OPf_WANT|OPf_PARENS|OPf_SPECIAL)));
16594                     ASSUME(!(o->op_private & ~(OPpEARLY_CV)));
16595                     if (  (o->op_flags & ~(OPf_PARENS|OPf_SPECIAL)) != OPf_WANT_SCALAR
16596                         || o->op_private != 0
16597                     )
16598                         break;
16599
16600                     kid = o->op_next;
16601                     if (kid->op_type != OP_RV2SV)
16602                         break;
16603
16604                     ASSUME(!(kid->op_flags &
16605                             ~(OPf_WANT|OPf_KIDS|OPf_MOD|OPf_REF
16606                              |OPf_SPECIAL|OPf_PARENS)));
16607                     ASSUME(!(kid->op_private &
16608                                     ~(OPpARG1_MASK
16609                                      |OPpHINT_STRICT_REFS|OPpOUR_INTRO
16610                                      |OPpDEREF|OPpLVAL_INTRO)));
16611                     if(   (kid->op_flags &~ OPf_PARENS)
16612                             != (OPf_WANT_SCALAR|OPf_KIDS)
16613                        || (kid->op_private & ~(OPpARG1_MASK|HINT_STRICT_REFS))
16614                     )
16615                         break;
16616
16617                     if (pass) {
16618 #ifdef USE_ITHREADS
16619                         arg->pad_offset = cPADOPx(o)->op_padix;
16620                         /* stop it being swiped when nulled */
16621                         cPADOPx(o)->op_padix = 0;
16622 #else
16623                         arg->sv = cSVOPx(o)->op_sv;
16624                         cSVOPo->op_sv = NULL;
16625 #endif
16626                     }
16627                     arg++;
16628                     index_type = MDEREF_INDEX_gvsv;
16629                     o = kid->op_next;
16630                     break;
16631
16632                 } /* switch */
16633             } /* action_count != index_skip */
16634
16635             action |= index_type;
16636
16637
16638             /* at this point we have either:
16639              *   * detected what looks like a simple index expression,
16640              *     and expect the next op to be an [ah]elem, or
16641              *     an nulled  [ah]elem followed by a delete or exists;
16642              *  * found a more complex expression, so something other
16643              *    than the above follows.
16644              */
16645
16646             /* possibly an optimised away [ah]elem (where op_next is
16647              * exists or delete) */
16648             if (o->op_type == OP_NULL)
16649                 o = o->op_next;
16650
16651             /* at this point we're looking for an OP_AELEM, OP_HELEM,
16652              * OP_EXISTS or OP_DELETE */
16653
16654             /* if a custom array/hash access checker is in scope,
16655              * abandon optimisation attempt */
16656             if (  (o->op_type == OP_AELEM || o->op_type == OP_HELEM)
16657                && PL_check[o->op_type] != Perl_ck_null)
16658                 return;
16659             /* similarly for customised exists and delete */
16660             if (  (o->op_type == OP_EXISTS)
16661                && PL_check[o->op_type] != Perl_ck_exists)
16662                 return;
16663             if (  (o->op_type == OP_DELETE)
16664                && PL_check[o->op_type] != Perl_ck_delete)
16665                 return;
16666
16667             if (   o->op_type != OP_AELEM
16668                 || (o->op_private &
16669                       (OPpLVAL_INTRO|OPpLVAL_DEFER|OPpDEREF|OPpMAYBE_LVSUB))
16670                 )
16671                 maybe_aelemfast = FALSE;
16672
16673             /* look for aelem/helem/exists/delete. If it's not the last elem
16674              * lookup, it *must* have OPpDEREF_AV/HV, but not many other
16675              * flags; if it's the last, then it mustn't have
16676              * OPpDEREF_AV/HV, but may have lots of other flags, like
16677              * OPpLVAL_INTRO etc
16678              */
16679
16680             if (   index_type == MDEREF_INDEX_none
16681                 || (   o->op_type != OP_AELEM  && o->op_type != OP_HELEM
16682                     && o->op_type != OP_EXISTS && o->op_type != OP_DELETE)
16683             )
16684                 ok = FALSE;
16685             else {
16686                 /* we have aelem/helem/exists/delete with valid simple index */
16687
16688                 is_deref =    (o->op_type == OP_AELEM || o->op_type == OP_HELEM)
16689                            && (   (o->op_private & OPpDEREF) == OPpDEREF_AV
16690                                || (o->op_private & OPpDEREF) == OPpDEREF_HV);
16691
16692                 /* This doesn't make much sense but is legal:
16693                  *    @{ local $x[0][0] } = 1
16694                  * Since scope exit will undo the autovivification,
16695                  * don't bother in the first place. The OP_LEAVE
16696                  * assertion is in case there are other cases of both
16697                  * OPpLVAL_INTRO and OPpDEREF which don't include a scope
16698                  * exit that would undo the local - in which case this
16699                  * block of code would need rethinking.
16700                  */
16701                 if (is_deref && (o->op_private & OPpLVAL_INTRO)) {
16702 #ifdef DEBUGGING
16703                     OP *n = o->op_next;
16704                     while (n && (  n->op_type == OP_NULL
16705                                 || n->op_type == OP_LIST
16706                                 || n->op_type == OP_SCALAR))
16707                         n = n->op_next;
16708                     assert(n && n->op_type == OP_LEAVE);
16709 #endif
16710                     o->op_private &= ~OPpDEREF;
16711                     is_deref = FALSE;
16712                 }
16713
16714                 if (is_deref) {
16715                     ASSUME(!(o->op_flags &
16716                                  ~(OPf_WANT|OPf_KIDS|OPf_MOD|OPf_PARENS)));
16717                     ASSUME(!(o->op_private & ~(OPpARG2_MASK|OPpDEREF)));
16718
16719                     ok =    (o->op_flags &~ OPf_PARENS)
16720                                == (OPf_WANT_SCALAR|OPf_KIDS|OPf_MOD)
16721                          && !(o->op_private & ~(OPpDEREF|OPpARG2_MASK));
16722                 }
16723                 else if (o->op_type == OP_EXISTS) {
16724                     ASSUME(!(o->op_flags & ~(OPf_WANT|OPf_KIDS|OPf_PARENS
16725                                 |OPf_REF|OPf_MOD|OPf_SPECIAL)));
16726                     ASSUME(!(o->op_private & ~(OPpARG1_MASK|OPpEXISTS_SUB)));
16727                     ok =  !(o->op_private & ~OPpARG1_MASK);
16728                 }
16729                 else if (o->op_type == OP_DELETE) {
16730                     ASSUME(!(o->op_flags & ~(OPf_WANT|OPf_KIDS|OPf_PARENS
16731                                 |OPf_REF|OPf_MOD|OPf_SPECIAL)));
16732                     ASSUME(!(o->op_private &
16733                                     ~(OPpARG1_MASK|OPpSLICE|OPpLVAL_INTRO)));
16734                     /* don't handle slices or 'local delete'; the latter
16735                      * is fairly rare, and has a complex runtime */
16736                     ok =  !(o->op_private & ~OPpARG1_MASK);
16737                     if (OP_TYPE_IS_OR_WAS(cUNOPo->op_first, OP_AELEM))
16738                         /* skip handling run-tome error */
16739                         ok = (ok && cBOOL(o->op_flags & OPf_SPECIAL));
16740                 }
16741                 else {
16742                     ASSUME(o->op_type == OP_AELEM || o->op_type == OP_HELEM);
16743                     ASSUME(!(o->op_flags & ~(OPf_WANT|OPf_KIDS|OPf_MOD
16744                                             |OPf_PARENS|OPf_REF|OPf_SPECIAL)));
16745                     ASSUME(!(o->op_private & ~(OPpARG2_MASK|OPpMAYBE_LVSUB
16746                                     |OPpLVAL_DEFER|OPpDEREF|OPpLVAL_INTRO)));
16747                     ok = (o->op_private & OPpDEREF) != OPpDEREF_SV;
16748                 }
16749             }
16750
16751             if (ok) {
16752                 if (!first_elem_op)
16753                     first_elem_op = o;
16754                 top_op = o;
16755                 if (is_deref) {
16756                     next_is_hash = cBOOL((o->op_private & OPpDEREF) == OPpDEREF_HV);
16757                     o = o->op_next;
16758                 }
16759                 else {
16760                     is_last = TRUE;
16761                     action |= MDEREF_FLAG_last;
16762                 }
16763             }
16764             else {
16765                 /* at this point we have something that started
16766                  * promisingly enough (with rv2av or whatever), but failed
16767                  * to find a simple index followed by an
16768                  * aelem/helem/exists/delete. If this is the first action,
16769                  * give up; but if we've already seen at least one
16770                  * aelem/helem, then keep them and add a new action with
16771                  * MDEREF_INDEX_none, which causes it to do the vivify
16772                  * from the end of the previous lookup, and do the deref,
16773                  * but stop at that point. So $a[0][expr] will do one
16774                  * av_fetch, vivify and deref, then continue executing at
16775                  * expr */
16776                 if (!action_count)
16777                     return;
16778                 is_last = TRUE;
16779                 index_skip = action_count;
16780                 action |= MDEREF_FLAG_last;
16781                 if (index_type != MDEREF_INDEX_none)
16782                     arg--;
16783             }
16784
16785             action_word |= (action << (action_ix * MDEREF_SHIFT));
16786             action_ix++;
16787             action_count++;
16788             /* if there's no space for the next action, reserve a new slot
16789              * for it *before* we start adding args for that action */
16790             if ((action_ix + 1) * MDEREF_SHIFT > UVSIZE*8) {
16791                 if (pass)
16792                     action_ptr->uv = action_word;
16793                 action_word = 0;
16794                 action_ptr = arg;
16795                 arg++;
16796                 action_ix = 0;
16797             }
16798         } /* while !is_last */
16799
16800         /* success! */
16801
16802         if (!action_ix)
16803             /* slot reserved for next action word not now needed */
16804             arg--;
16805         else if (pass)
16806             action_ptr->uv = action_word;
16807
16808         if (pass) {
16809             OP *mderef;
16810             OP *p, *q;
16811
16812             mderef = newUNOP_AUX(OP_MULTIDEREF, 0, NULL, arg_buf);
16813             if (index_skip == -1) {
16814                 mderef->op_flags = o->op_flags
16815                         & (OPf_WANT|OPf_MOD|(next_is_hash ? OPf_SPECIAL : 0));
16816                 if (o->op_type == OP_EXISTS)
16817                     mderef->op_private = OPpMULTIDEREF_EXISTS;
16818                 else if (o->op_type == OP_DELETE)
16819                     mderef->op_private = OPpMULTIDEREF_DELETE;
16820                 else
16821                     mderef->op_private = o->op_private
16822                         & (OPpMAYBE_LVSUB|OPpLVAL_DEFER|OPpLVAL_INTRO);
16823             }
16824             /* accumulate strictness from every level (although I don't think
16825              * they can actually vary) */
16826             mderef->op_private |= hints;
16827
16828             /* integrate the new multideref op into the optree and the
16829              * op_next chain.
16830              *
16831              * In general an op like aelem or helem has two child
16832              * sub-trees: the aggregate expression (a_expr) and the
16833              * index expression (i_expr):
16834              *
16835              *     aelem
16836              *       |
16837              *     a_expr - i_expr
16838              *
16839              * The a_expr returns an AV or HV, while the i-expr returns an
16840              * index. In general a multideref replaces most or all of a
16841              * multi-level tree, e.g.
16842              *
16843              *     exists
16844              *       |
16845              *     ex-aelem
16846              *       |
16847              *     rv2av  - i_expr1
16848              *       |
16849              *     helem
16850              *       |
16851              *     rv2hv  - i_expr2
16852              *       |
16853              *     aelem
16854              *       |
16855              *     a_expr - i_expr3
16856              *
16857              * With multideref, all the i_exprs will be simple vars or
16858              * constants, except that i_expr1 may be arbitrary in the case
16859              * of MDEREF_INDEX_none.
16860              *
16861              * The bottom-most a_expr will be either:
16862              *   1) a simple var (so padXv or gv+rv2Xv);
16863              *   2) a simple scalar var dereferenced (e.g. $r->[0]):
16864              *      so a simple var with an extra rv2Xv;
16865              *   3) or an arbitrary expression.
16866              *
16867              * 'start', the first op in the execution chain, will point to
16868              *   1),2): the padXv or gv op;
16869              *   3):    the rv2Xv which forms the last op in the a_expr
16870              *          execution chain, and the top-most op in the a_expr
16871              *          subtree.
16872              *
16873              * For all cases, the 'start' node is no longer required,
16874              * but we can't free it since one or more external nodes
16875              * may point to it. E.g. consider
16876              *     $h{foo} = $a ? $b : $c
16877              * Here, both the op_next and op_other branches of the
16878              * cond_expr point to the gv[*h] of the hash expression, so
16879              * we can't free the 'start' op.
16880              *
16881              * For expr->[...], we need to save the subtree containing the
16882              * expression; for the other cases, we just need to save the
16883              * start node.
16884              * So in all cases, we null the start op and keep it around by
16885              * making it the child of the multideref op; for the expr->
16886              * case, the expr will be a subtree of the start node.
16887              *
16888              * So in the simple 1,2 case the  optree above changes to
16889              *
16890              *     ex-exists
16891              *       |
16892              *     multideref
16893              *       |
16894              *     ex-gv (or ex-padxv)
16895              *
16896              *  with the op_next chain being
16897              *
16898              *  -> ex-gv -> multideref -> op-following-ex-exists ->
16899              *
16900              *  In the 3 case, we have
16901              *
16902              *     ex-exists
16903              *       |
16904              *     multideref
16905              *       |
16906              *     ex-rv2xv
16907              *       |
16908              *    rest-of-a_expr
16909              *      subtree
16910              *
16911              *  and
16912              *
16913              *  -> rest-of-a_expr subtree ->
16914              *    ex-rv2xv -> multideref -> op-following-ex-exists ->
16915              *
16916              *
16917              * Where the last i_expr is non-simple (i.e. MDEREF_INDEX_none,
16918              * e.g. $a[0]{foo}[$x+1], the next rv2xv is nulled and the
16919              * multideref attached as the child, e.g.
16920              *
16921              *     exists
16922              *       |
16923              *     ex-aelem
16924              *       |
16925              *     ex-rv2av  - i_expr1
16926              *       |
16927              *     multideref
16928              *       |
16929              *     ex-whatever
16930              *
16931              */
16932
16933             /* if we free this op, don't free the pad entry */
16934             if (reset_start_targ)
16935                 start->op_targ = 0;
16936
16937
16938             /* Cut the bit we need to save out of the tree and attach to
16939              * the multideref op, then free the rest of the tree */
16940
16941             /* find parent of node to be detached (for use by splice) */
16942             p = first_elem_op;
16943             if (   orig_action == MDEREF_AV_pop_rv2av_aelem
16944                 || orig_action == MDEREF_HV_pop_rv2hv_helem)
16945             {
16946                 /* there is an arbitrary expression preceding us, e.g.
16947                  * expr->[..]? so we need to save the 'expr' subtree */
16948                 if (p->op_type == OP_EXISTS || p->op_type == OP_DELETE)
16949                     p = cUNOPx(p)->op_first;
16950                 ASSUME(   start->op_type == OP_RV2AV
16951                        || start->op_type == OP_RV2HV);
16952             }
16953             else {
16954                 /* either a padXv or rv2Xv+gv, maybe with an ex-Xelem
16955                  * above for exists/delete. */
16956                 while (   (p->op_flags & OPf_KIDS)
16957                        && cUNOPx(p)->op_first != start
16958                 )
16959                     p = cUNOPx(p)->op_first;
16960             }
16961             ASSUME(cUNOPx(p)->op_first == start);
16962
16963             /* detach from main tree, and re-attach under the multideref */
16964             op_sibling_splice(mderef, NULL, 0,
16965                     op_sibling_splice(p, NULL, 1, NULL));
16966             op_null(start);
16967
16968             start->op_next = mderef;
16969
16970             mderef->op_next = index_skip == -1 ? o->op_next : o;
16971
16972             /* excise and free the original tree, and replace with
16973              * the multideref op */
16974             p = op_sibling_splice(top_op, NULL, -1, mderef);
16975             while (p) {
16976                 q = OpSIBLING(p);
16977                 op_free(p);
16978                 p = q;
16979             }
16980             op_null(top_op);
16981         }
16982         else {
16983             Size_t size = arg - arg_buf;
16984
16985             if (maybe_aelemfast && action_count == 1)
16986                 return;
16987
16988             arg_buf = (UNOP_AUX_item*)PerlMemShared_malloc(
16989                                 sizeof(UNOP_AUX_item) * (size + 1));
16990             /* for dumping etc: store the length in a hidden first slot;
16991              * we set the op_aux pointer to the second slot */
16992             arg_buf->uv = size;
16993             arg_buf++;
16994         }
16995     } /* for (pass = ...) */
16996 }
16997
16998 /* See if the ops following o are such that o will always be executed in
16999  * boolean context: that is, the SV which o pushes onto the stack will
17000  * only ever be consumed by later ops via SvTRUE(sv) or similar.
17001  * If so, set a suitable private flag on o. Normally this will be
17002  * bool_flag; but see below why maybe_flag is needed too.
17003  *
17004  * Typically the two flags you pass will be the generic OPpTRUEBOOL and
17005  * OPpMAYBE_TRUEBOOL, buts it's possible that for some ops those bits may
17006  * already be taken, so you'll have to give that op two different flags.
17007  *
17008  * More explanation of 'maybe_flag' and 'safe_and' parameters.
17009  * The binary logical ops &&, ||, // (plus 'if' and 'unless' which use
17010  * those underlying ops) short-circuit, which means that rather than
17011  * necessarily returning a truth value, they may return the LH argument,
17012  * which may not be boolean. For example in $x = (keys %h || -1), keys
17013  * should return a key count rather than a boolean, even though its
17014  * sort-of being used in boolean context.
17015  *
17016  * So we only consider such logical ops to provide boolean context to
17017  * their LH argument if they themselves are in void or boolean context.
17018  * However, sometimes the context isn't known until run-time. In this
17019  * case the op is marked with the maybe_flag flag it.
17020  *
17021  * Consider the following.
17022  *
17023  *     sub f { ....;  if (%h) { .... } }
17024  *
17025  * This is actually compiled as
17026  *
17027  *     sub f { ....;  %h && do { .... } }
17028  *
17029  * Here we won't know until runtime whether the final statement (and hence
17030  * the &&) is in void context and so is safe to return a boolean value.
17031  * So mark o with maybe_flag rather than the bool_flag.
17032  * Note that there is cost associated with determining context at runtime
17033  * (e.g. a call to block_gimme()), so it may not be worth setting (at
17034  * compile time) and testing (at runtime) maybe_flag if the scalar verses
17035  * boolean costs savings are marginal.
17036  *
17037  * However, we can do slightly better with && (compared to || and //):
17038  * this op only returns its LH argument when that argument is false. In
17039  * this case, as long as the op promises to return a false value which is
17040  * valid in both boolean and scalar contexts, we can mark an op consumed
17041  * by && with bool_flag rather than maybe_flag.
17042  * For example as long as pp_padhv and pp_rv2hv return &PL_sv_zero rather
17043  * than &PL_sv_no for a false result in boolean context, then it's safe. An
17044  * op which promises to handle this case is indicated by setting safe_and
17045  * to true.
17046  */
17047
17048 static void
17049 S_check_for_bool_cxt(OP*o, bool safe_and, U8 bool_flag, U8 maybe_flag)
17050 {
17051     OP *lop;
17052     U8 flag = 0;
17053
17054     assert((o->op_flags & OPf_WANT) == OPf_WANT_SCALAR);
17055
17056     /* OPpTARGET_MY and boolean context probably don't mix well.
17057      * If someone finds a valid use case, maybe add an extra flag to this
17058      * function which indicates its safe to do so for this op? */
17059     assert(!(   (PL_opargs[o->op_type] & OA_TARGLEX)
17060              && (o->op_private & OPpTARGET_MY)));
17061
17062     lop = o->op_next;
17063
17064     while (lop) {
17065         switch (lop->op_type) {
17066         case OP_NULL:
17067         case OP_SCALAR:
17068             break;
17069
17070         /* these two consume the stack argument in the scalar case,
17071          * and treat it as a boolean in the non linenumber case */
17072         case OP_FLIP:
17073         case OP_FLOP:
17074             if (   ((lop->op_flags & OPf_WANT) == OPf_WANT_LIST)
17075                 || (lop->op_private & OPpFLIP_LINENUM))
17076             {
17077                 lop = NULL;
17078                 break;
17079             }
17080             /* FALLTHROUGH */
17081         /* these never leave the original value on the stack */
17082         case OP_NOT:
17083         case OP_XOR:
17084         case OP_COND_EXPR:
17085         case OP_GREPWHILE:
17086             flag = bool_flag;
17087             lop = NULL;
17088             break;
17089
17090         /* OR DOR and AND evaluate their arg as a boolean, but then may
17091          * leave the original scalar value on the stack when following the
17092          * op_next route. If not in void context, we need to ensure
17093          * that whatever follows consumes the arg only in boolean context
17094          * too.
17095          */
17096         case OP_AND:
17097             if (safe_and) {
17098                 flag = bool_flag;
17099                 lop = NULL;
17100                 break;
17101             }
17102             /* FALLTHROUGH */
17103         case OP_OR:
17104         case OP_DOR:
17105             if ((lop->op_flags & OPf_WANT) == OPf_WANT_VOID) {
17106                 flag = bool_flag;
17107                 lop = NULL;
17108             }
17109             else if (!(lop->op_flags & OPf_WANT)) {
17110                 /* unknown context - decide at runtime */
17111                 flag = maybe_flag;
17112                 lop = NULL;
17113             }
17114             break;
17115
17116         default:
17117             lop = NULL;
17118             break;
17119         }
17120
17121         if (lop)
17122             lop = lop->op_next;
17123     }
17124
17125     o->op_private |= flag;
17126 }
17127
17128
17129
17130 /* mechanism for deferring recursion in rpeep() */
17131
17132 #define MAX_DEFERRED 4
17133
17134 #define DEFER(o) \
17135   STMT_START { \
17136     if (defer_ix == (MAX_DEFERRED-1)) { \
17137         OP **defer = defer_queue[defer_base]; \
17138         CALL_RPEEP(*defer); \
17139         S_prune_chain_head(defer); \
17140         defer_base = (defer_base + 1) % MAX_DEFERRED; \
17141         defer_ix--; \
17142     } \
17143     defer_queue[(defer_base + ++defer_ix) % MAX_DEFERRED] = &(o); \
17144   } STMT_END
17145
17146 #define IS_AND_OP(o)   (o->op_type == OP_AND)
17147 #define IS_OR_OP(o)    (o->op_type == OP_OR)
17148
17149
17150 /* A peephole optimizer.  We visit the ops in the order they're to execute.
17151  * See the comments at the top of this file for more details about when
17152  * peep() is called */
17153
17154 void
17155 Perl_rpeep(pTHX_ OP *o)
17156 {
17157     OP* oldop = NULL;
17158     OP* oldoldop = NULL;
17159     OP** defer_queue[MAX_DEFERRED]; /* small queue of deferred branches */
17160     int defer_base = 0;
17161     int defer_ix = -1;
17162
17163     if (!o || o->op_opt)
17164         return;
17165
17166     assert(o->op_type != OP_FREED);
17167
17168     ENTER;
17169     SAVEOP();
17170     SAVEVPTR(PL_curcop);
17171     for (;; o = o->op_next) {
17172         if (o && o->op_opt)
17173             o = NULL;
17174         if (!o) {
17175             while (defer_ix >= 0) {
17176                 OP **defer =
17177                         defer_queue[(defer_base + defer_ix--) % MAX_DEFERRED];
17178                 CALL_RPEEP(*defer);
17179                 S_prune_chain_head(defer);
17180             }
17181             break;
17182         }
17183
17184       redo:
17185
17186         /* oldoldop -> oldop -> o should be a chain of 3 adjacent ops */
17187         assert(!oldoldop || oldoldop->op_next == oldop);
17188         assert(!oldop    || oldop->op_next    == o);
17189
17190         /* By default, this op has now been optimised. A couple of cases below
17191            clear this again.  */
17192         o->op_opt = 1;
17193         PL_op = o;
17194
17195         /* look for a series of 1 or more aggregate derefs, e.g.
17196          *   $a[1]{foo}[$i]{$k}
17197          * and replace with a single OP_MULTIDEREF op.
17198          * Each index must be either a const, or a simple variable,
17199          *
17200          * First, look for likely combinations of starting ops,
17201          * corresponding to (global and lexical variants of)
17202          *     $a[...]   $h{...}
17203          *     $r->[...] $r->{...}
17204          *     (preceding expression)->[...]
17205          *     (preceding expression)->{...}
17206          * and if so, call maybe_multideref() to do a full inspection
17207          * of the op chain and if appropriate, replace with an
17208          * OP_MULTIDEREF
17209          */
17210         {
17211             UV action;
17212             OP *o2 = o;
17213             U8 hints = 0;
17214
17215             switch (o2->op_type) {
17216             case OP_GV:
17217                 /* $pkg[..]   :   gv[*pkg]
17218                  * $pkg->[...]:   gv[*pkg]; rv2sv sKM/DREFAV */
17219
17220                 /* Fail if there are new op flag combinations that we're
17221                  * not aware of, rather than:
17222                  *  * silently failing to optimise, or
17223                  *  * silently optimising the flag away.
17224                  * If this ASSUME starts failing, examine what new flag
17225                  * has been added to the op, and decide whether the
17226                  * optimisation should still occur with that flag, then
17227                  * update the code accordingly. This applies to all the
17228                  * other ASSUMEs in the block of code too.
17229                  */
17230                 ASSUME(!(o2->op_flags &
17231                             ~(OPf_WANT|OPf_MOD|OPf_PARENS|OPf_SPECIAL)));
17232                 ASSUME(!(o2->op_private & ~OPpEARLY_CV));
17233
17234                 o2 = o2->op_next;
17235
17236                 if (o2->op_type == OP_RV2AV) {
17237                     action = MDEREF_AV_gvav_aelem;
17238                     goto do_deref;
17239                 }
17240
17241                 if (o2->op_type == OP_RV2HV) {
17242                     action = MDEREF_HV_gvhv_helem;
17243                     goto do_deref;
17244                 }
17245
17246                 if (o2->op_type != OP_RV2SV)
17247                     break;
17248
17249                 /* at this point we've seen gv,rv2sv, so the only valid
17250                  * construct left is $pkg->[] or $pkg->{} */
17251
17252                 ASSUME(!(o2->op_flags & OPf_STACKED));
17253                 if ((o2->op_flags & (OPf_WANT|OPf_REF|OPf_MOD|OPf_SPECIAL))
17254                             != (OPf_WANT_SCALAR|OPf_MOD))
17255                     break;
17256
17257                 ASSUME(!(o2->op_private & ~(OPpARG1_MASK|HINT_STRICT_REFS
17258                                     |OPpOUR_INTRO|OPpDEREF|OPpLVAL_INTRO)));
17259                 if (o2->op_private & (OPpOUR_INTRO|OPpLVAL_INTRO))
17260                     break;
17261                 if (   (o2->op_private & OPpDEREF) != OPpDEREF_AV
17262                     && (o2->op_private & OPpDEREF) != OPpDEREF_HV)
17263                     break;
17264
17265                 o2 = o2->op_next;
17266                 if (o2->op_type == OP_RV2AV) {
17267                     action = MDEREF_AV_gvsv_vivify_rv2av_aelem;
17268                     goto do_deref;
17269                 }
17270                 if (o2->op_type == OP_RV2HV) {
17271                     action = MDEREF_HV_gvsv_vivify_rv2hv_helem;
17272                     goto do_deref;
17273                 }
17274                 break;
17275
17276             case OP_PADSV:
17277                 /* $lex->[...]: padsv[$lex] sM/DREFAV */
17278
17279                 ASSUME(!(o2->op_flags &
17280                     ~(OPf_WANT|OPf_PARENS|OPf_REF|OPf_MOD|OPf_SPECIAL)));
17281                 if ((o2->op_flags &
17282                         (OPf_WANT|OPf_REF|OPf_MOD|OPf_SPECIAL))
17283                      != (OPf_WANT_SCALAR|OPf_MOD))
17284                     break;
17285
17286                 ASSUME(!(o2->op_private &
17287                                 ~(OPpPAD_STATE|OPpDEREF|OPpLVAL_INTRO)));
17288                 /* skip if state or intro, or not a deref */
17289                 if (      o2->op_private != OPpDEREF_AV
17290                        && o2->op_private != OPpDEREF_HV)
17291                     break;
17292
17293                 o2 = o2->op_next;
17294                 if (o2->op_type == OP_RV2AV) {
17295                     action = MDEREF_AV_padsv_vivify_rv2av_aelem;
17296                     goto do_deref;
17297                 }
17298                 if (o2->op_type == OP_RV2HV) {
17299                     action = MDEREF_HV_padsv_vivify_rv2hv_helem;
17300                     goto do_deref;
17301                 }
17302                 break;
17303
17304             case OP_PADAV:
17305             case OP_PADHV:
17306                 /*    $lex[..]:  padav[@lex:1,2] sR *
17307                  * or $lex{..}:  padhv[%lex:1,2] sR */
17308                 ASSUME(!(o2->op_flags & ~(OPf_WANT|OPf_MOD|OPf_PARENS|
17309                                             OPf_REF|OPf_SPECIAL)));
17310                 if ((o2->op_flags &
17311                         (OPf_WANT|OPf_REF|OPf_MOD|OPf_SPECIAL))
17312                      != (OPf_WANT_SCALAR|OPf_REF))
17313                     break;
17314                 if (o2->op_flags != (OPf_WANT_SCALAR|OPf_REF))
17315                     break;
17316                 /* OPf_PARENS isn't currently used in this case;
17317                  * if that changes, let us know! */
17318                 ASSUME(!(o2->op_flags & OPf_PARENS));
17319
17320                 /* at this point, we wouldn't expect any of the remaining
17321                  * possible private flags:
17322                  * OPpPAD_STATE, OPpLVAL_INTRO, OPpTRUEBOOL,
17323                  * OPpMAYBE_TRUEBOOL, OPpMAYBE_LVSUB
17324                  *
17325                  * OPpSLICEWARNING shouldn't affect runtime
17326                  */
17327                 ASSUME(!(o2->op_private & ~(OPpSLICEWARNING)));
17328
17329                 action = o2->op_type == OP_PADAV
17330                             ? MDEREF_AV_padav_aelem
17331                             : MDEREF_HV_padhv_helem;
17332                 o2 = o2->op_next;
17333                 S_maybe_multideref(aTHX_ o, o2, action, 0);
17334                 break;
17335
17336
17337             case OP_RV2AV:
17338             case OP_RV2HV:
17339                 action = o2->op_type == OP_RV2AV
17340                             ? MDEREF_AV_pop_rv2av_aelem
17341                             : MDEREF_HV_pop_rv2hv_helem;
17342                 /* FALLTHROUGH */
17343             do_deref:
17344                 /* (expr)->[...]:  rv2av sKR/1;
17345                  * (expr)->{...}:  rv2hv sKR/1; */
17346
17347                 ASSUME(o2->op_type == OP_RV2AV || o2->op_type == OP_RV2HV);
17348
17349                 ASSUME(!(o2->op_flags & ~(OPf_WANT|OPf_KIDS|OPf_PARENS
17350                                 |OPf_REF|OPf_MOD|OPf_STACKED|OPf_SPECIAL)));
17351                 if (o2->op_flags != (OPf_WANT_SCALAR|OPf_KIDS|OPf_REF))
17352                     break;
17353
17354                 /* at this point, we wouldn't expect any of these
17355                  * possible private flags:
17356                  * OPpMAYBE_LVSUB, OPpLVAL_INTRO
17357                  * OPpTRUEBOOL, OPpMAYBE_TRUEBOOL, (rv2hv only)
17358                  */
17359                 ASSUME(!(o2->op_private &
17360                     ~(OPpHINT_STRICT_REFS|OPpARG1_MASK|OPpSLICEWARNING
17361                      |OPpOUR_INTRO)));
17362                 hints |= (o2->op_private & OPpHINT_STRICT_REFS);
17363
17364                 o2 = o2->op_next;
17365
17366                 S_maybe_multideref(aTHX_ o, o2, action, hints);
17367                 break;
17368
17369             default:
17370                 break;
17371             }
17372         }
17373
17374
17375         switch (o->op_type) {
17376         case OP_DBSTATE:
17377             PL_curcop = ((COP*)o);              /* for warnings */
17378             break;
17379         case OP_NEXTSTATE:
17380             PL_curcop = ((COP*)o);              /* for warnings */
17381
17382             /* Optimise a "return ..." at the end of a sub to just be "...".
17383              * This saves 2 ops. Before:
17384              * 1  <;> nextstate(main 1 -e:1) v ->2
17385              * 4  <@> return K ->5
17386              * 2    <0> pushmark s ->3
17387              * -    <1> ex-rv2sv sK/1 ->4
17388              * 3      <#> gvsv[*cat] s ->4
17389              *
17390              * After:
17391              * -  <@> return K ->-
17392              * -    <0> pushmark s ->2
17393              * -    <1> ex-rv2sv sK/1 ->-
17394              * 2      <$> gvsv(*cat) s ->3
17395              */
17396             {
17397                 OP *next = o->op_next;
17398                 OP *sibling = OpSIBLING(o);
17399                 if (   OP_TYPE_IS(next, OP_PUSHMARK)
17400                     && OP_TYPE_IS(sibling, OP_RETURN)
17401                     && OP_TYPE_IS(sibling->op_next, OP_LINESEQ)
17402                     && ( OP_TYPE_IS(sibling->op_next->op_next, OP_LEAVESUB)
17403                        ||OP_TYPE_IS(sibling->op_next->op_next,
17404                                     OP_LEAVESUBLV))
17405                     && cUNOPx(sibling)->op_first == next
17406                     && OpHAS_SIBLING(next) && OpSIBLING(next)->op_next
17407                     && next->op_next
17408                 ) {
17409                     /* Look through the PUSHMARK's siblings for one that
17410                      * points to the RETURN */
17411                     OP *top = OpSIBLING(next);
17412                     while (top && top->op_next) {
17413                         if (top->op_next == sibling) {
17414                             top->op_next = sibling->op_next;
17415                             o->op_next = next->op_next;
17416                             break;
17417                         }
17418                         top = OpSIBLING(top);
17419                     }
17420                 }
17421             }
17422
17423             /* Optimise 'my $x; my $y;' into 'my ($x, $y);'
17424              *
17425              * This latter form is then suitable for conversion into padrange
17426              * later on. Convert:
17427              *
17428              *   nextstate1 -> padop1 -> nextstate2 -> padop2 -> nextstate3
17429              *
17430              * into:
17431              *
17432              *   nextstate1 ->     listop     -> nextstate3
17433              *                 /            \
17434              *         pushmark -> padop1 -> padop2
17435              */
17436             if (o->op_next && (
17437                     o->op_next->op_type == OP_PADSV
17438                  || o->op_next->op_type == OP_PADAV
17439                  || o->op_next->op_type == OP_PADHV
17440                 )
17441                 && !(o->op_next->op_private & ~OPpLVAL_INTRO)
17442                 && o->op_next->op_next && o->op_next->op_next->op_type == OP_NEXTSTATE
17443                 && o->op_next->op_next->op_next && (
17444                     o->op_next->op_next->op_next->op_type == OP_PADSV
17445                  || o->op_next->op_next->op_next->op_type == OP_PADAV
17446                  || o->op_next->op_next->op_next->op_type == OP_PADHV
17447                 )
17448                 && !(o->op_next->op_next->op_next->op_private & ~OPpLVAL_INTRO)
17449                 && o->op_next->op_next->op_next->op_next && o->op_next->op_next->op_next->op_next->op_type == OP_NEXTSTATE
17450                 && (!CopLABEL((COP*)o)) /* Don't mess with labels */
17451                 && (!CopLABEL((COP*)o->op_next->op_next)) /* ... */
17452             ) {
17453                 OP *pad1, *ns2, *pad2, *ns3, *newop, *newpm;
17454
17455                 pad1 =    o->op_next;
17456                 ns2  = pad1->op_next;
17457                 pad2 =  ns2->op_next;
17458                 ns3  = pad2->op_next;
17459
17460                 /* we assume here that the op_next chain is the same as
17461                  * the op_sibling chain */
17462                 assert(OpSIBLING(o)    == pad1);
17463                 assert(OpSIBLING(pad1) == ns2);
17464                 assert(OpSIBLING(ns2)  == pad2);
17465                 assert(OpSIBLING(pad2) == ns3);
17466
17467                 /* excise and delete ns2 */
17468                 op_sibling_splice(NULL, pad1, 1, NULL);
17469                 op_free(ns2);
17470
17471                 /* excise pad1 and pad2 */
17472                 op_sibling_splice(NULL, o, 2, NULL);
17473
17474                 /* create new listop, with children consisting of:
17475                  * a new pushmark, pad1, pad2. */
17476                 newop = newLISTOP(OP_LIST, 0, pad1, pad2);
17477                 newop->op_flags |= OPf_PARENS;
17478                 newop->op_flags = (newop->op_flags & ~OPf_WANT) | OPf_WANT_VOID;
17479
17480                 /* insert newop between o and ns3 */
17481                 op_sibling_splice(NULL, o, 0, newop);
17482
17483                 /*fixup op_next chain */
17484                 newpm = cUNOPx(newop)->op_first; /* pushmark */
17485                 o    ->op_next = newpm;
17486                 newpm->op_next = pad1;
17487                 pad1 ->op_next = pad2;
17488                 pad2 ->op_next = newop; /* listop */
17489                 newop->op_next = ns3;
17490
17491                 /* Ensure pushmark has this flag if padops do */
17492                 if (pad1->op_flags & OPf_MOD && pad2->op_flags & OPf_MOD) {
17493                     newpm->op_flags |= OPf_MOD;
17494                 }
17495
17496                 break;
17497             }
17498
17499             /* Two NEXTSTATEs in a row serve no purpose. Except if they happen
17500                to carry two labels. For now, take the easier option, and skip
17501                this optimisation if the first NEXTSTATE has a label.  */
17502             if (!CopLABEL((COP*)o) && !PERLDB_NOOPT) {
17503                 OP *nextop = o->op_next;
17504                 while (nextop) {
17505                     switch (nextop->op_type) {
17506                         case OP_NULL:
17507                         case OP_SCALAR:
17508                         case OP_LINESEQ:
17509                         case OP_SCOPE:
17510                             nextop = nextop->op_next;
17511                             continue;
17512                     }
17513                     break;
17514                 }
17515
17516                 if (nextop && (nextop->op_type == OP_NEXTSTATE)) {
17517                     op_null(o);
17518                     if (oldop)
17519                         oldop->op_next = nextop;
17520                     o = nextop;
17521                     /* Skip (old)oldop assignment since the current oldop's
17522                        op_next already points to the next op.  */
17523                     goto redo;
17524                 }
17525             }
17526             break;
17527
17528         case OP_CONCAT:
17529             if (o->op_next && o->op_next->op_type == OP_STRINGIFY) {
17530                 if (o->op_next->op_private & OPpTARGET_MY) {
17531                     if (o->op_flags & OPf_STACKED) /* chained concats */
17532                         break; /* ignore_optimization */
17533                     else {
17534                         /* assert(PL_opargs[o->op_type] & OA_TARGLEX); */
17535                         o->op_targ = o->op_next->op_targ;
17536                         o->op_next->op_targ = 0;
17537                         o->op_private |= OPpTARGET_MY;
17538                     }
17539                 }
17540                 op_null(o->op_next);
17541             }
17542             break;
17543         case OP_STUB:
17544             if ((o->op_flags & OPf_WANT) != OPf_WANT_LIST) {
17545                 break; /* Scalar stub must produce undef.  List stub is noop */
17546             }
17547             goto nothin;
17548         case OP_NULL:
17549             if (o->op_targ == OP_NEXTSTATE
17550                 || o->op_targ == OP_DBSTATE)
17551             {
17552                 PL_curcop = ((COP*)o);
17553             }
17554             /* XXX: We avoid setting op_seq here to prevent later calls
17555                to rpeep() from mistakenly concluding that optimisation
17556                has already occurred. This doesn't fix the real problem,
17557                though (See 20010220.007 (#5874)). AMS 20010719 */
17558             /* op_seq functionality is now replaced by op_opt */
17559             o->op_opt = 0;
17560             /* FALLTHROUGH */
17561         case OP_SCALAR:
17562         case OP_LINESEQ:
17563         case OP_SCOPE:
17564         nothin:
17565             if (oldop) {
17566                 oldop->op_next = o->op_next;
17567                 o->op_opt = 0;
17568                 continue;
17569             }
17570             break;
17571
17572         case OP_PUSHMARK:
17573
17574             /* Given
17575                  5 repeat/DOLIST
17576                  3   ex-list
17577                  1     pushmark
17578                  2     scalar or const
17579                  4   const[0]
17580                convert repeat into a stub with no kids.
17581              */
17582             if (o->op_next->op_type == OP_CONST
17583              || (  o->op_next->op_type == OP_PADSV
17584                 && !(o->op_next->op_private & OPpLVAL_INTRO))
17585              || (  o->op_next->op_type == OP_GV
17586                 && o->op_next->op_next->op_type == OP_RV2SV
17587                 && !(o->op_next->op_next->op_private
17588                         & (OPpLVAL_INTRO|OPpOUR_INTRO))))
17589             {
17590                 const OP *kid = o->op_next->op_next;
17591                 if (o->op_next->op_type == OP_GV)
17592                    kid = kid->op_next;
17593                 /* kid is now the ex-list.  */
17594                 if (kid->op_type == OP_NULL
17595                  && (kid = kid->op_next)->op_type == OP_CONST
17596                     /* kid is now the repeat count.  */
17597                  && kid->op_next->op_type == OP_REPEAT
17598                  && kid->op_next->op_private & OPpREPEAT_DOLIST
17599                  && (kid->op_next->op_flags & OPf_WANT) == OPf_WANT_LIST
17600                  && SvIOK(kSVOP_sv) && SvIVX(kSVOP_sv) == 0
17601                  && oldop)
17602                 {
17603                     o = kid->op_next; /* repeat */
17604                     oldop->op_next = o;
17605                     op_free(cBINOPo->op_first);
17606                     op_free(cBINOPo->op_last );
17607                     o->op_flags &=~ OPf_KIDS;
17608                     /* stub is a baseop; repeat is a binop */
17609                     STATIC_ASSERT_STMT(sizeof(OP) <= sizeof(BINOP));
17610                     OpTYPE_set(o, OP_STUB);
17611                     o->op_private = 0;
17612                     break;
17613                 }
17614             }
17615
17616             /* Convert a series of PAD ops for my vars plus support into a
17617              * single padrange op. Basically
17618              *
17619              *    pushmark -> pad[ahs]v -> pad[ahs]?v -> ... -> (list) -> rest
17620              *
17621              * becomes, depending on circumstances, one of
17622              *
17623              *    padrange  ----------------------------------> (list) -> rest
17624              *    padrange  --------------------------------------------> rest
17625              *
17626              * where all the pad indexes are sequential and of the same type
17627              * (INTRO or not).
17628              * We convert the pushmark into a padrange op, then skip
17629              * any other pad ops, and possibly some trailing ops.
17630              * Note that we don't null() the skipped ops, to make it
17631              * easier for Deparse to undo this optimisation (and none of
17632              * the skipped ops are holding any resourses). It also makes
17633              * it easier for find_uninit_var(), as it can just ignore
17634              * padrange, and examine the original pad ops.
17635              */
17636         {
17637             OP *p;
17638             OP *followop = NULL; /* the op that will follow the padrange op */
17639             U8 count = 0;
17640             U8 intro = 0;
17641             PADOFFSET base = 0; /* init only to stop compiler whining */
17642             bool gvoid = 0;     /* init only to stop compiler whining */
17643             bool defav = 0;  /* seen (...) = @_ */
17644             bool reuse = 0;  /* reuse an existing padrange op */
17645
17646             /* look for a pushmark -> gv[_] -> rv2av */
17647
17648             {
17649                 OP *rv2av, *q;
17650                 p = o->op_next;
17651                 if (   p->op_type == OP_GV
17652                     && cGVOPx_gv(p) == PL_defgv
17653                     && (rv2av = p->op_next)
17654                     && rv2av->op_type == OP_RV2AV
17655                     && !(rv2av->op_flags & OPf_REF)
17656                     && !(rv2av->op_private & (OPpLVAL_INTRO|OPpMAYBE_LVSUB))
17657                     && ((rv2av->op_flags & OPf_WANT) == OPf_WANT_LIST)
17658                 ) {
17659                     q = rv2av->op_next;
17660                     if (q->op_type == OP_NULL)
17661                         q = q->op_next;
17662                     if (q->op_type == OP_PUSHMARK) {
17663                         defav = 1;
17664                         p = q;
17665                     }
17666                 }
17667             }
17668             if (!defav) {
17669                 p = o;
17670             }
17671
17672             /* scan for PAD ops */
17673
17674             for (p = p->op_next; p; p = p->op_next) {
17675                 if (p->op_type == OP_NULL)
17676                     continue;
17677
17678                 if ((     p->op_type != OP_PADSV
17679                        && p->op_type != OP_PADAV
17680                        && p->op_type != OP_PADHV
17681                     )
17682                       /* any private flag other than INTRO? e.g. STATE */
17683                    || (p->op_private & ~OPpLVAL_INTRO)
17684                 )
17685                     break;
17686
17687                 /* let $a[N] potentially be optimised into AELEMFAST_LEX
17688                  * instead */
17689                 if (   p->op_type == OP_PADAV
17690                     && p->op_next
17691                     && p->op_next->op_type == OP_CONST
17692                     && p->op_next->op_next
17693                     && p->op_next->op_next->op_type == OP_AELEM
17694                 )
17695                     break;
17696
17697                 /* for 1st padop, note what type it is and the range
17698                  * start; for the others, check that it's the same type
17699                  * and that the targs are contiguous */
17700                 if (count == 0) {
17701                     intro = (p->op_private & OPpLVAL_INTRO);
17702                     base = p->op_targ;
17703                     gvoid = OP_GIMME(p,0) == G_VOID;
17704                 }
17705                 else {
17706                     if ((p->op_private & OPpLVAL_INTRO) != intro)
17707                         break;
17708                     /* Note that you'd normally  expect targs to be
17709                      * contiguous in my($a,$b,$c), but that's not the case
17710                      * when external modules start doing things, e.g.
17711                      * Function::Parameters */
17712                     if (p->op_targ != base + count)
17713                         break;
17714                     assert(p->op_targ == base + count);
17715                     /* Either all the padops or none of the padops should
17716                        be in void context.  Since we only do the optimisa-
17717                        tion for av/hv when the aggregate itself is pushed
17718                        on to the stack (one item), there is no need to dis-
17719                        tinguish list from scalar context.  */
17720                     if (gvoid != (OP_GIMME(p,0) == G_VOID))
17721                         break;
17722                 }
17723
17724                 /* for AV, HV, only when we're not flattening */
17725                 if (   p->op_type != OP_PADSV
17726                     && !gvoid
17727                     && !(p->op_flags & OPf_REF)
17728                 )
17729                     break;
17730
17731                 if (count >= OPpPADRANGE_COUNTMASK)
17732                     break;
17733
17734                 /* there's a biggest base we can fit into a
17735                  * SAVEt_CLEARPADRANGE in pp_padrange.
17736                  * (The sizeof() stuff will be constant-folded, and is
17737                  * intended to avoid getting "comparison is always false"
17738                  * compiler warnings. See the comments above
17739                  * MEM_WRAP_CHECK for more explanation on why we do this
17740                  * in a weird way to avoid compiler warnings.)
17741                  */
17742                 if (   intro
17743                     && (8*sizeof(base) >
17744                         8*sizeof(UV)-OPpPADRANGE_COUNTSHIFT-SAVE_TIGHT_SHIFT
17745                         ? (Size_t)base
17746                         : (UV_MAX >> (OPpPADRANGE_COUNTSHIFT+SAVE_TIGHT_SHIFT))
17747                         ) >
17748                         (UV_MAX >> (OPpPADRANGE_COUNTSHIFT+SAVE_TIGHT_SHIFT))
17749                 )
17750                     break;
17751
17752                 /* Success! We've got another valid pad op to optimise away */
17753                 count++;
17754                 followop = p->op_next;
17755             }
17756
17757             if (count < 1 || (count == 1 && !defav))
17758                 break;
17759
17760             /* pp_padrange in specifically compile-time void context
17761              * skips pushing a mark and lexicals; in all other contexts
17762              * (including unknown till runtime) it pushes a mark and the
17763              * lexicals. We must be very careful then, that the ops we
17764              * optimise away would have exactly the same effect as the
17765              * padrange.
17766              * In particular in void context, we can only optimise to
17767              * a padrange if we see the complete sequence
17768              *     pushmark, pad*v, ...., list
17769              * which has the net effect of leaving the markstack as it
17770              * was.  Not pushing onto the stack (whereas padsv does touch
17771              * the stack) makes no difference in void context.
17772              */
17773             assert(followop);
17774             if (gvoid) {
17775                 if (followop->op_type == OP_LIST
17776                         && OP_GIMME(followop,0) == G_VOID
17777                    )
17778                 {
17779                     followop = followop->op_next; /* skip OP_LIST */
17780
17781                     /* consolidate two successive my(...);'s */
17782
17783                     if (   oldoldop
17784                         && oldoldop->op_type == OP_PADRANGE
17785                         && (oldoldop->op_flags & OPf_WANT) == OPf_WANT_VOID
17786                         && (oldoldop->op_private & OPpLVAL_INTRO) == intro
17787                         && !(oldoldop->op_flags & OPf_SPECIAL)
17788                     ) {
17789                         U8 old_count;
17790                         assert(oldoldop->op_next == oldop);
17791                         assert(   oldop->op_type == OP_NEXTSTATE
17792                                || oldop->op_type == OP_DBSTATE);
17793                         assert(oldop->op_next == o);
17794
17795                         old_count
17796                             = (oldoldop->op_private & OPpPADRANGE_COUNTMASK);
17797
17798                        /* Do not assume pad offsets for $c and $d are con-
17799                           tiguous in
17800                             my ($a,$b,$c);
17801                             my ($d,$e,$f);
17802                         */
17803                         if (  oldoldop->op_targ + old_count == base
17804                            && old_count < OPpPADRANGE_COUNTMASK - count) {
17805                             base = oldoldop->op_targ;
17806                             count += old_count;
17807                             reuse = 1;
17808                         }
17809                     }
17810
17811                     /* if there's any immediately following singleton
17812                      * my var's; then swallow them and the associated
17813                      * nextstates; i.e.
17814                      *    my ($a,$b); my $c; my $d;
17815                      * is treated as
17816                      *    my ($a,$b,$c,$d);
17817                      */
17818
17819                     while (    ((p = followop->op_next))
17820                             && (  p->op_type == OP_PADSV
17821                                || p->op_type == OP_PADAV
17822                                || p->op_type == OP_PADHV)
17823                             && (p->op_flags & OPf_WANT) == OPf_WANT_VOID
17824                             && (p->op_private & OPpLVAL_INTRO) == intro
17825                             && !(p->op_private & ~OPpLVAL_INTRO)
17826                             && p->op_next
17827                             && (   p->op_next->op_type == OP_NEXTSTATE
17828                                 || p->op_next->op_type == OP_DBSTATE)
17829                             && count < OPpPADRANGE_COUNTMASK
17830                             && base + count == p->op_targ
17831                     ) {
17832                         count++;
17833                         followop = p->op_next;
17834                     }
17835                 }
17836                 else
17837                     break;
17838             }
17839
17840             if (reuse) {
17841                 assert(oldoldop->op_type == OP_PADRANGE);
17842                 oldoldop->op_next = followop;
17843                 oldoldop->op_private = (intro | count);
17844                 o = oldoldop;
17845                 oldop = NULL;
17846                 oldoldop = NULL;
17847             }
17848             else {
17849                 /* Convert the pushmark into a padrange.
17850                  * To make Deparse easier, we guarantee that a padrange was
17851                  * *always* formerly a pushmark */
17852                 assert(o->op_type == OP_PUSHMARK);
17853                 o->op_next = followop;
17854                 OpTYPE_set(o, OP_PADRANGE);
17855                 o->op_targ = base;
17856                 /* bit 7: INTRO; bit 6..0: count */
17857                 o->op_private = (intro | count);
17858                 o->op_flags = ((o->op_flags & ~(OPf_WANT|OPf_SPECIAL))
17859                               | gvoid * OPf_WANT_VOID
17860                               | (defav ? OPf_SPECIAL : 0));
17861             }
17862             break;
17863         }
17864
17865         case OP_RV2AV:
17866             if ((o->op_flags & OPf_WANT) == OPf_WANT_SCALAR)
17867                 S_check_for_bool_cxt(o, 1, OPpTRUEBOOL, 0);
17868             break;
17869
17870         case OP_RV2HV:
17871         case OP_PADHV:
17872             /*'keys %h' in void or scalar context: skip the OP_KEYS
17873              * and perform the functionality directly in the RV2HV/PADHV
17874              * op
17875              */
17876             if (o->op_flags & OPf_REF) {
17877                 OP *k = o->op_next;
17878                 U8 want = (k->op_flags & OPf_WANT);
17879                 if (   k
17880                     && k->op_type == OP_KEYS
17881                     && (   want == OPf_WANT_VOID
17882                         || want == OPf_WANT_SCALAR)
17883                     && !(k->op_private & OPpMAYBE_LVSUB)
17884                     && !(k->op_flags & OPf_MOD)
17885                 ) {
17886                     o->op_next     = k->op_next;
17887                     o->op_flags   &= ~(OPf_REF|OPf_WANT);
17888                     o->op_flags   |= want;
17889                     o->op_private |= (o->op_type == OP_PADHV ?
17890                                       OPpPADHV_ISKEYS : OPpRV2HV_ISKEYS);
17891                     /* for keys(%lex), hold onto the OP_KEYS's targ
17892                      * since padhv doesn't have its own targ to return
17893                      * an int with */
17894                     if (!(o->op_type ==OP_PADHV && want == OPf_WANT_SCALAR))
17895                         op_null(k);
17896                 }
17897             }
17898
17899             /* see if %h is used in boolean context */
17900             if ((o->op_flags & OPf_WANT) == OPf_WANT_SCALAR)
17901                 S_check_for_bool_cxt(o, 1, OPpTRUEBOOL, OPpMAYBE_TRUEBOOL);
17902
17903
17904             if (o->op_type != OP_PADHV)
17905                 break;
17906             /* FALLTHROUGH */
17907         case OP_PADAV:
17908             if (   o->op_type == OP_PADAV
17909                 && (o->op_flags & OPf_WANT) == OPf_WANT_SCALAR
17910             )
17911                 S_check_for_bool_cxt(o, 1, OPpTRUEBOOL, 0);
17912             /* FALLTHROUGH */
17913         case OP_PADSV:
17914             /* Skip over state($x) in void context.  */
17915             if (oldop && o->op_private == (OPpPAD_STATE|OPpLVAL_INTRO)
17916              && (o->op_flags & OPf_WANT) == OPf_WANT_VOID)
17917             {
17918                 oldop->op_next = o->op_next;
17919                 goto redo_nextstate;
17920             }
17921             if (o->op_type != OP_PADAV)
17922                 break;
17923             /* FALLTHROUGH */
17924         case OP_GV:
17925             if (o->op_type == OP_PADAV || o->op_next->op_type == OP_RV2AV) {
17926                 OP* const pop = (o->op_type == OP_PADAV) ?
17927                             o->op_next : o->op_next->op_next;
17928                 IV i;
17929                 if (pop && pop->op_type == OP_CONST &&
17930                     ((PL_op = pop->op_next)) &&
17931                     pop->op_next->op_type == OP_AELEM &&
17932                     !(pop->op_next->op_private &
17933                       (OPpLVAL_INTRO|OPpLVAL_DEFER|OPpDEREF|OPpMAYBE_LVSUB)) &&
17934                     (i = SvIV(((SVOP*)pop)->op_sv)) >= -128 && i <= 127)
17935                 {
17936                     GV *gv;
17937                     if (cSVOPx(pop)->op_private & OPpCONST_STRICT)
17938                         no_bareword_allowed(pop);
17939                     if (o->op_type == OP_GV)
17940                         op_null(o->op_next);
17941                     op_null(pop->op_next);
17942                     op_null(pop);
17943                     o->op_flags |= pop->op_next->op_flags & OPf_MOD;
17944                     o->op_next = pop->op_next->op_next;
17945                     o->op_ppaddr = PL_ppaddr[OP_AELEMFAST];
17946                     o->op_private = (U8)i;
17947                     if (o->op_type == OP_GV) {
17948                         gv = cGVOPo_gv;
17949                         GvAVn(gv);
17950                         o->op_type = OP_AELEMFAST;
17951                     }
17952                     else
17953                         o->op_type = OP_AELEMFAST_LEX;
17954                 }
17955                 if (o->op_type != OP_GV)
17956                     break;
17957             }
17958
17959             /* Remove $foo from the op_next chain in void context.  */
17960             if (oldop
17961              && (  o->op_next->op_type == OP_RV2SV
17962                 || o->op_next->op_type == OP_RV2AV
17963                 || o->op_next->op_type == OP_RV2HV  )
17964              && (o->op_next->op_flags & OPf_WANT) == OPf_WANT_VOID
17965              && !(o->op_next->op_private & OPpLVAL_INTRO))
17966             {
17967                 oldop->op_next = o->op_next->op_next;
17968                 /* Reprocess the previous op if it is a nextstate, to
17969                    allow double-nextstate optimisation.  */
17970               redo_nextstate:
17971                 if (oldop->op_type == OP_NEXTSTATE) {
17972                     oldop->op_opt = 0;
17973                     o = oldop;
17974                     oldop = oldoldop;
17975                     oldoldop = NULL;
17976                     goto redo;
17977                 }
17978                 o = oldop->op_next;
17979                 goto redo;
17980             }
17981             else if (o->op_next->op_type == OP_RV2SV) {
17982                 if (!(o->op_next->op_private & OPpDEREF)) {
17983                     op_null(o->op_next);
17984                     o->op_private |= o->op_next->op_private & (OPpLVAL_INTRO
17985                                                                | OPpOUR_INTRO);
17986                     o->op_next = o->op_next->op_next;
17987                     OpTYPE_set(o, OP_GVSV);
17988                 }
17989             }
17990             else if (o->op_next->op_type == OP_READLINE
17991                     && o->op_next->op_next->op_type == OP_CONCAT
17992                     && (o->op_next->op_next->op_flags & OPf_STACKED))
17993             {
17994                 /* Turn "$a .= <FH>" into an OP_RCATLINE. AMS 20010917 */
17995                 OpTYPE_set(o, OP_RCATLINE);
17996                 o->op_flags |= OPf_STACKED;
17997                 op_null(o->op_next->op_next);
17998                 op_null(o->op_next);
17999             }
18000
18001             break;
18002
18003         case OP_NOT:
18004             break;
18005
18006         case OP_AND:
18007         case OP_OR:
18008         case OP_DOR:
18009         case OP_CMPCHAIN_AND:
18010         case OP_PUSHDEFER:
18011             while (cLOGOP->op_other->op_type == OP_NULL)
18012                 cLOGOP->op_other = cLOGOP->op_other->op_next;
18013             while (o->op_next && (   o->op_type == o->op_next->op_type
18014                                   || o->op_next->op_type == OP_NULL))
18015                 o->op_next = o->op_next->op_next;
18016
18017             /* If we're an OR and our next is an AND in void context, we'll
18018                follow its op_other on short circuit, same for reverse.
18019                We can't do this with OP_DOR since if it's true, its return
18020                value is the underlying value which must be evaluated
18021                by the next op. */
18022             if (o->op_next &&
18023                 (
18024                     (IS_AND_OP(o) && IS_OR_OP(o->op_next))
18025                  || (IS_OR_OP(o) && IS_AND_OP(o->op_next))
18026                 )
18027                 && (o->op_next->op_flags & OPf_WANT) == OPf_WANT_VOID
18028             ) {
18029                 o->op_next = ((LOGOP*)o->op_next)->op_other;
18030             }
18031             DEFER(cLOGOP->op_other);
18032             o->op_opt = 1;
18033             break;
18034
18035         case OP_GREPWHILE:
18036             if ((o->op_flags & OPf_WANT) == OPf_WANT_SCALAR)
18037                 S_check_for_bool_cxt(o, 1, OPpTRUEBOOL, 0);
18038             /* FALLTHROUGH */
18039         case OP_COND_EXPR:
18040         case OP_MAPWHILE:
18041         case OP_ANDASSIGN:
18042         case OP_ORASSIGN:
18043         case OP_DORASSIGN:
18044         case OP_RANGE:
18045         case OP_ONCE:
18046         case OP_ARGDEFELEM:
18047             while (cLOGOP->op_other->op_type == OP_NULL)
18048                 cLOGOP->op_other = cLOGOP->op_other->op_next;
18049             DEFER(cLOGOP->op_other);
18050             break;
18051
18052         case OP_ENTERLOOP:
18053         case OP_ENTERITER:
18054             while (cLOOP->op_redoop->op_type == OP_NULL)
18055                 cLOOP->op_redoop = cLOOP->op_redoop->op_next;
18056             while (cLOOP->op_nextop->op_type == OP_NULL)
18057                 cLOOP->op_nextop = cLOOP->op_nextop->op_next;
18058             while (cLOOP->op_lastop->op_type == OP_NULL)
18059                 cLOOP->op_lastop = cLOOP->op_lastop->op_next;
18060             /* a while(1) loop doesn't have an op_next that escapes the
18061              * loop, so we have to explicitly follow the op_lastop to
18062              * process the rest of the code */
18063             DEFER(cLOOP->op_lastop);
18064             break;
18065
18066         case OP_ENTERTRY:
18067             assert(cLOGOPo->op_other->op_type == OP_LEAVETRY);
18068             DEFER(cLOGOPo->op_other);
18069             break;
18070
18071         case OP_ENTERTRYCATCH:
18072             assert(cLOGOPo->op_other->op_type == OP_CATCH);
18073             /* catch body is the ->op_other of the OP_CATCH */
18074             DEFER(cLOGOPx(cLOGOPo->op_other)->op_other);
18075             break;
18076
18077         case OP_SUBST:
18078             if ((o->op_flags & OPf_WANT) == OPf_WANT_SCALAR)
18079                 S_check_for_bool_cxt(o, 1, OPpTRUEBOOL, 0);
18080             assert(!(cPMOP->op_pmflags & PMf_ONCE));
18081             while (cPMOP->op_pmstashstartu.op_pmreplstart &&
18082                    cPMOP->op_pmstashstartu.op_pmreplstart->op_type == OP_NULL)
18083                 cPMOP->op_pmstashstartu.op_pmreplstart
18084                     = cPMOP->op_pmstashstartu.op_pmreplstart->op_next;
18085             DEFER(cPMOP->op_pmstashstartu.op_pmreplstart);
18086             break;
18087
18088         case OP_SORT: {
18089             OP *oright;
18090
18091             if (o->op_flags & OPf_SPECIAL) {
18092                 /* first arg is a code block */
18093                 OP * const nullop = OpSIBLING(cLISTOP->op_first);
18094                 OP * kid          = cUNOPx(nullop)->op_first;
18095
18096                 assert(nullop->op_type == OP_NULL);
18097                 assert(kid->op_type == OP_SCOPE
18098                  || (kid->op_type == OP_NULL && kid->op_targ == OP_LEAVE));
18099                 /* since OP_SORT doesn't have a handy op_other-style
18100                  * field that can point directly to the start of the code
18101                  * block, store it in the otherwise-unused op_next field
18102                  * of the top-level OP_NULL. This will be quicker at
18103                  * run-time, and it will also allow us to remove leading
18104                  * OP_NULLs by just messing with op_nexts without
18105                  * altering the basic op_first/op_sibling layout. */
18106                 kid = kLISTOP->op_first;
18107                 assert(
18108                       (kid->op_type == OP_NULL
18109                       && (  kid->op_targ == OP_NEXTSTATE
18110                          || kid->op_targ == OP_DBSTATE  ))
18111                     || kid->op_type == OP_STUB
18112                     || kid->op_type == OP_ENTER
18113                     || (PL_parser && PL_parser->error_count));
18114                 nullop->op_next = kid->op_next;
18115                 DEFER(nullop->op_next);
18116             }
18117
18118             /* check that RHS of sort is a single plain array */
18119             oright = cUNOPo->op_first;
18120             if (!oright || oright->op_type != OP_PUSHMARK)
18121                 break;
18122
18123             if (o->op_private & OPpSORT_INPLACE)
18124                 break;
18125
18126             /* reverse sort ... can be optimised.  */
18127             if (!OpHAS_SIBLING(cUNOPo)) {
18128                 /* Nothing follows us on the list. */
18129                 OP * const reverse = o->op_next;
18130
18131                 if (reverse->op_type == OP_REVERSE &&
18132                     (reverse->op_flags & OPf_WANT) == OPf_WANT_LIST) {
18133                     OP * const pushmark = cUNOPx(reverse)->op_first;
18134                     if (pushmark && (pushmark->op_type == OP_PUSHMARK)
18135                         && (OpSIBLING(cUNOPx(pushmark)) == o)) {
18136                         /* reverse -> pushmark -> sort */
18137                         o->op_private |= OPpSORT_REVERSE;
18138                         op_null(reverse);
18139                         pushmark->op_next = oright->op_next;
18140                         op_null(oright);
18141                     }
18142                 }
18143             }
18144
18145             break;
18146         }
18147
18148         case OP_REVERSE: {
18149             OP *ourmark, *theirmark, *ourlast, *iter, *expushmark, *rv2av;
18150             OP *gvop = NULL;
18151             LISTOP *enter, *exlist;
18152
18153             if (o->op_private & OPpSORT_INPLACE)
18154                 break;
18155
18156             enter = (LISTOP *) o->op_next;
18157             if (!enter)
18158                 break;
18159             if (enter->op_type == OP_NULL) {
18160                 enter = (LISTOP *) enter->op_next;
18161                 if (!enter)
18162                     break;
18163             }
18164             /* for $a (...) will have OP_GV then OP_RV2GV here.
18165                for (...) just has an OP_GV.  */
18166             if (enter->op_type == OP_GV) {
18167                 gvop = (OP *) enter;
18168                 enter = (LISTOP *) enter->op_next;
18169                 if (!enter)
18170                     break;
18171                 if (enter->op_type == OP_RV2GV) {
18172                   enter = (LISTOP *) enter->op_next;
18173                   if (!enter)
18174                     break;
18175                 }
18176             }
18177
18178             if (enter->op_type != OP_ENTERITER)
18179                 break;
18180
18181             iter = enter->op_next;
18182             if (!iter || iter->op_type != OP_ITER)
18183                 break;
18184
18185             expushmark = enter->op_first;
18186             if (!expushmark || expushmark->op_type != OP_NULL
18187                 || expushmark->op_targ != OP_PUSHMARK)
18188                 break;
18189
18190             exlist = (LISTOP *) OpSIBLING(expushmark);
18191             if (!exlist || exlist->op_type != OP_NULL
18192                 || exlist->op_targ != OP_LIST)
18193                 break;
18194
18195             if (exlist->op_last != o) {
18196                 /* Mmm. Was expecting to point back to this op.  */
18197                 break;
18198             }
18199             theirmark = exlist->op_first;
18200             if (!theirmark || theirmark->op_type != OP_PUSHMARK)
18201                 break;
18202
18203             if (OpSIBLING(theirmark) != o) {
18204                 /* There's something between the mark and the reverse, eg
18205                    for (1, reverse (...))
18206                    so no go.  */
18207                 break;
18208             }
18209
18210             ourmark = ((LISTOP *)o)->op_first;
18211             if (!ourmark || ourmark->op_type != OP_PUSHMARK)
18212                 break;
18213
18214             ourlast = ((LISTOP *)o)->op_last;
18215             if (!ourlast || ourlast->op_next != o)
18216                 break;
18217
18218             rv2av = OpSIBLING(ourmark);
18219             if (rv2av && rv2av->op_type == OP_RV2AV && !OpHAS_SIBLING(rv2av)
18220                 && rv2av->op_flags == (OPf_WANT_LIST | OPf_KIDS)) {
18221                 /* We're just reversing a single array.  */
18222                 rv2av->op_flags = OPf_WANT_SCALAR | OPf_KIDS | OPf_REF;
18223                 enter->op_flags |= OPf_STACKED;
18224             }
18225
18226             /* We don't have control over who points to theirmark, so sacrifice
18227                ours.  */
18228             theirmark->op_next = ourmark->op_next;
18229             theirmark->op_flags = ourmark->op_flags;
18230             ourlast->op_next = gvop ? gvop : (OP *) enter;
18231             op_null(ourmark);
18232             op_null(o);
18233             enter->op_private |= OPpITER_REVERSED;
18234             iter->op_private |= OPpITER_REVERSED;
18235
18236             oldoldop = NULL;
18237             oldop    = ourlast;
18238             o        = oldop->op_next;
18239             goto redo;
18240             NOT_REACHED; /* NOTREACHED */
18241             break;
18242         }
18243
18244         case OP_QR:
18245         case OP_MATCH:
18246             if (!(cPMOP->op_pmflags & PMf_ONCE)) {
18247                 assert (!cPMOP->op_pmstashstartu.op_pmreplstart);
18248             }
18249             break;
18250
18251         case OP_RUNCV:
18252             if (!(o->op_private & OPpOFFBYONE) && !CvCLONE(PL_compcv)
18253              && (!CvANON(PL_compcv) || (!PL_cv_has_eval && !PL_perldb)))
18254             {
18255                 SV *sv;
18256                 if (CvEVAL(PL_compcv)) sv = &PL_sv_undef;
18257                 else {
18258                     sv = newRV((SV *)PL_compcv);
18259                     sv_rvweaken(sv);
18260                     SvREADONLY_on(sv);
18261                 }
18262                 OpTYPE_set(o, OP_CONST);
18263                 o->op_flags |= OPf_SPECIAL;
18264                 cSVOPo->op_sv = sv;
18265             }
18266             break;
18267
18268         case OP_SASSIGN:
18269             if (OP_GIMME(o,0) == G_VOID
18270              || (  o->op_next->op_type == OP_LINESEQ
18271                 && (  o->op_next->op_next->op_type == OP_LEAVESUB
18272                    || (  o->op_next->op_next->op_type == OP_RETURN
18273                       && !CvLVALUE(PL_compcv)))))
18274             {
18275                 OP *right = cBINOP->op_first;
18276                 if (right) {
18277                     /*   sassign
18278                     *      RIGHT
18279                     *      substr
18280                     *         pushmark
18281                     *         arg1
18282                     *         arg2
18283                     *         ...
18284                     * becomes
18285                     *
18286                     *  ex-sassign
18287                     *     substr
18288                     *        pushmark
18289                     *        RIGHT
18290                     *        arg1
18291                     *        arg2
18292                     *        ...
18293                     */
18294                     OP *left = OpSIBLING(right);
18295                     if (left->op_type == OP_SUBSTR
18296                          && (left->op_private & 7) < 4) {
18297                         op_null(o);
18298                         /* cut out right */
18299                         op_sibling_splice(o, NULL, 1, NULL);
18300                         /* and insert it as second child of OP_SUBSTR */
18301                         op_sibling_splice(left, cBINOPx(left)->op_first, 0,
18302                                     right);
18303                         left->op_private |= OPpSUBSTR_REPL_FIRST;
18304                         left->op_flags =
18305                             (o->op_flags & ~OPf_WANT) | OPf_WANT_VOID;
18306                     }
18307                 }
18308             }
18309             break;
18310
18311         case OP_AASSIGN: {
18312             int l, r, lr, lscalars, rscalars;
18313
18314             /* handle common vars detection, e.g. ($a,$b) = ($b,$a).
18315                Note that we do this now rather than in newASSIGNOP(),
18316                since only by now are aliased lexicals flagged as such
18317
18318                See the essay "Common vars in list assignment" above for
18319                the full details of the rationale behind all the conditions
18320                below.
18321
18322                PL_generation sorcery:
18323                To detect whether there are common vars, the global var
18324                PL_generation is incremented for each assign op we scan.
18325                Then we run through all the lexical variables on the LHS,
18326                of the assignment, setting a spare slot in each of them to
18327                PL_generation.  Then we scan the RHS, and if any lexicals
18328                already have that value, we know we've got commonality.
18329                Also, if the generation number is already set to
18330                PERL_INT_MAX, then the variable is involved in aliasing, so
18331                we also have potential commonality in that case.
18332              */
18333
18334             PL_generation++;
18335             /* scan LHS */
18336             lscalars = 0;
18337             l = S_aassign_scan(aTHX_ cLISTOPo->op_last,  FALSE, &lscalars);
18338             /* scan RHS */
18339             rscalars = 0;
18340             r = S_aassign_scan(aTHX_ cLISTOPo->op_first, TRUE, &rscalars);
18341             lr = (l|r);
18342
18343
18344             /* After looking for things which are *always* safe, this main
18345              * if/else chain selects primarily based on the type of the
18346              * LHS, gradually working its way down from the more dangerous
18347              * to the more restrictive and thus safer cases */
18348
18349             if (   !l                      /* () = ....; */
18350                 || !r                      /* .... = (); */
18351                 || !(l & ~AAS_SAFE_SCALAR) /* (undef, pos()) = ...; */
18352                 || !(r & ~AAS_SAFE_SCALAR) /* ... = (1,2,length,undef); */
18353                 || (lscalars < 2)          /* (undef, $x) = ... */
18354             ) {
18355                 NOOP; /* always safe */
18356             }
18357             else if (l & AAS_DANGEROUS) {
18358                 /* always dangerous */
18359                 o->op_private |= OPpASSIGN_COMMON_SCALAR;
18360                 o->op_private |= OPpASSIGN_COMMON_AGG;
18361             }
18362             else if (l & (AAS_PKG_SCALAR|AAS_PKG_AGG)) {
18363                 /* package vars are always dangerous - too many
18364                  * aliasing possibilities */
18365                 if (l & AAS_PKG_SCALAR)
18366                     o->op_private |= OPpASSIGN_COMMON_SCALAR;
18367                 if (l & AAS_PKG_AGG)
18368                     o->op_private |= OPpASSIGN_COMMON_AGG;
18369             }
18370             else if (l & ( AAS_MY_SCALAR|AAS_MY_AGG
18371                           |AAS_LEX_SCALAR|AAS_LEX_AGG))
18372             {
18373                 /* LHS contains only lexicals and safe ops */
18374
18375                 if (l & (AAS_MY_AGG|AAS_LEX_AGG))
18376                     o->op_private |= OPpASSIGN_COMMON_AGG;
18377
18378                 if (l & (AAS_MY_SCALAR|AAS_LEX_SCALAR)) {
18379                     if (lr & AAS_LEX_SCALAR_COMM)
18380                         o->op_private |= OPpASSIGN_COMMON_SCALAR;
18381                     else if (   !(l & AAS_LEX_SCALAR)
18382                              && (r & AAS_DEFAV))
18383                     {
18384                         /* falsely mark
18385                          *    my (...) = @_
18386                          * as scalar-safe for performance reasons.
18387                          * (it will still have been marked _AGG if necessary */
18388                         NOOP;
18389                     }
18390                     else if (r  & (AAS_PKG_SCALAR|AAS_PKG_AGG|AAS_DANGEROUS))
18391                         /* if there are only lexicals on the LHS and no
18392                          * common ones on the RHS, then we assume that the
18393                          * only way those lexicals could also get
18394                          * on the RHS is via some sort of dereffing or
18395                          * closure, e.g.
18396                          *    $r = \$lex;
18397                          *    ($lex, $x) = (1, $$r)
18398                          * and in this case we assume the var must have
18399                          *  a bumped ref count. So if its ref count is 1,
18400                          *  it must only be on the LHS.
18401                          */
18402                         o->op_private |= OPpASSIGN_COMMON_RC1;
18403                 }
18404             }
18405
18406             /* ... = ($x)
18407              * may have to handle aggregate on LHS, but we can't
18408              * have common scalars. */
18409             if (rscalars < 2)
18410                 o->op_private &=
18411                         ~(OPpASSIGN_COMMON_SCALAR|OPpASSIGN_COMMON_RC1);
18412
18413             if ((o->op_flags & OPf_WANT) == OPf_WANT_SCALAR)
18414                 S_check_for_bool_cxt(o, 1, OPpASSIGN_TRUEBOOL, 0);
18415             break;
18416         }
18417
18418         case OP_REF:
18419         case OP_BLESSED:
18420             /* if the op is used in boolean context, set the TRUEBOOL flag
18421              * which enables an optimisation at runtime which avoids creating
18422              * a stack temporary for known-true package names */
18423             if ((o->op_flags & OPf_WANT) == OPf_WANT_SCALAR)
18424                 S_check_for_bool_cxt(o, 1, OPpTRUEBOOL, OPpMAYBE_TRUEBOOL);
18425             break;
18426
18427         case OP_LENGTH:
18428             /* see if the op is used in known boolean context,
18429              * but not if OA_TARGLEX optimisation is enabled */
18430             if (   (o->op_flags & OPf_WANT) == OPf_WANT_SCALAR
18431                 && !(o->op_private & OPpTARGET_MY)
18432             )
18433                 S_check_for_bool_cxt(o, 1, OPpTRUEBOOL, 0);
18434             break;
18435
18436         case OP_POS:
18437             /* see if the op is used in known boolean context */
18438             if ((o->op_flags & OPf_WANT) == OPf_WANT_SCALAR)
18439                 S_check_for_bool_cxt(o, 1, OPpTRUEBOOL, 0);
18440             break;
18441
18442         case OP_CUSTOM: {
18443             Perl_cpeep_t cpeep =
18444                 XopENTRYCUSTOM(o, xop_peep);
18445             if (cpeep)
18446                 cpeep(aTHX_ o, oldop);
18447             break;
18448         }
18449
18450         }
18451         /* did we just null the current op? If so, re-process it to handle
18452          * eliding "empty" ops from the chain */
18453         if (o->op_type == OP_NULL && oldop && oldop->op_next == o) {
18454             o->op_opt = 0;
18455             o = oldop;
18456         }
18457         else {
18458             oldoldop = oldop;
18459             oldop = o;
18460         }
18461     }
18462     LEAVE;
18463 }
18464
18465 void
18466 Perl_peep(pTHX_ OP *o)
18467 {
18468     CALL_RPEEP(o);
18469 }
18470
18471 /*
18472 =for apidoc_section $custom
18473
18474 =for apidoc Perl_custom_op_xop
18475 Return the XOP structure for a given custom op.  This macro should be
18476 considered internal to C<OP_NAME> and the other access macros: use them instead.
18477 This macro does call a function.  Prior
18478 to 5.19.6, this was implemented as a
18479 function.
18480
18481 =cut
18482 */
18483
18484
18485 /* use PERL_MAGIC_ext to call a function to free the xop structure when
18486  * freeing PL_custom_ops */
18487
18488 static int
18489 custom_op_register_free(pTHX_ SV *sv, MAGIC *mg)
18490 {
18491     XOP *xop;
18492
18493     PERL_UNUSED_ARG(mg);
18494     xop = INT2PTR(XOP *, SvIV(sv));
18495     Safefree(xop->xop_name);
18496     Safefree(xop->xop_desc);
18497     Safefree(xop);
18498     return 0;
18499 }
18500
18501
18502 static const MGVTBL custom_op_register_vtbl = {
18503     0,                          /* get */
18504     0,                          /* set */
18505     0,                          /* len */
18506     0,                          /* clear */
18507     custom_op_register_free,     /* free */
18508     0,                          /* copy */
18509     0,                          /* dup */
18510 #ifdef MGf_LOCAL
18511     0,                          /* local */
18512 #endif
18513 };
18514
18515
18516 XOPRETANY
18517 Perl_custom_op_get_field(pTHX_ const OP *o, const xop_flags_enum field)
18518 {
18519     SV *keysv;
18520     HE *he = NULL;
18521     XOP *xop;
18522
18523     static const XOP xop_null = { 0, 0, 0, 0, 0 };
18524
18525     PERL_ARGS_ASSERT_CUSTOM_OP_GET_FIELD;
18526     assert(o->op_type == OP_CUSTOM);
18527
18528     /* This is wrong. It assumes a function pointer can be cast to IV,
18529      * which isn't guaranteed, but this is what the old custom OP code
18530      * did. In principle it should be safer to Copy the bytes of the
18531      * pointer into a PV: since the new interface is hidden behind
18532      * functions, this can be changed later if necessary.  */
18533     /* Change custom_op_xop if this ever happens */
18534     keysv = sv_2mortal(newSViv(PTR2IV(o->op_ppaddr)));
18535
18536     if (PL_custom_ops)
18537         he = hv_fetch_ent(PL_custom_ops, keysv, 0, 0);
18538
18539     /* See if the op isn't registered, but its name *is* registered.
18540      * That implies someone is using the pre-5.14 API,where only name and
18541      * description could be registered. If so, fake up a real
18542      * registration.
18543      * We only check for an existing name, and assume no one will have
18544      * just registered a desc */
18545     if (!he && PL_custom_op_names &&
18546         (he = hv_fetch_ent(PL_custom_op_names, keysv, 0, 0))
18547     ) {
18548         const char *pv;
18549         STRLEN l;
18550
18551         /* XXX does all this need to be shared mem? */
18552         Newxz(xop, 1, XOP);
18553         pv = SvPV(HeVAL(he), l);
18554         XopENTRY_set(xop, xop_name, savepvn(pv, l));
18555         if (PL_custom_op_descs &&
18556             (he = hv_fetch_ent(PL_custom_op_descs, keysv, 0, 0))
18557         ) {
18558             pv = SvPV(HeVAL(he), l);
18559             XopENTRY_set(xop, xop_desc, savepvn(pv, l));
18560         }
18561         Perl_custom_op_register(aTHX_ o->op_ppaddr, xop);
18562         he = hv_fetch_ent(PL_custom_ops, keysv, 0, 0);
18563         /* add magic to the SV so that the xop struct (pointed to by
18564          * SvIV(sv)) is freed. Normally a static xop is registered, but
18565          * for this backcompat hack, we've alloced one */
18566         (void)sv_magicext(HeVAL(he), NULL, PERL_MAGIC_ext,
18567                 &custom_op_register_vtbl, NULL, 0);
18568
18569     }
18570     else {
18571         if (!he)
18572             xop = (XOP *)&xop_null;
18573         else
18574             xop = INT2PTR(XOP *, SvIV(HeVAL(he)));
18575     }
18576
18577     {
18578         XOPRETANY any;
18579         if(field == XOPe_xop_ptr) {
18580             any.xop_ptr = xop;
18581         } else {
18582             const U32 flags = XopFLAGS(xop);
18583             if(flags & field) {
18584                 switch(field) {
18585                 case XOPe_xop_name:
18586                     any.xop_name = xop->xop_name;
18587                     break;
18588                 case XOPe_xop_desc:
18589                     any.xop_desc = xop->xop_desc;
18590                     break;
18591                 case XOPe_xop_class:
18592                     any.xop_class = xop->xop_class;
18593                     break;
18594                 case XOPe_xop_peep:
18595                     any.xop_peep = xop->xop_peep;
18596                     break;
18597                 default:
18598                   field_panic:
18599                     Perl_croak(aTHX_
18600                         "panic: custom_op_get_field(): invalid field %d\n",
18601                         (int)field);
18602                     break;
18603                 }
18604             } else {
18605                 switch(field) {
18606                 case XOPe_xop_name:
18607                     any.xop_name = XOPd_xop_name;
18608                     break;
18609                 case XOPe_xop_desc:
18610                     any.xop_desc = XOPd_xop_desc;
18611                     break;
18612                 case XOPe_xop_class:
18613                     any.xop_class = XOPd_xop_class;
18614                     break;
18615                 case XOPe_xop_peep:
18616                     any.xop_peep = XOPd_xop_peep;
18617                     break;
18618                 default:
18619                     goto field_panic;
18620                     break;
18621                 }
18622             }
18623         }
18624         return any;
18625     }
18626 }
18627
18628 /*
18629 =for apidoc custom_op_register
18630 Register a custom op.  See L<perlguts/"Custom Operators">.
18631
18632 =cut
18633 */
18634
18635 void
18636 Perl_custom_op_register(pTHX_ Perl_ppaddr_t ppaddr, const XOP *xop)
18637 {
18638     SV *keysv;
18639
18640     PERL_ARGS_ASSERT_CUSTOM_OP_REGISTER;
18641
18642     /* see the comment in custom_op_xop */
18643     keysv = sv_2mortal(newSViv(PTR2IV(ppaddr)));
18644
18645     if (!PL_custom_ops)
18646         PL_custom_ops = newHV();
18647
18648     if (!hv_store_ent(PL_custom_ops, keysv, newSViv(PTR2IV(xop)), 0))
18649         Perl_croak(aTHX_ "panic: can't register custom OP %s", xop->xop_name);
18650 }
18651
18652 /*
18653
18654 =for apidoc core_prototype
18655
18656 This function assigns the prototype of the named core function to C<sv>, or
18657 to a new mortal SV if C<sv> is C<NULL>.  It returns the modified C<sv>, or
18658 C<NULL> if the core function has no prototype.  C<code> is a code as returned
18659 by C<keyword()>.  It must not be equal to 0.
18660
18661 =cut
18662 */
18663
18664 SV *
18665 Perl_core_prototype(pTHX_ SV *sv, const char *name, const int code,
18666                           int * const opnum)
18667 {
18668     int i = 0, n = 0, seen_question = 0, defgv = 0;
18669     I32 oa;
18670 #define MAX_ARGS_OP ((sizeof(I32) - 1) * 2)
18671     char str[ MAX_ARGS_OP * 2 + 2 ]; /* One ';', one '\0' */
18672     bool nullret = FALSE;
18673
18674     PERL_ARGS_ASSERT_CORE_PROTOTYPE;
18675
18676     assert (code);
18677
18678     if (!sv) sv = sv_newmortal();
18679
18680 #define retsetpvs(x,y) sv_setpvs(sv, x); if(opnum) *opnum=(y); return sv
18681
18682     switch (code < 0 ? -code : code) {
18683     case KEY_and   : case KEY_chop: case KEY_chomp:
18684     case KEY_cmp   : case KEY_defined: case KEY_delete: case KEY_exec  :
18685     case KEY_exists: case KEY_eq     : case KEY_ge    : case KEY_goto  :
18686     case KEY_grep  : case KEY_gt     : case KEY_last  : case KEY_le    :
18687     case KEY_lt    : case KEY_map    : case KEY_ne    : case KEY_next  :
18688     case KEY_or    : case KEY_print  : case KEY_printf: case KEY_qr    :
18689     case KEY_redo  : case KEY_require: case KEY_return: case KEY_say   :
18690     case KEY_select: case KEY_sort   : case KEY_split : case KEY_system:
18691     case KEY_x     : case KEY_xor    :
18692         if (!opnum) return NULL; nullret = TRUE; goto findopnum;
18693     case KEY_glob:    retsetpvs("_;", OP_GLOB);
18694     case KEY_keys:    retsetpvs("\\[%@]", OP_KEYS);
18695     case KEY_values:  retsetpvs("\\[%@]", OP_VALUES);
18696     case KEY_each:    retsetpvs("\\[%@]", OP_EACH);
18697     case KEY_pos:     retsetpvs(";\\[$*]", OP_POS);
18698     case KEY___FILE__: case KEY___LINE__: case KEY___PACKAGE__:
18699         retsetpvs("", 0);
18700     case KEY_evalbytes:
18701         name = "entereval"; break;
18702     case KEY_readpipe:
18703         name = "backtick";
18704     }
18705
18706 #undef retsetpvs
18707
18708   findopnum:
18709     while (i < MAXO) {  /* The slow way. */
18710         if (strEQ(name, PL_op_name[i])
18711             || strEQ(name, PL_op_desc[i]))
18712         {
18713             if (nullret) { assert(opnum); *opnum = i; return NULL; }
18714             goto found;
18715         }
18716         i++;
18717     }
18718     return NULL;
18719   found:
18720     defgv = PL_opargs[i] & OA_DEFGV;
18721     oa = PL_opargs[i] >> OASHIFT;
18722     while (oa) {
18723         if (oa & OA_OPTIONAL && !seen_question && (
18724               !defgv || (oa & (OA_OPTIONAL - 1)) == OA_FILEREF
18725         )) {
18726             seen_question = 1;
18727             str[n++] = ';';
18728         }
18729         if ((oa & (OA_OPTIONAL - 1)) >= OA_AVREF
18730             && (oa & (OA_OPTIONAL - 1)) <= OA_SCALARREF
18731             /* But globs are already references (kinda) */
18732             && (oa & (OA_OPTIONAL - 1)) != OA_FILEREF
18733         ) {
18734             str[n++] = '\\';
18735         }
18736         if ((oa & (OA_OPTIONAL - 1)) == OA_SCALARREF
18737          && !scalar_mod_type(NULL, i)) {
18738             str[n++] = '[';
18739             str[n++] = '$';
18740             str[n++] = '@';
18741             str[n++] = '%';
18742             if (i == OP_LOCK || i == OP_UNDEF) str[n++] = '&';
18743             str[n++] = '*';
18744             str[n++] = ']';
18745         }
18746         else str[n++] = ("?$@@%&*$")[oa & (OA_OPTIONAL - 1)];
18747         if (oa & OA_OPTIONAL && defgv && str[n-1] == '$') {
18748             str[n-1] = '_'; defgv = 0;
18749         }
18750         oa = oa >> 4;
18751     }
18752     if (code == -KEY_not || code == -KEY_getprotobynumber) str[n++] = ';';
18753     str[n++] = '\0';
18754     sv_setpvn(sv, str, n - 1);
18755     if (opnum) *opnum = i;
18756     return sv;
18757 }
18758
18759 OP *
18760 Perl_coresub_op(pTHX_ SV * const coreargssv, const int code,
18761                       const int opnum)
18762 {
18763     OP * const argop = (opnum == OP_SELECT && code) ? NULL :
18764                                         newSVOP(OP_COREARGS,0,coreargssv);
18765     OP *o;
18766
18767     PERL_ARGS_ASSERT_CORESUB_OP;
18768
18769     switch(opnum) {
18770     case 0:
18771         return op_append_elem(OP_LINESEQ,
18772                        argop,
18773                        newSLICEOP(0,
18774                                   newSVOP(OP_CONST, 0, newSViv(-code % 3)),
18775                                   newOP(OP_CALLER,0)
18776                        )
18777                );
18778     case OP_EACH:
18779     case OP_KEYS:
18780     case OP_VALUES:
18781         o = newUNOP(OP_AVHVSWITCH,0,argop);
18782         o->op_private = opnum-OP_EACH;
18783         return o;
18784     case OP_SELECT: /* which represents OP_SSELECT as well */
18785         if (code)
18786             return newCONDOP(
18787                          0,
18788                          newBINOP(OP_GT, 0,
18789                                   newAVREF(newGVOP(OP_GV, 0, PL_defgv)),
18790                                   newSVOP(OP_CONST, 0, newSVuv(1))
18791                                  ),
18792                          coresub_op(newSVuv((UV)OP_SSELECT), 0,
18793                                     OP_SSELECT),
18794                          coresub_op(coreargssv, 0, OP_SELECT)
18795                    );
18796         /* FALLTHROUGH */
18797     default:
18798         switch (PL_opargs[opnum] & OA_CLASS_MASK) {
18799         case OA_BASEOP:
18800             return op_append_elem(
18801                         OP_LINESEQ, argop,
18802                         newOP(opnum,
18803                               opnum == OP_WANTARRAY || opnum == OP_RUNCV
18804                                 ? OPpOFFBYONE << 8 : 0)
18805                    );
18806         case OA_BASEOP_OR_UNOP:
18807             if (opnum == OP_ENTEREVAL) {
18808                 o = newUNOP(OP_ENTEREVAL,OPpEVAL_COPHH<<8,argop);
18809                 if (code == -KEY_evalbytes) o->op_private |= OPpEVAL_BYTES;
18810             }
18811             else o = newUNOP(opnum,0,argop);
18812             if (opnum == OP_CALLER) o->op_private |= OPpOFFBYONE;
18813             else {
18814           onearg:
18815               if (is_handle_constructor(o, 1))
18816                 argop->op_private |= OPpCOREARGS_DEREF1;
18817               if (scalar_mod_type(NULL, opnum))
18818                 argop->op_private |= OPpCOREARGS_SCALARMOD;
18819             }
18820             return o;
18821         default:
18822             o = op_convert_list(opnum,OPf_SPECIAL*(opnum == OP_GLOB),argop);
18823             if (is_handle_constructor(o, 2))
18824                 argop->op_private |= OPpCOREARGS_DEREF2;
18825             if (opnum == OP_SUBSTR) {
18826                 o->op_private |= OPpMAYBE_LVSUB;
18827                 return o;
18828             }
18829             else goto onearg;
18830         }
18831     }
18832 }
18833
18834 void
18835 Perl_report_redefined_cv(pTHX_ const SV *name, const CV *old_cv,
18836                                SV * const *new_const_svp)
18837 {
18838     const char *hvname;
18839     bool is_const = !!CvCONST(old_cv);
18840     SV *old_const_sv = is_const ? cv_const_sv(old_cv) : NULL;
18841
18842     PERL_ARGS_ASSERT_REPORT_REDEFINED_CV;
18843
18844     if (is_const && new_const_svp && old_const_sv == *new_const_svp)
18845         return;
18846         /* They are 2 constant subroutines generated from
18847            the same constant. This probably means that
18848            they are really the "same" proxy subroutine
18849            instantiated in 2 places. Most likely this is
18850            when a constant is exported twice.  Don't warn.
18851         */
18852     if (
18853         (ckWARN(WARN_REDEFINE)
18854          && !(
18855                 CvGV(old_cv) && GvSTASH(CvGV(old_cv))
18856              && HvNAMELEN(GvSTASH(CvGV(old_cv))) == 7
18857              && (hvname = HvNAME(GvSTASH(CvGV(old_cv))),
18858                  strEQ(hvname, "autouse"))
18859              )
18860         )
18861      || (is_const
18862          && ckWARN_d(WARN_REDEFINE)
18863          && (!new_const_svp || sv_cmp(old_const_sv, *new_const_svp))
18864         )
18865     )
18866         Perl_warner(aTHX_ packWARN(WARN_REDEFINE),
18867                           is_const
18868                             ? "Constant subroutine %" SVf " redefined"
18869                             : "Subroutine %" SVf " redefined",
18870                           SVfARG(name));
18871 }
18872
18873 /*
18874 =for apidoc_section $hook
18875
18876 These functions provide convenient and thread-safe means of manipulating
18877 hook variables.
18878
18879 =cut
18880 */
18881
18882 /*
18883 =for apidoc wrap_op_checker
18884
18885 Puts a C function into the chain of check functions for a specified op
18886 type.  This is the preferred way to manipulate the L</PL_check> array.
18887 C<opcode> specifies which type of op is to be affected.  C<new_checker>
18888 is a pointer to the C function that is to be added to that opcode's
18889 check chain, and C<old_checker_p> points to the storage location where a
18890 pointer to the next function in the chain will be stored.  The value of
18891 C<new_checker> is written into the L</PL_check> array, while the value
18892 previously stored there is written to C<*old_checker_p>.
18893
18894 L</PL_check> is global to an entire process, and a module wishing to
18895 hook op checking may find itself invoked more than once per process,
18896 typically in different threads.  To handle that situation, this function
18897 is idempotent.  The location C<*old_checker_p> must initially (once
18898 per process) contain a null pointer.  A C variable of static duration
18899 (declared at file scope, typically also marked C<static> to give
18900 it internal linkage) will be implicitly initialised appropriately,
18901 if it does not have an explicit initialiser.  This function will only
18902 actually modify the check chain if it finds C<*old_checker_p> to be null.
18903 This function is also thread safe on the small scale.  It uses appropriate
18904 locking to avoid race conditions in accessing L</PL_check>.
18905
18906 When this function is called, the function referenced by C<new_checker>
18907 must be ready to be called, except for C<*old_checker_p> being unfilled.
18908 In a threading situation, C<new_checker> may be called immediately,
18909 even before this function has returned.  C<*old_checker_p> will always
18910 be appropriately set before C<new_checker> is called.  If C<new_checker>
18911 decides not to do anything special with an op that it is given (which
18912 is the usual case for most uses of op check hooking), it must chain the
18913 check function referenced by C<*old_checker_p>.
18914
18915 Taken all together, XS code to hook an op checker should typically look
18916 something like this:
18917
18918     static Perl_check_t nxck_frob;
18919     static OP *myck_frob(pTHX_ OP *op) {
18920         ...
18921         op = nxck_frob(aTHX_ op);
18922         ...
18923         return op;
18924     }
18925     BOOT:
18926         wrap_op_checker(OP_FROB, myck_frob, &nxck_frob);
18927
18928 If you want to influence compilation of calls to a specific subroutine,
18929 then use L</cv_set_call_checker_flags> rather than hooking checking of
18930 all C<entersub> ops.
18931
18932 =cut
18933 */
18934
18935 void
18936 Perl_wrap_op_checker(pTHX_ Optype opcode,
18937     Perl_check_t new_checker, Perl_check_t *old_checker_p)
18938 {
18939
18940     PERL_UNUSED_CONTEXT;
18941     PERL_ARGS_ASSERT_WRAP_OP_CHECKER;
18942     if (*old_checker_p) return;
18943     OP_CHECK_MUTEX_LOCK;
18944     if (!*old_checker_p) {
18945         *old_checker_p = PL_check[opcode];
18946         PL_check[opcode] = new_checker;
18947     }
18948     OP_CHECK_MUTEX_UNLOCK;
18949 }
18950
18951 #include "XSUB.h"
18952
18953 /* Efficient sub that returns a constant scalar value. */
18954 static void
18955 const_sv_xsub(pTHX_ CV* cv)
18956 {
18957     dXSARGS;
18958     SV *const sv = MUTABLE_SV(XSANY.any_ptr);
18959     PERL_UNUSED_ARG(items);
18960     if (!sv) {
18961         XSRETURN(0);
18962     }
18963     EXTEND(sp, 1);
18964     ST(0) = sv;
18965     XSRETURN(1);
18966 }
18967
18968 static void
18969 const_av_xsub(pTHX_ CV* cv)
18970 {
18971     dXSARGS;
18972     AV * const av = MUTABLE_AV(XSANY.any_ptr);
18973     SP -= items;
18974     assert(av);
18975 #ifndef DEBUGGING
18976     if (!av) {
18977         XSRETURN(0);
18978     }
18979 #endif
18980     if (SvRMAGICAL(av))
18981         Perl_croak(aTHX_ "Magical list constants are not supported");
18982     if (GIMME_V != G_LIST) {
18983         EXTEND(SP, 1);
18984         ST(0) = sv_2mortal(newSViv((IV)AvFILLp(av)+1));
18985         XSRETURN(1);
18986     }
18987     EXTEND(SP, AvFILLp(av)+1);
18988     Copy(AvARRAY(av), &ST(0), AvFILLp(av)+1, SV *);
18989     XSRETURN(AvFILLp(av)+1);
18990 }
18991
18992 /* Copy an existing cop->cop_warnings field.
18993  * If it's one of the standard addresses, just re-use the address.
18994  * This is the e implementation for the DUP_WARNINGS() macro
18995  */
18996
18997 STRLEN*
18998 Perl_dup_warnings(pTHX_ STRLEN* warnings)
18999 {
19000     Size_t size;
19001     STRLEN *new_warnings;
19002
19003     if (warnings == NULL || specialWARN(warnings))
19004         return warnings;
19005
19006     size = sizeof(*warnings) + *warnings;
19007
19008     new_warnings = (STRLEN*)PerlMemShared_malloc(size);
19009     Copy(warnings, new_warnings, size, char);
19010     return new_warnings;
19011 }
19012
19013 /*
19014  * ex: set ts=8 sts=4 sw=4 et:
19015  */