This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Accept experimental alpha_assertions feature
[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
168 #define CALL_PEEP(o) PL_peepp(aTHX_ o)
169 #define CALL_RPEEP(o) PL_rpeepp(aTHX_ o)
170 #define CALL_OPFREEHOOK(o) if (PL_opfreehook) PL_opfreehook(aTHX_ o)
171
172 static const char array_passed_to_stat[] = "Array passed to stat will be coerced to a scalar";
173
174 /* remove any leading "empty" ops from the op_next chain whose first
175  * node's address is stored in op_p. Store the updated address of the
176  * first node in op_p.
177  */
178
179 STATIC void
180 S_prune_chain_head(OP** op_p)
181 {
182     while (*op_p
183         && (   (*op_p)->op_type == OP_NULL
184             || (*op_p)->op_type == OP_SCOPE
185             || (*op_p)->op_type == OP_SCALAR
186             || (*op_p)->op_type == OP_LINESEQ)
187     )
188         *op_p = (*op_p)->op_next;
189 }
190
191
192 /* See the explanatory comments above struct opslab in op.h. */
193
194 #ifdef PERL_DEBUG_READONLY_OPS
195 #  define PERL_SLAB_SIZE 128
196 #  define PERL_MAX_SLAB_SIZE 4096
197 #  include <sys/mman.h>
198 #endif
199
200 #ifndef PERL_SLAB_SIZE
201 #  define PERL_SLAB_SIZE 64
202 #endif
203 #ifndef PERL_MAX_SLAB_SIZE
204 #  define PERL_MAX_SLAB_SIZE 2048
205 #endif
206
207 /* rounds up to nearest pointer */
208 #define SIZE_TO_PSIZE(x)        (((x) + sizeof(I32 *) - 1)/sizeof(I32 *))
209 #define DIFF(o,p)               ((size_t)((I32 **)(p) - (I32**)(o)))
210
211 /* requires double parens and aTHX_ */
212 #define DEBUG_S_warn(args)                                             \
213     DEBUG_S(                                                            \
214         PerlIO_printf(Perl_debug_log, "%s", SvPVx_nolen(Perl_mess args)) \
215     )
216
217
218 /* malloc a new op slab (suitable for attaching to PL_compcv).
219  * sz is in units of pointers */
220
221 static OPSLAB *
222 S_new_slab(pTHX_ OPSLAB *head, size_t sz)
223 {
224     OPSLAB *slab;
225
226     /* opslot_offset is only U16 */
227     assert(sz  < U16_MAX);
228
229 #ifdef PERL_DEBUG_READONLY_OPS
230     slab = (OPSLAB *) mmap(0, sz * sizeof(I32 *),
231                                    PROT_READ|PROT_WRITE,
232                                    MAP_ANON|MAP_PRIVATE, -1, 0);
233     DEBUG_m(PerlIO_printf(Perl_debug_log, "mapped %lu at %p\n",
234                           (unsigned long) sz, slab));
235     if (slab == MAP_FAILED) {
236         perror("mmap failed");
237         abort();
238     }
239 #else
240     slab = (OPSLAB *)PerlMemShared_calloc(sz, sizeof(I32 *));
241 #endif
242     slab->opslab_size = (U16)sz;
243
244 #ifndef WIN32
245     /* The context is unused in non-Windows */
246     PERL_UNUSED_CONTEXT;
247 #endif
248     slab->opslab_free_space = sz - DIFF(slab, &slab->opslab_slots);
249     slab->opslab_head = head ? head : slab;
250     DEBUG_S_warn((aTHX_ "allocated new op slab sz 0x%x, %p, head slab %p",
251         (unsigned int)slab->opslab_size, (void*)slab,
252         (void*)(slab->opslab_head)));
253     return slab;
254 }
255
256
257 /* Returns a sz-sized block of memory (suitable for holding an op) from
258  * a free slot in the chain of op slabs attached to PL_compcv.
259  * Allocates a new slab if necessary.
260  * if PL_compcv isn't compiling, malloc() instead.
261  */
262
263 void *
264 Perl_Slab_Alloc(pTHX_ size_t sz)
265 {
266     OPSLAB *head_slab; /* first slab in the chain */
267     OPSLAB *slab2;
268     OPSLOT *slot;
269     OP *o;
270     size_t opsz;
271
272     /* We only allocate ops from the slab during subroutine compilation.
273        We find the slab via PL_compcv, hence that must be non-NULL. It could
274        also be pointing to a subroutine which is now fully set up (CvROOT()
275        pointing to the top of the optree for that sub), or a subroutine
276        which isn't using the slab allocator. If our sanity checks aren't met,
277        don't use a slab, but allocate the OP directly from the heap.  */
278     if (!PL_compcv || CvROOT(PL_compcv)
279      || (CvSTART(PL_compcv) && !CvSLABBED(PL_compcv)))
280     {
281         o = (OP*)PerlMemShared_calloc(1, sz);
282         goto gotit;
283     }
284
285     /* While the subroutine is under construction, the slabs are accessed via
286        CvSTART(), to avoid needing to expand PVCV by one pointer for something
287        unneeded at runtime. Once a subroutine is constructed, the slabs are
288        accessed via CvROOT(). So if CvSTART() is NULL, no slab has been
289        allocated yet.  See the commit message for 8be227ab5eaa23f2 for more
290        details.  */
291     if (!CvSTART(PL_compcv)) {
292         CvSTART(PL_compcv) =
293             (OP *)(head_slab = S_new_slab(aTHX_ NULL, PERL_SLAB_SIZE));
294         CvSLABBED_on(PL_compcv);
295         head_slab->opslab_refcnt = 2; /* one for the CV; one for the new OP */
296     }
297     else ++(head_slab = (OPSLAB *)CvSTART(PL_compcv))->opslab_refcnt;
298
299     opsz = SIZE_TO_PSIZE(sz);
300     sz = opsz + OPSLOT_HEADER_P;
301
302     /* The slabs maintain a free list of OPs. In particular, constant folding
303        will free up OPs, so it makes sense to re-use them where possible. A
304        freed up slot is used in preference to a new allocation.  */
305     if (head_slab->opslab_freed) {
306         OP **too = &head_slab->opslab_freed;
307         o = *too;
308         DEBUG_S_warn((aTHX_ "found free op at %p, slab %p, head slab %p",
309             (void*)o,
310             (I32**)OpSLOT(o) - OpSLOT(o)->opslot_offset,
311             (void*)head_slab));
312
313         while (o && OpSLOT(o)->opslot_size < sz) {
314             DEBUG_S_warn((aTHX_ "Alas! too small"));
315             o = *(too = &o->op_next);
316             if (o) { DEBUG_S_warn((aTHX_ "found another free op at %p", (void*)o)); }
317         }
318         if (o) {
319             DEBUG_S_warn((aTHX_ "realloced  op at %p, slab %p, head slab %p",
320                 (void*)o,
321                 (I32**)OpSLOT(o) - OpSLOT(o)->opslot_offset,
322                 (void*)head_slab));
323             *too = o->op_next;
324             Zero(o, opsz, I32 *);
325             o->op_slabbed = 1;
326             goto gotit;
327         }
328     }
329
330 #define INIT_OPSLOT(s) \
331             slot->opslot_offset = DIFF(slab2, slot) ;   \
332             slot->opslot_size = s;                      \
333             slab2->opslab_free_space -= s;              \
334             o = &slot->opslot_op;                       \
335             o->op_slabbed = 1
336
337     /* The partially-filled slab is next in the chain. */
338     slab2 = head_slab->opslab_next ? head_slab->opslab_next : head_slab;
339     if (slab2->opslab_free_space  < sz) {
340         /* Remaining space is too small. */
341         /* If we can fit a BASEOP, add it to the free chain, so as not
342            to waste it. */
343         if (slab2->opslab_free_space >= SIZE_TO_PSIZE(sizeof(OP)) + OPSLOT_HEADER_P) {
344             slot = &slab2->opslab_slots;
345             INIT_OPSLOT(slab2->opslab_free_space);
346             o->op_type = OP_FREED;
347             o->op_next = head_slab->opslab_freed;
348             head_slab->opslab_freed = o;
349         }
350
351         /* Create a new slab.  Make this one twice as big. */
352         slab2 = S_new_slab(aTHX_ head_slab,
353                             slab2->opslab_size  > PERL_MAX_SLAB_SIZE / 2
354                                 ? PERL_MAX_SLAB_SIZE
355                                 : slab2->opslab_size * 2);
356         slab2->opslab_next = head_slab->opslab_next;
357         head_slab->opslab_next = slab2;
358     }
359     assert(slab2->opslab_size >= sz);
360
361     /* Create a new op slot */
362     slot = (OPSLOT *)
363                 ((I32 **)&slab2->opslab_slots
364                                 + slab2->opslab_free_space - sz);
365     assert(slot >= &slab2->opslab_slots);
366     INIT_OPSLOT(sz);
367     DEBUG_S_warn((aTHX_ "allocating op at %p, slab %p, head slab %p",
368         (void*)o, (void*)slab2, (void*)head_slab));
369
370   gotit:
371     /* moresib == 0, op_sibling == 0 implies a solitary unattached op */
372     assert(!o->op_moresib);
373     assert(!o->op_sibparent);
374
375     return (void *)o;
376 }
377
378 #undef INIT_OPSLOT
379
380 #ifdef PERL_DEBUG_READONLY_OPS
381 void
382 Perl_Slab_to_ro(pTHX_ OPSLAB *slab)
383 {
384     PERL_ARGS_ASSERT_SLAB_TO_RO;
385
386     if (slab->opslab_readonly) return;
387     slab->opslab_readonly = 1;
388     for (; slab; slab = slab->opslab_next) {
389         /*DEBUG_U(PerlIO_printf(Perl_debug_log,"mprotect ->ro %lu at %p\n",
390                               (unsigned long) slab->opslab_size, slab));*/
391         if (mprotect(slab, slab->opslab_size * sizeof(I32 *), PROT_READ))
392             Perl_warn(aTHX_ "mprotect for %p %lu failed with %d", slab,
393                              (unsigned long)slab->opslab_size, errno);
394     }
395 }
396
397 void
398 Perl_Slab_to_rw(pTHX_ OPSLAB *const slab)
399 {
400     OPSLAB *slab2;
401
402     PERL_ARGS_ASSERT_SLAB_TO_RW;
403
404     if (!slab->opslab_readonly) return;
405     slab2 = slab;
406     for (; slab2; slab2 = slab2->opslab_next) {
407         /*DEBUG_U(PerlIO_printf(Perl_debug_log,"mprotect ->rw %lu at %p\n",
408                               (unsigned long) size, slab2));*/
409         if (mprotect((void *)slab2, slab2->opslab_size * sizeof(I32 *),
410                      PROT_READ|PROT_WRITE)) {
411             Perl_warn(aTHX_ "mprotect RW for %p %lu failed with %d", slab,
412                              (unsigned long)slab2->opslab_size, errno);
413         }
414     }
415     slab->opslab_readonly = 0;
416 }
417
418 #else
419 #  define Slab_to_rw(op)    NOOP
420 #endif
421
422 /* This cannot possibly be right, but it was copied from the old slab
423    allocator, to which it was originally added, without explanation, in
424    commit 083fcd5. */
425 #ifdef NETWARE
426 #    define PerlMemShared PerlMem
427 #endif
428
429 /* make freed ops die if they're inadvertently executed */
430 #ifdef DEBUGGING
431 static OP *
432 S_pp_freed(pTHX)
433 {
434     DIE(aTHX_ "panic: freed op 0x%p called\n", PL_op);
435 }
436 #endif
437
438
439 /* Return the block of memory used by an op to the free list of
440  * the OP slab associated with that op.
441  */
442
443 void
444 Perl_Slab_Free(pTHX_ void *op)
445 {
446     OP * const o = (OP *)op;
447     OPSLAB *slab;
448
449     PERL_ARGS_ASSERT_SLAB_FREE;
450
451 #ifdef DEBUGGING
452     o->op_ppaddr = S_pp_freed;
453 #endif
454
455     if (!o->op_slabbed) {
456         if (!o->op_static)
457             PerlMemShared_free(op);
458         return;
459     }
460
461     slab = OpSLAB(o);
462     /* If this op is already freed, our refcount will get screwy. */
463     assert(o->op_type != OP_FREED);
464     o->op_type = OP_FREED;
465     o->op_next = slab->opslab_freed;
466     slab->opslab_freed = o;
467     DEBUG_S_warn((aTHX_ "freeing    op at %p, slab %p, head slab %p",
468         (void*)o,
469         (I32**)OpSLOT(o) - OpSLOT(o)->opslot_offset,
470         (void*)slab));
471     OpslabREFCNT_dec_padok(slab);
472 }
473
474 void
475 Perl_opslab_free_nopad(pTHX_ OPSLAB *slab)
476 {
477     const bool havepad = !!PL_comppad;
478     PERL_ARGS_ASSERT_OPSLAB_FREE_NOPAD;
479     if (havepad) {
480         ENTER;
481         PAD_SAVE_SETNULLPAD();
482     }
483     opslab_free(slab);
484     if (havepad) LEAVE;
485 }
486
487 /* Free a chain of OP slabs. Should only be called after all ops contained
488  * in it have been freed. At this point, its reference count should be 1,
489  * because OpslabREFCNT_dec() skips doing rc-- when it detects that rc == 1,
490  * and just directly calls opslab_free().
491  * (Note that the reference count which PL_compcv held on the slab should
492  * have been removed once compilation of the sub was complete).
493  *
494  *
495  */
496
497 void
498 Perl_opslab_free(pTHX_ OPSLAB *slab)
499 {
500     OPSLAB *slab2;
501     PERL_ARGS_ASSERT_OPSLAB_FREE;
502     PERL_UNUSED_CONTEXT;
503     DEBUG_S_warn((aTHX_ "freeing slab %p", (void*)slab));
504     assert(slab->opslab_refcnt == 1);
505     do {
506         slab2 = slab->opslab_next;
507 #ifdef DEBUGGING
508         slab->opslab_refcnt = ~(size_t)0;
509 #endif
510 #ifdef PERL_DEBUG_READONLY_OPS
511         DEBUG_m(PerlIO_printf(Perl_debug_log, "Deallocate slab at %p\n",
512                                                (void*)slab));
513         if (munmap(slab, slab->opslab_size * sizeof(I32 *))) {
514             perror("munmap failed");
515             abort();
516         }
517 #else
518         PerlMemShared_free(slab);
519 #endif
520         slab = slab2;
521     } while (slab);
522 }
523
524 /* like opslab_free(), but first calls op_free() on any ops in the slab
525  * not marked as OP_FREED
526  */
527
528 void
529 Perl_opslab_force_free(pTHX_ OPSLAB *slab)
530 {
531     OPSLAB *slab2;
532 #ifdef DEBUGGING
533     size_t savestack_count = 0;
534 #endif
535     PERL_ARGS_ASSERT_OPSLAB_FORCE_FREE;
536     slab2 = slab;
537     do {
538         OPSLOT *slot = (OPSLOT*)
539                     ((I32**)&slab2->opslab_slots + slab2->opslab_free_space);
540         OPSLOT *end  = (OPSLOT*)
541                         ((I32**)slab2 + slab2->opslab_size);
542         for (; slot < end;
543                 slot = (OPSLOT*) ((I32**)slot + slot->opslot_size) )
544         {
545             if (slot->opslot_op.op_type != OP_FREED
546              && !(slot->opslot_op.op_savefree
547 #ifdef DEBUGGING
548                   && ++savestack_count
549 #endif
550                  )
551             ) {
552                 assert(slot->opslot_op.op_slabbed);
553                 op_free(&slot->opslot_op);
554                 if (slab->opslab_refcnt == 1) goto free;
555             }
556         }
557     } while ((slab2 = slab2->opslab_next));
558     /* > 1 because the CV still holds a reference count. */
559     if (slab->opslab_refcnt > 1) { /* still referenced by the savestack */
560 #ifdef DEBUGGING
561         assert(savestack_count == slab->opslab_refcnt-1);
562 #endif
563         /* Remove the CV’s reference count. */
564         slab->opslab_refcnt--;
565         return;
566     }
567    free:
568     opslab_free(slab);
569 }
570
571 #ifdef PERL_DEBUG_READONLY_OPS
572 OP *
573 Perl_op_refcnt_inc(pTHX_ OP *o)
574 {
575     if(o) {
576         OPSLAB *const slab = o->op_slabbed ? OpSLAB(o) : NULL;
577         if (slab && slab->opslab_readonly) {
578             Slab_to_rw(slab);
579             ++o->op_targ;
580             Slab_to_ro(slab);
581         } else {
582             ++o->op_targ;
583         }
584     }
585     return o;
586
587 }
588
589 PADOFFSET
590 Perl_op_refcnt_dec(pTHX_ OP *o)
591 {
592     PADOFFSET result;
593     OPSLAB *const slab = o->op_slabbed ? OpSLAB(o) : NULL;
594
595     PERL_ARGS_ASSERT_OP_REFCNT_DEC;
596
597     if (slab && slab->opslab_readonly) {
598         Slab_to_rw(slab);
599         result = --o->op_targ;
600         Slab_to_ro(slab);
601     } else {
602         result = --o->op_targ;
603     }
604     return result;
605 }
606 #endif
607 /*
608  * In the following definition, the ", (OP*)0" is just to make the compiler
609  * think the expression is of the right type: croak actually does a Siglongjmp.
610  */
611 #define CHECKOP(type,o) \
612     ((PL_op_mask && PL_op_mask[type])                           \
613      ? ( op_free((OP*)o),                                       \
614          Perl_croak(aTHX_ "'%s' trapped by operation mask", PL_op_desc[type]),  \
615          (OP*)0 )                                               \
616      : PL_check[type](aTHX_ (OP*)o))
617
618 #define RETURN_UNLIMITED_NUMBER (PERL_INT_MAX / 2)
619
620 #define OpTYPE_set(o,type) \
621     STMT_START {                                \
622         o->op_type = (OPCODE)type;              \
623         o->op_ppaddr = PL_ppaddr[type];         \
624     } STMT_END
625
626 STATIC OP *
627 S_no_fh_allowed(pTHX_ OP *o)
628 {
629     PERL_ARGS_ASSERT_NO_FH_ALLOWED;
630
631     yyerror(Perl_form(aTHX_ "Missing comma after first argument to %s function",
632                  OP_DESC(o)));
633     return o;
634 }
635
636 STATIC OP *
637 S_too_few_arguments_pv(pTHX_ OP *o, const char* name, U32 flags)
638 {
639     PERL_ARGS_ASSERT_TOO_FEW_ARGUMENTS_PV;
640     yyerror_pv(Perl_form(aTHX_ "Not enough arguments for %s", name), flags);
641     return o;
642 }
643  
644 STATIC OP *
645 S_too_many_arguments_pv(pTHX_ OP *o, const char *name, U32 flags)
646 {
647     PERL_ARGS_ASSERT_TOO_MANY_ARGUMENTS_PV;
648
649     yyerror_pv(Perl_form(aTHX_ "Too many arguments for %s", name), flags);
650     return o;
651 }
652
653 STATIC void
654 S_bad_type_pv(pTHX_ I32 n, const char *t, const OP *o, const OP *kid)
655 {
656     PERL_ARGS_ASSERT_BAD_TYPE_PV;
657
658     yyerror_pv(Perl_form(aTHX_ "Type of arg %d to %s must be %s (not %s)",
659                  (int)n, PL_op_desc[(o)->op_type], t, OP_DESC(kid)), 0);
660 }
661
662 /* remove flags var, its unused in all callers, move to to right end since gv
663   and kid are always the same */
664 STATIC void
665 S_bad_type_gv(pTHX_ I32 n, GV *gv, const OP *kid, const char *t)
666 {
667     SV * const namesv = cv_name((CV *)gv, NULL, 0);
668     PERL_ARGS_ASSERT_BAD_TYPE_GV;
669  
670     yyerror_pv(Perl_form(aTHX_ "Type of arg %d to %" SVf " must be %s (not %s)",
671                  (int)n, SVfARG(namesv), t, OP_DESC(kid)), SvUTF8(namesv));
672 }
673
674 STATIC void
675 S_no_bareword_allowed(pTHX_ OP *o)
676 {
677     PERL_ARGS_ASSERT_NO_BAREWORD_ALLOWED;
678
679     qerror(Perl_mess(aTHX_
680                      "Bareword \"%" SVf "\" not allowed while \"strict subs\" in use",
681                      SVfARG(cSVOPo_sv)));
682     o->op_private &= ~OPpCONST_STRICT; /* prevent warning twice about the same OP */
683 }
684
685 /* "register" allocation */
686
687 PADOFFSET
688 Perl_allocmy(pTHX_ const char *const name, const STRLEN len, const U32 flags)
689 {
690     PADOFFSET off;
691     const bool is_our = (PL_parser->in_my == KEY_our);
692
693     PERL_ARGS_ASSERT_ALLOCMY;
694
695     if (flags & ~SVf_UTF8)
696         Perl_croak(aTHX_ "panic: allocmy illegal flag bits 0x%" UVxf,
697                    (UV)flags);
698
699     /* complain about "my $<special_var>" etc etc */
700     if (   len
701         && !(  is_our
702             || isALPHA(name[1])
703             || (   (flags & SVf_UTF8)
704                 && isIDFIRST_utf8_safe((U8 *)name+1, name + len))
705             || (name[1] == '_' && len > 2)))
706     {
707         const char * const type =
708               PL_parser->in_my == KEY_sigvar ? "subroutine signature" :
709               PL_parser->in_my == KEY_state  ? "\"state\""     : "\"my\"";
710
711         if (!(flags & SVf_UTF8 && UTF8_IS_START(name[1]))
712          && isASCII(name[1])
713          && (!isPRINT(name[1]) || strchr("\t\n\r\f", name[1]))) {
714             /* diag_listed_as: Can't use global %s in %s */
715             yyerror(Perl_form(aTHX_ "Can't use global %c^%c%.*s in %s",
716                               name[0], toCTRL(name[1]),
717                               (int)(len - 2), name + 2,
718                               type));
719         } else {
720             yyerror_pv(Perl_form(aTHX_ "Can't use global %.*s in %s",
721                               (int) len, name,
722                               type), flags & SVf_UTF8);
723         }
724     }
725
726     /* allocate a spare slot and store the name in that slot */
727
728     off = pad_add_name_pvn(name, len,
729                        (is_our ? padadd_OUR :
730                         PL_parser->in_my == KEY_state ? padadd_STATE : 0),
731                     PL_parser->in_my_stash,
732                     (is_our
733                         /* $_ is always in main::, even with our */
734                         ? (PL_curstash && !memEQs(name,len,"$_")
735                             ? PL_curstash
736                             : PL_defstash)
737                         : NULL
738                     )
739     );
740     /* anon sub prototypes contains state vars should always be cloned,
741      * otherwise the state var would be shared between anon subs */
742
743     if (PL_parser->in_my == KEY_state && CvANON(PL_compcv))
744         CvCLONE_on(PL_compcv);
745
746     return off;
747 }
748
749 /*
750 =head1 Optree Manipulation Functions
751
752 =for apidoc alloccopstash
753
754 Available only under threaded builds, this function allocates an entry in
755 C<PL_stashpad> for the stash passed to it.
756
757 =cut
758 */
759
760 #ifdef USE_ITHREADS
761 PADOFFSET
762 Perl_alloccopstash(pTHX_ HV *hv)
763 {
764     PADOFFSET off = 0, o = 1;
765     bool found_slot = FALSE;
766
767     PERL_ARGS_ASSERT_ALLOCCOPSTASH;
768
769     if (PL_stashpad[PL_stashpadix] == hv) return PL_stashpadix;
770
771     for (; o < PL_stashpadmax; ++o) {
772         if (PL_stashpad[o] == hv) return PL_stashpadix = o;
773         if (!PL_stashpad[o] || SvTYPE(PL_stashpad[o]) != SVt_PVHV)
774             found_slot = TRUE, off = o;
775     }
776     if (!found_slot) {
777         Renew(PL_stashpad, PL_stashpadmax + 10, HV *);
778         Zero(PL_stashpad + PL_stashpadmax, 10, HV *);
779         off = PL_stashpadmax;
780         PL_stashpadmax += 10;
781     }
782
783     PL_stashpad[PL_stashpadix = off] = hv;
784     return off;
785 }
786 #endif
787
788 /* free the body of an op without examining its contents.
789  * Always use this rather than FreeOp directly */
790
791 static void
792 S_op_destroy(pTHX_ OP *o)
793 {
794     FreeOp(o);
795 }
796
797 /* Destructor */
798
799 /*
800 =for apidoc op_free
801
802 Free an op and its children. Only use this when an op is no longer linked
803 to from any optree.
804
805 =cut
806 */
807
808 void
809 Perl_op_free(pTHX_ OP *o)
810 {
811     dVAR;
812     OPCODE type;
813     OP *top_op = o;
814     OP *next_op = o;
815     bool went_up = FALSE; /* whether we reached the current node by
816                             following the parent pointer from a child, and
817                             so have already seen this node */
818
819     if (!o || o->op_type == OP_FREED)
820         return;
821
822     if (o->op_private & OPpREFCOUNTED) {
823         /* if base of tree is refcounted, just decrement */
824         switch (o->op_type) {
825         case OP_LEAVESUB:
826         case OP_LEAVESUBLV:
827         case OP_LEAVEEVAL:
828         case OP_LEAVE:
829         case OP_SCOPE:
830         case OP_LEAVEWRITE:
831             {
832                 PADOFFSET refcnt;
833                 OP_REFCNT_LOCK;
834                 refcnt = OpREFCNT_dec(o);
835                 OP_REFCNT_UNLOCK;
836                 if (refcnt) {
837                     /* Need to find and remove any pattern match ops from
838                      * the list we maintain for reset().  */
839                     find_and_forget_pmops(o);
840                     return;
841                 }
842             }
843             break;
844         default:
845             break;
846         }
847     }
848
849     while (next_op) {
850         o = next_op;
851
852         /* free child ops before ourself, (then free ourself "on the
853          * way back up") */
854
855         if (!went_up && o->op_flags & OPf_KIDS) {
856             next_op = cUNOPo->op_first;
857             continue;
858         }
859
860         /* find the next node to visit, *then* free the current node
861          * (can't rely on o->op_* fields being valid after o has been
862          * freed) */
863
864         /* The next node to visit will be either the sibling, or the
865          * parent if no siblings left, or NULL if we've worked our way
866          * back up to the top node in the tree */
867         next_op = (o == top_op) ? NULL : o->op_sibparent;
868         went_up = cBOOL(!OpHAS_SIBLING(o)); /* parents are already visited */
869
870         /* Now process the current node */
871
872         /* Though ops may be freed twice, freeing the op after its slab is a
873            big no-no. */
874         assert(!o->op_slabbed || OpSLAB(o)->opslab_refcnt != ~(size_t)0);
875         /* During the forced freeing of ops after compilation failure, kidops
876            may be freed before their parents. */
877         if (!o || o->op_type == OP_FREED)
878             continue;
879
880         type = o->op_type;
881
882         /* an op should only ever acquire op_private flags that we know about.
883          * If this fails, you may need to fix something in regen/op_private.
884          * Don't bother testing if:
885          *   * the op_ppaddr doesn't match the op; someone may have
886          *     overridden the op and be doing strange things with it;
887          *   * we've errored, as op flags are often left in an
888          *     inconsistent state then. Note that an error when
889          *     compiling the main program leaves PL_parser NULL, so
890          *     we can't spot faults in the main code, only
891          *     evaled/required code */
892 #ifdef DEBUGGING
893         if (   o->op_ppaddr == PL_ppaddr[type]
894             && PL_parser
895             && !PL_parser->error_count)
896         {
897             assert(!(o->op_private & ~PL_op_private_valid[type]));
898         }
899 #endif
900
901
902         /* Call the op_free hook if it has been set. Do it now so that it's called
903          * at the right time for refcounted ops, but still before all of the kids
904          * are freed. */
905         CALL_OPFREEHOOK(o);
906
907         if (type == OP_NULL)
908             type = (OPCODE)o->op_targ;
909
910         if (o->op_slabbed)
911             Slab_to_rw(OpSLAB(o));
912
913         /* COP* is not cleared by op_clear() so that we may track line
914          * numbers etc even after null() */
915         if (type == OP_NEXTSTATE || type == OP_DBSTATE) {
916             cop_free((COP*)o);
917         }
918
919         op_clear(o);
920         FreeOp(o);
921         if (PL_op == o)
922             PL_op = NULL;
923     }
924 }
925
926
927 /* S_op_clear_gv(): free a GV attached to an OP */
928
929 STATIC
930 #ifdef USE_ITHREADS
931 void S_op_clear_gv(pTHX_ OP *o, PADOFFSET *ixp)
932 #else
933 void S_op_clear_gv(pTHX_ OP *o, SV**svp)
934 #endif
935 {
936
937     GV *gv = (o->op_type == OP_GV || o->op_type == OP_GVSV
938             || o->op_type == OP_MULTIDEREF)
939 #ifdef USE_ITHREADS
940                 && PL_curpad
941                 ? ((GV*)PAD_SVl(*ixp)) : NULL;
942 #else
943                 ? (GV*)(*svp) : NULL;
944 #endif
945     /* It's possible during global destruction that the GV is freed
946        before the optree. Whilst the SvREFCNT_inc is happy to bump from
947        0 to 1 on a freed SV, the corresponding SvREFCNT_dec from 1 to 0
948        will trigger an assertion failure, because the entry to sv_clear
949        checks that the scalar is not already freed.  A check of for
950        !SvIS_FREED(gv) turns out to be invalid, because during global
951        destruction the reference count can be forced down to zero
952        (with SVf_BREAK set).  In which case raising to 1 and then
953        dropping to 0 triggers cleanup before it should happen.  I
954        *think* that this might actually be a general, systematic,
955        weakness of the whole idea of SVf_BREAK, in that code *is*
956        allowed to raise and lower references during global destruction,
957        so any *valid* code that happens to do this during global
958        destruction might well trigger premature cleanup.  */
959     bool still_valid = gv && SvREFCNT(gv);
960
961     if (still_valid)
962         SvREFCNT_inc_simple_void(gv);
963 #ifdef USE_ITHREADS
964     if (*ixp > 0) {
965         pad_swipe(*ixp, TRUE);
966         *ixp = 0;
967     }
968 #else
969     SvREFCNT_dec(*svp);
970     *svp = NULL;
971 #endif
972     if (still_valid) {
973         int try_downgrade = SvREFCNT(gv) == 2;
974         SvREFCNT_dec_NN(gv);
975         if (try_downgrade)
976             gv_try_downgrade(gv);
977     }
978 }
979
980
981 void
982 Perl_op_clear(pTHX_ OP *o)
983 {
984
985     dVAR;
986
987     PERL_ARGS_ASSERT_OP_CLEAR;
988
989     switch (o->op_type) {
990     case OP_NULL:       /* Was holding old type, if any. */
991         /* FALLTHROUGH */
992     case OP_ENTERTRY:
993     case OP_ENTEREVAL:  /* Was holding hints. */
994     case OP_ARGDEFELEM: /* Was holding signature index. */
995         o->op_targ = 0;
996         break;
997     default:
998         if (!(o->op_flags & OPf_REF) || !OP_IS_STAT(o->op_type))
999             break;
1000         /* FALLTHROUGH */
1001     case OP_GVSV:
1002     case OP_GV:
1003     case OP_AELEMFAST:
1004 #ifdef USE_ITHREADS
1005             S_op_clear_gv(aTHX_ o, &(cPADOPx(o)->op_padix));
1006 #else
1007             S_op_clear_gv(aTHX_ o, &(cSVOPx(o)->op_sv));
1008 #endif
1009         break;
1010     case OP_METHOD_REDIR:
1011     case OP_METHOD_REDIR_SUPER:
1012 #ifdef USE_ITHREADS
1013         if (cMETHOPx(o)->op_rclass_targ) {
1014             pad_swipe(cMETHOPx(o)->op_rclass_targ, 1);
1015             cMETHOPx(o)->op_rclass_targ = 0;
1016         }
1017 #else
1018         SvREFCNT_dec(cMETHOPx(o)->op_rclass_sv);
1019         cMETHOPx(o)->op_rclass_sv = NULL;
1020 #endif
1021         /* FALLTHROUGH */
1022     case OP_METHOD_NAMED:
1023     case OP_METHOD_SUPER:
1024         SvREFCNT_dec(cMETHOPx(o)->op_u.op_meth_sv);
1025         cMETHOPx(o)->op_u.op_meth_sv = NULL;
1026 #ifdef USE_ITHREADS
1027         if (o->op_targ) {
1028             pad_swipe(o->op_targ, 1);
1029             o->op_targ = 0;
1030         }
1031 #endif
1032         break;
1033     case OP_CONST:
1034     case OP_HINTSEVAL:
1035         SvREFCNT_dec(cSVOPo->op_sv);
1036         cSVOPo->op_sv = NULL;
1037 #ifdef USE_ITHREADS
1038         /** Bug #15654
1039           Even if op_clear does a pad_free for the target of the op,
1040           pad_free doesn't actually remove the sv that exists in the pad;
1041           instead it lives on. This results in that it could be reused as 
1042           a target later on when the pad was reallocated.
1043         **/
1044         if(o->op_targ) {
1045           pad_swipe(o->op_targ,1);
1046           o->op_targ = 0;
1047         }
1048 #endif
1049         break;
1050     case OP_DUMP:
1051     case OP_GOTO:
1052     case OP_NEXT:
1053     case OP_LAST:
1054     case OP_REDO:
1055         if (o->op_flags & (OPf_SPECIAL|OPf_STACKED|OPf_KIDS))
1056             break;
1057         /* FALLTHROUGH */
1058     case OP_TRANS:
1059     case OP_TRANSR:
1060         if (   (o->op_type == OP_TRANS || o->op_type == OP_TRANSR)
1061             && (o->op_private & (OPpTRANS_FROM_UTF|OPpTRANS_TO_UTF)))
1062         {
1063 #ifdef USE_ITHREADS
1064             if (cPADOPo->op_padix > 0) {
1065                 pad_swipe(cPADOPo->op_padix, TRUE);
1066                 cPADOPo->op_padix = 0;
1067             }
1068 #else
1069             SvREFCNT_dec(cSVOPo->op_sv);
1070             cSVOPo->op_sv = NULL;
1071 #endif
1072         }
1073         else {
1074             PerlMemShared_free(cPVOPo->op_pv);
1075             cPVOPo->op_pv = NULL;
1076         }
1077         break;
1078     case OP_SUBST:
1079         op_free(cPMOPo->op_pmreplrootu.op_pmreplroot);
1080         goto clear_pmop;
1081
1082     case OP_SPLIT:
1083         if (     (o->op_private & OPpSPLIT_ASSIGN) /* @array  = split */
1084             && !(o->op_flags & OPf_STACKED))       /* @{expr} = split */
1085         {
1086             if (o->op_private & OPpSPLIT_LEX)
1087                 pad_free(cPMOPo->op_pmreplrootu.op_pmtargetoff);
1088             else
1089 #ifdef USE_ITHREADS
1090                 pad_swipe(cPMOPo->op_pmreplrootu.op_pmtargetoff, TRUE);
1091 #else
1092                 SvREFCNT_dec(MUTABLE_SV(cPMOPo->op_pmreplrootu.op_pmtargetgv));
1093 #endif
1094         }
1095         /* FALLTHROUGH */
1096     case OP_MATCH:
1097     case OP_QR:
1098     clear_pmop:
1099         if (!(cPMOPo->op_pmflags & PMf_CODELIST_PRIVATE))
1100             op_free(cPMOPo->op_code_list);
1101         cPMOPo->op_code_list = NULL;
1102         forget_pmop(cPMOPo);
1103         cPMOPo->op_pmreplrootu.op_pmreplroot = NULL;
1104         /* we use the same protection as the "SAFE" version of the PM_ macros
1105          * here since sv_clean_all might release some PMOPs
1106          * after PL_regex_padav has been cleared
1107          * and the clearing of PL_regex_padav needs to
1108          * happen before sv_clean_all
1109          */
1110 #ifdef USE_ITHREADS
1111         if(PL_regex_pad) {        /* We could be in destruction */
1112             const IV offset = (cPMOPo)->op_pmoffset;
1113             ReREFCNT_dec(PM_GETRE(cPMOPo));
1114             PL_regex_pad[offset] = &PL_sv_undef;
1115             sv_catpvn_nomg(PL_regex_pad[0], (const char *)&offset,
1116                            sizeof(offset));
1117         }
1118 #else
1119         ReREFCNT_dec(PM_GETRE(cPMOPo));
1120         PM_SETRE(cPMOPo, NULL);
1121 #endif
1122
1123         break;
1124
1125     case OP_ARGCHECK:
1126         PerlMemShared_free(cUNOP_AUXo->op_aux);
1127         break;
1128
1129     case OP_MULTICONCAT:
1130         {
1131             UNOP_AUX_item *aux = cUNOP_AUXo->op_aux;
1132             /* aux[PERL_MULTICONCAT_IX_PLAIN_PV] and/or
1133              * aux[PERL_MULTICONCAT_IX_UTF8_PV] point to plain and/or
1134              * utf8 shared strings */
1135             char *p1 = aux[PERL_MULTICONCAT_IX_PLAIN_PV].pv;
1136             char *p2 = aux[PERL_MULTICONCAT_IX_UTF8_PV].pv;
1137             if (p1)
1138                 PerlMemShared_free(p1);
1139             if (p2 && p1 != p2)
1140                 PerlMemShared_free(p2);
1141             PerlMemShared_free(aux);
1142         }
1143         break;
1144
1145     case OP_MULTIDEREF:
1146         {
1147             UNOP_AUX_item *items = cUNOP_AUXo->op_aux;
1148             UV actions = items->uv;
1149             bool last = 0;
1150             bool is_hash = FALSE;
1151
1152             while (!last) {
1153                 switch (actions & MDEREF_ACTION_MASK) {
1154
1155                 case MDEREF_reload:
1156                     actions = (++items)->uv;
1157                     continue;
1158
1159                 case MDEREF_HV_padhv_helem:
1160                     is_hash = TRUE;
1161                     /* FALLTHROUGH */
1162                 case MDEREF_AV_padav_aelem:
1163                     pad_free((++items)->pad_offset);
1164                     goto do_elem;
1165
1166                 case MDEREF_HV_gvhv_helem:
1167                     is_hash = TRUE;
1168                     /* FALLTHROUGH */
1169                 case MDEREF_AV_gvav_aelem:
1170 #ifdef USE_ITHREADS
1171                     S_op_clear_gv(aTHX_ o, &((++items)->pad_offset));
1172 #else
1173                     S_op_clear_gv(aTHX_ o, &((++items)->sv));
1174 #endif
1175                     goto do_elem;
1176
1177                 case MDEREF_HV_gvsv_vivify_rv2hv_helem:
1178                     is_hash = TRUE;
1179                     /* FALLTHROUGH */
1180                 case MDEREF_AV_gvsv_vivify_rv2av_aelem:
1181 #ifdef USE_ITHREADS
1182                     S_op_clear_gv(aTHX_ o, &((++items)->pad_offset));
1183 #else
1184                     S_op_clear_gv(aTHX_ o, &((++items)->sv));
1185 #endif
1186                     goto do_vivify_rv2xv_elem;
1187
1188                 case MDEREF_HV_padsv_vivify_rv2hv_helem:
1189                     is_hash = TRUE;
1190                     /* FALLTHROUGH */
1191                 case MDEREF_AV_padsv_vivify_rv2av_aelem:
1192                     pad_free((++items)->pad_offset);
1193                     goto do_vivify_rv2xv_elem;
1194
1195                 case MDEREF_HV_pop_rv2hv_helem:
1196                 case MDEREF_HV_vivify_rv2hv_helem:
1197                     is_hash = TRUE;
1198                     /* FALLTHROUGH */
1199                 do_vivify_rv2xv_elem:
1200                 case MDEREF_AV_pop_rv2av_aelem:
1201                 case MDEREF_AV_vivify_rv2av_aelem:
1202                 do_elem:
1203                     switch (actions & MDEREF_INDEX_MASK) {
1204                     case MDEREF_INDEX_none:
1205                         last = 1;
1206                         break;
1207                     case MDEREF_INDEX_const:
1208                         if (is_hash) {
1209 #ifdef USE_ITHREADS
1210                             /* see RT #15654 */
1211                             pad_swipe((++items)->pad_offset, 1);
1212 #else
1213                             SvREFCNT_dec((++items)->sv);
1214 #endif
1215                         }
1216                         else
1217                             items++;
1218                         break;
1219                     case MDEREF_INDEX_padsv:
1220                         pad_free((++items)->pad_offset);
1221                         break;
1222                     case MDEREF_INDEX_gvsv:
1223 #ifdef USE_ITHREADS
1224                         S_op_clear_gv(aTHX_ o, &((++items)->pad_offset));
1225 #else
1226                         S_op_clear_gv(aTHX_ o, &((++items)->sv));
1227 #endif
1228                         break;
1229                     }
1230
1231                     if (actions & MDEREF_FLAG_last)
1232                         last = 1;
1233                     is_hash = FALSE;
1234
1235                     break;
1236
1237                 default:
1238                     assert(0);
1239                     last = 1;
1240                     break;
1241
1242                 } /* switch */
1243
1244                 actions >>= MDEREF_SHIFT;
1245             } /* while */
1246
1247             /* start of malloc is at op_aux[-1], where the length is
1248              * stored */
1249             PerlMemShared_free(cUNOP_AUXo->op_aux - 1);
1250         }
1251         break;
1252     }
1253
1254     if (o->op_targ > 0) {
1255         pad_free(o->op_targ);
1256         o->op_targ = 0;
1257     }
1258 }
1259
1260 STATIC void
1261 S_cop_free(pTHX_ COP* cop)
1262 {
1263     PERL_ARGS_ASSERT_COP_FREE;
1264
1265     CopFILE_free(cop);
1266     if (! specialWARN(cop->cop_warnings))
1267         PerlMemShared_free(cop->cop_warnings);
1268     cophh_free(CopHINTHASH_get(cop));
1269     if (PL_curcop == cop)
1270        PL_curcop = NULL;
1271 }
1272
1273 STATIC void
1274 S_forget_pmop(pTHX_ PMOP *const o)
1275 {
1276     HV * const pmstash = PmopSTASH(o);
1277
1278     PERL_ARGS_ASSERT_FORGET_PMOP;
1279
1280     if (pmstash && !SvIS_FREED(pmstash) && SvMAGICAL(pmstash)) {
1281         MAGIC * const mg = mg_find((const SV *)pmstash, PERL_MAGIC_symtab);
1282         if (mg) {
1283             PMOP **const array = (PMOP**) mg->mg_ptr;
1284             U32 count = mg->mg_len / sizeof(PMOP**);
1285             U32 i = count;
1286
1287             while (i--) {
1288                 if (array[i] == o) {
1289                     /* Found it. Move the entry at the end to overwrite it.  */
1290                     array[i] = array[--count];
1291                     mg->mg_len = count * sizeof(PMOP**);
1292                     /* Could realloc smaller at this point always, but probably
1293                        not worth it. Probably worth free()ing if we're the
1294                        last.  */
1295                     if(!count) {
1296                         Safefree(mg->mg_ptr);
1297                         mg->mg_ptr = NULL;
1298                     }
1299                     break;
1300                 }
1301             }
1302         }
1303     }
1304     if (PL_curpm == o) 
1305         PL_curpm = NULL;
1306 }
1307
1308
1309 STATIC void
1310 S_find_and_forget_pmops(pTHX_ OP *o)
1311 {
1312     OP* top_op = o;
1313
1314     PERL_ARGS_ASSERT_FIND_AND_FORGET_PMOPS;
1315
1316     while (1) {
1317         switch (o->op_type) {
1318         case OP_SUBST:
1319         case OP_SPLIT:
1320         case OP_MATCH:
1321         case OP_QR:
1322             forget_pmop((PMOP*)o);
1323         }
1324
1325         if (o->op_flags & OPf_KIDS) {
1326             o = cUNOPo->op_first;
1327             continue;
1328         }
1329
1330         while (1) {
1331             if (o == top_op)
1332                 return; /* at top; no parents/siblings to try */
1333             if (OpHAS_SIBLING(o)) {
1334                 o = o->op_sibparent; /* process next sibling */
1335                 break;
1336             }
1337             o = o->op_sibparent; /*try parent's next sibling */
1338         }
1339     }
1340 }
1341
1342
1343 /*
1344 =for apidoc op_null
1345
1346 Neutralizes an op when it is no longer needed, but is still linked to from
1347 other ops.
1348
1349 =cut
1350 */
1351
1352 void
1353 Perl_op_null(pTHX_ OP *o)
1354 {
1355     dVAR;
1356
1357     PERL_ARGS_ASSERT_OP_NULL;
1358
1359     if (o->op_type == OP_NULL)
1360         return;
1361     op_clear(o);
1362     o->op_targ = o->op_type;
1363     OpTYPE_set(o, OP_NULL);
1364 }
1365
1366 void
1367 Perl_op_refcnt_lock(pTHX)
1368   PERL_TSA_ACQUIRE(PL_op_mutex)
1369 {
1370 #ifdef USE_ITHREADS
1371     dVAR;
1372 #endif
1373     PERL_UNUSED_CONTEXT;
1374     OP_REFCNT_LOCK;
1375 }
1376
1377 void
1378 Perl_op_refcnt_unlock(pTHX)
1379   PERL_TSA_RELEASE(PL_op_mutex)
1380 {
1381 #ifdef USE_ITHREADS
1382     dVAR;
1383 #endif
1384     PERL_UNUSED_CONTEXT;
1385     OP_REFCNT_UNLOCK;
1386 }
1387
1388
1389 /*
1390 =for apidoc op_sibling_splice
1391
1392 A general function for editing the structure of an existing chain of
1393 op_sibling nodes.  By analogy with the perl-level C<splice()> function, allows
1394 you to delete zero or more sequential nodes, replacing them with zero or
1395 more different nodes.  Performs the necessary op_first/op_last
1396 housekeeping on the parent node and op_sibling manipulation on the
1397 children.  The last deleted node will be marked as as the last node by
1398 updating the op_sibling/op_sibparent or op_moresib field as appropriate.
1399
1400 Note that op_next is not manipulated, and nodes are not freed; that is the
1401 responsibility of the caller.  It also won't create a new list op for an
1402 empty list etc; use higher-level functions like op_append_elem() for that.
1403
1404 C<parent> is the parent node of the sibling chain. It may passed as C<NULL> if
1405 the splicing doesn't affect the first or last op in the chain.
1406
1407 C<start> is the node preceding the first node to be spliced.  Node(s)
1408 following it will be deleted, and ops will be inserted after it.  If it is
1409 C<NULL>, the first node onwards is deleted, and nodes are inserted at the
1410 beginning.
1411
1412 C<del_count> is the number of nodes to delete.  If zero, no nodes are deleted.
1413 If -1 or greater than or equal to the number of remaining kids, all
1414 remaining kids are deleted.
1415
1416 C<insert> is the first of a chain of nodes to be inserted in place of the nodes.
1417 If C<NULL>, no nodes are inserted.
1418
1419 The head of the chain of deleted ops is returned, or C<NULL> if no ops were
1420 deleted.
1421
1422 For example:
1423
1424     action                    before      after         returns
1425     ------                    -----       -----         -------
1426
1427                               P           P
1428     splice(P, A, 2, X-Y-Z)    |           |             B-C
1429                               A-B-C-D     A-X-Y-Z-D
1430
1431                               P           P
1432     splice(P, NULL, 1, X-Y)   |           |             A
1433                               A-B-C-D     X-Y-B-C-D
1434
1435                               P           P
1436     splice(P, NULL, 3, NULL)  |           |             A-B-C
1437                               A-B-C-D     D
1438
1439                               P           P
1440     splice(P, B, 0, X-Y)      |           |             NULL
1441                               A-B-C-D     A-B-X-Y-C-D
1442
1443
1444 For lower-level direct manipulation of C<op_sibparent> and C<op_moresib>,
1445 see C<L</OpMORESIB_set>>, C<L</OpLASTSIB_set>>, C<L</OpMAYBESIB_set>>.
1446
1447 =cut
1448 */
1449
1450 OP *
1451 Perl_op_sibling_splice(OP *parent, OP *start, int del_count, OP* insert)
1452 {
1453     OP *first;
1454     OP *rest;
1455     OP *last_del = NULL;
1456     OP *last_ins = NULL;
1457
1458     if (start)
1459         first = OpSIBLING(start);
1460     else if (!parent)
1461         goto no_parent;
1462     else
1463         first = cLISTOPx(parent)->op_first;
1464
1465     assert(del_count >= -1);
1466
1467     if (del_count && first) {
1468         last_del = first;
1469         while (--del_count && OpHAS_SIBLING(last_del))
1470             last_del = OpSIBLING(last_del);
1471         rest = OpSIBLING(last_del);
1472         OpLASTSIB_set(last_del, NULL);
1473     }
1474     else
1475         rest = first;
1476
1477     if (insert) {
1478         last_ins = insert;
1479         while (OpHAS_SIBLING(last_ins))
1480             last_ins = OpSIBLING(last_ins);
1481         OpMAYBESIB_set(last_ins, rest, NULL);
1482     }
1483     else
1484         insert = rest;
1485
1486     if (start) {
1487         OpMAYBESIB_set(start, insert, NULL);
1488     }
1489     else {
1490         assert(parent);
1491         cLISTOPx(parent)->op_first = insert;
1492         if (insert)
1493             parent->op_flags |= OPf_KIDS;
1494         else
1495             parent->op_flags &= ~OPf_KIDS;
1496     }
1497
1498     if (!rest) {
1499         /* update op_last etc */
1500         U32 type;
1501         OP *lastop;
1502
1503         if (!parent)
1504             goto no_parent;
1505
1506         /* ought to use OP_CLASS(parent) here, but that can't handle
1507          * ex-foo OP_NULL ops. Also note that XopENTRYCUSTOM() can't
1508          * either */
1509         type = parent->op_type;
1510         if (type == OP_CUSTOM) {
1511             dTHX;
1512             type = XopENTRYCUSTOM(parent, xop_class);
1513         }
1514         else {
1515             if (type == OP_NULL)
1516                 type = parent->op_targ;
1517             type = PL_opargs[type] & OA_CLASS_MASK;
1518         }
1519
1520         lastop = last_ins ? last_ins : start ? start : NULL;
1521         if (   type == OA_BINOP
1522             || type == OA_LISTOP
1523             || type == OA_PMOP
1524             || type == OA_LOOP
1525         )
1526             cLISTOPx(parent)->op_last = lastop;
1527
1528         if (lastop)
1529             OpLASTSIB_set(lastop, parent);
1530     }
1531     return last_del ? first : NULL;
1532
1533   no_parent:
1534     Perl_croak_nocontext("panic: op_sibling_splice(): NULL parent");
1535 }
1536
1537 /*
1538 =for apidoc op_parent
1539
1540 Returns the parent OP of C<o>, if it has a parent. Returns C<NULL> otherwise.
1541
1542 =cut
1543 */
1544
1545 OP *
1546 Perl_op_parent(OP *o)
1547 {
1548     PERL_ARGS_ASSERT_OP_PARENT;
1549     while (OpHAS_SIBLING(o))
1550         o = OpSIBLING(o);
1551     return o->op_sibparent;
1552 }
1553
1554 /* replace the sibling following start with a new UNOP, which becomes
1555  * the parent of the original sibling; e.g.
1556  *
1557  *  op_sibling_newUNOP(P, A, unop-args...)
1558  *
1559  *  P              P
1560  *  |      becomes |
1561  *  A-B-C          A-U-C
1562  *                   |
1563  *                   B
1564  *
1565  * where U is the new UNOP.
1566  *
1567  * parent and start args are the same as for op_sibling_splice();
1568  * type and flags args are as newUNOP().
1569  *
1570  * Returns the new UNOP.
1571  */
1572
1573 STATIC OP *
1574 S_op_sibling_newUNOP(pTHX_ OP *parent, OP *start, I32 type, I32 flags)
1575 {
1576     OP *kid, *newop;
1577
1578     kid = op_sibling_splice(parent, start, 1, NULL);
1579     newop = newUNOP(type, flags, kid);
1580     op_sibling_splice(parent, start, 0, newop);
1581     return newop;
1582 }
1583
1584
1585 /* lowest-level newLOGOP-style function - just allocates and populates
1586  * the struct. Higher-level stuff should be done by S_new_logop() /
1587  * newLOGOP(). This function exists mainly to avoid op_first assignment
1588  * being spread throughout this file.
1589  */
1590
1591 LOGOP *
1592 Perl_alloc_LOGOP(pTHX_ I32 type, OP *first, OP* other)
1593 {
1594     dVAR;
1595     LOGOP *logop;
1596     OP *kid = first;
1597     NewOp(1101, logop, 1, LOGOP);
1598     OpTYPE_set(logop, type);
1599     logop->op_first = first;
1600     logop->op_other = other;
1601     if (first)
1602         logop->op_flags = OPf_KIDS;
1603     while (kid && OpHAS_SIBLING(kid))
1604         kid = OpSIBLING(kid);
1605     if (kid)
1606         OpLASTSIB_set(kid, (OP*)logop);
1607     return logop;
1608 }
1609
1610
1611 /* Contextualizers */
1612
1613 /*
1614 =for apidoc op_contextualize
1615
1616 Applies a syntactic context to an op tree representing an expression.
1617 C<o> is the op tree, and C<context> must be C<G_SCALAR>, C<G_ARRAY>,
1618 or C<G_VOID> to specify the context to apply.  The modified op tree
1619 is returned.
1620
1621 =cut
1622 */
1623
1624 OP *
1625 Perl_op_contextualize(pTHX_ OP *o, I32 context)
1626 {
1627     PERL_ARGS_ASSERT_OP_CONTEXTUALIZE;
1628     switch (context) {
1629         case G_SCALAR: return scalar(o);
1630         case G_ARRAY:  return list(o);
1631         case G_VOID:   return scalarvoid(o);
1632         default:
1633             Perl_croak(aTHX_ "panic: op_contextualize bad context %ld",
1634                        (long) context);
1635     }
1636 }
1637
1638 /*
1639
1640 =for apidoc op_linklist
1641 This function is the implementation of the L</LINKLIST> macro.  It should
1642 not be called directly.
1643
1644 =cut
1645 */
1646
1647
1648 OP *
1649 Perl_op_linklist(pTHX_ OP *o)
1650 {
1651
1652     OP **prevp;
1653     OP *kid;
1654     OP * top_op = o;
1655
1656     PERL_ARGS_ASSERT_OP_LINKLIST;
1657
1658     while (1) {
1659         /* Descend down the tree looking for any unprocessed subtrees to
1660          * do first */
1661         if (!o->op_next) {
1662             if (o->op_flags & OPf_KIDS) {
1663                 o = cUNOPo->op_first;
1664                 continue;
1665             }
1666             o->op_next = o; /* leaf node; link to self initially */
1667         }
1668
1669         /* if we're at the top level, there either weren't any children
1670          * to process, or we've worked our way back to the top. */
1671         if (o == top_op)
1672             return o->op_next;
1673
1674         /* o is now processed. Next, process any sibling subtrees */
1675
1676         if (OpHAS_SIBLING(o)) {
1677             o = OpSIBLING(o);
1678             continue;
1679         }
1680
1681         /* Done all the subtrees at this level. Go back up a level and
1682          * link the parent in with all its (processed) children.
1683          */
1684
1685         o = o->op_sibparent;
1686         assert(!o->op_next);
1687         prevp = &(o->op_next);
1688         kid   = (o->op_flags & OPf_KIDS) ? cUNOPo->op_first : NULL;
1689         while (kid) {
1690             *prevp = kid->op_next;
1691             prevp = &(kid->op_next);
1692             kid = OpSIBLING(kid);
1693         }
1694         *prevp = o;
1695     }
1696 }
1697
1698
1699 static OP *
1700 S_scalarkids(pTHX_ OP *o)
1701 {
1702     if (o && o->op_flags & OPf_KIDS) {
1703         OP *kid;
1704         for (kid = cLISTOPo->op_first; kid; kid = OpSIBLING(kid))
1705             scalar(kid);
1706     }
1707     return o;
1708 }
1709
1710 STATIC OP *
1711 S_scalarboolean(pTHX_ OP *o)
1712 {
1713     PERL_ARGS_ASSERT_SCALARBOOLEAN;
1714
1715     if ((o->op_type == OP_SASSIGN && cBINOPo->op_first->op_type == OP_CONST &&
1716          !(cBINOPo->op_first->op_flags & OPf_SPECIAL)) ||
1717         (o->op_type == OP_NOT     && cUNOPo->op_first->op_type == OP_SASSIGN &&
1718          cBINOPx(cUNOPo->op_first)->op_first->op_type == OP_CONST &&
1719          !(cBINOPx(cUNOPo->op_first)->op_first->op_flags & OPf_SPECIAL))) {
1720         if (ckWARN(WARN_SYNTAX)) {
1721             const line_t oldline = CopLINE(PL_curcop);
1722
1723             if (PL_parser && PL_parser->copline != NOLINE) {
1724                 /* This ensures that warnings are reported at the first line
1725                    of the conditional, not the last.  */
1726                 CopLINE_set(PL_curcop, PL_parser->copline);
1727             }
1728             Perl_warner(aTHX_ packWARN(WARN_SYNTAX), "Found = in conditional, should be ==");
1729             CopLINE_set(PL_curcop, oldline);
1730         }
1731     }
1732     return scalar(o);
1733 }
1734
1735 static SV *
1736 S_op_varname_subscript(pTHX_ const OP *o, int subscript_type)
1737 {
1738     assert(o);
1739     assert(o->op_type == OP_PADAV || o->op_type == OP_RV2AV ||
1740            o->op_type == OP_PADHV || o->op_type == OP_RV2HV);
1741     {
1742         const char funny  = o->op_type == OP_PADAV
1743                          || o->op_type == OP_RV2AV ? '@' : '%';
1744         if (o->op_type == OP_RV2AV || o->op_type == OP_RV2HV) {
1745             GV *gv;
1746             if (cUNOPo->op_first->op_type != OP_GV
1747              || !(gv = cGVOPx_gv(cUNOPo->op_first)))
1748                 return NULL;
1749             return varname(gv, funny, 0, NULL, 0, subscript_type);
1750         }
1751         return
1752             varname(MUTABLE_GV(PL_compcv), funny, o->op_targ, NULL, 0, subscript_type);
1753     }
1754 }
1755
1756 static SV *
1757 S_op_varname(pTHX_ const OP *o)
1758 {
1759     return S_op_varname_subscript(aTHX_ o, 1);
1760 }
1761
1762 static void
1763 S_op_pretty(pTHX_ const OP *o, SV **retsv, const char **retpv)
1764 { /* or not so pretty :-) */
1765     if (o->op_type == OP_CONST) {
1766         *retsv = cSVOPo_sv;
1767         if (SvPOK(*retsv)) {
1768             SV *sv = *retsv;
1769             *retsv = sv_newmortal();
1770             pv_pretty(*retsv, SvPVX_const(sv), SvCUR(sv), 32, NULL, NULL,
1771                       PERL_PV_PRETTY_DUMP |PERL_PV_ESCAPE_UNI_DETECT);
1772         }
1773         else if (!SvOK(*retsv))
1774             *retpv = "undef";
1775     }
1776     else *retpv = "...";
1777 }
1778
1779 static void
1780 S_scalar_slice_warning(pTHX_ const OP *o)
1781 {
1782     OP *kid;
1783     const bool h = o->op_type == OP_HSLICE
1784                 || (o->op_type == OP_NULL && o->op_targ == OP_HSLICE);
1785     const char lbrack =
1786         h ? '{' : '[';
1787     const char rbrack =
1788         h ? '}' : ']';
1789     SV *name;
1790     SV *keysv = NULL; /* just to silence compiler warnings */
1791     const char *key = NULL;
1792
1793     if (!(o->op_private & OPpSLICEWARNING))
1794         return;
1795     if (PL_parser && PL_parser->error_count)
1796         /* This warning can be nonsensical when there is a syntax error. */
1797         return;
1798
1799     kid = cLISTOPo->op_first;
1800     kid = OpSIBLING(kid); /* get past pushmark */
1801     /* weed out false positives: any ops that can return lists */
1802     switch (kid->op_type) {
1803     case OP_BACKTICK:
1804     case OP_GLOB:
1805     case OP_READLINE:
1806     case OP_MATCH:
1807     case OP_RV2AV:
1808     case OP_EACH:
1809     case OP_VALUES:
1810     case OP_KEYS:
1811     case OP_SPLIT:
1812     case OP_LIST:
1813     case OP_SORT:
1814     case OP_REVERSE:
1815     case OP_ENTERSUB:
1816     case OP_CALLER:
1817     case OP_LSTAT:
1818     case OP_STAT:
1819     case OP_READDIR:
1820     case OP_SYSTEM:
1821     case OP_TMS:
1822     case OP_LOCALTIME:
1823     case OP_GMTIME:
1824     case OP_ENTEREVAL:
1825         return;
1826     }
1827
1828     /* Don't warn if we have a nulled list either. */
1829     if (kid->op_type == OP_NULL && kid->op_targ == OP_LIST)
1830         return;
1831
1832     assert(OpSIBLING(kid));
1833     name = S_op_varname(aTHX_ OpSIBLING(kid));
1834     if (!name) /* XS module fiddling with the op tree */
1835         return;
1836     S_op_pretty(aTHX_ kid, &keysv, &key);
1837     assert(SvPOK(name));
1838     sv_chop(name,SvPVX(name)+1);
1839     if (key)
1840        /* diag_listed_as: Scalar value @%s[%s] better written as $%s[%s] */
1841         Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
1842                    "Scalar value @%" SVf "%c%s%c better written as $%" SVf
1843                    "%c%s%c",
1844                     SVfARG(name), lbrack, key, rbrack, SVfARG(name),
1845                     lbrack, key, rbrack);
1846     else
1847        /* diag_listed_as: Scalar value @%s[%s] better written as $%s[%s] */
1848         Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
1849                    "Scalar value @%" SVf "%c%" SVf "%c better written as $%"
1850                     SVf "%c%" SVf "%c",
1851                     SVfARG(name), lbrack, SVfARG(keysv), rbrack,
1852                     SVfARG(name), lbrack, SVfARG(keysv), rbrack);
1853 }
1854
1855
1856
1857 /* apply scalar context to the o subtree */
1858
1859 OP *
1860 Perl_scalar(pTHX_ OP *o)
1861 {
1862     OP * top_op = o;
1863
1864     while (1) {
1865         OP *next_kid = NULL; /* what op (if any) to process next */
1866         OP *kid;
1867
1868         /* assumes no premature commitment */
1869         if (!o || (PL_parser && PL_parser->error_count)
1870              || (o->op_flags & OPf_WANT)
1871              || o->op_type == OP_RETURN)
1872         {
1873             goto do_next;
1874         }
1875
1876         o->op_flags = (o->op_flags & ~OPf_WANT) | OPf_WANT_SCALAR;
1877
1878         switch (o->op_type) {
1879         case OP_REPEAT:
1880             scalar(cBINOPo->op_first);
1881             /* convert what initially looked like a list repeat into a
1882              * scalar repeat, e.g. $s = (1) x $n
1883              */
1884             if (o->op_private & OPpREPEAT_DOLIST) {
1885                 kid = cLISTOPx(cUNOPo->op_first)->op_first;
1886                 assert(kid->op_type == OP_PUSHMARK);
1887                 if (OpHAS_SIBLING(kid) && !OpHAS_SIBLING(OpSIBLING(kid))) {
1888                     op_null(cLISTOPx(cUNOPo->op_first)->op_first);
1889                     o->op_private &=~ OPpREPEAT_DOLIST;
1890                 }
1891             }
1892             break;
1893
1894         case OP_OR:
1895         case OP_AND:
1896         case OP_COND_EXPR:
1897             /* impose scalar context on everything except the condition */
1898             next_kid = OpSIBLING(cUNOPo->op_first);
1899             break;
1900
1901         default:
1902             if (o->op_flags & OPf_KIDS)
1903                 next_kid = cUNOPo->op_first; /* do all kids */
1904             break;
1905
1906         /* the children of these ops are usually a list of statements,
1907          * except the leaves, whose first child is a corresponding enter
1908          */
1909         case OP_SCOPE:
1910         case OP_LINESEQ:
1911         case OP_LIST:
1912             kid = cLISTOPo->op_first;
1913             goto do_kids;
1914         case OP_LEAVE:
1915         case OP_LEAVETRY:
1916             kid = cLISTOPo->op_first;
1917             scalar(kid);
1918             kid = OpSIBLING(kid);
1919         do_kids:
1920             while (kid) {
1921                 OP *sib = OpSIBLING(kid);
1922                 /* Apply void context to all kids except the last, which
1923                  * is scalar (ignoring a trailing ex-nextstate in determining
1924                  * if it's the last kid). E.g.
1925                  *      $scalar = do { void; void; scalar }
1926                  * Except that 'when's are always scalar, e.g.
1927                  *      $scalar = do { given(..) {
1928                     *                 when (..) { scalar }
1929                     *                 when (..) { scalar }
1930                     *                 ...
1931                     *                }}
1932                     */
1933                 if (!sib
1934                      || (  !OpHAS_SIBLING(sib)
1935                          && sib->op_type == OP_NULL
1936                          && (   sib->op_targ == OP_NEXTSTATE
1937                              || sib->op_targ == OP_DBSTATE  )
1938                         )
1939                 )
1940                 {
1941                     /* tail call optimise calling scalar() on the last kid */
1942                     next_kid = kid;
1943                     goto do_next;
1944                 }
1945                 else if (kid->op_type == OP_LEAVEWHEN)
1946                     scalar(kid);
1947                 else
1948                     scalarvoid(kid);
1949                 kid = sib;
1950             }
1951             NOT_REACHED; /* NOTREACHED */
1952             break;
1953
1954         case OP_SORT:
1955             Perl_ck_warner(aTHX_ packWARN(WARN_VOID), "Useless use of sort in scalar context");
1956             break;
1957
1958         case OP_KVHSLICE:
1959         case OP_KVASLICE:
1960         {
1961             /* Warn about scalar context */
1962             const char lbrack = o->op_type == OP_KVHSLICE ? '{' : '[';
1963             const char rbrack = o->op_type == OP_KVHSLICE ? '}' : ']';
1964             SV *name;
1965             SV *keysv;
1966             const char *key = NULL;
1967
1968             /* This warning can be nonsensical when there is a syntax error. */
1969             if (PL_parser && PL_parser->error_count)
1970                 break;
1971
1972             if (!ckWARN(WARN_SYNTAX)) break;
1973
1974             kid = cLISTOPo->op_first;
1975             kid = OpSIBLING(kid); /* get past pushmark */
1976             assert(OpSIBLING(kid));
1977             name = S_op_varname(aTHX_ OpSIBLING(kid));
1978             if (!name) /* XS module fiddling with the op tree */
1979                 break;
1980             S_op_pretty(aTHX_ kid, &keysv, &key);
1981             assert(SvPOK(name));
1982             sv_chop(name,SvPVX(name)+1);
1983             if (key)
1984       /* diag_listed_as: %%s[%s] in scalar context better written as $%s[%s] */
1985                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
1986                            "%%%" SVf "%c%s%c in scalar context better written "
1987                            "as $%" SVf "%c%s%c",
1988                             SVfARG(name), lbrack, key, rbrack, SVfARG(name),
1989                             lbrack, key, rbrack);
1990             else
1991       /* diag_listed_as: %%s[%s] in scalar context better written as $%s[%s] */
1992                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
1993                            "%%%" SVf "%c%" SVf "%c in scalar context better "
1994                            "written as $%" SVf "%c%" SVf "%c",
1995                             SVfARG(name), lbrack, SVfARG(keysv), rbrack,
1996                             SVfARG(name), lbrack, SVfARG(keysv), rbrack);
1997         }
1998         } /* switch */
1999
2000         /* If next_kid is set, someone in the code above wanted us to process
2001          * that kid and all its remaining siblings.  Otherwise, work our way
2002          * back up the tree */
2003       do_next:
2004         while (!next_kid) {
2005             if (o == top_op)
2006                 return top_op; /* at top; no parents/siblings to try */
2007             if (OpHAS_SIBLING(o))
2008                 next_kid = o->op_sibparent;
2009             else {
2010                 o = o->op_sibparent; /*try parent's next sibling */
2011                 switch (o->op_type) {
2012                 case OP_SCOPE:
2013                 case OP_LINESEQ:
2014                 case OP_LIST:
2015                 case OP_LEAVE:
2016                 case OP_LEAVETRY:
2017                     /* should really restore PL_curcop to its old value, but
2018                      * setting it to PL_compiling is better than do nothing */
2019                     PL_curcop = &PL_compiling;
2020                 }
2021             }
2022         }
2023         o = next_kid;
2024     } /* while */
2025 }
2026
2027
2028 /* apply void context to the optree arg */
2029
2030 OP *
2031 Perl_scalarvoid(pTHX_ OP *arg)
2032 {
2033     dVAR;
2034     OP *kid;
2035     SV* sv;
2036     OP *o = arg;
2037
2038     PERL_ARGS_ASSERT_SCALARVOID;
2039
2040     while (1) {
2041         U8 want;
2042         SV *useless_sv = NULL;
2043         const char* useless = NULL;
2044         OP * next_kid = NULL;
2045
2046         if (o->op_type == OP_NEXTSTATE
2047             || o->op_type == OP_DBSTATE
2048             || (o->op_type == OP_NULL && (o->op_targ == OP_NEXTSTATE
2049                                           || o->op_targ == OP_DBSTATE)))
2050             PL_curcop = (COP*)o;                /* for warning below */
2051
2052         /* assumes no premature commitment */
2053         want = o->op_flags & OPf_WANT;
2054         if ((want && want != OPf_WANT_SCALAR)
2055             || (PL_parser && PL_parser->error_count)
2056             || o->op_type == OP_RETURN || o->op_type == OP_REQUIRE || o->op_type == OP_LEAVEWHEN)
2057         {
2058             goto get_next_op;
2059         }
2060
2061         if ((o->op_private & OPpTARGET_MY)
2062             && (PL_opargs[o->op_type] & OA_TARGLEX))/* OPp share the meaning */
2063         {
2064             /* newASSIGNOP has already applied scalar context, which we
2065                leave, as if this op is inside SASSIGN.  */
2066             goto get_next_op;
2067         }
2068
2069         o->op_flags = (o->op_flags & ~OPf_WANT) | OPf_WANT_VOID;
2070
2071         switch (o->op_type) {
2072         default:
2073             if (!(PL_opargs[o->op_type] & OA_FOLDCONST))
2074                 break;
2075             /* FALLTHROUGH */
2076         case OP_REPEAT:
2077             if (o->op_flags & OPf_STACKED)
2078                 break;
2079             if (o->op_type == OP_REPEAT)
2080                 scalar(cBINOPo->op_first);
2081             goto func_ops;
2082         case OP_CONCAT:
2083             if ((o->op_flags & OPf_STACKED) &&
2084                     !(o->op_private & OPpCONCAT_NESTED))
2085                 break;
2086             goto func_ops;
2087         case OP_SUBSTR:
2088             if (o->op_private == 4)
2089                 break;
2090             /* FALLTHROUGH */
2091         case OP_WANTARRAY:
2092         case OP_GV:
2093         case OP_SMARTMATCH:
2094         case OP_AV2ARYLEN:
2095         case OP_REF:
2096         case OP_REFGEN:
2097         case OP_SREFGEN:
2098         case OP_DEFINED:
2099         case OP_HEX:
2100         case OP_OCT:
2101         case OP_LENGTH:
2102         case OP_VEC:
2103         case OP_INDEX:
2104         case OP_RINDEX:
2105         case OP_SPRINTF:
2106         case OP_KVASLICE:
2107         case OP_KVHSLICE:
2108         case OP_UNPACK:
2109         case OP_PACK:
2110         case OP_JOIN:
2111         case OP_LSLICE:
2112         case OP_ANONLIST:
2113         case OP_ANONHASH:
2114         case OP_SORT:
2115         case OP_REVERSE:
2116         case OP_RANGE:
2117         case OP_FLIP:
2118         case OP_FLOP:
2119         case OP_CALLER:
2120         case OP_FILENO:
2121         case OP_EOF:
2122         case OP_TELL:
2123         case OP_GETSOCKNAME:
2124         case OP_GETPEERNAME:
2125         case OP_READLINK:
2126         case OP_TELLDIR:
2127         case OP_GETPPID:
2128         case OP_GETPGRP:
2129         case OP_GETPRIORITY:
2130         case OP_TIME:
2131         case OP_TMS:
2132         case OP_LOCALTIME:
2133         case OP_GMTIME:
2134         case OP_GHBYNAME:
2135         case OP_GHBYADDR:
2136         case OP_GHOSTENT:
2137         case OP_GNBYNAME:
2138         case OP_GNBYADDR:
2139         case OP_GNETENT:
2140         case OP_GPBYNAME:
2141         case OP_GPBYNUMBER:
2142         case OP_GPROTOENT:
2143         case OP_GSBYNAME:
2144         case OP_GSBYPORT:
2145         case OP_GSERVENT:
2146         case OP_GPWNAM:
2147         case OP_GPWUID:
2148         case OP_GGRNAM:
2149         case OP_GGRGID:
2150         case OP_GETLOGIN:
2151         case OP_PROTOTYPE:
2152         case OP_RUNCV:
2153         func_ops:
2154             useless = OP_DESC(o);
2155             break;
2156
2157         case OP_GVSV:
2158         case OP_PADSV:
2159         case OP_PADAV:
2160         case OP_PADHV:
2161         case OP_PADANY:
2162         case OP_AELEM:
2163         case OP_AELEMFAST:
2164         case OP_AELEMFAST_LEX:
2165         case OP_ASLICE:
2166         case OP_HELEM:
2167         case OP_HSLICE:
2168             if (!(o->op_private & (OPpLVAL_INTRO|OPpOUR_INTRO)))
2169                 /* Otherwise it's "Useless use of grep iterator" */
2170                 useless = OP_DESC(o);
2171             break;
2172
2173         case OP_SPLIT:
2174             if (!(o->op_private & OPpSPLIT_ASSIGN))
2175                 useless = OP_DESC(o);
2176             break;
2177
2178         case OP_NOT:
2179             kid = cUNOPo->op_first;
2180             if (kid->op_type != OP_MATCH && kid->op_type != OP_SUBST &&
2181                 kid->op_type != OP_TRANS && kid->op_type != OP_TRANSR) {
2182                 goto func_ops;
2183             }
2184             useless = "negative pattern binding (!~)";
2185             break;
2186
2187         case OP_SUBST:
2188             if (cPMOPo->op_pmflags & PMf_NONDESTRUCT)
2189                 useless = "non-destructive substitution (s///r)";
2190             break;
2191
2192         case OP_TRANSR:
2193             useless = "non-destructive transliteration (tr///r)";
2194             break;
2195
2196         case OP_RV2GV:
2197         case OP_RV2SV:
2198         case OP_RV2AV:
2199         case OP_RV2HV:
2200             if (!(o->op_private & (OPpLVAL_INTRO|OPpOUR_INTRO)) &&
2201                 (!OpHAS_SIBLING(o) || OpSIBLING(o)->op_type != OP_READLINE))
2202                 useless = "a variable";
2203             break;
2204
2205         case OP_CONST:
2206             sv = cSVOPo_sv;
2207             if (cSVOPo->op_private & OPpCONST_STRICT)
2208                 no_bareword_allowed(o);
2209             else {
2210                 if (ckWARN(WARN_VOID)) {
2211                     NV nv;
2212                     /* don't warn on optimised away booleans, eg
2213                      * use constant Foo, 5; Foo || print; */
2214                     if (cSVOPo->op_private & OPpCONST_SHORTCIRCUIT)
2215                         useless = NULL;
2216                     /* the constants 0 and 1 are permitted as they are
2217                        conventionally used as dummies in constructs like
2218                        1 while some_condition_with_side_effects;  */
2219                     else if (SvNIOK(sv) && ((nv = SvNV(sv)) == 0.0 || nv == 1.0))
2220                         useless = NULL;
2221                     else if (SvPOK(sv)) {
2222                         SV * const dsv = newSVpvs("");
2223                         useless_sv
2224                             = Perl_newSVpvf(aTHX_
2225                                             "a constant (%s)",
2226                                             pv_pretty(dsv, SvPVX_const(sv),
2227                                                       SvCUR(sv), 32, NULL, NULL,
2228                                                       PERL_PV_PRETTY_DUMP
2229                                                       | PERL_PV_ESCAPE_NOCLEAR
2230                                                       | PERL_PV_ESCAPE_UNI_DETECT));
2231                         SvREFCNT_dec_NN(dsv);
2232                     }
2233                     else if (SvOK(sv)) {
2234                         useless_sv = Perl_newSVpvf(aTHX_ "a constant (%" SVf ")", SVfARG(sv));
2235                     }
2236                     else
2237                         useless = "a constant (undef)";
2238                 }
2239             }
2240             op_null(o);         /* don't execute or even remember it */
2241             break;
2242
2243         case OP_POSTINC:
2244             OpTYPE_set(o, OP_PREINC);  /* pre-increment is faster */
2245             break;
2246
2247         case OP_POSTDEC:
2248             OpTYPE_set(o, OP_PREDEC);  /* pre-decrement is faster */
2249             break;
2250
2251         case OP_I_POSTINC:
2252             OpTYPE_set(o, OP_I_PREINC);        /* pre-increment is faster */
2253             break;
2254
2255         case OP_I_POSTDEC:
2256             OpTYPE_set(o, OP_I_PREDEC);        /* pre-decrement is faster */
2257             break;
2258
2259         case OP_SASSIGN: {
2260             OP *rv2gv;
2261             UNOP *refgen, *rv2cv;
2262             LISTOP *exlist;
2263
2264             if ((o->op_private & ~OPpASSIGN_BACKWARDS) != 2)
2265                 break;
2266
2267             rv2gv = ((BINOP *)o)->op_last;
2268             if (!rv2gv || rv2gv->op_type != OP_RV2GV)
2269                 break;
2270
2271             refgen = (UNOP *)((BINOP *)o)->op_first;
2272
2273             if (!refgen || (refgen->op_type != OP_REFGEN
2274                             && refgen->op_type != OP_SREFGEN))
2275                 break;
2276
2277             exlist = (LISTOP *)refgen->op_first;
2278             if (!exlist || exlist->op_type != OP_NULL
2279                 || exlist->op_targ != OP_LIST)
2280                 break;
2281
2282             if (exlist->op_first->op_type != OP_PUSHMARK
2283                 && exlist->op_first != exlist->op_last)
2284                 break;
2285
2286             rv2cv = (UNOP*)exlist->op_last;
2287
2288             if (rv2cv->op_type != OP_RV2CV)
2289                 break;
2290
2291             assert ((rv2gv->op_private & OPpDONT_INIT_GV) == 0);
2292             assert ((o->op_private & OPpASSIGN_CV_TO_GV) == 0);
2293             assert ((rv2cv->op_private & OPpMAY_RETURN_CONSTANT) == 0);
2294
2295             o->op_private |= OPpASSIGN_CV_TO_GV;
2296             rv2gv->op_private |= OPpDONT_INIT_GV;
2297             rv2cv->op_private |= OPpMAY_RETURN_CONSTANT;
2298
2299             break;
2300         }
2301
2302         case OP_AASSIGN: {
2303             inplace_aassign(o);
2304             break;
2305         }
2306
2307         case OP_OR:
2308         case OP_AND:
2309             kid = cLOGOPo->op_first;
2310             if (kid->op_type == OP_NOT
2311                 && (kid->op_flags & OPf_KIDS)) {
2312                 if (o->op_type == OP_AND) {
2313                     OpTYPE_set(o, OP_OR);
2314                 } else {
2315                     OpTYPE_set(o, OP_AND);
2316                 }
2317                 op_null(kid);
2318             }
2319             /* FALLTHROUGH */
2320
2321         case OP_DOR:
2322         case OP_COND_EXPR:
2323         case OP_ENTERGIVEN:
2324         case OP_ENTERWHEN:
2325             next_kid = OpSIBLING(cUNOPo->op_first);
2326         break;
2327
2328         case OP_NULL:
2329             if (o->op_flags & OPf_STACKED)
2330                 break;
2331             /* FALLTHROUGH */
2332         case OP_NEXTSTATE:
2333         case OP_DBSTATE:
2334         case OP_ENTERTRY:
2335         case OP_ENTER:
2336             if (!(o->op_flags & OPf_KIDS))
2337                 break;
2338             /* FALLTHROUGH */
2339         case OP_SCOPE:
2340         case OP_LEAVE:
2341         case OP_LEAVETRY:
2342         case OP_LEAVELOOP:
2343         case OP_LINESEQ:
2344         case OP_LEAVEGIVEN:
2345         case OP_LEAVEWHEN:
2346         kids:
2347             next_kid = cLISTOPo->op_first;
2348             break;
2349         case OP_LIST:
2350             /* If the first kid after pushmark is something that the padrange
2351                optimisation would reject, then null the list and the pushmark.
2352             */
2353             if ((kid = cLISTOPo->op_first)->op_type == OP_PUSHMARK
2354                 && (  !(kid = OpSIBLING(kid))
2355                       || (  kid->op_type != OP_PADSV
2356                             && kid->op_type != OP_PADAV
2357                             && kid->op_type != OP_PADHV)
2358                       || kid->op_private & ~OPpLVAL_INTRO
2359                       || !(kid = OpSIBLING(kid))
2360                       || (  kid->op_type != OP_PADSV
2361                             && kid->op_type != OP_PADAV
2362                             && kid->op_type != OP_PADHV)
2363                       || kid->op_private & ~OPpLVAL_INTRO)
2364             ) {
2365                 op_null(cUNOPo->op_first); /* NULL the pushmark */
2366                 op_null(o); /* NULL the list */
2367             }
2368             goto kids;
2369         case OP_ENTEREVAL:
2370             scalarkids(o);
2371             break;
2372         case OP_SCALAR:
2373             scalar(o);
2374             break;
2375         }
2376
2377         if (useless_sv) {
2378             /* mortalise it, in case warnings are fatal.  */
2379             Perl_ck_warner(aTHX_ packWARN(WARN_VOID),
2380                            "Useless use of %" SVf " in void context",
2381                            SVfARG(sv_2mortal(useless_sv)));
2382         }
2383         else if (useless) {
2384             Perl_ck_warner(aTHX_ packWARN(WARN_VOID),
2385                            "Useless use of %s in void context",
2386                            useless);
2387         }
2388
2389       get_next_op:
2390         /* if a kid hasn't been nominated to process, continue with the
2391          * next sibling, or if no siblings left, go back to the parent's
2392          * siblings and so on
2393          */
2394         while (!next_kid) {
2395             if (o == arg)
2396                 return arg; /* at top; no parents/siblings to try */
2397             if (OpHAS_SIBLING(o))
2398                 next_kid = o->op_sibparent;
2399             else
2400                 o = o->op_sibparent; /*try parent's next sibling */
2401         }
2402         o = next_kid;
2403     }
2404
2405     return arg;
2406 }
2407
2408
2409 static OP *
2410 S_listkids(pTHX_ OP *o)
2411 {
2412     if (o && o->op_flags & OPf_KIDS) {
2413         OP *kid;
2414         for (kid = cLISTOPo->op_first; kid; kid = OpSIBLING(kid))
2415             list(kid);
2416     }
2417     return o;
2418 }
2419
2420
2421 /* apply list context to the o subtree */
2422
2423 OP *
2424 Perl_list(pTHX_ OP *o)
2425 {
2426     OP * top_op = o;
2427
2428     while (1) {
2429         OP *next_kid = NULL; /* what op (if any) to process next */
2430
2431         OP *kid;
2432
2433         /* assumes no premature commitment */
2434         if (!o || (o->op_flags & OPf_WANT)
2435              || (PL_parser && PL_parser->error_count)
2436              || o->op_type == OP_RETURN)
2437         {
2438             goto do_next;
2439         }
2440
2441         if ((o->op_private & OPpTARGET_MY)
2442             && (PL_opargs[o->op_type] & OA_TARGLEX))/* OPp share the meaning */
2443         {
2444             goto do_next;                               /* As if inside SASSIGN */
2445         }
2446
2447         o->op_flags = (o->op_flags & ~OPf_WANT) | OPf_WANT_LIST;
2448
2449         switch (o->op_type) {
2450         case OP_REPEAT:
2451             if (o->op_private & OPpREPEAT_DOLIST
2452              && !(o->op_flags & OPf_STACKED))
2453             {
2454                 list(cBINOPo->op_first);
2455                 kid = cBINOPo->op_last;
2456                 /* optimise away (.....) x 1 */
2457                 if (kid->op_type == OP_CONST && SvIOK(kSVOP_sv)
2458                  && SvIVX(kSVOP_sv) == 1)
2459                 {
2460                     op_null(o); /* repeat */
2461                     op_null(cUNOPx(cBINOPo->op_first)->op_first);/* pushmark */
2462                     /* const (rhs): */
2463                     op_free(op_sibling_splice(o, cBINOPo->op_first, 1, NULL));
2464                 }
2465             }
2466             break;
2467
2468         case OP_OR:
2469         case OP_AND:
2470         case OP_COND_EXPR:
2471             /* impose list context on everything except the condition */
2472             next_kid = OpSIBLING(cUNOPo->op_first);
2473             break;
2474
2475         default:
2476             if (!(o->op_flags & OPf_KIDS))
2477                 break;
2478             /* possibly flatten 1..10 into a constant array */
2479             if (!o->op_next && cUNOPo->op_first->op_type == OP_FLOP) {
2480                 list(cBINOPo->op_first);
2481                 gen_constant_list(o);
2482                 goto do_next;
2483             }
2484             next_kid = cUNOPo->op_first; /* do all kids */
2485             break;
2486
2487         case OP_LIST:
2488             if (cLISTOPo->op_first->op_type == OP_PUSHMARK) {
2489                 op_null(cUNOPo->op_first); /* NULL the pushmark */
2490                 op_null(o); /* NULL the list */
2491             }
2492             if (o->op_flags & OPf_KIDS)
2493                 next_kid = cUNOPo->op_first; /* do all kids */
2494             break;
2495
2496         /* the children of these ops are usually a list of statements,
2497          * except the leaves, whose first child is a corresponding enter
2498          */
2499         case OP_SCOPE:
2500         case OP_LINESEQ:
2501             kid = cLISTOPo->op_first;
2502             goto do_kids;
2503         case OP_LEAVE:
2504         case OP_LEAVETRY:
2505             kid = cLISTOPo->op_first;
2506             list(kid);
2507             kid = OpSIBLING(kid);
2508         do_kids:
2509             while (kid) {
2510                 OP *sib = OpSIBLING(kid);
2511                 /* Apply void context to all kids except the last, which
2512                  * is list. E.g.
2513                  *      @a = do { void; void; list }
2514                  * Except that 'when's are always list context, e.g.
2515                  *      @a = do { given(..) {
2516                     *                 when (..) { list }
2517                     *                 when (..) { list }
2518                     *                 ...
2519                     *                }}
2520                     */
2521                 if (!sib) {
2522                     /* tail call optimise calling list() on the last kid */
2523                     next_kid = kid;
2524                     goto do_next;
2525                 }
2526                 else if (kid->op_type == OP_LEAVEWHEN)
2527                     list(kid);
2528                 else
2529                     scalarvoid(kid);
2530                 kid = sib;
2531             }
2532             NOT_REACHED; /* NOTREACHED */
2533             break;
2534
2535         }
2536
2537         /* If next_kid is set, someone in the code above wanted us to process
2538          * that kid and all its remaining siblings.  Otherwise, work our way
2539          * back up the tree */
2540       do_next:
2541         while (!next_kid) {
2542             if (o == top_op)
2543                 return top_op; /* at top; no parents/siblings to try */
2544             if (OpHAS_SIBLING(o))
2545                 next_kid = o->op_sibparent;
2546             else {
2547                 o = o->op_sibparent; /*try parent's next sibling */
2548                 switch (o->op_type) {
2549                 case OP_SCOPE:
2550                 case OP_LINESEQ:
2551                 case OP_LIST:
2552                 case OP_LEAVE:
2553                 case OP_LEAVETRY:
2554                     /* should really restore PL_curcop to its old value, but
2555                      * setting it to PL_compiling is better than do nothing */
2556                     PL_curcop = &PL_compiling;
2557                 }
2558             }
2559
2560
2561         }
2562         o = next_kid;
2563     } /* while */
2564 }
2565
2566
2567 static OP *
2568 S_scalarseq(pTHX_ OP *o)
2569 {
2570     if (o) {
2571         const OPCODE type = o->op_type;
2572
2573         if (type == OP_LINESEQ || type == OP_SCOPE ||
2574             type == OP_LEAVE || type == OP_LEAVETRY)
2575         {
2576             OP *kid, *sib;
2577             for (kid = cLISTOPo->op_first; kid; kid = sib) {
2578                 if ((sib = OpSIBLING(kid))
2579                  && (  OpHAS_SIBLING(sib) || sib->op_type != OP_NULL
2580                     || (  sib->op_targ != OP_NEXTSTATE
2581                        && sib->op_targ != OP_DBSTATE  )))
2582                 {
2583                     scalarvoid(kid);
2584                 }
2585             }
2586             PL_curcop = &PL_compiling;
2587         }
2588         o->op_flags &= ~OPf_PARENS;
2589         if (PL_hints & HINT_BLOCK_SCOPE)
2590             o->op_flags |= OPf_PARENS;
2591     }
2592     else
2593         o = newOP(OP_STUB, 0);
2594     return o;
2595 }
2596
2597 STATIC OP *
2598 S_modkids(pTHX_ OP *o, I32 type)
2599 {
2600     if (o && o->op_flags & OPf_KIDS) {
2601         OP *kid;
2602         for (kid = cLISTOPo->op_first; kid; kid = OpSIBLING(kid))
2603             op_lvalue(kid, type);
2604     }
2605     return o;
2606 }
2607
2608
2609 /* for a helem/hslice/kvslice, if its a fixed hash, croak on invalid
2610  * const fields. Also, convert CONST keys to HEK-in-SVs.
2611  * rop    is the op that retrieves the hash;
2612  * key_op is the first key
2613  * real   if false, only check (and possibly croak); don't update op
2614  */
2615
2616 STATIC void
2617 S_check_hash_fields_and_hekify(pTHX_ UNOP *rop, SVOP *key_op, int real)
2618 {
2619     PADNAME *lexname;
2620     GV **fields;
2621     bool check_fields;
2622
2623     /* find the padsv corresponding to $lex->{} or @{$lex}{} */
2624     if (rop) {
2625         if (rop->op_first->op_type == OP_PADSV)
2626             /* @$hash{qw(keys here)} */
2627             rop = (UNOP*)rop->op_first;
2628         else {
2629             /* @{$hash}{qw(keys here)} */
2630             if (rop->op_first->op_type == OP_SCOPE
2631                 && cLISTOPx(rop->op_first)->op_last->op_type == OP_PADSV)
2632                 {
2633                     rop = (UNOP*)cLISTOPx(rop->op_first)->op_last;
2634                 }
2635             else
2636                 rop = NULL;
2637         }
2638     }
2639
2640     lexname = NULL; /* just to silence compiler warnings */
2641     fields  = NULL; /* just to silence compiler warnings */
2642
2643     check_fields =
2644             rop
2645          && (lexname = padnamelist_fetch(PL_comppad_name, rop->op_targ),
2646              SvPAD_TYPED(lexname))
2647          && (fields = (GV**)hv_fetchs(PadnameTYPE(lexname), "FIELDS", FALSE))
2648          && isGV(*fields) && GvHV(*fields);
2649
2650     for (; key_op; key_op = (SVOP*)OpSIBLING(key_op)) {
2651         SV **svp, *sv;
2652         if (key_op->op_type != OP_CONST)
2653             continue;
2654         svp = cSVOPx_svp(key_op);
2655
2656         /* make sure it's not a bareword under strict subs */
2657         if (key_op->op_private & OPpCONST_BARE &&
2658             key_op->op_private & OPpCONST_STRICT)
2659         {
2660             no_bareword_allowed((OP*)key_op);
2661         }
2662
2663         /* Make the CONST have a shared SV */
2664         if (   !SvIsCOW_shared_hash(sv = *svp)
2665             && SvTYPE(sv) < SVt_PVMG
2666             && SvOK(sv)
2667             && !SvROK(sv)
2668             && real)
2669         {
2670             SSize_t keylen;
2671             const char * const key = SvPV_const(sv, *(STRLEN*)&keylen);
2672             SV *nsv = newSVpvn_share(key, SvUTF8(sv) ? -keylen : keylen, 0);
2673             SvREFCNT_dec_NN(sv);
2674             *svp = nsv;
2675         }
2676
2677         if (   check_fields
2678             && !hv_fetch_ent(GvHV(*fields), *svp, FALSE, 0))
2679         {
2680             Perl_croak(aTHX_ "No such class field \"%" SVf "\" "
2681                         "in variable %" PNf " of type %" HEKf,
2682                         SVfARG(*svp), PNfARG(lexname),
2683                         HEKfARG(HvNAME_HEK(PadnameTYPE(lexname))));
2684         }
2685     }
2686 }
2687
2688 /* info returned by S_sprintf_is_multiconcatable() */
2689
2690 struct sprintf_ismc_info {
2691     SSize_t nargs;    /* num of args to sprintf (not including the format) */
2692     char  *start;     /* start of raw format string */
2693     char  *end;       /* bytes after end of raw format string */
2694     STRLEN total_len; /* total length (in bytes) of format string, not
2695                          including '%s' and  half of '%%' */
2696     STRLEN variant;   /* number of bytes by which total_len_p would grow
2697                          if upgraded to utf8 */
2698     bool   utf8;      /* whether the format is utf8 */
2699 };
2700
2701
2702 /* is the OP_SPRINTF o suitable for converting into a multiconcat op?
2703  * i.e. its format argument is a const string with only '%s' and '%%'
2704  * formats, and the number of args is known, e.g.
2705  *    sprintf "a=%s f=%s", $a[0], scalar(f());
2706  * but not
2707  *    sprintf "i=%d a=%s f=%s", $i, @a, f();
2708  *
2709  * If successful, the sprintf_ismc_info struct pointed to by info will be
2710  * populated.
2711  */
2712
2713 STATIC bool
2714 S_sprintf_is_multiconcatable(pTHX_ OP *o,struct sprintf_ismc_info *info)
2715 {
2716     OP    *pm, *constop, *kid;
2717     SV    *sv;
2718     char  *s, *e, *p;
2719     SSize_t nargs, nformats;
2720     STRLEN cur, total_len, variant;
2721     bool   utf8;
2722
2723     /* if sprintf's behaviour changes, die here so that someone
2724      * can decide whether to enhance this function or skip optimising
2725      * under those new circumstances */
2726     assert(!(o->op_flags & OPf_STACKED));
2727     assert(!(PL_opargs[OP_SPRINTF] & OA_TARGLEX));
2728     assert(!(o->op_private & ~OPpARG4_MASK));
2729
2730     pm = cUNOPo->op_first;
2731     if (pm->op_type != OP_PUSHMARK) /* weird coreargs stuff */
2732         return FALSE;
2733     constop = OpSIBLING(pm);
2734     if (!constop || constop->op_type != OP_CONST)
2735         return FALSE;
2736     sv = cSVOPx_sv(constop);
2737     if (SvMAGICAL(sv) || !SvPOK(sv))
2738         return FALSE;
2739
2740     s = SvPV(sv, cur);
2741     e = s + cur;
2742
2743     /* Scan format for %% and %s and work out how many %s there are.
2744      * Abandon if other format types are found.
2745      */
2746
2747     nformats  = 0;
2748     total_len = 0;
2749     variant   = 0;
2750
2751     for (p = s; p < e; p++) {
2752         if (*p != '%') {
2753             total_len++;
2754             if (!UTF8_IS_INVARIANT(*p))
2755                 variant++;
2756             continue;
2757         }
2758         p++;
2759         if (p >= e)
2760             return FALSE; /* lone % at end gives "Invalid conversion" */
2761         if (*p == '%')
2762             total_len++;
2763         else if (*p == 's')
2764             nformats++;
2765         else
2766             return FALSE;
2767     }
2768
2769     if (!nformats || nformats > PERL_MULTICONCAT_MAXARG)
2770         return FALSE;
2771
2772     utf8 = cBOOL(SvUTF8(sv));
2773     if (utf8)
2774         variant = 0;
2775
2776     /* scan args; they must all be in scalar cxt */
2777
2778     nargs = 0;
2779     kid = OpSIBLING(constop);
2780
2781     while (kid) {
2782         if ((kid->op_flags & OPf_WANT) != OPf_WANT_SCALAR)
2783             return FALSE;
2784         nargs++;
2785         kid = OpSIBLING(kid);
2786     }
2787
2788     if (nargs != nformats)
2789         return FALSE; /* e.g. sprintf("%s%s", $a); */
2790
2791
2792     info->nargs      = nargs;
2793     info->start      = s;
2794     info->end        = e;
2795     info->total_len  = total_len;
2796     info->variant    = variant;
2797     info->utf8       = utf8;
2798
2799     return TRUE;
2800 }
2801
2802
2803
2804 /* S_maybe_multiconcat():
2805  *
2806  * given an OP_STRINGIFY, OP_SASSIGN, OP_CONCAT or OP_SPRINTF op, possibly
2807  * convert it (and its children) into an OP_MULTICONCAT. See the code
2808  * comments just before pp_multiconcat() for the full details of what
2809  * OP_MULTICONCAT supports.
2810  *
2811  * Basically we're looking for an optree with a chain of OP_CONCATS down
2812  * the LHS (or an OP_SPRINTF), with possibly an OP_SASSIGN, and/or
2813  * OP_STRINGIFY, and/or OP_CONCAT acting as '.=' at its head, e.g.
2814  *
2815  *      $x = "$a$b-$c"
2816  *
2817  *  looks like
2818  *
2819  *      SASSIGN
2820  *         |
2821  *      STRINGIFY   -- PADSV[$x]
2822  *         |
2823  *         |
2824  *      ex-PUSHMARK -- CONCAT/S
2825  *                        |
2826  *                     CONCAT/S  -- PADSV[$d]
2827  *                        |
2828  *                     CONCAT    -- CONST["-"]
2829  *                        |
2830  *                     PADSV[$a] -- PADSV[$b]
2831  *
2832  * Note that at this stage the OP_SASSIGN may have already been optimised
2833  * away with OPpTARGET_MY set on the OP_STRINGIFY or OP_CONCAT.
2834  */
2835
2836 STATIC void
2837 S_maybe_multiconcat(pTHX_ OP *o)
2838 {
2839     dVAR;
2840     OP *lastkidop;   /* the right-most of any kids unshifted onto o */
2841     OP *topop;       /* the top-most op in the concat tree (often equals o,
2842                         unless there are assign/stringify ops above it */
2843     OP *parentop;    /* the parent op of topop (or itself if no parent) */
2844     OP *targmyop;    /* the op (if any) with the OPpTARGET_MY flag */
2845     OP *targetop;    /* the op corresponding to target=... or target.=... */
2846     OP *stringop;    /* the OP_STRINGIFY op, if any */
2847     OP *nextop;      /* used for recreating the op_next chain without consts */
2848     OP *kid;         /* general-purpose op pointer */
2849     UNOP_AUX_item *aux;
2850     UNOP_AUX_item *lenp;
2851     char *const_str, *p;
2852     struct sprintf_ismc_info sprintf_info;
2853
2854                      /* store info about each arg in args[];
2855                       * toparg is the highest used slot; argp is a general
2856                       * pointer to args[] slots */
2857     struct {
2858         void *p;      /* initially points to const sv (or null for op);
2859                          later, set to SvPV(constsv), with ... */
2860         STRLEN len;   /* ... len set to SvPV(..., len) */
2861     } *argp, *toparg, args[PERL_MULTICONCAT_MAXARG*2 + 1];
2862
2863     SSize_t nargs  = 0;
2864     SSize_t nconst = 0;
2865     SSize_t nadjconst  = 0; /* adjacent consts - may be demoted to args */
2866     STRLEN variant;
2867     bool utf8 = FALSE;
2868     bool kid_is_last = FALSE; /* most args will be the RHS kid of a concat op;
2869                                  the last-processed arg will the LHS of one,
2870                                  as args are processed in reverse order */
2871     U8   stacked_last = 0;   /* whether the last seen concat op was STACKED */
2872     STRLEN total_len  = 0;   /* sum of the lengths of the const segments */
2873     U8 flags          = 0;   /* what will become the op_flags and ... */
2874     U8 private_flags  = 0;   /* ... op_private of the multiconcat op */
2875     bool is_sprintf = FALSE; /* we're optimising an sprintf */
2876     bool is_targable  = FALSE; /* targetop is an OPpTARGET_MY candidate */
2877     bool prev_was_const = FALSE; /* previous arg was a const */
2878
2879     /* -----------------------------------------------------------------
2880      * Phase 1:
2881      *
2882      * Examine the optree non-destructively to determine whether it's
2883      * suitable to be converted into an OP_MULTICONCAT. Accumulate
2884      * information about the optree in args[].
2885      */
2886
2887     argp     = args;
2888     targmyop = NULL;
2889     targetop = NULL;
2890     stringop = NULL;
2891     topop    = o;
2892     parentop = o;
2893
2894     assert(   o->op_type == OP_SASSIGN
2895            || o->op_type == OP_CONCAT
2896            || o->op_type == OP_SPRINTF
2897            || o->op_type == OP_STRINGIFY);
2898
2899     Zero(&sprintf_info, 1, struct sprintf_ismc_info);
2900
2901     /* first see if, at the top of the tree, there is an assign,
2902      * append and/or stringify */
2903
2904     if (topop->op_type == OP_SASSIGN) {
2905         /* expr = ..... */
2906         if (o->op_ppaddr != PL_ppaddr[OP_SASSIGN])
2907             return;
2908         if (o->op_private & (OPpASSIGN_BACKWARDS|OPpASSIGN_CV_TO_GV))
2909             return;
2910         assert(!(o->op_private & ~OPpARG2_MASK)); /* barf on unknown flags */
2911
2912         parentop = topop;
2913         topop = cBINOPo->op_first;
2914         targetop = OpSIBLING(topop);
2915         if (!targetop) /* probably some sort of syntax error */
2916             return;
2917     }
2918     else if (   topop->op_type == OP_CONCAT
2919              && (topop->op_flags & OPf_STACKED)
2920              && (!(topop->op_private & OPpCONCAT_NESTED))
2921             )
2922     {
2923         /* expr .= ..... */
2924
2925         /* OPpTARGET_MY shouldn't be able to be set here. If it is,
2926          * decide what to do about it */
2927         assert(!(o->op_private & OPpTARGET_MY));
2928
2929         /* barf on unknown flags */
2930         assert(!(o->op_private & ~(OPpARG2_MASK|OPpTARGET_MY)));
2931         private_flags |= OPpMULTICONCAT_APPEND;
2932         targetop = cBINOPo->op_first;
2933         parentop = topop;
2934         topop    = OpSIBLING(targetop);
2935
2936         /* $x .= <FOO> gets optimised to rcatline instead */
2937         if (topop->op_type == OP_READLINE)
2938             return;
2939     }
2940
2941     if (targetop) {
2942         /* Can targetop (the LHS) if it's a padsv, be be optimised
2943          * away and use OPpTARGET_MY instead?
2944          */
2945         if (    (targetop->op_type == OP_PADSV)
2946             && !(targetop->op_private & OPpDEREF)
2947             && !(targetop->op_private & OPpPAD_STATE)
2948                /* we don't support 'my $x .= ...' */
2949             && (   o->op_type == OP_SASSIGN
2950                 || !(targetop->op_private & OPpLVAL_INTRO))
2951         )
2952             is_targable = TRUE;
2953     }
2954
2955     if (topop->op_type == OP_STRINGIFY) {
2956         if (topop->op_ppaddr != PL_ppaddr[OP_STRINGIFY])
2957             return;
2958         stringop = topop;
2959
2960         /* barf on unknown flags */
2961         assert(!(o->op_private & ~(OPpARG4_MASK|OPpTARGET_MY)));
2962
2963         if ((topop->op_private & OPpTARGET_MY)) {
2964             if (o->op_type == OP_SASSIGN)
2965                 return; /* can't have two assigns */
2966             targmyop = topop;
2967         }
2968
2969         private_flags |= OPpMULTICONCAT_STRINGIFY;
2970         parentop = topop;
2971         topop = cBINOPx(topop)->op_first;
2972         assert(OP_TYPE_IS_OR_WAS_NN(topop, OP_PUSHMARK));
2973         topop = OpSIBLING(topop);
2974     }
2975
2976     if (topop->op_type == OP_SPRINTF) {
2977         if (topop->op_ppaddr != PL_ppaddr[OP_SPRINTF])
2978             return;
2979         if (S_sprintf_is_multiconcatable(aTHX_ topop, &sprintf_info)) {
2980             nargs     = sprintf_info.nargs;
2981             total_len = sprintf_info.total_len;
2982             variant   = sprintf_info.variant;
2983             utf8      = sprintf_info.utf8;
2984             is_sprintf = TRUE;
2985             private_flags |= OPpMULTICONCAT_FAKE;
2986             toparg = argp;
2987             /* we have an sprintf op rather than a concat optree.
2988              * Skip most of the code below which is associated with
2989              * processing that optree. We also skip phase 2, determining
2990              * whether its cost effective to optimise, since for sprintf,
2991              * multiconcat is *always* faster */
2992             goto create_aux;
2993         }
2994         /* note that even if the sprintf itself isn't multiconcatable,
2995          * the expression as a whole may be, e.g. in
2996          *    $x .= sprintf("%d",...)
2997          * the sprintf op will be left as-is, but the concat/S op may
2998          * be upgraded to multiconcat
2999          */
3000     }
3001     else if (topop->op_type == OP_CONCAT) {
3002         if (topop->op_ppaddr != PL_ppaddr[OP_CONCAT])
3003             return;
3004
3005         if ((topop->op_private & OPpTARGET_MY)) {
3006             if (o->op_type == OP_SASSIGN || targmyop)
3007                 return; /* can't have two assigns */
3008             targmyop = topop;
3009         }
3010     }
3011
3012     /* Is it safe to convert a sassign/stringify/concat op into
3013      * a multiconcat? */
3014     assert((PL_opargs[OP_SASSIGN]   & OA_CLASS_MASK) == OA_BINOP);
3015     assert((PL_opargs[OP_CONCAT]    & OA_CLASS_MASK) == OA_BINOP);
3016     assert((PL_opargs[OP_STRINGIFY] & OA_CLASS_MASK) == OA_LISTOP);
3017     assert((PL_opargs[OP_SPRINTF]   & OA_CLASS_MASK) == OA_LISTOP);
3018     STATIC_ASSERT_STMT(   STRUCT_OFFSET(BINOP,    op_last)
3019                        == STRUCT_OFFSET(UNOP_AUX, op_aux));
3020     STATIC_ASSERT_STMT(   STRUCT_OFFSET(LISTOP,   op_last)
3021                        == STRUCT_OFFSET(UNOP_AUX, op_aux));
3022
3023     /* Now scan the down the tree looking for a series of
3024      * CONCAT/OPf_STACKED ops on the LHS (with the last one not
3025      * stacked). For example this tree:
3026      *
3027      *     |
3028      *   CONCAT/STACKED
3029      *     |
3030      *   CONCAT/STACKED -- EXPR5
3031      *     |
3032      *   CONCAT/STACKED -- EXPR4
3033      *     |
3034      *   CONCAT -- EXPR3
3035      *     |
3036      *   EXPR1  -- EXPR2
3037      *
3038      * corresponds to an expression like
3039      *
3040      *   (EXPR1 . EXPR2 . EXPR3 . EXPR4 . EXPR5)
3041      *
3042      * Record info about each EXPR in args[]: in particular, whether it is
3043      * a stringifiable OP_CONST and if so what the const sv is.
3044      *
3045      * The reason why the last concat can't be STACKED is the difference
3046      * between
3047      *
3048      *    ((($a .= $a) .= $a) .= $a) .= $a
3049      *
3050      * and
3051      *    $a . $a . $a . $a . $a
3052      *
3053      * The main difference between the optrees for those two constructs
3054      * is the presence of the last STACKED. As well as modifying $a,
3055      * the former sees the changed $a between each concat, so if $s is
3056      * initially 'a', the first returns 'a' x 16, while the latter returns
3057      * 'a' x 5. And pp_multiconcat can't handle that kind of thing.
3058      */
3059
3060     kid = topop;
3061
3062     for (;;) {
3063         OP *argop;
3064         SV *sv;
3065         bool last = FALSE;
3066
3067         if (    kid->op_type == OP_CONCAT
3068             && !kid_is_last
3069         ) {
3070             OP *k1, *k2;
3071             k1 = cUNOPx(kid)->op_first;
3072             k2 = OpSIBLING(k1);
3073             /* shouldn't happen except maybe after compile err? */
3074             if (!k2)
3075                 return;
3076
3077             /* avoid turning (A . B . ($lex = C) ...)  into  (A . B . C ...) */
3078             if (kid->op_private & OPpTARGET_MY)
3079                 kid_is_last = TRUE;
3080
3081             stacked_last = (kid->op_flags & OPf_STACKED);
3082             if (!stacked_last)
3083                 kid_is_last = TRUE;
3084
3085             kid   = k1;
3086             argop = k2;
3087         }
3088         else {
3089             argop = kid;
3090             last = TRUE;
3091         }
3092
3093         if (   nargs + nadjconst  >  PERL_MULTICONCAT_MAXARG        - 2
3094             || (argp - args + 1)  > (PERL_MULTICONCAT_MAXARG*2 + 1) - 2)
3095         {
3096             /* At least two spare slots are needed to decompose both
3097              * concat args. If there are no slots left, continue to
3098              * examine the rest of the optree, but don't push new values
3099              * on args[]. If the optree as a whole is legal for conversion
3100              * (in particular that the last concat isn't STACKED), then
3101              * the first PERL_MULTICONCAT_MAXARG elements of the optree
3102              * can be converted into an OP_MULTICONCAT now, with the first
3103              * child of that op being the remainder of the optree -
3104              * which may itself later be converted to a multiconcat op
3105              * too.
3106              */
3107             if (last) {
3108                 /* the last arg is the rest of the optree */
3109                 argp++->p = NULL;
3110                 nargs++;
3111             }
3112         }
3113         else if (   argop->op_type == OP_CONST
3114             && ((sv = cSVOPx_sv(argop)))
3115             /* defer stringification until runtime of 'constant'
3116              * things that might stringify variantly, e.g. the radix
3117              * point of NVs, or overloaded RVs */
3118             && (SvPOK(sv) || SvIOK(sv))
3119             && (!SvGMAGICAL(sv))
3120         ) {
3121             argp++->p = sv;
3122             utf8   |= cBOOL(SvUTF8(sv));
3123             nconst++;
3124             if (prev_was_const)
3125                 /* this const may be demoted back to a plain arg later;
3126                  * make sure we have enough arg slots left */
3127                 nadjconst++;
3128             prev_was_const = !prev_was_const;
3129         }
3130         else {
3131             argp++->p = NULL;
3132             nargs++;
3133             prev_was_const = FALSE;
3134         }
3135
3136         if (last)
3137             break;
3138     }
3139
3140     toparg = argp - 1;
3141
3142     if (stacked_last)
3143         return; /* we don't support ((A.=B).=C)...) */
3144
3145     /* look for two adjacent consts and don't fold them together:
3146      *     $o . "a" . "b"
3147      * should do
3148      *     $o->concat("a")->concat("b")
3149      * rather than
3150      *     $o->concat("ab")
3151      * (but $o .=  "a" . "b" should still fold)
3152      */
3153     {
3154         bool seen_nonconst = FALSE;
3155         for (argp = toparg; argp >= args; argp--) {
3156             if (argp->p == NULL) {
3157                 seen_nonconst = TRUE;
3158                 continue;
3159             }
3160             if (!seen_nonconst)
3161                 continue;
3162             if (argp[1].p) {
3163                 /* both previous and current arg were constants;
3164                  * leave the current OP_CONST as-is */
3165                 argp->p = NULL;
3166                 nconst--;
3167                 nargs++;
3168             }
3169         }
3170     }
3171
3172     /* -----------------------------------------------------------------
3173      * Phase 2:
3174      *
3175      * At this point we have determined that the optree *can* be converted
3176      * into a multiconcat. Having gathered all the evidence, we now decide
3177      * whether it *should*.
3178      */
3179
3180
3181     /* we need at least one concat action, e.g.:
3182      *
3183      *  Y . Z
3184      *  X = Y . Z
3185      *  X .= Y
3186      *
3187      * otherwise we could be doing something like $x = "foo", which
3188      * if treated as as a concat, would fail to COW.
3189      */
3190     if (nargs + nconst + cBOOL(private_flags & OPpMULTICONCAT_APPEND) < 2)
3191         return;
3192
3193     /* Benchmarking seems to indicate that we gain if:
3194      * * we optimise at least two actions into a single multiconcat
3195      *    (e.g concat+concat, sassign+concat);
3196      * * or if we can eliminate at least 1 OP_CONST;
3197      * * or if we can eliminate a padsv via OPpTARGET_MY
3198      */
3199
3200     if (
3201            /* eliminated at least one OP_CONST */
3202            nconst >= 1
3203            /* eliminated an OP_SASSIGN */
3204         || o->op_type == OP_SASSIGN
3205            /* eliminated an OP_PADSV */
3206         || (!targmyop && is_targable)
3207     )
3208         /* definitely a net gain to optimise */
3209         goto optimise;
3210
3211     /* ... if not, what else? */
3212
3213     /* special-case '$lex1 = expr . $lex1' (where expr isn't lex1):
3214      * multiconcat is faster (due to not creating a temporary copy of
3215      * $lex1), whereas for a general $lex1 = $lex2 . $lex3, concat is
3216      * faster.
3217      */
3218     if (   nconst == 0
3219          && nargs == 2
3220          && targmyop
3221          && topop->op_type == OP_CONCAT
3222     ) {
3223         PADOFFSET t = targmyop->op_targ;
3224         OP *k1 = cBINOPx(topop)->op_first;
3225         OP *k2 = cBINOPx(topop)->op_last;
3226         if (   k2->op_type == OP_PADSV
3227             && k2->op_targ == t
3228             && (   k1->op_type != OP_PADSV
3229                 || k1->op_targ != t)
3230         )
3231             goto optimise;
3232     }
3233
3234     /* need at least two concats */
3235     if (nargs + nconst + cBOOL(private_flags & OPpMULTICONCAT_APPEND) < 3)
3236         return;
3237
3238
3239
3240     /* -----------------------------------------------------------------
3241      * Phase 3:
3242      *
3243      * At this point the optree has been verified as ok to be optimised
3244      * into an OP_MULTICONCAT. Now start changing things.
3245      */
3246
3247    optimise:
3248
3249     /* stringify all const args and determine utf8ness */
3250
3251     variant = 0;
3252     for (argp = args; argp <= toparg; argp++) {
3253         SV *sv = (SV*)argp->p;
3254         if (!sv)
3255             continue; /* not a const op */
3256         if (utf8 && !SvUTF8(sv))
3257             sv_utf8_upgrade_nomg(sv);
3258         argp->p = SvPV_nomg(sv, argp->len);
3259         total_len += argp->len;
3260         
3261         /* see if any strings would grow if converted to utf8 */
3262         if (!utf8) {
3263             variant += variant_under_utf8_count((U8 *) argp->p,
3264                                                 (U8 *) argp->p + argp->len);
3265         }
3266     }
3267
3268     /* create and populate aux struct */
3269
3270   create_aux:
3271
3272     aux = (UNOP_AUX_item*)PerlMemShared_malloc(
3273                     sizeof(UNOP_AUX_item)
3274                     *  (
3275                            PERL_MULTICONCAT_HEADER_SIZE
3276                          + ((nargs + 1) * (variant ? 2 : 1))
3277                         )
3278                     );
3279     const_str = (char *)PerlMemShared_malloc(total_len ? total_len : 1);
3280
3281     /* Extract all the non-const expressions from the concat tree then
3282      * dispose of the old tree, e.g. convert the tree from this:
3283      *
3284      *  o => SASSIGN
3285      *         |
3286      *       STRINGIFY   -- TARGET
3287      *         |
3288      *       ex-PUSHMARK -- CONCAT
3289      *                        |
3290      *                      CONCAT -- EXPR5
3291      *                        |
3292      *                      CONCAT -- EXPR4
3293      *                        |
3294      *                      CONCAT -- EXPR3
3295      *                        |
3296      *                      EXPR1  -- EXPR2
3297      *
3298      *
3299      * to:
3300      *
3301      *  o => MULTICONCAT
3302      *         |
3303      *       ex-PUSHMARK -- EXPR1 -- EXPR2 -- EXPR3 -- EXPR4 -- EXPR5 -- TARGET
3304      *
3305      * except that if EXPRi is an OP_CONST, it's discarded.
3306      *
3307      * During the conversion process, EXPR ops are stripped from the tree
3308      * and unshifted onto o. Finally, any of o's remaining original
3309      * childen are discarded and o is converted into an OP_MULTICONCAT.
3310      *
3311      * In this middle of this, o may contain both: unshifted args on the
3312      * left, and some remaining original args on the right. lastkidop
3313      * is set to point to the right-most unshifted arg to delineate
3314      * between the two sets.
3315      */
3316
3317
3318     if (is_sprintf) {
3319         /* create a copy of the format with the %'s removed, and record
3320          * the sizes of the const string segments in the aux struct */
3321         char *q, *oldq;
3322         lenp = aux + PERL_MULTICONCAT_IX_LENGTHS;
3323
3324         p    = sprintf_info.start;
3325         q    = const_str;
3326         oldq = q;
3327         for (; p < sprintf_info.end; p++) {
3328             if (*p == '%') {
3329                 p++;
3330                 if (*p != '%') {
3331                     (lenp++)->ssize = q - oldq;
3332                     oldq = q;
3333                     continue;
3334                 }
3335             }
3336             *q++ = *p;
3337         }
3338         lenp->ssize = q - oldq;
3339         assert((STRLEN)(q - const_str) == total_len);
3340
3341         /* Attach all the args (i.e. the kids of the sprintf) to o (which
3342          * may or may not be topop) The pushmark and const ops need to be
3343          * kept in case they're an op_next entry point.
3344          */
3345         lastkidop = cLISTOPx(topop)->op_last;
3346         kid = cUNOPx(topop)->op_first; /* pushmark */
3347         op_null(kid);
3348         op_null(OpSIBLING(kid));       /* const */
3349         if (o != topop) {
3350             kid = op_sibling_splice(topop, NULL, -1, NULL); /* cut all args */
3351             op_sibling_splice(o, NULL, 0, kid); /* and attach to o */
3352             lastkidop->op_next = o;
3353         }
3354     }
3355     else {
3356         p = const_str;
3357         lenp = aux + PERL_MULTICONCAT_IX_LENGTHS;
3358
3359         lenp->ssize = -1;
3360
3361         /* Concatenate all const strings into const_str.
3362          * Note that args[] contains the RHS args in reverse order, so
3363          * we scan args[] from top to bottom to get constant strings
3364          * in L-R order
3365          */
3366         for (argp = toparg; argp >= args; argp--) {
3367             if (!argp->p)
3368                 /* not a const op */
3369                 (++lenp)->ssize = -1;
3370             else {
3371                 STRLEN l = argp->len;
3372                 Copy(argp->p, p, l, char);
3373                 p += l;
3374                 if (lenp->ssize == -1)
3375                     lenp->ssize = l;
3376                 else
3377                     lenp->ssize += l;
3378             }
3379         }
3380
3381         kid = topop;
3382         nextop = o;
3383         lastkidop = NULL;
3384
3385         for (argp = args; argp <= toparg; argp++) {
3386             /* only keep non-const args, except keep the first-in-next-chain
3387              * arg no matter what it is (but nulled if OP_CONST), because it
3388              * may be the entry point to this subtree from the previous
3389              * op_next.
3390              */
3391             bool last = (argp == toparg);
3392             OP *prev;
3393
3394             /* set prev to the sibling *before* the arg to be cut out,
3395              * e.g. when cutting EXPR:
3396              *
3397              *         |
3398              * kid=  CONCAT
3399              *         |
3400              * prev= CONCAT -- EXPR
3401              *         |
3402              */
3403             if (argp == args && kid->op_type != OP_CONCAT) {
3404                 /* in e.g. '$x .= f(1)' there's no RHS concat tree
3405                  * so the expression to be cut isn't kid->op_last but
3406                  * kid itself */
3407                 OP *o1, *o2;
3408                 /* find the op before kid */
3409                 o1 = NULL;
3410                 o2 = cUNOPx(parentop)->op_first;
3411                 while (o2 && o2 != kid) {
3412                     o1 = o2;
3413                     o2 = OpSIBLING(o2);
3414                 }
3415                 assert(o2 == kid);
3416                 prev = o1;
3417                 kid  = parentop;
3418             }
3419             else if (kid == o && lastkidop)
3420                 prev = last ? lastkidop : OpSIBLING(lastkidop);
3421             else
3422                 prev = last ? NULL : cUNOPx(kid)->op_first;
3423
3424             if (!argp->p || last) {
3425                 /* cut RH op */
3426                 OP *aop = op_sibling_splice(kid, prev, 1, NULL);
3427                 /* and unshift to front of o */
3428                 op_sibling_splice(o, NULL, 0, aop);
3429                 /* record the right-most op added to o: later we will
3430                  * free anything to the right of it */
3431                 if (!lastkidop)
3432                     lastkidop = aop;
3433                 aop->op_next = nextop;
3434                 if (last) {
3435                     if (argp->p)
3436                         /* null the const at start of op_next chain */
3437                         op_null(aop);
3438                 }
3439                 else if (prev)
3440                     nextop = prev->op_next;
3441             }
3442
3443             /* the last two arguments are both attached to the same concat op */
3444             if (argp < toparg - 1)
3445                 kid = prev;
3446         }
3447     }
3448
3449     /* Populate the aux struct */
3450
3451     aux[PERL_MULTICONCAT_IX_NARGS].ssize     = nargs;
3452     aux[PERL_MULTICONCAT_IX_PLAIN_PV].pv    = utf8 ? NULL : const_str;
3453     aux[PERL_MULTICONCAT_IX_PLAIN_LEN].ssize = utf8 ?    0 : total_len;
3454     aux[PERL_MULTICONCAT_IX_UTF8_PV].pv     = const_str;
3455     aux[PERL_MULTICONCAT_IX_UTF8_LEN].ssize  = total_len;
3456
3457     /* if variant > 0, calculate a variant const string and lengths where
3458      * the utf8 version of the string will take 'variant' more bytes than
3459      * the plain one. */
3460
3461     if (variant) {
3462         char              *p = const_str;
3463         STRLEN          ulen = total_len + variant;
3464         UNOP_AUX_item  *lens = aux + PERL_MULTICONCAT_IX_LENGTHS;
3465         UNOP_AUX_item *ulens = lens + (nargs + 1);
3466         char             *up = (char*)PerlMemShared_malloc(ulen);
3467         SSize_t            n;
3468
3469         aux[PERL_MULTICONCAT_IX_UTF8_PV].pv    = up;
3470         aux[PERL_MULTICONCAT_IX_UTF8_LEN].ssize = ulen;
3471
3472         for (n = 0; n < (nargs + 1); n++) {
3473             SSize_t i;
3474             char * orig_up = up;
3475             for (i = (lens++)->ssize; i > 0; i--) {
3476                 U8 c = *p++;
3477                 append_utf8_from_native_byte(c, (U8**)&up);
3478             }
3479             (ulens++)->ssize = (i < 0) ? i : up - orig_up;
3480         }
3481     }
3482
3483     if (stringop) {
3484         /* if there was a top(ish)-level OP_STRINGIFY, we need to keep
3485          * that op's first child - an ex-PUSHMARK - because the op_next of
3486          * the previous op may point to it (i.e. it's the entry point for
3487          * the o optree)
3488          */
3489         OP *pmop =
3490             (stringop == o)
3491                 ? op_sibling_splice(o, lastkidop, 1, NULL)
3492                 : op_sibling_splice(stringop, NULL, 1, NULL);
3493         assert(OP_TYPE_IS_OR_WAS_NN(pmop, OP_PUSHMARK));
3494         op_sibling_splice(o, NULL, 0, pmop);
3495         if (!lastkidop)
3496             lastkidop = pmop;
3497     }
3498
3499     /* Optimise 
3500      *    target  = A.B.C...
3501      *    target .= A.B.C...
3502      */
3503
3504     if (targetop) {
3505         assert(!targmyop);
3506
3507         if (o->op_type == OP_SASSIGN) {
3508             /* Move the target subtree from being the last of o's children
3509              * to being the last of o's preserved children.
3510              * Note the difference between 'target = ...' and 'target .= ...':
3511              * for the former, target is executed last; for the latter,
3512              * first.
3513              */
3514             kid = OpSIBLING(lastkidop);
3515             op_sibling_splice(o, kid, 1, NULL); /* cut target op */
3516             op_sibling_splice(o, lastkidop, 0, targetop); /* and paste */
3517             lastkidop->op_next = kid->op_next;
3518             lastkidop = targetop;
3519         }
3520         else {
3521             /* Move the target subtree from being the first of o's
3522              * original children to being the first of *all* o's children.
3523              */
3524             if (lastkidop) {
3525                 op_sibling_splice(o, lastkidop, 1, NULL); /* cut target op */
3526                 op_sibling_splice(o, NULL, 0, targetop);  /* and paste*/
3527             }
3528             else {
3529                 /* if the RHS of .= doesn't contain a concat (e.g.
3530                  * $x .= "foo"), it gets missed by the "strip ops from the
3531                  * tree and add to o" loop earlier */
3532                 assert(topop->op_type != OP_CONCAT);
3533                 if (stringop) {
3534                     /* in e.g. $x .= "$y", move the $y expression
3535                      * from being a child of OP_STRINGIFY to being the
3536                      * second child of the OP_CONCAT
3537                      */
3538                     assert(cUNOPx(stringop)->op_first == topop);
3539                     op_sibling_splice(stringop, NULL, 1, NULL);
3540                     op_sibling_splice(o, cUNOPo->op_first, 0, topop);
3541                 }
3542                 assert(topop == OpSIBLING(cBINOPo->op_first));
3543                 if (toparg->p)
3544                     op_null(topop);
3545                 lastkidop = topop;
3546             }
3547         }
3548
3549         if (is_targable) {
3550             /* optimise
3551              *  my $lex  = A.B.C...
3552              *     $lex  = A.B.C...
3553              *     $lex .= A.B.C...
3554              * The original padsv op is kept but nulled in case it's the
3555              * entry point for the optree (which it will be for
3556              * '$lex .=  ... '
3557              */
3558             private_flags |= OPpTARGET_MY;
3559             private_flags |= (targetop->op_private & OPpLVAL_INTRO);
3560             o->op_targ = targetop->op_targ;
3561             targetop->op_targ = 0;
3562             op_null(targetop);
3563         }
3564         else
3565             flags |= OPf_STACKED;
3566     }
3567     else if (targmyop) {
3568         private_flags |= OPpTARGET_MY;
3569         if (o != targmyop) {
3570             o->op_targ = targmyop->op_targ;
3571             targmyop->op_targ = 0;
3572         }
3573     }
3574
3575     /* detach the emaciated husk of the sprintf/concat optree and free it */
3576     for (;;) {
3577         kid = op_sibling_splice(o, lastkidop, 1, NULL);
3578         if (!kid)
3579             break;
3580         op_free(kid);
3581     }
3582
3583     /* and convert o into a multiconcat */
3584
3585     o->op_flags        = (flags|OPf_KIDS|stacked_last
3586                          |(o->op_flags & (OPf_WANT|OPf_PARENS)));
3587     o->op_private      = private_flags;
3588     o->op_type         = OP_MULTICONCAT;
3589     o->op_ppaddr       = PL_ppaddr[OP_MULTICONCAT];
3590     cUNOP_AUXo->op_aux = aux;
3591 }
3592
3593
3594 /* do all the final processing on an optree (e.g. running the peephole
3595  * optimiser on it), then attach it to cv (if cv is non-null)
3596  */
3597
3598 static void
3599 S_process_optree(pTHX_ CV *cv, OP *optree, OP* start)
3600 {
3601     OP **startp;
3602
3603     /* XXX for some reason, evals, require and main optrees are
3604      * never attached to their CV; instead they just hang off
3605      * PL_main_root + PL_main_start or PL_eval_root + PL_eval_start
3606      * and get manually freed when appropriate */
3607     if (cv)
3608         startp = &CvSTART(cv);
3609     else
3610         startp = PL_in_eval? &PL_eval_start : &PL_main_start;
3611
3612     *startp = start;
3613     optree->op_private |= OPpREFCOUNTED;
3614     OpREFCNT_set(optree, 1);
3615     optimize_optree(optree);
3616     CALL_PEEP(*startp);
3617     finalize_optree(optree);
3618     S_prune_chain_head(startp);
3619
3620     if (cv) {
3621         /* now that optimizer has done its work, adjust pad values */
3622         pad_tidy(optree->op_type == OP_LEAVEWRITE ? padtidy_FORMAT
3623                  : CvCLONE(cv) ? padtidy_SUBCLONE : padtidy_SUB);
3624     }
3625 }
3626
3627
3628 /*
3629 =for apidoc optimize_optree
3630
3631 This function applies some optimisations to the optree in top-down order.
3632 It is called before the peephole optimizer, which processes ops in
3633 execution order. Note that finalize_optree() also does a top-down scan,
3634 but is called *after* the peephole optimizer.
3635
3636 =cut
3637 */
3638
3639 void
3640 Perl_optimize_optree(pTHX_ OP* o)
3641 {
3642     PERL_ARGS_ASSERT_OPTIMIZE_OPTREE;
3643
3644     ENTER;
3645     SAVEVPTR(PL_curcop);
3646
3647     optimize_op(o);
3648
3649     LEAVE;
3650 }
3651
3652
3653 /* helper for optimize_optree() which optimises one op then recurses
3654  * to optimise any children.
3655  */
3656
3657 STATIC void
3658 S_optimize_op(pTHX_ OP* o)
3659 {
3660     OP *top_op = o;
3661
3662     PERL_ARGS_ASSERT_OPTIMIZE_OP;
3663
3664     while (1) {
3665         OP * next_kid = NULL;
3666
3667         assert(o->op_type != OP_FREED);
3668
3669         switch (o->op_type) {
3670         case OP_NEXTSTATE:
3671         case OP_DBSTATE:
3672             PL_curcop = ((COP*)o);              /* for warnings */
3673             break;
3674
3675
3676         case OP_CONCAT:
3677         case OP_SASSIGN:
3678         case OP_STRINGIFY:
3679         case OP_SPRINTF:
3680             S_maybe_multiconcat(aTHX_ o);
3681             break;
3682
3683         case OP_SUBST:
3684             if (cPMOPo->op_pmreplrootu.op_pmreplroot) {
3685                 /* we can't assume that op_pmreplroot->op_sibparent == o
3686                  * and that it is thus possible to walk back up the tree
3687                  * past op_pmreplroot. So, although we try to avoid
3688                  * recursing through op trees, do it here. After all,
3689                  * there are unlikely to be many nested s///e's within
3690                  * the replacement part of a s///e.
3691                  */
3692                 optimize_op(cPMOPo->op_pmreplrootu.op_pmreplroot);
3693             }
3694             break;
3695
3696         default:
3697             break;
3698         }
3699
3700         if (o->op_flags & OPf_KIDS)
3701             next_kid = cUNOPo->op_first;
3702
3703         /* if a kid hasn't been nominated to process, continue with the
3704          * next sibling, or if no siblings left, go back to the parent's
3705          * siblings and so on
3706          */
3707         while (!next_kid) {
3708             if (o == top_op)
3709                 return; /* at top; no parents/siblings to try */
3710             if (OpHAS_SIBLING(o))
3711                 next_kid = o->op_sibparent;
3712             else
3713                 o = o->op_sibparent; /*try parent's next sibling */
3714         }
3715
3716       /* this label not yet used. Goto here if any code above sets
3717        * next-kid
3718        get_next_op:
3719        */
3720         o = next_kid;
3721     }
3722 }
3723
3724
3725 /*
3726 =for apidoc finalize_optree
3727
3728 This function finalizes the optree.  Should be called directly after
3729 the complete optree is built.  It does some additional
3730 checking which can't be done in the normal C<ck_>xxx functions and makes
3731 the tree thread-safe.
3732
3733 =cut
3734 */
3735 void
3736 Perl_finalize_optree(pTHX_ OP* o)
3737 {
3738     PERL_ARGS_ASSERT_FINALIZE_OPTREE;
3739
3740     ENTER;
3741     SAVEVPTR(PL_curcop);
3742
3743     finalize_op(o);
3744
3745     LEAVE;
3746 }
3747
3748 #ifdef USE_ITHREADS
3749 /* Relocate sv to the pad for thread safety.
3750  * Despite being a "constant", the SV is written to,
3751  * for reference counts, sv_upgrade() etc. */
3752 PERL_STATIC_INLINE void
3753 S_op_relocate_sv(pTHX_ SV** svp, PADOFFSET* targp)
3754 {
3755     PADOFFSET ix;
3756     PERL_ARGS_ASSERT_OP_RELOCATE_SV;
3757     if (!*svp) return;
3758     ix = pad_alloc(OP_CONST, SVf_READONLY);
3759     SvREFCNT_dec(PAD_SVl(ix));
3760     PAD_SETSV(ix, *svp);
3761     /* XXX I don't know how this isn't readonly already. */
3762     if (!SvIsCOW(PAD_SVl(ix))) SvREADONLY_on(PAD_SVl(ix));
3763     *svp = NULL;
3764     *targp = ix;
3765 }
3766 #endif
3767
3768 /*
3769 =for apidoc traverse_op_tree
3770
3771 Return the next op in a depth-first traversal of the op tree,
3772 returning NULL when the traversal is complete.
3773
3774 The initial call must supply the root of the tree as both top and o.
3775
3776 For now it's static, but it may be exposed to the API in the future.
3777
3778 =cut
3779 */
3780
3781 STATIC OP*
3782 S_traverse_op_tree(pTHX_ OP *top, OP *o) {
3783     OP *sib;
3784
3785     PERL_ARGS_ASSERT_TRAVERSE_OP_TREE;
3786
3787     if ((o->op_flags & OPf_KIDS) && cUNOPo->op_first) {
3788         return cUNOPo->op_first;
3789     }
3790     else if ((sib = OpSIBLING(o))) {
3791         return sib;
3792     }
3793     else {
3794         OP *parent = o->op_sibparent;
3795         assert(!(o->op_moresib));
3796         while (parent && parent != top) {
3797             OP *sib = OpSIBLING(parent);
3798             if (sib)
3799                 return sib;
3800             parent = parent->op_sibparent;
3801         }
3802
3803         return NULL;
3804     }
3805 }
3806
3807 STATIC void
3808 S_finalize_op(pTHX_ OP* o)
3809 {
3810     OP * const top = o;
3811     PERL_ARGS_ASSERT_FINALIZE_OP;
3812
3813     do {
3814         assert(o->op_type != OP_FREED);
3815
3816         switch (o->op_type) {
3817         case OP_NEXTSTATE:
3818         case OP_DBSTATE:
3819             PL_curcop = ((COP*)o);              /* for warnings */
3820             break;
3821         case OP_EXEC:
3822             if (OpHAS_SIBLING(o)) {
3823                 OP *sib = OpSIBLING(o);
3824                 if ((  sib->op_type == OP_NEXTSTATE || sib->op_type == OP_DBSTATE)
3825                     && ckWARN(WARN_EXEC)
3826                     && OpHAS_SIBLING(sib))
3827                 {
3828                     const OPCODE type = OpSIBLING(sib)->op_type;
3829                     if (type != OP_EXIT && type != OP_WARN && type != OP_DIE) {
3830                         const line_t oldline = CopLINE(PL_curcop);
3831                         CopLINE_set(PL_curcop, CopLINE((COP*)sib));
3832                         Perl_warner(aTHX_ packWARN(WARN_EXEC),
3833                             "Statement unlikely to be reached");
3834                         Perl_warner(aTHX_ packWARN(WARN_EXEC),
3835                             "\t(Maybe you meant system() when you said exec()?)\n");
3836                         CopLINE_set(PL_curcop, oldline);
3837                     }
3838                 }
3839             }
3840             break;
3841
3842         case OP_GV:
3843             if ((o->op_private & OPpEARLY_CV) && ckWARN(WARN_PROTOTYPE)) {
3844                 GV * const gv = cGVOPo_gv;
3845                 if (SvTYPE(gv) == SVt_PVGV && GvCV(gv) && SvPVX_const(GvCV(gv))) {
3846                     /* XXX could check prototype here instead of just carping */
3847                     SV * const sv = sv_newmortal();
3848                     gv_efullname3(sv, gv, NULL);
3849                     Perl_warner(aTHX_ packWARN(WARN_PROTOTYPE),
3850                                 "%" SVf "() called too early to check prototype",
3851                                 SVfARG(sv));
3852                 }
3853             }
3854             break;
3855
3856         case OP_CONST:
3857             if (cSVOPo->op_private & OPpCONST_STRICT)
3858                 no_bareword_allowed(o);
3859 #ifdef USE_ITHREADS
3860             /* FALLTHROUGH */
3861         case OP_HINTSEVAL:
3862             op_relocate_sv(&cSVOPo->op_sv, &o->op_targ);
3863 #endif
3864             break;
3865
3866 #ifdef USE_ITHREADS
3867             /* Relocate all the METHOP's SVs to the pad for thread safety. */
3868         case OP_METHOD_NAMED:
3869         case OP_METHOD_SUPER:
3870         case OP_METHOD_REDIR:
3871         case OP_METHOD_REDIR_SUPER:
3872             op_relocate_sv(&cMETHOPx(o)->op_u.op_meth_sv, &o->op_targ);
3873             break;
3874 #endif
3875
3876         case OP_HELEM: {
3877             UNOP *rop;
3878             SVOP *key_op;
3879             OP *kid;
3880
3881             if ((key_op = cSVOPx(((BINOP*)o)->op_last))->op_type != OP_CONST)
3882                 break;
3883
3884             rop = (UNOP*)((BINOP*)o)->op_first;
3885
3886             goto check_keys;
3887
3888             case OP_HSLICE:
3889                 S_scalar_slice_warning(aTHX_ o);
3890                 /* FALLTHROUGH */
3891
3892             case OP_KVHSLICE:
3893                 kid = OpSIBLING(cLISTOPo->op_first);
3894             if (/* I bet there's always a pushmark... */
3895                 OP_TYPE_ISNT_AND_WASNT_NN(kid, OP_LIST)
3896                 && OP_TYPE_ISNT_NN(kid, OP_CONST))
3897             {
3898                 break;
3899             }
3900
3901             key_op = (SVOP*)(kid->op_type == OP_CONST
3902                              ? kid
3903                              : OpSIBLING(kLISTOP->op_first));
3904
3905             rop = (UNOP*)((LISTOP*)o)->op_last;
3906
3907         check_keys:
3908             if (o->op_private & OPpLVAL_INTRO || rop->op_type != OP_RV2HV)
3909                 rop = NULL;
3910             S_check_hash_fields_and_hekify(aTHX_ rop, key_op, 1);
3911             break;
3912         }
3913         case OP_NULL:
3914             if (o->op_targ != OP_HSLICE && o->op_targ != OP_ASLICE)
3915                 break;
3916             /* FALLTHROUGH */
3917         case OP_ASLICE:
3918             S_scalar_slice_warning(aTHX_ o);
3919             break;
3920
3921         case OP_SUBST: {
3922             if (cPMOPo->op_pmreplrootu.op_pmreplroot)
3923                 finalize_op(cPMOPo->op_pmreplrootu.op_pmreplroot);
3924             break;
3925         }
3926         default:
3927             break;
3928         }
3929
3930 #ifdef DEBUGGING
3931         if (o->op_flags & OPf_KIDS) {
3932             OP *kid;
3933
3934             /* check that op_last points to the last sibling, and that
3935              * the last op_sibling/op_sibparent field points back to the
3936              * parent, and that the only ops with KIDS are those which are
3937              * entitled to them */
3938             U32 type = o->op_type;
3939             U32 family;
3940             bool has_last;
3941
3942             if (type == OP_NULL) {
3943                 type = o->op_targ;
3944                 /* ck_glob creates a null UNOP with ex-type GLOB
3945                  * (which is a list op. So pretend it wasn't a listop */
3946                 if (type == OP_GLOB)
3947                     type = OP_NULL;
3948             }
3949             family = PL_opargs[type] & OA_CLASS_MASK;
3950
3951             has_last = (   family == OA_BINOP
3952                         || family == OA_LISTOP
3953                         || family == OA_PMOP
3954                         || family == OA_LOOP
3955                        );
3956             assert(  has_last /* has op_first and op_last, or ...
3957                   ... has (or may have) op_first: */
3958                   || family == OA_UNOP
3959                   || family == OA_UNOP_AUX
3960                   || family == OA_LOGOP
3961                   || family == OA_BASEOP_OR_UNOP
3962                   || family == OA_FILESTATOP
3963                   || family == OA_LOOPEXOP
3964                   || family == OA_METHOP
3965                   || type == OP_CUSTOM
3966                   || type == OP_NULL /* new_logop does this */
3967                   );
3968
3969             for (kid = cUNOPo->op_first; kid; kid = OpSIBLING(kid)) {
3970                 if (!OpHAS_SIBLING(kid)) {
3971                     if (has_last)
3972                         assert(kid == cLISTOPo->op_last);
3973                     assert(kid->op_sibparent == o);
3974                 }
3975             }
3976         }
3977 #endif
3978     } while (( o = traverse_op_tree(top, o)) != NULL);
3979 }
3980
3981 static void
3982 S_mark_padname_lvalue(pTHX_ PADNAME *pn)
3983 {
3984     CV *cv = PL_compcv;
3985     PadnameLVALUE_on(pn);
3986     while (PadnameOUTER(pn) && PARENT_PAD_INDEX(pn)) {
3987         cv = CvOUTSIDE(cv);
3988         /* RT #127786: cv can be NULL due to an eval within the DB package
3989          * called from an anon sub - anon subs don't have CvOUTSIDE() set
3990          * unless they contain an eval, but calling eval within DB
3991          * pretends the eval was done in the caller's scope.
3992          */
3993         if (!cv)
3994             break;
3995         assert(CvPADLIST(cv));
3996         pn =
3997            PadlistNAMESARRAY(CvPADLIST(cv))[PARENT_PAD_INDEX(pn)];
3998         assert(PadnameLEN(pn));
3999         PadnameLVALUE_on(pn);
4000     }
4001 }
4002
4003 static bool
4004 S_vivifies(const OPCODE type)
4005 {
4006     switch(type) {
4007     case OP_RV2AV:     case   OP_ASLICE:
4008     case OP_RV2HV:     case OP_KVASLICE:
4009     case OP_RV2SV:     case   OP_HSLICE:
4010     case OP_AELEMFAST: case OP_KVHSLICE:
4011     case OP_HELEM:
4012     case OP_AELEM:
4013         return 1;
4014     }
4015     return 0;
4016 }
4017
4018
4019 /* apply lvalue reference (aliasing) context to the optree o.
4020  * E.g. in
4021  *     \($x,$y) = (...)
4022  * o would be the list ($x,$y) and type would be OP_AASSIGN.
4023  * It may descend and apply this to children too, for example in
4024  * \( $cond ? $x, $y) = (...)
4025  */
4026
4027 static void
4028 S_lvref(pTHX_ OP *o, I32 type)
4029 {
4030     dVAR;
4031     OP *kid;
4032     OP * top_op = o;
4033
4034     while (1) {
4035         switch (o->op_type) {
4036         case OP_COND_EXPR:
4037             o = OpSIBLING(cUNOPo->op_first);
4038             continue;
4039
4040         case OP_PUSHMARK:
4041             goto do_next;
4042
4043         case OP_RV2AV:
4044             if (cUNOPo->op_first->op_type != OP_GV) goto badref;
4045             o->op_flags |= OPf_STACKED;
4046             if (o->op_flags & OPf_PARENS) {
4047                 if (o->op_private & OPpLVAL_INTRO) {
4048                      yyerror(Perl_form(aTHX_ "Can't modify reference to "
4049                           "localized parenthesized array in list assignment"));
4050                     goto do_next;
4051                 }
4052               slurpy:
4053                 OpTYPE_set(o, OP_LVAVREF);
4054                 o->op_private &= OPpLVAL_INTRO|OPpPAD_STATE;
4055                 o->op_flags |= OPf_MOD|OPf_REF;
4056                 goto do_next;
4057             }
4058             o->op_private |= OPpLVREF_AV;
4059             goto checkgv;
4060
4061         case OP_RV2CV:
4062             kid = cUNOPo->op_first;
4063             if (kid->op_type == OP_NULL)
4064                 kid = cUNOPx(OpSIBLING(kUNOP->op_first))
4065                     ->op_first;
4066             o->op_private = OPpLVREF_CV;
4067             if (kid->op_type == OP_GV)
4068                 o->op_flags |= OPf_STACKED;
4069             else if (kid->op_type == OP_PADCV) {
4070                 o->op_targ = kid->op_targ;
4071                 kid->op_targ = 0;
4072                 op_free(cUNOPo->op_first);
4073                 cUNOPo->op_first = NULL;
4074                 o->op_flags &=~ OPf_KIDS;
4075             }
4076             else goto badref;
4077             break;
4078
4079         case OP_RV2HV:
4080             if (o->op_flags & OPf_PARENS) {
4081               parenhash:
4082                 yyerror(Perl_form(aTHX_ "Can't modify reference to "
4083                                      "parenthesized hash in list assignment"));
4084                     goto do_next;
4085             }
4086             o->op_private |= OPpLVREF_HV;
4087             /* FALLTHROUGH */
4088         case OP_RV2SV:
4089           checkgv:
4090             if (cUNOPo->op_first->op_type != OP_GV) goto badref;
4091             o->op_flags |= OPf_STACKED;
4092             break;
4093
4094         case OP_PADHV:
4095             if (o->op_flags & OPf_PARENS) goto parenhash;
4096             o->op_private |= OPpLVREF_HV;
4097             /* FALLTHROUGH */
4098         case OP_PADSV:
4099             PAD_COMPNAME_GEN_set(o->op_targ, PERL_INT_MAX);
4100             break;
4101
4102         case OP_PADAV:
4103             PAD_COMPNAME_GEN_set(o->op_targ, PERL_INT_MAX);
4104             if (o->op_flags & OPf_PARENS) goto slurpy;
4105             o->op_private |= OPpLVREF_AV;
4106             break;
4107
4108         case OP_AELEM:
4109         case OP_HELEM:
4110             o->op_private |= OPpLVREF_ELEM;
4111             o->op_flags   |= OPf_STACKED;
4112             break;
4113
4114         case OP_ASLICE:
4115         case OP_HSLICE:
4116             OpTYPE_set(o, OP_LVREFSLICE);
4117             o->op_private &= OPpLVAL_INTRO;
4118             goto do_next;
4119
4120         case OP_NULL:
4121             if (o->op_flags & OPf_SPECIAL)              /* do BLOCK */
4122                 goto badref;
4123             else if (!(o->op_flags & OPf_KIDS))
4124                 goto do_next;
4125
4126             /* the code formerly only recursed into the first child of
4127              * a non ex-list OP_NULL. if we ever encounter such a null op with
4128              * more than one child, need to decide whether its ok to process
4129              * *all* its kids or not */
4130             assert(o->op_targ == OP_LIST
4131                     || !(OpHAS_SIBLING(cBINOPo->op_first)));
4132             /* FALLTHROUGH */
4133         case OP_LIST:
4134             o = cLISTOPo->op_first;
4135             continue;
4136
4137         case OP_STUB:
4138             if (o->op_flags & OPf_PARENS)
4139                 goto do_next;
4140             /* FALLTHROUGH */
4141         default:
4142           badref:
4143             /* diag_listed_as: Can't modify reference to %s in %s assignment */
4144             yyerror(Perl_form(aTHX_ "Can't modify reference to %s in %s",
4145                          o->op_type == OP_NULL && o->op_flags & OPf_SPECIAL
4146                           ? "do block"
4147                           : OP_DESC(o),
4148                          PL_op_desc[type]));
4149             goto do_next;
4150         }
4151
4152         OpTYPE_set(o, OP_LVREF);
4153         o->op_private &=
4154             OPpLVAL_INTRO|OPpLVREF_ELEM|OPpLVREF_TYPE|OPpPAD_STATE;
4155         if (type == OP_ENTERLOOP)
4156             o->op_private |= OPpLVREF_ITER;
4157
4158       do_next:
4159         while (1) {
4160             if (o == top_op)
4161                 return; /* at top; no parents/siblings to try */
4162             if (OpHAS_SIBLING(o)) {
4163                 o = o->op_sibparent;
4164                 break;
4165             }
4166             o = o->op_sibparent; /*try parent's next sibling */
4167         }
4168     } /* while */
4169 }
4170
4171
4172 PERL_STATIC_INLINE bool
4173 S_potential_mod_type(I32 type)
4174 {
4175     /* Types that only potentially result in modification.  */
4176     return type == OP_GREPSTART || type == OP_ENTERSUB
4177         || type == OP_REFGEN    || type == OP_LEAVESUBLV;
4178 }
4179
4180
4181 /*
4182 =for apidoc op_lvalue
4183
4184 Propagate lvalue ("modifiable") context to an op and its children.
4185 C<type> represents the context type, roughly based on the type of op that
4186 would do the modifying, although C<local()> is represented by C<OP_NULL>,
4187 because it has no op type of its own (it is signalled by a flag on
4188 the lvalue op).
4189
4190 This function detects things that can't be modified, such as C<$x+1>, and
4191 generates errors for them.  For example, C<$x+1 = 2> would cause it to be
4192 called with an op of type C<OP_ADD> and a C<type> argument of C<OP_SASSIGN>.
4193
4194 It also flags things that need to behave specially in an lvalue context,
4195 such as C<$$x = 5> which might have to vivify a reference in C<$x>.
4196
4197 =cut
4198
4199 Perl_op_lvalue_flags() is a non-API lower-level interface to
4200 op_lvalue().  The flags param has these bits:
4201     OP_LVALUE_NO_CROAK:  return rather than croaking on error
4202
4203 */
4204
4205 OP *
4206 Perl_op_lvalue_flags(pTHX_ OP *o, I32 type, U32 flags)
4207 {
4208     dVAR;
4209     OP *top_op = o;
4210
4211     if (!o || (PL_parser && PL_parser->error_count))
4212         return o;
4213
4214     while (1) {
4215     OP *kid;
4216     /* -1 = error on localize, 0 = ignore localize, 1 = ok to localize */
4217     int localize = -1;
4218     OP *next_kid = NULL;
4219
4220     if ((o->op_private & OPpTARGET_MY)
4221         && (PL_opargs[o->op_type] & OA_TARGLEX))/* OPp share the meaning */
4222     {
4223         goto do_next;
4224     }
4225
4226     /* elements of a list might be in void context because the list is
4227        in scalar context or because they are attribute sub calls */
4228     if ((o->op_flags & OPf_WANT) == OPf_WANT_VOID)
4229         goto do_next;
4230
4231     if (type == OP_PRTF || type == OP_SPRINTF) type = OP_ENTERSUB;
4232
4233     switch (o->op_type) {
4234     case OP_UNDEF:
4235         PL_modcount++;
4236         goto do_next;
4237
4238     case OP_STUB:
4239         if ((o->op_flags & OPf_PARENS))
4240             break;
4241         goto nomod;
4242
4243     case OP_ENTERSUB:
4244         if ((type == OP_UNDEF || type == OP_REFGEN || type == OP_LOCK) &&
4245             !(o->op_flags & OPf_STACKED)) {
4246             OpTYPE_set(o, OP_RV2CV);            /* entersub => rv2cv */
4247             assert(cUNOPo->op_first->op_type == OP_NULL);
4248             op_null(((LISTOP*)cUNOPo->op_first)->op_first);/* disable pushmark */
4249             break;
4250         }
4251         else {                          /* lvalue subroutine call */
4252             o->op_private |= OPpLVAL_INTRO;
4253             PL_modcount = RETURN_UNLIMITED_NUMBER;
4254             if (S_potential_mod_type(type)) {
4255                 o->op_private |= OPpENTERSUB_INARGS;
4256                 break;
4257             }
4258             else {                      /* Compile-time error message: */
4259                 OP *kid = cUNOPo->op_first;
4260                 CV *cv;
4261                 GV *gv;
4262                 SV *namesv;
4263
4264                 if (kid->op_type != OP_PUSHMARK) {
4265                     if (kid->op_type != OP_NULL || kid->op_targ != OP_LIST)
4266                         Perl_croak(aTHX_
4267                                 "panic: unexpected lvalue entersub "
4268                                 "args: type/targ %ld:%" UVuf,
4269                                 (long)kid->op_type, (UV)kid->op_targ);
4270                     kid = kLISTOP->op_first;
4271                 }
4272                 while (OpHAS_SIBLING(kid))
4273                     kid = OpSIBLING(kid);
4274                 if (!(kid->op_type == OP_NULL && kid->op_targ == OP_RV2CV)) {
4275                     break;      /* Postpone until runtime */
4276                 }
4277
4278                 kid = kUNOP->op_first;
4279                 if (kid->op_type == OP_NULL && kid->op_targ == OP_RV2SV)
4280                     kid = kUNOP->op_first;
4281                 if (kid->op_type == OP_NULL)
4282                     Perl_croak(aTHX_
4283                                "Unexpected constant lvalue entersub "
4284                                "entry via type/targ %ld:%" UVuf,
4285                                (long)kid->op_type, (UV)kid->op_targ);
4286                 if (kid->op_type != OP_GV) {
4287                     break;
4288                 }
4289
4290                 gv = kGVOP_gv;
4291                 cv = isGV(gv)
4292                     ? GvCV(gv)
4293                     : SvROK(gv) && SvTYPE(SvRV(gv)) == SVt_PVCV
4294                         ? MUTABLE_CV(SvRV(gv))
4295                         : NULL;
4296                 if (!cv)
4297                     break;
4298                 if (CvLVALUE(cv))
4299                     break;
4300                 if (flags & OP_LVALUE_NO_CROAK)
4301                     return NULL;
4302
4303                 namesv = cv_name(cv, NULL, 0);
4304                 yyerror_pv(Perl_form(aTHX_ "Can't modify non-lvalue "
4305                                      "subroutine call of &%" SVf " in %s",
4306                                      SVfARG(namesv), PL_op_desc[type]),
4307                            SvUTF8(namesv));
4308                 goto do_next;
4309             }
4310         }
4311         /* FALLTHROUGH */
4312     default:
4313       nomod:
4314         if (flags & OP_LVALUE_NO_CROAK) return NULL;
4315         /* grep, foreach, subcalls, refgen */
4316         if (S_potential_mod_type(type))
4317             break;
4318         yyerror(Perl_form(aTHX_ "Can't modify %s in %s",
4319                      (o->op_type == OP_NULL && (o->op_flags & OPf_SPECIAL)
4320                       ? "do block"
4321                       : OP_DESC(o)),
4322                      type ? PL_op_desc[type] : "local"));
4323         goto do_next;
4324
4325     case OP_PREINC:
4326     case OP_PREDEC:
4327     case OP_POW:
4328     case OP_MULTIPLY:
4329     case OP_DIVIDE:
4330     case OP_MODULO:
4331     case OP_ADD:
4332     case OP_SUBTRACT:
4333     case OP_CONCAT:
4334     case OP_LEFT_SHIFT:
4335     case OP_RIGHT_SHIFT:
4336     case OP_BIT_AND:
4337     case OP_BIT_XOR:
4338     case OP_BIT_OR:
4339     case OP_I_MULTIPLY:
4340     case OP_I_DIVIDE:
4341     case OP_I_MODULO:
4342     case OP_I_ADD:
4343     case OP_I_SUBTRACT:
4344         if (!(o->op_flags & OPf_STACKED))
4345             goto nomod;
4346         PL_modcount++;
4347         break;
4348
4349     case OP_REPEAT:
4350         if (o->op_flags & OPf_STACKED) {
4351             PL_modcount++;
4352             break;
4353         }
4354         if (!(o->op_private & OPpREPEAT_DOLIST))
4355             goto nomod;
4356         else {
4357             const I32 mods = PL_modcount;
4358             /* we recurse rather than iterate here because we need to
4359              * calculate and use the delta applied to PL_modcount by the
4360              * first child. So in something like
4361              *     ($x, ($y) x 3) = split;
4362              * split knows that 4 elements are wanted
4363              */
4364             modkids(cBINOPo->op_first, type);
4365             if (type != OP_AASSIGN)
4366                 goto nomod;
4367             kid = cBINOPo->op_last;
4368             if (kid->op_type == OP_CONST && SvIOK(kSVOP_sv)) {
4369                 const IV iv = SvIV(kSVOP_sv);
4370                 if (PL_modcount != RETURN_UNLIMITED_NUMBER)
4371                     PL_modcount =
4372                         mods + (PL_modcount - mods) * (iv < 0 ? 0 : iv);
4373             }
4374             else
4375                 PL_modcount = RETURN_UNLIMITED_NUMBER;
4376         }
4377         break;
4378
4379     case OP_COND_EXPR:
4380         localize = 1;
4381         next_kid = OpSIBLING(cUNOPo->op_first);
4382         break;
4383
4384     case OP_RV2AV:
4385     case OP_RV2HV:
4386         if (type == OP_REFGEN && o->op_flags & OPf_PARENS) {
4387            PL_modcount = RETURN_UNLIMITED_NUMBER;
4388            /* Treat \(@foo) like ordinary list, but still mark it as modi-
4389               fiable since some contexts need to know.  */
4390            o->op_flags |= OPf_MOD;
4391            goto do_next;
4392         }
4393         /* FALLTHROUGH */
4394     case OP_RV2GV:
4395         if (scalar_mod_type(o, type))
4396             goto nomod;
4397         ref(cUNOPo->op_first, o->op_type);
4398         /* FALLTHROUGH */
4399     case OP_ASLICE:
4400     case OP_HSLICE:
4401         localize = 1;
4402         /* FALLTHROUGH */
4403     case OP_AASSIGN:
4404         /* Do not apply the lvsub flag for rv2[ah]v in scalar context.  */
4405         if (type == OP_LEAVESUBLV && (
4406                 (o->op_type != OP_RV2AV && o->op_type != OP_RV2HV)
4407              || (o->op_flags & OPf_WANT) != OPf_WANT_SCALAR
4408            ))
4409             o->op_private |= OPpMAYBE_LVSUB;
4410         /* FALLTHROUGH */
4411     case OP_NEXTSTATE:
4412     case OP_DBSTATE:
4413        PL_modcount = RETURN_UNLIMITED_NUMBER;
4414         break;
4415
4416     case OP_KVHSLICE:
4417     case OP_KVASLICE:
4418     case OP_AKEYS:
4419         if (type == OP_LEAVESUBLV)
4420             o->op_private |= OPpMAYBE_LVSUB;
4421         goto nomod;
4422
4423     case OP_AVHVSWITCH:
4424         if (type == OP_LEAVESUBLV
4425          && (o->op_private & OPpAVHVSWITCH_MASK) + OP_EACH == OP_KEYS)
4426             o->op_private |= OPpMAYBE_LVSUB;
4427         goto nomod;
4428
4429     case OP_AV2ARYLEN:
4430         PL_hints |= HINT_BLOCK_SCOPE;
4431         if (type == OP_LEAVESUBLV)
4432             o->op_private |= OPpMAYBE_LVSUB;
4433         PL_modcount++;
4434         break;
4435
4436     case OP_RV2SV:
4437         ref(cUNOPo->op_first, o->op_type);
4438         localize = 1;
4439         /* FALLTHROUGH */
4440     case OP_GV:
4441         PL_hints |= HINT_BLOCK_SCOPE;
4442         /* FALLTHROUGH */
4443     case OP_SASSIGN:
4444     case OP_ANDASSIGN:
4445     case OP_ORASSIGN:
4446     case OP_DORASSIGN:
4447         PL_modcount++;
4448         break;
4449
4450     case OP_AELEMFAST:
4451     case OP_AELEMFAST_LEX:
4452         localize = -1;
4453         PL_modcount++;
4454         break;
4455
4456     case OP_PADAV:
4457     case OP_PADHV:
4458        PL_modcount = RETURN_UNLIMITED_NUMBER;
4459         if (type == OP_REFGEN && o->op_flags & OPf_PARENS)
4460         {
4461            /* Treat \(@foo) like ordinary list, but still mark it as modi-
4462               fiable since some contexts need to know.  */
4463             o->op_flags |= OPf_MOD;
4464             goto do_next;
4465         }
4466         if (scalar_mod_type(o, type))
4467             goto nomod;
4468         if ((o->op_flags & OPf_WANT) != OPf_WANT_SCALAR
4469           && type == OP_LEAVESUBLV)
4470             o->op_private |= OPpMAYBE_LVSUB;
4471         /* FALLTHROUGH */
4472     case OP_PADSV:
4473         PL_modcount++;
4474         if (!type) /* local() */
4475             Perl_croak(aTHX_ "Can't localize lexical variable %" PNf,
4476                               PNfARG(PAD_COMPNAME(o->op_targ)));
4477         if (!(o->op_private & OPpLVAL_INTRO)
4478          || (  type != OP_SASSIGN && type != OP_AASSIGN
4479             && PadnameIsSTATE(PAD_COMPNAME_SV(o->op_targ))  ))
4480             S_mark_padname_lvalue(aTHX_ PAD_COMPNAME_SV(o->op_targ));
4481         break;
4482
4483     case OP_PUSHMARK:
4484         localize = 0;
4485         break;
4486
4487     case OP_KEYS:
4488         if (type != OP_LEAVESUBLV && !scalar_mod_type(NULL, type))
4489             goto nomod;
4490         goto lvalue_func;
4491     case OP_SUBSTR:
4492         if (o->op_private == 4) /* don't allow 4 arg substr as lvalue */
4493             goto nomod;
4494         /* FALLTHROUGH */
4495     case OP_POS:
4496     case OP_VEC:
4497       lvalue_func:
4498         if (type == OP_LEAVESUBLV)
4499             o->op_private |= OPpMAYBE_LVSUB;
4500         if (o->op_flags & OPf_KIDS && OpHAS_SIBLING(cBINOPo->op_first)) {
4501             /* we recurse rather than iterate here because the child
4502              * needs to be processed with a different 'type' parameter */
4503
4504             /* substr and vec */
4505             /* If this op is in merely potential (non-fatal) modifiable
4506                context, then apply OP_ENTERSUB context to
4507                the kid op (to avoid croaking).  Other-
4508                wise pass this op’s own type so the correct op is mentioned
4509                in error messages.  */
4510             op_lvalue(OpSIBLING(cBINOPo->op_first),
4511                       S_potential_mod_type(type)
4512                         ? (I32)OP_ENTERSUB
4513                         : o->op_type);
4514         }
4515         break;
4516
4517     case OP_AELEM:
4518     case OP_HELEM:
4519         ref(cBINOPo->op_first, o->op_type);
4520         if (type == OP_ENTERSUB &&
4521              !(o->op_private & (OPpLVAL_INTRO | OPpDEREF)))
4522             o->op_private |= OPpLVAL_DEFER;
4523         if (type == OP_LEAVESUBLV)
4524             o->op_private |= OPpMAYBE_LVSUB;
4525         localize = 1;
4526         PL_modcount++;
4527         break;
4528
4529     case OP_LEAVE:
4530     case OP_LEAVELOOP:
4531         o->op_private |= OPpLVALUE;
4532         /* FALLTHROUGH */
4533     case OP_SCOPE:
4534     case OP_ENTER:
4535     case OP_LINESEQ:
4536         localize = 0;
4537         if (o->op_flags & OPf_KIDS)
4538             next_kid = cLISTOPo->op_last;
4539         break;
4540
4541     case OP_NULL:
4542         localize = 0;
4543         if (o->op_flags & OPf_SPECIAL)          /* do BLOCK */
4544             goto nomod;
4545         else if (!(o->op_flags & OPf_KIDS))
4546             break;
4547
4548         if (o->op_targ != OP_LIST) {
4549             OP *sib = OpSIBLING(cLISTOPo->op_first);
4550             /* OP_TRANS and OP_TRANSR with argument have a weird optree
4551              * that looks like
4552              *
4553              *   null
4554              *      arg
4555              *      trans
4556              *
4557              * compared with things like OP_MATCH which have the argument
4558              * as a child:
4559              *
4560              *   match
4561              *      arg
4562              *
4563              * so handle specially to correctly get "Can't modify" croaks etc
4564              */
4565
4566             if (sib && (sib->op_type == OP_TRANS || sib->op_type == OP_TRANSR))
4567             {
4568                 /* this should trigger a "Can't modify transliteration" err */
4569                 op_lvalue(sib, type);
4570             }
4571             next_kid = cBINOPo->op_first;
4572             /* we assume OP_NULLs which aren't ex-list have no more than 2
4573              * children. If this assumption is wrong, increase the scan
4574              * limit below */
4575             assert(   !OpHAS_SIBLING(next_kid)
4576                    || !OpHAS_SIBLING(OpSIBLING(next_kid)));
4577             break;
4578         }
4579         /* FALLTHROUGH */
4580     case OP_LIST:
4581         localize = 0;
4582         next_kid = cLISTOPo->op_first;
4583         break;
4584
4585     case OP_COREARGS:
4586         goto do_next;
4587
4588     case OP_AND:
4589     case OP_OR:
4590         if (type == OP_LEAVESUBLV
4591          || !S_vivifies(cLOGOPo->op_first->op_type))
4592             next_kid = cLOGOPo->op_first;
4593         else if (type == OP_LEAVESUBLV
4594          || !S_vivifies(OpSIBLING(cLOGOPo->op_first)->op_type))
4595             next_kid = OpSIBLING(cLOGOPo->op_first);
4596         goto nomod;
4597
4598     case OP_SREFGEN:
4599         if (type == OP_NULL) { /* local */
4600           local_refgen:
4601             if (!FEATURE_MYREF_IS_ENABLED)
4602                 Perl_croak(aTHX_ "The experimental declared_refs "
4603                                  "feature is not enabled");
4604             Perl_ck_warner_d(aTHX_
4605                      packWARN(WARN_EXPERIMENTAL__DECLARED_REFS),
4606                     "Declaring references is experimental");
4607             next_kid = cUNOPo->op_first;
4608             goto do_next;
4609         }
4610         if (type != OP_AASSIGN && type != OP_SASSIGN
4611          && type != OP_ENTERLOOP)
4612             goto nomod;
4613         /* Don’t bother applying lvalue context to the ex-list.  */
4614         kid = cUNOPx(cUNOPo->op_first)->op_first;
4615         assert (!OpHAS_SIBLING(kid));
4616         goto kid_2lvref;
4617     case OP_REFGEN:
4618         if (type == OP_NULL) /* local */
4619             goto local_refgen;
4620         if (type != OP_AASSIGN) goto nomod;
4621         kid = cUNOPo->op_first;
4622       kid_2lvref:
4623         {
4624             const U8 ec = PL_parser ? PL_parser->error_count : 0;
4625             S_lvref(aTHX_ kid, type);
4626             if (!PL_parser || PL_parser->error_count == ec) {
4627                 if (!FEATURE_REFALIASING_IS_ENABLED)
4628                     Perl_croak(aTHX_
4629                        "Experimental aliasing via reference not enabled");
4630                 Perl_ck_warner_d(aTHX_
4631                                  packWARN(WARN_EXPERIMENTAL__REFALIASING),
4632                                 "Aliasing via reference is experimental");
4633             }
4634         }
4635         if (o->op_type == OP_REFGEN)
4636             op_null(cUNOPx(cUNOPo->op_first)->op_first); /* pushmark */
4637         op_null(o);
4638         goto do_next;
4639
4640     case OP_SPLIT:
4641         if ((o->op_private & OPpSPLIT_ASSIGN)) {
4642             /* This is actually @array = split.  */
4643             PL_modcount = RETURN_UNLIMITED_NUMBER;
4644             break;
4645         }
4646         goto nomod;
4647
4648     case OP_SCALAR:
4649         op_lvalue(cUNOPo->op_first, OP_ENTERSUB);
4650         goto nomod;
4651     }
4652
4653     /* [20011101.069 (#7861)] File test operators interpret OPf_REF to mean that
4654        their argument is a filehandle; thus \stat(".") should not set
4655        it. AMS 20011102 */
4656     if (type == OP_REFGEN && OP_IS_STAT(o->op_type))
4657         goto do_next;
4658
4659     if (type != OP_LEAVESUBLV)
4660         o->op_flags |= OPf_MOD;
4661
4662     if (type == OP_AASSIGN || type == OP_SASSIGN)
4663         o->op_flags |= OPf_SPECIAL
4664                       |(o->op_type == OP_ENTERSUB ? 0 : OPf_REF);
4665     else if (!type) { /* local() */
4666         switch (localize) {
4667         case 1:
4668             o->op_private |= OPpLVAL_INTRO;
4669             o->op_flags &= ~OPf_SPECIAL;
4670             PL_hints |= HINT_BLOCK_SCOPE;
4671             break;
4672         case 0:
4673             break;
4674         case -1:
4675             Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX),
4676                            "Useless localization of %s", OP_DESC(o));
4677         }
4678     }
4679     else if (type != OP_GREPSTART && type != OP_ENTERSUB
4680              && type != OP_LEAVESUBLV && o->op_type != OP_ENTERSUB)
4681         o->op_flags |= OPf_REF;
4682
4683   do_next:
4684     while (!next_kid) {
4685         if (o == top_op)
4686             return top_op; /* at top; no parents/siblings to try */
4687         if (OpHAS_SIBLING(o)) {
4688             next_kid = o->op_sibparent;
4689             if (!OpHAS_SIBLING(next_kid)) {
4690                 /* a few node types don't recurse into their second child */
4691                 OP *parent = next_kid->op_sibparent;
4692                 I32 ptype  = parent->op_type;
4693                 if (   (ptype == OP_NULL && parent->op_targ != OP_LIST)
4694                     || (   (ptype == OP_AND || ptype == OP_OR)
4695                         && (type != OP_LEAVESUBLV 
4696                             && S_vivifies(next_kid->op_type))
4697                        )
4698                 )  {
4699                     /*try parent's next sibling */
4700                     o = parent;
4701                     next_kid =  NULL;
4702                 }
4703             }
4704         }
4705         else
4706             o = o->op_sibparent; /*try parent's next sibling */
4707
4708     }
4709     o = next_kid;
4710
4711     } /* while */
4712
4713 }
4714
4715
4716 STATIC bool
4717 S_scalar_mod_type(const OP *o, I32 type)
4718 {
4719     switch (type) {
4720     case OP_POS:
4721     case OP_SASSIGN:
4722         if (o && o->op_type == OP_RV2GV)
4723             return FALSE;
4724         /* FALLTHROUGH */
4725     case OP_PREINC:
4726     case OP_PREDEC:
4727     case OP_POSTINC:
4728     case OP_POSTDEC:
4729     case OP_I_PREINC:
4730     case OP_I_PREDEC:
4731     case OP_I_POSTINC:
4732     case OP_I_POSTDEC:
4733     case OP_POW:
4734     case OP_MULTIPLY:
4735     case OP_DIVIDE:
4736     case OP_MODULO:
4737     case OP_REPEAT:
4738     case OP_ADD:
4739     case OP_SUBTRACT:
4740     case OP_I_MULTIPLY:
4741     case OP_I_DIVIDE:
4742     case OP_I_MODULO:
4743     case OP_I_ADD:
4744     case OP_I_SUBTRACT:
4745     case OP_LEFT_SHIFT:
4746     case OP_RIGHT_SHIFT:
4747     case OP_BIT_AND:
4748     case OP_BIT_XOR:
4749     case OP_BIT_OR:
4750     case OP_NBIT_AND:
4751     case OP_NBIT_XOR:
4752     case OP_NBIT_OR:
4753     case OP_SBIT_AND:
4754     case OP_SBIT_XOR:
4755     case OP_SBIT_OR:
4756     case OP_CONCAT:
4757     case OP_SUBST:
4758     case OP_TRANS:
4759     case OP_TRANSR:
4760     case OP_READ:
4761     case OP_SYSREAD:
4762     case OP_RECV:
4763     case OP_ANDASSIGN:
4764     case OP_ORASSIGN:
4765     case OP_DORASSIGN:
4766     case OP_VEC:
4767     case OP_SUBSTR:
4768         return TRUE;
4769     default:
4770         return FALSE;
4771     }
4772 }
4773
4774 STATIC bool
4775 S_is_handle_constructor(const OP *o, I32 numargs)
4776 {
4777     PERL_ARGS_ASSERT_IS_HANDLE_CONSTRUCTOR;
4778
4779     switch (o->op_type) {
4780     case OP_PIPE_OP:
4781     case OP_SOCKPAIR:
4782         if (numargs == 2)
4783             return TRUE;
4784         /* FALLTHROUGH */
4785     case OP_SYSOPEN:
4786     case OP_OPEN:
4787     case OP_SELECT:             /* XXX c.f. SelectSaver.pm */
4788     case OP_SOCKET:
4789     case OP_OPEN_DIR:
4790     case OP_ACCEPT:
4791         if (numargs == 1)
4792             return TRUE;
4793         /* FALLTHROUGH */
4794     default:
4795         return FALSE;
4796     }
4797 }
4798
4799 static OP *
4800 S_refkids(pTHX_ OP *o, I32 type)
4801 {
4802     if (o && o->op_flags & OPf_KIDS) {
4803         OP *kid;
4804         for (kid = cLISTOPo->op_first; kid; kid = OpSIBLING(kid))
4805             ref(kid, type);
4806     }
4807     return o;
4808 }
4809
4810
4811 /* Apply reference (autovivification) context to the subtree at o.
4812  * For example in
4813  *     push @{expression}, ....;
4814  * o will be the head of 'expression' and type will be OP_RV2AV.
4815  * It marks the op o (or a suitable child) as autovivifying, e.g. by
4816  * setting  OPf_MOD.
4817  * For OP_RV2AV/OP_PADAV and OP_RV2HV/OP_PADHV sets OPf_REF too if
4818  * set_op_ref is true.
4819  *
4820  * Also calls scalar(o).
4821  */
4822
4823 OP *
4824 Perl_doref(pTHX_ OP *o, I32 type, bool set_op_ref)
4825 {
4826     dVAR;
4827     OP * top_op = o;
4828
4829     PERL_ARGS_ASSERT_DOREF;
4830
4831     if (PL_parser && PL_parser->error_count)
4832         return o;
4833
4834     while (1) {
4835         switch (o->op_type) {
4836         case OP_ENTERSUB:
4837             if ((type == OP_EXISTS || type == OP_DEFINED) &&
4838                 !(o->op_flags & OPf_STACKED)) {
4839                 OpTYPE_set(o, OP_RV2CV);             /* entersub => rv2cv */
4840                 assert(cUNOPo->op_first->op_type == OP_NULL);
4841                 /* disable pushmark */
4842                 op_null(((LISTOP*)cUNOPo->op_first)->op_first);
4843                 o->op_flags |= OPf_SPECIAL;
4844             }
4845             else if (type == OP_RV2SV || type == OP_RV2AV || type == OP_RV2HV){
4846                 o->op_private |= (type == OP_RV2AV ? OPpDEREF_AV
4847                                   : type == OP_RV2HV ? OPpDEREF_HV
4848                                   : OPpDEREF_SV);
4849                 o->op_flags |= OPf_MOD;
4850             }
4851
4852             break;
4853
4854         case OP_COND_EXPR:
4855             o = OpSIBLING(cUNOPo->op_first);
4856             continue;
4857
4858         case OP_RV2SV:
4859             if (type == OP_DEFINED)
4860                 o->op_flags |= OPf_SPECIAL;             /* don't create GV */
4861             /* FALLTHROUGH */
4862         case OP_PADSV:
4863             if (type == OP_RV2SV || type == OP_RV2AV || type == OP_RV2HV) {
4864                 o->op_private |= (type == OP_RV2AV ? OPpDEREF_AV
4865                                   : type == OP_RV2HV ? OPpDEREF_HV
4866                                   : OPpDEREF_SV);
4867                 o->op_flags |= OPf_MOD;
4868             }
4869             if (o->op_flags & OPf_KIDS) {
4870                 type = o->op_type;
4871                 o = cUNOPo->op_first;
4872                 continue;
4873             }
4874             break;
4875
4876         case OP_RV2AV:
4877         case OP_RV2HV:
4878             if (set_op_ref)
4879                 o->op_flags |= OPf_REF;
4880             /* FALLTHROUGH */
4881         case OP_RV2GV:
4882             if (type == OP_DEFINED)
4883                 o->op_flags |= OPf_SPECIAL;             /* don't create GV */
4884             type = o->op_type;
4885             o = cUNOPo->op_first;
4886             continue;
4887
4888         case OP_PADAV:
4889         case OP_PADHV:
4890             if (set_op_ref)
4891                 o->op_flags |= OPf_REF;
4892             break;
4893
4894         case OP_SCALAR:
4895         case OP_NULL:
4896             if (!(o->op_flags & OPf_KIDS) || type == OP_DEFINED)
4897                 break;
4898              o = cBINOPo->op_first;
4899             continue;
4900
4901         case OP_AELEM:
4902         case OP_HELEM:
4903             if (type == OP_RV2SV || type == OP_RV2AV || type == OP_RV2HV) {
4904                 o->op_private |= (type == OP_RV2AV ? OPpDEREF_AV
4905                                   : type == OP_RV2HV ? OPpDEREF_HV
4906                                   : OPpDEREF_SV);
4907                 o->op_flags |= OPf_MOD;
4908             }
4909             type = o->op_type;
4910             o = cBINOPo->op_first;
4911             continue;;
4912
4913         case OP_SCOPE:
4914         case OP_LEAVE:
4915             set_op_ref = FALSE;
4916             /* FALLTHROUGH */
4917         case OP_ENTER:
4918         case OP_LIST:
4919             if (!(o->op_flags & OPf_KIDS))
4920                 break;
4921             o = cLISTOPo->op_last;
4922             continue;
4923
4924         default:
4925             break;
4926         } /* switch */
4927
4928         while (1) {
4929             if (o == top_op)
4930                 return scalar(top_op); /* at top; no parents/siblings to try */
4931             if (OpHAS_SIBLING(o)) {
4932                 o = o->op_sibparent;
4933                 /* Normally skip all siblings and go straight to the parent;
4934                  * the only op that requires two children to be processed
4935                  * is OP_COND_EXPR */
4936                 if (!OpHAS_SIBLING(o)
4937                         && o->op_sibparent->op_type == OP_COND_EXPR)
4938                     break;
4939                 continue;
4940             }
4941             o = o->op_sibparent; /*try parent's next sibling */
4942         }
4943     } /* while */
4944 }
4945
4946
4947 STATIC OP *
4948 S_dup_attrlist(pTHX_ OP *o)
4949 {
4950     OP *rop;
4951
4952     PERL_ARGS_ASSERT_DUP_ATTRLIST;
4953
4954     /* An attrlist is either a simple OP_CONST or an OP_LIST with kids,
4955      * where the first kid is OP_PUSHMARK and the remaining ones
4956      * are OP_CONST.  We need to push the OP_CONST values.
4957      */
4958     if (o->op_type == OP_CONST)
4959         rop = newSVOP(OP_CONST, o->op_flags, SvREFCNT_inc_NN(cSVOPo->op_sv));
4960     else {
4961         assert((o->op_type == OP_LIST) && (o->op_flags & OPf_KIDS));
4962         rop = NULL;
4963         for (o = cLISTOPo->op_first; o; o = OpSIBLING(o)) {
4964             if (o->op_type == OP_CONST)
4965                 rop = op_append_elem(OP_LIST, rop,
4966                                   newSVOP(OP_CONST, o->op_flags,
4967                                           SvREFCNT_inc_NN(cSVOPo->op_sv)));
4968         }
4969     }
4970     return rop;
4971 }
4972
4973 STATIC void
4974 S_apply_attrs(pTHX_ HV *stash, SV *target, OP *attrs)
4975 {
4976     PERL_ARGS_ASSERT_APPLY_ATTRS;
4977     {
4978         SV * const stashsv = newSVhek(HvNAME_HEK(stash));
4979
4980         /* fake up C<use attributes $pkg,$rv,@attrs> */
4981
4982 #define ATTRSMODULE "attributes"
4983 #define ATTRSMODULE_PM "attributes.pm"
4984
4985         Perl_load_module(
4986           aTHX_ PERL_LOADMOD_IMPORT_OPS,
4987           newSVpvs(ATTRSMODULE),
4988           NULL,
4989           op_prepend_elem(OP_LIST,
4990                           newSVOP(OP_CONST, 0, stashsv),
4991                           op_prepend_elem(OP_LIST,
4992                                           newSVOP(OP_CONST, 0,
4993                                                   newRV(target)),
4994                                           dup_attrlist(attrs))));
4995     }
4996 }
4997
4998 STATIC void
4999 S_apply_attrs_my(pTHX_ HV *stash, OP *target, OP *attrs, OP **imopsp)
5000 {
5001     OP *pack, *imop, *arg;
5002     SV *meth, *stashsv, **svp;
5003
5004     PERL_ARGS_ASSERT_APPLY_ATTRS_MY;
5005
5006     if (!attrs)
5007         return;
5008
5009     assert(target->op_type == OP_PADSV ||
5010            target->op_type == OP_PADHV ||
5011            target->op_type == OP_PADAV);
5012
5013     /* Ensure that attributes.pm is loaded. */
5014     /* Don't force the C<use> if we don't need it. */
5015     svp = hv_fetchs(GvHVn(PL_incgv), ATTRSMODULE_PM, FALSE);
5016     if (svp && *svp != &PL_sv_undef)
5017         NOOP;   /* already in %INC */
5018     else
5019         Perl_load_module(aTHX_ PERL_LOADMOD_NOIMPORT,
5020                                newSVpvs(ATTRSMODULE), NULL);
5021
5022     /* Need package name for method call. */
5023     pack = newSVOP(OP_CONST, 0, newSVpvs(ATTRSMODULE));
5024
5025     /* Build up the real arg-list. */
5026     stashsv = newSVhek(HvNAME_HEK(stash));
5027
5028     arg = newOP(OP_PADSV, 0);
5029     arg->op_targ = target->op_targ;
5030     arg = op_prepend_elem(OP_LIST,
5031                        newSVOP(OP_CONST, 0, stashsv),
5032                        op_prepend_elem(OP_LIST,
5033                                     newUNOP(OP_REFGEN, 0,
5034                                             arg),
5035                                     dup_attrlist(attrs)));
5036
5037     /* Fake up a method call to import */
5038     meth = newSVpvs_share("import");
5039     imop = op_convert_list(OP_ENTERSUB, OPf_STACKED|OPf_SPECIAL|OPf_WANT_VOID,
5040                    op_append_elem(OP_LIST,
5041                                op_prepend_elem(OP_LIST, pack, arg),
5042                                newMETHOP_named(OP_METHOD_NAMED, 0, meth)));
5043
5044     /* Combine the ops. */
5045     *imopsp = op_append_elem(OP_LIST, *imopsp, imop);
5046 }
5047
5048 /*
5049 =notfor apidoc apply_attrs_string
5050
5051 Attempts to apply a list of attributes specified by the C<attrstr> and
5052 C<len> arguments to the subroutine identified by the C<cv> argument which
5053 is expected to be associated with the package identified by the C<stashpv>
5054 argument (see L<attributes>).  It gets this wrong, though, in that it
5055 does not correctly identify the boundaries of the individual attribute
5056 specifications within C<attrstr>.  This is not really intended for the
5057 public API, but has to be listed here for systems such as AIX which
5058 need an explicit export list for symbols.  (It's called from XS code
5059 in support of the C<ATTRS:> keyword from F<xsubpp>.)  Patches to fix it
5060 to respect attribute syntax properly would be welcome.
5061
5062 =cut
5063 */
5064
5065 void
5066 Perl_apply_attrs_string(pTHX_ const char *stashpv, CV *cv,
5067                         const char *attrstr, STRLEN len)
5068 {
5069     OP *attrs = NULL;
5070
5071     PERL_ARGS_ASSERT_APPLY_ATTRS_STRING;
5072
5073     if (!len) {
5074         len = strlen(attrstr);
5075     }
5076
5077     while (len) {
5078         for (; isSPACE(*attrstr) && len; --len, ++attrstr) ;
5079         if (len) {
5080             const char * const sstr = attrstr;
5081             for (; !isSPACE(*attrstr) && len; --len, ++attrstr) ;
5082             attrs = op_append_elem(OP_LIST, attrs,
5083                                 newSVOP(OP_CONST, 0,
5084                                         newSVpvn(sstr, attrstr-sstr)));
5085         }
5086     }
5087
5088     Perl_load_module(aTHX_ PERL_LOADMOD_IMPORT_OPS,
5089                      newSVpvs(ATTRSMODULE),
5090                      NULL, op_prepend_elem(OP_LIST,
5091                                   newSVOP(OP_CONST, 0, newSVpv(stashpv,0)),
5092                                   op_prepend_elem(OP_LIST,
5093                                                newSVOP(OP_CONST, 0,
5094                                                        newRV(MUTABLE_SV(cv))),
5095                                                attrs)));
5096 }
5097
5098 STATIC void
5099 S_move_proto_attr(pTHX_ OP **proto, OP **attrs, const GV * name,
5100                         bool curstash)
5101 {
5102     OP *new_proto = NULL;
5103     STRLEN pvlen;
5104     char *pv;
5105     OP *o;
5106
5107     PERL_ARGS_ASSERT_MOVE_PROTO_ATTR;
5108
5109     if (!*attrs)
5110         return;
5111
5112     o = *attrs;
5113     if (o->op_type == OP_CONST) {
5114         pv = SvPV(cSVOPo_sv, pvlen);
5115         if (memBEGINs(pv, pvlen, "prototype(")) {
5116             SV * const tmpsv = newSVpvn_flags(pv + 10, pvlen - 11, SvUTF8(cSVOPo_sv));
5117             SV ** const tmpo = cSVOPx_svp(o);
5118             SvREFCNT_dec(cSVOPo_sv);
5119             *tmpo = tmpsv;
5120             new_proto = o;
5121             *attrs = NULL;
5122         }
5123     } else if (o->op_type == OP_LIST) {
5124         OP * lasto;
5125         assert(o->op_flags & OPf_KIDS);
5126         lasto = cLISTOPo->op_first;
5127         assert(lasto->op_type == OP_PUSHMARK);
5128         for (o = OpSIBLING(lasto); o; o = OpSIBLING(o)) {
5129             if (o->op_type == OP_CONST) {
5130                 pv = SvPV(cSVOPo_sv, pvlen);
5131                 if (memBEGINs(pv, pvlen, "prototype(")) {
5132                     SV * const tmpsv = newSVpvn_flags(pv + 10, pvlen - 11, SvUTF8(cSVOPo_sv));
5133                     SV ** const tmpo = cSVOPx_svp(o);
5134                     SvREFCNT_dec(cSVOPo_sv);
5135                     *tmpo = tmpsv;
5136                     if (new_proto && ckWARN(WARN_MISC)) {
5137                         STRLEN new_len;
5138                         const char * newp = SvPV(cSVOPo_sv, new_len);
5139                         Perl_warner(aTHX_ packWARN(WARN_MISC),
5140                             "Attribute prototype(%" UTF8f ") discards earlier prototype attribute in same sub",
5141                             UTF8fARG(SvUTF8(cSVOPo_sv), new_len, newp));
5142                         op_free(new_proto);
5143                     }
5144                     else if (new_proto)
5145                         op_free(new_proto);
5146                     new_proto = o;
5147                     /* excise new_proto from the list */
5148                     op_sibling_splice(*attrs, lasto, 1, NULL);
5149                     o = lasto;
5150                     continue;
5151                 }
5152             }
5153             lasto = o;
5154         }
5155         /* If the list is now just the PUSHMARK, scrap the whole thing; otherwise attributes.xs
5156            would get pulled in with no real need */
5157         if (!OpHAS_SIBLING(cLISTOPx(*attrs)->op_first)) {
5158             op_free(*attrs);
5159             *attrs = NULL;
5160         }
5161     }
5162
5163     if (new_proto) {
5164         SV *svname;
5165         if (isGV(name)) {
5166             svname = sv_newmortal();
5167             gv_efullname3(svname, name, NULL);
5168         }
5169         else if (SvPOK(name) && *SvPVX((SV *)name) == '&')
5170             svname = newSVpvn_flags(SvPVX((SV *)name)+1, SvCUR(name)-1, SvUTF8(name)|SVs_TEMP);
5171         else
5172             svname = (SV *)name;
5173         if (ckWARN(WARN_ILLEGALPROTO))
5174             (void)validate_proto(svname, cSVOPx_sv(new_proto), TRUE,
5175                                  curstash);
5176         if (*proto && ckWARN(WARN_PROTOTYPE)) {
5177             STRLEN old_len, new_len;
5178             const char * oldp = SvPV(cSVOPx_sv(*proto), old_len);
5179             const char * newp = SvPV(cSVOPx_sv(new_proto), new_len);
5180
5181             if (curstash && svname == (SV *)name
5182              && !memchr(SvPVX(svname), ':', SvCUR(svname))) {
5183                 svname = sv_2mortal(newSVsv(PL_curstname));
5184                 sv_catpvs(svname, "::");
5185                 sv_catsv(svname, (SV *)name);
5186             }
5187
5188             Perl_warner(aTHX_ packWARN(WARN_PROTOTYPE),
5189                 "Prototype '%" UTF8f "' overridden by attribute 'prototype(%" UTF8f ")'"
5190                 " in %" SVf,
5191                 UTF8fARG(SvUTF8(cSVOPx_sv(*proto)), old_len, oldp),
5192                 UTF8fARG(SvUTF8(cSVOPx_sv(new_proto)), new_len, newp),
5193                 SVfARG(svname));
5194         }
5195         if (*proto)
5196             op_free(*proto);
5197         *proto = new_proto;
5198     }
5199 }
5200
5201 static void
5202 S_cant_declare(pTHX_ OP *o)
5203 {
5204     if (o->op_type == OP_NULL
5205      && (o->op_flags & (OPf_SPECIAL|OPf_KIDS)) == OPf_KIDS)
5206         o = cUNOPo->op_first;
5207     yyerror(Perl_form(aTHX_ "Can't declare %s in \"%s\"",
5208                              o->op_type == OP_NULL
5209                                && o->op_flags & OPf_SPECIAL
5210                                  ? "do block"
5211                                  : OP_DESC(o),
5212                              PL_parser->in_my == KEY_our   ? "our"   :
5213                              PL_parser->in_my == KEY_state ? "state" :
5214                                                              "my"));
5215 }
5216
5217 STATIC OP *
5218 S_my_kid(pTHX_ OP *o, OP *attrs, OP **imopsp)
5219 {
5220     I32 type;
5221     const bool stately = PL_parser && PL_parser->in_my == KEY_state;
5222
5223     PERL_ARGS_ASSERT_MY_KID;
5224
5225     if (!o || (PL_parser && PL_parser->error_count))
5226         return o;
5227
5228     type = o->op_type;
5229
5230     if (OP_TYPE_IS_OR_WAS(o, OP_LIST)) {
5231         OP *kid;
5232         for (kid = cLISTOPo->op_first; kid; kid = OpSIBLING(kid))
5233             my_kid(kid, attrs, imopsp);
5234         return o;
5235     } else if (type == OP_UNDEF || type == OP_STUB) {
5236         return o;
5237     } else if (type == OP_RV2SV ||      /* "our" declaration */
5238                type == OP_RV2AV ||
5239                type == OP_RV2HV) {
5240         if (cUNOPo->op_first->op_type != OP_GV) { /* MJD 20011224 */
5241             S_cant_declare(aTHX_ o);
5242         } else if (attrs) {
5243             GV * const gv = cGVOPx_gv(cUNOPo->op_first);
5244             assert(PL_parser);
5245             PL_parser->in_my = FALSE;
5246             PL_parser->in_my_stash = NULL;
5247             apply_attrs(GvSTASH(gv),
5248                         (type == OP_RV2SV ? GvSVn(gv) :
5249                          type == OP_RV2AV ? MUTABLE_SV(GvAVn(gv)) :
5250                          type == OP_RV2HV ? MUTABLE_SV(GvHVn(gv)) : MUTABLE_SV(gv)),
5251                         attrs);
5252         }
5253         o->op_private |= OPpOUR_INTRO;
5254         return o;
5255     }
5256     else if (type == OP_REFGEN || type == OP_SREFGEN) {
5257         if (!FEATURE_MYREF_IS_ENABLED)
5258             Perl_croak(aTHX_ "The experimental declared_refs "
5259                              "feature is not enabled");
5260         Perl_ck_warner_d(aTHX_
5261              packWARN(WARN_EXPERIMENTAL__DECLARED_REFS),
5262             "Declaring references is experimental");
5263         /* Kid is a nulled OP_LIST, handled above.  */
5264         my_kid(cUNOPo->op_first, attrs, imopsp);
5265         return o;
5266     }
5267     else if (type != OP_PADSV &&
5268              type != OP_PADAV &&
5269              type != OP_PADHV &&
5270              type != OP_PUSHMARK)
5271     {
5272         S_cant_declare(aTHX_ o);
5273         return o;
5274     }
5275     else if (attrs && type != OP_PUSHMARK) {
5276         HV *stash;
5277
5278         assert(PL_parser);
5279         PL_parser->in_my = FALSE;
5280         PL_parser->in_my_stash = NULL;
5281
5282         /* check for C<my Dog $spot> when deciding package */
5283         stash = PAD_COMPNAME_TYPE(o->op_targ);
5284         if (!stash)
5285             stash = PL_curstash;
5286         apply_attrs_my(stash, o, attrs, imopsp);
5287     }
5288     o->op_flags |= OPf_MOD;
5289     o->op_private |= OPpLVAL_INTRO;
5290     if (stately)
5291         o->op_private |= OPpPAD_STATE;
5292     return o;
5293 }
5294
5295 OP *
5296 Perl_my_attrs(pTHX_ OP *o, OP *attrs)
5297 {
5298     OP *rops;
5299     int maybe_scalar = 0;
5300
5301     PERL_ARGS_ASSERT_MY_ATTRS;
5302
5303 /* [perl #17376]: this appears to be premature, and results in code such as
5304    C< our(%x); > executing in list mode rather than void mode */
5305 #if 0
5306     if (o->op_flags & OPf_PARENS)
5307         list(o);
5308     else
5309         maybe_scalar = 1;
5310 #else
5311     maybe_scalar = 1;
5312 #endif
5313     if (attrs)
5314         SAVEFREEOP(attrs);
5315     rops = NULL;
5316     o = my_kid(o, attrs, &rops);
5317     if (rops) {
5318         if (maybe_scalar && o->op_type == OP_PADSV) {
5319             o = scalar(op_append_list(OP_LIST, rops, o));
5320             o->op_private |= OPpLVAL_INTRO;
5321         }
5322         else {
5323             /* The listop in rops might have a pushmark at the beginning,
5324                which will mess up list assignment. */
5325             LISTOP * const lrops = (LISTOP *)rops; /* for brevity */
5326             if (rops->op_type == OP_LIST && 
5327                 lrops->op_first && lrops->op_first->op_type == OP_PUSHMARK)
5328             {
5329                 OP * const pushmark = lrops->op_first;
5330                 /* excise pushmark */
5331                 op_sibling_splice(rops, NULL, 1, NULL);
5332                 op_free(pushmark);
5333             }
5334             o = op_append_list(OP_LIST, o, rops);
5335         }
5336     }
5337     PL_parser->in_my = FALSE;
5338     PL_parser->in_my_stash = NULL;
5339     return o;
5340 }
5341
5342 OP *
5343 Perl_sawparens(pTHX_ OP *o)
5344 {
5345     PERL_UNUSED_CONTEXT;
5346     if (o)
5347         o->op_flags |= OPf_PARENS;
5348     return o;
5349 }
5350
5351 OP *
5352 Perl_bind_match(pTHX_ I32 type, OP *left, OP *right)
5353 {
5354     OP *o;
5355     bool ismatchop = 0;
5356     const OPCODE ltype = left->op_type;
5357     const OPCODE rtype = right->op_type;
5358
5359     PERL_ARGS_ASSERT_BIND_MATCH;
5360
5361     if ( (ltype == OP_RV2AV || ltype == OP_RV2HV || ltype == OP_PADAV
5362           || ltype == OP_PADHV) && ckWARN(WARN_MISC))
5363     {
5364       const char * const desc
5365           = PL_op_desc[(
5366                           rtype == OP_SUBST || rtype == OP_TRANS
5367                        || rtype == OP_TRANSR
5368                        )
5369                        ? (int)rtype : OP_MATCH];
5370       const bool isary = ltype == OP_RV2AV || ltype == OP_PADAV;
5371       SV * const name =
5372         S_op_varname(aTHX_ left);
5373       if (name)
5374         Perl_warner(aTHX_ packWARN(WARN_MISC),
5375              "Applying %s to %" SVf " will act on scalar(%" SVf ")",
5376              desc, SVfARG(name), SVfARG(name));
5377       else {
5378         const char * const sample = (isary
5379              ? "@array" : "%hash");
5380         Perl_warner(aTHX_ packWARN(WARN_MISC),
5381              "Applying %s to %s will act on scalar(%s)",
5382              desc, sample, sample);
5383       }
5384     }
5385
5386     if (rtype == OP_CONST &&
5387         cSVOPx(right)->op_private & OPpCONST_BARE &&
5388         cSVOPx(right)->op_private & OPpCONST_STRICT)
5389     {
5390         no_bareword_allowed(right);
5391     }
5392
5393     /* !~ doesn't make sense with /r, so error on it for now */
5394     if (rtype == OP_SUBST && (cPMOPx(right)->op_pmflags & PMf_NONDESTRUCT) &&
5395         type == OP_NOT)
5396         /* diag_listed_as: Using !~ with %s doesn't make sense */
5397         yyerror("Using !~ with s///r doesn't make sense");
5398     if (rtype == OP_TRANSR && type == OP_NOT)
5399         /* diag_listed_as: Using !~ with %s doesn't make sense */
5400         yyerror("Using !~ with tr///r doesn't make sense");
5401
5402     ismatchop = (rtype == OP_MATCH ||
5403                  rtype == OP_SUBST ||
5404                  rtype == OP_TRANS || rtype == OP_TRANSR)
5405              && !(right->op_flags & OPf_SPECIAL);
5406     if (ismatchop && right->op_private & OPpTARGET_MY) {
5407         right->op_targ = 0;
5408         right->op_private &= ~OPpTARGET_MY;
5409     }
5410     if (!(right->op_flags & OPf_STACKED) && !right->op_targ && ismatchop) {
5411         if (left->op_type == OP_PADSV
5412          && !(left->op_private & OPpLVAL_INTRO))
5413         {
5414             right->op_targ = left->op_targ;
5415             op_free(left);
5416             o = right;
5417         }
5418         else {
5419             right->op_flags |= OPf_STACKED;
5420             if (rtype != OP_MATCH && rtype != OP_TRANSR &&
5421             ! (rtype == OP_TRANS &&
5422                right->op_private & OPpTRANS_IDENTICAL) &&
5423             ! (rtype == OP_SUBST &&
5424                (cPMOPx(right)->op_pmflags & PMf_NONDESTRUCT)))
5425                 left = op_lvalue(left, rtype);
5426             if (right->op_type == OP_TRANS || right->op_type == OP_TRANSR)
5427                 o = newBINOP(OP_NULL, OPf_STACKED, scalar(left), right);
5428             else
5429                 o = op_prepend_elem(rtype, scalar(left), right);
5430         }
5431         if (type == OP_NOT)
5432             return newUNOP(OP_NOT, 0, scalar(o));
5433         return o;
5434     }
5435     else
5436         return bind_match(type, left,
5437                 pmruntime(newPMOP(OP_MATCH, 0), right, NULL, 0, 0));
5438 }
5439
5440 OP *
5441 Perl_invert(pTHX_ OP *o)
5442 {
5443     if (!o)
5444         return NULL;
5445     return newUNOP(OP_NOT, OPf_SPECIAL, scalar(o));
5446 }
5447
5448 /*
5449 =for apidoc op_scope
5450
5451 Wraps up an op tree with some additional ops so that at runtime a dynamic
5452 scope will be created.  The original ops run in the new dynamic scope,
5453 and then, provided that they exit normally, the scope will be unwound.
5454 The additional ops used to create and unwind the dynamic scope will
5455 normally be an C<enter>/C<leave> pair, but a C<scope> op may be used
5456 instead if the ops are simple enough to not need the full dynamic scope
5457 structure.
5458
5459 =cut
5460 */
5461
5462 OP *
5463 Perl_op_scope(pTHX_ OP *o)
5464 {
5465     dVAR;
5466     if (o) {
5467         if (o->op_flags & OPf_PARENS || PERLDB_NOOPT || TAINTING_get) {
5468             o = op_prepend_elem(OP_LINESEQ,
5469                     newOP(OP_ENTER, (o->op_flags & OPf_WANT)), o);
5470             OpTYPE_set(o, OP_LEAVE);
5471         }
5472         else if (o->op_type == OP_LINESEQ) {
5473             OP *kid;
5474             OpTYPE_set(o, OP_SCOPE);
5475             kid = ((LISTOP*)o)->op_first;
5476             if (kid->op_type == OP_NEXTSTATE || kid->op_type == OP_DBSTATE) {
5477                 op_null(kid);
5478
5479                 /* The following deals with things like 'do {1 for 1}' */
5480                 kid = OpSIBLING(kid);
5481                 if (kid &&
5482                     (kid->op_type == OP_NEXTSTATE || kid->op_type == OP_DBSTATE))
5483                     op_null(kid);
5484             }
5485         }
5486         else
5487             o = newLISTOP(OP_SCOPE, 0, o, NULL);
5488     }
5489     return o;
5490 }
5491
5492 OP *
5493 Perl_op_unscope(pTHX_ OP *o)
5494 {
5495     if (o && o->op_type == OP_LINESEQ) {
5496         OP *kid = cLISTOPo->op_first;
5497         for(; kid; kid = OpSIBLING(kid))
5498             if (kid->op_type == OP_NEXTSTATE || kid->op_type == OP_DBSTATE)
5499                 op_null(kid);
5500     }
5501     return o;
5502 }
5503
5504 /*
5505 =for apidoc block_start
5506
5507 Handles compile-time scope entry.
5508 Arranges for hints to be restored on block
5509 exit and also handles pad sequence numbers to make lexical variables scope
5510 right.  Returns a savestack index for use with C<block_end>.
5511
5512 =cut
5513 */
5514
5515 int
5516 Perl_block_start(pTHX_ int full)
5517 {
5518     const int retval = PL_savestack_ix;
5519
5520     PL_compiling.cop_seq = PL_cop_seqmax;
5521     COP_SEQMAX_INC;
5522     pad_block_start(full);
5523     SAVEHINTS();
5524     PL_hints &= ~HINT_BLOCK_SCOPE;
5525     SAVECOMPILEWARNINGS();
5526     PL_compiling.cop_warnings = DUP_WARNINGS(PL_compiling.cop_warnings);
5527     SAVEI32(PL_compiling.cop_seq);
5528     PL_compiling.cop_seq = 0;
5529
5530     CALL_BLOCK_HOOKS(bhk_start, full);
5531
5532     return retval;
5533 }
5534
5535 /*
5536 =for apidoc block_end
5537
5538 Handles compile-time scope exit.  C<floor>
5539 is the savestack index returned by
5540 C<block_start>, and C<seq> is the body of the block.  Returns the block,
5541 possibly modified.
5542
5543 =cut
5544 */
5545
5546 OP*
5547 Perl_block_end(pTHX_ I32 floor, OP *seq)
5548 {
5549     const int needblockscope = PL_hints & HINT_BLOCK_SCOPE;
5550     OP* retval = scalarseq(seq);
5551     OP *o;
5552
5553     /* XXX Is the null PL_parser check necessary here? */
5554     assert(PL_parser); /* Let’s find out under debugging builds.  */
5555     if (PL_parser && PL_parser->parsed_sub) {
5556         o = newSTATEOP(0, NULL, NULL);
5557         op_null(o);
5558         retval = op_append_elem(OP_LINESEQ, retval, o);
5559     }
5560
5561     CALL_BLOCK_HOOKS(bhk_pre_end, &retval);
5562
5563     LEAVE_SCOPE(floor);
5564     if (needblockscope)
5565         PL_hints |= HINT_BLOCK_SCOPE; /* propagate out */
5566     o = pad_leavemy();
5567
5568     if (o) {
5569         /* pad_leavemy has created a sequence of introcv ops for all my
5570            subs declared in the block.  We have to replicate that list with
5571            clonecv ops, to deal with this situation:
5572
5573                sub {
5574                    my sub s1;
5575                    my sub s2;
5576                    sub s1 { state sub foo { \&s2 } }
5577                }->()
5578
5579            Originally, I was going to have introcv clone the CV and turn
5580            off the stale flag.  Since &s1 is declared before &s2, the
5581            introcv op for &s1 is executed (on sub entry) before the one for
5582            &s2.  But the &foo sub inside &s1 (which is cloned when &s1 is
5583            cloned, since it is a state sub) closes over &s2 and expects
5584            to see it in its outer CV’s pad.  If the introcv op clones &s1,
5585            then &s2 is still marked stale.  Since &s1 is not active, and
5586            &foo closes over &s1’s implicit entry for &s2, we get a â€˜Varia-
5587            ble will not stay shared’ warning.  Because it is the same stub
5588            that will be used when the introcv op for &s2 is executed, clos-
5589            ing over it is safe.  Hence, we have to turn off the stale flag
5590            on all lexical subs in the block before we clone any of them.
5591            Hence, having introcv clone the sub cannot work.  So we create a
5592            list of ops like this:
5593
5594                lineseq
5595                   |
5596                   +-- introcv
5597                   |
5598                   +-- introcv
5599                   |
5600                   +-- introcv
5601                   |
5602                   .
5603                   .
5604                   .
5605                   |
5606                   +-- clonecv
5607                   |
5608                   +-- clonecv
5609                   |
5610                   +-- clonecv
5611                   |
5612                   .
5613                   .
5614                   .
5615          */
5616         OP *kid = o->op_flags & OPf_KIDS ? cLISTOPo->op_first : o;
5617         OP * const last = o->op_flags & OPf_KIDS ? cLISTOPo->op_last : o;
5618         for (;; kid = OpSIBLING(kid)) {
5619             OP *newkid = newOP(OP_CLONECV, 0);
5620             newkid->op_targ = kid->op_targ;
5621             o = op_append_elem(OP_LINESEQ, o, newkid);
5622             if (kid == last) break;
5623         }
5624         retval = op_prepend_elem(OP_LINESEQ, o, retval);
5625     }
5626
5627     CALL_BLOCK_HOOKS(bhk_post_end, &retval);
5628
5629     return retval;
5630 }
5631
5632 /*
5633 =head1 Compile-time scope hooks
5634
5635 =for apidoc blockhook_register
5636
5637 Register a set of hooks to be called when the Perl lexical scope changes
5638 at compile time.  See L<perlguts/"Compile-time scope hooks">.
5639
5640 =cut
5641 */
5642
5643 void
5644 Perl_blockhook_register(pTHX_ BHK *hk)
5645 {
5646     PERL_ARGS_ASSERT_BLOCKHOOK_REGISTER;
5647
5648     Perl_av_create_and_push(aTHX_ &PL_blockhooks, newSViv(PTR2IV(hk)));
5649 }
5650
5651 void
5652 Perl_newPROG(pTHX_ OP *o)
5653 {
5654     OP *start;
5655
5656     PERL_ARGS_ASSERT_NEWPROG;
5657
5658     if (PL_in_eval) {
5659         PERL_CONTEXT *cx;
5660         I32 i;
5661         if (PL_eval_root)
5662                 return;
5663         PL_eval_root = newUNOP(OP_LEAVEEVAL,
5664                                ((PL_in_eval & EVAL_KEEPERR)
5665                                 ? OPf_SPECIAL : 0), o);
5666
5667         cx = CX_CUR();
5668         assert(CxTYPE(cx) == CXt_EVAL);
5669
5670         if ((cx->blk_gimme & G_WANT) == G_VOID)
5671             scalarvoid(PL_eval_root);
5672         else if ((cx->blk_gimme & G_WANT) == G_ARRAY)
5673             list(PL_eval_root);
5674         else
5675             scalar(PL_eval_root);
5676
5677         start = op_linklist(PL_eval_root);
5678         PL_eval_root->op_next = 0;
5679         i = PL_savestack_ix;
5680         SAVEFREEOP(o);
5681         ENTER;
5682         S_process_optree(aTHX_ NULL, PL_eval_root, start);
5683         LEAVE;
5684         PL_savestack_ix = i;
5685     }
5686     else {
5687         if (o->op_type == OP_STUB) {
5688             /* This block is entered if nothing is compiled for the main
5689                program. This will be the case for an genuinely empty main
5690                program, or one which only has BEGIN blocks etc, so already
5691                run and freed.
5692
5693                Historically (5.000) the guard above was !o. However, commit
5694                f8a08f7b8bd67b28 (Jun 2001), integrated to blead as
5695                c71fccf11fde0068, changed perly.y so that newPROG() is now
5696                called with the output of block_end(), which returns a new
5697                OP_STUB for the case of an empty optree. ByteLoader (and
5698                maybe other things) also take this path, because they set up
5699                PL_main_start and PL_main_root directly, without generating an
5700                optree.
5701
5702                If the parsing the main program aborts (due to parse errors,
5703                or due to BEGIN or similar calling exit), then newPROG()
5704                isn't even called, and hence this code path and its cleanups
5705                are skipped. This shouldn't make a make a difference:
5706                * a non-zero return from perl_parse is a failure, and
5707                  perl_destruct() should be called immediately.
5708                * however, if exit(0) is called during the parse, then
5709                  perl_parse() returns 0, and perl_run() is called. As
5710                  PL_main_start will be NULL, perl_run() will return
5711                  promptly, and the exit code will remain 0.
5712             */
5713
5714             PL_comppad_name = 0;
5715             PL_compcv = 0;
5716             S_op_destroy(aTHX_ o);
5717             return;
5718         }
5719         PL_main_root = op_scope(sawparens(scalarvoid(o)));
5720         PL_curcop = &PL_compiling;
5721         start = LINKLIST(PL_main_root);
5722         PL_main_root->op_next = 0;
5723         S_process_optree(aTHX_ NULL, PL_main_root, start);
5724         if (!PL_parser->error_count)
5725             /* on error, leave CV slabbed so that ops left lying around
5726              * will eb cleaned up. Else unslab */
5727             cv_forget_slab(PL_compcv);
5728         PL_compcv = 0;
5729
5730         /* Register with debugger */
5731         if (PERLDB_INTER) {
5732             CV * const cv = get_cvs("DB::postponed", 0);
5733             if (cv) {
5734                 dSP;
5735                 PUSHMARK(SP);
5736                 XPUSHs(MUTABLE_SV(CopFILEGV(&PL_compiling)));
5737                 PUTBACK;
5738                 call_sv(MUTABLE_SV(cv), G_DISCARD);
5739             }
5740         }
5741     }
5742 }
5743
5744 OP *
5745 Perl_localize(pTHX_ OP *o, I32 lex)
5746 {
5747     PERL_ARGS_ASSERT_LOCALIZE;
5748
5749     if (o->op_flags & OPf_PARENS)
5750 /* [perl #17376]: this appears to be premature, and results in code such as
5751    C< our(%x); > executing in list mode rather than void mode */
5752 #if 0
5753         list(o);
5754 #else
5755         NOOP;
5756 #endif
5757     else {
5758         if ( PL_parser->bufptr > PL_parser->oldbufptr
5759             && PL_parser->bufptr[-1] == ','
5760             && ckWARN(WARN_PARENTHESIS))
5761         {
5762             char *s = PL_parser->bufptr;
5763             bool sigil = FALSE;
5764
5765             /* some heuristics to detect a potential error */
5766             while (*s && (strchr(", \t\n", *s)))
5767                 s++;
5768
5769             while (1) {
5770                 if (*s && (strchr("@$%", *s) || (!lex && *s == '*'))
5771                        && *++s
5772                        && (isWORDCHAR(*s) || UTF8_IS_CONTINUED(*s))) {
5773                     s++;
5774                     sigil = TRUE;
5775                     while (*s && (isWORDCHAR(*s) || UTF8_IS_CONTINUED(*s)))
5776                         s++;
5777                     while (*s && (strchr(", \t\n", *s)))
5778                         s++;
5779                 }
5780                 else
5781                     break;
5782             }
5783             if (sigil && (*s == ';' || *s == '=')) {
5784                 Perl_warner(aTHX_ packWARN(WARN_PARENTHESIS),
5785                                 "Parentheses missing around \"%s\" list",
5786                                 lex
5787                                     ? (PL_parser->in_my == KEY_our
5788                                         ? "our"
5789                                         : PL_parser->in_my == KEY_state
5790                                             ? "state"
5791                                             : "my")
5792                                     : "local");
5793             }
5794         }
5795     }
5796     if (lex)
5797         o = my(o);
5798     else
5799         o = op_lvalue(o, OP_NULL);              /* a bit kludgey */
5800     PL_parser->in_my = FALSE;
5801     PL_parser->in_my_stash = NULL;
5802     return o;
5803 }
5804
5805 OP *
5806 Perl_jmaybe(pTHX_ OP *o)
5807 {
5808     PERL_ARGS_ASSERT_JMAYBE;
5809
5810     if (o->op_type == OP_LIST) {
5811         OP * const o2
5812             = newSVREF(newGVOP(OP_GV, 0, gv_fetchpvs(";", GV_ADD|GV_NOTQUAL, SVt_PV)));
5813         o = op_convert_list(OP_JOIN, 0, op_prepend_elem(OP_LIST, o2, o));
5814     }
5815     return o;
5816 }
5817
5818 PERL_STATIC_INLINE OP *
5819 S_op_std_init(pTHX_ OP *o)
5820 {
5821     I32 type = o->op_type;
5822
5823     PERL_ARGS_ASSERT_OP_STD_INIT;
5824
5825     if (PL_opargs[type] & OA_RETSCALAR)
5826         scalar(o);
5827     if (PL_opargs[type] & OA_TARGET && !o->op_targ)
5828         o->op_targ = pad_alloc(type, SVs_PADTMP);
5829
5830     return o;
5831 }
5832
5833 PERL_STATIC_INLINE OP *
5834 S_op_integerize(pTHX_ OP *o)
5835 {
5836     I32 type = o->op_type;
5837
5838     PERL_ARGS_ASSERT_OP_INTEGERIZE;
5839
5840     /* integerize op. */
5841     if ((PL_opargs[type] & OA_OTHERINT) && (PL_hints & HINT_INTEGER))
5842     {
5843         dVAR;
5844         o->op_ppaddr = PL_ppaddr[++(o->op_type)];
5845     }
5846
5847     if (type == OP_NEGATE)
5848         /* XXX might want a ck_negate() for this */
5849         cUNOPo->op_first->op_private &= ~OPpCONST_STRICT;
5850
5851     return o;
5852 }
5853
5854 /* This function exists solely to provide a scope to limit
5855    setjmp/longjmp() messing with auto variables.
5856  */
5857 PERL_STATIC_INLINE int
5858 S_fold_constants_eval(pTHX) {
5859     int ret = 0;
5860     dJMPENV;
5861
5862     JMPENV_PUSH(ret);
5863
5864     if (ret == 0) {
5865         CALLRUNOPS(aTHX);
5866     }
5867
5868     JMPENV_POP;
5869
5870     return ret;
5871 }
5872
5873 static OP *
5874 S_fold_constants(pTHX_ OP *const o)
5875 {
5876     dVAR;
5877     OP *curop;
5878     OP *newop;
5879     I32 type = o->op_type;
5880     bool is_stringify;
5881     SV *sv = NULL;
5882     int ret = 0;
5883     OP *old_next;
5884     SV * const oldwarnhook = PL_warnhook;
5885     SV * const olddiehook  = PL_diehook;
5886     COP not_compiling;
5887     U8 oldwarn = PL_dowarn;
5888     I32 old_cxix;
5889
5890     PERL_ARGS_ASSERT_FOLD_CONSTANTS;
5891
5892     if (!(PL_opargs[type] & OA_FOLDCONST))
5893         goto nope;
5894
5895     switch (type) {
5896     case OP_UCFIRST:
5897     case OP_LCFIRST:
5898     case OP_UC:
5899     case OP_LC:
5900     case OP_FC:
5901 #ifdef USE_LOCALE_CTYPE
5902         if (IN_LC_COMPILETIME(LC_CTYPE))
5903             goto nope;
5904 #endif
5905         break;
5906     case OP_SLT:
5907     case OP_SGT:
5908     case OP_SLE:
5909     case OP_SGE:
5910     case OP_SCMP:
5911 #ifdef USE_LOCALE_COLLATE
5912         if (IN_LC_COMPILETIME(LC_COLLATE))
5913             goto nope;
5914 #endif
5915         break;
5916     case OP_SPRINTF:
5917         /* XXX what about the numeric ops? */
5918 #ifdef USE_LOCALE_NUMERIC
5919         if (IN_LC_COMPILETIME(LC_NUMERIC))
5920             goto nope;
5921 #endif
5922         break;
5923     case OP_PACK:
5924         if (!OpHAS_SIBLING(cLISTOPo->op_first)
5925           || OpSIBLING(cLISTOPo->op_first)->op_type != OP_CONST)
5926             goto nope;
5927         {
5928             SV * const sv = cSVOPx_sv(OpSIBLING(cLISTOPo->op_first));
5929             if (!SvPOK(sv) || SvGMAGICAL(sv)) goto nope;
5930             {
5931                 const char *s = SvPVX_const(sv);
5932                 while (s < SvEND(sv)) {
5933                     if (isALPHA_FOLD_EQ(*s, 'p')) goto nope;
5934                     s++;
5935                 }
5936             }
5937         }
5938         break;
5939     case OP_REPEAT:
5940         if (o->op_private & OPpREPEAT_DOLIST) goto nope;
5941         break;
5942     case OP_SREFGEN:
5943         if (cUNOPx(cUNOPo->op_first)->op_first->op_type != OP_CONST
5944          || SvPADTMP(cSVOPx_sv(cUNOPx(cUNOPo->op_first)->op_first)))
5945             goto nope;
5946     }
5947
5948     if (PL_parser && PL_parser->error_count)
5949         goto nope;              /* Don't try to run w/ errors */
5950
5951     for (curop = LINKLIST(o); curop != o; curop = LINKLIST(curop)) {
5952         switch (curop->op_type) {
5953         case OP_CONST:
5954             if (   (curop->op_private & OPpCONST_BARE)
5955                 && (curop->op_private & OPpCONST_STRICT)) {
5956                 no_bareword_allowed(curop);
5957                 goto nope;
5958             }
5959             /* FALLTHROUGH */
5960         case OP_LIST:
5961         case OP_SCALAR:
5962         case OP_NULL:
5963         case OP_PUSHMARK:
5964             /* Foldable; move to next op in list */
5965             break;
5966
5967         default:
5968             /* No other op types are considered foldable */
5969             goto nope;
5970         }
5971     }
5972
5973     curop = LINKLIST(o);
5974     old_next = o->op_next;
5975     o->op_next = 0;
5976     PL_op = curop;
5977
5978     old_cxix = cxstack_ix;
5979     create_eval_scope(NULL, G_FAKINGEVAL);
5980
5981     /* Verify that we don't need to save it:  */
5982     assert(PL_curcop == &PL_compiling);
5983     StructCopy(&PL_compiling, &not_compiling, COP);
5984     PL_curcop = &not_compiling;
5985     /* The above ensures that we run with all the correct hints of the
5986        currently compiling COP, but that IN_PERL_RUNTIME is true. */
5987     assert(IN_PERL_RUNTIME);
5988     PL_warnhook = PERL_WARNHOOK_FATAL;
5989     PL_diehook  = NULL;
5990
5991     /* Effective $^W=1.  */
5992     if ( ! (PL_dowarn & G_WARN_ALL_MASK))
5993         PL_dowarn |= G_WARN_ON;
5994
5995     ret = S_fold_constants_eval(aTHX);
5996
5997     switch (ret) {
5998     case 0:
5999         sv = *(PL_stack_sp--);
6000         if (o->op_targ && sv == PAD_SV(o->op_targ)) {   /* grab pad temp? */
6001             pad_swipe(o->op_targ,  FALSE);
6002         }
6003         else if (SvTEMP(sv)) {                  /* grab mortal temp? */
6004             SvREFCNT_inc_simple_void(sv);
6005             SvTEMP_off(sv);
6006         }
6007         else { assert(SvIMMORTAL(sv)); }
6008         break;
6009     case 3:
6010         /* Something tried to die.  Abandon constant folding.  */
6011         /* Pretend the error never happened.  */
6012         CLEAR_ERRSV();
6013         o->op_next = old_next;
6014         break;
6015     default:
6016         /* Don't expect 1 (setjmp failed) or 2 (something called my_exit)  */
6017         PL_warnhook = oldwarnhook;
6018         PL_diehook  = olddiehook;
6019         /* XXX note that this croak may fail as we've already blown away
6020          * the stack - eg any nested evals */
6021         Perl_croak(aTHX_ "panic: fold_constants JMPENV_PUSH returned %d", ret);
6022     }
6023     PL_dowarn   = oldwarn;
6024     PL_warnhook = oldwarnhook;
6025     PL_diehook  = olddiehook;
6026     PL_curcop = &PL_compiling;
6027
6028     /* if we croaked, depending on how we croaked the eval scope
6029      * may or may not have already been popped */
6030     if (cxstack_ix > old_cxix) {
6031         assert(cxstack_ix == old_cxix + 1);
6032         assert(CxTYPE(CX_CUR()) == CXt_EVAL);
6033         delete_eval_scope();
6034     }
6035     if (ret)
6036         goto nope;
6037
6038     /* OP_STRINGIFY and constant folding are used to implement qq.
6039        Here the constant folding is an implementation detail that we
6040        want to hide.  If the stringify op is itself already marked
6041        folded, however, then it is actually a folded join.  */
6042     is_stringify = type == OP_STRINGIFY && !o->op_folded;
6043     op_free(o);
6044     assert(sv);
6045     if (is_stringify)
6046         SvPADTMP_off(sv);
6047     else if (!SvIMMORTAL(sv)) {
6048         SvPADTMP_on(sv);
6049         SvREADONLY_on(sv);
6050     }
6051     newop = newSVOP(OP_CONST, 0, MUTABLE_SV(sv));
6052     if (!is_stringify) newop->op_folded = 1;
6053     return newop;
6054
6055  nope:
6056     return o;
6057 }
6058
6059 /* convert a constant range in list context into an OP_RV2AV, OP_CONST pair;
6060  * the constant value being an AV holding the flattened range.
6061  */
6062
6063 static void
6064 S_gen_constant_list(pTHX_ OP *o)
6065 {
6066     dVAR;
6067     OP *curop, *old_next;
6068     SV * const oldwarnhook = PL_warnhook;
6069     SV * const olddiehook  = PL_diehook;
6070     COP *old_curcop;
6071     U8 oldwarn = PL_dowarn;
6072     SV **svp;
6073     AV *av;
6074     I32 old_cxix;
6075     COP not_compiling;
6076     int ret = 0;
6077     dJMPENV;
6078     bool op_was_null;
6079
6080     list(o);
6081     if (PL_parser && PL_parser->error_count)
6082         return;         /* Don't attempt to run with errors */
6083
6084     curop = LINKLIST(o);
6085     old_next = o->op_next;
6086     o->op_next = 0;
6087     op_was_null = o->op_type == OP_NULL;
6088     if (op_was_null) /* b3698342565fb462291fba4b432cfcd05b6eb4e1 */
6089         o->op_type = OP_CUSTOM;
6090     CALL_PEEP(curop);
6091     if (op_was_null)
6092         o->op_type = OP_NULL;
6093     S_prune_chain_head(&curop);
6094     PL_op = curop;
6095
6096     old_cxix = cxstack_ix;
6097     create_eval_scope(NULL, G_FAKINGEVAL);
6098
6099     old_curcop = PL_curcop;
6100     StructCopy(old_curcop, &not_compiling, COP);
6101     PL_curcop = &not_compiling;
6102     /* The above ensures that we run with all the correct hints of the
6103        current COP, but that IN_PERL_RUNTIME is true. */
6104     assert(IN_PERL_RUNTIME);
6105     PL_warnhook = PERL_WARNHOOK_FATAL;
6106     PL_diehook  = NULL;
6107     JMPENV_PUSH(ret);
6108
6109     /* Effective $^W=1.  */
6110     if ( ! (PL_dowarn & G_WARN_ALL_MASK))
6111         PL_dowarn |= G_WARN_ON;
6112
6113     switch (ret) {
6114     case 0:
6115 #if defined DEBUGGING && !defined DEBUGGING_RE_ONLY
6116         PL_curstackinfo->si_stack_hwm = 0; /* stop valgrind complaining */
6117 #endif
6118         Perl_pp_pushmark(aTHX);
6119         CALLRUNOPS(aTHX);
6120         PL_op = curop;
6121         assert (!(curop->op_flags & OPf_SPECIAL));
6122         assert(curop->op_type == OP_RANGE);
6123         Perl_pp_anonlist(aTHX);
6124         break;
6125     case 3:
6126         CLEAR_ERRSV();
6127         o->op_next = old_next;
6128         break;
6129     default:
6130         JMPENV_POP;
6131         PL_warnhook = oldwarnhook;
6132         PL_diehook = olddiehook;
6133         Perl_croak(aTHX_ "panic: gen_constant_list JMPENV_PUSH returned %d",
6134             ret);
6135     }
6136
6137     JMPENV_POP;
6138     PL_dowarn = oldwarn;
6139     PL_warnhook = oldwarnhook;
6140     PL_diehook = olddiehook;
6141     PL_curcop = old_curcop;
6142
6143     if (cxstack_ix > old_cxix) {
6144         assert(cxstack_ix == old_cxix + 1);
6145         assert(CxTYPE(CX_CUR()) == CXt_EVAL);
6146         delete_eval_scope();
6147     }
6148     if (ret)
6149         return;
6150
6151     OpTYPE_set(o, OP_RV2AV);
6152     o->op_flags &= ~OPf_REF;    /* treat \(1..2) like an ordinary list */
6153     o->op_flags |= OPf_PARENS;  /* and flatten \(1..2,3) */
6154     o->op_opt = 0;              /* needs to be revisited in rpeep() */
6155     av = (AV *)SvREFCNT_inc_NN(*PL_stack_sp--);
6156
6157     /* replace subtree with an OP_CONST */
6158     curop = ((UNOP*)o)->op_first;
6159     op_sibling_splice(o, NULL, -1, newSVOP(OP_CONST, 0, (SV *)av));
6160     op_free(curop);
6161
6162     if (AvFILLp(av) != -1)
6163         for (svp = AvARRAY(av) + AvFILLp(av); svp >= AvARRAY(av); --svp)
6164         {
6165             SvPADTMP_on(*svp);
6166             SvREADONLY_on(*svp);
6167         }
6168     LINKLIST(o);
6169     list(o);
6170     return;
6171 }
6172
6173 /*
6174 =head1 Optree Manipulation Functions
6175 */
6176
6177 /* List constructors */
6178
6179 /*
6180 =for apidoc op_append_elem
6181
6182 Append an item to the list of ops contained directly within a list-type
6183 op, returning the lengthened list.  C<first> is the list-type op,
6184 and C<last> is the op to append to the list.  C<optype> specifies the
6185 intended opcode for the list.  If C<first> is not already a list of the
6186 right type, it will be upgraded into one.  If either C<first> or C<last>
6187 is null, the other is returned unchanged.
6188
6189 =cut
6190 */
6191
6192 OP *
6193 Perl_op_append_elem(pTHX_ I32 type, OP *first, OP *last)
6194 {
6195     if (!first)
6196         return last;
6197
6198     if (!last)
6199         return first;
6200
6201     if (first->op_type != (unsigned)type
6202         || (type == OP_LIST && (first->op_flags & OPf_PARENS)))
6203     {
6204         return newLISTOP(type, 0, first, last);
6205     }
6206
6207     op_sibling_splice(first, ((LISTOP*)first)->op_last, 0, last);
6208     first->op_flags |= OPf_KIDS;
6209     return first;
6210 }
6211
6212 /*
6213 =for apidoc op_append_list
6214
6215 Concatenate the lists of ops contained directly within two list-type ops,
6216 returning the combined list.  C<first> and C<last> are the list-type ops
6217 to concatenate.  C<optype> specifies the intended opcode for the list.
6218 If either C<first> or C<last> is not already a list of the right type,
6219 it will be upgraded into one.  If either C<first> or C<last> is null,
6220 the other is returned unchanged.
6221
6222 =cut
6223 */
6224
6225 OP *
6226 Perl_op_append_list(pTHX_ I32 type, OP *first, OP *last)
6227 {
6228     if (!first)
6229         return last;
6230
6231     if (!last)
6232         return first;
6233
6234     if (first->op_type != (unsigned)type)
6235         return op_prepend_elem(type, first, last);
6236
6237     if (last->op_type != (unsigned)type)
6238         return op_append_elem(type, first, last);
6239
6240     OpMORESIB_set(((LISTOP*)first)->op_last, ((LISTOP*)last)->op_first);
6241     ((LISTOP*)first)->op_last = ((LISTOP*)last)->op_last;
6242     OpLASTSIB_set(((LISTOP*)first)->op_last, first);
6243     first->op_flags |= (last->op_flags & OPf_KIDS);
6244
6245     S_op_destroy(aTHX_ last);
6246
6247     return first;
6248 }
6249
6250 /*
6251 =for apidoc op_prepend_elem
6252
6253 Prepend an item to the list of ops contained directly within a list-type
6254 op, returning the lengthened list.  C<first> is the op to prepend to the
6255 list, and C<last> is the list-type op.  C<optype> specifies the intended
6256 opcode for the list.  If C<last> is not already a list of the right type,
6257 it will be upgraded into one.  If either C<first> or C<last> is null,
6258 the other is returned unchanged.
6259
6260 =cut
6261 */
6262
6263 OP *
6264 Perl_op_prepend_elem(pTHX_ I32 type, OP *first, OP *last)
6265 {
6266     if (!first)
6267         return last;
6268
6269     if (!last)
6270         return first;
6271
6272     if (last->op_type == (unsigned)type) {
6273         if (type == OP_LIST) {  /* already a PUSHMARK there */
6274             /* insert 'first' after pushmark */
6275             op_sibling_splice(last, cLISTOPx(last)->op_first, 0, first);
6276             if (!(first->op_flags & OPf_PARENS))
6277                 last->op_flags &= ~OPf_PARENS;
6278         }
6279         else
6280             op_sibling_splice(last, NULL, 0, first);
6281         last->op_flags |= OPf_KIDS;
6282         return last;
6283     }
6284
6285     return newLISTOP(type, 0, first, last);
6286 }
6287
6288 /*
6289 =for apidoc op_convert_list
6290
6291 Converts C<o> into a list op if it is not one already, and then converts it
6292 into the specified C<type>, calling its check function, allocating a target if
6293 it needs one, and folding constants.
6294
6295 A list-type op is usually constructed one kid at a time via C<newLISTOP>,
6296 C<op_prepend_elem> and C<op_append_elem>.  Then finally it is passed to
6297 C<op_convert_list> to make it the right type.
6298
6299 =cut
6300 */
6301
6302 OP *
6303 Perl_op_convert_list(pTHX_ I32 type, I32 flags, OP *o)
6304 {
6305     dVAR;
6306     if (type < 0) type = -type, flags |= OPf_SPECIAL;
6307     if (!o || o->op_type != OP_LIST)
6308         o = force_list(o, 0);
6309     else
6310     {
6311         o->op_flags &= ~OPf_WANT;
6312         o->op_private &= ~OPpLVAL_INTRO;
6313     }
6314
6315     if (!(PL_opargs[type] & OA_MARK))
6316         op_null(cLISTOPo->op_first);
6317     else {
6318         OP * const kid2 = OpSIBLING(cLISTOPo->op_first);
6319         if (kid2 && kid2->op_type == OP_COREARGS) {
6320             op_null(cLISTOPo->op_first);
6321             kid2->op_private |= OPpCOREARGS_PUSHMARK;
6322         }
6323     }
6324
6325     if (type != OP_SPLIT)
6326         /* At this point o is a LISTOP, but OP_SPLIT is a PMOP; let
6327          * ck_split() create a real PMOP and leave the op's type as listop
6328          * for now. Otherwise op_free() etc will crash.
6329          */
6330         OpTYPE_set(o, type);
6331
6332     o->op_flags |= flags;
6333     if (flags & OPf_FOLDED)
6334         o->op_folded = 1;
6335
6336     o = CHECKOP(type, o);
6337     if (o->op_type != (unsigned)type)
6338         return o;
6339
6340     return fold_constants(op_integerize(op_std_init(o)));
6341 }
6342
6343 /* Constructors */
6344
6345
6346 /*
6347 =head1 Optree construction
6348
6349 =for apidoc newNULLLIST
6350
6351 Constructs, checks, and returns a new C<stub> op, which represents an
6352 empty list expression.
6353
6354 =cut
6355 */
6356
6357 OP *
6358 Perl_newNULLLIST(pTHX)
6359 {
6360     return newOP(OP_STUB, 0);
6361 }
6362
6363 /* promote o and any siblings to be a list if its not already; i.e.
6364  *
6365  *  o - A - B
6366  *
6367  * becomes
6368  *
6369  *  list
6370  *    |
6371  *  pushmark - o - A - B
6372  *
6373  * If nullit it true, the list op is nulled.
6374  */
6375
6376 static OP *
6377 S_force_list(pTHX_ OP *o, bool nullit)
6378 {
6379     if (!o || o->op_type != OP_LIST) {
6380         OP *rest = NULL;
6381         if (o) {
6382             /* manually detach any siblings then add them back later */
6383             rest = OpSIBLING(o);
6384             OpLASTSIB_set(o, NULL);
6385         }
6386         o = newLISTOP(OP_LIST, 0, o, NULL);
6387         if (rest)
6388             op_sibling_splice(o, cLISTOPo->op_last, 0, rest);
6389     }
6390     if (nullit)
6391         op_null(o);
6392     return o;
6393 }
6394
6395 /*
6396 =for apidoc newLISTOP
6397
6398 Constructs, checks, and returns an op of any list type.  C<type> is
6399 the opcode.  C<flags> gives the eight bits of C<op_flags>, except that
6400 C<OPf_KIDS> will be set automatically if required.  C<first> and C<last>
6401 supply up to two ops to be direct children of the list op; they are
6402 consumed by this function and become part of the constructed op tree.
6403
6404 For most list operators, the check function expects all the kid ops to be
6405 present already, so calling C<newLISTOP(OP_JOIN, ...)> (e.g.) is not
6406 appropriate.  What you want to do in that case is create an op of type
6407 C<OP_LIST>, append more children to it, and then call L</op_convert_list>.
6408 See L</op_convert_list> for more information.
6409
6410
6411 =cut
6412 */
6413
6414 OP *
6415 Perl_newLISTOP(pTHX_ I32 type, I32 flags, OP *first, OP *last)
6416 {
6417     dVAR;
6418     LISTOP *listop;
6419     /* Note that allocating an OP_PUSHMARK can die under Safe.pm if
6420      * pushmark is banned. So do it now while existing ops are in a
6421      * consistent state, in case they suddenly get freed */
6422     OP* const pushop = type == OP_LIST ? newOP(OP_PUSHMARK, 0) : NULL;
6423
6424     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_LISTOP
6425         || type == OP_CUSTOM);
6426
6427     NewOp(1101, listop, 1, LISTOP);
6428     OpTYPE_set(listop, type);
6429     if (first || last)
6430         flags |= OPf_KIDS;
6431     listop->op_flags = (U8)flags;
6432
6433     if (!last && first)
6434         last = first;
6435     else if (!first && last)
6436         first = last;
6437     else if (first)
6438         OpMORESIB_set(first, last);
6439     listop->op_first = first;
6440     listop->op_last = last;
6441
6442     if (pushop) {
6443         OpMORESIB_set(pushop, first);
6444         listop->op_first = pushop;
6445         listop->op_flags |= OPf_KIDS;
6446         if (!last)
6447             listop->op_last = pushop;
6448     }
6449     if (listop->op_last)
6450         OpLASTSIB_set(listop->op_last, (OP*)listop);
6451
6452     return CHECKOP(type, listop);
6453 }
6454
6455 /*
6456 =for apidoc newOP
6457
6458 Constructs, checks, and returns an op of any base type (any type that
6459 has no extra fields).  C<type> is the opcode.  C<flags> gives the
6460 eight bits of C<op_flags>, and, shifted up eight bits, the eight bits
6461 of C<op_private>.
6462
6463 =cut
6464 */
6465
6466 OP *
6467 Perl_newOP(pTHX_ I32 type, I32 flags)
6468 {
6469     dVAR;
6470     OP *o;
6471
6472     if (type == -OP_ENTEREVAL) {
6473         type = OP_ENTEREVAL;
6474         flags |= OPpEVAL_BYTES<<8;
6475     }
6476
6477     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_BASEOP
6478         || (PL_opargs[type] & OA_CLASS_MASK) == OA_BASEOP_OR_UNOP
6479         || (PL_opargs[type] & OA_CLASS_MASK) == OA_FILESTATOP
6480         || (PL_opargs[type] & OA_CLASS_MASK) == OA_LOOPEXOP);
6481
6482     NewOp(1101, o, 1, OP);
6483     OpTYPE_set(o, type);
6484     o->op_flags = (U8)flags;
6485
6486     o->op_next = o;
6487     o->op_private = (U8)(0 | (flags >> 8));
6488     if (PL_opargs[type] & OA_RETSCALAR)
6489         scalar(o);
6490     if (PL_opargs[type] & OA_TARGET)
6491         o->op_targ = pad_alloc(type, SVs_PADTMP);
6492     return CHECKOP(type, o);
6493 }
6494
6495 /*
6496 =for apidoc newUNOP
6497
6498 Constructs, checks, and returns an op of any unary type.  C<type> is
6499 the opcode.  C<flags> gives the eight bits of C<op_flags>, except that
6500 C<OPf_KIDS> will be set automatically if required, and, shifted up eight
6501 bits, the eight bits of C<op_private>, except that the bit with value 1
6502 is automatically set.  C<first> supplies an optional op to be the direct
6503 child of the unary op; it is consumed by this function and become part
6504 of the constructed op tree.
6505
6506 =cut
6507 */
6508
6509 OP *
6510 Perl_newUNOP(pTHX_ I32 type, I32 flags, OP *first)
6511 {
6512     dVAR;
6513     UNOP *unop;
6514
6515     if (type == -OP_ENTEREVAL) {
6516         type = OP_ENTEREVAL;
6517         flags |= OPpEVAL_BYTES<<8;
6518     }
6519
6520     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_UNOP
6521         || (PL_opargs[type] & OA_CLASS_MASK) == OA_BASEOP_OR_UNOP
6522         || (PL_opargs[type] & OA_CLASS_MASK) == OA_FILESTATOP
6523         || (PL_opargs[type] & OA_CLASS_MASK) == OA_LOOPEXOP
6524         || type == OP_SASSIGN
6525         || type == OP_ENTERTRY
6526         || type == OP_CUSTOM
6527         || type == OP_NULL );
6528
6529     if (!first)
6530         first = newOP(OP_STUB, 0);
6531     if (PL_opargs[type] & OA_MARK)
6532         first = force_list(first, 1);
6533
6534     NewOp(1101, unop, 1, UNOP);
6535     OpTYPE_set(unop, type);
6536     unop->op_first = first;
6537     unop->op_flags = (U8)(flags | OPf_KIDS);
6538     unop->op_private = (U8)(1 | (flags >> 8));
6539
6540     if (!OpHAS_SIBLING(first)) /* true unless weird syntax error */
6541         OpLASTSIB_set(first, (OP*)unop);
6542
6543     unop = (UNOP*) CHECKOP(type, unop);
6544     if (unop->op_next)
6545         return (OP*)unop;
6546
6547     return fold_constants(op_integerize(op_std_init((OP *) unop)));
6548 }
6549
6550 /*
6551 =for apidoc newUNOP_AUX
6552
6553 Similar to C<newUNOP>, but creates an C<UNOP_AUX> struct instead, with C<op_aux>
6554 initialised to C<aux>
6555
6556 =cut
6557 */
6558
6559 OP *
6560 Perl_newUNOP_AUX(pTHX_ I32 type, I32 flags, OP *first, UNOP_AUX_item *aux)
6561 {
6562     dVAR;
6563     UNOP_AUX *unop;
6564
6565     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_UNOP_AUX
6566         || type == OP_CUSTOM);
6567
6568     NewOp(1101, unop, 1, UNOP_AUX);
6569     unop->op_type = (OPCODE)type;
6570     unop->op_ppaddr = PL_ppaddr[type];
6571     unop->op_first = first;
6572     unop->op_flags = (U8)(flags | (first ? OPf_KIDS : 0));
6573     unop->op_private = (U8)((first ? 1 : 0) | (flags >> 8));
6574     unop->op_aux = aux;
6575
6576     if (first && !OpHAS_SIBLING(first)) /* true unless weird syntax error */
6577         OpLASTSIB_set(first, (OP*)unop);
6578
6579     unop = (UNOP_AUX*) CHECKOP(type, unop);
6580
6581     return op_std_init((OP *) unop);
6582 }
6583
6584 /*
6585 =for apidoc newMETHOP
6586
6587 Constructs, checks, and returns an op of method type with a method name
6588 evaluated at runtime.  C<type> is the opcode.  C<flags> gives the eight
6589 bits of C<op_flags>, except that C<OPf_KIDS> will be set automatically,
6590 and, shifted up eight bits, the eight bits of C<op_private>, except that
6591 the bit with value 1 is automatically set.  C<dynamic_meth> supplies an
6592 op which evaluates method name; it is consumed by this function and
6593 become part of the constructed op tree.
6594 Supported optypes: C<OP_METHOD>.
6595
6596 =cut
6597 */
6598
6599 static OP*
6600 S_newMETHOP_internal(pTHX_ I32 type, I32 flags, OP* dynamic_meth, SV* const_meth) {
6601     dVAR;
6602     METHOP *methop;
6603
6604     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_METHOP
6605         || type == OP_CUSTOM);
6606
6607     NewOp(1101, methop, 1, METHOP);
6608     if (dynamic_meth) {
6609         if (PL_opargs[type] & OA_MARK) dynamic_meth = force_list(dynamic_meth, 1);
6610         methop->op_flags = (U8)(flags | OPf_KIDS);
6611         methop->op_u.op_first = dynamic_meth;
6612         methop->op_private = (U8)(1 | (flags >> 8));
6613
6614         if (!OpHAS_SIBLING(dynamic_meth))
6615             OpLASTSIB_set(dynamic_meth, (OP*)methop);
6616     }
6617     else {
6618         assert(const_meth);
6619         methop->op_flags = (U8)(flags & ~OPf_KIDS);
6620         methop->op_u.op_meth_sv = const_meth;
6621         methop->op_private = (U8)(0 | (flags >> 8));
6622         methop->op_next = (OP*)methop;
6623     }
6624
6625 #ifdef USE_ITHREADS
6626     methop->op_rclass_targ = 0;
6627 #else
6628     methop->op_rclass_sv = NULL;
6629 #endif
6630
6631     OpTYPE_set(methop, type);
6632     return CHECKOP(type, methop);
6633 }
6634
6635 OP *
6636 Perl_newMETHOP (pTHX_ I32 type, I32 flags, OP* dynamic_meth) {
6637     PERL_ARGS_ASSERT_NEWMETHOP;
6638     return newMETHOP_internal(type, flags, dynamic_meth, NULL);
6639 }
6640
6641 /*
6642 =for apidoc newMETHOP_named
6643
6644 Constructs, checks, and returns an op of method type with a constant
6645 method name.  C<type> is the opcode.  C<flags> gives the eight bits of
6646 C<op_flags>, and, shifted up eight bits, the eight bits of
6647 C<op_private>.  C<const_meth> supplies a constant method name;
6648 it must be a shared COW string.
6649 Supported optypes: C<OP_METHOD_NAMED>.
6650
6651 =cut
6652 */
6653
6654 OP *
6655 Perl_newMETHOP_named (pTHX_ I32 type, I32 flags, SV* const_meth) {
6656     PERL_ARGS_ASSERT_NEWMETHOP_NAMED;
6657     return newMETHOP_internal(type, flags, NULL, const_meth);
6658 }
6659
6660 /*
6661 =for apidoc newBINOP
6662
6663 Constructs, checks, and returns an op of any binary type.  C<type>
6664 is the opcode.  C<flags> gives the eight bits of C<op_flags>, except
6665 that C<OPf_KIDS> will be set automatically, and, shifted up eight bits,
6666 the eight bits of C<op_private>, except that the bit with value 1 or
6667 2 is automatically set as required.  C<first> and C<last> supply up to
6668 two ops to be the direct children of the binary op; they are consumed
6669 by this function and become part of the constructed op tree.
6670
6671 =cut
6672 */
6673
6674 OP *
6675 Perl_newBINOP(pTHX_ I32 type, I32 flags, OP *first, OP *last)
6676 {
6677     dVAR;
6678     BINOP *binop;
6679
6680     ASSUME((PL_opargs[type] & OA_CLASS_MASK) == OA_BINOP
6681         || type == OP_NULL || type == OP_CUSTOM);
6682
6683     NewOp(1101, binop, 1, BINOP);
6684
6685     if (!first)
6686         first = newOP(OP_NULL, 0);
6687
6688     OpTYPE_set(binop, type);
6689     binop->op_first = first;
6690     binop->op_flags = (U8)(flags | OPf_KIDS);
6691     if (!last) {
6692         last = first;
6693         binop->op_private = (U8)(1 | (flags >> 8));
6694     }
6695     else {
6696         binop->op_private = (U8)(2 | (flags >> 8));
6697         OpMORESIB_set(first, last);
6698     }
6699
6700     if (!OpHAS_SIBLING(last)) /* true unless weird syntax error */
6701         OpLASTSIB_set(last, (OP*)binop);
6702
6703     binop->op_last = OpSIBLING(binop->op_first);
6704     if (binop->op_last)
6705         OpLASTSIB_set(binop->op_last, (OP*)binop);
6706
6707     binop = (BINOP*)CHECKOP(type, binop);
6708     if (binop->op_next || binop->op_type != (OPCODE)type)
6709         return (OP*)binop;
6710
6711     return fold_constants(op_integerize(op_std_init((OP *)binop)));
6712 }
6713
6714 /* Helper function for S_pmtrans(): comparison function to sort an array
6715  * of codepoint range pairs. Sorts by start point, or if equal, by end
6716  * point */
6717
6718 static int uvcompare(const void *a, const void *b)
6719     __attribute__nonnull__(1)
6720     __attribute__nonnull__(2)
6721     __attribute__pure__;
6722 static int uvcompare(const void *a, const void *b)
6723 {
6724     if (*((const UV *)a) < (*(const UV *)b))
6725         return -1;
6726     if (*((const UV *)a) > (*(const UV *)b))
6727         return 1;
6728     if (*((const UV *)a+1) < (*(const UV *)b+1))
6729         return -1;
6730     if (*((const UV *)a+1) > (*(const UV *)b+1))
6731         return 1;
6732     return 0;
6733 }
6734
6735 /* Given an OP_TRANS / OP_TRANSR op o, plus OP_CONST ops expr and repl
6736  * containing the search and replacement strings, assemble into
6737  * a translation table attached as o->op_pv.
6738  * Free expr and repl.
6739  * It expects the toker to have already set the
6740  *   OPpTRANS_COMPLEMENT
6741  *   OPpTRANS_SQUASH
6742  *   OPpTRANS_DELETE
6743  * flags as appropriate; this function may add
6744  *   OPpTRANS_FROM_UTF
6745  *   OPpTRANS_TO_UTF
6746  *   OPpTRANS_IDENTICAL
6747  *   OPpTRANS_GROWS
6748  * flags
6749  */
6750
6751 static OP *
6752 S_pmtrans(pTHX_ OP *o, OP *expr, OP *repl)
6753 {
6754     SV * const tstr = ((SVOP*)expr)->op_sv;
6755     SV * const rstr = ((SVOP*)repl)->op_sv;
6756     STRLEN tlen;
6757     STRLEN rlen;
6758     const U8 *t = (U8*)SvPV_const(tstr, tlen);
6759     const U8 *r = (U8*)SvPV_const(rstr, rlen);
6760     Size_t i, j;
6761     bool grows = FALSE;
6762     OPtrans_map *tbl;
6763     SSize_t struct_size; /* malloced size of table struct */
6764
6765     const bool complement = cBOOL(o->op_private & OPpTRANS_COMPLEMENT);
6766     const bool squash     = cBOOL(o->op_private & OPpTRANS_SQUASH);
6767     const bool del        = cBOOL(o->op_private & OPpTRANS_DELETE);
6768     SV* swash;
6769
6770     PERL_ARGS_ASSERT_PMTRANS;
6771
6772     PL_hints |= HINT_BLOCK_SCOPE;
6773
6774     if (SvUTF8(tstr))
6775         o->op_private |= OPpTRANS_FROM_UTF;
6776
6777     if (SvUTF8(rstr))
6778         o->op_private |= OPpTRANS_TO_UTF;
6779
6780     if (o->op_private & (OPpTRANS_FROM_UTF|OPpTRANS_TO_UTF)) {
6781
6782         /* for utf8 translations, op_sv will be set to point to a swash
6783          * containing codepoint ranges. This is done by first assembling
6784          * a textual representation of the ranges in listsv then compiling
6785          * it using swash_init(). For more details of the textual format,
6786          * see L<perlunicode.pod/"User-Defined Character Properties"> .
6787          */
6788
6789         SV* const listsv = newSVpvs("# comment\n");
6790         SV* transv = NULL;
6791         const U8* tend = t + tlen;
6792         const U8* rend = r + rlen;
6793         STRLEN ulen;
6794         UV tfirst = 1;
6795         UV tlast = 0;
6796         IV tdiff;
6797         STRLEN tcount = 0;
6798         UV rfirst = 1;
6799         UV rlast = 0;
6800         IV rdiff;
6801         STRLEN rcount = 0;
6802         IV diff;
6803         I32 none = 0;
6804         U32 max = 0;
6805         I32 bits;
6806         I32 havefinal = 0;
6807         U32 final = 0;
6808         const I32 from_utf  = o->op_private & OPpTRANS_FROM_UTF;
6809         const I32 to_utf    = o->op_private & OPpTRANS_TO_UTF;
6810         U8* tsave = NULL;
6811         U8* rsave = NULL;
6812         const U32 flags = UTF8_ALLOW_DEFAULT;
6813
6814         if (!from_utf) {
6815             STRLEN len = tlen;
6816             t = tsave = bytes_to_utf8(t, &len);
6817             tend = t + len;
6818         }
6819         if (!to_utf && rlen) {
6820             STRLEN len = rlen;
6821             r = rsave = bytes_to_utf8(r, &len);
6822             rend = r + len;
6823         }
6824
6825 /* There is a snag with this code on EBCDIC: scan_const() in toke.c has
6826  * encoded chars in native encoding which makes ranges in the EBCDIC 0..255
6827  * odd.  */
6828
6829         if (complement) {
6830             /* utf8 and /c:
6831              * replace t/tlen/tend with a version that has the ranges
6832              * complemented
6833              */
6834             U8 tmpbuf[UTF8_MAXBYTES+1];
6835             UV *cp;
6836             UV nextmin = 0;
6837             Newx(cp, 2*tlen, UV);
6838             i = 0;
6839             transv = newSVpvs("");
6840
6841             /* convert search string into array of (start,end) range
6842              * codepoint pairs stored in cp[]. Most "ranges" will start
6843              * and end at the same char */
6844             while (t < tend) {
6845                 cp[2*i] = utf8n_to_uvchr(t, tend-t, &ulen, flags);
6846                 t += ulen;
6847                 /* the toker converts X-Y into (X, ILLEGAL_UTF8_BYTE, Y) */
6848                 if (t < tend && *t == ILLEGAL_UTF8_BYTE) {
6849                     t++;
6850                     cp[2*i+1] = utf8n_to_uvchr(t, tend-t, &ulen, flags);
6851                     t += ulen;
6852                 }
6853                 else {
6854                  cp[2*i+1] = cp[2*i];
6855                 }
6856                 i++;
6857             }
6858
6859             /* sort the ranges */
6860             qsort(cp, i, 2*sizeof(UV), uvcompare);
6861
6862             /* Create a utf8 string containing the complement of the
6863              * codepoint ranges. For example if cp[] contains [A,B], [C,D],
6864              * then transv will contain the equivalent of:
6865              * join '', map chr, 0,     ILLEGAL_UTF8_BYTE, A - 1,
6866              *                   B + 1, ILLEGAL_UTF8_BYTE, C - 1,
6867              *                   D + 1, ILLEGAL_UTF8_BYTE, 0x7fffffff;
6868              * A range of a single char skips the ILLEGAL_UTF8_BYTE and
6869              * end cp.
6870              */
6871             for (j = 0; j < i; j++) {
6872                 UV  val = cp[2*j];
6873                 diff = val - nextmin;
6874                 if (diff > 0) {
6875                     t = uvchr_to_utf8(tmpbuf,nextmin);
6876                     sv_catpvn(transv, (char*)tmpbuf, t - tmpbuf);
6877                     if (diff > 1) {
6878                         U8  range_mark = ILLEGAL_UTF8_BYTE;
6879                         t = uvchr_to_utf8(tmpbuf, val - 1);
6880                         sv_catpvn(transv, (char *)&range_mark, 1);
6881                         sv_catpvn(transv, (char*)tmpbuf, t - tmpbuf);
6882                     }
6883                 }
6884                 val = cp[2*j+1];
6885                 if (val >= nextmin)
6886                     nextmin = val + 1;
6887             }
6888
6889             t = uvchr_to_utf8(tmpbuf,nextmin);
6890             sv_catpvn(transv, (char*)tmpbuf, t - tmpbuf);
6891             {
6892                 U8 range_mark = ILLEGAL_UTF8_BYTE;
6893                 sv_catpvn(transv, (char *)&range_mark, 1);
6894             }
6895             t = uvchr_to_utf8(tmpbuf, 0x7fffffff);
6896             sv_catpvn(transv, (char*)tmpbuf, t - tmpbuf);
6897             t = (const U8*)SvPVX_const(transv);
6898             tlen = SvCUR(transv);
6899             tend = t + tlen;
6900             Safefree(cp);
6901         }
6902         else if (!rlen && !del) {
6903             r = t; rlen = tlen; rend = tend;
6904         }
6905
6906         if (!squash) {
6907                 if ((!rlen && !del) || t == r ||
6908                     (tlen == rlen && memEQ((char *)t, (char *)r, tlen)))
6909                 {
6910                     o->op_private |= OPpTRANS_IDENTICAL;
6911                 }
6912         }
6913
6914         /* extract char ranges from t and r and append them to listsv */
6915
6916         while (t < tend || tfirst <= tlast) {
6917             /* see if we need more "t" chars */
6918             if (tfirst > tlast) {
6919                 tfirst = (I32)utf8n_to_uvchr(t, tend - t, &ulen, flags);
6920                 t += ulen;
6921                 if (t < tend && *t == ILLEGAL_UTF8_BYTE) {      /* illegal utf8 val indicates range */
6922                     t++;
6923                     tlast = (I32)utf8n_to_uvchr(t, tend - t, &ulen, flags);
6924                     t += ulen;
6925                 }
6926                 else
6927                     tlast = tfirst;
6928             }
6929
6930             /* now see if we need more "r" chars */
6931             if (rfirst > rlast) {
6932                 if (r < rend) {
6933                     rfirst = (I32)utf8n_to_uvchr(r, rend - r, &ulen, flags);
6934                     r += ulen;
6935                     if (r < rend && *r == ILLEGAL_UTF8_BYTE) {  /* illegal utf8 val indicates range */
6936                         r++;
6937                         rlast = (I32)utf8n_to_uvchr(r, rend - r, &ulen, flags);
6938                         r += ulen;
6939                     }
6940                     else
6941                         rlast = rfirst;
6942                 }
6943                 else {
6944                     if (!havefinal++)
6945                         final = rlast;
6946                     rfirst = rlast = 0xffffffff;
6947                 }
6948             }
6949
6950             /* now see which range will peter out first, if either. */
6951             tdiff = tlast - tfirst;
6952             rdiff = rlast - rfirst;
6953             tcount += tdiff + 1;
6954             rcount += rdiff + 1;
6955
6956             if (tdiff <= rdiff)
6957                 diff = tdiff;
6958             else
6959                 diff = rdiff;
6960
6961             if (rfirst == 0xffffffff) {
6962                 diff = tdiff;   /* oops, pretend rdiff is infinite */
6963                 if (diff > 0)
6964                     Perl_sv_catpvf(aTHX_ listsv, "%04lx\t%04lx\tXXXX\n",
6965                                    (long)tfirst, (long)tlast);
6966                 else
6967                     Perl_sv_catpvf(aTHX_ listsv, "%04lx\t\tXXXX\n", (long)tfirst);
6968             }
6969             else {
6970                 if (diff > 0)
6971                     Perl_sv_catpvf(aTHX_ listsv, "%04lx\t%04lx\t%04lx\n",
6972                                    (long)tfirst, (long)(tfirst + diff),
6973                                    (long)rfirst);
6974                 else
6975                     Perl_sv_catpvf(aTHX_ listsv, "%04lx\t\t%04lx\n",
6976                                    (long)tfirst, (long)rfirst);
6977
6978                 if (rfirst + diff > max)
6979                     max = rfirst + diff;
6980                 if (!grows)
6981                     grows = (tfirst < rfirst &&
6982                              UVCHR_SKIP(tfirst) < UVCHR_SKIP(rfirst + diff));
6983                 rfirst += diff + 1;
6984             }
6985             tfirst += diff + 1;
6986         }
6987
6988         /* compile listsv into a swash and attach to o */
6989
6990         none = ++max;
6991         if (del)
6992             ++max;
6993
6994         if (max > 0xffff)
6995             bits = 32;
6996         else if (max > 0xff)
6997             bits = 16;
6998         else
6999             bits = 8;
7000
7001         swash = MUTABLE_SV(swash_init("utf8", "", listsv, bits, none));
7002 #ifdef USE_ITHREADS
7003         cPADOPo->op_padix = pad_alloc(OP_TRANS, SVf_READONLY);
7004         SvREFCNT_dec(PAD_SVl(cPADOPo->op_padix));
7005         PAD_SETSV(cPADOPo->op_padix, swash);
7006         SvPADTMP_on(swash);
7007         SvREADONLY_on(swash);
7008 #else
7009         cSVOPo->op_sv = swash;
7010 #endif
7011         SvREFCNT_dec(listsv);
7012         SvREFCNT_dec(transv);
7013
7014         if (!del && havefinal && rlen)
7015             (void)hv_store(MUTABLE_HV(SvRV(swash)), "FINAL", 5,
7016                            newSVuv((UV)final), 0);
7017
7018         Safefree(tsave);
7019         Safefree(rsave);
7020
7021         tlen = tcount;
7022         rlen = rcount;
7023         if (r < rend)
7024             rlen++;
7025         else if (rlast == 0xffffffff)
7026             rlen = 0;
7027
7028         goto warnins;
7029     }
7030
7031     /* Non-utf8 case: set o->op_pv to point to a simple 256+ entry lookup
7032      * table. Entries with the value -1 indicate chars not to be
7033      * translated, while -2 indicates a search char without a
7034      * corresponding replacement char under /d.
7035      *
7036      * Normally, the table has 256 slots. However, in the presence of
7037      * /c, the search charlist has an implicit \x{100}-\x{7fffffff}
7038      * added, and if there are enough replacement chars to start pairing
7039      * with the \x{100},... search chars, then a larger (> 256) table
7040      * is allocated.
7041      *
7042      * In addition, regardless of whether under /c, an extra slot at the
7043      * end is used to store the final repeating char, or -3 under an empty
7044      * replacement list, or -2 under /d; which makes the runtime code
7045      * easier.
7046      *
7047      * The toker will have already expanded char ranges in t and r.
7048      */
7049
7050     /* Initially allocate 257-slot table: 256 for basic (non /c) usage,
7051      * plus final slot for repeat/-2/-3. Later we realloc if excess > * 0.
7052      * The OPtrans_map struct already contains one slot; hence the -1.
7053      */
7054     struct_size = sizeof(OPtrans_map) + (256 - 1 + 1)*sizeof(short);
7055     tbl = (OPtrans_map*)PerlMemShared_calloc(struct_size, 1);
7056     tbl->size = 256;
7057     cPVOPo->op_pv = (char*)tbl;
7058
7059     if (complement) {
7060         Size_t excess;
7061
7062         /* in this branch, j is a count of 'consumed' (i.e. paired off
7063          * with a search char) replacement chars (so j <= rlen always)
7064          */
7065         for (i = 0; i < tlen; i++)
7066             tbl->map[t[i]] = -1;
7067
7068         for (i = 0, j = 0; i < 256; i++) {
7069             if (!tbl->map[i]) {
7070                 if (j == rlen) {
7071                     if (del)
7072                         tbl->map[i] = -2;
7073                     else if (rlen)
7074                         tbl->map[i] = r[j-1];
7075                     else
7076                         tbl->map[i] = (short)i;
7077                 }
7078                 else {
7079                     tbl->map[i] = r[j++];
7080                 }
7081                 if (   tbl->map[i] >= 0
7082                     &&  UVCHR_IS_INVARIANT((UV)i)
7083                     && !UVCHR_IS_INVARIANT((UV)(tbl->map[i]))
7084                 )
7085                     grows = TRUE;
7086             }
7087         }
7088
7089         ASSUME(j <= rlen);
7090         excess = rlen - j;
7091
7092         if (excess) {
7093             /* More replacement chars than search chars:
7094              * store excess replacement chars at end of main table.
7095              */
7096
7097             struct_size += excess;
7098             tbl = (OPtrans_map*)PerlMemShared_realloc(tbl,
7099                         struct_size + excess * sizeof(short));
7100             tbl->size += excess;
7101             cPVOPo->op_pv = (char*)tbl;
7102
7103             for (i = 0; i < excess; i++)
7104                 tbl->map[i + 256] = r[j+i];
7105         }
7106         else {
7107             /* no more replacement chars than search chars */
7108             if (!rlen && !del && !squash)
7109                 o->op_private |= OPpTRANS_IDENTICAL;
7110         }
7111
7112         tbl->map[tbl->size] = del ? -2 : rlen ? r[rlen - 1] : -3;
7113     }
7114     else {
7115         if (!rlen && !del) {
7116             r = t; rlen = tlen;
7117             if (!squash)
7118                 o->op_private |= OPpTRANS_IDENTICAL;
7119         }
7120         else if (!squash && rlen == tlen && memEQ((char*)t, (char*)r, tlen)) {
7121             o->op_private |= OPpTRANS_IDENTICAL;
7122         }
7123
7124         for (i = 0; i < 256; i++)
7125             tbl->map[i] = -1;
7126         for (i = 0, j = 0; i < tlen; i++,j++) {
7127             if (j >= rlen) {
7128                 if (del) {
7129                     if (tbl->map[t[i]] == -1)
7130                         tbl->map[t[i]] = -2;
7131                     continue;
7132                 }
7133                 --j;
7134             }
7135             if (tbl->map[t[i]] == -1) {
7136                 if (     UVCHR_IS_INVARIANT(t[i])
7137                     && ! UVCHR_IS_INVARIANT(r[j]))
7138                     grows = TRUE;
7139                 tbl->map[t[i]] = r[j];
7140             }
7141         }
7142         tbl->map[tbl->size] = del ? -1 : rlen ? -1 : -3;
7143     }
7144
7145     /* both non-utf8 and utf8 code paths end up here */
7146
7147   warnins:
7148     if(del && rlen == tlen) {
7149         Perl_ck_warner(aTHX_ packWARN(WARN_MISC), "Useless use of /d modifier in transliteration operator"); 
7150     } else if(rlen > tlen && !complement) {
7151         Perl_ck_warner(aTHX_ packWARN(WARN_MISC), "Replacement list is longer than search list");
7152     }
7153
7154     if (grows)
7155         o->op_private |= OPpTRANS_GROWS;
7156     op_free(expr);
7157     op_free(repl);
7158
7159     return o;
7160 }
7161
7162
7163 /*
7164 =for apidoc newPMOP
7165
7166 Constructs, checks, and returns an op of any pattern matching type.
7167 C<type> is the opcode.  C<flags> gives the eight bits of C<op_flags>
7168 and, shifted up eight bits, the eight bits of C<op_private>.
7169
7170 =cut
7171 */
7172
7173 OP *
7174 Perl_newPMOP(pTHX_ I32 type, I32 flags)
7175 {
7176     dVAR;
7177     PMOP *pmop;
7178
7179     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_PMOP
7180         || type == OP_CUSTOM);
7181
7182     NewOp(1101, pmop, 1, PMOP);
7183     OpTYPE_set(pmop, type);
7184     pmop->op_flags = (U8)flags;
7185     pmop->op_private = (U8)(0 | (flags >> 8));
7186     if (PL_opargs[type] & OA_RETSCALAR)
7187         scalar((OP *)pmop);
7188
7189     if (PL_hints & HINT_RE_TAINT)
7190         pmop->op_pmflags |= PMf_RETAINT;
7191 #ifdef USE_LOCALE_CTYPE
7192     if (IN_LC_COMPILETIME(LC_CTYPE)) {
7193         set_regex_charset(&(pmop->op_pmflags), REGEX_LOCALE_CHARSET);
7194     }
7195     else
7196 #endif
7197          if (IN_UNI_8_BIT) {
7198         set_regex_charset(&(pmop->op_pmflags), REGEX_UNICODE_CHARSET);
7199     }
7200     if (PL_hints & HINT_RE_FLAGS) {
7201         SV *reflags = Perl_refcounted_he_fetch_pvn(aTHX_
7202          PL_compiling.cop_hints_hash, STR_WITH_LEN("reflags"), 0, 0
7203         );
7204         if (reflags && SvOK(reflags)) pmop->op_pmflags |= SvIV(reflags);
7205         reflags = Perl_refcounted_he_fetch_pvn(aTHX_
7206          PL_compiling.cop_hints_hash, STR_WITH_LEN("reflags_charset"), 0, 0
7207         );
7208         if (reflags && SvOK(reflags)) {
7209             set_regex_charset(&(pmop->op_pmflags), (regex_charset)SvIV(reflags));
7210         }
7211     }
7212
7213
7214 #ifdef USE_ITHREADS
7215     assert(SvPOK(PL_regex_pad[0]));
7216     if (SvCUR(PL_regex_pad[0])) {
7217         /* Pop off the "packed" IV from the end.  */
7218         SV *const repointer_list = PL_regex_pad[0];
7219         const char *p = SvEND(repointer_list) - sizeof(IV);
7220         const IV offset = *((IV*)p);
7221
7222         assert(SvCUR(repointer_list) % sizeof(IV) == 0);
7223
7224         SvEND_set(repointer_list, p);
7225
7226         pmop->op_pmoffset = offset;
7227         /* This slot should be free, so assert this:  */
7228         assert(PL_regex_pad[offset] == &PL_sv_undef);
7229     } else {
7230         SV * const repointer = &PL_sv_undef;
7231         av_push(PL_regex_padav, repointer);
7232         pmop->op_pmoffset = av_tindex(PL_regex_padav);
7233         PL_regex_pad = AvARRAY(PL_regex_padav);
7234     }
7235 #endif
7236
7237     return CHECKOP(type, pmop);
7238 }
7239
7240 static void
7241 S_set_haseval(pTHX)
7242 {
7243     PADOFFSET i = 1;
7244     PL_cv_has_eval = 1;
7245     /* Any pad names in scope are potentially lvalues.  */
7246     for (; i < PadnamelistMAXNAMED(PL_comppad_name); i++) {
7247         PADNAME *pn = PAD_COMPNAME_SV(i);
7248         if (!pn || !PadnameLEN(pn))
7249             continue;
7250         if (PadnameOUTER(pn) || PadnameIN_SCOPE(pn, PL_cop_seqmax))
7251             S_mark_padname_lvalue(aTHX_ pn);
7252     }
7253 }
7254
7255 /* Given some sort of match op o, and an expression expr containing a
7256  * pattern, either compile expr into a regex and attach it to o (if it's
7257  * constant), or convert expr into a runtime regcomp op sequence (if it's
7258  * not)
7259  *
7260  * Flags currently has 2 bits of meaning:
7261  * 1: isreg indicates that the pattern is part of a regex construct, eg
7262  * $x =~ /pattern/ or split /pattern/, as opposed to $x =~ $pattern or
7263  * split "pattern", which aren't. In the former case, expr will be a list
7264  * if the pattern contains more than one term (eg /a$b/).
7265  * 2: The pattern is for a split.
7266  *
7267  * When the pattern has been compiled within a new anon CV (for
7268  * qr/(?{...})/ ), then floor indicates the savestack level just before
7269  * the new sub was created
7270  */
7271
7272 OP *
7273 Perl_pmruntime(pTHX_ OP *o, OP *expr, OP *repl, UV flags, I32 floor)
7274 {
7275     PMOP *pm;
7276     LOGOP *rcop;
7277     I32 repl_has_vars = 0;
7278     bool is_trans = (o->op_type == OP_TRANS || o->op_type == OP_TRANSR);
7279     bool is_compiletime;
7280     bool has_code;
7281     bool isreg    = cBOOL(flags & 1);
7282     bool is_split = cBOOL(flags & 2);
7283
7284     PERL_ARGS_ASSERT_PMRUNTIME;
7285
7286     if (is_trans) {
7287         return pmtrans(o, expr, repl);
7288     }
7289
7290     /* find whether we have any runtime or code elements;
7291      * at the same time, temporarily set the op_next of each DO block;
7292      * then when we LINKLIST, this will cause the DO blocks to be excluded
7293      * from the op_next chain (and from having LINKLIST recursively
7294      * applied to them). We fix up the DOs specially later */
7295
7296     is_compiletime = 1;
7297     has_code = 0;
7298     if (expr->op_type == OP_LIST) {
7299         OP *o;
7300         for (o = cLISTOPx(expr)->op_first; o; o = OpSIBLING(o)) {
7301             if (o->op_type == OP_NULL && (o->op_flags & OPf_SPECIAL)) {
7302                 has_code = 1;
7303                 assert(!o->op_next);
7304                 if (UNLIKELY(!OpHAS_SIBLING(o))) {
7305                     assert(PL_parser && PL_parser->error_count);
7306                     /* This can happen with qr/ (?{(^{})/.  Just fake up
7307                        the op we were expecting to see, to avoid crashing
7308                        elsewhere.  */
7309                     op_sibling_splice(expr, o, 0,
7310                                       newSVOP(OP_CONST, 0, &PL_sv_no));
7311                 }
7312                 o->op_next = OpSIBLING(o);
7313             }
7314             else if (o->op_type != OP_CONST && o->op_type != OP_PUSHMARK)
7315                 is_compiletime = 0;
7316         }
7317     }
7318     else if (expr->op_type != OP_CONST)
7319         is_compiletime = 0;
7320
7321     LINKLIST(expr);
7322
7323     /* fix up DO blocks; treat each one as a separate little sub;
7324      * also, mark any arrays as LIST/REF */
7325
7326     if (expr->op_type == OP_LIST) {
7327         OP *o;
7328         for (o = cLISTOPx(expr)->op_first; o; o = OpSIBLING(o)) {
7329
7330             if (o->op_type == OP_PADAV || o->op_type == OP_RV2AV) {
7331                 assert( !(o->op_flags  & OPf_WANT));
7332                 /* push the array rather than its contents. The regex
7333                  * engine will retrieve and join the elements later */
7334                 o->op_flags |= (OPf_WANT_LIST | OPf_REF);
7335                 continue;
7336             }
7337
7338             if (!(o->op_type == OP_NULL && (o->op_flags & OPf_SPECIAL)))
7339                 continue;
7340             o->op_next = NULL; /* undo temporary hack from above */
7341             scalar(o);
7342             LINKLIST(o);
7343             if (cLISTOPo->op_first->op_type == OP_LEAVE) {
7344                 LISTOP *leaveop = cLISTOPx(cLISTOPo->op_first);
7345                 /* skip ENTER */
7346                 assert(leaveop->op_first->op_type == OP_ENTER);
7347                 assert(OpHAS_SIBLING(leaveop->op_first));
7348                 o->op_next = OpSIBLING(leaveop->op_first);
7349                 /* skip leave */
7350                 assert(leaveop->op_flags & OPf_KIDS);
7351                 assert(leaveop->op_last->op_next == (OP*)leaveop);
7352                 leaveop->op_next = NULL; /* stop on last op */
7353                 op_null((OP*)leaveop);
7354             }
7355             else {
7356                 /* skip SCOPE */
7357                 OP *scope = cLISTOPo->op_first;
7358                 assert(scope->op_type == OP_SCOPE);
7359                 assert(scope->op_flags & OPf_KIDS);
7360                 scope->op_next = NULL; /* stop on last op */
7361                 op_null(scope);
7362             }
7363
7364             /* XXX optimize_optree() must be called on o before
7365              * CALL_PEEP(), as currently S_maybe_multiconcat() can't
7366              * currently cope with a peephole-optimised optree.
7367              * Calling optimize_optree() here ensures that condition
7368              * is met, but may mean optimize_optree() is applied
7369              * to the same optree later (where hopefully it won't do any
7370              * harm as it can't convert an op to multiconcat if it's
7371              * already been converted */
7372             optimize_optree(o);
7373
7374             /* have to peep the DOs individually as we've removed it from
7375              * the op_next chain */
7376             CALL_PEEP(o);
7377             S_prune_chain_head(&(o->op_next));
7378             if (is_compiletime)
7379                 /* runtime finalizes as part of finalizing whole tree */
7380                 finalize_optree(o);
7381         }
7382     }
7383     else if (expr->op_type == OP_PADAV || expr->op_type == OP_RV2AV) {
7384         assert( !(expr->op_flags  & OPf_WANT));
7385         /* push the array rather than its contents. The regex
7386          * engine will retrieve and join the elements later */
7387         expr->op_flags |= (OPf_WANT_LIST | OPf_REF);
7388     }
7389
7390     PL_hints |= HINT_BLOCK_SCOPE;
7391     pm = (PMOP*)o;
7392     assert(floor==0 || (pm->op_pmflags & PMf_HAS_CV));
7393
7394     if (is_compiletime) {
7395         U32 rx_flags = pm->op_pmflags & RXf_PMf_COMPILETIME;
7396         regexp_engine const *eng = current_re_engine();
7397
7398         if (is_split) {
7399             /* make engine handle split ' ' specially */
7400             pm->op_pmflags |= PMf_SPLIT;
7401             rx_flags |= RXf_SPLIT;
7402         }
7403
7404         if (!has_code || !eng->op_comp) {
7405             /* compile-time simple constant pattern */
7406
7407             if ((pm->op_pmflags & PMf_HAS_CV) && !has_code) {
7408                 /* whoops! we guessed that a qr// had a code block, but we
7409                  * were wrong (e.g. /[(?{}]/ ). Throw away the PL_compcv
7410                  * that isn't required now. Note that we have to be pretty
7411                  * confident that nothing used that CV's pad while the
7412                  * regex was parsed, except maybe op targets for \Q etc.
7413                  * If there were any op targets, though, they should have
7414                  * been stolen by constant folding.
7415                  */
7416 #ifdef DEBUGGING
7417                 SSize_t i = 0;
7418                 assert(PadnamelistMAXNAMED(PL_comppad_name) == 0);
7419                 while (++i <= AvFILLp(PL_comppad)) {
7420 #  ifdef USE_PAD_RESET
7421                     /* under USE_PAD_RESET, pad swipe replaces a swiped
7422                      * folded constant with a fresh padtmp */
7423                     assert(!PL_curpad[i] || SvPADTMP(PL_curpad[i]));
7424 #  else
7425                     assert(!PL_curpad[i]);
7426 #  endif
7427                 }
7428 #endif
7429                 /* This LEAVE_SCOPE will restore PL_compcv to point to the
7430                  * outer CV (the one whose slab holds the pm op). The
7431                  * inner CV (which holds expr) will be freed later, once
7432                  * all the entries on the parse stack have been popped on
7433                  * return from this function. Which is why its safe to
7434                  * call op_free(expr) below.
7435                  */
7436                 LEAVE_SCOPE(floor);
7437                 pm->op_pmflags &= ~PMf_HAS_CV;
7438             }
7439
7440             /* Skip compiling if parser found an error for this pattern */
7441             if (pm->op_pmflags & PMf_HAS_ERROR) {
7442                 return o;
7443             }
7444
7445             PM_SETRE(pm,
7446                 eng->op_comp
7447                     ? eng->op_comp(aTHX_ NULL, 0, expr, eng, NULL, NULL,
7448                                         rx_flags, pm->op_pmflags)
7449                     : Perl_re_op_compile(aTHX_ NULL, 0, expr, eng, NULL, NULL,
7450                                         rx_flags, pm->op_pmflags)
7451             );
7452             op_free(expr);
7453         }
7454         else {
7455             /* compile-time pattern that includes literal code blocks */
7456
7457             REGEXP* re;
7458
7459             /* Skip compiling if parser found an error for this pattern */
7460             if (pm->op_pmflags & PMf_HAS_ERROR) {
7461                 return o;
7462             }
7463
7464             re = eng->op_comp(aTHX_ NULL, 0, expr, eng, NULL, NULL,
7465                         rx_flags,
7466                         (pm->op_pmflags |
7467                             ((PL_hints & HINT_RE_EVAL) ? PMf_USE_RE_EVAL : 0))
7468                     );
7469             PM_SETRE(pm, re);
7470             if (pm->op_pmflags & PMf_HAS_CV) {
7471                 CV *cv;
7472                 /* this QR op (and the anon sub we embed it in) is never
7473                  * actually executed. It's just a placeholder where we can
7474                  * squirrel away expr in op_code_list without the peephole
7475                  * optimiser etc processing it for a second time */
7476                 OP *qr = newPMOP(OP_QR, 0);
7477                 ((PMOP*)qr)->op_code_list = expr;
7478
7479                 /* handle the implicit sub{} wrapped round the qr/(?{..})/ */
7480                 SvREFCNT_inc_simple_void(PL_compcv);
7481                 cv = newATTRSUB(floor, 0, NULL, NULL, qr);
7482                 ReANY(re)->qr_anoncv = cv;
7483
7484                 /* attach the anon CV to the pad so that
7485                  * pad_fixup_inner_anons() can find it */
7486                 (void)pad_add_anon(cv, o->op_type);
7487                 SvREFCNT_inc_simple_void(cv);
7488             }
7489             else {
7490                 pm->op_code_list = expr;
7491             }
7492         }
7493     }
7494     else {
7495         /* runtime pattern: build chain of regcomp etc ops */
7496         bool reglist;
7497         PADOFFSET cv_targ = 0;
7498
7499         reglist = isreg && expr->op_type == OP_LIST;
7500         if (reglist)
7501             op_null(expr);
7502
7503         if (has_code) {
7504             pm->op_code_list = expr;
7505             /* don't free op_code_list; its ops are embedded elsewhere too */
7506             pm->op_pmflags |= PMf_CODELIST_PRIVATE;
7507         }
7508
7509         if (is_split)
7510             /* make engine handle split ' ' specially */
7511             pm->op_pmflags |= PMf_SPLIT;
7512
7513         /* the OP_REGCMAYBE is a placeholder in the non-threaded case
7514          * to allow its op_next to be pointed past the regcomp and
7515          * preceding stacking ops;
7516          * OP_REGCRESET is there to reset taint before executing the
7517          * stacking ops */
7518         if (pm->op_pmflags & PMf_KEEP || TAINTING_get)
7519             expr = newUNOP((TAINTING_get ? OP_REGCRESET : OP_REGCMAYBE),0,expr);
7520
7521         if (pm->op_pmflags & PMf_HAS_CV) {
7522             /* we have a runtime qr with literal code. This means
7523              * that the qr// has been wrapped in a new CV, which
7524              * means that runtime consts, vars etc will have been compiled
7525              * against a new pad. So... we need to execute those ops
7526              * within the environment of the new CV. So wrap them in a call
7527              * to a new anon sub. i.e. for
7528              *
7529              *     qr/a$b(?{...})/,
7530              *
7531              * we build an anon sub that looks like
7532              *
7533              *     sub { "a", $b, '(?{...})' }
7534              *
7535              * and call it, passing the returned list to regcomp.
7536              * Or to put it another way, the list of ops that get executed
7537              * are:
7538              *
7539              *     normal              PMf_HAS_CV
7540              *     ------              -------------------
7541              *                         pushmark (for regcomp)
7542              *                         pushmark (for entersub)
7543              *                         anoncode
7544              *                         srefgen
7545              *                         entersub
7546              *     regcreset                  regcreset
7547              *     pushmark                   pushmark
7548              *     const("a")                 const("a")
7549              *     gvsv(b)                    gvsv(b)
7550              *     const("(?{...})")          const("(?{...})")
7551              *                                leavesub
7552              *     regcomp             regcomp
7553              */
7554
7555             SvREFCNT_inc_simple_void(PL_compcv);
7556             CvLVALUE_on(PL_compcv);
7557             /* these lines are just an unrolled newANONATTRSUB */
7558             expr = newSVOP(OP_ANONCODE, 0,
7559                     MUTABLE_SV(newATTRSUB(floor, 0, NULL, NULL, expr)));
7560             cv_targ = expr->op_targ;
7561             expr = newUNOP(OP_REFGEN, 0, expr);
7562
7563             expr = list(force_list(newUNOP(OP_ENTERSUB, 0, scalar(expr)), 1));
7564         }
7565
7566         rcop = alloc_LOGOP(OP_REGCOMP, scalar(expr), o);
7567         rcop->op_flags |=  ((PL_hints & HINT_RE_EVAL) ? OPf_SPECIAL : 0)
7568                            | (reglist ? OPf_STACKED : 0);
7569         rcop->op_targ = cv_targ;
7570
7571         /* /$x/ may cause an eval, since $x might be qr/(?{..})/  */
7572         if (PL_hints & HINT_RE_EVAL)
7573             S_set_haseval(aTHX);
7574
7575         /* establish postfix order */
7576         if (expr->op_type == OP_REGCRESET || expr->op_type == OP_REGCMAYBE) {
7577             LINKLIST(expr);
7578             rcop->op_next = expr;
7579             ((UNOP*)expr)->op_first->op_next = (OP*)rcop;
7580         }
7581         else {
7582             rcop->op_next = LINKLIST(expr);
7583             expr->op_next = (OP*)rcop;
7584         }
7585
7586         op_prepend_elem(o->op_type, scalar((OP*)rcop), o);
7587     }
7588
7589     if (repl) {
7590         OP *curop = repl;
7591         bool konst;
7592         /* If we are looking at s//.../e with a single statement, get past
7593            the implicit do{}. */
7594         if (curop->op_type == OP_NULL && curop->op_flags & OPf_KIDS
7595              && cUNOPx(curop)->op_first->op_type == OP_SCOPE
7596              && cUNOPx(curop)->op_first->op_flags & OPf_KIDS)
7597          {
7598             OP *sib;
7599             OP *kid = cUNOPx(cUNOPx(curop)->op_first)->op_first;
7600             if (kid->op_type == OP_NULL && (sib = OpSIBLING(kid))
7601              && !OpHAS_SIBLING(sib))
7602                 curop = sib;
7603         }
7604         if (curop->op_type == OP_CONST)
7605             konst = TRUE;
7606         else if (( (curop->op_type == OP_RV2SV ||
7607                     curop->op_type == OP_RV2AV ||
7608                     curop->op_type == OP_RV2HV ||
7609                     curop->op_type == OP_RV2GV)
7610                    && cUNOPx(curop)->op_first
7611                    && cUNOPx(curop)->op_first->op_type == OP_GV )
7612                 || curop->op_type == OP_PADSV
7613                 || curop->op_type == OP_PADAV
7614                 || curop->op_type == OP_PADHV
7615                 || curop->op_type == OP_PADANY) {
7616             repl_has_vars = 1;
7617             konst = TRUE;
7618         }
7619         else konst = FALSE;
7620         if (konst
7621             && !(repl_has_vars
7622                  && (!PM_GETRE(pm)
7623                      || !RX_PRELEN(PM_GETRE(pm))
7624                      || RX_EXTFLAGS(PM_GETRE(pm)) & RXf_EVAL_SEEN)))
7625         {
7626             pm->op_pmflags |= PMf_CONST;        /* const for long enough */
7627             op_prepend_elem(o->op_type, scalar(repl), o);
7628         }
7629         else {
7630             rcop = alloc_LOGOP(OP_SUBSTCONT, scalar(repl), o);
7631             rcop->op_private = 1;
7632
7633             /* establish postfix order */
7634             rcop->op_next = LINKLIST(repl);
7635             repl->op_next = (OP*)rcop;
7636
7637             pm->op_pmreplrootu.op_pmreplroot = scalar((OP*)rcop);
7638             assert(!(pm->op_pmflags & PMf_ONCE));
7639             pm->op_pmstashstartu.op_pmreplstart = LINKLIST(rcop);
7640             rcop->op_next = 0;
7641         }
7642     }
7643
7644     return (OP*)pm;
7645 }
7646
7647 /*
7648 =for apidoc newSVOP
7649
7650 Constructs, checks, and returns an op of any type that involves an
7651 embedded SV.  C<type> is the opcode.  C<flags> gives the eight bits
7652 of C<op_flags>.  C<sv> gives the SV to embed in the op; this function
7653 takes ownership of one reference to it.
7654
7655 =cut
7656 */
7657
7658 OP *
7659 Perl_newSVOP(pTHX_ I32 type, I32 flags, SV *sv)
7660 {
7661     dVAR;
7662     SVOP *svop;
7663
7664     PERL_ARGS_ASSERT_NEWSVOP;
7665
7666     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_SVOP
7667         || (PL_opargs[type] & OA_CLASS_MASK) == OA_PVOP_OR_SVOP
7668         || (PL_opargs[type] & OA_CLASS_MASK) == OA_FILESTATOP
7669         || type == OP_CUSTOM);
7670
7671     NewOp(1101, svop, 1, SVOP);
7672     OpTYPE_set(svop, type);
7673     svop->op_sv = sv;
7674     svop->op_next = (OP*)svop;
7675     svop->op_flags = (U8)flags;
7676     svop->op_private = (U8)(0 | (flags >> 8));
7677     if (PL_opargs[type] & OA_RETSCALAR)
7678         scalar((OP*)svop);
7679     if (PL_opargs[type] & OA_TARGET)
7680         svop->op_targ = pad_alloc(type, SVs_PADTMP);
7681     return CHECKOP(type, svop);
7682 }
7683
7684 /*
7685 =for apidoc newDEFSVOP
7686
7687 Constructs and returns an op to access C<$_>.
7688
7689 =cut
7690 */
7691
7692 OP *
7693 Perl_newDEFSVOP(pTHX)
7694 {
7695         return newSVREF(newGVOP(OP_GV, 0, PL_defgv));
7696 }
7697
7698 #ifdef USE_ITHREADS
7699
7700 /*
7701 =for apidoc newPADOP
7702
7703 Constructs, checks, and returns an op of any type that involves a
7704 reference to a pad element.  C<type> is the opcode.  C<flags> gives the
7705 eight bits of C<op_flags>.  A pad slot is automatically allocated, and
7706 is populated with C<sv>; this function takes ownership of one reference
7707 to it.
7708
7709 This function only exists if Perl has been compiled to use ithreads.
7710
7711 =cut
7712 */
7713
7714 OP *
7715 Perl_newPADOP(pTHX_ I32 type, I32 flags, SV *sv)
7716 {
7717     dVAR;
7718     PADOP *padop;
7719
7720     PERL_ARGS_ASSERT_NEWPADOP;
7721
7722     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_SVOP
7723         || (PL_opargs[type] & OA_CLASS_MASK) == OA_PVOP_OR_SVOP
7724         || (PL_opargs[type] & OA_CLASS_MASK) == OA_FILESTATOP
7725         || type == OP_CUSTOM);
7726
7727     NewOp(1101, padop, 1, PADOP);
7728     OpTYPE_set(padop, type);
7729     padop->op_padix =
7730         pad_alloc(type, isGV(sv) ? SVf_READONLY : SVs_PADTMP);
7731     SvREFCNT_dec(PAD_SVl(padop->op_padix));
7732     PAD_SETSV(padop->op_padix, sv);
7733     assert(sv);
7734     padop->op_next = (OP*)padop;
7735     padop->op_flags = (U8)flags;
7736     if (PL_opargs[type] & OA_RETSCALAR)
7737         scalar((OP*)padop);
7738     if (PL_opargs[type] & OA_TARGET)
7739         padop->op_targ = pad_alloc(type, SVs_PADTMP);
7740     return CHECKOP(type, padop);
7741 }
7742
7743 #endif /* USE_ITHREADS */
7744
7745 /*
7746 =for apidoc newGVOP
7747
7748 Constructs, checks, and returns an op of any type that involves an
7749 embedded reference to a GV.  C<type> is the opcode.  C<flags> gives the
7750 eight bits of C<op_flags>.  C<gv> identifies the GV that the op should
7751 reference; calling this function does not transfer ownership of any
7752 reference to it.
7753
7754 =cut
7755 */
7756
7757 OP *
7758 Perl_newGVOP(pTHX_ I32 type, I32 flags, GV *gv)
7759 {
7760     PERL_ARGS_ASSERT_NEWGVOP;
7761
7762 #ifdef USE_ITHREADS
7763     return newPADOP(type, flags, SvREFCNT_inc_simple_NN(gv));
7764 #else
7765     return newSVOP(type, flags, SvREFCNT_inc_simple_NN(gv));
7766 #endif
7767 }
7768
7769 /*
7770 =for apidoc newPVOP
7771
7772 Constructs, checks, and returns an op of any type that involves an
7773 embedded C-level pointer (PV).  C<type> is the opcode.  C<flags> gives
7774 the eight bits of C<op_flags>.  C<pv> supplies the C-level pointer.
7775 Depending on the op type, the memory referenced by C<pv> may be freed
7776 when the op is destroyed.  If the op is of a freeing type, C<pv> must
7777 have been allocated using C<PerlMemShared_malloc>.
7778
7779 =cut
7780 */
7781
7782 OP *
7783 Perl_newPVOP(pTHX_ I32 type, I32 flags, char *pv)
7784 {
7785     dVAR;
7786     const bool utf8 = cBOOL(flags & SVf_UTF8);
7787     PVOP *pvop;
7788
7789     flags &= ~SVf_UTF8;
7790
7791     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_PVOP_OR_SVOP
7792         || type == OP_RUNCV || type == OP_CUSTOM
7793         || (PL_opargs[type] & OA_CLASS_MASK) == OA_LOOPEXOP);
7794
7795     NewOp(1101, pvop, 1, PVOP);
7796     OpTYPE_set(pvop, type);
7797     pvop->op_pv = pv;
7798     pvop->op_next = (OP*)pvop;
7799     pvop->op_flags = (U8)flags;
7800     pvop->op_private = utf8 ? OPpPV_IS_UTF8 : 0;
7801     if (PL_opargs[type] & OA_RETSCALAR)
7802         scalar((OP*)pvop);
7803     if (PL_opargs[type] & OA_TARGET)
7804         pvop->op_targ = pad_alloc(type, SVs_PADTMP);
7805     return CHECKOP(type, pvop);
7806 }
7807
7808 void
7809 Perl_package(pTHX_ OP *o)
7810 {
7811     SV *const sv = cSVOPo->op_sv;
7812
7813     PERL_ARGS_ASSERT_PACKAGE;
7814
7815     SAVEGENERICSV(PL_curstash);
7816     save_item(PL_curstname);
7817
7818     PL_curstash = (HV *)SvREFCNT_inc(gv_stashsv(sv, GV_ADD));
7819
7820     sv_setsv(PL_curstname, sv);
7821
7822     PL_hints |= HINT_BLOCK_SCOPE;
7823     PL_parser->copline = NOLINE;
7824
7825     op_free(o);
7826 }
7827
7828 void
7829 Perl_package_version( pTHX_ OP *v )
7830 {
7831     U32 savehints = PL_hints;
7832     PERL_ARGS_ASSERT_PACKAGE_VERSION;
7833     PL_hints &= ~HINT_STRICT_VARS;
7834     sv_setsv( GvSV(gv_fetchpvs("VERSION", GV_ADDMULTI, SVt_PV)), cSVOPx(v)->op_sv );
7835     PL_hints = savehints;
7836     op_free(v);
7837 }
7838
7839 void
7840 Perl_utilize(pTHX_ int aver, I32 floor, OP *version, OP *idop, OP *arg)
7841 {
7842     OP *pack;
7843     OP *imop;
7844     OP *veop;
7845     SV *use_version = NULL;
7846
7847     PERL_ARGS_ASSERT_UTILIZE;
7848
7849     if (idop->op_type != OP_CONST)
7850         Perl_croak(aTHX_ "Module name must be constant");
7851
7852     veop = NULL;
7853
7854     if (version) {
7855         SV * const vesv = ((SVOP*)version)->op_sv;
7856
7857         if (!arg && !SvNIOKp(vesv)) {
7858             arg = version;
7859         }
7860         else {
7861             OP *pack;
7862             SV *meth;
7863
7864             if (version->op_type != OP_CONST || !SvNIOKp(vesv))
7865                 Perl_croak(aTHX_ "Version number must be a constant number");
7866
7867             /* Make copy of idop so we don't free it twice */
7868             pack = newSVOP(OP_CONST, 0, newSVsv(((SVOP*)idop)->op_sv));
7869
7870             /* Fake up a method call to VERSION */
7871             meth = newSVpvs_share("VERSION");
7872             veop = op_convert_list(OP_ENTERSUB, OPf_STACKED|OPf_SPECIAL,
7873                             op_append_elem(OP_LIST,
7874                                         op_prepend_elem(OP_LIST, pack, version),
7875                                         newMETHOP_named(OP_METHOD_NAMED, 0, meth)));
7876         }
7877     }
7878
7879     /* Fake up an import/unimport */
7880     if (arg && arg->op_type == OP_STUB) {
7881         imop = arg;             /* no import on explicit () */
7882     }
7883     else if (SvNIOKp(((SVOP*)idop)->op_sv)) {
7884         imop = NULL;            /* use 5.0; */
7885         if (aver)
7886             use_version = ((SVOP*)idop)->op_sv;
7887         else
7888             idop->op_private |= OPpCONST_NOVER;
7889     }
7890     else {
7891         SV *meth;
7892
7893         /* Make copy of idop so we don't free it twice */
7894         pack = newSVOP(OP_CONST, 0, newSVsv(((SVOP*)idop)->op_sv));
7895
7896         /* Fake up a method call to import/unimport */
7897         meth = aver
7898             ? newSVpvs_share("import") : newSVpvs_share("unimport");
7899         imop = op_convert_list(OP_ENTERSUB, OPf_STACKED|OPf_SPECIAL,
7900                        op_append_elem(OP_LIST,
7901                                    op_prepend_elem(OP_LIST, pack, arg),
7902                                    newMETHOP_named(OP_METHOD_NAMED, 0, meth)
7903                        ));
7904     }
7905
7906     /* Fake up the BEGIN {}, which does its thing immediately. */
7907     newATTRSUB(floor,
7908         newSVOP(OP_CONST, 0, newSVpvs_share("BEGIN")),
7909         NULL,
7910         NULL,
7911         op_append_elem(OP_LINESEQ,
7912             op_append_elem(OP_LINESEQ,
7913                 newSTATEOP(0, NULL, newUNOP(OP_REQUIRE, 0, idop)),
7914                 newSTATEOP(0, NULL, veop)),
7915             newSTATEOP(0, NULL, imop) ));
7916
7917     if (use_version) {
7918         /* Enable the
7919          * feature bundle that corresponds to the required version. */
7920         use_version = sv_2mortal(new_version(use_version));
7921         S_enable_feature_bundle(aTHX_ use_version);
7922
7923         /* If a version >= 5.11.0 is requested, strictures are on by default! */
7924         if (vcmp(use_version,
7925                  sv_2mortal(upg_version(newSVnv(5.011000), FALSE))) >= 0) {
7926             if (!(PL_hints & HINT_EXPLICIT_STRICT_REFS))
7927                 PL_hints |= HINT_STRICT_REFS;
7928             if (!(PL_hints & HINT_EXPLICIT_STRICT_SUBS))
7929                 PL_hints |= HINT_STRICT_SUBS;
7930             if (!(PL_hints & HINT_EXPLICIT_STRICT_VARS))
7931                 PL_hints |= HINT_STRICT_VARS;
7932         }
7933         /* otherwise they are off */
7934         else {
7935             if (!(PL_hints & HINT_EXPLICIT_STRICT_REFS))
7936                 PL_hints &= ~HINT_STRICT_REFS;
7937             if (!(PL_hints & HINT_EXPLICIT_STRICT_SUBS))
7938                 PL_hints &= ~HINT_STRICT_SUBS;
7939             if (!(PL_hints & HINT_EXPLICIT_STRICT_VARS))
7940                 PL_hints &= ~HINT_STRICT_VARS;
7941         }
7942     }
7943
7944     /* The "did you use incorrect case?" warning used to be here.
7945      * The problem is that on case-insensitive filesystems one
7946      * might get false positives for "use" (and "require"):
7947      * "use Strict" or "require CARP" will work.  This causes
7948      * portability problems for the script: in case-strict
7949      * filesystems the script will stop working.
7950      *
7951      * The "incorrect case" warning checked whether "use Foo"
7952      * imported "Foo" to your namespace, but that is wrong, too:
7953      * there is no requirement nor promise in the language that
7954      * a Foo.pm should or would contain anything in package "Foo".
7955      *
7956      * There is very little Configure-wise that can be done, either:
7957      * the case-sensitivity of the build filesystem of Perl does not
7958      * help in guessing the case-sensitivity of the runtime environment.
7959      */
7960
7961     PL_hints |= HINT_BLOCK_SCOPE;
7962     PL_parser->copline = NOLINE;
7963     COP_SEQMAX_INC; /* Purely for B::*'s benefit */
7964 }
7965
7966 /*
7967 =head1 Embedding Functions
7968
7969 =for apidoc load_module
7970
7971 Loads the module whose name is pointed to by the string part of C<name>.
7972 Note that the actual module name, not its filename, should be given.
7973 Eg, "Foo::Bar" instead of "Foo/Bar.pm". ver, if specified and not NULL,
7974 provides version semantics similar to C<use Foo::Bar VERSION>. The optional
7975 trailing arguments can be used to specify arguments to the module's C<import()>
7976 method, similar to C<use Foo::Bar VERSION LIST>; their precise handling depends
7977 on the flags. The flags argument is a bitwise-ORed collection of any of
7978 C<PERL_LOADMOD_DENY>, C<PERL_LOADMOD_NOIMPORT>, or C<PERL_LOADMOD_IMPORT_OPS>
7979 (or 0 for no flags).
7980
7981 If C<PERL_LOADMOD_NOIMPORT> is set, the module is loaded as if with an empty
7982 import list, as in C<use Foo::Bar ()>; this is the only circumstance in which
7983 the trailing optional arguments may be omitted entirely. Otherwise, if
7984 C<PERL_LOADMOD_IMPORT_OPS> is set, the trailing arguments must consist of
7985 exactly one C<OP*>, containing the op tree that produces the relevant import
7986 arguments. Otherwise, the trailing arguments must all be C<SV*> values that
7987 will be used as import arguments; and the list must be terminated with C<(SV*)
7988 NULL>. If neither C<PERL_LOADMOD_NOIMPORT> nor C<PERL_LOADMOD_IMPORT_OPS> is
7989 set, the trailing C<NULL> pointer is needed even if no import arguments are
7990 desired. The reference count for each specified C<SV*> argument is
7991 decremented. In addition, the C<name> argument is modified.
7992
7993 If C<PERL_LOADMOD_DENY> is set, the module is loaded as if with C<no> rather
7994 than C<use>.
7995
7996 =cut */
7997
7998 void
7999 Perl_load_module(pTHX_ U32 flags, SV *name, SV *ver, ...)
8000 {
8001     va_list args;
8002
8003     PERL_ARGS_ASSERT_LOAD_MODULE;
8004
8005     va_start(args, ver);
8006     vload_module(flags, name, ver, &args);
8007     va_end(args);
8008 }
8009
8010 #ifdef PERL_IMPLICIT_CONTEXT
8011 void
8012 Perl_load_module_nocontext(U32 flags, SV *name, SV *ver, ...)
8013 {
8014     dTHX;
8015     va_list args;
8016     PERL_ARGS_ASSERT_LOAD_MODULE_NOCONTEXT;
8017     va_start(args, ver);
8018     vload_module(flags, name, ver, &args);
8019     va_end(args);
8020 }
8021 #endif
8022
8023 void
8024 Perl_vload_module(pTHX_ U32 flags, SV *name, SV *ver, va_list *args)
8025 {
8026     OP *veop, *imop;
8027     OP * modname;
8028     I32 floor;
8029
8030     PERL_ARGS_ASSERT_VLOAD_MODULE;
8031
8032     /* utilize() fakes up a BEGIN { require ..; import ... }, so make sure
8033      * that it has a PL_parser to play with while doing that, and also
8034      * that it doesn't mess with any existing parser, by creating a tmp
8035      * new parser with lex_start(). This won't actually be used for much,
8036      * since pp_require() will create another parser for the real work.
8037      * The ENTER/LEAVE pair protect callers from any side effects of use.
8038      *
8039      * start_subparse() creates a new PL_compcv. This means that any ops
8040      * allocated below will be allocated from that CV's op slab, and so
8041      * will be automatically freed if the utilise() fails
8042      */
8043
8044     ENTER;
8045     SAVEVPTR(PL_curcop);
8046     lex_start(NULL, NULL, LEX_START_SAME_FILTER);
8047     floor = start_subparse(FALSE, 0);
8048
8049     modname = newSVOP(OP_CONST, 0, name);
8050     modname->op_private |= OPpCONST_BARE;
8051     if (ver) {
8052         veop = newSVOP(OP_CONST, 0, ver);
8053     }
8054     else
8055         veop = NULL;
8056     if (flags & PERL_LOADMOD_NOIMPORT) {
8057         imop = sawparens(newNULLLIST());
8058     }
8059     else if (flags & PERL_LOADMOD_IMPORT_OPS) {
8060         imop = va_arg(*args, OP*);
8061     }
8062     else {
8063         SV *sv;
8064         imop = NULL;
8065         sv = va_arg(*args, SV*);
8066         while (sv) {
8067             imop = op_append_elem(OP_LIST, imop, newSVOP(OP_CONST, 0, sv));
8068             sv = va_arg(*args, SV*);
8069         }
8070     }
8071
8072     utilize(!(flags & PERL_LOADMOD_DENY), floor, veop, modname, imop);
8073     LEAVE;
8074 }
8075
8076 PERL_STATIC_INLINE OP *
8077 S_new_entersubop(pTHX_ GV *gv, OP *arg)
8078 {
8079     return newUNOP(OP_ENTERSUB, OPf_STACKED,
8080                    newLISTOP(OP_LIST, 0, arg,
8081                              newUNOP(OP_RV2CV, 0,
8082                                      newGVOP(OP_GV, 0, gv))));
8083 }
8084
8085 OP *
8086 Perl_dofile(pTHX_ OP *term, I32 force_builtin)
8087 {
8088     OP *doop;
8089     GV *gv;
8090
8091     PERL_ARGS_ASSERT_DOFILE;
8092
8093     if (!force_builtin && (gv = gv_override("do", 2))) {
8094         doop = S_new_entersubop(aTHX_ gv, term);
8095     }
8096     else {
8097         doop = newUNOP(OP_DOFILE, 0, scalar(term));
8098     }
8099     return doop;
8100 }
8101
8102 /*
8103 =head1 Optree construction
8104
8105 =for apidoc newSLICEOP
8106
8107 Constructs, checks, and returns an C<lslice> (list slice) op.  C<flags>
8108 gives the eight bits of C<op_flags>, except that C<OPf_KIDS> will
8109 be set automatically, and, shifted up eight bits, the eight bits of
8110 C<op_private>, except that the bit with value 1 or 2 is automatically
8111 set as required.  C<listval> and C<subscript> supply the parameters of
8112 the slice; they are consumed by this function and become part of the
8113 constructed op tree.
8114
8115 =cut
8116 */
8117
8118 OP *
8119 Perl_newSLICEOP(pTHX_ I32 flags, OP *subscript, OP *listval)
8120 {
8121     return newBINOP(OP_LSLICE, flags,
8122             list(force_list(subscript, 1)),
8123             list(force_list(listval,   1)) );
8124 }
8125
8126 #define ASSIGN_SCALAR 0
8127 #define ASSIGN_LIST   1
8128 #define ASSIGN_REF    2
8129
8130 /* given the optree o on the LHS of an assignment, determine whether its:
8131  *  ASSIGN_SCALAR   $x  = ...
8132  *  ASSIGN_LIST    ($x) = ...
8133  *  ASSIGN_REF     \$x  = ...
8134  */
8135
8136 STATIC I32
8137 S_assignment_type(pTHX_ const OP *o)
8138 {
8139     unsigned type;
8140     U8 flags;
8141     U8 ret;
8142
8143     if (!o)
8144         return ASSIGN_LIST;
8145
8146     if (o->op_type == OP_SREFGEN)
8147     {
8148         OP * const kid = cUNOPx(cUNOPo->op_first)->op_first;
8149         type = kid->op_type;
8150         flags = o->op_flags | kid->op_flags;
8151         if (!(flags & OPf_PARENS)
8152           && (kid->op_type == OP_RV2AV || kid->op_type == OP_PADAV ||
8153               kid->op_type == OP_RV2HV || kid->op_type == OP_PADHV ))
8154             return ASSIGN_REF;
8155         ret = ASSIGN_REF;
8156     } else {
8157         if ((o->op_type == OP_NULL) && (o->op_flags & OPf_KIDS))
8158             o = cUNOPo->op_first;
8159         flags = o->op_flags;
8160         type = o->op_type;
8161         ret = ASSIGN_SCALAR;
8162     }
8163
8164     if (type == OP_COND_EXPR) {
8165         OP * const sib = OpSIBLING(cLOGOPo->op_first);
8166         const I32 t = assignment_type(sib);
8167         const I32 f = assignment_type(OpSIBLING(sib));
8168
8169         if (t == ASSIGN_LIST && f == ASSIGN_LIST)
8170             return ASSIGN_LIST;
8171         if ((t == ASSIGN_LIST) ^ (f == ASSIGN_LIST))
8172             yyerror("Assignment to both a list and a scalar");
8173         return ASSIGN_SCALAR;
8174     }
8175
8176     if (type == OP_LIST &&
8177         (flags & OPf_WANT) == OPf_WANT_SCALAR &&
8178         o->op_private & OPpLVAL_INTRO)
8179         return ret;
8180
8181     if (type == OP_LIST || flags & OPf_PARENS ||
8182         type == OP_RV2AV || type == OP_RV2HV ||
8183         type == OP_ASLICE || type == OP_HSLICE ||
8184         type == OP_KVASLICE || type == OP_KVHSLICE || type == OP_REFGEN)
8185         return ASSIGN_LIST;
8186
8187     if (type == OP_PADAV || type == OP_PADHV)
8188         return ASSIGN_LIST;
8189
8190     if (type == OP_RV2SV)
8191         return ret;
8192
8193     return ret;
8194 }
8195
8196 static OP *
8197 S_newONCEOP(pTHX_ OP *initop, OP *padop)
8198 {
8199     dVAR;
8200     const PADOFFSET target = padop->op_targ;
8201     OP *const other = newOP(OP_PADSV,
8202                             padop->op_flags
8203                             | ((padop->op_private & ~OPpLVAL_INTRO) << 8));
8204     OP *const first = newOP(OP_NULL, 0);
8205     OP *const nullop = newCONDOP(0, first, initop, other);
8206     /* XXX targlex disabled for now; see ticket #124160
8207         newCONDOP(0, first, S_maybe_targlex(aTHX_ initop), other);
8208      */
8209     OP *const condop = first->op_next;
8210
8211     OpTYPE_set(condop, OP_ONCE);
8212     other->op_targ = target;
8213     nullop->op_flags |= OPf_WANT_SCALAR;
8214
8215     /* Store the initializedness of state vars in a separate
8216        pad entry.  */
8217     condop->op_targ =
8218       pad_add_name_pvn("$",1,padadd_NO_DUP_CHECK|padadd_STATE,0,0);
8219     /* hijacking PADSTALE for uninitialized state variables */
8220     SvPADSTALE_on(PAD_SVl(condop->op_targ));
8221
8222     return nullop;
8223 }
8224
8225 /*
8226 =for apidoc newASSIGNOP
8227
8228 Constructs, checks, and returns an assignment op.  C<left> and C<right>
8229 supply the parameters of the assignment; they are consumed by this
8230 function and become part of the constructed op tree.
8231
8232 If C<optype> is C<OP_ANDASSIGN>, C<OP_ORASSIGN>, or C<OP_DORASSIGN>, then
8233 a suitable conditional optree is constructed.  If C<optype> is the opcode
8234 of a binary operator, such as C<OP_BIT_OR>, then an op is constructed that
8235 performs the binary operation and assigns the result to the left argument.
8236 Either way, if C<optype> is non-zero then C<flags> has no effect.
8237
8238 If C<optype> is zero, then a plain scalar or list assignment is
8239 constructed.  Which type of assignment it is is automatically determined.
8240 C<flags> gives the eight bits of C<op_flags>, except that C<OPf_KIDS>
8241 will be set automatically, and, shifted up eight bits, the eight bits
8242 of C<op_private>, except that the bit with value 1 or 2 is automatically
8243 set as required.
8244
8245 =cut
8246 */
8247
8248 OP *
8249 Perl_newASSIGNOP(pTHX_ I32 flags, OP *left, I32 optype, OP *right)
8250 {
8251     OP *o;
8252     I32 assign_type;
8253
8254     if (optype) {
8255         if (optype == OP_ANDASSIGN || optype == OP_ORASSIGN || optype == OP_DORASSIGN) {
8256             right = scalar(right);
8257             return newLOGOP(optype, 0,
8258                 op_lvalue(scalar(left), optype),
8259                 newBINOP(OP_SASSIGN, OPpASSIGN_BACKWARDS<<8, right, right));
8260         }
8261         else {
8262             return newBINOP(optype, OPf_STACKED,
8263                 op_lvalue(scalar(left), optype), scalar(right));
8264         }
8265     }
8266
8267     if ((assign_type = assignment_type(left)) == ASSIGN_LIST) {
8268         OP *state_var_op = NULL;
8269         static const char no_list_state[] = "Initialization of state variables"
8270             " in list currently forbidden";
8271         OP *curop;
8272
8273         if (left->op_type == OP_ASLICE || left->op_type == OP_HSLICE)
8274             left->op_private &= ~ OPpSLICEWARNING;
8275
8276         PL_modcount = 0;
8277         left = op_lvalue(left, OP_AASSIGN);
8278         curop = list(force_list(left, 1));
8279         o = newBINOP(OP_AASSIGN, flags, list(force_list(right, 1)), curop);
8280         o->op_private = (U8)(0 | (flags >> 8));
8281
8282         if (OP_TYPE_IS_OR_WAS(left, OP_LIST))
8283         {
8284             OP *lop = ((LISTOP*)left)->op_first, *vop, *eop;
8285             if (!(left->op_flags & OPf_PARENS) &&
8286                     lop->op_type == OP_PUSHMARK &&
8287                     (vop = OpSIBLING(lop)) &&
8288                     (vop->op_type == OP_PADAV || vop->op_type == OP_PADHV) &&
8289                     !(vop->op_flags & OPf_PARENS) &&
8290                     (vop->op_private & (OPpLVAL_INTRO|OPpPAD_STATE)) ==
8291                         (OPpLVAL_INTRO|OPpPAD_STATE) &&
8292                     (eop = OpSIBLING(vop)) &&
8293                     eop->op_type == OP_ENTERSUB &&
8294                     !OpHAS_SIBLING(eop)) {
8295                 state_var_op = vop;
8296             } else {
8297                 while (lop) {
8298                     if ((lop->op_type == OP_PADSV ||
8299                          lop->op_type == OP_PADAV ||
8300                          lop->op_type == OP_PADHV ||
8301                          lop->op_type == OP_PADANY)
8302                       && (lop->op_private & OPpPAD_STATE)
8303                     )
8304                         yyerror(no_list_state);
8305                     lop = OpSIBLING(lop);
8306                 }
8307             }
8308         }
8309         else if (  (left->op_private & OPpLVAL_INTRO)
8310                 && (left->op_private & OPpPAD_STATE)
8311                 && (   left->op_type == OP_PADSV
8312                     || left->op_type == OP_PADAV
8313                     || left->op_type == OP_PADHV
8314                     || left->op_type == OP_PADANY)
8315         ) {
8316                 /* All single variable list context state assignments, hence
8317                    state ($a) = ...
8318                    (state $a) = ...
8319                    state @a = ...
8320                    state (@a) = ...
8321                    (state @a) = ...
8322                    state %a = ...
8323                    state (%a) = ...
8324                    (state %a) = ...
8325                 */
8326                 if (left->op_flags & OPf_PARENS)
8327                     yyerror(no_list_state);
8328                 else
8329                     state_var_op = left;
8330         }
8331
8332         /* optimise @a = split(...) into:
8333         * @{expr}:              split(..., @{expr}) (where @a is not flattened)
8334         * @a, my @a, local @a:  split(...)          (where @a is attached to
8335         *                                            the split op itself)
8336         */
8337
8338         if (   right
8339             && right->op_type == OP_SPLIT
8340             /* don't do twice, e.g. @b = (@a = split) */
8341             && !(right->op_private & OPpSPLIT_ASSIGN))
8342         {
8343             OP *gvop = NULL;
8344
8345             if (   (  left->op_type == OP_RV2AV
8346                    && (gvop=((UNOP*)left)->op_first)->op_type==OP_GV)
8347                 || left->op_type == OP_PADAV)
8348             {
8349                 /* @pkg or @lex or local @pkg' or 'my @lex' */
8350                 OP *tmpop;
8351                 if (gvop) {
8352 #ifdef USE_ITHREADS
8353                     ((PMOP*)right)->op_pmreplrootu.op_pmtargetoff
8354                         = cPADOPx(gvop)->op_padix;
8355                     cPADOPx(gvop)->op_padix = 0;        /* steal it */
8356 #else
8357                     ((PMOP*)right)->op_pmreplrootu.op_pmtargetgv
8358                         = MUTABLE_GV(cSVOPx(gvop)->op_sv);
8359                     cSVOPx(gvop)->op_sv = NULL; /* steal it */
8360 #endif
8361                     right->op_private |=
8362                         left->op_private & OPpOUR_INTRO;
8363                 }
8364                 else {
8365                     ((PMOP*)right)->op_pmreplrootu.op_pmtargetoff = left->op_targ;
8366                     left->op_targ = 0;  /* steal it */
8367                     right->op_private |= OPpSPLIT_LEX;
8368                 }
8369                 right->op_private |= left->op_private & OPpLVAL_INTRO;
8370
8371               detach_split:
8372                 tmpop = cUNOPo->op_first;       /* to list (nulled) */
8373                 tmpop = ((UNOP*)tmpop)->op_first; /* to pushmark */
8374                 assert(OpSIBLING(tmpop) == right);
8375                 assert(!OpHAS_SIBLING(right));
8376                 /* detach the split subtreee from the o tree,
8377                  * then free the residual o tree */
8378                 op_sibling_splice(cUNOPo->op_first, tmpop, 1, NULL);
8379                 op_free(o);                     /* blow off assign */
8380                 right->op_private |= OPpSPLIT_ASSIGN;
8381                 right->op_flags &= ~OPf_WANT;
8382                         /* "I don't know and I don't care." */
8383                 return right;
8384             }
8385             else if (left->op_type == OP_RV2AV) {
8386                 /* @{expr} */
8387
8388                 OP *pushop = cUNOPx(cBINOPo->op_last)->op_first;
8389                 assert(OpSIBLING(pushop) == left);
8390                 /* Detach the array ...  */
8391                 op_sibling_splice(cBINOPo->op_last, pushop, 1, NULL);
8392                 /* ... and attach it to the split.  */
8393                 op_sibling_splice(right, cLISTOPx(right)->op_last,
8394                                   0, left);
8395                 right->op_flags |= OPf_STACKED;
8396                 /* Detach split and expunge aassign as above.  */
8397                 goto detach_split;
8398             }
8399             else if (PL_modcount < RETURN_UNLIMITED_NUMBER &&
8400                     ((LISTOP*)right)->op_last->op_type == OP_CONST)
8401             {
8402                 /* convert split(...,0) to split(..., PL_modcount+1) */
8403                 SV ** const svp =
8404                     &((SVOP*)((LISTOP*)right)->op_last)->op_sv;
8405                 SV * const sv = *svp;
8406                 if (SvIOK(sv) && SvIVX(sv) == 0)
8407                 {
8408                   if (right->op_private & OPpSPLIT_IMPLIM) {
8409                     /* our own SV, created in ck_split */
8410                     SvREADONLY_off(sv);
8411                     sv_setiv(sv, PL_modcount+1);
8412                   }
8413                   else {
8414                     /* SV may belong to someone else */
8415                     SvREFCNT_dec(sv);
8416                     *svp = newSViv(PL_modcount+1);
8417                   }
8418                 }
8419             }
8420         }
8421
8422         if (state_var_op)
8423             o = S_newONCEOP(aTHX_ o, state_var_op);
8424         return o;
8425     }
8426     if (assign_type == ASSIGN_REF)
8427         return newBINOP(OP_REFASSIGN, flags, scalar(right), left);
8428     if (!right)
8429         right = newOP(OP_UNDEF, 0);
8430     if (right->op_type == OP_READLINE) {
8431         right->op_flags |= OPf_STACKED;
8432         return newBINOP(OP_NULL, flags, op_lvalue(scalar(left), OP_SASSIGN),
8433                 scalar(right));
8434     }
8435     else {
8436         o = newBINOP(OP_SASSIGN, flags,
8437             scalar(right), op_lvalue(scalar(left), OP_SASSIGN) );
8438     }
8439     return o;
8440 }
8441
8442 /*
8443 =for apidoc newSTATEOP
8444
8445 Constructs a state op (COP).  The state op is normally a C<nextstate> op,
8446 but will be a C<dbstate> op if debugging is enabled for currently-compiled
8447 code.  The state op is populated from C<PL_curcop> (or C<PL_compiling>).
8448 If C<label> is non-null, it supplies the name of a label to attach to
8449 the state op; this function takes ownership of the memory pointed at by
8450 C<label>, and will free it.  C<flags> gives the eight bits of C<op_flags>
8451 for the state op.
8452
8453 If C<o> is null, the state op is returned.  Otherwise the state op is
8454 combined with C<o> into a C<lineseq> list op, which is returned.  C<o>
8455 is consumed by this function and becomes part of the returned op tree.
8456
8457 =cut
8458 */
8459
8460 OP *
8461 Perl_newSTATEOP(pTHX_ I32 flags, char *label, OP *o)
8462 {
8463     dVAR;
8464     const U32 seq = intro_my();
8465     const U32 utf8 = flags & SVf_UTF8;
8466     COP *cop;
8467
8468     PL_parser->parsed_sub = 0;
8469
8470     flags &= ~SVf_UTF8;
8471
8472     NewOp(1101, cop, 1, COP);
8473     if (PERLDB_LINE && CopLINE(PL_curcop) && PL_curstash != PL_debstash) {
8474         OpTYPE_set(cop, OP_DBSTATE);
8475     }
8476     else {
8477         OpTYPE_set(cop, OP_NEXTSTATE);
8478     }
8479     cop->op_flags = (U8)flags;
8480     CopHINTS_set(cop, PL_hints);
8481 #ifdef VMS
8482     if (VMSISH_HUSHED) cop->op_private |= OPpHUSH_VMSISH;
8483 #endif
8484     cop->op_next = (OP*)cop;
8485
8486     cop->cop_seq = seq;
8487     cop->cop_warnings = DUP_WARNINGS(PL_curcop->cop_warnings);
8488     CopHINTHASH_set(cop, cophh_copy(CopHINTHASH_get(PL_curcop)));
8489     if (label) {
8490         Perl_cop_store_label(aTHX_ cop, label, strlen(label), utf8);
8491
8492         PL_hints |= HINT_BLOCK_SCOPE;
8493         /* It seems that we need to defer freeing this pointer, as other parts
8494            of the grammar end up wanting to copy it after this op has been
8495            created. */
8496         SAVEFREEPV(label);
8497     }
8498
8499     if (PL_parser->preambling != NOLINE) {
8500         CopLINE_set(cop, PL_parser->preambling);
8501         PL_parser->copline = NOLINE;
8502     }
8503     else if (PL_parser->copline == NOLINE)
8504         CopLINE_set(cop, CopLINE(PL_curcop));
8505     else {
8506         CopLINE_set(cop, PL_parser->copline);
8507         PL_parser->copline = NOLINE;
8508     }
8509 #ifdef USE_ITHREADS
8510     CopFILE_set(cop, CopFILE(PL_curcop));       /* XXX share in a pvtable? */
8511 #else
8512     CopFILEGV_set(cop, CopFILEGV(PL_curcop));
8513 #endif
8514     CopSTASH_set(cop, PL_curstash);
8515
8516     if (cop->op_type == OP_DBSTATE) {
8517         /* this line can have a breakpoint - store the cop in IV */
8518         AV *av = CopFILEAVx(PL_curcop);
8519         if (av) {
8520             SV * const * const svp = av_fetch(av, CopLINE(cop), FALSE);
8521             if (svp && *svp != &PL_sv_undef ) {
8522                 (void)SvIOK_on(*svp);
8523                 SvIV_set(*svp, PTR2IV(cop));
8524             }
8525         }
8526     }
8527
8528     if (flags & OPf_SPECIAL)
8529         op_null((OP*)cop);
8530     return op_prepend_elem(OP_LINESEQ, (OP*)cop, o);
8531 }
8532
8533 /*
8534 =for apidoc newLOGOP
8535
8536 Constructs, checks, and returns a logical (flow control) op.  C<type>
8537 is the opcode.  C<flags> gives the eight bits of C<op_flags>, except
8538 that C<OPf_KIDS> will be set automatically, and, shifted up eight bits,
8539 the eight bits of C<op_private>, except that the bit with value 1 is
8540 automatically set.  C<first> supplies the expression controlling the
8541 flow, and C<other> supplies the side (alternate) chain of ops; they are
8542 consumed by this function and become part of the constructed op tree.
8543
8544 =cut
8545 */
8546
8547 OP *
8548 Perl_newLOGOP(pTHX_ I32 type, I32 flags, OP *first, OP *other)
8549 {
8550     PERL_ARGS_ASSERT_NEWLOGOP;
8551
8552     return new_logop(type, flags, &first, &other);
8553 }
8554
8555
8556 /* See if the optree o contains a single OP_CONST (plus possibly
8557  * surrounding enter/nextstate/null etc). If so, return it, else return
8558  * NULL.
8559  */
8560
8561 STATIC OP *
8562 S_search_const(pTHX_ OP *o)
8563 {
8564     PERL_ARGS_ASSERT_SEARCH_CONST;
8565
8566   redo:
8567     switch (o->op_type) {
8568         case OP_CONST:
8569             return o;
8570         case OP_NULL:
8571             if (o->op_flags & OPf_KIDS) {
8572                 o = cUNOPo->op_first;
8573                 goto redo;
8574             }
8575             break;
8576         case OP_LEAVE:
8577         case OP_SCOPE:
8578         case OP_LINESEQ:
8579         {
8580             OP *kid;
8581             if (!(o->op_flags & OPf_KIDS))
8582                 return NULL;
8583             kid = cLISTOPo->op_first;
8584
8585             do {
8586                 switch (kid->op_type) {
8587                     case OP_ENTER:
8588                     case OP_NULL:
8589                     case OP_NEXTSTATE:
8590                         kid = OpSIBLING(kid);
8591                         break;
8592                     default:
8593                         if (kid != cLISTOPo->op_last)
8594                             return NULL;
8595                         goto last;
8596                 }
8597             } while (kid);
8598
8599             if (!kid)
8600                 kid = cLISTOPo->op_last;
8601           last:
8602              o = kid;
8603              goto redo;
8604         }
8605     }
8606
8607     return NULL;
8608 }
8609
8610
8611 STATIC OP *
8612 S_new_logop(pTHX_ I32 type, I32 flags, OP** firstp, OP** otherp)
8613 {
8614     dVAR;
8615     LOGOP *logop;
8616     OP *o;
8617     OP *first;
8618     OP *other;
8619     OP *cstop = NULL;
8620     int prepend_not = 0;
8621
8622     PERL_ARGS_ASSERT_NEW_LOGOP;
8623
8624     first = *firstp;
8625     other = *otherp;
8626
8627     /* [perl #59802]: Warn about things like "return $a or $b", which
8628        is parsed as "(return $a) or $b" rather than "return ($a or
8629        $b)".  NB: This also applies to xor, which is why we do it
8630        here.
8631      */
8632     switch (first->op_type) {
8633     case OP_NEXT:
8634     case OP_LAST:
8635     case OP_REDO:
8636         /* XXX: Perhaps we should emit a stronger warning for these.
8637            Even with the high-precedence operator they don't seem to do
8638            anything sensible.
8639
8640            But until we do, fall through here.
8641          */
8642     case OP_RETURN:
8643     case OP_EXIT:
8644     case OP_DIE:
8645     case OP_GOTO:
8646         /* XXX: Currently we allow people to "shoot themselves in the
8647            foot" by explicitly writing "(return $a) or $b".
8648
8649            Warn unless we are looking at the result from folding or if
8650            the programmer explicitly grouped the operators like this.
8651            The former can occur with e.g.
8652
8653                 use constant FEATURE => ( $] >= ... );
8654                 sub { not FEATURE and return or do_stuff(); }
8655          */
8656         if (!first->op_folded && !(first->op_flags & OPf_PARENS))
8657             Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX),
8658                            "Possible precedence issue with control flow operator");
8659         /* XXX: Should we optimze this to "return $a;" (i.e. remove
8660            the "or $b" part)?
8661         */
8662         break;
8663     }
8664
8665     if (type == OP_XOR)         /* Not short circuit, but here by precedence. */
8666         return newBINOP(type, flags, scalar(first), scalar(other));
8667
8668     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_LOGOP
8669         || type == OP_CUSTOM);
8670
8671     scalarboolean(first);
8672
8673     /* search for a constant op that could let us fold the test */
8674     if ((cstop = search_const(first))) {
8675         if (cstop->op_private & OPpCONST_STRICT)
8676             no_bareword_allowed(cstop);
8677         else if ((cstop->op_private & OPpCONST_BARE))
8678                 Perl_ck_warner(aTHX_ packWARN(WARN_BAREWORD), "Bareword found in conditional");
8679         if ((type == OP_AND &&  SvTRUE(((SVOP*)cstop)->op_sv)) ||
8680             (type == OP_OR  && !SvTRUE(((SVOP*)cstop)->op_sv)) ||
8681             (type == OP_DOR && !SvOK(((SVOP*)cstop)->op_sv))) {
8682             /* Elide the (constant) lhs, since it can't affect the outcome */
8683             *firstp = NULL;
8684             if (other->op_type == OP_CONST)
8685                 other->op_private |= OPpCONST_SHORTCIRCUIT;
8686             op_free(first);
8687             if (other->op_type == OP_LEAVE)
8688                 other = newUNOP(OP_NULL, OPf_SPECIAL, other);
8689             else if (other->op_type == OP_MATCH
8690                   || other->op_type == OP_SUBST
8691                   || other->op_type == OP_TRANSR
8692                   || other->op_type == OP_TRANS)
8693                 /* Mark the op as being unbindable with =~ */
8694                 other->op_flags |= OPf_SPECIAL;
8695
8696             other->op_folded = 1;
8697             return other;
8698         }
8699         else {
8700             /* Elide the rhs, since the outcome is entirely determined by
8701              * the (constant) lhs */
8702
8703             /* check for C<my $x if 0>, or C<my($x,$y) if 0> */
8704             const OP *o2 = other;
8705             if ( ! (o2->op_type == OP_LIST
8706                     && (( o2 = cUNOPx(o2)->op_first))
8707                     && o2->op_type == OP_PUSHMARK
8708                     && (( o2 = OpSIBLING(o2))) )
8709             )
8710                 o2 = other;
8711             if ((o2->op_type == OP_PADSV || o2->op_type == OP_PADAV
8712                         || o2->op_type == OP_PADHV)
8713                 && o2->op_private & OPpLVAL_INTRO
8714                 && !(o2->op_private & OPpPAD_STATE))
8715             {
8716         Perl_croak(aTHX_ "This use of my() in false conditional is "
8717                           "no longer allowed");
8718             }
8719
8720             *otherp = NULL;
8721             if (cstop->op_type == OP_CONST)
8722                 cstop->op_private |= OPpCONST_SHORTCIRCUIT;
8723             op_free(other);
8724             return first;
8725         }
8726     }
8727     else if ((first->op_flags & OPf_KIDS) && type != OP_DOR
8728         && ckWARN(WARN_MISC)) /* [#24076] Don't warn for <FH> err FOO. */
8729     {
8730         const OP * const k1 = ((UNOP*)first)->op_first;
8731         const OP * const k2 = OpSIBLING(k1);
8732         OPCODE warnop = 0;
8733         switch (first->op_type)
8734         {
8735         case OP_NULL:
8736             if (k2 && k2->op_type == OP_READLINE
8737                   && (k2->op_flags & OPf_STACKED)
8738                   && ((k1->op_flags & OPf_WANT) == OPf_WANT_SCALAR))
8739             {
8740                 warnop = k2->op_type;
8741             }
8742             break;
8743
8744         case OP_SASSIGN:
8745             if (k1->op_type == OP_READDIR
8746                   || k1->op_type == OP_GLOB
8747                   || (k1->op_type == OP_NULL && k1->op_targ == OP_GLOB)
8748                  || k1->op_type == OP_EACH
8749                  || k1->op_type == OP_AEACH)
8750             {
8751                 warnop = ((k1->op_type == OP_NULL)
8752                           ? (OPCODE)k1->op_targ : k1->op_type);
8753             }
8754             break;
8755         }
8756         if (warnop) {
8757             const line_t oldline = CopLINE(PL_curcop);
8758             /* This ensures that warnings are reported at the first line
8759                of the construction, not the last.  */
8760             CopLINE_set(PL_curcop, PL_parser->copline);
8761             Perl_warner(aTHX_ packWARN(WARN_MISC),
8762                  "Value of %s%s can be \"0\"; test with defined()",
8763                  PL_op_desc[warnop],
8764                  ((warnop == OP_READLINE || warnop == OP_GLOB)
8765                   ? " construct" : "() operator"));
8766             CopLINE_set(PL_curcop, oldline);
8767         }
8768     }
8769
8770     /* optimize AND and OR ops that have NOTs as children */
8771     if (first->op_type == OP_NOT
8772         && (first->op_flags & OPf_KIDS)
8773         && ((first->op_flags & OPf_SPECIAL) /* unless ($x) { } */
8774             || (other->op_type == OP_NOT))  /* if (!$x && !$y) { } */
8775         ) {
8776         if (type == OP_AND || type == OP_OR) {
8777             if (type == OP_AND)
8778                 type = OP_OR;
8779             else
8780                 type = OP_AND;
8781             op_null(first);
8782             if (other->op_type == OP_NOT) { /* !a AND|OR !b => !(a OR|AND b) */
8783                 op_null(other);
8784                 prepend_not = 1; /* prepend a NOT op later */
8785             }
8786         }
8787     }
8788
8789     logop = alloc_LOGOP(type, first, LINKLIST(other));
8790     logop->op_flags |= (U8)flags;
8791     logop->op_private = (U8)(1 | (flags >> 8));
8792
8793     /* establish postfix order */
8794     logop->op_next = LINKLIST(first);
8795     first->op_next = (OP*)logop;
8796     assert(!OpHAS_SIBLING(first));
8797     op_sibling_splice((OP*)logop, first, 0, other);
8798
8799     CHECKOP(type,logop);
8800
8801     o = newUNOP(prepend_not ? OP_NOT : OP_NULL,
8802                 PL_opargs[type] & OA_RETSCALAR ? OPf_WANT_SCALAR : 0,
8803                 (OP*)logop);
8804     other->op_next = o;
8805
8806     return o;
8807 }
8808
8809 /*
8810 =for apidoc newCONDOP
8811
8812 Constructs, checks, and returns a conditional-expression (C<cond_expr>)
8813 op.  C<flags> gives the eight bits of C<op_flags>, except that C<OPf_KIDS>
8814 will be set automatically, and, shifted up eight bits, the eight bits of
8815 C<op_private>, except that the bit with value 1 is automatically set.
8816 C<first> supplies the expression selecting between the two branches,
8817 and C<trueop> and C<falseop> supply the branches; they are consumed by
8818 this function and become part of the constructed op tree.
8819
8820 =cut
8821 */
8822
8823 OP *
8824 Perl_newCONDOP(pTHX_ I32 flags, OP *first, OP *trueop, OP *falseop)
8825 {
8826     dVAR;
8827     LOGOP *logop;
8828     OP *start;
8829     OP *o;
8830     OP *cstop;
8831
8832     PERL_ARGS_ASSERT_NEWCONDOP;
8833
8834     if (!falseop)
8835         return newLOGOP(OP_AND, 0, first, trueop);
8836     if (!trueop)
8837         return newLOGOP(OP_OR, 0, first, falseop);
8838
8839     scalarboolean(first);
8840     if ((cstop = search_const(first))) {
8841         /* Left or right arm of the conditional?  */
8842         const bool left = SvTRUE(((SVOP*)cstop)->op_sv);
8843         OP *live = left ? trueop : falseop;
8844         OP *const dead = left ? falseop : trueop;
8845         if (cstop->op_private & OPpCONST_BARE &&
8846             cstop->op_private & OPpCONST_STRICT) {
8847             no_bareword_allowed(cstop);
8848         }
8849         op_free(first);
8850         op_free(dead);
8851         if (live->op_type == OP_LEAVE)
8852             live = newUNOP(OP_NULL, OPf_SPECIAL, live);
8853         else if (live->op_type == OP_MATCH || live->op_type == OP_SUBST
8854               || live->op_type == OP_TRANS || live->op_type == OP_TRANSR)
8855             /* Mark the op as being unbindable with =~ */
8856             live->op_flags |= OPf_SPECIAL;
8857         live->op_folded = 1;
8858         return live;
8859     }
8860     logop = alloc_LOGOP(OP_COND_EXPR, first, LINKLIST(trueop));
8861     logop->op_flags |= (U8)flags;
8862     logop->op_private = (U8)(1 | (flags >> 8));
8863     logop->op_next = LINKLIST(falseop);
8864
8865     CHECKOP(OP_COND_EXPR, /* that's logop->op_type */
8866             logop);
8867
8868     /* establish postfix order */
8869     start = LINKLIST(first);
8870     first->op_next = (OP*)logop;
8871
8872     /* make first, trueop, falseop siblings */
8873     op_sibling_splice((OP*)logop, first,  0, trueop);
8874     op_sibling_splice((OP*)logop, trueop, 0, falseop);
8875
8876     o = newUNOP(OP_NULL, 0, (OP*)logop);
8877
8878     trueop->op_next = falseop->op_next = o;
8879
8880     o->op_next = start;
8881     return o;
8882 }
8883
8884 /*
8885 =for apidoc newRANGE
8886
8887 Constructs and returns a C<range> op, with subordinate C<flip> and
8888 C<flop> ops.  C<flags> gives the eight bits of C<op_flags> for the
8889 C<flip> op and, shifted up eight bits, the eight bits of C<op_private>
8890 for both the C<flip> and C<range> ops, except that the bit with value
8891 1 is automatically set.  C<left> and C<right> supply the expressions
8892 controlling the endpoints of the range; they are consumed by this function
8893 and become part of the constructed op tree.
8894
8895 =cut
8896 */
8897
8898 OP *
8899 Perl_newRANGE(pTHX_ I32 flags, OP *left, OP *right)
8900 {
8901     LOGOP *range;
8902     OP *flip;
8903     OP *flop;
8904     OP *leftstart;
8905     OP *o;
8906
8907     PERL_ARGS_ASSERT_NEWRANGE;
8908
8909     range = alloc_LOGOP(OP_RANGE, left, LINKLIST(right));
8910     range->op_flags = OPf_KIDS;
8911     leftstart = LINKLIST(left);
8912     range->op_private = (U8)(1 | (flags >> 8));
8913
8914     /* make left and right siblings */
8915     op_sibling_splice((OP*)range, left, 0, right);
8916
8917     range->op_next = (OP*)range;
8918     flip = newUNOP(OP_FLIP, flags, (OP*)range);
8919     flop = newUNOP(OP_FLOP, 0, flip);
8920     o = newUNOP(OP_NULL, 0, flop);
8921     LINKLIST(flop);
8922     range->op_next = leftstart;
8923
8924     left->op_next = flip;
8925     right->op_next = flop;
8926
8927     range->op_targ =
8928         pad_add_name_pvn("$", 1, padadd_NO_DUP_CHECK|padadd_STATE, 0, 0);
8929     sv_upgrade(PAD_SV(range->op_targ), SVt_PVNV);
8930     flip->op_targ =
8931         pad_add_name_pvn("$", 1, padadd_NO_DUP_CHECK|padadd_STATE, 0, 0);;
8932     sv_upgrade(PAD_SV(flip->op_targ), SVt_PVNV);
8933     SvPADTMP_on(PAD_SV(flip->op_targ));
8934
8935     flip->op_private =  left->op_type == OP_CONST ? OPpFLIP_LINENUM : 0;
8936     flop->op_private = right->op_type == OP_CONST ? OPpFLIP_LINENUM : 0;
8937
8938     /* check barewords before they might be optimized aways */
8939     if (flip->op_private && cSVOPx(left)->op_private & OPpCONST_STRICT)
8940         no_bareword_allowed(left);
8941     if (flop->op_private && cSVOPx(right)->op_private & OPpCONST_STRICT)
8942         no_bareword_allowed(right);
8943
8944     flip->op_next = o;
8945     if (!flip->op_private || !flop->op_private)
8946         LINKLIST(o);            /* blow off optimizer unless constant */
8947
8948     return o;
8949 }
8950
8951 /*
8952 =for apidoc newLOOPOP
8953
8954 Constructs, checks, and returns an op tree expressing a loop.  This is
8955 only a loop in the control flow through the op tree; it does not have
8956 the heavyweight loop structure that allows exiting the loop by C<last>
8957 and suchlike.  C<flags> gives the eight bits of C<op_flags> for the
8958 top-level op, except that some bits will be set automatically as required.
8959 C<expr> supplies the expression controlling loop iteration, and C<block>
8960 supplies the body of the loop; they are consumed by this function and
8961 become part of the constructed op tree.  C<debuggable> is currently
8962 unused and should always be 1.
8963
8964 =cut
8965 */
8966
8967 OP *
8968 Perl_newLOOPOP(pTHX_ I32 flags, I32 debuggable, OP *expr, OP *block)
8969 {
8970     OP* listop;
8971     OP* o;
8972     const bool once = block && block->op_flags & OPf_SPECIAL &&
8973                       block->op_type == OP_NULL;
8974
8975     PERL_UNUSED_ARG(debuggable);
8976
8977     if (expr) {
8978         if (once && (
8979               (expr->op_type == OP_CONST && !SvTRUE(((SVOP*)expr)->op_sv))
8980            || (  expr->op_type == OP_NOT
8981               && cUNOPx(expr)->op_first->op_type == OP_CONST
8982               && SvTRUE(cSVOPx_sv(cUNOPx(expr)->op_first))
8983               )
8984            ))
8985             /* Return the block now, so that S_new_logop does not try to
8986                fold it away. */
8987         {
8988             op_free(expr);
8989             return block;       /* do {} while 0 does once */
8990         }
8991
8992         if (expr->op_type == OP_READLINE
8993             || expr->op_type == OP_READDIR
8994             || expr->op_type == OP_GLOB
8995             || expr->op_type == OP_EACH || expr->op_type == OP_AEACH
8996             || (expr->op_type == OP_NULL && expr->op_targ == OP_GLOB)) {
8997             expr = newUNOP(OP_DEFINED, 0,
8998                 newASSIGNOP(0, newDEFSVOP(), 0, expr) );
8999         } else if (expr->op_flags & OPf_KIDS) {
9000             const OP * const k1 = ((UNOP*)expr)->op_first;
9001             const OP * const k2 = k1 ? OpSIBLING(k1) : NULL;
9002             switch (expr->op_type) {
9003               case OP_NULL:
9004                 if (k2 && (k2->op_type == OP_READLINE || k2->op_type == OP_READDIR)
9005                       && (k2->op_flags & OPf_STACKED)
9006                       && ((k1->op_flags & OPf_WANT) == OPf_WANT_SCALAR))
9007                     expr = newUNOP(OP_DEFINED, 0, expr);
9008                 break;
9009
9010               case OP_SASSIGN:
9011                 if (k1 && (k1->op_type == OP_READDIR
9012                       || k1->op_type == OP_GLOB
9013                       || (k1->op_type == OP_NULL && k1->op_targ == OP_GLOB)
9014                      || k1->op_type == OP_EACH
9015                      || k1->op_type == OP_AEACH))
9016                     expr = newUNOP(OP_DEFINED, 0, expr);
9017                 break;
9018             }
9019         }
9020     }
9021
9022     /* if block is null, the next op_append_elem() would put UNSTACK, a scalar
9023      * op, in listop. This is wrong. [perl #27024] */
9024     if (!block)
9025         block = newOP(OP_NULL, 0);
9026     listop = op_append_elem(OP_LINESEQ, block, newOP(OP_UNSTACK, 0));
9027     o = new_logop(OP_AND, 0, &expr, &listop);
9028
9029     if (once) {
9030         ASSUME(listop);
9031     }
9032
9033     if (listop)
9034         ((LISTOP*)listop)->op_last->op_next = LINKLIST(o);
9035
9036     if (once && o != listop)
9037     {
9038         assert(cUNOPo->op_first->op_type == OP_AND
9039             || cUNOPo->op_first->op_type == OP_OR);
9040         o->op_next = ((LOGOP*)cUNOPo->op_first)->op_other;
9041     }
9042
9043     if (o == listop)
9044         o = newUNOP(OP_NULL, 0, o);     /* or do {} while 1 loses outer block */
9045
9046     o->op_flags |= flags;
9047     o = op_scope(o);
9048     o->op_flags |= OPf_SPECIAL; /* suppress cx_popblock() curpm restoration*/
9049     return o;
9050 }
9051
9052 /*
9053 =for apidoc newWHILEOP
9054
9055 Constructs, checks, and returns an op tree expressing a C<while> loop.
9056 This is a heavyweight loop, with structure that allows exiting the loop
9057 by C<last> and suchlike.
9058
9059 C<loop> is an optional preconstructed C<enterloop> op to use in the
9060 loop; if it is null then a suitable op will be constructed automatically.
9061 C<expr> supplies the loop's controlling expression.  C<block> supplies the
9062 main body of the loop, and C<cont> optionally supplies a C<continue> block
9063 that operates as a second half of the body.  All of these optree inputs
9064 are consumed by this function and become part of the constructed op tree.
9065
9066 C<flags> gives the eight bits of C<op_flags> for the C<leaveloop>
9067 op and, shifted up eight bits, the eight bits of C<op_private> for
9068 the C<leaveloop> op, except that (in both cases) some bits will be set
9069 automatically.  C<debuggable> is currently unused and should always be 1.
9070 C<has_my> can be supplied as true to force the
9071 loop body to be enclosed in its own scope.
9072
9073 =cut
9074 */
9075
9076 OP *
9077 Perl_newWHILEOP(pTHX_ I32 flags, I32 debuggable, LOOP *loop,
9078         OP *expr, OP *block, OP *cont, I32 has_my)
9079 {
9080     dVAR;
9081     OP *redo;
9082     OP *next = NULL;
9083     OP *listop;
9084     OP *o;
9085     U8 loopflags = 0;
9086
9087     PERL_UNUSED_ARG(debuggable);
9088
9089     if (expr) {
9090         if (expr->op_type == OP_READLINE
9091          || expr->op_type == OP_READDIR
9092          || expr->op_type == OP_GLOB
9093          || expr->op_type == OP_EACH || expr->op_type == OP_AEACH
9094                      || (expr->op_type == OP_NULL && expr->op_targ == OP_GLOB)) {
9095             expr = newUNOP(OP_DEFINED, 0,
9096                 newASSIGNOP(0, newDEFSVOP(), 0, expr) );
9097         } else if (expr->op_flags & OPf_KIDS) {
9098             const OP * const k1 = ((UNOP*)expr)->op_first;
9099             const OP * const k2 = (k1) ? OpSIBLING(k1) : NULL;
9100             switch (expr->op_type) {
9101               case OP_NULL:
9102                 if (k2 && (k2->op_type == OP_READLINE || k2->op_type == OP_READDIR)
9103                       && (k2->op_flags & OPf_STACKED)
9104                       && ((k1->op_flags & OPf_WANT) == OPf_WANT_SCALAR))
9105                     expr = newUNOP(OP_DEFINED, 0, expr);
9106                 break;
9107
9108               case OP_SASSIGN:
9109                 if (k1 && (k1->op_type == OP_READDIR
9110                       || k1->op_type == OP_GLOB
9111                       || (k1->op_type == OP_NULL && k1->op_targ == OP_GLOB)
9112                      || k1->op_type == OP_EACH
9113                      || k1->op_type == OP_AEACH))
9114                     expr = newUNOP(OP_DEFINED, 0, expr);
9115                 break;
9116             }
9117         }
9118     }
9119
9120     if (!block)
9121         block = newOP(OP_NULL, 0);
9122     else if (cont || has_my) {
9123         block = op_scope(block);
9124     }
9125
9126     if (cont) {
9127         next = LINKLIST(cont);
9128     }
9129     if (expr) {
9130         OP * const unstack = newOP(OP_UNSTACK, 0);
9131         if (!next)
9132             next = unstack;
9133         cont = op_append_elem(OP_LINESEQ, cont, unstack);
9134     }
9135
9136     assert(block);
9137     listop = op_append_list(OP_LINESEQ, block, cont);
9138     assert(listop);
9139     redo = LINKLIST(listop);
9140
9141     if (expr) {
9142         scalar(listop);
9143         o = new_logop(OP_AND, 0, &expr, &listop);
9144         if (o == expr && o->op_type == OP_CONST && !SvTRUE(cSVOPo->op_sv)) {
9145             op_free((OP*)loop);
9146             return expr;                /* listop already freed by new_logop */
9147         }
9148         if (listop)
9149             ((LISTOP*)listop)->op_last->op_next =
9150                 (o == listop ? redo : LINKLIST(o));
9151     }
9152     else
9153         o = listop;
9154
9155     if (!loop) {
9156         NewOp(1101,loop,1,LOOP);
9157         OpTYPE_set(loop, OP_ENTERLOOP);
9158         loop->op_private = 0;
9159         loop->op_next = (OP*)loop;
9160     }
9161
9162     o = newBINOP(OP_LEAVELOOP, 0, (OP*)loop, o);
9163
9164     loop->op_redoop = redo;
9165     loop->op_lastop = o;
9166     o->op_private |= loopflags;
9167
9168     if (next)
9169         loop->op_nextop = next;
9170     else
9171         loop->op_nextop = o;
9172
9173     o->op_flags |= flags;
9174     o->op_private |= (flags >> 8);
9175     return o;
9176 }
9177
9178 /*
9179 =for apidoc newFOROP
9180
9181 Constructs, checks, and returns an op tree expressing a C<foreach>
9182 loop (iteration through a list of values).  This is a heavyweight loop,
9183 with structure that allows exiting the loop by C<last> and suchlike.
9184
9185 C<sv> optionally supplies the variable that will be aliased to each
9186 item in turn; if null, it defaults to C<$_>.
9187 C<expr> supplies the list of values to iterate over.  C<block> supplies
9188 the main body of the loop, and C<cont> optionally supplies a C<continue>
9189 block that operates as a second half of the body.  All of these optree
9190 inputs are consumed by this function and become part of the constructed
9191 op tree.
9192
9193 C<flags> gives the eight bits of C<op_flags> for the C<leaveloop>
9194 op and, shifted up eight bits, the eight bits of C<op_private> for
9195 the C<leaveloop> op, except that (in both cases) some bits will be set
9196 automatically.
9197
9198 =cut
9199 */
9200
9201 OP *
9202 Perl_newFOROP(pTHX_ I32 flags, OP *sv, OP *expr, OP *block, OP *cont)
9203 {
9204     dVAR;
9205     LOOP *loop;
9206     OP *wop;
9207     PADOFFSET padoff = 0;
9208     I32 iterflags = 0;
9209     I32 iterpflags = 0;
9210
9211     PERL_ARGS_ASSERT_NEWFOROP;
9212
9213     if (sv) {
9214         if (sv->op_type == OP_RV2SV) {  /* symbol table variable */
9215             iterpflags = sv->op_private & OPpOUR_INTRO; /* for our $x () */
9216             OpTYPE_set(sv, OP_RV2GV);
9217
9218             /* The op_type check is needed to prevent a possible segfault
9219              * if the loop variable is undeclared and 'strict vars' is in
9220              * effect. This is illegal but is nonetheless parsed, so we
9221              * may reach this point with an OP_CONST where we're expecting
9222              * an OP_GV.
9223              */
9224             if (cUNOPx(sv)->op_first->op_type == OP_GV
9225              && cGVOPx_gv(cUNOPx(sv)->op_first) == PL_defgv)
9226                 iterpflags |= OPpITER_DEF;
9227         }
9228         else if (sv->op_type == OP_PADSV) { /* private variable */
9229             iterpflags = sv->op_private & OPpLVAL_INTRO; /* for my $x () */
9230             padoff = sv->op_targ;
9231             sv->op_targ = 0;
9232             op_free(sv);
9233             sv = NULL;
9234             PAD_COMPNAME_GEN_set(padoff, PERL_INT_MAX);
9235         }
9236         else if (sv->op_type == OP_NULL && sv->op_targ == OP_SREFGEN)
9237             NOOP;
9238         else
9239             Perl_croak(aTHX_ "Can't use %s for loop variable", PL_op_desc[sv->op_type]);
9240         if (padoff) {
9241             PADNAME * const pn = PAD_COMPNAME(padoff);
9242             const char * const name = PadnamePV(pn);
9243
9244             if (PadnameLEN(pn) == 2 && name[0] == '$' && name[1] == '_')
9245                 iterpflags |= OPpITER_DEF;
9246         }
9247     }
9248     else {
9249         sv = newGVOP(OP_GV, 0, PL_defgv);
9250         iterpflags |= OPpITER_DEF;
9251     }
9252
9253     if (expr->op_type == OP_RV2AV || expr->op_type == OP_PADAV) {
9254         expr = op_lvalue(force_list(scalar(ref(expr, OP_ITER)), 1), OP_GREPSTART);
9255         iterflags |= OPf_STACKED;
9256     }
9257     else if (expr->op_type == OP_NULL &&
9258              (expr->op_flags & OPf_KIDS) &&
9259              ((BINOP*)expr)->op_first->op_type == OP_FLOP)
9260     {
9261         /* Basically turn for($x..$y) into the same as for($x,$y), but we
9262          * set the STACKED flag to indicate that these values are to be
9263          * treated as min/max values by 'pp_enteriter'.
9264          */
9265         const UNOP* const flip = (UNOP*)((UNOP*)((BINOP*)expr)->op_first)->op_first;
9266         LOGOP* const range = (LOGOP*) flip->op_first;
9267         OP* const left  = range->op_first;
9268         OP* const right = OpSIBLING(left);
9269         LISTOP* listop;
9270
9271         range->op_flags &= ~OPf_KIDS;
9272         /* detach range's children */
9273         op_sibling_splice((OP*)range, NULL, -1, NULL);
9274
9275         listop = (LISTOP*)newLISTOP(OP_LIST, 0, left, right);
9276         listop->op_first->op_next = range->op_next;
9277         left->op_next = range->op_other;
9278         right->op_next = (OP*)listop;
9279         listop->op_next = listop->op_first;
9280
9281         op_free(expr);
9282         expr = (OP*)(listop);
9283         op_null(expr);
9284         iterflags |= OPf_STACKED;
9285     }
9286     else {
9287         expr = op_lvalue(force_list(expr, 1), OP_GREPSTART);
9288     }
9289
9290     loop = (LOOP*)op_convert_list(OP_ENTERITER, iterflags,
9291                                   op_append_elem(OP_LIST, list(expr),
9292                                                  scalar(sv)));
9293     assert(!loop->op_next);
9294     /* for my  $x () sets OPpLVAL_INTRO;
9295      * for our $x () sets OPpOUR_INTRO */
9296     loop->op_private = (U8)iterpflags;
9297
9298     /* upgrade loop from a LISTOP to a LOOPOP;
9299      * keep it in-place if there's space */
9300     if (loop->op_slabbed
9301         &&    OpSLOT(loop)->opslot_size
9302             < SIZE_TO_PSIZE(sizeof(LOOP)) + OPSLOT_HEADER_P)
9303     {
9304         /* no space; allocate new op */
9305         LOOP *tmp;
9306         NewOp(1234,tmp,1,LOOP);
9307         Copy(loop,tmp,1,LISTOP);
9308         assert(loop->op_last->op_sibparent == (OP*)loop);
9309         OpLASTSIB_set(loop->op_last, (OP*)tmp); /*point back to new parent */
9310         S_op_destroy(aTHX_ (OP*)loop);
9311         loop = tmp;
9312     }
9313     else if (!loop->op_slabbed)
9314     {
9315         /* loop was malloc()ed */
9316         loop = (LOOP*)PerlMemShared_realloc(loop, sizeof(LOOP));
9317         OpLASTSIB_set(loop->op_last, (OP*)loop);
9318     }
9319     loop->op_targ = padoff;
9320     wop = newWHILEOP(flags, 1, loop, newOP(OP_ITER, 0), block, cont, 0);
9321     return wop;
9322 }
9323
9324 /*
9325 =for apidoc newLOOPEX
9326
9327 Constructs, checks, and returns a loop-exiting op (such as C<goto>
9328 or C<last>).  C<type> is the opcode.  C<label> supplies the parameter
9329 determining the target of the op; it is consumed by this function and
9330 becomes part of the constructed op tree.
9331
9332 =cut
9333 */
9334
9335 OP*
9336 Perl_newLOOPEX(pTHX_ I32 type, OP *label)
9337 {
9338     OP *o = NULL;
9339
9340     PERL_ARGS_ASSERT_NEWLOOPEX;
9341
9342     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_LOOPEXOP
9343         || type == OP_CUSTOM);
9344
9345     if (type != OP_GOTO) {
9346         /* "last()" means "last" */
9347         if (label->op_type == OP_STUB && (label->op_flags & OPf_PARENS)) {
9348             o = newOP(type, OPf_SPECIAL);
9349         }
9350     }
9351     else {
9352         /* Check whether it's going to be a goto &function */
9353         if (label->op_type == OP_ENTERSUB
9354                 && !(label->op_flags & OPf_STACKED))
9355             label = newUNOP(OP_REFGEN, 0, op_lvalue(label, OP_REFGEN));
9356     }
9357
9358     /* Check for a constant argument */
9359     if (label->op_type == OP_CONST) {
9360             SV * const sv = ((SVOP *)label)->op_sv;
9361             STRLEN l;
9362             const char *s = SvPV_const(sv,l);
9363             if (l == strlen(s)) {
9364                 o = newPVOP(type,
9365                             SvUTF8(((SVOP*)label)->op_sv),
9366                             savesharedpv(
9367                                 SvPV_nolen_const(((SVOP*)label)->op_sv)));
9368             }
9369     }
9370     
9371     /* If we have already created an op, we do not need the label. */
9372     if (o)
9373                 op_free(label);
9374     else o = newUNOP(type, OPf_STACKED, label);
9375
9376     PL_hints |= HINT_BLOCK_SCOPE;
9377     return o;
9378 }
9379
9380 /* if the condition is a literal array or hash
9381    (or @{ ... } etc), make a reference to it.
9382  */
9383 STATIC OP *
9384 S_ref_array_or_hash(pTHX_ OP *cond)
9385 {
9386     if (cond
9387     && (cond->op_type == OP_RV2AV
9388     ||  cond->op_type == OP_PADAV
9389     ||  cond->op_type == OP_RV2HV
9390     ||  cond->op_type == OP_PADHV))
9391
9392         return newUNOP(OP_REFGEN, 0, op_lvalue(cond, OP_REFGEN));
9393
9394     else if(cond
9395     && (cond->op_type == OP_ASLICE
9396     ||  cond->op_type == OP_KVASLICE
9397     ||  cond->op_type == OP_HSLICE
9398     ||  cond->op_type == OP_KVHSLICE)) {
9399
9400         /* anonlist now needs a list from this op, was previously used in
9401          * scalar context */
9402         cond->op_flags &= ~(OPf_WANT_SCALAR | OPf_REF);
9403         cond->op_flags |= OPf_WANT_LIST;
9404
9405         return newANONLIST(op_lvalue(cond, OP_ANONLIST));
9406     }
9407
9408     else
9409         return cond;
9410 }
9411
9412 /* These construct the optree fragments representing given()
9413    and when() blocks.
9414
9415    entergiven and enterwhen are LOGOPs; the op_other pointer
9416    points up to the associated leave op. We need this so we
9417    can put it in the context and make break/continue work.
9418    (Also, of course, pp_enterwhen will jump straight to
9419    op_other if the match fails.)
9420  */
9421
9422 STATIC OP *
9423 S_newGIVWHENOP(pTHX_ OP *cond, OP *block,
9424                    I32 enter_opcode, I32 leave_opcode,
9425                    PADOFFSET entertarg)
9426 {
9427     dVAR;
9428     LOGOP *enterop;
9429     OP *o;
9430
9431     PERL_ARGS_ASSERT_NEWGIVWHENOP;
9432     PERL_UNUSED_ARG(entertarg); /* used to indicate targ of lexical $_ */
9433
9434     enterop = alloc_LOGOP(enter_opcode, block, NULL);
9435     enterop->op_targ = 0;
9436     enterop->op_private = 0;
9437
9438     o = newUNOP(leave_opcode, 0, (OP *) enterop);
9439
9440     if (cond) {
9441         /* prepend cond if we have one */
9442         op_sibling_splice((OP*)enterop, NULL, 0, scalar(cond));
9443
9444         o->op_next = LINKLIST(cond);
9445         cond->op_next = (OP *) enterop;
9446     }
9447     else {
9448         /* This is a default {} block */
9449         enterop->op_flags |= OPf_SPECIAL;
9450         o      ->op_flags |= OPf_SPECIAL;
9451
9452         o->op_next = (OP *) enterop;
9453     }
9454
9455     CHECKOP(enter_opcode, enterop); /* Currently does nothing, since
9456                                        entergiven and enterwhen both
9457                                        use ck_null() */
9458
9459     enterop->op_next = LINKLIST(block);
9460     block->op_next = enterop->op_other = o;
9461
9462     return o;
9463 }
9464
9465
9466 /* For the purposes of 'when(implied_smartmatch)'
9467  *              versus 'when(boolean_expression)',
9468  * does this look like a boolean operation? For these purposes
9469    a boolean operation is:
9470      - a subroutine call [*]
9471      - a logical connective
9472      - a comparison operator
9473      - a filetest operator, with the exception of -s -M -A -C
9474      - defined(), exists() or eof()
9475      - /$re/ or $foo =~ /$re/
9476    
9477    [*] possibly surprising
9478  */
9479 STATIC bool
9480 S_looks_like_bool(pTHX_ const OP *o)
9481 {
9482     PERL_ARGS_ASSERT_LOOKS_LIKE_BOOL;
9483
9484     switch(o->op_type) {
9485         case OP_OR:
9486         case OP_DOR:
9487             return looks_like_bool(cLOGOPo->op_first);
9488
9489         case OP_AND:
9490         {
9491             OP* sibl = OpSIBLING(cLOGOPo->op_first);
9492             ASSUME(sibl);
9493             return (
9494                 looks_like_bool(cLOGOPo->op_first)
9495              && looks_like_bool(sibl));
9496         }
9497
9498         case OP_NULL:
9499         case OP_SCALAR:
9500             return (
9501                 o->op_flags & OPf_KIDS
9502             && looks_like_bool(cUNOPo->op_first));
9503
9504         case OP_ENTERSUB:
9505
9506         case OP_NOT:    case OP_XOR:
9507
9508         case OP_EQ:     case OP_NE:     case OP_LT:
9509         case OP_GT:     case OP_LE:     case OP_GE:
9510
9511         case OP_I_EQ:   case OP_I_NE:   case OP_I_LT:
9512         case OP_I_GT:   case OP_I_LE:   case OP_I_GE:
9513
9514         case OP_SEQ:    case OP_SNE:    case OP_SLT:
9515         case OP_SGT:    case OP_SLE:    case OP_SGE:
9516         
9517         case OP_SMARTMATCH:
9518         
9519         case OP_FTRREAD:  case OP_FTRWRITE: case OP_FTREXEC:
9520         case OP_FTEREAD:  case OP_FTEWRITE: case OP_FTEEXEC:
9521         case OP_FTIS:     case OP_FTEOWNED: case OP_FTROWNED:
9522         case OP_FTZERO:   case OP_FTSOCK:   case OP_FTCHR:
9523         case OP_FTBLK:    case OP_FTFILE:   case OP_FTDIR:
9524         case OP_FTPIPE:   case OP_FTLINK:   case OP_FTSUID:
9525         case OP_FTSGID:   case OP_FTSVTX:   case OP_FTTTY:
9526         case OP_FTTEXT:   case OP_FTBINARY:
9527         
9528         case OP_DEFINED: case OP_EXISTS:
9529         case OP_MATCH:   case OP_EOF:
9530
9531         case OP_FLOP:
9532
9533             return TRUE;
9534
9535         case OP_INDEX:
9536         case OP_RINDEX:
9537             /* optimised-away (index() != -1) or similar comparison */
9538             if (o->op_private & OPpTRUEBOOL)
9539                 return TRUE;
9540             return FALSE;
9541         
9542         case OP_CONST:
9543             /* Detect comparisons that have been optimized away */
9544             if (cSVOPo->op_sv == &PL_sv_yes
9545             ||  cSVOPo->op_sv == &PL_sv_no)
9546             
9547                 return TRUE;
9548             else
9549                 return FALSE;
9550         /* FALLTHROUGH */
9551         default:
9552             return FALSE;
9553     }
9554 }
9555
9556
9557 /*
9558 =for apidoc newGIVENOP
9559
9560 Constructs, checks, and returns an op tree expressing a C<given> block.
9561 C<cond> supplies the expression to whose value C<$_> will be locally
9562 aliased, and C<block> supplies the body of the C<given> construct; they
9563 are consumed by this function and become part of the constructed op tree.
9564 C<defsv_off> must be zero (it used to identity the pad slot of lexical $_).
9565
9566 =cut
9567 */
9568
9569 OP *
9570 Perl_newGIVENOP(pTHX_ OP *cond, OP *block, PADOFFSET defsv_off)
9571 {
9572     PERL_ARGS_ASSERT_NEWGIVENOP;
9573     PERL_UNUSED_ARG(defsv_off);
9574
9575     assert(!defsv_off);
9576     return newGIVWHENOP(
9577         ref_array_or_hash(cond),
9578         block,
9579         OP_ENTERGIVEN, OP_LEAVEGIVEN,
9580         0);
9581 }
9582
9583 /*
9584 =for apidoc newWHENOP
9585
9586 Constructs, checks, and returns an op tree expressing a C<when> block.
9587 C<cond> supplies the test expression, and C<block> supplies the block
9588 that will be executed if the test evaluates to true; they are consumed
9589 by this function and become part of the constructed op tree.  C<cond>
9590 will be interpreted DWIMically, often as a comparison against C<$_>,
9591 and may be null to generate a C<default> block.
9592
9593 =cut
9594 */
9595
9596 OP *
9597 Perl_newWHENOP(pTHX_ OP *cond, OP *block)
9598 {
9599     const bool cond_llb = (!cond || looks_like_bool(cond));
9600     OP *cond_op;
9601
9602     PERL_ARGS_ASSERT_NEWWHENOP;
9603
9604     if (cond_llb)
9605         cond_op = cond;
9606     else {
9607         cond_op = newBINOP(OP_SMARTMATCH, OPf_SPECIAL,
9608                 newDEFSVOP(),
9609                 scalar(ref_array_or_hash(cond)));
9610     }
9611     
9612     return newGIVWHENOP(cond_op, block, OP_ENTERWHEN, OP_LEAVEWHEN, 0);
9613 }
9614
9615 /* must not conflict with SVf_UTF8 */
9616 #define CV_CKPROTO_CURSTASH     0x1
9617
9618 void
9619 Perl_cv_ckproto_len_flags(pTHX_ const CV *cv, const GV *gv, const char *p,
9620                     const STRLEN len, const U32 flags)
9621 {
9622     SV *name = NULL, *msg;
9623     const char * cvp = SvROK(cv)
9624                         ? SvTYPE(SvRV_const(cv)) == SVt_PVCV
9625                            ? (cv = (const CV *)SvRV_const(cv), CvPROTO(cv))
9626                            : ""
9627                         : CvPROTO(cv);
9628     STRLEN clen = CvPROTOLEN(cv), plen = len;
9629
9630     PERL_ARGS_ASSERT_CV_CKPROTO_LEN_FLAGS;
9631
9632     if (p == NULL && cvp == NULL)
9633         return;
9634
9635     if (!ckWARN_d(WARN_PROTOTYPE))
9636         return;
9637
9638     if (p && cvp) {
9639         p = S_strip_spaces(aTHX_ p, &plen);
9640         cvp = S_strip_spaces(aTHX_ cvp, &clen);
9641         if ((flags & SVf_UTF8) == SvUTF8(cv)) {
9642             if (plen == clen && memEQ(cvp, p, plen))
9643                 return;
9644         } else {
9645             if (flags & SVf_UTF8) {
9646                 if (bytes_cmp_utf8((const U8 *)cvp, clen, (const U8 *)p, plen) == 0)
9647                     return;
9648             }
9649             else {
9650                 if (bytes_cmp_utf8((const U8 *)p, plen, (const U8 *)cvp, clen) == 0)
9651                     return;
9652             }
9653         }
9654     }
9655
9656     msg = sv_newmortal();
9657
9658     if (gv)
9659     {
9660         if (isGV(gv))
9661             gv_efullname3(name = sv_newmortal(), gv, NULL);
9662         else if (SvPOK(gv) && *SvPVX((SV *)gv) == '&')
9663             name = newSVpvn_flags(SvPVX((SV *)gv)+1, SvCUR(gv)-1, SvUTF8(gv)|SVs_TEMP);
9664         else if (flags & CV_CKPROTO_CURSTASH || SvROK(gv)) {
9665             name = sv_2mortal(newSVhek(HvNAME_HEK(PL_curstash)));
9666             sv_catpvs(name, "::");
9667             if (SvROK(gv)) {
9668                 assert (SvTYPE(SvRV_const(gv)) == SVt_PVCV);
9669                 assert (CvNAMED(SvRV_const(gv)));
9670                 sv_cathek(name, CvNAME_HEK(MUTABLE_CV(SvRV_const(gv))));
9671             }
9672             else sv_catsv(name, (SV *)gv);
9673         }
9674         else name = (SV *)gv;
9675     }
9676     sv_setpvs(msg, "Prototype mismatch:");
9677     if (name)
9678         Perl_sv_catpvf(aTHX_ msg, " sub %" SVf, SVfARG(name));
9679     if (cvp)
9680         Perl_sv_catpvf(aTHX_ msg, " (%" UTF8f ")",
9681             UTF8fARG(SvUTF8(cv),clen,cvp)
9682         );
9683     else
9684         sv_catpvs(msg, ": none");
9685     sv_catpvs(msg, " vs ");
9686     if (p)
9687         Perl_sv_catpvf(aTHX_ msg, "(%" UTF8f ")", UTF8fARG(flags & SVf_UTF8,len,p));
9688     else
9689         sv_catpvs(msg, "none");
9690     Perl_warner(aTHX_ packWARN(WARN_PROTOTYPE), "%" SVf, SVfARG(msg));
9691 }
9692
9693 static void const_sv_xsub(pTHX_ CV* cv);
9694 static void const_av_xsub(pTHX_ CV* cv);
9695
9696 /*
9697
9698 =head1 Optree Manipulation Functions
9699
9700 =for apidoc cv_const_sv
9701
9702 If C<cv> is a constant sub eligible for inlining, returns the constant
9703 value returned by the sub.  Otherwise, returns C<NULL>.
9704
9705 Constant subs can be created with C<newCONSTSUB> or as described in
9706 L<perlsub/"Constant Functions">.
9707
9708 =cut
9709 */
9710 SV *
9711 Perl_cv_const_sv(const CV *const cv)
9712 {
9713     SV *sv;
9714     if (!cv)
9715         return NULL;
9716     if (!(SvTYPE(cv) == SVt_PVCV || SvTYPE(cv) == SVt_PVFM))
9717         return NULL;
9718     sv = CvCONST(cv) ? MUTABLE_SV(CvXSUBANY(cv).any_ptr) : NULL;
9719     if (sv && SvTYPE(sv) == SVt_PVAV) return NULL;
9720     return sv;
9721 }
9722
9723 SV *
9724 Perl_cv_const_sv_or_av(const CV * const cv)
9725 {
9726     if (!cv)
9727         return NULL;
9728     if (SvROK(cv)) return SvRV((SV *)cv);
9729     assert (SvTYPE(cv) == SVt_PVCV || SvTYPE(cv) == SVt_PVFM);
9730     return CvCONST(cv) ? MUTABLE_SV(CvXSUBANY(cv).any_ptr) : NULL;
9731 }
9732
9733 /* op_const_sv:  examine an optree to determine whether it's in-lineable.
9734  * Can be called in 2 ways:
9735  *
9736  * !allow_lex
9737  *      look for a single OP_CONST with attached value: return the value
9738  *
9739  * allow_lex && !CvCONST(cv);
9740  *
9741  *      examine the clone prototype, and if contains only a single
9742  *      OP_CONST, return the value; or if it contains a single PADSV ref-
9743  *      erencing an outer lexical, turn on CvCONST to indicate the CV is
9744  *      a candidate for "constizing" at clone time, and return NULL.
9745  */
9746
9747 static SV *
9748 S_op_const_sv(pTHX_ const OP *o, CV *cv, bool allow_lex)
9749 {
9750     SV *sv = NULL;
9751     bool padsv = FALSE;
9752
9753     assert(o);
9754     assert(cv);
9755
9756     for (; o; o = o->op_next) {
9757         const OPCODE type = o->op_type;
9758
9759         if (type == OP_NEXTSTATE || type == OP_LINESEQ
9760              || type == OP_NULL
9761              || type == OP_PUSHMARK)
9762                 continue;
9763         if (type == OP_DBSTATE)
9764                 continue;
9765         if (type == OP_LEAVESUB)
9766             break;
9767         if (sv)
9768             return NULL;
9769         if (type == OP_CONST && cSVOPo->op_sv)
9770             sv = cSVOPo->op_sv;
9771         else if (type == OP_UNDEF && !o->op_private) {
9772             sv = newSV(0);
9773             SAVEFREESV(sv);
9774         }
9775         else if (allow_lex && type == OP_PADSV) {
9776                 if (PAD_COMPNAME_FLAGS(o->op_targ) & PADNAMEt_OUTER)
9777                 {
9778                     sv = &PL_sv_undef; /* an arbitrary non-null value */
9779                     padsv = TRUE;
9780                 }
9781                 else
9782                     return NULL;
9783         }
9784         else {
9785             return NULL;
9786         }
9787     }
9788     if (padsv) {
9789         CvCONST_on(cv);
9790         return NULL;
9791     }
9792     return sv;
9793 }
9794
9795 static void
9796 S_already_defined(pTHX_ CV *const cv, OP * const block, OP * const o,
9797                         PADNAME * const name, SV ** const const_svp)
9798 {
9799     assert (cv);
9800     assert (o || name);
9801     assert (const_svp);
9802     if (!block) {
9803         if (CvFLAGS(PL_compcv)) {
9804             /* might have had built-in attrs applied */
9805             const bool pureperl = !CvISXSUB(cv) && CvROOT(cv);
9806             if (CvLVALUE(PL_compcv) && ! CvLVALUE(cv) && pureperl
9807              && ckWARN(WARN_MISC))
9808             {
9809                 /* protect against fatal warnings leaking compcv */
9810                 SAVEFREESV(PL_compcv);
9811                 Perl_warner(aTHX_ packWARN(WARN_MISC), "lvalue attribute ignored after the subroutine has been defined");
9812                 SvREFCNT_inc_simple_void_NN(PL_compcv);
9813             }
9814             CvFLAGS(cv) |=
9815                 (CvFLAGS(PL_compcv) & CVf_BUILTIN_ATTRS
9816                   & ~(CVf_LVALUE * pureperl));
9817         }
9818         return;
9819     }
9820
9821     /* redundant check for speed: */
9822     if (CvCONST(cv) || ckWARN(WARN_REDEFINE)) {
9823         const line_t oldline = CopLINE(PL_curcop);
9824         SV *namesv = o
9825             ? cSVOPo->op_sv
9826             : sv_2mortal(newSVpvn_utf8(
9827                 PadnamePV(name)+1,PadnameLEN(name)-1, PadnameUTF8(name)
9828               ));
9829         if (PL_parser && PL_parser->copline != NOLINE)
9830             /* This ensures that warnings are reported at the first
9831                line of a redefinition, not the last.  */
9832             CopLINE_set(PL_curcop, PL_parser->copline);
9833         /* protect against fatal warnings leaking compcv */
9834         SAVEFREESV(PL_compcv);
9835         report_redefined_cv(namesv, cv, const_svp);
9836         SvREFCNT_inc_simple_void_NN(PL_compcv);
9837         CopLINE_set(PL_curcop, oldline);
9838     }
9839     SAVEFREESV(cv);
9840     return;
9841 }
9842
9843 CV *
9844 Perl_newMYSUB(pTHX_ I32 floor, OP *o, OP *proto, OP *attrs, OP *block)
9845 {
9846     CV **spot;
9847     SV **svspot;
9848     const char *ps;
9849     STRLEN ps_len = 0; /* init it to avoid false uninit warning from icc */
9850     U32 ps_utf8 = 0;
9851     CV *cv = NULL;
9852     CV *compcv = PL_compcv;
9853     SV *const_sv;
9854     PADNAME *name;
9855     PADOFFSET pax = o->op_targ;
9856     CV *outcv = CvOUTSIDE(PL_compcv);
9857     CV *clonee = NULL;
9858     HEK *hek = NULL;
9859     bool reusable = FALSE;
9860     OP *start = NULL;
9861 #ifdef PERL_DEBUG_READONLY_OPS
9862     OPSLAB *slab = NULL;
9863 #endif
9864
9865     PERL_ARGS_ASSERT_NEWMYSUB;
9866
9867     PL_hints |= HINT_BLOCK_SCOPE;
9868
9869     /* Find the pad slot for storing the new sub.
9870        We cannot use PL_comppad, as it is the pad owned by the new sub.  We
9871        need to look in CvOUTSIDE and find the pad belonging to the enclos-
9872        ing sub.  And then we need to dig deeper if this is a lexical from
9873        outside, as in:
9874            my sub foo; sub { sub foo { } }
9875      */
9876   redo:
9877     name = PadlistNAMESARRAY(CvPADLIST(outcv))[pax];
9878     if (PadnameOUTER(name) && PARENT_PAD_INDEX(name)) {
9879         pax = PARENT_PAD_INDEX(name);
9880         outcv = CvOUTSIDE(outcv);
9881         assert(outcv);
9882         goto redo;
9883     }
9884     svspot =
9885         &PadARRAY(PadlistARRAY(CvPADLIST(outcv))
9886                         [CvDEPTH(outcv) ? CvDEPTH(outcv) : 1])[pax];
9887     spot = (CV **)svspot;
9888
9889     if (!(PL_parser && PL_parser->error_count))
9890         move_proto_attr(&proto, &attrs, (GV *)PadnameSV(name), 0);
9891
9892     if (proto) {
9893         assert(proto->op_type == OP_CONST);
9894         ps = SvPV_const(((SVOP*)proto)->op_sv, ps_len);
9895         ps_utf8 = SvUTF8(((SVOP*)proto)->op_sv);
9896     }
9897     else
9898         ps = NULL;
9899
9900     if (proto)
9901         SAVEFREEOP(proto);
9902     if (attrs)
9903         SAVEFREEOP(attrs);
9904
9905     if (PL_parser && PL_parser->error_count) {
9906         op_free(block);
9907         SvREFCNT_dec(PL_compcv);
9908         PL_compcv = 0;
9909         goto done;
9910     }
9911
9912     if (CvDEPTH(outcv) && CvCLONE(compcv)) {
9913         cv = *spot;
9914         svspot = (SV **)(spot = &clonee);
9915     }
9916     else if (PadnameIsSTATE(name) || CvDEPTH(outcv))
9917         cv = *spot;
9918     else {
9919         assert (SvTYPE(*spot) == SVt_PVCV);
9920         if (CvNAMED(*spot))
9921             hek = CvNAME_HEK(*spot);
9922         else {
9923             dVAR;
9924             U32 hash;
9925             PERL_HASH(hash, PadnamePV(name)+1, PadnameLEN(name)-1);
9926             CvNAME_HEK_set(*spot, hek =
9927                 share_hek(
9928                     PadnamePV(name)+1,
9929                     (PadnameLEN(name)-1) * (PadnameUTF8(name) ? -1 : 1),
9930                     hash
9931                 )
9932             );
9933             CvLEXICAL_on(*spot);
9934         }
9935         cv = PadnamePROTOCV(name);
9936         svspot = (SV **)(spot = &PadnamePROTOCV(name));
9937     }
9938
9939     if (block) {
9940         /* This makes sub {}; work as expected.  */
9941         if (block->op_type == OP_STUB) {
9942             const line_t l = PL_parser->copline;
9943             op_free(block);
9944             block = newSTATEOP(0, NULL, 0);
9945             PL_parser->copline = l;
9946         }
9947         block = CvLVALUE(compcv)
9948              || (cv && CvLVALUE(cv) && !CvROOT(cv) && !CvXSUB(cv))
9949                    ? newUNOP(OP_LEAVESUBLV, 0,
9950                              op_lvalue(scalarseq(block), OP_LEAVESUBLV))
9951                    : newUNOP(OP_LEAVESUB, 0, scalarseq(block));
9952         start = LINKLIST(block);
9953         block->op_next = 0;
9954         if (ps && !*ps && !attrs && !CvLVALUE(compcv))
9955             const_sv = S_op_const_sv(aTHX_ start, compcv, FALSE);
9956         else
9957             const_sv = NULL;
9958     }
9959     else
9960         const_sv = NULL;
9961
9962     if (cv) {
9963         const bool exists = CvROOT(cv) || CvXSUB(cv);
9964
9965         /* if the subroutine doesn't exist and wasn't pre-declared
9966          * with a prototype, assume it will be AUTOLOADed,
9967          * skipping the prototype check
9968          */
9969         if (exists || SvPOK(cv))
9970             cv_ckproto_len_flags(cv, (GV *)PadnameSV(name), ps, ps_len,
9971                                  ps_utf8);
9972         /* already defined? */
9973         if (exists) {
9974             S_already_defined(aTHX_ cv, block, NULL, name, &const_sv);
9975             if (block)
9976                 cv = NULL;
9977             else {
9978                 if (attrs)
9979                     goto attrs;
9980                 /* just a "sub foo;" when &foo is already defined */
9981                 SAVEFREESV(compcv);
9982                 goto done;
9983             }
9984         }
9985         else if (CvDEPTH(outcv) && CvCLONE(compcv)) {
9986             cv = NULL;
9987             reusable = TRUE;
9988         }
9989     }
9990
9991     if (const_sv) {
9992         SvREFCNT_inc_simple_void_NN(const_sv);
9993         SvFLAGS(const_sv) |= SVs_PADTMP;
9994         if (cv) {
9995             assert(!CvROOT(cv) && !CvCONST(cv));
9996             cv_forget_slab(cv);
9997         }
9998         else {
9999             cv = MUTABLE_CV(newSV_type(SVt_PVCV));
10000             CvFILE_set_from_cop(cv, PL_curcop);
10001             CvSTASH_set(cv, PL_curstash);
10002             *spot = cv;
10003         }
10004         SvPVCLEAR(MUTABLE_SV(cv));  /* prototype is "" */
10005         CvXSUBANY(cv).any_ptr = const_sv;
10006         CvXSUB(cv) = const_sv_xsub;
10007         CvCONST_on(cv);
10008         CvISXSUB_on(cv);
10009         PoisonPADLIST(cv);
10010         CvFLAGS(cv) |= CvMETHOD(compcv);
10011         op_free(block);
10012         SvREFCNT_dec(compcv);
10013         PL_compcv = NULL;
10014         goto setname;
10015     }
10016
10017     /* Checking whether outcv is CvOUTSIDE(compcv) is not sufficient to
10018        determine whether this sub definition is in the same scope as its
10019        declaration.  If this sub definition is inside an inner named pack-
10020        age sub (my sub foo; sub bar { sub foo { ... } }), outcv points to
10021        the package sub.  So check PadnameOUTER(name) too.
10022      */
10023     if (outcv == CvOUTSIDE(compcv) && !PadnameOUTER(name)) { 
10024         assert(!CvWEAKOUTSIDE(compcv));
10025         SvREFCNT_dec(CvOUTSIDE(compcv));
10026         CvWEAKOUTSIDE_on(compcv);
10027     }
10028     /* XXX else do we have a circular reference? */
10029
10030     if (cv) {   /* must reuse cv in case stub is referenced elsewhere */
10031         /* transfer PL_compcv to cv */
10032         if (block) {
10033             bool free_file = CvFILE(cv) && CvDYNFILE(cv);
10034             cv_flags_t preserved_flags =
10035                 CvFLAGS(cv) & (CVf_BUILTIN_ATTRS|CVf_NAMED);
10036             PADLIST *const temp_padl = CvPADLIST(cv);
10037             CV *const temp_cv = CvOUTSIDE(cv);
10038             const cv_flags_t other_flags =
10039                 CvFLAGS(cv) & (CVf_SLABBED|CVf_WEAKOUTSIDE);
10040             OP * const cvstart = CvSTART(cv);
10041
10042             SvPOK_off(cv);
10043             CvFLAGS(cv) =
10044                 CvFLAGS(compcv) | preserved_flags;
10045             CvOUTSIDE(cv) = CvOUTSIDE(compcv);
10046             CvOUTSIDE_SEQ(cv) = CvOUTSIDE_SEQ(compcv);
10047             CvPADLIST_set(cv, CvPADLIST(compcv));
10048             CvOUTSIDE(compcv) = temp_cv;
10049             CvPADLIST_set(compcv, temp_padl);
10050             CvSTART(cv) = CvSTART(compcv);
10051             CvSTART(compcv) = cvstart;
10052             CvFLAGS(compcv) &= ~(CVf_SLABBED|CVf_WEAKOUTSIDE);
10053             CvFLAGS(compcv) |= other_flags;
10054
10055             if (free_file) {
10056                 Safefree(CvFILE(cv));
10057                 CvFILE(cv) = NULL;
10058             }
10059
10060             /* inner references to compcv must be fixed up ... */
10061             pad_fixup_inner_anons(CvPADLIST(cv), compcv, cv);
10062             if (PERLDB_INTER)/* Advice debugger on the new sub. */
10063                 ++PL_sub_generation;
10064         }
10065         else {
10066             /* Might have had built-in attributes applied -- propagate them. */
10067             CvFLAGS(cv) |= (CvFLAGS(compcv) & CVf_BUILTIN_ATTRS);
10068         }
10069         /* ... before we throw it away */
10070         SvREFCNT_dec(compcv);
10071         PL_compcv = compcv = cv;
10072     }
10073     else {
10074         cv = compcv;
10075         *spot = cv;
10076     }
10077
10078   setname:
10079     CvLEXICAL_on(cv);
10080     if (!CvNAME_HEK(cv)) {
10081         if (hek) (void)share_hek_hek(hek);
10082         else {
10083             dVAR;
10084             U32 hash;
10085             PERL_HASH(hash, PadnamePV(name)+1, PadnameLEN(name)-1);
10086             hek = share_hek(PadnamePV(name)+1,
10087                       (PadnameLEN(name)-1) * (PadnameUTF8(name) ? -1 : 1),
10088                       hash);
10089         }
10090         CvNAME_HEK_set(cv, hek);
10091     }
10092
10093     if (const_sv)
10094         goto clone;
10095
10096     if (CvFILE(cv) && CvDYNFILE(cv))
10097         Safefree(CvFILE(cv));
10098     CvFILE_set_from_cop(cv, PL_curcop);
10099     CvSTASH_set(cv, PL_curstash);
10100
10101     if (ps) {
10102         sv_setpvn(MUTABLE_SV(cv), ps, ps_len);
10103         if (ps_utf8)
10104             SvUTF8_on(MUTABLE_SV(cv));
10105     }
10106
10107     if (block) {
10108         /* If we assign an optree to a PVCV, then we've defined a
10109          * subroutine that the debugger could be able to set a breakpoint
10110          * in, so signal to pp_entereval that it should not throw away any
10111          * saved lines at scope exit.  */
10112
10113         PL_breakable_sub_gen++;
10114         CvROOT(cv) = block;
10115         /* The cv no longer needs to hold a refcount on the slab, as CvROOT
10116            itself has a refcount. */
10117         CvSLABBED_off(cv);
10118         OpslabREFCNT_dec_padok((OPSLAB *)CvSTART(cv));
10119 #ifdef PERL_DEBUG_READONLY_OPS
10120         slab = (OPSLAB *)CvSTART(cv);
10121 #endif
10122         S_process_optree(aTHX_ cv, block, start);
10123     }
10124
10125   attrs:
10126     if (attrs) {
10127         /* Need to do a C<use attributes $stash_of_cv,\&cv,@attrs>. */
10128         apply_attrs(PL_curstash, MUTABLE_SV(cv), attrs);
10129     }
10130
10131     if (block) {
10132         if (PERLDB_SUBLINE && PL_curstash != PL_debstash) {
10133             SV * const tmpstr = sv_newmortal();
10134             GV * const db_postponed = gv_fetchpvs("DB::postponed",
10135                                                   GV_ADDMULTI, SVt_PVHV);
10136             HV *hv;
10137             SV * const sv = Perl_newSVpvf(aTHX_ "%s:%ld-%ld",
10138                                           CopFILE(PL_curcop),
10139                                           (long)PL_subline,
10140                                           (long)CopLINE(PL_curcop));
10141             if (HvNAME_HEK(PL_curstash)) {
10142                 sv_sethek(tmpstr, HvNAME_HEK(PL_curstash));
10143                 sv_catpvs(tmpstr, "::");
10144             }
10145             else
10146                 sv_setpvs(tmpstr, "__ANON__::");
10147
10148             sv_catpvn_flags(tmpstr, PadnamePV(name)+1, PadnameLEN(name)-1,
10149                             PadnameUTF8(name) ? SV_CATUTF8 : SV_CATBYTES);
10150             (void)hv_store(GvHV(PL_DBsub), SvPVX_const(tmpstr),
10151                     SvUTF8(tmpstr) ? -(I32)SvCUR(tmpstr) : (I32)SvCUR(tmpstr), sv, 0);
10152             hv = GvHVn(db_postponed);
10153             if (HvTOTALKEYS(hv) > 0 && hv_exists(hv, SvPVX_const(tmpstr), SvUTF8(tmpstr) ? -(I32)SvCUR(tmpstr) : (I32)SvCUR(tmpstr))) {
10154                 CV * const pcv = GvCV(db_postponed);
10155                 if (pcv) {
10156                     dSP;
10157                     PUSHMARK(SP);
10158                     XPUSHs(tmpstr);
10159                     PUTBACK;
10160                     call_sv(MUTABLE_SV(pcv), G_DISCARD);
10161                 }
10162             }
10163         }
10164     }
10165
10166   clone:
10167     if (clonee) {
10168         assert(CvDEPTH(outcv));
10169         spot = (CV **)
10170             &PadARRAY(PadlistARRAY(CvPADLIST(outcv))[CvDEPTH(outcv)])[pax];
10171         if (reusable)
10172             cv_clone_into(clonee, *spot);
10173         else *spot = cv_clone(clonee);
10174         SvREFCNT_dec_NN(clonee);
10175         cv = *spot;
10176     }
10177
10178     if (CvDEPTH(outcv) && !reusable && PadnameIsSTATE(name)) {
10179         PADOFFSET depth = CvDEPTH(outcv);
10180         while (--depth) {
10181             SV *oldcv;
10182             svspot = &PadARRAY(PadlistARRAY(CvPADLIST(outcv))[depth])[pax];
10183             oldcv = *svspot;
10184             *svspot = SvREFCNT_inc_simple_NN(cv);
10185             SvREFCNT_dec(oldcv);
10186         }
10187     }
10188
10189   done:
10190     if (PL_parser)
10191         PL_parser->copline = NOLINE;
10192     LEAVE_SCOPE(floor);
10193 #ifdef PERL_DEBUG_READONLY_OPS
10194     if (slab)
10195         Slab_to_ro(slab);
10196 #endif
10197     op_free(o);
10198     return cv;
10199 }
10200
10201 /*
10202 =for apidoc newATTRSUB_x
10203
10204 Construct a Perl subroutine, also performing some surrounding jobs.
10205
10206 This function is expected to be called in a Perl compilation context,
10207 and some aspects of the subroutine are taken from global variables
10208 associated with compilation.  In particular, C<PL_compcv> represents
10209 the subroutine that is currently being compiled.  It must be non-null
10210 when this function is called, and some aspects of the subroutine being
10211 constructed are taken from it.  The constructed subroutine may actually
10212 be a reuse of the C<PL_compcv> object, but will not necessarily be so.
10213
10214 If C<block> is null then the subroutine will have no body, and for the
10215 time being it will be an error to call it.  This represents a forward
10216 subroutine declaration such as S<C<sub foo ($$);>>.  If C<block> is
10217 non-null then it provides the Perl code of the subroutine body, which
10218 will be executed when the subroutine is called.  This body includes
10219 any argument unwrapping code resulting from a subroutine signature or
10220 similar.  The pad use of the code must correspond to the pad attached
10221 to C<PL_compcv>.  The code is not expected to include a C<leavesub> or
10222 C<leavesublv> op; this function will add such an op.  C<block> is consumed
10223 by this function and will become part of the constructed subroutine.
10224
10225 C<proto> specifies the subroutine's prototype, unless one is supplied
10226 as an attribute (see below).  If C<proto> is null, then the subroutine
10227 will not have a prototype.  If C<proto> is non-null, it must point to a
10228 C<const> op whose value is a string, and the subroutine will have that
10229 string as its prototype.  If a prototype is supplied as an attribute, the
10230 attribute takes precedence over C<proto>, but in that case C<proto> should
10231 preferably be null.  In any case, C<proto> is consumed by this function.
10232
10233 C<attrs> supplies attributes to be applied the subroutine.  A handful of
10234 attributes take effect by built-in means, being applied to C<PL_compcv>
10235 immediately when seen.  Other attributes are collected up and attached
10236 to the subroutine by this route.  C<attrs> may be null to supply no
10237 attributes, or point to a C<const> op for a single attribute, or point
10238 to a C<list> op whose children apart from the C<pushmark> are C<const>
10239 ops for one or more attributes.  Each C<const> op must be a string,
10240 giving the attribute name optionally followed by parenthesised arguments,
10241 in the manner in which attributes appear in Perl source.  The attributes
10242 will be applied to the sub by this function.  C<attrs> is consumed by
10243 this function.
10244
10245 If C<o_is_gv> is false and C<o> is null, then the subroutine will
10246 be anonymous.  If C<o_is_gv> is false and C<o> is non-null, then C<o>
10247 must point to a C<const> op, which will be consumed by this function,
10248 and its string value supplies a name for the subroutine.  The name may
10249 be qualified or unqualified, and if it is unqualified then a default
10250 stash will be selected in some manner.  If C<o_is_gv> is true, then C<o>
10251 doesn't point to an C<OP> at all, but is instead a cast pointer to a C<GV>
10252 by which the subroutine will be named.
10253
10254 If there is already a subroutine of the specified name, then the new
10255 sub will either replace the existing one in the glob or be merged with
10256 the existing one.  A warning may be generated about redefinition.
10257
10258 If the subroutine has one of a few special names, such as C<BEGIN> or
10259 C<END>, then it will be claimed by the appropriate queue for automatic
10260 running of phase-related subroutines.  In this case the relevant glob will
10261 be left not containing any subroutine, even if it did contain one before.
10262 In the case of C<BEGIN>, the subroutine will be executed and the reference
10263 to it disposed of before this function returns.
10264
10265 The function returns a pointer to the constructed subroutine.  If the sub
10266 is anonymous then ownership of one counted reference to the subroutine
10267 is transferred to the caller.  If the sub is named then the caller does
10268 not get ownership of a reference.  In most such cases, where the sub
10269 has a non-phase name, the sub will be alive at the point it is returned
10270 by virtue of being contained in the glob that names it.  A phase-named
10271 subroutine will usually be alive by virtue of the reference owned by the
10272 phase's automatic run queue.  But a C<BEGIN> subroutine, having already
10273 been executed, will quite likely have been destroyed already by the
10274 time this function returns, making it erroneous for the caller to make
10275 any use of the returned pointer.  It is the caller's responsibility to
10276 ensure that it knows which of these situations applies.
10277
10278 =cut
10279 */
10280
10281 /* _x = extended */
10282 CV *
10283 Perl_newATTRSUB_x(pTHX_ I32 floor, OP *o, OP *proto, OP *attrs,
10284                             OP *block, bool o_is_gv)
10285 {
10286     GV *gv;
10287     const char *ps;
10288     STRLEN ps_len = 0; /* init it to avoid false uninit warning from icc */
10289     U32 ps_utf8 = 0;
10290     CV *cv = NULL;     /* the previous CV with this name, if any */
10291     SV *const_sv;
10292     const bool ec = PL_parser && PL_parser->error_count;
10293     /* If the subroutine has no body, no attributes, and no builtin attributes
10294        then it's just a sub declaration, and we may be able to get away with
10295        storing with a placeholder scalar in the symbol table, rather than a
10296        full CV.  If anything is present then it will take a full CV to
10297        store it.  */
10298     const I32 gv_fetch_flags
10299         = ec ? GV_NOADD_NOINIT :
10300         (block || attrs || (CvFLAGS(PL_compcv) & CVf_BUILTIN_ATTRS))
10301         ? GV_ADDMULTI : GV_ADDMULTI | GV_NOINIT;
10302     STRLEN namlen = 0;
10303     const char * const name =
10304          o ? SvPV_const(o_is_gv ? (SV *)o : cSVOPo->op_sv, namlen) : NULL;
10305     bool has_name;
10306     bool name_is_utf8 = o && !o_is_gv && SvUTF8(cSVOPo->op_sv);
10307     bool evanescent = FALSE;
10308     OP *start = NULL;
10309 #ifdef PERL_DEBUG_READONLY_OPS
10310     OPSLAB *slab = NULL;
10311 #endif
10312
10313     if (o_is_gv) {
10314         gv = (GV*)o;
10315         o = NULL;
10316         has_name = TRUE;
10317     } else if (name) {
10318         /* Try to optimise and avoid creating a GV.  Instead, the CV’s name
10319            hek and CvSTASH pointer together can imply the GV.  If the name
10320            contains a package name, then GvSTASH(CvGV(cv)) may differ from
10321            CvSTASH, so forego the optimisation if we find any.
10322            Also, we may be called from load_module at run time, so
10323            PL_curstash (which sets CvSTASH) may not point to the stash the
10324            sub is stored in.  */
10325         /* XXX This optimization is currently disabled for packages other
10326                than main, since there was too much CPAN breakage.  */
10327         const I32 flags =
10328            ec ? GV_NOADD_NOINIT
10329               :   (IN_PERL_RUNTIME && PL_curstash != CopSTASH(PL_curcop))
10330                || PL_curstash != PL_defstash
10331                || memchr(name, ':', namlen) || memchr(name, '\'', namlen)
10332                     ? gv_fetch_flags
10333                     : GV_ADDMULTI | GV_NOINIT | GV_NOTQUAL;
10334         gv = gv_fetchsv(cSVOPo->op_sv, flags, SVt_PVCV);
10335         has_name = TRUE;
10336     } else if (PERLDB_NAMEANON && CopLINE(PL_curcop)) {
10337         SV * const sv = sv_newmortal();
10338         Perl_sv_setpvf(aTHX_ sv, "%s[%s:%" IVdf "]",
10339                        PL_curstash ? "__ANON__" : "__ANON__::__ANON__",
10340                        CopFILE(PL_curcop), (IV)CopLINE(PL_curcop));
10341         gv = gv_fetchsv(sv, gv_fetch_flags, SVt_PVCV);
10342         has_name = TRUE;
10343     } else if (PL_curstash) {
10344         gv = gv_fetchpvs("__ANON__", gv_fetch_flags, SVt_PVCV);
10345         has_name = FALSE;
10346     } else {
10347         gv = gv_fetchpvs("__ANON__::__ANON__", gv_fetch_flags, SVt_PVCV);
10348         has_name = FALSE;
10349     }
10350
10351     if (!ec) {
10352         if (isGV(gv)) {
10353             move_proto_attr(&proto, &attrs, gv, 0);
10354         } else {
10355             assert(cSVOPo);
10356             move_proto_attr(&proto, &attrs, (GV *)cSVOPo->op_sv, 1);
10357         }
10358     }
10359
10360     if (proto) {
10361         assert(proto->op_type == OP_CONST);
10362         ps = SvPV_const(((SVOP*)proto)->op_sv, ps_len);
10363         ps_utf8 = SvUTF8(((SVOP*)proto)->op_sv);
10364     }
10365     else
10366         ps = NULL;
10367
10368     if (o)
10369         SAVEFREEOP(o);
10370     if (proto)
10371         SAVEFREEOP(proto);
10372     if (attrs)
10373         SAVEFREEOP(attrs);
10374
10375     if (ec) {
10376         op_free(block);
10377
10378         if (name)
10379             SvREFCNT_dec(PL_compcv);
10380         else
10381             cv = PL_compcv;
10382
10383         PL_compcv = 0;
10384         if (name && block) {
10385             const char *s = (char *) my_memrchr(name, ':', namlen);
10386             s = s ? s+1 : name;
10387             if (strEQ(s, "BEGIN")) {
10388                 if (PL_in_eval & EVAL_KEEPERR)
10389                     Perl_croak_nocontext("BEGIN not safe after errors--compilation aborted");
10390                 else {
10391                     SV * const errsv = ERRSV;
10392                     /* force display of errors found but not reported */
10393                     sv_catpvs(errsv, "BEGIN not safe after errors--compilation aborted");
10394                     Perl_croak_nocontext("%" SVf, SVfARG(errsv));
10395                 }
10396             }
10397         }
10398         goto done;
10399     }
10400
10401     if (!block && SvTYPE(gv) != SVt_PVGV) {
10402         /* If we are not defining a new sub and the existing one is not a
10403            full GV + CV... */
10404         if (attrs || (CvFLAGS(PL_compcv) & CVf_BUILTIN_ATTRS)) {
10405             /* We are applying attributes to an existing sub, so we need it
10406                upgraded if it is a constant.  */
10407             if (SvROK(gv) && SvTYPE(SvRV(gv)) != SVt_PVCV)
10408                 gv_init_pvn(gv, PL_curstash, name, namlen,
10409                             SVf_UTF8 * name_is_utf8);
10410         }
10411         else {                  /* Maybe prototype now, and had at maximum
10412                                    a prototype or const/sub ref before.  */
10413             if (SvTYPE(gv) > SVt_NULL) {
10414                 cv_ckproto_len_flags((const CV *)gv,
10415                                     o ? (const GV *)cSVOPo->op_sv : NULL, ps,
10416                                     ps_len, ps_utf8);
10417             }
10418
10419             if (!SvROK(gv)) {
10420                 if (ps) {
10421                     sv_setpvn(MUTABLE_SV(gv), ps, ps_len);
10422                     if (ps_utf8)
10423                         SvUTF8_on(MUTABLE_SV(gv));
10424                 }
10425                 else
10426                     sv_setiv(MUTABLE_SV(gv), -1);
10427             }
10428
10429             SvREFCNT_dec(PL_compcv);
10430             cv = PL_compcv = NULL;
10431             goto done;
10432         }
10433     }
10434
10435     cv = (!name || (isGV(gv) && GvCVGEN(gv)))
10436         ? NULL
10437         : isGV(gv)
10438             ? GvCV(gv)
10439             : SvROK(gv) && SvTYPE(SvRV(gv)) == SVt_PVCV
10440                 ? (CV *)SvRV(gv)
10441                 : NULL;
10442
10443     if (block) {
10444         assert(PL_parser);
10445         /* This makes sub {}; work as expected.  */
10446         if (block->op_type == OP_STUB) {
10447             const line_t l = PL_parser->copline;
10448             op_free(block);
10449             block = newSTATEOP(0, NULL, 0);
10450             PL_parser->copline = l;
10451         }
10452         block = CvLVALUE(PL_compcv)
10453              || (cv && CvLVALUE(cv) && !CvROOT(cv) && !CvXSUB(cv)
10454                     && (!isGV(gv) || !GvASSUMECV(gv)))
10455                    ? newUNOP(OP_LEAVESUBLV, 0,
10456                              op_lvalue(scalarseq(block), OP_LEAVESUBLV))
10457                    : newUNOP(OP_LEAVESUB, 0, scalarseq(block));
10458         start = LINKLIST(block);
10459         block->op_next = 0;
10460         if (ps && !*ps && !attrs && !CvLVALUE(PL_compcv))
10461             const_sv =
10462                 S_op_const_sv(aTHX_ start, PL_compcv,
10463                                         cBOOL(CvCLONE(PL_compcv)));
10464         else
10465             const_sv = NULL;
10466     }
10467     else
10468         const_sv = NULL;
10469
10470     if (SvPOK(gv) || (SvROK(gv) && SvTYPE(SvRV(gv)) != SVt_PVCV)) {
10471         cv_ckproto_len_flags((const CV *)gv,
10472                              o ? (const GV *)cSVOPo->op_sv : NULL, ps,
10473                              ps_len, ps_utf8|CV_CKPROTO_CURSTASH);
10474         if (SvROK(gv)) {
10475             /* All the other code for sub redefinition warnings expects the
10476                clobbered sub to be a CV.  Instead of making all those code
10477                paths more complex, just inline the RV version here.  */
10478             const line_t oldline = CopLINE(PL_curcop);
10479             assert(IN_PERL_COMPILETIME);
10480             if (PL_parser && PL_parser->copline != NOLINE)
10481                 /* This ensures that warnings are reported at the first
10482                    line of a redefinition, not the last.  */
10483                 CopLINE_set(PL_curcop, PL_parser->copline);
10484             /* protect against fatal warnings leaking compcv */
10485             SAVEFREESV(PL_compcv);
10486
10487             if (ckWARN(WARN_REDEFINE)
10488              || (  ckWARN_d(WARN_REDEFINE)
10489                 && (  !const_sv || SvRV(gv) == const_sv
10490                    || sv_cmp(SvRV(gv), const_sv)  ))) {
10491                 assert(cSVOPo);
10492                 Perl_warner(aTHX_ packWARN(WARN_REDEFINE),
10493                           "Constant subroutine %" SVf " redefined",
10494                           SVfARG(cSVOPo->op_sv));
10495             }
10496
10497             SvREFCNT_inc_simple_void_NN(PL_compcv);
10498             CopLINE_set(PL_curcop, oldline);
10499             SvREFCNT_dec(SvRV(gv));
10500         }
10501     }
10502
10503     if (cv) {
10504         const bool exists = CvROOT(cv) || CvXSUB(cv);
10505
10506         /* if the subroutine doesn't exist and wasn't pre-declared
10507          * with a prototype, assume it will be AUTOLOADed,
10508          * skipping the prototype check
10509          */
10510         if (exists || SvPOK(cv))
10511             cv_ckproto_len_flags(cv, gv, ps, ps_len, ps_utf8);
10512         /* already defined (or promised)? */
10513         if (exists || (isGV(gv) && GvASSUMECV(gv))) {
10514             S_already_defined(aTHX_ cv, block, o, NULL, &const_sv);
10515             if (block)
10516                 cv = NULL;
10517             else {
10518                 if (attrs)
10519                     goto attrs;
10520                 /* just a "sub foo;" when &foo is already defined */
10521                 SAVEFREESV(PL_compcv);
10522                 goto done;
10523             }
10524         }
10525     }
10526
10527     if (const_sv) {
10528         SvREFCNT_inc_simple_void_NN(const_sv);
10529         SvFLAGS(const_sv) |= SVs_PADTMP;
10530         if (cv) {
10531             assert(!CvROOT(cv) && !CvCONST(cv));
10532             cv_forget_slab(cv);
10533             SvPVCLEAR(MUTABLE_SV(cv));  /* prototype is "" */
10534             CvXSUBANY(cv).any_ptr = const_sv;
10535             CvXSUB(cv) = const_sv_xsub;
10536             CvCONST_on(cv);
10537             CvISXSUB_on(cv);
10538             PoisonPADLIST(cv);
10539             CvFLAGS(cv) |= CvMETHOD(PL_compcv);
10540         }
10541         else {
10542             if (isGV(gv) || CvMETHOD(PL_compcv)) {
10543                 if (name && isGV(gv))
10544                     GvCV_set(gv, NULL);
10545                 cv = newCONSTSUB_flags(
10546                     NULL, name, namlen, name_is_utf8 ? SVf_UTF8 : 0,
10547                     const_sv
10548                 );
10549                 assert(cv);
10550                 assert(SvREFCNT((SV*)cv) != 0);
10551                 CvFLAGS(cv) |= CvMETHOD(PL_compcv);
10552             }
10553             else {
10554                 if (!SvROK(gv)) {
10555                     SV_CHECK_THINKFIRST_COW_DROP((SV *)gv);
10556                     prepare_SV_for_RV((SV *)gv);
10557                     SvOK_off((SV *)gv);
10558                     SvROK_on(gv);
10559                 }
10560                 SvRV_set(gv, const_sv);
10561             }
10562         }
10563         op_free(block);
10564         SvREFCNT_dec(PL_compcv);
10565         PL_compcv = NULL;
10566         goto done;
10567     }
10568
10569     /* don't copy new BEGIN CV to old BEGIN CV - RT #129099 */
10570     if (name && cv && *name == 'B' && strEQ(name, "BEGIN"))
10571         cv = NULL;
10572
10573     if (cv) {                           /* must reuse cv if autoloaded */
10574         /* transfer PL_compcv to cv */
10575         if (block) {
10576             bool free_file = CvFILE(cv) && CvDYNFILE(cv);
10577             cv_flags_t existing_builtin_attrs = CvFLAGS(cv) & CVf_BUILTIN_ATTRS;
10578             PADLIST *const temp_av = CvPADLIST(cv);
10579             CV *const temp_cv = CvOUTSIDE(cv);
10580             const cv_flags_t other_flags =
10581                 CvFLAGS(cv) & (CVf_SLABBED|CVf_WEAKOUTSIDE);
10582             OP * const cvstart = CvSTART(cv);
10583
10584             if (isGV(gv)) {
10585                 CvGV_set(cv,gv);
10586                 assert(!CvCVGV_RC(cv));
10587                 assert(CvGV(cv) == gv);
10588             }
10589             else {
10590                 dVAR;
10591                 U32 hash;
10592                 PERL_HASH(hash, name, namlen);
10593                 CvNAME_HEK_set(cv,
10594                                share_hek(name,
10595                                          name_is_utf8
10596                                             ? -(SSize_t)namlen
10597                                             :  (SSize_t)namlen,
10598                                          hash));
10599             }
10600
10601             SvPOK_off(cv);
10602             CvFLAGS(cv) = CvFLAGS(PL_compcv) | existing_builtin_attrs
10603                                              | CvNAMED(cv);
10604             CvOUTSIDE(cv) = CvOUTSIDE(PL_compcv);
10605             CvOUTSIDE_SEQ(cv) = CvOUTSIDE_SEQ(PL_compcv);
10606             CvPADLIST_set(cv,CvPADLIST(PL_compcv));
10607             CvOUTSIDE(PL_compcv) = temp_cv;
10608             CvPADLIST_set(PL_compcv, temp_av);
10609             CvSTART(cv) = CvSTART(PL_compcv);
10610             CvSTART(PL_compcv) = cvstart;
10611             CvFLAGS(PL_compcv) &= ~(CVf_SLABBED|CVf_WEAKOUTSIDE);
10612             CvFLAGS(PL_compcv) |= other_flags;
10613
10614             if (free_file) {
10615                 Safefree(CvFILE(cv));
10616             }
10617             CvFILE_set_from_cop(cv, PL_curcop);
10618             CvSTASH_set(cv, PL_curstash);
10619
10620             /* inner references to PL_compcv must be fixed up ... */
10621             pad_fixup_inner_anons(CvPADLIST(cv), PL_compcv, cv);
10622             if (PERLDB_INTER)/* Advice debugger on the new sub. */
10623                 ++PL_sub_generation;
10624         }
10625         else {
10626             /* Might have had built-in attributes applied -- propagate them. */
10627             CvFLAGS(cv) |= (CvFLAGS(PL_compcv) & CVf_BUILTIN_ATTRS);
10628         }
10629         /* ... before we throw it away */
10630         SvREFCNT_dec(PL_compcv);
10631         PL_compcv = cv;
10632     }
10633     else {
10634         cv = PL_compcv;
10635         if (name && isGV(gv)) {
10636             GvCV_set(gv, cv);
10637             GvCVGEN(gv) = 0;
10638             if (HvENAME_HEK(GvSTASH(gv)))
10639                 /* sub Foo::bar { (shift)+1 } */
10640                 gv_method_changed(gv);
10641         }
10642         else if (name) {
10643             if (!SvROK(gv)) {
10644                 SV_CHECK_THINKFIRST_COW_DROP((SV *)gv);
10645                 prepare_SV_for_RV((SV *)gv);
10646                 SvOK_off((SV *)gv);
10647                 SvROK_on(gv);
10648             }
10649             SvRV_set(gv, (SV *)cv);
10650             if (HvENAME_HEK(PL_curstash))
10651                 mro_method_changed_in(PL_curstash);
10652         }
10653     }
10654     assert(cv);
10655     assert(SvREFCNT((SV*)cv) != 0);
10656
10657     if (!CvHASGV(cv)) {
10658         if (isGV(gv))
10659             CvGV_set(cv, gv);
10660         else {
10661             dVAR;
10662             U32 hash;
10663             PERL_HASH(hash, name, namlen);
10664             CvNAME_HEK_set(cv, share_hek(name,
10665                                          name_is_utf8
10666                                             ? -(SSize_t)namlen
10667                                             :  (SSize_t)namlen,
10668                                          hash));
10669         }
10670         CvFILE_set_from_cop(cv, PL_curcop);
10671         CvSTASH_set(cv, PL_curstash);
10672     }
10673
10674     if (ps) {
10675         sv_setpvn(MUTABLE_SV(cv), ps, ps_len);
10676         if ( ps_utf8 )
10677             SvUTF8_on(MUTABLE_SV(cv));
10678     }
10679
10680     if (block) {
10681         /* If we assign an optree to a PVCV, then we've defined a
10682          * subroutine that the debugger could be able to set a breakpoint
10683          * in, so signal to pp_entereval that it should not throw away any
10684          * saved lines at scope exit.  */
10685
10686         PL_breakable_sub_gen++;
10687         CvROOT(cv) = block;
10688         /* The cv no longer needs to hold a refcount on the slab, as CvROOT
10689            itself has a refcount. */
10690         CvSLABBED_off(cv);
10691         OpslabREFCNT_dec_padok((OPSLAB *)CvSTART(cv));
10692 #ifdef PERL_DEBUG_READONLY_OPS
10693         slab = (OPSLAB *)CvSTART(cv);
10694 #endif
10695         S_process_optree(aTHX_ cv, block, start);
10696     }
10697
10698   attrs:
10699     if (attrs) {
10700         /* Need to do a C<use attributes $stash_of_cv,\&cv,@attrs>. */
10701         HV *stash = name && !CvNAMED(cv) && GvSTASH(CvGV(cv))
10702                         ? GvSTASH(CvGV(cv))
10703                         : PL_curstash;
10704         if (!name)
10705             SAVEFREESV(cv);
10706         apply_attrs(stash, MUTABLE_SV(cv), attrs);
10707         if (!name)
10708             SvREFCNT_inc_simple_void_NN(cv);
10709     }
10710
10711     if (block && has_name) {
10712         if (PERLDB_SUBLINE && PL_curstash != PL_debstash) {
10713             SV * const tmpstr = cv_name(cv,NULL,0);
10714             GV * const db_postponed = gv_fetchpvs("DB::postponed",
10715                                                   GV_ADDMULTI, SVt_PVHV);
10716             HV *hv;
10717             SV * const sv = Perl_newSVpvf(aTHX_ "%s:%ld-%ld",
10718                                           CopFILE(PL_curcop),
10719                                           (long)PL_subline,
10720                                           (long)CopLINE(PL_curcop));
10721             (void)hv_store(GvHV(PL_DBsub), SvPVX_const(tmpstr),
10722                     SvUTF8(tmpstr) ? -(I32)SvCUR(tmpstr) : (I32)SvCUR(tmpstr), sv, 0);
10723             hv = GvHVn(db_postponed);
10724             if (HvTOTALKEYS(hv) > 0 && hv_exists(hv, SvPVX_const(tmpstr), SvUTF8(tmpstr) ? -(I32)SvCUR(tmpstr) : (I32)SvCUR(tmpstr))) {
10725                 CV * const pcv = GvCV(db_postponed);
10726                 if (pcv) {
10727                     dSP;
10728                     PUSHMARK(SP);
10729                     XPUSHs(tmpstr);
10730                     PUTBACK;
10731                     call_sv(MUTABLE_SV(pcv), G_DISCARD);
10732                 }
10733             }
10734         }
10735
10736         if (name) {
10737             if (PL_parser && PL_parser->error_count)
10738                 clear_special_blocks(name, gv, cv);
10739             else
10740                 evanescent =
10741                     process_special_blocks(floor, name, gv, cv);
10742         }
10743     }
10744     assert(cv);
10745
10746   done:
10747     assert(!cv || evanescent || SvREFCNT((SV*)cv) != 0);
10748     if (PL_parser)
10749         PL_parser->copline = NOLINE;
10750     LEAVE_SCOPE(floor);
10751
10752     assert(!cv || evanescent || SvREFCNT((SV*)cv) != 0);
10753     if (!evanescent) {
10754 #ifdef PERL_DEBUG_READONLY_OPS
10755     if (slab)
10756         Slab_to_ro(slab);
10757 #endif
10758     if (cv && name && block && CvOUTSIDE(cv) && !CvEVAL(CvOUTSIDE(cv)))
10759         pad_add_weakref(cv);
10760     }
10761     return cv;
10762 }
10763
10764 STATIC void
10765 S_clear_special_blocks(pTHX_ const char *const fullname,
10766                        GV *const gv, CV *const cv) {
10767     const char *colon;
10768     const char *name;
10769
10770     PERL_ARGS_ASSERT_CLEAR_SPECIAL_BLOCKS;
10771
10772     colon = strrchr(fullname,':');
10773     name = colon ? colon + 1 : fullname;
10774
10775     if ((*name == 'B' && strEQ(name, "BEGIN"))
10776         || (*name == 'E' && strEQ(name, "END"))
10777         || (*name == 'U' && strEQ(name, "UNITCHECK"))
10778         || (*name == 'C' && strEQ(name, "CHECK"))
10779         || (*name == 'I' && strEQ(name, "INIT"))) {
10780         if (!isGV(gv)) {
10781             (void)CvGV(cv);
10782             assert(isGV(gv));
10783         }
10784         GvCV_set(gv, NULL);
10785         SvREFCNT_dec_NN(MUTABLE_SV(cv));
10786     }
10787 }
10788
10789 /* Returns true if the sub has been freed.  */
10790 STATIC bool
10791 S_process_special_blocks(pTHX_ I32 floor, const char *const fullname,
10792                          GV *const gv,
10793                          CV *const cv)
10794 {
10795     const char *const colon = strrchr(fullname,':');
10796     const char *const name = colon ? colon + 1 : fullname;
10797
10798     PERL_ARGS_ASSERT_PROCESS_SPECIAL_BLOCKS;
10799
10800     if (*name == 'B') {
10801         if (strEQ(name, "BEGIN")) {
10802             const I32 oldscope = PL_scopestack_ix;
10803             dSP;
10804             (void)CvGV(cv);
10805             if (floor) LEAVE_SCOPE(floor);
10806             ENTER;
10807             PUSHSTACKi(PERLSI_REQUIRE);
10808             SAVECOPFILE(&PL_compiling);
10809             SAVECOPLINE(&PL_compiling);
10810             SAVEVPTR(PL_curcop);
10811
10812             DEBUG_x( dump_sub(gv) );
10813             Perl_av_create_and_push(aTHX_ &PL_beginav, MUTABLE_SV(cv));
10814             GvCV_set(gv,0);             /* cv has been hijacked */
10815             call_list(oldscope, PL_beginav);
10816
10817             POPSTACK;
10818             LEAVE;
10819             return !PL_savebegin;
10820         }
10821         else
10822             return FALSE;
10823     } else {
10824         if (*name == 'E') {
10825             if (strEQ(name, "END")) {
10826                 DEBUG_x( dump_sub(gv) );
10827                 Perl_av_create_and_unshift_one(aTHX_ &PL_endav, MUTABLE_SV(cv));
10828             } else
10829                 return FALSE;
10830         } else if (*name == 'U') {
10831             if (strEQ(name, "UNITCHECK")) {
10832                 /* It's never too late to run a unitcheck block */
10833                 Perl_av_create_and_unshift_one(aTHX_ &PL_unitcheckav, MUTABLE_SV(cv));
10834             }
10835             else
10836                 return FALSE;
10837         } else if (*name == 'C') {
10838             if (strEQ(name, "CHECK")) {
10839                 if (PL_main_start)
10840                     /* diag_listed_as: Too late to run %s block */
10841                     Perl_ck_warner(aTHX_ packWARN(WARN_VOID),
10842                                    "Too late to run CHECK block");
10843                 Perl_av_create_and_unshift_one(aTHX_ &PL_checkav, MUTABLE_SV(cv));
10844             }
10845             else
10846                 return FALSE;
10847         } else if (*name == 'I') {
10848             if (strEQ(name, "INIT")) {
10849                 if (PL_main_start)
10850                     /* diag_listed_as: Too late to run %s block */
10851                     Perl_ck_warner(aTHX_ packWARN(WARN_VOID),
10852                                    "Too late to run INIT block");
10853                 Perl_av_create_and_push(aTHX_ &PL_initav, MUTABLE_SV(cv));
10854             }
10855             else
10856                 return FALSE;
10857         } else
10858             return FALSE;
10859         DEBUG_x( dump_sub(gv) );
10860         (void)CvGV(cv);
10861         GvCV_set(gv,0);         /* cv has been hijacked */
10862         return FALSE;
10863     }
10864 }
10865
10866 /*
10867 =for apidoc newCONSTSUB
10868
10869 Behaves like L</newCONSTSUB_flags>, except that C<name> is nul-terminated
10870 rather than of counted length, and no flags are set.  (This means that
10871 C<name> is always interpreted as Latin-1.)
10872
10873 =cut
10874 */
10875
10876 CV *
10877 Perl_newCONSTSUB(pTHX_ HV *stash, const char *name, SV *sv)
10878 {
10879     return newCONSTSUB_flags(stash, name, name ? strlen(name) : 0, 0, sv);
10880 }
10881
10882 /*
10883 =for apidoc newCONSTSUB_flags
10884
10885 Construct a constant subroutine, also performing some surrounding
10886 jobs.  A scalar constant-valued subroutine is eligible for inlining
10887 at compile-time, and in Perl code can be created by S<C<sub FOO () {
10888 123 }>>.  Other kinds of constant subroutine have other treatment.
10889
10890 The subroutine will have an empty prototype and will ignore any arguments
10891 when called.  Its constant behaviour is determined by C<sv>.  If C<sv>
10892 is null, the subroutine will yield an empty list.  If C<sv> points to a
10893 scalar, the subroutine will always yield that scalar.  If C<sv> points
10894 to an array, the subroutine will always yield a list of the elements of
10895 that array in list context, or the number of elements in the array in
10896 scalar context.  This function takes ownership of one counted reference
10897 to the scalar or array, and will arrange for the object to live as long
10898 as the subroutine does.  If C<sv> points to a scalar then the inlining
10899 assumes that the value of the scalar will never change, so the caller
10900 must ensure that the scalar is not subsequently written to.  If C<sv>
10901 points to an array then no such assumption is made, so it is ostensibly
10902 safe to mutate the array or its elements, but whether this is really
10903 supported has not been determined.
10904
10905 The subroutine will have C<CvFILE> set according to C<PL_curcop>.
10906 Other aspects of the subroutine will be left in their default state.
10907 The caller is free to mutate the subroutine beyond its initial state
10908 after this function has returned.
10909
10910 If C<name> is null then the subroutine will be anonymous, with its
10911 C<CvGV> referring to an C<__ANON__> glob.  If C<name> is non-null then the
10912 subroutine will be named accordingly, referenced by the appropriate glob.
10913 C<name> is a string of length C<len> bytes giving a sigilless symbol
10914 name, in UTF-8 if C<flags> has the C<SVf_UTF8> bit set and in Latin-1
10915 otherwise.  The name may be either qualified or unqualified.  If the
10916 name is unqualified then it defaults to being in the stash specified by
10917 C<stash> if that is non-null, or to C<PL_curstash> if C<stash> is null.
10918 The symbol is always added to the stash if necessary, with C<GV_ADDMULTI>
10919 semantics.
10920
10921 C<flags> should not have bits set other than C<SVf_UTF8>.
10922
10923 If there is already a subroutine of the specified name, then the new sub
10924 will replace the existing one in the glob.  A warning may be generated
10925 about the redefinition.
10926
10927 If the subroutine has one of a few special names, such as C<BEGIN> or
10928 C<END>, then it will be claimed by the appropriate queue for automatic
10929 running of phase-related subroutines.  In this case the relevant glob will
10930 be left not containing any subroutine, even if it did contain one before.
10931 Execution of the subroutine will likely be a no-op, unless C<sv> was
10932 a tied array or the caller modified the subroutine in some interesting
10933 way before it was executed.  In the case of C<BEGIN>, the treatment is
10934 buggy: the sub will be executed when only half built, and may be deleted
10935 prematurely, possibly causing a crash.
10936
10937 The function returns a pointer to the constructed subroutine.  If the sub
10938 is anonymous then ownership of one counted reference to the subroutine
10939 is transferred to the caller.  If the sub is named then the caller does
10940 not get ownership of a reference.  In most such cases, where the sub
10941 has a non-phase name, the sub will be alive at the point it is returned
10942 by virtue of being contained in the glob that names it.  A phase-named
10943 subroutine will usually be alive by virtue of the reference owned by
10944 the phase's automatic run queue.  A C<BEGIN> subroutine may have been
10945 destroyed already by the time this function returns, but currently bugs
10946 occur in that case before the caller gets control.  It is the caller's
10947 responsibility to ensure that it knows which of these situations applies.
10948
10949 =cut
10950 */
10951
10952 CV *
10953 Perl_newCONSTSUB_flags(pTHX_ HV *stash, const char *name, STRLEN len,
10954                              U32 flags, SV *sv)
10955 {
10956     CV* cv;
10957     const char *const file = CopFILE(PL_curcop);
10958
10959     ENTER;
10960
10961     if (IN_PERL_RUNTIME) {
10962         /* at runtime, it's not safe to manipulate PL_curcop: it may be
10963          * an op shared between threads. Use a non-shared COP for our
10964          * dirty work */
10965          SAVEVPTR(PL_curcop);
10966          SAVECOMPILEWARNINGS();
10967          PL_compiling.cop_warnings = DUP_WARNINGS(PL_curcop->cop_warnings);
10968          PL_curcop = &PL_compiling;
10969     }
10970     SAVECOPLINE(PL_curcop);
10971     CopLINE_set(PL_curcop, PL_parser ? PL_parser->copline : NOLINE);
10972
10973     SAVEHINTS();
10974     PL_hints &= ~HINT_BLOCK_SCOPE;
10975
10976     if (stash) {
10977         SAVEGENERICSV(PL_curstash);
10978         PL_curstash = (HV *)SvREFCNT_inc_simple_NN(stash);
10979     }
10980
10981     /* Protect sv against leakage caused by fatal warnings. */
10982     if (sv) SAVEFREESV(sv);
10983
10984     /* file becomes the CvFILE. For an XS, it's usually static storage,
10985        and so doesn't get free()d.  (It's expected to be from the C pre-
10986        processor __FILE__ directive). But we need a dynamically allocated one,
10987        and we need it to get freed.  */
10988     cv = newXS_len_flags(name, len,
10989                          sv && SvTYPE(sv) == SVt_PVAV
10990                              ? const_av_xsub
10991                              : const_sv_xsub,
10992                          file ? file : "", "",
10993                          &sv, XS_DYNAMIC_FILENAME | flags);
10994     assert(cv);
10995     assert(SvREFCNT((SV*)cv) != 0);
10996     CvXSUBANY(cv).any_ptr = SvREFCNT_inc_simple(sv);
10997     CvCONST_on(cv);
10998
10999     LEAVE;
11000
11001     return cv;
11002 }
11003
11004 /*
11005 =for apidoc newXS
11006
11007 Used by C<xsubpp> to hook up XSUBs as Perl subs.  C<filename> needs to be
11008 static storage, as it is used directly as CvFILE(), without a copy being made.
11009
11010 =cut
11011 */
11012
11013 CV *
11014 Perl_newXS(pTHX_ const char *name, XSUBADDR_t subaddr, const char *filename)
11015 {
11016     PERL_ARGS_ASSERT_NEWXS;
11017     return newXS_len_flags(
11018         name, name ? strlen(name) : 0, subaddr, filename, NULL, NULL, 0
11019     );
11020 }
11021
11022 CV *
11023 Perl_newXS_flags(pTHX_ const char *name, XSUBADDR_t subaddr,
11024                  const char *const filename, const char *const proto,
11025                  U32 flags)
11026 {
11027     PERL_ARGS_ASSERT_NEWXS_FLAGS;
11028     return newXS_len_flags(
11029        name, name ? strlen(name) : 0, subaddr, filename, proto, NULL, flags
11030     );
11031 }
11032
11033 CV *
11034 Perl_newXS_deffile(pTHX_ const char *name, XSUBADDR_t subaddr)
11035 {
11036     PERL_ARGS_ASSERT_NEWXS_DEFFILE;
11037     return newXS_len_flags(
11038         name, strlen(name), subaddr, NULL, NULL, NULL, 0
11039     );
11040 }
11041
11042 /*
11043 =for apidoc newXS_len_flags
11044
11045 Construct an XS subroutine, also performing some surrounding jobs.
11046
11047 The subroutine will have the entry point C<subaddr>.  It will have
11048 the prototype specified by the nul-terminated string C<proto>, or
11049 no prototype if C<proto> is null.  The prototype string is copied;
11050 the caller can mutate the supplied string afterwards.  If C<filename>
11051 is non-null, it must be a nul-terminated filename, and the subroutine
11052 will have its C<CvFILE> set accordingly.  By default C<CvFILE> is set to
11053 point directly to the supplied string, which must be static.  If C<flags>
11054 has the C<XS_DYNAMIC_FILENAME> bit set, then a copy of the string will
11055 be taken instead.
11056
11057 Other aspects of the subroutine will be left in their default state.
11058 If anything else needs to be done to the subroutine for it to function
11059 correctly, it is the caller's responsibility to do that after this
11060 function has constructed it.  However, beware of the subroutine
11061 potentially being destroyed before this function returns, as described
11062 below.
11063
11064 If C<name> is null then the subroutine will be anonymous, with its
11065 C<CvGV> referring to an C<__ANON__> glob.  If C<name> is non-null then the
11066 subroutine will be named accordingly, referenced by the appropriate glob.
11067 C<name> is a string of length C<len> bytes giving a sigilless symbol name,
11068 in UTF-8 if C<flags> has the C<SVf_UTF8> bit set and in Latin-1 otherwise.
11069 The name may be either qualified or unqualified, with the stash defaulting
11070 in the same manner as for C<gv_fetchpvn_flags>.  C<flags> may contain
11071 flag bits understood by C<gv_fetchpvn_flags> with the same meaning as
11072 they have there, such as C<GV_ADDWARN>.  The symbol is always added to
11073 the stash if necessary, with C<GV_ADDMULTI> semantics.
11074
11075 If there is already a subroutine of the specified name, then the new sub
11076 will replace the existing one in the glob.  A warning may be generated
11077 about the redefinition.  If the old subroutine was C<CvCONST> then the
11078 decision about whether to warn is influenced by an expectation about
11079 whether the new subroutine will become a constant of similar value.
11080 That expectation is determined by C<const_svp>.  (Note that the call to
11081 this function doesn't make the new subroutine C<CvCONST> in any case;
11082 that is left to the caller.)  If C<const_svp> is null then it indicates
11083 that the new subroutine will not become a constant.  If C<const_svp>
11084 is non-null then it indicates that the new subroutine will become a
11085 constant, and it points to an C<SV*> that provides the constant value
11086 that the subroutine will have.
11087
11088 If the subroutine has one of a few special names, such as C<BEGIN> or
11089 C<END>, then it will be claimed by the appropriate queue for automatic
11090 running of phase-related subroutines.  In this case the relevant glob will
11091 be left not containing any subroutine, even if it did contain one before.
11092 In the case of C<BEGIN>, the subroutine will be executed and the reference
11093 to it disposed of before this function returns, and also before its
11094 prototype is set.  If a C<BEGIN> subroutine would not be sufficiently
11095 constructed by this function to be ready for execution then the caller
11096 must prevent this happening by giving the subroutine a different name.
11097
11098 The function returns a pointer to the constructed subroutine.  If the sub
11099 is anonymous then ownership of one counted reference to the subroutine
11100 is transferred to the caller.  If the sub is named then the caller does
11101 not get ownership of a reference.  In most such cases, where the sub
11102 has a non-phase name, the sub will be alive at the point it is returned
11103 by virtue of being contained in the glob that names it.  A phase-named
11104 subroutine will usually be alive by virtue of the reference owned by the
11105 phase's automatic run queue.  But a C<BEGIN> subroutine, having already
11106 been executed, will quite likely have been destroyed already by the
11107 time this function returns, making it erroneous for the caller to make
11108 any use of the returned pointer.  It is the caller's responsibility to
11109 ensure that it knows which of these situations applies.
11110
11111 =cut
11112 */
11113
11114 CV *
11115 Perl_newXS_len_flags(pTHX_ const char *name, STRLEN len,
11116                            XSUBADDR_t subaddr, const char *const filename,
11117                            const char *const proto, SV **const_svp,
11118                            U32 flags)
11119 {
11120     CV *cv;
11121     bool interleave = FALSE;
11122     bool evanescent = FALSE;
11123
11124     PERL_ARGS_ASSERT_NEWXS_LEN_FLAGS;
11125
11126     {
11127         GV * const gv = gv_fetchpvn(
11128                             name ? name : PL_curstash ? "__ANON__" : "__ANON__::__ANON__",
11129                             name ? len : PL_curstash ? sizeof("__ANON__") - 1:
11130                                 sizeof("__ANON__::__ANON__") - 1,
11131                             GV_ADDMULTI | flags, SVt_PVCV);
11132
11133         if ((cv = (name ? GvCV(gv) : NULL))) {
11134             if (GvCVGEN(gv)) {
11135                 /* just a cached method */
11136                 SvREFCNT_dec(cv);
11137                 cv = NULL;
11138             }
11139             else if (CvROOT(cv) || CvXSUB(cv) || GvASSUMECV(gv)) {
11140                 /* already defined (or promised) */
11141                 /* Redundant check that allows us to avoid creating an SV
11142                    most of the time: */
11143                 if (CvCONST(cv) || ckWARN(WARN_REDEFINE)) {
11144                     report_redefined_cv(newSVpvn_flags(
11145                                          name,len,(flags&SVf_UTF8)|SVs_TEMP
11146                                         ),
11147                                         cv, const_svp);
11148                 }
11149                 interleave = TRUE;
11150                 ENTER;
11151                 SAVEFREESV(cv);
11152                 cv = NULL;
11153             }
11154         }
11155     
11156         if (cv)                         /* must reuse cv if autoloaded */
11157             cv_undef(cv);
11158         else {
11159             cv = MUTABLE_CV(newSV_type(SVt_PVCV));
11160             if (name) {
11161                 GvCV_set(gv,cv);
11162                 GvCVGEN(gv) = 0;
11163                 if (HvENAME_HEK(GvSTASH(gv)))
11164                     gv_method_changed(gv); /* newXS */
11165             }
11166         }
11167         assert(cv);
11168         assert(SvREFCNT((SV*)cv) != 0);
11169
11170         CvGV_set(cv, gv);
11171         if(filename) {
11172             /* XSUBs can't be perl lang/perl5db.pl debugged
11173             if (PERLDB_LINE_OR_SAVESRC)
11174                 (void)gv_fetchfile(filename); */
11175             assert(!CvDYNFILE(cv)); /* cv_undef should have turned it off */
11176             if (flags & XS_DYNAMIC_FILENAME) {
11177                 CvDYNFILE_on(cv);
11178                 CvFILE(cv) = savepv(filename);
11179             } else {
11180             /* NOTE: not copied, as it is expected to be an external constant string */
11181                 CvFILE(cv) = (char *)filename;
11182             }
11183         } else {
11184             assert((flags & XS_DYNAMIC_FILENAME) == 0 && PL_xsubfilename);
11185             CvFILE(cv) = (char*)PL_xsubfilename;
11186         }
11187         CvISXSUB_on(cv);
11188         CvXSUB(cv) = subaddr;
11189 #ifndef PERL_IMPLICIT_CONTEXT
11190         CvHSCXT(cv) = &PL_stack_sp;
11191 #else
11192         PoisonPADLIST(cv);
11193 #endif
11194
11195         if (name)
11196             evanescent = process_special_blocks(0, name, gv, cv);
11197         else
11198             CvANON_on(cv);
11199     } /* <- not a conditional branch */
11200
11201     assert(cv);
11202     assert(evanescent || SvREFCNT((SV*)cv) != 0);
11203
11204     if (!evanescent) sv_setpv(MUTABLE_SV(cv), proto);
11205     if (interleave) LEAVE;
11206     assert(evanescent || SvREFCNT((SV*)cv) != 0);
11207     return cv;
11208 }
11209
11210 /* Add a stub CV to a typeglob.
11211  * This is the implementation of a forward declaration, 'sub foo';'
11212  */
11213
11214 CV *
11215 Perl_newSTUB(pTHX_ GV *gv, bool fake)
11216 {
11217     CV *cv = MUTABLE_CV(newSV_type(SVt_PVCV));
11218     GV *cvgv;
11219     PERL_ARGS_ASSERT_NEWSTUB;
11220     assert(!GvCVu(gv));
11221     GvCV_set(gv, cv);
11222     GvCVGEN(gv) = 0;
11223     if (!fake && GvSTASH(gv) && HvENAME_HEK(GvSTASH(gv)))
11224         gv_method_changed(gv);
11225     if (SvFAKE(gv)) {
11226         cvgv = gv_fetchsv((SV *)gv, GV_ADDMULTI, SVt_PVCV);
11227         SvFAKE_off(cvgv);
11228     }
11229     else cvgv = gv;
11230     CvGV_set(cv, cvgv);
11231     CvFILE_set_from_cop(cv, PL_curcop);
11232     CvSTASH_set(cv, PL_curstash);
11233     GvMULTI_on(gv);
11234     return cv;
11235 }
11236
11237 void
11238 Perl_newFORM(pTHX_ I32 floor, OP *o, OP *block)
11239 {
11240     CV *cv;
11241     GV *gv;
11242     OP *root;
11243     OP *start;
11244
11245     if (PL_parser && PL_parser->error_count) {
11246         op_free(block);
11247         goto finish;
11248     }
11249
11250     gv = o
11251         ? gv_fetchsv(cSVOPo->op_sv, GV_ADD, SVt_PVFM)
11252         : gv_fetchpvs("STDOUT", GV_ADD|GV_NOTQUAL, SVt_PVFM);
11253
11254     GvMULTI_on(gv);
11255     if ((cv = GvFORM(gv))) {
11256         if (ckWARN(WARN_REDEFINE)) {
11257             const line_t oldline = CopLINE(PL_curcop);
11258             if (PL_parser && PL_parser->copline != NOLINE)
11259                 CopLINE_set(PL_curcop, PL_parser->copline);
11260             if (o) {
11261                 Perl_warner(aTHX_ packWARN(WARN_REDEFINE),
11262                             "Format %" SVf " redefined", SVfARG(cSVOPo->op_sv));
11263             } else {
11264                 /* diag_listed_as: Format %s redefined */
11265                 Perl_warner(aTHX_ packWARN(WARN_REDEFINE),
11266                             "Format STDOUT redefined");
11267             }
11268             CopLINE_set(PL_curcop, oldline);
11269         }
11270         SvREFCNT_dec(cv);
11271     }
11272     cv = PL_compcv;
11273     GvFORM(gv) = (CV *)SvREFCNT_inc_simple_NN(cv);
11274     CvGV_set(cv, gv);
11275     CvFILE_set_from_cop(cv, PL_curcop);
11276
11277
11278     root = newUNOP(OP_LEAVEWRITE, 0, scalarseq(block));
11279     CvROOT(cv) = root;
11280     start = LINKLIST(root);
11281     root->op_next = 0;
11282     S_process_optree(aTHX_ cv, root, start);
11283     cv_forget_slab(cv);
11284
11285   finish:
11286     op_free(o);
11287     if (PL_parser)
11288         PL_parser->copline = NOLINE;
11289     LEAVE_SCOPE(floor);
11290     PL_compiling.cop_seq = 0;
11291 }
11292
11293 OP *
11294 Perl_newANONLIST(pTHX_ OP *o)
11295 {
11296     return op_convert_list(OP_ANONLIST, OPf_SPECIAL, o);
11297 }
11298
11299 OP *
11300 Perl_newANONHASH(pTHX_ OP *o)
11301 {
11302     return op_convert_list(OP_ANONHASH, OPf_SPECIAL, o);
11303 }
11304
11305 OP *
11306 Perl_newANONSUB(pTHX_ I32 floor, OP *proto, OP *block)
11307 {
11308     return newANONATTRSUB(floor, proto, NULL, block);
11309 }
11310
11311 OP *
11312 Perl_newANONATTRSUB(pTHX_ I32 floor, OP *proto, OP *attrs, OP *block)
11313 {
11314     SV * const cv = MUTABLE_SV(newATTRSUB(floor, 0, proto, attrs, block));
11315     OP * anoncode = 
11316         newSVOP(OP_ANONCODE, 0,
11317                 cv);
11318     if (CvANONCONST(cv))
11319         anoncode = newUNOP(OP_ANONCONST, 0,
11320                            op_convert_list(OP_ENTERSUB,
11321                                            OPf_STACKED|OPf_WANT_SCALAR,
11322                                            anoncode));
11323     return newUNOP(OP_REFGEN, 0, anoncode);
11324 }
11325
11326 OP *
11327 Perl_oopsAV(pTHX_ OP *o)
11328 {
11329     dVAR;
11330
11331     PERL_ARGS_ASSERT_OOPSAV;
11332
11333     switch (o->op_type) {
11334     case OP_PADSV:
11335     case OP_PADHV:
11336         OpTYPE_set(o, OP_PADAV);
11337         return ref(o, OP_RV2AV);
11338
11339     case OP_RV2SV:
11340     case OP_RV2HV:
11341         OpTYPE_set(o, OP_RV2AV);
11342         ref(o, OP_RV2AV);
11343         break;
11344
11345     default:
11346         Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL), "oops: oopsAV");
11347         break;
11348     }
11349     return o;
11350 }
11351
11352 OP *
11353 Perl_oopsHV(pTHX_ OP *o)
11354 {
11355     dVAR;
11356
11357     PERL_ARGS_ASSERT_OOPSHV;
11358
11359     switch (o->op_type) {
11360     case OP_PADSV:
11361     case OP_PADAV:
11362         OpTYPE_set(o, OP_PADHV);
11363         return ref(o, OP_RV2HV);
11364
11365     case OP_RV2SV:
11366     case OP_RV2AV:
11367         OpTYPE_set(o, OP_RV2HV);
11368         /* rv2hv steals the bottom bit for its own uses */
11369         o->op_private &= ~OPpARG1_MASK;
11370         ref(o, OP_RV2HV);
11371         break;
11372
11373     default:
11374         Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL), "oops: oopsHV");
11375         break;
11376     }
11377     return o;
11378 }
11379
11380 OP *
11381 Perl_newAVREF(pTHX_ OP *o)
11382 {
11383     dVAR;
11384
11385     PERL_ARGS_ASSERT_NEWAVREF;
11386
11387     if (o->op_type == OP_PADANY) {
11388         OpTYPE_set(o, OP_PADAV);
11389         return o;
11390     }
11391     else if ((o->op_type == OP_RV2AV || o->op_type == OP_PADAV)) {
11392         Perl_croak(aTHX_ "Can't use an array as a reference");
11393     }
11394     return newUNOP(OP_RV2AV, 0, scalar(o));
11395 }
11396
11397 OP *
11398 Perl_newGVREF(pTHX_ I32 type, OP *o)
11399 {
11400     if (type == OP_MAPSTART || type == OP_GREPSTART || type == OP_SORT)
11401         return newUNOP(OP_NULL, 0, o);
11402     return ref(newUNOP(OP_RV2GV, OPf_REF, o), type);
11403 }
11404
11405 OP *
11406 Perl_newHVREF(pTHX_ OP *o)
11407 {
11408     dVAR;
11409
11410     PERL_ARGS_ASSERT_NEWHVREF;
11411
11412     if (o->op_type == OP_PADANY) {
11413         OpTYPE_set(o, OP_PADHV);
11414         return o;
11415     }
11416     else if ((o->op_type == OP_RV2HV || o->op_type == OP_PADHV)) {
11417         Perl_croak(aTHX_ "Can't use a hash as a reference");
11418     }
11419     return newUNOP(OP_RV2HV, 0, scalar(o));
11420 }
11421
11422 OP *
11423 Perl_newCVREF(pTHX_ I32 flags, OP *o)
11424 {
11425     if (o->op_type == OP_PADANY) {
11426         dVAR;
11427         OpTYPE_set(o, OP_PADCV);
11428     }
11429     return newUNOP(OP_RV2CV, flags, scalar(o));
11430 }
11431
11432 OP *
11433 Perl_newSVREF(pTHX_ OP *o)
11434 {
11435     dVAR;
11436
11437     PERL_ARGS_ASSERT_NEWSVREF;
11438
11439     if (o->op_type == OP_PADANY) {
11440         OpTYPE_set(o, OP_PADSV);
11441         scalar(o);
11442         return o;
11443     }
11444     return newUNOP(OP_RV2SV, 0, scalar(o));
11445 }
11446
11447 /* Check routines. See the comments at the top of this file for details
11448  * on when these are called */
11449
11450 OP *
11451 Perl_ck_anoncode(pTHX_ OP *o)
11452 {
11453     PERL_ARGS_ASSERT_CK_ANONCODE;
11454
11455     cSVOPo->op_targ = pad_add_anon((CV*)cSVOPo->op_sv, o->op_type);
11456     cSVOPo->op_sv = NULL;
11457     return o;
11458 }
11459
11460 static void
11461 S_io_hints(pTHX_ OP *o)
11462 {
11463 #if O_BINARY != 0 || O_TEXT != 0
11464     HV * const table =
11465         PL_hints & HINT_LOCALIZE_HH ? GvHV(PL_hintgv) : NULL;;
11466     if (table) {
11467         SV **svp = hv_fetchs(table, "open_IN", FALSE);
11468         if (svp && *svp) {
11469             STRLEN len = 0;
11470             const char *d = SvPV_const(*svp, len);
11471             const I32 mode = mode_from_discipline(d, len);
11472             /* bit-and:ing with zero O_BINARY or O_TEXT would be useless. */
11473 #  if O_BINARY != 0
11474             if (mode & O_BINARY)
11475                 o->op_private |= OPpOPEN_IN_RAW;
11476 #  endif
11477 #  if O_TEXT != 0
11478             if (mode & O_TEXT)
11479                 o->op_private |= OPpOPEN_IN_CRLF;
11480 #  endif
11481         }
11482
11483         svp = hv_fetchs(table, "open_OUT", FALSE);
11484         if (svp && *svp) {
11485             STRLEN len = 0;
11486             const char *d = SvPV_const(*svp, len);
11487             const I32 mode = mode_from_discipline(d, len);
11488             /* bit-and:ing with zero O_BINARY or O_TEXT would be useless. */
11489 #  if O_BINARY != 0
11490             if (mode & O_BINARY)
11491                 o->op_private |= OPpOPEN_OUT_RAW;
11492 #  endif
11493 #  if O_TEXT != 0
11494             if (mode & O_TEXT)
11495                 o->op_private |= OPpOPEN_OUT_CRLF;
11496 #  endif
11497         }
11498     }
11499 #else
11500     PERL_UNUSED_CONTEXT;
11501     PERL_UNUSED_ARG(o);
11502 #endif
11503 }
11504
11505 OP *
11506 Perl_ck_backtick(pTHX_ OP *o)
11507 {
11508     GV *gv;
11509     OP *newop = NULL;
11510     OP *sibl;
11511     PERL_ARGS_ASSERT_CK_BACKTICK;
11512     o = ck_fun(o);
11513     /* qx and `` have a null pushmark; CORE::readpipe has only one kid. */
11514     if (o->op_flags & OPf_KIDS && (sibl = OpSIBLING(cUNOPo->op_first))
11515      && (gv = gv_override("readpipe",8)))
11516     {
11517         /* detach rest of siblings from o and its first child */
11518         op_sibling_splice(o, cUNOPo->op_first, -1, NULL);
11519         newop = S_new_entersubop(aTHX_ gv, sibl);
11520     }
11521     else if (!(o->op_flags & OPf_KIDS))
11522         newop = newUNOP(OP_BACKTICK, 0, newDEFSVOP());
11523     if (newop) {
11524         op_free(o);
11525         return newop;
11526     }
11527     S_io_hints(aTHX_ o);
11528     return o;
11529 }
11530
11531 OP *
11532 Perl_ck_bitop(pTHX_ OP *o)
11533 {
11534     PERL_ARGS_ASSERT_CK_BITOP;
11535
11536     o->op_private = (U8)(PL_hints & HINT_INTEGER);
11537
11538     if (!(o->op_flags & OPf_STACKED) /* Not an assignment */
11539             && OP_IS_INFIX_BIT(o->op_type))
11540     {
11541         const OP * const left = cBINOPo->op_first;
11542         const OP * const right = OpSIBLING(left);
11543         if ((OP_IS_NUMCOMPARE(left->op_type) &&
11544                 (left->op_flags & OPf_PARENS) == 0) ||
11545             (OP_IS_NUMCOMPARE(right->op_type) &&
11546                 (right->op_flags & OPf_PARENS) == 0))
11547             Perl_ck_warner(aTHX_ packWARN(WARN_PRECEDENCE),
11548                           "Possible precedence problem on bitwise %s operator",
11549                            o->op_type ==  OP_BIT_OR
11550                          ||o->op_type == OP_NBIT_OR  ? "|"
11551                         :  o->op_type ==  OP_BIT_AND
11552                          ||o->op_type == OP_NBIT_AND ? "&"
11553                         :  o->op_type ==  OP_BIT_XOR
11554                          ||o->op_type == OP_NBIT_XOR ? "^"
11555                         :  o->op_type == OP_SBIT_OR  ? "|."
11556                         :  o->op_type == OP_SBIT_AND ? "&." : "^."
11557                            );
11558     }
11559     return o;
11560 }
11561
11562 PERL_STATIC_INLINE bool
11563 is_dollar_bracket(pTHX_ const OP * const o)
11564 {
11565     const OP *kid;
11566     PERL_UNUSED_CONTEXT;
11567     return o->op_type == OP_RV2SV && o->op_flags & OPf_KIDS
11568         && (kid = cUNOPx(o)->op_first)
11569         && kid->op_type == OP_GV
11570         && strEQ(GvNAME(cGVOPx_gv(kid)), "[");
11571 }
11572
11573 /* for lt, gt, le, ge, eq, ne and their i_ variants */
11574
11575 OP *
11576 Perl_ck_cmp(pTHX_ OP *o)
11577 {
11578     bool is_eq;
11579     bool neg;
11580     bool reverse;
11581     bool iv0;
11582     OP *indexop, *constop, *start;
11583     SV *sv;
11584     IV iv;
11585
11586     PERL_ARGS_ASSERT_CK_CMP;
11587
11588     is_eq = (   o->op_type == OP_EQ
11589              || o->op_type == OP_NE
11590              || o->op_type == OP_I_EQ
11591              || o->op_type == OP_I_NE);
11592
11593     if (!is_eq && ckWARN(WARN_SYNTAX)) {
11594         const OP *kid = cUNOPo->op_first;
11595         if (kid &&
11596             (
11597                 (   is_dollar_bracket(aTHX_ kid)
11598                  && OpSIBLING(kid) && OpSIBLING(kid)->op_type == OP_CONST
11599                 )
11600              || (   kid->op_type == OP_CONST
11601                  && (kid = OpSIBLING(kid)) && is_dollar_bracket(aTHX_ kid)
11602                 )
11603            )
11604         )
11605             Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
11606                         "$[ used in %s (did you mean $] ?)", OP_DESC(o));
11607     }
11608
11609     /* convert (index(...) == -1) and variations into
11610      *   (r)index/BOOL(,NEG)
11611      */
11612
11613     reverse = FALSE;
11614
11615     indexop = cUNOPo->op_first;
11616     constop = OpSIBLING(indexop);
11617     start = NULL;
11618     if (indexop->op_type == OP_CONST) {
11619         constop = indexop;
11620         indexop = OpSIBLING(constop);
11621         start = constop;
11622         reverse = TRUE;
11623     }
11624
11625     if (indexop->op_type != OP_INDEX && indexop->op_type != OP_RINDEX)
11626         return o;
11627
11628     /* ($lex = index(....)) == -1 */
11629     if (indexop->op_private & OPpTARGET_MY)
11630         return o;
11631
11632     if (constop->op_type != OP_CONST)
11633         return o;
11634
11635     sv = cSVOPx_sv(constop);
11636     if (!(sv && SvIOK_notUV(sv)))
11637         return o;
11638
11639     iv = SvIVX(sv);
11640     if (iv != -1 && iv != 0)
11641         return o;
11642     iv0 = (iv == 0);
11643
11644     if (o->op_type == OP_LT || o->op_type == OP_I_LT) {
11645         if (!(iv0 ^ reverse))
11646             return o;
11647         neg = iv0;
11648     }
11649     else if (o->op_type == OP_LE || o->op_type == OP_I_LE) {
11650         if (iv0 ^ reverse)
11651             return o;
11652         neg = !iv0;
11653     }
11654     else if (o->op_type == OP_GE || o->op_type == OP_I_GE) {
11655         if (!(iv0 ^ reverse))
11656             return o;
11657         neg = !iv0;
11658     }
11659     else if (o->op_type == OP_GT || o->op_type == OP_I_GT) {
11660         if (iv0 ^ reverse)
11661             return o;
11662         neg = iv0;
11663     }
11664     else if (o->op_type == OP_EQ || o->op_type == OP_I_EQ) {
11665         if (iv0)
11666             return o;
11667         neg = TRUE;
11668     }
11669     else {
11670         assert(o->op_type == OP_NE || o->op_type == OP_I_NE);
11671         if (iv0)
11672             return o;
11673         neg = FALSE;
11674     }
11675
11676     indexop->op_flags &= ~OPf_PARENS;
11677     indexop->op_flags |= (o->op_flags & OPf_PARENS);
11678     indexop->op_private |= OPpTRUEBOOL;
11679     if (neg)
11680         indexop->op_private |= OPpINDEX_BOOLNEG;
11681     /* cut out the index op and free the eq,const ops */
11682     (void)op_sibling_splice(o, start, 1, NULL);
11683     op_free(o);
11684
11685     return indexop;
11686 }
11687
11688
11689 OP *
11690 Perl_ck_concat(pTHX_ OP *o)
11691 {
11692     const OP * const kid = cUNOPo->op_first;
11693
11694     PERL_ARGS_ASSERT_CK_CONCAT;
11695     PERL_UNUSED_CONTEXT;
11696
11697     /* reuse the padtmp returned by the concat child */
11698     if (kid->op_type == OP_CONCAT && !(kid->op_private & OPpTARGET_MY) &&
11699             !(kUNOP->op_first->op_flags & OPf_MOD))
11700     {
11701         o->op_flags |= OPf_STACKED;
11702         o->op_private |= OPpCONCAT_NESTED;
11703     }
11704     return o;
11705 }
11706
11707 OP *
11708 Perl_ck_spair(pTHX_ OP *o)
11709 {
11710     dVAR;
11711
11712     PERL_ARGS_ASSERT_CK_SPAIR;
11713
11714     if (o->op_flags & OPf_KIDS) {
11715         OP* newop;
11716         OP* kid;
11717         OP* kidkid;
11718         const OPCODE type = o->op_type;
11719         o = modkids(ck_fun(o), type);
11720         kid    = cUNOPo->op_first;
11721         kidkid = kUNOP->op_first;
11722         newop = OpSIBLING(kidkid);
11723         if (newop) {
11724             const OPCODE type = newop->op_type;
11725             if (OpHAS_SIBLING(newop))
11726                 return o;
11727             if (o->op_type == OP_REFGEN
11728              && (  type == OP_RV2CV
11729                 || (  !(newop->op_flags & OPf_PARENS)
11730                    && (  type == OP_RV2AV || type == OP_PADAV
11731                       || type == OP_RV2HV || type == OP_PADHV))))
11732                 NOOP; /* OK (allow srefgen for \@a and \%h) */
11733             else if (OP_GIMME(newop,0) != G_SCALAR)
11734                 return o;
11735         }
11736         /* excise first sibling */
11737         op_sibling_splice(kid, NULL, 1, NULL);
11738         op_free(kidkid);
11739     }
11740     /* transforms OP_REFGEN into OP_SREFGEN, OP_CHOP into OP_SCHOP,
11741      * and OP_CHOMP into OP_SCHOMP */
11742     o->op_ppaddr = PL_ppaddr[++o->op_type];
11743     return ck_fun(o);
11744 }
11745
11746 OP *
11747 Perl_ck_delete(pTHX_ OP *o)
11748 {
11749     PERL_ARGS_ASSERT_CK_DELETE;
11750
11751     o = ck_fun(o);
11752     o->op_private = 0;
11753     if (o->op_flags & OPf_KIDS) {
11754         OP * const kid = cUNOPo->op_first;
11755         switch (kid->op_type) {
11756         case OP_ASLICE:
11757             o->op_flags |= OPf_SPECIAL;
11758             /* FALLTHROUGH */
11759         case OP_HSLICE:
11760             o->op_private |= OPpSLICE;
11761             break;
11762         case OP_AELEM:
11763             o->op_flags |= OPf_SPECIAL;
11764             /* FALLTHROUGH */
11765         case OP_HELEM:
11766             break;
11767         case OP_KVASLICE:
11768             o->op_flags |= OPf_SPECIAL;
11769             /* FALLTHROUGH */
11770         case OP_KVHSLICE:
11771             o->op_private |= OPpKVSLICE;
11772             break;
11773         default:
11774             Perl_croak(aTHX_ "delete argument is not a HASH or ARRAY "
11775                              "element or slice");
11776         }
11777         if (kid->op_private & OPpLVAL_INTRO)
11778             o->op_private |= OPpLVAL_INTRO;
11779         op_null(kid);
11780     }
11781     return o;
11782 }
11783
11784 OP *
11785 Perl_ck_eof(pTHX_ OP *o)
11786 {
11787     PERL_ARGS_ASSERT_CK_EOF;
11788
11789     if (o->op_flags & OPf_KIDS) {
11790         OP *kid;
11791         if (cLISTOPo->op_first->op_type == OP_STUB) {
11792             OP * const newop
11793                 = newUNOP(o->op_type, OPf_SPECIAL, newGVOP(OP_GV, 0, PL_argvgv));
11794             op_free(o);
11795             o = newop;
11796         }
11797         o = ck_fun(o);
11798         kid = cLISTOPo->op_first;
11799         if (kid->op_type == OP_RV2GV)
11800             kid->op_private |= OPpALLOW_FAKE;
11801     }
11802     return o;
11803 }
11804
11805
11806 OP *
11807 Perl_ck_eval(pTHX_ OP *o)
11808 {
11809     dVAR;
11810
11811     PERL_ARGS_ASSERT_CK_EVAL;
11812
11813     PL_hints |= HINT_BLOCK_SCOPE;
11814     if (o->op_flags & OPf_KIDS) {
11815         SVOP * const kid = (SVOP*)cUNOPo->op_first;
11816         assert(kid);
11817
11818         if (o->op_type == OP_ENTERTRY) {
11819             LOGOP *enter;
11820
11821             /* cut whole sibling chain free from o */
11822             op_sibling_splice(o, NULL, -1, NULL);
11823             op_free(o);
11824
11825             enter = alloc_LOGOP(OP_ENTERTRY, NULL, NULL);
11826
11827             /* establish postfix order */
11828             enter->op_next = (OP*)enter;
11829
11830             o = op_prepend_elem(OP_LINESEQ, (OP*)enter, (OP*)kid);
11831             OpTYPE_set(o, OP_LEAVETRY);
11832             enter->op_other = o;
11833             return o;
11834         }
11835         else {
11836             scalar((OP*)kid);
11837             S_set_haseval(aTHX);
11838         }
11839     }
11840     else {
11841         const U8 priv = o->op_private;
11842         op_free(o);
11843         /* the newUNOP will recursively call ck_eval(), which will handle
11844          * all the stuff at the end of this function, like adding
11845          * OP_HINTSEVAL
11846          */
11847         return newUNOP(OP_ENTEREVAL, priv <<8, newDEFSVOP());
11848     }
11849     o->op_targ = (PADOFFSET)PL_hints;
11850     if (o->op_private & OPpEVAL_BYTES) o->op_targ &= ~HINT_UTF8;
11851     if ((PL_hints & HINT_LOCALIZE_HH) != 0
11852      && !(o->op_private & OPpEVAL_COPHH) && GvHV(PL_hintgv)) {
11853         /* Store a copy of %^H that pp_entereval can pick up. */
11854         HV *hh = hv_copy_hints_hv(GvHV(PL_hintgv));
11855         OP *hhop;
11856         STOREFEATUREBITSHH(hh);
11857         hhop = newSVOP(OP_HINTSEVAL, 0, MUTABLE_SV(hh));
11858         /* append hhop to only child  */
11859         op_sibling_splice(o, cUNOPo->op_first, 0, hhop);
11860
11861         o->op_private |= OPpEVAL_HAS_HH;
11862     }
11863     if (!(o->op_private & OPpEVAL_BYTES)
11864          && FEATURE_UNIEVAL_IS_ENABLED)
11865             o->op_private |= OPpEVAL_UNICODE;
11866     return o;
11867 }
11868
11869 OP *
11870 Perl_ck_exec(pTHX_ OP *o)
11871 {
11872     PERL_ARGS_ASSERT_CK_EXEC;
11873
11874     if (o->op_flags & OPf_STACKED) {
11875         OP *kid;
11876         o = ck_fun(o);
11877         kid = OpSIBLING(cUNOPo->op_first);
11878         if (kid->op_type == OP_RV2GV)
11879             op_null(kid);
11880     }
11881     else
11882         o = listkids(o);
11883     return o;
11884 }
11885
11886 OP *
11887 Perl_ck_exists(pTHX_ OP *o)
11888 {
11889     PERL_ARGS_ASSERT_CK_EXISTS;
11890
11891     o = ck_fun(o);
11892     if (o->op_flags & OPf_KIDS) {
11893         OP * const kid = cUNOPo->op_first;
11894         if (kid->op_type == OP_ENTERSUB) {
11895             (void) ref(kid, o->op_type);
11896             if (kid->op_type != OP_RV2CV
11897                         && !(PL_parser && PL_parser->error_count))
11898                 Perl_croak(aTHX_
11899                           "exists argument is not a subroutine name");
11900             o->op_private |= OPpEXISTS_SUB;
11901         }
11902         else if (kid->op_type == OP_AELEM)
11903             o->op_flags |= OPf_SPECIAL;
11904         else if (kid->op_type != OP_HELEM)
11905             Perl_croak(aTHX_ "exists argument is not a HASH or ARRAY "
11906                              "element or a subroutine");
11907         op_null(kid);
11908     }
11909     return o;
11910 }
11911
11912 OP *
11913 Perl_ck_rvconst(pTHX_ OP *o)
11914 {
11915     dVAR;
11916     SVOP * const kid = (SVOP*)cUNOPo->op_first;
11917
11918     PERL_ARGS_ASSERT_CK_RVCONST;
11919
11920     if (o->op_type == OP_RV2HV)
11921         /* rv2hv steals the bottom bit for its own uses */
11922         o->op_private &= ~OPpARG1_MASK;
11923
11924     o->op_private |= (PL_hints & HINT_STRICT_REFS);
11925
11926     if (kid->op_type == OP_CONST) {
11927         int iscv;
11928         GV *gv;
11929         SV * const kidsv = kid->op_sv;
11930
11931         /* Is it a constant from cv_const_sv()? */
11932         if ((SvROK(kidsv) || isGV_with_GP(kidsv)) && SvREADONLY(kidsv)) {
11933             return o;
11934         }
11935         if (SvTYPE(kidsv) == SVt_PVAV) return o;
11936         if ((o->op_private & HINT_STRICT_REFS) && (kid->op_private & OPpCONST_BARE)) {
11937             const char *badthing;
11938             switch (o->op_type) {
11939             case OP_RV2SV:
11940                 badthing = "a SCALAR";
11941                 break;
11942             case OP_RV2AV:
11943                 badthing = "an ARRAY";
11944                 break;
11945             case OP_RV2HV:
11946                 badthing = "a HASH";
11947                 break;
11948             default:
11949                 badthing = NULL;
11950                 break;
11951             }
11952             if (badthing)
11953                 Perl_croak(aTHX_
11954                            "Can't use bareword (\"%" SVf "\") as %s ref while \"strict refs\" in use",
11955                            SVfARG(kidsv), badthing);
11956         }
11957         /*
11958          * This is a little tricky.  We only want to add the symbol if we
11959          * didn't add it in the lexer.  Otherwise we get duplicate strict
11960          * warnings.  But if we didn't add it in the lexer, we must at
11961          * least pretend like we wanted to add it even if it existed before,
11962          * or we get possible typo warnings.  OPpCONST_ENTERED says
11963          * whether the lexer already added THIS instance of this symbol.
11964          */
11965         iscv = o->op_type == OP_RV2CV ? GV_NOEXPAND|GV_ADDMULTI : 0;
11966         gv = gv_fetchsv(kidsv,
11967                 o->op_type == OP_RV2CV
11968                         && o->op_private & OPpMAY_RETURN_CONSTANT
11969                     ? GV_NOEXPAND
11970                     : iscv | !(kid->op_private & OPpCONST_ENTERED),
11971                 iscv
11972                     ? SVt_PVCV
11973                     : o->op_type == OP_RV2SV
11974                         ? SVt_PV
11975                         : o->op_type == OP_RV2AV
11976                             ? SVt_PVAV
11977                             : o->op_type == OP_RV2HV
11978                                 ? SVt_PVHV
11979                                 : SVt_PVGV);
11980         if (gv) {
11981             if (!isGV(gv)) {
11982                 assert(iscv);
11983                 assert(SvROK(gv));
11984                 if (!(o->op_private & OPpMAY_RETURN_CONSTANT)
11985                   && SvTYPE(SvRV(gv)) != SVt_PVCV)
11986                     gv_fetchsv(kidsv, GV_ADDMULTI, SVt_PVCV);
11987             }
11988             OpTYPE_set(kid, OP_GV);
11989             SvREFCNT_dec(kid->op_sv);
11990 #ifdef USE_ITHREADS
11991             /* XXX hack: dependence on sizeof(PADOP) <= sizeof(SVOP) */
11992             STATIC_ASSERT_STMT(sizeof(PADOP) <= sizeof(SVOP));
11993             kPADOP->op_padix = pad_alloc(OP_GV, SVf_READONLY);
11994             SvREFCNT_dec(PAD_SVl(kPADOP->op_padix));
11995             PAD_SETSV(kPADOP->op_padix, MUTABLE_SV(SvREFCNT_inc_simple_NN(gv)));
11996 #else
11997             kid->op_sv = SvREFCNT_inc_simple_NN(gv);
11998 #endif
11999             kid->op_private = 0;
12000             /* FAKE globs in the symbol table cause weird bugs (#77810) */
12001             SvFAKE_off(gv);
12002         }
12003     }
12004     return o;
12005 }
12006
12007 OP *
12008 Perl_ck_ftst(pTHX_ OP *o)
12009 {
12010     dVAR;
12011     const I32 type = o->op_type;
12012
12013     PERL_ARGS_ASSERT_CK_FTST;
12014
12015     if (o->op_flags & OPf_REF) {
12016         NOOP;
12017     }
12018     else if (o->op_flags & OPf_KIDS && cUNOPo->op_first->op_type != OP_STUB) {
12019         SVOP * const kid = (SVOP*)cUNOPo->op_first;
12020         const OPCODE kidtype = kid->op_type;
12021
12022         if (kidtype == OP_CONST && (kid->op_private & OPpCONST_BARE)
12023          && !kid->op_folded) {
12024             OP * const newop = newGVOP(type, OPf_REF,
12025                 gv_fetchsv(kid->op_sv, GV_ADD, SVt_PVIO));
12026             op_free(o);
12027             return newop;
12028         }
12029
12030         if ((kidtype == OP_RV2AV || kidtype == OP_PADAV) && ckWARN(WARN_SYNTAX)) {
12031             SV *name = S_op_varname_subscript(aTHX_ (OP*)kid, 2);
12032             if (name) {
12033                 /* diag_listed_as: Array passed to stat will be coerced to a scalar%s */
12034                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX), "%s (did you want stat %" SVf "?)",
12035                             array_passed_to_stat, name);
12036             }
12037             else {
12038                 /* diag_listed_as: Array passed to stat will be coerced to a scalar%s */
12039                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX), "%s", array_passed_to_stat);
12040             }
12041        }
12042         scalar((OP *) kid);
12043         if ((PL_hints & HINT_FILETEST_ACCESS) && OP_IS_FILETEST_ACCESS(o->op_type))
12044             o->op_private |= OPpFT_ACCESS;
12045         if (OP_IS_FILETEST(type)
12046             && OP_IS_FILETEST(kidtype)
12047         ) {
12048             o->op_private |= OPpFT_STACKED;
12049             kid->op_private |= OPpFT_STACKING;
12050             if (kidtype == OP_FTTTY && (
12051                    !(kid->op_private & OPpFT_STACKED)
12052                 || kid->op_private & OPpFT_AFTER_t
12053                ))
12054                 o->op_private |= OPpFT_AFTER_t;
12055         }
12056     }
12057     else {
12058         op_free(o);
12059         if (type == OP_FTTTY)
12060             o = newGVOP(type, OPf_REF, PL_stdingv);
12061         else
12062             o = newUNOP(type, 0, newDEFSVOP());
12063     }
12064     return o;
12065 }
12066
12067 OP *
12068 Perl_ck_fun(pTHX_ OP *o)
12069 {
12070     const int type = o->op_type;
12071     I32 oa = PL_opargs[type] >> OASHIFT;
12072
12073     PERL_ARGS_ASSERT_CK_FUN;
12074
12075     if (o->op_flags & OPf_STACKED) {
12076         if ((oa & OA_OPTIONAL) && (oa >> 4) && !((oa >> 4) & OA_OPTIONAL))
12077             oa &= ~OA_OPTIONAL;
12078         else
12079             return no_fh_allowed(o);
12080     }
12081
12082     if (o->op_flags & OPf_KIDS) {
12083         OP *prev_kid = NULL;
12084         OP *kid = cLISTOPo->op_first;
12085         I32 numargs = 0;
12086         bool seen_optional = FALSE;
12087
12088         if (kid->op_type == OP_PUSHMARK ||
12089             (kid->op_type == OP_NULL && kid->op_targ == OP_PUSHMARK))
12090         {
12091             prev_kid = kid;
12092             kid = OpSIBLING(kid);
12093         }
12094         if (kid && kid->op_type == OP_COREARGS) {
12095             bool optional = FALSE;
12096             while (oa) {
12097                 numargs++;
12098                 if (oa & OA_OPTIONAL) optional = TRUE;
12099                 oa = oa >> 4;
12100             }
12101             if (optional) o->op_private |= numargs;
12102             return o;
12103         }
12104
12105         while (oa) {
12106             if (oa & OA_OPTIONAL || (oa & 7) == OA_LIST) {
12107                 if (!kid && !seen_optional && PL_opargs[type] & OA_DEFGV) {
12108                     kid = newDEFSVOP();
12109                     /* append kid to chain */
12110                     op_sibling_splice(o, prev_kid, 0, kid);
12111                 }
12112                 seen_optional = TRUE;
12113             }
12114             if (!kid) break;
12115
12116             numargs++;
12117             switch (oa & 7) {
12118             case OA_SCALAR:
12119                 /* list seen where single (scalar) arg expected? */
12120                 if (numargs == 1 && !(oa >> 4)
12121                     && kid->op_type == OP_LIST && type != OP_SCALAR)
12122                 {
12123                     return too_many_arguments_pv(o,PL_op_desc[type], 0);
12124                 }
12125                 if (type != OP_DELETE) scalar(kid);
12126                 break;
12127             case OA_LIST:
12128                 if (oa < 16) {
12129                     kid = 0;
12130                     continue;
12131                 }
12132                 else
12133                     list(kid);
12134                 break;
12135             case OA_AVREF:
12136                 if ((type == OP_PUSH || type == OP_UNSHIFT)
12137                     && !OpHAS_SIBLING(kid))
12138                     Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX),
12139                                    "Useless use of %s with no values",
12140                                    PL_op_desc[type]);
12141
12142                 if (kid->op_type == OP_CONST
12143                       && (  !SvROK(cSVOPx_sv(kid)) 
12144                          || SvTYPE(SvRV(cSVOPx_sv(kid))) != SVt_PVAV  )
12145                         )
12146                     bad_type_pv(numargs, "array", o, kid);
12147                 else if (kid->op_type == OP_RV2HV || kid->op_type == OP_PADHV
12148                          || kid->op_type == OP_RV2GV) {
12149                     bad_type_pv(1, "array", o, kid);
12150                 }
12151                 else if (kid->op_type != OP_RV2AV && kid->op_type != OP_PADAV) {
12152                     yyerror_pv(Perl_form(aTHX_ "Experimental %s on scalar is now forbidden",
12153                                          PL_op_desc[type]), 0);
12154                 }
12155                 else {
12156                     op_lvalue(kid, type);
12157                 }
12158                 break;
12159             case OA_HVREF:
12160                 if (kid->op_type != OP_RV2HV && kid->op_type != OP_PADHV)
12161                     bad_type_pv(numargs, "hash", o, kid);
12162                 op_lvalue(kid, type);
12163                 break;
12164             case OA_CVREF:
12165                 {
12166                     /* replace kid with newop in chain */
12167                     OP * const newop =
12168                         S_op_sibling_newUNOP(aTHX_ o, prev_kid, OP_NULL, 0);
12169                     newop->op_next = newop;
12170                     kid = newop;
12171                 }
12172                 break;
12173             case OA_FILEREF:
12174                 if (kid->op_type != OP_GV && kid->op_type != OP_RV2GV) {
12175                     if (kid->op_type == OP_CONST &&
12176                         (kid->op_private & OPpCONST_BARE))
12177                     {
12178                         OP * const newop = newGVOP(OP_GV, 0,
12179                             gv_fetchsv(((SVOP*)kid)->op_sv, GV_ADD, SVt_PVIO));
12180                         /* replace kid with newop in chain */
12181                         op_sibling_splice(o, prev_kid, 1, newop);
12182                         op_free(kid);
12183                         kid = newop;
12184                     }
12185                     else if (kid->op_type == OP_READLINE) {
12186                         /* neophyte patrol: open(<FH>), close(<FH>) etc. */
12187                         bad_type_pv(numargs, "HANDLE", o, kid);
12188                     }
12189                     else {
12190                         I32 flags = OPf_SPECIAL;
12191                         I32 priv = 0;
12192                         PADOFFSET targ = 0;
12193
12194                         /* is this op a FH constructor? */
12195                         if (is_handle_constructor(o,numargs)) {
12196                             const char *name = NULL;
12197                             STRLEN len = 0;
12198                             U32 name_utf8 = 0;
12199                             bool want_dollar = TRUE;
12200
12201                             flags = 0;
12202                             /* Set a flag to tell rv2gv to vivify
12203                              * need to "prove" flag does not mean something
12204                              * else already - NI-S 1999/05/07
12205                              */
12206                             priv = OPpDEREF;
12207                             if (kid->op_type == OP_PADSV) {
12208                                 PADNAME * const pn
12209                                     = PAD_COMPNAME_SV(kid->op_targ);
12210                                 name = PadnamePV (pn);
12211                                 len  = PadnameLEN(pn);
12212                                 name_utf8 = PadnameUTF8(pn);
12213                             }
12214                             else if (kid->op_type == OP_RV2SV
12215                                      && kUNOP->op_first->op_type == OP_GV)
12216                             {
12217                                 GV * const gv = cGVOPx_gv(kUNOP->op_first);
12218                                 name = GvNAME(gv);
12219                                 len = GvNAMELEN(gv);
12220                                 name_utf8 = GvNAMEUTF8(gv) ? SVf_UTF8 : 0;
12221                             }
12222                             else if (kid->op_type == OP_AELEM
12223                                      || kid->op_type == OP_HELEM)
12224                             {
12225                                  OP *firstop;
12226                                  OP *op = ((BINOP*)kid)->op_first;
12227                                  name = NULL;
12228                                  if (op) {
12229                                       SV *tmpstr = NULL;
12230                                       const char * const a =
12231                                            kid->op_type == OP_AELEM ?
12232                                            "[]" : "{}";
12233                                       if (((op->op_type == OP_RV2AV) ||
12234                                            (op->op_type == OP_RV2HV)) &&
12235                                           (firstop = ((UNOP*)op)->op_first) &&
12236                                           (firstop->op_type == OP_GV)) {
12237                                            /* packagevar $a[] or $h{} */
12238                                            GV * const gv = cGVOPx_gv(firstop);
12239                                            if (gv)
12240                                                 tmpstr =
12241                                                      Perl_newSVpvf(aTHX_
12242                                                                    "%s%c...%c",
12243                                                                    GvNAME(gv),
12244                                                                    a[0], a[1]);
12245                                       }
12246                                       else if (op->op_type == OP_PADAV
12247                                                || op->op_type == OP_PADHV) {
12248                                            /* lexicalvar $a[] or $h{} */
12249                                            const char * const padname =
12250                                                 PAD_COMPNAME_PV(op->op_targ);
12251                                            if (padname)
12252                                                 tmpstr =
12253                                                      Perl_newSVpvf(aTHX_
12254                                                                    "%s%c...%c",
12255                                                                    padname + 1,
12256                                                                    a[0], a[1]);
12257                                       }
12258                                       if (tmpstr) {
12259                                            name = SvPV_const(tmpstr, len);
12260                                            name_utf8 = SvUTF8(tmpstr);
12261                                            sv_2mortal(tmpstr);
12262                                       }
12263                                  }
12264                                  if (!name) {
12265                                       name = "__ANONIO__";
12266                                       len = 10;
12267                                       want_dollar = FALSE;
12268                                  }
12269                                  op_lvalue(kid, type);
12270                             }
12271                             if (name) {
12272                                 SV *namesv;
12273                                 targ = pad_alloc(OP_RV2GV, SVf_READONLY);
12274                                 namesv = PAD_SVl(targ);
12275                                 if (want_dollar && *name != '$')
12276                                     sv_setpvs(namesv, "$");
12277                                 else
12278                                     SvPVCLEAR(namesv);
12279                                 sv_catpvn(namesv, name, len);
12280                                 if ( name_utf8 ) SvUTF8_on(namesv);
12281                             }
12282                         }
12283                         scalar(kid);
12284                         kid = S_op_sibling_newUNOP(aTHX_ o, prev_kid,
12285                                     OP_RV2GV, flags);
12286                         kid->op_targ = targ;
12287                         kid->op_private |= priv;
12288                     }
12289                 }
12290                 scalar(kid);
12291                 break;
12292             case OA_SCALARREF:
12293                 if ((type == OP_UNDEF || type == OP_POS)
12294                     && numargs == 1 && !(oa >> 4)
12295                     && kid->op_type == OP_LIST)
12296                     return too_many_arguments_pv(o,PL_op_desc[type], 0);
12297                 op_lvalue(scalar(kid), type);
12298                 break;
12299             }
12300             oa >>= 4;
12301             prev_kid = kid;
12302             kid = OpSIBLING(kid);
12303         }
12304         /* FIXME - should the numargs or-ing move after the too many
12305          * arguments check? */
12306         o->op_private |= numargs;
12307         if (kid)
12308             return too_many_arguments_pv(o,OP_DESC(o), 0);
12309         listkids(o);
12310     }
12311     else if (PL_opargs[type] & OA_DEFGV) {
12312         /* Ordering of these two is important to keep f_map.t passing.  */
12313         op_free(o);
12314         return newUNOP(type, 0, newDEFSVOP());
12315     }
12316
12317     if (oa) {
12318         while (oa & OA_OPTIONAL)
12319             oa >>= 4;
12320         if (oa && oa != OA_LIST)
12321             return too_few_arguments_pv(o,OP_DESC(o), 0);
12322     }
12323     return o;
12324 }
12325
12326 OP *
12327 Perl_ck_glob(pTHX_ OP *o)
12328 {
12329     GV *gv;
12330
12331     PERL_ARGS_ASSERT_CK_GLOB;
12332
12333     o = ck_fun(o);
12334     if ((o->op_flags & OPf_KIDS) && !OpHAS_SIBLING(cLISTOPo->op_first))
12335         op_append_elem(OP_GLOB, o, newDEFSVOP()); /* glob() => glob($_) */
12336
12337     if (!(o->op_flags & OPf_SPECIAL) && (gv = gv_override("glob", 4)))
12338     {
12339         /* convert
12340          *     glob
12341          *       \ null - const(wildcard)
12342          * into
12343          *     null
12344          *       \ enter
12345          *            \ list
12346          *                 \ mark - glob - rv2cv
12347          *                             |        \ gv(CORE::GLOBAL::glob)
12348          *                             |
12349          *                              \ null - const(wildcard)
12350          */
12351         o->op_flags |= OPf_SPECIAL;
12352         o->op_targ = pad_alloc(OP_GLOB, SVs_PADTMP);
12353         o = S_new_entersubop(aTHX_ gv, o);
12354         o = newUNOP(OP_NULL, 0, o);
12355         o->op_targ = OP_GLOB; /* hint at what it used to be: eg in newWHILEOP */
12356         return o;
12357     }
12358     else o->op_flags &= ~OPf_SPECIAL;
12359 #if !defined(PERL_EXTERNAL_GLOB)
12360     if (!PL_globhook) {
12361         ENTER;
12362         Perl_load_module(aTHX_ PERL_LOADMOD_NOIMPORT,
12363                                newSVpvs("File::Glob"), NULL, NULL, NULL);
12364         LEAVE;
12365     }
12366 #endif /* !PERL_EXTERNAL_GLOB */
12367     gv = (GV *)newSV(0);
12368     gv_init(gv, 0, "", 0, 0);
12369     gv_IOadd(gv);
12370     op_append_elem(OP_GLOB, o, newGVOP(OP_GV, 0, gv));
12371     SvREFCNT_dec_NN(gv); /* newGVOP increased it */
12372     scalarkids(o);
12373     return o;
12374 }
12375
12376 OP *
12377 Perl_ck_grep(pTHX_ OP *o)
12378 {
12379     LOGOP *gwop;
12380     OP *kid;
12381     const OPCODE type = o->op_type == OP_GREPSTART ? OP_GREPWHILE : OP_MAPWHILE;
12382
12383     PERL_ARGS_ASSERT_CK_GREP;
12384
12385     /* don't allocate gwop here, as we may leak it if PL_parser->error_count > 0 */
12386
12387     if (o->op_flags & OPf_STACKED) {
12388         kid = cUNOPx(OpSIBLING(cLISTOPo->op_first))->op_first;
12389         if (kid->op_type != OP_SCOPE && kid->op_type != OP_LEAVE)
12390             return no_fh_allowed(o);
12391         o->op_flags &= ~OPf_STACKED;
12392     }
12393     kid = OpSIBLING(cLISTOPo->op_first);
12394     if (type == OP_MAPWHILE)
12395         list(kid);
12396     else
12397         scalar(kid);
12398     o = ck_fun(o);
12399     if (PL_parser && PL_parser->error_count)
12400         return o;
12401     kid = OpSIBLING(cLISTOPo->op_first);
12402     if (kid->op_type != OP_NULL)
12403         Perl_croak(aTHX_ "panic: ck_grep, type=%u", (unsigned) kid->op_type);
12404     kid = kUNOP->op_first;
12405
12406     gwop = alloc_LOGOP(type, o, LINKLIST(kid));
12407     kid->op_next = (OP*)gwop;
12408     o->op_private = gwop->op_private = 0;
12409     gwop->op_targ = pad_alloc(type, SVs_PADTMP);
12410
12411     kid = OpSIBLING(cLISTOPo->op_first);
12412     for (kid = OpSIBLING(kid); kid; kid = OpSIBLING(kid))
12413         op_lvalue(kid, OP_GREPSTART);
12414
12415     return (OP*)gwop;
12416 }
12417
12418 OP *
12419 Perl_ck_index(pTHX_ OP *o)
12420 {
12421     PERL_ARGS_ASSERT_CK_INDEX;
12422
12423     if (o->op_flags & OPf_KIDS) {
12424         OP *kid = OpSIBLING(cLISTOPo->op_first);        /* get past pushmark */
12425         if (kid)
12426             kid = OpSIBLING(kid);                       /* get past "big" */
12427         if (kid && kid->op_type == OP_CONST) {
12428             const bool save_taint = TAINT_get;
12429             SV *sv = kSVOP->op_sv;
12430             if (   (!SvPOK(sv) || SvNIOKp(sv) || isREGEXP(sv))
12431                 && SvOK(sv) && !SvROK(sv))
12432             {
12433                 sv = newSV(0);
12434                 sv_copypv(sv, kSVOP->op_sv);
12435                 SvREFCNT_dec_NN(kSVOP->op_sv);
12436                 kSVOP->op_sv = sv;
12437             }
12438             if (SvOK(sv)) fbm_compile(sv, 0);
12439             TAINT_set(save_taint);
12440 #ifdef NO_TAINT_SUPPORT
12441             PERL_UNUSED_VAR(save_taint);
12442 #endif
12443         }
12444     }
12445     return ck_fun(o);
12446 }
12447
12448 OP *
12449 Perl_ck_lfun(pTHX_ OP *o)
12450 {
12451     const OPCODE type = o->op_type;
12452
12453     PERL_ARGS_ASSERT_CK_LFUN;
12454
12455     return modkids(ck_fun(o), type);
12456 }
12457
12458 OP *
12459 Perl_ck_defined(pTHX_ OP *o)            /* 19990527 MJD */
12460 {
12461     PERL_ARGS_ASSERT_CK_DEFINED;
12462
12463     if ((o->op_flags & OPf_KIDS)) {
12464         switch (cUNOPo->op_first->op_type) {
12465         case OP_RV2AV:
12466         case OP_PADAV:
12467             Perl_croak(aTHX_ "Can't use 'defined(@array)'"
12468                              " (Maybe you should just omit the defined()?)");
12469             NOT_REACHED; /* NOTREACHED */
12470             break;
12471         case OP_RV2HV:
12472         case OP_PADHV:
12473             Perl_croak(aTHX_ "Can't use 'defined(%%hash)'"
12474                              " (Maybe you should just omit the defined()?)");
12475             NOT_REACHED; /* NOTREACHED */
12476             break;
12477         default:
12478             /* no warning */
12479             break;
12480         }
12481     }
12482     return ck_rfun(o);
12483 }
12484
12485 OP *
12486 Perl_ck_readline(pTHX_ OP *o)
12487 {
12488     PERL_ARGS_ASSERT_CK_READLINE;
12489
12490     if (o->op_flags & OPf_KIDS) {
12491          OP *kid = cLISTOPo->op_first;
12492          if (kid->op_type == OP_RV2GV) kid->op_private |= OPpALLOW_FAKE;
12493          scalar(kid);
12494     }
12495     else {
12496         OP * const newop
12497             = newUNOP(OP_READLINE, 0, newGVOP(OP_GV, 0, PL_argvgv));
12498         op_free(o);
12499         return newop;
12500     }
12501     return o;
12502 }
12503
12504 OP *
12505 Perl_ck_rfun(pTHX_ OP *o)
12506 {
12507     const OPCODE type = o->op_type;
12508
12509     PERL_ARGS_ASSERT_CK_RFUN;
12510
12511     return refkids(ck_fun(o), type);
12512 }
12513
12514 OP *
12515 Perl_ck_listiob(pTHX_ OP *o)
12516 {
12517     OP *kid;
12518
12519     PERL_ARGS_ASSERT_CK_LISTIOB;
12520
12521     kid = cLISTOPo->op_first;
12522     if (!kid) {
12523         o = force_list(o, 1);
12524         kid = cLISTOPo->op_first;
12525     }
12526     if (kid->op_type == OP_PUSHMARK)
12527         kid = OpSIBLING(kid);
12528     if (kid && o->op_flags & OPf_STACKED)
12529         kid = OpSIBLING(kid);
12530     else if (kid && !OpHAS_SIBLING(kid)) {              /* print HANDLE; */
12531         if (kid->op_type == OP_CONST && kid->op_private & OPpCONST_BARE
12532          && !kid->op_folded) {
12533             o->op_flags |= OPf_STACKED; /* make it a filehandle */
12534             scalar(kid);
12535             /* replace old const op with new OP_RV2GV parent */
12536             kid = S_op_sibling_newUNOP(aTHX_ o, cLISTOPo->op_first,
12537                                         OP_RV2GV, OPf_REF);
12538             kid = OpSIBLING(kid);
12539         }
12540     }
12541
12542     if (!kid)
12543         op_append_elem(o->op_type, o, newDEFSVOP());
12544
12545     if (o->op_type == OP_PRTF) return modkids(listkids(o), OP_PRTF);
12546     return listkids(o);
12547 }
12548
12549 OP *
12550 Perl_ck_smartmatch(pTHX_ OP *o)
12551 {
12552     dVAR;
12553     PERL_ARGS_ASSERT_CK_SMARTMATCH;
12554     if (0 == (o->op_flags & OPf_SPECIAL)) {
12555         OP *first  = cBINOPo->op_first;
12556         OP *second = OpSIBLING(first);
12557         
12558         /* Implicitly take a reference to an array or hash */
12559
12560         /* remove the original two siblings, then add back the
12561          * (possibly different) first and second sibs.
12562          */
12563         op_sibling_splice(o, NULL, 1, NULL);
12564         op_sibling_splice(o, NULL, 1, NULL);
12565         first  = ref_array_or_hash(first);
12566         second = ref_array_or_hash(second);
12567         op_sibling_splice(o, NULL, 0, second);
12568         op_sibling_splice(o, NULL, 0, first);
12569         
12570         /* Implicitly take a reference to a regular expression */
12571         if (first->op_type == OP_MATCH && !(first->op_flags & OPf_STACKED)) {
12572             OpTYPE_set(first, OP_QR);
12573         }
12574         if (second->op_type == OP_MATCH && !(second->op_flags & OPf_STACKED)) {
12575             OpTYPE_set(second, OP_QR);
12576         }
12577     }
12578     
12579     return o;
12580 }
12581
12582
12583 static OP *
12584 S_maybe_targlex(pTHX_ OP *o)
12585 {
12586     OP * const kid = cLISTOPo->op_first;
12587     /* has a disposable target? */
12588     if ((PL_opargs[kid->op_type] & OA_TARGLEX)
12589         && !(kid->op_flags & OPf_STACKED)
12590         /* Cannot steal the second time! */
12591         && !(kid->op_private & OPpTARGET_MY)
12592         )
12593     {
12594         OP * const kkid = OpSIBLING(kid);
12595
12596         /* Can just relocate the target. */
12597         if (kkid && kkid->op_type == OP_PADSV
12598             && (!(kkid->op_private & OPpLVAL_INTRO)
12599                || kkid->op_private & OPpPAD_STATE))
12600         {
12601             kid->op_targ = kkid->op_targ;
12602             kkid->op_targ = 0;
12603             /* Now we do not need PADSV and SASSIGN.
12604              * Detach kid and free the rest. */
12605             op_sibling_splice(o, NULL, 1, NULL);
12606             op_free(o);
12607             kid->op_private |= OPpTARGET_MY;    /* Used for context settings */
12608             return kid;
12609         }
12610     }
12611     return o;
12612 }
12613
12614 OP *
12615 Perl_ck_sassign(pTHX_ OP *o)
12616 {
12617     dVAR;
12618     OP * const kid = cBINOPo->op_first;
12619
12620     PERL_ARGS_ASSERT_CK_SASSIGN;
12621
12622     if (OpHAS_SIBLING(kid)) {
12623         OP *kkid = OpSIBLING(kid);
12624         /* For state variable assignment with attributes, kkid is a list op
12625            whose op_last is a padsv. */
12626         if ((kkid->op_type == OP_PADSV ||
12627              (OP_TYPE_IS_OR_WAS(kkid, OP_LIST) &&
12628               (kkid = cLISTOPx(kkid)->op_last)->op_type == OP_PADSV
12629              )
12630             )
12631                 && (kkid->op_private & (OPpLVAL_INTRO|OPpPAD_STATE))
12632                     == (OPpLVAL_INTRO|OPpPAD_STATE)) {
12633             return S_newONCEOP(aTHX_ o, kkid);
12634         }
12635     }
12636     return S_maybe_targlex(aTHX_ o);
12637 }
12638
12639
12640 OP *
12641 Perl_ck_match(pTHX_ OP *o)
12642 {
12643     PERL_UNUSED_CONTEXT;
12644     PERL_ARGS_ASSERT_CK_MATCH;
12645
12646     return o;
12647 }
12648
12649 OP *
12650 Perl_ck_method(pTHX_ OP *o)
12651 {
12652     SV *sv, *methsv, *rclass;
12653     const char* method;
12654     char* compatptr;
12655     int utf8;
12656     STRLEN len, nsplit = 0, i;
12657     OP* new_op;
12658     OP * const kid = cUNOPo->op_first;
12659
12660     PERL_ARGS_ASSERT_CK_METHOD;
12661     if (kid->op_type != OP_CONST) return o;
12662
12663     sv = kSVOP->op_sv;
12664
12665     /* replace ' with :: */
12666     while ((compatptr = (char *) memchr(SvPVX(sv), '\'',
12667                                         SvEND(sv) - SvPVX(sv) )))
12668     {
12669         *compatptr = ':';
12670         sv_insert(sv, compatptr - SvPVX_const(sv), 0, ":", 1);
12671     }
12672
12673     method = SvPVX_const(sv);
12674     len = SvCUR(sv);
12675     utf8 = SvUTF8(sv) ? -1 : 1;
12676
12677     for (i = len - 1; i > 0; --i) if (method[i] == ':') {
12678         nsplit = i+1;
12679         break;
12680     }
12681
12682     methsv = newSVpvn_share(method+nsplit, utf8*(len - nsplit), 0);
12683
12684     if (!nsplit) { /* $proto->method() */
12685         op_free(o);
12686         return newMETHOP_named(OP_METHOD_NAMED, 0, methsv);
12687     }
12688
12689     if (memEQs(method, nsplit, "SUPER::")) { /* $proto->SUPER::method() */
12690         op_free(o);
12691         return newMETHOP_named(OP_METHOD_SUPER, 0, methsv);
12692     }
12693
12694     /* $proto->MyClass::method() and $proto->MyClass::SUPER::method() */
12695     if (nsplit >= 9 && strBEGINs(method+nsplit-9, "::SUPER::")) {
12696         rclass = newSVpvn_share(method, utf8*(nsplit-9), 0);
12697         new_op = newMETHOP_named(OP_METHOD_REDIR_SUPER, 0, methsv);
12698     } else {
12699         rclass = newSVpvn_share(method, utf8*(nsplit-2), 0);
12700         new_op = newMETHOP_named(OP_METHOD_REDIR, 0, methsv);
12701     }
12702 #ifdef USE_ITHREADS
12703     op_relocate_sv(&rclass, &cMETHOPx(new_op)->op_rclass_targ);
12704 #else
12705     cMETHOPx(new_op)->op_rclass_sv = rclass;
12706 #endif
12707     op_free(o);
12708     return new_op;
12709 }
12710
12711 OP *
12712 Perl_ck_null(pTHX_ OP *o)
12713 {
12714     PERL_ARGS_ASSERT_CK_NULL;
12715     PERL_UNUSED_CONTEXT;
12716     return o;
12717 }
12718
12719 OP *
12720 Perl_ck_open(pTHX_ OP *o)
12721 {
12722     PERL_ARGS_ASSERT_CK_OPEN;
12723
12724     S_io_hints(aTHX_ o);
12725     {
12726          /* In case of three-arg dup open remove strictness
12727           * from the last arg if it is a bareword. */
12728          OP * const first = cLISTOPx(o)->op_first; /* The pushmark. */
12729          OP * const last  = cLISTOPx(o)->op_last;  /* The bareword. */
12730          OP *oa;
12731          const char *mode;
12732
12733          if ((last->op_type == OP_CONST) &&             /* The bareword. */
12734              (last->op_private & OPpCONST_BARE) &&
12735              (last->op_private & OPpCONST_STRICT) &&
12736              (oa = OpSIBLING(first)) &&         /* The fh. */
12737              (oa = OpSIBLING(oa)) &&                    /* The mode. */
12738              (oa->op_type == OP_CONST) &&
12739              SvPOK(((SVOP*)oa)->op_sv) &&
12740              (mode = SvPVX_const(((SVOP*)oa)->op_sv)) &&
12741              mode[0] == '>' && mode[1] == '&' &&        /* A dup open. */
12742              (last == OpSIBLING(oa)))                   /* The bareword. */
12743               last->op_private &= ~OPpCONST_STRICT;
12744     }
12745     return ck_fun(o);
12746 }
12747
12748 OP *
12749 Perl_ck_prototype(pTHX_ OP *o)
12750 {
12751     PERL_ARGS_ASSERT_CK_PROTOTYPE;
12752     if (!(o->op_flags & OPf_KIDS)) {
12753         op_free(o);
12754         return newUNOP(OP_PROTOTYPE, 0, newDEFSVOP());
12755     }
12756     return o;
12757 }
12758
12759 OP *
12760 Perl_ck_refassign(pTHX_ OP *o)
12761 {
12762     OP * const right = cLISTOPo->op_first;
12763     OP * const left = OpSIBLING(right);
12764     OP *varop = cUNOPx(cUNOPx(left)->op_first)->op_first;
12765     bool stacked = 0;
12766
12767     PERL_ARGS_ASSERT_CK_REFASSIGN;
12768     assert (left);
12769     assert (left->op_type == OP_SREFGEN);
12770
12771     o->op_private = 0;
12772     /* we use OPpPAD_STATE in refassign to mean either of those things,
12773      * and the code assumes the two flags occupy the same bit position
12774      * in the various ops below */
12775     assert(OPpPAD_STATE == OPpOUR_INTRO);
12776
12777     switch (varop->op_type) {
12778     case OP_PADAV:
12779         o->op_private |= OPpLVREF_AV;
12780         goto settarg;
12781     case OP_PADHV:
12782         o->op_private |= OPpLVREF_HV;
12783         /* FALLTHROUGH */
12784     case OP_PADSV:
12785       settarg:
12786         o->op_private |= (varop->op_private & (OPpLVAL_INTRO|OPpPAD_STATE));
12787         o->op_targ = varop->op_targ;
12788         varop->op_targ = 0;
12789         PAD_COMPNAME_GEN_set(o->op_targ, PERL_INT_MAX);
12790         break;
12791
12792     case OP_RV2AV:
12793         o->op_private |= OPpLVREF_AV;
12794         goto checkgv;
12795         NOT_REACHED; /* NOTREACHED */
12796     case OP_RV2HV:
12797         o->op_private |= OPpLVREF_HV;
12798         /* FALLTHROUGH */
12799     case OP_RV2SV:
12800       checkgv:
12801         o->op_private |= (varop->op_private & (OPpLVAL_INTRO|OPpOUR_INTRO));
12802         if (cUNOPx(varop)->op_first->op_type != OP_GV) goto bad;
12803       detach_and_stack:
12804         /* Point varop to its GV kid, detached.  */
12805         varop = op_sibling_splice(varop, NULL, -1, NULL);
12806         stacked = TRUE;
12807         break;
12808     case OP_RV2CV: {
12809         OP * const kidparent =
12810             OpSIBLING(cUNOPx(cUNOPx(varop)->op_first)->op_first);
12811         OP * const kid = cUNOPx(kidparent)->op_first;
12812         o->op_private |= OPpLVREF_CV;
12813         if (kid->op_type == OP_GV) {
12814             SV *sv = (SV*)cGVOPx_gv(kid);
12815             varop = kidparent;
12816             if (SvROK(sv) && SvTYPE(SvRV(sv)) == SVt_PVCV) {
12817                 /* a CVREF here confuses pp_refassign, so make sure
12818                    it gets a GV */
12819                 CV *const cv = (CV*)SvRV(sv);
12820                 SV *name_sv = sv_2mortal(newSVhek(CvNAME_HEK(cv)));
12821                 (void)gv_init_sv((GV*)sv, CvSTASH(cv), name_sv, 0);
12822                 assert(SvTYPE(sv) == SVt_PVGV);
12823             }
12824             goto detach_and_stack;
12825         }
12826         if (kid->op_type != OP_PADCV)   goto bad;
12827         o->op_targ = kid->op_targ;
12828         kid->op_targ = 0;
12829         break;
12830     }
12831     case OP_AELEM:
12832     case OP_HELEM:
12833         o->op_private |= (varop->op_private & OPpLVAL_INTRO);
12834         o->op_private |= OPpLVREF_ELEM;
12835         op_null(varop);
12836         stacked = TRUE;
12837         /* Detach varop.  */
12838         op_sibling_splice(cUNOPx(left)->op_first, NULL, -1, NULL);
12839         break;
12840     default:
12841       bad:
12842         /* diag_listed_as: Can't modify reference to %s in %s assignment */
12843         yyerror(Perl_form(aTHX_ "Can't modify reference to %s in scalar "
12844                                 "assignment",
12845                                  OP_DESC(varop)));
12846         return o;
12847     }
12848     if (!FEATURE_REFALIASING_IS_ENABLED)
12849         Perl_croak(aTHX_
12850                   "Experimental aliasing via reference not enabled");
12851     Perl_ck_warner_d(aTHX_
12852                      packWARN(WARN_EXPERIMENTAL__REFALIASING),
12853                     "Aliasing via reference is experimental");
12854     if (stacked) {
12855         o->op_flags |= OPf_STACKED;
12856         op_sibling_splice(o, right, 1, varop);
12857     }
12858     else {
12859         o->op_flags &=~ OPf_STACKED;
12860         op_sibling_splice(o, right, 1, NULL);
12861     }
12862     op_free(left);
12863     return o;
12864 }
12865
12866 OP *
12867 Perl_ck_repeat(pTHX_ OP *o)
12868 {
12869     PERL_ARGS_ASSERT_CK_REPEAT;
12870
12871     if (cBINOPo->op_first->op_flags & OPf_PARENS) {
12872         OP* kids;
12873         o->op_private |= OPpREPEAT_DOLIST;
12874         kids = op_sibling_splice(o, NULL, 1, NULL); /* detach first kid */
12875         kids = force_list(kids, 1); /* promote it to a list */
12876         op_sibling_splice(o, NULL, 0, kids); /* and add back */
12877     }
12878     else
12879         scalar(o);
12880     return o;
12881 }
12882
12883 OP *
12884 Perl_ck_require(pTHX_ OP *o)
12885 {
12886     GV* gv;
12887
12888     PERL_ARGS_ASSERT_CK_REQUIRE;
12889
12890     if (o->op_flags & OPf_KIDS) {       /* Shall we supply missing .pm? */
12891         SVOP * const kid = (SVOP*)cUNOPo->op_first;
12892         U32 hash;
12893         char *s;
12894         STRLEN len;
12895         if (kid->op_type == OP_CONST) {
12896           SV * const sv = kid->op_sv;
12897           U32 const was_readonly = SvREADONLY(sv);
12898           if (kid->op_private & OPpCONST_BARE) {
12899             dVAR;
12900             const char *end;
12901             HEK *hek;
12902
12903             if (was_readonly) {
12904                     SvREADONLY_off(sv);
12905             }   
12906             if (SvIsCOW(sv)) sv_force_normal_flags(sv, 0);
12907
12908             s = SvPVX(sv);
12909             len = SvCUR(sv);
12910             end = s + len;
12911             /* treat ::foo::bar as foo::bar */
12912             if (len >= 2 && s[0] == ':' && s[1] == ':')
12913                 DIE(aTHX_ "Bareword in require must not start with a double-colon: \"%s\"\n", s);
12914             if (s == end)
12915                 DIE(aTHX_ "Bareword in require maps to empty filename");
12916
12917             for (; s < end; s++) {
12918                 if (*s == ':' && s[1] == ':') {
12919                     *s = '/';
12920                     Move(s+2, s+1, end - s - 1, char);
12921                     --end;
12922                 }
12923             }
12924             SvEND_set(sv, end);
12925             sv_catpvs(sv, ".pm");
12926             PERL_HASH(hash, SvPVX(sv), SvCUR(sv));
12927             hek = share_hek(SvPVX(sv),
12928                             (SSize_t)SvCUR(sv) * (SvUTF8(sv) ? -1 : 1),
12929                             hash);
12930             sv_sethek(sv, hek);
12931             unshare_hek(hek);
12932             SvFLAGS(sv) |= was_readonly;
12933           }
12934           else if (SvPOK(sv) && !SvNIOK(sv) && !SvGMAGICAL(sv)
12935                 && !SvVOK(sv)) {
12936             s = SvPV(sv, len);
12937             if (SvREFCNT(sv) > 1) {
12938                 kid->op_sv = newSVpvn_share(
12939                     s, SvUTF8(sv) ? -(SSize_t)len : (SSize_t)len, 0);
12940                 SvREFCNT_dec_NN(sv);
12941             }
12942             else {
12943                 dVAR;
12944                 HEK *hek;
12945                 if (was_readonly) SvREADONLY_off(sv);
12946                 PERL_HASH(hash, s, len);
12947                 hek = share_hek(s,
12948                                 SvUTF8(sv) ? -(SSize_t)len : (SSize_t)len,
12949                                 hash);
12950                 sv_sethek(sv, hek);
12951                 unshare_hek(hek);
12952                 SvFLAGS(sv) |= was_readonly;
12953             }
12954           }
12955         }
12956     }
12957
12958     if (!(o->op_flags & OPf_SPECIAL) /* Wasn't written as CORE::require */
12959         /* handle override, if any */
12960      && (gv = gv_override("require", 7))) {
12961         OP *kid, *newop;
12962         if (o->op_flags & OPf_KIDS) {
12963             kid = cUNOPo->op_first;
12964             op_sibling_splice(o, NULL, -1, NULL);
12965         }
12966         else {
12967             kid = newDEFSVOP();
12968         }
12969         op_free(o);
12970         newop = S_new_entersubop(aTHX_ gv, kid);
12971         return newop;
12972     }
12973
12974     return ck_fun(o);
12975 }
12976
12977 OP *
12978 Perl_ck_return(pTHX_ OP *o)
12979 {
12980     OP *kid;
12981
12982     PERL_ARGS_ASSERT_CK_RETURN;
12983
12984     kid = OpSIBLING(cLISTOPo->op_first);
12985     if (PL_compcv && CvLVALUE(PL_compcv)) {
12986         for (; kid; kid = OpSIBLING(kid))
12987             op_lvalue(kid, OP_LEAVESUBLV);
12988     }
12989
12990     return o;
12991 }
12992
12993 OP *
12994 Perl_ck_select(pTHX_ OP *o)
12995 {
12996     dVAR;
12997     OP* kid;
12998
12999     PERL_ARGS_ASSERT_CK_SELECT;
13000
13001     if (o->op_flags & OPf_KIDS) {
13002         kid = OpSIBLING(cLISTOPo->op_first);     /* get past pushmark */
13003         if (kid && OpHAS_SIBLING(kid)) {
13004             OpTYPE_set(o, OP_SSELECT);
13005             o = ck_fun(o);
13006             return fold_constants(op_integerize(op_std_init(o)));
13007         }
13008     }
13009     o = ck_fun(o);
13010     kid = OpSIBLING(cLISTOPo->op_first);    /* get past pushmark */
13011     if (kid && kid->op_type == OP_RV2GV)
13012         kid->op_private &= ~HINT_STRICT_REFS;
13013     return o;
13014 }
13015
13016 OP *
13017 Perl_ck_shift(pTHX_ OP *o)
13018 {
13019     const I32 type = o->op_type;
13020
13021     PERL_ARGS_ASSERT_CK_SHIFT;
13022
13023     if (!(o->op_flags & OPf_KIDS)) {
13024         OP *argop;
13025
13026         if (!CvUNIQUE(PL_compcv)) {
13027             o->op_flags |= OPf_SPECIAL;
13028             return o;
13029         }
13030
13031         argop = newUNOP(OP_RV2AV, 0, scalar(newGVOP(OP_GV, 0, PL_argvgv)));
13032         op_free(o);
13033         return newUNOP(type, 0, scalar(argop));
13034     }
13035     return scalar(ck_fun(o));
13036 }
13037
13038 OP *
13039 Perl_ck_sort(pTHX_ OP *o)
13040 {
13041     OP *firstkid;
13042     OP *kid;
13043     HV * const hinthv =
13044         PL_hints & HINT_LOCALIZE_HH ? GvHV(PL_hintgv) : NULL;
13045     U8 stacked;
13046
13047     PERL_ARGS_ASSERT_CK_SORT;
13048
13049     if (hinthv) {
13050             SV ** const svp = hv_fetchs(hinthv, "sort", FALSE);
13051             if (svp) {
13052                 const I32 sorthints = (I32)SvIV(*svp);
13053                 if ((sorthints & HINT_SORT_STABLE) != 0)
13054                     o->op_private |= OPpSORT_STABLE;
13055                 if ((sorthints & HINT_SORT_UNSTABLE) != 0)
13056                     o->op_private |= OPpSORT_UNSTABLE;
13057             }
13058     }
13059
13060     if (o->op_flags & OPf_STACKED)
13061         simplify_sort(o);
13062     firstkid = OpSIBLING(cLISTOPo->op_first);           /* get past pushmark */
13063
13064     if ((stacked = o->op_flags & OPf_STACKED)) {        /* may have been cleared */
13065         OP *kid = cUNOPx(firstkid)->op_first;           /* get past null */
13066
13067         /* if the first arg is a code block, process it and mark sort as
13068          * OPf_SPECIAL */
13069         if (kid->op_type == OP_SCOPE || kid->op_type == OP_LEAVE) {
13070             LINKLIST(kid);
13071             if (kid->op_type == OP_LEAVE)
13072                     op_null(kid);                       /* wipe out leave */
13073             /* Prevent execution from escaping out of the sort block. */
13074             kid->op_next = 0;
13075
13076             /* provide scalar context for comparison function/block */
13077             kid = scalar(firstkid);
13078             kid->op_next = kid;
13079             o->op_flags |= OPf_SPECIAL;
13080         }
13081         else if (kid->op_type == OP_CONST
13082               && kid->op_private & OPpCONST_BARE) {
13083             char tmpbuf[256];
13084             STRLEN len;
13085             PADOFFSET off;
13086             const char * const name = SvPV(kSVOP_sv, len);
13087             *tmpbuf = '&';
13088             assert (len < 256);
13089             Copy(name, tmpbuf+1, len, char);
13090             off = pad_findmy_pvn(tmpbuf, len+1, 0);
13091             if (off != NOT_IN_PAD) {
13092                 if (PAD_COMPNAME_FLAGS_isOUR(off)) {
13093                     SV * const fq =
13094                         newSVhek(HvNAME_HEK(PAD_COMPNAME_OURSTASH(off)));
13095                     sv_catpvs(fq, "::");
13096                     sv_catsv(fq, kSVOP_sv);
13097                     SvREFCNT_dec_NN(kSVOP_sv);
13098                     kSVOP->op_sv = fq;
13099                 }
13100                 else {
13101                     OP * const padop = newOP(OP_PADCV, 0);
13102                     padop->op_targ = off;
13103                     /* replace the const op with the pad op */
13104                     op_sibling_splice(firstkid, NULL, 1, padop);
13105                     op_free(kid);
13106                 }
13107             }
13108         }
13109
13110         firstkid = OpSIBLING(firstkid);
13111     }
13112
13113     for (kid = firstkid; kid; kid = OpSIBLING(kid)) {
13114         /* provide list context for arguments */
13115         list(kid);
13116         if (stacked)
13117             op_lvalue(kid, OP_GREPSTART);
13118     }
13119
13120     return o;
13121 }
13122
13123 /* for sort { X } ..., where X is one of
13124  *   $a <=> $b, $b <=> $a, $a cmp $b, $b cmp $a
13125  * elide the second child of the sort (the one containing X),
13126  * and set these flags as appropriate
13127         OPpSORT_NUMERIC;
13128         OPpSORT_INTEGER;
13129         OPpSORT_DESCEND;
13130  * Also, check and warn on lexical $a, $b.
13131  */
13132
13133 STATIC void
13134 S_simplify_sort(pTHX_ OP *o)
13135 {
13136     OP *kid = OpSIBLING(cLISTOPo->op_first);    /* get past pushmark */
13137     OP *k;
13138     int descending;
13139     GV *gv;
13140     const char *gvname;
13141     bool have_scopeop;
13142
13143     PERL_ARGS_ASSERT_SIMPLIFY_SORT;
13144
13145     kid = kUNOP->op_first;                              /* get past null */
13146     if (!(have_scopeop = kid->op_type == OP_SCOPE)
13147      && kid->op_type != OP_LEAVE)
13148         return;
13149     kid = kLISTOP->op_last;                             /* get past scope */
13150     switch(kid->op_type) {
13151         case OP_NCMP:
13152         case OP_I_NCMP:
13153         case OP_SCMP:
13154             if (!have_scopeop) goto padkids;
13155             break;
13156         default:
13157             return;
13158     }
13159     k = kid;                                            /* remember this node*/
13160     if (kBINOP->op_first->op_type != OP_RV2SV
13161      || kBINOP->op_last ->op_type != OP_RV2SV)
13162     {
13163         /*
13164            Warn about my($a) or my($b) in a sort block, *if* $a or $b is
13165            then used in a comparison.  This catches most, but not
13166            all cases.  For instance, it catches
13167                sort { my($a); $a <=> $b }
13168            but not
13169                sort { my($a); $a < $b ? -1 : $a == $b ? 0 : 1; }
13170            (although why you'd do that is anyone's guess).
13171         */
13172
13173        padkids:
13174         if (!ckWARN(WARN_SYNTAX)) return;
13175         kid = kBINOP->op_first;
13176         do {
13177             if (kid->op_type == OP_PADSV) {
13178                 PADNAME * const name = PAD_COMPNAME(kid->op_targ);
13179                 if (PadnameLEN(name) == 2 && *PadnamePV(name) == '$'
13180                  && (  PadnamePV(name)[1] == 'a'
13181                     || PadnamePV(name)[1] == 'b'  ))
13182                     /* diag_listed_as: "my %s" used in sort comparison */
13183                     Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
13184                                      "\"%s %s\" used in sort comparison",
13185                                       PadnameIsSTATE(name)
13186                                         ? "state"
13187                                         : "my",
13188                                       PadnamePV(name));
13189             }
13190         } while ((kid = OpSIBLING(kid)));
13191         return;
13192     }
13193     kid = kBINOP->op_first;                             /* get past cmp */
13194     if (kUNOP->op_first->op_type != OP_GV)
13195         return;
13196     kid = kUNOP->op_first;                              /* get past rv2sv */
13197     gv = kGVOP_gv;
13198     if (GvSTASH(gv) != PL_curstash)
13199         return;
13200     gvname = GvNAME(gv);
13201     if (*gvname == 'a' && gvname[1] == '\0')
13202         descending = 0;
13203     else if (*gvname == 'b' && gvname[1] == '\0')
13204         descending = 1;
13205     else
13206         return;
13207
13208     kid = k;                                            /* back to cmp */
13209     /* already checked above that it is rv2sv */
13210     kid = kBINOP->op_last;                              /* down to 2nd arg */
13211     if (kUNOP->op_first->op_type != OP_GV)
13212         return;
13213     kid = kUNOP->op_first;                              /* get past rv2sv */
13214     gv = kGVOP_gv;
13215     if (GvSTASH(gv) != PL_curstash)
13216         return;
13217     gvname = GvNAME(gv);
13218     if ( descending
13219          ? !(*gvname == 'a' && gvname[1] == '\0')
13220          : !(*gvname == 'b' && gvname[1] == '\0'))
13221         return;
13222     o->op_flags &= ~(OPf_STACKED | OPf_SPECIAL);
13223     if (descending)
13224         o->op_private |= OPpSORT_DESCEND;
13225     if (k->op_type == OP_NCMP)
13226         o->op_private |= OPpSORT_NUMERIC;
13227     if (k->op_type == OP_I_NCMP)
13228         o->op_private |= OPpSORT_NUMERIC | OPpSORT_INTEGER;
13229     kid = OpSIBLING(cLISTOPo->op_first);
13230     /* cut out and delete old block (second sibling) */
13231     op_sibling_splice(o, cLISTOPo->op_first, 1, NULL);
13232     op_free(kid);
13233 }
13234
13235 OP *
13236 Perl_ck_split(pTHX_ OP *o)
13237 {
13238     dVAR;
13239     OP *kid;
13240     OP *sibs;
13241
13242     PERL_ARGS_ASSERT_CK_SPLIT;
13243
13244     assert(o->op_type == OP_LIST);
13245
13246     if (o->op_flags & OPf_STACKED)
13247         return no_fh_allowed(o);
13248
13249     kid = cLISTOPo->op_first;
13250     /* delete leading NULL node, then add a CONST if no other nodes */
13251     assert(kid->op_type == OP_NULL);
13252     op_sibling_splice(o, NULL, 1,
13253         OpHAS_SIBLING(kid) ? NULL : newSVOP(OP_CONST, 0, newSVpvs(" ")));
13254     op_free(kid);
13255     kid = cLISTOPo->op_first;
13256
13257     if (kid->op_type != OP_MATCH || kid->op_flags & OPf_STACKED) {
13258         /* remove match expression, and replace with new optree with
13259          * a match op at its head */
13260         op_sibling_splice(o, NULL, 1, NULL);
13261         /* pmruntime will handle split " " behavior with flag==2 */
13262         kid = pmruntime(newPMOP(OP_MATCH, 0), kid, NULL, 2, 0);
13263         op_sibling_splice(o, NULL, 0, kid);
13264     }
13265
13266     assert(kid->op_type == OP_MATCH || kid->op_type == OP_SPLIT);
13267
13268     if (((PMOP *)kid)->op_pmflags & PMf_GLOBAL) {
13269       Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP),
13270                      "Use of /g modifier is meaningless in split");
13271     }
13272
13273     /* eliminate the split op, and move the match op (plus any children)
13274      * into its place, then convert the match op into a split op. i.e.
13275      *
13276      *  SPLIT                    MATCH                 SPLIT(ex-MATCH)
13277      *    |                        |                     |
13278      *  MATCH - A - B - C   =>     R - A - B - C   =>    R - A - B - C
13279      *    |                        |                     |
13280      *    R                        X - Y                 X - Y
13281      *    |
13282      *    X - Y
13283      *
13284      * (R, if it exists, will be a regcomp op)
13285      */
13286
13287     op_sibling_splice(o, NULL, 1, NULL); /* detach match op from o */
13288     sibs = op_sibling_splice(o, NULL, -1, NULL); /* detach any other sibs */
13289     op_sibling_splice(kid, cLISTOPx(kid)->op_last, 0, sibs); /* and reattach */
13290     OpTYPE_set(kid, OP_SPLIT);
13291     kid->op_flags   = (o->op_flags | (kid->op_flags & OPf_KIDS));
13292     kid->op_private = o->op_private;
13293     op_free(o);
13294     o = kid;
13295     kid = sibs; /* kid is now the string arg of the split */
13296
13297     if (!kid) {
13298         kid = newDEFSVOP();
13299         op_append_elem(OP_SPLIT, o, kid);
13300     }
13301     scalar(kid);
13302
13303     kid = OpSIBLING(kid);
13304     if (!kid) {
13305         kid = newSVOP(OP_CONST, 0, newSViv(0));
13306         op_append_elem(OP_SPLIT, o, kid);
13307         o->op_private |= OPpSPLIT_IMPLIM;
13308     }
13309     scalar(kid);
13310
13311     if (OpHAS_SIBLING(kid))
13312         return too_many_arguments_pv(o,OP_DESC(o), 0);
13313
13314     return o;
13315 }
13316
13317 OP *
13318 Perl_ck_stringify(pTHX_ OP *o)
13319 {
13320     OP * const kid = OpSIBLING(cUNOPo->op_first);
13321     PERL_ARGS_ASSERT_CK_STRINGIFY;
13322     if ((   kid->op_type == OP_JOIN || kid->op_type == OP_QUOTEMETA
13323          || kid->op_type == OP_LC   || kid->op_type == OP_LCFIRST
13324          || kid->op_type == OP_UC   || kid->op_type == OP_UCFIRST)
13325         && !OpHAS_SIBLING(kid)) /* syntax errs can leave extra children */
13326     {
13327         op_sibling_splice(o, cUNOPo->op_first, -1, NULL);
13328         op_free(o);
13329         return kid;
13330     }
13331     return ck_fun(o);
13332 }
13333         
13334 OP *
13335 Perl_ck_join(pTHX_ OP *o)
13336 {
13337     OP * const kid = OpSIBLING(cLISTOPo->op_first);
13338
13339     PERL_ARGS_ASSERT_CK_JOIN;
13340
13341     if (kid && kid->op_type == OP_MATCH) {
13342         if (ckWARN(WARN_SYNTAX)) {
13343             const REGEXP *re = PM_GETRE(kPMOP);
13344             const SV *msg = re
13345                     ? newSVpvn_flags( RX_PRECOMP_const(re), RX_PRELEN(re),
13346                                             SVs_TEMP | ( RX_UTF8(re) ? SVf_UTF8 : 0 ) )
13347                     : newSVpvs_flags( "STRING", SVs_TEMP );
13348             Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
13349                         "/%" SVf "/ should probably be written as \"%" SVf "\"",
13350                         SVfARG(msg), SVfARG(msg));
13351         }
13352     }
13353     if (kid
13354      && (kid->op_type == OP_CONST /* an innocent, unsuspicious separator */
13355         || (kid->op_type == OP_PADSV && !(kid->op_private & OPpLVAL_INTRO))
13356         || (  kid->op_type==OP_RV2SV && kUNOP->op_first->op_type == OP_GV
13357            && !(kid->op_private & (OPpLVAL_INTRO|OPpOUR_INTRO)))))
13358     {
13359         const OP * const bairn = OpSIBLING(kid); /* the list */
13360         if (bairn && !OpHAS_SIBLING(bairn) /* single-item list */
13361          && OP_GIMME(bairn,0) == G_SCALAR)
13362         {
13363             OP * const ret = op_convert_list(OP_STRINGIFY, OPf_FOLDED,
13364                                      op_sibling_splice(o, kid, 1, NULL));
13365             op_free(o);
13366             return ret;
13367         }
13368     }
13369
13370     return ck_fun(o);
13371 }
13372
13373 /*
13374 =for apidoc rv2cv_op_cv
13375
13376 Examines an op, which is expected to identify a subroutine at runtime,
13377 and attempts to determine at compile time which subroutine it identifies.
13378 This is normally used during Perl compilation to determine whether
13379 a prototype can be applied to a function call.  C<cvop> is the op
13380 being considered, normally an C<rv2cv> op.  A pointer to the identified
13381 subroutine is returned, if it could be determined statically, and a null
13382 pointer is returned if it was not possible to determine statically.
13383
13384 Currently, the subroutine can be identified statically if the RV that the
13385 C<rv2cv> is to operate on is provided by a suitable C<gv> or C<const> op.
13386 A C<gv> op is suitable if the GV's CV slot is populated.  A C<const> op is
13387 suitable if the constant value must be an RV pointing to a CV.  Details of
13388 this process may change in future versions of Perl.  If the C<rv2cv> op
13389 has the C<OPpENTERSUB_AMPER> flag set then no attempt is made to identify
13390 the subroutine statically: this flag is used to suppress compile-time
13391 magic on a subroutine call, forcing it to use default runtime behaviour.
13392
13393 If C<flags> has the bit C<RV2CVOPCV_MARK_EARLY> set, then the handling
13394 of a GV reference is modified.  If a GV was examined and its CV slot was
13395 found to be empty, then the C<gv> op has the C<OPpEARLY_CV> flag set.
13396 If the op is not optimised away, and the CV slot is later populated with
13397 a subroutine having a prototype, that flag eventually triggers the warning
13398 "called too early to check prototype".
13399
13400 If C<flags> has the bit C<RV2CVOPCV_RETURN_NAME_GV> set, then instead
13401 of returning a pointer to the subroutine it returns a pointer to the
13402 GV giving the most appropriate name for the subroutine in this context.
13403 Normally this is just the C<CvGV> of the subroutine, but for an anonymous
13404 (C<CvANON>) subroutine that is referenced through a GV it will be the
13405 referencing GV.  The resulting C<GV*> is cast to C<CV*> to be returned.
13406 A null pointer is returned as usual if there is no statically-determinable
13407 subroutine.
13408
13409 =cut
13410 */
13411
13412 /* shared by toke.c:yylex */
13413 CV *
13414 Perl_find_lexical_cv(pTHX_ PADOFFSET off)
13415 {
13416     PADNAME *name = PAD_COMPNAME(off);
13417     CV *compcv = PL_compcv;
13418     while (PadnameOUTER(name)) {
13419         assert(PARENT_PAD_INDEX(name));
13420         compcv = CvOUTSIDE(compcv);
13421         name = PadlistNAMESARRAY(CvPADLIST(compcv))
13422                 [off = PARENT_PAD_INDEX(name)];
13423     }
13424     assert(!PadnameIsOUR(name));
13425     if (!PadnameIsSTATE(name) && PadnamePROTOCV(name)) {
13426         return PadnamePROTOCV(name);
13427     }
13428     return (CV *)AvARRAY(PadlistARRAY(CvPADLIST(compcv))[1])[off];
13429 }
13430
13431 CV *
13432 Perl_rv2cv_op_cv(pTHX_ OP *cvop, U32 flags)
13433 {
13434     OP *rvop;
13435     CV *cv;
13436     GV *gv;
13437     PERL_ARGS_ASSERT_RV2CV_OP_CV;
13438     if (flags & ~RV2CVOPCV_FLAG_MASK)
13439         Perl_croak(aTHX_ "panic: rv2cv_op_cv bad flags %x", (unsigned)flags);
13440     if (cvop->op_type != OP_RV2CV)
13441         return NULL;
13442     if (cvop->op_private & OPpENTERSUB_AMPER)
13443         return NULL;
13444     if (!(cvop->op_flags & OPf_KIDS))
13445         return NULL;
13446     rvop = cUNOPx(cvop)->op_first;
13447     switch (rvop->op_type) {
13448         case OP_GV: {
13449             gv = cGVOPx_gv(rvop);
13450             if (!isGV(gv)) {
13451                 if (SvROK(gv) && SvTYPE(SvRV(gv)) == SVt_PVCV) {
13452                     cv = MUTABLE_CV(SvRV(gv));
13453                     gv = NULL;
13454                     break;
13455                 }
13456                 if (flags & RV2CVOPCV_RETURN_STUB)
13457                     return (CV *)gv;
13458                 else return NULL;
13459             }
13460             cv = GvCVu(gv);
13461             if (!cv) {
13462                 if (flags & RV2CVOPCV_MARK_EARLY)
13463                     rvop->op_private |= OPpEARLY_CV;
13464                 return NULL;
13465             }
13466         } break;
13467         case OP_CONST: {
13468             SV *rv = cSVOPx_sv(rvop);
13469             if (!SvROK(rv))
13470                 return NULL;
13471             cv = (CV*)SvRV(rv);
13472             gv = NULL;
13473         } break;
13474         case OP_PADCV: {
13475             cv = find_lexical_cv(rvop->op_targ);
13476             gv = NULL;
13477         } break;
13478         default: {
13479             return NULL;
13480         } NOT_REACHED; /* NOTREACHED */
13481     }
13482     if (SvTYPE((SV*)cv) != SVt_PVCV)
13483         return NULL;
13484     if (flags & RV2CVOPCV_RETURN_NAME_GV) {
13485         if ((!CvANON(cv) && !CvLEXICAL(cv)) || !gv)
13486             gv = CvGV(cv);
13487         return (CV*)gv;
13488     }
13489     else if (flags & RV2CVOPCV_MAYBE_NAME_GV) {
13490         if (CvLEXICAL(cv) || CvNAMED(cv))
13491             return NULL;
13492         if (!CvANON(cv) || !gv)
13493             gv = CvGV(cv);
13494         return (CV*)gv;
13495
13496     } else {
13497         return cv;
13498     }
13499 }
13500
13501 /*
13502 =for apidoc ck_entersub_args_list
13503
13504 Performs the default fixup of the arguments part of an C<entersub>
13505 op tree.  This consists of applying list context to each of the
13506 argument ops.  This is the standard treatment used on a call marked
13507 with C<&>, or a method call, or a call through a subroutine reference,
13508 or any other call where the callee can't be identified at compile time,
13509 or a call where the callee has no prototype.
13510
13511 =cut
13512 */
13513
13514 OP *
13515 Perl_ck_entersub_args_list(pTHX_ OP *entersubop)
13516 {
13517     OP *aop;
13518
13519     PERL_ARGS_ASSERT_CK_ENTERSUB_ARGS_LIST;
13520
13521     aop = cUNOPx(entersubop)->op_first;
13522     if (!OpHAS_SIBLING(aop))
13523         aop = cUNOPx(aop)->op_first;
13524     for (aop = OpSIBLING(aop); OpHAS_SIBLING(aop); aop = OpSIBLING(aop)) {
13525         /* skip the extra attributes->import() call implicitly added in
13526          * something like foo(my $x : bar)
13527          */
13528         if (   aop->op_type == OP_ENTERSUB
13529             && (aop->op_flags & OPf_WANT) == OPf_WANT_VOID
13530         )
13531             continue;
13532         list(aop);
13533         op_lvalue(aop, OP_ENTERSUB);
13534     }
13535     return entersubop;
13536 }
13537
13538 /*
13539 =for apidoc ck_entersub_args_proto
13540
13541 Performs the fixup of the arguments part of an C<entersub> op tree
13542 based on a subroutine prototype.  This makes various modifications to
13543 the argument ops, from applying context up to inserting C<refgen> ops,
13544 and checking the number and syntactic types of arguments, as directed by
13545 the prototype.  This is the standard treatment used on a subroutine call,
13546 not marked with C<&>, where the callee can be identified at compile time
13547 and has a prototype.
13548
13549 C<protosv> supplies the subroutine prototype to be applied to the call.
13550 It may be a normal defined scalar, of which the string value will be used.
13551 Alternatively, for convenience, it may be a subroutine object (a C<CV*>
13552 that has been cast to C<SV*>) which has a prototype.  The prototype
13553 supplied, in whichever form, does not need to match the actual callee
13554 referenced by the op tree.
13555
13556 If the argument ops disagree with the prototype, for example by having
13557 an unacceptable number of arguments, a valid op tree is returned anyway.
13558 The error is reflected in the parser state, normally resulting in a single
13559 exception at the top level of parsing which covers all the compilation
13560 errors that occurred.  In the error message, the callee is referred to
13561 by the name defined by the C<namegv> parameter.
13562
13563 =cut
13564 */
13565
13566 OP *
13567 Perl_ck_entersub_args_proto(pTHX_ OP *entersubop, GV *namegv, SV *protosv)
13568 {
13569     STRLEN proto_len;
13570     const char *proto, *proto_end;
13571     OP *aop, *prev, *cvop, *parent;
13572     int optional = 0;
13573     I32 arg = 0;
13574     I32 contextclass = 0;
13575     const char *e = NULL;
13576     PERL_ARGS_ASSERT_CK_ENTERSUB_ARGS_PROTO;
13577     if (SvTYPE(protosv) == SVt_PVCV ? !SvPOK(protosv) : !SvOK(protosv))
13578         Perl_croak(aTHX_ "panic: ck_entersub_args_proto CV with no proto, "
13579                    "flags=%lx", (unsigned long) SvFLAGS(protosv));
13580     if (SvTYPE(protosv) == SVt_PVCV)
13581          proto = CvPROTO(protosv), proto_len = CvPROTOLEN(protosv);
13582     else proto = SvPV(protosv, proto_len);
13583     proto = S_strip_spaces(aTHX_ proto, &proto_len);
13584     proto_end = proto + proto_len;
13585     parent = entersubop;
13586     aop = cUNOPx(entersubop)->op_first;
13587     if (!OpHAS_SIBLING(aop)) {
13588         parent = aop;
13589         aop = cUNOPx(aop)->op_first;
13590     }
13591     prev = aop;
13592     aop = OpSIBLING(aop);
13593     for (cvop = aop; OpHAS_SIBLING(cvop); cvop = OpSIBLING(cvop)) ;
13594     while (aop != cvop) {
13595         OP* o3 = aop;
13596
13597         if (proto >= proto_end)
13598         {
13599             SV * const namesv = cv_name((CV *)namegv, NULL, 0);
13600             yyerror_pv(Perl_form(aTHX_ "Too many arguments for %" SVf,
13601                                         SVfARG(namesv)), SvUTF8(namesv));
13602             return entersubop;
13603         }
13604
13605         switch (*proto) {
13606             case ';':
13607                 optional = 1;
13608                 proto++;
13609                 continue;
13610             case '_':
13611                 /* _ must be at the end */
13612                 if (proto[1] && !strchr(";@%", proto[1]))
13613                     goto oops;
13614                 /* FALLTHROUGH */
13615             case '$':
13616                 proto++;
13617                 arg++;
13618                 scalar(aop);
13619                 break;
13620             case '%':
13621             case '@':
13622                 list(aop);
13623                 arg++;
13624                 break;
13625             case '&':
13626                 proto++;
13627                 arg++;
13628                 if (    o3->op_type != OP_UNDEF
13629                     && (o3->op_type != OP_SREFGEN
13630                         || (  cUNOPx(cUNOPx(o3)->op_first)->op_first->op_type
13631                                 != OP_ANONCODE
13632                             && cUNOPx(cUNOPx(o3)->op_first)->op_first->op_type
13633                                 != OP_RV2CV)))
13634                     bad_type_gv(arg, namegv, o3,
13635                             arg == 1 ? "block or sub {}" : "sub {}");
13636                 break;
13637             case '*':
13638                 /* '*' allows any scalar type, including bareword */
13639                 proto++;
13640                 arg++;
13641                 if (o3->op_type == OP_RV2GV)
13642                     goto wrapref;       /* autoconvert GLOB -> GLOBref */
13643                 else if (o3->op_type == OP_CONST)
13644                     o3->op_private &= ~OPpCONST_STRICT;
13645                 scalar(aop);
13646                 break;
13647             case '+':
13648                 proto++;
13649                 arg++;
13650                 if (o3->op_type == OP_RV2AV ||
13651                     o3->op_type == OP_PADAV ||
13652                     o3->op_type == OP_RV2HV ||
13653                     o3->op_type == OP_PADHV
13654                 ) {
13655                     goto wrapref;
13656                 }
13657                 scalar(aop);
13658                 break;
13659             case '[': case ']':
13660                 goto oops;
13661
13662             case '\\':
13663                 proto++;
13664                 arg++;
13665             again:
13666                 switch (*proto++) {
13667                     case '[':
13668                         if (contextclass++ == 0) {
13669                             e = (char *) memchr(proto, ']', proto_end - proto);
13670                             if (!e || e == proto)
13671                                 goto oops;
13672                         }
13673                         else
13674                             goto oops;
13675                         goto again;
13676
13677                     case ']':
13678                         if (contextclass) {
13679                             const char *p = proto;
13680                             const char *const end = proto;
13681                             contextclass = 0;
13682                             while (*--p != '[')
13683                                 /* \[$] accepts any scalar lvalue */
13684                                 if (*p == '$'
13685                                  && Perl_op_lvalue_flags(aTHX_
13686                                      scalar(o3),
13687                                      OP_READ, /* not entersub */
13688                                      OP_LVALUE_NO_CROAK
13689                                     )) goto wrapref;
13690                             bad_type_gv(arg, namegv, o3,
13691                                     Perl_form(aTHX_ "one of %.*s",(int)(end - p), p));
13692                         } else
13693                             goto oops;
13694                         break;
13695                     case '*':
13696                         if (o3->op_type == OP_RV2GV)
13697                             goto wrapref;
13698                         if (!contextclass)
13699                             bad_type_gv(arg, namegv, o3, "symbol");
13700                         break;
13701                     case '&':
13702                         if (o3->op_type == OP_ENTERSUB
13703                          && !(o3->op_flags & OPf_STACKED))
13704                             goto wrapref;
13705                         if (!contextclass)
13706                             bad_type_gv(arg, namegv, o3, "subroutine");
13707                         break;
13708                     case '$':
13709                         if (o3->op_type == OP_RV2SV ||
13710                                 o3->op_type == OP_PADSV ||
13711                                 o3->op_type == OP_HELEM ||
13712                                 o3->op_type == OP_AELEM)
13713                             goto wrapref;
13714                         if (!contextclass) {
13715                             /* \$ accepts any scalar lvalue */
13716                             if (Perl_op_lvalue_flags(aTHX_
13717                                     scalar(o3),
13718                                     OP_READ,  /* not entersub */
13719                                     OP_LVALUE_NO_CROAK
13720                                )) goto wrapref;
13721                             bad_type_gv(arg, namegv, o3, "scalar");
13722                         }
13723                         break;
13724                     case '@':
13725                         if (o3->op_type == OP_RV2AV ||
13726                                 o3->op_type == OP_PADAV)
13727                         {
13728                             o3->op_flags &=~ OPf_PARENS;
13729                             goto wrapref;
13730                         }
13731                         if (!contextclass)
13732                             bad_type_gv(arg, namegv, o3, "array");
13733                         break;
13734                     case '%':
13735                         if (o3->op_type == OP_RV2HV ||
13736                                 o3->op_type == OP_PADHV)
13737                         {
13738                             o3->op_flags &=~ OPf_PARENS;
13739                             goto wrapref;
13740                         }
13741                         if (!contextclass)
13742                             bad_type_gv(arg, namegv, o3, "hash");
13743                         break;
13744                     wrapref:
13745                             aop = S_op_sibling_newUNOP(aTHX_ parent, prev,
13746                                                 OP_REFGEN, 0);
13747                         if (contextclass && e) {
13748                             proto = e + 1;
13749                             contextclass = 0;
13750                         }
13751                         break;
13752                     default: goto oops;
13753                 }
13754                 if (contextclass)
13755                     goto again;
13756                 break;
13757             case ' ':
13758                 proto++;
13759                 continue;
13760             default:
13761             oops: {
13762                 Perl_croak(aTHX_ "Malformed prototype for %" SVf ": %" SVf,
13763                                   SVfARG(cv_name((CV *)namegv, NULL, 0)),
13764                                   SVfARG(protosv));
13765             }
13766         }
13767
13768         op_lvalue(aop, OP_ENTERSUB);
13769         prev = aop;
13770         aop = OpSIBLING(aop);
13771     }
13772     if (aop == cvop && *proto == '_') {
13773         /* generate an access to $_ */
13774         op_sibling_splice(parent, prev, 0, newDEFSVOP());
13775     }
13776     if (!optional && proto_end > proto &&
13777         (*proto != '@' && *proto != '%' && *proto != ';' && *proto != '_'))
13778     {
13779         SV * const namesv = cv_name((CV *)namegv, NULL, 0);
13780         yyerror_pv(Perl_form(aTHX_ "Not enough arguments for %" SVf,
13781                                     SVfARG(namesv)), SvUTF8(namesv));
13782     }
13783     return entersubop;
13784 }
13785
13786 /*
13787 =for apidoc ck_entersub_args_proto_or_list
13788
13789 Performs the fixup of the arguments part of an C<entersub> op tree either
13790 based on a subroutine prototype or using default list-context processing.
13791 This is the standard treatment used on a subroutine call, not marked
13792 with C<&>, where the callee can be identified at compile time.
13793
13794 C<protosv> supplies the subroutine prototype to be applied to the call,
13795 or indicates that there is no prototype.  It may be a normal scalar,
13796 in which case if it is defined then the string value will be used
13797 as a prototype, and if it is undefined then there is no prototype.
13798 Alternatively, for convenience, it may be a subroutine object (a C<CV*>
13799 that has been cast to C<SV*>), of which the prototype will be used if it
13800 has one.  The prototype (or lack thereof) supplied, in whichever form,
13801 does not need to match the actual callee referenced by the op tree.
13802
13803 If the argument ops disagree with the prototype, for example by having
13804 an unacceptable number of arguments, a valid op tree is returned anyway.
13805 The error is reflected in the parser state, normally resulting in a single
13806 exception at the top level of parsing which covers all the compilation
13807 errors that occurred.  In the error message, the callee is referred to
13808 by the name defined by the C<namegv> parameter.
13809
13810 =cut
13811 */
13812
13813 OP *
13814 Perl_ck_entersub_args_proto_or_list(pTHX_ OP *entersubop,
13815         GV *namegv, SV *protosv)
13816 {
13817     PERL_ARGS_ASSERT_CK_ENTERSUB_ARGS_PROTO_OR_LIST;
13818     if (SvTYPE(protosv) == SVt_PVCV ? SvPOK(protosv) : SvOK(protosv))
13819         return ck_entersub_args_proto(entersubop, namegv, protosv);
13820     else
13821         return ck_entersub_args_list(entersubop);
13822 }
13823
13824 OP *
13825 Perl_ck_entersub_args_core(pTHX_ OP *entersubop, GV *namegv, SV *protosv)
13826 {
13827     IV cvflags = SvIVX(protosv);
13828     int opnum = cvflags & 0xffff;
13829     OP *aop = cUNOPx(entersubop)->op_first;
13830
13831     PERL_ARGS_ASSERT_CK_ENTERSUB_ARGS_CORE;
13832
13833     if (!opnum) {
13834         OP *cvop;
13835         if (!OpHAS_SIBLING(aop))
13836             aop = cUNOPx(aop)->op_first;
13837         aop = OpSIBLING(aop);
13838         for (cvop = aop; OpSIBLING(cvop); cvop = OpSIBLING(cvop)) ;
13839         if (aop != cvop) {
13840             SV *namesv = cv_name((CV *)namegv, NULL, CV_NAME_NOTQUAL);
13841             yyerror_pv(Perl_form(aTHX_ "Too many arguments for %" SVf,
13842                 SVfARG(namesv)), SvUTF8(namesv));
13843         }
13844         
13845         op_free(entersubop);
13846         switch(cvflags >> 16) {
13847         case 'F': return newSVOP(OP_CONST, 0,
13848                                         newSVpv(CopFILE(PL_curcop),0));
13849         case 'L': return newSVOP(
13850                            OP_CONST, 0,
13851                            Perl_newSVpvf(aTHX_
13852                              "%" IVdf, (IV)CopLINE(PL_curcop)
13853                            )
13854                          );
13855         case 'P': return newSVOP(OP_CONST, 0,
13856                                    (PL_curstash
13857                                      ? newSVhek(HvNAME_HEK(PL_curstash))
13858                                      : &PL_sv_undef
13859                                    )
13860                                 );
13861         }
13862         NOT_REACHED; /* NOTREACHED */
13863     }
13864     else {
13865         OP *prev, *cvop, *first, *parent;
13866         U32 flags = 0;
13867
13868         parent = entersubop;
13869         if (!OpHAS_SIBLING(aop)) {
13870             parent = aop;
13871             aop = cUNOPx(aop)->op_first;
13872         }
13873         
13874         first = prev = aop;
13875         aop = OpSIBLING(aop);
13876         /* find last sibling */
13877         for (cvop = aop;
13878              OpHAS_SIBLING(cvop);
13879              prev = cvop, cvop = OpSIBLING(cvop))
13880             ;
13881         if (!(cvop->op_private & OPpENTERSUB_NOPAREN)
13882             /* Usually, OPf_SPECIAL on an op with no args means that it had
13883              * parens, but these have their own meaning for that flag: */
13884             && opnum != OP_VALUES && opnum != OP_KEYS && opnum != OP_EACH
13885             && opnum != OP_DELETE && opnum != OP_EXISTS)
13886                 flags |= OPf_SPECIAL;
13887         /* excise cvop from end of sibling chain */
13888         op_sibling_splice(parent, prev, 1, NULL);
13889         op_free(cvop);
13890         if (aop == cvop) aop = NULL;
13891
13892         /* detach remaining siblings from the first sibling, then
13893          * dispose of original optree */
13894
13895         if (aop)
13896             op_sibling_splice(parent, first, -1, NULL);
13897         op_free(entersubop);
13898
13899         if (cvflags == (OP_ENTEREVAL | (1<<16)))
13900             flags |= OPpEVAL_BYTES <<8;
13901         
13902         switch (PL_opargs[opnum] & OA_CLASS_MASK) {
13903         case OA_UNOP:
13904         case OA_BASEOP_OR_UNOP:
13905         case OA_FILESTATOP:
13906             if (!aop)
13907                 return newOP(opnum,flags);       /* zero args */
13908             if (aop == prev)
13909                 return newUNOP(opnum,flags,aop); /* one arg */
13910             /* too many args */
13911             /* FALLTHROUGH */
13912         case OA_BASEOP:
13913             if (aop) {
13914                 SV *namesv;
13915                 OP *nextop;
13916
13917                 namesv = cv_name((CV *)namegv, NULL, CV_NAME_NOTQUAL);
13918                 yyerror_pv(Perl_form(aTHX_ "Too many arguments for %" SVf,
13919                     SVfARG(namesv)), SvUTF8(namesv));
13920                 while (aop) {
13921                     nextop = OpSIBLING(aop);
13922                     op_free(aop);
13923                     aop = nextop;
13924                 }
13925
13926             }
13927             return opnum == OP_RUNCV
13928                 ? newPVOP(OP_RUNCV,0,NULL)
13929                 : newOP(opnum,0);
13930         default:
13931             return op_convert_list(opnum,0,aop);
13932         }
13933     }
13934     NOT_REACHED; /* NOTREACHED */
13935     return entersubop;
13936 }
13937
13938 /*
13939 =for apidoc cv_get_call_checker_flags
13940
13941 Retrieves the function that will be used to fix up a call to C<cv>.
13942 Specifically, the function is applied to an C<entersub> op tree for a
13943 subroutine call, not marked with C<&>, where the callee can be identified
13944 at compile time as C<cv>.
13945
13946 The C-level function pointer is returned in C<*ckfun_p>, an SV argument
13947 for it is returned in C<*ckobj_p>, and control flags are returned in
13948 C<*ckflags_p>.  The function is intended to be called in this manner:
13949
13950  entersubop = (*ckfun_p)(aTHX_ entersubop, namegv, (*ckobj_p));
13951
13952 In this call, C<entersubop> is a pointer to the C<entersub> op,
13953 which may be replaced by the check function, and C<namegv> supplies
13954 the name that should be used by the check function to refer
13955 to the callee of the C<entersub> op if it needs to emit any diagnostics.
13956 It is permitted to apply the check function in non-standard situations,
13957 such as to a call to a different subroutine or to a method call.
13958
13959 C<namegv> may not actually be a GV.  If the C<CALL_CHECKER_REQUIRE_GV>
13960 bit is clear in C<*ckflags_p>, it is permitted to pass a CV or other SV
13961 instead, anything that can be used as the first argument to L</cv_name>.
13962 If the C<CALL_CHECKER_REQUIRE_GV> bit is set in C<*ckflags_p> then the
13963 check function requires C<namegv> to be a genuine GV.
13964
13965 By default, the check function is
13966 L<Perl_ck_entersub_args_proto_or_list|/ck_entersub_args_proto_or_list>,
13967 the SV parameter is C<cv> itself, and the C<CALL_CHECKER_REQUIRE_GV>
13968 flag is clear.  This implements standard prototype processing.  It can
13969 be changed, for a particular subroutine, by L</cv_set_call_checker_flags>.
13970
13971 If the C<CALL_CHECKER_REQUIRE_GV> bit is set in C<gflags> then it
13972 indicates that the caller only knows about the genuine GV version of
13973 C<namegv>, and accordingly the corresponding bit will always be set in
13974 C<*ckflags_p>, regardless of the check function's recorded requirements.
13975 If the C<CALL_CHECKER_REQUIRE_GV> bit is clear in C<gflags> then it
13976 indicates the caller knows about the possibility of passing something
13977 other than a GV as C<namegv>, and accordingly the corresponding bit may
13978 be either set or clear in C<*ckflags_p>, indicating the check function's
13979 recorded requirements.
13980
13981 C<gflags> is a bitset passed into C<cv_get_call_checker_flags>, in which
13982 only the C<CALL_CHECKER_REQUIRE_GV> bit currently has a defined meaning
13983 (for which see above).  All other bits should be clear.
13984
13985 =for apidoc cv_get_call_checker
13986
13987 The original form of L</cv_get_call_checker_flags>, which does not return
13988 checker flags.  When using a checker function returned by this function,
13989 it is only safe to call it with a genuine GV as its C<namegv> argument.
13990
13991 =cut
13992 */
13993
13994 void
13995 Perl_cv_get_call_checker_flags(pTHX_ CV *cv, U32 gflags,
13996         Perl_call_checker *ckfun_p, SV **ckobj_p, U32 *ckflags_p)
13997 {
13998     MAGIC *callmg;
13999     PERL_ARGS_ASSERT_CV_GET_CALL_CHECKER_FLAGS;
14000     PERL_UNUSED_CONTEXT;
14001     callmg = SvMAGICAL((SV*)cv) ? mg_find((SV*)cv, PERL_MAGIC_checkcall) : NULL;
14002     if (callmg) {
14003         *ckfun_p = DPTR2FPTR(Perl_call_checker, callmg->mg_ptr);
14004         *ckobj_p = callmg->mg_obj;
14005         *ckflags_p = (callmg->mg_flags | gflags) & MGf_REQUIRE_GV;
14006     } else {
14007         *ckfun_p = Perl_ck_entersub_args_proto_or_list;
14008         *ckobj_p = (SV*)cv;
14009         *ckflags_p = gflags & MGf_REQUIRE_GV;
14010     }
14011 }
14012
14013 void
14014 Perl_cv_get_call_checker(pTHX_ CV *cv, Perl_call_checker *ckfun_p, SV **ckobj_p)
14015 {
14016     U32 ckflags;
14017     PERL_ARGS_ASSERT_CV_GET_CALL_CHECKER;
14018     PERL_UNUSED_CONTEXT;
14019     cv_get_call_checker_flags(cv, CALL_CHECKER_REQUIRE_GV, ckfun_p, ckobj_p,
14020         &ckflags);
14021 }
14022
14023 /*
14024 =for apidoc cv_set_call_checker_flags
14025
14026 Sets the function that will be used to fix up a call to C<cv>.
14027 Specifically, the function is applied to an C<entersub> op tree for a
14028 subroutine call, not marked with C<&>, where the callee can be identified
14029 at compile time as C<cv>.
14030
14031 The C-level function pointer is supplied in C<ckfun>, an SV argument for
14032 it is supplied in C<ckobj>, and control flags are supplied in C<ckflags>.
14033 The function should be defined like this:
14034
14035     STATIC OP * ckfun(pTHX_ OP *op, GV *namegv, SV *ckobj)
14036
14037 It is intended to be called in this manner:
14038
14039     entersubop = ckfun(aTHX_ entersubop, namegv, ckobj);
14040
14041 In this call, C<entersubop> is a pointer to the C<entersub> op,
14042 which may be replaced by the check function, and C<namegv> supplies
14043 the name that should be used by the check function to refer
14044 to the callee of the C<entersub> op if it needs to emit any diagnostics.
14045 It is permitted to apply the check function in non-standard situations,
14046 such as to a call to a different subroutine or to a method call.
14047
14048 C<namegv> may not actually be a GV.  For efficiency, perl may pass a
14049 CV or other SV instead.  Whatever is passed can be used as the first
14050 argument to L</cv_name>.  You can force perl to pass a GV by including
14051 C<CALL_CHECKER_REQUIRE_GV> in the C<ckflags>.
14052
14053 C<ckflags> is a bitset, in which only the C<CALL_CHECKER_REQUIRE_GV>
14054 bit currently has a defined meaning (for which see above).  All other
14055 bits should be clear.
14056
14057 The current setting for a particular CV can be retrieved by
14058 L</cv_get_call_checker_flags>.
14059
14060 =for apidoc cv_set_call_checker
14061
14062 The original form of L</cv_set_call_checker_flags>, which passes it the
14063 C<CALL_CHECKER_REQUIRE_GV> flag for backward-compatibility.  The effect
14064 of that flag setting is that the check function is guaranteed to get a
14065 genuine GV as its C<namegv> argument.
14066
14067 =cut
14068 */
14069
14070 void
14071 Perl_cv_set_call_checker(pTHX_ CV *cv, Perl_call_checker ckfun, SV *ckobj)
14072 {
14073     PERL_ARGS_ASSERT_CV_SET_CALL_CHECKER;
14074     cv_set_call_checker_flags(cv, ckfun, ckobj, CALL_CHECKER_REQUIRE_GV);
14075 }
14076
14077 void
14078 Perl_cv_set_call_checker_flags(pTHX_ CV *cv, Perl_call_checker ckfun,
14079                                      SV *ckobj, U32 ckflags)
14080 {
14081     PERL_ARGS_ASSERT_CV_SET_CALL_CHECKER_FLAGS;
14082     if (ckfun == Perl_ck_entersub_args_proto_or_list && ckobj == (SV*)cv) {
14083         if (SvMAGICAL((SV*)cv))
14084             mg_free_type((SV*)cv, PERL_MAGIC_checkcall);
14085     } else {
14086         MAGIC *callmg;
14087         sv_magic((SV*)cv, &PL_sv_undef, PERL_MAGIC_checkcall, NULL, 0);
14088         callmg = mg_find((SV*)cv, PERL_MAGIC_checkcall);
14089         assert(callmg);
14090         if (callmg->mg_flags & MGf_REFCOUNTED) {
14091             SvREFCNT_dec(callmg->mg_obj);
14092             callmg->mg_flags &= ~MGf_REFCOUNTED;
14093         }
14094         callmg->mg_ptr = FPTR2DPTR(char *, ckfun);
14095         callmg->mg_obj = ckobj;
14096         if (ckobj != (SV*)cv) {
14097             SvREFCNT_inc_simple_void_NN(ckobj);
14098             callmg->mg_flags |= MGf_REFCOUNTED;
14099         }
14100         callmg->mg_flags = (callmg->mg_flags &~ MGf_REQUIRE_GV)
14101                          | (U8)(ckflags & MGf_REQUIRE_GV) | MGf_COPY;
14102     }
14103 }
14104
14105 static void
14106 S_entersub_alloc_targ(pTHX_ OP * const o)
14107 {
14108     o->op_targ = pad_alloc(OP_ENTERSUB, SVs_PADTMP);
14109     o->op_private |= OPpENTERSUB_HASTARG;
14110 }
14111
14112 OP *
14113 Perl_ck_subr(pTHX_ OP *o)
14114 {
14115     OP *aop, *cvop;
14116     CV *cv;
14117     GV *namegv;
14118     SV **const_class = NULL;
14119
14120     PERL_ARGS_ASSERT_CK_SUBR;
14121
14122     aop = cUNOPx(o)->op_first;
14123     if (!OpHAS_SIBLING(aop))
14124         aop = cUNOPx(aop)->op_first;
14125     aop = OpSIBLING(aop);
14126     for (cvop = aop; OpHAS_SIBLING(cvop); cvop = OpSIBLING(cvop)) ;
14127     cv = rv2cv_op_cv(cvop, RV2CVOPCV_MARK_EARLY);
14128     namegv = cv ? (GV*)rv2cv_op_cv(cvop, RV2CVOPCV_MAYBE_NAME_GV) : NULL;
14129
14130     o->op_private &= ~1;
14131     o->op_private |= (PL_hints & HINT_STRICT_REFS);
14132     if (PERLDB_SUB && PL_curstash != PL_debstash)
14133         o->op_private |= OPpENTERSUB_DB;
14134     switch (cvop->op_type) {
14135         case OP_RV2CV:
14136             o->op_private |= (cvop->op_private & OPpENTERSUB_AMPER);
14137             op_null(cvop);
14138             break;
14139         case OP_METHOD:
14140         case OP_METHOD_NAMED:
14141         case OP_METHOD_SUPER:
14142         case OP_METHOD_REDIR:
14143         case OP_METHOD_REDIR_SUPER:
14144             o->op_flags |= OPf_REF;
14145             if (aop->op_type == OP_CONST) {
14146                 aop->op_private &= ~OPpCONST_STRICT;
14147                 const_class = &cSVOPx(aop)->op_sv;
14148             }
14149             else if (aop->op_type == OP_LIST) {
14150                 OP * const sib = OpSIBLING(((UNOP*)aop)->op_first);
14151                 if (sib && sib->op_type == OP_CONST) {
14152                     sib->op_private &= ~OPpCONST_STRICT;
14153                     const_class = &cSVOPx(sib)->op_sv;
14154                 }
14155             }
14156             /* make class name a shared cow string to speedup method calls */
14157             /* constant string might be replaced with object, f.e. bigint */
14158             if (const_class && SvPOK(*const_class)) {
14159                 STRLEN len;
14160                 const char* str = SvPV(*const_class, len);
14161                 if (len) {
14162                     SV* const shared = newSVpvn_share(
14163                         str, SvUTF8(*const_class)
14164                                     ? -(SSize_t)len : (SSize_t)len,
14165                         0
14166                     );
14167                     if (SvREADONLY(*const_class))
14168                         SvREADONLY_on(shared);
14169                     SvREFCNT_dec(*const_class);
14170                     *const_class = shared;
14171                 }
14172             }
14173             break;
14174     }
14175
14176     if (!cv) {
14177         S_entersub_alloc_targ(aTHX_ o);
14178         return ck_entersub_args_list(o);
14179     } else {
14180         Perl_call_checker ckfun;
14181         SV *ckobj;
14182         U32 ckflags;
14183         cv_get_call_checker_flags(cv, 0, &ckfun, &ckobj, &ckflags);
14184         if (CvISXSUB(cv) || !CvROOT(cv))
14185             S_entersub_alloc_targ(aTHX_ o);
14186         if (!namegv) {
14187             /* The original call checker API guarantees that a GV will be
14188                be provided with the right name.  So, if the old API was
14189                used (or the REQUIRE_GV flag was passed), we have to reify
14190                the CV’s GV, unless this is an anonymous sub.  This is not
14191                ideal for lexical subs, as its stringification will include
14192                the package.  But it is the best we can do.  */
14193             if (ckflags & CALL_CHECKER_REQUIRE_GV) {
14194                 if (!CvANON(cv) && (!CvNAMED(cv) || CvNAME_HEK(cv)))
14195                     namegv = CvGV(cv);
14196             }
14197             else namegv = MUTABLE_GV(cv);
14198             /* After a syntax error in a lexical sub, the cv that
14199                rv2cv_op_cv returns may be a nameless stub. */
14200             if (!namegv) return ck_entersub_args_list(o);
14201
14202         }
14203         return ckfun(aTHX_ o, namegv, ckobj);
14204     }
14205 }
14206
14207 OP *
14208 Perl_ck_svconst(pTHX_ OP *o)
14209 {
14210     SV * const sv = cSVOPo->op_sv;
14211     PERL_ARGS_ASSERT_CK_SVCONST;
14212     PERL_UNUSED_CONTEXT;
14213 #ifdef PERL_COPY_ON_WRITE
14214     /* Since the read-only flag may be used to protect a string buffer, we
14215        cannot do copy-on-write with existing read-only scalars that are not
14216        already copy-on-write scalars.  To allow $_ = "hello" to do COW with
14217        that constant, mark the constant as COWable here, if it is not
14218        already read-only. */
14219     if (!SvREADONLY(sv) && !SvIsCOW(sv) && SvCANCOW(sv)) {
14220         SvIsCOW_on(sv);
14221         CowREFCNT(sv) = 0;
14222 # ifdef PERL_DEBUG_READONLY_COW
14223         sv_buf_to_ro(sv);
14224 # endif
14225     }
14226 #endif
14227     SvREADONLY_on(sv);
14228     return o;
14229 }
14230
14231 OP *
14232 Perl_ck_trunc(pTHX_ OP *o)
14233 {
14234     PERL_ARGS_ASSERT_CK_TRUNC;
14235
14236     if (o->op_flags & OPf_KIDS) {
14237         SVOP *kid = (SVOP*)cUNOPo->op_first;
14238
14239         if (kid->op_type == OP_NULL)
14240             kid = (SVOP*)OpSIBLING(kid);
14241         if (kid && kid->op_type == OP_CONST &&
14242             (kid->op_private & OPpCONST_BARE) &&
14243             !kid->op_folded)
14244         {
14245             o->op_flags |= OPf_SPECIAL;
14246             kid->op_private &= ~OPpCONST_STRICT;
14247         }
14248     }
14249     return ck_fun(o);
14250 }
14251
14252 OP *
14253 Perl_ck_substr(pTHX_ OP *o)
14254 {
14255     PERL_ARGS_ASSERT_CK_SUBSTR;
14256
14257     o = ck_fun(o);
14258     if ((o->op_flags & OPf_KIDS) && (o->op_private == 4)) {
14259         OP *kid = cLISTOPo->op_first;
14260
14261         if (kid->op_type == OP_NULL)
14262             kid = OpSIBLING(kid);
14263         if (kid)
14264             /* Historically, substr(delete $foo{bar},...) has been allowed
14265                with 4-arg substr.  Keep it working by applying entersub
14266                lvalue context.  */
14267             op_lvalue(kid, OP_ENTERSUB);
14268
14269     }
14270     return o;
14271 }
14272
14273 OP *
14274 Perl_ck_tell(pTHX_ OP *o)
14275 {
14276     PERL_ARGS_ASSERT_CK_TELL;
14277     o = ck_fun(o);
14278     if (o->op_flags & OPf_KIDS) {
14279      OP *kid = cLISTOPo->op_first;
14280      if (kid->op_type == OP_NULL && OpHAS_SIBLING(kid)) kid = OpSIBLING(kid);
14281      if (kid->op_type == OP_RV2GV) kid->op_private |= OPpALLOW_FAKE;
14282     }
14283     return o;
14284 }
14285
14286 OP *
14287 Perl_ck_each(pTHX_ OP *o)
14288 {
14289     dVAR;
14290     OP *kid = o->op_flags & OPf_KIDS ? cUNOPo->op_first : NULL;
14291     const unsigned orig_type  = o->op_type;
14292
14293     PERL_ARGS_ASSERT_CK_EACH;
14294
14295     if (kid) {
14296         switch (kid->op_type) {
14297             case OP_PADHV:
14298             case OP_RV2HV:
14299                 break;
14300             case OP_PADAV:
14301             case OP_RV2AV:
14302                 OpTYPE_set(o, orig_type == OP_EACH ? OP_AEACH
14303                             : orig_type == OP_KEYS ? OP_AKEYS
14304                             :                        OP_AVALUES);
14305                 break;
14306             case OP_CONST:
14307                 if (kid->op_private == OPpCONST_BARE
14308                  || !SvROK(cSVOPx_sv(kid))
14309                  || (  SvTYPE(SvRV(cSVOPx_sv(kid))) != SVt_PVAV
14310                     && SvTYPE(SvRV(cSVOPx_sv(kid))) != SVt_PVHV  )
14311                    )
14312                     goto bad;
14313                 /* FALLTHROUGH */
14314             default:
14315                 qerror(Perl_mess(aTHX_
14316                     "Experimental %s on scalar is now forbidden",
14317                      PL_op_desc[orig_type]));
14318                bad:
14319                 bad_type_pv(1, "hash or array", o, kid);
14320                 return o;
14321         }
14322     }
14323     return ck_fun(o);
14324 }
14325
14326 OP *
14327 Perl_ck_length(pTHX_ OP *o)
14328 {
14329     PERL_ARGS_ASSERT_CK_LENGTH;
14330
14331     o = ck_fun(o);
14332
14333     if (ckWARN(WARN_SYNTAX)) {
14334         const OP *kid = o->op_flags & OPf_KIDS ? cLISTOPo->op_first : NULL;
14335
14336         if (kid) {
14337             SV *name = NULL;
14338             const bool hash = kid->op_type == OP_PADHV
14339                            || kid->op_type == OP_RV2HV;
14340             switch (kid->op_type) {
14341                 case OP_PADHV:
14342                 case OP_PADAV:
14343                 case OP_RV2HV:
14344                 case OP_RV2AV:
14345                     name = S_op_varname(aTHX_ kid);
14346                     break;
14347                 default:
14348                     return o;
14349             }
14350             if (name)
14351                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
14352                     "length() used on %" SVf " (did you mean \"scalar(%s%" SVf
14353                     ")\"?)",
14354                     SVfARG(name), hash ? "keys " : "", SVfARG(name)
14355                 );
14356             else if (hash)
14357      /* diag_listed_as: length() used on %s (did you mean "scalar(%s)"?) */
14358                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
14359                     "length() used on %%hash (did you mean \"scalar(keys %%hash)\"?)");
14360             else
14361      /* diag_listed_as: length() used on %s (did you mean "scalar(%s)"?) */
14362                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
14363                     "length() used on @array (did you mean \"scalar(@array)\"?)");
14364         }
14365     }
14366
14367     return o;
14368 }
14369
14370
14371
14372 /* 
14373    ---------------------------------------------------------
14374  
14375    Common vars in list assignment
14376
14377    There now follows some enums and static functions for detecting
14378    common variables in list assignments. Here is a little essay I wrote
14379    for myself when trying to get my head around this. DAPM.
14380
14381    ----
14382
14383    First some random observations:
14384    
14385    * If a lexical var is an alias of something else, e.g.
14386        for my $x ($lex, $pkg, $a[0]) {...}
14387      then the act of aliasing will increase the reference count of the SV
14388    
14389    * If a package var is an alias of something else, it may still have a
14390      reference count of 1, depending on how the alias was created, e.g.
14391      in *a = *b, $a may have a refcount of 1 since the GP is shared
14392      with a single GvSV pointer to the SV. So If it's an alias of another
14393      package var, then RC may be 1; if it's an alias of another scalar, e.g.
14394      a lexical var or an array element, then it will have RC > 1.
14395    
14396    * There are many ways to create a package alias; ultimately, XS code
14397      may quite legally do GvSV(gv) = SvREFCNT_inc(sv) for example, so
14398      run-time tracing mechanisms are unlikely to be able to catch all cases.
14399    
14400    * When the LHS is all my declarations, the same vars can't appear directly
14401      on the RHS, but they can indirectly via closures, aliasing and lvalue
14402      subs. But those techniques all involve an increase in the lexical
14403      scalar's ref count.
14404    
14405    * When the LHS is all lexical vars (but not necessarily my declarations),
14406      it is possible for the same lexicals to appear directly on the RHS, and
14407      without an increased ref count, since the stack isn't refcounted.
14408      This case can be detected at compile time by scanning for common lex
14409      vars with PL_generation.
14410    
14411    * lvalue subs defeat common var detection, but they do at least
14412      return vars with a temporary ref count increment. Also, you can't
14413      tell at compile time whether a sub call is lvalue.
14414    
14415     
14416    So...
14417          
14418    A: There are a few circumstances where there definitely can't be any
14419      commonality:
14420    
14421        LHS empty:  () = (...);
14422        RHS empty:  (....) = ();
14423        RHS contains only constants or other 'can't possibly be shared'
14424            elements (e.g. ops that return PADTMPs):  (...) = (1,2, length)
14425            i.e. they only contain ops not marked as dangerous, whose children
14426            are also not dangerous;
14427        LHS ditto;
14428        LHS contains a single scalar element: e.g. ($x) = (....); because
14429            after $x has been modified, it won't be used again on the RHS;
14430        RHS contains a single element with no aggregate on LHS: e.g.
14431            ($a,$b,$c)  = ($x); again, once $a has been modified, its value
14432            won't be used again.
14433    
14434    B: If LHS are all 'my' lexical var declarations (or safe ops, which
14435      we can ignore):
14436    
14437        my ($a, $b, @c) = ...;
14438    
14439        Due to closure and goto tricks, these vars may already have content.
14440        For the same reason, an element on the RHS may be a lexical or package
14441        alias of one of the vars on the left, or share common elements, for
14442        example:
14443    
14444            my ($x,$y) = f(); # $x and $y on both sides
14445            sub f : lvalue { ($x,$y) = (1,2); $y, $x }
14446    
14447        and
14448    
14449            my $ra = f();
14450            my @a = @$ra;  # elements of @a on both sides
14451            sub f { @a = 1..4; \@a }
14452    
14453    
14454        First, just consider scalar vars on LHS:
14455    
14456            RHS is safe only if (A), or in addition,
14457                * contains only lexical *scalar* vars, where neither side's
14458                  lexicals have been flagged as aliases 
14459    
14460            If RHS is not safe, then it's always legal to check LHS vars for
14461            RC==1, since the only RHS aliases will always be associated
14462            with an RC bump.
14463    
14464            Note that in particular, RHS is not safe if:
14465    
14466                * it contains package scalar vars; e.g.:
14467    
14468                    f();
14469                    my ($x, $y) = (2, $x_alias);
14470                    sub f { $x = 1; *x_alias = \$x; }
14471    
14472                * It contains other general elements, such as flattened or
14473                * spliced or single array or hash elements, e.g.
14474    
14475                    f();
14476                    my ($x,$y) = @a; # or $a[0] or @a{@b} etc 
14477    
14478                    sub f {
14479                        ($x, $y) = (1,2);
14480                        use feature 'refaliasing';
14481                        \($a[0], $a[1]) = \($y,$x);
14482                    }
14483    
14484                  It doesn't matter if the array/hash is lexical or package.
14485    
14486                * it contains a function call that happens to be an lvalue
14487                  sub which returns one or more of the above, e.g.
14488    
14489                    f();
14490                    my ($x,$y) = f();
14491    
14492                    sub f : lvalue {
14493                        ($x, $y) = (1,2);
14494                        *x1 = \$x;
14495                        $y, $x1;
14496                    }
14497    
14498                    (so a sub call on the RHS should be treated the same
14499                    as having a package var on the RHS).
14500    
14501                * any other "dangerous" thing, such an op or built-in that
14502                  returns one of the above, e.g. pp_preinc
14503    
14504    
14505            If RHS is not safe, what we can do however is at compile time flag
14506            that the LHS are all my declarations, and at run time check whether
14507            all the LHS have RC == 1, and if so skip the full scan.
14508    
14509        Now consider array and hash vars on LHS: e.g. my (...,@a) = ...;
14510    
14511            Here the issue is whether there can be elements of @a on the RHS
14512            which will get prematurely freed when @a is cleared prior to
14513            assignment. This is only a problem if the aliasing mechanism
14514            is one which doesn't increase the refcount - only if RC == 1
14515            will the RHS element be prematurely freed.
14516    
14517            Because the array/hash is being INTROed, it or its elements
14518            can't directly appear on the RHS:
14519    
14520                my (@a) = ($a[0], @a, etc) # NOT POSSIBLE
14521    
14522            but can indirectly, e.g.:
14523    
14524                my $r = f();
14525                my (@a) = @$r;
14526                sub f { @a = 1..3; \@a }
14527    
14528            So if the RHS isn't safe as defined by (A), we must always
14529            mortalise and bump the ref count of any remaining RHS elements
14530            when assigning to a non-empty LHS aggregate.
14531    
14532            Lexical scalars on the RHS aren't safe if they've been involved in
14533            aliasing, e.g.
14534    
14535                use feature 'refaliasing';
14536    
14537                f();
14538                \(my $lex) = \$pkg;
14539                my @a = ($lex,3); # equivalent to ($a[0],3)
14540    
14541                sub f {
14542                    @a = (1,2);
14543                    \$pkg = \$a[0];
14544                }
14545    
14546            Similarly with lexical arrays and hashes on the RHS:
14547    
14548                f();
14549                my @b;
14550                my @a = (@b);
14551    
14552                sub f {
14553                    @a = (1,2);
14554                    \$b[0] = \$a[1];
14555                    \$b[1] = \$a[0];
14556                }
14557    
14558    
14559    
14560    C: As (B), but in addition the LHS may contain non-intro lexicals, e.g.
14561        my $a; ($a, my $b) = (....);
14562    
14563        The difference between (B) and (C) is that it is now physically
14564        possible for the LHS vars to appear on the RHS too, where they
14565        are not reference counted; but in this case, the compile-time
14566        PL_generation sweep will detect such common vars.
14567    
14568        So the rules for (C) differ from (B) in that if common vars are
14569        detected, the runtime "test RC==1" optimisation can no longer be used,
14570        and a full mark and sweep is required
14571    
14572    D: As (C), but in addition the LHS may contain package vars.
14573    
14574        Since package vars can be aliased without a corresponding refcount
14575        increase, all bets are off. It's only safe if (A). E.g.
14576    
14577            my ($x, $y) = (1,2);
14578    
14579            for $x_alias ($x) {
14580                ($x_alias, $y) = (3, $x); # whoops
14581            }
14582    
14583        Ditto for LHS aggregate package vars.
14584    
14585    E: Any other dangerous ops on LHS, e.g.
14586            (f(), $a[0], @$r) = (...);
14587    
14588        this is similar to (E) in that all bets are off. In addition, it's
14589        impossible to determine at compile time whether the LHS
14590        contains a scalar or an aggregate, e.g.
14591    
14592            sub f : lvalue { @a }
14593            (f()) = 1..3;
14594
14595 * ---------------------------------------------------------
14596 */
14597
14598
14599 /* A set of bit flags returned by S_aassign_scan(). Each flag indicates
14600  * that at least one of the things flagged was seen.
14601  */
14602
14603 enum {
14604     AAS_MY_SCALAR       = 0x001, /* my $scalar */
14605     AAS_MY_AGG          = 0x002, /* aggregate: my @array or my %hash */
14606     AAS_LEX_SCALAR      = 0x004, /* $lexical */
14607     AAS_LEX_AGG         = 0x008, /* @lexical or %lexical aggregate */
14608     AAS_LEX_SCALAR_COMM = 0x010, /* $lexical seen on both sides */
14609     AAS_PKG_SCALAR      = 0x020, /* $scalar (where $scalar is pkg var) */
14610     AAS_PKG_AGG         = 0x040, /* package @array or %hash aggregate */
14611     AAS_DANGEROUS       = 0x080, /* an op (other than the above)
14612                                          that's flagged OA_DANGEROUS */
14613     AAS_SAFE_SCALAR     = 0x100, /* produces at least one scalar SV that's
14614                                         not in any of the categories above */
14615     AAS_DEFAV           = 0x200  /* contains just a single '@_' on RHS */
14616 };
14617
14618
14619
14620 /* helper function for S_aassign_scan().
14621  * check a PAD-related op for commonality and/or set its generation number.
14622  * Returns a boolean indicating whether its shared */
14623
14624 static bool
14625 S_aassign_padcheck(pTHX_ OP* o, bool rhs)
14626 {
14627     if (PAD_COMPNAME_GEN(o->op_targ) == PERL_INT_MAX)
14628         /* lexical used in aliasing */
14629         return TRUE;
14630
14631     if (rhs)
14632         return cBOOL(PAD_COMPNAME_GEN(o->op_targ) == (STRLEN)PL_generation);
14633     else
14634         PAD_COMPNAME_GEN_set(o->op_targ, PL_generation);
14635
14636     return FALSE;
14637 }
14638
14639
14640 /*
14641   Helper function for OPpASSIGN_COMMON* detection in rpeep().
14642   It scans the left or right hand subtree of the aassign op, and returns a
14643   set of flags indicating what sorts of things it found there.
14644   'rhs' indicates whether we're scanning the LHS or RHS. If the former, we
14645   set PL_generation on lexical vars; if the latter, we see if
14646   PL_generation matches.
14647   'scalars_p' is a pointer to a counter of the number of scalar SVs seen.
14648   This fn will increment it by the number seen. It's not intended to
14649   be an accurate count (especially as many ops can push a variable
14650   number of SVs onto the stack); rather it's used as to test whether there
14651   can be at most 1 SV pushed; so it's only meanings are "0, 1, many".
14652 */
14653
14654 static int
14655 S_aassign_scan(pTHX_ OP* o, bool rhs, int *scalars_p)
14656 {
14657     OP *top_op           = o;
14658     OP *effective_top_op = o;
14659     int all_flags = 0;
14660
14661     while (1) {
14662     bool top = o == effective_top_op;
14663     int flags = 0;
14664     OP* next_kid = NULL;
14665
14666     /* first, look for a solitary @_ on the RHS */
14667     if (   rhs
14668         && top
14669         && (o->op_flags & OPf_KIDS)
14670         && OP_TYPE_IS_OR_WAS(o, OP_LIST)
14671     ) {
14672         OP *kid = cUNOPo->op_first;
14673         if (   (   kid->op_type == OP_PUSHMARK
14674                 || kid->op_type == OP_PADRANGE) /* ex-pushmark */
14675             && ((kid = OpSIBLING(kid)))
14676             && !OpHAS_SIBLING(kid)
14677             && kid->op_type == OP_RV2AV
14678             && !(kid->op_flags & OPf_REF)
14679             && !(kid->op_private & (OPpLVAL_INTRO|OPpMAYBE_LVSUB))
14680             && ((kid->op_flags & OPf_WANT) == OPf_WANT_LIST)
14681             && ((kid = cUNOPx(kid)->op_first))
14682             && kid->op_type == OP_GV
14683             && cGVOPx_gv(kid) == PL_defgv
14684         )
14685             flags = AAS_DEFAV;
14686     }
14687
14688     switch (o->op_type) {
14689     case OP_GVSV:
14690         (*scalars_p)++;
14691         all_flags |= AAS_PKG_SCALAR;
14692         goto do_next;
14693
14694     case OP_PADAV:
14695     case OP_PADHV:
14696         (*scalars_p) += 2;
14697         /* if !top, could be e.g. @a[0,1] */
14698         all_flags |=  (top && (o->op_flags & OPf_REF))
14699                         ? ((o->op_private & OPpLVAL_INTRO)
14700                             ? AAS_MY_AGG : AAS_LEX_AGG)
14701                         : AAS_DANGEROUS;
14702         goto do_next;
14703
14704     case OP_PADSV:
14705         {
14706             int comm = S_aassign_padcheck(aTHX_ o, rhs)
14707                         ?  AAS_LEX_SCALAR_COMM : 0;
14708             (*scalars_p)++;
14709             all_flags |= (o->op_private & OPpLVAL_INTRO)
14710                 ? (AAS_MY_SCALAR|comm) : (AAS_LEX_SCALAR|comm);
14711             goto do_next;
14712
14713         }
14714
14715     case OP_RV2AV:
14716     case OP_RV2HV:
14717         (*scalars_p) += 2;
14718         if (cUNOPx(o)->op_first->op_type != OP_GV)
14719             all_flags |= AAS_DANGEROUS; /* @{expr}, %{expr} */
14720         /* @pkg, %pkg */
14721         /* if !top, could be e.g. @a[0,1] */
14722         else if (top && (o->op_flags & OPf_REF))
14723             all_flags |= AAS_PKG_AGG;
14724         else
14725             all_flags |= AAS_DANGEROUS;
14726         goto do_next;
14727
14728     case OP_RV2SV:
14729         (*scalars_p)++;
14730         if (cUNOPx(o)->op_first->op_type != OP_GV) {
14731             (*scalars_p) += 2;
14732             all_flags |= AAS_DANGEROUS; /* ${expr} */
14733         }
14734         else
14735             all_flags |= AAS_PKG_SCALAR; /* $pkg */
14736         goto do_next;
14737
14738     case OP_SPLIT:
14739         if (o->op_private & OPpSPLIT_ASSIGN) {
14740             /* the assign in @a = split() has been optimised away
14741              * and the @a attached directly to the split op
14742              * Treat the array as appearing on the RHS, i.e.
14743              *    ... = (@a = split)
14744              * is treated like
14745              *    ... = @a;
14746              */
14747
14748             if (o->op_flags & OPf_STACKED) {
14749                 /* @{expr} = split() - the array expression is tacked
14750                  * on as an extra child to split - process kid */
14751                 next_kid = cLISTOPo->op_last;
14752                 goto do_next;
14753             }
14754
14755             /* ... else array is directly attached to split op */
14756             (*scalars_p) += 2;
14757             all_flags |= (PL_op->op_private & OPpSPLIT_LEX)
14758                             ? ((o->op_private & OPpLVAL_INTRO)
14759                                 ? AAS_MY_AGG : AAS_LEX_AGG)
14760                             : AAS_PKG_AGG;
14761             goto do_next;
14762         }
14763         (*scalars_p)++;
14764         /* other args of split can't be returned */
14765         all_flags |= AAS_SAFE_SCALAR;
14766         goto do_next;
14767
14768     case OP_UNDEF:
14769         /* undef counts as a scalar on the RHS:
14770          *   (undef, $x) = ...;         # only 1 scalar on LHS: always safe
14771          *   ($x, $y)    = (undef, $x); # 2 scalars on RHS: unsafe
14772          */
14773         if (rhs)
14774             (*scalars_p)++;
14775         flags = AAS_SAFE_SCALAR;
14776         break;
14777
14778     case OP_PUSHMARK:
14779     case OP_STUB:
14780         /* these are all no-ops; they don't push a potentially common SV
14781          * onto the stack, so they are neither AAS_DANGEROUS nor
14782          * AAS_SAFE_SCALAR */
14783         goto do_next;
14784
14785     case OP_PADRANGE: /* Ignore padrange; checking its siblings is enough */
14786         break;
14787
14788     case OP_NULL:
14789     case OP_LIST:
14790         /* these do nothing, but may have children */
14791         break;
14792
14793     default:
14794         if (PL_opargs[o->op_type] & OA_DANGEROUS) {
14795             (*scalars_p) += 2;
14796             flags = AAS_DANGEROUS;
14797             break;
14798         }
14799
14800         if (   (PL_opargs[o->op_type] & OA_TARGLEX)
14801             && (o->op_private & OPpTARGET_MY))
14802         {
14803             (*scalars_p)++;
14804             all_flags |= S_aassign_padcheck(aTHX_ o, rhs)
14805                             ? AAS_LEX_SCALAR_COMM : AAS_LEX_SCALAR;
14806             goto do_next;
14807         }
14808
14809         /* if its an unrecognised, non-dangerous op, assume that it
14810          * it the cause of at least one safe scalar */
14811         (*scalars_p)++;
14812         flags = AAS_SAFE_SCALAR;
14813         break;
14814     }
14815
14816     all_flags |= flags;
14817
14818     /* by default, process all kids next
14819      * XXX this assumes that all other ops are "transparent" - i.e. that
14820      * they can return some of their children. While this true for e.g.
14821      * sort and grep, it's not true for e.g. map. We really need a
14822      * 'transparent' flag added to regen/opcodes
14823      */
14824     if (o->op_flags & OPf_KIDS) {
14825         next_kid = cUNOPo->op_first;
14826         /* these ops do nothing but may have children; but their
14827          * children should also be treated as top-level */
14828         if (   o == effective_top_op
14829             && (o->op_type == OP_NULL || o->op_type == OP_LIST)
14830         )
14831             effective_top_op = next_kid;
14832     }
14833
14834
14835     /* If next_kid is set, someone in the code above wanted us to process
14836      * that kid and all its remaining siblings.  Otherwise, work our way
14837      * back up the tree */
14838   do_next:
14839     while (!next_kid) {
14840         if (o == top_op)
14841             return all_flags; /* at top; no parents/siblings to try */
14842         if (OpHAS_SIBLING(o)) {
14843             next_kid = o->op_sibparent;
14844             if (o == effective_top_op)
14845                 effective_top_op = next_kid;
14846         }
14847         else
14848             if (o == effective_top_op)
14849                 effective_top_op = o->op_sibparent;
14850             o = o->op_sibparent; /* try parent's next sibling */
14851
14852     }
14853     o = next_kid;
14854     } /* while */
14855
14856 }
14857
14858
14859 /* Check for in place reverse and sort assignments like "@a = reverse @a"
14860    and modify the optree to make them work inplace */
14861
14862 STATIC void
14863 S_inplace_aassign(pTHX_ OP *o) {
14864
14865     OP *modop, *modop_pushmark;
14866     OP *oright;
14867     OP *oleft, *oleft_pushmark;
14868
14869     PERL_ARGS_ASSERT_INPLACE_AASSIGN;
14870
14871     assert((o->op_flags & OPf_WANT) == OPf_WANT_VOID);
14872
14873     assert(cUNOPo->op_first->op_type == OP_NULL);
14874     modop_pushmark = cUNOPx(cUNOPo->op_first)->op_first;
14875     assert(modop_pushmark->op_type == OP_PUSHMARK);
14876     modop = OpSIBLING(modop_pushmark);
14877
14878     if (modop->op_type != OP_SORT && modop->op_type != OP_REVERSE)
14879         return;
14880
14881     /* no other operation except sort/reverse */
14882     if (OpHAS_SIBLING(modop))
14883         return;
14884
14885     assert(cUNOPx(modop)->op_first->op_type == OP_PUSHMARK);
14886     if (!(oright = OpSIBLING(cUNOPx(modop)->op_first))) return;
14887
14888     if (modop->op_flags & OPf_STACKED) {
14889         /* skip sort subroutine/block */
14890         assert(oright->op_type == OP_NULL);
14891         oright = OpSIBLING(oright);
14892     }
14893
14894     assert(OpSIBLING(cUNOPo->op_first)->op_type == OP_NULL);
14895     oleft_pushmark = cUNOPx(OpSIBLING(cUNOPo->op_first))->op_first;
14896     assert(oleft_pushmark->op_type == OP_PUSHMARK);
14897     oleft = OpSIBLING(oleft_pushmark);
14898
14899     /* Check the lhs is an array */
14900     if (!oleft ||
14901         (oleft->op_type != OP_RV2AV && oleft->op_type != OP_PADAV)
14902         || OpHAS_SIBLING(oleft)
14903         || (oleft->op_private & OPpLVAL_INTRO)
14904     )
14905         return;
14906
14907     /* Only one thing on the rhs */
14908     if (OpHAS_SIBLING(oright))
14909         return;
14910
14911     /* check the array is the same on both sides */
14912     if (oleft->op_type == OP_RV2AV) {
14913         if (oright->op_type != OP_RV2AV
14914             || !cUNOPx(oright)->op_first
14915             || cUNOPx(oright)->op_first->op_type != OP_GV
14916             || cUNOPx(oleft )->op_first->op_type != OP_GV
14917             || cGVOPx_gv(cUNOPx(oleft)->op_first) !=
14918                cGVOPx_gv(cUNOPx(oright)->op_first)
14919         )
14920             return;
14921     }
14922     else if (oright->op_type != OP_PADAV
14923         || oright->op_targ != oleft->op_targ
14924     )
14925         return;
14926
14927     /* This actually is an inplace assignment */
14928
14929     modop->op_private |= OPpSORT_INPLACE;
14930
14931     /* transfer MODishness etc from LHS arg to RHS arg */
14932     oright->op_flags = oleft->op_flags;
14933
14934     /* remove the aassign op and the lhs */
14935     op_null(o);
14936     op_null(oleft_pushmark);
14937     if (oleft->op_type == OP_RV2AV && cUNOPx(oleft)->op_first)
14938         op_null(cUNOPx(oleft)->op_first);
14939     op_null(oleft);
14940 }
14941
14942
14943
14944 /* S_maybe_multideref(): given an op_next chain of ops beginning at 'start'
14945  * that potentially represent a series of one or more aggregate derefs
14946  * (such as $a->[1]{$key}), examine the chain, and if appropriate, convert
14947  * the whole chain to a single OP_MULTIDEREF op (maybe with a few
14948  * additional ops left in too).
14949  *
14950  * The caller will have already verified that the first few ops in the
14951  * chain following 'start' indicate a multideref candidate, and will have
14952  * set 'orig_o' to the point further on in the chain where the first index
14953  * expression (if any) begins.  'orig_action' specifies what type of
14954  * beginning has already been determined by the ops between start..orig_o
14955  * (e.g.  $lex_ary[], $pkg_ary->{}, expr->[], etc).
14956  *
14957  * 'hints' contains any hints flags that need adding (currently just
14958  * OPpHINT_STRICT_REFS) as found in any rv2av/hv skipped by the caller.
14959  */
14960
14961 STATIC void
14962 S_maybe_multideref(pTHX_ OP *start, OP *orig_o, UV orig_action, U8 hints)
14963 {
14964     dVAR;
14965     int pass;
14966     UNOP_AUX_item *arg_buf = NULL;
14967     bool reset_start_targ  = FALSE; /* start->op_targ needs zeroing */
14968     int index_skip         = -1;    /* don't output index arg on this action */
14969
14970     /* similar to regex compiling, do two passes; the first pass
14971      * determines whether the op chain is convertible and calculates the
14972      * buffer size; the second pass populates the buffer and makes any
14973      * changes necessary to ops (such as moving consts to the pad on
14974      * threaded builds).
14975      *
14976      * NB: for things like Coverity, note that both passes take the same
14977      * path through the logic tree (except for 'if (pass)' bits), since
14978      * both passes are following the same op_next chain; and in
14979      * particular, if it would return early on the second pass, it would
14980      * already have returned early on the first pass.
14981      */
14982     for (pass = 0; pass < 2; pass++) {
14983         OP *o                = orig_o;
14984         UV action            = orig_action;
14985         OP *first_elem_op    = NULL;  /* first seen aelem/helem */
14986         OP *top_op           = NULL;  /* highest [ah]elem/exists/del/rv2[ah]v */
14987         int action_count     = 0;     /* number of actions seen so far */
14988         int action_ix        = 0;     /* action_count % (actions per IV) */
14989         bool next_is_hash    = FALSE; /* is the next lookup to be a hash? */
14990         bool is_last         = FALSE; /* no more derefs to follow */
14991         bool maybe_aelemfast = FALSE; /* we can replace with aelemfast? */
14992         UNOP_AUX_item *arg     = arg_buf;
14993         UNOP_AUX_item *action_ptr = arg_buf;
14994
14995         if (pass)
14996             action_ptr->uv = 0;
14997         arg++;
14998
14999         switch (action) {
15000         case MDEREF_HV_gvsv_vivify_rv2hv_helem:
15001         case MDEREF_HV_gvhv_helem:
15002             next_is_hash = TRUE;
15003             /* FALLTHROUGH */
15004         case MDEREF_AV_gvsv_vivify_rv2av_aelem:
15005         case MDEREF_AV_gvav_aelem:
15006             if (pass) {
15007 #ifdef USE_ITHREADS
15008                 arg->pad_offset = cPADOPx(start)->op_padix;
15009                 /* stop it being swiped when nulled */
15010                 cPADOPx(start)->op_padix = 0;
15011 #else
15012                 arg->sv = cSVOPx(start)->op_sv;
15013                 cSVOPx(start)->op_sv = NULL;
15014 #endif
15015             }
15016             arg++;
15017             break;
15018
15019         case MDEREF_HV_padhv_helem:
15020         case MDEREF_HV_padsv_vivify_rv2hv_helem:
15021             next_is_hash = TRUE;
15022             /* FALLTHROUGH */
15023         case MDEREF_AV_padav_aelem:
15024         case MDEREF_AV_padsv_vivify_rv2av_aelem:
15025             if (pass) {
15026                 arg->pad_offset = start->op_targ;
15027                 /* we skip setting op_targ = 0 for now, since the intact
15028                  * OP_PADXV is needed by S_check_hash_fields_and_hekify */
15029                 reset_start_targ = TRUE;
15030             }
15031             arg++;
15032             break;
15033
15034         case MDEREF_HV_pop_rv2hv_helem:
15035             next_is_hash = TRUE;
15036             /* FALLTHROUGH */
15037         case MDEREF_AV_pop_rv2av_aelem:
15038             break;
15039
15040         default:
15041             NOT_REACHED; /* NOTREACHED */
15042             return;
15043         }
15044
15045         while (!is_last) {
15046             /* look for another (rv2av/hv; get index;
15047              * aelem/helem/exists/delele) sequence */
15048
15049             OP *kid;
15050             bool is_deref;
15051             bool ok;
15052             UV index_type = MDEREF_INDEX_none;
15053
15054             if (action_count) {
15055                 /* if this is not the first lookup, consume the rv2av/hv  */
15056
15057                 /* for N levels of aggregate lookup, we normally expect
15058                  * that the first N-1 [ah]elem ops will be flagged as
15059                  * /DEREF (so they autovivifiy if necessary), and the last
15060                  * lookup op not to be.
15061                  * For other things (like @{$h{k1}{k2}}) extra scope or
15062                  * leave ops can appear, so abandon the effort in that
15063                  * case */
15064                 if (o->op_type != OP_RV2AV && o->op_type != OP_RV2HV)
15065                     return;
15066
15067                 /* rv2av or rv2hv sKR/1 */
15068
15069                 ASSUME(!(o->op_flags & ~(OPf_WANT|OPf_KIDS|OPf_PARENS
15070                                             |OPf_REF|OPf_MOD|OPf_SPECIAL)));
15071                 if (o->op_flags != (OPf_WANT_SCALAR|OPf_KIDS|OPf_REF))
15072                     return;
15073
15074                 /* at this point, we wouldn't expect any of these
15075                  * possible private flags:
15076                  * OPpMAYBE_LVSUB, OPpOUR_INTRO, OPpLVAL_INTRO
15077                  * OPpTRUEBOOL, OPpMAYBE_TRUEBOOL (rv2hv only)
15078                  */
15079                 ASSUME(!(o->op_private &
15080                     ~(OPpHINT_STRICT_REFS|OPpARG1_MASK|OPpSLICEWARNING)));
15081
15082                 hints = (o->op_private & OPpHINT_STRICT_REFS);
15083
15084                 /* make sure the type of the previous /DEREF matches the
15085                  * type of the next lookup */
15086                 ASSUME(o->op_type == (next_is_hash ? OP_RV2HV : OP_RV2AV));
15087                 top_op = o;
15088
15089                 action = next_is_hash
15090                             ? MDEREF_HV_vivify_rv2hv_helem
15091                             : MDEREF_AV_vivify_rv2av_aelem;
15092                 o = o->op_next;
15093             }
15094
15095             /* if this is the second pass, and we're at the depth where
15096              * previously we encountered a non-simple index expression,
15097              * stop processing the index at this point */
15098             if (action_count != index_skip) {
15099
15100                 /* look for one or more simple ops that return an array
15101                  * index or hash key */
15102
15103                 switch (o->op_type) {
15104                 case OP_PADSV:
15105                     /* it may be a lexical var index */
15106                     ASSUME(!(o->op_flags & ~(OPf_WANT|OPf_PARENS
15107                                             |OPf_REF|OPf_MOD|OPf_SPECIAL)));
15108                     ASSUME(!(o->op_private &
15109                             ~(OPpPAD_STATE|OPpDEREF|OPpLVAL_INTRO)));
15110
15111                     if (   OP_GIMME(o,0) == G_SCALAR
15112                         && !(o->op_flags & (OPf_REF|OPf_MOD))
15113                         && o->op_private == 0)
15114                     {
15115                         if (pass)
15116                             arg->pad_offset = o->op_targ;
15117                         arg++;
15118                         index_type = MDEREF_INDEX_padsv;
15119                         o = o->op_next;
15120                     }
15121                     break;
15122
15123                 case OP_CONST:
15124                     if (next_is_hash) {
15125                         /* it's a constant hash index */
15126                         if (!(SvFLAGS(cSVOPo_sv) & (SVf_IOK|SVf_NOK|SVf_POK)))
15127                             /* "use constant foo => FOO; $h{+foo}" for
15128                              * some weird FOO, can leave you with constants
15129                              * that aren't simple strings. It's not worth
15130                              * the extra hassle for those edge cases */
15131                             break;
15132
15133                         {
15134                             UNOP *rop = NULL;
15135                             OP * helem_op = o->op_next;
15136
15137                             ASSUME(   helem_op->op_type == OP_HELEM
15138                                    || helem_op->op_type == OP_NULL
15139                                    || pass == 0);
15140                             if (helem_op->op_type == OP_HELEM) {
15141                                 rop = (UNOP*)(((BINOP*)helem_op)->op_first);
15142                                 if (   helem_op->op_private & OPpLVAL_INTRO
15143                                     || rop->op_type != OP_RV2HV
15144                                 )
15145                                     rop = NULL;
15146                             }
15147                             /* on first pass just check; on second pass
15148                              * hekify */
15149                             S_check_hash_fields_and_hekify(aTHX_ rop, cSVOPo,
15150                                                             pass);
15151                         }
15152
15153                         if (pass) {
15154 #ifdef USE_ITHREADS
15155                             /* Relocate sv to the pad for thread safety */
15156                             op_relocate_sv(&cSVOPo->op_sv, &o->op_targ);
15157                             arg->pad_offset = o->op_targ;
15158                             o->op_targ = 0;
15159 #else
15160                             arg->sv = cSVOPx_sv(o);
15161 #endif
15162                         }
15163                     }
15164                     else {
15165                         /* it's a constant array index */
15166                         IV iv;
15167                         SV *ix_sv = cSVOPo->op_sv;
15168                         if (!SvIOK(ix_sv))
15169                             break;
15170                         iv = SvIV(ix_sv);
15171
15172                         if (   action_count == 0
15173                             && iv >= -128
15174                             && iv <= 127
15175                             && (   action == MDEREF_AV_padav_aelem
15176                                 || action == MDEREF_AV_gvav_aelem)
15177                         )
15178                             maybe_aelemfast = TRUE;
15179
15180                         if (pass) {
15181                             arg->iv = iv;
15182                             SvREFCNT_dec_NN(cSVOPo->op_sv);
15183                         }
15184                     }
15185                     if (pass)
15186                         /* we've taken ownership of the SV */
15187                         cSVOPo->op_sv = NULL;
15188                     arg++;
15189                     index_type = MDEREF_INDEX_const;
15190                     o = o->op_next;
15191                     break;
15192
15193                 case OP_GV:
15194                     /* it may be a package var index */
15195
15196                     ASSUME(!(o->op_flags & ~(OPf_WANT|OPf_PARENS|OPf_SPECIAL)));
15197                     ASSUME(!(o->op_private & ~(OPpEARLY_CV)));
15198                     if (  (o->op_flags & ~(OPf_PARENS|OPf_SPECIAL)) != OPf_WANT_SCALAR
15199                         || o->op_private != 0
15200                     )
15201                         break;
15202
15203                     kid = o->op_next;
15204                     if (kid->op_type != OP_RV2SV)
15205                         break;
15206
15207                     ASSUME(!(kid->op_flags &
15208                             ~(OPf_WANT|OPf_KIDS|OPf_MOD|OPf_REF
15209                              |OPf_SPECIAL|OPf_PARENS)));
15210                     ASSUME(!(kid->op_private &
15211                                     ~(OPpARG1_MASK
15212                                      |OPpHINT_STRICT_REFS|OPpOUR_INTRO
15213                                      |OPpDEREF|OPpLVAL_INTRO)));
15214                     if(   (kid->op_flags &~ OPf_PARENS)
15215                             != (OPf_WANT_SCALAR|OPf_KIDS)
15216                        || (kid->op_private & ~(OPpARG1_MASK|HINT_STRICT_REFS))
15217                     )
15218                         break;
15219
15220                     if (pass) {
15221 #ifdef USE_ITHREADS
15222                         arg->pad_offset = cPADOPx(o)->op_padix;
15223                         /* stop it being swiped when nulled */
15224                         cPADOPx(o)->op_padix = 0;
15225 #else
15226                         arg->sv = cSVOPx(o)->op_sv;
15227                         cSVOPo->op_sv = NULL;
15228 #endif
15229                     }
15230                     arg++;
15231                     index_type = MDEREF_INDEX_gvsv;
15232                     o = kid->op_next;
15233                     break;
15234
15235                 } /* switch */
15236             } /* action_count != index_skip */
15237
15238             action |= index_type;
15239
15240
15241             /* at this point we have either:
15242              *   * detected what looks like a simple index expression,
15243              *     and expect the next op to be an [ah]elem, or
15244              *     an nulled  [ah]elem followed by a delete or exists;
15245              *  * found a more complex expression, so something other
15246              *    than the above follows.
15247              */
15248
15249             /* possibly an optimised away [ah]elem (where op_next is
15250              * exists or delete) */
15251             if (o->op_type == OP_NULL)
15252                 o = o->op_next;
15253
15254             /* at this point we're looking for an OP_AELEM, OP_HELEM,
15255              * OP_EXISTS or OP_DELETE */
15256
15257             /* if a custom array/hash access checker is in scope,
15258              * abandon optimisation attempt */
15259             if (  (o->op_type == OP_AELEM || o->op_type == OP_HELEM)
15260                && PL_check[o->op_type] != Perl_ck_null)
15261                 return;
15262             /* similarly for customised exists and delete */
15263             if (  (o->op_type == OP_EXISTS)
15264                && PL_check[o->op_type] != Perl_ck_exists)
15265                 return;
15266             if (  (o->op_type == OP_DELETE)
15267                && PL_check[o->op_type] != Perl_ck_delete)
15268                 return;
15269
15270             if (   o->op_type != OP_AELEM
15271                 || (o->op_private &
15272                       (OPpLVAL_INTRO|OPpLVAL_DEFER|OPpDEREF|OPpMAYBE_LVSUB))
15273                 )
15274                 maybe_aelemfast = FALSE;
15275
15276             /* look for aelem/helem/exists/delete. If it's not the last elem
15277              * lookup, it *must* have OPpDEREF_AV/HV, but not many other
15278              * flags; if it's the last, then it mustn't have
15279              * OPpDEREF_AV/HV, but may have lots of other flags, like
15280              * OPpLVAL_INTRO etc
15281              */
15282
15283             if (   index_type == MDEREF_INDEX_none
15284                 || (   o->op_type != OP_AELEM  && o->op_type != OP_HELEM
15285                     && o->op_type != OP_EXISTS && o->op_type != OP_DELETE)
15286             )
15287                 ok = FALSE;
15288             else {
15289                 /* we have aelem/helem/exists/delete with valid simple index */
15290
15291                 is_deref =    (o->op_type == OP_AELEM || o->op_type == OP_HELEM)
15292                            && (   (o->op_private & OPpDEREF) == OPpDEREF_AV
15293                                || (o->op_private & OPpDEREF) == OPpDEREF_HV);
15294
15295                 /* This doesn't make much sense but is legal:
15296                  *    @{ local $x[0][0] } = 1
15297                  * Since scope exit will undo the autovivification,
15298                  * don't bother in the first place. The OP_LEAVE
15299                  * assertion is in case there are other cases of both
15300                  * OPpLVAL_INTRO and OPpDEREF which don't include a scope
15301                  * exit that would undo the local - in which case this
15302                  * block of code would need rethinking.
15303                  */
15304                 if (is_deref && (o->op_private & OPpLVAL_INTRO)) {
15305 #ifdef DEBUGGING
15306                     OP *n = o->op_next;
15307                     while (n && (  n->op_type == OP_NULL
15308                                 || n->op_type == OP_LIST
15309                                 || n->op_type == OP_SCALAR))
15310                         n = n->op_next;
15311                     assert(n && n->op_type == OP_LEAVE);
15312 #endif
15313                     o->op_private &= ~OPpDEREF;
15314                     is_deref = FALSE;
15315                 }
15316
15317                 if (is_deref) {
15318                     ASSUME(!(o->op_flags &
15319                                  ~(OPf_WANT|OPf_KIDS|OPf_MOD|OPf_PARENS)));
15320                     ASSUME(!(o->op_private & ~(OPpARG2_MASK|OPpDEREF)));
15321
15322                     ok =    (o->op_flags &~ OPf_PARENS)
15323                                == (OPf_WANT_SCALAR|OPf_KIDS|OPf_MOD)
15324                          && !(o->op_private & ~(OPpDEREF|OPpARG2_MASK));
15325                 }
15326                 else if (o->op_type == OP_EXISTS) {
15327                     ASSUME(!(o->op_flags & ~(OPf_WANT|OPf_KIDS|OPf_PARENS
15328                                 |OPf_REF|OPf_MOD|OPf_SPECIAL)));
15329                     ASSUME(!(o->op_private & ~(OPpARG1_MASK|OPpEXISTS_SUB)));
15330                     ok =  !(o->op_private & ~OPpARG1_MASK);
15331                 }
15332                 else if (o->op_type == OP_DELETE) {
15333                     ASSUME(!(o->op_flags & ~(OPf_WANT|OPf_KIDS|OPf_PARENS
15334                                 |OPf_REF|OPf_MOD|OPf_SPECIAL)));
15335                     ASSUME(!(o->op_private &
15336                                     ~(OPpARG1_MASK|OPpSLICE|OPpLVAL_INTRO)));
15337                     /* don't handle slices or 'local delete'; the latter
15338                      * is fairly rare, and has a complex runtime */
15339                     ok =  !(o->op_private & ~OPpARG1_MASK);
15340                     if (OP_TYPE_IS_OR_WAS(cUNOPo->op_first, OP_AELEM))
15341                         /* skip handling run-tome error */
15342                         ok = (ok && cBOOL(o->op_flags & OPf_SPECIAL));
15343                 }
15344                 else {
15345                     ASSUME(o->op_type == OP_AELEM || o->op_type == OP_HELEM);
15346                     ASSUME(!(o->op_flags & ~(OPf_WANT|OPf_KIDS|OPf_MOD
15347                                             |OPf_PARENS|OPf_REF|OPf_SPECIAL)));
15348                     ASSUME(!(o->op_private & ~(OPpARG2_MASK|OPpMAYBE_LVSUB
15349                                     |OPpLVAL_DEFER|OPpDEREF|OPpLVAL_INTRO)));
15350                     ok = (o->op_private & OPpDEREF) != OPpDEREF_SV;
15351                 }
15352             }
15353
15354             if (ok) {
15355                 if (!first_elem_op)
15356                     first_elem_op = o;
15357                 top_op = o;
15358                 if (is_deref) {
15359                     next_is_hash = cBOOL((o->op_private & OPpDEREF) == OPpDEREF_HV);
15360                     o = o->op_next;
15361                 }
15362                 else {
15363                     is_last = TRUE;
15364                     action |= MDEREF_FLAG_last;
15365                 }
15366             }
15367             else {
15368                 /* at this point we have something that started
15369                  * promisingly enough (with rv2av or whatever), but failed
15370                  * to find a simple index followed by an
15371                  * aelem/helem/exists/delete. If this is the first action,
15372                  * give up; but if we've already seen at least one
15373                  * aelem/helem, then keep them and add a new action with
15374                  * MDEREF_INDEX_none, which causes it to do the vivify
15375                  * from the end of the previous lookup, and do the deref,
15376                  * but stop at that point. So $a[0][expr] will do one
15377                  * av_fetch, vivify and deref, then continue executing at
15378                  * expr */
15379                 if (!action_count)
15380                     return;
15381                 is_last = TRUE;
15382                 index_skip = action_count;
15383                 action |= MDEREF_FLAG_last;
15384                 if (index_type != MDEREF_INDEX_none)
15385                     arg--;
15386             }
15387
15388             if (pass)
15389                 action_ptr->uv |= (action << (action_ix * MDEREF_SHIFT));
15390             action_ix++;
15391             action_count++;
15392             /* if there's no space for the next action, create a new slot
15393              * for it *before* we start adding args for that action */
15394             if ((action_ix + 1) * MDEREF_SHIFT > UVSIZE*8) {
15395                 action_ptr = arg;
15396                 if (pass)
15397                     arg->uv = 0;
15398                 arg++;
15399                 action_ix = 0;
15400             }
15401         } /* while !is_last */
15402
15403         /* success! */
15404
15405         if (pass) {
15406             OP *mderef;
15407             OP *p, *q;
15408
15409             mderef = newUNOP_AUX(OP_MULTIDEREF, 0, NULL, arg_buf);
15410             if (index_skip == -1) {
15411                 mderef->op_flags = o->op_flags
15412                         & (OPf_WANT|OPf_MOD|(next_is_hash ? OPf_SPECIAL : 0));
15413                 if (o->op_type == OP_EXISTS)
15414                     mderef->op_private = OPpMULTIDEREF_EXISTS;
15415                 else if (o->op_type == OP_DELETE)
15416                     mderef->op_private = OPpMULTIDEREF_DELETE;
15417                 else
15418                     mderef->op_private = o->op_private
15419                         & (OPpMAYBE_LVSUB|OPpLVAL_DEFER|OPpLVAL_INTRO);
15420             }
15421             /* accumulate strictness from every level (although I don't think
15422              * they can actually vary) */
15423             mderef->op_private |= hints;
15424
15425             /* integrate the new multideref op into the optree and the
15426              * op_next chain.
15427              *
15428              * In general an op like aelem or helem has two child
15429              * sub-trees: the aggregate expression (a_expr) and the
15430              * index expression (i_expr):
15431              *
15432              *     aelem
15433              *       |
15434              *     a_expr - i_expr
15435              *
15436              * The a_expr returns an AV or HV, while the i-expr returns an
15437              * index. In general a multideref replaces most or all of a
15438              * multi-level tree, e.g.
15439              *
15440              *     exists
15441              *       |
15442              *     ex-aelem
15443              *       |
15444              *     rv2av  - i_expr1
15445              *       |
15446              *     helem
15447              *       |
15448              *     rv2hv  - i_expr2
15449              *       |
15450              *     aelem
15451              *       |
15452              *     a_expr - i_expr3
15453              *
15454              * With multideref, all the i_exprs will be simple vars or
15455              * constants, except that i_expr1 may be arbitrary in the case
15456              * of MDEREF_INDEX_none.
15457              *
15458              * The bottom-most a_expr will be either:
15459              *   1) a simple var (so padXv or gv+rv2Xv);
15460              *   2) a simple scalar var dereferenced (e.g. $r->[0]):
15461              *      so a simple var with an extra rv2Xv;
15462              *   3) or an arbitrary expression.
15463              *
15464              * 'start', the first op in the execution chain, will point to
15465              *   1),2): the padXv or gv op;
15466              *   3):    the rv2Xv which forms the last op in the a_expr
15467              *          execution chain, and the top-most op in the a_expr
15468              *          subtree.
15469              *
15470              * For all cases, the 'start' node is no longer required,
15471              * but we can't free it since one or more external nodes
15472              * may point to it. E.g. consider
15473              *     $h{foo} = $a ? $b : $c
15474              * Here, both the op_next and op_other branches of the
15475              * cond_expr point to the gv[*h] of the hash expression, so
15476              * we can't free the 'start' op.
15477              *
15478              * For expr->[...], we need to save the subtree containing the
15479              * expression; for the other cases, we just need to save the
15480              * start node.
15481              * So in all cases, we null the start op and keep it around by
15482              * making it the child of the multideref op; for the expr->
15483              * case, the expr will be a subtree of the start node.
15484              *
15485              * So in the simple 1,2 case the  optree above changes to
15486              *
15487              *     ex-exists
15488              *       |
15489              *     multideref
15490              *       |
15491              *     ex-gv (or ex-padxv)
15492              *
15493              *  with the op_next chain being
15494              *
15495              *  -> ex-gv -> multideref -> op-following-ex-exists ->
15496              *
15497              *  In the 3 case, we have
15498              *
15499              *     ex-exists
15500              *       |
15501              *     multideref
15502              *       |
15503              *     ex-rv2xv
15504              *       |
15505              *    rest-of-a_expr
15506              *      subtree
15507              *
15508              *  and
15509              *
15510              *  -> rest-of-a_expr subtree ->
15511              *    ex-rv2xv -> multideref -> op-following-ex-exists ->
15512              *
15513              *
15514              * Where the last i_expr is non-simple (i.e. MDEREF_INDEX_none,
15515              * e.g. $a[0]{foo}[$x+1], the next rv2xv is nulled and the
15516              * multideref attached as the child, e.g.
15517              *
15518              *     exists
15519              *       |
15520              *     ex-aelem
15521              *       |
15522              *     ex-rv2av  - i_expr1
15523              *       |
15524              *     multideref
15525              *       |
15526              *     ex-whatever
15527              *
15528              */
15529
15530             /* if we free this op, don't free the pad entry */
15531             if (reset_start_targ)
15532                 start->op_targ = 0;
15533
15534
15535             /* Cut the bit we need to save out of the tree and attach to
15536              * the multideref op, then free the rest of the tree */
15537
15538             /* find parent of node to be detached (for use by splice) */
15539             p = first_elem_op;
15540             if (   orig_action == MDEREF_AV_pop_rv2av_aelem
15541                 || orig_action == MDEREF_HV_pop_rv2hv_helem)
15542             {
15543                 /* there is an arbitrary expression preceding us, e.g.
15544                  * expr->[..]? so we need to save the 'expr' subtree */
15545                 if (p->op_type == OP_EXISTS || p->op_type == OP_DELETE)
15546                     p = cUNOPx(p)->op_first;
15547                 ASSUME(   start->op_type == OP_RV2AV
15548                        || start->op_type == OP_RV2HV);
15549             }
15550             else {
15551                 /* either a padXv or rv2Xv+gv, maybe with an ex-Xelem
15552                  * above for exists/delete. */
15553                 while (   (p->op_flags & OPf_KIDS)
15554                        && cUNOPx(p)->op_first != start
15555                 )
15556                     p = cUNOPx(p)->op_first;
15557             }
15558             ASSUME(cUNOPx(p)->op_first == start);
15559
15560             /* detach from main tree, and re-attach under the multideref */
15561             op_sibling_splice(mderef, NULL, 0,
15562                     op_sibling_splice(p, NULL, 1, NULL));
15563             op_null(start);
15564
15565             start->op_next = mderef;
15566
15567             mderef->op_next = index_skip == -1 ? o->op_next : o;
15568
15569             /* excise and free the original tree, and replace with
15570              * the multideref op */
15571             p = op_sibling_splice(top_op, NULL, -1, mderef);
15572             while (p) {
15573                 q = OpSIBLING(p);
15574                 op_free(p);
15575                 p = q;
15576             }
15577             op_null(top_op);
15578         }
15579         else {
15580             Size_t size = arg - arg_buf;
15581
15582             if (maybe_aelemfast && action_count == 1)
15583                 return;
15584
15585             arg_buf = (UNOP_AUX_item*)PerlMemShared_malloc(
15586                                 sizeof(UNOP_AUX_item) * (size + 1));
15587             /* for dumping etc: store the length in a hidden first slot;
15588              * we set the op_aux pointer to the second slot */
15589             arg_buf->uv = size;
15590             arg_buf++;
15591         }
15592     } /* for (pass = ...) */
15593 }
15594
15595 /* See if the ops following o are such that o will always be executed in
15596  * boolean context: that is, the SV which o pushes onto the stack will
15597  * only ever be consumed by later ops via SvTRUE(sv) or similar.
15598  * If so, set a suitable private flag on o. Normally this will be
15599  * bool_flag; but see below why maybe_flag is needed too.
15600  *
15601  * Typically the two flags you pass will be the generic OPpTRUEBOOL and
15602  * OPpMAYBE_TRUEBOOL, buts it's possible that for some ops those bits may
15603  * already be taken, so you'll have to give that op two different flags.
15604  *
15605  * More explanation of 'maybe_flag' and 'safe_and' parameters.
15606  * The binary logical ops &&, ||, // (plus 'if' and 'unless' which use
15607  * those underlying ops) short-circuit, which means that rather than
15608  * necessarily returning a truth value, they may return the LH argument,
15609  * which may not be boolean. For example in $x = (keys %h || -1), keys
15610  * should return a key count rather than a boolean, even though its
15611  * sort-of being used in boolean context.
15612  *
15613  * So we only consider such logical ops to provide boolean context to
15614  * their LH argument if they themselves are in void or boolean context.
15615  * However, sometimes the context isn't known until run-time. In this
15616  * case the op is marked with the maybe_flag flag it.
15617  *
15618  * Consider the following.
15619  *
15620  *     sub f { ....;  if (%h) { .... } }
15621  *
15622  * This is actually compiled as
15623  *
15624  *     sub f { ....;  %h && do { .... } }
15625  *
15626  * Here we won't know until runtime whether the final statement (and hence
15627  * the &&) is in void context and so is safe to return a boolean value.
15628  * So mark o with maybe_flag rather than the bool_flag.
15629  * Note that there is cost associated with determining context at runtime
15630  * (e.g. a call to block_gimme()), so it may not be worth setting (at
15631  * compile time) and testing (at runtime) maybe_flag if the scalar verses
15632  * boolean costs savings are marginal.
15633  *
15634  * However, we can do slightly better with && (compared to || and //):
15635  * this op only returns its LH argument when that argument is false. In
15636  * this case, as long as the op promises to return a false value which is
15637  * valid in both boolean and scalar contexts, we can mark an op consumed
15638  * by && with bool_flag rather than maybe_flag.
15639  * For example as long as pp_padhv and pp_rv2hv return &PL_sv_zero rather
15640  * than &PL_sv_no for a false result in boolean context, then it's safe. An
15641  * op which promises to handle this case is indicated by setting safe_and
15642  * to true.
15643  */
15644
15645 static void
15646 S_check_for_bool_cxt(OP*o, bool safe_and, U8 bool_flag, U8 maybe_flag)
15647 {
15648     OP *lop;
15649     U8 flag = 0;
15650
15651     assert((o->op_flags & OPf_WANT) == OPf_WANT_SCALAR);
15652
15653     /* OPpTARGET_MY and boolean context probably don't mix well.
15654      * If someone finds a valid use case, maybe add an extra flag to this
15655      * function which indicates its safe to do so for this op? */
15656     assert(!(   (PL_opargs[o->op_type] & OA_TARGLEX)
15657              && (o->op_private & OPpTARGET_MY)));
15658
15659     lop = o->op_next;
15660
15661     while (lop) {
15662         switch (lop->op_type) {
15663         case OP_NULL:
15664         case OP_SCALAR:
15665             break;
15666
15667         /* these two consume the stack argument in the scalar case,
15668          * and treat it as a boolean in the non linenumber case */
15669         case OP_FLIP:
15670         case OP_FLOP:
15671             if (   ((lop->op_flags & OPf_WANT) == OPf_WANT_LIST)
15672                 || (lop->op_private & OPpFLIP_LINENUM))
15673             {
15674                 lop = NULL;
15675                 break;
15676             }
15677             /* FALLTHROUGH */
15678         /* these never leave the original value on the stack */
15679         case OP_NOT:
15680         case OP_XOR:
15681         case OP_COND_EXPR:
15682         case OP_GREPWHILE:
15683             flag = bool_flag;
15684             lop = NULL;
15685             break;
15686
15687         /* OR DOR and AND evaluate their arg as a boolean, but then may
15688          * leave the original scalar value on the stack when following the
15689          * op_next route. If not in void context, we need to ensure
15690          * that whatever follows consumes the arg only in boolean context
15691          * too.
15692          */
15693         case OP_AND:
15694             if (safe_and) {
15695                 flag = bool_flag;
15696                 lop = NULL;
15697                 break;
15698             }
15699             /* FALLTHROUGH */
15700         case OP_OR:
15701         case OP_DOR:
15702             if ((lop->op_flags & OPf_WANT) == OPf_WANT_VOID) {
15703                 flag = bool_flag;
15704                 lop = NULL;
15705             }
15706             else if (!(lop->op_flags & OPf_WANT)) {
15707                 /* unknown context - decide at runtime */
15708                 flag = maybe_flag;
15709                 lop = NULL;
15710             }
15711             break;
15712
15713         default:
15714             lop = NULL;
15715             break;
15716         }
15717
15718         if (lop)
15719             lop = lop->op_next;
15720     }
15721
15722     o->op_private |= flag;
15723 }
15724
15725
15726
15727 /* mechanism for deferring recursion in rpeep() */
15728
15729 #define MAX_DEFERRED 4
15730
15731 #define DEFER(o) \
15732   STMT_START { \
15733     if (defer_ix == (MAX_DEFERRED-1)) { \
15734         OP **defer = defer_queue[defer_base]; \
15735         CALL_RPEEP(*defer); \
15736         S_prune_chain_head(defer); \
15737         defer_base = (defer_base + 1) % MAX_DEFERRED; \
15738         defer_ix--; \
15739     } \
15740     defer_queue[(defer_base + ++defer_ix) % MAX_DEFERRED] = &(o); \
15741   } STMT_END
15742
15743 #define IS_AND_OP(o)   (o->op_type == OP_AND)
15744 #define IS_OR_OP(o)    (o->op_type == OP_OR)
15745
15746
15747 /* A peephole optimizer.  We visit the ops in the order they're to execute.
15748  * See the comments at the top of this file for more details about when
15749  * peep() is called */
15750
15751 void
15752 Perl_rpeep(pTHX_ OP *o)
15753 {
15754     dVAR;
15755     OP* oldop = NULL;
15756     OP* oldoldop = NULL;
15757     OP** defer_queue[MAX_DEFERRED]; /* small queue of deferred branches */
15758     int defer_base = 0;
15759     int defer_ix = -1;
15760
15761     if (!o || o->op_opt)
15762         return;
15763
15764     assert(o->op_type != OP_FREED);
15765
15766     ENTER;
15767     SAVEOP();
15768     SAVEVPTR(PL_curcop);
15769     for (;; o = o->op_next) {
15770         if (o && o->op_opt)
15771             o = NULL;
15772         if (!o) {
15773             while (defer_ix >= 0) {
15774                 OP **defer =
15775                         defer_queue[(defer_base + defer_ix--) % MAX_DEFERRED];
15776                 CALL_RPEEP(*defer);
15777                 S_prune_chain_head(defer);
15778             }
15779             break;
15780         }
15781
15782       redo:
15783
15784         /* oldoldop -> oldop -> o should be a chain of 3 adjacent ops */
15785         assert(!oldoldop || oldoldop->op_next == oldop);
15786         assert(!oldop    || oldop->op_next    == o);
15787
15788         /* By default, this op has now been optimised. A couple of cases below
15789            clear this again.  */
15790         o->op_opt = 1;
15791         PL_op = o;
15792
15793         /* look for a series of 1 or more aggregate derefs, e.g.
15794          *   $a[1]{foo}[$i]{$k}
15795          * and replace with a single OP_MULTIDEREF op.
15796          * Each index must be either a const, or a simple variable,
15797          *
15798          * First, look for likely combinations of starting ops,
15799          * corresponding to (global and lexical variants of)
15800          *     $a[...]   $h{...}
15801          *     $r->[...] $r->{...}
15802          *     (preceding expression)->[...]
15803          *     (preceding expression)->{...}
15804          * and if so, call maybe_multideref() to do a full inspection
15805          * of the op chain and if appropriate, replace with an
15806          * OP_MULTIDEREF
15807          */
15808         {
15809             UV action;
15810             OP *o2 = o;
15811             U8 hints = 0;
15812
15813             switch (o2->op_type) {
15814             case OP_GV:
15815                 /* $pkg[..]   :   gv[*pkg]
15816                  * $pkg->[...]:   gv[*pkg]; rv2sv sKM/DREFAV */
15817
15818                 /* Fail if there are new op flag combinations that we're
15819                  * not aware of, rather than:
15820                  *  * silently failing to optimise, or
15821                  *  * silently optimising the flag away.
15822                  * If this ASSUME starts failing, examine what new flag
15823                  * has been added to the op, and decide whether the
15824                  * optimisation should still occur with that flag, then
15825                  * update the code accordingly. This applies to all the
15826                  * other ASSUMEs in the block of code too.
15827                  */
15828                 ASSUME(!(o2->op_flags &
15829                             ~(OPf_WANT|OPf_MOD|OPf_PARENS|OPf_SPECIAL)));
15830                 ASSUME(!(o2->op_private & ~OPpEARLY_CV));
15831
15832                 o2 = o2->op_next;
15833
15834                 if (o2->op_type == OP_RV2AV) {
15835                     action = MDEREF_AV_gvav_aelem;
15836                     goto do_deref;
15837                 }
15838
15839                 if (o2->op_type == OP_RV2HV) {
15840                     action = MDEREF_HV_gvhv_helem;
15841                     goto do_deref;
15842                 }
15843
15844                 if (o2->op_type != OP_RV2SV)
15845                     break;
15846
15847                 /* at this point we've seen gv,rv2sv, so the only valid
15848                  * construct left is $pkg->[] or $pkg->{} */
15849
15850                 ASSUME(!(o2->op_flags & OPf_STACKED));
15851                 if ((o2->op_flags & (OPf_WANT|OPf_REF|OPf_MOD|OPf_SPECIAL))
15852                             != (OPf_WANT_SCALAR|OPf_MOD))
15853                     break;
15854
15855                 ASSUME(!(o2->op_private & ~(OPpARG1_MASK|HINT_STRICT_REFS
15856                                     |OPpOUR_INTRO|OPpDEREF|OPpLVAL_INTRO)));
15857                 if (o2->op_private & (OPpOUR_INTRO|OPpLVAL_INTRO))
15858                     break;
15859                 if (   (o2->op_private & OPpDEREF) != OPpDEREF_AV
15860                     && (o2->op_private & OPpDEREF) != OPpDEREF_HV)
15861                     break;
15862
15863                 o2 = o2->op_next;
15864                 if (o2->op_type == OP_RV2AV) {
15865                     action = MDEREF_AV_gvsv_vivify_rv2av_aelem;
15866                     goto do_deref;
15867                 }
15868                 if (o2->op_type == OP_RV2HV) {
15869                     action = MDEREF_HV_gvsv_vivify_rv2hv_helem;
15870                     goto do_deref;
15871                 }
15872                 break;
15873
15874             case OP_PADSV:
15875                 /* $lex->[...]: padsv[$lex] sM/DREFAV */
15876
15877                 ASSUME(!(o2->op_flags &
15878                     ~(OPf_WANT|OPf_PARENS|OPf_REF|OPf_MOD|OPf_SPECIAL)));
15879                 if ((o2->op_flags &
15880                         (OPf_WANT|OPf_REF|OPf_MOD|OPf_SPECIAL))
15881                      != (OPf_WANT_SCALAR|OPf_MOD))
15882                     break;
15883
15884                 ASSUME(!(o2->op_private &
15885                                 ~(OPpPAD_STATE|OPpDEREF|OPpLVAL_INTRO)));
15886                 /* skip if state or intro, or not a deref */
15887                 if (      o2->op_private != OPpDEREF_AV
15888                        && o2->op_private != OPpDEREF_HV)
15889                     break;
15890
15891                 o2 = o2->op_next;
15892                 if (o2->op_type == OP_RV2AV) {
15893                     action = MDEREF_AV_padsv_vivify_rv2av_aelem;
15894                     goto do_deref;
15895                 }
15896                 if (o2->op_type == OP_RV2HV) {
15897                     action = MDEREF_HV_padsv_vivify_rv2hv_helem;
15898                     goto do_deref;
15899                 }
15900                 break;
15901
15902             case OP_PADAV:
15903             case OP_PADHV:
15904                 /*    $lex[..]:  padav[@lex:1,2] sR *
15905                  * or $lex{..}:  padhv[%lex:1,2] sR */
15906                 ASSUME(!(o2->op_flags & ~(OPf_WANT|OPf_MOD|OPf_PARENS|
15907                                             OPf_REF|OPf_SPECIAL)));
15908                 if ((o2->op_flags &
15909                         (OPf_WANT|OPf_REF|OPf_MOD|OPf_SPECIAL))
15910                      != (OPf_WANT_SCALAR|OPf_REF))
15911                     break;
15912                 if (o2->op_flags != (OPf_WANT_SCALAR|OPf_REF))
15913                     break;
15914                 /* OPf_PARENS isn't currently used in this case;
15915                  * if that changes, let us know! */
15916                 ASSUME(!(o2->op_flags & OPf_PARENS));
15917
15918                 /* at this point, we wouldn't expect any of the remaining
15919                  * possible private flags:
15920                  * OPpPAD_STATE, OPpLVAL_INTRO, OPpTRUEBOOL,
15921                  * OPpMAYBE_TRUEBOOL, OPpMAYBE_LVSUB
15922                  *
15923                  * OPpSLICEWARNING shouldn't affect runtime
15924                  */
15925                 ASSUME(!(o2->op_private & ~(OPpSLICEWARNING)));
15926
15927                 action = o2->op_type == OP_PADAV
15928                             ? MDEREF_AV_padav_aelem
15929                             : MDEREF_HV_padhv_helem;
15930                 o2 = o2->op_next;
15931                 S_maybe_multideref(aTHX_ o, o2, action, 0);
15932                 break;
15933
15934
15935             case OP_RV2AV:
15936             case OP_RV2HV:
15937                 action = o2->op_type == OP_RV2AV
15938                             ? MDEREF_AV_pop_rv2av_aelem
15939                             : MDEREF_HV_pop_rv2hv_helem;
15940                 /* FALLTHROUGH */
15941             do_deref:
15942                 /* (expr)->[...]:  rv2av sKR/1;
15943                  * (expr)->{...}:  rv2hv sKR/1; */
15944
15945                 ASSUME(o2->op_type == OP_RV2AV || o2->op_type == OP_RV2HV);
15946
15947                 ASSUME(!(o2->op_flags & ~(OPf_WANT|OPf_KIDS|OPf_PARENS
15948                                 |OPf_REF|OPf_MOD|OPf_STACKED|OPf_SPECIAL)));
15949                 if (o2->op_flags != (OPf_WANT_SCALAR|OPf_KIDS|OPf_REF))
15950                     break;
15951
15952                 /* at this point, we wouldn't expect any of these
15953                  * possible private flags:
15954                  * OPpMAYBE_LVSUB, OPpLVAL_INTRO
15955                  * OPpTRUEBOOL, OPpMAYBE_TRUEBOOL, (rv2hv only)
15956                  */
15957                 ASSUME(!(o2->op_private &
15958                     ~(OPpHINT_STRICT_REFS|OPpARG1_MASK|OPpSLICEWARNING
15959                      |OPpOUR_INTRO)));
15960                 hints |= (o2->op_private & OPpHINT_STRICT_REFS);
15961
15962                 o2 = o2->op_next;
15963
15964                 S_maybe_multideref(aTHX_ o, o2, action, hints);
15965                 break;
15966
15967             default:
15968                 break;
15969             }
15970         }
15971
15972
15973         switch (o->op_type) {
15974         case OP_DBSTATE:
15975             PL_curcop = ((COP*)o);              /* for warnings */
15976             break;
15977         case OP_NEXTSTATE:
15978             PL_curcop = ((COP*)o);              /* for warnings */
15979
15980             /* Optimise a "return ..." at the end of a sub to just be "...".
15981              * This saves 2 ops. Before:
15982              * 1  <;> nextstate(main 1 -e:1) v ->2
15983              * 4  <@> return K ->5
15984              * 2    <0> pushmark s ->3
15985              * -    <1> ex-rv2sv sK/1 ->4
15986              * 3      <#> gvsv[*cat] s ->4
15987              *
15988              * After:
15989              * -  <@> return K ->-
15990              * -    <0> pushmark s ->2
15991              * -    <1> ex-rv2sv sK/1 ->-
15992              * 2      <$> gvsv(*cat) s ->3
15993              */
15994             {
15995                 OP *next = o->op_next;
15996                 OP *sibling = OpSIBLING(o);
15997                 if (   OP_TYPE_IS(next, OP_PUSHMARK)
15998                     && OP_TYPE_IS(sibling, OP_RETURN)
15999                     && OP_TYPE_IS(sibling->op_next, OP_LINESEQ)
16000                     && ( OP_TYPE_IS(sibling->op_next->op_next, OP_LEAVESUB)
16001                        ||OP_TYPE_IS(sibling->op_next->op_next,
16002                                     OP_LEAVESUBLV))
16003                     && cUNOPx(sibling)->op_first == next
16004                     && OpHAS_SIBLING(next) && OpSIBLING(next)->op_next
16005                     && next->op_next
16006                 ) {
16007                     /* Look through the PUSHMARK's siblings for one that
16008                      * points to the RETURN */
16009                     OP *top = OpSIBLING(next);
16010                     while (top && top->op_next) {
16011                         if (top->op_next == sibling) {
16012                             top->op_next = sibling->op_next;
16013                             o->op_next = next->op_next;
16014                             break;
16015                         }
16016                         top = OpSIBLING(top);
16017                     }
16018                 }
16019             }
16020
16021             /* Optimise 'my $x; my $y;' into 'my ($x, $y);'
16022              *
16023              * This latter form is then suitable for conversion into padrange
16024              * later on. Convert:
16025              *
16026              *   nextstate1 -> padop1 -> nextstate2 -> padop2 -> nextstate3
16027              *
16028              * into:
16029              *
16030              *   nextstate1 ->     listop     -> nextstate3
16031              *                 /            \
16032              *         pushmark -> padop1 -> padop2
16033              */
16034             if (o->op_next && (
16035                     o->op_next->op_type == OP_PADSV
16036                  || o->op_next->op_type == OP_PADAV
16037                  || o->op_next->op_type == OP_PADHV
16038                 )
16039                 && !(o->op_next->op_private & ~OPpLVAL_INTRO)
16040                 && o->op_next->op_next && o->op_next->op_next->op_type == OP_NEXTSTATE
16041                 && o->op_next->op_next->op_next && (
16042                     o->op_next->op_next->op_next->op_type == OP_PADSV
16043                  || o->op_next->op_next->op_next->op_type == OP_PADAV
16044                  || o->op_next->op_next->op_next->op_type == OP_PADHV
16045                 )
16046                 && !(o->op_next->op_next->op_next->op_private & ~OPpLVAL_INTRO)
16047                 && o->op_next->op_next->op_next->op_next && o->op_next->op_next->op_next->op_next->op_type == OP_NEXTSTATE
16048                 && (!CopLABEL((COP*)o)) /* Don't mess with labels */
16049                 && (!CopLABEL((COP*)o->op_next->op_next)) /* ... */
16050             ) {
16051                 OP *pad1, *ns2, *pad2, *ns3, *newop, *newpm;
16052
16053                 pad1 =    o->op_next;
16054                 ns2  = pad1->op_next;
16055                 pad2 =  ns2->op_next;
16056                 ns3  = pad2->op_next;
16057
16058                 /* we assume here that the op_next chain is the same as
16059                  * the op_sibling chain */
16060                 assert(OpSIBLING(o)    == pad1);
16061                 assert(OpSIBLING(pad1) == ns2);
16062                 assert(OpSIBLING(ns2)  == pad2);
16063                 assert(OpSIBLING(pad2) == ns3);
16064
16065                 /* excise and delete ns2 */
16066                 op_sibling_splice(NULL, pad1, 1, NULL);
16067                 op_free(ns2);
16068
16069                 /* excise pad1 and pad2 */
16070                 op_sibling_splice(NULL, o, 2, NULL);
16071
16072                 /* create new listop, with children consisting of:
16073                  * a new pushmark, pad1, pad2. */
16074                 newop = newLISTOP(OP_LIST, 0, pad1, pad2);
16075                 newop->op_flags |= OPf_PARENS;
16076                 newop->op_flags = (newop->op_flags & ~OPf_WANT) | OPf_WANT_VOID;
16077
16078                 /* insert newop between o and ns3 */
16079                 op_sibling_splice(NULL, o, 0, newop);
16080
16081                 /*fixup op_next chain */
16082                 newpm = cUNOPx(newop)->op_first; /* pushmark */
16083                 o    ->op_next = newpm;
16084                 newpm->op_next = pad1;
16085                 pad1 ->op_next = pad2;
16086                 pad2 ->op_next = newop; /* listop */
16087                 newop->op_next = ns3;
16088
16089                 /* Ensure pushmark has this flag if padops do */
16090                 if (pad1->op_flags & OPf_MOD && pad2->op_flags & OPf_MOD) {
16091                     newpm->op_flags |= OPf_MOD;
16092                 }
16093
16094                 break;
16095             }
16096
16097             /* Two NEXTSTATEs in a row serve no purpose. Except if they happen
16098                to carry two labels. For now, take the easier option, and skip
16099                this optimisation if the first NEXTSTATE has a label.  */
16100             if (!CopLABEL((COP*)o) && !PERLDB_NOOPT) {
16101                 OP *nextop = o->op_next;
16102                 while (nextop) {
16103                     switch (nextop->op_type) {
16104                         case OP_NULL:
16105                         case OP_SCALAR:
16106                         case OP_LINESEQ:
16107                         case OP_SCOPE:
16108                             nextop = nextop->op_next;
16109                             continue;
16110                     }
16111                     break;
16112                 }
16113
16114                 if (nextop && (nextop->op_type == OP_NEXTSTATE)) {
16115                     op_null(o);
16116                     if (oldop)
16117                         oldop->op_next = nextop;
16118                     o = nextop;
16119                     /* Skip (old)oldop assignment since the current oldop's
16120                        op_next already points to the next op.  */
16121                     goto redo;
16122                 }
16123             }
16124             break;
16125
16126         case OP_CONCAT:
16127             if (o->op_next && o->op_next->op_type == OP_STRINGIFY) {
16128                 if (o->op_next->op_private & OPpTARGET_MY) {
16129                     if (o->op_flags & OPf_STACKED) /* chained concats */
16130                         break; /* ignore_optimization */
16131                     else {
16132                         /* assert(PL_opargs[o->op_type] & OA_TARGLEX); */
16133                         o->op_targ = o->op_next->op_targ;
16134                         o->op_next->op_targ = 0;
16135                         o->op_private |= OPpTARGET_MY;
16136                     }
16137                 }
16138                 op_null(o->op_next);
16139             }
16140             break;
16141         case OP_STUB:
16142             if ((o->op_flags & OPf_WANT) != OPf_WANT_LIST) {
16143                 break; /* Scalar stub must produce undef.  List stub is noop */
16144             }
16145             goto nothin;
16146         case OP_NULL:
16147             if (o->op_targ == OP_NEXTSTATE
16148                 || o->op_targ == OP_DBSTATE)
16149             {
16150                 PL_curcop = ((COP*)o);
16151             }
16152             /* XXX: We avoid setting op_seq here to prevent later calls
16153                to rpeep() from mistakenly concluding that optimisation
16154                has already occurred. This doesn't fix the real problem,
16155                though (See 20010220.007 (#5874)). AMS 20010719 */
16156             /* op_seq functionality is now replaced by op_opt */
16157             o->op_opt = 0;
16158             /* FALLTHROUGH */
16159         case OP_SCALAR:
16160         case OP_LINESEQ:
16161         case OP_SCOPE:
16162         nothin:
16163             if (oldop) {
16164                 oldop->op_next = o->op_next;
16165                 o->op_opt = 0;
16166                 continue;
16167             }
16168             break;
16169
16170         case OP_PUSHMARK:
16171
16172             /* Given
16173                  5 repeat/DOLIST
16174                  3   ex-list
16175                  1     pushmark
16176                  2     scalar or const
16177                  4   const[0]
16178                convert repeat into a stub with no kids.
16179              */
16180             if (o->op_next->op_type == OP_CONST
16181              || (  o->op_next->op_type == OP_PADSV
16182                 && !(o->op_next->op_private & OPpLVAL_INTRO))
16183              || (  o->op_next->op_type == OP_GV
16184                 && o->op_next->op_next->op_type == OP_RV2SV
16185                 && !(o->op_next->op_next->op_private
16186                         & (OPpLVAL_INTRO|OPpOUR_INTRO))))
16187             {
16188                 const OP *kid = o->op_next->op_next;
16189                 if (o->op_next->op_type == OP_GV)
16190                    kid = kid->op_next;
16191                 /* kid is now the ex-list.  */
16192                 if (kid->op_type == OP_NULL
16193                  && (kid = kid->op_next)->op_type == OP_CONST
16194                     /* kid is now the repeat count.  */
16195                  && kid->op_next->op_type == OP_REPEAT
16196                  && kid->op_next->op_private & OPpREPEAT_DOLIST
16197                  && (kid->op_next->op_flags & OPf_WANT) == OPf_WANT_LIST
16198                  && SvIOK(kSVOP_sv) && SvIVX(kSVOP_sv) == 0
16199                  && oldop)
16200                 {
16201                     o = kid->op_next; /* repeat */
16202                     oldop->op_next = o;
16203                     op_free(cBINOPo->op_first);
16204                     op_free(cBINOPo->op_last );
16205                     o->op_flags &=~ OPf_KIDS;
16206                     /* stub is a baseop; repeat is a binop */
16207                     STATIC_ASSERT_STMT(sizeof(OP) <= sizeof(BINOP));
16208                     OpTYPE_set(o, OP_STUB);
16209                     o->op_private = 0;
16210                     break;
16211                 }
16212             }
16213
16214             /* Convert a series of PAD ops for my vars plus support into a
16215              * single padrange op. Basically
16216              *
16217              *    pushmark -> pad[ahs]v -> pad[ahs]?v -> ... -> (list) -> rest
16218              *
16219              * becomes, depending on circumstances, one of
16220              *
16221              *    padrange  ----------------------------------> (list) -> rest
16222              *    padrange  --------------------------------------------> rest
16223              *
16224              * where all the pad indexes are sequential and of the same type
16225              * (INTRO or not).
16226              * We convert the pushmark into a padrange op, then skip
16227              * any other pad ops, and possibly some trailing ops.
16228              * Note that we don't null() the skipped ops, to make it
16229              * easier for Deparse to undo this optimisation (and none of
16230              * the skipped ops are holding any resourses). It also makes
16231              * it easier for find_uninit_var(), as it can just ignore
16232              * padrange, and examine the original pad ops.
16233              */
16234         {
16235             OP *p;
16236             OP *followop = NULL; /* the op that will follow the padrange op */
16237             U8 count = 0;
16238             U8 intro = 0;
16239             PADOFFSET base = 0; /* init only to stop compiler whining */
16240             bool gvoid = 0;     /* init only to stop compiler whining */
16241             bool defav = 0;  /* seen (...) = @_ */
16242             bool reuse = 0;  /* reuse an existing padrange op */
16243
16244             /* look for a pushmark -> gv[_] -> rv2av */
16245
16246             {
16247                 OP *rv2av, *q;
16248                 p = o->op_next;
16249                 if (   p->op_type == OP_GV
16250                     && cGVOPx_gv(p) == PL_defgv
16251                     && (rv2av = p->op_next)
16252                     && rv2av->op_type == OP_RV2AV
16253                     && !(rv2av->op_flags & OPf_REF)
16254                     && !(rv2av->op_private & (OPpLVAL_INTRO|OPpMAYBE_LVSUB))
16255                     && ((rv2av->op_flags & OPf_WANT) == OPf_WANT_LIST)
16256                 ) {
16257                     q = rv2av->op_next;
16258                     if (q->op_type == OP_NULL)
16259                         q = q->op_next;
16260                     if (q->op_type == OP_PUSHMARK) {
16261                         defav = 1;
16262                         p = q;
16263                     }
16264                 }
16265             }
16266             if (!defav) {
16267                 p = o;
16268             }
16269
16270             /* scan for PAD ops */
16271
16272             for (p = p->op_next; p; p = p->op_next) {
16273                 if (p->op_type == OP_NULL)
16274                     continue;
16275
16276                 if ((     p->op_type != OP_PADSV
16277                        && p->op_type != OP_PADAV
16278                        && p->op_type != OP_PADHV
16279                     )
16280                       /* any private flag other than INTRO? e.g. STATE */
16281                    || (p->op_private & ~OPpLVAL_INTRO)
16282                 )
16283                     break;
16284
16285                 /* let $a[N] potentially be optimised into AELEMFAST_LEX
16286                  * instead */
16287                 if (   p->op_type == OP_PADAV
16288                     && p->op_next
16289                     && p->op_next->op_type == OP_CONST
16290                     && p->op_next->op_next
16291                     && p->op_next->op_next->op_type == OP_AELEM
16292                 )
16293                     break;
16294
16295                 /* for 1st padop, note what type it is and the range
16296                  * start; for the others, check that it's the same type
16297                  * and that the targs are contiguous */
16298                 if (count == 0) {
16299                     intro = (p->op_private & OPpLVAL_INTRO);
16300                     base = p->op_targ;
16301                     gvoid = OP_GIMME(p,0) == G_VOID;
16302                 }
16303                 else {
16304                     if ((p->op_private & OPpLVAL_INTRO) != intro)
16305                         break;
16306                     /* Note that you'd normally  expect targs to be
16307                      * contiguous in my($a,$b,$c), but that's not the case
16308                      * when external modules start doing things, e.g.
16309                      * Function::Parameters */
16310                     if (p->op_targ != base + count)
16311                         break;
16312                     assert(p->op_targ == base + count);
16313                     /* Either all the padops or none of the padops should
16314                        be in void context.  Since we only do the optimisa-
16315                        tion for av/hv when the aggregate itself is pushed
16316                        on to the stack (one item), there is no need to dis-
16317                        tinguish list from scalar context.  */
16318                     if (gvoid != (OP_GIMME(p,0) == G_VOID))
16319                         break;
16320                 }
16321
16322                 /* for AV, HV, only when we're not flattening */
16323                 if (   p->op_type != OP_PADSV
16324                     && !gvoid
16325                     && !(p->op_flags & OPf_REF)
16326                 )
16327                     break;
16328
16329                 if (count >= OPpPADRANGE_COUNTMASK)
16330                     break;
16331
16332                 /* there's a biggest base we can fit into a
16333                  * SAVEt_CLEARPADRANGE in pp_padrange.
16334                  * (The sizeof() stuff will be constant-folded, and is
16335                  * intended to avoid getting "comparison is always false"
16336                  * compiler warnings. See the comments above
16337                  * MEM_WRAP_CHECK for more explanation on why we do this
16338                  * in a weird way to avoid compiler warnings.)
16339                  */
16340                 if (   intro
16341                     && (8*sizeof(base) >
16342                         8*sizeof(UV)-OPpPADRANGE_COUNTSHIFT-SAVE_TIGHT_SHIFT
16343                         ? (Size_t)base
16344                         : (UV_MAX >> (OPpPADRANGE_COUNTSHIFT+SAVE_TIGHT_SHIFT))
16345                         ) >
16346                         (UV_MAX >> (OPpPADRANGE_COUNTSHIFT+SAVE_TIGHT_SHIFT))
16347                 )
16348                     break;
16349
16350                 /* Success! We've got another valid pad op to optimise away */
16351                 count++;
16352                 followop = p->op_next;
16353             }
16354
16355             if (count < 1 || (count == 1 && !defav))
16356                 break;
16357
16358             /* pp_padrange in specifically compile-time void context
16359              * skips pushing a mark and lexicals; in all other contexts
16360              * (including unknown till runtime) it pushes a mark and the
16361              * lexicals. We must be very careful then, that the ops we
16362              * optimise away would have exactly the same effect as the
16363              * padrange.
16364              * In particular in void context, we can only optimise to
16365              * a padrange if we see the complete sequence
16366              *     pushmark, pad*v, ...., list
16367              * which has the net effect of leaving the markstack as it
16368              * was.  Not pushing onto the stack (whereas padsv does touch
16369              * the stack) makes no difference in void context.
16370              */
16371             assert(followop);
16372             if (gvoid) {
16373                 if (followop->op_type == OP_LIST
16374                         && OP_GIMME(followop,0) == G_VOID
16375                    )
16376                 {
16377                     followop = followop->op_next; /* skip OP_LIST */
16378
16379                     /* consolidate two successive my(...);'s */
16380
16381                     if (   oldoldop
16382                         && oldoldop->op_type == OP_PADRANGE
16383                         && (oldoldop->op_flags & OPf_WANT) == OPf_WANT_VOID
16384                         && (oldoldop->op_private & OPpLVAL_INTRO) == intro
16385                         && !(oldoldop->op_flags & OPf_SPECIAL)
16386                     ) {
16387                         U8 old_count;
16388                         assert(oldoldop->op_next == oldop);
16389                         assert(   oldop->op_type == OP_NEXTSTATE
16390                                || oldop->op_type == OP_DBSTATE);
16391                         assert(oldop->op_next == o);
16392
16393                         old_count
16394                             = (oldoldop->op_private & OPpPADRANGE_COUNTMASK);
16395
16396                        /* Do not assume pad offsets for $c and $d are con-
16397                           tiguous in
16398                             my ($a,$b,$c);
16399                             my ($d,$e,$f);
16400                         */
16401                         if (  oldoldop->op_targ + old_count == base
16402                            && old_count < OPpPADRANGE_COUNTMASK - count) {
16403                             base = oldoldop->op_targ;
16404                             count += old_count;
16405                             reuse = 1;
16406                         }
16407                     }
16408
16409                     /* if there's any immediately following singleton
16410                      * my var's; then swallow them and the associated
16411                      * nextstates; i.e.
16412                      *    my ($a,$b); my $c; my $d;
16413                      * is treated as
16414                      *    my ($a,$b,$c,$d);
16415                      */
16416
16417                     while (    ((p = followop->op_next))
16418                             && (  p->op_type == OP_PADSV
16419                                || p->op_type == OP_PADAV
16420                                || p->op_type == OP_PADHV)
16421                             && (p->op_flags & OPf_WANT) == OPf_WANT_VOID
16422                             && (p->op_private & OPpLVAL_INTRO) == intro
16423                             && !(p->op_private & ~OPpLVAL_INTRO)
16424                             && p->op_next
16425                             && (   p->op_next->op_type == OP_NEXTSTATE
16426                                 || p->op_next->op_type == OP_DBSTATE)
16427                             && count < OPpPADRANGE_COUNTMASK
16428                             && base + count == p->op_targ
16429                     ) {
16430                         count++;
16431                         followop = p->op_next;
16432                     }
16433                 }
16434                 else
16435                     break;
16436             }
16437
16438             if (reuse) {
16439                 assert(oldoldop->op_type == OP_PADRANGE);
16440                 oldoldop->op_next = followop;
16441                 oldoldop->op_private = (intro | count);
16442                 o = oldoldop;
16443                 oldop = NULL;
16444                 oldoldop = NULL;
16445             }
16446             else {
16447                 /* Convert the pushmark into a padrange.
16448                  * To make Deparse easier, we guarantee that a padrange was
16449                  * *always* formerly a pushmark */
16450                 assert(o->op_type == OP_PUSHMARK);
16451                 o->op_next = followop;
16452                 OpTYPE_set(o, OP_PADRANGE);
16453                 o->op_targ = base;
16454                 /* bit 7: INTRO; bit 6..0: count */
16455                 o->op_private = (intro | count);
16456                 o->op_flags = ((o->op_flags & ~(OPf_WANT|OPf_SPECIAL))
16457                               | gvoid * OPf_WANT_VOID
16458                               | (defav ? OPf_SPECIAL : 0));
16459             }
16460             break;
16461         }
16462
16463         case OP_RV2AV:
16464             if ((o->op_flags & OPf_WANT) == OPf_WANT_SCALAR)
16465                 S_check_for_bool_cxt(o, 1, OPpTRUEBOOL, 0);
16466             break;
16467
16468         case OP_RV2HV:
16469         case OP_PADHV:
16470             /*'keys %h' in void or scalar context: skip the OP_KEYS
16471              * and perform the functionality directly in the RV2HV/PADHV
16472              * op
16473              */
16474             if (o->op_flags & OPf_REF) {
16475                 OP *k = o->op_next;
16476                 U8 want = (k->op_flags & OPf_WANT);
16477                 if (   k
16478                     && k->op_type == OP_KEYS
16479                     && (   want == OPf_WANT_VOID
16480                         || want == OPf_WANT_SCALAR)
16481                     && !(k->op_private & OPpMAYBE_LVSUB)
16482                     && !(k->op_flags & OPf_MOD)
16483                 ) {
16484                     o->op_next     = k->op_next;
16485                     o->op_flags   &= ~(OPf_REF|OPf_WANT);
16486                     o->op_flags   |= want;
16487                     o->op_private |= (o->op_type == OP_PADHV ?
16488                                       OPpPADHV_ISKEYS : OPpRV2HV_ISKEYS);
16489                     /* for keys(%lex), hold onto the OP_KEYS's targ
16490                      * since padhv doesn't have its own targ to return
16491                      * an int with */
16492                     if (!(o->op_type ==OP_PADHV && want == OPf_WANT_SCALAR))
16493                         op_null(k);
16494                 }
16495             }
16496
16497             /* see if %h is used in boolean context */
16498             if ((o->op_flags & OPf_WANT) == OPf_WANT_SCALAR)
16499                 S_check_for_bool_cxt(o, 1, OPpTRUEBOOL, OPpMAYBE_TRUEBOOL);
16500
16501
16502             if (o->op_type != OP_PADHV)
16503                 break;
16504             /* FALLTHROUGH */
16505         case OP_PADAV:
16506             if (   o->op_type == OP_PADAV
16507                 && (o->op_flags & OPf_WANT) == OPf_WANT_SCALAR
16508             )
16509                 S_check_for_bool_cxt(o, 1, OPpTRUEBOOL, 0);
16510             /* FALLTHROUGH */
16511         case OP_PADSV:
16512             /* Skip over state($x) in void context.  */
16513             if (oldop && o->op_private == (OPpPAD_STATE|OPpLVAL_INTRO)
16514              && (o->op_flags & OPf_WANT) == OPf_WANT_VOID)
16515             {
16516                 oldop->op_next = o->op_next;
16517                 goto redo_nextstate;
16518             }
16519             if (o->op_type != OP_PADAV)
16520                 break;
16521             /* FALLTHROUGH */
16522         case OP_GV:
16523             if (o->op_type == OP_PADAV || o->op_next->op_type == OP_RV2AV) {
16524                 OP* const pop = (o->op_type == OP_PADAV) ?
16525                             o->op_next : o->op_next->op_next;
16526                 IV i;
16527                 if (pop && pop->op_type == OP_CONST &&
16528                     ((PL_op = pop->op_next)) &&
16529                     pop->op_next->op_type == OP_AELEM &&
16530                     !(pop->op_next->op_private &
16531                       (OPpLVAL_INTRO|OPpLVAL_DEFER|OPpDEREF|OPpMAYBE_LVSUB)) &&
16532                     (i = SvIV(((SVOP*)pop)->op_sv)) >= -128 && i <= 127)
16533                 {
16534                     GV *gv;
16535                     if (cSVOPx(pop)->op_private & OPpCONST_STRICT)
16536                         no_bareword_allowed(pop);
16537                     if (o->op_type == OP_GV)
16538                         op_null(o->op_next);
16539                     op_null(pop->op_next);
16540                     op_null(pop);
16541                     o->op_flags |= pop->op_next->op_flags & OPf_MOD;
16542                     o->op_next = pop->op_next->op_next;
16543                     o->op_ppaddr = PL_ppaddr[OP_AELEMFAST];
16544                     o->op_private = (U8)i;
16545                     if (o->op_type == OP_GV) {
16546                         gv = cGVOPo_gv;
16547                         GvAVn(gv);
16548                         o->op_type = OP_AELEMFAST;
16549                     }
16550                     else
16551                         o->op_type = OP_AELEMFAST_LEX;
16552                 }
16553                 if (o->op_type != OP_GV)
16554                     break;
16555             }
16556
16557             /* Remove $foo from the op_next chain in void context.  */
16558             if (oldop
16559              && (  o->op_next->op_type == OP_RV2SV
16560                 || o->op_next->op_type == OP_RV2AV
16561                 || o->op_next->op_type == OP_RV2HV  )
16562              && (o->op_next->op_flags & OPf_WANT) == OPf_WANT_VOID
16563              && !(o->op_next->op_private & OPpLVAL_INTRO))
16564             {
16565                 oldop->op_next = o->op_next->op_next;
16566                 /* Reprocess the previous op if it is a nextstate, to
16567                    allow double-nextstate optimisation.  */
16568               redo_nextstate:
16569                 if (oldop->op_type == OP_NEXTSTATE) {
16570                     oldop->op_opt = 0;
16571                     o = oldop;
16572                     oldop = oldoldop;
16573                     oldoldop = NULL;
16574                     goto redo;
16575                 }
16576                 o = oldop->op_next;
16577                 goto redo;
16578             }
16579             else if (o->op_next->op_type == OP_RV2SV) {
16580                 if (!(o->op_next->op_private & OPpDEREF)) {
16581                     op_null(o->op_next);
16582                     o->op_private |= o->op_next->op_private & (OPpLVAL_INTRO
16583                                                                | OPpOUR_INTRO);
16584                     o->op_next = o->op_next->op_next;
16585                     OpTYPE_set(o, OP_GVSV);
16586                 }
16587             }
16588             else if (o->op_next->op_type == OP_READLINE
16589                     && o->op_next->op_next->op_type == OP_CONCAT
16590                     && (o->op_next->op_next->op_flags & OPf_STACKED))
16591             {
16592                 /* Turn "$a .= <FH>" into an OP_RCATLINE. AMS 20010917 */
16593                 OpTYPE_set(o, OP_RCATLINE);
16594                 o->op_flags |= OPf_STACKED;
16595                 op_null(o->op_next->op_next);
16596                 op_null(o->op_next);
16597             }
16598
16599             break;
16600         
16601         case OP_NOT:
16602             break;
16603
16604         case OP_AND:
16605         case OP_OR:
16606         case OP_DOR:
16607             while (cLOGOP->op_other->op_type == OP_NULL)
16608                 cLOGOP->op_other = cLOGOP->op_other->op_next;
16609             while (o->op_next && (   o->op_type == o->op_next->op_type
16610                                   || o->op_next->op_type == OP_NULL))
16611                 o->op_next = o->op_next->op_next;
16612
16613             /* If we're an OR and our next is an AND in void context, we'll
16614                follow its op_other on short circuit, same for reverse.
16615                We can't do this with OP_DOR since if it's true, its return
16616                value is the underlying value which must be evaluated
16617                by the next op. */
16618             if (o->op_next &&
16619                 (
16620                     (IS_AND_OP(o) && IS_OR_OP(o->op_next))
16621                  || (IS_OR_OP(o) && IS_AND_OP(o->op_next))
16622                 )
16623                 && (o->op_next->op_flags & OPf_WANT) == OPf_WANT_VOID
16624             ) {
16625                 o->op_next = ((LOGOP*)o->op_next)->op_other;
16626             }
16627             DEFER(cLOGOP->op_other);
16628             o->op_opt = 1;
16629             break;
16630         
16631         case OP_GREPWHILE:
16632             if ((o->op_flags & OPf_WANT) == OPf_WANT_SCALAR)
16633                 S_check_for_bool_cxt(o, 1, OPpTRUEBOOL, 0);
16634             /* FALLTHROUGH */
16635         case OP_COND_EXPR:
16636         case OP_MAPWHILE:
16637         case OP_ANDASSIGN:
16638         case OP_ORASSIGN:
16639         case OP_DORASSIGN:
16640         case OP_RANGE:
16641         case OP_ONCE:
16642         case OP_ARGDEFELEM:
16643             while (cLOGOP->op_other->op_type == OP_NULL)
16644                 cLOGOP->op_other = cLOGOP->op_other->op_next;
16645             DEFER(cLOGOP->op_other);
16646             break;
16647
16648         case OP_ENTERLOOP:
16649         case OP_ENTERITER:
16650             while (cLOOP->op_redoop->op_type == OP_NULL)
16651                 cLOOP->op_redoop = cLOOP->op_redoop->op_next;
16652             while (cLOOP->op_nextop->op_type == OP_NULL)
16653                 cLOOP->op_nextop = cLOOP->op_nextop->op_next;
16654             while (cLOOP->op_lastop->op_type == OP_NULL)
16655                 cLOOP->op_lastop = cLOOP->op_lastop->op_next;
16656             /* a while(1) loop doesn't have an op_next that escapes the
16657              * loop, so we have to explicitly follow the op_lastop to
16658              * process the rest of the code */
16659             DEFER(cLOOP->op_lastop);
16660             break;
16661
16662         case OP_ENTERTRY:
16663             assert(cLOGOPo->op_other->op_type == OP_LEAVETRY);
16664             DEFER(cLOGOPo->op_other);
16665             break;
16666
16667         case OP_SUBST:
16668             if ((o->op_flags & OPf_WANT) == OPf_WANT_SCALAR)
16669                 S_check_for_bool_cxt(o, 1, OPpTRUEBOOL, 0);
16670             assert(!(cPMOP->op_pmflags & PMf_ONCE));
16671             while (cPMOP->op_pmstashstartu.op_pmreplstart &&
16672                    cPMOP->op_pmstashstartu.op_pmreplstart->op_type == OP_NULL)
16673                 cPMOP->op_pmstashstartu.op_pmreplstart
16674                     = cPMOP->op_pmstashstartu.op_pmreplstart->op_next;
16675             DEFER(cPMOP->op_pmstashstartu.op_pmreplstart);
16676             break;
16677
16678         case OP_SORT: {
16679             OP *oright;
16680
16681             if (o->op_flags & OPf_SPECIAL) {
16682                 /* first arg is a code block */
16683                 OP * const nullop = OpSIBLING(cLISTOP->op_first);
16684                 OP * kid          = cUNOPx(nullop)->op_first;
16685
16686                 assert(nullop->op_type == OP_NULL);
16687                 assert(kid->op_type == OP_SCOPE
16688                  || (kid->op_type == OP_NULL && kid->op_targ == OP_LEAVE));
16689                 /* since OP_SORT doesn't have a handy op_other-style
16690                  * field that can point directly to the start of the code
16691                  * block, store it in the otherwise-unused op_next field
16692                  * of the top-level OP_NULL. This will be quicker at
16693                  * run-time, and it will also allow us to remove leading
16694                  * OP_NULLs by just messing with op_nexts without
16695                  * altering the basic op_first/op_sibling layout. */
16696                 kid = kLISTOP->op_first;
16697                 assert(
16698                       (kid->op_type == OP_NULL
16699                       && (  kid->op_targ == OP_NEXTSTATE
16700                          || kid->op_targ == OP_DBSTATE  ))
16701                     || kid->op_type == OP_STUB
16702                     || kid->op_type == OP_ENTER
16703                     || (PL_parser && PL_parser->error_count));
16704                 nullop->op_next = kid->op_next;
16705                 DEFER(nullop->op_next);
16706             }
16707
16708             /* check that RHS of sort is a single plain array */
16709             oright = cUNOPo->op_first;
16710             if (!oright || oright->op_type != OP_PUSHMARK)
16711                 break;
16712
16713             if (o->op_private & OPpSORT_INPLACE)
16714                 break;
16715
16716             /* reverse sort ... can be optimised.  */
16717             if (!OpHAS_SIBLING(cUNOPo)) {
16718                 /* Nothing follows us on the list. */
16719                 OP * const reverse = o->op_next;
16720
16721                 if (reverse->op_type == OP_REVERSE &&
16722                     (reverse->op_flags & OPf_WANT) == OPf_WANT_LIST) {
16723                     OP * const pushmark = cUNOPx(reverse)->op_first;
16724                     if (pushmark && (pushmark->op_type == OP_PUSHMARK)
16725                         && (OpSIBLING(cUNOPx(pushmark)) == o)) {
16726                         /* reverse -> pushmark -> sort */
16727                         o->op_private |= OPpSORT_REVERSE;
16728                         op_null(reverse);
16729                         pushmark->op_next = oright->op_next;
16730                         op_null(oright);
16731                     }
16732                 }
16733             }
16734
16735             break;
16736         }
16737
16738         case OP_REVERSE: {
16739             OP *ourmark, *theirmark, *ourlast, *iter, *expushmark, *rv2av;
16740             OP *gvop = NULL;
16741             LISTOP *enter, *exlist;
16742
16743             if (o->op_private & OPpSORT_INPLACE)
16744                 break;
16745
16746             enter = (LISTOP *) o->op_next;
16747             if (!enter)
16748                 break;
16749             if (enter->op_type == OP_NULL) {
16750                 enter = (LISTOP *) enter->op_next;
16751                 if (!enter)
16752                     break;
16753             }
16754             /* for $a (...) will have OP_GV then OP_RV2GV here.
16755                for (...) just has an OP_GV.  */
16756             if (enter->op_type == OP_GV) {
16757                 gvop = (OP *) enter;
16758                 enter = (LISTOP *) enter->op_next;
16759                 if (!enter)
16760                     break;
16761                 if (enter->op_type == OP_RV2GV) {
16762                   enter = (LISTOP *) enter->op_next;
16763                   if (!enter)
16764                     break;
16765                 }
16766             }
16767
16768             if (enter->op_type != OP_ENTERITER)
16769                 break;
16770
16771             iter = enter->op_next;
16772             if (!iter || iter->op_type != OP_ITER)
16773                 break;
16774             
16775             expushmark = enter->op_first;
16776             if (!expushmark || expushmark->op_type != OP_NULL
16777                 || expushmark->op_targ != OP_PUSHMARK)
16778                 break;
16779
16780             exlist = (LISTOP *) OpSIBLING(expushmark);
16781             if (!exlist || exlist->op_type != OP_NULL
16782                 || exlist->op_targ != OP_LIST)
16783                 break;
16784
16785             if (exlist->op_last != o) {
16786                 /* Mmm. Was expecting to point back to this op.  */
16787                 break;
16788             }
16789             theirmark = exlist->op_first;
16790             if (!theirmark || theirmark->op_type != OP_PUSHMARK)
16791                 break;
16792
16793             if (OpSIBLING(theirmark) != o) {
16794                 /* There's something between the mark and the reverse, eg
16795                    for (1, reverse (...))
16796                    so no go.  */
16797                 break;
16798             }
16799
16800             ourmark = ((LISTOP *)o)->op_first;
16801             if (!ourmark || ourmark->op_type != OP_PUSHMARK)
16802                 break;
16803
16804             ourlast = ((LISTOP *)o)->op_last;
16805             if (!ourlast || ourlast->op_next != o)
16806                 break;
16807
16808             rv2av = OpSIBLING(ourmark);
16809             if (rv2av && rv2av->op_type == OP_RV2AV && !OpHAS_SIBLING(rv2av)
16810                 && rv2av->op_flags == (OPf_WANT_LIST | OPf_KIDS)) {
16811                 /* We're just reversing a single array.  */
16812                 rv2av->op_flags = OPf_WANT_SCALAR | OPf_KIDS | OPf_REF;
16813                 enter->op_flags |= OPf_STACKED;
16814             }
16815
16816             /* We don't have control over who points to theirmark, so sacrifice
16817                ours.  */
16818             theirmark->op_next = ourmark->op_next;
16819             theirmark->op_flags = ourmark->op_flags;
16820             ourlast->op_next = gvop ? gvop : (OP *) enter;
16821             op_null(ourmark);
16822             op_null(o);
16823             enter->op_private |= OPpITER_REVERSED;
16824             iter->op_private |= OPpITER_REVERSED;
16825
16826             oldoldop = NULL;
16827             oldop    = ourlast;
16828             o        = oldop->op_next;
16829             goto redo;
16830             NOT_REACHED; /* NOTREACHED */
16831             break;
16832         }
16833
16834         case OP_QR:
16835         case OP_MATCH:
16836             if (!(cPMOP->op_pmflags & PMf_ONCE)) {
16837                 assert (!cPMOP->op_pmstashstartu.op_pmreplstart);
16838             }
16839             break;
16840
16841         case OP_RUNCV:
16842             if (!(o->op_private & OPpOFFBYONE) && !CvCLONE(PL_compcv)
16843              && (!CvANON(PL_compcv) || (!PL_cv_has_eval && !PL_perldb)))
16844             {
16845                 SV *sv;
16846                 if (CvEVAL(PL_compcv)) sv = &PL_sv_undef;
16847                 else {
16848                     sv = newRV((SV *)PL_compcv);
16849                     sv_rvweaken(sv);
16850                     SvREADONLY_on(sv);
16851                 }
16852                 OpTYPE_set(o, OP_CONST);
16853                 o->op_flags |= OPf_SPECIAL;
16854                 cSVOPo->op_sv = sv;
16855             }
16856             break;
16857
16858         case OP_SASSIGN:
16859             if (OP_GIMME(o,0) == G_VOID
16860              || (  o->op_next->op_type == OP_LINESEQ
16861                 && (  o->op_next->op_next->op_type == OP_LEAVESUB
16862                    || (  o->op_next->op_next->op_type == OP_RETURN
16863                       && !CvLVALUE(PL_compcv)))))
16864             {
16865                 OP *right = cBINOP->op_first;
16866                 if (right) {
16867                     /*   sassign
16868                     *      RIGHT
16869                     *      substr
16870                     *         pushmark
16871                     *         arg1
16872                     *         arg2
16873                     *         ...
16874                     * becomes
16875                     *
16876                     *  ex-sassign
16877                     *     substr
16878                     *        pushmark
16879                     *        RIGHT
16880                     *        arg1
16881                     *        arg2
16882                     *        ...
16883                     */
16884                     OP *left = OpSIBLING(right);
16885                     if (left->op_type == OP_SUBSTR
16886                          && (left->op_private & 7) < 4) {
16887                         op_null(o);
16888                         /* cut out right */
16889                         op_sibling_splice(o, NULL, 1, NULL);
16890                         /* and insert it as second child of OP_SUBSTR */
16891                         op_sibling_splice(left, cBINOPx(left)->op_first, 0,
16892                                     right);
16893                         left->op_private |= OPpSUBSTR_REPL_FIRST;
16894                         left->op_flags =
16895                             (o->op_flags & ~OPf_WANT) | OPf_WANT_VOID;
16896                     }
16897                 }
16898             }
16899             break;
16900
16901         case OP_AASSIGN: {
16902             int l, r, lr, lscalars, rscalars;
16903
16904             /* handle common vars detection, e.g. ($a,$b) = ($b,$a).
16905                Note that we do this now rather than in newASSIGNOP(),
16906                since only by now are aliased lexicals flagged as such
16907
16908                See the essay "Common vars in list assignment" above for
16909                the full details of the rationale behind all the conditions
16910                below.
16911
16912                PL_generation sorcery:
16913                To detect whether there are common vars, the global var
16914                PL_generation is incremented for each assign op we scan.
16915                Then we run through all the lexical variables on the LHS,
16916                of the assignment, setting a spare slot in each of them to
16917                PL_generation.  Then we scan the RHS, and if any lexicals
16918                already have that value, we know we've got commonality.
16919                Also, if the generation number is already set to
16920                PERL_INT_MAX, then the variable is involved in aliasing, so
16921                we also have potential commonality in that case.
16922              */
16923
16924             PL_generation++;
16925             /* scan LHS */
16926             lscalars = 0;
16927             l = S_aassign_scan(aTHX_ cLISTOPo->op_last,  FALSE, &lscalars);
16928             /* scan RHS */
16929             rscalars = 0;
16930             r = S_aassign_scan(aTHX_ cLISTOPo->op_first, TRUE, &rscalars);
16931             lr = (l|r);
16932
16933
16934             /* After looking for things which are *always* safe, this main
16935              * if/else chain selects primarily based on the type of the
16936              * LHS, gradually working its way down from the more dangerous
16937              * to the more restrictive and thus safer cases */
16938
16939             if (   !l                      /* () = ....; */
16940                 || !r                      /* .... = (); */
16941                 || !(l & ~AAS_SAFE_SCALAR) /* (undef, pos()) = ...; */
16942                 || !(r & ~AAS_SAFE_SCALAR) /* ... = (1,2,length,undef); */
16943                 || (lscalars < 2)          /* ($x, undef) = ... */
16944             ) {
16945                 NOOP; /* always safe */
16946             }
16947             else if (l & AAS_DANGEROUS) {
16948                 /* always dangerous */
16949                 o->op_private |= OPpASSIGN_COMMON_SCALAR;
16950                 o->op_private |= OPpASSIGN_COMMON_AGG;
16951             }
16952             else if (l & (AAS_PKG_SCALAR|AAS_PKG_AGG)) {
16953                 /* package vars are always dangerous - too many
16954                  * aliasing possibilities */
16955                 if (l & AAS_PKG_SCALAR)
16956                     o->op_private |= OPpASSIGN_COMMON_SCALAR;
16957                 if (l & AAS_PKG_AGG)
16958                     o->op_private |= OPpASSIGN_COMMON_AGG;
16959             }
16960             else if (l & ( AAS_MY_SCALAR|AAS_MY_AGG
16961                           |AAS_LEX_SCALAR|AAS_LEX_AGG))
16962             {
16963                 /* LHS contains only lexicals and safe ops */
16964
16965                 if (l & (AAS_MY_AGG|AAS_LEX_AGG))
16966                     o->op_private |= OPpASSIGN_COMMON_AGG;
16967
16968                 if (l & (AAS_MY_SCALAR|AAS_LEX_SCALAR)) {
16969                     if (lr & AAS_LEX_SCALAR_COMM)
16970                         o->op_private |= OPpASSIGN_COMMON_SCALAR;
16971                     else if (   !(l & AAS_LEX_SCALAR)
16972                              && (r & AAS_DEFAV))
16973                     {
16974                         /* falsely mark
16975                          *    my (...) = @_
16976                          * as scalar-safe for performance reasons.
16977                          * (it will still have been marked _AGG if necessary */
16978                         NOOP;
16979                     }
16980                     else if (r  & (AAS_PKG_SCALAR|AAS_PKG_AGG|AAS_DANGEROUS))
16981                         /* if there are only lexicals on the LHS and no
16982                          * common ones on the RHS, then we assume that the
16983                          * only way those lexicals could also get
16984                          * on the RHS is via some sort of dereffing or
16985                          * closure, e.g.
16986                          *    $r = \$lex;
16987                          *    ($lex, $x) = (1, $$r)
16988                          * and in this case we assume the var must have
16989                          *  a bumped ref count. So if its ref count is 1,
16990                          *  it must only be on the LHS.
16991                          */
16992                         o->op_private |= OPpASSIGN_COMMON_RC1;
16993                 }
16994             }
16995
16996             /* ... = ($x)
16997              * may have to handle aggregate on LHS, but we can't
16998              * have common scalars. */
16999             if (rscalars < 2)
17000                 o->op_private &=
17001                         ~(OPpASSIGN_COMMON_SCALAR|OPpASSIGN_COMMON_RC1);
17002
17003             if ((o->op_flags & OPf_WANT) == OPf_WANT_SCALAR)
17004                 S_check_for_bool_cxt(o, 1, OPpASSIGN_TRUEBOOL, 0);
17005             break;
17006         }
17007
17008         case OP_REF:
17009             /* see if ref() is used in boolean context */
17010             if ((o->op_flags & OPf_WANT) == OPf_WANT_SCALAR)
17011                 S_check_for_bool_cxt(o, 1, OPpTRUEBOOL, OPpMAYBE_TRUEBOOL);
17012             break;
17013
17014         case OP_LENGTH:
17015             /* see if the op is used in known boolean context,
17016              * but not if OA_TARGLEX optimisation is enabled */
17017             if (   (o->op_flags & OPf_WANT) == OPf_WANT_SCALAR
17018                 && !(o->op_private & OPpTARGET_MY)
17019             )
17020                 S_check_for_bool_cxt(o, 1, OPpTRUEBOOL, 0);
17021             break;
17022
17023         case OP_POS:
17024             /* see if the op is used in known boolean context */
17025             if ((o->op_flags & OPf_WANT) == OPf_WANT_SCALAR)
17026                 S_check_for_bool_cxt(o, 1, OPpTRUEBOOL, 0);
17027             break;
17028
17029         case OP_CUSTOM: {
17030             Perl_cpeep_t cpeep = 
17031                 XopENTRYCUSTOM(o, xop_peep);
17032             if (cpeep)
17033                 cpeep(aTHX_ o, oldop);
17034             break;
17035         }
17036             
17037         }
17038         /* did we just null the current op? If so, re-process it to handle
17039          * eliding "empty" ops from the chain */
17040         if (o->op_type == OP_NULL && oldop && oldop->op_next == o) {
17041             o->op_opt = 0;
17042             o = oldop;
17043         }
17044         else {
17045             oldoldop = oldop;
17046             oldop = o;
17047         }
17048     }
17049     LEAVE;
17050 }
17051
17052 void
17053 Perl_peep(pTHX_ OP *o)
17054 {
17055     CALL_RPEEP(o);
17056 }
17057
17058 /*
17059 =head1 Custom Operators
17060
17061 =for apidoc Perl_custom_op_xop
17062 Return the XOP structure for a given custom op.  This macro should be
17063 considered internal to C<OP_NAME> and the other access macros: use them instead.
17064 This macro does call a function.  Prior
17065 to 5.19.6, this was implemented as a
17066 function.
17067
17068 =cut
17069 */
17070
17071
17072 /* use PERL_MAGIC_ext to call a function to free the xop structure when
17073  * freeing PL_custom_ops */
17074
17075 static int
17076 custom_op_register_free(pTHX_ SV *sv, MAGIC *mg)
17077 {
17078     XOP *xop;
17079
17080     PERL_UNUSED_ARG(mg);
17081     xop = INT2PTR(XOP *, SvIV(sv));
17082     Safefree(xop->xop_name);
17083     Safefree(xop->xop_desc);
17084     Safefree(xop);
17085     return 0;
17086 }
17087
17088
17089 static const MGVTBL custom_op_register_vtbl = {
17090     0,                          /* get */
17091     0,                          /* set */
17092     0,                          /* len */
17093     0,                          /* clear */
17094     custom_op_register_free,     /* free */
17095     0,                          /* copy */
17096     0,                          /* dup */
17097 #ifdef MGf_LOCAL
17098     0,                          /* local */
17099 #endif
17100 };
17101
17102
17103 XOPRETANY
17104 Perl_custom_op_get_field(pTHX_ const OP *o, const xop_flags_enum field)
17105 {
17106     SV *keysv;
17107     HE *he = NULL;
17108     XOP *xop;
17109
17110     static const XOP xop_null = { 0, 0, 0, 0, 0 };
17111
17112     PERL_ARGS_ASSERT_CUSTOM_OP_GET_FIELD;
17113     assert(o->op_type == OP_CUSTOM);
17114
17115     /* This is wrong. It assumes a function pointer can be cast to IV,
17116      * which isn't guaranteed, but this is what the old custom OP code
17117      * did. In principle it should be safer to Copy the bytes of the
17118      * pointer into a PV: since the new interface is hidden behind
17119      * functions, this can be changed later if necessary.  */
17120     /* Change custom_op_xop if this ever happens */
17121     keysv = sv_2mortal(newSViv(PTR2IV(o->op_ppaddr)));
17122
17123     if (PL_custom_ops)
17124         he = hv_fetch_ent(PL_custom_ops, keysv, 0, 0);
17125
17126     /* See if the op isn't registered, but its name *is* registered.
17127      * That implies someone is using the pre-5.14 API,where only name and
17128      * description could be registered. If so, fake up a real
17129      * registration.
17130      * We only check for an existing name, and assume no one will have
17131      * just registered a desc */
17132     if (!he && PL_custom_op_names &&
17133         (he = hv_fetch_ent(PL_custom_op_names, keysv, 0, 0))
17134     ) {
17135         const char *pv;
17136         STRLEN l;
17137
17138         /* XXX does all this need to be shared mem? */
17139         Newxz(xop, 1, XOP);
17140         pv = SvPV(HeVAL(he), l);
17141         XopENTRY_set(xop, xop_name, savepvn(pv, l));
17142         if (PL_custom_op_descs &&
17143             (he = hv_fetch_ent(PL_custom_op_descs, keysv, 0, 0))
17144         ) {
17145             pv = SvPV(HeVAL(he), l);
17146             XopENTRY_set(xop, xop_desc, savepvn(pv, l));
17147         }
17148         Perl_custom_op_register(aTHX_ o->op_ppaddr, xop);
17149         he = hv_fetch_ent(PL_custom_ops, keysv, 0, 0);
17150         /* add magic to the SV so that the xop struct (pointed to by
17151          * SvIV(sv)) is freed. Normally a static xop is registered, but
17152          * for this backcompat hack, we've alloced one */
17153         (void)sv_magicext(HeVAL(he), NULL, PERL_MAGIC_ext,
17154                 &custom_op_register_vtbl, NULL, 0);
17155
17156     }
17157     else {
17158         if (!he)
17159             xop = (XOP *)&xop_null;
17160         else
17161             xop = INT2PTR(XOP *, SvIV(HeVAL(he)));
17162     }
17163     {
17164         XOPRETANY any;
17165         if(field == XOPe_xop_ptr) {
17166             any.xop_ptr = xop;
17167         } else {
17168             const U32 flags = XopFLAGS(xop);
17169             if(flags & field) {
17170                 switch(field) {
17171                 case XOPe_xop_name:
17172                     any.xop_name = xop->xop_name;
17173                     break;
17174                 case XOPe_xop_desc:
17175                     any.xop_desc = xop->xop_desc;
17176                     break;
17177                 case XOPe_xop_class:
17178                     any.xop_class = xop->xop_class;
17179                     break;
17180                 case XOPe_xop_peep:
17181                     any.xop_peep = xop->xop_peep;
17182                     break;
17183                 default:
17184                     NOT_REACHED; /* NOTREACHED */
17185                     break;
17186                 }
17187             } else {
17188                 switch(field) {
17189                 case XOPe_xop_name:
17190                     any.xop_name = XOPd_xop_name;
17191                     break;
17192                 case XOPe_xop_desc:
17193                     any.xop_desc = XOPd_xop_desc;
17194                     break;
17195                 case XOPe_xop_class:
17196                     any.xop_class = XOPd_xop_class;
17197                     break;
17198                 case XOPe_xop_peep:
17199                     any.xop_peep = XOPd_xop_peep;
17200                     break;
17201                 default:
17202                     NOT_REACHED; /* NOTREACHED */
17203                     break;
17204                 }
17205             }
17206         }
17207         /* On some platforms (HP-UX, IA64) gcc emits a warning for this function:
17208          * op.c: In function 'Perl_custom_op_get_field':
17209          * op.c:...: warning: 'any.xop_name' may be used uninitialized in this function [-Wmaybe-uninitialized]
17210          * This is because on those platforms (with -DEBUGGING) NOT_REACHED
17211          * expands to assert(0), which expands to ((0) ? (void)0 :
17212          * __assert(...)), and gcc doesn't know that __assert can never return. */
17213         return any;
17214     }
17215 }
17216
17217 /*
17218 =for apidoc custom_op_register
17219 Register a custom op.  See L<perlguts/"Custom Operators">.
17220
17221 =cut
17222 */
17223
17224 void
17225 Perl_custom_op_register(pTHX_ Perl_ppaddr_t ppaddr, const XOP *xop)
17226 {
17227     SV *keysv;
17228
17229     PERL_ARGS_ASSERT_CUSTOM_OP_REGISTER;
17230
17231     /* see the comment in custom_op_xop */
17232     keysv = sv_2mortal(newSViv(PTR2IV(ppaddr)));
17233
17234     if (!PL_custom_ops)
17235         PL_custom_ops = newHV();
17236
17237     if (!hv_store_ent(PL_custom_ops, keysv, newSViv(PTR2IV(xop)), 0))
17238         Perl_croak(aTHX_ "panic: can't register custom OP %s", xop->xop_name);
17239 }
17240
17241 /*
17242
17243 =for apidoc core_prototype
17244
17245 This function assigns the prototype of the named core function to C<sv>, or
17246 to a new mortal SV if C<sv> is C<NULL>.  It returns the modified C<sv>, or
17247 C<NULL> if the core function has no prototype.  C<code> is a code as returned
17248 by C<keyword()>.  It must not be equal to 0.
17249
17250 =cut
17251 */
17252
17253 SV *
17254 Perl_core_prototype(pTHX_ SV *sv, const char *name, const int code,
17255                           int * const opnum)
17256 {
17257     int i = 0, n = 0, seen_question = 0, defgv = 0;
17258     I32 oa;
17259 #define MAX_ARGS_OP ((sizeof(I32) - 1) * 2)
17260     char str[ MAX_ARGS_OP * 2 + 2 ]; /* One ';', one '\0' */
17261     bool nullret = FALSE;
17262
17263     PERL_ARGS_ASSERT_CORE_PROTOTYPE;
17264
17265     assert (code);
17266
17267     if (!sv) sv = sv_newmortal();
17268
17269 #define retsetpvs(x,y) sv_setpvs(sv, x); if(opnum) *opnum=(y); return sv
17270
17271     switch (code < 0 ? -code : code) {
17272     case KEY_and   : case KEY_chop: case KEY_chomp:
17273     case KEY_cmp   : case KEY_defined: case KEY_delete: case KEY_exec  :
17274     case KEY_exists: case KEY_eq     : case KEY_ge    : case KEY_goto  :
17275     case KEY_grep  : case KEY_gt     : case KEY_last  : case KEY_le    :
17276     case KEY_lt    : case KEY_map    : case KEY_ne    : case KEY_next  :
17277     case KEY_or    : case KEY_print  : case KEY_printf: case KEY_qr    :
17278     case KEY_redo  : case KEY_require: case KEY_return: case KEY_say   :
17279     case KEY_select: case KEY_sort   : case KEY_split : case KEY_system:
17280     case KEY_x     : case KEY_xor    :
17281         if (!opnum) return NULL; nullret = TRUE; goto findopnum;
17282     case KEY_glob:    retsetpvs("_;", OP_GLOB);
17283     case KEY_keys:    retsetpvs("\\[%@]", OP_KEYS);
17284     case KEY_values:  retsetpvs("\\[%@]", OP_VALUES);
17285     case KEY_each:    retsetpvs("\\[%@]", OP_EACH);
17286     case KEY_pos:     retsetpvs(";\\[$*]", OP_POS);
17287     case KEY___FILE__: case KEY___LINE__: case KEY___PACKAGE__:
17288         retsetpvs("", 0);
17289     case KEY_evalbytes:
17290         name = "entereval"; break;
17291     case KEY_readpipe:
17292         name = "backtick";
17293     }
17294
17295 #undef retsetpvs
17296
17297   findopnum:
17298     while (i < MAXO) {  /* The slow way. */
17299         if (strEQ(name, PL_op_name[i])
17300             || strEQ(name, PL_op_desc[i]))
17301         {
17302             if (nullret) { assert(opnum); *opnum = i; return NULL; }
17303             goto found;
17304         }
17305         i++;
17306     }
17307     return NULL;
17308   found:
17309     defgv = PL_opargs[i] & OA_DEFGV;
17310     oa = PL_opargs[i] >> OASHIFT;
17311     while (oa) {
17312         if (oa & OA_OPTIONAL && !seen_question && (
17313               !defgv || (oa & (OA_OPTIONAL - 1)) == OA_FILEREF
17314         )) {
17315             seen_question = 1;
17316             str[n++] = ';';
17317         }
17318         if ((oa & (OA_OPTIONAL - 1)) >= OA_AVREF
17319             && (oa & (OA_OPTIONAL - 1)) <= OA_SCALARREF
17320             /* But globs are already references (kinda) */
17321             && (oa & (OA_OPTIONAL - 1)) != OA_FILEREF
17322         ) {
17323             str[n++] = '\\';
17324         }
17325         if ((oa & (OA_OPTIONAL - 1)) == OA_SCALARREF
17326          && !scalar_mod_type(NULL, i)) {
17327             str[n++] = '[';
17328             str[n++] = '$';
17329             str[n++] = '@';
17330             str[n++] = '%';
17331             if (i == OP_LOCK || i == OP_UNDEF) str[n++] = '&';
17332             str[n++] = '*';
17333             str[n++] = ']';
17334         }
17335         else str[n++] = ("?$@@%&*$")[oa & (OA_OPTIONAL - 1)];
17336         if (oa & OA_OPTIONAL && defgv && str[n-1] == '$') {
17337             str[n-1] = '_'; defgv = 0;
17338         }
17339         oa = oa >> 4;
17340     }
17341     if (code == -KEY_not || code == -KEY_getprotobynumber) str[n++] = ';';
17342     str[n++] = '\0';
17343     sv_setpvn(sv, str, n - 1);
17344     if (opnum) *opnum = i;
17345     return sv;
17346 }
17347
17348 OP *
17349 Perl_coresub_op(pTHX_ SV * const coreargssv, const int code,
17350                       const int opnum)
17351 {
17352     OP * const argop = (opnum == OP_SELECT && code) ? NULL :
17353                                         newSVOP(OP_COREARGS,0,coreargssv);
17354     OP *o;
17355
17356     PERL_ARGS_ASSERT_CORESUB_OP;
17357
17358     switch(opnum) {
17359     case 0:
17360         return op_append_elem(OP_LINESEQ,
17361                        argop,
17362                        newSLICEOP(0,
17363                                   newSVOP(OP_CONST, 0, newSViv(-code % 3)),
17364                                   newOP(OP_CALLER,0)
17365                        )
17366                );
17367     case OP_EACH:
17368     case OP_KEYS:
17369     case OP_VALUES:
17370         o = newUNOP(OP_AVHVSWITCH,0,argop);
17371         o->op_private = opnum-OP_EACH;
17372         return o;
17373     case OP_SELECT: /* which represents OP_SSELECT as well */
17374         if (code)
17375             return newCONDOP(
17376                          0,
17377                          newBINOP(OP_GT, 0,
17378                                   newAVREF(newGVOP(OP_GV, 0, PL_defgv)),
17379                                   newSVOP(OP_CONST, 0, newSVuv(1))
17380                                  ),
17381                          coresub_op(newSVuv((UV)OP_SSELECT), 0,
17382                                     OP_SSELECT),
17383                          coresub_op(coreargssv, 0, OP_SELECT)
17384                    );
17385         /* FALLTHROUGH */
17386     default:
17387         switch (PL_opargs[opnum] & OA_CLASS_MASK) {
17388         case OA_BASEOP:
17389             return op_append_elem(
17390                         OP_LINESEQ, argop,
17391                         newOP(opnum,
17392                               opnum == OP_WANTARRAY || opnum == OP_RUNCV
17393                                 ? OPpOFFBYONE << 8 : 0)
17394                    );
17395         case OA_BASEOP_OR_UNOP:
17396             if (opnum == OP_ENTEREVAL) {
17397                 o = newUNOP(OP_ENTEREVAL,OPpEVAL_COPHH<<8,argop);
17398                 if (code == -KEY_evalbytes) o->op_private |= OPpEVAL_BYTES;
17399             }
17400             else o = newUNOP(opnum,0,argop);
17401             if (opnum == OP_CALLER) o->op_private |= OPpOFFBYONE;
17402             else {
17403           onearg:
17404               if (is_handle_constructor(o, 1))
17405                 argop->op_private |= OPpCOREARGS_DEREF1;
17406               if (scalar_mod_type(NULL, opnum))
17407                 argop->op_private |= OPpCOREARGS_SCALARMOD;
17408             }
17409             return o;
17410         default:
17411             o = op_convert_list(opnum,OPf_SPECIAL*(opnum == OP_GLOB),argop);
17412             if (is_handle_constructor(o, 2))
17413                 argop->op_private |= OPpCOREARGS_DEREF2;
17414             if (opnum == OP_SUBSTR) {
17415                 o->op_private |= OPpMAYBE_LVSUB;
17416                 return o;
17417             }
17418             else goto onearg;
17419         }
17420     }
17421 }
17422
17423 void
17424 Perl_report_redefined_cv(pTHX_ const SV *name, const CV *old_cv,
17425                                SV * const *new_const_svp)
17426 {
17427     const char *hvname;
17428     bool is_const = !!CvCONST(old_cv);
17429     SV *old_const_sv = is_const ? cv_const_sv(old_cv) : NULL;
17430
17431     PERL_ARGS_ASSERT_REPORT_REDEFINED_CV;
17432
17433     if (is_const && new_const_svp && old_const_sv == *new_const_svp)
17434         return;
17435         /* They are 2 constant subroutines generated from
17436            the same constant. This probably means that
17437            they are really the "same" proxy subroutine
17438            instantiated in 2 places. Most likely this is
17439            when a constant is exported twice.  Don't warn.
17440         */
17441     if (
17442         (ckWARN(WARN_REDEFINE)
17443          && !(
17444                 CvGV(old_cv) && GvSTASH(CvGV(old_cv))
17445              && HvNAMELEN(GvSTASH(CvGV(old_cv))) == 7
17446              && (hvname = HvNAME(GvSTASH(CvGV(old_cv))),
17447                  strEQ(hvname, "autouse"))
17448              )
17449         )
17450      || (is_const
17451          && ckWARN_d(WARN_REDEFINE)
17452          && (!new_const_svp || sv_cmp(old_const_sv, *new_const_svp))
17453         )
17454     )
17455         Perl_warner(aTHX_ packWARN(WARN_REDEFINE),
17456                           is_const
17457                             ? "Constant subroutine %" SVf " redefined"
17458                             : "Subroutine %" SVf " redefined",
17459                           SVfARG(name));
17460 }
17461
17462 /*
17463 =head1 Hook manipulation
17464
17465 These functions provide convenient and thread-safe means of manipulating
17466 hook variables.
17467
17468 =cut
17469 */
17470
17471 /*
17472 =for apidoc wrap_op_checker
17473
17474 Puts a C function into the chain of check functions for a specified op
17475 type.  This is the preferred way to manipulate the L</PL_check> array.
17476 C<opcode> specifies which type of op is to be affected.  C<new_checker>
17477 is a pointer to the C function that is to be added to that opcode's
17478 check chain, and C<old_checker_p> points to the storage location where a
17479 pointer to the next function in the chain will be stored.  The value of
17480 C<new_checker> is written into the L</PL_check> array, while the value
17481 previously stored there is written to C<*old_checker_p>.
17482
17483 L</PL_check> is global to an entire process, and a module wishing to
17484 hook op checking may find itself invoked more than once per process,
17485 typically in different threads.  To handle that situation, this function
17486 is idempotent.  The location C<*old_checker_p> must initially (once
17487 per process) contain a null pointer.  A C variable of static duration
17488 (declared at file scope, typically also marked C<static> to give
17489 it internal linkage) will be implicitly initialised appropriately,
17490 if it does not have an explicit initialiser.  This function will only
17491 actually modify the check chain if it finds C<*old_checker_p> to be null.
17492 This function is also thread safe on the small scale.  It uses appropriate
17493 locking to avoid race conditions in accessing L</PL_check>.
17494
17495 When this function is called, the function referenced by C<new_checker>
17496 must be ready to be called, except for C<*old_checker_p> being unfilled.
17497 In a threading situation, C<new_checker> may be called immediately,
17498 even before this function has returned.  C<*old_checker_p> will always
17499 be appropriately set before C<new_checker> is called.  If C<new_checker>
17500 decides not to do anything special with an op that it is given (which
17501 is the usual case for most uses of op check hooking), it must chain the
17502 check function referenced by C<*old_checker_p>.
17503
17504 Taken all together, XS code to hook an op checker should typically look
17505 something like this:
17506
17507     static Perl_check_t nxck_frob;
17508     static OP *myck_frob(pTHX_ OP *op) {
17509         ...
17510         op = nxck_frob(aTHX_ op);
17511         ...
17512         return op;
17513     }
17514     BOOT:
17515         wrap_op_checker(OP_FROB, myck_frob, &nxck_frob);
17516
17517 If you want to influence compilation of calls to a specific subroutine,
17518 then use L</cv_set_call_checker_flags> rather than hooking checking of
17519 all C<entersub> ops.
17520
17521 =cut
17522 */
17523
17524 void
17525 Perl_wrap_op_checker(pTHX_ Optype opcode,
17526     Perl_check_t new_checker, Perl_check_t *old_checker_p)
17527 {
17528     dVAR;
17529
17530     PERL_UNUSED_CONTEXT;
17531     PERL_ARGS_ASSERT_WRAP_OP_CHECKER;
17532     if (*old_checker_p) return;
17533     OP_CHECK_MUTEX_LOCK;
17534     if (!*old_checker_p) {
17535         *old_checker_p = PL_check[opcode];
17536         PL_check[opcode] = new_checker;
17537     }
17538     OP_CHECK_MUTEX_UNLOCK;
17539 }
17540
17541 #include "XSUB.h"
17542
17543 /* Efficient sub that returns a constant scalar value. */
17544 static void
17545 const_sv_xsub(pTHX_ CV* cv)
17546 {
17547     dXSARGS;
17548     SV *const sv = MUTABLE_SV(XSANY.any_ptr);
17549     PERL_UNUSED_ARG(items);
17550     if (!sv) {
17551         XSRETURN(0);
17552     }
17553     EXTEND(sp, 1);
17554     ST(0) = sv;
17555     XSRETURN(1);
17556 }
17557
17558 static void
17559 const_av_xsub(pTHX_ CV* cv)
17560 {
17561     dXSARGS;
17562     AV * const av = MUTABLE_AV(XSANY.any_ptr);
17563     SP -= items;
17564     assert(av);
17565 #ifndef DEBUGGING
17566     if (!av) {
17567         XSRETURN(0);
17568     }
17569 #endif
17570     if (SvRMAGICAL(av))
17571         Perl_croak(aTHX_ "Magical list constants are not supported");
17572     if (GIMME_V != G_ARRAY) {
17573         EXTEND(SP, 1);
17574         ST(0) = sv_2mortal(newSViv((IV)AvFILLp(av)+1));
17575         XSRETURN(1);
17576     }
17577     EXTEND(SP, AvFILLp(av)+1);
17578     Copy(AvARRAY(av), &ST(0), AvFILLp(av)+1, SV *);
17579     XSRETURN(AvFILLp(av)+1);
17580 }
17581
17582 /* Copy an existing cop->cop_warnings field.
17583  * If it's one of the standard addresses, just re-use the address.
17584  * This is the e implementation for the DUP_WARNINGS() macro
17585  */
17586
17587 STRLEN*
17588 Perl_dup_warnings(pTHX_ STRLEN* warnings)
17589 {
17590     Size_t size;
17591     STRLEN *new_warnings;
17592
17593     if (warnings == NULL || specialWARN(warnings))
17594         return warnings;
17595
17596     size = sizeof(*warnings) + *warnings;
17597
17598     new_warnings = (STRLEN*)PerlMemShared_malloc(size);
17599     Copy(warnings, new_warnings, size, char);
17600     return new_warnings;
17601 }
17602
17603 /*
17604  * ex: set ts=8 sts=4 sw=4 et:
17605  */