This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
lib/charnames.t: Move initialization line
[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 #define DIFF(o,p)               ((size_t)((I32 **)(p) - (I32**)(o)))
211
212 /* requires double parens and aTHX_ */
213 #define DEBUG_S_warn(args)                                             \
214     DEBUG_S(                                                            \
215         PerlIO_printf(Perl_debug_log, "%s", SvPVx_nolen(Perl_mess args)) \
216     )
217
218
219 /* malloc a new op slab (suitable for attaching to PL_compcv).
220  * sz is in units of pointers */
221
222 static OPSLAB *
223 S_new_slab(pTHX_ OPSLAB *head, size_t sz)
224 {
225     OPSLAB *slab;
226
227     /* opslot_offset is only U16 */
228     assert(sz  < U16_MAX);
229
230 #ifdef PERL_DEBUG_READONLY_OPS
231     slab = (OPSLAB *) mmap(0, sz * sizeof(I32 *),
232                                    PROT_READ|PROT_WRITE,
233                                    MAP_ANON|MAP_PRIVATE, -1, 0);
234     DEBUG_m(PerlIO_printf(Perl_debug_log, "mapped %lu at %p\n",
235                           (unsigned long) sz, slab));
236     if (slab == MAP_FAILED) {
237         perror("mmap failed");
238         abort();
239     }
240 #else
241     slab = (OPSLAB *)PerlMemShared_calloc(sz, sizeof(I32 *));
242 #endif
243     slab->opslab_size = (U16)sz;
244
245 #ifndef WIN32
246     /* The context is unused in non-Windows */
247     PERL_UNUSED_CONTEXT;
248 #endif
249     slab->opslab_free_space = sz - DIFF(slab, &slab->opslab_slots);
250     slab->opslab_head = head ? head : slab;
251     DEBUG_S_warn((aTHX_ "allocated new op slab sz 0x%x, %p, head slab %p",
252         (unsigned int)slab->opslab_size, (void*)slab,
253         (void*)(slab->opslab_head)));
254     return slab;
255 }
256
257
258 /* Returns a sz-sized block of memory (suitable for holding an op) from
259  * a free slot in the chain of op slabs attached to PL_compcv.
260  * Allocates a new slab if necessary.
261  * if PL_compcv isn't compiling, malloc() instead.
262  */
263
264 void *
265 Perl_Slab_Alloc(pTHX_ size_t sz)
266 {
267     OPSLAB *head_slab; /* first slab in the chain */
268     OPSLAB *slab2;
269     OPSLOT *slot;
270     OP *o;
271     size_t opsz;
272
273     /* We only allocate ops from the slab during subroutine compilation.
274        We find the slab via PL_compcv, hence that must be non-NULL. It could
275        also be pointing to a subroutine which is now fully set up (CvROOT()
276        pointing to the top of the optree for that sub), or a subroutine
277        which isn't using the slab allocator. If our sanity checks aren't met,
278        don't use a slab, but allocate the OP directly from the heap.  */
279     if (!PL_compcv || CvROOT(PL_compcv)
280      || (CvSTART(PL_compcv) && !CvSLABBED(PL_compcv)))
281     {
282         o = (OP*)PerlMemShared_calloc(1, sz);
283         goto gotit;
284     }
285
286     /* While the subroutine is under construction, the slabs are accessed via
287        CvSTART(), to avoid needing to expand PVCV by one pointer for something
288        unneeded at runtime. Once a subroutine is constructed, the slabs are
289        accessed via CvROOT(). So if CvSTART() is NULL, no slab has been
290        allocated yet.  See the commit message for 8be227ab5eaa23f2 for more
291        details.  */
292     if (!CvSTART(PL_compcv)) {
293         CvSTART(PL_compcv) =
294             (OP *)(head_slab = S_new_slab(aTHX_ NULL, PERL_SLAB_SIZE));
295         CvSLABBED_on(PL_compcv);
296         head_slab->opslab_refcnt = 2; /* one for the CV; one for the new OP */
297     }
298     else ++(head_slab = (OPSLAB *)CvSTART(PL_compcv))->opslab_refcnt;
299
300     opsz = SIZE_TO_PSIZE(sz);
301     sz = opsz + OPSLOT_HEADER_P;
302
303     /* The slabs maintain a free list of OPs. In particular, constant folding
304        will free up OPs, so it makes sense to re-use them where possible. A
305        freed up slot is used in preference to a new allocation.  */
306     if (head_slab->opslab_freed) {
307         OP **too = &head_slab->opslab_freed;
308         o = *too;
309         DEBUG_S_warn((aTHX_ "found free op at %p, slab %p, head slab %p",
310             (void*)o,
311             (I32**)OpSLOT(o) - OpSLOT(o)->opslot_offset,
312             (void*)head_slab));
313
314         while (o && OpSLOT(o)->opslot_size < sz) {
315             DEBUG_S_warn((aTHX_ "Alas! too small"));
316             o = *(too = &o->op_next);
317             if (o) { DEBUG_S_warn((aTHX_ "found another free op at %p", (void*)o)); }
318         }
319         if (o) {
320             DEBUG_S_warn((aTHX_ "realloced  op at %p, slab %p, head slab %p",
321                 (void*)o,
322                 (I32**)OpSLOT(o) - OpSLOT(o)->opslot_offset,
323                 (void*)head_slab));
324             *too = o->op_next;
325             Zero(o, opsz, I32 *);
326             o->op_slabbed = 1;
327             goto gotit;
328         }
329     }
330
331 #define INIT_OPSLOT(s) \
332             slot->opslot_offset = DIFF(slab2, slot) ;   \
333             slot->opslot_size = s;                      \
334             slab2->opslab_free_space -= s;              \
335             o = &slot->opslot_op;                       \
336             o->op_slabbed = 1
337
338     /* The partially-filled slab is next in the chain. */
339     slab2 = head_slab->opslab_next ? head_slab->opslab_next : head_slab;
340     if (slab2->opslab_free_space  < sz) {
341         /* Remaining space is too small. */
342         /* If we can fit a BASEOP, add it to the free chain, so as not
343            to waste it. */
344         if (slab2->opslab_free_space >= SIZE_TO_PSIZE(sizeof(OP)) + OPSLOT_HEADER_P) {
345             slot = &slab2->opslab_slots;
346             INIT_OPSLOT(slab2->opslab_free_space);
347             o->op_type = OP_FREED;
348             o->op_next = head_slab->opslab_freed;
349             head_slab->opslab_freed = o;
350         }
351
352         /* Create a new slab.  Make this one twice as big. */
353         slab2 = S_new_slab(aTHX_ head_slab,
354                             slab2->opslab_size  > PERL_MAX_SLAB_SIZE / 2
355                                 ? PERL_MAX_SLAB_SIZE
356                                 : slab2->opslab_size * 2);
357         slab2->opslab_next = head_slab->opslab_next;
358         head_slab->opslab_next = slab2;
359     }
360     assert(slab2->opslab_size >= sz);
361
362     /* Create a new op slot */
363     slot = (OPSLOT *)
364                 ((I32 **)&slab2->opslab_slots
365                                 + slab2->opslab_free_space - sz);
366     assert(slot >= &slab2->opslab_slots);
367     INIT_OPSLOT(sz);
368     DEBUG_S_warn((aTHX_ "allocating op at %p, slab %p, head slab %p",
369         (void*)o, (void*)slab2, (void*)head_slab));
370
371   gotit:
372     /* moresib == 0, op_sibling == 0 implies a solitary unattached op */
373     assert(!o->op_moresib);
374     assert(!o->op_sibparent);
375
376     return (void *)o;
377 }
378
379 #undef INIT_OPSLOT
380
381 #ifdef PERL_DEBUG_READONLY_OPS
382 void
383 Perl_Slab_to_ro(pTHX_ OPSLAB *slab)
384 {
385     PERL_ARGS_ASSERT_SLAB_TO_RO;
386
387     if (slab->opslab_readonly) return;
388     slab->opslab_readonly = 1;
389     for (; slab; slab = slab->opslab_next) {
390         /*DEBUG_U(PerlIO_printf(Perl_debug_log,"mprotect ->ro %lu at %p\n",
391                               (unsigned long) slab->opslab_size, slab));*/
392         if (mprotect(slab, slab->opslab_size * sizeof(I32 *), PROT_READ))
393             Perl_warn(aTHX_ "mprotect for %p %lu failed with %d", slab,
394                              (unsigned long)slab->opslab_size, errno);
395     }
396 }
397
398 void
399 Perl_Slab_to_rw(pTHX_ OPSLAB *const slab)
400 {
401     OPSLAB *slab2;
402
403     PERL_ARGS_ASSERT_SLAB_TO_RW;
404
405     if (!slab->opslab_readonly) return;
406     slab2 = slab;
407     for (; slab2; slab2 = slab2->opslab_next) {
408         /*DEBUG_U(PerlIO_printf(Perl_debug_log,"mprotect ->rw %lu at %p\n",
409                               (unsigned long) size, slab2));*/
410         if (mprotect((void *)slab2, slab2->opslab_size * sizeof(I32 *),
411                      PROT_READ|PROT_WRITE)) {
412             Perl_warn(aTHX_ "mprotect RW for %p %lu failed with %d", slab,
413                              (unsigned long)slab2->opslab_size, errno);
414         }
415     }
416     slab->opslab_readonly = 0;
417 }
418
419 #else
420 #  define Slab_to_rw(op)    NOOP
421 #endif
422
423 /* This cannot possibly be right, but it was copied from the old slab
424    allocator, to which it was originally added, without explanation, in
425    commit 083fcd5. */
426 #ifdef NETWARE
427 #    define PerlMemShared PerlMem
428 #endif
429
430 /* make freed ops die if they're inadvertently executed */
431 #ifdef DEBUGGING
432 static OP *
433 S_pp_freed(pTHX)
434 {
435     DIE(aTHX_ "panic: freed op 0x%p called\n", PL_op);
436 }
437 #endif
438
439
440 /* Return the block of memory used by an op to the free list of
441  * the OP slab associated with that op.
442  */
443
444 void
445 Perl_Slab_Free(pTHX_ void *op)
446 {
447     OP * const o = (OP *)op;
448     OPSLAB *slab;
449
450     PERL_ARGS_ASSERT_SLAB_FREE;
451
452 #ifdef DEBUGGING
453     o->op_ppaddr = S_pp_freed;
454 #endif
455
456     if (!o->op_slabbed) {
457         if (!o->op_static)
458             PerlMemShared_free(op);
459         return;
460     }
461
462     slab = OpSLAB(o);
463     /* If this op is already freed, our refcount will get screwy. */
464     assert(o->op_type != OP_FREED);
465     o->op_type = OP_FREED;
466     o->op_next = slab->opslab_freed;
467     slab->opslab_freed = o;
468     DEBUG_S_warn((aTHX_ "freeing    op at %p, slab %p, head slab %p",
469         (void*)o,
470         (I32**)OpSLOT(o) - OpSLOT(o)->opslot_offset,
471         (void*)slab));
472     OpslabREFCNT_dec_padok(slab);
473 }
474
475 void
476 Perl_opslab_free_nopad(pTHX_ OPSLAB *slab)
477 {
478     const bool havepad = !!PL_comppad;
479     PERL_ARGS_ASSERT_OPSLAB_FREE_NOPAD;
480     if (havepad) {
481         ENTER;
482         PAD_SAVE_SETNULLPAD();
483     }
484     opslab_free(slab);
485     if (havepad) LEAVE;
486 }
487
488 /* Free a chain of OP slabs. Should only be called after all ops contained
489  * in it have been freed. At this point, its reference count should be 1,
490  * because OpslabREFCNT_dec() skips doing rc-- when it detects that rc == 1,
491  * and just directly calls opslab_free().
492  * (Note that the reference count which PL_compcv held on the slab should
493  * have been removed once compilation of the sub was complete).
494  *
495  *
496  */
497
498 void
499 Perl_opslab_free(pTHX_ OPSLAB *slab)
500 {
501     OPSLAB *slab2;
502     PERL_ARGS_ASSERT_OPSLAB_FREE;
503     PERL_UNUSED_CONTEXT;
504     DEBUG_S_warn((aTHX_ "freeing slab %p", (void*)slab));
505     assert(slab->opslab_refcnt == 1);
506     do {
507         slab2 = slab->opslab_next;
508 #ifdef DEBUGGING
509         slab->opslab_refcnt = ~(size_t)0;
510 #endif
511 #ifdef PERL_DEBUG_READONLY_OPS
512         DEBUG_m(PerlIO_printf(Perl_debug_log, "Deallocate slab at %p\n",
513                                                (void*)slab));
514         if (munmap(slab, slab->opslab_size * sizeof(I32 *))) {
515             perror("munmap failed");
516             abort();
517         }
518 #else
519         PerlMemShared_free(slab);
520 #endif
521         slab = slab2;
522     } while (slab);
523 }
524
525 /* like opslab_free(), but first calls op_free() on any ops in the slab
526  * not marked as OP_FREED
527  */
528
529 void
530 Perl_opslab_force_free(pTHX_ OPSLAB *slab)
531 {
532     OPSLAB *slab2;
533 #ifdef DEBUGGING
534     size_t savestack_count = 0;
535 #endif
536     PERL_ARGS_ASSERT_OPSLAB_FORCE_FREE;
537     slab2 = slab;
538     do {
539         OPSLOT *slot = (OPSLOT*)
540                     ((I32**)&slab2->opslab_slots + slab2->opslab_free_space);
541         OPSLOT *end  = (OPSLOT*)
542                         ((I32**)slab2 + slab2->opslab_size);
543         for (; slot < end;
544                 slot = (OPSLOT*) ((I32**)slot + slot->opslot_size) )
545         {
546             if (slot->opslot_op.op_type != OP_FREED
547              && !(slot->opslot_op.op_savefree
548 #ifdef DEBUGGING
549                   && ++savestack_count
550 #endif
551                  )
552             ) {
553                 assert(slot->opslot_op.op_slabbed);
554                 op_free(&slot->opslot_op);
555                 if (slab->opslab_refcnt == 1) goto free;
556             }
557         }
558     } while ((slab2 = slab2->opslab_next));
559     /* > 1 because the CV still holds a reference count. */
560     if (slab->opslab_refcnt > 1) { /* still referenced by the savestack */
561 #ifdef DEBUGGING
562         assert(savestack_count == slab->opslab_refcnt-1);
563 #endif
564         /* Remove the CV’s reference count. */
565         slab->opslab_refcnt--;
566         return;
567     }
568    free:
569     opslab_free(slab);
570 }
571
572 #ifdef PERL_DEBUG_READONLY_OPS
573 OP *
574 Perl_op_refcnt_inc(pTHX_ OP *o)
575 {
576     if(o) {
577         OPSLAB *const slab = o->op_slabbed ? OpSLAB(o) : NULL;
578         if (slab && slab->opslab_readonly) {
579             Slab_to_rw(slab);
580             ++o->op_targ;
581             Slab_to_ro(slab);
582         } else {
583             ++o->op_targ;
584         }
585     }
586     return o;
587
588 }
589
590 PADOFFSET
591 Perl_op_refcnt_dec(pTHX_ OP *o)
592 {
593     PADOFFSET result;
594     OPSLAB *const slab = o->op_slabbed ? OpSLAB(o) : NULL;
595
596     PERL_ARGS_ASSERT_OP_REFCNT_DEC;
597
598     if (slab && slab->opslab_readonly) {
599         Slab_to_rw(slab);
600         result = --o->op_targ;
601         Slab_to_ro(slab);
602     } else {
603         result = --o->op_targ;
604     }
605     return result;
606 }
607 #endif
608 /*
609  * In the following definition, the ", (OP*)0" is just to make the compiler
610  * think the expression is of the right type: croak actually does a Siglongjmp.
611  */
612 #define CHECKOP(type,o) \
613     ((PL_op_mask && PL_op_mask[type])                           \
614      ? ( op_free((OP*)o),                                       \
615          Perl_croak(aTHX_ "'%s' trapped by operation mask", PL_op_desc[type]),  \
616          (OP*)0 )                                               \
617      : PL_check[type](aTHX_ (OP*)o))
618
619 #define RETURN_UNLIMITED_NUMBER (PERL_INT_MAX / 2)
620
621 #define OpTYPE_set(o,type) \
622     STMT_START {                                \
623         o->op_type = (OPCODE)type;              \
624         o->op_ppaddr = PL_ppaddr[type];         \
625     } STMT_END
626
627 STATIC OP *
628 S_no_fh_allowed(pTHX_ OP *o)
629 {
630     PERL_ARGS_ASSERT_NO_FH_ALLOWED;
631
632     yyerror(Perl_form(aTHX_ "Missing comma after first argument to %s function",
633                  OP_DESC(o)));
634     return o;
635 }
636
637 STATIC OP *
638 S_too_few_arguments_pv(pTHX_ OP *o, const char* name, U32 flags)
639 {
640     PERL_ARGS_ASSERT_TOO_FEW_ARGUMENTS_PV;
641     yyerror_pv(Perl_form(aTHX_ "Not enough arguments for %s", name), flags);
642     return o;
643 }
644
645 STATIC OP *
646 S_too_many_arguments_pv(pTHX_ OP *o, const char *name, U32 flags)
647 {
648     PERL_ARGS_ASSERT_TOO_MANY_ARGUMENTS_PV;
649
650     yyerror_pv(Perl_form(aTHX_ "Too many arguments for %s", name), flags);
651     return o;
652 }
653
654 STATIC void
655 S_bad_type_pv(pTHX_ I32 n, const char *t, const OP *o, const OP *kid)
656 {
657     PERL_ARGS_ASSERT_BAD_TYPE_PV;
658
659     yyerror_pv(Perl_form(aTHX_ "Type of arg %d to %s must be %s (not %s)",
660                  (int)n, PL_op_desc[(o)->op_type], t, OP_DESC(kid)), 0);
661 }
662
663 /* remove flags var, its unused in all callers, move to to right end since gv
664   and kid are always the same */
665 STATIC void
666 S_bad_type_gv(pTHX_ I32 n, GV *gv, const OP *kid, const char *t)
667 {
668     SV * const namesv = cv_name((CV *)gv, NULL, 0);
669     PERL_ARGS_ASSERT_BAD_TYPE_GV;
670
671     yyerror_pv(Perl_form(aTHX_ "Type of arg %d to %" SVf " must be %s (not %s)",
672                  (int)n, SVfARG(namesv), t, OP_DESC(kid)), SvUTF8(namesv));
673 }
674
675 STATIC void
676 S_no_bareword_allowed(pTHX_ OP *o)
677 {
678     PERL_ARGS_ASSERT_NO_BAREWORD_ALLOWED;
679
680     qerror(Perl_mess(aTHX_
681                      "Bareword \"%" SVf "\" not allowed while \"strict subs\" in use",
682                      SVfARG(cSVOPo_sv)));
683     o->op_private &= ~OPpCONST_STRICT; /* prevent warning twice about the same OP */
684 }
685
686 /* "register" allocation */
687
688 PADOFFSET
689 Perl_allocmy(pTHX_ const char *const name, const STRLEN len, const U32 flags)
690 {
691     PADOFFSET off;
692     const bool is_our = (PL_parser->in_my == KEY_our);
693
694     PERL_ARGS_ASSERT_ALLOCMY;
695
696     if (flags & ~SVf_UTF8)
697         Perl_croak(aTHX_ "panic: allocmy illegal flag bits 0x%" UVxf,
698                    (UV)flags);
699
700     /* complain about "my $<special_var>" etc etc */
701     if (   len
702         && !(  is_our
703             || isALPHA(name[1])
704             || (   (flags & SVf_UTF8)
705                 && isIDFIRST_utf8_safe((U8 *)name+1, name + len))
706             || (name[1] == '_' && len > 2)))
707     {
708         const char * const type =
709               PL_parser->in_my == KEY_sigvar ? "subroutine signature" :
710               PL_parser->in_my == KEY_state  ? "\"state\""     : "\"my\"";
711
712         if (!(flags & SVf_UTF8 && UTF8_IS_START(name[1]))
713          && isASCII(name[1])
714          && (!isPRINT(name[1]) || memCHRs("\t\n\r\f", name[1]))) {
715             /* diag_listed_as: Can't use global %s in %s */
716             yyerror(Perl_form(aTHX_ "Can't use global %c^%c%.*s in %s",
717                               name[0], toCTRL(name[1]),
718                               (int)(len - 2), name + 2,
719                               type));
720         } else {
721             yyerror_pv(Perl_form(aTHX_ "Can't use global %.*s in %s",
722                               (int) len, name,
723                               type), flags & SVf_UTF8);
724         }
725     }
726
727     /* allocate a spare slot and store the name in that slot */
728
729     off = pad_add_name_pvn(name, len,
730                        (is_our ? padadd_OUR :
731                         PL_parser->in_my == KEY_state ? padadd_STATE : 0),
732                     PL_parser->in_my_stash,
733                     (is_our
734                         /* $_ is always in main::, even with our */
735                         ? (PL_curstash && !memEQs(name,len,"$_")
736                             ? PL_curstash
737                             : PL_defstash)
738                         : NULL
739                     )
740     );
741     /* anon sub prototypes contains state vars should always be cloned,
742      * otherwise the state var would be shared between anon subs */
743
744     if (PL_parser->in_my == KEY_state && CvANON(PL_compcv))
745         CvCLONE_on(PL_compcv);
746
747     return off;
748 }
749
750 /*
751 =head1 Optree Manipulation Functions
752
753 =for apidoc alloccopstash
754
755 Available only under threaded builds, this function allocates an entry in
756 C<PL_stashpad> for the stash passed to it.
757
758 =cut
759 */
760
761 #ifdef USE_ITHREADS
762 PADOFFSET
763 Perl_alloccopstash(pTHX_ HV *hv)
764 {
765     PADOFFSET off = 0, o = 1;
766     bool found_slot = FALSE;
767
768     PERL_ARGS_ASSERT_ALLOCCOPSTASH;
769
770     if (PL_stashpad[PL_stashpadix] == hv) return PL_stashpadix;
771
772     for (; o < PL_stashpadmax; ++o) {
773         if (PL_stashpad[o] == hv) return PL_stashpadix = o;
774         if (!PL_stashpad[o] || SvTYPE(PL_stashpad[o]) != SVt_PVHV)
775             found_slot = TRUE, off = o;
776     }
777     if (!found_slot) {
778         Renew(PL_stashpad, PL_stashpadmax + 10, HV *);
779         Zero(PL_stashpad + PL_stashpadmax, 10, HV *);
780         off = PL_stashpadmax;
781         PL_stashpadmax += 10;
782     }
783
784     PL_stashpad[PL_stashpadix = off] = hv;
785     return off;
786 }
787 #endif
788
789 /* free the body of an op without examining its contents.
790  * Always use this rather than FreeOp directly */
791
792 static void
793 S_op_destroy(pTHX_ OP *o)
794 {
795     FreeOp(o);
796 }
797
798 /* Destructor */
799
800 /*
801 =for apidoc op_free
802
803 Free an op and its children. Only use this when an op is no longer linked
804 to from any optree.
805
806 =cut
807 */
808
809 void
810 Perl_op_free(pTHX_ OP *o)
811 {
812     dVAR;
813     OPCODE type;
814     OP *top_op = o;
815     OP *next_op = o;
816     bool went_up = FALSE; /* whether we reached the current node by
817                             following the parent pointer from a child, and
818                             so have already seen this node */
819
820     if (!o || o->op_type == OP_FREED)
821         return;
822
823     if (o->op_private & OPpREFCOUNTED) {
824         /* if base of tree is refcounted, just decrement */
825         switch (o->op_type) {
826         case OP_LEAVESUB:
827         case OP_LEAVESUBLV:
828         case OP_LEAVEEVAL:
829         case OP_LEAVE:
830         case OP_SCOPE:
831         case OP_LEAVEWRITE:
832             {
833                 PADOFFSET refcnt;
834                 OP_REFCNT_LOCK;
835                 refcnt = OpREFCNT_dec(o);
836                 OP_REFCNT_UNLOCK;
837                 if (refcnt) {
838                     /* Need to find and remove any pattern match ops from
839                      * the list we maintain for reset().  */
840                     find_and_forget_pmops(o);
841                     return;
842                 }
843             }
844             break;
845         default:
846             break;
847         }
848     }
849
850     while (next_op) {
851         o = next_op;
852
853         /* free child ops before ourself, (then free ourself "on the
854          * way back up") */
855
856         if (!went_up && o->op_flags & OPf_KIDS) {
857             next_op = cUNOPo->op_first;
858             continue;
859         }
860
861         /* find the next node to visit, *then* free the current node
862          * (can't rely on o->op_* fields being valid after o has been
863          * freed) */
864
865         /* The next node to visit will be either the sibling, or the
866          * parent if no siblings left, or NULL if we've worked our way
867          * back up to the top node in the tree */
868         next_op = (o == top_op) ? NULL : o->op_sibparent;
869         went_up = cBOOL(!OpHAS_SIBLING(o)); /* parents are already visited */
870
871         /* Now process the current node */
872
873         /* Though ops may be freed twice, freeing the op after its slab is a
874            big no-no. */
875         assert(!o->op_slabbed || OpSLAB(o)->opslab_refcnt != ~(size_t)0);
876         /* During the forced freeing of ops after compilation failure, kidops
877            may be freed before their parents. */
878         if (!o || o->op_type == OP_FREED)
879             continue;
880
881         type = o->op_type;
882
883         /* an op should only ever acquire op_private flags that we know about.
884          * If this fails, you may need to fix something in regen/op_private.
885          * Don't bother testing if:
886          *   * the op_ppaddr doesn't match the op; someone may have
887          *     overridden the op and be doing strange things with it;
888          *   * we've errored, as op flags are often left in an
889          *     inconsistent state then. Note that an error when
890          *     compiling the main program leaves PL_parser NULL, so
891          *     we can't spot faults in the main code, only
892          *     evaled/required code */
893 #ifdef DEBUGGING
894         if (   o->op_ppaddr == PL_ppaddr[type]
895             && PL_parser
896             && !PL_parser->error_count)
897         {
898             assert(!(o->op_private & ~PL_op_private_valid[type]));
899         }
900 #endif
901
902
903         /* Call the op_free hook if it has been set. Do it now so that it's called
904          * at the right time for refcounted ops, but still before all of the kids
905          * are freed. */
906         CALL_OPFREEHOOK(o);
907
908         if (type == OP_NULL)
909             type = (OPCODE)o->op_targ;
910
911         if (o->op_slabbed)
912             Slab_to_rw(OpSLAB(o));
913
914         /* COP* is not cleared by op_clear() so that we may track line
915          * numbers etc even after null() */
916         if (type == OP_NEXTSTATE || type == OP_DBSTATE) {
917             cop_free((COP*)o);
918         }
919
920         op_clear(o);
921         FreeOp(o);
922         if (PL_op == o)
923             PL_op = NULL;
924     }
925 }
926
927
928 /* S_op_clear_gv(): free a GV attached to an OP */
929
930 STATIC
931 #ifdef USE_ITHREADS
932 void S_op_clear_gv(pTHX_ OP *o, PADOFFSET *ixp)
933 #else
934 void S_op_clear_gv(pTHX_ OP *o, SV**svp)
935 #endif
936 {
937
938     GV *gv = (o->op_type == OP_GV || o->op_type == OP_GVSV
939             || o->op_type == OP_MULTIDEREF)
940 #ifdef USE_ITHREADS
941                 && PL_curpad
942                 ? ((GV*)PAD_SVl(*ixp)) : NULL;
943 #else
944                 ? (GV*)(*svp) : NULL;
945 #endif
946     /* It's possible during global destruction that the GV is freed
947        before the optree. Whilst the SvREFCNT_inc is happy to bump from
948        0 to 1 on a freed SV, the corresponding SvREFCNT_dec from 1 to 0
949        will trigger an assertion failure, because the entry to sv_clear
950        checks that the scalar is not already freed.  A check of for
951        !SvIS_FREED(gv) turns out to be invalid, because during global
952        destruction the reference count can be forced down to zero
953        (with SVf_BREAK set).  In which case raising to 1 and then
954        dropping to 0 triggers cleanup before it should happen.  I
955        *think* that this might actually be a general, systematic,
956        weakness of the whole idea of SVf_BREAK, in that code *is*
957        allowed to raise and lower references during global destruction,
958        so any *valid* code that happens to do this during global
959        destruction might well trigger premature cleanup.  */
960     bool still_valid = gv && SvREFCNT(gv);
961
962     if (still_valid)
963         SvREFCNT_inc_simple_void(gv);
964 #ifdef USE_ITHREADS
965     if (*ixp > 0) {
966         pad_swipe(*ixp, TRUE);
967         *ixp = 0;
968     }
969 #else
970     SvREFCNT_dec(*svp);
971     *svp = NULL;
972 #endif
973     if (still_valid) {
974         int try_downgrade = SvREFCNT(gv) == 2;
975         SvREFCNT_dec_NN(gv);
976         if (try_downgrade)
977             gv_try_downgrade(gv);
978     }
979 }
980
981
982 void
983 Perl_op_clear(pTHX_ OP *o)
984 {
985
986     dVAR;
987
988     PERL_ARGS_ASSERT_OP_CLEAR;
989
990     switch (o->op_type) {
991     case OP_NULL:       /* Was holding old type, if any. */
992         /* FALLTHROUGH */
993     case OP_ENTERTRY:
994     case OP_ENTEREVAL:  /* Was holding hints. */
995     case OP_ARGDEFELEM: /* Was holding signature index. */
996         o->op_targ = 0;
997         break;
998     default:
999         if (!(o->op_flags & OPf_REF) || !OP_IS_STAT(o->op_type))
1000             break;
1001         /* FALLTHROUGH */
1002     case OP_GVSV:
1003     case OP_GV:
1004     case OP_AELEMFAST:
1005 #ifdef USE_ITHREADS
1006             S_op_clear_gv(aTHX_ o, &(cPADOPx(o)->op_padix));
1007 #else
1008             S_op_clear_gv(aTHX_ o, &(cSVOPx(o)->op_sv));
1009 #endif
1010         break;
1011     case OP_METHOD_REDIR:
1012     case OP_METHOD_REDIR_SUPER:
1013 #ifdef USE_ITHREADS
1014         if (cMETHOPx(o)->op_rclass_targ) {
1015             pad_swipe(cMETHOPx(o)->op_rclass_targ, 1);
1016             cMETHOPx(o)->op_rclass_targ = 0;
1017         }
1018 #else
1019         SvREFCNT_dec(cMETHOPx(o)->op_rclass_sv);
1020         cMETHOPx(o)->op_rclass_sv = NULL;
1021 #endif
1022         /* FALLTHROUGH */
1023     case OP_METHOD_NAMED:
1024     case OP_METHOD_SUPER:
1025         SvREFCNT_dec(cMETHOPx(o)->op_u.op_meth_sv);
1026         cMETHOPx(o)->op_u.op_meth_sv = NULL;
1027 #ifdef USE_ITHREADS
1028         if (o->op_targ) {
1029             pad_swipe(o->op_targ, 1);
1030             o->op_targ = 0;
1031         }
1032 #endif
1033         break;
1034     case OP_CONST:
1035     case OP_HINTSEVAL:
1036         SvREFCNT_dec(cSVOPo->op_sv);
1037         cSVOPo->op_sv = NULL;
1038 #ifdef USE_ITHREADS
1039         /** Bug #15654
1040           Even if op_clear does a pad_free for the target of the op,
1041           pad_free doesn't actually remove the sv that exists in the pad;
1042           instead it lives on. This results in that it could be reused as
1043           a target later on when the pad was reallocated.
1044         **/
1045         if(o->op_targ) {
1046           pad_swipe(o->op_targ,1);
1047           o->op_targ = 0;
1048         }
1049 #endif
1050         break;
1051     case OP_DUMP:
1052     case OP_GOTO:
1053     case OP_NEXT:
1054     case OP_LAST:
1055     case OP_REDO:
1056         if (o->op_flags & (OPf_SPECIAL|OPf_STACKED|OPf_KIDS))
1057             break;
1058         /* FALLTHROUGH */
1059     case OP_TRANS:
1060     case OP_TRANSR:
1061         if (   (o->op_type == OP_TRANS || o->op_type == OP_TRANSR)
1062             && (o->op_private & OPpTRANS_USE_SVOP))
1063         {
1064 #ifdef USE_ITHREADS
1065             if (cPADOPo->op_padix > 0) {
1066                 pad_swipe(cPADOPo->op_padix, TRUE);
1067                 cPADOPo->op_padix = 0;
1068             }
1069 #else
1070             SvREFCNT_dec(cSVOPo->op_sv);
1071             cSVOPo->op_sv = NULL;
1072 #endif
1073         }
1074         else {
1075             PerlMemShared_free(cPVOPo->op_pv);
1076             cPVOPo->op_pv = NULL;
1077         }
1078         break;
1079     case OP_SUBST:
1080         op_free(cPMOPo->op_pmreplrootu.op_pmreplroot);
1081         goto clear_pmop;
1082
1083     case OP_SPLIT:
1084         if (     (o->op_private & OPpSPLIT_ASSIGN) /* @array  = split */
1085             && !(o->op_flags & OPf_STACKED))       /* @{expr} = split */
1086         {
1087             if (o->op_private & OPpSPLIT_LEX)
1088                 pad_free(cPMOPo->op_pmreplrootu.op_pmtargetoff);
1089             else
1090 #ifdef USE_ITHREADS
1091                 pad_swipe(cPMOPo->op_pmreplrootu.op_pmtargetoff, TRUE);
1092 #else
1093                 SvREFCNT_dec(MUTABLE_SV(cPMOPo->op_pmreplrootu.op_pmtargetgv));
1094 #endif
1095         }
1096         /* FALLTHROUGH */
1097     case OP_MATCH:
1098     case OP_QR:
1099     clear_pmop:
1100         if (!(cPMOPo->op_pmflags & PMf_CODELIST_PRIVATE))
1101             op_free(cPMOPo->op_code_list);
1102         cPMOPo->op_code_list = NULL;
1103         forget_pmop(cPMOPo);
1104         cPMOPo->op_pmreplrootu.op_pmreplroot = NULL;
1105         /* we use the same protection as the "SAFE" version of the PM_ macros
1106          * here since sv_clean_all might release some PMOPs
1107          * after PL_regex_padav has been cleared
1108          * and the clearing of PL_regex_padav needs to
1109          * happen before sv_clean_all
1110          */
1111 #ifdef USE_ITHREADS
1112         if(PL_regex_pad) {        /* We could be in destruction */
1113             const IV offset = (cPMOPo)->op_pmoffset;
1114             ReREFCNT_dec(PM_GETRE(cPMOPo));
1115             PL_regex_pad[offset] = &PL_sv_undef;
1116             sv_catpvn_nomg(PL_regex_pad[0], (const char *)&offset,
1117                            sizeof(offset));
1118         }
1119 #else
1120         ReREFCNT_dec(PM_GETRE(cPMOPo));
1121         PM_SETRE(cPMOPo, NULL);
1122 #endif
1123
1124         break;
1125
1126     case OP_ARGCHECK:
1127         PerlMemShared_free(cUNOP_AUXo->op_aux);
1128         break;
1129
1130     case OP_MULTICONCAT:
1131         {
1132             UNOP_AUX_item *aux = cUNOP_AUXo->op_aux;
1133             /* aux[PERL_MULTICONCAT_IX_PLAIN_PV] and/or
1134              * aux[PERL_MULTICONCAT_IX_UTF8_PV] point to plain and/or
1135              * utf8 shared strings */
1136             char *p1 = aux[PERL_MULTICONCAT_IX_PLAIN_PV].pv;
1137             char *p2 = aux[PERL_MULTICONCAT_IX_UTF8_PV].pv;
1138             if (p1)
1139                 PerlMemShared_free(p1);
1140             if (p2 && p1 != p2)
1141                 PerlMemShared_free(p2);
1142             PerlMemShared_free(aux);
1143         }
1144         break;
1145
1146     case OP_MULTIDEREF:
1147         {
1148             UNOP_AUX_item *items = cUNOP_AUXo->op_aux;
1149             UV actions = items->uv;
1150             bool last = 0;
1151             bool is_hash = FALSE;
1152
1153             while (!last) {
1154                 switch (actions & MDEREF_ACTION_MASK) {
1155
1156                 case MDEREF_reload:
1157                     actions = (++items)->uv;
1158                     continue;
1159
1160                 case MDEREF_HV_padhv_helem:
1161                     is_hash = TRUE;
1162                     /* FALLTHROUGH */
1163                 case MDEREF_AV_padav_aelem:
1164                     pad_free((++items)->pad_offset);
1165                     goto do_elem;
1166
1167                 case MDEREF_HV_gvhv_helem:
1168                     is_hash = TRUE;
1169                     /* FALLTHROUGH */
1170                 case MDEREF_AV_gvav_aelem:
1171 #ifdef USE_ITHREADS
1172                     S_op_clear_gv(aTHX_ o, &((++items)->pad_offset));
1173 #else
1174                     S_op_clear_gv(aTHX_ o, &((++items)->sv));
1175 #endif
1176                     goto do_elem;
1177
1178                 case MDEREF_HV_gvsv_vivify_rv2hv_helem:
1179                     is_hash = TRUE;
1180                     /* FALLTHROUGH */
1181                 case MDEREF_AV_gvsv_vivify_rv2av_aelem:
1182 #ifdef USE_ITHREADS
1183                     S_op_clear_gv(aTHX_ o, &((++items)->pad_offset));
1184 #else
1185                     S_op_clear_gv(aTHX_ o, &((++items)->sv));
1186 #endif
1187                     goto do_vivify_rv2xv_elem;
1188
1189                 case MDEREF_HV_padsv_vivify_rv2hv_helem:
1190                     is_hash = TRUE;
1191                     /* FALLTHROUGH */
1192                 case MDEREF_AV_padsv_vivify_rv2av_aelem:
1193                     pad_free((++items)->pad_offset);
1194                     goto do_vivify_rv2xv_elem;
1195
1196                 case MDEREF_HV_pop_rv2hv_helem:
1197                 case MDEREF_HV_vivify_rv2hv_helem:
1198                     is_hash = TRUE;
1199                     /* FALLTHROUGH */
1200                 do_vivify_rv2xv_elem:
1201                 case MDEREF_AV_pop_rv2av_aelem:
1202                 case MDEREF_AV_vivify_rv2av_aelem:
1203                 do_elem:
1204                     switch (actions & MDEREF_INDEX_MASK) {
1205                     case MDEREF_INDEX_none:
1206                         last = 1;
1207                         break;
1208                     case MDEREF_INDEX_const:
1209                         if (is_hash) {
1210 #ifdef USE_ITHREADS
1211                             /* see RT #15654 */
1212                             pad_swipe((++items)->pad_offset, 1);
1213 #else
1214                             SvREFCNT_dec((++items)->sv);
1215 #endif
1216                         }
1217                         else
1218                             items++;
1219                         break;
1220                     case MDEREF_INDEX_padsv:
1221                         pad_free((++items)->pad_offset);
1222                         break;
1223                     case MDEREF_INDEX_gvsv:
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                         break;
1230                     }
1231
1232                     if (actions & MDEREF_FLAG_last)
1233                         last = 1;
1234                     is_hash = FALSE;
1235
1236                     break;
1237
1238                 default:
1239                     assert(0);
1240                     last = 1;
1241                     break;
1242
1243                 } /* switch */
1244
1245                 actions >>= MDEREF_SHIFT;
1246             } /* while */
1247
1248             /* start of malloc is at op_aux[-1], where the length is
1249              * stored */
1250             PerlMemShared_free(cUNOP_AUXo->op_aux - 1);
1251         }
1252         break;
1253     }
1254
1255     if (o->op_targ > 0) {
1256         pad_free(o->op_targ);
1257         o->op_targ = 0;
1258     }
1259 }
1260
1261 STATIC void
1262 S_cop_free(pTHX_ COP* cop)
1263 {
1264     PERL_ARGS_ASSERT_COP_FREE;
1265
1266     CopFILE_free(cop);
1267     if (! specialWARN(cop->cop_warnings))
1268         PerlMemShared_free(cop->cop_warnings);
1269     cophh_free(CopHINTHASH_get(cop));
1270     if (PL_curcop == cop)
1271        PL_curcop = NULL;
1272 }
1273
1274 STATIC void
1275 S_forget_pmop(pTHX_ PMOP *const o)
1276 {
1277     HV * const pmstash = PmopSTASH(o);
1278
1279     PERL_ARGS_ASSERT_FORGET_PMOP;
1280
1281     if (pmstash && !SvIS_FREED(pmstash) && SvMAGICAL(pmstash)) {
1282         MAGIC * const mg = mg_find((const SV *)pmstash, PERL_MAGIC_symtab);
1283         if (mg) {
1284             PMOP **const array = (PMOP**) mg->mg_ptr;
1285             U32 count = mg->mg_len / sizeof(PMOP**);
1286             U32 i = count;
1287
1288             while (i--) {
1289                 if (array[i] == o) {
1290                     /* Found it. Move the entry at the end to overwrite it.  */
1291                     array[i] = array[--count];
1292                     mg->mg_len = count * sizeof(PMOP**);
1293                     /* Could realloc smaller at this point always, but probably
1294                        not worth it. Probably worth free()ing if we're the
1295                        last.  */
1296                     if(!count) {
1297                         Safefree(mg->mg_ptr);
1298                         mg->mg_ptr = NULL;
1299                     }
1300                     break;
1301                 }
1302             }
1303         }
1304     }
1305     if (PL_curpm == o)
1306         PL_curpm = NULL;
1307 }
1308
1309
1310 STATIC void
1311 S_find_and_forget_pmops(pTHX_ OP *o)
1312 {
1313     OP* top_op = o;
1314
1315     PERL_ARGS_ASSERT_FIND_AND_FORGET_PMOPS;
1316
1317     while (1) {
1318         switch (o->op_type) {
1319         case OP_SUBST:
1320         case OP_SPLIT:
1321         case OP_MATCH:
1322         case OP_QR:
1323             forget_pmop((PMOP*)o);
1324         }
1325
1326         if (o->op_flags & OPf_KIDS) {
1327             o = cUNOPo->op_first;
1328             continue;
1329         }
1330
1331         while (1) {
1332             if (o == top_op)
1333                 return; /* at top; no parents/siblings to try */
1334             if (OpHAS_SIBLING(o)) {
1335                 o = o->op_sibparent; /* process next sibling */
1336                 break;
1337             }
1338             o = o->op_sibparent; /*try parent's next sibling */
1339         }
1340     }
1341 }
1342
1343
1344 /*
1345 =for apidoc op_null
1346
1347 Neutralizes an op when it is no longer needed, but is still linked to from
1348 other ops.
1349
1350 =cut
1351 */
1352
1353 void
1354 Perl_op_null(pTHX_ OP *o)
1355 {
1356     dVAR;
1357
1358     PERL_ARGS_ASSERT_OP_NULL;
1359
1360     if (o->op_type == OP_NULL)
1361         return;
1362     op_clear(o);
1363     o->op_targ = o->op_type;
1364     OpTYPE_set(o, OP_NULL);
1365 }
1366
1367 void
1368 Perl_op_refcnt_lock(pTHX)
1369   PERL_TSA_ACQUIRE(PL_op_mutex)
1370 {
1371 #ifdef USE_ITHREADS
1372     dVAR;
1373 #endif
1374     PERL_UNUSED_CONTEXT;
1375     OP_REFCNT_LOCK;
1376 }
1377
1378 void
1379 Perl_op_refcnt_unlock(pTHX)
1380   PERL_TSA_RELEASE(PL_op_mutex)
1381 {
1382 #ifdef USE_ITHREADS
1383     dVAR;
1384 #endif
1385     PERL_UNUSED_CONTEXT;
1386     OP_REFCNT_UNLOCK;
1387 }
1388
1389
1390 /*
1391 =for apidoc op_sibling_splice
1392
1393 A general function for editing the structure of an existing chain of
1394 op_sibling nodes.  By analogy with the perl-level C<splice()> function, allows
1395 you to delete zero or more sequential nodes, replacing them with zero or
1396 more different nodes.  Performs the necessary op_first/op_last
1397 housekeeping on the parent node and op_sibling manipulation on the
1398 children.  The last deleted node will be marked as as the last node by
1399 updating the op_sibling/op_sibparent or op_moresib field as appropriate.
1400
1401 Note that op_next is not manipulated, and nodes are not freed; that is the
1402 responsibility of the caller.  It also won't create a new list op for an
1403 empty list etc; use higher-level functions like op_append_elem() for that.
1404
1405 C<parent> is the parent node of the sibling chain. It may passed as C<NULL> if
1406 the splicing doesn't affect the first or last op in the chain.
1407
1408 C<start> is the node preceding the first node to be spliced.  Node(s)
1409 following it will be deleted, and ops will be inserted after it.  If it is
1410 C<NULL>, the first node onwards is deleted, and nodes are inserted at the
1411 beginning.
1412
1413 C<del_count> is the number of nodes to delete.  If zero, no nodes are deleted.
1414 If -1 or greater than or equal to the number of remaining kids, all
1415 remaining kids are deleted.
1416
1417 C<insert> is the first of a chain of nodes to be inserted in place of the nodes.
1418 If C<NULL>, no nodes are inserted.
1419
1420 The head of the chain of deleted ops is returned, or C<NULL> if no ops were
1421 deleted.
1422
1423 For example:
1424
1425     action                    before      after         returns
1426     ------                    -----       -----         -------
1427
1428                               P           P
1429     splice(P, A, 2, X-Y-Z)    |           |             B-C
1430                               A-B-C-D     A-X-Y-Z-D
1431
1432                               P           P
1433     splice(P, NULL, 1, X-Y)   |           |             A
1434                               A-B-C-D     X-Y-B-C-D
1435
1436                               P           P
1437     splice(P, NULL, 3, NULL)  |           |             A-B-C
1438                               A-B-C-D     D
1439
1440                               P           P
1441     splice(P, B, 0, X-Y)      |           |             NULL
1442                               A-B-C-D     A-B-X-Y-C-D
1443
1444
1445 For lower-level direct manipulation of C<op_sibparent> and C<op_moresib>,
1446 see C<L</OpMORESIB_set>>, C<L</OpLASTSIB_set>>, C<L</OpMAYBESIB_set>>.
1447
1448 =cut
1449 */
1450
1451 OP *
1452 Perl_op_sibling_splice(OP *parent, OP *start, int del_count, OP* insert)
1453 {
1454     OP *first;
1455     OP *rest;
1456     OP *last_del = NULL;
1457     OP *last_ins = NULL;
1458
1459     if (start)
1460         first = OpSIBLING(start);
1461     else if (!parent)
1462         goto no_parent;
1463     else
1464         first = cLISTOPx(parent)->op_first;
1465
1466     assert(del_count >= -1);
1467
1468     if (del_count && first) {
1469         last_del = first;
1470         while (--del_count && OpHAS_SIBLING(last_del))
1471             last_del = OpSIBLING(last_del);
1472         rest = OpSIBLING(last_del);
1473         OpLASTSIB_set(last_del, NULL);
1474     }
1475     else
1476         rest = first;
1477
1478     if (insert) {
1479         last_ins = insert;
1480         while (OpHAS_SIBLING(last_ins))
1481             last_ins = OpSIBLING(last_ins);
1482         OpMAYBESIB_set(last_ins, rest, NULL);
1483     }
1484     else
1485         insert = rest;
1486
1487     if (start) {
1488         OpMAYBESIB_set(start, insert, NULL);
1489     }
1490     else {
1491         assert(parent);
1492         cLISTOPx(parent)->op_first = insert;
1493         if (insert)
1494             parent->op_flags |= OPf_KIDS;
1495         else
1496             parent->op_flags &= ~OPf_KIDS;
1497     }
1498
1499     if (!rest) {
1500         /* update op_last etc */
1501         U32 type;
1502         OP *lastop;
1503
1504         if (!parent)
1505             goto no_parent;
1506
1507         /* ought to use OP_CLASS(parent) here, but that can't handle
1508          * ex-foo OP_NULL ops. Also note that XopENTRYCUSTOM() can't
1509          * either */
1510         type = parent->op_type;
1511         if (type == OP_CUSTOM) {
1512             dTHX;
1513             type = XopENTRYCUSTOM(parent, xop_class);
1514         }
1515         else {
1516             if (type == OP_NULL)
1517                 type = parent->op_targ;
1518             type = PL_opargs[type] & OA_CLASS_MASK;
1519         }
1520
1521         lastop = last_ins ? last_ins : start ? start : NULL;
1522         if (   type == OA_BINOP
1523             || type == OA_LISTOP
1524             || type == OA_PMOP
1525             || type == OA_LOOP
1526         )
1527             cLISTOPx(parent)->op_last = lastop;
1528
1529         if (lastop)
1530             OpLASTSIB_set(lastop, parent);
1531     }
1532     return last_del ? first : NULL;
1533
1534   no_parent:
1535     Perl_croak_nocontext("panic: op_sibling_splice(): NULL parent");
1536 }
1537
1538 /*
1539 =for apidoc op_parent
1540
1541 Returns the parent OP of C<o>, if it has a parent. Returns C<NULL> otherwise.
1542
1543 =cut
1544 */
1545
1546 OP *
1547 Perl_op_parent(OP *o)
1548 {
1549     PERL_ARGS_ASSERT_OP_PARENT;
1550     while (OpHAS_SIBLING(o))
1551         o = OpSIBLING(o);
1552     return o->op_sibparent;
1553 }
1554
1555 /* replace the sibling following start with a new UNOP, which becomes
1556  * the parent of the original sibling; e.g.
1557  *
1558  *  op_sibling_newUNOP(P, A, unop-args...)
1559  *
1560  *  P              P
1561  *  |      becomes |
1562  *  A-B-C          A-U-C
1563  *                   |
1564  *                   B
1565  *
1566  * where U is the new UNOP.
1567  *
1568  * parent and start args are the same as for op_sibling_splice();
1569  * type and flags args are as newUNOP().
1570  *
1571  * Returns the new UNOP.
1572  */
1573
1574 STATIC OP *
1575 S_op_sibling_newUNOP(pTHX_ OP *parent, OP *start, I32 type, I32 flags)
1576 {
1577     OP *kid, *newop;
1578
1579     kid = op_sibling_splice(parent, start, 1, NULL);
1580     newop = newUNOP(type, flags, kid);
1581     op_sibling_splice(parent, start, 0, newop);
1582     return newop;
1583 }
1584
1585
1586 /* lowest-level newLOGOP-style function - just allocates and populates
1587  * the struct. Higher-level stuff should be done by S_new_logop() /
1588  * newLOGOP(). This function exists mainly to avoid op_first assignment
1589  * being spread throughout this file.
1590  */
1591
1592 LOGOP *
1593 Perl_alloc_LOGOP(pTHX_ I32 type, OP *first, OP* other)
1594 {
1595     dVAR;
1596     LOGOP *logop;
1597     OP *kid = first;
1598     NewOp(1101, logop, 1, LOGOP);
1599     OpTYPE_set(logop, type);
1600     logop->op_first = first;
1601     logop->op_other = other;
1602     if (first)
1603         logop->op_flags = OPf_KIDS;
1604     while (kid && OpHAS_SIBLING(kid))
1605         kid = OpSIBLING(kid);
1606     if (kid)
1607         OpLASTSIB_set(kid, (OP*)logop);
1608     return logop;
1609 }
1610
1611
1612 /* Contextualizers */
1613
1614 /*
1615 =for apidoc op_contextualize
1616
1617 Applies a syntactic context to an op tree representing an expression.
1618 C<o> is the op tree, and C<context> must be C<G_SCALAR>, C<G_ARRAY>,
1619 or C<G_VOID> to specify the context to apply.  The modified op tree
1620 is returned.
1621
1622 =cut
1623 */
1624
1625 OP *
1626 Perl_op_contextualize(pTHX_ OP *o, I32 context)
1627 {
1628     PERL_ARGS_ASSERT_OP_CONTEXTUALIZE;
1629     switch (context) {
1630         case G_SCALAR: return scalar(o);
1631         case G_ARRAY:  return list(o);
1632         case G_VOID:   return scalarvoid(o);
1633         default:
1634             Perl_croak(aTHX_ "panic: op_contextualize bad context %ld",
1635                        (long) context);
1636     }
1637 }
1638
1639 /*
1640
1641 =for apidoc op_linklist
1642 This function is the implementation of the L</LINKLIST> macro.  It should
1643 not be called directly.
1644
1645 =cut
1646 */
1647
1648
1649 OP *
1650 Perl_op_linklist(pTHX_ OP *o)
1651 {
1652
1653     OP **prevp;
1654     OP *kid;
1655     OP * top_op = o;
1656
1657     PERL_ARGS_ASSERT_OP_LINKLIST;
1658
1659     while (1) {
1660         /* Descend down the tree looking for any unprocessed subtrees to
1661          * do first */
1662         if (!o->op_next) {
1663             if (o->op_flags & OPf_KIDS) {
1664                 o = cUNOPo->op_first;
1665                 continue;
1666             }
1667             o->op_next = o; /* leaf node; link to self initially */
1668         }
1669
1670         /* if we're at the top level, there either weren't any children
1671          * to process, or we've worked our way back to the top. */
1672         if (o == top_op)
1673             return o->op_next;
1674
1675         /* o is now processed. Next, process any sibling subtrees */
1676
1677         if (OpHAS_SIBLING(o)) {
1678             o = OpSIBLING(o);
1679             continue;
1680         }
1681
1682         /* Done all the subtrees at this level. Go back up a level and
1683          * link the parent in with all its (processed) children.
1684          */
1685
1686         o = o->op_sibparent;
1687         assert(!o->op_next);
1688         prevp = &(o->op_next);
1689         kid   = (o->op_flags & OPf_KIDS) ? cUNOPo->op_first : NULL;
1690         while (kid) {
1691             *prevp = kid->op_next;
1692             prevp = &(kid->op_next);
1693             kid = OpSIBLING(kid);
1694         }
1695         *prevp = o;
1696     }
1697 }
1698
1699
1700 static OP *
1701 S_scalarkids(pTHX_ OP *o)
1702 {
1703     if (o && o->op_flags & OPf_KIDS) {
1704         OP *kid;
1705         for (kid = cLISTOPo->op_first; kid; kid = OpSIBLING(kid))
1706             scalar(kid);
1707     }
1708     return o;
1709 }
1710
1711 STATIC OP *
1712 S_scalarboolean(pTHX_ OP *o)
1713 {
1714     PERL_ARGS_ASSERT_SCALARBOOLEAN;
1715
1716     if ((o->op_type == OP_SASSIGN && cBINOPo->op_first->op_type == OP_CONST &&
1717          !(cBINOPo->op_first->op_flags & OPf_SPECIAL)) ||
1718         (o->op_type == OP_NOT     && cUNOPo->op_first->op_type == OP_SASSIGN &&
1719          cBINOPx(cUNOPo->op_first)->op_first->op_type == OP_CONST &&
1720          !(cBINOPx(cUNOPo->op_first)->op_first->op_flags & OPf_SPECIAL))) {
1721         if (ckWARN(WARN_SYNTAX)) {
1722             const line_t oldline = CopLINE(PL_curcop);
1723
1724             if (PL_parser && PL_parser->copline != NOLINE) {
1725                 /* This ensures that warnings are reported at the first line
1726                    of the conditional, not the last.  */
1727                 CopLINE_set(PL_curcop, PL_parser->copline);
1728             }
1729             Perl_warner(aTHX_ packWARN(WARN_SYNTAX), "Found = in conditional, should be ==");
1730             CopLINE_set(PL_curcop, oldline);
1731         }
1732     }
1733     return scalar(o);
1734 }
1735
1736 static SV *
1737 S_op_varname_subscript(pTHX_ const OP *o, int subscript_type)
1738 {
1739     assert(o);
1740     assert(o->op_type == OP_PADAV || o->op_type == OP_RV2AV ||
1741            o->op_type == OP_PADHV || o->op_type == OP_RV2HV);
1742     {
1743         const char funny  = o->op_type == OP_PADAV
1744                          || o->op_type == OP_RV2AV ? '@' : '%';
1745         if (o->op_type == OP_RV2AV || o->op_type == OP_RV2HV) {
1746             GV *gv;
1747             if (cUNOPo->op_first->op_type != OP_GV
1748              || !(gv = cGVOPx_gv(cUNOPo->op_first)))
1749                 return NULL;
1750             return varname(gv, funny, 0, NULL, 0, subscript_type);
1751         }
1752         return
1753             varname(MUTABLE_GV(PL_compcv), funny, o->op_targ, NULL, 0, subscript_type);
1754     }
1755 }
1756
1757 static SV *
1758 S_op_varname(pTHX_ const OP *o)
1759 {
1760     return S_op_varname_subscript(aTHX_ o, 1);
1761 }
1762
1763 static void
1764 S_op_pretty(pTHX_ const OP *o, SV **retsv, const char **retpv)
1765 { /* or not so pretty :-) */
1766     if (o->op_type == OP_CONST) {
1767         *retsv = cSVOPo_sv;
1768         if (SvPOK(*retsv)) {
1769             SV *sv = *retsv;
1770             *retsv = sv_newmortal();
1771             pv_pretty(*retsv, SvPVX_const(sv), SvCUR(sv), 32, NULL, NULL,
1772                       PERL_PV_PRETTY_DUMP |PERL_PV_ESCAPE_UNI_DETECT);
1773         }
1774         else if (!SvOK(*retsv))
1775             *retpv = "undef";
1776     }
1777     else *retpv = "...";
1778 }
1779
1780 static void
1781 S_scalar_slice_warning(pTHX_ const OP *o)
1782 {
1783     OP *kid;
1784     const bool h = o->op_type == OP_HSLICE
1785                 || (o->op_type == OP_NULL && o->op_targ == OP_HSLICE);
1786     const char lbrack =
1787         h ? '{' : '[';
1788     const char rbrack =
1789         h ? '}' : ']';
1790     SV *name;
1791     SV *keysv = NULL; /* just to silence compiler warnings */
1792     const char *key = NULL;
1793
1794     if (!(o->op_private & OPpSLICEWARNING))
1795         return;
1796     if (PL_parser && PL_parser->error_count)
1797         /* This warning can be nonsensical when there is a syntax error. */
1798         return;
1799
1800     kid = cLISTOPo->op_first;
1801     kid = OpSIBLING(kid); /* get past pushmark */
1802     /* weed out false positives: any ops that can return lists */
1803     switch (kid->op_type) {
1804     case OP_BACKTICK:
1805     case OP_GLOB:
1806     case OP_READLINE:
1807     case OP_MATCH:
1808     case OP_RV2AV:
1809     case OP_EACH:
1810     case OP_VALUES:
1811     case OP_KEYS:
1812     case OP_SPLIT:
1813     case OP_LIST:
1814     case OP_SORT:
1815     case OP_REVERSE:
1816     case OP_ENTERSUB:
1817     case OP_CALLER:
1818     case OP_LSTAT:
1819     case OP_STAT:
1820     case OP_READDIR:
1821     case OP_SYSTEM:
1822     case OP_TMS:
1823     case OP_LOCALTIME:
1824     case OP_GMTIME:
1825     case OP_ENTEREVAL:
1826         return;
1827     }
1828
1829     /* Don't warn if we have a nulled list either. */
1830     if (kid->op_type == OP_NULL && kid->op_targ == OP_LIST)
1831         return;
1832
1833     assert(OpSIBLING(kid));
1834     name = S_op_varname(aTHX_ OpSIBLING(kid));
1835     if (!name) /* XS module fiddling with the op tree */
1836         return;
1837     S_op_pretty(aTHX_ kid, &keysv, &key);
1838     assert(SvPOK(name));
1839     sv_chop(name,SvPVX(name)+1);
1840     if (key)
1841        /* diag_listed_as: Scalar value @%s[%s] better written as $%s[%s] */
1842         Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
1843                    "Scalar value @%" SVf "%c%s%c better written as $%" SVf
1844                    "%c%s%c",
1845                     SVfARG(name), lbrack, key, rbrack, SVfARG(name),
1846                     lbrack, key, rbrack);
1847     else
1848        /* diag_listed_as: Scalar value @%s[%s] better written as $%s[%s] */
1849         Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
1850                    "Scalar value @%" SVf "%c%" SVf "%c better written as $%"
1851                     SVf "%c%" SVf "%c",
1852                     SVfARG(name), lbrack, SVfARG(keysv), rbrack,
1853                     SVfARG(name), lbrack, SVfARG(keysv), rbrack);
1854 }
1855
1856
1857
1858 /* apply scalar context to the o subtree */
1859
1860 OP *
1861 Perl_scalar(pTHX_ OP *o)
1862 {
1863     OP * top_op = o;
1864
1865     while (1) {
1866         OP *next_kid = NULL; /* what op (if any) to process next */
1867         OP *kid;
1868
1869         /* assumes no premature commitment */
1870         if (!o || (PL_parser && PL_parser->error_count)
1871              || (o->op_flags & OPf_WANT)
1872              || o->op_type == OP_RETURN)
1873         {
1874             goto do_next;
1875         }
1876
1877         o->op_flags = (o->op_flags & ~OPf_WANT) | OPf_WANT_SCALAR;
1878
1879         switch (o->op_type) {
1880         case OP_REPEAT:
1881             scalar(cBINOPo->op_first);
1882             /* convert what initially looked like a list repeat into a
1883              * scalar repeat, e.g. $s = (1) x $n
1884              */
1885             if (o->op_private & OPpREPEAT_DOLIST) {
1886                 kid = cLISTOPx(cUNOPo->op_first)->op_first;
1887                 assert(kid->op_type == OP_PUSHMARK);
1888                 if (OpHAS_SIBLING(kid) && !OpHAS_SIBLING(OpSIBLING(kid))) {
1889                     op_null(cLISTOPx(cUNOPo->op_first)->op_first);
1890                     o->op_private &=~ OPpREPEAT_DOLIST;
1891                 }
1892             }
1893             break;
1894
1895         case OP_OR:
1896         case OP_AND:
1897         case OP_COND_EXPR:
1898             /* impose scalar context on everything except the condition */
1899             next_kid = OpSIBLING(cUNOPo->op_first);
1900             break;
1901
1902         default:
1903             if (o->op_flags & OPf_KIDS)
1904                 next_kid = cUNOPo->op_first; /* do all kids */
1905             break;
1906
1907         /* the children of these ops are usually a list of statements,
1908          * except the leaves, whose first child is a corresponding enter
1909          */
1910         case OP_SCOPE:
1911         case OP_LINESEQ:
1912         case OP_LIST:
1913             kid = cLISTOPo->op_first;
1914             goto do_kids;
1915         case OP_LEAVE:
1916         case OP_LEAVETRY:
1917             kid = cLISTOPo->op_first;
1918             scalar(kid);
1919             kid = OpSIBLING(kid);
1920         do_kids:
1921             while (kid) {
1922                 OP *sib = OpSIBLING(kid);
1923                 /* Apply void context to all kids except the last, which
1924                  * is scalar (ignoring a trailing ex-nextstate in determining
1925                  * if it's the last kid). E.g.
1926                  *      $scalar = do { void; void; scalar }
1927                  * Except that 'when's are always scalar, e.g.
1928                  *      $scalar = do { given(..) {
1929                     *                 when (..) { scalar }
1930                     *                 when (..) { scalar }
1931                     *                 ...
1932                     *                }}
1933                     */
1934                 if (!sib
1935                      || (  !OpHAS_SIBLING(sib)
1936                          && sib->op_type == OP_NULL
1937                          && (   sib->op_targ == OP_NEXTSTATE
1938                              || sib->op_targ == OP_DBSTATE  )
1939                         )
1940                 )
1941                 {
1942                     /* tail call optimise calling scalar() on the last kid */
1943                     next_kid = kid;
1944                     goto do_next;
1945                 }
1946                 else if (kid->op_type == OP_LEAVEWHEN)
1947                     scalar(kid);
1948                 else
1949                     scalarvoid(kid);
1950                 kid = sib;
1951             }
1952             NOT_REACHED; /* NOTREACHED */
1953             break;
1954
1955         case OP_SORT:
1956             Perl_ck_warner(aTHX_ packWARN(WARN_VOID), "Useless use of sort in scalar context");
1957             break;
1958
1959         case OP_KVHSLICE:
1960         case OP_KVASLICE:
1961         {
1962             /* Warn about scalar context */
1963             const char lbrack = o->op_type == OP_KVHSLICE ? '{' : '[';
1964             const char rbrack = o->op_type == OP_KVHSLICE ? '}' : ']';
1965             SV *name;
1966             SV *keysv;
1967             const char *key = NULL;
1968
1969             /* This warning can be nonsensical when there is a syntax error. */
1970             if (PL_parser && PL_parser->error_count)
1971                 break;
1972
1973             if (!ckWARN(WARN_SYNTAX)) break;
1974
1975             kid = cLISTOPo->op_first;
1976             kid = OpSIBLING(kid); /* get past pushmark */
1977             assert(OpSIBLING(kid));
1978             name = S_op_varname(aTHX_ OpSIBLING(kid));
1979             if (!name) /* XS module fiddling with the op tree */
1980                 break;
1981             S_op_pretty(aTHX_ kid, &keysv, &key);
1982             assert(SvPOK(name));
1983             sv_chop(name,SvPVX(name)+1);
1984             if (key)
1985       /* diag_listed_as: %%s[%s] in scalar context better written as $%s[%s] */
1986                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
1987                            "%%%" SVf "%c%s%c in scalar context better written "
1988                            "as $%" SVf "%c%s%c",
1989                             SVfARG(name), lbrack, key, rbrack, SVfARG(name),
1990                             lbrack, key, rbrack);
1991             else
1992       /* diag_listed_as: %%s[%s] in scalar context better written as $%s[%s] */
1993                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
1994                            "%%%" SVf "%c%" SVf "%c in scalar context better "
1995                            "written as $%" SVf "%c%" SVf "%c",
1996                             SVfARG(name), lbrack, SVfARG(keysv), rbrack,
1997                             SVfARG(name), lbrack, SVfARG(keysv), rbrack);
1998         }
1999         } /* switch */
2000
2001         /* If next_kid is set, someone in the code above wanted us to process
2002          * that kid and all its remaining siblings.  Otherwise, work our way
2003          * back up the tree */
2004       do_next:
2005         while (!next_kid) {
2006             if (o == top_op)
2007                 return top_op; /* at top; no parents/siblings to try */
2008             if (OpHAS_SIBLING(o))
2009                 next_kid = o->op_sibparent;
2010             else {
2011                 o = o->op_sibparent; /*try parent's next sibling */
2012                 switch (o->op_type) {
2013                 case OP_SCOPE:
2014                 case OP_LINESEQ:
2015                 case OP_LIST:
2016                 case OP_LEAVE:
2017                 case OP_LEAVETRY:
2018                     /* should really restore PL_curcop to its old value, but
2019                      * setting it to PL_compiling is better than do nothing */
2020                     PL_curcop = &PL_compiling;
2021                 }
2022             }
2023         }
2024         o = next_kid;
2025     } /* while */
2026 }
2027
2028
2029 /* apply void context to the optree arg */
2030
2031 OP *
2032 Perl_scalarvoid(pTHX_ OP *arg)
2033 {
2034     dVAR;
2035     OP *kid;
2036     SV* sv;
2037     OP *o = arg;
2038
2039     PERL_ARGS_ASSERT_SCALARVOID;
2040
2041     while (1) {
2042         U8 want;
2043         SV *useless_sv = NULL;
2044         const char* useless = NULL;
2045         OP * next_kid = NULL;
2046
2047         if (o->op_type == OP_NEXTSTATE
2048             || o->op_type == OP_DBSTATE
2049             || (o->op_type == OP_NULL && (o->op_targ == OP_NEXTSTATE
2050                                           || o->op_targ == OP_DBSTATE)))
2051             PL_curcop = (COP*)o;                /* for warning below */
2052
2053         /* assumes no premature commitment */
2054         want = o->op_flags & OPf_WANT;
2055         if ((want && want != OPf_WANT_SCALAR)
2056             || (PL_parser && PL_parser->error_count)
2057             || o->op_type == OP_RETURN || o->op_type == OP_REQUIRE || o->op_type == OP_LEAVEWHEN)
2058         {
2059             goto get_next_op;
2060         }
2061
2062         if ((o->op_private & OPpTARGET_MY)
2063             && (PL_opargs[o->op_type] & OA_TARGLEX))/* OPp share the meaning */
2064         {
2065             /* newASSIGNOP has already applied scalar context, which we
2066                leave, as if this op is inside SASSIGN.  */
2067             goto get_next_op;
2068         }
2069
2070         o->op_flags = (o->op_flags & ~OPf_WANT) | OPf_WANT_VOID;
2071
2072         switch (o->op_type) {
2073         default:
2074             if (!(PL_opargs[o->op_type] & OA_FOLDCONST))
2075                 break;
2076             /* FALLTHROUGH */
2077         case OP_REPEAT:
2078             if (o->op_flags & OPf_STACKED)
2079                 break;
2080             if (o->op_type == OP_REPEAT)
2081                 scalar(cBINOPo->op_first);
2082             goto func_ops;
2083         case OP_CONCAT:
2084             if ((o->op_flags & OPf_STACKED) &&
2085                     !(o->op_private & OPpCONCAT_NESTED))
2086                 break;
2087             goto func_ops;
2088         case OP_SUBSTR:
2089             if (o->op_private == 4)
2090                 break;
2091             /* FALLTHROUGH */
2092         case OP_WANTARRAY:
2093         case OP_GV:
2094         case OP_SMARTMATCH:
2095         case OP_AV2ARYLEN:
2096         case OP_REF:
2097         case OP_REFGEN:
2098         case OP_SREFGEN:
2099         case OP_DEFINED:
2100         case OP_HEX:
2101         case OP_OCT:
2102         case OP_LENGTH:
2103         case OP_VEC:
2104         case OP_INDEX:
2105         case OP_RINDEX:
2106         case OP_SPRINTF:
2107         case OP_KVASLICE:
2108         case OP_KVHSLICE:
2109         case OP_UNPACK:
2110         case OP_PACK:
2111         case OP_JOIN:
2112         case OP_LSLICE:
2113         case OP_ANONLIST:
2114         case OP_ANONHASH:
2115         case OP_SORT:
2116         case OP_REVERSE:
2117         case OP_RANGE:
2118         case OP_FLIP:
2119         case OP_FLOP:
2120         case OP_CALLER:
2121         case OP_FILENO:
2122         case OP_EOF:
2123         case OP_TELL:
2124         case OP_GETSOCKNAME:
2125         case OP_GETPEERNAME:
2126         case OP_READLINK:
2127         case OP_TELLDIR:
2128         case OP_GETPPID:
2129         case OP_GETPGRP:
2130         case OP_GETPRIORITY:
2131         case OP_TIME:
2132         case OP_TMS:
2133         case OP_LOCALTIME:
2134         case OP_GMTIME:
2135         case OP_GHBYNAME:
2136         case OP_GHBYADDR:
2137         case OP_GHOSTENT:
2138         case OP_GNBYNAME:
2139         case OP_GNBYADDR:
2140         case OP_GNETENT:
2141         case OP_GPBYNAME:
2142         case OP_GPBYNUMBER:
2143         case OP_GPROTOENT:
2144         case OP_GSBYNAME:
2145         case OP_GSBYPORT:
2146         case OP_GSERVENT:
2147         case OP_GPWNAM:
2148         case OP_GPWUID:
2149         case OP_GGRNAM:
2150         case OP_GGRGID:
2151         case OP_GETLOGIN:
2152         case OP_PROTOTYPE:
2153         case OP_RUNCV:
2154         func_ops:
2155             useless = OP_DESC(o);
2156             break;
2157
2158         case OP_GVSV:
2159         case OP_PADSV:
2160         case OP_PADAV:
2161         case OP_PADHV:
2162         case OP_PADANY:
2163         case OP_AELEM:
2164         case OP_AELEMFAST:
2165         case OP_AELEMFAST_LEX:
2166         case OP_ASLICE:
2167         case OP_HELEM:
2168         case OP_HSLICE:
2169             if (!(o->op_private & (OPpLVAL_INTRO|OPpOUR_INTRO)))
2170                 /* Otherwise it's "Useless use of grep iterator" */
2171                 useless = OP_DESC(o);
2172             break;
2173
2174         case OP_SPLIT:
2175             if (!(o->op_private & OPpSPLIT_ASSIGN))
2176                 useless = OP_DESC(o);
2177             break;
2178
2179         case OP_NOT:
2180             kid = cUNOPo->op_first;
2181             if (kid->op_type != OP_MATCH && kid->op_type != OP_SUBST &&
2182                 kid->op_type != OP_TRANS && kid->op_type != OP_TRANSR) {
2183                 goto func_ops;
2184             }
2185             useless = "negative pattern binding (!~)";
2186             break;
2187
2188         case OP_SUBST:
2189             if (cPMOPo->op_pmflags & PMf_NONDESTRUCT)
2190                 useless = "non-destructive substitution (s///r)";
2191             break;
2192
2193         case OP_TRANSR:
2194             useless = "non-destructive transliteration (tr///r)";
2195             break;
2196
2197         case OP_RV2GV:
2198         case OP_RV2SV:
2199         case OP_RV2AV:
2200         case OP_RV2HV:
2201             if (!(o->op_private & (OPpLVAL_INTRO|OPpOUR_INTRO)) &&
2202                 (!OpHAS_SIBLING(o) || OpSIBLING(o)->op_type != OP_READLINE))
2203                 useless = "a variable";
2204             break;
2205
2206         case OP_CONST:
2207             sv = cSVOPo_sv;
2208             if (cSVOPo->op_private & OPpCONST_STRICT)
2209                 no_bareword_allowed(o);
2210             else {
2211                 if (ckWARN(WARN_VOID)) {
2212                     NV nv;
2213                     /* don't warn on optimised away booleans, eg
2214                      * use constant Foo, 5; Foo || print; */
2215                     if (cSVOPo->op_private & OPpCONST_SHORTCIRCUIT)
2216                         useless = NULL;
2217                     /* the constants 0 and 1 are permitted as they are
2218                        conventionally used as dummies in constructs like
2219                        1 while some_condition_with_side_effects;  */
2220                     else if (SvNIOK(sv) && ((nv = SvNV(sv)) == 0.0 || nv == 1.0))
2221                         useless = NULL;
2222                     else if (SvPOK(sv)) {
2223                         SV * const dsv = newSVpvs("");
2224                         useless_sv
2225                             = Perl_newSVpvf(aTHX_
2226                                             "a constant (%s)",
2227                                             pv_pretty(dsv, SvPVX_const(sv),
2228                                                       SvCUR(sv), 32, NULL, NULL,
2229                                                       PERL_PV_PRETTY_DUMP
2230                                                       | PERL_PV_ESCAPE_NOCLEAR
2231                                                       | PERL_PV_ESCAPE_UNI_DETECT));
2232                         SvREFCNT_dec_NN(dsv);
2233                     }
2234                     else if (SvOK(sv)) {
2235                         useless_sv = Perl_newSVpvf(aTHX_ "a constant (%" SVf ")", SVfARG(sv));
2236                     }
2237                     else
2238                         useless = "a constant (undef)";
2239                 }
2240             }
2241             op_null(o);         /* don't execute or even remember it */
2242             break;
2243
2244         case OP_POSTINC:
2245             OpTYPE_set(o, OP_PREINC);  /* pre-increment is faster */
2246             break;
2247
2248         case OP_POSTDEC:
2249             OpTYPE_set(o, OP_PREDEC);  /* pre-decrement is faster */
2250             break;
2251
2252         case OP_I_POSTINC:
2253             OpTYPE_set(o, OP_I_PREINC);        /* pre-increment is faster */
2254             break;
2255
2256         case OP_I_POSTDEC:
2257             OpTYPE_set(o, OP_I_PREDEC);        /* pre-decrement is faster */
2258             break;
2259
2260         case OP_SASSIGN: {
2261             OP *rv2gv;
2262             UNOP *refgen, *rv2cv;
2263             LISTOP *exlist;
2264
2265             if ((o->op_private & ~OPpASSIGN_BACKWARDS) != 2)
2266                 break;
2267
2268             rv2gv = ((BINOP *)o)->op_last;
2269             if (!rv2gv || rv2gv->op_type != OP_RV2GV)
2270                 break;
2271
2272             refgen = (UNOP *)((BINOP *)o)->op_first;
2273
2274             if (!refgen || (refgen->op_type != OP_REFGEN
2275                             && refgen->op_type != OP_SREFGEN))
2276                 break;
2277
2278             exlist = (LISTOP *)refgen->op_first;
2279             if (!exlist || exlist->op_type != OP_NULL
2280                 || exlist->op_targ != OP_LIST)
2281                 break;
2282
2283             if (exlist->op_first->op_type != OP_PUSHMARK
2284                 && exlist->op_first != exlist->op_last)
2285                 break;
2286
2287             rv2cv = (UNOP*)exlist->op_last;
2288
2289             if (rv2cv->op_type != OP_RV2CV)
2290                 break;
2291
2292             assert ((rv2gv->op_private & OPpDONT_INIT_GV) == 0);
2293             assert ((o->op_private & OPpASSIGN_CV_TO_GV) == 0);
2294             assert ((rv2cv->op_private & OPpMAY_RETURN_CONSTANT) == 0);
2295
2296             o->op_private |= OPpASSIGN_CV_TO_GV;
2297             rv2gv->op_private |= OPpDONT_INIT_GV;
2298             rv2cv->op_private |= OPpMAY_RETURN_CONSTANT;
2299
2300             break;
2301         }
2302
2303         case OP_AASSIGN: {
2304             inplace_aassign(o);
2305             break;
2306         }
2307
2308         case OP_OR:
2309         case OP_AND:
2310             kid = cLOGOPo->op_first;
2311             if (kid->op_type == OP_NOT
2312                 && (kid->op_flags & OPf_KIDS)) {
2313                 if (o->op_type == OP_AND) {
2314                     OpTYPE_set(o, OP_OR);
2315                 } else {
2316                     OpTYPE_set(o, OP_AND);
2317                 }
2318                 op_null(kid);
2319             }
2320             /* FALLTHROUGH */
2321
2322         case OP_DOR:
2323         case OP_COND_EXPR:
2324         case OP_ENTERGIVEN:
2325         case OP_ENTERWHEN:
2326             next_kid = OpSIBLING(cUNOPo->op_first);
2327         break;
2328
2329         case OP_NULL:
2330             if (o->op_flags & OPf_STACKED)
2331                 break;
2332             /* FALLTHROUGH */
2333         case OP_NEXTSTATE:
2334         case OP_DBSTATE:
2335         case OP_ENTERTRY:
2336         case OP_ENTER:
2337             if (!(o->op_flags & OPf_KIDS))
2338                 break;
2339             /* FALLTHROUGH */
2340         case OP_SCOPE:
2341         case OP_LEAVE:
2342         case OP_LEAVETRY:
2343         case OP_LEAVELOOP:
2344         case OP_LINESEQ:
2345         case OP_LEAVEGIVEN:
2346         case OP_LEAVEWHEN:
2347         kids:
2348             next_kid = cLISTOPo->op_first;
2349             break;
2350         case OP_LIST:
2351             /* If the first kid after pushmark is something that the padrange
2352                optimisation would reject, then null the list and the pushmark.
2353             */
2354             if ((kid = cLISTOPo->op_first)->op_type == OP_PUSHMARK
2355                 && (  !(kid = OpSIBLING(kid))
2356                       || (  kid->op_type != OP_PADSV
2357                             && kid->op_type != OP_PADAV
2358                             && kid->op_type != OP_PADHV)
2359                       || kid->op_private & ~OPpLVAL_INTRO
2360                       || !(kid = OpSIBLING(kid))
2361                       || (  kid->op_type != OP_PADSV
2362                             && kid->op_type != OP_PADAV
2363                             && kid->op_type != OP_PADHV)
2364                       || kid->op_private & ~OPpLVAL_INTRO)
2365             ) {
2366                 op_null(cUNOPo->op_first); /* NULL the pushmark */
2367                 op_null(o); /* NULL the list */
2368             }
2369             goto kids;
2370         case OP_ENTEREVAL:
2371             scalarkids(o);
2372             break;
2373         case OP_SCALAR:
2374             scalar(o);
2375             break;
2376         }
2377
2378         if (useless_sv) {
2379             /* mortalise it, in case warnings are fatal.  */
2380             Perl_ck_warner(aTHX_ packWARN(WARN_VOID),
2381                            "Useless use of %" SVf " in void context",
2382                            SVfARG(sv_2mortal(useless_sv)));
2383         }
2384         else if (useless) {
2385             Perl_ck_warner(aTHX_ packWARN(WARN_VOID),
2386                            "Useless use of %s in void context",
2387                            useless);
2388         }
2389
2390       get_next_op:
2391         /* if a kid hasn't been nominated to process, continue with the
2392          * next sibling, or if no siblings left, go back to the parent's
2393          * siblings and so on
2394          */
2395         while (!next_kid) {
2396             if (o == arg)
2397                 return arg; /* at top; no parents/siblings to try */
2398             if (OpHAS_SIBLING(o))
2399                 next_kid = o->op_sibparent;
2400             else
2401                 o = o->op_sibparent; /*try parent's next sibling */
2402         }
2403         o = next_kid;
2404     }
2405
2406     return arg;
2407 }
2408
2409
2410 static OP *
2411 S_listkids(pTHX_ OP *o)
2412 {
2413     if (o && o->op_flags & OPf_KIDS) {
2414         OP *kid;
2415         for (kid = cLISTOPo->op_first; kid; kid = OpSIBLING(kid))
2416             list(kid);
2417     }
2418     return o;
2419 }
2420
2421
2422 /* apply list context to the o subtree */
2423
2424 OP *
2425 Perl_list(pTHX_ OP *o)
2426 {
2427     OP * top_op = o;
2428
2429     while (1) {
2430         OP *next_kid = NULL; /* what op (if any) to process next */
2431
2432         OP *kid;
2433
2434         /* assumes no premature commitment */
2435         if (!o || (o->op_flags & OPf_WANT)
2436              || (PL_parser && PL_parser->error_count)
2437              || o->op_type == OP_RETURN)
2438         {
2439             goto do_next;
2440         }
2441
2442         if ((o->op_private & OPpTARGET_MY)
2443             && (PL_opargs[o->op_type] & OA_TARGLEX))/* OPp share the meaning */
2444         {
2445             goto do_next;                               /* As if inside SASSIGN */
2446         }
2447
2448         o->op_flags = (o->op_flags & ~OPf_WANT) | OPf_WANT_LIST;
2449
2450         switch (o->op_type) {
2451         case OP_REPEAT:
2452             if (o->op_private & OPpREPEAT_DOLIST
2453              && !(o->op_flags & OPf_STACKED))
2454             {
2455                 list(cBINOPo->op_first);
2456                 kid = cBINOPo->op_last;
2457                 /* optimise away (.....) x 1 */
2458                 if (kid->op_type == OP_CONST && SvIOK(kSVOP_sv)
2459                  && SvIVX(kSVOP_sv) == 1)
2460                 {
2461                     op_null(o); /* repeat */
2462                     op_null(cUNOPx(cBINOPo->op_first)->op_first);/* pushmark */
2463                     /* const (rhs): */
2464                     op_free(op_sibling_splice(o, cBINOPo->op_first, 1, NULL));
2465                 }
2466             }
2467             break;
2468
2469         case OP_OR:
2470         case OP_AND:
2471         case OP_COND_EXPR:
2472             /* impose list context on everything except the condition */
2473             next_kid = OpSIBLING(cUNOPo->op_first);
2474             break;
2475
2476         default:
2477             if (!(o->op_flags & OPf_KIDS))
2478                 break;
2479             /* possibly flatten 1..10 into a constant array */
2480             if (!o->op_next && cUNOPo->op_first->op_type == OP_FLOP) {
2481                 list(cBINOPo->op_first);
2482                 gen_constant_list(o);
2483                 goto do_next;
2484             }
2485             next_kid = cUNOPo->op_first; /* do all kids */
2486             break;
2487
2488         case OP_LIST:
2489             if (cLISTOPo->op_first->op_type == OP_PUSHMARK) {
2490                 op_null(cUNOPo->op_first); /* NULL the pushmark */
2491                 op_null(o); /* NULL the list */
2492             }
2493             if (o->op_flags & OPf_KIDS)
2494                 next_kid = cUNOPo->op_first; /* do all kids */
2495             break;
2496
2497         /* the children of these ops are usually a list of statements,
2498          * except the leaves, whose first child is a corresponding enter
2499          */
2500         case OP_SCOPE:
2501         case OP_LINESEQ:
2502             kid = cLISTOPo->op_first;
2503             goto do_kids;
2504         case OP_LEAVE:
2505         case OP_LEAVETRY:
2506             kid = cLISTOPo->op_first;
2507             list(kid);
2508             kid = OpSIBLING(kid);
2509         do_kids:
2510             while (kid) {
2511                 OP *sib = OpSIBLING(kid);
2512                 /* Apply void context to all kids except the last, which
2513                  * is list. E.g.
2514                  *      @a = do { void; void; list }
2515                  * Except that 'when's are always list context, e.g.
2516                  *      @a = do { given(..) {
2517                     *                 when (..) { list }
2518                     *                 when (..) { list }
2519                     *                 ...
2520                     *                }}
2521                     */
2522                 if (!sib) {
2523                     /* tail call optimise calling list() on the last kid */
2524                     next_kid = kid;
2525                     goto do_next;
2526                 }
2527                 else if (kid->op_type == OP_LEAVEWHEN)
2528                     list(kid);
2529                 else
2530                     scalarvoid(kid);
2531                 kid = sib;
2532             }
2533             NOT_REACHED; /* NOTREACHED */
2534             break;
2535
2536         }
2537
2538         /* If next_kid is set, someone in the code above wanted us to process
2539          * that kid and all its remaining siblings.  Otherwise, work our way
2540          * back up the tree */
2541       do_next:
2542         while (!next_kid) {
2543             if (o == top_op)
2544                 return top_op; /* at top; no parents/siblings to try */
2545             if (OpHAS_SIBLING(o))
2546                 next_kid = o->op_sibparent;
2547             else {
2548                 o = o->op_sibparent; /*try parent's next sibling */
2549                 switch (o->op_type) {
2550                 case OP_SCOPE:
2551                 case OP_LINESEQ:
2552                 case OP_LIST:
2553                 case OP_LEAVE:
2554                 case OP_LEAVETRY:
2555                     /* should really restore PL_curcop to its old value, but
2556                      * setting it to PL_compiling is better than do nothing */
2557                     PL_curcop = &PL_compiling;
2558                 }
2559             }
2560
2561
2562         }
2563         o = next_kid;
2564     } /* while */
2565 }
2566
2567
2568 static OP *
2569 S_scalarseq(pTHX_ OP *o)
2570 {
2571     if (o) {
2572         const OPCODE type = o->op_type;
2573
2574         if (type == OP_LINESEQ || type == OP_SCOPE ||
2575             type == OP_LEAVE || type == OP_LEAVETRY)
2576         {
2577             OP *kid, *sib;
2578             for (kid = cLISTOPo->op_first; kid; kid = sib) {
2579                 if ((sib = OpSIBLING(kid))
2580                  && (  OpHAS_SIBLING(sib) || sib->op_type != OP_NULL
2581                     || (  sib->op_targ != OP_NEXTSTATE
2582                        && sib->op_targ != OP_DBSTATE  )))
2583                 {
2584                     scalarvoid(kid);
2585                 }
2586             }
2587             PL_curcop = &PL_compiling;
2588         }
2589         o->op_flags &= ~OPf_PARENS;
2590         if (PL_hints & HINT_BLOCK_SCOPE)
2591             o->op_flags |= OPf_PARENS;
2592     }
2593     else
2594         o = newOP(OP_STUB, 0);
2595     return o;
2596 }
2597
2598 STATIC OP *
2599 S_modkids(pTHX_ OP *o, I32 type)
2600 {
2601     if (o && o->op_flags & OPf_KIDS) {
2602         OP *kid;
2603         for (kid = cLISTOPo->op_first; kid; kid = OpSIBLING(kid))
2604             op_lvalue(kid, type);
2605     }
2606     return o;
2607 }
2608
2609
2610 /* for a helem/hslice/kvslice, if its a fixed hash, croak on invalid
2611  * const fields. Also, convert CONST keys to HEK-in-SVs.
2612  * rop    is the op that retrieves the hash;
2613  * key_op is the first key
2614  * real   if false, only check (and possibly croak); don't update op
2615  */
2616
2617 STATIC void
2618 S_check_hash_fields_and_hekify(pTHX_ UNOP *rop, SVOP *key_op, int real)
2619 {
2620     PADNAME *lexname;
2621     GV **fields;
2622     bool check_fields;
2623
2624     /* find the padsv corresponding to $lex->{} or @{$lex}{} */
2625     if (rop) {
2626         if (rop->op_first->op_type == OP_PADSV)
2627             /* @$hash{qw(keys here)} */
2628             rop = (UNOP*)rop->op_first;
2629         else {
2630             /* @{$hash}{qw(keys here)} */
2631             if (rop->op_first->op_type == OP_SCOPE
2632                 && cLISTOPx(rop->op_first)->op_last->op_type == OP_PADSV)
2633                 {
2634                     rop = (UNOP*)cLISTOPx(rop->op_first)->op_last;
2635                 }
2636             else
2637                 rop = NULL;
2638         }
2639     }
2640
2641     lexname = NULL; /* just to silence compiler warnings */
2642     fields  = NULL; /* just to silence compiler warnings */
2643
2644     check_fields =
2645             rop
2646          && (lexname = padnamelist_fetch(PL_comppad_name, rop->op_targ),
2647              SvPAD_TYPED(lexname))
2648          && (fields = (GV**)hv_fetchs(PadnameTYPE(lexname), "FIELDS", FALSE))
2649          && isGV(*fields) && GvHV(*fields);
2650
2651     for (; key_op; key_op = (SVOP*)OpSIBLING(key_op)) {
2652         SV **svp, *sv;
2653         if (key_op->op_type != OP_CONST)
2654             continue;
2655         svp = cSVOPx_svp(key_op);
2656
2657         /* make sure it's not a bareword under strict subs */
2658         if (key_op->op_private & OPpCONST_BARE &&
2659             key_op->op_private & OPpCONST_STRICT)
2660         {
2661             no_bareword_allowed((OP*)key_op);
2662         }
2663
2664         /* Make the CONST have a shared SV */
2665         if (   !SvIsCOW_shared_hash(sv = *svp)
2666             && SvTYPE(sv) < SVt_PVMG
2667             && SvOK(sv)
2668             && !SvROK(sv)
2669             && real)
2670         {
2671             SSize_t keylen;
2672             const char * const key = SvPV_const(sv, *(STRLEN*)&keylen);
2673             SV *nsv = newSVpvn_share(key, SvUTF8(sv) ? -keylen : keylen, 0);
2674             SvREFCNT_dec_NN(sv);
2675             *svp = nsv;
2676         }
2677
2678         if (   check_fields
2679             && !hv_fetch_ent(GvHV(*fields), *svp, FALSE, 0))
2680         {
2681             Perl_croak(aTHX_ "No such class field \"%" SVf "\" "
2682                         "in variable %" PNf " of type %" HEKf,
2683                         SVfARG(*svp), PNfARG(lexname),
2684                         HEKfARG(HvNAME_HEK(PadnameTYPE(lexname))));
2685         }
2686     }
2687 }
2688
2689 /* info returned by S_sprintf_is_multiconcatable() */
2690
2691 struct sprintf_ismc_info {
2692     SSize_t nargs;    /* num of args to sprintf (not including the format) */
2693     char  *start;     /* start of raw format string */
2694     char  *end;       /* bytes after end of raw format string */
2695     STRLEN total_len; /* total length (in bytes) of format string, not
2696                          including '%s' and  half of '%%' */
2697     STRLEN variant;   /* number of bytes by which total_len_p would grow
2698                          if upgraded to utf8 */
2699     bool   utf8;      /* whether the format is utf8 */
2700 };
2701
2702
2703 /* is the OP_SPRINTF o suitable for converting into a multiconcat op?
2704  * i.e. its format argument is a const string with only '%s' and '%%'
2705  * formats, and the number of args is known, e.g.
2706  *    sprintf "a=%s f=%s", $a[0], scalar(f());
2707  * but not
2708  *    sprintf "i=%d a=%s f=%s", $i, @a, f();
2709  *
2710  * If successful, the sprintf_ismc_info struct pointed to by info will be
2711  * populated.
2712  */
2713
2714 STATIC bool
2715 S_sprintf_is_multiconcatable(pTHX_ OP *o,struct sprintf_ismc_info *info)
2716 {
2717     OP    *pm, *constop, *kid;
2718     SV    *sv;
2719     char  *s, *e, *p;
2720     SSize_t nargs, nformats;
2721     STRLEN cur, total_len, variant;
2722     bool   utf8;
2723
2724     /* if sprintf's behaviour changes, die here so that someone
2725      * can decide whether to enhance this function or skip optimising
2726      * under those new circumstances */
2727     assert(!(o->op_flags & OPf_STACKED));
2728     assert(!(PL_opargs[OP_SPRINTF] & OA_TARGLEX));
2729     assert(!(o->op_private & ~OPpARG4_MASK));
2730
2731     pm = cUNOPo->op_first;
2732     if (pm->op_type != OP_PUSHMARK) /* weird coreargs stuff */
2733         return FALSE;
2734     constop = OpSIBLING(pm);
2735     if (!constop || constop->op_type != OP_CONST)
2736         return FALSE;
2737     sv = cSVOPx_sv(constop);
2738     if (SvMAGICAL(sv) || !SvPOK(sv))
2739         return FALSE;
2740
2741     s = SvPV(sv, cur);
2742     e = s + cur;
2743
2744     /* Scan format for %% and %s and work out how many %s there are.
2745      * Abandon if other format types are found.
2746      */
2747
2748     nformats  = 0;
2749     total_len = 0;
2750     variant   = 0;
2751
2752     for (p = s; p < e; p++) {
2753         if (*p != '%') {
2754             total_len++;
2755             if (!UTF8_IS_INVARIANT(*p))
2756                 variant++;
2757             continue;
2758         }
2759         p++;
2760         if (p >= e)
2761             return FALSE; /* lone % at end gives "Invalid conversion" */
2762         if (*p == '%')
2763             total_len++;
2764         else if (*p == 's')
2765             nformats++;
2766         else
2767             return FALSE;
2768     }
2769
2770     if (!nformats || nformats > PERL_MULTICONCAT_MAXARG)
2771         return FALSE;
2772
2773     utf8 = cBOOL(SvUTF8(sv));
2774     if (utf8)
2775         variant = 0;
2776
2777     /* scan args; they must all be in scalar cxt */
2778
2779     nargs = 0;
2780     kid = OpSIBLING(constop);
2781
2782     while (kid) {
2783         if ((kid->op_flags & OPf_WANT) != OPf_WANT_SCALAR)
2784             return FALSE;
2785         nargs++;
2786         kid = OpSIBLING(kid);
2787     }
2788
2789     if (nargs != nformats)
2790         return FALSE; /* e.g. sprintf("%s%s", $a); */
2791
2792
2793     info->nargs      = nargs;
2794     info->start      = s;
2795     info->end        = e;
2796     info->total_len  = total_len;
2797     info->variant    = variant;
2798     info->utf8       = utf8;
2799
2800     return TRUE;
2801 }
2802
2803
2804
2805 /* S_maybe_multiconcat():
2806  *
2807  * given an OP_STRINGIFY, OP_SASSIGN, OP_CONCAT or OP_SPRINTF op, possibly
2808  * convert it (and its children) into an OP_MULTICONCAT. See the code
2809  * comments just before pp_multiconcat() for the full details of what
2810  * OP_MULTICONCAT supports.
2811  *
2812  * Basically we're looking for an optree with a chain of OP_CONCATS down
2813  * the LHS (or an OP_SPRINTF), with possibly an OP_SASSIGN, and/or
2814  * OP_STRINGIFY, and/or OP_CONCAT acting as '.=' at its head, e.g.
2815  *
2816  *      $x = "$a$b-$c"
2817  *
2818  *  looks like
2819  *
2820  *      SASSIGN
2821  *         |
2822  *      STRINGIFY   -- PADSV[$x]
2823  *         |
2824  *         |
2825  *      ex-PUSHMARK -- CONCAT/S
2826  *                        |
2827  *                     CONCAT/S  -- PADSV[$d]
2828  *                        |
2829  *                     CONCAT    -- CONST["-"]
2830  *                        |
2831  *                     PADSV[$a] -- PADSV[$b]
2832  *
2833  * Note that at this stage the OP_SASSIGN may have already been optimised
2834  * away with OPpTARGET_MY set on the OP_STRINGIFY or OP_CONCAT.
2835  */
2836
2837 STATIC void
2838 S_maybe_multiconcat(pTHX_ OP *o)
2839 {
2840     dVAR;
2841     OP *lastkidop;   /* the right-most of any kids unshifted onto o */
2842     OP *topop;       /* the top-most op in the concat tree (often equals o,
2843                         unless there are assign/stringify ops above it */
2844     OP *parentop;    /* the parent op of topop (or itself if no parent) */
2845     OP *targmyop;    /* the op (if any) with the OPpTARGET_MY flag */
2846     OP *targetop;    /* the op corresponding to target=... or target.=... */
2847     OP *stringop;    /* the OP_STRINGIFY op, if any */
2848     OP *nextop;      /* used for recreating the op_next chain without consts */
2849     OP *kid;         /* general-purpose op pointer */
2850     UNOP_AUX_item *aux;
2851     UNOP_AUX_item *lenp;
2852     char *const_str, *p;
2853     struct sprintf_ismc_info sprintf_info;
2854
2855                      /* store info about each arg in args[];
2856                       * toparg is the highest used slot; argp is a general
2857                       * pointer to args[] slots */
2858     struct {
2859         void *p;      /* initially points to const sv (or null for op);
2860                          later, set to SvPV(constsv), with ... */
2861         STRLEN len;   /* ... len set to SvPV(..., len) */
2862     } *argp, *toparg, args[PERL_MULTICONCAT_MAXARG*2 + 1];
2863
2864     SSize_t nargs  = 0;
2865     SSize_t nconst = 0;
2866     SSize_t nadjconst  = 0; /* adjacent consts - may be demoted to args */
2867     STRLEN variant;
2868     bool utf8 = FALSE;
2869     bool kid_is_last = FALSE; /* most args will be the RHS kid of a concat op;
2870                                  the last-processed arg will the LHS of one,
2871                                  as args are processed in reverse order */
2872     U8   stacked_last = 0;   /* whether the last seen concat op was STACKED */
2873     STRLEN total_len  = 0;   /* sum of the lengths of the const segments */
2874     U8 flags          = 0;   /* what will become the op_flags and ... */
2875     U8 private_flags  = 0;   /* ... op_private of the multiconcat op */
2876     bool is_sprintf = FALSE; /* we're optimising an sprintf */
2877     bool is_targable  = FALSE; /* targetop is an OPpTARGET_MY candidate */
2878     bool prev_was_const = FALSE; /* previous arg was a const */
2879
2880     /* -----------------------------------------------------------------
2881      * Phase 1:
2882      *
2883      * Examine the optree non-destructively to determine whether it's
2884      * suitable to be converted into an OP_MULTICONCAT. Accumulate
2885      * information about the optree in args[].
2886      */
2887
2888     argp     = args;
2889     targmyop = NULL;
2890     targetop = NULL;
2891     stringop = NULL;
2892     topop    = o;
2893     parentop = o;
2894
2895     assert(   o->op_type == OP_SASSIGN
2896            || o->op_type == OP_CONCAT
2897            || o->op_type == OP_SPRINTF
2898            || o->op_type == OP_STRINGIFY);
2899
2900     Zero(&sprintf_info, 1, struct sprintf_ismc_info);
2901
2902     /* first see if, at the top of the tree, there is an assign,
2903      * append and/or stringify */
2904
2905     if (topop->op_type == OP_SASSIGN) {
2906         /* expr = ..... */
2907         if (o->op_ppaddr != PL_ppaddr[OP_SASSIGN])
2908             return;
2909         if (o->op_private & (OPpASSIGN_BACKWARDS|OPpASSIGN_CV_TO_GV))
2910             return;
2911         assert(!(o->op_private & ~OPpARG2_MASK)); /* barf on unknown flags */
2912
2913         parentop = topop;
2914         topop = cBINOPo->op_first;
2915         targetop = OpSIBLING(topop);
2916         if (!targetop) /* probably some sort of syntax error */
2917             return;
2918
2919         /* don't optimise away assign in 'local $foo = ....' */
2920         if (   (targetop->op_private & OPpLVAL_INTRO)
2921             /* these are the common ops which do 'local', but
2922              * not all */
2923             && (   targetop->op_type == OP_GVSV
2924                 || targetop->op_type == OP_RV2SV
2925                 || targetop->op_type == OP_AELEM
2926                 || targetop->op_type == OP_HELEM
2927                 )
2928         )
2929             return;
2930     }
2931     else if (   topop->op_type == OP_CONCAT
2932              && (topop->op_flags & OPf_STACKED)
2933              && (!(topop->op_private & OPpCONCAT_NESTED))
2934             )
2935     {
2936         /* expr .= ..... */
2937
2938         /* OPpTARGET_MY shouldn't be able to be set here. If it is,
2939          * decide what to do about it */
2940         assert(!(o->op_private & OPpTARGET_MY));
2941
2942         /* barf on unknown flags */
2943         assert(!(o->op_private & ~(OPpARG2_MASK|OPpTARGET_MY)));
2944         private_flags |= OPpMULTICONCAT_APPEND;
2945         targetop = cBINOPo->op_first;
2946         parentop = topop;
2947         topop    = OpSIBLING(targetop);
2948
2949         /* $x .= <FOO> gets optimised to rcatline instead */
2950         if (topop->op_type == OP_READLINE)
2951             return;
2952     }
2953
2954     if (targetop) {
2955         /* Can targetop (the LHS) if it's a padsv, be be optimised
2956          * away and use OPpTARGET_MY instead?
2957          */
2958         if (    (targetop->op_type == OP_PADSV)
2959             && !(targetop->op_private & OPpDEREF)
2960             && !(targetop->op_private & OPpPAD_STATE)
2961                /* we don't support 'my $x .= ...' */
2962             && (   o->op_type == OP_SASSIGN
2963                 || !(targetop->op_private & OPpLVAL_INTRO))
2964         )
2965             is_targable = TRUE;
2966     }
2967
2968     if (topop->op_type == OP_STRINGIFY) {
2969         if (topop->op_ppaddr != PL_ppaddr[OP_STRINGIFY])
2970             return;
2971         stringop = topop;
2972
2973         /* barf on unknown flags */
2974         assert(!(o->op_private & ~(OPpARG4_MASK|OPpTARGET_MY)));
2975
2976         if ((topop->op_private & OPpTARGET_MY)) {
2977             if (o->op_type == OP_SASSIGN)
2978                 return; /* can't have two assigns */
2979             targmyop = topop;
2980         }
2981
2982         private_flags |= OPpMULTICONCAT_STRINGIFY;
2983         parentop = topop;
2984         topop = cBINOPx(topop)->op_first;
2985         assert(OP_TYPE_IS_OR_WAS_NN(topop, OP_PUSHMARK));
2986         topop = OpSIBLING(topop);
2987     }
2988
2989     if (topop->op_type == OP_SPRINTF) {
2990         if (topop->op_ppaddr != PL_ppaddr[OP_SPRINTF])
2991             return;
2992         if (S_sprintf_is_multiconcatable(aTHX_ topop, &sprintf_info)) {
2993             nargs     = sprintf_info.nargs;
2994             total_len = sprintf_info.total_len;
2995             variant   = sprintf_info.variant;
2996             utf8      = sprintf_info.utf8;
2997             is_sprintf = TRUE;
2998             private_flags |= OPpMULTICONCAT_FAKE;
2999             toparg = argp;
3000             /* we have an sprintf op rather than a concat optree.
3001              * Skip most of the code below which is associated with
3002              * processing that optree. We also skip phase 2, determining
3003              * whether its cost effective to optimise, since for sprintf,
3004              * multiconcat is *always* faster */
3005             goto create_aux;
3006         }
3007         /* note that even if the sprintf itself isn't multiconcatable,
3008          * the expression as a whole may be, e.g. in
3009          *    $x .= sprintf("%d",...)
3010          * the sprintf op will be left as-is, but the concat/S op may
3011          * be upgraded to multiconcat
3012          */
3013     }
3014     else if (topop->op_type == OP_CONCAT) {
3015         if (topop->op_ppaddr != PL_ppaddr[OP_CONCAT])
3016             return;
3017
3018         if ((topop->op_private & OPpTARGET_MY)) {
3019             if (o->op_type == OP_SASSIGN || targmyop)
3020                 return; /* can't have two assigns */
3021             targmyop = topop;
3022         }
3023     }
3024
3025     /* Is it safe to convert a sassign/stringify/concat op into
3026      * a multiconcat? */
3027     assert((PL_opargs[OP_SASSIGN]   & OA_CLASS_MASK) == OA_BINOP);
3028     assert((PL_opargs[OP_CONCAT]    & OA_CLASS_MASK) == OA_BINOP);
3029     assert((PL_opargs[OP_STRINGIFY] & OA_CLASS_MASK) == OA_LISTOP);
3030     assert((PL_opargs[OP_SPRINTF]   & OA_CLASS_MASK) == OA_LISTOP);
3031     STATIC_ASSERT_STMT(   STRUCT_OFFSET(BINOP,    op_last)
3032                        == STRUCT_OFFSET(UNOP_AUX, op_aux));
3033     STATIC_ASSERT_STMT(   STRUCT_OFFSET(LISTOP,   op_last)
3034                        == STRUCT_OFFSET(UNOP_AUX, op_aux));
3035
3036     /* Now scan the down the tree looking for a series of
3037      * CONCAT/OPf_STACKED ops on the LHS (with the last one not
3038      * stacked). For example this tree:
3039      *
3040      *     |
3041      *   CONCAT/STACKED
3042      *     |
3043      *   CONCAT/STACKED -- EXPR5
3044      *     |
3045      *   CONCAT/STACKED -- EXPR4
3046      *     |
3047      *   CONCAT -- EXPR3
3048      *     |
3049      *   EXPR1  -- EXPR2
3050      *
3051      * corresponds to an expression like
3052      *
3053      *   (EXPR1 . EXPR2 . EXPR3 . EXPR4 . EXPR5)
3054      *
3055      * Record info about each EXPR in args[]: in particular, whether it is
3056      * a stringifiable OP_CONST and if so what the const sv is.
3057      *
3058      * The reason why the last concat can't be STACKED is the difference
3059      * between
3060      *
3061      *    ((($a .= $a) .= $a) .= $a) .= $a
3062      *
3063      * and
3064      *    $a . $a . $a . $a . $a
3065      *
3066      * The main difference between the optrees for those two constructs
3067      * is the presence of the last STACKED. As well as modifying $a,
3068      * the former sees the changed $a between each concat, so if $s is
3069      * initially 'a', the first returns 'a' x 16, while the latter returns
3070      * 'a' x 5. And pp_multiconcat can't handle that kind of thing.
3071      */
3072
3073     kid = topop;
3074
3075     for (;;) {
3076         OP *argop;
3077         SV *sv;
3078         bool last = FALSE;
3079
3080         if (    kid->op_type == OP_CONCAT
3081             && !kid_is_last
3082         ) {
3083             OP *k1, *k2;
3084             k1 = cUNOPx(kid)->op_first;
3085             k2 = OpSIBLING(k1);
3086             /* shouldn't happen except maybe after compile err? */
3087             if (!k2)
3088                 return;
3089
3090             /* avoid turning (A . B . ($lex = C) ...)  into  (A . B . C ...) */
3091             if (kid->op_private & OPpTARGET_MY)
3092                 kid_is_last = TRUE;
3093
3094             stacked_last = (kid->op_flags & OPf_STACKED);
3095             if (!stacked_last)
3096                 kid_is_last = TRUE;
3097
3098             kid   = k1;
3099             argop = k2;
3100         }
3101         else {
3102             argop = kid;
3103             last = TRUE;
3104         }
3105
3106         if (   nargs + nadjconst  >  PERL_MULTICONCAT_MAXARG        - 2
3107             || (argp - args + 1)  > (PERL_MULTICONCAT_MAXARG*2 + 1) - 2)
3108         {
3109             /* At least two spare slots are needed to decompose both
3110              * concat args. If there are no slots left, continue to
3111              * examine the rest of the optree, but don't push new values
3112              * on args[]. If the optree as a whole is legal for conversion
3113              * (in particular that the last concat isn't STACKED), then
3114              * the first PERL_MULTICONCAT_MAXARG elements of the optree
3115              * can be converted into an OP_MULTICONCAT now, with the first
3116              * child of that op being the remainder of the optree -
3117              * which may itself later be converted to a multiconcat op
3118              * too.
3119              */
3120             if (last) {
3121                 /* the last arg is the rest of the optree */
3122                 argp++->p = NULL;
3123                 nargs++;
3124             }
3125         }
3126         else if (   argop->op_type == OP_CONST
3127             && ((sv = cSVOPx_sv(argop)))
3128             /* defer stringification until runtime of 'constant'
3129              * things that might stringify variantly, e.g. the radix
3130              * point of NVs, or overloaded RVs */
3131             && (SvPOK(sv) || SvIOK(sv))
3132             && (!SvGMAGICAL(sv))
3133         ) {
3134             if (argop->op_private & OPpCONST_STRICT)
3135                 no_bareword_allowed(argop);
3136             argp++->p = sv;
3137             utf8   |= cBOOL(SvUTF8(sv));
3138             nconst++;
3139             if (prev_was_const)
3140                 /* this const may be demoted back to a plain arg later;
3141                  * make sure we have enough arg slots left */
3142                 nadjconst++;
3143             prev_was_const = !prev_was_const;
3144         }
3145         else {
3146             argp++->p = NULL;
3147             nargs++;
3148             prev_was_const = FALSE;
3149         }
3150
3151         if (last)
3152             break;
3153     }
3154
3155     toparg = argp - 1;
3156
3157     if (stacked_last)
3158         return; /* we don't support ((A.=B).=C)...) */
3159
3160     /* look for two adjacent consts and don't fold them together:
3161      *     $o . "a" . "b"
3162      * should do
3163      *     $o->concat("a")->concat("b")
3164      * rather than
3165      *     $o->concat("ab")
3166      * (but $o .=  "a" . "b" should still fold)
3167      */
3168     {
3169         bool seen_nonconst = FALSE;
3170         for (argp = toparg; argp >= args; argp--) {
3171             if (argp->p == NULL) {
3172                 seen_nonconst = TRUE;
3173                 continue;
3174             }
3175             if (!seen_nonconst)
3176                 continue;
3177             if (argp[1].p) {
3178                 /* both previous and current arg were constants;
3179                  * leave the current OP_CONST as-is */
3180                 argp->p = NULL;
3181                 nconst--;
3182                 nargs++;
3183             }
3184         }
3185     }
3186
3187     /* -----------------------------------------------------------------
3188      * Phase 2:
3189      *
3190      * At this point we have determined that the optree *can* be converted
3191      * into a multiconcat. Having gathered all the evidence, we now decide
3192      * whether it *should*.
3193      */
3194
3195
3196     /* we need at least one concat action, e.g.:
3197      *
3198      *  Y . Z
3199      *  X = Y . Z
3200      *  X .= Y
3201      *
3202      * otherwise we could be doing something like $x = "foo", which
3203      * if treated as as a concat, would fail to COW.
3204      */
3205     if (nargs + nconst + cBOOL(private_flags & OPpMULTICONCAT_APPEND) < 2)
3206         return;
3207
3208     /* Benchmarking seems to indicate that we gain if:
3209      * * we optimise at least two actions into a single multiconcat
3210      *    (e.g concat+concat, sassign+concat);
3211      * * or if we can eliminate at least 1 OP_CONST;
3212      * * or if we can eliminate a padsv via OPpTARGET_MY
3213      */
3214
3215     if (
3216            /* eliminated at least one OP_CONST */
3217            nconst >= 1
3218            /* eliminated an OP_SASSIGN */
3219         || o->op_type == OP_SASSIGN
3220            /* eliminated an OP_PADSV */
3221         || (!targmyop && is_targable)
3222     )
3223         /* definitely a net gain to optimise */
3224         goto optimise;
3225
3226     /* ... if not, what else? */
3227
3228     /* special-case '$lex1 = expr . $lex1' (where expr isn't lex1):
3229      * multiconcat is faster (due to not creating a temporary copy of
3230      * $lex1), whereas for a general $lex1 = $lex2 . $lex3, concat is
3231      * faster.
3232      */
3233     if (   nconst == 0
3234          && nargs == 2
3235          && targmyop
3236          && topop->op_type == OP_CONCAT
3237     ) {
3238         PADOFFSET t = targmyop->op_targ;
3239         OP *k1 = cBINOPx(topop)->op_first;
3240         OP *k2 = cBINOPx(topop)->op_last;
3241         if (   k2->op_type == OP_PADSV
3242             && k2->op_targ == t
3243             && (   k1->op_type != OP_PADSV
3244                 || k1->op_targ != t)
3245         )
3246             goto optimise;
3247     }
3248
3249     /* need at least two concats */
3250     if (nargs + nconst + cBOOL(private_flags & OPpMULTICONCAT_APPEND) < 3)
3251         return;
3252
3253
3254
3255     /* -----------------------------------------------------------------
3256      * Phase 3:
3257      *
3258      * At this point the optree has been verified as ok to be optimised
3259      * into an OP_MULTICONCAT. Now start changing things.
3260      */
3261
3262    optimise:
3263
3264     /* stringify all const args and determine utf8ness */
3265
3266     variant = 0;
3267     for (argp = args; argp <= toparg; argp++) {
3268         SV *sv = (SV*)argp->p;
3269         if (!sv)
3270             continue; /* not a const op */
3271         if (utf8 && !SvUTF8(sv))
3272             sv_utf8_upgrade_nomg(sv);
3273         argp->p = SvPV_nomg(sv, argp->len);
3274         total_len += argp->len;
3275
3276         /* see if any strings would grow if converted to utf8 */
3277         if (!utf8) {
3278             variant += variant_under_utf8_count((U8 *) argp->p,
3279                                                 (U8 *) argp->p + argp->len);
3280         }
3281     }
3282
3283     /* create and populate aux struct */
3284
3285   create_aux:
3286
3287     aux = (UNOP_AUX_item*)PerlMemShared_malloc(
3288                     sizeof(UNOP_AUX_item)
3289                     *  (
3290                            PERL_MULTICONCAT_HEADER_SIZE
3291                          + ((nargs + 1) * (variant ? 2 : 1))
3292                         )
3293                     );
3294     const_str = (char *)PerlMemShared_malloc(total_len ? total_len : 1);
3295
3296     /* Extract all the non-const expressions from the concat tree then
3297      * dispose of the old tree, e.g. convert the tree from this:
3298      *
3299      *  o => SASSIGN
3300      *         |
3301      *       STRINGIFY   -- TARGET
3302      *         |
3303      *       ex-PUSHMARK -- CONCAT
3304      *                        |
3305      *                      CONCAT -- EXPR5
3306      *                        |
3307      *                      CONCAT -- EXPR4
3308      *                        |
3309      *                      CONCAT -- EXPR3
3310      *                        |
3311      *                      EXPR1  -- EXPR2
3312      *
3313      *
3314      * to:
3315      *
3316      *  o => MULTICONCAT
3317      *         |
3318      *       ex-PUSHMARK -- EXPR1 -- EXPR2 -- EXPR3 -- EXPR4 -- EXPR5 -- TARGET
3319      *
3320      * except that if EXPRi is an OP_CONST, it's discarded.
3321      *
3322      * During the conversion process, EXPR ops are stripped from the tree
3323      * and unshifted onto o. Finally, any of o's remaining original
3324      * childen are discarded and o is converted into an OP_MULTICONCAT.
3325      *
3326      * In this middle of this, o may contain both: unshifted args on the
3327      * left, and some remaining original args on the right. lastkidop
3328      * is set to point to the right-most unshifted arg to delineate
3329      * between the two sets.
3330      */
3331
3332
3333     if (is_sprintf) {
3334         /* create a copy of the format with the %'s removed, and record
3335          * the sizes of the const string segments in the aux struct */
3336         char *q, *oldq;
3337         lenp = aux + PERL_MULTICONCAT_IX_LENGTHS;
3338
3339         p    = sprintf_info.start;
3340         q    = const_str;
3341         oldq = q;
3342         for (; p < sprintf_info.end; p++) {
3343             if (*p == '%') {
3344                 p++;
3345                 if (*p != '%') {
3346                     (lenp++)->ssize = q - oldq;
3347                     oldq = q;
3348                     continue;
3349                 }
3350             }
3351             *q++ = *p;
3352         }
3353         lenp->ssize = q - oldq;
3354         assert((STRLEN)(q - const_str) == total_len);
3355
3356         /* Attach all the args (i.e. the kids of the sprintf) to o (which
3357          * may or may not be topop) The pushmark and const ops need to be
3358          * kept in case they're an op_next entry point.
3359          */
3360         lastkidop = cLISTOPx(topop)->op_last;
3361         kid = cUNOPx(topop)->op_first; /* pushmark */
3362         op_null(kid);
3363         op_null(OpSIBLING(kid));       /* const */
3364         if (o != topop) {
3365             kid = op_sibling_splice(topop, NULL, -1, NULL); /* cut all args */
3366             op_sibling_splice(o, NULL, 0, kid); /* and attach to o */
3367             lastkidop->op_next = o;
3368         }
3369     }
3370     else {
3371         p = const_str;
3372         lenp = aux + PERL_MULTICONCAT_IX_LENGTHS;
3373
3374         lenp->ssize = -1;
3375
3376         /* Concatenate all const strings into const_str.
3377          * Note that args[] contains the RHS args in reverse order, so
3378          * we scan args[] from top to bottom to get constant strings
3379          * in L-R order
3380          */
3381         for (argp = toparg; argp >= args; argp--) {
3382             if (!argp->p)
3383                 /* not a const op */
3384                 (++lenp)->ssize = -1;
3385             else {
3386                 STRLEN l = argp->len;
3387                 Copy(argp->p, p, l, char);
3388                 p += l;
3389                 if (lenp->ssize == -1)
3390                     lenp->ssize = l;
3391                 else
3392                     lenp->ssize += l;
3393             }
3394         }
3395
3396         kid = topop;
3397         nextop = o;
3398         lastkidop = NULL;
3399
3400         for (argp = args; argp <= toparg; argp++) {
3401             /* only keep non-const args, except keep the first-in-next-chain
3402              * arg no matter what it is (but nulled if OP_CONST), because it
3403              * may be the entry point to this subtree from the previous
3404              * op_next.
3405              */
3406             bool last = (argp == toparg);
3407             OP *prev;
3408
3409             /* set prev to the sibling *before* the arg to be cut out,
3410              * e.g. when cutting EXPR:
3411              *
3412              *         |
3413              * kid=  CONCAT
3414              *         |
3415              * prev= CONCAT -- EXPR
3416              *         |
3417              */
3418             if (argp == args && kid->op_type != OP_CONCAT) {
3419                 /* in e.g. '$x .= f(1)' there's no RHS concat tree
3420                  * so the expression to be cut isn't kid->op_last but
3421                  * kid itself */
3422                 OP *o1, *o2;
3423                 /* find the op before kid */
3424                 o1 = NULL;
3425                 o2 = cUNOPx(parentop)->op_first;
3426                 while (o2 && o2 != kid) {
3427                     o1 = o2;
3428                     o2 = OpSIBLING(o2);
3429                 }
3430                 assert(o2 == kid);
3431                 prev = o1;
3432                 kid  = parentop;
3433             }
3434             else if (kid == o && lastkidop)
3435                 prev = last ? lastkidop : OpSIBLING(lastkidop);
3436             else
3437                 prev = last ? NULL : cUNOPx(kid)->op_first;
3438
3439             if (!argp->p || last) {
3440                 /* cut RH op */
3441                 OP *aop = op_sibling_splice(kid, prev, 1, NULL);
3442                 /* and unshift to front of o */
3443                 op_sibling_splice(o, NULL, 0, aop);
3444                 /* record the right-most op added to o: later we will
3445                  * free anything to the right of it */
3446                 if (!lastkidop)
3447                     lastkidop = aop;
3448                 aop->op_next = nextop;
3449                 if (last) {
3450                     if (argp->p)
3451                         /* null the const at start of op_next chain */
3452                         op_null(aop);
3453                 }
3454                 else if (prev)
3455                     nextop = prev->op_next;
3456             }
3457
3458             /* the last two arguments are both attached to the same concat op */
3459             if (argp < toparg - 1)
3460                 kid = prev;
3461         }
3462     }
3463
3464     /* Populate the aux struct */
3465
3466     aux[PERL_MULTICONCAT_IX_NARGS].ssize     = nargs;
3467     aux[PERL_MULTICONCAT_IX_PLAIN_PV].pv    = utf8 ? NULL : const_str;
3468     aux[PERL_MULTICONCAT_IX_PLAIN_LEN].ssize = utf8 ?    0 : total_len;
3469     aux[PERL_MULTICONCAT_IX_UTF8_PV].pv     = const_str;
3470     aux[PERL_MULTICONCAT_IX_UTF8_LEN].ssize  = total_len;
3471
3472     /* if variant > 0, calculate a variant const string and lengths where
3473      * the utf8 version of the string will take 'variant' more bytes than
3474      * the plain one. */
3475
3476     if (variant) {
3477         char              *p = const_str;
3478         STRLEN          ulen = total_len + variant;
3479         UNOP_AUX_item  *lens = aux + PERL_MULTICONCAT_IX_LENGTHS;
3480         UNOP_AUX_item *ulens = lens + (nargs + 1);
3481         char             *up = (char*)PerlMemShared_malloc(ulen);
3482         SSize_t            n;
3483
3484         aux[PERL_MULTICONCAT_IX_UTF8_PV].pv    = up;
3485         aux[PERL_MULTICONCAT_IX_UTF8_LEN].ssize = ulen;
3486
3487         for (n = 0; n < (nargs + 1); n++) {
3488             SSize_t i;
3489             char * orig_up = up;
3490             for (i = (lens++)->ssize; i > 0; i--) {
3491                 U8 c = *p++;
3492                 append_utf8_from_native_byte(c, (U8**)&up);
3493             }
3494             (ulens++)->ssize = (i < 0) ? i : up - orig_up;
3495         }
3496     }
3497
3498     if (stringop) {
3499         /* if there was a top(ish)-level OP_STRINGIFY, we need to keep
3500          * that op's first child - an ex-PUSHMARK - because the op_next of
3501          * the previous op may point to it (i.e. it's the entry point for
3502          * the o optree)
3503          */
3504         OP *pmop =
3505             (stringop == o)
3506                 ? op_sibling_splice(o, lastkidop, 1, NULL)
3507                 : op_sibling_splice(stringop, NULL, 1, NULL);
3508         assert(OP_TYPE_IS_OR_WAS_NN(pmop, OP_PUSHMARK));
3509         op_sibling_splice(o, NULL, 0, pmop);
3510         if (!lastkidop)
3511             lastkidop = pmop;
3512     }
3513
3514     /* Optimise
3515      *    target  = A.B.C...
3516      *    target .= A.B.C...
3517      */
3518
3519     if (targetop) {
3520         assert(!targmyop);
3521
3522         if (o->op_type == OP_SASSIGN) {
3523             /* Move the target subtree from being the last of o's children
3524              * to being the last of o's preserved children.
3525              * Note the difference between 'target = ...' and 'target .= ...':
3526              * for the former, target is executed last; for the latter,
3527              * first.
3528              */
3529             kid = OpSIBLING(lastkidop);
3530             op_sibling_splice(o, kid, 1, NULL); /* cut target op */
3531             op_sibling_splice(o, lastkidop, 0, targetop); /* and paste */
3532             lastkidop->op_next = kid->op_next;
3533             lastkidop = targetop;
3534         }
3535         else {
3536             /* Move the target subtree from being the first of o's
3537              * original children to being the first of *all* o's children.
3538              */
3539             if (lastkidop) {
3540                 op_sibling_splice(o, lastkidop, 1, NULL); /* cut target op */
3541                 op_sibling_splice(o, NULL, 0, targetop);  /* and paste*/
3542             }
3543             else {
3544                 /* if the RHS of .= doesn't contain a concat (e.g.
3545                  * $x .= "foo"), it gets missed by the "strip ops from the
3546                  * tree and add to o" loop earlier */
3547                 assert(topop->op_type != OP_CONCAT);
3548                 if (stringop) {
3549                     /* in e.g. $x .= "$y", move the $y expression
3550                      * from being a child of OP_STRINGIFY to being the
3551                      * second child of the OP_CONCAT
3552                      */
3553                     assert(cUNOPx(stringop)->op_first == topop);
3554                     op_sibling_splice(stringop, NULL, 1, NULL);
3555                     op_sibling_splice(o, cUNOPo->op_first, 0, topop);
3556                 }
3557                 assert(topop == OpSIBLING(cBINOPo->op_first));
3558                 if (toparg->p)
3559                     op_null(topop);
3560                 lastkidop = topop;
3561             }
3562         }
3563
3564         if (is_targable) {
3565             /* optimise
3566              *  my $lex  = A.B.C...
3567              *     $lex  = A.B.C...
3568              *     $lex .= A.B.C...
3569              * The original padsv op is kept but nulled in case it's the
3570              * entry point for the optree (which it will be for
3571              * '$lex .=  ... '
3572              */
3573             private_flags |= OPpTARGET_MY;
3574             private_flags |= (targetop->op_private & OPpLVAL_INTRO);
3575             o->op_targ = targetop->op_targ;
3576             targetop->op_targ = 0;
3577             op_null(targetop);
3578         }
3579         else
3580             flags |= OPf_STACKED;
3581     }
3582     else if (targmyop) {
3583         private_flags |= OPpTARGET_MY;
3584         if (o != targmyop) {
3585             o->op_targ = targmyop->op_targ;
3586             targmyop->op_targ = 0;
3587         }
3588     }
3589
3590     /* detach the emaciated husk of the sprintf/concat optree and free it */
3591     for (;;) {
3592         kid = op_sibling_splice(o, lastkidop, 1, NULL);
3593         if (!kid)
3594             break;
3595         op_free(kid);
3596     }
3597
3598     /* and convert o into a multiconcat */
3599
3600     o->op_flags        = (flags|OPf_KIDS|stacked_last
3601                          |(o->op_flags & (OPf_WANT|OPf_PARENS)));
3602     o->op_private      = private_flags;
3603     o->op_type         = OP_MULTICONCAT;
3604     o->op_ppaddr       = PL_ppaddr[OP_MULTICONCAT];
3605     cUNOP_AUXo->op_aux = aux;
3606 }
3607
3608
3609 /* do all the final processing on an optree (e.g. running the peephole
3610  * optimiser on it), then attach it to cv (if cv is non-null)
3611  */
3612
3613 static void
3614 S_process_optree(pTHX_ CV *cv, OP *optree, OP* start)
3615 {
3616     OP **startp;
3617
3618     /* XXX for some reason, evals, require and main optrees are
3619      * never attached to their CV; instead they just hang off
3620      * PL_main_root + PL_main_start or PL_eval_root + PL_eval_start
3621      * and get manually freed when appropriate */
3622     if (cv)
3623         startp = &CvSTART(cv);
3624     else
3625         startp = PL_in_eval? &PL_eval_start : &PL_main_start;
3626
3627     *startp = start;
3628     optree->op_private |= OPpREFCOUNTED;
3629     OpREFCNT_set(optree, 1);
3630     optimize_optree(optree);
3631     CALL_PEEP(*startp);
3632     finalize_optree(optree);
3633     S_prune_chain_head(startp);
3634
3635     if (cv) {
3636         /* now that optimizer has done its work, adjust pad values */
3637         pad_tidy(optree->op_type == OP_LEAVEWRITE ? padtidy_FORMAT
3638                  : CvCLONE(cv) ? padtidy_SUBCLONE : padtidy_SUB);
3639     }
3640 }
3641
3642
3643 /*
3644 =for apidoc optimize_optree
3645
3646 This function applies some optimisations to the optree in top-down order.
3647 It is called before the peephole optimizer, which processes ops in
3648 execution order. Note that finalize_optree() also does a top-down scan,
3649 but is called *after* the peephole optimizer.
3650
3651 =cut
3652 */
3653
3654 void
3655 Perl_optimize_optree(pTHX_ OP* o)
3656 {
3657     PERL_ARGS_ASSERT_OPTIMIZE_OPTREE;
3658
3659     ENTER;
3660     SAVEVPTR(PL_curcop);
3661
3662     optimize_op(o);
3663
3664     LEAVE;
3665 }
3666
3667
3668 /* helper for optimize_optree() which optimises one op then recurses
3669  * to optimise any children.
3670  */
3671
3672 STATIC void
3673 S_optimize_op(pTHX_ OP* o)
3674 {
3675     OP *top_op = o;
3676
3677     PERL_ARGS_ASSERT_OPTIMIZE_OP;
3678
3679     while (1) {
3680         OP * next_kid = NULL;
3681
3682         assert(o->op_type != OP_FREED);
3683
3684         switch (o->op_type) {
3685         case OP_NEXTSTATE:
3686         case OP_DBSTATE:
3687             PL_curcop = ((COP*)o);              /* for warnings */
3688             break;
3689
3690
3691         case OP_CONCAT:
3692         case OP_SASSIGN:
3693         case OP_STRINGIFY:
3694         case OP_SPRINTF:
3695             S_maybe_multiconcat(aTHX_ o);
3696             break;
3697
3698         case OP_SUBST:
3699             if (cPMOPo->op_pmreplrootu.op_pmreplroot) {
3700                 /* we can't assume that op_pmreplroot->op_sibparent == o
3701                  * and that it is thus possible to walk back up the tree
3702                  * past op_pmreplroot. So, although we try to avoid
3703                  * recursing through op trees, do it here. After all,
3704                  * there are unlikely to be many nested s///e's within
3705                  * the replacement part of a s///e.
3706                  */
3707                 optimize_op(cPMOPo->op_pmreplrootu.op_pmreplroot);
3708             }
3709             break;
3710
3711         default:
3712             break;
3713         }
3714
3715         if (o->op_flags & OPf_KIDS)
3716             next_kid = cUNOPo->op_first;
3717
3718         /* if a kid hasn't been nominated to process, continue with the
3719          * next sibling, or if no siblings left, go back to the parent's
3720          * siblings and so on
3721          */
3722         while (!next_kid) {
3723             if (o == top_op)
3724                 return; /* at top; no parents/siblings to try */
3725             if (OpHAS_SIBLING(o))
3726                 next_kid = o->op_sibparent;
3727             else
3728                 o = o->op_sibparent; /*try parent's next sibling */
3729         }
3730
3731       /* this label not yet used. Goto here if any code above sets
3732        * next-kid
3733        get_next_op:
3734        */
3735         o = next_kid;
3736     }
3737 }
3738
3739
3740 /*
3741 =for apidoc finalize_optree
3742
3743 This function finalizes the optree.  Should be called directly after
3744 the complete optree is built.  It does some additional
3745 checking which can't be done in the normal C<ck_>xxx functions and makes
3746 the tree thread-safe.
3747
3748 =cut
3749 */
3750 void
3751 Perl_finalize_optree(pTHX_ OP* o)
3752 {
3753     PERL_ARGS_ASSERT_FINALIZE_OPTREE;
3754
3755     ENTER;
3756     SAVEVPTR(PL_curcop);
3757
3758     finalize_op(o);
3759
3760     LEAVE;
3761 }
3762
3763 #ifdef USE_ITHREADS
3764 /* Relocate sv to the pad for thread safety.
3765  * Despite being a "constant", the SV is written to,
3766  * for reference counts, sv_upgrade() etc. */
3767 PERL_STATIC_INLINE void
3768 S_op_relocate_sv(pTHX_ SV** svp, PADOFFSET* targp)
3769 {
3770     PADOFFSET ix;
3771     PERL_ARGS_ASSERT_OP_RELOCATE_SV;
3772     if (!*svp) return;
3773     ix = pad_alloc(OP_CONST, SVf_READONLY);
3774     SvREFCNT_dec(PAD_SVl(ix));
3775     PAD_SETSV(ix, *svp);
3776     /* XXX I don't know how this isn't readonly already. */
3777     if (!SvIsCOW(PAD_SVl(ix))) SvREADONLY_on(PAD_SVl(ix));
3778     *svp = NULL;
3779     *targp = ix;
3780 }
3781 #endif
3782
3783 /*
3784 =for apidoc traverse_op_tree
3785
3786 Return the next op in a depth-first traversal of the op tree,
3787 returning NULL when the traversal is complete.
3788
3789 The initial call must supply the root of the tree as both top and o.
3790
3791 For now it's static, but it may be exposed to the API in the future.
3792
3793 =cut
3794 */
3795
3796 STATIC OP*
3797 S_traverse_op_tree(pTHX_ OP *top, OP *o) {
3798     OP *sib;
3799
3800     PERL_ARGS_ASSERT_TRAVERSE_OP_TREE;
3801
3802     if ((o->op_flags & OPf_KIDS) && cUNOPo->op_first) {
3803         return cUNOPo->op_first;
3804     }
3805     else if ((sib = OpSIBLING(o))) {
3806         return sib;
3807     }
3808     else {
3809         OP *parent = o->op_sibparent;
3810         assert(!(o->op_moresib));
3811         while (parent && parent != top) {
3812             OP *sib = OpSIBLING(parent);
3813             if (sib)
3814                 return sib;
3815             parent = parent->op_sibparent;
3816         }
3817
3818         return NULL;
3819     }
3820 }
3821
3822 STATIC void
3823 S_finalize_op(pTHX_ OP* o)
3824 {
3825     OP * const top = o;
3826     PERL_ARGS_ASSERT_FINALIZE_OP;
3827
3828     do {
3829         assert(o->op_type != OP_FREED);
3830
3831         switch (o->op_type) {
3832         case OP_NEXTSTATE:
3833         case OP_DBSTATE:
3834             PL_curcop = ((COP*)o);              /* for warnings */
3835             break;
3836         case OP_EXEC:
3837             if (OpHAS_SIBLING(o)) {
3838                 OP *sib = OpSIBLING(o);
3839                 if ((  sib->op_type == OP_NEXTSTATE || sib->op_type == OP_DBSTATE)
3840                     && ckWARN(WARN_EXEC)
3841                     && OpHAS_SIBLING(sib))
3842                 {
3843                     const OPCODE type = OpSIBLING(sib)->op_type;
3844                     if (type != OP_EXIT && type != OP_WARN && type != OP_DIE) {
3845                         const line_t oldline = CopLINE(PL_curcop);
3846                         CopLINE_set(PL_curcop, CopLINE((COP*)sib));
3847                         Perl_warner(aTHX_ packWARN(WARN_EXEC),
3848                             "Statement unlikely to be reached");
3849                         Perl_warner(aTHX_ packWARN(WARN_EXEC),
3850                             "\t(Maybe you meant system() when you said exec()?)\n");
3851                         CopLINE_set(PL_curcop, oldline);
3852                     }
3853                 }
3854             }
3855             break;
3856
3857         case OP_GV:
3858             if ((o->op_private & OPpEARLY_CV) && ckWARN(WARN_PROTOTYPE)) {
3859                 GV * const gv = cGVOPo_gv;
3860                 if (SvTYPE(gv) == SVt_PVGV && GvCV(gv) && SvPVX_const(GvCV(gv))) {
3861                     /* XXX could check prototype here instead of just carping */
3862                     SV * const sv = sv_newmortal();
3863                     gv_efullname3(sv, gv, NULL);
3864                     Perl_warner(aTHX_ packWARN(WARN_PROTOTYPE),
3865                                 "%" SVf "() called too early to check prototype",
3866                                 SVfARG(sv));
3867                 }
3868             }
3869             break;
3870
3871         case OP_CONST:
3872             if (cSVOPo->op_private & OPpCONST_STRICT)
3873                 no_bareword_allowed(o);
3874 #ifdef USE_ITHREADS
3875             /* FALLTHROUGH */
3876         case OP_HINTSEVAL:
3877             op_relocate_sv(&cSVOPo->op_sv, &o->op_targ);
3878 #endif
3879             break;
3880
3881 #ifdef USE_ITHREADS
3882             /* Relocate all the METHOP's SVs to the pad for thread safety. */
3883         case OP_METHOD_NAMED:
3884         case OP_METHOD_SUPER:
3885         case OP_METHOD_REDIR:
3886         case OP_METHOD_REDIR_SUPER:
3887             op_relocate_sv(&cMETHOPx(o)->op_u.op_meth_sv, &o->op_targ);
3888             break;
3889 #endif
3890
3891         case OP_HELEM: {
3892             UNOP *rop;
3893             SVOP *key_op;
3894             OP *kid;
3895
3896             if ((key_op = cSVOPx(((BINOP*)o)->op_last))->op_type != OP_CONST)
3897                 break;
3898
3899             rop = (UNOP*)((BINOP*)o)->op_first;
3900
3901             goto check_keys;
3902
3903             case OP_HSLICE:
3904                 S_scalar_slice_warning(aTHX_ o);
3905                 /* FALLTHROUGH */
3906
3907             case OP_KVHSLICE:
3908                 kid = OpSIBLING(cLISTOPo->op_first);
3909             if (/* I bet there's always a pushmark... */
3910                 OP_TYPE_ISNT_AND_WASNT_NN(kid, OP_LIST)
3911                 && OP_TYPE_ISNT_NN(kid, OP_CONST))
3912             {
3913                 break;
3914             }
3915
3916             key_op = (SVOP*)(kid->op_type == OP_CONST
3917                              ? kid
3918                              : OpSIBLING(kLISTOP->op_first));
3919
3920             rop = (UNOP*)((LISTOP*)o)->op_last;
3921
3922         check_keys:
3923             if (o->op_private & OPpLVAL_INTRO || rop->op_type != OP_RV2HV)
3924                 rop = NULL;
3925             S_check_hash_fields_and_hekify(aTHX_ rop, key_op, 1);
3926             break;
3927         }
3928         case OP_NULL:
3929             if (o->op_targ != OP_HSLICE && o->op_targ != OP_ASLICE)
3930                 break;
3931             /* FALLTHROUGH */
3932         case OP_ASLICE:
3933             S_scalar_slice_warning(aTHX_ o);
3934             break;
3935
3936         case OP_SUBST: {
3937             if (cPMOPo->op_pmreplrootu.op_pmreplroot)
3938                 finalize_op(cPMOPo->op_pmreplrootu.op_pmreplroot);
3939             break;
3940         }
3941         default:
3942             break;
3943         }
3944
3945 #ifdef DEBUGGING
3946         if (o->op_flags & OPf_KIDS) {
3947             OP *kid;
3948
3949             /* check that op_last points to the last sibling, and that
3950              * the last op_sibling/op_sibparent field points back to the
3951              * parent, and that the only ops with KIDS are those which are
3952              * entitled to them */
3953             U32 type = o->op_type;
3954             U32 family;
3955             bool has_last;
3956
3957             if (type == OP_NULL) {
3958                 type = o->op_targ;
3959                 /* ck_glob creates a null UNOP with ex-type GLOB
3960                  * (which is a list op. So pretend it wasn't a listop */
3961                 if (type == OP_GLOB)
3962                     type = OP_NULL;
3963             }
3964             family = PL_opargs[type] & OA_CLASS_MASK;
3965
3966             has_last = (   family == OA_BINOP
3967                         || family == OA_LISTOP
3968                         || family == OA_PMOP
3969                         || family == OA_LOOP
3970                        );
3971             assert(  has_last /* has op_first and op_last, or ...
3972                   ... has (or may have) op_first: */
3973                   || family == OA_UNOP
3974                   || family == OA_UNOP_AUX
3975                   || family == OA_LOGOP
3976                   || family == OA_BASEOP_OR_UNOP
3977                   || family == OA_FILESTATOP
3978                   || family == OA_LOOPEXOP
3979                   || family == OA_METHOP
3980                   || type == OP_CUSTOM
3981                   || type == OP_NULL /* new_logop does this */
3982                   );
3983
3984             for (kid = cUNOPo->op_first; kid; kid = OpSIBLING(kid)) {
3985                 if (!OpHAS_SIBLING(kid)) {
3986                     if (has_last)
3987                         assert(kid == cLISTOPo->op_last);
3988                     assert(kid->op_sibparent == o);
3989                 }
3990             }
3991         }
3992 #endif
3993     } while (( o = traverse_op_tree(top, o)) != NULL);
3994 }
3995
3996 static void
3997 S_mark_padname_lvalue(pTHX_ PADNAME *pn)
3998 {
3999     CV *cv = PL_compcv;
4000     PadnameLVALUE_on(pn);
4001     while (PadnameOUTER(pn) && PARENT_PAD_INDEX(pn)) {
4002         cv = CvOUTSIDE(cv);
4003         /* RT #127786: cv can be NULL due to an eval within the DB package
4004          * called from an anon sub - anon subs don't have CvOUTSIDE() set
4005          * unless they contain an eval, but calling eval within DB
4006          * pretends the eval was done in the caller's scope.
4007          */
4008         if (!cv)
4009             break;
4010         assert(CvPADLIST(cv));
4011         pn =
4012            PadlistNAMESARRAY(CvPADLIST(cv))[PARENT_PAD_INDEX(pn)];
4013         assert(PadnameLEN(pn));
4014         PadnameLVALUE_on(pn);
4015     }
4016 }
4017
4018 static bool
4019 S_vivifies(const OPCODE type)
4020 {
4021     switch(type) {
4022     case OP_RV2AV:     case   OP_ASLICE:
4023     case OP_RV2HV:     case OP_KVASLICE:
4024     case OP_RV2SV:     case   OP_HSLICE:
4025     case OP_AELEMFAST: case OP_KVHSLICE:
4026     case OP_HELEM:
4027     case OP_AELEM:
4028         return 1;
4029     }
4030     return 0;
4031 }
4032
4033
4034 /* apply lvalue reference (aliasing) context to the optree o.
4035  * E.g. in
4036  *     \($x,$y) = (...)
4037  * o would be the list ($x,$y) and type would be OP_AASSIGN.
4038  * It may descend and apply this to children too, for example in
4039  * \( $cond ? $x, $y) = (...)
4040  */
4041
4042 static void
4043 S_lvref(pTHX_ OP *o, I32 type)
4044 {
4045     dVAR;
4046     OP *kid;
4047     OP * top_op = o;
4048
4049     while (1) {
4050         switch (o->op_type) {
4051         case OP_COND_EXPR:
4052             o = OpSIBLING(cUNOPo->op_first);
4053             continue;
4054
4055         case OP_PUSHMARK:
4056             goto do_next;
4057
4058         case OP_RV2AV:
4059             if (cUNOPo->op_first->op_type != OP_GV) goto badref;
4060             o->op_flags |= OPf_STACKED;
4061             if (o->op_flags & OPf_PARENS) {
4062                 if (o->op_private & OPpLVAL_INTRO) {
4063                      yyerror(Perl_form(aTHX_ "Can't modify reference to "
4064                           "localized parenthesized array in list assignment"));
4065                     goto do_next;
4066                 }
4067               slurpy:
4068                 OpTYPE_set(o, OP_LVAVREF);
4069                 o->op_private &= OPpLVAL_INTRO|OPpPAD_STATE;
4070                 o->op_flags |= OPf_MOD|OPf_REF;
4071                 goto do_next;
4072             }
4073             o->op_private |= OPpLVREF_AV;
4074             goto checkgv;
4075
4076         case OP_RV2CV:
4077             kid = cUNOPo->op_first;
4078             if (kid->op_type == OP_NULL)
4079                 kid = cUNOPx(OpSIBLING(kUNOP->op_first))
4080                     ->op_first;
4081             o->op_private = OPpLVREF_CV;
4082             if (kid->op_type == OP_GV)
4083                 o->op_flags |= OPf_STACKED;
4084             else if (kid->op_type == OP_PADCV) {
4085                 o->op_targ = kid->op_targ;
4086                 kid->op_targ = 0;
4087                 op_free(cUNOPo->op_first);
4088                 cUNOPo->op_first = NULL;
4089                 o->op_flags &=~ OPf_KIDS;
4090             }
4091             else goto badref;
4092             break;
4093
4094         case OP_RV2HV:
4095             if (o->op_flags & OPf_PARENS) {
4096               parenhash:
4097                 yyerror(Perl_form(aTHX_ "Can't modify reference to "
4098                                      "parenthesized hash in list assignment"));
4099                     goto do_next;
4100             }
4101             o->op_private |= OPpLVREF_HV;
4102             /* FALLTHROUGH */
4103         case OP_RV2SV:
4104           checkgv:
4105             if (cUNOPo->op_first->op_type != OP_GV) goto badref;
4106             o->op_flags |= OPf_STACKED;
4107             break;
4108
4109         case OP_PADHV:
4110             if (o->op_flags & OPf_PARENS) goto parenhash;
4111             o->op_private |= OPpLVREF_HV;
4112             /* FALLTHROUGH */
4113         case OP_PADSV:
4114             PAD_COMPNAME_GEN_set(o->op_targ, PERL_INT_MAX);
4115             break;
4116
4117         case OP_PADAV:
4118             PAD_COMPNAME_GEN_set(o->op_targ, PERL_INT_MAX);
4119             if (o->op_flags & OPf_PARENS) goto slurpy;
4120             o->op_private |= OPpLVREF_AV;
4121             break;
4122
4123         case OP_AELEM:
4124         case OP_HELEM:
4125             o->op_private |= OPpLVREF_ELEM;
4126             o->op_flags   |= OPf_STACKED;
4127             break;
4128
4129         case OP_ASLICE:
4130         case OP_HSLICE:
4131             OpTYPE_set(o, OP_LVREFSLICE);
4132             o->op_private &= OPpLVAL_INTRO;
4133             goto do_next;
4134
4135         case OP_NULL:
4136             if (o->op_flags & OPf_SPECIAL)              /* do BLOCK */
4137                 goto badref;
4138             else if (!(o->op_flags & OPf_KIDS))
4139                 goto do_next;
4140
4141             /* the code formerly only recursed into the first child of
4142              * a non ex-list OP_NULL. if we ever encounter such a null op with
4143              * more than one child, need to decide whether its ok to process
4144              * *all* its kids or not */
4145             assert(o->op_targ == OP_LIST
4146                     || !(OpHAS_SIBLING(cBINOPo->op_first)));
4147             /* FALLTHROUGH */
4148         case OP_LIST:
4149             o = cLISTOPo->op_first;
4150             continue;
4151
4152         case OP_STUB:
4153             if (o->op_flags & OPf_PARENS)
4154                 goto do_next;
4155             /* FALLTHROUGH */
4156         default:
4157           badref:
4158             /* diag_listed_as: Can't modify reference to %s in %s assignment */
4159             yyerror(Perl_form(aTHX_ "Can't modify reference to %s in %s",
4160                          o->op_type == OP_NULL && o->op_flags & OPf_SPECIAL
4161                           ? "do block"
4162                           : OP_DESC(o),
4163                          PL_op_desc[type]));
4164             goto do_next;
4165         }
4166
4167         OpTYPE_set(o, OP_LVREF);
4168         o->op_private &=
4169             OPpLVAL_INTRO|OPpLVREF_ELEM|OPpLVREF_TYPE|OPpPAD_STATE;
4170         if (type == OP_ENTERLOOP)
4171             o->op_private |= OPpLVREF_ITER;
4172
4173       do_next:
4174         while (1) {
4175             if (o == top_op)
4176                 return; /* at top; no parents/siblings to try */
4177             if (OpHAS_SIBLING(o)) {
4178                 o = o->op_sibparent;
4179                 break;
4180             }
4181             o = o->op_sibparent; /*try parent's next sibling */
4182         }
4183     } /* while */
4184 }
4185
4186
4187 PERL_STATIC_INLINE bool
4188 S_potential_mod_type(I32 type)
4189 {
4190     /* Types that only potentially result in modification.  */
4191     return type == OP_GREPSTART || type == OP_ENTERSUB
4192         || type == OP_REFGEN    || type == OP_LEAVESUBLV;
4193 }
4194
4195
4196 /*
4197 =for apidoc op_lvalue
4198
4199 Propagate lvalue ("modifiable") context to an op and its children.
4200 C<type> represents the context type, roughly based on the type of op that
4201 would do the modifying, although C<local()> is represented by C<OP_NULL>,
4202 because it has no op type of its own (it is signalled by a flag on
4203 the lvalue op).
4204
4205 This function detects things that can't be modified, such as C<$x+1>, and
4206 generates errors for them.  For example, C<$x+1 = 2> would cause it to be
4207 called with an op of type C<OP_ADD> and a C<type> argument of C<OP_SASSIGN>.
4208
4209 It also flags things that need to behave specially in an lvalue context,
4210 such as C<$$x = 5> which might have to vivify a reference in C<$x>.
4211
4212 =cut
4213
4214 Perl_op_lvalue_flags() is a non-API lower-level interface to
4215 op_lvalue().  The flags param has these bits:
4216     OP_LVALUE_NO_CROAK:  return rather than croaking on error
4217
4218 */
4219
4220 OP *
4221 Perl_op_lvalue_flags(pTHX_ OP *o, I32 type, U32 flags)
4222 {
4223     dVAR;
4224     OP *top_op = o;
4225
4226     if (!o || (PL_parser && PL_parser->error_count))
4227         return o;
4228
4229     while (1) {
4230     OP *kid;
4231     /* -1 = error on localize, 0 = ignore localize, 1 = ok to localize */
4232     int localize = -1;
4233     OP *next_kid = NULL;
4234
4235     if ((o->op_private & OPpTARGET_MY)
4236         && (PL_opargs[o->op_type] & OA_TARGLEX))/* OPp share the meaning */
4237     {
4238         goto do_next;
4239     }
4240
4241     /* elements of a list might be in void context because the list is
4242        in scalar context or because they are attribute sub calls */
4243     if ((o->op_flags & OPf_WANT) == OPf_WANT_VOID)
4244         goto do_next;
4245
4246     if (type == OP_PRTF || type == OP_SPRINTF) type = OP_ENTERSUB;
4247
4248     switch (o->op_type) {
4249     case OP_UNDEF:
4250         PL_modcount++;
4251         goto do_next;
4252
4253     case OP_STUB:
4254         if ((o->op_flags & OPf_PARENS))
4255             break;
4256         goto nomod;
4257
4258     case OP_ENTERSUB:
4259         if ((type == OP_UNDEF || type == OP_REFGEN || type == OP_LOCK) &&
4260             !(o->op_flags & OPf_STACKED)) {
4261             OpTYPE_set(o, OP_RV2CV);            /* entersub => rv2cv */
4262             assert(cUNOPo->op_first->op_type == OP_NULL);
4263             op_null(((LISTOP*)cUNOPo->op_first)->op_first);/* disable pushmark */
4264             break;
4265         }
4266         else {                          /* lvalue subroutine call */
4267             o->op_private |= OPpLVAL_INTRO;
4268             PL_modcount = RETURN_UNLIMITED_NUMBER;
4269             if (S_potential_mod_type(type)) {
4270                 o->op_private |= OPpENTERSUB_INARGS;
4271                 break;
4272             }
4273             else {                      /* Compile-time error message: */
4274                 OP *kid = cUNOPo->op_first;
4275                 CV *cv;
4276                 GV *gv;
4277                 SV *namesv;
4278
4279                 if (kid->op_type != OP_PUSHMARK) {
4280                     if (kid->op_type != OP_NULL || kid->op_targ != OP_LIST)
4281                         Perl_croak(aTHX_
4282                                 "panic: unexpected lvalue entersub "
4283                                 "args: type/targ %ld:%" UVuf,
4284                                 (long)kid->op_type, (UV)kid->op_targ);
4285                     kid = kLISTOP->op_first;
4286                 }
4287                 while (OpHAS_SIBLING(kid))
4288                     kid = OpSIBLING(kid);
4289                 if (!(kid->op_type == OP_NULL && kid->op_targ == OP_RV2CV)) {
4290                     break;      /* Postpone until runtime */
4291                 }
4292
4293                 kid = kUNOP->op_first;
4294                 if (kid->op_type == OP_NULL && kid->op_targ == OP_RV2SV)
4295                     kid = kUNOP->op_first;
4296                 if (kid->op_type == OP_NULL)
4297                     Perl_croak(aTHX_
4298                                "Unexpected constant lvalue entersub "
4299                                "entry via type/targ %ld:%" UVuf,
4300                                (long)kid->op_type, (UV)kid->op_targ);
4301                 if (kid->op_type != OP_GV) {
4302                     break;
4303                 }
4304
4305                 gv = kGVOP_gv;
4306                 cv = isGV(gv)
4307                     ? GvCV(gv)
4308                     : SvROK(gv) && SvTYPE(SvRV(gv)) == SVt_PVCV
4309                         ? MUTABLE_CV(SvRV(gv))
4310                         : NULL;
4311                 if (!cv)
4312                     break;
4313                 if (CvLVALUE(cv))
4314                     break;
4315                 if (flags & OP_LVALUE_NO_CROAK)
4316                     return NULL;
4317
4318                 namesv = cv_name(cv, NULL, 0);
4319                 yyerror_pv(Perl_form(aTHX_ "Can't modify non-lvalue "
4320                                      "subroutine call of &%" SVf " in %s",
4321                                      SVfARG(namesv), PL_op_desc[type]),
4322                            SvUTF8(namesv));
4323                 goto do_next;
4324             }
4325         }
4326         /* FALLTHROUGH */
4327     default:
4328       nomod:
4329         if (flags & OP_LVALUE_NO_CROAK) return NULL;
4330         /* grep, foreach, subcalls, refgen */
4331         if (S_potential_mod_type(type))
4332             break;
4333         yyerror(Perl_form(aTHX_ "Can't modify %s in %s",
4334                      (o->op_type == OP_NULL && (o->op_flags & OPf_SPECIAL)
4335                       ? "do block"
4336                       : OP_DESC(o)),
4337                      type ? PL_op_desc[type] : "local"));
4338         goto do_next;
4339
4340     case OP_PREINC:
4341     case OP_PREDEC:
4342     case OP_POW:
4343     case OP_MULTIPLY:
4344     case OP_DIVIDE:
4345     case OP_MODULO:
4346     case OP_ADD:
4347     case OP_SUBTRACT:
4348     case OP_CONCAT:
4349     case OP_LEFT_SHIFT:
4350     case OP_RIGHT_SHIFT:
4351     case OP_BIT_AND:
4352     case OP_BIT_XOR:
4353     case OP_BIT_OR:
4354     case OP_I_MULTIPLY:
4355     case OP_I_DIVIDE:
4356     case OP_I_MODULO:
4357     case OP_I_ADD:
4358     case OP_I_SUBTRACT:
4359         if (!(o->op_flags & OPf_STACKED))
4360             goto nomod;
4361         PL_modcount++;
4362         break;
4363
4364     case OP_REPEAT:
4365         if (o->op_flags & OPf_STACKED) {
4366             PL_modcount++;
4367             break;
4368         }
4369         if (!(o->op_private & OPpREPEAT_DOLIST))
4370             goto nomod;
4371         else {
4372             const I32 mods = PL_modcount;
4373             /* we recurse rather than iterate here because we need to
4374              * calculate and use the delta applied to PL_modcount by the
4375              * first child. So in something like
4376              *     ($x, ($y) x 3) = split;
4377              * split knows that 4 elements are wanted
4378              */
4379             modkids(cBINOPo->op_first, type);
4380             if (type != OP_AASSIGN)
4381                 goto nomod;
4382             kid = cBINOPo->op_last;
4383             if (kid->op_type == OP_CONST && SvIOK(kSVOP_sv)) {
4384                 const IV iv = SvIV(kSVOP_sv);
4385                 if (PL_modcount != RETURN_UNLIMITED_NUMBER)
4386                     PL_modcount =
4387                         mods + (PL_modcount - mods) * (iv < 0 ? 0 : iv);
4388             }
4389             else
4390                 PL_modcount = RETURN_UNLIMITED_NUMBER;
4391         }
4392         break;
4393
4394     case OP_COND_EXPR:
4395         localize = 1;
4396         next_kid = OpSIBLING(cUNOPo->op_first);
4397         break;
4398
4399     case OP_RV2AV:
4400     case OP_RV2HV:
4401         if (type == OP_REFGEN && o->op_flags & OPf_PARENS) {
4402            PL_modcount = RETURN_UNLIMITED_NUMBER;
4403            /* Treat \(@foo) like ordinary list, but still mark it as modi-
4404               fiable since some contexts need to know.  */
4405            o->op_flags |= OPf_MOD;
4406            goto do_next;
4407         }
4408         /* FALLTHROUGH */
4409     case OP_RV2GV:
4410         if (scalar_mod_type(o, type))
4411             goto nomod;
4412         ref(cUNOPo->op_first, o->op_type);
4413         /* FALLTHROUGH */
4414     case OP_ASLICE:
4415     case OP_HSLICE:
4416         localize = 1;
4417         /* FALLTHROUGH */
4418     case OP_AASSIGN:
4419         /* Do not apply the lvsub flag for rv2[ah]v in scalar context.  */
4420         if (type == OP_LEAVESUBLV && (
4421                 (o->op_type != OP_RV2AV && o->op_type != OP_RV2HV)
4422              || (o->op_flags & OPf_WANT) != OPf_WANT_SCALAR
4423            ))
4424             o->op_private |= OPpMAYBE_LVSUB;
4425         /* FALLTHROUGH */
4426     case OP_NEXTSTATE:
4427     case OP_DBSTATE:
4428        PL_modcount = RETURN_UNLIMITED_NUMBER;
4429         break;
4430
4431     case OP_KVHSLICE:
4432     case OP_KVASLICE:
4433     case OP_AKEYS:
4434         if (type == OP_LEAVESUBLV)
4435             o->op_private |= OPpMAYBE_LVSUB;
4436         goto nomod;
4437
4438     case OP_AVHVSWITCH:
4439         if (type == OP_LEAVESUBLV
4440          && (o->op_private & OPpAVHVSWITCH_MASK) + OP_EACH == OP_KEYS)
4441             o->op_private |= OPpMAYBE_LVSUB;
4442         goto nomod;
4443
4444     case OP_AV2ARYLEN:
4445         PL_hints |= HINT_BLOCK_SCOPE;
4446         if (type == OP_LEAVESUBLV)
4447             o->op_private |= OPpMAYBE_LVSUB;
4448         PL_modcount++;
4449         break;
4450
4451     case OP_RV2SV:
4452         ref(cUNOPo->op_first, o->op_type);
4453         localize = 1;
4454         /* FALLTHROUGH */
4455     case OP_GV:
4456         PL_hints |= HINT_BLOCK_SCOPE;
4457         /* FALLTHROUGH */
4458     case OP_SASSIGN:
4459     case OP_ANDASSIGN:
4460     case OP_ORASSIGN:
4461     case OP_DORASSIGN:
4462         PL_modcount++;
4463         break;
4464
4465     case OP_AELEMFAST:
4466     case OP_AELEMFAST_LEX:
4467         localize = -1;
4468         PL_modcount++;
4469         break;
4470
4471     case OP_PADAV:
4472     case OP_PADHV:
4473        PL_modcount = RETURN_UNLIMITED_NUMBER;
4474         if (type == OP_REFGEN && o->op_flags & OPf_PARENS)
4475         {
4476            /* Treat \(@foo) like ordinary list, but still mark it as modi-
4477               fiable since some contexts need to know.  */
4478             o->op_flags |= OPf_MOD;
4479             goto do_next;
4480         }
4481         if (scalar_mod_type(o, type))
4482             goto nomod;
4483         if ((o->op_flags & OPf_WANT) != OPf_WANT_SCALAR
4484           && type == OP_LEAVESUBLV)
4485             o->op_private |= OPpMAYBE_LVSUB;
4486         /* FALLTHROUGH */
4487     case OP_PADSV:
4488         PL_modcount++;
4489         if (!type) /* local() */
4490             Perl_croak(aTHX_ "Can't localize lexical variable %" PNf,
4491                               PNfARG(PAD_COMPNAME(o->op_targ)));
4492         if (!(o->op_private & OPpLVAL_INTRO)
4493          || (  type != OP_SASSIGN && type != OP_AASSIGN
4494             && PadnameIsSTATE(PAD_COMPNAME_SV(o->op_targ))  ))
4495             S_mark_padname_lvalue(aTHX_ PAD_COMPNAME_SV(o->op_targ));
4496         break;
4497
4498     case OP_PUSHMARK:
4499         localize = 0;
4500         break;
4501
4502     case OP_KEYS:
4503         if (type != OP_LEAVESUBLV && !scalar_mod_type(NULL, type))
4504             goto nomod;
4505         goto lvalue_func;
4506     case OP_SUBSTR:
4507         if (o->op_private == 4) /* don't allow 4 arg substr as lvalue */
4508             goto nomod;
4509         /* FALLTHROUGH */
4510     case OP_POS:
4511     case OP_VEC:
4512       lvalue_func:
4513         if (type == OP_LEAVESUBLV)
4514             o->op_private |= OPpMAYBE_LVSUB;
4515         if (o->op_flags & OPf_KIDS && OpHAS_SIBLING(cBINOPo->op_first)) {
4516             /* we recurse rather than iterate here because the child
4517              * needs to be processed with a different 'type' parameter */
4518
4519             /* substr and vec */
4520             /* If this op is in merely potential (non-fatal) modifiable
4521                context, then apply OP_ENTERSUB context to
4522                the kid op (to avoid croaking).  Other-
4523                wise pass this op’s own type so the correct op is mentioned
4524                in error messages.  */
4525             op_lvalue(OpSIBLING(cBINOPo->op_first),
4526                       S_potential_mod_type(type)
4527                         ? (I32)OP_ENTERSUB
4528                         : o->op_type);
4529         }
4530         break;
4531
4532     case OP_AELEM:
4533     case OP_HELEM:
4534         ref(cBINOPo->op_first, o->op_type);
4535         if (type == OP_ENTERSUB &&
4536              !(o->op_private & (OPpLVAL_INTRO | OPpDEREF)))
4537             o->op_private |= OPpLVAL_DEFER;
4538         if (type == OP_LEAVESUBLV)
4539             o->op_private |= OPpMAYBE_LVSUB;
4540         localize = 1;
4541         PL_modcount++;
4542         break;
4543
4544     case OP_LEAVE:
4545     case OP_LEAVELOOP:
4546         o->op_private |= OPpLVALUE;
4547         /* FALLTHROUGH */
4548     case OP_SCOPE:
4549     case OP_ENTER:
4550     case OP_LINESEQ:
4551         localize = 0;
4552         if (o->op_flags & OPf_KIDS)
4553             next_kid = cLISTOPo->op_last;
4554         break;
4555
4556     case OP_NULL:
4557         localize = 0;
4558         if (o->op_flags & OPf_SPECIAL)          /* do BLOCK */
4559             goto nomod;
4560         else if (!(o->op_flags & OPf_KIDS))
4561             break;
4562
4563         if (o->op_targ != OP_LIST) {
4564             OP *sib = OpSIBLING(cLISTOPo->op_first);
4565             /* OP_TRANS and OP_TRANSR with argument have a weird optree
4566              * that looks like
4567              *
4568              *   null
4569              *      arg
4570              *      trans
4571              *
4572              * compared with things like OP_MATCH which have the argument
4573              * as a child:
4574              *
4575              *   match
4576              *      arg
4577              *
4578              * so handle specially to correctly get "Can't modify" croaks etc
4579              */
4580
4581             if (sib && (sib->op_type == OP_TRANS || sib->op_type == OP_TRANSR))
4582             {
4583                 /* this should trigger a "Can't modify transliteration" err */
4584                 op_lvalue(sib, type);
4585             }
4586             next_kid = cBINOPo->op_first;
4587             /* we assume OP_NULLs which aren't ex-list have no more than 2
4588              * children. If this assumption is wrong, increase the scan
4589              * limit below */
4590             assert(   !OpHAS_SIBLING(next_kid)
4591                    || !OpHAS_SIBLING(OpSIBLING(next_kid)));
4592             break;
4593         }
4594         /* FALLTHROUGH */
4595     case OP_LIST:
4596         localize = 0;
4597         next_kid = cLISTOPo->op_first;
4598         break;
4599
4600     case OP_COREARGS:
4601         goto do_next;
4602
4603     case OP_AND:
4604     case OP_OR:
4605         if (type == OP_LEAVESUBLV
4606          || !S_vivifies(cLOGOPo->op_first->op_type))
4607             next_kid = cLOGOPo->op_first;
4608         else if (type == OP_LEAVESUBLV
4609          || !S_vivifies(OpSIBLING(cLOGOPo->op_first)->op_type))
4610             next_kid = OpSIBLING(cLOGOPo->op_first);
4611         goto nomod;
4612
4613     case OP_SREFGEN:
4614         if (type == OP_NULL) { /* local */
4615           local_refgen:
4616             if (!FEATURE_MYREF_IS_ENABLED)
4617                 Perl_croak(aTHX_ "The experimental declared_refs "
4618                                  "feature is not enabled");
4619             Perl_ck_warner_d(aTHX_
4620                      packWARN(WARN_EXPERIMENTAL__DECLARED_REFS),
4621                     "Declaring references is experimental");
4622             next_kid = cUNOPo->op_first;
4623             goto do_next;
4624         }
4625         if (type != OP_AASSIGN && type != OP_SASSIGN
4626          && type != OP_ENTERLOOP)
4627             goto nomod;
4628         /* Don’t bother applying lvalue context to the ex-list.  */
4629         kid = cUNOPx(cUNOPo->op_first)->op_first;
4630         assert (!OpHAS_SIBLING(kid));
4631         goto kid_2lvref;
4632     case OP_REFGEN:
4633         if (type == OP_NULL) /* local */
4634             goto local_refgen;
4635         if (type != OP_AASSIGN) goto nomod;
4636         kid = cUNOPo->op_first;
4637       kid_2lvref:
4638         {
4639             const U8 ec = PL_parser ? PL_parser->error_count : 0;
4640             S_lvref(aTHX_ kid, type);
4641             if (!PL_parser || PL_parser->error_count == ec) {
4642                 if (!FEATURE_REFALIASING_IS_ENABLED)
4643                     Perl_croak(aTHX_
4644                        "Experimental aliasing via reference not enabled");
4645                 Perl_ck_warner_d(aTHX_
4646                                  packWARN(WARN_EXPERIMENTAL__REFALIASING),
4647                                 "Aliasing via reference is experimental");
4648             }
4649         }
4650         if (o->op_type == OP_REFGEN)
4651             op_null(cUNOPx(cUNOPo->op_first)->op_first); /* pushmark */
4652         op_null(o);
4653         goto do_next;
4654
4655     case OP_SPLIT:
4656         if ((o->op_private & OPpSPLIT_ASSIGN)) {
4657             /* This is actually @array = split.  */
4658             PL_modcount = RETURN_UNLIMITED_NUMBER;
4659             break;
4660         }
4661         goto nomod;
4662
4663     case OP_SCALAR:
4664         op_lvalue(cUNOPo->op_first, OP_ENTERSUB);
4665         goto nomod;
4666     }
4667
4668     /* [20011101.069 (#7861)] File test operators interpret OPf_REF to mean that
4669        their argument is a filehandle; thus \stat(".") should not set
4670        it. AMS 20011102 */
4671     if (type == OP_REFGEN && OP_IS_STAT(o->op_type))
4672         goto do_next;
4673
4674     if (type != OP_LEAVESUBLV)
4675         o->op_flags |= OPf_MOD;
4676
4677     if (type == OP_AASSIGN || type == OP_SASSIGN)
4678         o->op_flags |= OPf_SPECIAL
4679                       |(o->op_type == OP_ENTERSUB ? 0 : OPf_REF);
4680     else if (!type) { /* local() */
4681         switch (localize) {
4682         case 1:
4683             o->op_private |= OPpLVAL_INTRO;
4684             o->op_flags &= ~OPf_SPECIAL;
4685             PL_hints |= HINT_BLOCK_SCOPE;
4686             break;
4687         case 0:
4688             break;
4689         case -1:
4690             Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX),
4691                            "Useless localization of %s", OP_DESC(o));
4692         }
4693     }
4694     else if (type != OP_GREPSTART && type != OP_ENTERSUB
4695              && type != OP_LEAVESUBLV && o->op_type != OP_ENTERSUB)
4696         o->op_flags |= OPf_REF;
4697
4698   do_next:
4699     while (!next_kid) {
4700         if (o == top_op)
4701             return top_op; /* at top; no parents/siblings to try */
4702         if (OpHAS_SIBLING(o)) {
4703             next_kid = o->op_sibparent;
4704             if (!OpHAS_SIBLING(next_kid)) {
4705                 /* a few node types don't recurse into their second child */
4706                 OP *parent = next_kid->op_sibparent;
4707                 I32 ptype  = parent->op_type;
4708                 if (   (ptype == OP_NULL && parent->op_targ != OP_LIST)
4709                     || (   (ptype == OP_AND || ptype == OP_OR)
4710                         && (type != OP_LEAVESUBLV 
4711                             && S_vivifies(next_kid->op_type))
4712                        )
4713                 )  {
4714                     /*try parent's next sibling */
4715                     o = parent;
4716                     next_kid =  NULL;
4717                 }
4718             }
4719         }
4720         else
4721             o = o->op_sibparent; /*try parent's next sibling */
4722
4723     }
4724     o = next_kid;
4725
4726     } /* while */
4727
4728 }
4729
4730
4731 STATIC bool
4732 S_scalar_mod_type(const OP *o, I32 type)
4733 {
4734     switch (type) {
4735     case OP_POS:
4736     case OP_SASSIGN:
4737         if (o && o->op_type == OP_RV2GV)
4738             return FALSE;
4739         /* FALLTHROUGH */
4740     case OP_PREINC:
4741     case OP_PREDEC:
4742     case OP_POSTINC:
4743     case OP_POSTDEC:
4744     case OP_I_PREINC:
4745     case OP_I_PREDEC:
4746     case OP_I_POSTINC:
4747     case OP_I_POSTDEC:
4748     case OP_POW:
4749     case OP_MULTIPLY:
4750     case OP_DIVIDE:
4751     case OP_MODULO:
4752     case OP_REPEAT:
4753     case OP_ADD:
4754     case OP_SUBTRACT:
4755     case OP_I_MULTIPLY:
4756     case OP_I_DIVIDE:
4757     case OP_I_MODULO:
4758     case OP_I_ADD:
4759     case OP_I_SUBTRACT:
4760     case OP_LEFT_SHIFT:
4761     case OP_RIGHT_SHIFT:
4762     case OP_BIT_AND:
4763     case OP_BIT_XOR:
4764     case OP_BIT_OR:
4765     case OP_NBIT_AND:
4766     case OP_NBIT_XOR:
4767     case OP_NBIT_OR:
4768     case OP_SBIT_AND:
4769     case OP_SBIT_XOR:
4770     case OP_SBIT_OR:
4771     case OP_CONCAT:
4772     case OP_SUBST:
4773     case OP_TRANS:
4774     case OP_TRANSR:
4775     case OP_READ:
4776     case OP_SYSREAD:
4777     case OP_RECV:
4778     case OP_ANDASSIGN:
4779     case OP_ORASSIGN:
4780     case OP_DORASSIGN:
4781     case OP_VEC:
4782     case OP_SUBSTR:
4783         return TRUE;
4784     default:
4785         return FALSE;
4786     }
4787 }
4788
4789 STATIC bool
4790 S_is_handle_constructor(const OP *o, I32 numargs)
4791 {
4792     PERL_ARGS_ASSERT_IS_HANDLE_CONSTRUCTOR;
4793
4794     switch (o->op_type) {
4795     case OP_PIPE_OP:
4796     case OP_SOCKPAIR:
4797         if (numargs == 2)
4798             return TRUE;
4799         /* FALLTHROUGH */
4800     case OP_SYSOPEN:
4801     case OP_OPEN:
4802     case OP_SELECT:             /* XXX c.f. SelectSaver.pm */
4803     case OP_SOCKET:
4804     case OP_OPEN_DIR:
4805     case OP_ACCEPT:
4806         if (numargs == 1)
4807             return TRUE;
4808         /* FALLTHROUGH */
4809     default:
4810         return FALSE;
4811     }
4812 }
4813
4814 static OP *
4815 S_refkids(pTHX_ OP *o, I32 type)
4816 {
4817     if (o && o->op_flags & OPf_KIDS) {
4818         OP *kid;
4819         for (kid = cLISTOPo->op_first; kid; kid = OpSIBLING(kid))
4820             ref(kid, type);
4821     }
4822     return o;
4823 }
4824
4825
4826 /* Apply reference (autovivification) context to the subtree at o.
4827  * For example in
4828  *     push @{expression}, ....;
4829  * o will be the head of 'expression' and type will be OP_RV2AV.
4830  * It marks the op o (or a suitable child) as autovivifying, e.g. by
4831  * setting  OPf_MOD.
4832  * For OP_RV2AV/OP_PADAV and OP_RV2HV/OP_PADHV sets OPf_REF too if
4833  * set_op_ref is true.
4834  *
4835  * Also calls scalar(o).
4836  */
4837
4838 OP *
4839 Perl_doref(pTHX_ OP *o, I32 type, bool set_op_ref)
4840 {
4841     dVAR;
4842     OP * top_op = o;
4843
4844     PERL_ARGS_ASSERT_DOREF;
4845
4846     if (PL_parser && PL_parser->error_count)
4847         return o;
4848
4849     while (1) {
4850         switch (o->op_type) {
4851         case OP_ENTERSUB:
4852             if ((type == OP_EXISTS || type == OP_DEFINED) &&
4853                 !(o->op_flags & OPf_STACKED)) {
4854                 OpTYPE_set(o, OP_RV2CV);             /* entersub => rv2cv */
4855                 assert(cUNOPo->op_first->op_type == OP_NULL);
4856                 /* disable pushmark */
4857                 op_null(((LISTOP*)cUNOPo->op_first)->op_first);
4858                 o->op_flags |= OPf_SPECIAL;
4859             }
4860             else if (type == OP_RV2SV || type == OP_RV2AV || type == OP_RV2HV){
4861                 o->op_private |= (type == OP_RV2AV ? OPpDEREF_AV
4862                                   : type == OP_RV2HV ? OPpDEREF_HV
4863                                   : OPpDEREF_SV);
4864                 o->op_flags |= OPf_MOD;
4865             }
4866
4867             break;
4868
4869         case OP_COND_EXPR:
4870             o = OpSIBLING(cUNOPo->op_first);
4871             continue;
4872
4873         case OP_RV2SV:
4874             if (type == OP_DEFINED)
4875                 o->op_flags |= OPf_SPECIAL;             /* don't create GV */
4876             /* FALLTHROUGH */
4877         case OP_PADSV:
4878             if (type == OP_RV2SV || type == OP_RV2AV || type == OP_RV2HV) {
4879                 o->op_private |= (type == OP_RV2AV ? OPpDEREF_AV
4880                                   : type == OP_RV2HV ? OPpDEREF_HV
4881                                   : OPpDEREF_SV);
4882                 o->op_flags |= OPf_MOD;
4883             }
4884             if (o->op_flags & OPf_KIDS) {
4885                 type = o->op_type;
4886                 o = cUNOPo->op_first;
4887                 continue;
4888             }
4889             break;
4890
4891         case OP_RV2AV:
4892         case OP_RV2HV:
4893             if (set_op_ref)
4894                 o->op_flags |= OPf_REF;
4895             /* FALLTHROUGH */
4896         case OP_RV2GV:
4897             if (type == OP_DEFINED)
4898                 o->op_flags |= OPf_SPECIAL;             /* don't create GV */
4899             type = o->op_type;
4900             o = cUNOPo->op_first;
4901             continue;
4902
4903         case OP_PADAV:
4904         case OP_PADHV:
4905             if (set_op_ref)
4906                 o->op_flags |= OPf_REF;
4907             break;
4908
4909         case OP_SCALAR:
4910         case OP_NULL:
4911             if (!(o->op_flags & OPf_KIDS) || type == OP_DEFINED)
4912                 break;
4913              o = cBINOPo->op_first;
4914             continue;
4915
4916         case OP_AELEM:
4917         case OP_HELEM:
4918             if (type == OP_RV2SV || type == OP_RV2AV || type == OP_RV2HV) {
4919                 o->op_private |= (type == OP_RV2AV ? OPpDEREF_AV
4920                                   : type == OP_RV2HV ? OPpDEREF_HV
4921                                   : OPpDEREF_SV);
4922                 o->op_flags |= OPf_MOD;
4923             }
4924             type = o->op_type;
4925             o = cBINOPo->op_first;
4926             continue;;
4927
4928         case OP_SCOPE:
4929         case OP_LEAVE:
4930             set_op_ref = FALSE;
4931             /* FALLTHROUGH */
4932         case OP_ENTER:
4933         case OP_LIST:
4934             if (!(o->op_flags & OPf_KIDS))
4935                 break;
4936             o = cLISTOPo->op_last;
4937             continue;
4938
4939         default:
4940             break;
4941         } /* switch */
4942
4943         while (1) {
4944             if (o == top_op)
4945                 return scalar(top_op); /* at top; no parents/siblings to try */
4946             if (OpHAS_SIBLING(o)) {
4947                 o = o->op_sibparent;
4948                 /* Normally skip all siblings and go straight to the parent;
4949                  * the only op that requires two children to be processed
4950                  * is OP_COND_EXPR */
4951                 if (!OpHAS_SIBLING(o)
4952                         && o->op_sibparent->op_type == OP_COND_EXPR)
4953                     break;
4954                 continue;
4955             }
4956             o = o->op_sibparent; /*try parent's next sibling */
4957         }
4958     } /* while */
4959 }
4960
4961
4962 STATIC OP *
4963 S_dup_attrlist(pTHX_ OP *o)
4964 {
4965     OP *rop;
4966
4967     PERL_ARGS_ASSERT_DUP_ATTRLIST;
4968
4969     /* An attrlist is either a simple OP_CONST or an OP_LIST with kids,
4970      * where the first kid is OP_PUSHMARK and the remaining ones
4971      * are OP_CONST.  We need to push the OP_CONST values.
4972      */
4973     if (o->op_type == OP_CONST)
4974         rop = newSVOP(OP_CONST, o->op_flags, SvREFCNT_inc_NN(cSVOPo->op_sv));
4975     else {
4976         assert((o->op_type == OP_LIST) && (o->op_flags & OPf_KIDS));
4977         rop = NULL;
4978         for (o = cLISTOPo->op_first; o; o = OpSIBLING(o)) {
4979             if (o->op_type == OP_CONST)
4980                 rop = op_append_elem(OP_LIST, rop,
4981                                   newSVOP(OP_CONST, o->op_flags,
4982                                           SvREFCNT_inc_NN(cSVOPo->op_sv)));
4983         }
4984     }
4985     return rop;
4986 }
4987
4988 STATIC void
4989 S_apply_attrs(pTHX_ HV *stash, SV *target, OP *attrs)
4990 {
4991     PERL_ARGS_ASSERT_APPLY_ATTRS;
4992     {
4993         SV * const stashsv = newSVhek(HvNAME_HEK(stash));
4994
4995         /* fake up C<use attributes $pkg,$rv,@attrs> */
4996
4997 #define ATTRSMODULE "attributes"
4998 #define ATTRSMODULE_PM "attributes.pm"
4999
5000         Perl_load_module(
5001           aTHX_ PERL_LOADMOD_IMPORT_OPS,
5002           newSVpvs(ATTRSMODULE),
5003           NULL,
5004           op_prepend_elem(OP_LIST,
5005                           newSVOP(OP_CONST, 0, stashsv),
5006                           op_prepend_elem(OP_LIST,
5007                                           newSVOP(OP_CONST, 0,
5008                                                   newRV(target)),
5009                                           dup_attrlist(attrs))));
5010     }
5011 }
5012
5013 STATIC void
5014 S_apply_attrs_my(pTHX_ HV *stash, OP *target, OP *attrs, OP **imopsp)
5015 {
5016     OP *pack, *imop, *arg;
5017     SV *meth, *stashsv, **svp;
5018
5019     PERL_ARGS_ASSERT_APPLY_ATTRS_MY;
5020
5021     if (!attrs)
5022         return;
5023
5024     assert(target->op_type == OP_PADSV ||
5025            target->op_type == OP_PADHV ||
5026            target->op_type == OP_PADAV);
5027
5028     /* Ensure that attributes.pm is loaded. */
5029     /* Don't force the C<use> if we don't need it. */
5030     svp = hv_fetchs(GvHVn(PL_incgv), ATTRSMODULE_PM, FALSE);
5031     if (svp && *svp != &PL_sv_undef)
5032         NOOP;   /* already in %INC */
5033     else
5034         Perl_load_module(aTHX_ PERL_LOADMOD_NOIMPORT,
5035                                newSVpvs(ATTRSMODULE), NULL);
5036
5037     /* Need package name for method call. */
5038     pack = newSVOP(OP_CONST, 0, newSVpvs(ATTRSMODULE));
5039
5040     /* Build up the real arg-list. */
5041     stashsv = newSVhek(HvNAME_HEK(stash));
5042
5043     arg = newOP(OP_PADSV, 0);
5044     arg->op_targ = target->op_targ;
5045     arg = op_prepend_elem(OP_LIST,
5046                        newSVOP(OP_CONST, 0, stashsv),
5047                        op_prepend_elem(OP_LIST,
5048                                     newUNOP(OP_REFGEN, 0,
5049                                             arg),
5050                                     dup_attrlist(attrs)));
5051
5052     /* Fake up a method call to import */
5053     meth = newSVpvs_share("import");
5054     imop = op_convert_list(OP_ENTERSUB, OPf_STACKED|OPf_SPECIAL|OPf_WANT_VOID,
5055                    op_append_elem(OP_LIST,
5056                                op_prepend_elem(OP_LIST, pack, arg),
5057                                newMETHOP_named(OP_METHOD_NAMED, 0, meth)));
5058
5059     /* Combine the ops. */
5060     *imopsp = op_append_elem(OP_LIST, *imopsp, imop);
5061 }
5062
5063 /*
5064 =notfor apidoc apply_attrs_string
5065
5066 Attempts to apply a list of attributes specified by the C<attrstr> and
5067 C<len> arguments to the subroutine identified by the C<cv> argument which
5068 is expected to be associated with the package identified by the C<stashpv>
5069 argument (see L<attributes>).  It gets this wrong, though, in that it
5070 does not correctly identify the boundaries of the individual attribute
5071 specifications within C<attrstr>.  This is not really intended for the
5072 public API, but has to be listed here for systems such as AIX which
5073 need an explicit export list for symbols.  (It's called from XS code
5074 in support of the C<ATTRS:> keyword from F<xsubpp>.)  Patches to fix it
5075 to respect attribute syntax properly would be welcome.
5076
5077 =cut
5078 */
5079
5080 void
5081 Perl_apply_attrs_string(pTHX_ const char *stashpv, CV *cv,
5082                         const char *attrstr, STRLEN len)
5083 {
5084     OP *attrs = NULL;
5085
5086     PERL_ARGS_ASSERT_APPLY_ATTRS_STRING;
5087
5088     if (!len) {
5089         len = strlen(attrstr);
5090     }
5091
5092     while (len) {
5093         for (; isSPACE(*attrstr) && len; --len, ++attrstr) ;
5094         if (len) {
5095             const char * const sstr = attrstr;
5096             for (; !isSPACE(*attrstr) && len; --len, ++attrstr) ;
5097             attrs = op_append_elem(OP_LIST, attrs,
5098                                 newSVOP(OP_CONST, 0,
5099                                         newSVpvn(sstr, attrstr-sstr)));
5100         }
5101     }
5102
5103     Perl_load_module(aTHX_ PERL_LOADMOD_IMPORT_OPS,
5104                      newSVpvs(ATTRSMODULE),
5105                      NULL, op_prepend_elem(OP_LIST,
5106                                   newSVOP(OP_CONST, 0, newSVpv(stashpv,0)),
5107                                   op_prepend_elem(OP_LIST,
5108                                                newSVOP(OP_CONST, 0,
5109                                                        newRV(MUTABLE_SV(cv))),
5110                                                attrs)));
5111 }
5112
5113 STATIC void
5114 S_move_proto_attr(pTHX_ OP **proto, OP **attrs, const GV * name,
5115                         bool curstash)
5116 {
5117     OP *new_proto = NULL;
5118     STRLEN pvlen;
5119     char *pv;
5120     OP *o;
5121
5122     PERL_ARGS_ASSERT_MOVE_PROTO_ATTR;
5123
5124     if (!*attrs)
5125         return;
5126
5127     o = *attrs;
5128     if (o->op_type == OP_CONST) {
5129         pv = SvPV(cSVOPo_sv, pvlen);
5130         if (memBEGINs(pv, pvlen, "prototype(")) {
5131             SV * const tmpsv = newSVpvn_flags(pv + 10, pvlen - 11, SvUTF8(cSVOPo_sv));
5132             SV ** const tmpo = cSVOPx_svp(o);
5133             SvREFCNT_dec(cSVOPo_sv);
5134             *tmpo = tmpsv;
5135             new_proto = o;
5136             *attrs = NULL;
5137         }
5138     } else if (o->op_type == OP_LIST) {
5139         OP * lasto;
5140         assert(o->op_flags & OPf_KIDS);
5141         lasto = cLISTOPo->op_first;
5142         assert(lasto->op_type == OP_PUSHMARK);
5143         for (o = OpSIBLING(lasto); o; o = OpSIBLING(o)) {
5144             if (o->op_type == OP_CONST) {
5145                 pv = SvPV(cSVOPo_sv, pvlen);
5146                 if (memBEGINs(pv, pvlen, "prototype(")) {
5147                     SV * const tmpsv = newSVpvn_flags(pv + 10, pvlen - 11, SvUTF8(cSVOPo_sv));
5148                     SV ** const tmpo = cSVOPx_svp(o);
5149                     SvREFCNT_dec(cSVOPo_sv);
5150                     *tmpo = tmpsv;
5151                     if (new_proto && ckWARN(WARN_MISC)) {
5152                         STRLEN new_len;
5153                         const char * newp = SvPV(cSVOPo_sv, new_len);
5154                         Perl_warner(aTHX_ packWARN(WARN_MISC),
5155                             "Attribute prototype(%" UTF8f ") discards earlier prototype attribute in same sub",
5156                             UTF8fARG(SvUTF8(cSVOPo_sv), new_len, newp));
5157                         op_free(new_proto);
5158                     }
5159                     else if (new_proto)
5160                         op_free(new_proto);
5161                     new_proto = o;
5162                     /* excise new_proto from the list */
5163                     op_sibling_splice(*attrs, lasto, 1, NULL);
5164                     o = lasto;
5165                     continue;
5166                 }
5167             }
5168             lasto = o;
5169         }
5170         /* If the list is now just the PUSHMARK, scrap the whole thing; otherwise attributes.xs
5171            would get pulled in with no real need */
5172         if (!OpHAS_SIBLING(cLISTOPx(*attrs)->op_first)) {
5173             op_free(*attrs);
5174             *attrs = NULL;
5175         }
5176     }
5177
5178     if (new_proto) {
5179         SV *svname;
5180         if (isGV(name)) {
5181             svname = sv_newmortal();
5182             gv_efullname3(svname, name, NULL);
5183         }
5184         else if (SvPOK(name) && *SvPVX((SV *)name) == '&')
5185             svname = newSVpvn_flags(SvPVX((SV *)name)+1, SvCUR(name)-1, SvUTF8(name)|SVs_TEMP);
5186         else
5187             svname = (SV *)name;
5188         if (ckWARN(WARN_ILLEGALPROTO))
5189             (void)validate_proto(svname, cSVOPx_sv(new_proto), TRUE,
5190                                  curstash);
5191         if (*proto && ckWARN(WARN_PROTOTYPE)) {
5192             STRLEN old_len, new_len;
5193             const char * oldp = SvPV(cSVOPx_sv(*proto), old_len);
5194             const char * newp = SvPV(cSVOPx_sv(new_proto), new_len);
5195
5196             if (curstash && svname == (SV *)name
5197              && !memchr(SvPVX(svname), ':', SvCUR(svname))) {
5198                 svname = sv_2mortal(newSVsv(PL_curstname));
5199                 sv_catpvs(svname, "::");
5200                 sv_catsv(svname, (SV *)name);
5201             }
5202
5203             Perl_warner(aTHX_ packWARN(WARN_PROTOTYPE),
5204                 "Prototype '%" UTF8f "' overridden by attribute 'prototype(%" UTF8f ")'"
5205                 " in %" SVf,
5206                 UTF8fARG(SvUTF8(cSVOPx_sv(*proto)), old_len, oldp),
5207                 UTF8fARG(SvUTF8(cSVOPx_sv(new_proto)), new_len, newp),
5208                 SVfARG(svname));
5209         }
5210         if (*proto)
5211             op_free(*proto);
5212         *proto = new_proto;
5213     }
5214 }
5215
5216 static void
5217 S_cant_declare(pTHX_ OP *o)
5218 {
5219     if (o->op_type == OP_NULL
5220      && (o->op_flags & (OPf_SPECIAL|OPf_KIDS)) == OPf_KIDS)
5221         o = cUNOPo->op_first;
5222     yyerror(Perl_form(aTHX_ "Can't declare %s in \"%s\"",
5223                              o->op_type == OP_NULL
5224                                && o->op_flags & OPf_SPECIAL
5225                                  ? "do block"
5226                                  : OP_DESC(o),
5227                              PL_parser->in_my == KEY_our   ? "our"   :
5228                              PL_parser->in_my == KEY_state ? "state" :
5229                                                              "my"));
5230 }
5231
5232 STATIC OP *
5233 S_my_kid(pTHX_ OP *o, OP *attrs, OP **imopsp)
5234 {
5235     I32 type;
5236     const bool stately = PL_parser && PL_parser->in_my == KEY_state;
5237
5238     PERL_ARGS_ASSERT_MY_KID;
5239
5240     if (!o || (PL_parser && PL_parser->error_count))
5241         return o;
5242
5243     type = o->op_type;
5244
5245     if (OP_TYPE_IS_OR_WAS(o, OP_LIST)) {
5246         OP *kid;
5247         for (kid = cLISTOPo->op_first; kid; kid = OpSIBLING(kid))
5248             my_kid(kid, attrs, imopsp);
5249         return o;
5250     } else if (type == OP_UNDEF || type == OP_STUB) {
5251         return o;
5252     } else if (type == OP_RV2SV ||      /* "our" declaration */
5253                type == OP_RV2AV ||
5254                type == OP_RV2HV) {
5255         if (cUNOPo->op_first->op_type != OP_GV) { /* MJD 20011224 */
5256             S_cant_declare(aTHX_ o);
5257         } else if (attrs) {
5258             GV * const gv = cGVOPx_gv(cUNOPo->op_first);
5259             assert(PL_parser);
5260             PL_parser->in_my = FALSE;
5261             PL_parser->in_my_stash = NULL;
5262             apply_attrs(GvSTASH(gv),
5263                         (type == OP_RV2SV ? GvSVn(gv) :
5264                          type == OP_RV2AV ? MUTABLE_SV(GvAVn(gv)) :
5265                          type == OP_RV2HV ? MUTABLE_SV(GvHVn(gv)) : MUTABLE_SV(gv)),
5266                         attrs);
5267         }
5268         o->op_private |= OPpOUR_INTRO;
5269         return o;
5270     }
5271     else if (type == OP_REFGEN || type == OP_SREFGEN) {
5272         if (!FEATURE_MYREF_IS_ENABLED)
5273             Perl_croak(aTHX_ "The experimental declared_refs "
5274                              "feature is not enabled");
5275         Perl_ck_warner_d(aTHX_
5276              packWARN(WARN_EXPERIMENTAL__DECLARED_REFS),
5277             "Declaring references is experimental");
5278         /* Kid is a nulled OP_LIST, handled above.  */
5279         my_kid(cUNOPo->op_first, attrs, imopsp);
5280         return o;
5281     }
5282     else if (type != OP_PADSV &&
5283              type != OP_PADAV &&
5284              type != OP_PADHV &&
5285              type != OP_PUSHMARK)
5286     {
5287         S_cant_declare(aTHX_ o);
5288         return o;
5289     }
5290     else if (attrs && type != OP_PUSHMARK) {
5291         HV *stash;
5292
5293         assert(PL_parser);
5294         PL_parser->in_my = FALSE;
5295         PL_parser->in_my_stash = NULL;
5296
5297         /* check for C<my Dog $spot> when deciding package */
5298         stash = PAD_COMPNAME_TYPE(o->op_targ);
5299         if (!stash)
5300             stash = PL_curstash;
5301         apply_attrs_my(stash, o, attrs, imopsp);
5302     }
5303     o->op_flags |= OPf_MOD;
5304     o->op_private |= OPpLVAL_INTRO;
5305     if (stately)
5306         o->op_private |= OPpPAD_STATE;
5307     return o;
5308 }
5309
5310 OP *
5311 Perl_my_attrs(pTHX_ OP *o, OP *attrs)
5312 {
5313     OP *rops;
5314     int maybe_scalar = 0;
5315
5316     PERL_ARGS_ASSERT_MY_ATTRS;
5317
5318 /* [perl #17376]: this appears to be premature, and results in code such as
5319    C< our(%x); > executing in list mode rather than void mode */
5320 #if 0
5321     if (o->op_flags & OPf_PARENS)
5322         list(o);
5323     else
5324         maybe_scalar = 1;
5325 #else
5326     maybe_scalar = 1;
5327 #endif
5328     if (attrs)
5329         SAVEFREEOP(attrs);
5330     rops = NULL;
5331     o = my_kid(o, attrs, &rops);
5332     if (rops) {
5333         if (maybe_scalar && o->op_type == OP_PADSV) {
5334             o = scalar(op_append_list(OP_LIST, rops, o));
5335             o->op_private |= OPpLVAL_INTRO;
5336         }
5337         else {
5338             /* The listop in rops might have a pushmark at the beginning,
5339                which will mess up list assignment. */
5340             LISTOP * const lrops = (LISTOP *)rops; /* for brevity */
5341             if (rops->op_type == OP_LIST &&
5342                 lrops->op_first && lrops->op_first->op_type == OP_PUSHMARK)
5343             {
5344                 OP * const pushmark = lrops->op_first;
5345                 /* excise pushmark */
5346                 op_sibling_splice(rops, NULL, 1, NULL);
5347                 op_free(pushmark);
5348             }
5349             o = op_append_list(OP_LIST, o, rops);
5350         }
5351     }
5352     PL_parser->in_my = FALSE;
5353     PL_parser->in_my_stash = NULL;
5354     return o;
5355 }
5356
5357 OP *
5358 Perl_sawparens(pTHX_ OP *o)
5359 {
5360     PERL_UNUSED_CONTEXT;
5361     if (o)
5362         o->op_flags |= OPf_PARENS;
5363     return o;
5364 }
5365
5366 OP *
5367 Perl_bind_match(pTHX_ I32 type, OP *left, OP *right)
5368 {
5369     OP *o;
5370     bool ismatchop = 0;
5371     const OPCODE ltype = left->op_type;
5372     const OPCODE rtype = right->op_type;
5373
5374     PERL_ARGS_ASSERT_BIND_MATCH;
5375
5376     if ( (ltype == OP_RV2AV || ltype == OP_RV2HV || ltype == OP_PADAV
5377           || ltype == OP_PADHV) && ckWARN(WARN_MISC))
5378     {
5379       const char * const desc
5380           = PL_op_desc[(
5381                           rtype == OP_SUBST || rtype == OP_TRANS
5382                        || rtype == OP_TRANSR
5383                        )
5384                        ? (int)rtype : OP_MATCH];
5385       const bool isary = ltype == OP_RV2AV || ltype == OP_PADAV;
5386       SV * const name =
5387         S_op_varname(aTHX_ left);
5388       if (name)
5389         Perl_warner(aTHX_ packWARN(WARN_MISC),
5390              "Applying %s to %" SVf " will act on scalar(%" SVf ")",
5391              desc, SVfARG(name), SVfARG(name));
5392       else {
5393         const char * const sample = (isary
5394              ? "@array" : "%hash");
5395         Perl_warner(aTHX_ packWARN(WARN_MISC),
5396              "Applying %s to %s will act on scalar(%s)",
5397              desc, sample, sample);
5398       }
5399     }
5400
5401     if (rtype == OP_CONST &&
5402         cSVOPx(right)->op_private & OPpCONST_BARE &&
5403         cSVOPx(right)->op_private & OPpCONST_STRICT)
5404     {
5405         no_bareword_allowed(right);
5406     }
5407
5408     /* !~ doesn't make sense with /r, so error on it for now */
5409     if (rtype == OP_SUBST && (cPMOPx(right)->op_pmflags & PMf_NONDESTRUCT) &&
5410         type == OP_NOT)
5411         /* diag_listed_as: Using !~ with %s doesn't make sense */
5412         yyerror("Using !~ with s///r doesn't make sense");
5413     if (rtype == OP_TRANSR && type == OP_NOT)
5414         /* diag_listed_as: Using !~ with %s doesn't make sense */
5415         yyerror("Using !~ with tr///r doesn't make sense");
5416
5417     ismatchop = (rtype == OP_MATCH ||
5418                  rtype == OP_SUBST ||
5419                  rtype == OP_TRANS || rtype == OP_TRANSR)
5420              && !(right->op_flags & OPf_SPECIAL);
5421     if (ismatchop && right->op_private & OPpTARGET_MY) {
5422         right->op_targ = 0;
5423         right->op_private &= ~OPpTARGET_MY;
5424     }
5425     if (!(right->op_flags & OPf_STACKED) && !right->op_targ && ismatchop) {
5426         if (left->op_type == OP_PADSV
5427          && !(left->op_private & OPpLVAL_INTRO))
5428         {
5429             right->op_targ = left->op_targ;
5430             op_free(left);
5431             o = right;
5432         }
5433         else {
5434             right->op_flags |= OPf_STACKED;
5435             if (rtype != OP_MATCH && rtype != OP_TRANSR &&
5436             ! (rtype == OP_TRANS &&
5437                right->op_private & OPpTRANS_IDENTICAL) &&
5438             ! (rtype == OP_SUBST &&
5439                (cPMOPx(right)->op_pmflags & PMf_NONDESTRUCT)))
5440                 left = op_lvalue(left, rtype);
5441             if (right->op_type == OP_TRANS || right->op_type == OP_TRANSR)
5442                 o = newBINOP(OP_NULL, OPf_STACKED, scalar(left), right);
5443             else
5444                 o = op_prepend_elem(rtype, scalar(left), right);
5445         }
5446         if (type == OP_NOT)
5447             return newUNOP(OP_NOT, 0, scalar(o));
5448         return o;
5449     }
5450     else
5451         return bind_match(type, left,
5452                 pmruntime(newPMOP(OP_MATCH, 0), right, NULL, 0, 0));
5453 }
5454
5455 OP *
5456 Perl_invert(pTHX_ OP *o)
5457 {
5458     if (!o)
5459         return NULL;
5460     return newUNOP(OP_NOT, OPf_SPECIAL, scalar(o));
5461 }
5462
5463 /*
5464 =for apidoc op_scope
5465
5466 Wraps up an op tree with some additional ops so that at runtime a dynamic
5467 scope will be created.  The original ops run in the new dynamic scope,
5468 and then, provided that they exit normally, the scope will be unwound.
5469 The additional ops used to create and unwind the dynamic scope will
5470 normally be an C<enter>/C<leave> pair, but a C<scope> op may be used
5471 instead if the ops are simple enough to not need the full dynamic scope
5472 structure.
5473
5474 =cut
5475 */
5476
5477 OP *
5478 Perl_op_scope(pTHX_ OP *o)
5479 {
5480     dVAR;
5481     if (o) {
5482         if (o->op_flags & OPf_PARENS || PERLDB_NOOPT || TAINTING_get) {
5483             o = op_prepend_elem(OP_LINESEQ,
5484                     newOP(OP_ENTER, (o->op_flags & OPf_WANT)), o);
5485             OpTYPE_set(o, OP_LEAVE);
5486         }
5487         else if (o->op_type == OP_LINESEQ) {
5488             OP *kid;
5489             OpTYPE_set(o, OP_SCOPE);
5490             kid = ((LISTOP*)o)->op_first;
5491             if (kid->op_type == OP_NEXTSTATE || kid->op_type == OP_DBSTATE) {
5492                 op_null(kid);
5493
5494                 /* The following deals with things like 'do {1 for 1}' */
5495                 kid = OpSIBLING(kid);
5496                 if (kid &&
5497                     (kid->op_type == OP_NEXTSTATE || kid->op_type == OP_DBSTATE))
5498                     op_null(kid);
5499             }
5500         }
5501         else
5502             o = newLISTOP(OP_SCOPE, 0, o, NULL);
5503     }
5504     return o;
5505 }
5506
5507 OP *
5508 Perl_op_unscope(pTHX_ OP *o)
5509 {
5510     if (o && o->op_type == OP_LINESEQ) {
5511         OP *kid = cLISTOPo->op_first;
5512         for(; kid; kid = OpSIBLING(kid))
5513             if (kid->op_type == OP_NEXTSTATE || kid->op_type == OP_DBSTATE)
5514                 op_null(kid);
5515     }
5516     return o;
5517 }
5518
5519 /*
5520 =for apidoc block_start
5521
5522 Handles compile-time scope entry.
5523 Arranges for hints to be restored on block
5524 exit and also handles pad sequence numbers to make lexical variables scope
5525 right.  Returns a savestack index for use with C<block_end>.
5526
5527 =cut
5528 */
5529
5530 int
5531 Perl_block_start(pTHX_ int full)
5532 {
5533     const int retval = PL_savestack_ix;
5534
5535     PL_compiling.cop_seq = PL_cop_seqmax;
5536     COP_SEQMAX_INC;
5537     pad_block_start(full);
5538     SAVEHINTS();
5539     PL_hints &= ~HINT_BLOCK_SCOPE;
5540     SAVECOMPILEWARNINGS();
5541     PL_compiling.cop_warnings = DUP_WARNINGS(PL_compiling.cop_warnings);
5542     SAVEI32(PL_compiling.cop_seq);
5543     PL_compiling.cop_seq = 0;
5544
5545     CALL_BLOCK_HOOKS(bhk_start, full);
5546
5547     return retval;
5548 }
5549
5550 /*
5551 =for apidoc block_end
5552
5553 Handles compile-time scope exit.  C<floor>
5554 is the savestack index returned by
5555 C<block_start>, and C<seq> is the body of the block.  Returns the block,
5556 possibly modified.
5557
5558 =cut
5559 */
5560
5561 OP*
5562 Perl_block_end(pTHX_ I32 floor, OP *seq)
5563 {
5564     const int needblockscope = PL_hints & HINT_BLOCK_SCOPE;
5565     OP* retval = scalarseq(seq);
5566     OP *o;
5567
5568     /* XXX Is the null PL_parser check necessary here? */
5569     assert(PL_parser); /* Let’s find out under debugging builds.  */
5570     if (PL_parser && PL_parser->parsed_sub) {
5571         o = newSTATEOP(0, NULL, NULL);
5572         op_null(o);
5573         retval = op_append_elem(OP_LINESEQ, retval, o);
5574     }
5575
5576     CALL_BLOCK_HOOKS(bhk_pre_end, &retval);
5577
5578     LEAVE_SCOPE(floor);
5579     if (needblockscope)
5580         PL_hints |= HINT_BLOCK_SCOPE; /* propagate out */
5581     o = pad_leavemy();
5582
5583     if (o) {
5584         /* pad_leavemy has created a sequence of introcv ops for all my
5585            subs declared in the block.  We have to replicate that list with
5586            clonecv ops, to deal with this situation:
5587
5588                sub {
5589                    my sub s1;
5590                    my sub s2;
5591                    sub s1 { state sub foo { \&s2 } }
5592                }->()
5593
5594            Originally, I was going to have introcv clone the CV and turn
5595            off the stale flag.  Since &s1 is declared before &s2, the
5596            introcv op for &s1 is executed (on sub entry) before the one for
5597            &s2.  But the &foo sub inside &s1 (which is cloned when &s1 is
5598            cloned, since it is a state sub) closes over &s2 and expects
5599            to see it in its outer CV’s pad.  If the introcv op clones &s1,
5600            then &s2 is still marked stale.  Since &s1 is not active, and
5601            &foo closes over &s1’s implicit entry for &s2, we get a â€˜Varia-
5602            ble will not stay shared’ warning.  Because it is the same stub
5603            that will be used when the introcv op for &s2 is executed, clos-
5604            ing over it is safe.  Hence, we have to turn off the stale flag
5605            on all lexical subs in the block before we clone any of them.
5606            Hence, having introcv clone the sub cannot work.  So we create a
5607            list of ops like this:
5608
5609                lineseq
5610                   |
5611                   +-- introcv
5612                   |
5613                   +-- introcv
5614                   |
5615                   +-- introcv
5616                   |
5617                   .
5618                   .
5619                   .
5620                   |
5621                   +-- clonecv
5622                   |
5623                   +-- clonecv
5624                   |
5625                   +-- clonecv
5626                   |
5627                   .
5628                   .
5629                   .
5630          */
5631         OP *kid = o->op_flags & OPf_KIDS ? cLISTOPo->op_first : o;
5632         OP * const last = o->op_flags & OPf_KIDS ? cLISTOPo->op_last : o;
5633         for (;; kid = OpSIBLING(kid)) {
5634             OP *newkid = newOP(OP_CLONECV, 0);
5635             newkid->op_targ = kid->op_targ;
5636             o = op_append_elem(OP_LINESEQ, o, newkid);
5637             if (kid == last) break;
5638         }
5639         retval = op_prepend_elem(OP_LINESEQ, o, retval);
5640     }
5641
5642     CALL_BLOCK_HOOKS(bhk_post_end, &retval);
5643
5644     return retval;
5645 }
5646
5647 /*
5648 =head1 Compile-time scope hooks
5649
5650 =for apidoc blockhook_register
5651
5652 Register a set of hooks to be called when the Perl lexical scope changes
5653 at compile time.  See L<perlguts/"Compile-time scope hooks">.
5654
5655 =cut
5656 */
5657
5658 void
5659 Perl_blockhook_register(pTHX_ BHK *hk)
5660 {
5661     PERL_ARGS_ASSERT_BLOCKHOOK_REGISTER;
5662
5663     Perl_av_create_and_push(aTHX_ &PL_blockhooks, newSViv(PTR2IV(hk)));
5664 }
5665
5666 void
5667 Perl_newPROG(pTHX_ OP *o)
5668 {
5669     OP *start;
5670
5671     PERL_ARGS_ASSERT_NEWPROG;
5672
5673     if (PL_in_eval) {
5674         PERL_CONTEXT *cx;
5675         I32 i;
5676         if (PL_eval_root)
5677                 return;
5678         PL_eval_root = newUNOP(OP_LEAVEEVAL,
5679                                ((PL_in_eval & EVAL_KEEPERR)
5680                                 ? OPf_SPECIAL : 0), o);
5681
5682         cx = CX_CUR();
5683         assert(CxTYPE(cx) == CXt_EVAL);
5684
5685         if ((cx->blk_gimme & G_WANT) == G_VOID)
5686             scalarvoid(PL_eval_root);
5687         else if ((cx->blk_gimme & G_WANT) == G_ARRAY)
5688             list(PL_eval_root);
5689         else
5690             scalar(PL_eval_root);
5691
5692         start = op_linklist(PL_eval_root);
5693         PL_eval_root->op_next = 0;
5694         i = PL_savestack_ix;
5695         SAVEFREEOP(o);
5696         ENTER;
5697         S_process_optree(aTHX_ NULL, PL_eval_root, start);
5698         LEAVE;
5699         PL_savestack_ix = i;
5700     }
5701     else {
5702         if (o->op_type == OP_STUB) {
5703             /* This block is entered if nothing is compiled for the main
5704                program. This will be the case for an genuinely empty main
5705                program, or one which only has BEGIN blocks etc, so already
5706                run and freed.
5707
5708                Historically (5.000) the guard above was !o. However, commit
5709                f8a08f7b8bd67b28 (Jun 2001), integrated to blead as
5710                c71fccf11fde0068, changed perly.y so that newPROG() is now
5711                called with the output of block_end(), which returns a new
5712                OP_STUB for the case of an empty optree. ByteLoader (and
5713                maybe other things) also take this path, because they set up
5714                PL_main_start and PL_main_root directly, without generating an
5715                optree.
5716
5717                If the parsing the main program aborts (due to parse errors,
5718                or due to BEGIN or similar calling exit), then newPROG()
5719                isn't even called, and hence this code path and its cleanups
5720                are skipped. This shouldn't make a make a difference:
5721                * a non-zero return from perl_parse is a failure, and
5722                  perl_destruct() should be called immediately.
5723                * however, if exit(0) is called during the parse, then
5724                  perl_parse() returns 0, and perl_run() is called. As
5725                  PL_main_start will be NULL, perl_run() will return
5726                  promptly, and the exit code will remain 0.
5727             */
5728
5729             PL_comppad_name = 0;
5730             PL_compcv = 0;
5731             S_op_destroy(aTHX_ o);
5732             return;
5733         }
5734         PL_main_root = op_scope(sawparens(scalarvoid(o)));
5735         PL_curcop = &PL_compiling;
5736         start = LINKLIST(PL_main_root);
5737         PL_main_root->op_next = 0;
5738         S_process_optree(aTHX_ NULL, PL_main_root, start);
5739         if (!PL_parser->error_count)
5740             /* on error, leave CV slabbed so that ops left lying around
5741              * will eb cleaned up. Else unslab */
5742             cv_forget_slab(PL_compcv);
5743         PL_compcv = 0;
5744
5745         /* Register with debugger */
5746         if (PERLDB_INTER) {
5747             CV * const cv = get_cvs("DB::postponed", 0);
5748             if (cv) {
5749                 dSP;
5750                 PUSHMARK(SP);
5751                 XPUSHs(MUTABLE_SV(CopFILEGV(&PL_compiling)));
5752                 PUTBACK;
5753                 call_sv(MUTABLE_SV(cv), G_DISCARD);
5754             }
5755         }
5756     }
5757 }
5758
5759 OP *
5760 Perl_localize(pTHX_ OP *o, I32 lex)
5761 {
5762     PERL_ARGS_ASSERT_LOCALIZE;
5763
5764     if (o->op_flags & OPf_PARENS)
5765 /* [perl #17376]: this appears to be premature, and results in code such as
5766    C< our(%x); > executing in list mode rather than void mode */
5767 #if 0
5768         list(o);
5769 #else
5770         NOOP;
5771 #endif
5772     else {
5773         if ( PL_parser->bufptr > PL_parser->oldbufptr
5774             && PL_parser->bufptr[-1] == ','
5775             && ckWARN(WARN_PARENTHESIS))
5776         {
5777             char *s = PL_parser->bufptr;
5778             bool sigil = FALSE;
5779
5780             /* some heuristics to detect a potential error */
5781             while (*s && (memCHRs(", \t\n", *s)))
5782                 s++;
5783
5784             while (1) {
5785                 if (*s && (memCHRs("@$%", *s) || (!lex && *s == '*'))
5786                        && *++s
5787                        && (isWORDCHAR(*s) || UTF8_IS_CONTINUED(*s))) {
5788                     s++;
5789                     sigil = TRUE;
5790                     while (*s && (isWORDCHAR(*s) || UTF8_IS_CONTINUED(*s)))
5791                         s++;
5792                     while (*s && (memCHRs(", \t\n", *s)))
5793                         s++;
5794                 }
5795                 else
5796                     break;
5797             }
5798             if (sigil && (*s == ';' || *s == '=')) {
5799                 Perl_warner(aTHX_ packWARN(WARN_PARENTHESIS),
5800                                 "Parentheses missing around \"%s\" list",
5801                                 lex
5802                                     ? (PL_parser->in_my == KEY_our
5803                                         ? "our"
5804                                         : PL_parser->in_my == KEY_state
5805                                             ? "state"
5806                                             : "my")
5807                                     : "local");
5808             }
5809         }
5810     }
5811     if (lex)
5812         o = my(o);
5813     else
5814         o = op_lvalue(o, OP_NULL);              /* a bit kludgey */
5815     PL_parser->in_my = FALSE;
5816     PL_parser->in_my_stash = NULL;
5817     return o;
5818 }
5819
5820 OP *
5821 Perl_jmaybe(pTHX_ OP *o)
5822 {
5823     PERL_ARGS_ASSERT_JMAYBE;
5824
5825     if (o->op_type == OP_LIST) {
5826         OP * const o2
5827             = newSVREF(newGVOP(OP_GV, 0, gv_fetchpvs(";", GV_ADD|GV_NOTQUAL, SVt_PV)));
5828         o = op_convert_list(OP_JOIN, 0, op_prepend_elem(OP_LIST, o2, o));
5829     }
5830     return o;
5831 }
5832
5833 PERL_STATIC_INLINE OP *
5834 S_op_std_init(pTHX_ OP *o)
5835 {
5836     I32 type = o->op_type;
5837
5838     PERL_ARGS_ASSERT_OP_STD_INIT;
5839
5840     if (PL_opargs[type] & OA_RETSCALAR)
5841         scalar(o);
5842     if (PL_opargs[type] & OA_TARGET && !o->op_targ)
5843         o->op_targ = pad_alloc(type, SVs_PADTMP);
5844
5845     return o;
5846 }
5847
5848 PERL_STATIC_INLINE OP *
5849 S_op_integerize(pTHX_ OP *o)
5850 {
5851     I32 type = o->op_type;
5852
5853     PERL_ARGS_ASSERT_OP_INTEGERIZE;
5854
5855     /* integerize op. */
5856     if ((PL_opargs[type] & OA_OTHERINT) && (PL_hints & HINT_INTEGER))
5857     {
5858         dVAR;
5859         o->op_ppaddr = PL_ppaddr[++(o->op_type)];
5860     }
5861
5862     if (type == OP_NEGATE)
5863         /* XXX might want a ck_negate() for this */
5864         cUNOPo->op_first->op_private &= ~OPpCONST_STRICT;
5865
5866     return o;
5867 }
5868
5869 /* This function exists solely to provide a scope to limit
5870    setjmp/longjmp() messing with auto variables.
5871  */
5872 PERL_STATIC_INLINE int
5873 S_fold_constants_eval(pTHX) {
5874     int ret = 0;
5875     dJMPENV;
5876
5877     JMPENV_PUSH(ret);
5878
5879     if (ret == 0) {
5880         CALLRUNOPS(aTHX);
5881     }
5882
5883     JMPENV_POP;
5884
5885     return ret;
5886 }
5887
5888 static OP *
5889 S_fold_constants(pTHX_ OP *const o)
5890 {
5891     dVAR;
5892     OP *curop;
5893     OP *newop;
5894     I32 type = o->op_type;
5895     bool is_stringify;
5896     SV *sv = NULL;
5897     int ret = 0;
5898     OP *old_next;
5899     SV * const oldwarnhook = PL_warnhook;
5900     SV * const olddiehook  = PL_diehook;
5901     COP not_compiling;
5902     U8 oldwarn = PL_dowarn;
5903     I32 old_cxix;
5904
5905     PERL_ARGS_ASSERT_FOLD_CONSTANTS;
5906
5907     if (!(PL_opargs[type] & OA_FOLDCONST))
5908         goto nope;
5909
5910     switch (type) {
5911     case OP_UCFIRST:
5912     case OP_LCFIRST:
5913     case OP_UC:
5914     case OP_LC:
5915     case OP_FC:
5916 #ifdef USE_LOCALE_CTYPE
5917         if (IN_LC_COMPILETIME(LC_CTYPE))
5918             goto nope;
5919 #endif
5920         break;
5921     case OP_SLT:
5922     case OP_SGT:
5923     case OP_SLE:
5924     case OP_SGE:
5925     case OP_SCMP:
5926 #ifdef USE_LOCALE_COLLATE
5927         if (IN_LC_COMPILETIME(LC_COLLATE))
5928             goto nope;
5929 #endif
5930         break;
5931     case OP_SPRINTF:
5932         /* XXX what about the numeric ops? */
5933 #ifdef USE_LOCALE_NUMERIC
5934         if (IN_LC_COMPILETIME(LC_NUMERIC))
5935             goto nope;
5936 #endif
5937         break;
5938     case OP_PACK:
5939         if (!OpHAS_SIBLING(cLISTOPo->op_first)
5940           || OpSIBLING(cLISTOPo->op_first)->op_type != OP_CONST)
5941             goto nope;
5942         {
5943             SV * const sv = cSVOPx_sv(OpSIBLING(cLISTOPo->op_first));
5944             if (!SvPOK(sv) || SvGMAGICAL(sv)) goto nope;
5945             {
5946                 const char *s = SvPVX_const(sv);
5947                 while (s < SvEND(sv)) {
5948                     if (isALPHA_FOLD_EQ(*s, 'p')) goto nope;
5949                     s++;
5950                 }
5951             }
5952         }
5953         break;
5954     case OP_REPEAT:
5955         if (o->op_private & OPpREPEAT_DOLIST) goto nope;
5956         break;
5957     case OP_SREFGEN:
5958         if (cUNOPx(cUNOPo->op_first)->op_first->op_type != OP_CONST
5959          || SvPADTMP(cSVOPx_sv(cUNOPx(cUNOPo->op_first)->op_first)))
5960             goto nope;
5961     }
5962
5963     if (PL_parser && PL_parser->error_count)
5964         goto nope;              /* Don't try to run w/ errors */
5965
5966     for (curop = LINKLIST(o); curop != o; curop = LINKLIST(curop)) {
5967         switch (curop->op_type) {
5968         case OP_CONST:
5969             if (   (curop->op_private & OPpCONST_BARE)
5970                 && (curop->op_private & OPpCONST_STRICT)) {
5971                 no_bareword_allowed(curop);
5972                 goto nope;
5973             }
5974             /* FALLTHROUGH */
5975         case OP_LIST:
5976         case OP_SCALAR:
5977         case OP_NULL:
5978         case OP_PUSHMARK:
5979             /* Foldable; move to next op in list */
5980             break;
5981
5982         default:
5983             /* No other op types are considered foldable */
5984             goto nope;
5985         }
5986     }
5987
5988     curop = LINKLIST(o);
5989     old_next = o->op_next;
5990     o->op_next = 0;
5991     PL_op = curop;
5992
5993     old_cxix = cxstack_ix;
5994     create_eval_scope(NULL, G_FAKINGEVAL);
5995
5996     /* Verify that we don't need to save it:  */
5997     assert(PL_curcop == &PL_compiling);
5998     StructCopy(&PL_compiling, &not_compiling, COP);
5999     PL_curcop = &not_compiling;
6000     /* The above ensures that we run with all the correct hints of the
6001        currently compiling COP, but that IN_PERL_RUNTIME is true. */
6002     assert(IN_PERL_RUNTIME);
6003     PL_warnhook = PERL_WARNHOOK_FATAL;
6004     PL_diehook  = NULL;
6005
6006     /* Effective $^W=1.  */
6007     if ( ! (PL_dowarn & G_WARN_ALL_MASK))
6008         PL_dowarn |= G_WARN_ON;
6009
6010     ret = S_fold_constants_eval(aTHX);
6011
6012     switch (ret) {
6013     case 0:
6014         sv = *(PL_stack_sp--);
6015         if (o->op_targ && sv == PAD_SV(o->op_targ)) {   /* grab pad temp? */
6016             pad_swipe(o->op_targ,  FALSE);
6017         }
6018         else if (SvTEMP(sv)) {                  /* grab mortal temp? */
6019             SvREFCNT_inc_simple_void(sv);
6020             SvTEMP_off(sv);
6021         }
6022         else { assert(SvIMMORTAL(sv)); }
6023         break;
6024     case 3:
6025         /* Something tried to die.  Abandon constant folding.  */
6026         /* Pretend the error never happened.  */
6027         CLEAR_ERRSV();
6028         o->op_next = old_next;
6029         break;
6030     default:
6031         /* Don't expect 1 (setjmp failed) or 2 (something called my_exit)  */
6032         PL_warnhook = oldwarnhook;
6033         PL_diehook  = olddiehook;
6034         /* XXX note that this croak may fail as we've already blown away
6035          * the stack - eg any nested evals */
6036         Perl_croak(aTHX_ "panic: fold_constants JMPENV_PUSH returned %d", ret);
6037     }
6038     PL_dowarn   = oldwarn;
6039     PL_warnhook = oldwarnhook;
6040     PL_diehook  = olddiehook;
6041     PL_curcop = &PL_compiling;
6042
6043     /* if we croaked, depending on how we croaked the eval scope
6044      * may or may not have already been popped */
6045     if (cxstack_ix > old_cxix) {
6046         assert(cxstack_ix == old_cxix + 1);
6047         assert(CxTYPE(CX_CUR()) == CXt_EVAL);
6048         delete_eval_scope();
6049     }
6050     if (ret)
6051         goto nope;
6052
6053     /* OP_STRINGIFY and constant folding are used to implement qq.
6054        Here the constant folding is an implementation detail that we
6055        want to hide.  If the stringify op is itself already marked
6056        folded, however, then it is actually a folded join.  */
6057     is_stringify = type == OP_STRINGIFY && !o->op_folded;
6058     op_free(o);
6059     assert(sv);
6060     if (is_stringify)
6061         SvPADTMP_off(sv);
6062     else if (!SvIMMORTAL(sv)) {
6063         SvPADTMP_on(sv);
6064         SvREADONLY_on(sv);
6065     }
6066     newop = newSVOP(OP_CONST, 0, MUTABLE_SV(sv));
6067     if (!is_stringify) newop->op_folded = 1;
6068     return newop;
6069
6070  nope:
6071     return o;
6072 }
6073
6074 /* convert a constant range in list context into an OP_RV2AV, OP_CONST pair;
6075  * the constant value being an AV holding the flattened range.
6076  */
6077
6078 static void
6079 S_gen_constant_list(pTHX_ OP *o)
6080 {
6081     dVAR;
6082     OP *curop, *old_next;
6083     SV * const oldwarnhook = PL_warnhook;
6084     SV * const olddiehook  = PL_diehook;
6085     COP *old_curcop;
6086     U8 oldwarn = PL_dowarn;
6087     SV **svp;
6088     AV *av;
6089     I32 old_cxix;
6090     COP not_compiling;
6091     int ret = 0;
6092     dJMPENV;
6093     bool op_was_null;
6094
6095     list(o);
6096     if (PL_parser && PL_parser->error_count)
6097         return;         /* Don't attempt to run with errors */
6098
6099     curop = LINKLIST(o);
6100     old_next = o->op_next;
6101     o->op_next = 0;
6102     op_was_null = o->op_type == OP_NULL;
6103     if (op_was_null) /* b3698342565fb462291fba4b432cfcd05b6eb4e1 */
6104         o->op_type = OP_CUSTOM;
6105     CALL_PEEP(curop);
6106     if (op_was_null)
6107         o->op_type = OP_NULL;
6108     S_prune_chain_head(&curop);
6109     PL_op = curop;
6110
6111     old_cxix = cxstack_ix;
6112     create_eval_scope(NULL, G_FAKINGEVAL);
6113
6114     old_curcop = PL_curcop;
6115     StructCopy(old_curcop, &not_compiling, COP);
6116     PL_curcop = &not_compiling;
6117     /* The above ensures that we run with all the correct hints of the
6118        current COP, but that IN_PERL_RUNTIME is true. */
6119     assert(IN_PERL_RUNTIME);
6120     PL_warnhook = PERL_WARNHOOK_FATAL;
6121     PL_diehook  = NULL;
6122     JMPENV_PUSH(ret);
6123
6124     /* Effective $^W=1.  */
6125     if ( ! (PL_dowarn & G_WARN_ALL_MASK))
6126         PL_dowarn |= G_WARN_ON;
6127
6128     switch (ret) {
6129     case 0:
6130 #if defined DEBUGGING && !defined DEBUGGING_RE_ONLY
6131         PL_curstackinfo->si_stack_hwm = 0; /* stop valgrind complaining */
6132 #endif
6133         Perl_pp_pushmark(aTHX);
6134         CALLRUNOPS(aTHX);
6135         PL_op = curop;
6136         assert (!(curop->op_flags & OPf_SPECIAL));
6137         assert(curop->op_type == OP_RANGE);
6138         Perl_pp_anonlist(aTHX);
6139         break;
6140     case 3:
6141         CLEAR_ERRSV();
6142         o->op_next = old_next;
6143         break;
6144     default:
6145         JMPENV_POP;
6146         PL_warnhook = oldwarnhook;
6147         PL_diehook = olddiehook;
6148         Perl_croak(aTHX_ "panic: gen_constant_list JMPENV_PUSH returned %d",
6149             ret);
6150     }
6151
6152     JMPENV_POP;
6153     PL_dowarn = oldwarn;
6154     PL_warnhook = oldwarnhook;
6155     PL_diehook = olddiehook;
6156     PL_curcop = old_curcop;
6157
6158     if (cxstack_ix > old_cxix) {
6159         assert(cxstack_ix == old_cxix + 1);
6160         assert(CxTYPE(CX_CUR()) == CXt_EVAL);
6161         delete_eval_scope();
6162     }
6163     if (ret)
6164         return;
6165
6166     OpTYPE_set(o, OP_RV2AV);
6167     o->op_flags &= ~OPf_REF;    /* treat \(1..2) like an ordinary list */
6168     o->op_flags |= OPf_PARENS;  /* and flatten \(1..2,3) */
6169     o->op_opt = 0;              /* needs to be revisited in rpeep() */
6170     av = (AV *)SvREFCNT_inc_NN(*PL_stack_sp--);
6171
6172     /* replace subtree with an OP_CONST */
6173     curop = ((UNOP*)o)->op_first;
6174     op_sibling_splice(o, NULL, -1, newSVOP(OP_CONST, 0, (SV *)av));
6175     op_free(curop);
6176
6177     if (AvFILLp(av) != -1)
6178         for (svp = AvARRAY(av) + AvFILLp(av); svp >= AvARRAY(av); --svp)
6179         {
6180             SvPADTMP_on(*svp);
6181             SvREADONLY_on(*svp);
6182         }
6183     LINKLIST(o);
6184     list(o);
6185     return;
6186 }
6187
6188 /*
6189 =head1 Optree Manipulation Functions
6190 */
6191
6192 /* List constructors */
6193
6194 /*
6195 =for apidoc op_append_elem
6196
6197 Append an item to the list of ops contained directly within a list-type
6198 op, returning the lengthened list.  C<first> is the list-type op,
6199 and C<last> is the op to append to the list.  C<optype> specifies the
6200 intended opcode for the list.  If C<first> is not already a list of the
6201 right type, it will be upgraded into one.  If either C<first> or C<last>
6202 is null, the other is returned unchanged.
6203
6204 =cut
6205 */
6206
6207 OP *
6208 Perl_op_append_elem(pTHX_ I32 type, OP *first, OP *last)
6209 {
6210     if (!first)
6211         return last;
6212
6213     if (!last)
6214         return first;
6215
6216     if (first->op_type != (unsigned)type
6217         || (type == OP_LIST && (first->op_flags & OPf_PARENS)))
6218     {
6219         return newLISTOP(type, 0, first, last);
6220     }
6221
6222     op_sibling_splice(first, ((LISTOP*)first)->op_last, 0, last);
6223     first->op_flags |= OPf_KIDS;
6224     return first;
6225 }
6226
6227 /*
6228 =for apidoc op_append_list
6229
6230 Concatenate the lists of ops contained directly within two list-type ops,
6231 returning the combined list.  C<first> and C<last> are the list-type ops
6232 to concatenate.  C<optype> specifies the intended opcode for the list.
6233 If either C<first> or C<last> is not already a list of the right type,
6234 it will be upgraded into one.  If either C<first> or C<last> is null,
6235 the other is returned unchanged.
6236
6237 =cut
6238 */
6239
6240 OP *
6241 Perl_op_append_list(pTHX_ I32 type, OP *first, OP *last)
6242 {
6243     if (!first)
6244         return last;
6245
6246     if (!last)
6247         return first;
6248
6249     if (first->op_type != (unsigned)type)
6250         return op_prepend_elem(type, first, last);
6251
6252     if (last->op_type != (unsigned)type)
6253         return op_append_elem(type, first, last);
6254
6255     OpMORESIB_set(((LISTOP*)first)->op_last, ((LISTOP*)last)->op_first);
6256     ((LISTOP*)first)->op_last = ((LISTOP*)last)->op_last;
6257     OpLASTSIB_set(((LISTOP*)first)->op_last, first);
6258     first->op_flags |= (last->op_flags & OPf_KIDS);
6259
6260     S_op_destroy(aTHX_ last);
6261
6262     return first;
6263 }
6264
6265 /*
6266 =for apidoc op_prepend_elem
6267
6268 Prepend an item to the list of ops contained directly within a list-type
6269 op, returning the lengthened list.  C<first> is the op to prepend to the
6270 list, and C<last> is the list-type op.  C<optype> specifies the intended
6271 opcode for the list.  If C<last> is not already a list of the right type,
6272 it will be upgraded into one.  If either C<first> or C<last> is null,
6273 the other is returned unchanged.
6274
6275 =cut
6276 */
6277
6278 OP *
6279 Perl_op_prepend_elem(pTHX_ I32 type, OP *first, OP *last)
6280 {
6281     if (!first)
6282         return last;
6283
6284     if (!last)
6285         return first;
6286
6287     if (last->op_type == (unsigned)type) {
6288         if (type == OP_LIST) {  /* already a PUSHMARK there */
6289             /* insert 'first' after pushmark */
6290             op_sibling_splice(last, cLISTOPx(last)->op_first, 0, first);
6291             if (!(first->op_flags & OPf_PARENS))
6292                 last->op_flags &= ~OPf_PARENS;
6293         }
6294         else
6295             op_sibling_splice(last, NULL, 0, first);
6296         last->op_flags |= OPf_KIDS;
6297         return last;
6298     }
6299
6300     return newLISTOP(type, 0, first, last);
6301 }
6302
6303 /*
6304 =for apidoc op_convert_list
6305
6306 Converts C<o> into a list op if it is not one already, and then converts it
6307 into the specified C<type>, calling its check function, allocating a target if
6308 it needs one, and folding constants.
6309
6310 A list-type op is usually constructed one kid at a time via C<newLISTOP>,
6311 C<op_prepend_elem> and C<op_append_elem>.  Then finally it is passed to
6312 C<op_convert_list> to make it the right type.
6313
6314 =cut
6315 */
6316
6317 OP *
6318 Perl_op_convert_list(pTHX_ I32 type, I32 flags, OP *o)
6319 {
6320     dVAR;
6321     if (type < 0) type = -type, flags |= OPf_SPECIAL;
6322     if (!o || o->op_type != OP_LIST)
6323         o = force_list(o, 0);
6324     else
6325     {
6326         o->op_flags &= ~OPf_WANT;
6327         o->op_private &= ~OPpLVAL_INTRO;
6328     }
6329
6330     if (!(PL_opargs[type] & OA_MARK))
6331         op_null(cLISTOPo->op_first);
6332     else {
6333         OP * const kid2 = OpSIBLING(cLISTOPo->op_first);
6334         if (kid2 && kid2->op_type == OP_COREARGS) {
6335             op_null(cLISTOPo->op_first);
6336             kid2->op_private |= OPpCOREARGS_PUSHMARK;
6337         }
6338     }
6339
6340     if (type != OP_SPLIT)
6341         /* At this point o is a LISTOP, but OP_SPLIT is a PMOP; let
6342          * ck_split() create a real PMOP and leave the op's type as listop
6343          * for now. Otherwise op_free() etc will crash.
6344          */
6345         OpTYPE_set(o, type);
6346
6347     o->op_flags |= flags;
6348     if (flags & OPf_FOLDED)
6349         o->op_folded = 1;
6350
6351     o = CHECKOP(type, o);
6352     if (o->op_type != (unsigned)type)
6353         return o;
6354
6355     return fold_constants(op_integerize(op_std_init(o)));
6356 }
6357
6358 /* Constructors */
6359
6360
6361 /*
6362 =head1 Optree construction
6363
6364 =for apidoc newNULLLIST
6365
6366 Constructs, checks, and returns a new C<stub> op, which represents an
6367 empty list expression.
6368
6369 =cut
6370 */
6371
6372 OP *
6373 Perl_newNULLLIST(pTHX)
6374 {
6375     return newOP(OP_STUB, 0);
6376 }
6377
6378 /* promote o and any siblings to be a list if its not already; i.e.
6379  *
6380  *  o - A - B
6381  *
6382  * becomes
6383  *
6384  *  list
6385  *    |
6386  *  pushmark - o - A - B
6387  *
6388  * If nullit it true, the list op is nulled.
6389  */
6390
6391 static OP *
6392 S_force_list(pTHX_ OP *o, bool nullit)
6393 {
6394     if (!o || o->op_type != OP_LIST) {
6395         OP *rest = NULL;
6396         if (o) {
6397             /* manually detach any siblings then add them back later */
6398             rest = OpSIBLING(o);
6399             OpLASTSIB_set(o, NULL);
6400         }
6401         o = newLISTOP(OP_LIST, 0, o, NULL);
6402         if (rest)
6403             op_sibling_splice(o, cLISTOPo->op_last, 0, rest);
6404     }
6405     if (nullit)
6406         op_null(o);
6407     return o;
6408 }
6409
6410 /*
6411 =for apidoc newLISTOP
6412
6413 Constructs, checks, and returns an op of any list type.  C<type> is
6414 the opcode.  C<flags> gives the eight bits of C<op_flags>, except that
6415 C<OPf_KIDS> will be set automatically if required.  C<first> and C<last>
6416 supply up to two ops to be direct children of the list op; they are
6417 consumed by this function and become part of the constructed op tree.
6418
6419 For most list operators, the check function expects all the kid ops to be
6420 present already, so calling C<newLISTOP(OP_JOIN, ...)> (e.g.) is not
6421 appropriate.  What you want to do in that case is create an op of type
6422 C<OP_LIST>, append more children to it, and then call L</op_convert_list>.
6423 See L</op_convert_list> for more information.
6424
6425
6426 =cut
6427 */
6428
6429 OP *
6430 Perl_newLISTOP(pTHX_ I32 type, I32 flags, OP *first, OP *last)
6431 {
6432     dVAR;
6433     LISTOP *listop;
6434     /* Note that allocating an OP_PUSHMARK can die under Safe.pm if
6435      * pushmark is banned. So do it now while existing ops are in a
6436      * consistent state, in case they suddenly get freed */
6437     OP* const pushop = type == OP_LIST ? newOP(OP_PUSHMARK, 0) : NULL;
6438
6439     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_LISTOP
6440         || type == OP_CUSTOM);
6441
6442     NewOp(1101, listop, 1, LISTOP);
6443     OpTYPE_set(listop, type);
6444     if (first || last)
6445         flags |= OPf_KIDS;
6446     listop->op_flags = (U8)flags;
6447
6448     if (!last && first)
6449         last = first;
6450     else if (!first && last)
6451         first = last;
6452     else if (first)
6453         OpMORESIB_set(first, last);
6454     listop->op_first = first;
6455     listop->op_last = last;
6456
6457     if (pushop) {
6458         OpMORESIB_set(pushop, first);
6459         listop->op_first = pushop;
6460         listop->op_flags |= OPf_KIDS;
6461         if (!last)
6462             listop->op_last = pushop;
6463     }
6464     if (listop->op_last)
6465         OpLASTSIB_set(listop->op_last, (OP*)listop);
6466
6467     return CHECKOP(type, listop);
6468 }
6469
6470 /*
6471 =for apidoc newOP
6472
6473 Constructs, checks, and returns an op of any base type (any type that
6474 has no extra fields).  C<type> is the opcode.  C<flags> gives the
6475 eight bits of C<op_flags>, and, shifted up eight bits, the eight bits
6476 of C<op_private>.
6477
6478 =cut
6479 */
6480
6481 OP *
6482 Perl_newOP(pTHX_ I32 type, I32 flags)
6483 {
6484     dVAR;
6485     OP *o;
6486
6487     if (type == -OP_ENTEREVAL) {
6488         type = OP_ENTEREVAL;
6489         flags |= OPpEVAL_BYTES<<8;
6490     }
6491
6492     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_BASEOP
6493         || (PL_opargs[type] & OA_CLASS_MASK) == OA_BASEOP_OR_UNOP
6494         || (PL_opargs[type] & OA_CLASS_MASK) == OA_FILESTATOP
6495         || (PL_opargs[type] & OA_CLASS_MASK) == OA_LOOPEXOP);
6496
6497     NewOp(1101, o, 1, OP);
6498     OpTYPE_set(o, type);
6499     o->op_flags = (U8)flags;
6500
6501     o->op_next = o;
6502     o->op_private = (U8)(0 | (flags >> 8));
6503     if (PL_opargs[type] & OA_RETSCALAR)
6504         scalar(o);
6505     if (PL_opargs[type] & OA_TARGET)
6506         o->op_targ = pad_alloc(type, SVs_PADTMP);
6507     return CHECKOP(type, o);
6508 }
6509
6510 /*
6511 =for apidoc newUNOP
6512
6513 Constructs, checks, and returns an op of any unary type.  C<type> is
6514 the opcode.  C<flags> gives the eight bits of C<op_flags>, except that
6515 C<OPf_KIDS> will be set automatically if required, and, shifted up eight
6516 bits, the eight bits of C<op_private>, except that the bit with value 1
6517 is automatically set.  C<first> supplies an optional op to be the direct
6518 child of the unary op; it is consumed by this function and become part
6519 of the constructed op tree.
6520
6521 =for apidoc Amnh||OPf_KIDS
6522
6523 =cut
6524 */
6525
6526 OP *
6527 Perl_newUNOP(pTHX_ I32 type, I32 flags, OP *first)
6528 {
6529     dVAR;
6530     UNOP *unop;
6531
6532     if (type == -OP_ENTEREVAL) {
6533         type = OP_ENTEREVAL;
6534         flags |= OPpEVAL_BYTES<<8;
6535     }
6536
6537     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_UNOP
6538         || (PL_opargs[type] & OA_CLASS_MASK) == OA_BASEOP_OR_UNOP
6539         || (PL_opargs[type] & OA_CLASS_MASK) == OA_FILESTATOP
6540         || (PL_opargs[type] & OA_CLASS_MASK) == OA_LOOPEXOP
6541         || type == OP_SASSIGN
6542         || type == OP_ENTERTRY
6543         || type == OP_CUSTOM
6544         || type == OP_NULL );
6545
6546     if (!first)
6547         first = newOP(OP_STUB, 0);
6548     if (PL_opargs[type] & OA_MARK)
6549         first = force_list(first, 1);
6550
6551     NewOp(1101, unop, 1, UNOP);
6552     OpTYPE_set(unop, type);
6553     unop->op_first = first;
6554     unop->op_flags = (U8)(flags | OPf_KIDS);
6555     unop->op_private = (U8)(1 | (flags >> 8));
6556
6557     if (!OpHAS_SIBLING(first)) /* true unless weird syntax error */
6558         OpLASTSIB_set(first, (OP*)unop);
6559
6560     unop = (UNOP*) CHECKOP(type, unop);
6561     if (unop->op_next)
6562         return (OP*)unop;
6563
6564     return fold_constants(op_integerize(op_std_init((OP *) unop)));
6565 }
6566
6567 /*
6568 =for apidoc newUNOP_AUX
6569
6570 Similar to C<newUNOP>, but creates an C<UNOP_AUX> struct instead, with C<op_aux>
6571 initialised to C<aux>
6572
6573 =cut
6574 */
6575
6576 OP *
6577 Perl_newUNOP_AUX(pTHX_ I32 type, I32 flags, OP *first, UNOP_AUX_item *aux)
6578 {
6579     dVAR;
6580     UNOP_AUX *unop;
6581
6582     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_UNOP_AUX
6583         || type == OP_CUSTOM);
6584
6585     NewOp(1101, unop, 1, UNOP_AUX);
6586     unop->op_type = (OPCODE)type;
6587     unop->op_ppaddr = PL_ppaddr[type];
6588     unop->op_first = first;
6589     unop->op_flags = (U8)(flags | (first ? OPf_KIDS : 0));
6590     unop->op_private = (U8)((first ? 1 : 0) | (flags >> 8));
6591     unop->op_aux = aux;
6592
6593     if (first && !OpHAS_SIBLING(first)) /* true unless weird syntax error */
6594         OpLASTSIB_set(first, (OP*)unop);
6595
6596     unop = (UNOP_AUX*) CHECKOP(type, unop);
6597
6598     return op_std_init((OP *) unop);
6599 }
6600
6601 /*
6602 =for apidoc newMETHOP
6603
6604 Constructs, checks, and returns an op of method type with a method name
6605 evaluated at runtime.  C<type> is the opcode.  C<flags> gives the eight
6606 bits of C<op_flags>, except that C<OPf_KIDS> will be set automatically,
6607 and, shifted up eight bits, the eight bits of C<op_private>, except that
6608 the bit with value 1 is automatically set.  C<dynamic_meth> supplies an
6609 op which evaluates method name; it is consumed by this function and
6610 become part of the constructed op tree.
6611 Supported optypes: C<OP_METHOD>.
6612
6613 =cut
6614 */
6615
6616 static OP*
6617 S_newMETHOP_internal(pTHX_ I32 type, I32 flags, OP* dynamic_meth, SV* const_meth) {
6618     dVAR;
6619     METHOP *methop;
6620
6621     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_METHOP
6622         || type == OP_CUSTOM);
6623
6624     NewOp(1101, methop, 1, METHOP);
6625     if (dynamic_meth) {
6626         if (PL_opargs[type] & OA_MARK) dynamic_meth = force_list(dynamic_meth, 1);
6627         methop->op_flags = (U8)(flags | OPf_KIDS);
6628         methop->op_u.op_first = dynamic_meth;
6629         methop->op_private = (U8)(1 | (flags >> 8));
6630
6631         if (!OpHAS_SIBLING(dynamic_meth))
6632             OpLASTSIB_set(dynamic_meth, (OP*)methop);
6633     }
6634     else {
6635         assert(const_meth);
6636         methop->op_flags = (U8)(flags & ~OPf_KIDS);
6637         methop->op_u.op_meth_sv = const_meth;
6638         methop->op_private = (U8)(0 | (flags >> 8));
6639         methop->op_next = (OP*)methop;
6640     }
6641
6642 #ifdef USE_ITHREADS
6643     methop->op_rclass_targ = 0;
6644 #else
6645     methop->op_rclass_sv = NULL;
6646 #endif
6647
6648     OpTYPE_set(methop, type);
6649     return CHECKOP(type, methop);
6650 }
6651
6652 OP *
6653 Perl_newMETHOP (pTHX_ I32 type, I32 flags, OP* dynamic_meth) {
6654     PERL_ARGS_ASSERT_NEWMETHOP;
6655     return newMETHOP_internal(type, flags, dynamic_meth, NULL);
6656 }
6657
6658 /*
6659 =for apidoc newMETHOP_named
6660
6661 Constructs, checks, and returns an op of method type with a constant
6662 method name.  C<type> is the opcode.  C<flags> gives the eight bits of
6663 C<op_flags>, and, shifted up eight bits, the eight bits of
6664 C<op_private>.  C<const_meth> supplies a constant method name;
6665 it must be a shared COW string.
6666 Supported optypes: C<OP_METHOD_NAMED>.
6667
6668 =cut
6669 */
6670
6671 OP *
6672 Perl_newMETHOP_named (pTHX_ I32 type, I32 flags, SV* const_meth) {
6673     PERL_ARGS_ASSERT_NEWMETHOP_NAMED;
6674     return newMETHOP_internal(type, flags, NULL, const_meth);
6675 }
6676
6677 /*
6678 =for apidoc newBINOP
6679
6680 Constructs, checks, and returns an op of any binary type.  C<type>
6681 is the opcode.  C<flags> gives the eight bits of C<op_flags>, except
6682 that C<OPf_KIDS> will be set automatically, and, shifted up eight bits,
6683 the eight bits of C<op_private>, except that the bit with value 1 or
6684 2 is automatically set as required.  C<first> and C<last> supply up to
6685 two ops to be the direct children of the binary op; they are consumed
6686 by this function and become part of the constructed op tree.
6687
6688 =cut
6689 */
6690
6691 OP *
6692 Perl_newBINOP(pTHX_ I32 type, I32 flags, OP *first, OP *last)
6693 {
6694     dVAR;
6695     BINOP *binop;
6696
6697     ASSUME((PL_opargs[type] & OA_CLASS_MASK) == OA_BINOP
6698         || type == OP_NULL || type == OP_CUSTOM);
6699
6700     NewOp(1101, binop, 1, BINOP);
6701
6702     if (!first)
6703         first = newOP(OP_NULL, 0);
6704
6705     OpTYPE_set(binop, type);
6706     binop->op_first = first;
6707     binop->op_flags = (U8)(flags | OPf_KIDS);
6708     if (!last) {
6709         last = first;
6710         binop->op_private = (U8)(1 | (flags >> 8));
6711     }
6712     else {
6713         binop->op_private = (U8)(2 | (flags >> 8));
6714         OpMORESIB_set(first, last);
6715     }
6716
6717     if (!OpHAS_SIBLING(last)) /* true unless weird syntax error */
6718         OpLASTSIB_set(last, (OP*)binop);
6719
6720     binop->op_last = OpSIBLING(binop->op_first);
6721     if (binop->op_last)
6722         OpLASTSIB_set(binop->op_last, (OP*)binop);
6723
6724     binop = (BINOP*)CHECKOP(type, binop);
6725     if (binop->op_next || binop->op_type != (OPCODE)type)
6726         return (OP*)binop;
6727
6728     return fold_constants(op_integerize(op_std_init((OP *)binop)));
6729 }
6730
6731 void
6732 Perl_invmap_dump(pTHX_ SV* invlist, UV *map)
6733 {
6734     const char indent[] = "    ";
6735
6736     UV len = _invlist_len(invlist);
6737     UV * array = invlist_array(invlist);
6738     UV i;
6739
6740     PERL_ARGS_ASSERT_INVMAP_DUMP;
6741
6742     for (i = 0; i < len; i++) {
6743         UV start = array[i];
6744         UV end   = (i + 1 < len) ? array[i+1] - 1 : IV_MAX;
6745
6746         PerlIO_printf(Perl_debug_log, "%s[%" UVuf "] 0x%04" UVXf, indent, i, start);
6747         if (end == IV_MAX) {
6748             PerlIO_printf(Perl_debug_log, " .. INFTY");
6749         }
6750         else if (end != start) {
6751             PerlIO_printf(Perl_debug_log, " .. 0x%04" UVXf, end);
6752         }
6753         else {
6754             PerlIO_printf(Perl_debug_log, "            ");
6755         }
6756
6757         PerlIO_printf(Perl_debug_log, "\t");
6758
6759         if (map[i] == TR_UNLISTED) {
6760             PerlIO_printf(Perl_debug_log, "TR_UNLISTED\n");
6761         }
6762         else if (map[i] == TR_SPECIAL_HANDLING) {
6763             PerlIO_printf(Perl_debug_log, "TR_SPECIAL_HANDLING\n");
6764         }
6765         else {
6766             PerlIO_printf(Perl_debug_log, "0x%04" UVXf "\n", map[i]);
6767         }
6768     }
6769 }
6770
6771 /* Given an OP_TRANS / OP_TRANSR op o, plus OP_CONST ops expr and repl
6772  * containing the search and replacement strings, assemble into
6773  * a translation table attached as o->op_pv.
6774  * Free expr and repl.
6775  * It expects the toker to have already set the
6776  *   OPpTRANS_COMPLEMENT
6777  *   OPpTRANS_SQUASH
6778  *   OPpTRANS_DELETE
6779  * flags as appropriate; this function may add
6780  *   OPpTRANS_USE_SVOP
6781  *   OPpTRANS_CAN_FORCE_UTF8
6782  *   OPpTRANS_IDENTICAL
6783  *   OPpTRANS_GROWS
6784  * flags
6785  */
6786
6787 static OP *
6788 S_pmtrans(pTHX_ OP *o, OP *expr, OP *repl)
6789 {
6790     /* This function compiles a tr///, from data gathered from toke.c, into a
6791      * form suitable for use by do_trans() in doop.c at runtime.
6792      *
6793      * It first normalizes the data, while discarding extraneous inputs; then
6794      * writes out the compiled data.  The normalization allows for complete
6795      * analysis, and avoids some false negatives and positives earlier versions
6796      * of this code had.
6797      *
6798      * The normalization form is an inversion map (described below in detail).
6799      * This is essentially the compiled form for tr///'s that require UTF-8,
6800      * and its easy to use it to write the 257-byte table for tr///'s that
6801      * don't need UTF-8.  That table is identical to what's been in use for
6802      * many perl versions, except that it doesn't handle some edge cases that
6803      * it used to, involving code points above 255.  The UTF-8 form now handles
6804      * these.  (This could be changed with extra coding should it shown to be
6805      * desirable.)
6806      *
6807      * If the complement (/c) option is specified, the lhs string (tstr) is
6808      * parsed into an inversion list.  Complementing these is trivial.  Then a
6809      * complemented tstr is built from that, and used thenceforth.  This hides
6810      * the fact that it was complemented from almost all successive code.
6811      *
6812      * One of the important characteristics to know about the input is whether
6813      * the transliteration may be done in place, or does a temporary need to be
6814      * allocated, then copied.  If the replacement for every character in every
6815      * possible string takes up no more bytes than the the character it
6816      * replaces, then it can be edited in place.  Otherwise the replacement
6817      * could "grow", depending on the strings being processed.  Some inputs
6818      * won't grow, and might even shrink under /d, but some inputs could grow,
6819      * so we have to assume any given one might grow.  On very long inputs, the
6820      * temporary could eat up a lot of memory, so we want to avoid it if
6821      * possible.  For non-UTF-8 inputs, everything is single-byte, so can be
6822      * edited in place, unless there is something in the pattern that could
6823      * force it into UTF-8.  The inversion map makes it feasible to determine
6824      * this.  Previous versions of this code pretty much punted on determining
6825      * if UTF-8 could be edited in place.  Now, this code is rigorous in making
6826      * that determination.
6827      *
6828      * Another characteristic we need to know is whether the lhs and rhs are
6829      * identical.  If so, and no other flags are present, the only effect of
6830      * the tr/// is to count the characters present in the input that are
6831      * mentioned in the lhs string.  The implementation of that is easier and
6832      * runs faster than the more general case.  Normalizing here allows for
6833      * accurate determination of this.  Previously there were false negatives
6834      * possible.
6835      *
6836      * Instead of 'transliterated', the comments here use 'unmapped' for the
6837      * characters that are left unchanged by the operation; otherwise they are
6838      * 'mapped'
6839      *
6840      * The lhs of the tr/// is here referred to as the t side.
6841      * The rhs of the tr/// is here referred to as the r side.
6842      */
6843
6844     SV * const tstr = ((SVOP*)expr)->op_sv;
6845     SV * const rstr = ((SVOP*)repl)->op_sv;
6846     STRLEN tlen;
6847     STRLEN rlen;
6848     const U8 * t0 = (U8*)SvPV_const(tstr, tlen);
6849     const U8 * r0 = (U8*)SvPV_const(rstr, rlen);
6850     const U8 * t = t0;
6851     const U8 * r = r0;
6852     UV t_count = 0, r_count = 0;  /* Number of characters in search and
6853                                          replacement lists */
6854
6855     /* khw thinks some of the private flags for this op are quaintly named.
6856      * OPpTRANS_GROWS for example is TRUE if the replacement for some lhs
6857      * character when represented in UTF-8 is longer than the original
6858      * character's UTF-8 representation */
6859     const bool complement = cBOOL(o->op_private & OPpTRANS_COMPLEMENT);
6860     const bool squash     = cBOOL(o->op_private & OPpTRANS_SQUASH);
6861     const bool del        = cBOOL(o->op_private & OPpTRANS_DELETE);
6862
6863     /* Set to true if there is some character < 256 in the lhs that maps to >
6864      * 255.  If so, a non-UTF-8 match string can be forced into requiring to be
6865      * in UTF-8 by a tr/// operation. */
6866     bool can_force_utf8 = FALSE;
6867
6868     /* What is the maximum expansion factor in UTF-8 transliterations.  If a
6869      * 2-byte UTF-8 encoded character is to be replaced by a 3-byte one, its
6870      * expansion factor is 1.5.  This number is used at runtime to calculate
6871      * how much space to allocate for non-inplace transliterations.  Without
6872      * this number, the worst case is 14, which is extremely unlikely to happen
6873      * in real life, and would require significant memory overhead. */
6874     NV max_expansion = 1.;
6875
6876     UV t_range_count, r_range_count, min_range_count;
6877     UV* t_array;
6878     SV* t_invlist;
6879     UV* r_map;
6880     UV r_cp, t_cp;
6881     UV t_cp_end = (UV) -1;
6882     UV r_cp_end;
6883     Size_t len;
6884     AV* invmap;
6885     UV final_map = TR_UNLISTED;    /* The final character in the replacement
6886                                       list, updated as we go along.  Initialize
6887                                       to something illegal */
6888
6889     bool rstr_utf8 = cBOOL(SvUTF8(rstr));
6890     bool tstr_utf8 = cBOOL(SvUTF8(tstr));
6891
6892     const U8* tend = t + tlen;
6893     const U8* rend = r + rlen;
6894
6895     SV * inverted_tstr = NULL;
6896
6897     Size_t i;
6898     unsigned int pass2;
6899
6900     /* This routine implements detection of a transliteration having a longer
6901      * UTF-8 representation than its source, by partitioning all the possible
6902      * code points of the platform into equivalence classes of the same UTF-8
6903      * byte length in the first pass.  As it constructs the mappings, it carves
6904      * these up into smaller chunks, but doesn't merge any together.  This
6905      * makes it easy to find the instances it's looking for.  A second pass is
6906      * done after this has been determined which merges things together to
6907      * shrink the table for runtime.  For ASCII platforms, the table is
6908      * trivial, given below, and uses the fundamental characteristics of UTF-8
6909      * to construct the values.  For EBCDIC, it isn't so, and we rely on a
6910      * table constructed by the perl script that generates these kinds of
6911      * things */
6912 #ifndef EBCDIC
6913     UV PL_partition_by_byte_length[] = {
6914         0,
6915         0x80,
6916         (32 * (1UL << (    UTF_ACCUMULATION_SHIFT))),
6917         (16 * (1UL << (2 * UTF_ACCUMULATION_SHIFT))),
6918         ( 8 * (1UL << (3 * UTF_ACCUMULATION_SHIFT))),
6919         ( 4 * (1UL << (4 * UTF_ACCUMULATION_SHIFT))),
6920         ( 2 * (1UL << (5 * UTF_ACCUMULATION_SHIFT)))
6921
6922 #  ifdef UV_IS_QUAD
6923                                                     ,
6924         ( ((UV) 1U << (6 * UTF_ACCUMULATION_SHIFT)))
6925 #  endif
6926
6927     };
6928
6929 #endif
6930
6931     PERL_ARGS_ASSERT_PMTRANS;
6932
6933     PL_hints |= HINT_BLOCK_SCOPE;
6934
6935     /* If /c, the search list is sorted and complemented.  This is now done by
6936      * creating an inversion list from it, and then trivially inverting that.
6937      * The previous implementation used qsort, but creating the list
6938      * automatically keeps it sorted as we go along */
6939     if (complement) {
6940         UV start, end;
6941         SV * inverted_tlist = _new_invlist(tlen);
6942         Size_t temp_len;
6943
6944         DEBUG_y(PerlIO_printf(Perl_debug_log,
6945                     "%s: %d: tstr before inversion=\n%s\n",
6946                     __FILE__, __LINE__, _byte_dump_string(t, tend - t, 0)));
6947
6948         while (t < tend) {
6949
6950             /* Non-utf8 strings don't have ranges, so each character is listed
6951              * out */
6952             if (! tstr_utf8) {
6953                 inverted_tlist = add_cp_to_invlist(inverted_tlist, *t);
6954                 t++;
6955             }
6956             else {  /* But UTF-8 strings have been parsed in toke.c to have
6957                  * ranges if appropriate. */
6958                 UV t_cp;
6959                 Size_t t_char_len;
6960
6961                 /* Get the first character */
6962                 t_cp = valid_utf8_to_uvchr(t, &t_char_len);
6963                 t += t_char_len;
6964
6965                 /* If the next byte indicates that this wasn't the first
6966                  * element of a range, the range is just this one */
6967                 if (t >= tend || *t != RANGE_INDICATOR) {
6968                     inverted_tlist = add_cp_to_invlist(inverted_tlist, t_cp);
6969                 }
6970                 else { /* Otherwise, ignore the indicator byte, and get the
6971                           final element, and add the whole range */
6972                     t++;
6973                     t_cp_end = valid_utf8_to_uvchr(t, &t_char_len);
6974                     t += t_char_len;
6975
6976                     inverted_tlist = _add_range_to_invlist(inverted_tlist,
6977                                                       t_cp, t_cp_end);
6978                 }
6979             }
6980         } /* End of parse through tstr */
6981
6982         /* The inversion list is done; now invert it */
6983         _invlist_invert(inverted_tlist);
6984
6985         /* Now go through the inverted list and create a new tstr for the rest
6986          * of the routine to use.  Since the UTF-8 version can have ranges, and
6987          * can be much more compact than the non-UTF-8 version, we create the
6988          * string in UTF-8 even if not necessary.  (This is just an intermediate
6989          * value that gets thrown away anyway.) */
6990         invlist_iterinit(inverted_tlist);
6991         inverted_tstr = newSVpvs("");
6992         while (invlist_iternext(inverted_tlist, &start, &end)) {
6993             U8 temp[UTF8_MAXBYTES];
6994             U8 * temp_end_pos;
6995
6996             /* IV_MAX keeps things from going out of bounds */
6997             start = MIN(IV_MAX, start);
6998             end   = MIN(IV_MAX, end);
6999
7000             temp_end_pos = uvchr_to_utf8(temp, start);
7001             sv_catpvn(inverted_tstr, (char *) temp, temp_end_pos - temp);
7002
7003             if (start != end) {
7004                 Perl_sv_catpvf(aTHX_ inverted_tstr, "%c", RANGE_INDICATOR);
7005                 temp_end_pos = uvchr_to_utf8(temp, end);
7006                 sv_catpvn(inverted_tstr, (char *) temp, temp_end_pos - temp);
7007             }
7008         }
7009
7010         /* Set up so the remainder of the routine uses this complement, instead
7011          * of the actual input */
7012         t0 = t = (U8*)SvPV_const(inverted_tstr, temp_len);
7013         tend = t0 + temp_len;
7014         tstr_utf8 = TRUE;
7015
7016         SvREFCNT_dec_NN(inverted_tlist);
7017     }
7018
7019     /* For non-/d, an empty rhs means to use the lhs */
7020     if (rlen == 0 && ! del) {
7021         r0 = t0;
7022         rend = tend;
7023         rstr_utf8  = tstr_utf8;
7024     }
7025
7026     t_invlist = _new_invlist(1);
7027
7028     /* Initialize to a single range */
7029     t_invlist = _add_range_to_invlist(t_invlist, 0, UV_MAX);
7030
7031     /* For the first pass, the lhs is partitioned such that the
7032      * number of UTF-8 bytes required to represent a code point in each
7033      * partition is the same as the number for any other code point in
7034      * that partion.  We copy the pre-compiled partion. */
7035     len = C_ARRAY_LENGTH(PL_partition_by_byte_length);
7036     invlist_extend(t_invlist, len);
7037     t_array = invlist_array(t_invlist);
7038     Copy(PL_partition_by_byte_length, t_array, len, UV);
7039     invlist_set_len(t_invlist, len, *(get_invlist_offset_addr(t_invlist)));
7040     Newx(r_map, len + 1, UV);
7041
7042     /* Parse the (potentially adjusted) input, creating the inversion map.
7043      * This is done in two passes.  The first pass is to determine if the
7044      * transliteration can be done in place.  The inversion map it creates
7045      * could be used, but generally would be larger and slower to run than the
7046      * output of the second pass, which starts with a more compact table and
7047      * allows more ranges to be merged */
7048     for (pass2 = 0; pass2 < 2; pass2++) {
7049         if (pass2) {
7050             /* Initialize to a single range */
7051             t_invlist = _add_range_to_invlist(t_invlist, 0, UV_MAX);
7052
7053             /* In the second pass, we just have the single range */
7054             len = 1;
7055             t_array = invlist_array(t_invlist);
7056         }
7057
7058         /* And the mapping of each of the ranges is initialized.  Initially,
7059          * everything is TR_UNLISTED. */
7060         for (i = 0; i < len; i++) {
7061             r_map[i] = TR_UNLISTED;
7062         }
7063
7064         t = t0;
7065         t_count = 0;
7066         r = r0;
7067         r_count = 0;
7068         t_range_count = r_range_count = 0;
7069
7070         DEBUG_y(PerlIO_printf(Perl_debug_log, "%s: %d:\ntstr=%s\n",
7071                     __FILE__, __LINE__, _byte_dump_string(t, tend - t, 0)));
7072         DEBUG_y(PerlIO_printf(Perl_debug_log, "rstr=%s\n",
7073                                         _byte_dump_string(r, rend - r, 0)));
7074         DEBUG_y(PerlIO_printf(Perl_debug_log, "/c=%d; /s=%d; /d=%d\n",
7075                                                   complement, squash, del));
7076         DEBUG_y(invmap_dump(t_invlist, r_map));
7077
7078         /* Now go through the search list constructing an inversion map.  The
7079          * input is not necessarily in any particular order.  Making it an
7080          * inversion map orders it, potentially simplifying, and makes it easy
7081          * to deal with at run time.  This is the only place in core that
7082          * generates an inversion map; if others were introduced, it might be
7083          * better to create general purpose routines to handle them.
7084          * (Inversion maps are created in perl in other places.)
7085          *
7086          * An inversion map consists of two parallel arrays.  One is
7087          * essentially an inversion list: an ordered list of code points such
7088          * that each element gives the first code point of a range of
7089          * consecutive code points that map to the element in the other array
7090          * that has the same index as this one (in other words, the
7091          * corresponding element).  Thus the range extends up to (but not
7092          * including) the code point given by the next higher element.  In a
7093          * true inversion map, the corresponding element in the other array
7094          * gives the mapping of the first code point in the range, with the
7095          * understanding that the next higher code point in the inversion
7096          * list's range will map to the next higher code point in the map.
7097          *
7098          * So if at element [i], let's say we have:
7099          *
7100          *     t_invlist  r_map
7101          * [i]    A         a
7102          *
7103          * This means that A => a, B => b, C => c....  Let's say that the
7104          * situation is such that:
7105          *
7106          * [i+1]  L        -1
7107          *
7108          * This means the sequence that started at [i] stops at K => k.  This
7109          * illustrates that you need to look at the next element to find where
7110          * a sequence stops.  Except, the highest element in the inversion list
7111          * begins a range that is understood to extend to the platform's
7112          * infinity.
7113          *
7114          * This routine modifies traditional inversion maps to reserve two
7115          * mappings:
7116          *
7117          *  TR_UNLISTED (or -1) indicates that no code point in the range
7118          *      is listed in the tr/// searchlist.  At runtime, these are
7119          *      always passed through unchanged.  In the inversion map, all
7120          *      points in the range are mapped to -1, instead of increasing,
7121          *      like the 'L' in the example above.
7122          *
7123          *      We start the parse with every code point mapped to this, and as
7124          *      we parse and find ones that are listed in the search list, we
7125          *      carve out ranges as we go along that override that.
7126          *
7127          *  TR_SPECIAL_HANDLING (or -2) indicates that every code point in the
7128          *      range needs special handling.  Again, all code points in the
7129          *      range are mapped to -2, instead of increasing.
7130          *
7131          *      Under /d this value means the code point should be deleted from
7132          *      the transliteration when encountered.
7133          *
7134          *      Otherwise, it marks that every code point in the range is to
7135          *      map to the final character in the replacement list.  This
7136          *      happens only when the replacement list is shorter than the
7137          *      search one, so there are things in the search list that have no
7138          *      correspondence in the replacement list.  For example, in
7139          *      tr/a-z/A/, 'A' is the final value, and the inversion map
7140          *      generated for this would be like this:
7141          *          \0  =>  -1
7142          *          a   =>   A
7143          *          b-z =>  -2
7144          *          z+1 =>  -1
7145          *      'A' appears once, then the remainder of the range maps to -2.
7146          *      The use of -2 isn't strictly necessary, as an inversion map is
7147          *      capable of representing this situation, but not nearly so
7148          *      compactly, and this is actually quite commonly encountered.
7149          *      Indeed, the original design of this code used a full inversion
7150          *      map for this.  But things like
7151          *          tr/\0-\x{FFFF}/A/
7152          *      generated huge data structures, slowly, and the execution was
7153          *      also slow.  So the current scheme was implemented.
7154          *
7155          *  So, if the next element in our example is:
7156          *
7157          * [i+2]  Q        q
7158          *
7159          * Then all of L, M, N, O, and P map to TR_UNLISTED.  If the next
7160          * elements are
7161          *
7162          * [i+3]  R        z
7163          * [i+4]  S       TR_UNLISTED
7164          *
7165          * Then Q => q; R => z; and S => TR_UNLISTED.  If [i+4] (the 'S') is
7166          * the final element in the arrays, every code point from S to infinity
7167          * maps to TR_UNLISTED.
7168          *
7169          */
7170                            /* Finish up range started in what otherwise would
7171                             * have been the final iteration */
7172         while (t < tend || t_range_count > 0) {
7173             bool adjacent_to_range_above = FALSE;
7174             bool adjacent_to_range_below = FALSE;
7175
7176             bool merge_with_range_above = FALSE;
7177             bool merge_with_range_below = FALSE;
7178
7179             UV span, invmap_range_length_remaining;
7180             SSize_t j;
7181             Size_t i;
7182
7183             /* If we are in the middle of processing a range in the 'target'
7184              * side, the previous iteration has set us up.  Otherwise, look at
7185              * the next character in the search list */
7186             if (t_range_count <= 0) {
7187                 if (! tstr_utf8) {
7188
7189                     /* Here, not in the middle of a range, and not UTF-8.  The
7190                      * next code point is the single byte where we're at */
7191                     t_cp = *t;
7192                     t_range_count = 1;
7193                     t++;
7194                 }
7195                 else {
7196                     Size_t t_char_len;
7197
7198                     /* Here, not in the middle of a range, and is UTF-8.  The
7199                      * next code point is the next UTF-8 char in the input.  We
7200                      * know the input is valid, because the toker constructed
7201                      * it */
7202                     t_cp = valid_utf8_to_uvchr(t, &t_char_len);
7203                     t += t_char_len;
7204
7205                     /* UTF-8 strings (only) have been parsed in toke.c to have
7206                      * ranges.  See if the next byte indicates that this was
7207                      * the first element of a range.  If so, get the final
7208                      * element and calculate the range size.  If not, the range
7209                      * size is 1 */
7210                     if (t < tend && *t == RANGE_INDICATOR) {
7211                         t++;
7212                         t_range_count = valid_utf8_to_uvchr(t, &t_char_len)
7213                                       - t_cp + 1;
7214                         t += t_char_len;
7215                     }
7216                     else {
7217                         t_range_count = 1;
7218                     }
7219                 }
7220
7221                 /* Count the total number of listed code points * */
7222                 t_count += t_range_count;
7223             }
7224
7225             /* Similarly, get the next character in the replacement list */
7226             if (r_range_count <= 0) {
7227                 if (r >= rend) {
7228
7229                     /* But if we've exhausted the rhs, there is nothing to map
7230                      * to, except the special handling one, and we make the
7231                      * range the same size as the lhs one. */
7232                     r_cp = TR_SPECIAL_HANDLING;
7233                     r_range_count = t_range_count;
7234
7235                     if (! del) {
7236                         DEBUG_yv(PerlIO_printf(Perl_debug_log,
7237                                         "final_map =%" UVXf "\n", final_map));
7238                     }
7239                 }
7240                 else {
7241                     if (! rstr_utf8) {
7242                         r_cp = *r;
7243                         r_range_count = 1;
7244                         r++;
7245                     }
7246                     else {
7247                         Size_t r_char_len;
7248
7249                         r_cp = valid_utf8_to_uvchr(r, &r_char_len);
7250                         r += r_char_len;
7251                         if (r < rend && *r == RANGE_INDICATOR) {
7252                             r++;
7253                             r_range_count = valid_utf8_to_uvchr(r,
7254                                                     &r_char_len) - r_cp + 1;
7255                             r += r_char_len;
7256                         }
7257                         else {
7258                             r_range_count = 1;
7259                         }
7260                     }
7261
7262                     if (r_cp == TR_SPECIAL_HANDLING) {
7263                         r_range_count = t_range_count;
7264                     }
7265
7266                     /* This is the final character so far */
7267                     final_map = r_cp + r_range_count - 1;
7268
7269                     r_count += r_range_count;
7270                 }
7271             }
7272
7273             /* Here, we have the next things ready in both sides.  They are
7274              * potentially ranges.  We try to process as big a chunk as
7275              * possible at once, but the lhs and rhs must be synchronized, so
7276              * things like tr/A-Z/a-ij-z/ will need to be processed in 2 chunks
7277              * */
7278             min_range_count = MIN(t_range_count, r_range_count);
7279
7280             /* Search the inversion list for the entry that contains the input
7281              * code point <cp>.  The inversion map was initialized to cover the
7282              * entire range of possible inputs, so this should not fail.  So
7283              * the return value is the index into the list's array of the range
7284              * that contains <cp>, that is, 'i' such that array[i] <= cp <
7285              * array[i+1] */
7286             j = _invlist_search(t_invlist, t_cp);
7287             assert(j >= 0);
7288             i = j;
7289
7290             /* Here, the data structure might look like:
7291              *
7292              * index    t   r     Meaning
7293              * [i-1]    J   j   # J-L => j-l
7294              * [i]      M  -1   # M => default; as do N, O, P, Q
7295              * [i+1]    R   x   # R => x, S => x+1, T => x+2
7296              * [i+2]    U   y   # U => y, V => y+1, ...
7297              * ...
7298              * [-1]     Z  -1   # Z => default; as do Z+1, ... infinity
7299              *
7300              * where 'x' and 'y' above are not to be taken literally.
7301              *
7302              * The maximum chunk we can handle in this loop iteration, is the
7303              * smallest of the three components: the lhs 't_', the rhs 'r_',
7304              * and the remainder of the range in element [i].  (In pass 1, that
7305              * range will have everything in it be of the same class; we can't
7306              * cross into another class.)  'min_range_count' already contains
7307              * the smallest of the first two values.  The final one is
7308              * irrelevant if the map is to the special indicator */
7309
7310             invmap_range_length_remaining = (i + 1 < len)
7311                                             ? t_array[i+1] - t_cp
7312                                             : IV_MAX - t_cp;
7313             span = MAX(1, MIN(min_range_count, invmap_range_length_remaining));
7314
7315             /* The end point of this chunk is where we are, plus the span, but
7316              * never larger than the platform's infinity */
7317             t_cp_end = MIN(IV_MAX, t_cp + span - 1);
7318
7319             if (r_cp == TR_SPECIAL_HANDLING) {
7320                 r_cp_end = TR_SPECIAL_HANDLING;
7321             }
7322             else {
7323                 r_cp_end = MIN(IV_MAX, r_cp + span - 1);
7324
7325                 /* If something on the lhs is below 256, and something on the
7326                  * rhs is above, there is a potential mapping here across that
7327                  * boundary.  Indeed the only way there isn't is if both sides
7328                  * start at the same point.  That means they both cross at the
7329                  * same time.  But otherwise one crosses before the other */
7330                 if (t_cp < 256 && r_cp_end > 255 && r_cp != t_cp) {
7331                     can_force_utf8 = TRUE;
7332                 }
7333             }
7334
7335             /* If a character appears in the search list more than once, the
7336              * 2nd and succeeding occurrences are ignored, so only do this
7337              * range if haven't already processed this character.  (The range
7338              * has been set up so that all members in it will be of the same
7339              * ilk) */
7340             if (r_map[i] == TR_UNLISTED) {
7341                 DEBUG_yv(PerlIO_printf(Perl_debug_log,
7342                     "Processing %" UVxf "-%" UVxf " => %" UVxf "-%" UVxf "\n",
7343                     t_cp, t_cp_end, r_cp, r_cp_end));
7344
7345                 /* This is the first definition for this chunk, hence is valid
7346                  * and needs to be processed.  Here and in the comments below,
7347                  * we use the above sample data.  The t_cp chunk must be any
7348                  * contiguous subset of M, N, O, P, and/or Q.
7349                  *
7350                  * In the first pass, the t_invlist has been partitioned so
7351                  * that all elements in any single range have the same number
7352                  * of bytes in their UTF-8 representations.  And the r space is
7353                  * either a single byte, or a range of strictly monotonically
7354                  * increasing code points.  So the final element in the range
7355                  * will be represented by no fewer bytes than the initial one.
7356                  * That means that if the final code point in the t range has
7357                  * at least as many bytes as the final code point in the r,
7358                  * then all code points in the t range have at least as many
7359                  * bytes as their corresponding r range element.  But if that's
7360                  * not true, the transliteration of at least the final code
7361                  * point grows in length.  As an example, suppose we had
7362                  *      tr/\x{fff0}-\x{fff1}/\x{ffff}-\x{10000}/
7363                  * The UTF-8 for all but 10000 occupies 3 bytes on ASCII
7364                  * platforms.  We have deliberately set up the data structure
7365                  * so that any range in the lhs gets split into chunks for
7366                  * processing, such that every code point in a chunk has the
7367                  * same number of UTF-8 bytes.  We only have to check the final
7368                  * code point in the rhs against any code point in the lhs. */
7369                 if ( ! pass2
7370                     && r_cp_end != TR_SPECIAL_HANDLING
7371                     && UVCHR_SKIP(t_cp_end) < UVCHR_SKIP(r_cp_end))
7372                 {
7373                     /* Consider tr/\xCB/\X{E000}/.  The maximum expansion
7374                      * factor is 1 byte going to 3 if the lhs is not UTF-8, but
7375                      * 2 bytes going to 3 if it is in UTF-8.  We could pass two
7376                      * different values so doop could choose based on the
7377                      * UTF-8ness of the target.  But khw thinks (perhaps
7378                      * wrongly) that is overkill.  It is used only to make sure
7379                      * we malloc enough space.  If no target string can force
7380                      * the result to be UTF-8, then we don't have to worry
7381                      * about this */
7382                     NV t_size = (can_force_utf8 && t_cp < 256)
7383                                 ? 1
7384                                 : UVCHR_SKIP(t_cp_end);
7385                     NV ratio = UVCHR_SKIP(r_cp_end) / t_size;
7386
7387                     o->op_private |= OPpTRANS_GROWS;
7388
7389                     /* Now that we know it grows, we can keep track of the
7390                      * largest ratio */
7391                     if (ratio > max_expansion) {
7392                         max_expansion = ratio;
7393                         DEBUG_y(PerlIO_printf(Perl_debug_log,
7394                                         "New expansion factor: %" NVgf "\n",
7395                                         max_expansion));
7396                     }
7397                 }
7398
7399                 /* The very first range is marked as adjacent to the
7400                  * non-existent range below it, as it causes things to "just
7401                  * work" (TradeMark)
7402                  *
7403                  * If the lowest code point in this chunk is M, it adjoins the
7404                  * J-L range */
7405                 if (t_cp == t_array[i]) {
7406                     adjacent_to_range_below = TRUE;
7407
7408                     /* And if the map has the same offset from the beginning of
7409                      * the range as does this new code point (or both are for
7410                      * TR_SPECIAL_HANDLING), this chunk can be completely
7411                      * merged with the range below.  EXCEPT, in the first pass,
7412                      * we don't merge ranges whose UTF-8 byte representations
7413                      * have different lengths, so that we can more easily
7414                      * detect if a replacement is longer than the source, that
7415                      * is if it 'grows'.  But in the 2nd pass, there's no
7416                      * reason to not merge */
7417                     if (   (i > 0 && (   pass2
7418                                       || UVCHR_SKIP(t_array[i-1])
7419                                                         == UVCHR_SKIP(t_cp)))
7420                         && (   (   r_cp == TR_SPECIAL_HANDLING
7421                                 && r_map[i-1] == TR_SPECIAL_HANDLING)
7422                             || (   r_cp != TR_SPECIAL_HANDLING
7423                                 && r_cp - r_map[i-1] == t_cp - t_array[i-1])))
7424                     {
7425                         merge_with_range_below = TRUE;
7426                     }
7427                 }
7428
7429                 /* Similarly, if the highest code point in this chunk is 'Q',
7430                  * it adjoins the range above, and if the map is suitable, can
7431                  * be merged with it */
7432                 if (    t_cp_end >= IV_MAX - 1
7433                     || (   i + 1 < len
7434                         && t_cp_end + 1 == t_array[i+1]))
7435                 {
7436                     adjacent_to_range_above = TRUE;
7437                     if (i + 1 < len)
7438                     if (    (   pass2
7439                              || UVCHR_SKIP(t_cp) == UVCHR_SKIP(t_array[i+1]))
7440                         && (   (   r_cp == TR_SPECIAL_HANDLING
7441                                 && r_map[i+1] == (UV) TR_SPECIAL_HANDLING)
7442                             || (   r_cp != TR_SPECIAL_HANDLING
7443                                 && r_cp_end == r_map[i+1] - 1)))
7444                     {
7445                         merge_with_range_above = TRUE;
7446                     }
7447                 }
7448
7449                 if (merge_with_range_below && merge_with_range_above) {
7450
7451                     /* Here the new chunk looks like M => m, ... Q => q; and
7452                      * the range above is like R => r, ....  Thus, the [i-1]
7453                      * and [i+1] ranges should be seamlessly melded so the
7454                      * result looks like
7455                      *
7456                      * [i-1]    J   j   # J-T => j-t
7457                      * [i]      U   y   # U => y, V => y+1, ...
7458                      * ...
7459                      * [-1]     Z  -1   # Z => default; as do Z+1, ... infinity
7460                      */
7461                     Move(t_array + i + 2, t_array + i, len - i - 2, UV);
7462                     Move(r_map   + i + 2, r_map   + i, len - i - 2, UV);
7463                     len -= 2;
7464                     invlist_set_len(t_invlist,
7465                                     len,
7466                                     *(get_invlist_offset_addr(t_invlist)));
7467                 }
7468                 else if (merge_with_range_below) {
7469
7470                     /* Here the new chunk looks like M => m, .... But either
7471                      * (or both) it doesn't extend all the way up through Q; or
7472                      * the range above doesn't start with R => r. */
7473                     if (! adjacent_to_range_above) {
7474
7475                         /* In the first case, let's say the new chunk extends
7476                          * through O.  We then want:
7477                          *
7478                          * [i-1]    J   j   # J-O => j-o
7479                          * [i]      P  -1   # P => -1, Q => -1
7480                          * [i+1]    R   x   # R => x, S => x+1, T => x+2
7481                          * [i+2]    U   y   # U => y, V => y+1, ...
7482                          * ...
7483                          * [-1]     Z  -1   # Z => default; as do Z+1, ...
7484                          *                                            infinity
7485                          */
7486                         t_array[i] = t_cp_end + 1;
7487                         r_map[i] = TR_UNLISTED;
7488                     }
7489                     else { /* Adjoins the range above, but can't merge with it
7490                               (because 'x' is not the next map after q) */
7491                         /*
7492                          * [i-1]    J   j   # J-Q => j-q
7493                          * [i]      R   x   # R => x, S => x+1, T => x+2
7494                          * [i+1]    U   y   # U => y, V => y+1, ...
7495                          * ...
7496                          * [-1]     Z  -1   # Z => default; as do Z+1, ...
7497                          *                                          infinity
7498                          */
7499
7500                         Move(t_array + i + 1, t_array + i, len - i - 1, UV);
7501                         Move(r_map + i + 1, r_map + i, len - i - 1, UV);
7502                         len--;
7503                         invlist_set_len(t_invlist, len,
7504                                         *(get_invlist_offset_addr(t_invlist)));
7505                     }
7506                 }
7507                 else if (merge_with_range_above) {
7508
7509                     /* Here the new chunk ends with Q => q, and the range above
7510                      * must start with R => r, so the two can be merged. But
7511                      * either (or both) the new chunk doesn't extend all the
7512                      * way down to M; or the mapping of the final code point
7513                      * range below isn't m */
7514                     if (! adjacent_to_range_below) {
7515
7516                         /* In the first case, let's assume the new chunk starts
7517                          * with P => p.  Then, because it's merge-able with the
7518                          * range above, that range must be R => r.  We want:
7519                          *
7520                          * [i-1]    J   j   # J-L => j-l
7521                          * [i]      M  -1   # M => -1, N => -1
7522                          * [i+1]    P   p   # P-T => p-t
7523                          * [i+2]    U   y   # U => y, V => y+1, ...
7524                          * ...
7525                          * [-1]     Z  -1   # Z => default; as do Z+1, ...
7526                          *                                          infinity
7527                          */
7528                         t_array[i+1] = t_cp;
7529                         r_map[i+1] = r_cp;
7530                     }
7531                     else { /* Adjoins the range below, but can't merge with it
7532                             */
7533                         /*
7534                          * [i-1]    J   j   # J-L => j-l
7535                          * [i]      M   x   # M-T => x-5 .. x+2
7536                          * [i+1]    U   y   # U => y, V => y+1, ...
7537                          * ...
7538                          * [-1]     Z  -1   # Z => default; as do Z+1, ...
7539                          *                                          infinity
7540                          */
7541                         Move(t_array + i + 1, t_array + i, len - i - 1, UV);
7542                         Move(r_map   + i + 1, r_map   + i, len - i - 1, UV);
7543                         len--;
7544                         t_array[i] = t_cp;
7545                         r_map[i] = r_cp;
7546                         invlist_set_len(t_invlist, len,
7547                                         *(get_invlist_offset_addr(t_invlist)));
7548                     }
7549                 }
7550                 else if (adjacent_to_range_below && adjacent_to_range_above) {
7551                     /* The new chunk completely fills the gap between the
7552                      * ranges on either side, but can't merge with either of
7553                      * them.
7554                      *
7555                      * [i-1]    J   j   # J-L => j-l
7556                      * [i]      M   z   # M => z, N => z+1 ... Q => z+4
7557                      * [i+1]    R   x   # R => x, S => x+1, T => x+2
7558                      * [i+2]    U   y   # U => y, V => y+1, ...
7559                      * ...
7560                      * [-1]     Z  -1   # Z => default; as do Z+1, ... infinity
7561                      */
7562                     r_map[i] = r_cp;
7563                 }
7564                 else if (adjacent_to_range_below) {
7565                     /* The new chunk adjoins the range below, but not the range
7566                      * above, and can't merge.  Let's assume the chunk ends at
7567                      * O.
7568                      *
7569                      * [i-1]    J   j   # J-L => j-l
7570                      * [i]      M   z   # M => z, N => z+1, O => z+2
7571                      * [i+1]    P   -1  # P => -1, Q => -1
7572                      * [i+2]    R   x   # R => x, S => x+1, T => x+2
7573                      * [i+3]    U   y   # U => y, V => y+1, ...
7574                      * ...
7575                      * [-w]     Z  -1   # Z => default; as do Z+1, ... infinity
7576                      */
7577                     invlist_extend(t_invlist, len + 1);
7578                     t_array = invlist_array(t_invlist);
7579                     Renew(r_map, len + 1, UV);
7580
7581                     Move(t_array + i + 1, t_array + i + 2, len - i - 1, UV);
7582                     Move(r_map + i + 1,   r_map   + i + 2, len - i - 1, UV);
7583                     r_map[i] = r_cp;
7584                     t_array[i+1] = t_cp_end + 1;
7585                     r_map[i+1] = TR_UNLISTED;
7586                     len++;
7587                     invlist_set_len(t_invlist, len,
7588                                     *(get_invlist_offset_addr(t_invlist)));
7589                 }
7590                 else if (adjacent_to_range_above) {
7591                     /* The new chunk adjoins the range above, but not the range
7592                      * below, and can't merge.  Let's assume the new chunk
7593                      * starts at O
7594                      *
7595                      * [i-1]    J   j   # J-L => j-l
7596                      * [i]      M  -1   # M => default, N => default
7597                      * [i+1]    O   z   # O => z, P => z+1, Q => z+2
7598                      * [i+2]    R   x   # R => x, S => x+1, T => x+2
7599                      * [i+3]    U   y   # U => y, V => y+1, ...
7600                      * ...
7601                      * [-1]     Z  -1   # Z => default; as do Z+1, ... infinity
7602                      */
7603                     invlist_extend(t_invlist, len + 1);
7604                     t_array = invlist_array(t_invlist);
7605                     Renew(r_map, len + 1, UV);
7606
7607                     Move(t_array + i + 1, t_array + i + 2, len - i - 1, UV);
7608                     Move(r_map   + i + 1, r_map   + i + 2, len - i - 1, UV);
7609                     t_array[i+1] = t_cp;
7610                     r_map[i+1] = r_cp;
7611                     len++;
7612                     invlist_set_len(t_invlist, len,
7613                                     *(get_invlist_offset_addr(t_invlist)));
7614                 }
7615                 else {
7616                     /* The new chunk adjoins neither the range above, nor the
7617                      * range below.  Lets assume it is N..P => n..p
7618                      *
7619                      * [i-1]    J   j   # J-L => j-l
7620                      * [i]      M  -1   # M => default
7621                      * [i+1]    N   n   # N..P => n..p
7622                      * [i+2]    Q  -1   # Q => default
7623                      * [i+3]    R   x   # R => x, S => x+1, T => x+2
7624                      * [i+4]    U   y   # U => y, V => y+1, ...
7625                      * ...
7626                      * [-1]     Z  -1   # Z => default; as do Z+1, ... infinity
7627                      */
7628
7629                     DEBUG_yv(PerlIO_printf(Perl_debug_log,
7630                                         "Before fixing up: len=%d, i=%d\n",
7631                                         (int) len, (int) i));
7632                     DEBUG_yv(invmap_dump(t_invlist, r_map));
7633
7634                     invlist_extend(t_invlist, len + 2);
7635                     t_array = invlist_array(t_invlist);
7636                     Renew(r_map, len + 2, UV);
7637
7638                     Move(t_array + i + 1,
7639                          t_array + i + 2 + 1, len - i - (2 - 1), UV);
7640                     Move(r_map   + i + 1,
7641                          r_map   + i + 2 + 1, len - i - (2 - 1), UV);
7642
7643                     len += 2;
7644                     invlist_set_len(t_invlist, len,
7645                                     *(get_invlist_offset_addr(t_invlist)));
7646
7647                     t_array[i+1] = t_cp;
7648                     r_map[i+1] = r_cp;
7649
7650                     t_array[i+2] = t_cp_end + 1;
7651                     r_map[i+2] = TR_UNLISTED;
7652                 }
7653                 DEBUG_yv(PerlIO_printf(Perl_debug_log,
7654                           "After iteration: span=%" UVuf ", t_range_count=%"
7655                           UVuf " r_range_count=%" UVuf "\n",
7656                           span, t_range_count, r_range_count));
7657                 DEBUG_yv(invmap_dump(t_invlist, r_map));
7658             } /* End of this chunk needs to be processed */
7659
7660             /* Done with this chunk. */
7661             t_cp += span;
7662             if (t_cp >= IV_MAX) {
7663                 break;
7664             }
7665             t_range_count -= span;
7666             if (r_cp != TR_SPECIAL_HANDLING) {
7667                 r_cp += span;
7668                 r_range_count -= span;
7669             }
7670             else {
7671                 r_range_count = 0;
7672             }
7673
7674         } /* End of loop through the search list */
7675
7676         /* We don't need an exact count, but we do need to know if there is
7677          * anything left over in the replacement list.  So, just assume it's
7678          * one byte per character */
7679         if (rend > r) {
7680             r_count++;
7681         }
7682     } /* End of passes */
7683
7684     SvREFCNT_dec(inverted_tstr);
7685
7686     DEBUG_y(PerlIO_printf(Perl_debug_log, "After everything: \n"));
7687     DEBUG_y(invmap_dump(t_invlist, r_map));
7688
7689     /* We now have normalized the input into an inversion map.
7690      *
7691      * See if the lhs and rhs are equivalent.  If so, this tr/// is a no-op
7692      * except for the count, and streamlined runtime code can be used */
7693     if (!del && !squash) {
7694
7695         /* They are identical if they point to same address, or if everything
7696          * maps to UNLISTED or to itself.  This catches things that not looking
7697          * at the normalized inversion map doesn't catch, like tr/aa/ab/ or
7698          * tr/\x{100}-\x{104}/\x{100}-\x{102}\x{103}-\x{104}  */
7699         if (r0 != t0) {
7700             for (i = 0; i < len; i++) {
7701                 if (r_map[i] != TR_UNLISTED && r_map[i] != t_array[i]) {
7702                     goto done_identical_check;
7703                 }
7704             }
7705         }
7706
7707         /* Here have gone through entire list, and didn't find any
7708          * non-identical mappings */
7709         o->op_private |= OPpTRANS_IDENTICAL;
7710
7711       done_identical_check: ;
7712     }
7713
7714     t_array = invlist_array(t_invlist);
7715
7716     /* If has components above 255, we generally need to use the inversion map
7717      * implementation */
7718     if (   can_force_utf8
7719         || (   len > 0
7720             && t_array[len-1] > 255
7721                  /* If the final range is 0x100-INFINITY and is a special
7722                   * mapping, the table implementation can handle it */
7723             && ! (   t_array[len-1] == 256
7724                   && (   r_map[len-1] == TR_UNLISTED
7725                       || r_map[len-1] == TR_SPECIAL_HANDLING))))
7726     {
7727         SV* r_map_sv;
7728
7729         /* A UTF-8 op is generated, indicated by this flag.  This op is an
7730          * sv_op */
7731         o->op_private |= OPpTRANS_USE_SVOP;
7732
7733         if (can_force_utf8) {
7734             o->op_private |= OPpTRANS_CAN_FORCE_UTF8;
7735         }
7736
7737         /* The inversion map is pushed; first the list. */
7738         invmap = MUTABLE_AV(newAV());
7739         av_push(invmap, t_invlist);
7740
7741         /* 2nd is the mapping */
7742         r_map_sv = newSVpvn((char *) r_map, len * sizeof(UV));
7743         av_push(invmap, r_map_sv);
7744
7745         /* 3rd is the max possible expansion factor */
7746         av_push(invmap, newSVnv(max_expansion));
7747
7748         /* Characters that are in the search list, but not in the replacement
7749          * list are mapped to the final character in the replacement list */
7750         if (! del && r_count < t_count) {
7751             av_push(invmap, newSVuv(final_map));
7752         }
7753
7754 #ifdef USE_ITHREADS
7755         cPADOPo->op_padix = pad_alloc(OP_TRANS, SVf_READONLY);
7756         SvREFCNT_dec(PAD_SVl(cPADOPo->op_padix));
7757         PAD_SETSV(cPADOPo->op_padix, (SV *) invmap);
7758         SvPADTMP_on(invmap);
7759         SvREADONLY_on(invmap);
7760 #else
7761         cSVOPo->op_sv = (SV *) invmap;
7762 #endif
7763
7764     }
7765     else {
7766         OPtrans_map *tbl;
7767         unsigned short i;
7768
7769         /* The OPtrans_map struct already contains one slot; hence the -1. */
7770         SSize_t struct_size = sizeof(OPtrans_map)
7771                             + (256 - 1 + 1)*sizeof(short);
7772
7773         /* Non-utf8 case: set o->op_pv to point to a simple 256+ entry lookup
7774         * table. Entries with the value TR_UNMAPPED indicate chars not to be
7775         * translated, while TR_DELETE indicates a search char without a
7776         * corresponding replacement char under /d.
7777         *
7778         * In addition, an extra slot at the end is used to store the final
7779         * repeating char, or TR_R_EMPTY under an empty replacement list, or
7780         * TR_DELETE under /d; which makes the runtime code easier.
7781         */
7782
7783         /* Indicate this is an op_pv */
7784         o->op_private &= ~OPpTRANS_USE_SVOP;
7785
7786         tbl = (OPtrans_map*)PerlMemShared_calloc(struct_size, 1);
7787         tbl->size = 256;
7788         cPVOPo->op_pv = (char*)tbl;
7789
7790         for (i = 0; i < len; i++) {
7791             STATIC_ASSERT_DECL(TR_SPECIAL_HANDLING == TR_DELETE);
7792             short upper = i >= len - 1 ? 256 : (short) t_array[i+1];
7793             short to = (short) r_map[i];
7794             short j;
7795             bool do_increment = TRUE;
7796
7797             /* Any code points above our limit should be irrelevant */
7798             if (t_array[i] >= tbl->size) break;
7799
7800             /* Set up the map */
7801             if (to == (short) TR_SPECIAL_HANDLING && ! del) {
7802                 to = (short) final_map;
7803                 do_increment = FALSE;
7804             }
7805             else if (to < 0) {
7806                 do_increment = FALSE;
7807             }
7808
7809             /* Create a map for everything in this range.  The value increases
7810              * except for the special cases */
7811             for (j = (short) t_array[i]; j < upper; j++) {
7812                 tbl->map[j] = to;
7813                 if (do_increment) to++;
7814             }
7815         }
7816
7817         tbl->map[tbl->size] = del
7818                               ? (short) TR_DELETE
7819                               : (short) rlen
7820                                 ? (short) final_map
7821                                 : (short) TR_R_EMPTY;
7822         DEBUG_y(PerlIO_printf(Perl_debug_log,"%s: %d\n", __FILE__, __LINE__));
7823         for (i = 0; i < tbl->size; i++) {
7824             if (tbl->map[i] < 0) {
7825                 DEBUG_y(PerlIO_printf(Perl_debug_log," %02x=>%d",
7826                                                 (unsigned) i, tbl->map[i]));
7827             }
7828             else {
7829                 DEBUG_y(PerlIO_printf(Perl_debug_log," %02x=>%02x",
7830                                                 (unsigned) i, tbl->map[i]));
7831             }
7832             if ((i+1) % 8 == 0 || i + 1 == (short) tbl->size) {
7833                 DEBUG_y(PerlIO_printf(Perl_debug_log,"\n"));
7834             }
7835         }
7836         DEBUG_y(PerlIO_printf(Perl_debug_log,"Final map 0x%x=>%02x\n",
7837                                 (unsigned) tbl->size, tbl->map[tbl->size]));
7838
7839         SvREFCNT_dec(t_invlist);
7840
7841 #if 0   /* code that added excess above-255 chars at the end of the table, in
7842            case we ever want to not use the inversion map implementation for
7843            this */
7844
7845         ASSUME(j <= rlen);
7846         excess = rlen - j;
7847
7848         if (excess) {
7849             /* More replacement chars than search chars:
7850              * store excess replacement chars at end of main table.
7851              */
7852
7853             struct_size += excess;
7854             tbl = (OPtrans_map*)PerlMemShared_realloc(tbl,
7855                         struct_size + excess * sizeof(short));
7856             tbl->size += excess;
7857             cPVOPo->op_pv = (char*)tbl;
7858
7859             for (i = 0; i < excess; i++)
7860                 tbl->map[i + 256] = r[j+i];
7861         }
7862         else {
7863             /* no more replacement chars than search chars */
7864         }
7865 #endif
7866
7867     }
7868
7869     DEBUG_y(PerlIO_printf(Perl_debug_log,
7870             "/d=%d, /s=%d, /c=%d, identical=%d, grows=%d,"
7871             " use_svop=%d, can_force_utf8=%d,\nexpansion=%" NVgf "\n",
7872             del, squash, complement,
7873             cBOOL(o->op_private & OPpTRANS_IDENTICAL),
7874             cBOOL(o->op_private & OPpTRANS_USE_SVOP),
7875             cBOOL(o->op_private & OPpTRANS_GROWS),
7876             cBOOL(o->op_private & OPpTRANS_CAN_FORCE_UTF8),
7877             max_expansion));
7878
7879     Safefree(r_map);
7880
7881     if(del && rlen != 0 && r_count == t_count) {
7882         Perl_ck_warner(aTHX_ packWARN(WARN_MISC), "Useless use of /d modifier in transliteration operator");
7883     } else if(r_count > t_count) {
7884         Perl_ck_warner(aTHX_ packWARN(WARN_MISC), "Replacement list is longer than search list");
7885     }
7886
7887     op_free(expr);
7888     op_free(repl);
7889
7890     return o;
7891 }
7892
7893
7894 /*
7895 =for apidoc newPMOP
7896
7897 Constructs, checks, and returns an op of any pattern matching type.
7898 C<type> is the opcode.  C<flags> gives the eight bits of C<op_flags>
7899 and, shifted up eight bits, the eight bits of C<op_private>.
7900
7901 =cut
7902 */
7903
7904 OP *
7905 Perl_newPMOP(pTHX_ I32 type, I32 flags)
7906 {
7907     dVAR;
7908     PMOP *pmop;
7909
7910     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_PMOP
7911         || type == OP_CUSTOM);
7912
7913     NewOp(1101, pmop, 1, PMOP);
7914     OpTYPE_set(pmop, type);
7915     pmop->op_flags = (U8)flags;
7916     pmop->op_private = (U8)(0 | (flags >> 8));
7917     if (PL_opargs[type] & OA_RETSCALAR)
7918         scalar((OP *)pmop);
7919
7920     if (PL_hints & HINT_RE_TAINT)
7921         pmop->op_pmflags |= PMf_RETAINT;
7922 #ifdef USE_LOCALE_CTYPE
7923     if (IN_LC_COMPILETIME(LC_CTYPE)) {
7924         set_regex_charset(&(pmop->op_pmflags), REGEX_LOCALE_CHARSET);
7925     }
7926     else
7927 #endif
7928          if (IN_UNI_8_BIT) {
7929         set_regex_charset(&(pmop->op_pmflags), REGEX_UNICODE_CHARSET);
7930     }
7931     if (PL_hints & HINT_RE_FLAGS) {
7932         SV *reflags = Perl_refcounted_he_fetch_pvn(aTHX_
7933          PL_compiling.cop_hints_hash, STR_WITH_LEN("reflags"), 0, 0
7934         );
7935         if (reflags && SvOK(reflags)) pmop->op_pmflags |= SvIV(reflags);
7936         reflags = Perl_refcounted_he_fetch_pvn(aTHX_
7937          PL_compiling.cop_hints_hash, STR_WITH_LEN("reflags_charset"), 0, 0
7938         );
7939         if (reflags && SvOK(reflags)) {
7940             set_regex_charset(&(pmop->op_pmflags), (regex_charset)SvIV(reflags));
7941         }
7942     }
7943
7944
7945 #ifdef USE_ITHREADS
7946     assert(SvPOK(PL_regex_pad[0]));
7947     if (SvCUR(PL_regex_pad[0])) {
7948         /* Pop off the "packed" IV from the end.  */
7949         SV *const repointer_list = PL_regex_pad[0];
7950         const char *p = SvEND(repointer_list) - sizeof(IV);
7951         const IV offset = *((IV*)p);
7952
7953         assert(SvCUR(repointer_list) % sizeof(IV) == 0);
7954
7955         SvEND_set(repointer_list, p);
7956
7957         pmop->op_pmoffset = offset;
7958         /* This slot should be free, so assert this:  */
7959         assert(PL_regex_pad[offset] == &PL_sv_undef);
7960     } else {
7961         SV * const repointer = &PL_sv_undef;
7962         av_push(PL_regex_padav, repointer);
7963         pmop->op_pmoffset = av_tindex(PL_regex_padav);
7964         PL_regex_pad = AvARRAY(PL_regex_padav);
7965     }
7966 #endif
7967
7968     return CHECKOP(type, pmop);
7969 }
7970
7971 static void
7972 S_set_haseval(pTHX)
7973 {
7974     PADOFFSET i = 1;
7975     PL_cv_has_eval = 1;
7976     /* Any pad names in scope are potentially lvalues.  */
7977     for (; i < PadnamelistMAXNAMED(PL_comppad_name); i++) {
7978         PADNAME *pn = PAD_COMPNAME_SV(i);
7979         if (!pn || !PadnameLEN(pn))
7980             continue;
7981         if (PadnameOUTER(pn) || PadnameIN_SCOPE(pn, PL_cop_seqmax))
7982             S_mark_padname_lvalue(aTHX_ pn);
7983     }
7984 }
7985
7986 /* Given some sort of match op o, and an expression expr containing a
7987  * pattern, either compile expr into a regex and attach it to o (if it's
7988  * constant), or convert expr into a runtime regcomp op sequence (if it's
7989  * not)
7990  *
7991  * Flags currently has 2 bits of meaning:
7992  * 1: isreg indicates that the pattern is part of a regex construct, eg
7993  *      $x =~ /pattern/ or split /pattern/, as opposed to $x =~ $pattern or
7994  *      split "pattern", which aren't. In the former case, expr will be a list
7995  *      if the pattern contains more than one term (eg /a$b/).
7996  * 2: The pattern is for a split.
7997  *
7998  * When the pattern has been compiled within a new anon CV (for
7999  * qr/(?{...})/ ), then floor indicates the savestack level just before
8000  * the new sub was created
8001  *
8002  * tr/// is also handled.
8003  */
8004
8005 OP *
8006 Perl_pmruntime(pTHX_ OP *o, OP *expr, OP *repl, UV flags, I32 floor)
8007 {
8008     PMOP *pm;
8009     LOGOP *rcop;
8010     I32 repl_has_vars = 0;
8011     bool is_trans = (o->op_type == OP_TRANS || o->op_type == OP_TRANSR);
8012     bool is_compiletime;
8013     bool has_code;
8014     bool isreg    = cBOOL(flags & 1);
8015     bool is_split = cBOOL(flags & 2);
8016
8017     PERL_ARGS_ASSERT_PMRUNTIME;
8018
8019     if (is_trans) {
8020         return pmtrans(o, expr, repl);
8021     }
8022
8023     /* find whether we have any runtime or code elements;
8024      * at the same time, temporarily set the op_next of each DO block;
8025      * then when we LINKLIST, this will cause the DO blocks to be excluded
8026      * from the op_next chain (and from having LINKLIST recursively
8027      * applied to them). We fix up the DOs specially later */
8028
8029     is_compiletime = 1;
8030     has_code = 0;
8031     if (expr->op_type == OP_LIST) {
8032         OP *child;
8033         for (child = cLISTOPx(expr)->op_first; child; child = OpSIBLING(child)) {
8034             if (child->op_type == OP_NULL && (child->op_flags & OPf_SPECIAL)) {
8035                 has_code = 1;
8036                 assert(!child->op_next);
8037                 if (UNLIKELY(!OpHAS_SIBLING(child))) {
8038                     assert(PL_parser && PL_parser->error_count);
8039                     /* This can happen with qr/ (?{(^{})/.  Just fake up
8040                        the op we were expecting to see, to avoid crashing
8041                        elsewhere.  */
8042                     op_sibling_splice(expr, child, 0,
8043                               newSVOP(OP_CONST, 0, &PL_sv_no));
8044                 }
8045                 child->op_next = OpSIBLING(child);
8046             }
8047             else if (child->op_type != OP_CONST && child->op_type != OP_PUSHMARK)
8048             is_compiletime = 0;
8049         }
8050     }
8051     else if (expr->op_type != OP_CONST)
8052         is_compiletime = 0;
8053
8054     LINKLIST(expr);
8055
8056     /* fix up DO blocks; treat each one as a separate little sub;
8057      * also, mark any arrays as LIST/REF */
8058
8059     if (expr->op_type == OP_LIST) {
8060         OP *child;
8061         for (child = cLISTOPx(expr)->op_first; child; child = OpSIBLING(child)) {
8062
8063             if (child->op_type == OP_PADAV || child->op_type == OP_RV2AV) {
8064                 assert( !(child->op_flags  & OPf_WANT));
8065                 /* push the array rather than its contents. The regex
8066                  * engine will retrieve and join the elements later */
8067                 child->op_flags |= (OPf_WANT_LIST | OPf_REF);
8068                 continue;
8069             }
8070
8071             if (!(child->op_type == OP_NULL && (child->op_flags & OPf_SPECIAL)))
8072                 continue;
8073             child->op_next = NULL; /* undo temporary hack from above */
8074             scalar(child);
8075             LINKLIST(child);
8076             if (cLISTOPx(child)->op_first->op_type == OP_LEAVE) {
8077                 LISTOP *leaveop = cLISTOPx(cLISTOPx(child)->op_first);
8078                 /* skip ENTER */
8079                 assert(leaveop->op_first->op_type == OP_ENTER);
8080                 assert(OpHAS_SIBLING(leaveop->op_first));
8081                 child->op_next = OpSIBLING(leaveop->op_first);
8082                 /* skip leave */
8083                 assert(leaveop->op_flags & OPf_KIDS);
8084                 assert(leaveop->op_last->op_next == (OP*)leaveop);
8085                 leaveop->op_next = NULL; /* stop on last op */
8086                 op_null((OP*)leaveop);
8087             }
8088             else {
8089                 /* skip SCOPE */
8090                 OP *scope = cLISTOPx(child)->op_first;
8091                 assert(scope->op_type == OP_SCOPE);
8092                 assert(scope->op_flags & OPf_KIDS);
8093                 scope->op_next = NULL; /* stop on last op */
8094                 op_null(scope);
8095             }
8096
8097             /* XXX optimize_optree() must be called on o before
8098              * CALL_PEEP(), as currently S_maybe_multiconcat() can't
8099              * currently cope with a peephole-optimised optree.
8100              * Calling optimize_optree() here ensures that condition
8101              * is met, but may mean optimize_optree() is applied
8102              * to the same optree later (where hopefully it won't do any
8103              * harm as it can't convert an op to multiconcat if it's
8104              * already been converted */
8105             optimize_optree(child);
8106
8107             /* have to peep the DOs individually as we've removed it from
8108              * the op_next chain */
8109             CALL_PEEP(child);
8110             S_prune_chain_head(&(child->op_next));
8111             if (is_compiletime)
8112                 /* runtime finalizes as part of finalizing whole tree */
8113                 finalize_optree(child);
8114         }
8115     }
8116     else if (expr->op_type == OP_PADAV || expr->op_type == OP_RV2AV) {
8117         assert( !(expr->op_flags  & OPf_WANT));
8118         /* push the array rather than its contents. The regex
8119          * engine will retrieve and join the elements later */
8120         expr->op_flags |= (OPf_WANT_LIST | OPf_REF);
8121     }
8122
8123     PL_hints |= HINT_BLOCK_SCOPE;
8124     pm = (PMOP*)o;
8125     assert(floor==0 || (pm->op_pmflags & PMf_HAS_CV));
8126
8127     if (is_compiletime) {
8128         U32 rx_flags = pm->op_pmflags & RXf_PMf_COMPILETIME;
8129         regexp_engine const *eng = current_re_engine();
8130
8131         if (is_split) {
8132             /* make engine handle split ' ' specially */
8133             pm->op_pmflags |= PMf_SPLIT;
8134             rx_flags |= RXf_SPLIT;
8135         }
8136
8137         if (!has_code || !eng->op_comp) {
8138             /* compile-time simple constant pattern */
8139
8140             if ((pm->op_pmflags & PMf_HAS_CV) && !has_code) {
8141                 /* whoops! we guessed that a qr// had a code block, but we
8142                  * were wrong (e.g. /[(?{}]/ ). Throw away the PL_compcv
8143                  * that isn't required now. Note that we have to be pretty
8144                  * confident that nothing used that CV's pad while the
8145                  * regex was parsed, except maybe op targets for \Q etc.
8146                  * If there were any op targets, though, they should have
8147                  * been stolen by constant folding.
8148                  */
8149 #ifdef DEBUGGING
8150                 SSize_t i = 0;
8151                 assert(PadnamelistMAXNAMED(PL_comppad_name) == 0);
8152                 while (++i <= AvFILLp(PL_comppad)) {
8153 #  ifdef USE_PAD_RESET
8154                     /* under USE_PAD_RESET, pad swipe replaces a swiped
8155                      * folded constant with a fresh padtmp */
8156                     assert(!PL_curpad[i] || SvPADTMP(PL_curpad[i]));
8157 #  else
8158                     assert(!PL_curpad[i]);
8159 #  endif
8160                 }
8161 #endif
8162                 /* This LEAVE_SCOPE will restore PL_compcv to point to the
8163                  * outer CV (the one whose slab holds the pm op). The
8164                  * inner CV (which holds expr) will be freed later, once
8165                  * all the entries on the parse stack have been popped on
8166                  * return from this function. Which is why its safe to
8167                  * call op_free(expr) below.
8168                  */
8169                 LEAVE_SCOPE(floor);
8170                 pm->op_pmflags &= ~PMf_HAS_CV;
8171             }
8172
8173             /* Skip compiling if parser found an error for this pattern */
8174             if (pm->op_pmflags & PMf_HAS_ERROR) {
8175                 return o;
8176             }
8177
8178             PM_SETRE(pm,
8179                 eng->op_comp
8180                     ? eng->op_comp(aTHX_ NULL, 0, expr, eng, NULL, NULL,
8181                                         rx_flags, pm->op_pmflags)
8182                     : Perl_re_op_compile(aTHX_ NULL, 0, expr, eng, NULL, NULL,
8183                                         rx_flags, pm->op_pmflags)
8184             );
8185             op_free(expr);
8186         }
8187         else {
8188             /* compile-time pattern that includes literal code blocks */
8189
8190             REGEXP* re;
8191
8192             /* Skip compiling if parser found an error for this pattern */
8193             if (pm->op_pmflags & PMf_HAS_ERROR) {
8194                 return o;
8195             }
8196
8197             re = eng->op_comp(aTHX_ NULL, 0, expr, eng, NULL, NULL,
8198                         rx_flags,
8199                         (pm->op_pmflags |
8200                             ((PL_hints & HINT_RE_EVAL) ? PMf_USE_RE_EVAL : 0))
8201                     );
8202             PM_SETRE(pm, re);
8203             if (pm->op_pmflags & PMf_HAS_CV) {
8204                 CV *cv;
8205                 /* this QR op (and the anon sub we embed it in) is never
8206                  * actually executed. It's just a placeholder where we can
8207                  * squirrel away expr in op_code_list without the peephole
8208                  * optimiser etc processing it for a second time */
8209                 OP *qr = newPMOP(OP_QR, 0);
8210                 ((PMOP*)qr)->op_code_list = expr;
8211
8212                 /* handle the implicit sub{} wrapped round the qr/(?{..})/ */
8213                 SvREFCNT_inc_simple_void(PL_compcv);
8214                 cv = newATTRSUB(floor, 0, NULL, NULL, qr);
8215                 ReANY(re)->qr_anoncv = cv;
8216
8217                 /* attach the anon CV to the pad so that
8218                  * pad_fixup_inner_anons() can find it */
8219                 (void)pad_add_anon(cv, o->op_type);
8220                 SvREFCNT_inc_simple_void(cv);
8221             }
8222             else {
8223                 pm->op_code_list = expr;
8224             }
8225         }
8226     }
8227     else {
8228         /* runtime pattern: build chain of regcomp etc ops */
8229         bool reglist;
8230         PADOFFSET cv_targ = 0;
8231
8232         reglist = isreg && expr->op_type == OP_LIST;
8233         if (reglist)
8234             op_null(expr);
8235
8236         if (has_code) {
8237             pm->op_code_list = expr;
8238             /* don't free op_code_list; its ops are embedded elsewhere too */
8239             pm->op_pmflags |= PMf_CODELIST_PRIVATE;
8240         }
8241
8242         if (is_split)
8243             /* make engine handle split ' ' specially */
8244             pm->op_pmflags |= PMf_SPLIT;
8245
8246         /* the OP_REGCMAYBE is a placeholder in the non-threaded case
8247          * to allow its op_next to be pointed past the regcomp and
8248          * preceding stacking ops;
8249          * OP_REGCRESET is there to reset taint before executing the
8250          * stacking ops */
8251         if (pm->op_pmflags & PMf_KEEP || TAINTING_get)
8252             expr = newUNOP((TAINTING_get ? OP_REGCRESET : OP_REGCMAYBE),0,expr);
8253
8254         if (pm->op_pmflags & PMf_HAS_CV) {
8255             /* we have a runtime qr with literal code. This means
8256              * that the qr// has been wrapped in a new CV, which
8257              * means that runtime consts, vars etc will have been compiled
8258              * against a new pad. So... we need to execute those ops
8259              * within the environment of the new CV. So wrap them in a call
8260              * to a new anon sub. i.e. for
8261              *
8262              *     qr/a$b(?{...})/,
8263              *
8264              * we build an anon sub that looks like
8265              *
8266              *     sub { "a", $b, '(?{...})' }
8267              *
8268              * and call it, passing the returned list to regcomp.
8269              * Or to put it another way, the list of ops that get executed
8270              * are:
8271              *
8272              *     normal              PMf_HAS_CV
8273              *     ------              -------------------
8274              *                         pushmark (for regcomp)
8275              *                         pushmark (for entersub)
8276              *                         anoncode
8277              *                         srefgen
8278              *                         entersub
8279              *     regcreset                  regcreset
8280              *     pushmark                   pushmark
8281              *     const("a")                 const("a")
8282              *     gvsv(b)                    gvsv(b)
8283              *     const("(?{...})")          const("(?{...})")
8284              *                                leavesub
8285              *     regcomp             regcomp
8286              */
8287
8288             SvREFCNT_inc_simple_void(PL_compcv);
8289             CvLVALUE_on(PL_compcv);
8290             /* these lines are just an unrolled newANONATTRSUB */
8291             expr = newSVOP(OP_ANONCODE, 0,
8292                     MUTABLE_SV(newATTRSUB(floor, 0, NULL, NULL, expr)));
8293             cv_targ = expr->op_targ;
8294             expr = newUNOP(OP_REFGEN, 0, expr);
8295
8296             expr = list(force_list(newUNOP(OP_ENTERSUB, 0, scalar(expr)), 1));
8297         }
8298
8299         rcop = alloc_LOGOP(OP_REGCOMP, scalar(expr), o);
8300         rcop->op_flags |=  ((PL_hints & HINT_RE_EVAL) ? OPf_SPECIAL : 0)
8301                            | (reglist ? OPf_STACKED : 0);
8302         rcop->op_targ = cv_targ;
8303
8304         /* /$x/ may cause an eval, since $x might be qr/(?{..})/  */
8305         if (PL_hints & HINT_RE_EVAL)
8306             S_set_haseval(aTHX);
8307
8308         /* establish postfix order */
8309         if (expr->op_type == OP_REGCRESET || expr->op_type == OP_REGCMAYBE) {
8310             LINKLIST(expr);
8311             rcop->op_next = expr;
8312             ((UNOP*)expr)->op_first->op_next = (OP*)rcop;
8313         }
8314         else {
8315             rcop->op_next = LINKLIST(expr);
8316             expr->op_next = (OP*)rcop;
8317         }
8318
8319         op_prepend_elem(o->op_type, scalar((OP*)rcop), o);
8320     }
8321
8322     if (repl) {
8323         OP *curop = repl;
8324         bool konst;
8325         /* If we are looking at s//.../e with a single statement, get past
8326            the implicit do{}. */
8327         if (curop->op_type == OP_NULL && curop->op_flags & OPf_KIDS
8328              && cUNOPx(curop)->op_first->op_type == OP_SCOPE
8329              && cUNOPx(curop)->op_first->op_flags & OPf_KIDS)
8330          {
8331             OP *sib;
8332             OP *kid = cUNOPx(cUNOPx(curop)->op_first)->op_first;
8333             if (kid->op_type == OP_NULL && (sib = OpSIBLING(kid))
8334              && !OpHAS_SIBLING(sib))
8335                 curop = sib;
8336         }
8337         if (curop->op_type == OP_CONST)
8338             konst = TRUE;
8339         else if (( (curop->op_type == OP_RV2SV ||
8340                     curop->op_type == OP_RV2AV ||
8341                     curop->op_type == OP_RV2HV ||
8342                     curop->op_type == OP_RV2GV)
8343                    && cUNOPx(curop)->op_first
8344                    && cUNOPx(curop)->op_first->op_type == OP_GV )
8345                 || curop->op_type == OP_PADSV
8346                 || curop->op_type == OP_PADAV
8347                 || curop->op_type == OP_PADHV
8348                 || curop->op_type == OP_PADANY) {
8349             repl_has_vars = 1;
8350             konst = TRUE;
8351         }
8352         else konst = FALSE;
8353         if (konst
8354             && !(repl_has_vars
8355                  && (!PM_GETRE(pm)
8356                      || !RX_PRELEN(PM_GETRE(pm))
8357                      || RX_EXTFLAGS(PM_GETRE(pm)) & RXf_EVAL_SEEN)))
8358         {
8359             pm->op_pmflags |= PMf_CONST;        /* const for long enough */
8360             op_prepend_elem(o->op_type, scalar(repl), o);
8361         }
8362         else {
8363             rcop = alloc_LOGOP(OP_SUBSTCONT, scalar(repl), o);
8364             rcop->op_private = 1;
8365
8366             /* establish postfix order */
8367             rcop->op_next = LINKLIST(repl);
8368             repl->op_next = (OP*)rcop;
8369
8370             pm->op_pmreplrootu.op_pmreplroot = scalar((OP*)rcop);
8371             assert(!(pm->op_pmflags & PMf_ONCE));
8372             pm->op_pmstashstartu.op_pmreplstart = LINKLIST(rcop);
8373             rcop->op_next = 0;
8374         }
8375     }
8376
8377     return (OP*)pm;
8378 }
8379
8380 /*
8381 =for apidoc newSVOP
8382
8383 Constructs, checks, and returns an op of any type that involves an
8384 embedded SV.  C<type> is the opcode.  C<flags> gives the eight bits
8385 of C<op_flags>.  C<sv> gives the SV to embed in the op; this function
8386 takes ownership of one reference to it.
8387
8388 =cut
8389 */
8390
8391 OP *
8392 Perl_newSVOP(pTHX_ I32 type, I32 flags, SV *sv)
8393 {
8394     dVAR;
8395     SVOP *svop;
8396
8397     PERL_ARGS_ASSERT_NEWSVOP;
8398
8399     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_SVOP
8400         || (PL_opargs[type] & OA_CLASS_MASK) == OA_PVOP_OR_SVOP
8401         || (PL_opargs[type] & OA_CLASS_MASK) == OA_FILESTATOP
8402         || type == OP_CUSTOM);
8403
8404     NewOp(1101, svop, 1, SVOP);
8405     OpTYPE_set(svop, type);
8406     svop->op_sv = sv;
8407     svop->op_next = (OP*)svop;
8408     svop->op_flags = (U8)flags;
8409     svop->op_private = (U8)(0 | (flags >> 8));
8410     if (PL_opargs[type] & OA_RETSCALAR)
8411         scalar((OP*)svop);
8412     if (PL_opargs[type] & OA_TARGET)
8413         svop->op_targ = pad_alloc(type, SVs_PADTMP);
8414     return CHECKOP(type, svop);
8415 }
8416
8417 /*
8418 =for apidoc newDEFSVOP
8419
8420 Constructs and returns an op to access C<$_>.
8421
8422 =cut
8423 */
8424
8425 OP *
8426 Perl_newDEFSVOP(pTHX)
8427 {
8428         return newSVREF(newGVOP(OP_GV, 0, PL_defgv));
8429 }
8430
8431 #ifdef USE_ITHREADS
8432
8433 /*
8434 =for apidoc newPADOP
8435
8436 Constructs, checks, and returns an op of any type that involves a
8437 reference to a pad element.  C<type> is the opcode.  C<flags> gives the
8438 eight bits of C<op_flags>.  A pad slot is automatically allocated, and
8439 is populated with C<sv>; this function takes ownership of one reference
8440 to it.
8441
8442 This function only exists if Perl has been compiled to use ithreads.
8443
8444 =cut
8445 */
8446
8447 OP *
8448 Perl_newPADOP(pTHX_ I32 type, I32 flags, SV *sv)
8449 {
8450     dVAR;
8451     PADOP *padop;
8452
8453     PERL_ARGS_ASSERT_NEWPADOP;
8454
8455     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_SVOP
8456         || (PL_opargs[type] & OA_CLASS_MASK) == OA_PVOP_OR_SVOP
8457         || (PL_opargs[type] & OA_CLASS_MASK) == OA_FILESTATOP
8458         || type == OP_CUSTOM);
8459
8460     NewOp(1101, padop, 1, PADOP);
8461     OpTYPE_set(padop, type);
8462     padop->op_padix =
8463         pad_alloc(type, isGV(sv) ? SVf_READONLY : SVs_PADTMP);
8464     SvREFCNT_dec(PAD_SVl(padop->op_padix));
8465     PAD_SETSV(padop->op_padix, sv);
8466     assert(sv);
8467     padop->op_next = (OP*)padop;
8468     padop->op_flags = (U8)flags;
8469     if (PL_opargs[type] & OA_RETSCALAR)
8470         scalar((OP*)padop);
8471     if (PL_opargs[type] & OA_TARGET)
8472         padop->op_targ = pad_alloc(type, SVs_PADTMP);
8473     return CHECKOP(type, padop);
8474 }
8475
8476 #endif /* USE_ITHREADS */
8477
8478 /*
8479 =for apidoc newGVOP
8480
8481 Constructs, checks, and returns an op of any type that involves an
8482 embedded reference to a GV.  C<type> is the opcode.  C<flags> gives the
8483 eight bits of C<op_flags>.  C<gv> identifies the GV that the op should
8484 reference; calling this function does not transfer ownership of any
8485 reference to it.
8486
8487 =cut
8488 */
8489
8490 OP *
8491 Perl_newGVOP(pTHX_ I32 type, I32 flags, GV *gv)
8492 {
8493     PERL_ARGS_ASSERT_NEWGVOP;
8494
8495 #ifdef USE_ITHREADS
8496     return newPADOP(type, flags, SvREFCNT_inc_simple_NN(gv));
8497 #else
8498     return newSVOP(type, flags, SvREFCNT_inc_simple_NN(gv));
8499 #endif
8500 }
8501
8502 /*
8503 =for apidoc newPVOP
8504
8505 Constructs, checks, and returns an op of any type that involves an
8506 embedded C-level pointer (PV).  C<type> is the opcode.  C<flags> gives
8507 the eight bits of C<op_flags>.  C<pv> supplies the C-level pointer.
8508 Depending on the op type, the memory referenced by C<pv> may be freed
8509 when the op is destroyed.  If the op is of a freeing type, C<pv> must
8510 have been allocated using C<PerlMemShared_malloc>.
8511
8512 =cut
8513 */
8514
8515 OP *
8516 Perl_newPVOP(pTHX_ I32 type, I32 flags, char *pv)
8517 {
8518     dVAR;
8519     const bool utf8 = cBOOL(flags & SVf_UTF8);
8520     PVOP *pvop;
8521
8522     flags &= ~SVf_UTF8;
8523
8524     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_PVOP_OR_SVOP
8525         || type == OP_RUNCV || type == OP_CUSTOM
8526         || (PL_opargs[type] & OA_CLASS_MASK) == OA_LOOPEXOP);
8527
8528     NewOp(1101, pvop, 1, PVOP);
8529     OpTYPE_set(pvop, type);
8530     pvop->op_pv = pv;
8531     pvop->op_next = (OP*)pvop;
8532     pvop->op_flags = (U8)flags;
8533     pvop->op_private = utf8 ? OPpPV_IS_UTF8 : 0;
8534     if (PL_opargs[type] & OA_RETSCALAR)
8535         scalar((OP*)pvop);
8536     if (PL_opargs[type] & OA_TARGET)
8537         pvop->op_targ = pad_alloc(type, SVs_PADTMP);
8538     return CHECKOP(type, pvop);
8539 }
8540
8541 void
8542 Perl_package(pTHX_ OP *o)
8543 {
8544     SV *const sv = cSVOPo->op_sv;
8545
8546     PERL_ARGS_ASSERT_PACKAGE;
8547
8548     SAVEGENERICSV(PL_curstash);
8549     save_item(PL_curstname);
8550
8551     PL_curstash = (HV *)SvREFCNT_inc(gv_stashsv(sv, GV_ADD));
8552
8553     sv_setsv(PL_curstname, sv);
8554
8555     PL_hints |= HINT_BLOCK_SCOPE;
8556     PL_parser->copline = NOLINE;
8557
8558     op_free(o);
8559 }
8560
8561 void
8562 Perl_package_version( pTHX_ OP *v )
8563 {
8564     U32 savehints = PL_hints;
8565     PERL_ARGS_ASSERT_PACKAGE_VERSION;
8566     PL_hints &= ~HINT_STRICT_VARS;
8567     sv_setsv( GvSV(gv_fetchpvs("VERSION", GV_ADDMULTI, SVt_PV)), cSVOPx(v)->op_sv );
8568     PL_hints = savehints;
8569     op_free(v);
8570 }
8571
8572 void
8573 Perl_utilize(pTHX_ int aver, I32 floor, OP *version, OP *idop, OP *arg)
8574 {
8575     OP *pack;
8576     OP *imop;
8577     OP *veop;
8578     SV *use_version = NULL;
8579
8580     PERL_ARGS_ASSERT_UTILIZE;
8581
8582     if (idop->op_type != OP_CONST)
8583         Perl_croak(aTHX_ "Module name must be constant");
8584
8585     veop = NULL;
8586
8587     if (version) {
8588         SV * const vesv = ((SVOP*)version)->op_sv;
8589
8590         if (!arg && !SvNIOKp(vesv)) {
8591             arg = version;
8592         }
8593         else {
8594             OP *pack;
8595             SV *meth;
8596
8597             if (version->op_type != OP_CONST || !SvNIOKp(vesv))
8598                 Perl_croak(aTHX_ "Version number must be a constant number");
8599
8600             /* Make copy of idop so we don't free it twice */
8601             pack = newSVOP(OP_CONST, 0, newSVsv(((SVOP*)idop)->op_sv));
8602
8603             /* Fake up a method call to VERSION */
8604             meth = newSVpvs_share("VERSION");
8605             veop = op_convert_list(OP_ENTERSUB, OPf_STACKED|OPf_SPECIAL,
8606                             op_append_elem(OP_LIST,
8607                                         op_prepend_elem(OP_LIST, pack, version),
8608                                         newMETHOP_named(OP_METHOD_NAMED, 0, meth)));
8609         }
8610     }
8611
8612     /* Fake up an import/unimport */
8613     if (arg && arg->op_type == OP_STUB) {
8614         imop = arg;             /* no import on explicit () */
8615     }
8616     else if (SvNIOKp(((SVOP*)idop)->op_sv)) {
8617         imop = NULL;            /* use 5.0; */
8618         if (aver)
8619             use_version = ((SVOP*)idop)->op_sv;
8620         else
8621             idop->op_private |= OPpCONST_NOVER;
8622     }
8623     else {
8624         SV *meth;
8625
8626         /* Make copy of idop so we don't free it twice */
8627         pack = newSVOP(OP_CONST, 0, newSVsv(((SVOP*)idop)->op_sv));
8628
8629         /* Fake up a method call to import/unimport */
8630         meth = aver
8631             ? newSVpvs_share("import") : newSVpvs_share("unimport");
8632         imop = op_convert_list(OP_ENTERSUB, OPf_STACKED|OPf_SPECIAL,
8633                        op_append_elem(OP_LIST,
8634                                    op_prepend_elem(OP_LIST, pack, arg),
8635                                    newMETHOP_named(OP_METHOD_NAMED, 0, meth)
8636                        ));
8637     }
8638
8639     /* Fake up the BEGIN {}, which does its thing immediately. */
8640     newATTRSUB(floor,
8641         newSVOP(OP_CONST, 0, newSVpvs_share("BEGIN")),
8642         NULL,
8643         NULL,
8644         op_append_elem(OP_LINESEQ,
8645             op_append_elem(OP_LINESEQ,
8646                 newSTATEOP(0, NULL, newUNOP(OP_REQUIRE, 0, idop)),
8647                 newSTATEOP(0, NULL, veop)),
8648             newSTATEOP(0, NULL, imop) ));
8649
8650     if (use_version) {
8651         /* Enable the
8652          * feature bundle that corresponds to the required version. */
8653         use_version = sv_2mortal(new_version(use_version));
8654         S_enable_feature_bundle(aTHX_ use_version);
8655
8656         /* If a version >= 5.11.0 is requested, strictures are on by default! */
8657         if (vcmp(use_version,
8658                  sv_2mortal(upg_version(newSVnv(5.011000), FALSE))) >= 0) {
8659             if (!(PL_hints & HINT_EXPLICIT_STRICT_REFS))
8660                 PL_hints |= HINT_STRICT_REFS;
8661             if (!(PL_hints & HINT_EXPLICIT_STRICT_SUBS))
8662                 PL_hints |= HINT_STRICT_SUBS;
8663             if (!(PL_hints & HINT_EXPLICIT_STRICT_VARS))
8664                 PL_hints |= HINT_STRICT_VARS;
8665         }
8666         /* otherwise they are off */
8667         else {
8668             if (!(PL_hints & HINT_EXPLICIT_STRICT_REFS))
8669                 PL_hints &= ~HINT_STRICT_REFS;
8670             if (!(PL_hints & HINT_EXPLICIT_STRICT_SUBS))
8671                 PL_hints &= ~HINT_STRICT_SUBS;
8672             if (!(PL_hints & HINT_EXPLICIT_STRICT_VARS))
8673                 PL_hints &= ~HINT_STRICT_VARS;
8674         }
8675     }
8676
8677     /* The "did you use incorrect case?" warning used to be here.
8678      * The problem is that on case-insensitive filesystems one
8679      * might get false positives for "use" (and "require"):
8680      * "use Strict" or "require CARP" will work.  This causes
8681      * portability problems for the script: in case-strict
8682      * filesystems the script will stop working.
8683      *
8684      * The "incorrect case" warning checked whether "use Foo"
8685      * imported "Foo" to your namespace, but that is wrong, too:
8686      * there is no requirement nor promise in the language that
8687      * a Foo.pm should or would contain anything in package "Foo".
8688      *
8689      * There is very little Configure-wise that can be done, either:
8690      * the case-sensitivity of the build filesystem of Perl does not
8691      * help in guessing the case-sensitivity of the runtime environment.
8692      */
8693
8694     PL_hints |= HINT_BLOCK_SCOPE;
8695     PL_parser->copline = NOLINE;
8696     COP_SEQMAX_INC; /* Purely for B::*'s benefit */
8697 }
8698
8699 /*
8700 =head1 Embedding Functions
8701
8702 =for apidoc load_module
8703
8704 Loads the module whose name is pointed to by the string part of C<name>.
8705 Note that the actual module name, not its filename, should be given.
8706 Eg, "Foo::Bar" instead of "Foo/Bar.pm". ver, if specified and not NULL,
8707 provides version semantics similar to C<use Foo::Bar VERSION>. The optional
8708 trailing arguments can be used to specify arguments to the module's C<import()>
8709 method, similar to C<use Foo::Bar VERSION LIST>; their precise handling depends
8710 on the flags. The flags argument is a bitwise-ORed collection of any of
8711 C<PERL_LOADMOD_DENY>, C<PERL_LOADMOD_NOIMPORT>, or C<PERL_LOADMOD_IMPORT_OPS>
8712 (or 0 for no flags).
8713
8714 If C<PERL_LOADMOD_NOIMPORT> is set, the module is loaded as if with an empty
8715 import list, as in C<use Foo::Bar ()>; this is the only circumstance in which
8716 the trailing optional arguments may be omitted entirely. Otherwise, if
8717 C<PERL_LOADMOD_IMPORT_OPS> is set, the trailing arguments must consist of
8718 exactly one C<OP*>, containing the op tree that produces the relevant import
8719 arguments. Otherwise, the trailing arguments must all be C<SV*> values that
8720 will be used as import arguments; and the list must be terminated with C<(SV*)
8721 NULL>. If neither C<PERL_LOADMOD_NOIMPORT> nor C<PERL_LOADMOD_IMPORT_OPS> is
8722 set, the trailing C<NULL> pointer is needed even if no import arguments are
8723 desired. The reference count for each specified C<SV*> argument is
8724 decremented. In addition, the C<name> argument is modified.
8725
8726 If C<PERL_LOADMOD_DENY> is set, the module is loaded as if with C<no> rather
8727 than C<use>.
8728
8729 =for apidoc Amnh||PERL_LOADMOD_DENY
8730 =for apidoc Amnh||PERL_LOADMOD_NOIMPORT
8731 =for apidoc Amnh||PERL_LOADMOD_IMPORT_OPS
8732
8733 =cut */
8734
8735 void
8736 Perl_load_module(pTHX_ U32 flags, SV *name, SV *ver, ...)
8737 {
8738     va_list args;
8739
8740     PERL_ARGS_ASSERT_LOAD_MODULE;
8741
8742     va_start(args, ver);
8743     vload_module(flags, name, ver, &args);
8744     va_end(args);
8745 }
8746
8747 #ifdef PERL_IMPLICIT_CONTEXT
8748 void
8749 Perl_load_module_nocontext(U32 flags, SV *name, SV *ver, ...)
8750 {
8751     dTHX;
8752     va_list args;
8753     PERL_ARGS_ASSERT_LOAD_MODULE_NOCONTEXT;
8754     va_start(args, ver);
8755     vload_module(flags, name, ver, &args);
8756     va_end(args);
8757 }
8758 #endif
8759
8760 void
8761 Perl_vload_module(pTHX_ U32 flags, SV *name, SV *ver, va_list *args)
8762 {
8763     OP *veop, *imop;
8764     OP * modname;
8765     I32 floor;
8766
8767     PERL_ARGS_ASSERT_VLOAD_MODULE;
8768
8769     /* utilize() fakes up a BEGIN { require ..; import ... }, so make sure
8770      * that it has a PL_parser to play with while doing that, and also
8771      * that it doesn't mess with any existing parser, by creating a tmp
8772      * new parser with lex_start(). This won't actually be used for much,
8773      * since pp_require() will create another parser for the real work.
8774      * The ENTER/LEAVE pair protect callers from any side effects of use.
8775      *
8776      * start_subparse() creates a new PL_compcv. This means that any ops
8777      * allocated below will be allocated from that CV's op slab, and so
8778      * will be automatically freed if the utilise() fails
8779      */
8780
8781     ENTER;
8782     SAVEVPTR(PL_curcop);
8783     lex_start(NULL, NULL, LEX_START_SAME_FILTER);
8784     floor = start_subparse(FALSE, 0);
8785
8786     modname = newSVOP(OP_CONST, 0, name);
8787     modname->op_private |= OPpCONST_BARE;
8788     if (ver) {
8789         veop = newSVOP(OP_CONST, 0, ver);
8790     }
8791     else
8792         veop = NULL;
8793     if (flags & PERL_LOADMOD_NOIMPORT) {
8794         imop = sawparens(newNULLLIST());
8795     }
8796     else if (flags & PERL_LOADMOD_IMPORT_OPS) {
8797         imop = va_arg(*args, OP*);
8798     }
8799     else {
8800         SV *sv;
8801         imop = NULL;
8802         sv = va_arg(*args, SV*);
8803         while (sv) {
8804             imop = op_append_elem(OP_LIST, imop, newSVOP(OP_CONST, 0, sv));
8805             sv = va_arg(*args, SV*);
8806         }
8807     }
8808
8809     utilize(!(flags & PERL_LOADMOD_DENY), floor, veop, modname, imop);
8810     LEAVE;
8811 }
8812
8813 PERL_STATIC_INLINE OP *
8814 S_new_entersubop(pTHX_ GV *gv, OP *arg)
8815 {
8816     return newUNOP(OP_ENTERSUB, OPf_STACKED,
8817                    newLISTOP(OP_LIST, 0, arg,
8818                              newUNOP(OP_RV2CV, 0,
8819                                      newGVOP(OP_GV, 0, gv))));
8820 }
8821
8822 OP *
8823 Perl_dofile(pTHX_ OP *term, I32 force_builtin)
8824 {
8825     OP *doop;
8826     GV *gv;
8827
8828     PERL_ARGS_ASSERT_DOFILE;
8829
8830     if (!force_builtin && (gv = gv_override("do", 2))) {
8831         doop = S_new_entersubop(aTHX_ gv, term);
8832     }
8833     else {
8834         doop = newUNOP(OP_DOFILE, 0, scalar(term));
8835     }
8836     return doop;
8837 }
8838
8839 /*
8840 =head1 Optree construction
8841
8842 =for apidoc newSLICEOP
8843
8844 Constructs, checks, and returns an C<lslice> (list slice) op.  C<flags>
8845 gives the eight bits of C<op_flags>, except that C<OPf_KIDS> will
8846 be set automatically, and, shifted up eight bits, the eight bits of
8847 C<op_private>, except that the bit with value 1 or 2 is automatically
8848 set as required.  C<listval> and C<subscript> supply the parameters of
8849 the slice; they are consumed by this function and become part of the
8850 constructed op tree.
8851
8852 =cut
8853 */
8854
8855 OP *
8856 Perl_newSLICEOP(pTHX_ I32 flags, OP *subscript, OP *listval)
8857 {
8858     return newBINOP(OP_LSLICE, flags,
8859             list(force_list(subscript, 1)),
8860             list(force_list(listval,   1)) );
8861 }
8862
8863 #define ASSIGN_SCALAR 0
8864 #define ASSIGN_LIST   1
8865 #define ASSIGN_REF    2
8866
8867 /* given the optree o on the LHS of an assignment, determine whether its:
8868  *  ASSIGN_SCALAR   $x  = ...
8869  *  ASSIGN_LIST    ($x) = ...
8870  *  ASSIGN_REF     \$x  = ...
8871  */
8872
8873 STATIC I32
8874 S_assignment_type(pTHX_ const OP *o)
8875 {
8876     unsigned type;
8877     U8 flags;
8878     U8 ret;
8879
8880     if (!o)
8881         return ASSIGN_LIST;
8882
8883     if (o->op_type == OP_SREFGEN)
8884     {
8885         OP * const kid = cUNOPx(cUNOPo->op_first)->op_first;
8886         type = kid->op_type;
8887         flags = o->op_flags | kid->op_flags;
8888         if (!(flags & OPf_PARENS)
8889           && (kid->op_type == OP_RV2AV || kid->op_type == OP_PADAV ||
8890               kid->op_type == OP_RV2HV || kid->op_type == OP_PADHV ))
8891             return ASSIGN_REF;
8892         ret = ASSIGN_REF;
8893     } else {
8894         if ((o->op_type == OP_NULL) && (o->op_flags & OPf_KIDS))
8895             o = cUNOPo->op_first;
8896         flags = o->op_flags;
8897         type = o->op_type;
8898         ret = ASSIGN_SCALAR;
8899     }
8900
8901     if (type == OP_COND_EXPR) {
8902         OP * const sib = OpSIBLING(cLOGOPo->op_first);
8903         const I32 t = assignment_type(sib);
8904         const I32 f = assignment_type(OpSIBLING(sib));
8905
8906         if (t == ASSIGN_LIST && f == ASSIGN_LIST)
8907             return ASSIGN_LIST;
8908         if ((t == ASSIGN_LIST) ^ (f == ASSIGN_LIST))
8909             yyerror("Assignment to both a list and a scalar");
8910         return ASSIGN_SCALAR;
8911     }
8912
8913     if (type == OP_LIST &&
8914         (flags & OPf_WANT) == OPf_WANT_SCALAR &&
8915         o->op_private & OPpLVAL_INTRO)
8916         return ret;
8917
8918     if (type == OP_LIST || flags & OPf_PARENS ||
8919         type == OP_RV2AV || type == OP_RV2HV ||
8920         type == OP_ASLICE || type == OP_HSLICE ||
8921         type == OP_KVASLICE || type == OP_KVHSLICE || type == OP_REFGEN)
8922         return ASSIGN_LIST;
8923
8924     if (type == OP_PADAV || type == OP_PADHV)
8925         return ASSIGN_LIST;
8926
8927     if (type == OP_RV2SV)
8928         return ret;
8929
8930     return ret;
8931 }
8932
8933 static OP *
8934 S_newONCEOP(pTHX_ OP *initop, OP *padop)
8935 {
8936     dVAR;
8937     const PADOFFSET target = padop->op_targ;
8938     OP *const other = newOP(OP_PADSV,
8939                             padop->op_flags
8940                             | ((padop->op_private & ~OPpLVAL_INTRO) << 8));
8941     OP *const first = newOP(OP_NULL, 0);
8942     OP *const nullop = newCONDOP(0, first, initop, other);
8943     /* XXX targlex disabled for now; see ticket #124160
8944         newCONDOP(0, first, S_maybe_targlex(aTHX_ initop), other);
8945      */
8946     OP *const condop = first->op_next;
8947
8948     OpTYPE_set(condop, OP_ONCE);
8949     other->op_targ = target;
8950     nullop->op_flags |= OPf_WANT_SCALAR;
8951
8952     /* Store the initializedness of state vars in a separate
8953        pad entry.  */
8954     condop->op_targ =
8955       pad_add_name_pvn("$",1,padadd_NO_DUP_CHECK|padadd_STATE,0,0);
8956     /* hijacking PADSTALE for uninitialized state variables */
8957     SvPADSTALE_on(PAD_SVl(condop->op_targ));
8958
8959     return nullop;
8960 }
8961
8962 /*
8963 =for apidoc newASSIGNOP
8964
8965 Constructs, checks, and returns an assignment op.  C<left> and C<right>
8966 supply the parameters of the assignment; they are consumed by this
8967 function and become part of the constructed op tree.
8968
8969 If C<optype> is C<OP_ANDASSIGN>, C<OP_ORASSIGN>, or C<OP_DORASSIGN>, then
8970 a suitable conditional optree is constructed.  If C<optype> is the opcode
8971 of a binary operator, such as C<OP_BIT_OR>, then an op is constructed that
8972 performs the binary operation and assigns the result to the left argument.
8973 Either way, if C<optype> is non-zero then C<flags> has no effect.
8974
8975 If C<optype> is zero, then a plain scalar or list assignment is
8976 constructed.  Which type of assignment it is is automatically determined.
8977 C<flags> gives the eight bits of C<op_flags>, except that C<OPf_KIDS>
8978 will be set automatically, and, shifted up eight bits, the eight bits
8979 of C<op_private>, except that the bit with value 1 or 2 is automatically
8980 set as required.
8981
8982 =cut
8983 */
8984
8985 OP *
8986 Perl_newASSIGNOP(pTHX_ I32 flags, OP *left, I32 optype, OP *right)
8987 {
8988     OP *o;
8989     I32 assign_type;
8990
8991     if (optype) {
8992         if (optype == OP_ANDASSIGN || optype == OP_ORASSIGN || optype == OP_DORASSIGN) {
8993             right = scalar(right);
8994             return newLOGOP(optype, 0,
8995                 op_lvalue(scalar(left), optype),
8996                 newBINOP(OP_SASSIGN, OPpASSIGN_BACKWARDS<<8, right, right));
8997         }
8998         else {
8999             return newBINOP(optype, OPf_STACKED,
9000                 op_lvalue(scalar(left), optype), scalar(right));
9001         }
9002     }
9003
9004     if ((assign_type = assignment_type(left)) == ASSIGN_LIST) {
9005         OP *state_var_op = NULL;
9006         static const char no_list_state[] = "Initialization of state variables"
9007             " in list currently forbidden";
9008         OP *curop;
9009
9010         if (left->op_type == OP_ASLICE || left->op_type == OP_HSLICE)
9011             left->op_private &= ~ OPpSLICEWARNING;
9012
9013         PL_modcount = 0;
9014         left = op_lvalue(left, OP_AASSIGN);
9015         curop = list(force_list(left, 1));
9016         o = newBINOP(OP_AASSIGN, flags, list(force_list(right, 1)), curop);
9017         o->op_private = (U8)(0 | (flags >> 8));
9018
9019         if (OP_TYPE_IS_OR_WAS(left, OP_LIST))
9020         {
9021             OP *lop = ((LISTOP*)left)->op_first, *vop, *eop;
9022             if (!(left->op_flags & OPf_PARENS) &&
9023                     lop->op_type == OP_PUSHMARK &&
9024                     (vop = OpSIBLING(lop)) &&
9025                     (vop->op_type == OP_PADAV || vop->op_type == OP_PADHV) &&
9026                     !(vop->op_flags & OPf_PARENS) &&
9027                     (vop->op_private & (OPpLVAL_INTRO|OPpPAD_STATE)) ==
9028                         (OPpLVAL_INTRO|OPpPAD_STATE) &&
9029                     (eop = OpSIBLING(vop)) &&
9030                     eop->op_type == OP_ENTERSUB &&
9031                     !OpHAS_SIBLING(eop)) {
9032                 state_var_op = vop;
9033             } else {
9034                 while (lop) {
9035                     if ((lop->op_type == OP_PADSV ||
9036                          lop->op_type == OP_PADAV ||
9037                          lop->op_type == OP_PADHV ||
9038                          lop->op_type == OP_PADANY)
9039                       && (lop->op_private & OPpPAD_STATE)
9040                     )
9041                         yyerror(no_list_state);
9042                     lop = OpSIBLING(lop);
9043                 }
9044             }
9045         }
9046         else if (  (left->op_private & OPpLVAL_INTRO)
9047                 && (left->op_private & OPpPAD_STATE)
9048                 && (   left->op_type == OP_PADSV
9049                     || left->op_type == OP_PADAV
9050                     || left->op_type == OP_PADHV
9051                     || left->op_type == OP_PADANY)
9052         ) {
9053                 /* All single variable list context state assignments, hence
9054                    state ($a) = ...
9055                    (state $a) = ...
9056                    state @a = ...
9057                    state (@a) = ...
9058                    (state @a) = ...
9059                    state %a = ...
9060                    state (%a) = ...
9061                    (state %a) = ...
9062                 */
9063                 if (left->op_flags & OPf_PARENS)
9064                     yyerror(no_list_state);
9065                 else
9066                     state_var_op = left;
9067         }
9068
9069         /* optimise @a = split(...) into:
9070         * @{expr}:              split(..., @{expr}) (where @a is not flattened)
9071         * @a, my @a, local @a:  split(...)          (where @a is attached to
9072         *                                            the split op itself)
9073         */
9074
9075         if (   right
9076             && right->op_type == OP_SPLIT
9077             /* don't do twice, e.g. @b = (@a = split) */
9078             && !(right->op_private & OPpSPLIT_ASSIGN))
9079         {
9080             OP *gvop = NULL;
9081
9082             if (   (  left->op_type == OP_RV2AV
9083                    && (gvop=((UNOP*)left)->op_first)->op_type==OP_GV)
9084                 || left->op_type == OP_PADAV)
9085             {
9086                 /* @pkg or @lex or local @pkg' or 'my @lex' */
9087                 OP *tmpop;
9088                 if (gvop) {
9089 #ifdef USE_ITHREADS
9090                     ((PMOP*)right)->op_pmreplrootu.op_pmtargetoff
9091                         = cPADOPx(gvop)->op_padix;
9092                     cPADOPx(gvop)->op_padix = 0;        /* steal it */
9093 #else
9094                     ((PMOP*)right)->op_pmreplrootu.op_pmtargetgv
9095                         = MUTABLE_GV(cSVOPx(gvop)->op_sv);
9096                     cSVOPx(gvop)->op_sv = NULL; /* steal it */
9097 #endif
9098                     right->op_private |=
9099                         left->op_private & OPpOUR_INTRO;
9100                 }
9101                 else {
9102                     ((PMOP*)right)->op_pmreplrootu.op_pmtargetoff = left->op_targ;
9103                     left->op_targ = 0;  /* steal it */
9104                     right->op_private |= OPpSPLIT_LEX;
9105                 }
9106                 right->op_private |= left->op_private & OPpLVAL_INTRO;
9107
9108               detach_split:
9109                 tmpop = cUNOPo->op_first;       /* to list (nulled) */
9110                 tmpop = ((UNOP*)tmpop)->op_first; /* to pushmark */
9111                 assert(OpSIBLING(tmpop) == right);
9112                 assert(!OpHAS_SIBLING(right));
9113                 /* detach the split subtreee from the o tree,
9114                  * then free the residual o tree */
9115                 op_sibling_splice(cUNOPo->op_first, tmpop, 1, NULL);
9116                 op_free(o);                     /* blow off assign */
9117                 right->op_private |= OPpSPLIT_ASSIGN;
9118                 right->op_flags &= ~OPf_WANT;
9119                         /* "I don't know and I don't care." */
9120                 return right;
9121             }
9122             else if (left->op_type == OP_RV2AV) {
9123                 /* @{expr} */
9124
9125                 OP *pushop = cUNOPx(cBINOPo->op_last)->op_first;
9126                 assert(OpSIBLING(pushop) == left);
9127                 /* Detach the array ...  */
9128                 op_sibling_splice(cBINOPo->op_last, pushop, 1, NULL);
9129                 /* ... and attach it to the split.  */
9130                 op_sibling_splice(right, cLISTOPx(right)->op_last,
9131                                   0, left);
9132                 right->op_flags |= OPf_STACKED;
9133                 /* Detach split and expunge aassign as above.  */
9134                 goto detach_split;
9135             }
9136             else if (PL_modcount < RETURN_UNLIMITED_NUMBER &&
9137                     ((LISTOP*)right)->op_last->op_type == OP_CONST)
9138             {
9139                 /* convert split(...,0) to split(..., PL_modcount+1) */
9140                 SV ** const svp =
9141                     &((SVOP*)((LISTOP*)right)->op_last)->op_sv;
9142                 SV * const sv = *svp;
9143                 if (SvIOK(sv) && SvIVX(sv) == 0)
9144                 {
9145                   if (right->op_private & OPpSPLIT_IMPLIM) {
9146                     /* our own SV, created in ck_split */
9147                     SvREADONLY_off(sv);
9148                     sv_setiv(sv, PL_modcount+1);
9149                   }
9150                   else {
9151                     /* SV may belong to someone else */
9152                     SvREFCNT_dec(sv);
9153                     *svp = newSViv(PL_modcount+1);
9154                   }
9155                 }
9156             }
9157         }
9158
9159         if (state_var_op)
9160             o = S_newONCEOP(aTHX_ o, state_var_op);
9161         return o;
9162     }
9163     if (assign_type == ASSIGN_REF)
9164         return newBINOP(OP_REFASSIGN, flags, scalar(right), left);
9165     if (!right)
9166         right = newOP(OP_UNDEF, 0);
9167     if (right->op_type == OP_READLINE) {
9168         right->op_flags |= OPf_STACKED;
9169         return newBINOP(OP_NULL, flags, op_lvalue(scalar(left), OP_SASSIGN),
9170                 scalar(right));
9171     }
9172     else {
9173         o = newBINOP(OP_SASSIGN, flags,
9174             scalar(right), op_lvalue(scalar(left), OP_SASSIGN) );
9175     }
9176     return o;
9177 }
9178
9179 /*
9180 =for apidoc newSTATEOP
9181
9182 Constructs a state op (COP).  The state op is normally a C<nextstate> op,
9183 but will be a C<dbstate> op if debugging is enabled for currently-compiled
9184 code.  The state op is populated from C<PL_curcop> (or C<PL_compiling>).
9185 If C<label> is non-null, it supplies the name of a label to attach to
9186 the state op; this function takes ownership of the memory pointed at by
9187 C<label>, and will free it.  C<flags> gives the eight bits of C<op_flags>
9188 for the state op.
9189
9190 If C<o> is null, the state op is returned.  Otherwise the state op is
9191 combined with C<o> into a C<lineseq> list op, which is returned.  C<o>
9192 is consumed by this function and becomes part of the returned op tree.
9193
9194 =cut
9195 */
9196
9197 OP *
9198 Perl_newSTATEOP(pTHX_ I32 flags, char *label, OP *o)
9199 {
9200     dVAR;
9201     const U32 seq = intro_my();
9202     const U32 utf8 = flags & SVf_UTF8;
9203     COP *cop;
9204
9205     PL_parser->parsed_sub = 0;
9206
9207     flags &= ~SVf_UTF8;
9208
9209     NewOp(1101, cop, 1, COP);
9210     if (PERLDB_LINE && CopLINE(PL_curcop) && PL_curstash != PL_debstash) {
9211         OpTYPE_set(cop, OP_DBSTATE);
9212     }
9213     else {
9214         OpTYPE_set(cop, OP_NEXTSTATE);
9215     }
9216     cop->op_flags = (U8)flags;
9217     CopHINTS_set(cop, PL_hints);
9218 #ifdef VMS
9219     if (VMSISH_HUSHED) cop->op_private |= OPpHUSH_VMSISH;
9220 #endif
9221     cop->op_next = (OP*)cop;
9222
9223     cop->cop_seq = seq;
9224     cop->cop_warnings = DUP_WARNINGS(PL_curcop->cop_warnings);
9225     CopHINTHASH_set(cop, cophh_copy(CopHINTHASH_get(PL_curcop)));
9226     if (label) {
9227         Perl_cop_store_label(aTHX_ cop, label, strlen(label), utf8);
9228
9229         PL_hints |= HINT_BLOCK_SCOPE;
9230         /* It seems that we need to defer freeing this pointer, as other parts
9231            of the grammar end up wanting to copy it after this op has been
9232            created. */
9233         SAVEFREEPV(label);
9234     }
9235
9236     if (PL_parser->preambling != NOLINE) {
9237         CopLINE_set(cop, PL_parser->preambling);
9238         PL_parser->copline = NOLINE;
9239     }
9240     else if (PL_parser->copline == NOLINE)
9241         CopLINE_set(cop, CopLINE(PL_curcop));
9242     else {
9243         CopLINE_set(cop, PL_parser->copline);
9244         PL_parser->copline = NOLINE;
9245     }
9246 #ifdef USE_ITHREADS
9247     CopFILE_set(cop, CopFILE(PL_curcop));       /* XXX share in a pvtable? */
9248 #else
9249     CopFILEGV_set(cop, CopFILEGV(PL_curcop));
9250 #endif
9251     CopSTASH_set(cop, PL_curstash);
9252
9253     if (cop->op_type == OP_DBSTATE) {
9254         /* this line can have a breakpoint - store the cop in IV */
9255         AV *av = CopFILEAVx(PL_curcop);
9256         if (av) {
9257             SV * const * const svp = av_fetch(av, CopLINE(cop), FALSE);
9258             if (svp && *svp != &PL_sv_undef ) {
9259                 (void)SvIOK_on(*svp);
9260                 SvIV_set(*svp, PTR2IV(cop));
9261             }
9262         }
9263     }
9264
9265     if (flags & OPf_SPECIAL)
9266         op_null((OP*)cop);
9267     return op_prepend_elem(OP_LINESEQ, (OP*)cop, o);
9268 }
9269
9270 /*
9271 =for apidoc newLOGOP
9272
9273 Constructs, checks, and returns a logical (flow control) op.  C<type>
9274 is the opcode.  C<flags> gives the eight bits of C<op_flags>, except
9275 that C<OPf_KIDS> will be set automatically, and, shifted up eight bits,
9276 the eight bits of C<op_private>, except that the bit with value 1 is
9277 automatically set.  C<first> supplies the expression controlling the
9278 flow, and C<other> supplies the side (alternate) chain of ops; they are
9279 consumed by this function and become part of the constructed op tree.
9280
9281 =cut
9282 */
9283
9284 OP *
9285 Perl_newLOGOP(pTHX_ I32 type, I32 flags, OP *first, OP *other)
9286 {
9287     PERL_ARGS_ASSERT_NEWLOGOP;
9288
9289     return new_logop(type, flags, &first, &other);
9290 }
9291
9292
9293 /* See if the optree o contains a single OP_CONST (plus possibly
9294  * surrounding enter/nextstate/null etc). If so, return it, else return
9295  * NULL.
9296  */
9297
9298 STATIC OP *
9299 S_search_const(pTHX_ OP *o)
9300 {
9301     PERL_ARGS_ASSERT_SEARCH_CONST;
9302
9303   redo:
9304     switch (o->op_type) {
9305         case OP_CONST:
9306             return o;
9307         case OP_NULL:
9308             if (o->op_flags & OPf_KIDS) {
9309                 o = cUNOPo->op_first;
9310                 goto redo;
9311             }
9312             break;
9313         case OP_LEAVE:
9314         case OP_SCOPE:
9315         case OP_LINESEQ:
9316         {
9317             OP *kid;
9318             if (!(o->op_flags & OPf_KIDS))
9319                 return NULL;
9320             kid = cLISTOPo->op_first;
9321
9322             do {
9323                 switch (kid->op_type) {
9324                     case OP_ENTER:
9325                     case OP_NULL:
9326                     case OP_NEXTSTATE:
9327                         kid = OpSIBLING(kid);
9328                         break;
9329                     default:
9330                         if (kid != cLISTOPo->op_last)
9331                             return NULL;
9332                         goto last;
9333                 }
9334             } while (kid);
9335
9336             if (!kid)
9337                 kid = cLISTOPo->op_last;
9338           last:
9339              o = kid;
9340              goto redo;
9341         }
9342     }
9343
9344     return NULL;
9345 }
9346
9347
9348 STATIC OP *
9349 S_new_logop(pTHX_ I32 type, I32 flags, OP** firstp, OP** otherp)
9350 {
9351     dVAR;
9352     LOGOP *logop;
9353     OP *o;
9354     OP *first;
9355     OP *other;
9356     OP *cstop = NULL;
9357     int prepend_not = 0;
9358
9359     PERL_ARGS_ASSERT_NEW_LOGOP;
9360
9361     first = *firstp;
9362     other = *otherp;
9363
9364     /* [perl #59802]: Warn about things like "return $a or $b", which
9365        is parsed as "(return $a) or $b" rather than "return ($a or
9366        $b)".  NB: This also applies to xor, which is why we do it
9367        here.
9368      */
9369     switch (first->op_type) {
9370     case OP_NEXT:
9371     case OP_LAST:
9372     case OP_REDO:
9373         /* XXX: Perhaps we should emit a stronger warning for these.
9374            Even with the high-precedence operator they don't seem to do
9375            anything sensible.
9376
9377            But until we do, fall through here.
9378          */
9379     case OP_RETURN:
9380     case OP_EXIT:
9381     case OP_DIE:
9382     case OP_GOTO:
9383         /* XXX: Currently we allow people to "shoot themselves in the
9384            foot" by explicitly writing "(return $a) or $b".
9385
9386            Warn unless we are looking at the result from folding or if
9387            the programmer explicitly grouped the operators like this.
9388            The former can occur with e.g.
9389
9390                 use constant FEATURE => ( $] >= ... );
9391                 sub { not FEATURE and return or do_stuff(); }
9392          */
9393         if (!first->op_folded && !(first->op_flags & OPf_PARENS))
9394             Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX),
9395                            "Possible precedence issue with control flow operator");
9396         /* XXX: Should we optimze this to "return $a;" (i.e. remove
9397            the "or $b" part)?
9398         */
9399         break;
9400     }
9401
9402     if (type == OP_XOR)         /* Not short circuit, but here by precedence. */
9403         return newBINOP(type, flags, scalar(first), scalar(other));
9404
9405     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_LOGOP
9406         || type == OP_CUSTOM);
9407
9408     scalarboolean(first);
9409
9410     /* search for a constant op that could let us fold the test */
9411     if ((cstop = search_const(first))) {
9412         if (cstop->op_private & OPpCONST_STRICT)
9413             no_bareword_allowed(cstop);
9414         else if ((cstop->op_private & OPpCONST_BARE))
9415                 Perl_ck_warner(aTHX_ packWARN(WARN_BAREWORD), "Bareword found in conditional");
9416         if ((type == OP_AND &&  SvTRUE(((SVOP*)cstop)->op_sv)) ||
9417             (type == OP_OR  && !SvTRUE(((SVOP*)cstop)->op_sv)) ||
9418             (type == OP_DOR && !SvOK(((SVOP*)cstop)->op_sv))) {
9419             /* Elide the (constant) lhs, since it can't affect the outcome */
9420             *firstp = NULL;
9421             if (other->op_type == OP_CONST)
9422                 other->op_private |= OPpCONST_SHORTCIRCUIT;
9423             op_free(first);
9424             if (other->op_type == OP_LEAVE)
9425                 other = newUNOP(OP_NULL, OPf_SPECIAL, other);
9426             else if (other->op_type == OP_MATCH
9427                   || other->op_type == OP_SUBST
9428                   || other->op_type == OP_TRANSR
9429                   || other->op_type == OP_TRANS)
9430                 /* Mark the op as being unbindable with =~ */
9431                 other->op_flags |= OPf_SPECIAL;
9432
9433             other->op_folded = 1;
9434             return other;
9435         }
9436         else {
9437             /* Elide the rhs, since the outcome is entirely determined by
9438              * the (constant) lhs */
9439
9440             /* check for C<my $x if 0>, or C<my($x,$y) if 0> */
9441             const OP *o2 = other;
9442             if ( ! (o2->op_type == OP_LIST
9443                     && (( o2 = cUNOPx(o2)->op_first))
9444                     && o2->op_type == OP_PUSHMARK
9445                     && (( o2 = OpSIBLING(o2))) )
9446             )
9447                 o2 = other;
9448             if ((o2->op_type == OP_PADSV || o2->op_type == OP_PADAV
9449                         || o2->op_type == OP_PADHV)
9450                 && o2->op_private & OPpLVAL_INTRO
9451                 && !(o2->op_private & OPpPAD_STATE))
9452             {
9453         Perl_croak(aTHX_ "This use of my() in false conditional is "
9454                           "no longer allowed");
9455             }
9456
9457             *otherp = NULL;
9458             if (cstop->op_type == OP_CONST)
9459                 cstop->op_private |= OPpCONST_SHORTCIRCUIT;
9460             op_free(other);
9461             return first;
9462         }
9463     }
9464     else if ((first->op_flags & OPf_KIDS) && type != OP_DOR
9465         && ckWARN(WARN_MISC)) /* [#24076] Don't warn for <FH> err FOO. */
9466     {
9467         const OP * const k1 = ((UNOP*)first)->op_first;
9468         const OP * const k2 = OpSIBLING(k1);
9469         OPCODE warnop = 0;
9470         switch (first->op_type)
9471         {
9472         case OP_NULL:
9473             if (k2 && k2->op_type == OP_READLINE
9474                   && (k2->op_flags & OPf_STACKED)
9475                   && ((k1->op_flags & OPf_WANT) == OPf_WANT_SCALAR))
9476             {
9477                 warnop = k2->op_type;
9478             }
9479             break;
9480
9481         case OP_SASSIGN:
9482             if (k1->op_type == OP_READDIR
9483                   || k1->op_type == OP_GLOB
9484                   || (k1->op_type == OP_NULL && k1->op_targ == OP_GLOB)
9485                  || k1->op_type == OP_EACH
9486                  || k1->op_type == OP_AEACH)
9487             {
9488                 warnop = ((k1->op_type == OP_NULL)
9489                           ? (OPCODE)k1->op_targ : k1->op_type);
9490             }
9491             break;
9492         }
9493         if (warnop) {
9494             const line_t oldline = CopLINE(PL_curcop);
9495             /* This ensures that warnings are reported at the first line
9496                of the construction, not the last.  */
9497             CopLINE_set(PL_curcop, PL_parser->copline);
9498             Perl_warner(aTHX_ packWARN(WARN_MISC),
9499                  "Value of %s%s can be \"0\"; test with defined()",
9500                  PL_op_desc[warnop],
9501                  ((warnop == OP_READLINE || warnop == OP_GLOB)
9502                   ? " construct" : "() operator"));
9503             CopLINE_set(PL_curcop, oldline);
9504         }
9505     }
9506
9507     /* optimize AND and OR ops that have NOTs as children */
9508     if (first->op_type == OP_NOT
9509         && (first->op_flags & OPf_KIDS)
9510         && ((first->op_flags & OPf_SPECIAL) /* unless ($x) { } */
9511             || (other->op_type == OP_NOT))  /* if (!$x && !$y) { } */
9512         ) {
9513         if (type == OP_AND || type == OP_OR) {
9514             if (type == OP_AND)
9515                 type = OP_OR;
9516             else
9517                 type = OP_AND;
9518             op_null(first);
9519             if (other->op_type == OP_NOT) { /* !a AND|OR !b => !(a OR|AND b) */
9520                 op_null(other);
9521                 prepend_not = 1; /* prepend a NOT op later */
9522             }
9523         }
9524     }
9525
9526     logop = alloc_LOGOP(type, first, LINKLIST(other));
9527     logop->op_flags |= (U8)flags;
9528     logop->op_private = (U8)(1 | (flags >> 8));
9529
9530     /* establish postfix order */
9531     logop->op_next = LINKLIST(first);
9532     first->op_next = (OP*)logop;
9533     assert(!OpHAS_SIBLING(first));
9534     op_sibling_splice((OP*)logop, first, 0, other);
9535
9536     CHECKOP(type,logop);
9537
9538     o = newUNOP(prepend_not ? OP_NOT : OP_NULL,
9539                 PL_opargs[type] & OA_RETSCALAR ? OPf_WANT_SCALAR : 0,
9540                 (OP*)logop);
9541     other->op_next = o;
9542
9543     return o;
9544 }
9545
9546 /*
9547 =for apidoc newCONDOP
9548
9549 Constructs, checks, and returns a conditional-expression (C<cond_expr>)
9550 op.  C<flags> gives the eight bits of C<op_flags>, except that C<OPf_KIDS>
9551 will be set automatically, and, shifted up eight bits, the eight bits of
9552 C<op_private>, except that the bit with value 1 is automatically set.
9553 C<first> supplies the expression selecting between the two branches,
9554 and C<trueop> and C<falseop> supply the branches; they are consumed by
9555 this function and become part of the constructed op tree.
9556
9557 =cut
9558 */
9559
9560 OP *
9561 Perl_newCONDOP(pTHX_ I32 flags, OP *first, OP *trueop, OP *falseop)
9562 {
9563     dVAR;
9564     LOGOP *logop;
9565     OP *start;
9566     OP *o;
9567     OP *cstop;
9568
9569     PERL_ARGS_ASSERT_NEWCONDOP;
9570
9571     if (!falseop)
9572         return newLOGOP(OP_AND, 0, first, trueop);
9573     if (!trueop)
9574         return newLOGOP(OP_OR, 0, first, falseop);
9575
9576     scalarboolean(first);
9577     if ((cstop = search_const(first))) {
9578         /* Left or right arm of the conditional?  */
9579         const bool left = SvTRUE(((SVOP*)cstop)->op_sv);
9580         OP *live = left ? trueop : falseop;
9581         OP *const dead = left ? falseop : trueop;
9582         if (cstop->op_private & OPpCONST_BARE &&
9583             cstop->op_private & OPpCONST_STRICT) {
9584             no_bareword_allowed(cstop);
9585         }
9586         op_free(first);
9587         op_free(dead);
9588         if (live->op_type == OP_LEAVE)
9589             live = newUNOP(OP_NULL, OPf_SPECIAL, live);
9590         else if (live->op_type == OP_MATCH || live->op_type == OP_SUBST
9591               || live->op_type == OP_TRANS || live->op_type == OP_TRANSR)
9592             /* Mark the op as being unbindable with =~ */
9593             live->op_flags |= OPf_SPECIAL;
9594         live->op_folded = 1;
9595         return live;
9596     }
9597     logop = alloc_LOGOP(OP_COND_EXPR, first, LINKLIST(trueop));
9598     logop->op_flags |= (U8)flags;
9599     logop->op_private = (U8)(1 | (flags >> 8));
9600     logop->op_next = LINKLIST(falseop);
9601
9602     CHECKOP(OP_COND_EXPR, /* that's logop->op_type */
9603             logop);
9604
9605     /* establish postfix order */
9606     start = LINKLIST(first);
9607     first->op_next = (OP*)logop;
9608
9609     /* make first, trueop, falseop siblings */
9610     op_sibling_splice((OP*)logop, first,  0, trueop);
9611     op_sibling_splice((OP*)logop, trueop, 0, falseop);
9612
9613     o = newUNOP(OP_NULL, 0, (OP*)logop);
9614
9615     trueop->op_next = falseop->op_next = o;
9616
9617     o->op_next = start;
9618     return o;
9619 }
9620
9621 /*
9622 =for apidoc newRANGE
9623
9624 Constructs and returns a C<range> op, with subordinate C<flip> and
9625 C<flop> ops.  C<flags> gives the eight bits of C<op_flags> for the
9626 C<flip> op and, shifted up eight bits, the eight bits of C<op_private>
9627 for both the C<flip> and C<range> ops, except that the bit with value
9628 1 is automatically set.  C<left> and C<right> supply the expressions
9629 controlling the endpoints of the range; they are consumed by this function
9630 and become part of the constructed op tree.
9631
9632 =cut
9633 */
9634
9635 OP *
9636 Perl_newRANGE(pTHX_ I32 flags, OP *left, OP *right)
9637 {
9638     LOGOP *range;
9639     OP *flip;
9640     OP *flop;
9641     OP *leftstart;
9642     OP *o;
9643
9644     PERL_ARGS_ASSERT_NEWRANGE;
9645
9646     range = alloc_LOGOP(OP_RANGE, left, LINKLIST(right));
9647     range->op_flags = OPf_KIDS;
9648     leftstart = LINKLIST(left);
9649     range->op_private = (U8)(1 | (flags >> 8));
9650
9651     /* make left and right siblings */
9652     op_sibling_splice((OP*)range, left, 0, right);
9653
9654     range->op_next = (OP*)range;
9655     flip = newUNOP(OP_FLIP, flags, (OP*)range);
9656     flop = newUNOP(OP_FLOP, 0, flip);
9657     o = newUNOP(OP_NULL, 0, flop);
9658     LINKLIST(flop);
9659     range->op_next = leftstart;
9660
9661     left->op_next = flip;
9662     right->op_next = flop;
9663
9664     range->op_targ =
9665         pad_add_name_pvn("$", 1, padadd_NO_DUP_CHECK|padadd_STATE, 0, 0);
9666     sv_upgrade(PAD_SV(range->op_targ), SVt_PVNV);
9667     flip->op_targ =
9668         pad_add_name_pvn("$", 1, padadd_NO_DUP_CHECK|padadd_STATE, 0, 0);;
9669     sv_upgrade(PAD_SV(flip->op_targ), SVt_PVNV);
9670     SvPADTMP_on(PAD_SV(flip->op_targ));
9671
9672     flip->op_private =  left->op_type == OP_CONST ? OPpFLIP_LINENUM : 0;
9673     flop->op_private = right->op_type == OP_CONST ? OPpFLIP_LINENUM : 0;
9674
9675     /* check barewords before they might be optimized aways */
9676     if (flip->op_private && cSVOPx(left)->op_private & OPpCONST_STRICT)
9677         no_bareword_allowed(left);
9678     if (flop->op_private && cSVOPx(right)->op_private & OPpCONST_STRICT)
9679         no_bareword_allowed(right);
9680
9681     flip->op_next = o;
9682     if (!flip->op_private || !flop->op_private)
9683         LINKLIST(o);            /* blow off optimizer unless constant */
9684
9685     return o;
9686 }
9687
9688 /*
9689 =for apidoc newLOOPOP
9690
9691 Constructs, checks, and returns an op tree expressing a loop.  This is
9692 only a loop in the control flow through the op tree; it does not have
9693 the heavyweight loop structure that allows exiting the loop by C<last>
9694 and suchlike.  C<flags> gives the eight bits of C<op_flags> for the
9695 top-level op, except that some bits will be set automatically as required.
9696 C<expr> supplies the expression controlling loop iteration, and C<block>
9697 supplies the body of the loop; they are consumed by this function and
9698 become part of the constructed op tree.  C<debuggable> is currently
9699 unused and should always be 1.
9700
9701 =cut
9702 */
9703
9704 OP *
9705 Perl_newLOOPOP(pTHX_ I32 flags, I32 debuggable, OP *expr, OP *block)
9706 {
9707     OP* listop;
9708     OP* o;
9709     const bool once = block && block->op_flags & OPf_SPECIAL &&
9710                       block->op_type == OP_NULL;
9711
9712     PERL_UNUSED_ARG(debuggable);
9713
9714     if (expr) {
9715         if (once && (
9716               (expr->op_type == OP_CONST && !SvTRUE(((SVOP*)expr)->op_sv))
9717            || (  expr->op_type == OP_NOT
9718               && cUNOPx(expr)->op_first->op_type == OP_CONST
9719               && SvTRUE(cSVOPx_sv(cUNOPx(expr)->op_first))
9720               )
9721            ))
9722             /* Return the block now, so that S_new_logop does not try to
9723                fold it away. */
9724         {
9725             op_free(expr);
9726             return block;       /* do {} while 0 does once */
9727         }
9728
9729         if (expr->op_type == OP_READLINE
9730             || expr->op_type == OP_READDIR
9731             || expr->op_type == OP_GLOB
9732             || expr->op_type == OP_EACH || expr->op_type == OP_AEACH
9733             || (expr->op_type == OP_NULL && expr->op_targ == OP_GLOB)) {
9734             expr = newUNOP(OP_DEFINED, 0,
9735                 newASSIGNOP(0, newDEFSVOP(), 0, expr) );
9736         } else if (expr->op_flags & OPf_KIDS) {
9737             const OP * const k1 = ((UNOP*)expr)->op_first;
9738             const OP * const k2 = k1 ? OpSIBLING(k1) : NULL;
9739             switch (expr->op_type) {
9740               case OP_NULL:
9741                 if (k2 && (k2->op_type == OP_READLINE || k2->op_type == OP_READDIR)
9742                       && (k2->op_flags & OPf_STACKED)
9743                       && ((k1->op_flags & OPf_WANT) == OPf_WANT_SCALAR))
9744                     expr = newUNOP(OP_DEFINED, 0, expr);
9745                 break;
9746
9747               case OP_SASSIGN:
9748                 if (k1 && (k1->op_type == OP_READDIR
9749                       || k1->op_type == OP_GLOB
9750                       || (k1->op_type == OP_NULL && k1->op_targ == OP_GLOB)
9751                      || k1->op_type == OP_EACH
9752                      || k1->op_type == OP_AEACH))
9753                     expr = newUNOP(OP_DEFINED, 0, expr);
9754                 break;
9755             }
9756         }
9757     }
9758
9759     /* if block is null, the next op_append_elem() would put UNSTACK, a scalar
9760      * op, in listop. This is wrong. [perl #27024] */
9761     if (!block)
9762         block = newOP(OP_NULL, 0);
9763     listop = op_append_elem(OP_LINESEQ, block, newOP(OP_UNSTACK, 0));
9764     o = new_logop(OP_AND, 0, &expr, &listop);
9765
9766     if (once) {
9767         ASSUME(listop);
9768     }
9769
9770     if (listop)
9771         ((LISTOP*)listop)->op_last->op_next = LINKLIST(o);
9772
9773     if (once && o != listop)
9774     {
9775         assert(cUNOPo->op_first->op_type == OP_AND
9776             || cUNOPo->op_first->op_type == OP_OR);
9777         o->op_next = ((LOGOP*)cUNOPo->op_first)->op_other;
9778     }
9779
9780     if (o == listop)
9781         o = newUNOP(OP_NULL, 0, o);     /* or do {} while 1 loses outer block */
9782
9783     o->op_flags |= flags;
9784     o = op_scope(o);
9785     o->op_flags |= OPf_SPECIAL; /* suppress cx_popblock() curpm restoration*/
9786     return o;
9787 }
9788
9789 /*
9790 =for apidoc newWHILEOP
9791
9792 Constructs, checks, and returns an op tree expressing a C<while> loop.
9793 This is a heavyweight loop, with structure that allows exiting the loop
9794 by C<last> and suchlike.
9795
9796 C<loop> is an optional preconstructed C<enterloop> op to use in the
9797 loop; if it is null then a suitable op will be constructed automatically.
9798 C<expr> supplies the loop's controlling expression.  C<block> supplies the
9799 main body of the loop, and C<cont> optionally supplies a C<continue> block
9800 that operates as a second half of the body.  All of these optree inputs
9801 are consumed by this function and become part of the constructed op tree.
9802
9803 C<flags> gives the eight bits of C<op_flags> for the C<leaveloop>
9804 op and, shifted up eight bits, the eight bits of C<op_private> for
9805 the C<leaveloop> op, except that (in both cases) some bits will be set
9806 automatically.  C<debuggable> is currently unused and should always be 1.
9807 C<has_my> can be supplied as true to force the
9808 loop body to be enclosed in its own scope.
9809
9810 =cut
9811 */
9812
9813 OP *
9814 Perl_newWHILEOP(pTHX_ I32 flags, I32 debuggable, LOOP *loop,
9815         OP *expr, OP *block, OP *cont, I32 has_my)
9816 {
9817     dVAR;
9818     OP *redo;
9819     OP *next = NULL;
9820     OP *listop;
9821     OP *o;
9822     U8 loopflags = 0;
9823
9824     PERL_UNUSED_ARG(debuggable);
9825
9826     if (expr) {
9827         if (expr->op_type == OP_READLINE
9828          || expr->op_type == OP_READDIR
9829          || expr->op_type == OP_GLOB
9830          || expr->op_type == OP_EACH || expr->op_type == OP_AEACH
9831                      || (expr->op_type == OP_NULL && expr->op_targ == OP_GLOB)) {
9832             expr = newUNOP(OP_DEFINED, 0,
9833                 newASSIGNOP(0, newDEFSVOP(), 0, expr) );
9834         } else if (expr->op_flags & OPf_KIDS) {
9835             const OP * const k1 = ((UNOP*)expr)->op_first;
9836             const OP * const k2 = (k1) ? OpSIBLING(k1) : NULL;
9837             switch (expr->op_type) {
9838               case OP_NULL:
9839                 if (k2 && (k2->op_type == OP_READLINE || k2->op_type == OP_READDIR)
9840                       && (k2->op_flags & OPf_STACKED)
9841                       && ((k1->op_flags & OPf_WANT) == OPf_WANT_SCALAR))
9842                     expr = newUNOP(OP_DEFINED, 0, expr);
9843                 break;
9844
9845               case OP_SASSIGN:
9846                 if (k1 && (k1->op_type == OP_READDIR
9847                       || k1->op_type == OP_GLOB
9848                       || (k1->op_type == OP_NULL && k1->op_targ == OP_GLOB)
9849                      || k1->op_type == OP_EACH
9850                      || k1->op_type == OP_AEACH))
9851                     expr = newUNOP(OP_DEFINED, 0, expr);
9852                 break;
9853             }
9854         }
9855     }
9856
9857     if (!block)
9858         block = newOP(OP_NULL, 0);
9859     else if (cont || has_my) {
9860         block = op_scope(block);
9861     }
9862
9863     if (cont) {
9864         next = LINKLIST(cont);
9865     }
9866     if (expr) {
9867         OP * const unstack = newOP(OP_UNSTACK, 0);
9868         if (!next)
9869             next = unstack;
9870         cont = op_append_elem(OP_LINESEQ, cont, unstack);
9871     }
9872
9873     assert(block);
9874     listop = op_append_list(OP_LINESEQ, block, cont);
9875     assert(listop);
9876     redo = LINKLIST(listop);
9877
9878     if (expr) {
9879         scalar(listop);
9880         o = new_logop(OP_AND, 0, &expr, &listop);
9881         if (o == expr && o->op_type == OP_CONST && !SvTRUE(cSVOPo->op_sv)) {
9882             op_free((OP*)loop);
9883             return expr;                /* listop already freed by new_logop */
9884         }
9885         if (listop)
9886             ((LISTOP*)listop)->op_last->op_next =
9887                 (o == listop ? redo : LINKLIST(o));
9888     }
9889     else
9890         o = listop;
9891
9892     if (!loop) {
9893         NewOp(1101,loop,1,LOOP);
9894         OpTYPE_set(loop, OP_ENTERLOOP);
9895         loop->op_private = 0;
9896         loop->op_next = (OP*)loop;
9897     }
9898
9899     o = newBINOP(OP_LEAVELOOP, 0, (OP*)loop, o);
9900
9901     loop->op_redoop = redo;
9902     loop->op_lastop = o;
9903     o->op_private |= loopflags;
9904
9905     if (next)
9906         loop->op_nextop = next;
9907     else
9908         loop->op_nextop = o;
9909
9910     o->op_flags |= flags;
9911     o->op_private |= (flags >> 8);
9912     return o;
9913 }
9914
9915 /*
9916 =for apidoc newFOROP
9917
9918 Constructs, checks, and returns an op tree expressing a C<foreach>
9919 loop (iteration through a list of values).  This is a heavyweight loop,
9920 with structure that allows exiting the loop by C<last> and suchlike.
9921
9922 C<sv> optionally supplies the variable that will be aliased to each
9923 item in turn; if null, it defaults to C<$_>.
9924 C<expr> supplies the list of values to iterate over.  C<block> supplies
9925 the main body of the loop, and C<cont> optionally supplies a C<continue>
9926 block that operates as a second half of the body.  All of these optree
9927 inputs are consumed by this function and become part of the constructed
9928 op tree.
9929
9930 C<flags> gives the eight bits of C<op_flags> for the C<leaveloop>
9931 op and, shifted up eight bits, the eight bits of C<op_private> for
9932 the C<leaveloop> op, except that (in both cases) some bits will be set
9933 automatically.
9934
9935 =cut
9936 */
9937
9938 OP *
9939 Perl_newFOROP(pTHX_ I32 flags, OP *sv, OP *expr, OP *block, OP *cont)
9940 {
9941     dVAR;
9942     LOOP *loop;
9943     OP *wop;
9944     PADOFFSET padoff = 0;
9945     I32 iterflags = 0;
9946     I32 iterpflags = 0;
9947
9948     PERL_ARGS_ASSERT_NEWFOROP;
9949
9950     if (sv) {
9951         if (sv->op_type == OP_RV2SV) {  /* symbol table variable */
9952             iterpflags = sv->op_private & OPpOUR_INTRO; /* for our $x () */
9953             OpTYPE_set(sv, OP_RV2GV);
9954
9955             /* The op_type check is needed to prevent a possible segfault
9956              * if the loop variable is undeclared and 'strict vars' is in
9957              * effect. This is illegal but is nonetheless parsed, so we
9958              * may reach this point with an OP_CONST where we're expecting
9959              * an OP_GV.
9960              */
9961             if (cUNOPx(sv)->op_first->op_type == OP_GV
9962              && cGVOPx_gv(cUNOPx(sv)->op_first) == PL_defgv)
9963                 iterpflags |= OPpITER_DEF;
9964         }
9965         else if (sv->op_type == OP_PADSV) { /* private variable */
9966             iterpflags = sv->op_private & OPpLVAL_INTRO; /* for my $x () */
9967             padoff = sv->op_targ;
9968             sv->op_targ = 0;
9969             op_free(sv);
9970             sv = NULL;
9971             PAD_COMPNAME_GEN_set(padoff, PERL_INT_MAX);
9972         }
9973         else if (sv->op_type == OP_NULL && sv->op_targ == OP_SREFGEN)
9974             NOOP;
9975         else
9976             Perl_croak(aTHX_ "Can't use %s for loop variable", PL_op_desc[sv->op_type]);
9977         if (padoff) {
9978             PADNAME * const pn = PAD_COMPNAME(padoff);
9979             const char * const name = PadnamePV(pn);
9980
9981             if (PadnameLEN(pn) == 2 && name[0] == '$' && name[1] == '_')
9982                 iterpflags |= OPpITER_DEF;
9983         }
9984     }
9985     else {
9986         sv = newGVOP(OP_GV, 0, PL_defgv);
9987         iterpflags |= OPpITER_DEF;
9988     }
9989
9990     if (expr->op_type == OP_RV2AV || expr->op_type == OP_PADAV) {
9991         expr = op_lvalue(force_list(scalar(ref(expr, OP_ITER)), 1), OP_GREPSTART);
9992         iterflags |= OPf_STACKED;
9993     }
9994     else if (expr->op_type == OP_NULL &&
9995              (expr->op_flags & OPf_KIDS) &&
9996              ((BINOP*)expr)->op_first->op_type == OP_FLOP)
9997     {
9998         /* Basically turn for($x..$y) into the same as for($x,$y), but we
9999          * set the STACKED flag to indicate that these values are to be
10000          * treated as min/max values by 'pp_enteriter'.
10001          */
10002         const UNOP* const flip = (UNOP*)((UNOP*)((BINOP*)expr)->op_first)->op_first;
10003         LOGOP* const range = (LOGOP*) flip->op_first;
10004         OP* const left  = range->op_first;
10005         OP* const right = OpSIBLING(left);
10006         LISTOP* listop;
10007
10008         range->op_flags &= ~OPf_KIDS;
10009         /* detach range's children */
10010         op_sibling_splice((OP*)range, NULL, -1, NULL);
10011
10012         listop = (LISTOP*)newLISTOP(OP_LIST, 0, left, right);
10013         listop->op_first->op_next = range->op_next;
10014         left->op_next = range->op_other;
10015         right->op_next = (OP*)listop;
10016         listop->op_next = listop->op_first;
10017
10018         op_free(expr);
10019         expr = (OP*)(listop);
10020         op_null(expr);
10021         iterflags |= OPf_STACKED;
10022     }
10023     else {
10024         expr = op_lvalue(force_list(expr, 1), OP_GREPSTART);
10025     }
10026
10027     loop = (LOOP*)op_convert_list(OP_ENTERITER, iterflags,
10028                                   op_append_elem(OP_LIST, list(expr),
10029                                                  scalar(sv)));
10030     assert(!loop->op_next);
10031     /* for my  $x () sets OPpLVAL_INTRO;
10032      * for our $x () sets OPpOUR_INTRO */
10033     loop->op_private = (U8)iterpflags;
10034
10035     /* upgrade loop from a LISTOP to a LOOPOP;
10036      * keep it in-place if there's space */
10037     if (loop->op_slabbed
10038         &&    OpSLOT(loop)->opslot_size
10039             < SIZE_TO_PSIZE(sizeof(LOOP)) + OPSLOT_HEADER_P)
10040     {
10041         /* no space; allocate new op */
10042         LOOP *tmp;
10043         NewOp(1234,tmp,1,LOOP);
10044         Copy(loop,tmp,1,LISTOP);
10045         assert(loop->op_last->op_sibparent == (OP*)loop);
10046         OpLASTSIB_set(loop->op_last, (OP*)tmp); /*point back to new parent */
10047         S_op_destroy(aTHX_ (OP*)loop);
10048         loop = tmp;
10049     }
10050     else if (!loop->op_slabbed)
10051     {
10052         /* loop was malloc()ed */
10053         loop = (LOOP*)PerlMemShared_realloc(loop, sizeof(LOOP));
10054         OpLASTSIB_set(loop->op_last, (OP*)loop);
10055     }
10056     loop->op_targ = padoff;
10057     wop = newWHILEOP(flags, 1, loop, newOP(OP_ITER, 0), block, cont, 0);
10058     return wop;
10059 }
10060
10061 /*
10062 =for apidoc newLOOPEX
10063
10064 Constructs, checks, and returns a loop-exiting op (such as C<goto>
10065 or C<last>).  C<type> is the opcode.  C<label> supplies the parameter
10066 determining the target of the op; it is consumed by this function and
10067 becomes part of the constructed op tree.
10068
10069 =cut
10070 */
10071
10072 OP*
10073 Perl_newLOOPEX(pTHX_ I32 type, OP *label)
10074 {
10075     OP *o = NULL;
10076
10077     PERL_ARGS_ASSERT_NEWLOOPEX;
10078
10079     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_LOOPEXOP
10080         || type == OP_CUSTOM);
10081
10082     if (type != OP_GOTO) {
10083         /* "last()" means "last" */
10084         if (label->op_type == OP_STUB && (label->op_flags & OPf_PARENS)) {
10085             o = newOP(type, OPf_SPECIAL);
10086         }
10087     }
10088     else {
10089         /* Check whether it's going to be a goto &function */
10090         if (label->op_type == OP_ENTERSUB
10091                 && !(label->op_flags & OPf_STACKED))
10092             label = newUNOP(OP_REFGEN, 0, op_lvalue(label, OP_REFGEN));
10093     }
10094
10095     /* Check for a constant argument */
10096     if (label->op_type == OP_CONST) {
10097             SV * const sv = ((SVOP *)label)->op_sv;
10098             STRLEN l;
10099             const char *s = SvPV_const(sv,l);
10100             if (l == strlen(s)) {
10101                 o = newPVOP(type,
10102                             SvUTF8(((SVOP*)label)->op_sv),
10103                             savesharedpv(
10104                                 SvPV_nolen_const(((SVOP*)label)->op_sv)));
10105             }
10106     }
10107
10108     /* If we have already created an op, we do not need the label. */
10109     if (o)
10110                 op_free(label);
10111     else o = newUNOP(type, OPf_STACKED, label);
10112
10113     PL_hints |= HINT_BLOCK_SCOPE;
10114     return o;
10115 }
10116
10117 /* if the condition is a literal array or hash
10118    (or @{ ... } etc), make a reference to it.
10119  */
10120 STATIC OP *
10121 S_ref_array_or_hash(pTHX_ OP *cond)
10122 {
10123     if (cond
10124     && (cond->op_type == OP_RV2AV
10125     ||  cond->op_type == OP_PADAV
10126     ||  cond->op_type == OP_RV2HV
10127     ||  cond->op_type == OP_PADHV))
10128
10129         return newUNOP(OP_REFGEN, 0, op_lvalue(cond, OP_REFGEN));
10130
10131     else if(cond
10132     && (cond->op_type == OP_ASLICE
10133     ||  cond->op_type == OP_KVASLICE
10134     ||  cond->op_type == OP_HSLICE
10135     ||  cond->op_type == OP_KVHSLICE)) {
10136
10137         /* anonlist now needs a list from this op, was previously used in
10138          * scalar context */
10139         cond->op_flags &= ~(OPf_WANT_SCALAR | OPf_REF);
10140         cond->op_flags |= OPf_WANT_LIST;
10141
10142         return newANONLIST(op_lvalue(cond, OP_ANONLIST));
10143     }
10144
10145     else
10146         return cond;
10147 }
10148
10149 /* These construct the optree fragments representing given()
10150    and when() blocks.
10151
10152    entergiven and enterwhen are LOGOPs; the op_other pointer
10153    points up to the associated leave op. We need this so we
10154    can put it in the context and make break/continue work.
10155    (Also, of course, pp_enterwhen will jump straight to
10156    op_other if the match fails.)
10157  */
10158
10159 STATIC OP *
10160 S_newGIVWHENOP(pTHX_ OP *cond, OP *block,
10161                    I32 enter_opcode, I32 leave_opcode,
10162                    PADOFFSET entertarg)
10163 {
10164     dVAR;
10165     LOGOP *enterop;
10166     OP *o;
10167
10168     PERL_ARGS_ASSERT_NEWGIVWHENOP;
10169     PERL_UNUSED_ARG(entertarg); /* used to indicate targ of lexical $_ */
10170
10171     enterop = alloc_LOGOP(enter_opcode, block, NULL);
10172     enterop->op_targ = 0;
10173     enterop->op_private = 0;
10174
10175     o = newUNOP(leave_opcode, 0, (OP *) enterop);
10176
10177     if (cond) {
10178         /* prepend cond if we have one */
10179         op_sibling_splice((OP*)enterop, NULL, 0, scalar(cond));
10180
10181         o->op_next = LINKLIST(cond);
10182         cond->op_next = (OP *) enterop;
10183     }
10184     else {
10185         /* This is a default {} block */
10186         enterop->op_flags |= OPf_SPECIAL;
10187         o      ->op_flags |= OPf_SPECIAL;
10188
10189         o->op_next = (OP *) enterop;
10190     }
10191
10192     CHECKOP(enter_opcode, enterop); /* Currently does nothing, since
10193                                        entergiven and enterwhen both
10194                                        use ck_null() */
10195
10196     enterop->op_next = LINKLIST(block);
10197     block->op_next = enterop->op_other = o;
10198
10199     return o;
10200 }
10201
10202
10203 /* For the purposes of 'when(implied_smartmatch)'
10204  *              versus 'when(boolean_expression)',
10205  * does this look like a boolean operation? For these purposes
10206    a boolean operation is:
10207      - a subroutine call [*]
10208      - a logical connective
10209      - a comparison operator
10210      - a filetest operator, with the exception of -s -M -A -C
10211      - defined(), exists() or eof()
10212      - /$re/ or $foo =~ /$re/
10213
10214    [*] possibly surprising
10215  */
10216 STATIC bool
10217 S_looks_like_bool(pTHX_ const OP *o)
10218 {
10219     PERL_ARGS_ASSERT_LOOKS_LIKE_BOOL;
10220
10221     switch(o->op_type) {
10222         case OP_OR:
10223         case OP_DOR:
10224             return looks_like_bool(cLOGOPo->op_first);
10225
10226         case OP_AND:
10227         {
10228             OP* sibl = OpSIBLING(cLOGOPo->op_first);
10229             ASSUME(sibl);
10230             return (
10231                 looks_like_bool(cLOGOPo->op_first)
10232              && looks_like_bool(sibl));
10233         }
10234
10235         case OP_NULL:
10236         case OP_SCALAR:
10237             return (
10238                 o->op_flags & OPf_KIDS
10239             && looks_like_bool(cUNOPo->op_first));
10240
10241         case OP_ENTERSUB:
10242
10243         case OP_NOT:    case OP_XOR:
10244
10245         case OP_EQ:     case OP_NE:     case OP_LT:
10246         case OP_GT:     case OP_LE:     case OP_GE:
10247
10248         case OP_I_EQ:   case OP_I_NE:   case OP_I_LT:
10249         case OP_I_GT:   case OP_I_LE:   case OP_I_GE:
10250
10251         case OP_SEQ:    case OP_SNE:    case OP_SLT:
10252         case OP_SGT:    case OP_SLE:    case OP_SGE:
10253
10254         case OP_SMARTMATCH:
10255
10256         case OP_FTRREAD:  case OP_FTRWRITE: case OP_FTREXEC:
10257         case OP_FTEREAD:  case OP_FTEWRITE: case OP_FTEEXEC:
10258         case OP_FTIS:     case OP_FTEOWNED: case OP_FTROWNED:
10259         case OP_FTZERO:   case OP_FTSOCK:   case OP_FTCHR:
10260         case OP_FTBLK:    case OP_FTFILE:   case OP_FTDIR:
10261         case OP_FTPIPE:   case OP_FTLINK:   case OP_FTSUID:
10262         case OP_FTSGID:   case OP_FTSVTX:   case OP_FTTTY:
10263         case OP_FTTEXT:   case OP_FTBINARY:
10264
10265         case OP_DEFINED: case OP_EXISTS:
10266         case OP_MATCH:   case OP_EOF:
10267
10268         case OP_FLOP:
10269
10270             return TRUE;
10271
10272         case OP_INDEX:
10273         case OP_RINDEX:
10274             /* optimised-away (index() != -1) or similar comparison */
10275             if (o->op_private & OPpTRUEBOOL)
10276                 return TRUE;
10277             return FALSE;
10278
10279         case OP_CONST:
10280             /* Detect comparisons that have been optimized away */
10281             if (cSVOPo->op_sv == &PL_sv_yes
10282             ||  cSVOPo->op_sv == &PL_sv_no)
10283
10284                 return TRUE;
10285             else
10286                 return FALSE;
10287         /* FALLTHROUGH */
10288         default:
10289             return FALSE;
10290     }
10291 }
10292
10293
10294 /*
10295 =for apidoc newGIVENOP
10296
10297 Constructs, checks, and returns an op tree expressing a C<given> block.
10298 C<cond> supplies the expression to whose value C<$_> will be locally
10299 aliased, and C<block> supplies the body of the C<given> construct; they
10300 are consumed by this function and become part of the constructed op tree.
10301 C<defsv_off> must be zero (it used to identity the pad slot of lexical $_).
10302
10303 =cut
10304 */
10305
10306 OP *
10307 Perl_newGIVENOP(pTHX_ OP *cond, OP *block, PADOFFSET defsv_off)
10308 {
10309     PERL_ARGS_ASSERT_NEWGIVENOP;
10310     PERL_UNUSED_ARG(defsv_off);
10311
10312     assert(!defsv_off);
10313     return newGIVWHENOP(
10314         ref_array_or_hash(cond),
10315         block,
10316         OP_ENTERGIVEN, OP_LEAVEGIVEN,
10317         0);
10318 }
10319
10320 /*
10321 =for apidoc newWHENOP
10322
10323 Constructs, checks, and returns an op tree expressing a C<when> block.
10324 C<cond> supplies the test expression, and C<block> supplies the block
10325 that will be executed if the test evaluates to true; they are consumed
10326 by this function and become part of the constructed op tree.  C<cond>
10327 will be interpreted DWIMically, often as a comparison against C<$_>,
10328 and may be null to generate a C<default> block.
10329
10330 =cut
10331 */
10332
10333 OP *
10334 Perl_newWHENOP(pTHX_ OP *cond, OP *block)
10335 {
10336     const bool cond_llb = (!cond || looks_like_bool(cond));
10337     OP *cond_op;
10338
10339     PERL_ARGS_ASSERT_NEWWHENOP;
10340
10341     if (cond_llb)
10342         cond_op = cond;
10343     else {
10344         cond_op = newBINOP(OP_SMARTMATCH, OPf_SPECIAL,
10345                 newDEFSVOP(),
10346                 scalar(ref_array_or_hash(cond)));
10347     }
10348
10349     return newGIVWHENOP(cond_op, block, OP_ENTERWHEN, OP_LEAVEWHEN, 0);
10350 }
10351
10352 /* must not conflict with SVf_UTF8 */
10353 #define CV_CKPROTO_CURSTASH     0x1
10354
10355 void
10356 Perl_cv_ckproto_len_flags(pTHX_ const CV *cv, const GV *gv, const char *p,
10357                     const STRLEN len, const U32 flags)
10358 {
10359     SV *name = NULL, *msg;
10360     const char * cvp = SvROK(cv)
10361                         ? SvTYPE(SvRV_const(cv)) == SVt_PVCV
10362                            ? (cv = (const CV *)SvRV_const(cv), CvPROTO(cv))
10363                            : ""
10364                         : CvPROTO(cv);
10365     STRLEN clen = CvPROTOLEN(cv), plen = len;
10366
10367     PERL_ARGS_ASSERT_CV_CKPROTO_LEN_FLAGS;
10368
10369     if (p == NULL && cvp == NULL)
10370         return;
10371
10372     if (!ckWARN_d(WARN_PROTOTYPE))
10373         return;
10374
10375     if (p && cvp) {
10376         p = S_strip_spaces(aTHX_ p, &plen);
10377         cvp = S_strip_spaces(aTHX_ cvp, &clen);
10378         if ((flags & SVf_UTF8) == SvUTF8(cv)) {
10379             if (plen == clen && memEQ(cvp, p, plen))
10380                 return;
10381         } else {
10382             if (flags & SVf_UTF8) {
10383                 if (bytes_cmp_utf8((const U8 *)cvp, clen, (const U8 *)p, plen) == 0)
10384                     return;
10385             }
10386             else {
10387                 if (bytes_cmp_utf8((const U8 *)p, plen, (const U8 *)cvp, clen) == 0)
10388                     return;
10389             }
10390         }
10391     }
10392
10393     msg = sv_newmortal();
10394
10395     if (gv)
10396     {
10397         if (isGV(gv))
10398             gv_efullname3(name = sv_newmortal(), gv, NULL);
10399         else if (SvPOK(gv) && *SvPVX((SV *)gv) == '&')
10400             name = newSVpvn_flags(SvPVX((SV *)gv)+1, SvCUR(gv)-1, SvUTF8(gv)|SVs_TEMP);
10401         else if (flags & CV_CKPROTO_CURSTASH || SvROK(gv)) {
10402             name = sv_2mortal(newSVhek(HvNAME_HEK(PL_curstash)));
10403             sv_catpvs(name, "::");
10404             if (SvROK(gv)) {
10405                 assert (SvTYPE(SvRV_const(gv)) == SVt_PVCV);
10406                 assert (CvNAMED(SvRV_const(gv)));
10407                 sv_cathek(name, CvNAME_HEK(MUTABLE_CV(SvRV_const(gv))));
10408             }
10409             else sv_catsv(name, (SV *)gv);
10410         }
10411         else name = (SV *)gv;
10412     }
10413     sv_setpvs(msg, "Prototype mismatch:");
10414     if (name)
10415         Perl_sv_catpvf(aTHX_ msg, " sub %" SVf, SVfARG(name));
10416     if (cvp)
10417         Perl_sv_catpvf(aTHX_ msg, " (%" UTF8f ")",
10418             UTF8fARG(SvUTF8(cv),clen,cvp)
10419         );
10420     else
10421         sv_catpvs(msg, ": none");
10422     sv_catpvs(msg, " vs ");
10423     if (p)
10424         Perl_sv_catpvf(aTHX_ msg, "(%" UTF8f ")", UTF8fARG(flags & SVf_UTF8,len,p));
10425     else
10426         sv_catpvs(msg, "none");
10427     Perl_warner(aTHX_ packWARN(WARN_PROTOTYPE), "%" SVf, SVfARG(msg));
10428 }
10429
10430 static void const_sv_xsub(pTHX_ CV* cv);
10431 static void const_av_xsub(pTHX_ CV* cv);
10432
10433 /*
10434
10435 =head1 Optree Manipulation Functions
10436
10437 =for apidoc cv_const_sv
10438
10439 If C<cv> is a constant sub eligible for inlining, returns the constant
10440 value returned by the sub.  Otherwise, returns C<NULL>.
10441
10442 Constant subs can be created with C<newCONSTSUB> or as described in
10443 L<perlsub/"Constant Functions">.
10444
10445 =cut
10446 */
10447 SV *
10448 Perl_cv_const_sv(const CV *const cv)
10449 {
10450     SV *sv;
10451     if (!cv)
10452         return NULL;
10453     if (!(SvTYPE(cv) == SVt_PVCV || SvTYPE(cv) == SVt_PVFM))
10454         return NULL;
10455     sv = CvCONST(cv) ? MUTABLE_SV(CvXSUBANY(cv).any_ptr) : NULL;
10456     if (sv && SvTYPE(sv) == SVt_PVAV) return NULL;
10457     return sv;
10458 }
10459
10460 SV *
10461 Perl_cv_const_sv_or_av(const CV * const cv)
10462 {
10463     if (!cv)
10464         return NULL;
10465     if (SvROK(cv)) return SvRV((SV *)cv);
10466     assert (SvTYPE(cv) == SVt_PVCV || SvTYPE(cv) == SVt_PVFM);
10467     return CvCONST(cv) ? MUTABLE_SV(CvXSUBANY(cv).any_ptr) : NULL;
10468 }
10469
10470 /* op_const_sv:  examine an optree to determine whether it's in-lineable.
10471  * Can be called in 2 ways:
10472  *
10473  * !allow_lex
10474  *      look for a single OP_CONST with attached value: return the value
10475  *
10476  * allow_lex && !CvCONST(cv);
10477  *
10478  *      examine the clone prototype, and if contains only a single
10479  *      OP_CONST, return the value; or if it contains a single PADSV ref-
10480  *      erencing an outer lexical, turn on CvCONST to indicate the CV is
10481  *      a candidate for "constizing" at clone time, and return NULL.
10482  */
10483
10484 static SV *
10485 S_op_const_sv(pTHX_ const OP *o, CV *cv, bool allow_lex)
10486 {
10487     SV *sv = NULL;
10488     bool padsv = FALSE;
10489
10490     assert(o);
10491     assert(cv);
10492
10493     for (; o; o = o->op_next) {
10494         const OPCODE type = o->op_type;
10495
10496         if (type == OP_NEXTSTATE || type == OP_LINESEQ
10497              || type == OP_NULL
10498              || type == OP_PUSHMARK)
10499                 continue;
10500         if (type == OP_DBSTATE)
10501                 continue;
10502         if (type == OP_LEAVESUB)
10503             break;
10504         if (sv)
10505             return NULL;
10506         if (type == OP_CONST && cSVOPo->op_sv)
10507             sv = cSVOPo->op_sv;
10508         else if (type == OP_UNDEF && !o->op_private) {
10509             sv = newSV(0);
10510             SAVEFREESV(sv);
10511         }
10512         else if (allow_lex && type == OP_PADSV) {
10513                 if (PAD_COMPNAME_FLAGS(o->op_targ) & PADNAMEt_OUTER)
10514                 {
10515                     sv = &PL_sv_undef; /* an arbitrary non-null value */
10516                     padsv = TRUE;
10517                 }
10518                 else
10519                     return NULL;
10520         }
10521         else {
10522             return NULL;
10523         }
10524     }
10525     if (padsv) {
10526         CvCONST_on(cv);
10527         return NULL;
10528     }
10529     return sv;
10530 }
10531
10532 static void
10533 S_already_defined(pTHX_ CV *const cv, OP * const block, OP * const o,
10534                         PADNAME * const name, SV ** const const_svp)
10535 {
10536     assert (cv);
10537     assert (o || name);
10538     assert (const_svp);
10539     if (!block) {
10540         if (CvFLAGS(PL_compcv)) {
10541             /* might have had built-in attrs applied */
10542             const bool pureperl = !CvISXSUB(cv) && CvROOT(cv);
10543             if (CvLVALUE(PL_compcv) && ! CvLVALUE(cv) && pureperl
10544              && ckWARN(WARN_MISC))
10545             {
10546                 /* protect against fatal warnings leaking compcv */
10547                 SAVEFREESV(PL_compcv);
10548                 Perl_warner(aTHX_ packWARN(WARN_MISC), "lvalue attribute ignored after the subroutine has been defined");
10549                 SvREFCNT_inc_simple_void_NN(PL_compcv);
10550             }
10551             CvFLAGS(cv) |=
10552                 (CvFLAGS(PL_compcv) & CVf_BUILTIN_ATTRS
10553                   & ~(CVf_LVALUE * pureperl));
10554         }
10555         return;
10556     }
10557
10558     /* redundant check for speed: */
10559     if (CvCONST(cv) || ckWARN(WARN_REDEFINE)) {
10560         const line_t oldline = CopLINE(PL_curcop);
10561         SV *namesv = o
10562             ? cSVOPo->op_sv
10563             : sv_2mortal(newSVpvn_utf8(
10564                 PadnamePV(name)+1,PadnameLEN(name)-1, PadnameUTF8(name)
10565               ));
10566         if (PL_parser && PL_parser->copline != NOLINE)
10567             /* This ensures that warnings are reported at the first
10568                line of a redefinition, not the last.  */
10569             CopLINE_set(PL_curcop, PL_parser->copline);
10570         /* protect against fatal warnings leaking compcv */
10571         SAVEFREESV(PL_compcv);
10572         report_redefined_cv(namesv, cv, const_svp);
10573         SvREFCNT_inc_simple_void_NN(PL_compcv);
10574         CopLINE_set(PL_curcop, oldline);
10575     }
10576     SAVEFREESV(cv);
10577     return;
10578 }
10579
10580 CV *
10581 Perl_newMYSUB(pTHX_ I32 floor, OP *o, OP *proto, OP *attrs, OP *block)
10582 {
10583     CV **spot;
10584     SV **svspot;
10585     const char *ps;
10586     STRLEN ps_len = 0; /* init it to avoid false uninit warning from icc */
10587     U32 ps_utf8 = 0;
10588     CV *cv = NULL;
10589     CV *compcv = PL_compcv;
10590     SV *const_sv;
10591     PADNAME *name;
10592     PADOFFSET pax = o->op_targ;
10593     CV *outcv = CvOUTSIDE(PL_compcv);
10594     CV *clonee = NULL;
10595     HEK *hek = NULL;
10596     bool reusable = FALSE;
10597     OP *start = NULL;
10598 #ifdef PERL_DEBUG_READONLY_OPS
10599     OPSLAB *slab = NULL;
10600 #endif
10601
10602     PERL_ARGS_ASSERT_NEWMYSUB;
10603
10604     PL_hints |= HINT_BLOCK_SCOPE;
10605
10606     /* Find the pad slot for storing the new sub.
10607        We cannot use PL_comppad, as it is the pad owned by the new sub.  We
10608        need to look in CvOUTSIDE and find the pad belonging to the enclos-
10609        ing sub.  And then we need to dig deeper if this is a lexical from
10610        outside, as in:
10611            my sub foo; sub { sub foo { } }
10612      */
10613   redo:
10614     name = PadlistNAMESARRAY(CvPADLIST(outcv))[pax];
10615     if (PadnameOUTER(name) && PARENT_PAD_INDEX(name)) {
10616         pax = PARENT_PAD_INDEX(name);
10617         outcv = CvOUTSIDE(outcv);
10618         assert(outcv);
10619         goto redo;
10620     }
10621     svspot =
10622         &PadARRAY(PadlistARRAY(CvPADLIST(outcv))
10623                         [CvDEPTH(outcv) ? CvDEPTH(outcv) : 1])[pax];
10624     spot = (CV **)svspot;
10625
10626     if (!(PL_parser && PL_parser->error_count))
10627         move_proto_attr(&proto, &attrs, (GV *)PadnameSV(name), 0);
10628
10629     if (proto) {
10630         assert(proto->op_type == OP_CONST);
10631         ps = SvPV_const(((SVOP*)proto)->op_sv, ps_len);
10632         ps_utf8 = SvUTF8(((SVOP*)proto)->op_sv);
10633     }
10634     else
10635         ps = NULL;
10636
10637     if (proto)
10638         SAVEFREEOP(proto);
10639     if (attrs)
10640         SAVEFREEOP(attrs);
10641
10642     if (PL_parser && PL_parser->error_count) {
10643         op_free(block);
10644         SvREFCNT_dec(PL_compcv);
10645         PL_compcv = 0;
10646         goto done;
10647     }
10648
10649     if (CvDEPTH(outcv) && CvCLONE(compcv)) {
10650         cv = *spot;
10651         svspot = (SV **)(spot = &clonee);
10652     }
10653     else if (PadnameIsSTATE(name) || CvDEPTH(outcv))
10654         cv = *spot;
10655     else {
10656         assert (SvTYPE(*spot) == SVt_PVCV);
10657         if (CvNAMED(*spot))
10658             hek = CvNAME_HEK(*spot);
10659         else {
10660             dVAR;
10661             U32 hash;
10662             PERL_HASH(hash, PadnamePV(name)+1, PadnameLEN(name)-1);
10663             CvNAME_HEK_set(*spot, hek =
10664                 share_hek(
10665                     PadnamePV(name)+1,
10666                     (PadnameLEN(name)-1) * (PadnameUTF8(name) ? -1 : 1),
10667                     hash
10668                 )
10669             );
10670             CvLEXICAL_on(*spot);
10671         }
10672         cv = PadnamePROTOCV(name);
10673         svspot = (SV **)(spot = &PadnamePROTOCV(name));
10674     }
10675
10676     if (block) {
10677         /* This makes sub {}; work as expected.  */
10678         if (block->op_type == OP_STUB) {
10679             const line_t l = PL_parser->copline;
10680             op_free(block);
10681             block = newSTATEOP(0, NULL, 0);
10682             PL_parser->copline = l;
10683         }
10684         block = CvLVALUE(compcv)
10685              || (cv && CvLVALUE(cv) && !CvROOT(cv) && !CvXSUB(cv))
10686                    ? newUNOP(OP_LEAVESUBLV, 0,
10687                              op_lvalue(scalarseq(block), OP_LEAVESUBLV))
10688                    : newUNOP(OP_LEAVESUB, 0, scalarseq(block));
10689         start = LINKLIST(block);
10690         block->op_next = 0;
10691         if (ps && !*ps && !attrs && !CvLVALUE(compcv))
10692             const_sv = S_op_const_sv(aTHX_ start, compcv, FALSE);
10693         else
10694             const_sv = NULL;
10695     }
10696     else
10697         const_sv = NULL;
10698
10699     if (cv) {
10700         const bool exists = CvROOT(cv) || CvXSUB(cv);
10701
10702         /* if the subroutine doesn't exist and wasn't pre-declared
10703          * with a prototype, assume it will be AUTOLOADed,
10704          * skipping the prototype check
10705          */
10706         if (exists || SvPOK(cv))
10707             cv_ckproto_len_flags(cv, (GV *)PadnameSV(name), ps, ps_len,
10708                                  ps_utf8);
10709         /* already defined? */
10710         if (exists) {
10711             S_already_defined(aTHX_ cv, block, NULL, name, &const_sv);
10712             if (block)
10713                 cv = NULL;
10714             else {
10715                 if (attrs)
10716                     goto attrs;
10717                 /* just a "sub foo;" when &foo is already defined */
10718                 SAVEFREESV(compcv);
10719                 goto done;
10720             }
10721         }
10722         else if (CvDEPTH(outcv) && CvCLONE(compcv)) {
10723             cv = NULL;
10724             reusable = TRUE;
10725         }
10726     }
10727
10728     if (const_sv) {
10729         SvREFCNT_inc_simple_void_NN(const_sv);
10730         SvFLAGS(const_sv) |= SVs_PADTMP;
10731         if (cv) {
10732             assert(!CvROOT(cv) && !CvCONST(cv));
10733             cv_forget_slab(cv);
10734         }
10735         else {
10736             cv = MUTABLE_CV(newSV_type(SVt_PVCV));
10737             CvFILE_set_from_cop(cv, PL_curcop);
10738             CvSTASH_set(cv, PL_curstash);
10739             *spot = cv;
10740         }
10741         SvPVCLEAR(MUTABLE_SV(cv));  /* prototype is "" */
10742         CvXSUBANY(cv).any_ptr = const_sv;
10743         CvXSUB(cv) = const_sv_xsub;
10744         CvCONST_on(cv);
10745         CvISXSUB_on(cv);
10746         PoisonPADLIST(cv);
10747         CvFLAGS(cv) |= CvMETHOD(compcv);
10748         op_free(block);
10749         SvREFCNT_dec(compcv);
10750         PL_compcv = NULL;
10751         goto setname;
10752     }
10753
10754     /* Checking whether outcv is CvOUTSIDE(compcv) is not sufficient to
10755        determine whether this sub definition is in the same scope as its
10756        declaration.  If this sub definition is inside an inner named pack-
10757        age sub (my sub foo; sub bar { sub foo { ... } }), outcv points to
10758        the package sub.  So check PadnameOUTER(name) too.
10759      */
10760     if (outcv == CvOUTSIDE(compcv) && !PadnameOUTER(name)) {
10761         assert(!CvWEAKOUTSIDE(compcv));
10762         SvREFCNT_dec(CvOUTSIDE(compcv));
10763         CvWEAKOUTSIDE_on(compcv);
10764     }
10765     /* XXX else do we have a circular reference? */
10766
10767     if (cv) {   /* must reuse cv in case stub is referenced elsewhere */
10768         /* transfer PL_compcv to cv */
10769         if (block) {
10770             bool free_file = CvFILE(cv) && CvDYNFILE(cv);
10771             cv_flags_t preserved_flags =
10772                 CvFLAGS(cv) & (CVf_BUILTIN_ATTRS|CVf_NAMED);
10773             PADLIST *const temp_padl = CvPADLIST(cv);
10774             CV *const temp_cv = CvOUTSIDE(cv);
10775             const cv_flags_t other_flags =
10776                 CvFLAGS(cv) & (CVf_SLABBED|CVf_WEAKOUTSIDE);
10777             OP * const cvstart = CvSTART(cv);
10778
10779             SvPOK_off(cv);
10780             CvFLAGS(cv) =
10781                 CvFLAGS(compcv) | preserved_flags;
10782             CvOUTSIDE(cv) = CvOUTSIDE(compcv);
10783             CvOUTSIDE_SEQ(cv) = CvOUTSIDE_SEQ(compcv);
10784             CvPADLIST_set(cv, CvPADLIST(compcv));
10785             CvOUTSIDE(compcv) = temp_cv;
10786             CvPADLIST_set(compcv, temp_padl);
10787             CvSTART(cv) = CvSTART(compcv);
10788             CvSTART(compcv) = cvstart;
10789             CvFLAGS(compcv) &= ~(CVf_SLABBED|CVf_WEAKOUTSIDE);
10790             CvFLAGS(compcv) |= other_flags;
10791
10792             if (free_file) {
10793                 Safefree(CvFILE(cv));
10794                 CvFILE(cv) = NULL;
10795             }
10796
10797             /* inner references to compcv must be fixed up ... */
10798             pad_fixup_inner_anons(CvPADLIST(cv), compcv, cv);
10799             if (PERLDB_INTER)/* Advice debugger on the new sub. */
10800                 ++PL_sub_generation;
10801         }
10802         else {
10803             /* Might have had built-in attributes applied -- propagate them. */
10804             CvFLAGS(cv) |= (CvFLAGS(compcv) & CVf_BUILTIN_ATTRS);
10805         }
10806         /* ... before we throw it away */
10807         SvREFCNT_dec(compcv);
10808         PL_compcv = compcv = cv;
10809     }
10810     else {
10811         cv = compcv;
10812         *spot = cv;
10813     }
10814
10815   setname:
10816     CvLEXICAL_on(cv);
10817     if (!CvNAME_HEK(cv)) {
10818         if (hek) (void)share_hek_hek(hek);
10819         else {
10820             dVAR;
10821             U32 hash;
10822             PERL_HASH(hash, PadnamePV(name)+1, PadnameLEN(name)-1);
10823             hek = share_hek(PadnamePV(name)+1,
10824                       (PadnameLEN(name)-1) * (PadnameUTF8(name) ? -1 : 1),
10825                       hash);
10826         }
10827         CvNAME_HEK_set(cv, hek);
10828     }
10829
10830     if (const_sv)
10831         goto clone;
10832
10833     if (CvFILE(cv) && CvDYNFILE(cv))
10834         Safefree(CvFILE(cv));
10835     CvFILE_set_from_cop(cv, PL_curcop);
10836     CvSTASH_set(cv, PL_curstash);
10837
10838     if (ps) {
10839         sv_setpvn(MUTABLE_SV(cv), ps, ps_len);
10840         if (ps_utf8)
10841             SvUTF8_on(MUTABLE_SV(cv));
10842     }
10843
10844     if (block) {
10845         /* If we assign an optree to a PVCV, then we've defined a
10846          * subroutine that the debugger could be able to set a breakpoint
10847          * in, so signal to pp_entereval that it should not throw away any
10848          * saved lines at scope exit.  */
10849
10850         PL_breakable_sub_gen++;
10851         CvROOT(cv) = block;
10852         /* The cv no longer needs to hold a refcount on the slab, as CvROOT
10853            itself has a refcount. */
10854         CvSLABBED_off(cv);
10855         OpslabREFCNT_dec_padok((OPSLAB *)CvSTART(cv));
10856 #ifdef PERL_DEBUG_READONLY_OPS
10857         slab = (OPSLAB *)CvSTART(cv);
10858 #endif
10859         S_process_optree(aTHX_ cv, block, start);
10860     }
10861
10862   attrs:
10863     if (attrs) {
10864         /* Need to do a C<use attributes $stash_of_cv,\&cv,@attrs>. */
10865         apply_attrs(PL_curstash, MUTABLE_SV(cv), attrs);
10866     }
10867
10868     if (block) {
10869         if (PERLDB_SUBLINE && PL_curstash != PL_debstash) {
10870             SV * const tmpstr = sv_newmortal();
10871             GV * const db_postponed = gv_fetchpvs("DB::postponed",
10872                                                   GV_ADDMULTI, SVt_PVHV);
10873             HV *hv;
10874             SV * const sv = Perl_newSVpvf(aTHX_ "%s:%ld-%ld",
10875                                           CopFILE(PL_curcop),
10876                                           (long)PL_subline,
10877                                           (long)CopLINE(PL_curcop));
10878             if (HvNAME_HEK(PL_curstash)) {
10879                 sv_sethek(tmpstr, HvNAME_HEK(PL_curstash));
10880                 sv_catpvs(tmpstr, "::");
10881             }
10882             else
10883                 sv_setpvs(tmpstr, "__ANON__::");
10884
10885             sv_catpvn_flags(tmpstr, PadnamePV(name)+1, PadnameLEN(name)-1,
10886                             PadnameUTF8(name) ? SV_CATUTF8 : SV_CATBYTES);
10887             (void)hv_store(GvHV(PL_DBsub), SvPVX_const(tmpstr),
10888                     SvUTF8(tmpstr) ? -(I32)SvCUR(tmpstr) : (I32)SvCUR(tmpstr), sv, 0);
10889             hv = GvHVn(db_postponed);
10890             if (HvTOTALKEYS(hv) > 0 && hv_exists(hv, SvPVX_const(tmpstr), SvUTF8(tmpstr) ? -(I32)SvCUR(tmpstr) : (I32)SvCUR(tmpstr))) {
10891                 CV * const pcv = GvCV(db_postponed);
10892                 if (pcv) {
10893                     dSP;
10894                     PUSHMARK(SP);
10895                     XPUSHs(tmpstr);
10896                     PUTBACK;
10897                     call_sv(MUTABLE_SV(pcv), G_DISCARD);
10898                 }
10899             }
10900         }
10901     }
10902
10903   clone:
10904     if (clonee) {
10905         assert(CvDEPTH(outcv));
10906         spot = (CV **)
10907             &PadARRAY(PadlistARRAY(CvPADLIST(outcv))[CvDEPTH(outcv)])[pax];
10908         if (reusable)
10909             cv_clone_into(clonee, *spot);
10910         else *spot = cv_clone(clonee);
10911         SvREFCNT_dec_NN(clonee);
10912         cv = *spot;
10913     }
10914
10915     if (CvDEPTH(outcv) && !reusable && PadnameIsSTATE(name)) {
10916         PADOFFSET depth = CvDEPTH(outcv);
10917         while (--depth) {
10918             SV *oldcv;
10919             svspot = &PadARRAY(PadlistARRAY(CvPADLIST(outcv))[depth])[pax];
10920             oldcv = *svspot;
10921             *svspot = SvREFCNT_inc_simple_NN(cv);
10922             SvREFCNT_dec(oldcv);
10923         }
10924     }
10925
10926   done:
10927     if (PL_parser)
10928         PL_parser->copline = NOLINE;
10929     LEAVE_SCOPE(floor);
10930 #ifdef PERL_DEBUG_READONLY_OPS
10931     if (slab)
10932         Slab_to_ro(slab);
10933 #endif
10934     op_free(o);
10935     return cv;
10936 }
10937
10938 /*
10939 =for apidoc newATTRSUB_x
10940
10941 Construct a Perl subroutine, also performing some surrounding jobs.
10942
10943 This function is expected to be called in a Perl compilation context,
10944 and some aspects of the subroutine are taken from global variables
10945 associated with compilation.  In particular, C<PL_compcv> represents
10946 the subroutine that is currently being compiled.  It must be non-null
10947 when this function is called, and some aspects of the subroutine being
10948 constructed are taken from it.  The constructed subroutine may actually
10949 be a reuse of the C<PL_compcv> object, but will not necessarily be so.
10950
10951 If C<block> is null then the subroutine will have no body, and for the
10952 time being it will be an error to call it.  This represents a forward
10953 subroutine declaration such as S<C<sub foo ($$);>>.  If C<block> is
10954 non-null then it provides the Perl code of the subroutine body, which
10955 will be executed when the subroutine is called.  This body includes
10956 any argument unwrapping code resulting from a subroutine signature or
10957 similar.  The pad use of the code must correspond to the pad attached
10958 to C<PL_compcv>.  The code is not expected to include a C<leavesub> or
10959 C<leavesublv> op; this function will add such an op.  C<block> is consumed
10960 by this function and will become part of the constructed subroutine.
10961
10962 C<proto> specifies the subroutine's prototype, unless one is supplied
10963 as an attribute (see below).  If C<proto> is null, then the subroutine
10964 will not have a prototype.  If C<proto> is non-null, it must point to a
10965 C<const> op whose value is a string, and the subroutine will have that
10966 string as its prototype.  If a prototype is supplied as an attribute, the
10967 attribute takes precedence over C<proto>, but in that case C<proto> should
10968 preferably be null.  In any case, C<proto> is consumed by this function.
10969
10970 C<attrs> supplies attributes to be applied the subroutine.  A handful of
10971 attributes take effect by built-in means, being applied to C<PL_compcv>
10972 immediately when seen.  Other attributes are collected up and attached
10973 to the subroutine by this route.  C<attrs> may be null to supply no
10974 attributes, or point to a C<const> op for a single attribute, or point
10975 to a C<list> op whose children apart from the C<pushmark> are C<const>
10976 ops for one or more attributes.  Each C<const> op must be a string,
10977 giving the attribute name optionally followed by parenthesised arguments,
10978 in the manner in which attributes appear in Perl source.  The attributes
10979 will be applied to the sub by this function.  C<attrs> is consumed by
10980 this function.
10981
10982 If C<o_is_gv> is false and C<o> is null, then the subroutine will
10983 be anonymous.  If C<o_is_gv> is false and C<o> is non-null, then C<o>
10984 must point to a C<const> op, which will be consumed by this function,
10985 and its string value supplies a name for the subroutine.  The name may
10986 be qualified or unqualified, and if it is unqualified then a default
10987 stash will be selected in some manner.  If C<o_is_gv> is true, then C<o>
10988 doesn't point to an C<OP> at all, but is instead a cast pointer to a C<GV>
10989 by which the subroutine will be named.
10990
10991 If there is already a subroutine of the specified name, then the new
10992 sub will either replace the existing one in the glob or be merged with
10993 the existing one.  A warning may be generated about redefinition.
10994
10995 If the subroutine has one of a few special names, such as C<BEGIN> or
10996 C<END>, then it will be claimed by the appropriate queue for automatic
10997 running of phase-related subroutines.  In this case the relevant glob will
10998 be left not containing any subroutine, even if it did contain one before.
10999 In the case of C<BEGIN>, the subroutine will be executed and the reference
11000 to it disposed of before this function returns.
11001
11002 The function returns a pointer to the constructed subroutine.  If the sub
11003 is anonymous then ownership of one counted reference to the subroutine
11004 is transferred to the caller.  If the sub is named then the caller does
11005 not get ownership of a reference.  In most such cases, where the sub
11006 has a non-phase name, the sub will be alive at the point it is returned
11007 by virtue of being contained in the glob that names it.  A phase-named
11008 subroutine will usually be alive by virtue of the reference owned by the
11009 phase's automatic run queue.  But a C<BEGIN> subroutine, having already
11010 been executed, will quite likely have been destroyed already by the
11011 time this function returns, making it erroneous for the caller to make
11012 any use of the returned pointer.  It is the caller's responsibility to
11013 ensure that it knows which of these situations applies.
11014
11015 =cut
11016 */
11017
11018 /* _x = extended */
11019 CV *
11020 Perl_newATTRSUB_x(pTHX_ I32 floor, OP *o, OP *proto, OP *attrs,
11021                             OP *block, bool o_is_gv)
11022 {
11023     GV *gv;
11024     const char *ps;
11025     STRLEN ps_len = 0; /* init it to avoid false uninit warning from icc */
11026     U32 ps_utf8 = 0;
11027     CV *cv = NULL;     /* the previous CV with this name, if any */
11028     SV *const_sv;
11029     const bool ec = PL_parser && PL_parser->error_count;
11030     /* If the subroutine has no body, no attributes, and no builtin attributes
11031        then it's just a sub declaration, and we may be able to get away with
11032        storing with a placeholder scalar in the symbol table, rather than a
11033        full CV.  If anything is present then it will take a full CV to
11034        store it.  */
11035     const I32 gv_fetch_flags
11036         = ec ? GV_NOADD_NOINIT :
11037         (block || attrs || (CvFLAGS(PL_compcv) & CVf_BUILTIN_ATTRS))
11038         ? GV_ADDMULTI : GV_ADDMULTI | GV_NOINIT;
11039     STRLEN namlen = 0;
11040     const char * const name =
11041          o ? SvPV_const(o_is_gv ? (SV *)o : cSVOPo->op_sv, namlen) : NULL;
11042     bool has_name;
11043     bool name_is_utf8 = o && !o_is_gv && SvUTF8(cSVOPo->op_sv);
11044     bool evanescent = FALSE;
11045     OP *start = NULL;
11046 #ifdef PERL_DEBUG_READONLY_OPS
11047     OPSLAB *slab = NULL;
11048 #endif
11049
11050     if (o_is_gv) {
11051         gv = (GV*)o;
11052         o = NULL;
11053         has_name = TRUE;
11054     } else if (name) {
11055         /* Try to optimise and avoid creating a GV.  Instead, the CV’s name
11056            hek and CvSTASH pointer together can imply the GV.  If the name
11057            contains a package name, then GvSTASH(CvGV(cv)) may differ from
11058            CvSTASH, so forego the optimisation if we find any.
11059            Also, we may be called from load_module at run time, so
11060            PL_curstash (which sets CvSTASH) may not point to the stash the
11061            sub is stored in.  */
11062         /* XXX This optimization is currently disabled for packages other
11063                than main, since there was too much CPAN breakage.  */
11064         const I32 flags =
11065            ec ? GV_NOADD_NOINIT
11066               :   (IN_PERL_RUNTIME && PL_curstash != CopSTASH(PL_curcop))
11067                || PL_curstash != PL_defstash
11068                || memchr(name, ':', namlen) || memchr(name, '\'', namlen)
11069                     ? gv_fetch_flags
11070                     : GV_ADDMULTI | GV_NOINIT | GV_NOTQUAL;
11071         gv = gv_fetchsv(cSVOPo->op_sv, flags, SVt_PVCV);
11072         has_name = TRUE;
11073     } else if (PERLDB_NAMEANON && CopLINE(PL_curcop)) {
11074         SV * const sv = sv_newmortal();
11075         Perl_sv_setpvf(aTHX_ sv, "%s[%s:%" IVdf "]",
11076                        PL_curstash ? "__ANON__" : "__ANON__::__ANON__",
11077                        CopFILE(PL_curcop), (IV)CopLINE(PL_curcop));
11078         gv = gv_fetchsv(sv, gv_fetch_flags, SVt_PVCV);
11079         has_name = TRUE;
11080     } else if (PL_curstash) {
11081         gv = gv_fetchpvs("__ANON__", gv_fetch_flags, SVt_PVCV);
11082         has_name = FALSE;
11083     } else {
11084         gv = gv_fetchpvs("__ANON__::__ANON__", gv_fetch_flags, SVt_PVCV);
11085         has_name = FALSE;
11086     }
11087
11088     if (!ec) {
11089         if (isGV(gv)) {
11090             move_proto_attr(&proto, &attrs, gv, 0);
11091         } else {
11092             assert(cSVOPo);
11093             move_proto_attr(&proto, &attrs, (GV *)cSVOPo->op_sv, 1);
11094         }
11095     }
11096
11097     if (proto) {
11098         assert(proto->op_type == OP_CONST);
11099         ps = SvPV_const(((SVOP*)proto)->op_sv, ps_len);
11100         ps_utf8 = SvUTF8(((SVOP*)proto)->op_sv);
11101     }
11102     else
11103         ps = NULL;
11104
11105     if (o)
11106         SAVEFREEOP(o);
11107     if (proto)
11108         SAVEFREEOP(proto);
11109     if (attrs)
11110         SAVEFREEOP(attrs);
11111
11112     if (ec) {
11113         op_free(block);
11114
11115         if (name)
11116             SvREFCNT_dec(PL_compcv);
11117         else
11118             cv = PL_compcv;
11119
11120         PL_compcv = 0;
11121         if (name && block) {
11122             const char *s = (char *) my_memrchr(name, ':', namlen);
11123             s = s ? s+1 : name;
11124             if (strEQ(s, "BEGIN")) {
11125                 if (PL_in_eval & EVAL_KEEPERR)
11126                     Perl_croak_nocontext("BEGIN not safe after errors--compilation aborted");
11127                 else {
11128                     SV * const errsv = ERRSV;
11129                     /* force display of errors found but not reported */
11130                     sv_catpvs(errsv, "BEGIN not safe after errors--compilation aborted");
11131                     Perl_croak_nocontext("%" SVf, SVfARG(errsv));
11132                 }
11133             }
11134         }
11135         goto done;
11136     }
11137
11138     if (!block && SvTYPE(gv) != SVt_PVGV) {
11139         /* If we are not defining a new sub and the existing one is not a
11140            full GV + CV... */
11141         if (attrs || (CvFLAGS(PL_compcv) & CVf_BUILTIN_ATTRS)) {
11142             /* We are applying attributes to an existing sub, so we need it
11143                upgraded if it is a constant.  */
11144             if (SvROK(gv) && SvTYPE(SvRV(gv)) != SVt_PVCV)
11145                 gv_init_pvn(gv, PL_curstash, name, namlen,
11146                             SVf_UTF8 * name_is_utf8);
11147         }
11148         else {                  /* Maybe prototype now, and had at maximum
11149                                    a prototype or const/sub ref before.  */
11150             if (SvTYPE(gv) > SVt_NULL) {
11151                 cv_ckproto_len_flags((const CV *)gv,
11152                                     o ? (const GV *)cSVOPo->op_sv : NULL, ps,
11153                                     ps_len, ps_utf8);
11154             }
11155
11156             if (!SvROK(gv)) {
11157                 if (ps) {
11158                     sv_setpvn(MUTABLE_SV(gv), ps, ps_len);
11159                     if (ps_utf8)
11160                         SvUTF8_on(MUTABLE_SV(gv));
11161                 }
11162                 else
11163                     sv_setiv(MUTABLE_SV(gv), -1);
11164             }
11165
11166             SvREFCNT_dec(PL_compcv);
11167             cv = PL_compcv = NULL;
11168             goto done;
11169         }
11170     }
11171
11172     cv = (!name || (isGV(gv) && GvCVGEN(gv)))
11173         ? NULL
11174         : isGV(gv)
11175             ? GvCV(gv)
11176             : SvROK(gv) && SvTYPE(SvRV(gv)) == SVt_PVCV
11177                 ? (CV *)SvRV(gv)
11178                 : NULL;
11179
11180     if (block) {
11181         assert(PL_parser);
11182         /* This makes sub {}; work as expected.  */
11183         if (block->op_type == OP_STUB) {
11184             const line_t l = PL_parser->copline;
11185             op_free(block);
11186             block = newSTATEOP(0, NULL, 0);
11187             PL_parser->copline = l;
11188         }
11189         block = CvLVALUE(PL_compcv)
11190              || (cv && CvLVALUE(cv) && !CvROOT(cv) && !CvXSUB(cv)
11191                     && (!isGV(gv) || !GvASSUMECV(gv)))
11192                    ? newUNOP(OP_LEAVESUBLV, 0,
11193                              op_lvalue(scalarseq(block), OP_LEAVESUBLV))
11194                    : newUNOP(OP_LEAVESUB, 0, scalarseq(block));
11195         start = LINKLIST(block);
11196         block->op_next = 0;
11197         if (ps && !*ps && !attrs && !CvLVALUE(PL_compcv))
11198             const_sv =
11199                 S_op_const_sv(aTHX_ start, PL_compcv,
11200                                         cBOOL(CvCLONE(PL_compcv)));
11201         else
11202             const_sv = NULL;
11203     }
11204     else
11205         const_sv = NULL;
11206
11207     if (SvPOK(gv) || (SvROK(gv) && SvTYPE(SvRV(gv)) != SVt_PVCV)) {
11208         cv_ckproto_len_flags((const CV *)gv,
11209                              o ? (const GV *)cSVOPo->op_sv : NULL, ps,
11210                              ps_len, ps_utf8|CV_CKPROTO_CURSTASH);
11211         if (SvROK(gv)) {
11212             /* All the other code for sub redefinition warnings expects the
11213                clobbered sub to be a CV.  Instead of making all those code
11214                paths more complex, just inline the RV version here.  */
11215             const line_t oldline = CopLINE(PL_curcop);
11216             assert(IN_PERL_COMPILETIME);
11217             if (PL_parser && PL_parser->copline != NOLINE)
11218                 /* This ensures that warnings are reported at the first
11219                    line of a redefinition, not the last.  */
11220                 CopLINE_set(PL_curcop, PL_parser->copline);
11221             /* protect against fatal warnings leaking compcv */
11222             SAVEFREESV(PL_compcv);
11223
11224             if (ckWARN(WARN_REDEFINE)
11225              || (  ckWARN_d(WARN_REDEFINE)
11226                 && (  !const_sv || SvRV(gv) == const_sv
11227                    || sv_cmp(SvRV(gv), const_sv)  ))) {
11228                 assert(cSVOPo);
11229                 Perl_warner(aTHX_ packWARN(WARN_REDEFINE),
11230                           "Constant subroutine %" SVf " redefined",
11231                           SVfARG(cSVOPo->op_sv));
11232             }
11233
11234             SvREFCNT_inc_simple_void_NN(PL_compcv);
11235             CopLINE_set(PL_curcop, oldline);
11236             SvREFCNT_dec(SvRV(gv));
11237         }
11238     }
11239
11240     if (cv) {
11241         const bool exists = CvROOT(cv) || CvXSUB(cv);
11242
11243         /* if the subroutine doesn't exist and wasn't pre-declared
11244          * with a prototype, assume it will be AUTOLOADed,
11245          * skipping the prototype check
11246          */
11247         if (exists || SvPOK(cv))
11248             cv_ckproto_len_flags(cv, gv, ps, ps_len, ps_utf8);
11249         /* already defined (or promised)? */
11250         if (exists || (isGV(gv) && GvASSUMECV(gv))) {
11251             S_already_defined(aTHX_ cv, block, o, NULL, &const_sv);
11252             if (block)
11253                 cv = NULL;
11254             else {
11255                 if (attrs)
11256                     goto attrs;
11257                 /* just a "sub foo;" when &foo is already defined */
11258                 SAVEFREESV(PL_compcv);
11259                 goto done;
11260             }
11261         }
11262     }
11263
11264     if (const_sv) {
11265         SvREFCNT_inc_simple_void_NN(const_sv);
11266         SvFLAGS(const_sv) |= SVs_PADTMP;
11267         if (cv) {
11268             assert(!CvROOT(cv) && !CvCONST(cv));
11269             cv_forget_slab(cv);
11270             SvPVCLEAR(MUTABLE_SV(cv));  /* prototype is "" */
11271             CvXSUBANY(cv).any_ptr = const_sv;
11272             CvXSUB(cv) = const_sv_xsub;
11273             CvCONST_on(cv);
11274             CvISXSUB_on(cv);
11275             PoisonPADLIST(cv);
11276             CvFLAGS(cv) |= CvMETHOD(PL_compcv);
11277         }
11278         else {
11279             if (isGV(gv) || CvMETHOD(PL_compcv)) {
11280                 if (name && isGV(gv))
11281                     GvCV_set(gv, NULL);
11282                 cv = newCONSTSUB_flags(
11283                     NULL, name, namlen, name_is_utf8 ? SVf_UTF8 : 0,
11284                     const_sv
11285                 );
11286                 assert(cv);
11287                 assert(SvREFCNT((SV*)cv) != 0);
11288                 CvFLAGS(cv) |= CvMETHOD(PL_compcv);
11289             }
11290             else {
11291                 if (!SvROK(gv)) {
11292                     SV_CHECK_THINKFIRST_COW_DROP((SV *)gv);
11293                     prepare_SV_for_RV((SV *)gv);
11294                     SvOK_off((SV *)gv);
11295                     SvROK_on(gv);
11296                 }
11297                 SvRV_set(gv, const_sv);
11298             }
11299         }
11300         op_free(block);
11301         SvREFCNT_dec(PL_compcv);
11302         PL_compcv = NULL;
11303         goto done;
11304     }
11305
11306     /* don't copy new BEGIN CV to old BEGIN CV - RT #129099 */
11307     if (name && cv && *name == 'B' && strEQ(name, "BEGIN"))
11308         cv = NULL;
11309
11310     if (cv) {                           /* must reuse cv if autoloaded */
11311         /* transfer PL_compcv to cv */
11312         if (block) {
11313             bool free_file = CvFILE(cv) && CvDYNFILE(cv);
11314             cv_flags_t existing_builtin_attrs = CvFLAGS(cv) & CVf_BUILTIN_ATTRS;
11315             PADLIST *const temp_av = CvPADLIST(cv);
11316             CV *const temp_cv = CvOUTSIDE(cv);
11317             const cv_flags_t other_flags =
11318                 CvFLAGS(cv) & (CVf_SLABBED|CVf_WEAKOUTSIDE);
11319             OP * const cvstart = CvSTART(cv);
11320
11321             if (isGV(gv)) {
11322                 CvGV_set(cv,gv);
11323                 assert(!CvCVGV_RC(cv));
11324                 assert(CvGV(cv) == gv);
11325             }
11326             else {
11327                 dVAR;
11328                 U32 hash;
11329                 PERL_HASH(hash, name, namlen);
11330                 CvNAME_HEK_set(cv,
11331                                share_hek(name,
11332                                          name_is_utf8
11333                                             ? -(SSize_t)namlen
11334                                             :  (SSize_t)namlen,
11335                                          hash));
11336             }
11337
11338             SvPOK_off(cv);
11339             CvFLAGS(cv) = CvFLAGS(PL_compcv) | existing_builtin_attrs
11340                                              | CvNAMED(cv);
11341             CvOUTSIDE(cv) = CvOUTSIDE(PL_compcv);
11342             CvOUTSIDE_SEQ(cv) = CvOUTSIDE_SEQ(PL_compcv);
11343             CvPADLIST_set(cv,CvPADLIST(PL_compcv));
11344             CvOUTSIDE(PL_compcv) = temp_cv;
11345             CvPADLIST_set(PL_compcv, temp_av);
11346             CvSTART(cv) = CvSTART(PL_compcv);
11347             CvSTART(PL_compcv) = cvstart;
11348             CvFLAGS(PL_compcv) &= ~(CVf_SLABBED|CVf_WEAKOUTSIDE);
11349             CvFLAGS(PL_compcv) |= other_flags;
11350
11351             if (free_file) {
11352                 Safefree(CvFILE(cv));
11353             }
11354             CvFILE_set_from_cop(cv, PL_curcop);
11355             CvSTASH_set(cv, PL_curstash);
11356
11357             /* inner references to PL_compcv must be fixed up ... */
11358             pad_fixup_inner_anons(CvPADLIST(cv), PL_compcv, cv);
11359             if (PERLDB_INTER)/* Advice debugger on the new sub. */
11360                 ++PL_sub_generation;
11361         }
11362         else {
11363             /* Might have had built-in attributes applied -- propagate them. */
11364             CvFLAGS(cv) |= (CvFLAGS(PL_compcv) & CVf_BUILTIN_ATTRS);
11365         }
11366         /* ... before we throw it away */
11367         SvREFCNT_dec(PL_compcv);
11368         PL_compcv = cv;
11369     }
11370     else {
11371         cv = PL_compcv;
11372         if (name && isGV(gv)) {
11373             GvCV_set(gv, cv);
11374             GvCVGEN(gv) = 0;
11375             if (HvENAME_HEK(GvSTASH(gv)))
11376                 /* sub Foo::bar { (shift)+1 } */
11377                 gv_method_changed(gv);
11378         }
11379         else if (name) {
11380             if (!SvROK(gv)) {
11381                 SV_CHECK_THINKFIRST_COW_DROP((SV *)gv);
11382                 prepare_SV_for_RV((SV *)gv);
11383                 SvOK_off((SV *)gv);
11384                 SvROK_on(gv);
11385             }
11386             SvRV_set(gv, (SV *)cv);
11387             if (HvENAME_HEK(PL_curstash))
11388                 mro_method_changed_in(PL_curstash);
11389         }
11390     }
11391     assert(cv);
11392     assert(SvREFCNT((SV*)cv) != 0);
11393
11394     if (!CvHASGV(cv)) {
11395         if (isGV(gv))
11396             CvGV_set(cv, gv);
11397         else {
11398             dVAR;
11399             U32 hash;
11400             PERL_HASH(hash, name, namlen);
11401             CvNAME_HEK_set(cv, share_hek(name,
11402                                          name_is_utf8
11403                                             ? -(SSize_t)namlen
11404                                             :  (SSize_t)namlen,
11405                                          hash));
11406         }
11407         CvFILE_set_from_cop(cv, PL_curcop);
11408         CvSTASH_set(cv, PL_curstash);
11409     }
11410
11411     if (ps) {
11412         sv_setpvn(MUTABLE_SV(cv), ps, ps_len);
11413         if ( ps_utf8 )
11414             SvUTF8_on(MUTABLE_SV(cv));
11415     }
11416
11417     if (block) {
11418         /* If we assign an optree to a PVCV, then we've defined a
11419          * subroutine that the debugger could be able to set a breakpoint
11420          * in, so signal to pp_entereval that it should not throw away any
11421          * saved lines at scope exit.  */
11422
11423         PL_breakable_sub_gen++;
11424         CvROOT(cv) = block;
11425         /* The cv no longer needs to hold a refcount on the slab, as CvROOT
11426            itself has a refcount. */
11427         CvSLABBED_off(cv);
11428         OpslabREFCNT_dec_padok((OPSLAB *)CvSTART(cv));
11429 #ifdef PERL_DEBUG_READONLY_OPS
11430         slab = (OPSLAB *)CvSTART(cv);
11431 #endif
11432         S_process_optree(aTHX_ cv, block, start);
11433     }
11434
11435   attrs:
11436     if (attrs) {
11437         /* Need to do a C<use attributes $stash_of_cv,\&cv,@attrs>. */
11438         HV *stash = name && !CvNAMED(cv) && GvSTASH(CvGV(cv))
11439                         ? GvSTASH(CvGV(cv))
11440                         : PL_curstash;
11441         if (!name)
11442             SAVEFREESV(cv);
11443         apply_attrs(stash, MUTABLE_SV(cv), attrs);
11444         if (!name)
11445             SvREFCNT_inc_simple_void_NN(cv);
11446     }
11447
11448     if (block && has_name) {
11449         if (PERLDB_SUBLINE && PL_curstash != PL_debstash) {
11450             SV * const tmpstr = cv_name(cv,NULL,0);
11451             GV * const db_postponed = gv_fetchpvs("DB::postponed",
11452                                                   GV_ADDMULTI, SVt_PVHV);
11453             HV *hv;
11454             SV * const sv = Perl_newSVpvf(aTHX_ "%s:%ld-%ld",
11455                                           CopFILE(PL_curcop),
11456                                           (long)PL_subline,
11457                                           (long)CopLINE(PL_curcop));
11458             (void)hv_store(GvHV(PL_DBsub), SvPVX_const(tmpstr),
11459                     SvUTF8(tmpstr) ? -(I32)SvCUR(tmpstr) : (I32)SvCUR(tmpstr), sv, 0);
11460             hv = GvHVn(db_postponed);
11461             if (HvTOTALKEYS(hv) > 0 && hv_exists(hv, SvPVX_const(tmpstr), SvUTF8(tmpstr) ? -(I32)SvCUR(tmpstr) : (I32)SvCUR(tmpstr))) {
11462                 CV * const pcv = GvCV(db_postponed);
11463                 if (pcv) {
11464                     dSP;
11465                     PUSHMARK(SP);
11466                     XPUSHs(tmpstr);
11467                     PUTBACK;
11468                     call_sv(MUTABLE_SV(pcv), G_DISCARD);
11469                 }
11470             }
11471         }
11472
11473         if (name) {
11474             if (PL_parser && PL_parser->error_count)
11475                 clear_special_blocks(name, gv, cv);
11476             else
11477                 evanescent =
11478                     process_special_blocks(floor, name, gv, cv);
11479         }
11480     }
11481     assert(cv);
11482
11483   done:
11484     assert(!cv || evanescent || SvREFCNT((SV*)cv) != 0);
11485     if (PL_parser)
11486         PL_parser->copline = NOLINE;
11487     LEAVE_SCOPE(floor);
11488
11489     assert(!cv || evanescent || SvREFCNT((SV*)cv) != 0);
11490     if (!evanescent) {
11491 #ifdef PERL_DEBUG_READONLY_OPS
11492     if (slab)
11493         Slab_to_ro(slab);
11494 #endif
11495     if (cv && name && block && CvOUTSIDE(cv) && !CvEVAL(CvOUTSIDE(cv)))
11496         pad_add_weakref(cv);
11497     }
11498     return cv;
11499 }
11500
11501 STATIC void
11502 S_clear_special_blocks(pTHX_ const char *const fullname,
11503                        GV *const gv, CV *const cv) {
11504     const char *colon;
11505     const char *name;
11506
11507     PERL_ARGS_ASSERT_CLEAR_SPECIAL_BLOCKS;
11508
11509     colon = strrchr(fullname,':');
11510     name = colon ? colon + 1 : fullname;
11511
11512     if ((*name == 'B' && strEQ(name, "BEGIN"))
11513         || (*name == 'E' && strEQ(name, "END"))
11514         || (*name == 'U' && strEQ(name, "UNITCHECK"))
11515         || (*name == 'C' && strEQ(name, "CHECK"))
11516         || (*name == 'I' && strEQ(name, "INIT"))) {
11517         if (!isGV(gv)) {
11518             (void)CvGV(cv);
11519             assert(isGV(gv));
11520         }
11521         GvCV_set(gv, NULL);
11522         SvREFCNT_dec_NN(MUTABLE_SV(cv));
11523     }
11524 }
11525
11526 /* Returns true if the sub has been freed.  */
11527 STATIC bool
11528 S_process_special_blocks(pTHX_ I32 floor, const char *const fullname,
11529                          GV *const gv,
11530                          CV *const cv)
11531 {
11532     const char *const colon = strrchr(fullname,':');
11533     const char *const name = colon ? colon + 1 : fullname;
11534
11535     PERL_ARGS_ASSERT_PROCESS_SPECIAL_BLOCKS;
11536
11537     if (*name == 'B') {
11538         if (strEQ(name, "BEGIN")) {
11539             const I32 oldscope = PL_scopestack_ix;
11540             dSP;
11541             (void)CvGV(cv);
11542             if (floor) LEAVE_SCOPE(floor);
11543             ENTER;
11544
11545             SAVEVPTR(PL_curcop);
11546             if (PL_curcop == &PL_compiling) {
11547                 /* Avoid pushing the "global" &PL_compiling onto the
11548                  * context stack. For example, a stack trace inside
11549                  * nested use's would show all calls coming from whoever
11550                  * most recently updated PL_compiling.cop_file and
11551                  * cop_line.  So instead, temporarily set PL_curcop to a
11552                  * private copy of &PL_compiling. PL_curcop will soon be
11553                  * set to point back to &PL_compiling anyway but only
11554                  * after the temp value has been pushed onto the context
11555                  * stack as blk_oldcop.
11556                  * This is slightly hacky, but necessary. Note also
11557                  * that in the brief window before PL_curcop is set back
11558                  * to PL_compiling, IN_PERL_COMPILETIME/IN_PERL_RUNTIME
11559                  * will give the wrong answer.
11560                  */
11561                 Newx(PL_curcop, 1, COP);
11562                 StructCopy(&PL_compiling, PL_curcop, COP);
11563                 PL_curcop->op_slabbed = 0;
11564                 SAVEFREEPV(PL_curcop);
11565             }
11566
11567             PUSHSTACKi(PERLSI_REQUIRE);
11568             SAVECOPFILE(&PL_compiling);
11569             SAVECOPLINE(&PL_compiling);
11570
11571             DEBUG_x( dump_sub(gv) );
11572             Perl_av_create_and_push(aTHX_ &PL_beginav, MUTABLE_SV(cv));
11573             GvCV_set(gv,0);             /* cv has been hijacked */
11574             call_list(oldscope, PL_beginav);
11575
11576             POPSTACK;
11577             LEAVE;
11578             return !PL_savebegin;
11579         }
11580         else
11581             return FALSE;
11582     } else {
11583         if (*name == 'E') {
11584             if (strEQ(name, "END")) {
11585                 DEBUG_x( dump_sub(gv) );
11586                 Perl_av_create_and_unshift_one(aTHX_ &PL_endav, MUTABLE_SV(cv));
11587             } else
11588                 return FALSE;
11589         } else if (*name == 'U') {
11590             if (strEQ(name, "UNITCHECK")) {
11591                 /* It's never too late to run a unitcheck block */
11592                 Perl_av_create_and_unshift_one(aTHX_ &PL_unitcheckav, MUTABLE_SV(cv));
11593             }
11594             else
11595                 return FALSE;
11596         } else if (*name == 'C') {
11597             if (strEQ(name, "CHECK")) {
11598                 if (PL_main_start)
11599                     /* diag_listed_as: Too late to run %s block */
11600                     Perl_ck_warner(aTHX_ packWARN(WARN_VOID),
11601                                    "Too late to run CHECK block");
11602                 Perl_av_create_and_unshift_one(aTHX_ &PL_checkav, MUTABLE_SV(cv));
11603             }
11604             else
11605                 return FALSE;
11606         } else if (*name == 'I') {
11607             if (strEQ(name, "INIT")) {
11608                 if (PL_main_start)
11609                     /* diag_listed_as: Too late to run %s block */
11610                     Perl_ck_warner(aTHX_ packWARN(WARN_VOID),
11611                                    "Too late to run INIT block");
11612                 Perl_av_create_and_push(aTHX_ &PL_initav, MUTABLE_SV(cv));
11613             }
11614             else
11615                 return FALSE;
11616         } else
11617             return FALSE;
11618         DEBUG_x( dump_sub(gv) );
11619         (void)CvGV(cv);
11620         GvCV_set(gv,0);         /* cv has been hijacked */
11621         return FALSE;
11622     }
11623 }
11624
11625 /*
11626 =for apidoc newCONSTSUB
11627
11628 Behaves like L</newCONSTSUB_flags>, except that C<name> is nul-terminated
11629 rather than of counted length, and no flags are set.  (This means that
11630 C<name> is always interpreted as Latin-1.)
11631
11632 =cut
11633 */
11634
11635 CV *
11636 Perl_newCONSTSUB(pTHX_ HV *stash, const char *name, SV *sv)
11637 {
11638     return newCONSTSUB_flags(stash, name, name ? strlen(name) : 0, 0, sv);
11639 }
11640
11641 /*
11642 =for apidoc newCONSTSUB_flags
11643
11644 Construct a constant subroutine, also performing some surrounding
11645 jobs.  A scalar constant-valued subroutine is eligible for inlining
11646 at compile-time, and in Perl code can be created by S<C<sub FOO () {
11647 123 }>>.  Other kinds of constant subroutine have other treatment.
11648
11649 The subroutine will have an empty prototype and will ignore any arguments
11650 when called.  Its constant behaviour is determined by C<sv>.  If C<sv>
11651 is null, the subroutine will yield an empty list.  If C<sv> points to a
11652 scalar, the subroutine will always yield that scalar.  If C<sv> points
11653 to an array, the subroutine will always yield a list of the elements of
11654 that array in list context, or the number of elements in the array in
11655 scalar context.  This function takes ownership of one counted reference
11656 to the scalar or array, and will arrange for the object to live as long
11657 as the subroutine does.  If C<sv> points to a scalar then the inlining
11658 assumes that the value of the scalar will never change, so the caller
11659 must ensure that the scalar is not subsequently written to.  If C<sv>
11660 points to an array then no such assumption is made, so it is ostensibly
11661 safe to mutate the array or its elements, but whether this is really
11662 supported has not been determined.
11663
11664 The subroutine will have C<CvFILE> set according to C<PL_curcop>.
11665 Other aspects of the subroutine will be left in their default state.
11666 The caller is free to mutate the subroutine beyond its initial state
11667 after this function has returned.
11668
11669 If C<name> is null then the subroutine will be anonymous, with its
11670 C<CvGV> referring to an C<__ANON__> glob.  If C<name> is non-null then the
11671 subroutine will be named accordingly, referenced by the appropriate glob.
11672 C<name> is a string of length C<len> bytes giving a sigilless symbol
11673 name, in UTF-8 if C<flags> has the C<SVf_UTF8> bit set and in Latin-1
11674 otherwise.  The name may be either qualified or unqualified.  If the
11675 name is unqualified then it defaults to being in the stash specified by
11676 C<stash> if that is non-null, or to C<PL_curstash> if C<stash> is null.
11677 The symbol is always added to the stash if necessary, with C<GV_ADDMULTI>
11678 semantics.
11679
11680 C<flags> should not have bits set other than C<SVf_UTF8>.
11681
11682 If there is already a subroutine of the specified name, then the new sub
11683 will replace the existing one in the glob.  A warning may be generated
11684 about the redefinition.
11685
11686 If the subroutine has one of a few special names, such as C<BEGIN> or
11687 C<END>, then it will be claimed by the appropriate queue for automatic
11688 running of phase-related subroutines.  In this case the relevant glob will
11689 be left not containing any subroutine, even if it did contain one before.
11690 Execution of the subroutine will likely be a no-op, unless C<sv> was
11691 a tied array or the caller modified the subroutine in some interesting
11692 way before it was executed.  In the case of C<BEGIN>, the treatment is
11693 buggy: the sub will be executed when only half built, and may be deleted
11694 prematurely, possibly causing a crash.
11695
11696 The function returns a pointer to the constructed subroutine.  If the sub
11697 is anonymous then ownership of one counted reference to the subroutine
11698 is transferred to the caller.  If the sub is named then the caller does
11699 not get ownership of a reference.  In most such cases, where the sub
11700 has a non-phase name, the sub will be alive at the point it is returned
11701 by virtue of being contained in the glob that names it.  A phase-named
11702 subroutine will usually be alive by virtue of the reference owned by
11703 the phase's automatic run queue.  A C<BEGIN> subroutine may have been
11704 destroyed already by the time this function returns, but currently bugs
11705 occur in that case before the caller gets control.  It is the caller's
11706 responsibility to ensure that it knows which of these situations applies.
11707
11708 =cut
11709 */
11710
11711 CV *
11712 Perl_newCONSTSUB_flags(pTHX_ HV *stash, const char *name, STRLEN len,
11713                              U32 flags, SV *sv)
11714 {
11715     CV* cv;
11716     const char *const file = CopFILE(PL_curcop);
11717
11718     ENTER;
11719
11720     if (IN_PERL_RUNTIME) {
11721         /* at runtime, it's not safe to manipulate PL_curcop: it may be
11722          * an op shared between threads. Use a non-shared COP for our
11723          * dirty work */
11724          SAVEVPTR(PL_curcop);
11725          SAVECOMPILEWARNINGS();
11726          PL_compiling.cop_warnings = DUP_WARNINGS(PL_curcop->cop_warnings);
11727          PL_curcop = &PL_compiling;
11728     }
11729     SAVECOPLINE(PL_curcop);
11730     CopLINE_set(PL_curcop, PL_parser ? PL_parser->copline : NOLINE);
11731
11732     SAVEHINTS();
11733     PL_hints &= ~HINT_BLOCK_SCOPE;
11734
11735     if (stash) {
11736         SAVEGENERICSV(PL_curstash);
11737         PL_curstash = (HV *)SvREFCNT_inc_simple_NN(stash);
11738     }
11739
11740     /* Protect sv against leakage caused by fatal warnings. */
11741     if (sv) SAVEFREESV(sv);
11742
11743     /* file becomes the CvFILE. For an XS, it's usually static storage,
11744        and so doesn't get free()d.  (It's expected to be from the C pre-
11745        processor __FILE__ directive). But we need a dynamically allocated one,
11746        and we need it to get freed.  */
11747     cv = newXS_len_flags(name, len,
11748                          sv && SvTYPE(sv) == SVt_PVAV
11749                              ? const_av_xsub
11750                              : const_sv_xsub,
11751                          file ? file : "", "",
11752                          &sv, XS_DYNAMIC_FILENAME | flags);
11753     assert(cv);
11754     assert(SvREFCNT((SV*)cv) != 0);
11755     CvXSUBANY(cv).any_ptr = SvREFCNT_inc_simple(sv);
11756     CvCONST_on(cv);
11757
11758     LEAVE;
11759
11760     return cv;
11761 }
11762
11763 /*
11764 =for apidoc newXS
11765
11766 Used by C<xsubpp> to hook up XSUBs as Perl subs.  C<filename> needs to be
11767 static storage, as it is used directly as CvFILE(), without a copy being made.
11768
11769 =cut
11770 */
11771
11772 CV *
11773 Perl_newXS(pTHX_ const char *name, XSUBADDR_t subaddr, const char *filename)
11774 {
11775     PERL_ARGS_ASSERT_NEWXS;
11776     return newXS_len_flags(
11777         name, name ? strlen(name) : 0, subaddr, filename, NULL, NULL, 0
11778     );
11779 }
11780
11781 CV *
11782 Perl_newXS_flags(pTHX_ const char *name, XSUBADDR_t subaddr,
11783                  const char *const filename, const char *const proto,
11784                  U32 flags)
11785 {
11786     PERL_ARGS_ASSERT_NEWXS_FLAGS;
11787     return newXS_len_flags(
11788        name, name ? strlen(name) : 0, subaddr, filename, proto, NULL, flags
11789     );
11790 }
11791
11792 CV *
11793 Perl_newXS_deffile(pTHX_ const char *name, XSUBADDR_t subaddr)
11794 {
11795     PERL_ARGS_ASSERT_NEWXS_DEFFILE;
11796     return newXS_len_flags(
11797         name, strlen(name), subaddr, NULL, NULL, NULL, 0
11798     );
11799 }
11800
11801 /*
11802 =for apidoc newXS_len_flags
11803
11804 Construct an XS subroutine, also performing some surrounding jobs.
11805
11806 The subroutine will have the entry point C<subaddr>.  It will have
11807 the prototype specified by the nul-terminated string C<proto>, or
11808 no prototype if C<proto> is null.  The prototype string is copied;
11809 the caller can mutate the supplied string afterwards.  If C<filename>
11810 is non-null, it must be a nul-terminated filename, and the subroutine
11811 will have its C<CvFILE> set accordingly.  By default C<CvFILE> is set to
11812 point directly to the supplied string, which must be static.  If C<flags>
11813 has the C<XS_DYNAMIC_FILENAME> bit set, then a copy of the string will
11814 be taken instead.
11815
11816 Other aspects of the subroutine will be left in their default state.
11817 If anything else needs to be done to the subroutine for it to function
11818 correctly, it is the caller's responsibility to do that after this
11819 function has constructed it.  However, beware of the subroutine
11820 potentially being destroyed before this function returns, as described
11821 below.
11822
11823 If C<name> is null then the subroutine will be anonymous, with its
11824 C<CvGV> referring to an C<__ANON__> glob.  If C<name> is non-null then the
11825 subroutine will be named accordingly, referenced by the appropriate glob.
11826 C<name> is a string of length C<len> bytes giving a sigilless symbol name,
11827 in UTF-8 if C<flags> has the C<SVf_UTF8> bit set and in Latin-1 otherwise.
11828 The name may be either qualified or unqualified, with the stash defaulting
11829 in the same manner as for C<gv_fetchpvn_flags>.  C<flags> may contain
11830 flag bits understood by C<gv_fetchpvn_flags> with the same meaning as
11831 they have there, such as C<GV_ADDWARN>.  The symbol is always added to
11832 the stash if necessary, with C<GV_ADDMULTI> semantics.
11833
11834 If there is already a subroutine of the specified name, then the new sub
11835 will replace the existing one in the glob.  A warning may be generated
11836 about the redefinition.  If the old subroutine was C<CvCONST> then the
11837 decision about whether to warn is influenced by an expectation about
11838 whether the new subroutine will become a constant of similar value.
11839 That expectation is determined by C<const_svp>.  (Note that the call to
11840 this function doesn't make the new subroutine C<CvCONST> in any case;
11841 that is left to the caller.)  If C<const_svp> is null then it indicates
11842 that the new subroutine will not become a constant.  If C<const_svp>
11843 is non-null then it indicates that the new subroutine will become a
11844 constant, and it points to an C<SV*> that provides the constant value
11845 that the subroutine will have.
11846
11847 If the subroutine has one of a few special names, such as C<BEGIN> or
11848 C<END>, then it will be claimed by the appropriate queue for automatic
11849 running of phase-related subroutines.  In this case the relevant glob will
11850 be left not containing any subroutine, even if it did contain one before.
11851 In the case of C<BEGIN>, the subroutine will be executed and the reference
11852 to it disposed of before this function returns, and also before its
11853 prototype is set.  If a C<BEGIN> subroutine would not be sufficiently
11854 constructed by this function to be ready for execution then the caller
11855 must prevent this happening by giving the subroutine a different name.
11856
11857 The function returns a pointer to the constructed subroutine.  If the sub
11858 is anonymous then ownership of one counted reference to the subroutine
11859 is transferred to the caller.  If the sub is named then the caller does
11860 not get ownership of a reference.  In most such cases, where the sub
11861 has a non-phase name, the sub will be alive at the point it is returned
11862 by virtue of being contained in the glob that names it.  A phase-named
11863 subroutine will usually be alive by virtue of the reference owned by the
11864 phase's automatic run queue.  But a C<BEGIN> subroutine, having already
11865 been executed, will quite likely have been destroyed already by the
11866 time this function returns, making it erroneous for the caller to make
11867 any use of the returned pointer.  It is the caller's responsibility to
11868 ensure that it knows which of these situations applies.
11869
11870 =cut
11871 */
11872
11873 CV *
11874 Perl_newXS_len_flags(pTHX_ const char *name, STRLEN len,
11875                            XSUBADDR_t subaddr, const char *const filename,
11876                            const char *const proto, SV **const_svp,
11877                            U32 flags)
11878 {
11879     CV *cv;
11880     bool interleave = FALSE;
11881     bool evanescent = FALSE;
11882
11883     PERL_ARGS_ASSERT_NEWXS_LEN_FLAGS;
11884
11885     {
11886         GV * const gv = gv_fetchpvn(
11887                             name ? name : PL_curstash ? "__ANON__" : "__ANON__::__ANON__",
11888                             name ? len : PL_curstash ? sizeof("__ANON__") - 1:
11889                                 sizeof("__ANON__::__ANON__") - 1,
11890                             GV_ADDMULTI | flags, SVt_PVCV);
11891
11892         if ((cv = (name ? GvCV(gv) : NULL))) {
11893             if (GvCVGEN(gv)) {
11894                 /* just a cached method */
11895                 SvREFCNT_dec(cv);
11896                 cv = NULL;
11897             }
11898             else if (CvROOT(cv) || CvXSUB(cv) || GvASSUMECV(gv)) {
11899                 /* already defined (or promised) */
11900                 /* Redundant check that allows us to avoid creating an SV
11901                    most of the time: */
11902                 if (CvCONST(cv) || ckWARN(WARN_REDEFINE)) {
11903                     report_redefined_cv(newSVpvn_flags(
11904                                          name,len,(flags&SVf_UTF8)|SVs_TEMP
11905                                         ),
11906                                         cv, const_svp);
11907                 }
11908                 interleave = TRUE;
11909                 ENTER;
11910                 SAVEFREESV(cv);
11911                 cv = NULL;
11912             }
11913         }
11914
11915         if (cv)                         /* must reuse cv if autoloaded */
11916             cv_undef(cv);
11917         else {
11918             cv = MUTABLE_CV(newSV_type(SVt_PVCV));
11919             if (name) {
11920                 GvCV_set(gv,cv);
11921                 GvCVGEN(gv) = 0;
11922                 if (HvENAME_HEK(GvSTASH(gv)))
11923                     gv_method_changed(gv); /* newXS */
11924             }
11925         }
11926         assert(cv);
11927         assert(SvREFCNT((SV*)cv) != 0);
11928
11929         CvGV_set(cv, gv);
11930         if(filename) {
11931             /* XSUBs can't be perl lang/perl5db.pl debugged
11932             if (PERLDB_LINE_OR_SAVESRC)
11933                 (void)gv_fetchfile(filename); */
11934             assert(!CvDYNFILE(cv)); /* cv_undef should have turned it off */
11935             if (flags & XS_DYNAMIC_FILENAME) {
11936                 CvDYNFILE_on(cv);
11937                 CvFILE(cv) = savepv(filename);
11938             } else {
11939             /* NOTE: not copied, as it is expected to be an external constant string */
11940                 CvFILE(cv) = (char *)filename;
11941             }
11942         } else {
11943             assert((flags & XS_DYNAMIC_FILENAME) == 0 && PL_xsubfilename);
11944             CvFILE(cv) = (char*)PL_xsubfilename;
11945         }
11946         CvISXSUB_on(cv);
11947         CvXSUB(cv) = subaddr;
11948 #ifndef PERL_IMPLICIT_CONTEXT
11949         CvHSCXT(cv) = &PL_stack_sp;
11950 #else
11951         PoisonPADLIST(cv);
11952 #endif
11953
11954         if (name)
11955             evanescent = process_special_blocks(0, name, gv, cv);
11956         else
11957             CvANON_on(cv);
11958     } /* <- not a conditional branch */
11959
11960     assert(cv);
11961     assert(evanescent || SvREFCNT((SV*)cv) != 0);
11962
11963     if (!evanescent) sv_setpv(MUTABLE_SV(cv), proto);
11964     if (interleave) LEAVE;
11965     assert(evanescent || SvREFCNT((SV*)cv) != 0);
11966     return cv;
11967 }
11968
11969 /* Add a stub CV to a typeglob.
11970  * This is the implementation of a forward declaration, 'sub foo';'
11971  */
11972
11973 CV *
11974 Perl_newSTUB(pTHX_ GV *gv, bool fake)
11975 {
11976     CV *cv = MUTABLE_CV(newSV_type(SVt_PVCV));
11977     GV *cvgv;
11978     PERL_ARGS_ASSERT_NEWSTUB;
11979     assert(!GvCVu(gv));
11980     GvCV_set(gv, cv);
11981     GvCVGEN(gv) = 0;
11982     if (!fake && GvSTASH(gv) && HvENAME_HEK(GvSTASH(gv)))
11983         gv_method_changed(gv);
11984     if (SvFAKE(gv)) {
11985         cvgv = gv_fetchsv((SV *)gv, GV_ADDMULTI, SVt_PVCV);
11986         SvFAKE_off(cvgv);
11987     }
11988     else cvgv = gv;
11989     CvGV_set(cv, cvgv);
11990     CvFILE_set_from_cop(cv, PL_curcop);
11991     CvSTASH_set(cv, PL_curstash);
11992     GvMULTI_on(gv);
11993     return cv;
11994 }
11995
11996 void
11997 Perl_newFORM(pTHX_ I32 floor, OP *o, OP *block)
11998 {
11999     CV *cv;
12000     GV *gv;
12001     OP *root;
12002     OP *start;
12003
12004     if (PL_parser && PL_parser->error_count) {
12005         op_free(block);
12006         goto finish;
12007     }
12008
12009     gv = o
12010         ? gv_fetchsv(cSVOPo->op_sv, GV_ADD, SVt_PVFM)
12011         : gv_fetchpvs("STDOUT", GV_ADD|GV_NOTQUAL, SVt_PVFM);
12012
12013     GvMULTI_on(gv);
12014     if ((cv = GvFORM(gv))) {
12015         if (ckWARN(WARN_REDEFINE)) {
12016             const line_t oldline = CopLINE(PL_curcop);
12017             if (PL_parser && PL_parser->copline != NOLINE)
12018                 CopLINE_set(PL_curcop, PL_parser->copline);
12019             if (o) {
12020                 Perl_warner(aTHX_ packWARN(WARN_REDEFINE),
12021                             "Format %" SVf " redefined", SVfARG(cSVOPo->op_sv));
12022             } else {
12023                 /* diag_listed_as: Format %s redefined */
12024                 Perl_warner(aTHX_ packWARN(WARN_REDEFINE),
12025                             "Format STDOUT redefined");
12026             }
12027             CopLINE_set(PL_curcop, oldline);
12028         }
12029         SvREFCNT_dec(cv);
12030     }
12031     cv = PL_compcv;
12032     GvFORM(gv) = (CV *)SvREFCNT_inc_simple_NN(cv);
12033     CvGV_set(cv, gv);
12034     CvFILE_set_from_cop(cv, PL_curcop);
12035
12036
12037     root = newUNOP(OP_LEAVEWRITE, 0, scalarseq(block));
12038     CvROOT(cv) = root;
12039     start = LINKLIST(root);
12040     root->op_next = 0;
12041     S_process_optree(aTHX_ cv, root, start);
12042     cv_forget_slab(cv);
12043
12044   finish:
12045     op_free(o);
12046     if (PL_parser)
12047         PL_parser->copline = NOLINE;
12048     LEAVE_SCOPE(floor);
12049     PL_compiling.cop_seq = 0;
12050 }
12051
12052 OP *
12053 Perl_newANONLIST(pTHX_ OP *o)
12054 {
12055     return op_convert_list(OP_ANONLIST, OPf_SPECIAL, o);
12056 }
12057
12058 OP *
12059 Perl_newANONHASH(pTHX_ OP *o)
12060 {
12061     return op_convert_list(OP_ANONHASH, OPf_SPECIAL, o);
12062 }
12063
12064 OP *
12065 Perl_newANONSUB(pTHX_ I32 floor, OP *proto, OP *block)
12066 {
12067     return newANONATTRSUB(floor, proto, NULL, block);
12068 }
12069
12070 OP *
12071 Perl_newANONATTRSUB(pTHX_ I32 floor, OP *proto, OP *attrs, OP *block)
12072 {
12073     SV * const cv = MUTABLE_SV(newATTRSUB(floor, 0, proto, attrs, block));
12074     OP * anoncode =
12075         newSVOP(OP_ANONCODE, 0,
12076                 cv);
12077     if (CvANONCONST(cv))
12078         anoncode = newUNOP(OP_ANONCONST, 0,
12079                            op_convert_list(OP_ENTERSUB,
12080                                            OPf_STACKED|OPf_WANT_SCALAR,
12081                                            anoncode));
12082     return newUNOP(OP_REFGEN, 0, anoncode);
12083 }
12084
12085 OP *
12086 Perl_oopsAV(pTHX_ OP *o)
12087 {
12088     dVAR;
12089
12090     PERL_ARGS_ASSERT_OOPSAV;
12091
12092     switch (o->op_type) {
12093     case OP_PADSV:
12094     case OP_PADHV:
12095         OpTYPE_set(o, OP_PADAV);
12096         return ref(o, OP_RV2AV);
12097
12098     case OP_RV2SV:
12099     case OP_RV2HV:
12100         OpTYPE_set(o, OP_RV2AV);
12101         ref(o, OP_RV2AV);
12102         break;
12103
12104     default:
12105         Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL), "oops: oopsAV");
12106         break;
12107     }
12108     return o;
12109 }
12110
12111 OP *
12112 Perl_oopsHV(pTHX_ OP *o)
12113 {
12114     dVAR;
12115
12116     PERL_ARGS_ASSERT_OOPSHV;
12117
12118     switch (o->op_type) {
12119     case OP_PADSV:
12120     case OP_PADAV:
12121         OpTYPE_set(o, OP_PADHV);
12122         return ref(o, OP_RV2HV);
12123
12124     case OP_RV2SV:
12125     case OP_RV2AV:
12126         OpTYPE_set(o, OP_RV2HV);
12127         /* rv2hv steals the bottom bit for its own uses */
12128         o->op_private &= ~OPpARG1_MASK;
12129         ref(o, OP_RV2HV);
12130         break;
12131
12132     default:
12133         Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL), "oops: oopsHV");
12134         break;
12135     }
12136     return o;
12137 }
12138
12139 OP *
12140 Perl_newAVREF(pTHX_ OP *o)
12141 {
12142     dVAR;
12143
12144     PERL_ARGS_ASSERT_NEWAVREF;
12145
12146     if (o->op_type == OP_PADANY) {
12147         OpTYPE_set(o, OP_PADAV);
12148         return o;
12149     }
12150     else if ((o->op_type == OP_RV2AV || o->op_type == OP_PADAV)) {
12151         Perl_croak(aTHX_ "Can't use an array as a reference");
12152     }
12153     return newUNOP(OP_RV2AV, 0, scalar(o));
12154 }
12155
12156 OP *
12157 Perl_newGVREF(pTHX_ I32 type, OP *o)
12158 {
12159     if (type == OP_MAPSTART || type == OP_GREPSTART || type == OP_SORT)
12160         return newUNOP(OP_NULL, 0, o);
12161     return ref(newUNOP(OP_RV2GV, OPf_REF, o), type);
12162 }
12163
12164 OP *
12165 Perl_newHVREF(pTHX_ OP *o)
12166 {
12167     dVAR;
12168
12169     PERL_ARGS_ASSERT_NEWHVREF;
12170
12171     if (o->op_type == OP_PADANY) {
12172         OpTYPE_set(o, OP_PADHV);
12173         return o;
12174     }
12175     else if ((o->op_type == OP_RV2HV || o->op_type == OP_PADHV)) {
12176         Perl_croak(aTHX_ "Can't use a hash as a reference");
12177     }
12178     return newUNOP(OP_RV2HV, 0, scalar(o));
12179 }
12180
12181 OP *
12182 Perl_newCVREF(pTHX_ I32 flags, OP *o)
12183 {
12184     if (o->op_type == OP_PADANY) {
12185         dVAR;
12186         OpTYPE_set(o, OP_PADCV);
12187     }
12188     return newUNOP(OP_RV2CV, flags, scalar(o));
12189 }
12190
12191 OP *
12192 Perl_newSVREF(pTHX_ OP *o)
12193 {
12194     dVAR;
12195
12196     PERL_ARGS_ASSERT_NEWSVREF;
12197
12198     if (o->op_type == OP_PADANY) {
12199         OpTYPE_set(o, OP_PADSV);
12200         scalar(o);
12201         return o;
12202     }
12203     return newUNOP(OP_RV2SV, 0, scalar(o));
12204 }
12205
12206 /* Check routines. See the comments at the top of this file for details
12207  * on when these are called */
12208
12209 OP *
12210 Perl_ck_anoncode(pTHX_ OP *o)
12211 {
12212     PERL_ARGS_ASSERT_CK_ANONCODE;
12213
12214     cSVOPo->op_targ = pad_add_anon((CV*)cSVOPo->op_sv, o->op_type);
12215     cSVOPo->op_sv = NULL;
12216     return o;
12217 }
12218
12219 static void
12220 S_io_hints(pTHX_ OP *o)
12221 {
12222 #if O_BINARY != 0 || O_TEXT != 0
12223     HV * const table =
12224         PL_hints & HINT_LOCALIZE_HH ? GvHV(PL_hintgv) : NULL;;
12225     if (table) {
12226         SV **svp = hv_fetchs(table, "open_IN", FALSE);
12227         if (svp && *svp) {
12228             STRLEN len = 0;
12229             const char *d = SvPV_const(*svp, len);
12230             const I32 mode = mode_from_discipline(d, len);
12231             /* bit-and:ing with zero O_BINARY or O_TEXT would be useless. */
12232 #  if O_BINARY != 0
12233             if (mode & O_BINARY)
12234                 o->op_private |= OPpOPEN_IN_RAW;
12235 #  endif
12236 #  if O_TEXT != 0
12237             if (mode & O_TEXT)
12238                 o->op_private |= OPpOPEN_IN_CRLF;
12239 #  endif
12240         }
12241
12242         svp = hv_fetchs(table, "open_OUT", FALSE);
12243         if (svp && *svp) {
12244             STRLEN len = 0;
12245             const char *d = SvPV_const(*svp, len);
12246             const I32 mode = mode_from_discipline(d, len);
12247             /* bit-and:ing with zero O_BINARY or O_TEXT would be useless. */
12248 #  if O_BINARY != 0
12249             if (mode & O_BINARY)
12250                 o->op_private |= OPpOPEN_OUT_RAW;
12251 #  endif
12252 #  if O_TEXT != 0
12253             if (mode & O_TEXT)
12254                 o->op_private |= OPpOPEN_OUT_CRLF;
12255 #  endif
12256         }
12257     }
12258 #else
12259     PERL_UNUSED_CONTEXT;
12260     PERL_UNUSED_ARG(o);
12261 #endif
12262 }
12263
12264 OP *
12265 Perl_ck_backtick(pTHX_ OP *o)
12266 {
12267     GV *gv;
12268     OP *newop = NULL;
12269     OP *sibl;
12270     PERL_ARGS_ASSERT_CK_BACKTICK;
12271     o = ck_fun(o);
12272     /* qx and `` have a null pushmark; CORE::readpipe has only one kid. */
12273     if (o->op_flags & OPf_KIDS && (sibl = OpSIBLING(cUNOPo->op_first))
12274      && (gv = gv_override("readpipe",8)))
12275     {
12276         /* detach rest of siblings from o and its first child */
12277         op_sibling_splice(o, cUNOPo->op_first, -1, NULL);
12278         newop = S_new_entersubop(aTHX_ gv, sibl);
12279     }
12280     else if (!(o->op_flags & OPf_KIDS))
12281         newop = newUNOP(OP_BACKTICK, 0, newDEFSVOP());
12282     if (newop) {
12283         op_free(o);
12284         return newop;
12285     }
12286     S_io_hints(aTHX_ o);
12287     return o;
12288 }
12289
12290 OP *
12291 Perl_ck_bitop(pTHX_ OP *o)
12292 {
12293     PERL_ARGS_ASSERT_CK_BITOP;
12294
12295     o->op_private = (U8)(PL_hints & HINT_INTEGER);
12296
12297     if (!(o->op_flags & OPf_STACKED) /* Not an assignment */
12298             && OP_IS_INFIX_BIT(o->op_type))
12299     {
12300         const OP * const left = cBINOPo->op_first;
12301         const OP * const right = OpSIBLING(left);
12302         if ((OP_IS_NUMCOMPARE(left->op_type) &&
12303                 (left->op_flags & OPf_PARENS) == 0) ||
12304             (OP_IS_NUMCOMPARE(right->op_type) &&
12305                 (right->op_flags & OPf_PARENS) == 0))
12306             Perl_ck_warner(aTHX_ packWARN(WARN_PRECEDENCE),
12307                           "Possible precedence problem on bitwise %s operator",
12308                            o->op_type ==  OP_BIT_OR
12309                          ||o->op_type == OP_NBIT_OR  ? "|"
12310                         :  o->op_type ==  OP_BIT_AND
12311                          ||o->op_type == OP_NBIT_AND ? "&"
12312                         :  o->op_type ==  OP_BIT_XOR
12313                          ||o->op_type == OP_NBIT_XOR ? "^"
12314                         :  o->op_type == OP_SBIT_OR  ? "|."
12315                         :  o->op_type == OP_SBIT_AND ? "&." : "^."
12316                            );
12317     }
12318     return o;
12319 }
12320
12321 PERL_STATIC_INLINE bool
12322 is_dollar_bracket(pTHX_ const OP * const o)
12323 {
12324     const OP *kid;
12325     PERL_UNUSED_CONTEXT;
12326     return o->op_type == OP_RV2SV && o->op_flags & OPf_KIDS
12327         && (kid = cUNOPx(o)->op_first)
12328         && kid->op_type == OP_GV
12329         && strEQ(GvNAME(cGVOPx_gv(kid)), "[");
12330 }
12331
12332 /* for lt, gt, le, ge, eq, ne and their i_ variants */
12333
12334 OP *
12335 Perl_ck_cmp(pTHX_ OP *o)
12336 {
12337     bool is_eq;
12338     bool neg;
12339     bool reverse;
12340     bool iv0;
12341     OP *indexop, *constop, *start;
12342     SV *sv;
12343     IV iv;
12344
12345     PERL_ARGS_ASSERT_CK_CMP;
12346
12347     is_eq = (   o->op_type == OP_EQ
12348              || o->op_type == OP_NE
12349              || o->op_type == OP_I_EQ
12350              || o->op_type == OP_I_NE);
12351
12352     if (!is_eq && ckWARN(WARN_SYNTAX)) {
12353         const OP *kid = cUNOPo->op_first;
12354         if (kid &&
12355             (
12356                 (   is_dollar_bracket(aTHX_ kid)
12357                  && OpSIBLING(kid) && OpSIBLING(kid)->op_type == OP_CONST
12358                 )
12359              || (   kid->op_type == OP_CONST
12360                  && (kid = OpSIBLING(kid)) && is_dollar_bracket(aTHX_ kid)
12361                 )
12362            )
12363         )
12364             Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
12365                         "$[ used in %s (did you mean $] ?)", OP_DESC(o));
12366     }
12367
12368     /* convert (index(...) == -1) and variations into
12369      *   (r)index/BOOL(,NEG)
12370      */
12371
12372     reverse = FALSE;
12373
12374     indexop = cUNOPo->op_first;
12375     constop = OpSIBLING(indexop);
12376     start = NULL;
12377     if (indexop->op_type == OP_CONST) {
12378         constop = indexop;
12379         indexop = OpSIBLING(constop);
12380         start = constop;
12381         reverse = TRUE;
12382     }
12383
12384     if (indexop->op_type != OP_INDEX && indexop->op_type != OP_RINDEX)
12385         return o;
12386
12387     /* ($lex = index(....)) == -1 */
12388     if (indexop->op_private & OPpTARGET_MY)
12389         return o;
12390
12391     if (constop->op_type != OP_CONST)
12392         return o;
12393
12394     sv = cSVOPx_sv(constop);
12395     if (!(sv && SvIOK_notUV(sv)))
12396         return o;
12397
12398     iv = SvIVX(sv);
12399     if (iv != -1 && iv != 0)
12400         return o;
12401     iv0 = (iv == 0);
12402
12403     if (o->op_type == OP_LT || o->op_type == OP_I_LT) {
12404         if (!(iv0 ^ reverse))
12405             return o;
12406         neg = iv0;
12407     }
12408     else if (o->op_type == OP_LE || o->op_type == OP_I_LE) {
12409         if (iv0 ^ reverse)
12410             return o;
12411         neg = !iv0;
12412     }
12413     else if (o->op_type == OP_GE || o->op_type == OP_I_GE) {
12414         if (!(iv0 ^ reverse))
12415             return o;
12416         neg = !iv0;
12417     }
12418     else if (o->op_type == OP_GT || o->op_type == OP_I_GT) {
12419         if (iv0 ^ reverse)
12420             return o;
12421         neg = iv0;
12422     }
12423     else if (o->op_type == OP_EQ || o->op_type == OP_I_EQ) {
12424         if (iv0)
12425             return o;
12426         neg = TRUE;
12427     }
12428     else {
12429         assert(o->op_type == OP_NE || o->op_type == OP_I_NE);
12430         if (iv0)
12431             return o;
12432         neg = FALSE;
12433     }
12434
12435     indexop->op_flags &= ~OPf_PARENS;
12436     indexop->op_flags |= (o->op_flags & OPf_PARENS);
12437     indexop->op_private |= OPpTRUEBOOL;
12438     if (neg)
12439         indexop->op_private |= OPpINDEX_BOOLNEG;
12440     /* cut out the index op and free the eq,const ops */
12441     (void)op_sibling_splice(o, start, 1, NULL);
12442     op_free(o);
12443
12444     return indexop;
12445 }
12446
12447
12448 OP *
12449 Perl_ck_concat(pTHX_ OP *o)
12450 {
12451     const OP * const kid = cUNOPo->op_first;
12452
12453     PERL_ARGS_ASSERT_CK_CONCAT;
12454     PERL_UNUSED_CONTEXT;
12455
12456     /* reuse the padtmp returned by the concat child */
12457     if (kid->op_type == OP_CONCAT && !(kid->op_private & OPpTARGET_MY) &&
12458             !(kUNOP->op_first->op_flags & OPf_MOD))
12459     {
12460         o->op_flags |= OPf_STACKED;
12461         o->op_private |= OPpCONCAT_NESTED;
12462     }
12463     return o;
12464 }
12465
12466 OP *
12467 Perl_ck_spair(pTHX_ OP *o)
12468 {
12469     dVAR;
12470
12471     PERL_ARGS_ASSERT_CK_SPAIR;
12472
12473     if (o->op_flags & OPf_KIDS) {
12474         OP* newop;
12475         OP* kid;
12476         OP* kidkid;
12477         const OPCODE type = o->op_type;
12478         o = modkids(ck_fun(o), type);
12479         kid    = cUNOPo->op_first;
12480         kidkid = kUNOP->op_first;
12481         newop = OpSIBLING(kidkid);
12482         if (newop) {
12483             const OPCODE type = newop->op_type;
12484             if (OpHAS_SIBLING(newop))
12485                 return o;
12486             if (o->op_type == OP_REFGEN
12487              && (  type == OP_RV2CV
12488                 || (  !(newop->op_flags & OPf_PARENS)
12489                    && (  type == OP_RV2AV || type == OP_PADAV
12490                       || type == OP_RV2HV || type == OP_PADHV))))
12491                 NOOP; /* OK (allow srefgen for \@a and \%h) */
12492             else if (OP_GIMME(newop,0) != G_SCALAR)
12493                 return o;
12494         }
12495         /* excise first sibling */
12496         op_sibling_splice(kid, NULL, 1, NULL);
12497         op_free(kidkid);
12498     }
12499     /* transforms OP_REFGEN into OP_SREFGEN, OP_CHOP into OP_SCHOP,
12500      * and OP_CHOMP into OP_SCHOMP */
12501     o->op_ppaddr = PL_ppaddr[++o->op_type];
12502     return ck_fun(o);
12503 }
12504
12505 OP *
12506 Perl_ck_delete(pTHX_ OP *o)
12507 {
12508     PERL_ARGS_ASSERT_CK_DELETE;
12509
12510     o = ck_fun(o);
12511     o->op_private = 0;
12512     if (o->op_flags & OPf_KIDS) {
12513         OP * const kid = cUNOPo->op_first;
12514         switch (kid->op_type) {
12515         case OP_ASLICE:
12516             o->op_flags |= OPf_SPECIAL;
12517             /* FALLTHROUGH */
12518         case OP_HSLICE:
12519             o->op_private |= OPpSLICE;
12520             break;
12521         case OP_AELEM:
12522             o->op_flags |= OPf_SPECIAL;
12523             /* FALLTHROUGH */
12524         case OP_HELEM:
12525             break;
12526         case OP_KVASLICE:
12527             o->op_flags |= OPf_SPECIAL;
12528             /* FALLTHROUGH */
12529         case OP_KVHSLICE:
12530             o->op_private |= OPpKVSLICE;
12531             break;
12532         default:
12533             Perl_croak(aTHX_ "delete argument is not a HASH or ARRAY "
12534                              "element or slice");
12535         }
12536         if (kid->op_private & OPpLVAL_INTRO)
12537             o->op_private |= OPpLVAL_INTRO;
12538         op_null(kid);
12539     }
12540     return o;
12541 }
12542
12543 OP *
12544 Perl_ck_eof(pTHX_ OP *o)
12545 {
12546     PERL_ARGS_ASSERT_CK_EOF;
12547
12548     if (o->op_flags & OPf_KIDS) {
12549         OP *kid;
12550         if (cLISTOPo->op_first->op_type == OP_STUB) {
12551             OP * const newop
12552                 = newUNOP(o->op_type, OPf_SPECIAL, newGVOP(OP_GV, 0, PL_argvgv));
12553             op_free(o);
12554             o = newop;
12555         }
12556         o = ck_fun(o);
12557         kid = cLISTOPo->op_first;
12558         if (kid->op_type == OP_RV2GV)
12559             kid->op_private |= OPpALLOW_FAKE;
12560     }
12561     return o;
12562 }
12563
12564
12565 OP *
12566 Perl_ck_eval(pTHX_ OP *o)
12567 {
12568     dVAR;
12569
12570     PERL_ARGS_ASSERT_CK_EVAL;
12571
12572     PL_hints |= HINT_BLOCK_SCOPE;
12573     if (o->op_flags & OPf_KIDS) {
12574         SVOP * const kid = (SVOP*)cUNOPo->op_first;
12575         assert(kid);
12576
12577         if (o->op_type == OP_ENTERTRY) {
12578             LOGOP *enter;
12579
12580             /* cut whole sibling chain free from o */
12581             op_sibling_splice(o, NULL, -1, NULL);
12582             op_free(o);
12583
12584             enter = alloc_LOGOP(OP_ENTERTRY, NULL, NULL);
12585
12586             /* establish postfix order */
12587             enter->op_next = (OP*)enter;
12588
12589             o = op_prepend_elem(OP_LINESEQ, (OP*)enter, (OP*)kid);
12590             OpTYPE_set(o, OP_LEAVETRY);
12591             enter->op_other = o;
12592             return o;
12593         }
12594         else {
12595             scalar((OP*)kid);
12596             S_set_haseval(aTHX);
12597         }
12598     }
12599     else {
12600         const U8 priv = o->op_private;
12601         op_free(o);
12602         /* the newUNOP will recursively call ck_eval(), which will handle
12603          * all the stuff at the end of this function, like adding
12604          * OP_HINTSEVAL
12605          */
12606         return newUNOP(OP_ENTEREVAL, priv <<8, newDEFSVOP());
12607     }
12608     o->op_targ = (PADOFFSET)PL_hints;
12609     if (o->op_private & OPpEVAL_BYTES) o->op_targ &= ~HINT_UTF8;
12610     if ((PL_hints & HINT_LOCALIZE_HH) != 0
12611      && !(o->op_private & OPpEVAL_COPHH) && GvHV(PL_hintgv)) {
12612         /* Store a copy of %^H that pp_entereval can pick up. */
12613         HV *hh = hv_copy_hints_hv(GvHV(PL_hintgv));
12614         OP *hhop;
12615         STOREFEATUREBITSHH(hh);
12616         hhop = newSVOP(OP_HINTSEVAL, 0, MUTABLE_SV(hh));
12617         /* append hhop to only child  */
12618         op_sibling_splice(o, cUNOPo->op_first, 0, hhop);
12619
12620         o->op_private |= OPpEVAL_HAS_HH;
12621     }
12622     if (!(o->op_private & OPpEVAL_BYTES)
12623          && FEATURE_UNIEVAL_IS_ENABLED)
12624             o->op_private |= OPpEVAL_UNICODE;
12625     return o;
12626 }
12627
12628 OP *
12629 Perl_ck_exec(pTHX_ OP *o)
12630 {
12631     PERL_ARGS_ASSERT_CK_EXEC;
12632
12633     if (o->op_flags & OPf_STACKED) {
12634         OP *kid;
12635         o = ck_fun(o);
12636         kid = OpSIBLING(cUNOPo->op_first);
12637         if (kid->op_type == OP_RV2GV)
12638             op_null(kid);
12639     }
12640     else
12641         o = listkids(o);
12642     return o;
12643 }
12644
12645 OP *
12646 Perl_ck_exists(pTHX_ OP *o)
12647 {
12648     PERL_ARGS_ASSERT_CK_EXISTS;
12649
12650     o = ck_fun(o);
12651     if (o->op_flags & OPf_KIDS) {
12652         OP * const kid = cUNOPo->op_first;
12653         if (kid->op_type == OP_ENTERSUB) {
12654             (void) ref(kid, o->op_type);
12655             if (kid->op_type != OP_RV2CV
12656                         && !(PL_parser && PL_parser->error_count))
12657                 Perl_croak(aTHX_
12658                           "exists argument is not a subroutine name");
12659             o->op_private |= OPpEXISTS_SUB;
12660         }
12661         else if (kid->op_type == OP_AELEM)
12662             o->op_flags |= OPf_SPECIAL;
12663         else if (kid->op_type != OP_HELEM)
12664             Perl_croak(aTHX_ "exists argument is not a HASH or ARRAY "
12665                              "element or a subroutine");
12666         op_null(kid);
12667     }
12668     return o;
12669 }
12670
12671 OP *
12672 Perl_ck_rvconst(pTHX_ OP *o)
12673 {
12674     dVAR;
12675     SVOP * const kid = (SVOP*)cUNOPo->op_first;
12676
12677     PERL_ARGS_ASSERT_CK_RVCONST;
12678
12679     if (o->op_type == OP_RV2HV)
12680         /* rv2hv steals the bottom bit for its own uses */
12681         o->op_private &= ~OPpARG1_MASK;
12682
12683     o->op_private |= (PL_hints & HINT_STRICT_REFS);
12684
12685     if (kid->op_type == OP_CONST) {
12686         int iscv;
12687         GV *gv;
12688         SV * const kidsv = kid->op_sv;
12689
12690         /* Is it a constant from cv_const_sv()? */
12691         if ((SvROK(kidsv) || isGV_with_GP(kidsv)) && SvREADONLY(kidsv)) {
12692             return o;
12693         }
12694         if (SvTYPE(kidsv) == SVt_PVAV) return o;
12695         if ((o->op_private & HINT_STRICT_REFS) && (kid->op_private & OPpCONST_BARE)) {
12696             const char *badthing;
12697             switch (o->op_type) {
12698             case OP_RV2SV:
12699                 badthing = "a SCALAR";
12700                 break;
12701             case OP_RV2AV:
12702                 badthing = "an ARRAY";
12703                 break;
12704             case OP_RV2HV:
12705                 badthing = "a HASH";
12706                 break;
12707             default:
12708                 badthing = NULL;
12709                 break;
12710             }
12711             if (badthing)
12712                 Perl_croak(aTHX_
12713                            "Can't use bareword (\"%" SVf "\") as %s ref while \"strict refs\" in use",
12714                            SVfARG(kidsv), badthing);
12715         }
12716         /*
12717          * This is a little tricky.  We only want to add the symbol if we
12718          * didn't add it in the lexer.  Otherwise we get duplicate strict
12719          * warnings.  But if we didn't add it in the lexer, we must at
12720          * least pretend like we wanted to add it even if it existed before,
12721          * or we get possible typo warnings.  OPpCONST_ENTERED says
12722          * whether the lexer already added THIS instance of this symbol.
12723          */
12724         iscv = o->op_type == OP_RV2CV ? GV_NOEXPAND|GV_ADDMULTI : 0;
12725         gv = gv_fetchsv(kidsv,
12726                 o->op_type == OP_RV2CV
12727                         && o->op_private & OPpMAY_RETURN_CONSTANT
12728                     ? GV_NOEXPAND
12729                     : iscv | !(kid->op_private & OPpCONST_ENTERED),
12730                 iscv
12731                     ? SVt_PVCV
12732                     : o->op_type == OP_RV2SV
12733                         ? SVt_PV
12734                         : o->op_type == OP_RV2AV
12735                             ? SVt_PVAV
12736                             : o->op_type == OP_RV2HV
12737                                 ? SVt_PVHV
12738                                 : SVt_PVGV);
12739         if (gv) {
12740             if (!isGV(gv)) {
12741                 assert(iscv);
12742                 assert(SvROK(gv));
12743                 if (!(o->op_private & OPpMAY_RETURN_CONSTANT)
12744                   && SvTYPE(SvRV(gv)) != SVt_PVCV)
12745                     gv_fetchsv(kidsv, GV_ADDMULTI, SVt_PVCV);
12746             }
12747             OpTYPE_set(kid, OP_GV);
12748             SvREFCNT_dec(kid->op_sv);
12749 #ifdef USE_ITHREADS
12750             /* XXX hack: dependence on sizeof(PADOP) <= sizeof(SVOP) */
12751             STATIC_ASSERT_STMT(sizeof(PADOP) <= sizeof(SVOP));
12752             kPADOP->op_padix = pad_alloc(OP_GV, SVf_READONLY);
12753             SvREFCNT_dec(PAD_SVl(kPADOP->op_padix));
12754             PAD_SETSV(kPADOP->op_padix, MUTABLE_SV(SvREFCNT_inc_simple_NN(gv)));
12755 #else
12756             kid->op_sv = SvREFCNT_inc_simple_NN(gv);
12757 #endif
12758             kid->op_private = 0;
12759             /* FAKE globs in the symbol table cause weird bugs (#77810) */
12760             SvFAKE_off(gv);
12761         }
12762     }
12763     return o;
12764 }
12765
12766 OP *
12767 Perl_ck_ftst(pTHX_ OP *o)
12768 {
12769     dVAR;
12770     const I32 type = o->op_type;
12771
12772     PERL_ARGS_ASSERT_CK_FTST;
12773
12774     if (o->op_flags & OPf_REF) {
12775         NOOP;
12776     }
12777     else if (o->op_flags & OPf_KIDS && cUNOPo->op_first->op_type != OP_STUB) {
12778         SVOP * const kid = (SVOP*)cUNOPo->op_first;
12779         const OPCODE kidtype = kid->op_type;
12780
12781         if (kidtype == OP_CONST && (kid->op_private & OPpCONST_BARE)
12782          && !kid->op_folded) {
12783             OP * const newop = newGVOP(type, OPf_REF,
12784                 gv_fetchsv(kid->op_sv, GV_ADD, SVt_PVIO));
12785             op_free(o);
12786             return newop;
12787         }
12788
12789         if ((kidtype == OP_RV2AV || kidtype == OP_PADAV) && ckWARN(WARN_SYNTAX)) {
12790             SV *name = S_op_varname_subscript(aTHX_ (OP*)kid, 2);
12791             if (name) {
12792                 /* diag_listed_as: Array passed to stat will be coerced to a scalar%s */
12793                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX), "%s (did you want stat %" SVf "?)",
12794                             array_passed_to_stat, name);
12795             }
12796             else {
12797                 /* diag_listed_as: Array passed to stat will be coerced to a scalar%s */
12798                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX), "%s", array_passed_to_stat);
12799             }
12800        }
12801         scalar((OP *) kid);
12802         if ((PL_hints & HINT_FILETEST_ACCESS) && OP_IS_FILETEST_ACCESS(o->op_type))
12803             o->op_private |= OPpFT_ACCESS;
12804         if (OP_IS_FILETEST(type)
12805             && OP_IS_FILETEST(kidtype)
12806         ) {
12807             o->op_private |= OPpFT_STACKED;
12808             kid->op_private |= OPpFT_STACKING;
12809             if (kidtype == OP_FTTTY && (
12810                    !(kid->op_private & OPpFT_STACKED)
12811                 || kid->op_private & OPpFT_AFTER_t
12812                ))
12813                 o->op_private |= OPpFT_AFTER_t;
12814         }
12815     }
12816     else {
12817         op_free(o);
12818         if (type == OP_FTTTY)
12819             o = newGVOP(type, OPf_REF, PL_stdingv);
12820         else
12821             o = newUNOP(type, 0, newDEFSVOP());
12822     }
12823     return o;
12824 }
12825
12826 OP *
12827 Perl_ck_fun(pTHX_ OP *o)
12828 {
12829     const int type = o->op_type;
12830     I32 oa = PL_opargs[type] >> OASHIFT;
12831
12832     PERL_ARGS_ASSERT_CK_FUN;
12833
12834     if (o->op_flags & OPf_STACKED) {
12835         if ((oa & OA_OPTIONAL) && (oa >> 4) && !((oa >> 4) & OA_OPTIONAL))
12836             oa &= ~OA_OPTIONAL;
12837         else
12838             return no_fh_allowed(o);
12839     }
12840
12841     if (o->op_flags & OPf_KIDS) {
12842         OP *prev_kid = NULL;
12843         OP *kid = cLISTOPo->op_first;
12844         I32 numargs = 0;
12845         bool seen_optional = FALSE;
12846
12847         if (kid->op_type == OP_PUSHMARK ||
12848             (kid->op_type == OP_NULL && kid->op_targ == OP_PUSHMARK))
12849         {
12850             prev_kid = kid;
12851             kid = OpSIBLING(kid);
12852         }
12853         if (kid && kid->op_type == OP_COREARGS) {
12854             bool optional = FALSE;
12855             while (oa) {
12856                 numargs++;
12857                 if (oa & OA_OPTIONAL) optional = TRUE;
12858                 oa = oa >> 4;
12859             }
12860             if (optional) o->op_private |= numargs;
12861             return o;
12862         }
12863
12864         while (oa) {
12865             if (oa & OA_OPTIONAL || (oa & 7) == OA_LIST) {
12866                 if (!kid && !seen_optional && PL_opargs[type] & OA_DEFGV) {
12867                     kid = newDEFSVOP();
12868                     /* append kid to chain */
12869                     op_sibling_splice(o, prev_kid, 0, kid);
12870                 }
12871                 seen_optional = TRUE;
12872             }
12873             if (!kid) break;
12874
12875             numargs++;
12876             switch (oa & 7) {
12877             case OA_SCALAR:
12878                 /* list seen where single (scalar) arg expected? */
12879                 if (numargs == 1 && !(oa >> 4)
12880                     && kid->op_type == OP_LIST && type != OP_SCALAR)
12881                 {
12882                     return too_many_arguments_pv(o,PL_op_desc[type], 0);
12883                 }
12884                 if (type != OP_DELETE) scalar(kid);
12885                 break;
12886             case OA_LIST:
12887                 if (oa < 16) {
12888                     kid = 0;
12889                     continue;
12890                 }
12891                 else
12892                     list(kid);
12893                 break;
12894             case OA_AVREF:
12895                 if ((type == OP_PUSH || type == OP_UNSHIFT)
12896                     && !OpHAS_SIBLING(kid))
12897                     Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX),
12898                                    "Useless use of %s with no values",
12899                                    PL_op_desc[type]);
12900
12901                 if (kid->op_type == OP_CONST
12902                       && (  !SvROK(cSVOPx_sv(kid))
12903                          || SvTYPE(SvRV(cSVOPx_sv(kid))) != SVt_PVAV  )
12904                         )
12905                     bad_type_pv(numargs, "array", o, kid);
12906                 else if (kid->op_type == OP_RV2HV || kid->op_type == OP_PADHV
12907                          || kid->op_type == OP_RV2GV) {
12908                     bad_type_pv(1, "array", o, kid);
12909                 }
12910                 else if (kid->op_type != OP_RV2AV && kid->op_type != OP_PADAV) {
12911                     yyerror_pv(Perl_form(aTHX_ "Experimental %s on scalar is now forbidden",
12912                                          PL_op_desc[type]), 0);
12913                 }
12914                 else {
12915                     op_lvalue(kid, type);
12916                 }
12917                 break;
12918             case OA_HVREF:
12919                 if (kid->op_type != OP_RV2HV && kid->op_type != OP_PADHV)
12920                     bad_type_pv(numargs, "hash", o, kid);
12921                 op_lvalue(kid, type);
12922                 break;
12923             case OA_CVREF:
12924                 {
12925                     /* replace kid with newop in chain */
12926                     OP * const newop =
12927                         S_op_sibling_newUNOP(aTHX_ o, prev_kid, OP_NULL, 0);
12928                     newop->op_next = newop;
12929                     kid = newop;
12930                 }
12931                 break;
12932             case OA_FILEREF:
12933                 if (kid->op_type != OP_GV && kid->op_type != OP_RV2GV) {
12934                     if (kid->op_type == OP_CONST &&
12935                         (kid->op_private & OPpCONST_BARE))
12936                     {
12937                         OP * const newop = newGVOP(OP_GV, 0,
12938                             gv_fetchsv(((SVOP*)kid)->op_sv, GV_ADD, SVt_PVIO));
12939                         /* replace kid with newop in chain */
12940                         op_sibling_splice(o, prev_kid, 1, newop);
12941                         op_free(kid);
12942                         kid = newop;
12943                     }
12944                     else if (kid->op_type == OP_READLINE) {
12945                         /* neophyte patrol: open(<FH>), close(<FH>) etc. */
12946                         bad_type_pv(numargs, "HANDLE", o, kid);
12947                     }
12948                     else {
12949                         I32 flags = OPf_SPECIAL;
12950                         I32 priv = 0;
12951                         PADOFFSET targ = 0;
12952
12953                         /* is this op a FH constructor? */
12954                         if (is_handle_constructor(o,numargs)) {
12955                             const char *name = NULL;
12956                             STRLEN len = 0;
12957                             U32 name_utf8 = 0;
12958                             bool want_dollar = TRUE;
12959
12960                             flags = 0;
12961                             /* Set a flag to tell rv2gv to vivify
12962                              * need to "prove" flag does not mean something
12963                              * else already - NI-S 1999/05/07
12964                              */
12965                             priv = OPpDEREF;
12966                             if (kid->op_type == OP_PADSV) {
12967                                 PADNAME * const pn
12968                                     = PAD_COMPNAME_SV(kid->op_targ);
12969                                 name = PadnamePV (pn);
12970                                 len  = PadnameLEN(pn);
12971                                 name_utf8 = PadnameUTF8(pn);
12972                             }
12973                             else if (kid->op_type == OP_RV2SV
12974                                      && kUNOP->op_first->op_type == OP_GV)
12975                             {
12976                                 GV * const gv = cGVOPx_gv(kUNOP->op_first);
12977                                 name = GvNAME(gv);
12978                                 len = GvNAMELEN(gv);
12979                                 name_utf8 = GvNAMEUTF8(gv) ? SVf_UTF8 : 0;
12980                             }
12981                             else if (kid->op_type == OP_AELEM
12982                                      || kid->op_type == OP_HELEM)
12983                             {
12984                                  OP *firstop;
12985                                  OP *op = ((BINOP*)kid)->op_first;
12986                                  name = NULL;
12987                                  if (op) {
12988                                       SV *tmpstr = NULL;
12989                                       const char * const a =
12990                                            kid->op_type == OP_AELEM ?
12991                                            "[]" : "{}";
12992                                       if (((op->op_type == OP_RV2AV) ||
12993                                            (op->op_type == OP_RV2HV)) &&
12994                                           (firstop = ((UNOP*)op)->op_first) &&
12995                                           (firstop->op_type == OP_GV)) {
12996                                            /* packagevar $a[] or $h{} */
12997                                            GV * const gv = cGVOPx_gv(firstop);
12998                                            if (gv)
12999                                                 tmpstr =
13000                                                      Perl_newSVpvf(aTHX_
13001                                                                    "%s%c...%c",
13002                                                                    GvNAME(gv),
13003                                                                    a[0], a[1]);
13004                                       }
13005                                       else if (op->op_type == OP_PADAV
13006                                                || op->op_type == OP_PADHV) {
13007                                            /* lexicalvar $a[] or $h{} */
13008                                            const char * const padname =
13009                                                 PAD_COMPNAME_PV(op->op_targ);
13010                                            if (padname)
13011                                                 tmpstr =
13012                                                      Perl_newSVpvf(aTHX_
13013                                                                    "%s%c...%c",
13014                                                                    padname + 1,
13015                                                                    a[0], a[1]);
13016                                       }
13017                                       if (tmpstr) {
13018                                            name = SvPV_const(tmpstr, len);
13019                                            name_utf8 = SvUTF8(tmpstr);
13020                                            sv_2mortal(tmpstr);
13021                                       }
13022                                  }
13023                                  if (!name) {
13024                                       name = "__ANONIO__";
13025                                       len = 10;
13026                                       want_dollar = FALSE;
13027                                  }
13028                                  op_lvalue(kid, type);
13029                             }
13030                             if (name) {
13031                                 SV *namesv;
13032                                 targ = pad_alloc(OP_RV2GV, SVf_READONLY);
13033                                 namesv = PAD_SVl(targ);
13034                                 if (want_dollar && *name != '$')
13035                                     sv_setpvs(namesv, "$");
13036                                 else
13037                                     SvPVCLEAR(namesv);
13038                                 sv_catpvn(namesv, name, len);
13039                                 if ( name_utf8 ) SvUTF8_on(namesv);
13040                             }
13041                         }
13042                         scalar(kid);
13043                         kid = S_op_sibling_newUNOP(aTHX_ o, prev_kid,
13044                                     OP_RV2GV, flags);
13045                         kid->op_targ = targ;
13046                         kid->op_private |= priv;
13047                     }
13048                 }
13049                 scalar(kid);
13050                 break;
13051             case OA_SCALARREF:
13052                 if ((type == OP_UNDEF || type == OP_POS)
13053                     && numargs == 1 && !(oa >> 4)
13054                     && kid->op_type == OP_LIST)
13055                     return too_many_arguments_pv(o,PL_op_desc[type], 0);
13056                 op_lvalue(scalar(kid), type);
13057                 break;
13058             }
13059             oa >>= 4;
13060             prev_kid = kid;
13061             kid = OpSIBLING(kid);
13062         }
13063         /* FIXME - should the numargs or-ing move after the too many
13064          * arguments check? */
13065         o->op_private |= numargs;
13066         if (kid)
13067             return too_many_arguments_pv(o,OP_DESC(o), 0);
13068         listkids(o);
13069     }
13070     else if (PL_opargs[type] & OA_DEFGV) {
13071         /* Ordering of these two is important to keep f_map.t passing.  */
13072         op_free(o);
13073         return newUNOP(type, 0, newDEFSVOP());
13074     }
13075
13076     if (oa) {
13077         while (oa & OA_OPTIONAL)
13078             oa >>= 4;
13079         if (oa && oa != OA_LIST)
13080             return too_few_arguments_pv(o,OP_DESC(o), 0);
13081     }
13082     return o;
13083 }
13084
13085 OP *
13086 Perl_ck_glob(pTHX_ OP *o)
13087 {
13088     GV *gv;
13089
13090     PERL_ARGS_ASSERT_CK_GLOB;
13091
13092     o = ck_fun(o);
13093     if ((o->op_flags & OPf_KIDS) && !OpHAS_SIBLING(cLISTOPo->op_first))
13094         op_append_elem(OP_GLOB, o, newDEFSVOP()); /* glob() => glob($_) */
13095
13096     if (!(o->op_flags & OPf_SPECIAL) && (gv = gv_override("glob", 4)))
13097     {
13098         /* convert
13099          *     glob
13100          *       \ null - const(wildcard)
13101          * into
13102          *     null
13103          *       \ enter
13104          *            \ list
13105          *                 \ mark - glob - rv2cv
13106          *                             |        \ gv(CORE::GLOBAL::glob)
13107          *                             |
13108          *                              \ null - const(wildcard)
13109          */
13110         o->op_flags |= OPf_SPECIAL;
13111         o->op_targ = pad_alloc(OP_GLOB, SVs_PADTMP);
13112         o = S_new_entersubop(aTHX_ gv, o);
13113         o = newUNOP(OP_NULL, 0, o);
13114         o->op_targ = OP_GLOB; /* hint at what it used to be: eg in newWHILEOP */
13115         return o;
13116     }
13117     else o->op_flags &= ~OPf_SPECIAL;
13118 #if !defined(PERL_EXTERNAL_GLOB)
13119     if (!PL_globhook) {
13120         ENTER;
13121         Perl_load_module(aTHX_ PERL_LOADMOD_NOIMPORT,
13122                                newSVpvs("File::Glob"), NULL, NULL, NULL);
13123         LEAVE;
13124     }
13125 #endif /* !PERL_EXTERNAL_GLOB */
13126     gv = (GV *)newSV(0);
13127     gv_init(gv, 0, "", 0, 0);
13128     gv_IOadd(gv);
13129     op_append_elem(OP_GLOB, o, newGVOP(OP_GV, 0, gv));
13130     SvREFCNT_dec_NN(gv); /* newGVOP increased it */
13131     scalarkids(o);
13132     return o;
13133 }
13134
13135 OP *
13136 Perl_ck_grep(pTHX_ OP *o)
13137 {
13138     LOGOP *gwop;
13139     OP *kid;
13140     const OPCODE type = o->op_type == OP_GREPSTART ? OP_GREPWHILE : OP_MAPWHILE;
13141
13142     PERL_ARGS_ASSERT_CK_GREP;
13143
13144     /* don't allocate gwop here, as we may leak it if PL_parser->error_count > 0 */
13145
13146     if (o->op_flags & OPf_STACKED) {
13147         kid = cUNOPx(OpSIBLING(cLISTOPo->op_first))->op_first;
13148         if (kid->op_type != OP_SCOPE && kid->op_type != OP_LEAVE)
13149             return no_fh_allowed(o);
13150         o->op_flags &= ~OPf_STACKED;
13151     }
13152     kid = OpSIBLING(cLISTOPo->op_first);
13153     if (type == OP_MAPWHILE)
13154         list(kid);
13155     else
13156         scalar(kid);
13157     o = ck_fun(o);
13158     if (PL_parser && PL_parser->error_count)
13159         return o;
13160     kid = OpSIBLING(cLISTOPo->op_first);
13161     if (kid->op_type != OP_NULL)
13162         Perl_croak(aTHX_ "panic: ck_grep, type=%u", (unsigned) kid->op_type);
13163     kid = kUNOP->op_first;
13164
13165     gwop = alloc_LOGOP(type, o, LINKLIST(kid));
13166     kid->op_next = (OP*)gwop;
13167     o->op_private = gwop->op_private = 0;
13168     gwop->op_targ = pad_alloc(type, SVs_PADTMP);
13169
13170     kid = OpSIBLING(cLISTOPo->op_first);
13171     for (kid = OpSIBLING(kid); kid; kid = OpSIBLING(kid))
13172         op_lvalue(kid, OP_GREPSTART);
13173
13174     return (OP*)gwop;
13175 }
13176
13177 OP *
13178 Perl_ck_index(pTHX_ OP *o)
13179 {
13180     PERL_ARGS_ASSERT_CK_INDEX;
13181
13182     if (o->op_flags & OPf_KIDS) {
13183         OP *kid = OpSIBLING(cLISTOPo->op_first);        /* get past pushmark */
13184         if (kid)
13185             kid = OpSIBLING(kid);                       /* get past "big" */
13186         if (kid && kid->op_type == OP_CONST) {
13187             const bool save_taint = TAINT_get;
13188             SV *sv = kSVOP->op_sv;
13189             if (   (!SvPOK(sv) || SvNIOKp(sv) || isREGEXP(sv))
13190                 && SvOK(sv) && !SvROK(sv))
13191             {
13192                 sv = newSV(0);
13193                 sv_copypv(sv, kSVOP->op_sv);
13194                 SvREFCNT_dec_NN(kSVOP->op_sv);
13195                 kSVOP->op_sv = sv;
13196             }
13197             if (SvOK(sv)) fbm_compile(sv, 0);
13198             TAINT_set(save_taint);
13199 #ifdef NO_TAINT_SUPPORT
13200             PERL_UNUSED_VAR(save_taint);
13201 #endif
13202         }
13203     }
13204     return ck_fun(o);
13205 }
13206
13207 OP *
13208 Perl_ck_lfun(pTHX_ OP *o)
13209 {
13210     const OPCODE type = o->op_type;
13211
13212     PERL_ARGS_ASSERT_CK_LFUN;
13213
13214     return modkids(ck_fun(o), type);
13215 }
13216
13217 OP *
13218 Perl_ck_defined(pTHX_ OP *o)            /* 19990527 MJD */
13219 {
13220     PERL_ARGS_ASSERT_CK_DEFINED;
13221
13222     if ((o->op_flags & OPf_KIDS)) {
13223         switch (cUNOPo->op_first->op_type) {
13224         case OP_RV2AV:
13225         case OP_PADAV:
13226             Perl_croak(aTHX_ "Can't use 'defined(@array)'"
13227                              " (Maybe you should just omit the defined()?)");
13228             NOT_REACHED; /* NOTREACHED */
13229             break;
13230         case OP_RV2HV:
13231         case OP_PADHV:
13232             Perl_croak(aTHX_ "Can't use 'defined(%%hash)'"
13233                              " (Maybe you should just omit the defined()?)");
13234             NOT_REACHED; /* NOTREACHED */
13235             break;
13236         default:
13237             /* no warning */
13238             break;
13239         }
13240     }
13241     return ck_rfun(o);
13242 }
13243
13244 OP *
13245 Perl_ck_readline(pTHX_ OP *o)
13246 {
13247     PERL_ARGS_ASSERT_CK_READLINE;
13248
13249     if (o->op_flags & OPf_KIDS) {
13250          OP *kid = cLISTOPo->op_first;
13251          if (kid->op_type == OP_RV2GV) kid->op_private |= OPpALLOW_FAKE;
13252          scalar(kid);
13253     }
13254     else {
13255         OP * const newop
13256             = newUNOP(OP_READLINE, 0, newGVOP(OP_GV, 0, PL_argvgv));
13257         op_free(o);
13258         return newop;
13259     }
13260     return o;
13261 }
13262
13263 OP *
13264 Perl_ck_rfun(pTHX_ OP *o)
13265 {
13266     const OPCODE type = o->op_type;
13267
13268     PERL_ARGS_ASSERT_CK_RFUN;
13269
13270     return refkids(ck_fun(o), type);
13271 }
13272
13273 OP *
13274 Perl_ck_listiob(pTHX_ OP *o)
13275 {
13276     OP *kid;
13277
13278     PERL_ARGS_ASSERT_CK_LISTIOB;
13279
13280     kid = cLISTOPo->op_first;
13281     if (!kid) {
13282         o = force_list(o, 1);
13283         kid = cLISTOPo->op_first;
13284     }
13285     if (kid->op_type == OP_PUSHMARK)
13286         kid = OpSIBLING(kid);
13287     if (kid && o->op_flags & OPf_STACKED)
13288         kid = OpSIBLING(kid);
13289     else if (kid && !OpHAS_SIBLING(kid)) {              /* print HANDLE; */
13290         if (kid->op_type == OP_CONST && kid->op_private & OPpCONST_BARE
13291          && !kid->op_folded) {
13292             o->op_flags |= OPf_STACKED; /* make it a filehandle */
13293             scalar(kid);
13294             /* replace old const op with new OP_RV2GV parent */
13295             kid = S_op_sibling_newUNOP(aTHX_ o, cLISTOPo->op_first,
13296                                         OP_RV2GV, OPf_REF);
13297             kid = OpSIBLING(kid);
13298         }
13299     }
13300
13301     if (!kid)
13302         op_append_elem(o->op_type, o, newDEFSVOP());
13303
13304     if (o->op_type == OP_PRTF) return modkids(listkids(o), OP_PRTF);
13305     return listkids(o);
13306 }
13307
13308 OP *
13309 Perl_ck_smartmatch(pTHX_ OP *o)
13310 {
13311     dVAR;
13312     PERL_ARGS_ASSERT_CK_SMARTMATCH;
13313     if (0 == (o->op_flags & OPf_SPECIAL)) {
13314         OP *first  = cBINOPo->op_first;
13315         OP *second = OpSIBLING(first);
13316
13317         /* Implicitly take a reference to an array or hash */
13318
13319         /* remove the original two siblings, then add back the
13320          * (possibly different) first and second sibs.
13321          */
13322         op_sibling_splice(o, NULL, 1, NULL);
13323         op_sibling_splice(o, NULL, 1, NULL);
13324         first  = ref_array_or_hash(first);
13325         second = ref_array_or_hash(second);
13326         op_sibling_splice(o, NULL, 0, second);
13327         op_sibling_splice(o, NULL, 0, first);
13328
13329         /* Implicitly take a reference to a regular expression */
13330         if (first->op_type == OP_MATCH && !(first->op_flags & OPf_STACKED)) {
13331             OpTYPE_set(first, OP_QR);
13332         }
13333         if (second->op_type == OP_MATCH && !(second->op_flags & OPf_STACKED)) {
13334             OpTYPE_set(second, OP_QR);
13335         }
13336     }
13337
13338     return o;
13339 }
13340
13341
13342 static OP *
13343 S_maybe_targlex(pTHX_ OP *o)
13344 {
13345     OP * const kid = cLISTOPo->op_first;
13346     /* has a disposable target? */
13347     if ((PL_opargs[kid->op_type] & OA_TARGLEX)
13348         && !(kid->op_flags & OPf_STACKED)
13349         /* Cannot steal the second time! */
13350         && !(kid->op_private & OPpTARGET_MY)
13351         )
13352     {
13353         OP * const kkid = OpSIBLING(kid);
13354
13355         /* Can just relocate the target. */
13356         if (kkid && kkid->op_type == OP_PADSV
13357             && (!(kkid->op_private & OPpLVAL_INTRO)
13358                || kkid->op_private & OPpPAD_STATE))
13359         {
13360             kid->op_targ = kkid->op_targ;
13361             kkid->op_targ = 0;
13362             /* Now we do not need PADSV and SASSIGN.
13363              * Detach kid and free the rest. */
13364             op_sibling_splice(o, NULL, 1, NULL);
13365             op_free(o);
13366             kid->op_private |= OPpTARGET_MY;    /* Used for context settings */
13367             return kid;
13368         }
13369     }
13370     return o;
13371 }
13372
13373 OP *
13374 Perl_ck_sassign(pTHX_ OP *o)
13375 {
13376     dVAR;
13377     OP * const kid = cBINOPo->op_first;
13378
13379     PERL_ARGS_ASSERT_CK_SASSIGN;
13380
13381     if (OpHAS_SIBLING(kid)) {
13382         OP *kkid = OpSIBLING(kid);
13383         /* For state variable assignment with attributes, kkid is a list op
13384            whose op_last is a padsv. */
13385         if ((kkid->op_type == OP_PADSV ||
13386              (OP_TYPE_IS_OR_WAS(kkid, OP_LIST) &&
13387               (kkid = cLISTOPx(kkid)->op_last)->op_type == OP_PADSV
13388              )
13389             )
13390                 && (kkid->op_private & (OPpLVAL_INTRO|OPpPAD_STATE))
13391                     == (OPpLVAL_INTRO|OPpPAD_STATE)) {
13392             return S_newONCEOP(aTHX_ o, kkid);
13393         }
13394     }
13395     return S_maybe_targlex(aTHX_ o);
13396 }
13397
13398
13399 OP *
13400 Perl_ck_match(pTHX_ OP *o)
13401 {
13402     PERL_UNUSED_CONTEXT;
13403     PERL_ARGS_ASSERT_CK_MATCH;
13404
13405     return o;
13406 }
13407
13408 OP *
13409 Perl_ck_method(pTHX_ OP *o)
13410 {
13411     SV *sv, *methsv, *rclass;
13412     const char* method;
13413     char* compatptr;
13414     int utf8;
13415     STRLEN len, nsplit = 0, i;
13416     OP* new_op;
13417     OP * const kid = cUNOPo->op_first;
13418
13419     PERL_ARGS_ASSERT_CK_METHOD;
13420     if (kid->op_type != OP_CONST) return o;
13421
13422     sv = kSVOP->op_sv;
13423
13424     /* replace ' with :: */
13425     while ((compatptr = (char *) memchr(SvPVX(sv), '\'',
13426                                         SvEND(sv) - SvPVX(sv) )))
13427     {
13428         *compatptr = ':';
13429         sv_insert(sv, compatptr - SvPVX_const(sv), 0, ":", 1);
13430     }
13431
13432     method = SvPVX_const(sv);
13433     len = SvCUR(sv);
13434     utf8 = SvUTF8(sv) ? -1 : 1;
13435
13436     for (i = len - 1; i > 0; --i) if (method[i] == ':') {
13437         nsplit = i+1;
13438         break;
13439     }
13440
13441     methsv = newSVpvn_share(method+nsplit, utf8*(len - nsplit), 0);
13442
13443     if (!nsplit) { /* $proto->method() */
13444         op_free(o);
13445         return newMETHOP_named(OP_METHOD_NAMED, 0, methsv);
13446     }
13447
13448     if (memEQs(method, nsplit, "SUPER::")) { /* $proto->SUPER::method() */
13449         op_free(o);
13450         return newMETHOP_named(OP_METHOD_SUPER, 0, methsv);
13451     }
13452
13453     /* $proto->MyClass::method() and $proto->MyClass::SUPER::method() */
13454     if (nsplit >= 9 && strBEGINs(method+nsplit-9, "::SUPER::")) {
13455         rclass = newSVpvn_share(method, utf8*(nsplit-9), 0);
13456         new_op = newMETHOP_named(OP_METHOD_REDIR_SUPER, 0, methsv);
13457     } else {
13458         rclass = newSVpvn_share(method, utf8*(nsplit-2), 0);
13459         new_op = newMETHOP_named(OP_METHOD_REDIR, 0, methsv);
13460     }
13461 #ifdef USE_ITHREADS
13462     op_relocate_sv(&rclass, &cMETHOPx(new_op)->op_rclass_targ);
13463 #else
13464     cMETHOPx(new_op)->op_rclass_sv = rclass;
13465 #endif
13466     op_free(o);
13467     return new_op;
13468 }
13469
13470 OP *
13471 Perl_ck_null(pTHX_ OP *o)
13472 {
13473     PERL_ARGS_ASSERT_CK_NULL;
13474     PERL_UNUSED_CONTEXT;
13475     return o;
13476 }
13477
13478 OP *
13479 Perl_ck_open(pTHX_ OP *o)
13480 {
13481     PERL_ARGS_ASSERT_CK_OPEN;
13482
13483     S_io_hints(aTHX_ o);
13484     {
13485          /* In case of three-arg dup open remove strictness
13486           * from the last arg if it is a bareword. */
13487          OP * const first = cLISTOPx(o)->op_first; /* The pushmark. */
13488          OP * const last  = cLISTOPx(o)->op_last;  /* The bareword. */
13489          OP *oa;
13490          const char *mode;
13491
13492          if ((last->op_type == OP_CONST) &&             /* The bareword. */
13493              (last->op_private & OPpCONST_BARE) &&
13494              (last->op_private & OPpCONST_STRICT) &&
13495              (oa = OpSIBLING(first)) &&         /* The fh. */
13496              (oa = OpSIBLING(oa)) &&                    /* The mode. */
13497              (oa->op_type == OP_CONST) &&
13498              SvPOK(((SVOP*)oa)->op_sv) &&
13499              (mode = SvPVX_const(((SVOP*)oa)->op_sv)) &&
13500              mode[0] == '>' && mode[1] == '&' &&        /* A dup open. */
13501              (last == OpSIBLING(oa)))                   /* The bareword. */
13502               last->op_private &= ~OPpCONST_STRICT;
13503     }
13504     return ck_fun(o);
13505 }
13506
13507 OP *
13508 Perl_ck_prototype(pTHX_ OP *o)
13509 {
13510     PERL_ARGS_ASSERT_CK_PROTOTYPE;
13511     if (!(o->op_flags & OPf_KIDS)) {
13512         op_free(o);
13513         return newUNOP(OP_PROTOTYPE, 0, newDEFSVOP());
13514     }
13515     return o;
13516 }
13517
13518 OP *
13519 Perl_ck_refassign(pTHX_ OP *o)
13520 {
13521     OP * const right = cLISTOPo->op_first;
13522     OP * const left = OpSIBLING(right);
13523     OP *varop = cUNOPx(cUNOPx(left)->op_first)->op_first;
13524     bool stacked = 0;
13525
13526     PERL_ARGS_ASSERT_CK_REFASSIGN;
13527     assert (left);
13528     assert (left->op_type == OP_SREFGEN);
13529
13530     o->op_private = 0;
13531     /* we use OPpPAD_STATE in refassign to mean either of those things,
13532      * and the code assumes the two flags occupy the same bit position
13533      * in the various ops below */
13534     assert(OPpPAD_STATE == OPpOUR_INTRO);
13535
13536     switch (varop->op_type) {
13537     case OP_PADAV:
13538         o->op_private |= OPpLVREF_AV;
13539         goto settarg;
13540     case OP_PADHV:
13541         o->op_private |= OPpLVREF_HV;
13542         /* FALLTHROUGH */
13543     case OP_PADSV:
13544       settarg:
13545         o->op_private |= (varop->op_private & (OPpLVAL_INTRO|OPpPAD_STATE));
13546         o->op_targ = varop->op_targ;
13547         varop->op_targ = 0;
13548         PAD_COMPNAME_GEN_set(o->op_targ, PERL_INT_MAX);
13549         break;
13550
13551     case OP_RV2AV:
13552         o->op_private |= OPpLVREF_AV;
13553         goto checkgv;
13554         NOT_REACHED; /* NOTREACHED */
13555     case OP_RV2HV:
13556         o->op_private |= OPpLVREF_HV;
13557         /* FALLTHROUGH */
13558     case OP_RV2SV:
13559       checkgv:
13560         o->op_private |= (varop->op_private & (OPpLVAL_INTRO|OPpOUR_INTRO));
13561         if (cUNOPx(varop)->op_first->op_type != OP_GV) goto bad;
13562       detach_and_stack:
13563         /* Point varop to its GV kid, detached.  */
13564         varop = op_sibling_splice(varop, NULL, -1, NULL);
13565         stacked = TRUE;
13566         break;
13567     case OP_RV2CV: {
13568         OP * const kidparent =
13569             OpSIBLING(cUNOPx(cUNOPx(varop)->op_first)->op_first);
13570         OP * const kid = cUNOPx(kidparent)->op_first;
13571         o->op_private |= OPpLVREF_CV;
13572         if (kid->op_type == OP_GV) {
13573             SV *sv = (SV*)cGVOPx_gv(kid);
13574             varop = kidparent;
13575             if (SvROK(sv) && SvTYPE(SvRV(sv)) == SVt_PVCV) {
13576                 /* a CVREF here confuses pp_refassign, so make sure
13577                    it gets a GV */
13578                 CV *const cv = (CV*)SvRV(sv);
13579                 SV *name_sv = sv_2mortal(newSVhek(CvNAME_HEK(cv)));
13580                 (void)gv_init_sv((GV*)sv, CvSTASH(cv), name_sv, 0);
13581                 assert(SvTYPE(sv) == SVt_PVGV);
13582             }
13583             goto detach_and_stack;
13584         }
13585         if (kid->op_type != OP_PADCV)   goto bad;
13586         o->op_targ = kid->op_targ;
13587         kid->op_targ = 0;
13588         break;
13589     }
13590     case OP_AELEM:
13591     case OP_HELEM:
13592         o->op_private |= (varop->op_private & OPpLVAL_INTRO);
13593         o->op_private |= OPpLVREF_ELEM;
13594         op_null(varop);
13595         stacked = TRUE;
13596         /* Detach varop.  */
13597         op_sibling_splice(cUNOPx(left)->op_first, NULL, -1, NULL);
13598         break;
13599     default:
13600       bad:
13601         /* diag_listed_as: Can't modify reference to %s in %s assignment */
13602         yyerror(Perl_form(aTHX_ "Can't modify reference to %s in scalar "
13603                                 "assignment",
13604                                  OP_DESC(varop)));
13605         return o;
13606     }
13607     if (!FEATURE_REFALIASING_IS_ENABLED)
13608         Perl_croak(aTHX_
13609                   "Experimental aliasing via reference not enabled");
13610     Perl_ck_warner_d(aTHX_
13611                      packWARN(WARN_EXPERIMENTAL__REFALIASING),
13612                     "Aliasing via reference is experimental");
13613     if (stacked) {
13614         o->op_flags |= OPf_STACKED;
13615         op_sibling_splice(o, right, 1, varop);
13616     }
13617     else {
13618         o->op_flags &=~ OPf_STACKED;
13619         op_sibling_splice(o, right, 1, NULL);
13620     }
13621     op_free(left);
13622     return o;
13623 }
13624
13625 OP *
13626 Perl_ck_repeat(pTHX_ OP *o)
13627 {
13628     PERL_ARGS_ASSERT_CK_REPEAT;
13629
13630     if (cBINOPo->op_first->op_flags & OPf_PARENS) {
13631         OP* kids;
13632         o->op_private |= OPpREPEAT_DOLIST;
13633         kids = op_sibling_splice(o, NULL, 1, NULL); /* detach first kid */
13634         kids = force_list(kids, 1); /* promote it to a list */
13635         op_sibling_splice(o, NULL, 0, kids); /* and add back */
13636     }
13637     else
13638         scalar(o);
13639     return o;
13640 }
13641
13642 OP *
13643 Perl_ck_require(pTHX_ OP *o)
13644 {
13645     GV* gv;
13646
13647     PERL_ARGS_ASSERT_CK_REQUIRE;
13648
13649     if (o->op_flags & OPf_KIDS) {       /* Shall we supply missing .pm? */
13650         SVOP * const kid = (SVOP*)cUNOPo->op_first;
13651         U32 hash;
13652         char *s;
13653         STRLEN len;
13654         if (kid->op_type == OP_CONST) {
13655           SV * const sv = kid->op_sv;
13656           U32 const was_readonly = SvREADONLY(sv);
13657           if (kid->op_private & OPpCONST_BARE) {
13658             dVAR;
13659             const char *end;
13660             HEK *hek;
13661
13662             if (was_readonly) {
13663                 SvREADONLY_off(sv);
13664             }
13665
13666             if (SvIsCOW(sv)) sv_force_normal_flags(sv, 0);
13667
13668             s = SvPVX(sv);
13669             len = SvCUR(sv);
13670             end = s + len;
13671             /* treat ::foo::bar as foo::bar */
13672             if (len >= 2 && s[0] == ':' && s[1] == ':')
13673                 DIE(aTHX_ "Bareword in require must not start with a double-colon: \"%s\"\n", s);
13674             if (s == end)
13675                 DIE(aTHX_ "Bareword in require maps to empty filename");
13676
13677             for (; s < end; s++) {
13678                 if (*s == ':' && s[1] == ':') {
13679                     *s = '/';
13680                     Move(s+2, s+1, end - s - 1, char);
13681                     --end;
13682                 }
13683             }
13684             SvEND_set(sv, end);
13685             sv_catpvs(sv, ".pm");
13686             PERL_HASH(hash, SvPVX(sv), SvCUR(sv));
13687             hek = share_hek(SvPVX(sv),
13688                             (SSize_t)SvCUR(sv) * (SvUTF8(sv) ? -1 : 1),
13689                             hash);
13690             sv_sethek(sv, hek);
13691             unshare_hek(hek);
13692             SvFLAGS(sv) |= was_readonly;
13693           }
13694           else if (SvPOK(sv) && !SvNIOK(sv) && !SvGMAGICAL(sv)
13695                 && !SvVOK(sv)) {
13696             s = SvPV(sv, len);
13697             if (SvREFCNT(sv) > 1) {
13698                 kid->op_sv = newSVpvn_share(
13699                     s, SvUTF8(sv) ? -(SSize_t)len : (SSize_t)len, 0);
13700                 SvREFCNT_dec_NN(sv);
13701             }
13702             else {
13703                 dVAR;
13704                 HEK *hek;
13705                 if (was_readonly) SvREADONLY_off(sv);
13706                 PERL_HASH(hash, s, len);
13707                 hek = share_hek(s,
13708                                 SvUTF8(sv) ? -(SSize_t)len : (SSize_t)len,
13709                                 hash);
13710                 sv_sethek(sv, hek);
13711                 unshare_hek(hek);
13712                 SvFLAGS(sv) |= was_readonly;
13713             }
13714           }
13715         }
13716     }
13717
13718     if (!(o->op_flags & OPf_SPECIAL) /* Wasn't written as CORE::require */
13719         /* handle override, if any */
13720      && (gv = gv_override("require", 7))) {
13721         OP *kid, *newop;
13722         if (o->op_flags & OPf_KIDS) {
13723             kid = cUNOPo->op_first;
13724             op_sibling_splice(o, NULL, -1, NULL);
13725         }
13726         else {
13727             kid = newDEFSVOP();
13728         }
13729         op_free(o);
13730         newop = S_new_entersubop(aTHX_ gv, kid);
13731         return newop;
13732     }
13733
13734     return ck_fun(o);
13735 }
13736
13737 OP *
13738 Perl_ck_return(pTHX_ OP *o)
13739 {
13740     OP *kid;
13741
13742     PERL_ARGS_ASSERT_CK_RETURN;
13743
13744     kid = OpSIBLING(cLISTOPo->op_first);
13745     if (PL_compcv && CvLVALUE(PL_compcv)) {
13746         for (; kid; kid = OpSIBLING(kid))
13747             op_lvalue(kid, OP_LEAVESUBLV);
13748     }
13749
13750     return o;
13751 }
13752
13753 OP *
13754 Perl_ck_select(pTHX_ OP *o)
13755 {
13756     dVAR;
13757     OP* kid;
13758
13759     PERL_ARGS_ASSERT_CK_SELECT;
13760
13761     if (o->op_flags & OPf_KIDS) {
13762         kid = OpSIBLING(cLISTOPo->op_first);     /* get past pushmark */
13763         if (kid && OpHAS_SIBLING(kid)) {
13764             OpTYPE_set(o, OP_SSELECT);
13765             o = ck_fun(o);
13766             return fold_constants(op_integerize(op_std_init(o)));
13767         }
13768     }
13769     o = ck_fun(o);
13770     kid = OpSIBLING(cLISTOPo->op_first);    /* get past pushmark */
13771     if (kid && kid->op_type == OP_RV2GV)
13772         kid->op_private &= ~HINT_STRICT_REFS;
13773     return o;
13774 }
13775
13776 OP *
13777 Perl_ck_shift(pTHX_ OP *o)
13778 {
13779     const I32 type = o->op_type;
13780
13781     PERL_ARGS_ASSERT_CK_SHIFT;
13782
13783     if (!(o->op_flags & OPf_KIDS)) {
13784         OP *argop;
13785
13786         if (!CvUNIQUE(PL_compcv)) {
13787             o->op_flags |= OPf_SPECIAL;
13788             return o;
13789         }
13790
13791         argop = newUNOP(OP_RV2AV, 0, scalar(newGVOP(OP_GV, 0, PL_argvgv)));
13792         op_free(o);
13793         return newUNOP(type, 0, scalar(argop));
13794     }
13795     return scalar(ck_fun(o));
13796 }
13797
13798 OP *
13799 Perl_ck_sort(pTHX_ OP *o)
13800 {
13801     OP *firstkid;
13802     OP *kid;
13803     HV * const hinthv =
13804         PL_hints & HINT_LOCALIZE_HH ? GvHV(PL_hintgv) : NULL;
13805     U8 stacked;
13806
13807     PERL_ARGS_ASSERT_CK_SORT;
13808
13809     if (hinthv) {
13810             SV ** const svp = hv_fetchs(hinthv, "sort", FALSE);
13811             if (svp) {
13812                 const I32 sorthints = (I32)SvIV(*svp);
13813                 if ((sorthints & HINT_SORT_STABLE) != 0)
13814                     o->op_private |= OPpSORT_STABLE;
13815                 if ((sorthints & HINT_SORT_UNSTABLE) != 0)
13816                     o->op_private |= OPpSORT_UNSTABLE;
13817             }
13818     }
13819
13820     if (o->op_flags & OPf_STACKED)
13821         simplify_sort(o);
13822     firstkid = OpSIBLING(cLISTOPo->op_first);           /* get past pushmark */
13823
13824     if ((stacked = o->op_flags & OPf_STACKED)) {        /* may have been cleared */
13825         OP *kid = cUNOPx(firstkid)->op_first;           /* get past null */
13826
13827         /* if the first arg is a code block, process it and mark sort as
13828          * OPf_SPECIAL */
13829         if (kid->op_type == OP_SCOPE || kid->op_type == OP_LEAVE) {
13830             LINKLIST(kid);
13831             if (kid->op_type == OP_LEAVE)
13832                     op_null(kid);                       /* wipe out leave */
13833             /* Prevent execution from escaping out of the sort block. */
13834             kid->op_next = 0;
13835
13836             /* provide scalar context for comparison function/block */
13837             kid = scalar(firstkid);
13838             kid->op_next = kid;
13839             o->op_flags |= OPf_SPECIAL;
13840         }
13841         else if (kid->op_type == OP_CONST
13842               && kid->op_private & OPpCONST_BARE) {
13843             char tmpbuf[256];
13844             STRLEN len;
13845             PADOFFSET off;
13846             const char * const name = SvPV(kSVOP_sv, len);
13847             *tmpbuf = '&';
13848             assert (len < 256);
13849             Copy(name, tmpbuf+1, len, char);
13850             off = pad_findmy_pvn(tmpbuf, len+1, 0);
13851             if (off != NOT_IN_PAD) {
13852                 if (PAD_COMPNAME_FLAGS_isOUR(off)) {
13853                     SV * const fq =
13854                         newSVhek(HvNAME_HEK(PAD_COMPNAME_OURSTASH(off)));
13855                     sv_catpvs(fq, "::");
13856                     sv_catsv(fq, kSVOP_sv);
13857                     SvREFCNT_dec_NN(kSVOP_sv);
13858                     kSVOP->op_sv = fq;
13859                 }
13860                 else {
13861                     OP * const padop = newOP(OP_PADCV, 0);
13862                     padop->op_targ = off;
13863                     /* replace the const op with the pad op */
13864                     op_sibling_splice(firstkid, NULL, 1, padop);
13865                     op_free(kid);
13866                 }
13867             }
13868         }
13869
13870         firstkid = OpSIBLING(firstkid);
13871     }
13872
13873     for (kid = firstkid; kid; kid = OpSIBLING(kid)) {
13874         /* provide list context for arguments */
13875         list(kid);
13876         if (stacked)
13877             op_lvalue(kid, OP_GREPSTART);
13878     }
13879
13880     return o;
13881 }
13882
13883 /* for sort { X } ..., where X is one of
13884  *   $a <=> $b, $b <=> $a, $a cmp $b, $b cmp $a
13885  * elide the second child of the sort (the one containing X),
13886  * and set these flags as appropriate
13887         OPpSORT_NUMERIC;
13888         OPpSORT_INTEGER;
13889         OPpSORT_DESCEND;
13890  * Also, check and warn on lexical $a, $b.
13891  */
13892
13893 STATIC void
13894 S_simplify_sort(pTHX_ OP *o)
13895 {
13896     OP *kid = OpSIBLING(cLISTOPo->op_first);    /* get past pushmark */
13897     OP *k;
13898     int descending;
13899     GV *gv;
13900     const char *gvname;
13901     bool have_scopeop;
13902
13903     PERL_ARGS_ASSERT_SIMPLIFY_SORT;
13904
13905     kid = kUNOP->op_first;                              /* get past null */
13906     if (!(have_scopeop = kid->op_type == OP_SCOPE)
13907      && kid->op_type != OP_LEAVE)
13908         return;
13909     kid = kLISTOP->op_last;                             /* get past scope */
13910     switch(kid->op_type) {
13911         case OP_NCMP:
13912         case OP_I_NCMP:
13913         case OP_SCMP:
13914             if (!have_scopeop) goto padkids;
13915             break;
13916         default:
13917             return;
13918     }
13919     k = kid;                                            /* remember this node*/
13920     if (kBINOP->op_first->op_type != OP_RV2SV
13921      || kBINOP->op_last ->op_type != OP_RV2SV)
13922     {
13923         /*
13924            Warn about my($a) or my($b) in a sort block, *if* $a or $b is
13925            then used in a comparison.  This catches most, but not
13926            all cases.  For instance, it catches
13927                sort { my($a); $a <=> $b }
13928            but not
13929                sort { my($a); $a < $b ? -1 : $a == $b ? 0 : 1; }
13930            (although why you'd do that is anyone's guess).
13931         */
13932
13933        padkids:
13934         if (!ckWARN(WARN_SYNTAX)) return;
13935         kid = kBINOP->op_first;
13936         do {
13937             if (kid->op_type == OP_PADSV) {
13938                 PADNAME * const name = PAD_COMPNAME(kid->op_targ);
13939                 if (PadnameLEN(name) == 2 && *PadnamePV(name) == '$'
13940                  && (  PadnamePV(name)[1] == 'a'
13941                     || PadnamePV(name)[1] == 'b'  ))
13942                     /* diag_listed_as: "my %s" used in sort comparison */
13943                     Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
13944                                      "\"%s %s\" used in sort comparison",
13945                                       PadnameIsSTATE(name)
13946                                         ? "state"
13947                                         : "my",
13948                                       PadnamePV(name));
13949             }
13950         } while ((kid = OpSIBLING(kid)));
13951         return;
13952     }
13953     kid = kBINOP->op_first;                             /* get past cmp */
13954     if (kUNOP->op_first->op_type != OP_GV)
13955         return;
13956     kid = kUNOP->op_first;                              /* get past rv2sv */
13957     gv = kGVOP_gv;
13958     if (GvSTASH(gv) != PL_curstash)
13959         return;
13960     gvname = GvNAME(gv);
13961     if (*gvname == 'a' && gvname[1] == '\0')
13962         descending = 0;
13963     else if (*gvname == 'b' && gvname[1] == '\0')
13964         descending = 1;
13965     else
13966         return;
13967
13968     kid = k;                                            /* back to cmp */
13969     /* already checked above that it is rv2sv */
13970     kid = kBINOP->op_last;                              /* down to 2nd arg */
13971     if (kUNOP->op_first->op_type != OP_GV)
13972         return;
13973     kid = kUNOP->op_first;                              /* get past rv2sv */
13974     gv = kGVOP_gv;
13975     if (GvSTASH(gv) != PL_curstash)
13976         return;
13977     gvname = GvNAME(gv);
13978     if ( descending
13979          ? !(*gvname == 'a' && gvname[1] == '\0')
13980          : !(*gvname == 'b' && gvname[1] == '\0'))
13981         return;
13982     o->op_flags &= ~(OPf_STACKED | OPf_SPECIAL);
13983     if (descending)
13984         o->op_private |= OPpSORT_DESCEND;
13985     if (k->op_type == OP_NCMP)
13986         o->op_private |= OPpSORT_NUMERIC;
13987     if (k->op_type == OP_I_NCMP)
13988         o->op_private |= OPpSORT_NUMERIC | OPpSORT_INTEGER;
13989     kid = OpSIBLING(cLISTOPo->op_first);
13990     /* cut out and delete old block (second sibling) */
13991     op_sibling_splice(o, cLISTOPo->op_first, 1, NULL);
13992     op_free(kid);
13993 }
13994
13995 OP *
13996 Perl_ck_split(pTHX_ OP *o)
13997 {
13998     dVAR;
13999     OP *kid;
14000     OP *sibs;
14001
14002     PERL_ARGS_ASSERT_CK_SPLIT;
14003
14004     assert(o->op_type == OP_LIST);
14005
14006     if (o->op_flags & OPf_STACKED)
14007         return no_fh_allowed(o);
14008
14009     kid = cLISTOPo->op_first;
14010     /* delete leading NULL node, then add a CONST if no other nodes */
14011     assert(kid->op_type == OP_NULL);
14012     op_sibling_splice(o, NULL, 1,
14013         OpHAS_SIBLING(kid) ? NULL : newSVOP(OP_CONST, 0, newSVpvs(" ")));
14014     op_free(kid);
14015     kid = cLISTOPo->op_first;
14016
14017     if (kid->op_type != OP_MATCH || kid->op_flags & OPf_STACKED) {
14018         /* remove match expression, and replace with new optree with
14019          * a match op at its head */
14020         op_sibling_splice(o, NULL, 1, NULL);
14021         /* pmruntime will handle split " " behavior with flag==2 */
14022         kid = pmruntime(newPMOP(OP_MATCH, 0), kid, NULL, 2, 0);
14023         op_sibling_splice(o, NULL, 0, kid);
14024     }
14025
14026     assert(kid->op_type == OP_MATCH || kid->op_type == OP_SPLIT);
14027
14028     if (((PMOP *)kid)->op_pmflags & PMf_GLOBAL) {
14029       Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP),
14030                      "Use of /g modifier is meaningless in split");
14031     }
14032
14033     /* eliminate the split op, and move the match op (plus any children)
14034      * into its place, then convert the match op into a split op. i.e.
14035      *
14036      *  SPLIT                    MATCH                 SPLIT(ex-MATCH)
14037      *    |                        |                     |
14038      *  MATCH - A - B - C   =>     R - A - B - C   =>    R - A - B - C
14039      *    |                        |                     |
14040      *    R                        X - Y                 X - Y
14041      *    |
14042      *    X - Y
14043      *
14044      * (R, if it exists, will be a regcomp op)
14045      */
14046
14047     op_sibling_splice(o, NULL, 1, NULL); /* detach match op from o */
14048     sibs = op_sibling_splice(o, NULL, -1, NULL); /* detach any other sibs */
14049     op_sibling_splice(kid, cLISTOPx(kid)->op_last, 0, sibs); /* and reattach */
14050     OpTYPE_set(kid, OP_SPLIT);
14051     kid->op_flags   = (o->op_flags | (kid->op_flags & OPf_KIDS));
14052     kid->op_private = o->op_private;
14053     op_free(o);
14054     o = kid;
14055     kid = sibs; /* kid is now the string arg of the split */
14056
14057     if (!kid) {
14058         kid = newDEFSVOP();
14059         op_append_elem(OP_SPLIT, o, kid);
14060     }
14061     scalar(kid);
14062
14063     kid = OpSIBLING(kid);
14064     if (!kid) {
14065         kid = newSVOP(OP_CONST, 0, newSViv(0));
14066         op_append_elem(OP_SPLIT, o, kid);
14067         o->op_private |= OPpSPLIT_IMPLIM;
14068     }
14069     scalar(kid);
14070
14071     if (OpHAS_SIBLING(kid))
14072         return too_many_arguments_pv(o,OP_DESC(o), 0);
14073
14074     return o;
14075 }
14076
14077 OP *
14078 Perl_ck_stringify(pTHX_ OP *o)
14079 {
14080     OP * const kid = OpSIBLING(cUNOPo->op_first);
14081     PERL_ARGS_ASSERT_CK_STRINGIFY;
14082     if ((   kid->op_type == OP_JOIN || kid->op_type == OP_QUOTEMETA
14083          || kid->op_type == OP_LC   || kid->op_type == OP_LCFIRST
14084          || kid->op_type == OP_UC   || kid->op_type == OP_UCFIRST)
14085         && !OpHAS_SIBLING(kid)) /* syntax errs can leave extra children */
14086     {
14087         op_sibling_splice(o, cUNOPo->op_first, -1, NULL);
14088         op_free(o);
14089         return kid;
14090     }
14091     return ck_fun(o);
14092 }
14093
14094 OP *
14095 Perl_ck_join(pTHX_ OP *o)
14096 {
14097     OP * const kid = OpSIBLING(cLISTOPo->op_first);
14098
14099     PERL_ARGS_ASSERT_CK_JOIN;
14100
14101     if (kid && kid->op_type == OP_MATCH) {
14102         if (ckWARN(WARN_SYNTAX)) {
14103             const REGEXP *re = PM_GETRE(kPMOP);
14104             const SV *msg = re
14105                     ? newSVpvn_flags( RX_PRECOMP_const(re), RX_PRELEN(re),
14106                                             SVs_TEMP | ( RX_UTF8(re) ? SVf_UTF8 : 0 ) )
14107                     : newSVpvs_flags( "STRING", SVs_TEMP );
14108             Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
14109                         "/%" SVf "/ should probably be written as \"%" SVf "\"",
14110                         SVfARG(msg), SVfARG(msg));
14111         }
14112     }
14113     if (kid
14114      && (kid->op_type == OP_CONST /* an innocent, unsuspicious separator */
14115         || (kid->op_type == OP_PADSV && !(kid->op_private & OPpLVAL_INTRO))
14116         || (  kid->op_type==OP_RV2SV && kUNOP->op_first->op_type == OP_GV
14117            && !(kid->op_private & (OPpLVAL_INTRO|OPpOUR_INTRO)))))
14118     {
14119         const OP * const bairn = OpSIBLING(kid); /* the list */
14120         if (bairn && !OpHAS_SIBLING(bairn) /* single-item list */
14121          && OP_GIMME(bairn,0) == G_SCALAR)
14122         {
14123             OP * const ret = op_convert_list(OP_STRINGIFY, OPf_FOLDED,
14124                                      op_sibling_splice(o, kid, 1, NULL));
14125             op_free(o);
14126             return ret;
14127         }
14128     }
14129
14130     return ck_fun(o);
14131 }
14132
14133 /*
14134 =for apidoc rv2cv_op_cv
14135
14136 Examines an op, which is expected to identify a subroutine at runtime,
14137 and attempts to determine at compile time which subroutine it identifies.
14138 This is normally used during Perl compilation to determine whether
14139 a prototype can be applied to a function call.  C<cvop> is the op
14140 being considered, normally an C<rv2cv> op.  A pointer to the identified
14141 subroutine is returned, if it could be determined statically, and a null
14142 pointer is returned if it was not possible to determine statically.
14143
14144 Currently, the subroutine can be identified statically if the RV that the
14145 C<rv2cv> is to operate on is provided by a suitable C<gv> or C<const> op.
14146 A C<gv> op is suitable if the GV's CV slot is populated.  A C<const> op is
14147 suitable if the constant value must be an RV pointing to a CV.  Details of
14148 this process may change in future versions of Perl.  If the C<rv2cv> op
14149 has the C<OPpENTERSUB_AMPER> flag set then no attempt is made to identify
14150 the subroutine statically: this flag is used to suppress compile-time
14151 magic on a subroutine call, forcing it to use default runtime behaviour.
14152
14153 If C<flags> has the bit C<RV2CVOPCV_MARK_EARLY> set, then the handling
14154 of a GV reference is modified.  If a GV was examined and its CV slot was
14155 found to be empty, then the C<gv> op has the C<OPpEARLY_CV> flag set.
14156 If the op is not optimised away, and the CV slot is later populated with
14157 a subroutine having a prototype, that flag eventually triggers the warning
14158 "called too early to check prototype".
14159
14160 If C<flags> has the bit C<RV2CVOPCV_RETURN_NAME_GV> set, then instead
14161 of returning a pointer to the subroutine it returns a pointer to the
14162 GV giving the most appropriate name for the subroutine in this context.
14163 Normally this is just the C<CvGV> of the subroutine, but for an anonymous
14164 (C<CvANON>) subroutine that is referenced through a GV it will be the
14165 referencing GV.  The resulting C<GV*> is cast to C<CV*> to be returned.
14166 A null pointer is returned as usual if there is no statically-determinable
14167 subroutine.
14168
14169 =for apidoc Amnh||OPpEARLY_CV
14170 =for apidoc Amnh||OPpENTERSUB_AMPER
14171 =for apidoc Amnh||RV2CVOPCV_MARK_EARLY
14172 =for apidoc Amnh||RV2CVOPCV_RETURN_NAME_GV
14173
14174 =cut
14175 */
14176
14177 /* shared by toke.c:yylex */
14178 CV *
14179 Perl_find_lexical_cv(pTHX_ PADOFFSET off)
14180 {
14181     PADNAME *name = PAD_COMPNAME(off);
14182     CV *compcv = PL_compcv;
14183     while (PadnameOUTER(name)) {
14184         assert(PARENT_PAD_INDEX(name));
14185         compcv = CvOUTSIDE(compcv);
14186         name = PadlistNAMESARRAY(CvPADLIST(compcv))
14187                 [off = PARENT_PAD_INDEX(name)];
14188     }
14189     assert(!PadnameIsOUR(name));
14190     if (!PadnameIsSTATE(name) && PadnamePROTOCV(name)) {
14191         return PadnamePROTOCV(name);
14192     }
14193     return (CV *)AvARRAY(PadlistARRAY(CvPADLIST(compcv))[1])[off];
14194 }
14195
14196 CV *
14197 Perl_rv2cv_op_cv(pTHX_ OP *cvop, U32 flags)
14198 {
14199     OP *rvop;
14200     CV *cv;
14201     GV *gv;
14202     PERL_ARGS_ASSERT_RV2CV_OP_CV;
14203     if (flags & ~RV2CVOPCV_FLAG_MASK)
14204         Perl_croak(aTHX_ "panic: rv2cv_op_cv bad flags %x", (unsigned)flags);
14205     if (cvop->op_type != OP_RV2CV)
14206         return NULL;
14207     if (cvop->op_private & OPpENTERSUB_AMPER)
14208         return NULL;
14209     if (!(cvop->op_flags & OPf_KIDS))
14210         return NULL;
14211     rvop = cUNOPx(cvop)->op_first;
14212     switch (rvop->op_type) {
14213         case OP_GV: {
14214             gv = cGVOPx_gv(rvop);
14215             if (!isGV(gv)) {
14216                 if (SvROK(gv) && SvTYPE(SvRV(gv)) == SVt_PVCV) {
14217                     cv = MUTABLE_CV(SvRV(gv));
14218                     gv = NULL;
14219                     break;
14220                 }
14221                 if (flags & RV2CVOPCV_RETURN_STUB)
14222                     return (CV *)gv;
14223                 else return NULL;
14224             }
14225             cv = GvCVu(gv);
14226             if (!cv) {
14227                 if (flags & RV2CVOPCV_MARK_EARLY)
14228                     rvop->op_private |= OPpEARLY_CV;
14229                 return NULL;
14230             }
14231         } break;
14232         case OP_CONST: {
14233             SV *rv = cSVOPx_sv(rvop);
14234             if (!SvROK(rv))
14235                 return NULL;
14236             cv = (CV*)SvRV(rv);
14237             gv = NULL;
14238         } break;
14239         case OP_PADCV: {
14240             cv = find_lexical_cv(rvop->op_targ);
14241             gv = NULL;
14242         } break;
14243         default: {
14244             return NULL;
14245         } NOT_REACHED; /* NOTREACHED */
14246     }
14247     if (SvTYPE((SV*)cv) != SVt_PVCV)
14248         return NULL;
14249     if (flags & RV2CVOPCV_RETURN_NAME_GV) {
14250         if ((!CvANON(cv) && !CvLEXICAL(cv)) || !gv)
14251             gv = CvGV(cv);
14252         return (CV*)gv;
14253     }
14254     else if (flags & RV2CVOPCV_MAYBE_NAME_GV) {
14255         if (CvLEXICAL(cv) || CvNAMED(cv))
14256             return NULL;
14257         if (!CvANON(cv) || !gv)
14258             gv = CvGV(cv);
14259         return (CV*)gv;
14260
14261     } else {
14262         return cv;
14263     }
14264 }
14265
14266 /*
14267 =for apidoc ck_entersub_args_list
14268
14269 Performs the default fixup of the arguments part of an C<entersub>
14270 op tree.  This consists of applying list context to each of the
14271 argument ops.  This is the standard treatment used on a call marked
14272 with C<&>, or a method call, or a call through a subroutine reference,
14273 or any other call where the callee can't be identified at compile time,
14274 or a call where the callee has no prototype.
14275
14276 =cut
14277 */
14278
14279 OP *
14280 Perl_ck_entersub_args_list(pTHX_ OP *entersubop)
14281 {
14282     OP *aop;
14283
14284     PERL_ARGS_ASSERT_CK_ENTERSUB_ARGS_LIST;
14285
14286     aop = cUNOPx(entersubop)->op_first;
14287     if (!OpHAS_SIBLING(aop))
14288         aop = cUNOPx(aop)->op_first;
14289     for (aop = OpSIBLING(aop); OpHAS_SIBLING(aop); aop = OpSIBLING(aop)) {
14290         /* skip the extra attributes->import() call implicitly added in
14291          * something like foo(my $x : bar)
14292          */
14293         if (   aop->op_type == OP_ENTERSUB
14294             && (aop->op_flags & OPf_WANT) == OPf_WANT_VOID
14295         )
14296             continue;
14297         list(aop);
14298         op_lvalue(aop, OP_ENTERSUB);
14299     }
14300     return entersubop;
14301 }
14302
14303 /*
14304 =for apidoc ck_entersub_args_proto
14305
14306 Performs the fixup of the arguments part of an C<entersub> op tree
14307 based on a subroutine prototype.  This makes various modifications to
14308 the argument ops, from applying context up to inserting C<refgen> ops,
14309 and checking the number and syntactic types of arguments, as directed by
14310 the prototype.  This is the standard treatment used on a subroutine call,
14311 not marked with C<&>, where the callee can be identified at compile time
14312 and has a prototype.
14313
14314 C<protosv> supplies the subroutine prototype to be applied to the call.
14315 It may be a normal defined scalar, of which the string value will be used.
14316 Alternatively, for convenience, it may be a subroutine object (a C<CV*>
14317 that has been cast to C<SV*>) which has a prototype.  The prototype
14318 supplied, in whichever form, does not need to match the actual callee
14319 referenced by the op tree.
14320
14321 If the argument ops disagree with the prototype, for example by having
14322 an unacceptable number of arguments, a valid op tree is returned anyway.
14323 The error is reflected in the parser state, normally resulting in a single
14324 exception at the top level of parsing which covers all the compilation
14325 errors that occurred.  In the error message, the callee is referred to
14326 by the name defined by the C<namegv> parameter.
14327
14328 =cut
14329 */
14330
14331 OP *
14332 Perl_ck_entersub_args_proto(pTHX_ OP *entersubop, GV *namegv, SV *protosv)
14333 {
14334     STRLEN proto_len;
14335     const char *proto, *proto_end;
14336     OP *aop, *prev, *cvop, *parent;
14337     int optional = 0;
14338     I32 arg = 0;
14339     I32 contextclass = 0;
14340     const char *e = NULL;
14341     PERL_ARGS_ASSERT_CK_ENTERSUB_ARGS_PROTO;
14342     if (SvTYPE(protosv) == SVt_PVCV ? !SvPOK(protosv) : !SvOK(protosv))
14343         Perl_croak(aTHX_ "panic: ck_entersub_args_proto CV with no proto, "
14344                    "flags=%lx", (unsigned long) SvFLAGS(protosv));
14345     if (SvTYPE(protosv) == SVt_PVCV)
14346          proto = CvPROTO(protosv), proto_len = CvPROTOLEN(protosv);
14347     else proto = SvPV(protosv, proto_len);
14348     proto = S_strip_spaces(aTHX_ proto, &proto_len);
14349     proto_end = proto + proto_len;
14350     parent = entersubop;
14351     aop = cUNOPx(entersubop)->op_first;
14352     if (!OpHAS_SIBLING(aop)) {
14353         parent = aop;
14354         aop = cUNOPx(aop)->op_first;
14355     }
14356     prev = aop;
14357     aop = OpSIBLING(aop);
14358     for (cvop = aop; OpHAS_SIBLING(cvop); cvop = OpSIBLING(cvop)) ;
14359     while (aop != cvop) {
14360         OP* o3 = aop;
14361
14362         if (proto >= proto_end)
14363         {
14364             SV * const namesv = cv_name((CV *)namegv, NULL, 0);
14365             yyerror_pv(Perl_form(aTHX_ "Too many arguments for %" SVf,
14366                                         SVfARG(namesv)), SvUTF8(namesv));
14367             return entersubop;
14368         }
14369
14370         switch (*proto) {
14371             case ';':
14372                 optional = 1;
14373                 proto++;
14374                 continue;
14375             case '_':
14376                 /* _ must be at the end */
14377                 if (proto[1] && !memCHRs(";@%", proto[1]))
14378                     goto oops;
14379                 /* FALLTHROUGH */
14380             case '$':
14381                 proto++;
14382                 arg++;
14383                 scalar(aop);
14384                 break;
14385             case '%':
14386             case '@':
14387                 list(aop);
14388                 arg++;
14389                 break;
14390             case '&':
14391                 proto++;
14392                 arg++;
14393                 if (    o3->op_type != OP_UNDEF
14394                     && (o3->op_type != OP_SREFGEN
14395                         || (  cUNOPx(cUNOPx(o3)->op_first)->op_first->op_type
14396                                 != OP_ANONCODE
14397                             && cUNOPx(cUNOPx(o3)->op_first)->op_first->op_type
14398                                 != OP_RV2CV)))
14399                     bad_type_gv(arg, namegv, o3,
14400                             arg == 1 ? "block or sub {}" : "sub {}");
14401                 break;
14402             case '*':
14403                 /* '*' allows any scalar type, including bareword */
14404                 proto++;
14405                 arg++;
14406                 if (o3->op_type == OP_RV2GV)
14407                     goto wrapref;       /* autoconvert GLOB -> GLOBref */
14408                 else if (o3->op_type == OP_CONST)
14409                     o3->op_private &= ~OPpCONST_STRICT;
14410                 scalar(aop);
14411                 break;
14412             case '+':
14413                 proto++;
14414                 arg++;
14415                 if (o3->op_type == OP_RV2AV ||
14416                     o3->op_type == OP_PADAV ||
14417                     o3->op_type == OP_RV2HV ||
14418                     o3->op_type == OP_PADHV
14419                 ) {
14420                     goto wrapref;
14421                 }
14422                 scalar(aop);
14423                 break;
14424             case '[': case ']':
14425                 goto oops;
14426
14427             case '\\':
14428                 proto++;
14429                 arg++;
14430             again:
14431                 switch (*proto++) {
14432                     case '[':
14433                         if (contextclass++ == 0) {
14434                             e = (char *) memchr(proto, ']', proto_end - proto);
14435                             if (!e || e == proto)
14436                                 goto oops;
14437                         }
14438                         else
14439                             goto oops;
14440                         goto again;
14441
14442                     case ']':
14443                         if (contextclass) {
14444                             const char *p = proto;
14445                             const char *const end = proto;
14446                             contextclass = 0;
14447                             while (*--p != '[')
14448                                 /* \[$] accepts any scalar lvalue */
14449                                 if (*p == '$'
14450                                  && Perl_op_lvalue_flags(aTHX_
14451                                      scalar(o3),
14452                                      OP_READ, /* not entersub */
14453                                      OP_LVALUE_NO_CROAK
14454                                     )) goto wrapref;
14455                             bad_type_gv(arg, namegv, o3,
14456                                     Perl_form(aTHX_ "one of %.*s",(int)(end - p), p));
14457                         } else
14458                             goto oops;
14459                         break;
14460                     case '*':
14461                         if (o3->op_type == OP_RV2GV)
14462                             goto wrapref;
14463                         if (!contextclass)
14464                             bad_type_gv(arg, namegv, o3, "symbol");
14465                         break;
14466                     case '&':
14467                         if (o3->op_type == OP_ENTERSUB
14468                          && !(o3->op_flags & OPf_STACKED))
14469                             goto wrapref;
14470                         if (!contextclass)
14471                             bad_type_gv(arg, namegv, o3, "subroutine");
14472                         break;
14473                     case '$':
14474                         if (o3->op_type == OP_RV2SV ||
14475                                 o3->op_type == OP_PADSV ||
14476                                 o3->op_type == OP_HELEM ||
14477                                 o3->op_type == OP_AELEM)
14478                             goto wrapref;
14479                         if (!contextclass) {
14480                             /* \$ accepts any scalar lvalue */
14481                             if (Perl_op_lvalue_flags(aTHX_
14482                                     scalar(o3),
14483                                     OP_READ,  /* not entersub */
14484                                     OP_LVALUE_NO_CROAK
14485                                )) goto wrapref;
14486                             bad_type_gv(arg, namegv, o3, "scalar");
14487                         }
14488                         break;
14489                     case '@':
14490                         if (o3->op_type == OP_RV2AV ||
14491                                 o3->op_type == OP_PADAV)
14492                         {
14493                             o3->op_flags &=~ OPf_PARENS;
14494                             goto wrapref;
14495                         }
14496                         if (!contextclass)
14497                             bad_type_gv(arg, namegv, o3, "array");
14498                         break;
14499                     case '%':
14500                         if (o3->op_type == OP_RV2HV ||
14501                                 o3->op_type == OP_PADHV)
14502                         {
14503                             o3->op_flags &=~ OPf_PARENS;
14504                             goto wrapref;
14505                         }
14506                         if (!contextclass)
14507                             bad_type_gv(arg, namegv, o3, "hash");
14508                         break;
14509                     wrapref:
14510                             aop = S_op_sibling_newUNOP(aTHX_ parent, prev,
14511                                                 OP_REFGEN, 0);
14512                         if (contextclass && e) {
14513                             proto = e + 1;
14514                             contextclass = 0;
14515                         }
14516                         break;
14517                     default: goto oops;
14518                 }
14519                 if (contextclass)
14520                     goto again;
14521                 break;
14522             case ' ':
14523                 proto++;
14524                 continue;
14525             default:
14526             oops: {
14527                 Perl_croak(aTHX_ "Malformed prototype for %" SVf ": %" SVf,
14528                                   SVfARG(cv_name((CV *)namegv, NULL, 0)),
14529                                   SVfARG(protosv));
14530             }
14531         }
14532
14533         op_lvalue(aop, OP_ENTERSUB);
14534         prev = aop;
14535         aop = OpSIBLING(aop);
14536     }
14537     if (aop == cvop && *proto == '_') {
14538         /* generate an access to $_ */
14539         op_sibling_splice(parent, prev, 0, newDEFSVOP());
14540     }
14541     if (!optional && proto_end > proto &&
14542         (*proto != '@' && *proto != '%' && *proto != ';' && *proto != '_'))
14543     {
14544         SV * const namesv = cv_name((CV *)namegv, NULL, 0);
14545         yyerror_pv(Perl_form(aTHX_ "Not enough arguments for %" SVf,
14546                                     SVfARG(namesv)), SvUTF8(namesv));
14547     }
14548     return entersubop;
14549 }
14550
14551 /*
14552 =for apidoc ck_entersub_args_proto_or_list
14553
14554 Performs the fixup of the arguments part of an C<entersub> op tree either
14555 based on a subroutine prototype or using default list-context processing.
14556 This is the standard treatment used on a subroutine call, not marked
14557 with C<&>, where the callee can be identified at compile time.
14558
14559 C<protosv> supplies the subroutine prototype to be applied to the call,
14560 or indicates that there is no prototype.  It may be a normal scalar,
14561 in which case if it is defined then the string value will be used
14562 as a prototype, and if it is undefined then there is no prototype.
14563 Alternatively, for convenience, it may be a subroutine object (a C<CV*>
14564 that has been cast to C<SV*>), of which the prototype will be used if it
14565 has one.  The prototype (or lack thereof) supplied, in whichever form,
14566 does not need to match the actual callee referenced by the op tree.
14567
14568 If the argument ops disagree with the prototype, for example by having
14569 an unacceptable number of arguments, a valid op tree is returned anyway.
14570 The error is reflected in the parser state, normally resulting in a single
14571 exception at the top level of parsing which covers all the compilation
14572 errors that occurred.  In the error message, the callee is referred to
14573 by the name defined by the C<namegv> parameter.
14574
14575 =cut
14576 */
14577
14578 OP *
14579 Perl_ck_entersub_args_proto_or_list(pTHX_ OP *entersubop,
14580         GV *namegv, SV *protosv)
14581 {
14582     PERL_ARGS_ASSERT_CK_ENTERSUB_ARGS_PROTO_OR_LIST;
14583     if (SvTYPE(protosv) == SVt_PVCV ? SvPOK(protosv) : SvOK(protosv))
14584         return ck_entersub_args_proto(entersubop, namegv, protosv);
14585     else
14586         return ck_entersub_args_list(entersubop);
14587 }
14588
14589 OP *
14590 Perl_ck_entersub_args_core(pTHX_ OP *entersubop, GV *namegv, SV *protosv)
14591 {
14592     IV cvflags = SvIVX(protosv);
14593     int opnum = cvflags & 0xffff;
14594     OP *aop = cUNOPx(entersubop)->op_first;
14595
14596     PERL_ARGS_ASSERT_CK_ENTERSUB_ARGS_CORE;
14597
14598     if (!opnum) {
14599         OP *cvop;
14600         if (!OpHAS_SIBLING(aop))
14601             aop = cUNOPx(aop)->op_first;
14602         aop = OpSIBLING(aop);
14603         for (cvop = aop; OpSIBLING(cvop); cvop = OpSIBLING(cvop)) ;
14604         if (aop != cvop) {
14605             SV *namesv = cv_name((CV *)namegv, NULL, CV_NAME_NOTQUAL);
14606             yyerror_pv(Perl_form(aTHX_ "Too many arguments for %" SVf,
14607                 SVfARG(namesv)), SvUTF8(namesv));
14608         }
14609
14610         op_free(entersubop);
14611         switch(cvflags >> 16) {
14612         case 'F': return newSVOP(OP_CONST, 0,
14613                                         newSVpv(CopFILE(PL_curcop),0));
14614         case 'L': return newSVOP(
14615                            OP_CONST, 0,
14616                            Perl_newSVpvf(aTHX_
14617                              "%" IVdf, (IV)CopLINE(PL_curcop)
14618                            )
14619                          );
14620         case 'P': return newSVOP(OP_CONST, 0,
14621                                    (PL_curstash
14622                                      ? newSVhek(HvNAME_HEK(PL_curstash))
14623                                      : &PL_sv_undef
14624                                    )
14625                                 );
14626         }
14627         NOT_REACHED; /* NOTREACHED */
14628     }
14629     else {
14630         OP *prev, *cvop, *first, *parent;
14631         U32 flags = 0;
14632
14633         parent = entersubop;
14634         if (!OpHAS_SIBLING(aop)) {
14635             parent = aop;
14636             aop = cUNOPx(aop)->op_first;
14637         }
14638
14639         first = prev = aop;
14640         aop = OpSIBLING(aop);
14641         /* find last sibling */
14642         for (cvop = aop;
14643              OpHAS_SIBLING(cvop);
14644              prev = cvop, cvop = OpSIBLING(cvop))
14645             ;
14646         if (!(cvop->op_private & OPpENTERSUB_NOPAREN)
14647             /* Usually, OPf_SPECIAL on an op with no args means that it had
14648              * parens, but these have their own meaning for that flag: */
14649             && opnum != OP_VALUES && opnum != OP_KEYS && opnum != OP_EACH
14650             && opnum != OP_DELETE && opnum != OP_EXISTS)
14651                 flags |= OPf_SPECIAL;
14652         /* excise cvop from end of sibling chain */
14653         op_sibling_splice(parent, prev, 1, NULL);
14654         op_free(cvop);
14655         if (aop == cvop) aop = NULL;
14656
14657         /* detach remaining siblings from the first sibling, then
14658          * dispose of original optree */
14659
14660         if (aop)
14661             op_sibling_splice(parent, first, -1, NULL);
14662         op_free(entersubop);
14663
14664         if (cvflags == (OP_ENTEREVAL | (1<<16)))
14665             flags |= OPpEVAL_BYTES <<8;
14666
14667         switch (PL_opargs[opnum] & OA_CLASS_MASK) {
14668         case OA_UNOP:
14669         case OA_BASEOP_OR_UNOP:
14670         case OA_FILESTATOP:
14671             if (!aop)
14672                 return newOP(opnum,flags);       /* zero args */
14673             if (aop == prev)
14674                 return newUNOP(opnum,flags,aop); /* one arg */
14675             /* too many args */
14676             /* FALLTHROUGH */
14677         case OA_BASEOP:
14678             if (aop) {
14679                 SV *namesv;
14680                 OP *nextop;
14681
14682                 namesv = cv_name((CV *)namegv, NULL, CV_NAME_NOTQUAL);
14683                 yyerror_pv(Perl_form(aTHX_ "Too many arguments for %" SVf,
14684                     SVfARG(namesv)), SvUTF8(namesv));
14685                 while (aop) {
14686                     nextop = OpSIBLING(aop);
14687                     op_free(aop);
14688                     aop = nextop;
14689                 }
14690
14691             }
14692             return opnum == OP_RUNCV
14693                 ? newPVOP(OP_RUNCV,0,NULL)
14694                 : newOP(opnum,0);
14695         default:
14696             return op_convert_list(opnum,0,aop);
14697         }
14698     }
14699     NOT_REACHED; /* NOTREACHED */
14700     return entersubop;
14701 }
14702
14703 /*
14704 =for apidoc cv_get_call_checker_flags
14705
14706 Retrieves the function that will be used to fix up a call to C<cv>.
14707 Specifically, the function is applied to an C<entersub> op tree for a
14708 subroutine call, not marked with C<&>, where the callee can be identified
14709 at compile time as C<cv>.
14710
14711 The C-level function pointer is returned in C<*ckfun_p>, an SV argument
14712 for it is returned in C<*ckobj_p>, and control flags are returned in
14713 C<*ckflags_p>.  The function is intended to be called in this manner:
14714
14715  entersubop = (*ckfun_p)(aTHX_ entersubop, namegv, (*ckobj_p));
14716
14717 In this call, C<entersubop> is a pointer to the C<entersub> op,
14718 which may be replaced by the check function, and C<namegv> supplies
14719 the name that should be used by the check function to refer
14720 to the callee of the C<entersub> op if it needs to emit any diagnostics.
14721 It is permitted to apply the check function in non-standard situations,
14722 such as to a call to a different subroutine or to a method call.
14723
14724 C<namegv> may not actually be a GV.  If the C<CALL_CHECKER_REQUIRE_GV>
14725 bit is clear in C<*ckflags_p>, it is permitted to pass a CV or other SV
14726 instead, anything that can be used as the first argument to L</cv_name>.
14727 If the C<CALL_CHECKER_REQUIRE_GV> bit is set in C<*ckflags_p> then the
14728 check function requires C<namegv> to be a genuine GV.
14729
14730 By default, the check function is
14731 L<Perl_ck_entersub_args_proto_or_list|/ck_entersub_args_proto_or_list>,
14732 the SV parameter is C<cv> itself, and the C<CALL_CHECKER_REQUIRE_GV>
14733 flag is clear.  This implements standard prototype processing.  It can
14734 be changed, for a particular subroutine, by L</cv_set_call_checker_flags>.
14735
14736 If the C<CALL_CHECKER_REQUIRE_GV> bit is set in C<gflags> then it
14737 indicates that the caller only knows about the genuine GV version of
14738 C<namegv>, and accordingly the corresponding bit will always be set in
14739 C<*ckflags_p>, regardless of the check function's recorded requirements.
14740 If the C<CALL_CHECKER_REQUIRE_GV> bit is clear in C<gflags> then it
14741 indicates the caller knows about the possibility of passing something
14742 other than a GV as C<namegv>, and accordingly the corresponding bit may
14743 be either set or clear in C<*ckflags_p>, indicating the check function's
14744 recorded requirements.
14745
14746 C<gflags> is a bitset passed into C<cv_get_call_checker_flags>, in which
14747 only the C<CALL_CHECKER_REQUIRE_GV> bit currently has a defined meaning
14748 (for which see above).  All other bits should be clear.
14749
14750 =for apidoc Amnh||CALL_CHECKER_REQUIRE_GV
14751
14752 =for apidoc cv_get_call_checker
14753
14754 The original form of L</cv_get_call_checker_flags>, which does not return
14755 checker flags.  When using a checker function returned by this function,
14756 it is only safe to call it with a genuine GV as its C<namegv> argument.
14757
14758 =cut
14759 */
14760
14761 void
14762 Perl_cv_get_call_checker_flags(pTHX_ CV *cv, U32 gflags,
14763         Perl_call_checker *ckfun_p, SV **ckobj_p, U32 *ckflags_p)
14764 {
14765     MAGIC *callmg;
14766     PERL_ARGS_ASSERT_CV_GET_CALL_CHECKER_FLAGS;
14767     PERL_UNUSED_CONTEXT;
14768     callmg = SvMAGICAL((SV*)cv) ? mg_find((SV*)cv, PERL_MAGIC_checkcall) : NULL;
14769     if (callmg) {
14770         *ckfun_p = DPTR2FPTR(Perl_call_checker, callmg->mg_ptr);
14771         *ckobj_p = callmg->mg_obj;
14772         *ckflags_p = (callmg->mg_flags | gflags) & MGf_REQUIRE_GV;
14773     } else {
14774         *ckfun_p = Perl_ck_entersub_args_proto_or_list;
14775         *ckobj_p = (SV*)cv;
14776         *ckflags_p = gflags & MGf_REQUIRE_GV;
14777     }
14778 }
14779
14780 void
14781 Perl_cv_get_call_checker(pTHX_ CV *cv, Perl_call_checker *ckfun_p, SV **ckobj_p)
14782 {
14783     U32 ckflags;
14784     PERL_ARGS_ASSERT_CV_GET_CALL_CHECKER;
14785     PERL_UNUSED_CONTEXT;
14786     cv_get_call_checker_flags(cv, CALL_CHECKER_REQUIRE_GV, ckfun_p, ckobj_p,
14787         &ckflags);
14788 }
14789
14790 /*
14791 =for apidoc cv_set_call_checker_flags
14792
14793 Sets the function that will be used to fix up a call to C<cv>.
14794 Specifically, the function is applied to an C<entersub> op tree for a
14795 subroutine call, not marked with C<&>, where the callee can be identified
14796 at compile time as C<cv>.
14797
14798 The C-level function pointer is supplied in C<ckfun>, an SV argument for
14799 it is supplied in C<ckobj>, and control flags are supplied in C<ckflags>.
14800 The function should be defined like this:
14801
14802     STATIC OP * ckfun(pTHX_ OP *op, GV *namegv, SV *ckobj)
14803
14804 It is intended to be called in this manner:
14805
14806     entersubop = ckfun(aTHX_ entersubop, namegv, ckobj);
14807
14808 In this call, C<entersubop> is a pointer to the C<entersub> op,
14809 which may be replaced by the check function, and C<namegv> supplies
14810 the name that should be used by the check function to refer
14811 to the callee of the C<entersub> op if it needs to emit any diagnostics.
14812 It is permitted to apply the check function in non-standard situations,
14813 such as to a call to a different subroutine or to a method call.
14814
14815 C<namegv> may not actually be a GV.  For efficiency, perl may pass a
14816 CV or other SV instead.  Whatever is passed can be used as the first
14817 argument to L</cv_name>.  You can force perl to pass a GV by including
14818 C<CALL_CHECKER_REQUIRE_GV> in the C<ckflags>.
14819
14820 C<ckflags> is a bitset, in which only the C<CALL_CHECKER_REQUIRE_GV>
14821 bit currently has a defined meaning (for which see above).  All other
14822 bits should be clear.
14823
14824 The current setting for a particular CV can be retrieved by
14825 L</cv_get_call_checker_flags>.
14826
14827 =for apidoc cv_set_call_checker
14828
14829 The original form of L</cv_set_call_checker_flags>, which passes it the
14830 C<CALL_CHECKER_REQUIRE_GV> flag for backward-compatibility.  The effect
14831 of that flag setting is that the check function is guaranteed to get a
14832 genuine GV as its C<namegv> argument.
14833
14834 =cut
14835 */
14836
14837 void
14838 Perl_cv_set_call_checker(pTHX_ CV *cv, Perl_call_checker ckfun, SV *ckobj)
14839 {
14840     PERL_ARGS_ASSERT_CV_SET_CALL_CHECKER;
14841     cv_set_call_checker_flags(cv, ckfun, ckobj, CALL_CHECKER_REQUIRE_GV);
14842 }
14843
14844 void
14845 Perl_cv_set_call_checker_flags(pTHX_ CV *cv, Perl_call_checker ckfun,
14846                                      SV *ckobj, U32 ckflags)
14847 {
14848     PERL_ARGS_ASSERT_CV_SET_CALL_CHECKER_FLAGS;
14849     if (ckfun == Perl_ck_entersub_args_proto_or_list && ckobj == (SV*)cv) {
14850         if (SvMAGICAL((SV*)cv))
14851             mg_free_type((SV*)cv, PERL_MAGIC_checkcall);
14852     } else {
14853         MAGIC *callmg;
14854         sv_magic((SV*)cv, &PL_sv_undef, PERL_MAGIC_checkcall, NULL, 0);
14855         callmg = mg_find((SV*)cv, PERL_MAGIC_checkcall);
14856         assert(callmg);
14857         if (callmg->mg_flags & MGf_REFCOUNTED) {
14858             SvREFCNT_dec(callmg->mg_obj);
14859             callmg->mg_flags &= ~MGf_REFCOUNTED;
14860         }
14861         callmg->mg_ptr = FPTR2DPTR(char *, ckfun);
14862         callmg->mg_obj = ckobj;
14863         if (ckobj != (SV*)cv) {
14864             SvREFCNT_inc_simple_void_NN(ckobj);
14865             callmg->mg_flags |= MGf_REFCOUNTED;
14866         }
14867         callmg->mg_flags = (callmg->mg_flags &~ MGf_REQUIRE_GV)
14868                          | (U8)(ckflags & MGf_REQUIRE_GV) | MGf_COPY;
14869     }
14870 }
14871
14872 static void
14873 S_entersub_alloc_targ(pTHX_ OP * const o)
14874 {
14875     o->op_targ = pad_alloc(OP_ENTERSUB, SVs_PADTMP);
14876     o->op_private |= OPpENTERSUB_HASTARG;
14877 }
14878
14879 OP *
14880 Perl_ck_subr(pTHX_ OP *o)
14881 {
14882     OP *aop, *cvop;
14883     CV *cv;
14884     GV *namegv;
14885     SV **const_class = NULL;
14886
14887     PERL_ARGS_ASSERT_CK_SUBR;
14888
14889     aop = cUNOPx(o)->op_first;
14890     if (!OpHAS_SIBLING(aop))
14891         aop = cUNOPx(aop)->op_first;
14892     aop = OpSIBLING(aop);
14893     for (cvop = aop; OpHAS_SIBLING(cvop); cvop = OpSIBLING(cvop)) ;
14894     cv = rv2cv_op_cv(cvop, RV2CVOPCV_MARK_EARLY);
14895     namegv = cv ? (GV*)rv2cv_op_cv(cvop, RV2CVOPCV_MAYBE_NAME_GV) : NULL;
14896
14897     o->op_private &= ~1;
14898     o->op_private |= (PL_hints & HINT_STRICT_REFS);
14899     if (PERLDB_SUB && PL_curstash != PL_debstash)
14900         o->op_private |= OPpENTERSUB_DB;
14901     switch (cvop->op_type) {
14902         case OP_RV2CV:
14903             o->op_private |= (cvop->op_private & OPpENTERSUB_AMPER);
14904             op_null(cvop);
14905             break;
14906         case OP_METHOD:
14907         case OP_METHOD_NAMED:
14908         case OP_METHOD_SUPER:
14909         case OP_METHOD_REDIR:
14910         case OP_METHOD_REDIR_SUPER:
14911             o->op_flags |= OPf_REF;
14912             if (aop->op_type == OP_CONST) {
14913                 aop->op_private &= ~OPpCONST_STRICT;
14914                 const_class = &cSVOPx(aop)->op_sv;
14915             }
14916             else if (aop->op_type == OP_LIST) {
14917                 OP * const sib = OpSIBLING(((UNOP*)aop)->op_first);
14918                 if (sib && sib->op_type == OP_CONST) {
14919                     sib->op_private &= ~OPpCONST_STRICT;
14920                     const_class = &cSVOPx(sib)->op_sv;
14921                 }
14922             }
14923             /* make class name a shared cow string to speedup method calls */
14924             /* constant string might be replaced with object, f.e. bigint */
14925             if (const_class && SvPOK(*const_class)) {
14926                 STRLEN len;
14927                 const char* str = SvPV(*const_class, len);
14928                 if (len) {
14929                     SV* const shared = newSVpvn_share(
14930                         str, SvUTF8(*const_class)
14931                                     ? -(SSize_t)len : (SSize_t)len,
14932                         0
14933                     );
14934                     if (SvREADONLY(*const_class))
14935                         SvREADONLY_on(shared);
14936                     SvREFCNT_dec(*const_class);
14937                     *const_class = shared;
14938                 }
14939             }
14940             break;
14941     }
14942
14943     if (!cv) {
14944         S_entersub_alloc_targ(aTHX_ o);
14945         return ck_entersub_args_list(o);
14946     } else {
14947         Perl_call_checker ckfun;
14948         SV *ckobj;
14949         U32 ckflags;
14950         cv_get_call_checker_flags(cv, 0, &ckfun, &ckobj, &ckflags);
14951         if (CvISXSUB(cv) || !CvROOT(cv))
14952             S_entersub_alloc_targ(aTHX_ o);
14953         if (!namegv) {
14954             /* The original call checker API guarantees that a GV will be
14955                be provided with the right name.  So, if the old API was
14956                used (or the REQUIRE_GV flag was passed), we have to reify
14957                the CV’s GV, unless this is an anonymous sub.  This is not
14958                ideal for lexical subs, as its stringification will include
14959                the package.  But it is the best we can do.  */
14960             if (ckflags & CALL_CHECKER_REQUIRE_GV) {
14961                 if (!CvANON(cv) && (!CvNAMED(cv) || CvNAME_HEK(cv)))
14962                     namegv = CvGV(cv);
14963             }
14964             else namegv = MUTABLE_GV(cv);
14965             /* After a syntax error in a lexical sub, the cv that
14966                rv2cv_op_cv returns may be a nameless stub. */
14967             if (!namegv) return ck_entersub_args_list(o);
14968
14969         }
14970         return ckfun(aTHX_ o, namegv, ckobj);
14971     }
14972 }
14973
14974 OP *
14975 Perl_ck_svconst(pTHX_ OP *o)
14976 {
14977     SV * const sv = cSVOPo->op_sv;
14978     PERL_ARGS_ASSERT_CK_SVCONST;
14979     PERL_UNUSED_CONTEXT;
14980 #ifdef PERL_COPY_ON_WRITE
14981     /* Since the read-only flag may be used to protect a string buffer, we
14982        cannot do copy-on-write with existing read-only scalars that are not
14983        already copy-on-write scalars.  To allow $_ = "hello" to do COW with
14984        that constant, mark the constant as COWable here, if it is not
14985        already read-only. */
14986     if (!SvREADONLY(sv) && !SvIsCOW(sv) && SvCANCOW(sv)) {
14987         SvIsCOW_on(sv);
14988         CowREFCNT(sv) = 0;
14989 # ifdef PERL_DEBUG_READONLY_COW
14990         sv_buf_to_ro(sv);
14991 # endif
14992     }
14993 #endif
14994     SvREADONLY_on(sv);
14995     return o;
14996 }
14997
14998 OP *
14999 Perl_ck_trunc(pTHX_ OP *o)
15000 {
15001     PERL_ARGS_ASSERT_CK_TRUNC;
15002
15003     if (o->op_flags & OPf_KIDS) {
15004         SVOP *kid = (SVOP*)cUNOPo->op_first;
15005
15006         if (kid->op_type == OP_NULL)
15007             kid = (SVOP*)OpSIBLING(kid);
15008         if (kid && kid->op_type == OP_CONST &&
15009             (kid->op_private & OPpCONST_BARE) &&
15010             !kid->op_folded)
15011         {
15012             o->op_flags |= OPf_SPECIAL;
15013             kid->op_private &= ~OPpCONST_STRICT;
15014         }
15015     }
15016     return ck_fun(o);
15017 }
15018
15019 OP *
15020 Perl_ck_substr(pTHX_ OP *o)
15021 {
15022     PERL_ARGS_ASSERT_CK_SUBSTR;
15023
15024     o = ck_fun(o);
15025     if ((o->op_flags & OPf_KIDS) && (o->op_private == 4)) {
15026         OP *kid = cLISTOPo->op_first;
15027
15028         if (kid->op_type == OP_NULL)
15029             kid = OpSIBLING(kid);
15030         if (kid)
15031             /* Historically, substr(delete $foo{bar},...) has been allowed
15032                with 4-arg substr.  Keep it working by applying entersub
15033                lvalue context.  */
15034             op_lvalue(kid, OP_ENTERSUB);
15035
15036     }
15037     return o;
15038 }
15039
15040 OP *
15041 Perl_ck_tell(pTHX_ OP *o)
15042 {
15043     PERL_ARGS_ASSERT_CK_TELL;
15044     o = ck_fun(o);
15045     if (o->op_flags & OPf_KIDS) {
15046      OP *kid = cLISTOPo->op_first;
15047      if (kid->op_type == OP_NULL && OpHAS_SIBLING(kid)) kid = OpSIBLING(kid);
15048      if (kid->op_type == OP_RV2GV) kid->op_private |= OPpALLOW_FAKE;
15049     }
15050     return o;
15051 }
15052
15053 OP *
15054 Perl_ck_each(pTHX_ OP *o)
15055 {
15056     dVAR;
15057     OP *kid = o->op_flags & OPf_KIDS ? cUNOPo->op_first : NULL;
15058     const unsigned orig_type  = o->op_type;
15059
15060     PERL_ARGS_ASSERT_CK_EACH;
15061
15062     if (kid) {
15063         switch (kid->op_type) {
15064             case OP_PADHV:
15065             case OP_RV2HV:
15066                 break;
15067             case OP_PADAV:
15068             case OP_RV2AV:
15069                 OpTYPE_set(o, orig_type == OP_EACH ? OP_AEACH
15070                             : orig_type == OP_KEYS ? OP_AKEYS
15071                             :                        OP_AVALUES);
15072                 break;
15073             case OP_CONST:
15074                 if (kid->op_private == OPpCONST_BARE
15075                  || !SvROK(cSVOPx_sv(kid))
15076                  || (  SvTYPE(SvRV(cSVOPx_sv(kid))) != SVt_PVAV
15077                     && SvTYPE(SvRV(cSVOPx_sv(kid))) != SVt_PVHV  )
15078                    )
15079                     goto bad;
15080                 /* FALLTHROUGH */
15081             default:
15082                 qerror(Perl_mess(aTHX_
15083                     "Experimental %s on scalar is now forbidden",
15084                      PL_op_desc[orig_type]));
15085                bad:
15086                 bad_type_pv(1, "hash or array", o, kid);
15087                 return o;
15088         }
15089     }
15090     return ck_fun(o);
15091 }
15092
15093 OP *
15094 Perl_ck_length(pTHX_ OP *o)
15095 {
15096     PERL_ARGS_ASSERT_CK_LENGTH;
15097
15098     o = ck_fun(o);
15099
15100     if (ckWARN(WARN_SYNTAX)) {
15101         const OP *kid = o->op_flags & OPf_KIDS ? cLISTOPo->op_first : NULL;
15102
15103         if (kid) {
15104             SV *name = NULL;
15105             const bool hash = kid->op_type == OP_PADHV
15106                            || kid->op_type == OP_RV2HV;
15107             switch (kid->op_type) {
15108                 case OP_PADHV:
15109                 case OP_PADAV:
15110                 case OP_RV2HV:
15111                 case OP_RV2AV:
15112                     name = S_op_varname(aTHX_ kid);
15113                     break;
15114                 default:
15115                     return o;
15116             }
15117             if (name)
15118                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
15119                     "length() used on %" SVf " (did you mean \"scalar(%s%" SVf
15120                     ")\"?)",
15121                     SVfARG(name), hash ? "keys " : "", SVfARG(name)
15122                 );
15123             else if (hash)
15124      /* diag_listed_as: length() used on %s (did you mean "scalar(%s)"?) */
15125                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
15126                     "length() used on %%hash (did you mean \"scalar(keys %%hash)\"?)");
15127             else
15128      /* diag_listed_as: length() used on %s (did you mean "scalar(%s)"?) */
15129                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
15130                     "length() used on @array (did you mean \"scalar(@array)\"?)");
15131         }
15132     }
15133
15134     return o;
15135 }
15136
15137
15138 OP *
15139 Perl_ck_isa(pTHX_ OP *o)
15140 {
15141     OP *classop = cBINOPo->op_last;
15142
15143     PERL_ARGS_ASSERT_CK_ISA;
15144
15145     /* Convert barename into PV */
15146     if(classop->op_type == OP_CONST && classop->op_private & OPpCONST_BARE) {
15147         /* TODO: Optionally convert package to raw HV here */
15148         classop->op_private &= ~(OPpCONST_BARE|OPpCONST_STRICT);
15149     }
15150
15151     return o;
15152 }
15153
15154
15155 /*
15156    ---------------------------------------------------------
15157
15158    Common vars in list assignment
15159
15160    There now follows some enums and static functions for detecting
15161    common variables in list assignments. Here is a little essay I wrote
15162    for myself when trying to get my head around this. DAPM.
15163
15164    ----
15165
15166    First some random observations:
15167
15168    * If a lexical var is an alias of something else, e.g.
15169        for my $x ($lex, $pkg, $a[0]) {...}
15170      then the act of aliasing will increase the reference count of the SV
15171
15172    * If a package var is an alias of something else, it may still have a
15173      reference count of 1, depending on how the alias was created, e.g.
15174      in *a = *b, $a may have a refcount of 1 since the GP is shared
15175      with a single GvSV pointer to the SV. So If it's an alias of another
15176      package var, then RC may be 1; if it's an alias of another scalar, e.g.
15177      a lexical var or an array element, then it will have RC > 1.
15178
15179    * There are many ways to create a package alias; ultimately, XS code
15180      may quite legally do GvSV(gv) = SvREFCNT_inc(sv) for example, so
15181      run-time tracing mechanisms are unlikely to be able to catch all cases.
15182
15183    * When the LHS is all my declarations, the same vars can't appear directly
15184      on the RHS, but they can indirectly via closures, aliasing and lvalue
15185      subs. But those techniques all involve an increase in the lexical
15186      scalar's ref count.
15187
15188    * When the LHS is all lexical vars (but not necessarily my declarations),
15189      it is possible for the same lexicals to appear directly on the RHS, and
15190      without an increased ref count, since the stack isn't refcounted.
15191      This case can be detected at compile time by scanning for common lex
15192      vars with PL_generation.
15193
15194    * lvalue subs defeat common var detection, but they do at least
15195      return vars with a temporary ref count increment. Also, you can't
15196      tell at compile time whether a sub call is lvalue.
15197
15198
15199    So...
15200
15201    A: There are a few circumstances where there definitely can't be any
15202      commonality:
15203
15204        LHS empty:  () = (...);
15205        RHS empty:  (....) = ();
15206        RHS contains only constants or other 'can't possibly be shared'
15207            elements (e.g. ops that return PADTMPs):  (...) = (1,2, length)
15208            i.e. they only contain ops not marked as dangerous, whose children
15209            are also not dangerous;
15210        LHS ditto;
15211        LHS contains a single scalar element: e.g. ($x) = (....); because
15212            after $x has been modified, it won't be used again on the RHS;
15213        RHS contains a single element with no aggregate on LHS: e.g.
15214            ($a,$b,$c)  = ($x); again, once $a has been modified, its value
15215            won't be used again.
15216
15217    B: If LHS are all 'my' lexical var declarations (or safe ops, which
15218      we can ignore):
15219
15220        my ($a, $b, @c) = ...;
15221
15222        Due to closure and goto tricks, these vars may already have content.
15223        For the same reason, an element on the RHS may be a lexical or package
15224        alias of one of the vars on the left, or share common elements, for
15225        example:
15226
15227            my ($x,$y) = f(); # $x and $y on both sides
15228            sub f : lvalue { ($x,$y) = (1,2); $y, $x }
15229
15230        and
15231
15232            my $ra = f();
15233            my @a = @$ra;  # elements of @a on both sides
15234            sub f { @a = 1..4; \@a }
15235
15236
15237        First, just consider scalar vars on LHS:
15238
15239            RHS is safe only if (A), or in addition,
15240                * contains only lexical *scalar* vars, where neither side's
15241                  lexicals have been flagged as aliases
15242
15243            If RHS is not safe, then it's always legal to check LHS vars for
15244            RC==1, since the only RHS aliases will always be associated
15245            with an RC bump.
15246
15247            Note that in particular, RHS is not safe if:
15248
15249                * it contains package scalar vars; e.g.:
15250
15251                    f();
15252                    my ($x, $y) = (2, $x_alias);
15253                    sub f { $x = 1; *x_alias = \$x; }
15254
15255                * It contains other general elements, such as flattened or
15256                * spliced or single array or hash elements, e.g.
15257
15258                    f();
15259                    my ($x,$y) = @a; # or $a[0] or @a{@b} etc
15260
15261                    sub f {
15262                        ($x, $y) = (1,2);
15263                        use feature 'refaliasing';
15264                        \($a[0], $a[1]) = \($y,$x);
15265                    }
15266
15267                  It doesn't matter if the array/hash is lexical or package.
15268
15269                * it contains a function call that happens to be an lvalue
15270                  sub which returns one or more of the above, e.g.
15271
15272                    f();
15273                    my ($x,$y) = f();
15274
15275                    sub f : lvalue {
15276                        ($x, $y) = (1,2);
15277                        *x1 = \$x;
15278                        $y, $x1;
15279                    }
15280
15281                    (so a sub call on the RHS should be treated the same
15282                    as having a package var on the RHS).
15283
15284                * any other "dangerous" thing, such an op or built-in that
15285                  returns one of the above, e.g. pp_preinc
15286
15287
15288            If RHS is not safe, what we can do however is at compile time flag
15289            that the LHS are all my declarations, and at run time check whether
15290            all the LHS have RC == 1, and if so skip the full scan.
15291
15292        Now consider array and hash vars on LHS: e.g. my (...,@a) = ...;
15293
15294            Here the issue is whether there can be elements of @a on the RHS
15295            which will get prematurely freed when @a is cleared prior to
15296            assignment. This is only a problem if the aliasing mechanism
15297            is one which doesn't increase the refcount - only if RC == 1
15298            will the RHS element be prematurely freed.
15299
15300            Because the array/hash is being INTROed, it or its elements
15301            can't directly appear on the RHS:
15302
15303                my (@a) = ($a[0], @a, etc) # NOT POSSIBLE
15304
15305            but can indirectly, e.g.:
15306
15307                my $r = f();
15308                my (@a) = @$r;
15309                sub f { @a = 1..3; \@a }
15310
15311            So if the RHS isn't safe as defined by (A), we must always
15312            mortalise and bump the ref count of any remaining RHS elements
15313            when assigning to a non-empty LHS aggregate.
15314
15315            Lexical scalars on the RHS aren't safe if they've been involved in
15316            aliasing, e.g.
15317
15318                use feature 'refaliasing';
15319
15320                f();
15321                \(my $lex) = \$pkg;
15322                my @a = ($lex,3); # equivalent to ($a[0],3)
15323
15324                sub f {
15325                    @a = (1,2);
15326                    \$pkg = \$a[0];
15327                }
15328
15329            Similarly with lexical arrays and hashes on the RHS:
15330
15331                f();
15332                my @b;
15333                my @a = (@b);
15334
15335                sub f {
15336                    @a = (1,2);
15337                    \$b[0] = \$a[1];
15338                    \$b[1] = \$a[0];
15339                }
15340
15341
15342
15343    C: As (B), but in addition the LHS may contain non-intro lexicals, e.g.
15344        my $a; ($a, my $b) = (....);
15345
15346        The difference between (B) and (C) is that it is now physically
15347        possible for the LHS vars to appear on the RHS too, where they
15348        are not reference counted; but in this case, the compile-time
15349        PL_generation sweep will detect such common vars.
15350
15351        So the rules for (C) differ from (B) in that if common vars are
15352        detected, the runtime "test RC==1" optimisation can no longer be used,
15353        and a full mark and sweep is required
15354
15355    D: As (C), but in addition the LHS may contain package vars.
15356
15357        Since package vars can be aliased without a corresponding refcount
15358        increase, all bets are off. It's only safe if (A). E.g.
15359
15360            my ($x, $y) = (1,2);
15361
15362            for $x_alias ($x) {
15363                ($x_alias, $y) = (3, $x); # whoops
15364            }
15365
15366        Ditto for LHS aggregate package vars.
15367
15368    E: Any other dangerous ops on LHS, e.g.
15369            (f(), $a[0], @$r) = (...);
15370
15371        this is similar to (E) in that all bets are off. In addition, it's
15372        impossible to determine at compile time whether the LHS
15373        contains a scalar or an aggregate, e.g.
15374
15375            sub f : lvalue { @a }
15376            (f()) = 1..3;
15377
15378 * ---------------------------------------------------------
15379 */
15380
15381
15382 /* A set of bit flags returned by S_aassign_scan(). Each flag indicates
15383  * that at least one of the things flagged was seen.
15384  */
15385
15386 enum {
15387     AAS_MY_SCALAR       = 0x001, /* my $scalar */
15388     AAS_MY_AGG          = 0x002, /* aggregate: my @array or my %hash */
15389     AAS_LEX_SCALAR      = 0x004, /* $lexical */
15390     AAS_LEX_AGG         = 0x008, /* @lexical or %lexical aggregate */
15391     AAS_LEX_SCALAR_COMM = 0x010, /* $lexical seen on both sides */
15392     AAS_PKG_SCALAR      = 0x020, /* $scalar (where $scalar is pkg var) */
15393     AAS_PKG_AGG         = 0x040, /* package @array or %hash aggregate */
15394     AAS_DANGEROUS       = 0x080, /* an op (other than the above)
15395                                          that's flagged OA_DANGEROUS */
15396     AAS_SAFE_SCALAR     = 0x100, /* produces at least one scalar SV that's
15397                                         not in any of the categories above */
15398     AAS_DEFAV           = 0x200  /* contains just a single '@_' on RHS */
15399 };
15400
15401
15402
15403 /* helper function for S_aassign_scan().
15404  * check a PAD-related op for commonality and/or set its generation number.
15405  * Returns a boolean indicating whether its shared */
15406
15407 static bool
15408 S_aassign_padcheck(pTHX_ OP* o, bool rhs)
15409 {
15410     if (PAD_COMPNAME_GEN(o->op_targ) == PERL_INT_MAX)
15411         /* lexical used in aliasing */
15412         return TRUE;
15413
15414     if (rhs)
15415         return cBOOL(PAD_COMPNAME_GEN(o->op_targ) == (STRLEN)PL_generation);
15416     else
15417         PAD_COMPNAME_GEN_set(o->op_targ, PL_generation);
15418
15419     return FALSE;
15420 }
15421
15422
15423 /*
15424   Helper function for OPpASSIGN_COMMON* detection in rpeep().
15425   It scans the left or right hand subtree of the aassign op, and returns a
15426   set of flags indicating what sorts of things it found there.
15427   'rhs' indicates whether we're scanning the LHS or RHS. If the former, we
15428   set PL_generation on lexical vars; if the latter, we see if
15429   PL_generation matches.
15430   'scalars_p' is a pointer to a counter of the number of scalar SVs seen.
15431   This fn will increment it by the number seen. It's not intended to
15432   be an accurate count (especially as many ops can push a variable
15433   number of SVs onto the stack); rather it's used as to test whether there
15434   can be at most 1 SV pushed; so it's only meanings are "0, 1, many".
15435 */
15436
15437 static int
15438 S_aassign_scan(pTHX_ OP* o, bool rhs, int *scalars_p)
15439 {
15440     OP *top_op           = o;
15441     OP *effective_top_op = o;
15442     int all_flags = 0;
15443
15444     while (1) {
15445     bool top = o == effective_top_op;
15446     int flags = 0;
15447     OP* next_kid = NULL;
15448
15449     /* first, look for a solitary @_ on the RHS */
15450     if (   rhs
15451         && top
15452         && (o->op_flags & OPf_KIDS)
15453         && OP_TYPE_IS_OR_WAS(o, OP_LIST)
15454     ) {
15455         OP *kid = cUNOPo->op_first;
15456         if (   (   kid->op_type == OP_PUSHMARK
15457                 || kid->op_type == OP_PADRANGE) /* ex-pushmark */
15458             && ((kid = OpSIBLING(kid)))
15459             && !OpHAS_SIBLING(kid)
15460             && kid->op_type == OP_RV2AV
15461             && !(kid->op_flags & OPf_REF)
15462             && !(kid->op_private & (OPpLVAL_INTRO|OPpMAYBE_LVSUB))
15463             && ((kid->op_flags & OPf_WANT) == OPf_WANT_LIST)
15464             && ((kid = cUNOPx(kid)->op_first))
15465             && kid->op_type == OP_GV
15466             && cGVOPx_gv(kid) == PL_defgv
15467         )
15468             flags = AAS_DEFAV;
15469     }
15470
15471     switch (o->op_type) {
15472     case OP_GVSV:
15473         (*scalars_p)++;
15474         all_flags |= AAS_PKG_SCALAR;
15475         goto do_next;
15476
15477     case OP_PADAV:
15478     case OP_PADHV:
15479         (*scalars_p) += 2;
15480         /* if !top, could be e.g. @a[0,1] */
15481         all_flags |=  (top && (o->op_flags & OPf_REF))
15482                         ? ((o->op_private & OPpLVAL_INTRO)
15483                             ? AAS_MY_AGG : AAS_LEX_AGG)
15484                         : AAS_DANGEROUS;
15485         goto do_next;
15486
15487     case OP_PADSV:
15488         {
15489             int comm = S_aassign_padcheck(aTHX_ o, rhs)
15490                         ?  AAS_LEX_SCALAR_COMM : 0;
15491             (*scalars_p)++;
15492             all_flags |= (o->op_private & OPpLVAL_INTRO)
15493                 ? (AAS_MY_SCALAR|comm) : (AAS_LEX_SCALAR|comm);
15494             goto do_next;
15495
15496         }
15497
15498     case OP_RV2AV:
15499     case OP_RV2HV:
15500         (*scalars_p) += 2;
15501         if (cUNOPx(o)->op_first->op_type != OP_GV)
15502             all_flags |= AAS_DANGEROUS; /* @{expr}, %{expr} */
15503         /* @pkg, %pkg */
15504         /* if !top, could be e.g. @a[0,1] */
15505         else if (top && (o->op_flags & OPf_REF))
15506             all_flags |= AAS_PKG_AGG;
15507         else
15508             all_flags |= AAS_DANGEROUS;
15509         goto do_next;
15510
15511     case OP_RV2SV:
15512         (*scalars_p)++;
15513         if (cUNOPx(o)->op_first->op_type != OP_GV) {
15514             (*scalars_p) += 2;
15515             all_flags |= AAS_DANGEROUS; /* ${expr} */
15516         }
15517         else
15518             all_flags |= AAS_PKG_SCALAR; /* $pkg */
15519         goto do_next;
15520
15521     case OP_SPLIT:
15522         if (o->op_private & OPpSPLIT_ASSIGN) {
15523             /* the assign in @a = split() has been optimised away
15524              * and the @a attached directly to the split op
15525              * Treat the array as appearing on the RHS, i.e.
15526              *    ... = (@a = split)
15527              * is treated like
15528              *    ... = @a;
15529              */
15530
15531             if (o->op_flags & OPf_STACKED) {
15532                 /* @{expr} = split() - the array expression is tacked
15533                  * on as an extra child to split - process kid */
15534                 next_kid = cLISTOPo->op_last;
15535                 goto do_next;
15536             }
15537
15538             /* ... else array is directly attached to split op */
15539             (*scalars_p) += 2;
15540             all_flags |= (PL_op->op_private & OPpSPLIT_LEX)
15541                             ? ((o->op_private & OPpLVAL_INTRO)
15542                                 ? AAS_MY_AGG : AAS_LEX_AGG)
15543                             : AAS_PKG_AGG;
15544             goto do_next;
15545         }
15546         (*scalars_p)++;
15547         /* other args of split can't be returned */
15548         all_flags |= AAS_SAFE_SCALAR;
15549         goto do_next;
15550
15551     case OP_UNDEF:
15552         /* undef counts as a scalar on the RHS:
15553          *   (undef, $x) = ...;         # only 1 scalar on LHS: always safe
15554          *   ($x, $y)    = (undef, $x); # 2 scalars on RHS: unsafe
15555          */
15556         if (rhs)
15557             (*scalars_p)++;
15558         flags = AAS_SAFE_SCALAR;
15559         break;
15560
15561     case OP_PUSHMARK:
15562     case OP_STUB:
15563         /* these are all no-ops; they don't push a potentially common SV
15564          * onto the stack, so they are neither AAS_DANGEROUS nor
15565          * AAS_SAFE_SCALAR */
15566         goto do_next;
15567
15568     case OP_PADRANGE: /* Ignore padrange; checking its siblings is enough */
15569         break;
15570
15571     case OP_NULL:
15572     case OP_LIST:
15573         /* these do nothing, but may have children */
15574         break;
15575
15576     default:
15577         if (PL_opargs[o->op_type] & OA_DANGEROUS) {
15578             (*scalars_p) += 2;
15579             flags = AAS_DANGEROUS;
15580             break;
15581         }
15582
15583         if (   (PL_opargs[o->op_type] & OA_TARGLEX)
15584             && (o->op_private & OPpTARGET_MY))
15585         {
15586             (*scalars_p)++;
15587             all_flags |= S_aassign_padcheck(aTHX_ o, rhs)
15588                             ? AAS_LEX_SCALAR_COMM : AAS_LEX_SCALAR;
15589             goto do_next;
15590         }
15591
15592         /* if its an unrecognised, non-dangerous op, assume that it
15593          * it the cause of at least one safe scalar */
15594         (*scalars_p)++;
15595         flags = AAS_SAFE_SCALAR;
15596         break;
15597     }
15598
15599     all_flags |= flags;
15600
15601     /* by default, process all kids next
15602      * XXX this assumes that all other ops are "transparent" - i.e. that
15603      * they can return some of their children. While this true for e.g.
15604      * sort and grep, it's not true for e.g. map. We really need a
15605      * 'transparent' flag added to regen/opcodes
15606      */
15607     if (o->op_flags & OPf_KIDS) {
15608         next_kid = cUNOPo->op_first;
15609         /* these ops do nothing but may have children; but their
15610          * children should also be treated as top-level */
15611         if (   o == effective_top_op
15612             && (o->op_type == OP_NULL || o->op_type == OP_LIST)
15613         )
15614             effective_top_op = next_kid;
15615     }
15616
15617
15618     /* If next_kid is set, someone in the code above wanted us to process
15619      * that kid and all its remaining siblings.  Otherwise, work our way
15620      * back up the tree */
15621   do_next:
15622     while (!next_kid) {
15623         if (o == top_op)
15624             return all_flags; /* at top; no parents/siblings to try */
15625         if (OpHAS_SIBLING(o)) {
15626             next_kid = o->op_sibparent;
15627             if (o == effective_top_op)
15628                 effective_top_op = next_kid;
15629         }
15630         else
15631             if (o == effective_top_op)
15632                 effective_top_op = o->op_sibparent;
15633             o = o->op_sibparent; /* try parent's next sibling */
15634
15635     }
15636     o = next_kid;
15637     } /* while */
15638
15639 }
15640
15641
15642 /* Check for in place reverse and sort assignments like "@a = reverse @a"
15643    and modify the optree to make them work inplace */
15644
15645 STATIC void
15646 S_inplace_aassign(pTHX_ OP *o) {
15647
15648     OP *modop, *modop_pushmark;
15649     OP *oright;
15650     OP *oleft, *oleft_pushmark;
15651
15652     PERL_ARGS_ASSERT_INPLACE_AASSIGN;
15653
15654     assert((o->op_flags & OPf_WANT) == OPf_WANT_VOID);
15655
15656     assert(cUNOPo->op_first->op_type == OP_NULL);
15657     modop_pushmark = cUNOPx(cUNOPo->op_first)->op_first;
15658     assert(modop_pushmark->op_type == OP_PUSHMARK);
15659     modop = OpSIBLING(modop_pushmark);
15660
15661     if (modop->op_type != OP_SORT && modop->op_type != OP_REVERSE)
15662         return;
15663
15664     /* no other operation except sort/reverse */
15665     if (OpHAS_SIBLING(modop))
15666         return;
15667
15668     assert(cUNOPx(modop)->op_first->op_type == OP_PUSHMARK);
15669     if (!(oright = OpSIBLING(cUNOPx(modop)->op_first))) return;
15670
15671     if (modop->op_flags & OPf_STACKED) {
15672         /* skip sort subroutine/block */
15673         assert(oright->op_type == OP_NULL);
15674         oright = OpSIBLING(oright);
15675     }
15676
15677     assert(OpSIBLING(cUNOPo->op_first)->op_type == OP_NULL);
15678     oleft_pushmark = cUNOPx(OpSIBLING(cUNOPo->op_first))->op_first;
15679     assert(oleft_pushmark->op_type == OP_PUSHMARK);
15680     oleft = OpSIBLING(oleft_pushmark);
15681
15682     /* Check the lhs is an array */
15683     if (!oleft ||
15684         (oleft->op_type != OP_RV2AV && oleft->op_type != OP_PADAV)
15685         || OpHAS_SIBLING(oleft)
15686         || (oleft->op_private & OPpLVAL_INTRO)
15687     )
15688         return;
15689
15690     /* Only one thing on the rhs */
15691     if (OpHAS_SIBLING(oright))
15692         return;
15693
15694     /* check the array is the same on both sides */
15695     if (oleft->op_type == OP_RV2AV) {
15696         if (oright->op_type != OP_RV2AV
15697             || !cUNOPx(oright)->op_first
15698             || cUNOPx(oright)->op_first->op_type != OP_GV
15699             || cUNOPx(oleft )->op_first->op_type != OP_GV
15700             || cGVOPx_gv(cUNOPx(oleft)->op_first) !=
15701                cGVOPx_gv(cUNOPx(oright)->op_first)
15702         )
15703             return;
15704     }
15705     else if (oright->op_type != OP_PADAV
15706         || oright->op_targ != oleft->op_targ
15707     )
15708         return;
15709
15710     /* This actually is an inplace assignment */
15711
15712     modop->op_private |= OPpSORT_INPLACE;
15713
15714     /* transfer MODishness etc from LHS arg to RHS arg */
15715     oright->op_flags = oleft->op_flags;
15716
15717     /* remove the aassign op and the lhs */
15718     op_null(o);
15719     op_null(oleft_pushmark);
15720     if (oleft->op_type == OP_RV2AV && cUNOPx(oleft)->op_first)
15721         op_null(cUNOPx(oleft)->op_first);
15722     op_null(oleft);
15723 }
15724
15725
15726
15727 /* S_maybe_multideref(): given an op_next chain of ops beginning at 'start'
15728  * that potentially represent a series of one or more aggregate derefs
15729  * (such as $a->[1]{$key}), examine the chain, and if appropriate, convert
15730  * the whole chain to a single OP_MULTIDEREF op (maybe with a few
15731  * additional ops left in too).
15732  *
15733  * The caller will have already verified that the first few ops in the
15734  * chain following 'start' indicate a multideref candidate, and will have
15735  * set 'orig_o' to the point further on in the chain where the first index
15736  * expression (if any) begins.  'orig_action' specifies what type of
15737  * beginning has already been determined by the ops between start..orig_o
15738  * (e.g.  $lex_ary[], $pkg_ary->{}, expr->[], etc).
15739  *
15740  * 'hints' contains any hints flags that need adding (currently just
15741  * OPpHINT_STRICT_REFS) as found in any rv2av/hv skipped by the caller.
15742  */
15743
15744 STATIC void
15745 S_maybe_multideref(pTHX_ OP *start, OP *orig_o, UV orig_action, U8 hints)
15746 {
15747     dVAR;
15748     int pass;
15749     UNOP_AUX_item *arg_buf = NULL;
15750     bool reset_start_targ  = FALSE; /* start->op_targ needs zeroing */
15751     int index_skip         = -1;    /* don't output index arg on this action */
15752
15753     /* similar to regex compiling, do two passes; the first pass
15754      * determines whether the op chain is convertible and calculates the
15755      * buffer size; the second pass populates the buffer and makes any
15756      * changes necessary to ops (such as moving consts to the pad on
15757      * threaded builds).
15758      *
15759      * NB: for things like Coverity, note that both passes take the same
15760      * path through the logic tree (except for 'if (pass)' bits), since
15761      * both passes are following the same op_next chain; and in
15762      * particular, if it would return early on the second pass, it would
15763      * already have returned early on the first pass.
15764      */
15765     for (pass = 0; pass < 2; pass++) {
15766         OP *o                = orig_o;
15767         UV action            = orig_action;
15768         OP *first_elem_op    = NULL;  /* first seen aelem/helem */
15769         OP *top_op           = NULL;  /* highest [ah]elem/exists/del/rv2[ah]v */
15770         int action_count     = 0;     /* number of actions seen so far */
15771         int action_ix        = 0;     /* action_count % (actions per IV) */
15772         bool next_is_hash    = FALSE; /* is the next lookup to be a hash? */
15773         bool is_last         = FALSE; /* no more derefs to follow */
15774         bool maybe_aelemfast = FALSE; /* we can replace with aelemfast? */
15775         UV action_word       = 0;     /* all actions so far */
15776         UNOP_AUX_item *arg     = arg_buf;
15777         UNOP_AUX_item *action_ptr = arg_buf;
15778
15779         arg++; /* reserve slot for first action word */
15780
15781         switch (action) {
15782         case MDEREF_HV_gvsv_vivify_rv2hv_helem:
15783         case MDEREF_HV_gvhv_helem:
15784             next_is_hash = TRUE;
15785             /* FALLTHROUGH */
15786         case MDEREF_AV_gvsv_vivify_rv2av_aelem:
15787         case MDEREF_AV_gvav_aelem:
15788             if (pass) {
15789 #ifdef USE_ITHREADS
15790                 arg->pad_offset = cPADOPx(start)->op_padix;
15791                 /* stop it being swiped when nulled */
15792                 cPADOPx(start)->op_padix = 0;
15793 #else
15794                 arg->sv = cSVOPx(start)->op_sv;
15795                 cSVOPx(start)->op_sv = NULL;
15796 #endif
15797             }
15798             arg++;
15799             break;
15800
15801         case MDEREF_HV_padhv_helem:
15802         case MDEREF_HV_padsv_vivify_rv2hv_helem:
15803             next_is_hash = TRUE;
15804             /* FALLTHROUGH */
15805         case MDEREF_AV_padav_aelem:
15806         case MDEREF_AV_padsv_vivify_rv2av_aelem:
15807             if (pass) {
15808                 arg->pad_offset = start->op_targ;
15809                 /* we skip setting op_targ = 0 for now, since the intact
15810                  * OP_PADXV is needed by S_check_hash_fields_and_hekify */
15811                 reset_start_targ = TRUE;
15812             }
15813             arg++;
15814             break;
15815
15816         case MDEREF_HV_pop_rv2hv_helem:
15817             next_is_hash = TRUE;
15818             /* FALLTHROUGH */
15819         case MDEREF_AV_pop_rv2av_aelem:
15820             break;
15821
15822         default:
15823             NOT_REACHED; /* NOTREACHED */
15824             return;
15825         }
15826
15827         while (!is_last) {
15828             /* look for another (rv2av/hv; get index;
15829              * aelem/helem/exists/delele) sequence */
15830
15831             OP *kid;
15832             bool is_deref;
15833             bool ok;
15834             UV index_type = MDEREF_INDEX_none;
15835
15836             if (action_count) {
15837                 /* if this is not the first lookup, consume the rv2av/hv  */
15838
15839                 /* for N levels of aggregate lookup, we normally expect
15840                  * that the first N-1 [ah]elem ops will be flagged as
15841                  * /DEREF (so they autovivifiy if necessary), and the last
15842                  * lookup op not to be.
15843                  * For other things (like @{$h{k1}{k2}}) extra scope or
15844                  * leave ops can appear, so abandon the effort in that
15845                  * case */
15846                 if (o->op_type != OP_RV2AV && o->op_type != OP_RV2HV)
15847                     return;
15848
15849                 /* rv2av or rv2hv sKR/1 */
15850
15851                 ASSUME(!(o->op_flags & ~(OPf_WANT|OPf_KIDS|OPf_PARENS
15852                                             |OPf_REF|OPf_MOD|OPf_SPECIAL)));
15853                 if (o->op_flags != (OPf_WANT_SCALAR|OPf_KIDS|OPf_REF))
15854                     return;
15855
15856                 /* at this point, we wouldn't expect any of these
15857                  * possible private flags:
15858                  * OPpMAYBE_LVSUB, OPpOUR_INTRO, OPpLVAL_INTRO
15859                  * OPpTRUEBOOL, OPpMAYBE_TRUEBOOL (rv2hv only)
15860                  */
15861                 ASSUME(!(o->op_private &
15862                     ~(OPpHINT_STRICT_REFS|OPpARG1_MASK|OPpSLICEWARNING)));
15863
15864                 hints = (o->op_private & OPpHINT_STRICT_REFS);
15865
15866                 /* make sure the type of the previous /DEREF matches the
15867                  * type of the next lookup */
15868                 ASSUME(o->op_type == (next_is_hash ? OP_RV2HV : OP_RV2AV));
15869                 top_op = o;
15870
15871                 action = next_is_hash
15872                             ? MDEREF_HV_vivify_rv2hv_helem
15873                             : MDEREF_AV_vivify_rv2av_aelem;
15874                 o = o->op_next;
15875             }
15876
15877             /* if this is the second pass, and we're at the depth where
15878              * previously we encountered a non-simple index expression,
15879              * stop processing the index at this point */
15880             if (action_count != index_skip) {
15881
15882                 /* look for one or more simple ops that return an array
15883                  * index or hash key */
15884
15885                 switch (o->op_type) {
15886                 case OP_PADSV:
15887                     /* it may be a lexical var index */
15888                     ASSUME(!(o->op_flags & ~(OPf_WANT|OPf_PARENS
15889                                             |OPf_REF|OPf_MOD|OPf_SPECIAL)));
15890                     ASSUME(!(o->op_private &
15891                             ~(OPpPAD_STATE|OPpDEREF|OPpLVAL_INTRO)));
15892
15893                     if (   OP_GIMME(o,0) == G_SCALAR
15894                         && !(o->op_flags & (OPf_REF|OPf_MOD))
15895                         && o->op_private == 0)
15896                     {
15897                         if (pass)
15898                             arg->pad_offset = o->op_targ;
15899                         arg++;
15900                         index_type = MDEREF_INDEX_padsv;
15901                         o = o->op_next;
15902                     }
15903                     break;
15904
15905                 case OP_CONST:
15906                     if (next_is_hash) {
15907                         /* it's a constant hash index */
15908                         if (!(SvFLAGS(cSVOPo_sv) & (SVf_IOK|SVf_NOK|SVf_POK)))
15909                             /* "use constant foo => FOO; $h{+foo}" for
15910                              * some weird FOO, can leave you with constants
15911                              * that aren't simple strings. It's not worth
15912                              * the extra hassle for those edge cases */
15913                             break;
15914
15915                         {
15916                             UNOP *rop = NULL;
15917                             OP * helem_op = o->op_next;
15918
15919                             ASSUME(   helem_op->op_type == OP_HELEM
15920                                    || helem_op->op_type == OP_NULL
15921                                    || pass == 0);
15922                             if (helem_op->op_type == OP_HELEM) {
15923                                 rop = (UNOP*)(((BINOP*)helem_op)->op_first);
15924                                 if (   helem_op->op_private & OPpLVAL_INTRO
15925                                     || rop->op_type != OP_RV2HV
15926                                 )
15927                                     rop = NULL;
15928                             }
15929                             /* on first pass just check; on second pass
15930                              * hekify */
15931                             S_check_hash_fields_and_hekify(aTHX_ rop, cSVOPo,
15932                                                             pass);
15933                         }
15934
15935                         if (pass) {
15936 #ifdef USE_ITHREADS
15937                             /* Relocate sv to the pad for thread safety */
15938                             op_relocate_sv(&cSVOPo->op_sv, &o->op_targ);
15939                             arg->pad_offset = o->op_targ;
15940                             o->op_targ = 0;
15941 #else
15942                             arg->sv = cSVOPx_sv(o);
15943 #endif
15944                         }
15945                     }
15946                     else {
15947                         /* it's a constant array index */
15948                         IV iv;
15949                         SV *ix_sv = cSVOPo->op_sv;
15950                         if (!SvIOK(ix_sv))
15951                             break;
15952                         iv = SvIV(ix_sv);
15953
15954                         if (   action_count == 0
15955                             && iv >= -128
15956                             && iv <= 127
15957                             && (   action == MDEREF_AV_padav_aelem
15958                                 || action == MDEREF_AV_gvav_aelem)
15959                         )
15960                             maybe_aelemfast = TRUE;
15961
15962                         if (pass) {
15963                             arg->iv = iv;
15964                             SvREFCNT_dec_NN(cSVOPo->op_sv);
15965                         }
15966                     }
15967                     if (pass)
15968                         /* we've taken ownership of the SV */
15969                         cSVOPo->op_sv = NULL;
15970                     arg++;
15971                     index_type = MDEREF_INDEX_const;
15972                     o = o->op_next;
15973                     break;
15974
15975                 case OP_GV:
15976                     /* it may be a package var index */
15977
15978                     ASSUME(!(o->op_flags & ~(OPf_WANT|OPf_PARENS|OPf_SPECIAL)));
15979                     ASSUME(!(o->op_private & ~(OPpEARLY_CV)));
15980                     if (  (o->op_flags & ~(OPf_PARENS|OPf_SPECIAL)) != OPf_WANT_SCALAR
15981                         || o->op_private != 0
15982                     )
15983                         break;
15984
15985                     kid = o->op_next;
15986                     if (kid->op_type != OP_RV2SV)
15987                         break;
15988
15989                     ASSUME(!(kid->op_flags &
15990                             ~(OPf_WANT|OPf_KIDS|OPf_MOD|OPf_REF
15991                              |OPf_SPECIAL|OPf_PARENS)));
15992                     ASSUME(!(kid->op_private &
15993                                     ~(OPpARG1_MASK
15994                                      |OPpHINT_STRICT_REFS|OPpOUR_INTRO
15995                                      |OPpDEREF|OPpLVAL_INTRO)));
15996                     if(   (kid->op_flags &~ OPf_PARENS)
15997                             != (OPf_WANT_SCALAR|OPf_KIDS)
15998                        || (kid->op_private & ~(OPpARG1_MASK|HINT_STRICT_REFS))
15999                     )
16000                         break;
16001
16002                     if (pass) {
16003 #ifdef USE_ITHREADS
16004                         arg->pad_offset = cPADOPx(o)->op_padix;
16005                         /* stop it being swiped when nulled */
16006                         cPADOPx(o)->op_padix = 0;
16007 #else
16008                         arg->sv = cSVOPx(o)->op_sv;
16009                         cSVOPo->op_sv = NULL;
16010 #endif
16011                     }
16012                     arg++;
16013                     index_type = MDEREF_INDEX_gvsv;
16014                     o = kid->op_next;
16015                     break;
16016
16017                 } /* switch */
16018             } /* action_count != index_skip */
16019
16020             action |= index_type;
16021
16022
16023             /* at this point we have either:
16024              *   * detected what looks like a simple index expression,
16025              *     and expect the next op to be an [ah]elem, or
16026              *     an nulled  [ah]elem followed by a delete or exists;
16027              *  * found a more complex expression, so something other
16028              *    than the above follows.
16029              */
16030
16031             /* possibly an optimised away [ah]elem (where op_next is
16032              * exists or delete) */
16033             if (o->op_type == OP_NULL)
16034                 o = o->op_next;
16035
16036             /* at this point we're looking for an OP_AELEM, OP_HELEM,
16037              * OP_EXISTS or OP_DELETE */
16038
16039             /* if a custom array/hash access checker is in scope,
16040              * abandon optimisation attempt */
16041             if (  (o->op_type == OP_AELEM || o->op_type == OP_HELEM)
16042                && PL_check[o->op_type] != Perl_ck_null)
16043                 return;
16044             /* similarly for customised exists and delete */
16045             if (  (o->op_type == OP_EXISTS)
16046                && PL_check[o->op_type] != Perl_ck_exists)
16047                 return;
16048             if (  (o->op_type == OP_DELETE)
16049                && PL_check[o->op_type] != Perl_ck_delete)
16050                 return;
16051
16052             if (   o->op_type != OP_AELEM
16053                 || (o->op_private &
16054                       (OPpLVAL_INTRO|OPpLVAL_DEFER|OPpDEREF|OPpMAYBE_LVSUB))
16055                 )
16056                 maybe_aelemfast = FALSE;
16057
16058             /* look for aelem/helem/exists/delete. If it's not the last elem
16059              * lookup, it *must* have OPpDEREF_AV/HV, but not many other
16060              * flags; if it's the last, then it mustn't have
16061              * OPpDEREF_AV/HV, but may have lots of other flags, like
16062              * OPpLVAL_INTRO etc
16063              */
16064
16065             if (   index_type == MDEREF_INDEX_none
16066                 || (   o->op_type != OP_AELEM  && o->op_type != OP_HELEM
16067                     && o->op_type != OP_EXISTS && o->op_type != OP_DELETE)
16068             )
16069                 ok = FALSE;
16070             else {
16071                 /* we have aelem/helem/exists/delete with valid simple index */
16072
16073                 is_deref =    (o->op_type == OP_AELEM || o->op_type == OP_HELEM)
16074                            && (   (o->op_private & OPpDEREF) == OPpDEREF_AV
16075                                || (o->op_private & OPpDEREF) == OPpDEREF_HV);
16076
16077                 /* This doesn't make much sense but is legal:
16078                  *    @{ local $x[0][0] } = 1
16079                  * Since scope exit will undo the autovivification,
16080                  * don't bother in the first place. The OP_LEAVE
16081                  * assertion is in case there are other cases of both
16082                  * OPpLVAL_INTRO and OPpDEREF which don't include a scope
16083                  * exit that would undo the local - in which case this
16084                  * block of code would need rethinking.
16085                  */
16086                 if (is_deref && (o->op_private & OPpLVAL_INTRO)) {
16087 #ifdef DEBUGGING
16088                     OP *n = o->op_next;
16089                     while (n && (  n->op_type == OP_NULL
16090                                 || n->op_type == OP_LIST
16091                                 || n->op_type == OP_SCALAR))
16092                         n = n->op_next;
16093                     assert(n && n->op_type == OP_LEAVE);
16094 #endif
16095                     o->op_private &= ~OPpDEREF;
16096                     is_deref = FALSE;
16097                 }
16098
16099                 if (is_deref) {
16100                     ASSUME(!(o->op_flags &
16101                                  ~(OPf_WANT|OPf_KIDS|OPf_MOD|OPf_PARENS)));
16102                     ASSUME(!(o->op_private & ~(OPpARG2_MASK|OPpDEREF)));
16103
16104                     ok =    (o->op_flags &~ OPf_PARENS)
16105                                == (OPf_WANT_SCALAR|OPf_KIDS|OPf_MOD)
16106                          && !(o->op_private & ~(OPpDEREF|OPpARG2_MASK));
16107                 }
16108                 else if (o->op_type == OP_EXISTS) {
16109                     ASSUME(!(o->op_flags & ~(OPf_WANT|OPf_KIDS|OPf_PARENS
16110                                 |OPf_REF|OPf_MOD|OPf_SPECIAL)));
16111                     ASSUME(!(o->op_private & ~(OPpARG1_MASK|OPpEXISTS_SUB)));
16112                     ok =  !(o->op_private & ~OPpARG1_MASK);
16113                 }
16114                 else if (o->op_type == OP_DELETE) {
16115                     ASSUME(!(o->op_flags & ~(OPf_WANT|OPf_KIDS|OPf_PARENS
16116                                 |OPf_REF|OPf_MOD|OPf_SPECIAL)));
16117                     ASSUME(!(o->op_private &
16118                                     ~(OPpARG1_MASK|OPpSLICE|OPpLVAL_INTRO)));
16119                     /* don't handle slices or 'local delete'; the latter
16120                      * is fairly rare, and has a complex runtime */
16121                     ok =  !(o->op_private & ~OPpARG1_MASK);
16122                     if (OP_TYPE_IS_OR_WAS(cUNOPo->op_first, OP_AELEM))
16123                         /* skip handling run-tome error */
16124                         ok = (ok && cBOOL(o->op_flags & OPf_SPECIAL));
16125                 }
16126                 else {
16127                     ASSUME(o->op_type == OP_AELEM || o->op_type == OP_HELEM);
16128                     ASSUME(!(o->op_flags & ~(OPf_WANT|OPf_KIDS|OPf_MOD
16129                                             |OPf_PARENS|OPf_REF|OPf_SPECIAL)));
16130                     ASSUME(!(o->op_private & ~(OPpARG2_MASK|OPpMAYBE_LVSUB
16131                                     |OPpLVAL_DEFER|OPpDEREF|OPpLVAL_INTRO)));
16132                     ok = (o->op_private & OPpDEREF) != OPpDEREF_SV;
16133                 }
16134             }
16135
16136             if (ok) {
16137                 if (!first_elem_op)
16138                     first_elem_op = o;
16139                 top_op = o;
16140                 if (is_deref) {
16141                     next_is_hash = cBOOL((o->op_private & OPpDEREF) == OPpDEREF_HV);
16142                     o = o->op_next;
16143                 }
16144                 else {
16145                     is_last = TRUE;
16146                     action |= MDEREF_FLAG_last;
16147                 }
16148             }
16149             else {
16150                 /* at this point we have something that started
16151                  * promisingly enough (with rv2av or whatever), but failed
16152                  * to find a simple index followed by an
16153                  * aelem/helem/exists/delete. If this is the first action,
16154                  * give up; but if we've already seen at least one
16155                  * aelem/helem, then keep them and add a new action with
16156                  * MDEREF_INDEX_none, which causes it to do the vivify
16157                  * from the end of the previous lookup, and do the deref,
16158                  * but stop at that point. So $a[0][expr] will do one
16159                  * av_fetch, vivify and deref, then continue executing at
16160                  * expr */
16161                 if (!action_count)
16162                     return;
16163                 is_last = TRUE;
16164                 index_skip = action_count;
16165                 action |= MDEREF_FLAG_last;
16166                 if (index_type != MDEREF_INDEX_none)
16167                     arg--;
16168             }
16169
16170             action_word |= (action << (action_ix * MDEREF_SHIFT));
16171             action_ix++;
16172             action_count++;
16173             /* if there's no space for the next action, reserve a new slot
16174              * for it *before* we start adding args for that action */
16175             if ((action_ix + 1) * MDEREF_SHIFT > UVSIZE*8) {
16176                 if (pass)
16177                     action_ptr->uv = action_word;
16178                 action_word = 0;
16179                 action_ptr = arg;
16180                 arg++;
16181                 action_ix = 0;
16182             }
16183         } /* while !is_last */
16184
16185         /* success! */
16186
16187         if (!action_ix)
16188             /* slot reserved for next action word not now needed */
16189             arg--;
16190         else if (pass)
16191             action_ptr->uv = action_word;
16192
16193         if (pass) {
16194             OP *mderef;
16195             OP *p, *q;
16196
16197             mderef = newUNOP_AUX(OP_MULTIDEREF, 0, NULL, arg_buf);
16198             if (index_skip == -1) {
16199                 mderef->op_flags = o->op_flags
16200                         & (OPf_WANT|OPf_MOD|(next_is_hash ? OPf_SPECIAL : 0));
16201                 if (o->op_type == OP_EXISTS)
16202                     mderef->op_private = OPpMULTIDEREF_EXISTS;
16203                 else if (o->op_type == OP_DELETE)
16204                     mderef->op_private = OPpMULTIDEREF_DELETE;
16205                 else
16206                     mderef->op_private = o->op_private
16207                         & (OPpMAYBE_LVSUB|OPpLVAL_DEFER|OPpLVAL_INTRO);
16208             }
16209             /* accumulate strictness from every level (although I don't think
16210              * they can actually vary) */
16211             mderef->op_private |= hints;
16212
16213             /* integrate the new multideref op into the optree and the
16214              * op_next chain.
16215              *
16216              * In general an op like aelem or helem has two child
16217              * sub-trees: the aggregate expression (a_expr) and the
16218              * index expression (i_expr):
16219              *
16220              *     aelem
16221              *       |
16222              *     a_expr - i_expr
16223              *
16224              * The a_expr returns an AV or HV, while the i-expr returns an
16225              * index. In general a multideref replaces most or all of a
16226              * multi-level tree, e.g.
16227              *
16228              *     exists
16229              *       |
16230              *     ex-aelem
16231              *       |
16232              *     rv2av  - i_expr1
16233              *       |
16234              *     helem
16235              *       |
16236              *     rv2hv  - i_expr2
16237              *       |
16238              *     aelem
16239              *       |
16240              *     a_expr - i_expr3
16241              *
16242              * With multideref, all the i_exprs will be simple vars or
16243              * constants, except that i_expr1 may be arbitrary in the case
16244              * of MDEREF_INDEX_none.
16245              *
16246              * The bottom-most a_expr will be either:
16247              *   1) a simple var (so padXv or gv+rv2Xv);
16248              *   2) a simple scalar var dereferenced (e.g. $r->[0]):
16249              *      so a simple var with an extra rv2Xv;
16250              *   3) or an arbitrary expression.
16251              *
16252              * 'start', the first op in the execution chain, will point to
16253              *   1),2): the padXv or gv op;
16254              *   3):    the rv2Xv which forms the last op in the a_expr
16255              *          execution chain, and the top-most op in the a_expr
16256              *          subtree.
16257              *
16258              * For all cases, the 'start' node is no longer required,
16259              * but we can't free it since one or more external nodes
16260              * may point to it. E.g. consider
16261              *     $h{foo} = $a ? $b : $c
16262              * Here, both the op_next and op_other branches of the
16263              * cond_expr point to the gv[*h] of the hash expression, so
16264              * we can't free the 'start' op.
16265              *
16266              * For expr->[...], we need to save the subtree containing the
16267              * expression; for the other cases, we just need to save the
16268              * start node.
16269              * So in all cases, we null the start op and keep it around by
16270              * making it the child of the multideref op; for the expr->
16271              * case, the expr will be a subtree of the start node.
16272              *
16273              * So in the simple 1,2 case the  optree above changes to
16274              *
16275              *     ex-exists
16276              *       |
16277              *     multideref
16278              *       |
16279              *     ex-gv (or ex-padxv)
16280              *
16281              *  with the op_next chain being
16282              *
16283              *  -> ex-gv -> multideref -> op-following-ex-exists ->
16284              *
16285              *  In the 3 case, we have
16286              *
16287              *     ex-exists
16288              *       |
16289              *     multideref
16290              *       |
16291              *     ex-rv2xv
16292              *       |
16293              *    rest-of-a_expr
16294              *      subtree
16295              *
16296              *  and
16297              *
16298              *  -> rest-of-a_expr subtree ->
16299              *    ex-rv2xv -> multideref -> op-following-ex-exists ->
16300              *
16301              *
16302              * Where the last i_expr is non-simple (i.e. MDEREF_INDEX_none,
16303              * e.g. $a[0]{foo}[$x+1], the next rv2xv is nulled and the
16304              * multideref attached as the child, e.g.
16305              *
16306              *     exists
16307              *       |
16308              *     ex-aelem
16309              *       |
16310              *     ex-rv2av  - i_expr1
16311              *       |
16312              *     multideref
16313              *       |
16314              *     ex-whatever
16315              *
16316              */
16317
16318             /* if we free this op, don't free the pad entry */
16319             if (reset_start_targ)
16320                 start->op_targ = 0;
16321
16322
16323             /* Cut the bit we need to save out of the tree and attach to
16324              * the multideref op, then free the rest of the tree */
16325
16326             /* find parent of node to be detached (for use by splice) */
16327             p = first_elem_op;
16328             if (   orig_action == MDEREF_AV_pop_rv2av_aelem
16329                 || orig_action == MDEREF_HV_pop_rv2hv_helem)
16330             {
16331                 /* there is an arbitrary expression preceding us, e.g.
16332                  * expr->[..]? so we need to save the 'expr' subtree */
16333                 if (p->op_type == OP_EXISTS || p->op_type == OP_DELETE)
16334                     p = cUNOPx(p)->op_first;
16335                 ASSUME(   start->op_type == OP_RV2AV
16336                        || start->op_type == OP_RV2HV);
16337             }
16338             else {
16339                 /* either a padXv or rv2Xv+gv, maybe with an ex-Xelem
16340                  * above for exists/delete. */
16341                 while (   (p->op_flags & OPf_KIDS)
16342                        && cUNOPx(p)->op_first != start
16343                 )
16344                     p = cUNOPx(p)->op_first;
16345             }
16346             ASSUME(cUNOPx(p)->op_first == start);
16347
16348             /* detach from main tree, and re-attach under the multideref */
16349             op_sibling_splice(mderef, NULL, 0,
16350                     op_sibling_splice(p, NULL, 1, NULL));
16351             op_null(start);
16352
16353             start->op_next = mderef;
16354
16355             mderef->op_next = index_skip == -1 ? o->op_next : o;
16356
16357             /* excise and free the original tree, and replace with
16358              * the multideref op */
16359             p = op_sibling_splice(top_op, NULL, -1, mderef);
16360             while (p) {
16361                 q = OpSIBLING(p);
16362                 op_free(p);
16363                 p = q;
16364             }
16365             op_null(top_op);
16366         }
16367         else {
16368             Size_t size = arg - arg_buf;
16369
16370             if (maybe_aelemfast && action_count == 1)
16371                 return;
16372
16373             arg_buf = (UNOP_AUX_item*)PerlMemShared_malloc(
16374                                 sizeof(UNOP_AUX_item) * (size + 1));
16375             /* for dumping etc: store the length in a hidden first slot;
16376              * we set the op_aux pointer to the second slot */
16377             arg_buf->uv = size;
16378             arg_buf++;
16379         }
16380     } /* for (pass = ...) */
16381 }
16382
16383 /* See if the ops following o are such that o will always be executed in
16384  * boolean context: that is, the SV which o pushes onto the stack will
16385  * only ever be consumed by later ops via SvTRUE(sv) or similar.
16386  * If so, set a suitable private flag on o. Normally this will be
16387  * bool_flag; but see below why maybe_flag is needed too.
16388  *
16389  * Typically the two flags you pass will be the generic OPpTRUEBOOL and
16390  * OPpMAYBE_TRUEBOOL, buts it's possible that for some ops those bits may
16391  * already be taken, so you'll have to give that op two different flags.
16392  *
16393  * More explanation of 'maybe_flag' and 'safe_and' parameters.
16394  * The binary logical ops &&, ||, // (plus 'if' and 'unless' which use
16395  * those underlying ops) short-circuit, which means that rather than
16396  * necessarily returning a truth value, they may return the LH argument,
16397  * which may not be boolean. For example in $x = (keys %h || -1), keys
16398  * should return a key count rather than a boolean, even though its
16399  * sort-of being used in boolean context.
16400  *
16401  * So we only consider such logical ops to provide boolean context to
16402  * their LH argument if they themselves are in void or boolean context.
16403  * However, sometimes the context isn't known until run-time. In this
16404  * case the op is marked with the maybe_flag flag it.
16405  *
16406  * Consider the following.
16407  *
16408  *     sub f { ....;  if (%h) { .... } }
16409  *
16410  * This is actually compiled as
16411  *
16412  *     sub f { ....;  %h && do { .... } }
16413  *
16414  * Here we won't know until runtime whether the final statement (and hence
16415  * the &&) is in void context and so is safe to return a boolean value.
16416  * So mark o with maybe_flag rather than the bool_flag.
16417  * Note that there is cost associated with determining context at runtime
16418  * (e.g. a call to block_gimme()), so it may not be worth setting (at
16419  * compile time) and testing (at runtime) maybe_flag if the scalar verses
16420  * boolean costs savings are marginal.
16421  *
16422  * However, we can do slightly better with && (compared to || and //):
16423  * this op only returns its LH argument when that argument is false. In
16424  * this case, as long as the op promises to return a false value which is
16425  * valid in both boolean and scalar contexts, we can mark an op consumed
16426  * by && with bool_flag rather than maybe_flag.
16427  * For example as long as pp_padhv and pp_rv2hv return &PL_sv_zero rather
16428  * than &PL_sv_no for a false result in boolean context, then it's safe. An
16429  * op which promises to handle this case is indicated by setting safe_and
16430  * to true.
16431  */
16432
16433 static void
16434 S_check_for_bool_cxt(OP*o, bool safe_and, U8 bool_flag, U8 maybe_flag)
16435 {
16436     OP *lop;
16437     U8 flag = 0;
16438
16439     assert((o->op_flags & OPf_WANT) == OPf_WANT_SCALAR);
16440
16441     /* OPpTARGET_MY and boolean context probably don't mix well.
16442      * If someone finds a valid use case, maybe add an extra flag to this
16443      * function which indicates its safe to do so for this op? */
16444     assert(!(   (PL_opargs[o->op_type] & OA_TARGLEX)
16445              && (o->op_private & OPpTARGET_MY)));
16446
16447     lop = o->op_next;
16448
16449     while (lop) {
16450         switch (lop->op_type) {
16451         case OP_NULL:
16452         case OP_SCALAR:
16453             break;
16454
16455         /* these two consume the stack argument in the scalar case,
16456          * and treat it as a boolean in the non linenumber case */
16457         case OP_FLIP:
16458         case OP_FLOP:
16459             if (   ((lop->op_flags & OPf_WANT) == OPf_WANT_LIST)
16460                 || (lop->op_private & OPpFLIP_LINENUM))
16461             {
16462                 lop = NULL;
16463                 break;
16464             }
16465             /* FALLTHROUGH */
16466         /* these never leave the original value on the stack */
16467         case OP_NOT:
16468         case OP_XOR:
16469         case OP_COND_EXPR:
16470         case OP_GREPWHILE:
16471             flag = bool_flag;
16472             lop = NULL;
16473             break;
16474
16475         /* OR DOR and AND evaluate their arg as a boolean, but then may
16476          * leave the original scalar value on the stack when following the
16477          * op_next route. If not in void context, we need to ensure
16478          * that whatever follows consumes the arg only in boolean context
16479          * too.
16480          */
16481         case OP_AND:
16482             if (safe_and) {
16483                 flag = bool_flag;
16484                 lop = NULL;
16485                 break;
16486             }
16487             /* FALLTHROUGH */
16488         case OP_OR:
16489         case OP_DOR:
16490             if ((lop->op_flags & OPf_WANT) == OPf_WANT_VOID) {
16491                 flag = bool_flag;
16492                 lop = NULL;
16493             }
16494             else if (!(lop->op_flags & OPf_WANT)) {
16495                 /* unknown context - decide at runtime */
16496                 flag = maybe_flag;
16497                 lop = NULL;
16498             }
16499             break;
16500
16501         default:
16502             lop = NULL;
16503             break;
16504         }
16505
16506         if (lop)
16507             lop = lop->op_next;
16508     }
16509
16510     o->op_private |= flag;
16511 }
16512
16513
16514
16515 /* mechanism for deferring recursion in rpeep() */
16516
16517 #define MAX_DEFERRED 4
16518
16519 #define DEFER(o) \
16520   STMT_START { \
16521     if (defer_ix == (MAX_DEFERRED-1)) { \
16522         OP **defer = defer_queue[defer_base]; \
16523         CALL_RPEEP(*defer); \
16524         S_prune_chain_head(defer); \
16525         defer_base = (defer_base + 1) % MAX_DEFERRED; \
16526         defer_ix--; \
16527     } \
16528     defer_queue[(defer_base + ++defer_ix) % MAX_DEFERRED] = &(o); \
16529   } STMT_END
16530
16531 #define IS_AND_OP(o)   (o->op_type == OP_AND)
16532 #define IS_OR_OP(o)    (o->op_type == OP_OR)
16533
16534
16535 /* A peephole optimizer.  We visit the ops in the order they're to execute.
16536  * See the comments at the top of this file for more details about when
16537  * peep() is called */
16538
16539 void
16540 Perl_rpeep(pTHX_ OP *o)
16541 {
16542     dVAR;
16543     OP* oldop = NULL;
16544     OP* oldoldop = NULL;
16545     OP** defer_queue[MAX_DEFERRED]; /* small queue of deferred branches */
16546     int defer_base = 0;
16547     int defer_ix = -1;
16548
16549     if (!o || o->op_opt)
16550         return;
16551
16552     assert(o->op_type != OP_FREED);
16553
16554     ENTER;
16555     SAVEOP();
16556     SAVEVPTR(PL_curcop);
16557     for (;; o = o->op_next) {
16558         if (o && o->op_opt)
16559             o = NULL;
16560         if (!o) {
16561             while (defer_ix >= 0) {
16562                 OP **defer =
16563                         defer_queue[(defer_base + defer_ix--) % MAX_DEFERRED];
16564                 CALL_RPEEP(*defer);
16565                 S_prune_chain_head(defer);
16566             }
16567             break;
16568         }
16569
16570       redo:
16571
16572         /* oldoldop -> oldop -> o should be a chain of 3 adjacent ops */
16573         assert(!oldoldop || oldoldop->op_next == oldop);
16574         assert(!oldop    || oldop->op_next    == o);
16575
16576         /* By default, this op has now been optimised. A couple of cases below
16577            clear this again.  */
16578         o->op_opt = 1;
16579         PL_op = o;
16580
16581         /* look for a series of 1 or more aggregate derefs, e.g.
16582          *   $a[1]{foo}[$i]{$k}
16583          * and replace with a single OP_MULTIDEREF op.
16584          * Each index must be either a const, or a simple variable,
16585          *
16586          * First, look for likely combinations of starting ops,
16587          * corresponding to (global and lexical variants of)
16588          *     $a[...]   $h{...}
16589          *     $r->[...] $r->{...}
16590          *     (preceding expression)->[...]
16591          *     (preceding expression)->{...}
16592          * and if so, call maybe_multideref() to do a full inspection
16593          * of the op chain and if appropriate, replace with an
16594          * OP_MULTIDEREF
16595          */
16596         {
16597             UV action;
16598             OP *o2 = o;
16599             U8 hints = 0;
16600
16601             switch (o2->op_type) {
16602             case OP_GV:
16603                 /* $pkg[..]   :   gv[*pkg]
16604                  * $pkg->[...]:   gv[*pkg]; rv2sv sKM/DREFAV */
16605
16606                 /* Fail if there are new op flag combinations that we're
16607                  * not aware of, rather than:
16608                  *  * silently failing to optimise, or
16609                  *  * silently optimising the flag away.
16610                  * If this ASSUME starts failing, examine what new flag
16611                  * has been added to the op, and decide whether the
16612                  * optimisation should still occur with that flag, then
16613                  * update the code accordingly. This applies to all the
16614                  * other ASSUMEs in the block of code too.
16615                  */
16616                 ASSUME(!(o2->op_flags &
16617                             ~(OPf_WANT|OPf_MOD|OPf_PARENS|OPf_SPECIAL)));
16618                 ASSUME(!(o2->op_private & ~OPpEARLY_CV));
16619
16620                 o2 = o2->op_next;
16621
16622                 if (o2->op_type == OP_RV2AV) {
16623                     action = MDEREF_AV_gvav_aelem;
16624                     goto do_deref;
16625                 }
16626
16627                 if (o2->op_type == OP_RV2HV) {
16628                     action = MDEREF_HV_gvhv_helem;
16629                     goto do_deref;
16630                 }
16631
16632                 if (o2->op_type != OP_RV2SV)
16633                     break;
16634
16635                 /* at this point we've seen gv,rv2sv, so the only valid
16636                  * construct left is $pkg->[] or $pkg->{} */
16637
16638                 ASSUME(!(o2->op_flags & OPf_STACKED));
16639                 if ((o2->op_flags & (OPf_WANT|OPf_REF|OPf_MOD|OPf_SPECIAL))
16640                             != (OPf_WANT_SCALAR|OPf_MOD))
16641                     break;
16642
16643                 ASSUME(!(o2->op_private & ~(OPpARG1_MASK|HINT_STRICT_REFS
16644                                     |OPpOUR_INTRO|OPpDEREF|OPpLVAL_INTRO)));
16645                 if (o2->op_private & (OPpOUR_INTRO|OPpLVAL_INTRO))
16646                     break;
16647                 if (   (o2->op_private & OPpDEREF) != OPpDEREF_AV
16648                     && (o2->op_private & OPpDEREF) != OPpDEREF_HV)
16649                     break;
16650
16651                 o2 = o2->op_next;
16652                 if (o2->op_type == OP_RV2AV) {
16653                     action = MDEREF_AV_gvsv_vivify_rv2av_aelem;
16654                     goto do_deref;
16655                 }
16656                 if (o2->op_type == OP_RV2HV) {
16657                     action = MDEREF_HV_gvsv_vivify_rv2hv_helem;
16658                     goto do_deref;
16659                 }
16660                 break;
16661
16662             case OP_PADSV:
16663                 /* $lex->[...]: padsv[$lex] sM/DREFAV */
16664
16665                 ASSUME(!(o2->op_flags &
16666                     ~(OPf_WANT|OPf_PARENS|OPf_REF|OPf_MOD|OPf_SPECIAL)));
16667                 if ((o2->op_flags &
16668                         (OPf_WANT|OPf_REF|OPf_MOD|OPf_SPECIAL))
16669                      != (OPf_WANT_SCALAR|OPf_MOD))
16670                     break;
16671
16672                 ASSUME(!(o2->op_private &
16673                                 ~(OPpPAD_STATE|OPpDEREF|OPpLVAL_INTRO)));
16674                 /* skip if state or intro, or not a deref */
16675                 if (      o2->op_private != OPpDEREF_AV
16676                        && o2->op_private != OPpDEREF_HV)
16677                     break;
16678
16679                 o2 = o2->op_next;
16680                 if (o2->op_type == OP_RV2AV) {
16681                     action = MDEREF_AV_padsv_vivify_rv2av_aelem;
16682                     goto do_deref;
16683                 }
16684                 if (o2->op_type == OP_RV2HV) {
16685                     action = MDEREF_HV_padsv_vivify_rv2hv_helem;
16686                     goto do_deref;
16687                 }
16688                 break;
16689
16690             case OP_PADAV:
16691             case OP_PADHV:
16692                 /*    $lex[..]:  padav[@lex:1,2] sR *
16693                  * or $lex{..}:  padhv[%lex:1,2] sR */
16694                 ASSUME(!(o2->op_flags & ~(OPf_WANT|OPf_MOD|OPf_PARENS|
16695                                             OPf_REF|OPf_SPECIAL)));
16696                 if ((o2->op_flags &
16697                         (OPf_WANT|OPf_REF|OPf_MOD|OPf_SPECIAL))
16698                      != (OPf_WANT_SCALAR|OPf_REF))
16699                     break;
16700                 if (o2->op_flags != (OPf_WANT_SCALAR|OPf_REF))
16701                     break;
16702                 /* OPf_PARENS isn't currently used in this case;
16703                  * if that changes, let us know! */
16704                 ASSUME(!(o2->op_flags & OPf_PARENS));
16705
16706                 /* at this point, we wouldn't expect any of the remaining
16707                  * possible private flags:
16708                  * OPpPAD_STATE, OPpLVAL_INTRO, OPpTRUEBOOL,
16709                  * OPpMAYBE_TRUEBOOL, OPpMAYBE_LVSUB
16710                  *
16711                  * OPpSLICEWARNING shouldn't affect runtime
16712                  */
16713                 ASSUME(!(o2->op_private & ~(OPpSLICEWARNING)));
16714
16715                 action = o2->op_type == OP_PADAV
16716                             ? MDEREF_AV_padav_aelem
16717                             : MDEREF_HV_padhv_helem;
16718                 o2 = o2->op_next;
16719                 S_maybe_multideref(aTHX_ o, o2, action, 0);
16720                 break;
16721
16722
16723             case OP_RV2AV:
16724             case OP_RV2HV:
16725                 action = o2->op_type == OP_RV2AV
16726                             ? MDEREF_AV_pop_rv2av_aelem
16727                             : MDEREF_HV_pop_rv2hv_helem;
16728                 /* FALLTHROUGH */
16729             do_deref:
16730                 /* (expr)->[...]:  rv2av sKR/1;
16731                  * (expr)->{...}:  rv2hv sKR/1; */
16732
16733                 ASSUME(o2->op_type == OP_RV2AV || o2->op_type == OP_RV2HV);
16734
16735                 ASSUME(!(o2->op_flags & ~(OPf_WANT|OPf_KIDS|OPf_PARENS
16736                                 |OPf_REF|OPf_MOD|OPf_STACKED|OPf_SPECIAL)));
16737                 if (o2->op_flags != (OPf_WANT_SCALAR|OPf_KIDS|OPf_REF))
16738                     break;
16739
16740                 /* at this point, we wouldn't expect any of these
16741                  * possible private flags:
16742                  * OPpMAYBE_LVSUB, OPpLVAL_INTRO
16743                  * OPpTRUEBOOL, OPpMAYBE_TRUEBOOL, (rv2hv only)
16744                  */
16745                 ASSUME(!(o2->op_private &
16746                     ~(OPpHINT_STRICT_REFS|OPpARG1_MASK|OPpSLICEWARNING
16747                      |OPpOUR_INTRO)));
16748                 hints |= (o2->op_private & OPpHINT_STRICT_REFS);
16749
16750                 o2 = o2->op_next;
16751
16752                 S_maybe_multideref(aTHX_ o, o2, action, hints);
16753                 break;
16754
16755             default:
16756                 break;
16757             }
16758         }
16759
16760
16761         switch (o->op_type) {
16762         case OP_DBSTATE:
16763             PL_curcop = ((COP*)o);              /* for warnings */
16764             break;
16765         case OP_NEXTSTATE:
16766             PL_curcop = ((COP*)o);              /* for warnings */
16767
16768             /* Optimise a "return ..." at the end of a sub to just be "...".
16769              * This saves 2 ops. Before:
16770              * 1  <;> nextstate(main 1 -e:1) v ->2
16771              * 4  <@> return K ->5
16772              * 2    <0> pushmark s ->3
16773              * -    <1> ex-rv2sv sK/1 ->4
16774              * 3      <#> gvsv[*cat] s ->4
16775              *
16776              * After:
16777              * -  <@> return K ->-
16778              * -    <0> pushmark s ->2
16779              * -    <1> ex-rv2sv sK/1 ->-
16780              * 2      <$> gvsv(*cat) s ->3
16781              */
16782             {
16783                 OP *next = o->op_next;
16784                 OP *sibling = OpSIBLING(o);
16785                 if (   OP_TYPE_IS(next, OP_PUSHMARK)
16786                     && OP_TYPE_IS(sibling, OP_RETURN)
16787                     && OP_TYPE_IS(sibling->op_next, OP_LINESEQ)
16788                     && ( OP_TYPE_IS(sibling->op_next->op_next, OP_LEAVESUB)
16789                        ||OP_TYPE_IS(sibling->op_next->op_next,
16790                                     OP_LEAVESUBLV))
16791                     && cUNOPx(sibling)->op_first == next
16792                     && OpHAS_SIBLING(next) && OpSIBLING(next)->op_next
16793                     && next->op_next
16794                 ) {
16795                     /* Look through the PUSHMARK's siblings for one that
16796                      * points to the RETURN */
16797                     OP *top = OpSIBLING(next);
16798                     while (top && top->op_next) {
16799                         if (top->op_next == sibling) {
16800                             top->op_next = sibling->op_next;
16801                             o->op_next = next->op_next;
16802                             break;
16803                         }
16804                         top = OpSIBLING(top);
16805                     }
16806                 }
16807             }
16808
16809             /* Optimise 'my $x; my $y;' into 'my ($x, $y);'
16810              *
16811              * This latter form is then suitable for conversion into padrange
16812              * later on. Convert:
16813              *
16814              *   nextstate1 -> padop1 -> nextstate2 -> padop2 -> nextstate3
16815              *
16816              * into:
16817              *
16818              *   nextstate1 ->     listop     -> nextstate3
16819              *                 /            \
16820              *         pushmark -> padop1 -> padop2
16821              */
16822             if (o->op_next && (
16823                     o->op_next->op_type == OP_PADSV
16824                  || o->op_next->op_type == OP_PADAV
16825                  || o->op_next->op_type == OP_PADHV
16826                 )
16827                 && !(o->op_next->op_private & ~OPpLVAL_INTRO)
16828                 && o->op_next->op_next && o->op_next->op_next->op_type == OP_NEXTSTATE
16829                 && o->op_next->op_next->op_next && (
16830                     o->op_next->op_next->op_next->op_type == OP_PADSV
16831                  || o->op_next->op_next->op_next->op_type == OP_PADAV
16832                  || o->op_next->op_next->op_next->op_type == OP_PADHV
16833                 )
16834                 && !(o->op_next->op_next->op_next->op_private & ~OPpLVAL_INTRO)
16835                 && o->op_next->op_next->op_next->op_next && o->op_next->op_next->op_next->op_next->op_type == OP_NEXTSTATE
16836                 && (!CopLABEL((COP*)o)) /* Don't mess with labels */
16837                 && (!CopLABEL((COP*)o->op_next->op_next)) /* ... */
16838             ) {
16839                 OP *pad1, *ns2, *pad2, *ns3, *newop, *newpm;
16840
16841                 pad1 =    o->op_next;
16842                 ns2  = pad1->op_next;
16843                 pad2 =  ns2->op_next;
16844                 ns3  = pad2->op_next;
16845
16846                 /* we assume here that the op_next chain is the same as
16847                  * the op_sibling chain */
16848                 assert(OpSIBLING(o)    == pad1);
16849                 assert(OpSIBLING(pad1) == ns2);
16850                 assert(OpSIBLING(ns2)  == pad2);
16851                 assert(OpSIBLING(pad2) == ns3);
16852
16853                 /* excise and delete ns2 */
16854                 op_sibling_splice(NULL, pad1, 1, NULL);
16855                 op_free(ns2);
16856
16857                 /* excise pad1 and pad2 */
16858                 op_sibling_splice(NULL, o, 2, NULL);
16859
16860                 /* create new listop, with children consisting of:
16861                  * a new pushmark, pad1, pad2. */
16862                 newop = newLISTOP(OP_LIST, 0, pad1, pad2);
16863                 newop->op_flags |= OPf_PARENS;
16864                 newop->op_flags = (newop->op_flags & ~OPf_WANT) | OPf_WANT_VOID;
16865
16866                 /* insert newop between o and ns3 */
16867                 op_sibling_splice(NULL, o, 0, newop);
16868
16869                 /*fixup op_next chain */
16870                 newpm = cUNOPx(newop)->op_first; /* pushmark */
16871                 o    ->op_next = newpm;
16872                 newpm->op_next = pad1;
16873                 pad1 ->op_next = pad2;
16874                 pad2 ->op_next = newop; /* listop */
16875                 newop->op_next = ns3;
16876
16877                 /* Ensure pushmark has this flag if padops do */
16878                 if (pad1->op_flags & OPf_MOD && pad2->op_flags & OPf_MOD) {
16879                     newpm->op_flags |= OPf_MOD;
16880                 }
16881
16882                 break;
16883             }
16884
16885             /* Two NEXTSTATEs in a row serve no purpose. Except if they happen
16886                to carry two labels. For now, take the easier option, and skip
16887                this optimisation if the first NEXTSTATE has a label.  */
16888             if (!CopLABEL((COP*)o) && !PERLDB_NOOPT) {
16889                 OP *nextop = o->op_next;
16890                 while (nextop) {
16891                     switch (nextop->op_type) {
16892                         case OP_NULL:
16893                         case OP_SCALAR:
16894                         case OP_LINESEQ:
16895                         case OP_SCOPE:
16896                             nextop = nextop->op_next;
16897                             continue;
16898                     }
16899                     break;
16900                 }
16901
16902                 if (nextop && (nextop->op_type == OP_NEXTSTATE)) {
16903                     op_null(o);
16904                     if (oldop)
16905                         oldop->op_next = nextop;
16906                     o = nextop;
16907                     /* Skip (old)oldop assignment since the current oldop's
16908                        op_next already points to the next op.  */
16909                     goto redo;
16910                 }
16911             }
16912             break;
16913
16914         case OP_CONCAT:
16915             if (o->op_next && o->op_next->op_type == OP_STRINGIFY) {
16916                 if (o->op_next->op_private & OPpTARGET_MY) {
16917                     if (o->op_flags & OPf_STACKED) /* chained concats */
16918                         break; /* ignore_optimization */
16919                     else {
16920                         /* assert(PL_opargs[o->op_type] & OA_TARGLEX); */
16921                         o->op_targ = o->op_next->op_targ;
16922                         o->op_next->op_targ = 0;
16923                         o->op_private |= OPpTARGET_MY;
16924                     }
16925                 }
16926                 op_null(o->op_next);
16927             }
16928             break;
16929         case OP_STUB:
16930             if ((o->op_flags & OPf_WANT) != OPf_WANT_LIST) {
16931                 break; /* Scalar stub must produce undef.  List stub is noop */
16932             }
16933             goto nothin;
16934         case OP_NULL:
16935             if (o->op_targ == OP_NEXTSTATE
16936                 || o->op_targ == OP_DBSTATE)
16937             {
16938                 PL_curcop = ((COP*)o);
16939             }
16940             /* XXX: We avoid setting op_seq here to prevent later calls
16941                to rpeep() from mistakenly concluding that optimisation
16942                has already occurred. This doesn't fix the real problem,
16943                though (See 20010220.007 (#5874)). AMS 20010719 */
16944             /* op_seq functionality is now replaced by op_opt */
16945             o->op_opt = 0;
16946             /* FALLTHROUGH */
16947         case OP_SCALAR:
16948         case OP_LINESEQ:
16949         case OP_SCOPE:
16950         nothin:
16951             if (oldop) {
16952                 oldop->op_next = o->op_next;
16953                 o->op_opt = 0;
16954                 continue;
16955             }
16956             break;
16957
16958         case OP_PUSHMARK:
16959
16960             /* Given
16961                  5 repeat/DOLIST
16962                  3   ex-list
16963                  1     pushmark
16964                  2     scalar or const
16965                  4   const[0]
16966                convert repeat into a stub with no kids.
16967              */
16968             if (o->op_next->op_type == OP_CONST
16969              || (  o->op_next->op_type == OP_PADSV
16970                 && !(o->op_next->op_private & OPpLVAL_INTRO))
16971              || (  o->op_next->op_type == OP_GV
16972                 && o->op_next->op_next->op_type == OP_RV2SV
16973                 && !(o->op_next->op_next->op_private
16974                         & (OPpLVAL_INTRO|OPpOUR_INTRO))))
16975             {
16976                 const OP *kid = o->op_next->op_next;
16977                 if (o->op_next->op_type == OP_GV)
16978                    kid = kid->op_next;
16979                 /* kid is now the ex-list.  */
16980                 if (kid->op_type == OP_NULL
16981                  && (kid = kid->op_next)->op_type == OP_CONST
16982                     /* kid is now the repeat count.  */
16983                  && kid->op_next->op_type == OP_REPEAT
16984                  && kid->op_next->op_private & OPpREPEAT_DOLIST
16985                  && (kid->op_next->op_flags & OPf_WANT) == OPf_WANT_LIST
16986                  && SvIOK(kSVOP_sv) && SvIVX(kSVOP_sv) == 0
16987                  && oldop)
16988                 {
16989                     o = kid->op_next; /* repeat */
16990                     oldop->op_next = o;
16991                     op_free(cBINOPo->op_first);
16992                     op_free(cBINOPo->op_last );
16993                     o->op_flags &=~ OPf_KIDS;
16994                     /* stub is a baseop; repeat is a binop */
16995                     STATIC_ASSERT_STMT(sizeof(OP) <= sizeof(BINOP));
16996                     OpTYPE_set(o, OP_STUB);
16997                     o->op_private = 0;
16998                     break;
16999                 }
17000             }
17001
17002             /* Convert a series of PAD ops for my vars plus support into a
17003              * single padrange op. Basically
17004              *
17005              *    pushmark -> pad[ahs]v -> pad[ahs]?v -> ... -> (list) -> rest
17006              *
17007              * becomes, depending on circumstances, one of
17008              *
17009              *    padrange  ----------------------------------> (list) -> rest
17010              *    padrange  --------------------------------------------> rest
17011              *
17012              * where all the pad indexes are sequential and of the same type
17013              * (INTRO or not).
17014              * We convert the pushmark into a padrange op, then skip
17015              * any other pad ops, and possibly some trailing ops.
17016              * Note that we don't null() the skipped ops, to make it
17017              * easier for Deparse to undo this optimisation (and none of
17018              * the skipped ops are holding any resourses). It also makes
17019              * it easier for find_uninit_var(), as it can just ignore
17020              * padrange, and examine the original pad ops.
17021              */
17022         {
17023             OP *p;
17024             OP *followop = NULL; /* the op that will follow the padrange op */
17025             U8 count = 0;
17026             U8 intro = 0;
17027             PADOFFSET base = 0; /* init only to stop compiler whining */
17028             bool gvoid = 0;     /* init only to stop compiler whining */
17029             bool defav = 0;  /* seen (...) = @_ */
17030             bool reuse = 0;  /* reuse an existing padrange op */
17031
17032             /* look for a pushmark -> gv[_] -> rv2av */
17033
17034             {
17035                 OP *rv2av, *q;
17036                 p = o->op_next;
17037                 if (   p->op_type == OP_GV
17038                     && cGVOPx_gv(p) == PL_defgv
17039                     && (rv2av = p->op_next)
17040                     && rv2av->op_type == OP_RV2AV
17041                     && !(rv2av->op_flags & OPf_REF)
17042                     && !(rv2av->op_private & (OPpLVAL_INTRO|OPpMAYBE_LVSUB))
17043                     && ((rv2av->op_flags & OPf_WANT) == OPf_WANT_LIST)
17044                 ) {
17045                     q = rv2av->op_next;
17046                     if (q->op_type == OP_NULL)
17047                         q = q->op_next;
17048                     if (q->op_type == OP_PUSHMARK) {
17049                         defav = 1;
17050                         p = q;
17051                     }
17052                 }
17053             }
17054             if (!defav) {
17055                 p = o;
17056             }
17057
17058             /* scan for PAD ops */
17059
17060             for (p = p->op_next; p; p = p->op_next) {
17061                 if (p->op_type == OP_NULL)
17062                     continue;
17063
17064                 if ((     p->op_type != OP_PADSV
17065                        && p->op_type != OP_PADAV
17066                        && p->op_type != OP_PADHV
17067                     )
17068                       /* any private flag other than INTRO? e.g. STATE */
17069                    || (p->op_private & ~OPpLVAL_INTRO)
17070                 )
17071                     break;
17072
17073                 /* let $a[N] potentially be optimised into AELEMFAST_LEX
17074                  * instead */
17075                 if (   p->op_type == OP_PADAV
17076                     && p->op_next
17077                     && p->op_next->op_type == OP_CONST
17078                     && p->op_next->op_next
17079                     && p->op_next->op_next->op_type == OP_AELEM
17080                 )
17081                     break;
17082
17083                 /* for 1st padop, note what type it is and the range
17084                  * start; for the others, check that it's the same type
17085                  * and that the targs are contiguous */
17086                 if (count == 0) {
17087                     intro = (p->op_private & OPpLVAL_INTRO);
17088                     base = p->op_targ;
17089                     gvoid = OP_GIMME(p,0) == G_VOID;
17090                 }
17091                 else {
17092                     if ((p->op_private & OPpLVAL_INTRO) != intro)
17093                         break;
17094                     /* Note that you'd normally  expect targs to be
17095                      * contiguous in my($a,$b,$c), but that's not the case
17096                      * when external modules start doing things, e.g.
17097                      * Function::Parameters */
17098                     if (p->op_targ != base + count)
17099                         break;
17100                     assert(p->op_targ == base + count);
17101                     /* Either all the padops or none of the padops should
17102                        be in void context.  Since we only do the optimisa-
17103                        tion for av/hv when the aggregate itself is pushed
17104                        on to the stack (one item), there is no need to dis-
17105                        tinguish list from scalar context.  */
17106                     if (gvoid != (OP_GIMME(p,0) == G_VOID))
17107                         break;
17108                 }
17109
17110                 /* for AV, HV, only when we're not flattening */
17111                 if (   p->op_type != OP_PADSV
17112                     && !gvoid
17113                     && !(p->op_flags & OPf_REF)
17114                 )
17115                     break;
17116
17117                 if (count >= OPpPADRANGE_COUNTMASK)
17118                     break;
17119
17120                 /* there's a biggest base we can fit into a
17121                  * SAVEt_CLEARPADRANGE in pp_padrange.
17122                  * (The sizeof() stuff will be constant-folded, and is
17123                  * intended to avoid getting "comparison is always false"
17124                  * compiler warnings. See the comments above
17125                  * MEM_WRAP_CHECK for more explanation on why we do this
17126                  * in a weird way to avoid compiler warnings.)
17127                  */
17128                 if (   intro
17129                     && (8*sizeof(base) >
17130                         8*sizeof(UV)-OPpPADRANGE_COUNTSHIFT-SAVE_TIGHT_SHIFT
17131                         ? (Size_t)base
17132                         : (UV_MAX >> (OPpPADRANGE_COUNTSHIFT+SAVE_TIGHT_SHIFT))
17133                         ) >
17134                         (UV_MAX >> (OPpPADRANGE_COUNTSHIFT+SAVE_TIGHT_SHIFT))
17135                 )
17136                     break;
17137
17138                 /* Success! We've got another valid pad op to optimise away */
17139                 count++;
17140                 followop = p->op_next;
17141             }
17142
17143             if (count < 1 || (count == 1 && !defav))
17144                 break;
17145
17146             /* pp_padrange in specifically compile-time void context
17147              * skips pushing a mark and lexicals; in all other contexts
17148              * (including unknown till runtime) it pushes a mark and the
17149              * lexicals. We must be very careful then, that the ops we
17150              * optimise away would have exactly the same effect as the
17151              * padrange.
17152              * In particular in void context, we can only optimise to
17153              * a padrange if we see the complete sequence
17154              *     pushmark, pad*v, ...., list
17155              * which has the net effect of leaving the markstack as it
17156              * was.  Not pushing onto the stack (whereas padsv does touch
17157              * the stack) makes no difference in void context.
17158              */
17159             assert(followop);
17160             if (gvoid) {
17161                 if (followop->op_type == OP_LIST
17162                         && OP_GIMME(followop,0) == G_VOID
17163                    )
17164                 {
17165                     followop = followop->op_next; /* skip OP_LIST */
17166
17167                     /* consolidate two successive my(...);'s */
17168
17169                     if (   oldoldop
17170                         && oldoldop->op_type == OP_PADRANGE
17171                         && (oldoldop->op_flags & OPf_WANT) == OPf_WANT_VOID
17172                         && (oldoldop->op_private & OPpLVAL_INTRO) == intro
17173                         && !(oldoldop->op_flags & OPf_SPECIAL)
17174                     ) {
17175                         U8 old_count;
17176                         assert(oldoldop->op_next == oldop);
17177                         assert(   oldop->op_type == OP_NEXTSTATE
17178                                || oldop->op_type == OP_DBSTATE);
17179                         assert(oldop->op_next == o);
17180
17181                         old_count
17182                             = (oldoldop->op_private & OPpPADRANGE_COUNTMASK);
17183
17184                        /* Do not assume pad offsets for $c and $d are con-
17185                           tiguous in
17186                             my ($a,$b,$c);
17187                             my ($d,$e,$f);
17188                         */
17189                         if (  oldoldop->op_targ + old_count == base
17190                            && old_count < OPpPADRANGE_COUNTMASK - count) {
17191                             base = oldoldop->op_targ;
17192                             count += old_count;
17193                             reuse = 1;
17194                         }
17195                     }
17196
17197                     /* if there's any immediately following singleton
17198                      * my var's; then swallow them and the associated
17199                      * nextstates; i.e.
17200                      *    my ($a,$b); my $c; my $d;
17201                      * is treated as
17202                      *    my ($a,$b,$c,$d);
17203                      */
17204
17205                     while (    ((p = followop->op_next))
17206                             && (  p->op_type == OP_PADSV
17207                                || p->op_type == OP_PADAV
17208                                || p->op_type == OP_PADHV)
17209                             && (p->op_flags & OPf_WANT) == OPf_WANT_VOID
17210                             && (p->op_private & OPpLVAL_INTRO) == intro
17211                             && !(p->op_private & ~OPpLVAL_INTRO)
17212                             && p->op_next
17213                             && (   p->op_next->op_type == OP_NEXTSTATE
17214                                 || p->op_next->op_type == OP_DBSTATE)
17215                             && count < OPpPADRANGE_COUNTMASK
17216                             && base + count == p->op_targ
17217                     ) {
17218                         count++;
17219                         followop = p->op_next;
17220                     }
17221                 }
17222                 else
17223                     break;
17224             }
17225
17226             if (reuse) {
17227                 assert(oldoldop->op_type == OP_PADRANGE);
17228                 oldoldop->op_next = followop;
17229                 oldoldop->op_private = (intro | count);
17230                 o = oldoldop;
17231                 oldop = NULL;
17232                 oldoldop = NULL;
17233             }
17234             else {
17235                 /* Convert the pushmark into a padrange.
17236                  * To make Deparse easier, we guarantee that a padrange was
17237                  * *always* formerly a pushmark */
17238                 assert(o->op_type == OP_PUSHMARK);
17239                 o->op_next = followop;
17240                 OpTYPE_set(o, OP_PADRANGE);
17241                 o->op_targ = base;
17242                 /* bit 7: INTRO; bit 6..0: count */
17243                 o->op_private = (intro | count);
17244                 o->op_flags = ((o->op_flags & ~(OPf_WANT|OPf_SPECIAL))
17245                               | gvoid * OPf_WANT_VOID
17246                               | (defav ? OPf_SPECIAL : 0));
17247             }
17248             break;
17249         }
17250
17251         case OP_RV2AV:
17252             if ((o->op_flags & OPf_WANT) == OPf_WANT_SCALAR)
17253                 S_check_for_bool_cxt(o, 1, OPpTRUEBOOL, 0);
17254             break;
17255
17256         case OP_RV2HV:
17257         case OP_PADHV:
17258             /*'keys %h' in void or scalar context: skip the OP_KEYS
17259              * and perform the functionality directly in the RV2HV/PADHV
17260              * op
17261              */
17262             if (o->op_flags & OPf_REF) {
17263                 OP *k = o->op_next;
17264                 U8 want = (k->op_flags & OPf_WANT);
17265                 if (   k
17266                     && k->op_type == OP_KEYS
17267                     && (   want == OPf_WANT_VOID
17268                         || want == OPf_WANT_SCALAR)
17269                     && !(k->op_private & OPpMAYBE_LVSUB)
17270                     && !(k->op_flags & OPf_MOD)
17271                 ) {
17272                     o->op_next     = k->op_next;
17273                     o->op_flags   &= ~(OPf_REF|OPf_WANT);
17274                     o->op_flags   |= want;
17275                     o->op_private |= (o->op_type == OP_PADHV ?
17276                                       OPpPADHV_ISKEYS : OPpRV2HV_ISKEYS);
17277                     /* for keys(%lex), hold onto the OP_KEYS's targ
17278                      * since padhv doesn't have its own targ to return
17279                      * an int with */
17280                     if (!(o->op_type ==OP_PADHV && want == OPf_WANT_SCALAR))
17281                         op_null(k);
17282                 }
17283             }
17284
17285             /* see if %h is used in boolean context */
17286             if ((o->op_flags & OPf_WANT) == OPf_WANT_SCALAR)
17287                 S_check_for_bool_cxt(o, 1, OPpTRUEBOOL, OPpMAYBE_TRUEBOOL);
17288
17289
17290             if (o->op_type != OP_PADHV)
17291                 break;
17292             /* FALLTHROUGH */
17293         case OP_PADAV:
17294             if (   o->op_type == OP_PADAV
17295                 && (o->op_flags & OPf_WANT) == OPf_WANT_SCALAR
17296             )
17297                 S_check_for_bool_cxt(o, 1, OPpTRUEBOOL, 0);
17298             /* FALLTHROUGH */
17299         case OP_PADSV:
17300             /* Skip over state($x) in void context.  */
17301             if (oldop && o->op_private == (OPpPAD_STATE|OPpLVAL_INTRO)
17302              && (o->op_flags & OPf_WANT) == OPf_WANT_VOID)
17303             {
17304                 oldop->op_next = o->op_next;
17305                 goto redo_nextstate;
17306             }
17307             if (o->op_type != OP_PADAV)
17308                 break;
17309             /* FALLTHROUGH */
17310         case OP_GV:
17311             if (o->op_type == OP_PADAV || o->op_next->op_type == OP_RV2AV) {
17312                 OP* const pop = (o->op_type == OP_PADAV) ?
17313                             o->op_next : o->op_next->op_next;
17314                 IV i;
17315                 if (pop && pop->op_type == OP_CONST &&
17316                     ((PL_op = pop->op_next)) &&
17317                     pop->op_next->op_type == OP_AELEM &&
17318                     !(pop->op_next->op_private &
17319                       (OPpLVAL_INTRO|OPpLVAL_DEFER|OPpDEREF|OPpMAYBE_LVSUB)) &&
17320                     (i = SvIV(((SVOP*)pop)->op_sv)) >= -128 && i <= 127)
17321                 {
17322                     GV *gv;
17323                     if (cSVOPx(pop)->op_private & OPpCONST_STRICT)
17324                         no_bareword_allowed(pop);
17325                     if (o->op_type == OP_GV)
17326                         op_null(o->op_next);
17327                     op_null(pop->op_next);
17328                     op_null(pop);
17329                     o->op_flags |= pop->op_next->op_flags & OPf_MOD;
17330                     o->op_next = pop->op_next->op_next;
17331                     o->op_ppaddr = PL_ppaddr[OP_AELEMFAST];
17332                     o->op_private = (U8)i;
17333                     if (o->op_type == OP_GV) {
17334                         gv = cGVOPo_gv;
17335                         GvAVn(gv);
17336                         o->op_type = OP_AELEMFAST;
17337                     }
17338                     else
17339                         o->op_type = OP_AELEMFAST_LEX;
17340                 }
17341                 if (o->op_type != OP_GV)
17342                     break;
17343             }
17344
17345             /* Remove $foo from the op_next chain in void context.  */
17346             if (oldop
17347              && (  o->op_next->op_type == OP_RV2SV
17348                 || o->op_next->op_type == OP_RV2AV
17349                 || o->op_next->op_type == OP_RV2HV  )
17350              && (o->op_next->op_flags & OPf_WANT) == OPf_WANT_VOID
17351              && !(o->op_next->op_private & OPpLVAL_INTRO))
17352             {
17353                 oldop->op_next = o->op_next->op_next;
17354                 /* Reprocess the previous op if it is a nextstate, to
17355                    allow double-nextstate optimisation.  */
17356               redo_nextstate:
17357                 if (oldop->op_type == OP_NEXTSTATE) {
17358                     oldop->op_opt = 0;
17359                     o = oldop;
17360                     oldop = oldoldop;
17361                     oldoldop = NULL;
17362                     goto redo;
17363                 }
17364                 o = oldop->op_next;
17365                 goto redo;
17366             }
17367             else if (o->op_next->op_type == OP_RV2SV) {
17368                 if (!(o->op_next->op_private & OPpDEREF)) {
17369                     op_null(o->op_next);
17370                     o->op_private |= o->op_next->op_private & (OPpLVAL_INTRO
17371                                                                | OPpOUR_INTRO);
17372                     o->op_next = o->op_next->op_next;
17373                     OpTYPE_set(o, OP_GVSV);
17374                 }
17375             }
17376             else if (o->op_next->op_type == OP_READLINE
17377                     && o->op_next->op_next->op_type == OP_CONCAT
17378                     && (o->op_next->op_next->op_flags & OPf_STACKED))
17379             {
17380                 /* Turn "$a .= <FH>" into an OP_RCATLINE. AMS 20010917 */
17381                 OpTYPE_set(o, OP_RCATLINE);
17382                 o->op_flags |= OPf_STACKED;
17383                 op_null(o->op_next->op_next);
17384                 op_null(o->op_next);
17385             }
17386
17387             break;
17388
17389         case OP_NOT:
17390             break;
17391
17392         case OP_AND:
17393         case OP_OR:
17394         case OP_DOR:
17395             while (cLOGOP->op_other->op_type == OP_NULL)
17396                 cLOGOP->op_other = cLOGOP->op_other->op_next;
17397             while (o->op_next && (   o->op_type == o->op_next->op_type
17398                                   || o->op_next->op_type == OP_NULL))
17399                 o->op_next = o->op_next->op_next;
17400
17401             /* If we're an OR and our next is an AND in void context, we'll
17402                follow its op_other on short circuit, same for reverse.
17403                We can't do this with OP_DOR since if it's true, its return
17404                value is the underlying value which must be evaluated
17405                by the next op. */
17406             if (o->op_next &&
17407                 (
17408                     (IS_AND_OP(o) && IS_OR_OP(o->op_next))
17409                  || (IS_OR_OP(o) && IS_AND_OP(o->op_next))
17410                 )
17411                 && (o->op_next->op_flags & OPf_WANT) == OPf_WANT_VOID
17412             ) {
17413                 o->op_next = ((LOGOP*)o->op_next)->op_other;
17414             }
17415             DEFER(cLOGOP->op_other);
17416             o->op_opt = 1;
17417             break;
17418
17419         case OP_GREPWHILE:
17420             if ((o->op_flags & OPf_WANT) == OPf_WANT_SCALAR)
17421                 S_check_for_bool_cxt(o, 1, OPpTRUEBOOL, 0);
17422             /* FALLTHROUGH */
17423         case OP_COND_EXPR:
17424         case OP_MAPWHILE:
17425         case OP_ANDASSIGN:
17426         case OP_ORASSIGN:
17427         case OP_DORASSIGN:
17428         case OP_RANGE:
17429         case OP_ONCE:
17430         case OP_ARGDEFELEM:
17431             while (cLOGOP->op_other->op_type == OP_NULL)
17432                 cLOGOP->op_other = cLOGOP->op_other->op_next;
17433             DEFER(cLOGOP->op_other);
17434             break;
17435
17436         case OP_ENTERLOOP:
17437         case OP_ENTERITER:
17438             while (cLOOP->op_redoop->op_type == OP_NULL)
17439                 cLOOP->op_redoop = cLOOP->op_redoop->op_next;
17440             while (cLOOP->op_nextop->op_type == OP_NULL)
17441                 cLOOP->op_nextop = cLOOP->op_nextop->op_next;
17442             while (cLOOP->op_lastop->op_type == OP_NULL)
17443                 cLOOP->op_lastop = cLOOP->op_lastop->op_next;
17444             /* a while(1) loop doesn't have an op_next that escapes the
17445              * loop, so we have to explicitly follow the op_lastop to
17446              * process the rest of the code */
17447             DEFER(cLOOP->op_lastop);
17448             break;
17449
17450         case OP_ENTERTRY:
17451             assert(cLOGOPo->op_other->op_type == OP_LEAVETRY);
17452             DEFER(cLOGOPo->op_other);
17453             break;
17454
17455         case OP_SUBST:
17456             if ((o->op_flags & OPf_WANT) == OPf_WANT_SCALAR)
17457                 S_check_for_bool_cxt(o, 1, OPpTRUEBOOL, 0);
17458             assert(!(cPMOP->op_pmflags & PMf_ONCE));
17459             while (cPMOP->op_pmstashstartu.op_pmreplstart &&
17460                    cPMOP->op_pmstashstartu.op_pmreplstart->op_type == OP_NULL)
17461                 cPMOP->op_pmstashstartu.op_pmreplstart
17462                     = cPMOP->op_pmstashstartu.op_pmreplstart->op_next;
17463             DEFER(cPMOP->op_pmstashstartu.op_pmreplstart);
17464             break;
17465
17466         case OP_SORT: {
17467             OP *oright;
17468
17469             if (o->op_flags & OPf_SPECIAL) {
17470                 /* first arg is a code block */
17471                 OP * const nullop = OpSIBLING(cLISTOP->op_first);
17472                 OP * kid          = cUNOPx(nullop)->op_first;
17473
17474                 assert(nullop->op_type == OP_NULL);
17475                 assert(kid->op_type == OP_SCOPE
17476                  || (kid->op_type == OP_NULL && kid->op_targ == OP_LEAVE));
17477                 /* since OP_SORT doesn't have a handy op_other-style
17478                  * field that can point directly to the start of the code
17479                  * block, store it in the otherwise-unused op_next field
17480                  * of the top-level OP_NULL. This will be quicker at
17481                  * run-time, and it will also allow us to remove leading
17482                  * OP_NULLs by just messing with op_nexts without
17483                  * altering the basic op_first/op_sibling layout. */
17484                 kid = kLISTOP->op_first;
17485                 assert(
17486                       (kid->op_type == OP_NULL
17487                       && (  kid->op_targ == OP_NEXTSTATE
17488                          || kid->op_targ == OP_DBSTATE  ))
17489                     || kid->op_type == OP_STUB
17490                     || kid->op_type == OP_ENTER
17491                     || (PL_parser && PL_parser->error_count));
17492                 nullop->op_next = kid->op_next;
17493                 DEFER(nullop->op_next);
17494             }
17495
17496             /* check that RHS of sort is a single plain array */
17497             oright = cUNOPo->op_first;
17498             if (!oright || oright->op_type != OP_PUSHMARK)
17499                 break;
17500
17501             if (o->op_private & OPpSORT_INPLACE)
17502                 break;
17503
17504             /* reverse sort ... can be optimised.  */
17505             if (!OpHAS_SIBLING(cUNOPo)) {
17506                 /* Nothing follows us on the list. */
17507                 OP * const reverse = o->op_next;
17508
17509                 if (reverse->op_type == OP_REVERSE &&
17510                     (reverse->op_flags & OPf_WANT) == OPf_WANT_LIST) {
17511                     OP * const pushmark = cUNOPx(reverse)->op_first;
17512                     if (pushmark && (pushmark->op_type == OP_PUSHMARK)
17513                         && (OpSIBLING(cUNOPx(pushmark)) == o)) {
17514                         /* reverse -> pushmark -> sort */
17515                         o->op_private |= OPpSORT_REVERSE;
17516                         op_null(reverse);
17517                         pushmark->op_next = oright->op_next;
17518                         op_null(oright);
17519                     }
17520                 }
17521             }
17522
17523             break;
17524         }
17525
17526         case OP_REVERSE: {
17527             OP *ourmark, *theirmark, *ourlast, *iter, *expushmark, *rv2av;
17528             OP *gvop = NULL;
17529             LISTOP *enter, *exlist;
17530
17531             if (o->op_private & OPpSORT_INPLACE)
17532                 break;
17533
17534             enter = (LISTOP *) o->op_next;
17535             if (!enter)
17536                 break;
17537             if (enter->op_type == OP_NULL) {
17538                 enter = (LISTOP *) enter->op_next;
17539                 if (!enter)
17540                     break;
17541             }
17542             /* for $a (...) will have OP_GV then OP_RV2GV here.
17543                for (...) just has an OP_GV.  */
17544             if (enter->op_type == OP_GV) {
17545                 gvop = (OP *) enter;
17546                 enter = (LISTOP *) enter->op_next;
17547                 if (!enter)
17548                     break;
17549                 if (enter->op_type == OP_RV2GV) {
17550                   enter = (LISTOP *) enter->op_next;
17551                   if (!enter)
17552                     break;
17553                 }
17554             }
17555
17556             if (enter->op_type != OP_ENTERITER)
17557                 break;
17558
17559             iter = enter->op_next;
17560             if (!iter || iter->op_type != OP_ITER)
17561                 break;
17562
17563             expushmark = enter->op_first;
17564             if (!expushmark || expushmark->op_type != OP_NULL
17565                 || expushmark->op_targ != OP_PUSHMARK)
17566                 break;
17567
17568             exlist = (LISTOP *) OpSIBLING(expushmark);
17569             if (!exlist || exlist->op_type != OP_NULL
17570                 || exlist->op_targ != OP_LIST)
17571                 break;
17572
17573             if (exlist->op_last != o) {
17574                 /* Mmm. Was expecting to point back to this op.  */
17575                 break;
17576             }
17577             theirmark = exlist->op_first;
17578             if (!theirmark || theirmark->op_type != OP_PUSHMARK)
17579                 break;
17580
17581             if (OpSIBLING(theirmark) != o) {
17582                 /* There's something between the mark and the reverse, eg
17583                    for (1, reverse (...))
17584                    so no go.  */
17585                 break;
17586             }
17587
17588             ourmark = ((LISTOP *)o)->op_first;
17589             if (!ourmark || ourmark->op_type != OP_PUSHMARK)
17590                 break;
17591
17592             ourlast = ((LISTOP *)o)->op_last;
17593             if (!ourlast || ourlast->op_next != o)
17594                 break;
17595
17596             rv2av = OpSIBLING(ourmark);
17597             if (rv2av && rv2av->op_type == OP_RV2AV && !OpHAS_SIBLING(rv2av)
17598                 && rv2av->op_flags == (OPf_WANT_LIST | OPf_KIDS)) {
17599                 /* We're just reversing a single array.  */
17600                 rv2av->op_flags = OPf_WANT_SCALAR | OPf_KIDS | OPf_REF;
17601                 enter->op_flags |= OPf_STACKED;
17602             }
17603
17604             /* We don't have control over who points to theirmark, so sacrifice
17605                ours.  */
17606             theirmark->op_next = ourmark->op_next;
17607             theirmark->op_flags = ourmark->op_flags;
17608             ourlast->op_next = gvop ? gvop : (OP *) enter;
17609             op_null(ourmark);
17610             op_null(o);
17611             enter->op_private |= OPpITER_REVERSED;
17612             iter->op_private |= OPpITER_REVERSED;
17613
17614             oldoldop = NULL;
17615             oldop    = ourlast;
17616             o        = oldop->op_next;
17617             goto redo;
17618             NOT_REACHED; /* NOTREACHED */
17619             break;
17620         }
17621
17622         case OP_QR:
17623         case OP_MATCH:
17624             if (!(cPMOP->op_pmflags & PMf_ONCE)) {
17625                 assert (!cPMOP->op_pmstashstartu.op_pmreplstart);
17626             }
17627             break;
17628
17629         case OP_RUNCV:
17630             if (!(o->op_private & OPpOFFBYONE) && !CvCLONE(PL_compcv)
17631              && (!CvANON(PL_compcv) || (!PL_cv_has_eval && !PL_perldb)))
17632             {
17633                 SV *sv;
17634                 if (CvEVAL(PL_compcv)) sv = &PL_sv_undef;
17635                 else {
17636                     sv = newRV((SV *)PL_compcv);
17637                     sv_rvweaken(sv);
17638                     SvREADONLY_on(sv);
17639                 }
17640                 OpTYPE_set(o, OP_CONST);
17641                 o->op_flags |= OPf_SPECIAL;
17642                 cSVOPo->op_sv = sv;
17643             }
17644             break;
17645
17646         case OP_SASSIGN:
17647             if (OP_GIMME(o,0) == G_VOID
17648              || (  o->op_next->op_type == OP_LINESEQ
17649                 && (  o->op_next->op_next->op_type == OP_LEAVESUB
17650                    || (  o->op_next->op_next->op_type == OP_RETURN
17651                       && !CvLVALUE(PL_compcv)))))
17652             {
17653                 OP *right = cBINOP->op_first;
17654                 if (right) {
17655                     /*   sassign
17656                     *      RIGHT
17657                     *      substr
17658                     *         pushmark
17659                     *         arg1
17660                     *         arg2
17661                     *         ...
17662                     * becomes
17663                     *
17664                     *  ex-sassign
17665                     *     substr
17666                     *        pushmark
17667                     *        RIGHT
17668                     *        arg1
17669                     *        arg2
17670                     *        ...
17671                     */
17672                     OP *left = OpSIBLING(right);
17673                     if (left->op_type == OP_SUBSTR
17674                          && (left->op_private & 7) < 4) {
17675                         op_null(o);
17676                         /* cut out right */
17677                         op_sibling_splice(o, NULL, 1, NULL);
17678                         /* and insert it as second child of OP_SUBSTR */
17679                         op_sibling_splice(left, cBINOPx(left)->op_first, 0,
17680                                     right);
17681                         left->op_private |= OPpSUBSTR_REPL_FIRST;
17682                         left->op_flags =
17683                             (o->op_flags & ~OPf_WANT) | OPf_WANT_VOID;
17684                     }
17685                 }
17686             }
17687             break;
17688
17689         case OP_AASSIGN: {
17690             int l, r, lr, lscalars, rscalars;
17691
17692             /* handle common vars detection, e.g. ($a,$b) = ($b,$a).
17693                Note that we do this now rather than in newASSIGNOP(),
17694                since only by now are aliased lexicals flagged as such
17695
17696                See the essay "Common vars in list assignment" above for
17697                the full details of the rationale behind all the conditions
17698                below.
17699
17700                PL_generation sorcery:
17701                To detect whether there are common vars, the global var
17702                PL_generation is incremented for each assign op we scan.
17703                Then we run through all the lexical variables on the LHS,
17704                of the assignment, setting a spare slot in each of them to
17705                PL_generation.  Then we scan the RHS, and if any lexicals
17706                already have that value, we know we've got commonality.
17707                Also, if the generation number is already set to
17708                PERL_INT_MAX, then the variable is involved in aliasing, so
17709                we also have potential commonality in that case.
17710              */
17711
17712             PL_generation++;
17713             /* scan LHS */
17714             lscalars = 0;
17715             l = S_aassign_scan(aTHX_ cLISTOPo->op_last,  FALSE, &lscalars);
17716             /* scan RHS */
17717             rscalars = 0;
17718             r = S_aassign_scan(aTHX_ cLISTOPo->op_first, TRUE, &rscalars);
17719             lr = (l|r);
17720
17721
17722             /* After looking for things which are *always* safe, this main
17723              * if/else chain selects primarily based on the type of the
17724              * LHS, gradually working its way down from the more dangerous
17725              * to the more restrictive and thus safer cases */
17726
17727             if (   !l                      /* () = ....; */
17728                 || !r                      /* .... = (); */
17729                 || !(l & ~AAS_SAFE_SCALAR) /* (undef, pos()) = ...; */
17730                 || !(r & ~AAS_SAFE_SCALAR) /* ... = (1,2,length,undef); */
17731                 || (lscalars < 2)          /* ($x, undef) = ... */
17732             ) {
17733                 NOOP; /* always safe */
17734             }
17735             else if (l & AAS_DANGEROUS) {
17736                 /* always dangerous */
17737                 o->op_private |= OPpASSIGN_COMMON_SCALAR;
17738                 o->op_private |= OPpASSIGN_COMMON_AGG;
17739             }
17740             else if (l & (AAS_PKG_SCALAR|AAS_PKG_AGG)) {
17741                 /* package vars are always dangerous - too many
17742                  * aliasing possibilities */
17743                 if (l & AAS_PKG_SCALAR)
17744                     o->op_private |= OPpASSIGN_COMMON_SCALAR;
17745                 if (l & AAS_PKG_AGG)
17746                     o->op_private |= OPpASSIGN_COMMON_AGG;
17747             }
17748             else if (l & ( AAS_MY_SCALAR|AAS_MY_AGG
17749                           |AAS_LEX_SCALAR|AAS_LEX_AGG))
17750             {
17751                 /* LHS contains only lexicals and safe ops */
17752
17753                 if (l & (AAS_MY_AGG|AAS_LEX_AGG))
17754                     o->op_private |= OPpASSIGN_COMMON_AGG;
17755
17756                 if (l & (AAS_MY_SCALAR|AAS_LEX_SCALAR)) {
17757                     if (lr & AAS_LEX_SCALAR_COMM)
17758                         o->op_private |= OPpASSIGN_COMMON_SCALAR;
17759                     else if (   !(l & AAS_LEX_SCALAR)
17760                              && (r & AAS_DEFAV))
17761                     {
17762                         /* falsely mark
17763                          *    my (...) = @_
17764                          * as scalar-safe for performance reasons.
17765                          * (it will still have been marked _AGG if necessary */
17766                         NOOP;
17767                     }
17768                     else if (r  & (AAS_PKG_SCALAR|AAS_PKG_AGG|AAS_DANGEROUS))
17769                         /* if there are only lexicals on the LHS and no
17770                          * common ones on the RHS, then we assume that the
17771                          * only way those lexicals could also get
17772                          * on the RHS is via some sort of dereffing or
17773                          * closure, e.g.
17774                          *    $r = \$lex;
17775                          *    ($lex, $x) = (1, $$r)
17776                          * and in this case we assume the var must have
17777                          *  a bumped ref count. So if its ref count is 1,
17778                          *  it must only be on the LHS.
17779                          */
17780                         o->op_private |= OPpASSIGN_COMMON_RC1;
17781                 }
17782             }
17783
17784             /* ... = ($x)
17785              * may have to handle aggregate on LHS, but we can't
17786              * have common scalars. */
17787             if (rscalars < 2)
17788                 o->op_private &=
17789                         ~(OPpASSIGN_COMMON_SCALAR|OPpASSIGN_COMMON_RC1);
17790
17791             if ((o->op_flags & OPf_WANT) == OPf_WANT_SCALAR)
17792                 S_check_for_bool_cxt(o, 1, OPpASSIGN_TRUEBOOL, 0);
17793             break;
17794         }
17795
17796         case OP_REF:
17797             /* see if ref() is used in boolean context */
17798             if ((o->op_flags & OPf_WANT) == OPf_WANT_SCALAR)
17799                 S_check_for_bool_cxt(o, 1, OPpTRUEBOOL, OPpMAYBE_TRUEBOOL);
17800             break;
17801
17802         case OP_LENGTH:
17803             /* see if the op is used in known boolean context,
17804              * but not if OA_TARGLEX optimisation is enabled */
17805             if (   (o->op_flags & OPf_WANT) == OPf_WANT_SCALAR
17806                 && !(o->op_private & OPpTARGET_MY)
17807             )
17808                 S_check_for_bool_cxt(o, 1, OPpTRUEBOOL, 0);
17809             break;
17810
17811         case OP_POS:
17812             /* see if the op is used in known boolean context */
17813             if ((o->op_flags & OPf_WANT) == OPf_WANT_SCALAR)
17814                 S_check_for_bool_cxt(o, 1, OPpTRUEBOOL, 0);
17815             break;
17816
17817         case OP_CUSTOM: {
17818             Perl_cpeep_t cpeep =
17819                 XopENTRYCUSTOM(o, xop_peep);
17820             if (cpeep)
17821                 cpeep(aTHX_ o, oldop);
17822             break;
17823         }
17824
17825         }
17826         /* did we just null the current op? If so, re-process it to handle
17827          * eliding "empty" ops from the chain */
17828         if (o->op_type == OP_NULL && oldop && oldop->op_next == o) {
17829             o->op_opt = 0;
17830             o = oldop;
17831         }
17832         else {
17833             oldoldop = oldop;
17834             oldop = o;
17835         }
17836     }
17837     LEAVE;
17838 }
17839
17840 void
17841 Perl_peep(pTHX_ OP *o)
17842 {
17843     CALL_RPEEP(o);
17844 }
17845
17846 /*
17847 =head1 Custom Operators
17848
17849 =for apidoc Perl_custom_op_xop
17850 Return the XOP structure for a given custom op.  This macro should be
17851 considered internal to C<OP_NAME> and the other access macros: use them instead.
17852 This macro does call a function.  Prior
17853 to 5.19.6, this was implemented as a
17854 function.
17855
17856 =cut
17857 */
17858
17859
17860 /* use PERL_MAGIC_ext to call a function to free the xop structure when
17861  * freeing PL_custom_ops */
17862
17863 static int
17864 custom_op_register_free(pTHX_ SV *sv, MAGIC *mg)
17865 {
17866     XOP *xop;
17867
17868     PERL_UNUSED_ARG(mg);
17869     xop = INT2PTR(XOP *, SvIV(sv));
17870     Safefree(xop->xop_name);
17871     Safefree(xop->xop_desc);
17872     Safefree(xop);
17873     return 0;
17874 }
17875
17876
17877 static const MGVTBL custom_op_register_vtbl = {
17878     0,                          /* get */
17879     0,                          /* set */
17880     0,                          /* len */
17881     0,                          /* clear */
17882     custom_op_register_free,     /* free */
17883     0,                          /* copy */
17884     0,                          /* dup */
17885 #ifdef MGf_LOCAL
17886     0,                          /* local */
17887 #endif
17888 };
17889
17890
17891 XOPRETANY
17892 Perl_custom_op_get_field(pTHX_ const OP *o, const xop_flags_enum field)
17893 {
17894     SV *keysv;
17895     HE *he = NULL;
17896     XOP *xop;
17897
17898     static const XOP xop_null = { 0, 0, 0, 0, 0 };
17899
17900     PERL_ARGS_ASSERT_CUSTOM_OP_GET_FIELD;
17901     assert(o->op_type == OP_CUSTOM);
17902
17903     /* This is wrong. It assumes a function pointer can be cast to IV,
17904      * which isn't guaranteed, but this is what the old custom OP code
17905      * did. In principle it should be safer to Copy the bytes of the
17906      * pointer into a PV: since the new interface is hidden behind
17907      * functions, this can be changed later if necessary.  */
17908     /* Change custom_op_xop if this ever happens */
17909     keysv = sv_2mortal(newSViv(PTR2IV(o->op_ppaddr)));
17910
17911     if (PL_custom_ops)
17912         he = hv_fetch_ent(PL_custom_ops, keysv, 0, 0);
17913
17914     /* See if the op isn't registered, but its name *is* registered.
17915      * That implies someone is using the pre-5.14 API,where only name and
17916      * description could be registered. If so, fake up a real
17917      * registration.
17918      * We only check for an existing name, and assume no one will have
17919      * just registered a desc */
17920     if (!he && PL_custom_op_names &&
17921         (he = hv_fetch_ent(PL_custom_op_names, keysv, 0, 0))
17922     ) {
17923         const char *pv;
17924         STRLEN l;
17925
17926         /* XXX does all this need to be shared mem? */
17927         Newxz(xop, 1, XOP);
17928         pv = SvPV(HeVAL(he), l);
17929         XopENTRY_set(xop, xop_name, savepvn(pv, l));
17930         if (PL_custom_op_descs &&
17931             (he = hv_fetch_ent(PL_custom_op_descs, keysv, 0, 0))
17932         ) {
17933             pv = SvPV(HeVAL(he), l);
17934             XopENTRY_set(xop, xop_desc, savepvn(pv, l));
17935         }
17936         Perl_custom_op_register(aTHX_ o->op_ppaddr, xop);
17937         he = hv_fetch_ent(PL_custom_ops, keysv, 0, 0);
17938         /* add magic to the SV so that the xop struct (pointed to by
17939          * SvIV(sv)) is freed. Normally a static xop is registered, but
17940          * for this backcompat hack, we've alloced one */
17941         (void)sv_magicext(HeVAL(he), NULL, PERL_MAGIC_ext,
17942                 &custom_op_register_vtbl, NULL, 0);
17943
17944     }
17945     else {
17946         if (!he)
17947             xop = (XOP *)&xop_null;
17948         else
17949             xop = INT2PTR(XOP *, SvIV(HeVAL(he)));
17950     }
17951     {
17952         XOPRETANY any;
17953         if(field == XOPe_xop_ptr) {
17954             any.xop_ptr = xop;
17955         } else {
17956             const U32 flags = XopFLAGS(xop);
17957             if(flags & field) {
17958                 switch(field) {
17959                 case XOPe_xop_name:
17960                     any.xop_name = xop->xop_name;
17961                     break;
17962                 case XOPe_xop_desc:
17963                     any.xop_desc = xop->xop_desc;
17964                     break;
17965                 case XOPe_xop_class:
17966                     any.xop_class = xop->xop_class;
17967                     break;
17968                 case XOPe_xop_peep:
17969                     any.xop_peep = xop->xop_peep;
17970                     break;
17971                 default:
17972                     NOT_REACHED; /* NOTREACHED */
17973                     break;
17974                 }
17975             } else {
17976                 switch(field) {
17977                 case XOPe_xop_name:
17978                     any.xop_name = XOPd_xop_name;
17979                     break;
17980                 case XOPe_xop_desc:
17981                     any.xop_desc = XOPd_xop_desc;
17982                     break;
17983                 case XOPe_xop_class:
17984                     any.xop_class = XOPd_xop_class;
17985                     break;
17986                 case XOPe_xop_peep:
17987                     any.xop_peep = XOPd_xop_peep;
17988                     break;
17989                 default:
17990                     NOT_REACHED; /* NOTREACHED */
17991                     break;
17992                 }
17993             }
17994         }
17995         /* On some platforms (HP-UX, IA64) gcc emits a warning for this function:
17996          * op.c: In function 'Perl_custom_op_get_field':
17997          * op.c:...: warning: 'any.xop_name' may be used uninitialized in this function [-Wmaybe-uninitialized]
17998          * This is because on those platforms (with -DEBUGGING) NOT_REACHED
17999          * expands to assert(0), which expands to ((0) ? (void)0 :
18000          * __assert(...)), and gcc doesn't know that __assert can never return. */
18001         return any;
18002     }
18003 }
18004
18005 /*
18006 =for apidoc custom_op_register
18007 Register a custom op.  See L<perlguts/"Custom Operators">.
18008
18009 =cut
18010 */
18011
18012 void
18013 Perl_custom_op_register(pTHX_ Perl_ppaddr_t ppaddr, const XOP *xop)
18014 {
18015     SV *keysv;
18016
18017     PERL_ARGS_ASSERT_CUSTOM_OP_REGISTER;
18018
18019     /* see the comment in custom_op_xop */
18020     keysv = sv_2mortal(newSViv(PTR2IV(ppaddr)));
18021
18022     if (!PL_custom_ops)
18023         PL_custom_ops = newHV();
18024
18025     if (!hv_store_ent(PL_custom_ops, keysv, newSViv(PTR2IV(xop)), 0))
18026         Perl_croak(aTHX_ "panic: can't register custom OP %s", xop->xop_name);
18027 }
18028
18029 /*
18030
18031 =for apidoc core_prototype
18032
18033 This function assigns the prototype of the named core function to C<sv>, or
18034 to a new mortal SV if C<sv> is C<NULL>.  It returns the modified C<sv>, or
18035 C<NULL> if the core function has no prototype.  C<code> is a code as returned
18036 by C<keyword()>.  It must not be equal to 0.
18037
18038 =cut
18039 */
18040
18041 SV *
18042 Perl_core_prototype(pTHX_ SV *sv, const char *name, const int code,
18043                           int * const opnum)
18044 {
18045     int i = 0, n = 0, seen_question = 0, defgv = 0;
18046     I32 oa;
18047 #define MAX_ARGS_OP ((sizeof(I32) - 1) * 2)
18048     char str[ MAX_ARGS_OP * 2 + 2 ]; /* One ';', one '\0' */
18049     bool nullret = FALSE;
18050
18051     PERL_ARGS_ASSERT_CORE_PROTOTYPE;
18052
18053     assert (code);
18054
18055     if (!sv) sv = sv_newmortal();
18056
18057 #define retsetpvs(x,y) sv_setpvs(sv, x); if(opnum) *opnum=(y); return sv
18058
18059     switch (code < 0 ? -code : code) {
18060     case KEY_and   : case KEY_chop: case KEY_chomp:
18061     case KEY_cmp   : case KEY_defined: case KEY_delete: case KEY_exec  :
18062     case KEY_exists: case KEY_eq     : case KEY_ge    : case KEY_goto  :
18063     case KEY_grep  : case KEY_gt     : case KEY_last  : case KEY_le    :
18064     case KEY_lt    : case KEY_map    : case KEY_ne    : case KEY_next  :
18065     case KEY_or    : case KEY_print  : case KEY_printf: case KEY_qr    :
18066     case KEY_redo  : case KEY_require: case KEY_return: case KEY_say   :
18067     case KEY_select: case KEY_sort   : case KEY_split : case KEY_system:
18068     case KEY_x     : case KEY_xor    :
18069         if (!opnum) return NULL; nullret = TRUE; goto findopnum;
18070     case KEY_glob:    retsetpvs("_;", OP_GLOB);
18071     case KEY_keys:    retsetpvs("\\[%@]", OP_KEYS);
18072     case KEY_values:  retsetpvs("\\[%@]", OP_VALUES);
18073     case KEY_each:    retsetpvs("\\[%@]", OP_EACH);
18074     case KEY_pos:     retsetpvs(";\\[$*]", OP_POS);
18075     case KEY___FILE__: case KEY___LINE__: case KEY___PACKAGE__:
18076         retsetpvs("", 0);
18077     case KEY_evalbytes:
18078         name = "entereval"; break;
18079     case KEY_readpipe:
18080         name = "backtick";
18081     }
18082
18083 #undef retsetpvs
18084
18085   findopnum:
18086     while (i < MAXO) {  /* The slow way. */
18087         if (strEQ(name, PL_op_name[i])
18088             || strEQ(name, PL_op_desc[i]))
18089         {
18090             if (nullret) { assert(opnum); *opnum = i; return NULL; }
18091             goto found;
18092         }
18093         i++;
18094     }
18095     return NULL;
18096   found:
18097     defgv = PL_opargs[i] & OA_DEFGV;
18098     oa = PL_opargs[i] >> OASHIFT;
18099     while (oa) {
18100         if (oa & OA_OPTIONAL && !seen_question && (
18101               !defgv || (oa & (OA_OPTIONAL - 1)) == OA_FILEREF
18102         )) {
18103             seen_question = 1;
18104             str[n++] = ';';
18105         }
18106         if ((oa & (OA_OPTIONAL - 1)) >= OA_AVREF
18107             && (oa & (OA_OPTIONAL - 1)) <= OA_SCALARREF
18108             /* But globs are already references (kinda) */
18109             && (oa & (OA_OPTIONAL - 1)) != OA_FILEREF
18110         ) {
18111             str[n++] = '\\';
18112         }
18113         if ((oa & (OA_OPTIONAL - 1)) == OA_SCALARREF
18114          && !scalar_mod_type(NULL, i)) {
18115             str[n++] = '[';
18116             str[n++] = '$';
18117             str[n++] = '@';
18118             str[n++] = '%';
18119             if (i == OP_LOCK || i == OP_UNDEF) str[n++] = '&';
18120             str[n++] = '*';
18121             str[n++] = ']';
18122         }
18123         else str[n++] = ("?$@@%&*$")[oa & (OA_OPTIONAL - 1)];
18124         if (oa & OA_OPTIONAL && defgv && str[n-1] == '$') {
18125             str[n-1] = '_'; defgv = 0;
18126         }
18127         oa = oa >> 4;
18128     }
18129     if (code == -KEY_not || code == -KEY_getprotobynumber) str[n++] = ';';
18130     str[n++] = '\0';
18131     sv_setpvn(sv, str, n - 1);
18132     if (opnum) *opnum = i;
18133     return sv;
18134 }
18135
18136 OP *
18137 Perl_coresub_op(pTHX_ SV * const coreargssv, const int code,
18138                       const int opnum)
18139 {
18140     OP * const argop = (opnum == OP_SELECT && code) ? NULL :
18141                                         newSVOP(OP_COREARGS,0,coreargssv);
18142     OP *o;
18143
18144     PERL_ARGS_ASSERT_CORESUB_OP;
18145
18146     switch(opnum) {
18147     case 0:
18148         return op_append_elem(OP_LINESEQ,
18149                        argop,
18150                        newSLICEOP(0,
18151                                   newSVOP(OP_CONST, 0, newSViv(-code % 3)),
18152                                   newOP(OP_CALLER,0)
18153                        )
18154                );
18155     case OP_EACH:
18156     case OP_KEYS:
18157     case OP_VALUES:
18158         o = newUNOP(OP_AVHVSWITCH,0,argop);
18159         o->op_private = opnum-OP_EACH;
18160         return o;
18161     case OP_SELECT: /* which represents OP_SSELECT as well */
18162         if (code)
18163             return newCONDOP(
18164                          0,
18165                          newBINOP(OP_GT, 0,
18166                                   newAVREF(newGVOP(OP_GV, 0, PL_defgv)),
18167                                   newSVOP(OP_CONST, 0, newSVuv(1))
18168                                  ),
18169                          coresub_op(newSVuv((UV)OP_SSELECT), 0,
18170                                     OP_SSELECT),
18171                          coresub_op(coreargssv, 0, OP_SELECT)
18172                    );
18173         /* FALLTHROUGH */
18174     default:
18175         switch (PL_opargs[opnum] & OA_CLASS_MASK) {
18176         case OA_BASEOP:
18177             return op_append_elem(
18178                         OP_LINESEQ, argop,
18179                         newOP(opnum,
18180                               opnum == OP_WANTARRAY || opnum == OP_RUNCV
18181                                 ? OPpOFFBYONE << 8 : 0)
18182                    );
18183         case OA_BASEOP_OR_UNOP:
18184             if (opnum == OP_ENTEREVAL) {
18185                 o = newUNOP(OP_ENTEREVAL,OPpEVAL_COPHH<<8,argop);
18186                 if (code == -KEY_evalbytes) o->op_private |= OPpEVAL_BYTES;
18187             }
18188             else o = newUNOP(opnum,0,argop);
18189             if (opnum == OP_CALLER) o->op_private |= OPpOFFBYONE;
18190             else {
18191           onearg:
18192               if (is_handle_constructor(o, 1))
18193                 argop->op_private |= OPpCOREARGS_DEREF1;
18194               if (scalar_mod_type(NULL, opnum))
18195                 argop->op_private |= OPpCOREARGS_SCALARMOD;
18196             }
18197             return o;
18198         default:
18199             o = op_convert_list(opnum,OPf_SPECIAL*(opnum == OP_GLOB),argop);
18200             if (is_handle_constructor(o, 2))
18201                 argop->op_private |= OPpCOREARGS_DEREF2;
18202             if (opnum == OP_SUBSTR) {
18203                 o->op_private |= OPpMAYBE_LVSUB;
18204                 return o;
18205             }
18206             else goto onearg;
18207         }
18208     }
18209 }
18210
18211 void
18212 Perl_report_redefined_cv(pTHX_ const SV *name, const CV *old_cv,
18213                                SV * const *new_const_svp)
18214 {
18215     const char *hvname;
18216     bool is_const = !!CvCONST(old_cv);
18217     SV *old_const_sv = is_const ? cv_const_sv(old_cv) : NULL;
18218
18219     PERL_ARGS_ASSERT_REPORT_REDEFINED_CV;
18220
18221     if (is_const && new_const_svp && old_const_sv == *new_const_svp)
18222         return;
18223         /* They are 2 constant subroutines generated from
18224            the same constant. This probably means that
18225            they are really the "same" proxy subroutine
18226            instantiated in 2 places. Most likely this is
18227            when a constant is exported twice.  Don't warn.
18228         */
18229     if (
18230         (ckWARN(WARN_REDEFINE)
18231          && !(
18232                 CvGV(old_cv) && GvSTASH(CvGV(old_cv))
18233              && HvNAMELEN(GvSTASH(CvGV(old_cv))) == 7
18234              && (hvname = HvNAME(GvSTASH(CvGV(old_cv))),
18235                  strEQ(hvname, "autouse"))
18236              )
18237         )
18238      || (is_const
18239          && ckWARN_d(WARN_REDEFINE)
18240          && (!new_const_svp || sv_cmp(old_const_sv, *new_const_svp))
18241         )
18242     )
18243         Perl_warner(aTHX_ packWARN(WARN_REDEFINE),
18244                           is_const
18245                             ? "Constant subroutine %" SVf " redefined"
18246                             : "Subroutine %" SVf " redefined",
18247                           SVfARG(name));
18248 }
18249
18250 /*
18251 =head1 Hook manipulation
18252
18253 These functions provide convenient and thread-safe means of manipulating
18254 hook variables.
18255
18256 =cut
18257 */
18258
18259 /*
18260 =for apidoc wrap_op_checker
18261
18262 Puts a C function into the chain of check functions for a specified op
18263 type.  This is the preferred way to manipulate the L</PL_check> array.
18264 C<opcode> specifies which type of op is to be affected.  C<new_checker>
18265 is a pointer to the C function that is to be added to that opcode's
18266 check chain, and C<old_checker_p> points to the storage location where a
18267 pointer to the next function in the chain will be stored.  The value of
18268 C<new_checker> is written into the L</PL_check> array, while the value
18269 previously stored there is written to C<*old_checker_p>.
18270
18271 L</PL_check> is global to an entire process, and a module wishing to
18272 hook op checking may find itself invoked more than once per process,
18273 typically in different threads.  To handle that situation, this function
18274 is idempotent.  The location C<*old_checker_p> must initially (once
18275 per process) contain a null pointer.  A C variable of static duration
18276 (declared at file scope, typically also marked C<static> to give
18277 it internal linkage) will be implicitly initialised appropriately,
18278 if it does not have an explicit initialiser.  This function will only
18279 actually modify the check chain if it finds C<*old_checker_p> to be null.
18280 This function is also thread safe on the small scale.  It uses appropriate
18281 locking to avoid race conditions in accessing L</PL_check>.
18282
18283 When this function is called, the function referenced by C<new_checker>
18284 must be ready to be called, except for C<*old_checker_p> being unfilled.
18285 In a threading situation, C<new_checker> may be called immediately,
18286 even before this function has returned.  C<*old_checker_p> will always
18287 be appropriately set before C<new_checker> is called.  If C<new_checker>
18288 decides not to do anything special with an op that it is given (which
18289 is the usual case for most uses of op check hooking), it must chain the
18290 check function referenced by C<*old_checker_p>.
18291
18292 Taken all together, XS code to hook an op checker should typically look
18293 something like this:
18294
18295     static Perl_check_t nxck_frob;
18296     static OP *myck_frob(pTHX_ OP *op) {
18297         ...
18298         op = nxck_frob(aTHX_ op);
18299         ...
18300         return op;
18301     }
18302     BOOT:
18303         wrap_op_checker(OP_FROB, myck_frob, &nxck_frob);
18304
18305 If you want to influence compilation of calls to a specific subroutine,
18306 then use L</cv_set_call_checker_flags> rather than hooking checking of
18307 all C<entersub> ops.
18308
18309 =cut
18310 */
18311
18312 void
18313 Perl_wrap_op_checker(pTHX_ Optype opcode,
18314     Perl_check_t new_checker, Perl_check_t *old_checker_p)
18315 {
18316     dVAR;
18317
18318     PERL_UNUSED_CONTEXT;
18319     PERL_ARGS_ASSERT_WRAP_OP_CHECKER;
18320     if (*old_checker_p) return;
18321     OP_CHECK_MUTEX_LOCK;
18322     if (!*old_checker_p) {
18323         *old_checker_p = PL_check[opcode];
18324         PL_check[opcode] = new_checker;
18325     }
18326     OP_CHECK_MUTEX_UNLOCK;
18327 }
18328
18329 #include "XSUB.h"
18330
18331 /* Efficient sub that returns a constant scalar value. */
18332 static void
18333 const_sv_xsub(pTHX_ CV* cv)
18334 {
18335     dXSARGS;
18336     SV *const sv = MUTABLE_SV(XSANY.any_ptr);
18337     PERL_UNUSED_ARG(items);
18338     if (!sv) {
18339         XSRETURN(0);
18340     }
18341     EXTEND(sp, 1);
18342     ST(0) = sv;
18343     XSRETURN(1);
18344 }
18345
18346 static void
18347 const_av_xsub(pTHX_ CV* cv)
18348 {
18349     dXSARGS;
18350     AV * const av = MUTABLE_AV(XSANY.any_ptr);
18351     SP -= items;
18352     assert(av);
18353 #ifndef DEBUGGING
18354     if (!av) {
18355         XSRETURN(0);
18356     }
18357 #endif
18358     if (SvRMAGICAL(av))
18359         Perl_croak(aTHX_ "Magical list constants are not supported");
18360     if (GIMME_V != G_ARRAY) {
18361         EXTEND(SP, 1);
18362         ST(0) = sv_2mortal(newSViv((IV)AvFILLp(av)+1));
18363         XSRETURN(1);
18364     }
18365     EXTEND(SP, AvFILLp(av)+1);
18366     Copy(AvARRAY(av), &ST(0), AvFILLp(av)+1, SV *);
18367     XSRETURN(AvFILLp(av)+1);
18368 }
18369
18370 /* Copy an existing cop->cop_warnings field.
18371  * If it's one of the standard addresses, just re-use the address.
18372  * This is the e implementation for the DUP_WARNINGS() macro
18373  */
18374
18375 STRLEN*
18376 Perl_dup_warnings(pTHX_ STRLEN* warnings)
18377 {
18378     Size_t size;
18379     STRLEN *new_warnings;
18380
18381     if (warnings == NULL || specialWARN(warnings))
18382         return warnings;
18383
18384     size = sizeof(*warnings) + *warnings;
18385
18386     new_warnings = (STRLEN*)PerlMemShared_malloc(size);
18387     Copy(warnings, new_warnings, size, char);
18388     return new_warnings;
18389 }
18390
18391 /*
18392  * ex: set ts=8 sts=4 sw=4 et:
18393  */