This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
C99 math under C++ on VMS.
[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  * A Perl program is compiled into a tree of OPs. Each op contains
26  * structural pointers (eg to its siblings and the next op in the
27  * execution sequence), a pointer to the function that would execute the
28  * op, plus any data specific to that op. For example, an OP_CONST op
29  * points to the pp_const() function and to an SV containing the constant
30  * value. When pp_const() is executed, its job is to push that SV onto the
31  * stack.
32  *
33  * OPs are mainly created by the newFOO() functions, which are mainly
34  * called from the parser (in perly.y) as the code is parsed. For example
35  * the Perl code $a + $b * $c would cause the equivalent of the following
36  * to be called (oversimplifying a bit):
37  *
38  *  newBINOP(OP_ADD, flags,
39  *      newSVREF($a),
40  *      newBINOP(OP_MULTIPLY, flags, newSVREF($b), newSVREF($c))
41  *  )
42  *
43  * Note that during the build of miniperl, a temporary copy of this file
44  * is made, called opmini.c.
45  */
46
47 /*
48 Perl's compiler is essentially a 3-pass compiler with interleaved phases:
49
50     A bottom-up pass
51     A top-down pass
52     An execution-order pass
53
54 The bottom-up pass is represented by all the "newOP" routines and
55 the ck_ routines.  The bottom-upness is actually driven by yacc.
56 So at the point that a ck_ routine fires, we have no idea what the
57 context is, either upward in the syntax tree, or either forward or
58 backward in the execution order.  (The bottom-up parser builds that
59 part of the execution order it knows about, but if you follow the "next"
60 links around, you'll find it's actually a closed loop through the
61 top level node.)
62
63 Whenever the bottom-up parser gets to a node that supplies context to
64 its components, it invokes that portion of the top-down pass that applies
65 to that part of the subtree (and marks the top node as processed, so
66 if a node further up supplies context, it doesn't have to take the
67 plunge again).  As a particular subcase of this, as the new node is
68 built, it takes all the closed execution loops of its subcomponents
69 and links them into a new closed loop for the higher level node.  But
70 it's still not the real execution order.
71
72 The actual execution order is not known till we get a grammar reduction
73 to a top-level unit like a subroutine or file that will be called by
74 "name" rather than via a "next" pointer.  At that point, we can call
75 into peep() to do that code's portion of the 3rd pass.  It has to be
76 recursive, but it's recursive on basic blocks, not on tree nodes.
77 */
78
79 /* To implement user lexical pragmas, there needs to be a way at run time to
80    get the compile time state of %^H for that block.  Storing %^H in every
81    block (or even COP) would be very expensive, so a different approach is
82    taken.  The (running) state of %^H is serialised into a tree of HE-like
83    structs.  Stores into %^H are chained onto the current leaf as a struct
84    refcounted_he * with the key and the value.  Deletes from %^H are saved
85    with a value of PL_sv_placeholder.  The state of %^H at any point can be
86    turned back into a regular HV by walking back up the tree from that point's
87    leaf, ignoring any key you've already seen (placeholder or not), storing
88    the rest into the HV structure, then removing the placeholders. Hence
89    memory is only used to store the %^H deltas from the enclosing COP, rather
90    than the entire %^H on each COP.
91
92    To cause actions on %^H to write out the serialisation records, it has
93    magic type 'H'. This magic (itself) does nothing, but its presence causes
94    the values to gain magic type 'h', which has entries for set and clear.
95    C<Perl_magic_sethint> updates C<PL_compiling.cop_hints_hash> with a store
96    record, with deletes written by C<Perl_magic_clearhint>. C<SAVEHINTS>
97    saves the current C<PL_compiling.cop_hints_hash> on the save stack, so that
98    it will be correctly restored when any inner compiling scope is exited.
99 */
100
101 #include "EXTERN.h"
102 #define PERL_IN_OP_C
103 #include "perl.h"
104 #include "keywords.h"
105 #include "feature.h"
106 #include "regcomp.h"
107
108 #define CALL_PEEP(o) PL_peepp(aTHX_ o)
109 #define CALL_RPEEP(o) PL_rpeepp(aTHX_ o)
110 #define CALL_OPFREEHOOK(o) if (PL_opfreehook) PL_opfreehook(aTHX_ o)
111
112 /* Used to avoid recursion through the op tree in scalarvoid() and
113    op_free()
114 */
115
116 #define DEFERRED_OP_STEP 100
117 #define DEFER_OP(o) \
118   STMT_START { \
119     if (UNLIKELY(defer_ix == (defer_stack_alloc-1))) {    \
120         defer_stack_alloc += DEFERRED_OP_STEP; \
121         assert(defer_stack_alloc > 0); \
122         Renew(defer_stack, defer_stack_alloc, OP *); \
123     } \
124     defer_stack[++defer_ix] = o; \
125   } STMT_END
126
127 #define POP_DEFERRED_OP() (defer_ix >= 0 ? defer_stack[defer_ix--] : (OP *)NULL)
128
129 /* remove any leading "empty" ops from the op_next chain whose first
130  * node's address is stored in op_p. Store the updated address of the
131  * first node in op_p.
132  */
133
134 STATIC void
135 S_prune_chain_head(OP** op_p)
136 {
137     while (*op_p
138         && (   (*op_p)->op_type == OP_NULL
139             || (*op_p)->op_type == OP_SCOPE
140             || (*op_p)->op_type == OP_SCALAR
141             || (*op_p)->op_type == OP_LINESEQ)
142     )
143         *op_p = (*op_p)->op_next;
144 }
145
146
147 /* See the explanatory comments above struct opslab in op.h. */
148
149 #ifdef PERL_DEBUG_READONLY_OPS
150 #  define PERL_SLAB_SIZE 128
151 #  define PERL_MAX_SLAB_SIZE 4096
152 #  include <sys/mman.h>
153 #endif
154
155 #ifndef PERL_SLAB_SIZE
156 #  define PERL_SLAB_SIZE 64
157 #endif
158 #ifndef PERL_MAX_SLAB_SIZE
159 #  define PERL_MAX_SLAB_SIZE 2048
160 #endif
161
162 /* rounds up to nearest pointer */
163 #define SIZE_TO_PSIZE(x)        (((x) + sizeof(I32 *) - 1)/sizeof(I32 *))
164 #define DIFF(o,p)               ((size_t)((I32 **)(p) - (I32**)(o)))
165
166 static OPSLAB *
167 S_new_slab(pTHX_ size_t sz)
168 {
169 #ifdef PERL_DEBUG_READONLY_OPS
170     OPSLAB *slab = (OPSLAB *) mmap(0, sz * sizeof(I32 *),
171                                    PROT_READ|PROT_WRITE,
172                                    MAP_ANON|MAP_PRIVATE, -1, 0);
173     DEBUG_m(PerlIO_printf(Perl_debug_log, "mapped %lu at %p\n",
174                           (unsigned long) sz, slab));
175     if (slab == MAP_FAILED) {
176         perror("mmap failed");
177         abort();
178     }
179     slab->opslab_size = (U16)sz;
180 #else
181     OPSLAB *slab = (OPSLAB *)PerlMemShared_calloc(sz, sizeof(I32 *));
182 #endif
183 #ifndef WIN32
184     /* The context is unused in non-Windows */
185     PERL_UNUSED_CONTEXT;
186 #endif
187     slab->opslab_first = (OPSLOT *)((I32 **)slab + sz - 1);
188     return slab;
189 }
190
191 /* requires double parens and aTHX_ */
192 #define DEBUG_S_warn(args)                                             \
193     DEBUG_S(                                                            \
194         PerlIO_printf(Perl_debug_log, "%s", SvPVx_nolen(Perl_mess args)) \
195     )
196
197 void *
198 Perl_Slab_Alloc(pTHX_ size_t sz)
199 {
200     OPSLAB *slab;
201     OPSLAB *slab2;
202     OPSLOT *slot;
203     OP *o;
204     size_t opsz, space;
205
206     /* We only allocate ops from the slab during subroutine compilation.
207        We find the slab via PL_compcv, hence that must be non-NULL. It could
208        also be pointing to a subroutine which is now fully set up (CvROOT()
209        pointing to the top of the optree for that sub), or a subroutine
210        which isn't using the slab allocator. If our sanity checks aren't met,
211        don't use a slab, but allocate the OP directly from the heap.  */
212     if (!PL_compcv || CvROOT(PL_compcv)
213      || (CvSTART(PL_compcv) && !CvSLABBED(PL_compcv)))
214     {
215         o = (OP*)PerlMemShared_calloc(1, sz);
216         goto gotit;
217     }
218
219     /* While the subroutine is under construction, the slabs are accessed via
220        CvSTART(), to avoid needing to expand PVCV by one pointer for something
221        unneeded at runtime. Once a subroutine is constructed, the slabs are
222        accessed via CvROOT(). So if CvSTART() is NULL, no slab has been
223        allocated yet.  See the commit message for 8be227ab5eaa23f2 for more
224        details.  */
225     if (!CvSTART(PL_compcv)) {
226         CvSTART(PL_compcv) =
227             (OP *)(slab = S_new_slab(aTHX_ PERL_SLAB_SIZE));
228         CvSLABBED_on(PL_compcv);
229         slab->opslab_refcnt = 2; /* one for the CV; one for the new OP */
230     }
231     else ++(slab = (OPSLAB *)CvSTART(PL_compcv))->opslab_refcnt;
232
233     opsz = SIZE_TO_PSIZE(sz);
234     sz = opsz + OPSLOT_HEADER_P;
235
236     /* The slabs maintain a free list of OPs. In particular, constant folding
237        will free up OPs, so it makes sense to re-use them where possible. A
238        freed up slot is used in preference to a new allocation.  */
239     if (slab->opslab_freed) {
240         OP **too = &slab->opslab_freed;
241         o = *too;
242         DEBUG_S_warn((aTHX_ "found free op at %p, slab %p", (void*)o, (void*)slab));
243         while (o && DIFF(OpSLOT(o), OpSLOT(o)->opslot_next) < sz) {
244             DEBUG_S_warn((aTHX_ "Alas! too small"));
245             o = *(too = &o->op_next);
246             if (o) { DEBUG_S_warn((aTHX_ "found another free op at %p", (void*)o)); }
247         }
248         if (o) {
249             *too = o->op_next;
250             Zero(o, opsz, I32 *);
251             o->op_slabbed = 1;
252             goto gotit;
253         }
254     }
255
256 #define INIT_OPSLOT \
257             slot->opslot_slab = slab;                   \
258             slot->opslot_next = slab2->opslab_first;    \
259             slab2->opslab_first = slot;                 \
260             o = &slot->opslot_op;                       \
261             o->op_slabbed = 1
262
263     /* The partially-filled slab is next in the chain. */
264     slab2 = slab->opslab_next ? slab->opslab_next : slab;
265     if ((space = DIFF(&slab2->opslab_slots, slab2->opslab_first)) < sz) {
266         /* Remaining space is too small. */
267
268         /* If we can fit a BASEOP, add it to the free chain, so as not
269            to waste it. */
270         if (space >= SIZE_TO_PSIZE(sizeof(OP)) + OPSLOT_HEADER_P) {
271             slot = &slab2->opslab_slots;
272             INIT_OPSLOT;
273             o->op_type = OP_FREED;
274             o->op_next = slab->opslab_freed;
275             slab->opslab_freed = o;
276         }
277
278         /* Create a new slab.  Make this one twice as big. */
279         slot = slab2->opslab_first;
280         while (slot->opslot_next) slot = slot->opslot_next;
281         slab2 = S_new_slab(aTHX_
282                             (DIFF(slab2, slot)+1)*2 > PERL_MAX_SLAB_SIZE
283                                         ? PERL_MAX_SLAB_SIZE
284                                         : (DIFF(slab2, slot)+1)*2);
285         slab2->opslab_next = slab->opslab_next;
286         slab->opslab_next = slab2;
287     }
288     assert(DIFF(&slab2->opslab_slots, slab2->opslab_first) >= sz);
289
290     /* Create a new op slot */
291     slot = (OPSLOT *)((I32 **)slab2->opslab_first - sz);
292     assert(slot >= &slab2->opslab_slots);
293     if (DIFF(&slab2->opslab_slots, slot)
294          < SIZE_TO_PSIZE(sizeof(OP)) + OPSLOT_HEADER_P)
295         slot = &slab2->opslab_slots;
296     INIT_OPSLOT;
297     DEBUG_S_warn((aTHX_ "allocating op at %p, slab %p", (void*)o, (void*)slab));
298
299   gotit:
300 #ifdef PERL_OP_PARENT
301     /* moresib == 0, op_sibling == 0 implies a solitary unattached op */
302     assert(!o->op_moresib);
303     assert(!o->op_sibparent);
304 #endif
305
306     return (void *)o;
307 }
308
309 #undef INIT_OPSLOT
310
311 #ifdef PERL_DEBUG_READONLY_OPS
312 void
313 Perl_Slab_to_ro(pTHX_ OPSLAB *slab)
314 {
315     PERL_ARGS_ASSERT_SLAB_TO_RO;
316
317     if (slab->opslab_readonly) return;
318     slab->opslab_readonly = 1;
319     for (; slab; slab = slab->opslab_next) {
320         /*DEBUG_U(PerlIO_printf(Perl_debug_log,"mprotect ->ro %lu at %p\n",
321                               (unsigned long) slab->opslab_size, slab));*/
322         if (mprotect(slab, slab->opslab_size * sizeof(I32 *), PROT_READ))
323             Perl_warn(aTHX_ "mprotect for %p %lu failed with %d", slab,
324                              (unsigned long)slab->opslab_size, errno);
325     }
326 }
327
328 void
329 Perl_Slab_to_rw(pTHX_ OPSLAB *const slab)
330 {
331     OPSLAB *slab2;
332
333     PERL_ARGS_ASSERT_SLAB_TO_RW;
334
335     if (!slab->opslab_readonly) return;
336     slab2 = slab;
337     for (; slab2; slab2 = slab2->opslab_next) {
338         /*DEBUG_U(PerlIO_printf(Perl_debug_log,"mprotect ->rw %lu at %p\n",
339                               (unsigned long) size, slab2));*/
340         if (mprotect((void *)slab2, slab2->opslab_size * sizeof(I32 *),
341                      PROT_READ|PROT_WRITE)) {
342             Perl_warn(aTHX_ "mprotect RW for %p %lu failed with %d", slab,
343                              (unsigned long)slab2->opslab_size, errno);
344         }
345     }
346     slab->opslab_readonly = 0;
347 }
348
349 #else
350 #  define Slab_to_rw(op)    NOOP
351 #endif
352
353 /* This cannot possibly be right, but it was copied from the old slab
354    allocator, to which it was originally added, without explanation, in
355    commit 083fcd5. */
356 #ifdef NETWARE
357 #    define PerlMemShared PerlMem
358 #endif
359
360 void
361 Perl_Slab_Free(pTHX_ void *op)
362 {
363     OP * const o = (OP *)op;
364     OPSLAB *slab;
365
366     PERL_ARGS_ASSERT_SLAB_FREE;
367
368     if (!o->op_slabbed) {
369         if (!o->op_static)
370             PerlMemShared_free(op);
371         return;
372     }
373
374     slab = OpSLAB(o);
375     /* If this op is already freed, our refcount will get screwy. */
376     assert(o->op_type != OP_FREED);
377     o->op_type = OP_FREED;
378     o->op_next = slab->opslab_freed;
379     slab->opslab_freed = o;
380     DEBUG_S_warn((aTHX_ "free op at %p, recorded in slab %p", (void*)o, (void*)slab));
381     OpslabREFCNT_dec_padok(slab);
382 }
383
384 void
385 Perl_opslab_free_nopad(pTHX_ OPSLAB *slab)
386 {
387     const bool havepad = !!PL_comppad;
388     PERL_ARGS_ASSERT_OPSLAB_FREE_NOPAD;
389     if (havepad) {
390         ENTER;
391         PAD_SAVE_SETNULLPAD();
392     }
393     opslab_free(slab);
394     if (havepad) LEAVE;
395 }
396
397 void
398 Perl_opslab_free(pTHX_ OPSLAB *slab)
399 {
400     OPSLAB *slab2;
401     PERL_ARGS_ASSERT_OPSLAB_FREE;
402     PERL_UNUSED_CONTEXT;
403     DEBUG_S_warn((aTHX_ "freeing slab %p", (void*)slab));
404     assert(slab->opslab_refcnt == 1);
405     do {
406         slab2 = slab->opslab_next;
407 #ifdef DEBUGGING
408         slab->opslab_refcnt = ~(size_t)0;
409 #endif
410 #ifdef PERL_DEBUG_READONLY_OPS
411         DEBUG_m(PerlIO_printf(Perl_debug_log, "Deallocate slab at %p\n",
412                                                (void*)slab));
413         if (munmap(slab, slab->opslab_size * sizeof(I32 *))) {
414             perror("munmap failed");
415             abort();
416         }
417 #else
418         PerlMemShared_free(slab);
419 #endif
420         slab = slab2;
421     } while (slab);
422 }
423
424 void
425 Perl_opslab_force_free(pTHX_ OPSLAB *slab)
426 {
427     OPSLAB *slab2;
428     OPSLOT *slot;
429 #ifdef DEBUGGING
430     size_t savestack_count = 0;
431 #endif
432     PERL_ARGS_ASSERT_OPSLAB_FORCE_FREE;
433     slab2 = slab;
434     do {
435         for (slot = slab2->opslab_first;
436              slot->opslot_next;
437              slot = slot->opslot_next) {
438             if (slot->opslot_op.op_type != OP_FREED
439              && !(slot->opslot_op.op_savefree
440 #ifdef DEBUGGING
441                   && ++savestack_count
442 #endif
443                  )
444             ) {
445                 assert(slot->opslot_op.op_slabbed);
446                 op_free(&slot->opslot_op);
447                 if (slab->opslab_refcnt == 1) goto free;
448             }
449         }
450     } while ((slab2 = slab2->opslab_next));
451     /* > 1 because the CV still holds a reference count. */
452     if (slab->opslab_refcnt > 1) { /* still referenced by the savestack */
453 #ifdef DEBUGGING
454         assert(savestack_count == slab->opslab_refcnt-1);
455 #endif
456         /* Remove the CV’s reference count. */
457         slab->opslab_refcnt--;
458         return;
459     }
460    free:
461     opslab_free(slab);
462 }
463
464 #ifdef PERL_DEBUG_READONLY_OPS
465 OP *
466 Perl_op_refcnt_inc(pTHX_ OP *o)
467 {
468     if(o) {
469         OPSLAB *const slab = o->op_slabbed ? OpSLAB(o) : NULL;
470         if (slab && slab->opslab_readonly) {
471             Slab_to_rw(slab);
472             ++o->op_targ;
473             Slab_to_ro(slab);
474         } else {
475             ++o->op_targ;
476         }
477     }
478     return o;
479
480 }
481
482 PADOFFSET
483 Perl_op_refcnt_dec(pTHX_ OP *o)
484 {
485     PADOFFSET result;
486     OPSLAB *const slab = o->op_slabbed ? OpSLAB(o) : NULL;
487
488     PERL_ARGS_ASSERT_OP_REFCNT_DEC;
489
490     if (slab && slab->opslab_readonly) {
491         Slab_to_rw(slab);
492         result = --o->op_targ;
493         Slab_to_ro(slab);
494     } else {
495         result = --o->op_targ;
496     }
497     return result;
498 }
499 #endif
500 /*
501  * In the following definition, the ", (OP*)0" is just to make the compiler
502  * think the expression is of the right type: croak actually does a Siglongjmp.
503  */
504 #define CHECKOP(type,o) \
505     ((PL_op_mask && PL_op_mask[type])                           \
506      ? ( op_free((OP*)o),                                       \
507          Perl_croak(aTHX_ "'%s' trapped by operation mask", PL_op_desc[type]),  \
508          (OP*)0 )                                               \
509      : PL_check[type](aTHX_ (OP*)o))
510
511 #define RETURN_UNLIMITED_NUMBER (PERL_INT_MAX / 2)
512
513 #define OpTYPE_set(o,type) \
514     STMT_START {                                \
515         o->op_type = (OPCODE)type;              \
516         o->op_ppaddr = PL_ppaddr[type];         \
517     } STMT_END
518
519 STATIC OP *
520 S_no_fh_allowed(pTHX_ OP *o)
521 {
522     PERL_ARGS_ASSERT_NO_FH_ALLOWED;
523
524     yyerror(Perl_form(aTHX_ "Missing comma after first argument to %s function",
525                  OP_DESC(o)));
526     return o;
527 }
528
529 STATIC OP *
530 S_too_few_arguments_pv(pTHX_ OP *o, const char* name, U32 flags)
531 {
532     PERL_ARGS_ASSERT_TOO_FEW_ARGUMENTS_PV;
533     yyerror_pv(Perl_form(aTHX_ "Not enough arguments for %s", name), flags);
534     return o;
535 }
536  
537 STATIC OP *
538 S_too_many_arguments_pv(pTHX_ OP *o, const char *name, U32 flags)
539 {
540     PERL_ARGS_ASSERT_TOO_MANY_ARGUMENTS_PV;
541
542     yyerror_pv(Perl_form(aTHX_ "Too many arguments for %s", name), flags);
543     return o;
544 }
545
546 STATIC void
547 S_bad_type_pv(pTHX_ I32 n, const char *t, const OP *o, const OP *kid)
548 {
549     PERL_ARGS_ASSERT_BAD_TYPE_PV;
550
551     yyerror_pv(Perl_form(aTHX_ "Type of arg %d to %s must be %s (not %s)",
552                  (int)n, PL_op_desc[(o)->op_type], t, OP_DESC(kid)), 0);
553 }
554
555 /* remove flags var, its unused in all callers, move to to right end since gv
556   and kid are always the same */
557 STATIC void
558 S_bad_type_gv(pTHX_ I32 n, GV *gv, const OP *kid, const char *t)
559 {
560     SV * const namesv = cv_name((CV *)gv, NULL, 0);
561     PERL_ARGS_ASSERT_BAD_TYPE_GV;
562  
563     yyerror_pv(Perl_form(aTHX_ "Type of arg %d to %"SVf" must be %s (not %s)",
564                  (int)n, SVfARG(namesv), t, OP_DESC(kid)), SvUTF8(namesv));
565 }
566
567 STATIC void
568 S_no_bareword_allowed(pTHX_ OP *o)
569 {
570     PERL_ARGS_ASSERT_NO_BAREWORD_ALLOWED;
571
572     qerror(Perl_mess(aTHX_
573                      "Bareword \"%"SVf"\" not allowed while \"strict subs\" in use",
574                      SVfARG(cSVOPo_sv)));
575     o->op_private &= ~OPpCONST_STRICT; /* prevent warning twice about the same OP */
576 }
577
578 /* "register" allocation */
579
580 PADOFFSET
581 Perl_allocmy(pTHX_ const char *const name, const STRLEN len, const U32 flags)
582 {
583     PADOFFSET off;
584     const bool is_our = (PL_parser->in_my == KEY_our);
585
586     PERL_ARGS_ASSERT_ALLOCMY;
587
588     if (flags & ~SVf_UTF8)
589         Perl_croak(aTHX_ "panic: allocmy illegal flag bits 0x%" UVxf,
590                    (UV)flags);
591
592     /* complain about "my $<special_var>" etc etc */
593     if (len &&
594         !(is_our ||
595           isALPHA(name[1]) ||
596           ((flags & SVf_UTF8) && isIDFIRST_utf8((U8 *)name+1)) ||
597           (name[1] == '_' && len > 2)))
598     {
599         if (!(flags & SVf_UTF8 && UTF8_IS_START(name[1]))
600          && isASCII(name[1])
601          && (!isPRINT(name[1]) || strchr("\t\n\r\f", name[1]))) {
602             yyerror(Perl_form(aTHX_ "Can't use global %c^%c%.*s in \"%s\"",
603                               name[0], toCTRL(name[1]), (int)(len - 2), name + 2,
604                               PL_parser->in_my == KEY_state ? "state" : "my"));
605         } else {
606             yyerror_pv(Perl_form(aTHX_ "Can't use global %.*s in \"%s\"", (int) len, name,
607                               PL_parser->in_my == KEY_state ? "state" : "my"), flags & SVf_UTF8);
608         }
609     }
610
611     /* allocate a spare slot and store the name in that slot */
612
613     off = pad_add_name_pvn(name, len,
614                        (is_our ? padadd_OUR :
615                         PL_parser->in_my == KEY_state ? padadd_STATE : 0),
616                     PL_parser->in_my_stash,
617                     (is_our
618                         /* $_ is always in main::, even with our */
619                         ? (PL_curstash && !memEQs(name,len,"$_")
620                             ? PL_curstash
621                             : PL_defstash)
622                         : NULL
623                     )
624     );
625     /* anon sub prototypes contains state vars should always be cloned,
626      * otherwise the state var would be shared between anon subs */
627
628     if (PL_parser->in_my == KEY_state && CvANON(PL_compcv))
629         CvCLONE_on(PL_compcv);
630
631     return off;
632 }
633
634 /*
635 =head1 Optree Manipulation Functions
636
637 =for apidoc alloccopstash
638
639 Available only under threaded builds, this function allocates an entry in
640 C<PL_stashpad> for the stash passed to it.
641
642 =cut
643 */
644
645 #ifdef USE_ITHREADS
646 PADOFFSET
647 Perl_alloccopstash(pTHX_ HV *hv)
648 {
649     PADOFFSET off = 0, o = 1;
650     bool found_slot = FALSE;
651
652     PERL_ARGS_ASSERT_ALLOCCOPSTASH;
653
654     if (PL_stashpad[PL_stashpadix] == hv) return PL_stashpadix;
655
656     for (; o < PL_stashpadmax; ++o) {
657         if (PL_stashpad[o] == hv) return PL_stashpadix = o;
658         if (!PL_stashpad[o] || SvTYPE(PL_stashpad[o]) != SVt_PVHV)
659             found_slot = TRUE, off = o;
660     }
661     if (!found_slot) {
662         Renew(PL_stashpad, PL_stashpadmax + 10, HV *);
663         Zero(PL_stashpad + PL_stashpadmax, 10, HV *);
664         off = PL_stashpadmax;
665         PL_stashpadmax += 10;
666     }
667
668     PL_stashpad[PL_stashpadix = off] = hv;
669     return off;
670 }
671 #endif
672
673 /* free the body of an op without examining its contents.
674  * Always use this rather than FreeOp directly */
675
676 static void
677 S_op_destroy(pTHX_ OP *o)
678 {
679     FreeOp(o);
680 }
681
682 /* Destructor */
683
684 /*
685 =for apidoc Am|void|op_free|OP *o
686
687 Free an op.  Only use this when an op is no longer linked to from any
688 optree.
689
690 =cut
691 */
692
693 void
694 Perl_op_free(pTHX_ OP *o)
695 {
696     dVAR;
697     OPCODE type;
698     SSize_t defer_ix = -1;
699     SSize_t defer_stack_alloc = 0;
700     OP **defer_stack = NULL;
701
702     do {
703
704         /* Though ops may be freed twice, freeing the op after its slab is a
705            big no-no. */
706         assert(!o || !o->op_slabbed || OpSLAB(o)->opslab_refcnt != ~(size_t)0);
707         /* During the forced freeing of ops after compilation failure, kidops
708            may be freed before their parents. */
709         if (!o || o->op_type == OP_FREED)
710             continue;
711
712         type = o->op_type;
713
714         /* an op should only ever acquire op_private flags that we know about.
715          * If this fails, you may need to fix something in regen/op_private.
716          * Don't bother testing if:
717          *   * the op_ppaddr doesn't match the op; someone may have
718          *     overridden the op and be doing strange things with it;
719          *   * we've errored, as op flags are often left in an
720          *     inconsistent state then. Note that an error when
721          *     compiling the main program leaves PL_parser NULL, so
722          *     we can't spot faults in the main code, only
723          *     evaled/required code */
724 #ifdef DEBUGGING
725         if (   o->op_ppaddr == PL_ppaddr[o->op_type]
726             && PL_parser
727             && !PL_parser->error_count)
728         {
729             assert(!(o->op_private & ~PL_op_private_valid[type]));
730         }
731 #endif
732
733         if (o->op_private & OPpREFCOUNTED) {
734             switch (type) {
735             case OP_LEAVESUB:
736             case OP_LEAVESUBLV:
737             case OP_LEAVEEVAL:
738             case OP_LEAVE:
739             case OP_SCOPE:
740             case OP_LEAVEWRITE:
741                 {
742                 PADOFFSET refcnt;
743                 OP_REFCNT_LOCK;
744                 refcnt = OpREFCNT_dec(o);
745                 OP_REFCNT_UNLOCK;
746                 if (refcnt) {
747                     /* Need to find and remove any pattern match ops from the list
748                        we maintain for reset().  */
749                     find_and_forget_pmops(o);
750                     continue;
751                 }
752                 }
753                 break;
754             default:
755                 break;
756             }
757         }
758
759         /* Call the op_free hook if it has been set. Do it now so that it's called
760          * at the right time for refcounted ops, but still before all of the kids
761          * are freed. */
762         CALL_OPFREEHOOK(o);
763
764         if (o->op_flags & OPf_KIDS) {
765             OP *kid, *nextkid;
766             for (kid = cUNOPo->op_first; kid; kid = nextkid) {
767                 nextkid = OpSIBLING(kid); /* Get before next freeing kid */
768                 if (!kid || kid->op_type == OP_FREED)
769                     /* During the forced freeing of ops after
770                        compilation failure, kidops may be freed before
771                        their parents. */
772                     continue;
773                 if (!(kid->op_flags & OPf_KIDS))
774                     /* If it has no kids, just free it now */
775                     op_free(kid);
776                 else
777                     DEFER_OP(kid);
778             }
779         }
780         if (type == OP_NULL)
781             type = (OPCODE)o->op_targ;
782
783         if (o->op_slabbed)
784             Slab_to_rw(OpSLAB(o));
785
786         /* COP* is not cleared by op_clear() so that we may track line
787          * numbers etc even after null() */
788         if (type == OP_NEXTSTATE || type == OP_DBSTATE) {
789             cop_free((COP*)o);
790         }
791
792         op_clear(o);
793         FreeOp(o);
794 #ifdef DEBUG_LEAKING_SCALARS
795         if (PL_op == o)
796             PL_op = NULL;
797 #endif
798     } while ( (o = POP_DEFERRED_OP()) );
799
800     Safefree(defer_stack);
801 }
802
803 /* S_op_clear_gv(): free a GV attached to an OP */
804
805 #ifdef USE_ITHREADS
806 void S_op_clear_gv(pTHX_ OP *o, PADOFFSET *ixp)
807 #else
808 void S_op_clear_gv(pTHX_ OP *o, SV**svp)
809 #endif
810 {
811
812     GV *gv = (o->op_type == OP_GV || o->op_type == OP_GVSV
813             || o->op_type == OP_MULTIDEREF)
814 #ifdef USE_ITHREADS
815                 && PL_curpad
816                 ? ((GV*)PAD_SVl(*ixp)) : NULL;
817 #else
818                 ? (GV*)(*svp) : NULL;
819 #endif
820     /* It's possible during global destruction that the GV is freed
821        before the optree. Whilst the SvREFCNT_inc is happy to bump from
822        0 to 1 on a freed SV, the corresponding SvREFCNT_dec from 1 to 0
823        will trigger an assertion failure, because the entry to sv_clear
824        checks that the scalar is not already freed.  A check of for
825        !SvIS_FREED(gv) turns out to be invalid, because during global
826        destruction the reference count can be forced down to zero
827        (with SVf_BREAK set).  In which case raising to 1 and then
828        dropping to 0 triggers cleanup before it should happen.  I
829        *think* that this might actually be a general, systematic,
830        weakness of the whole idea of SVf_BREAK, in that code *is*
831        allowed to raise and lower references during global destruction,
832        so any *valid* code that happens to do this during global
833        destruction might well trigger premature cleanup.  */
834     bool still_valid = gv && SvREFCNT(gv);
835
836     if (still_valid)
837         SvREFCNT_inc_simple_void(gv);
838 #ifdef USE_ITHREADS
839     if (*ixp > 0) {
840         pad_swipe(*ixp, TRUE);
841         *ixp = 0;
842     }
843 #else
844     SvREFCNT_dec(*svp);
845     *svp = NULL;
846 #endif
847     if (still_valid) {
848         int try_downgrade = SvREFCNT(gv) == 2;
849         SvREFCNT_dec_NN(gv);
850         if (try_downgrade)
851             gv_try_downgrade(gv);
852     }
853 }
854
855
856 void
857 Perl_op_clear(pTHX_ OP *o)
858 {
859
860     dVAR;
861
862     PERL_ARGS_ASSERT_OP_CLEAR;
863
864     switch (o->op_type) {
865     case OP_NULL:       /* Was holding old type, if any. */
866         /* FALLTHROUGH */
867     case OP_ENTERTRY:
868     case OP_ENTEREVAL:  /* Was holding hints. */
869         o->op_targ = 0;
870         break;
871     default:
872         if (!(o->op_flags & OPf_REF)
873             || (PL_check[o->op_type] != Perl_ck_ftst))
874             break;
875         /* FALLTHROUGH */
876     case OP_GVSV:
877     case OP_GV:
878     case OP_AELEMFAST:
879 #ifdef USE_ITHREADS
880             S_op_clear_gv(aTHX_ o, &(cPADOPx(o)->op_padix));
881 #else
882             S_op_clear_gv(aTHX_ o, &(cSVOPx(o)->op_sv));
883 #endif
884         break;
885     case OP_METHOD_REDIR:
886     case OP_METHOD_REDIR_SUPER:
887 #ifdef USE_ITHREADS
888         if (cMETHOPx(o)->op_rclass_targ) {
889             pad_swipe(cMETHOPx(o)->op_rclass_targ, 1);
890             cMETHOPx(o)->op_rclass_targ = 0;
891         }
892 #else
893         SvREFCNT_dec(cMETHOPx(o)->op_rclass_sv);
894         cMETHOPx(o)->op_rclass_sv = NULL;
895 #endif
896     case OP_METHOD_NAMED:
897     case OP_METHOD_SUPER:
898         SvREFCNT_dec(cMETHOPx(o)->op_u.op_meth_sv);
899         cMETHOPx(o)->op_u.op_meth_sv = NULL;
900 #ifdef USE_ITHREADS
901         if (o->op_targ) {
902             pad_swipe(o->op_targ, 1);
903             o->op_targ = 0;
904         }
905 #endif
906         break;
907     case OP_CONST:
908     case OP_HINTSEVAL:
909         SvREFCNT_dec(cSVOPo->op_sv);
910         cSVOPo->op_sv = NULL;
911 #ifdef USE_ITHREADS
912         /** Bug #15654
913           Even if op_clear does a pad_free for the target of the op,
914           pad_free doesn't actually remove the sv that exists in the pad;
915           instead it lives on. This results in that it could be reused as 
916           a target later on when the pad was reallocated.
917         **/
918         if(o->op_targ) {
919           pad_swipe(o->op_targ,1);
920           o->op_targ = 0;
921         }
922 #endif
923         break;
924     case OP_DUMP:
925     case OP_GOTO:
926     case OP_NEXT:
927     case OP_LAST:
928     case OP_REDO:
929         if (o->op_flags & (OPf_SPECIAL|OPf_STACKED|OPf_KIDS))
930             break;
931         /* FALLTHROUGH */
932     case OP_TRANS:
933     case OP_TRANSR:
934         if (o->op_private & (OPpTRANS_FROM_UTF|OPpTRANS_TO_UTF)) {
935             assert(o->op_type == OP_TRANS || o->op_type == OP_TRANSR);
936 #ifdef USE_ITHREADS
937             if (cPADOPo->op_padix > 0) {
938                 pad_swipe(cPADOPo->op_padix, TRUE);
939                 cPADOPo->op_padix = 0;
940             }
941 #else
942             SvREFCNT_dec(cSVOPo->op_sv);
943             cSVOPo->op_sv = NULL;
944 #endif
945         }
946         else {
947             PerlMemShared_free(cPVOPo->op_pv);
948             cPVOPo->op_pv = NULL;
949         }
950         break;
951     case OP_SUBST:
952         op_free(cPMOPo->op_pmreplrootu.op_pmreplroot);
953         goto clear_pmop;
954     case OP_PUSHRE:
955 #ifdef USE_ITHREADS
956         if (cPMOPo->op_pmreplrootu.op_pmtargetoff) {
957             pad_swipe(cPMOPo->op_pmreplrootu.op_pmtargetoff, TRUE);
958         }
959 #else
960         SvREFCNT_dec(MUTABLE_SV(cPMOPo->op_pmreplrootu.op_pmtargetgv));
961 #endif
962         /* FALLTHROUGH */
963     case OP_MATCH:
964     case OP_QR:
965     clear_pmop:
966         if (!(cPMOPo->op_pmflags & PMf_CODELIST_PRIVATE))
967             op_free(cPMOPo->op_code_list);
968         cPMOPo->op_code_list = NULL;
969         forget_pmop(cPMOPo);
970         cPMOPo->op_pmreplrootu.op_pmreplroot = NULL;
971         /* we use the same protection as the "SAFE" version of the PM_ macros
972          * here since sv_clean_all might release some PMOPs
973          * after PL_regex_padav has been cleared
974          * and the clearing of PL_regex_padav needs to
975          * happen before sv_clean_all
976          */
977 #ifdef USE_ITHREADS
978         if(PL_regex_pad) {        /* We could be in destruction */
979             const IV offset = (cPMOPo)->op_pmoffset;
980             ReREFCNT_dec(PM_GETRE(cPMOPo));
981             PL_regex_pad[offset] = &PL_sv_undef;
982             sv_catpvn_nomg(PL_regex_pad[0], (const char *)&offset,
983                            sizeof(offset));
984         }
985 #else
986         ReREFCNT_dec(PM_GETRE(cPMOPo));
987         PM_SETRE(cPMOPo, NULL);
988 #endif
989
990         break;
991
992     case OP_MULTIDEREF:
993         {
994             UNOP_AUX_item *items = cUNOP_AUXo->op_aux;
995             UV actions = items->uv;
996             bool last = 0;
997             bool is_hash = FALSE;
998
999             while (!last) {
1000                 switch (actions & MDEREF_ACTION_MASK) {
1001
1002                 case MDEREF_reload:
1003                     actions = (++items)->uv;
1004                     continue;
1005
1006                 case MDEREF_HV_padhv_helem:
1007                     is_hash = TRUE;
1008                 case MDEREF_AV_padav_aelem:
1009                     pad_free((++items)->pad_offset);
1010                     goto do_elem;
1011
1012                 case MDEREF_HV_gvhv_helem:
1013                     is_hash = TRUE;
1014                 case MDEREF_AV_gvav_aelem:
1015 #ifdef USE_ITHREADS
1016                     S_op_clear_gv(aTHX_ o, &((++items)->pad_offset));
1017 #else
1018                     S_op_clear_gv(aTHX_ o, &((++items)->sv));
1019 #endif
1020                     goto do_elem;
1021
1022                 case MDEREF_HV_gvsv_vivify_rv2hv_helem:
1023                     is_hash = TRUE;
1024                 case MDEREF_AV_gvsv_vivify_rv2av_aelem:
1025 #ifdef USE_ITHREADS
1026                     S_op_clear_gv(aTHX_ o, &((++items)->pad_offset));
1027 #else
1028                     S_op_clear_gv(aTHX_ o, &((++items)->sv));
1029 #endif
1030                     goto do_vivify_rv2xv_elem;
1031
1032                 case MDEREF_HV_padsv_vivify_rv2hv_helem:
1033                     is_hash = TRUE;
1034                 case MDEREF_AV_padsv_vivify_rv2av_aelem:
1035                     pad_free((++items)->pad_offset);
1036                     goto do_vivify_rv2xv_elem;
1037
1038                 case MDEREF_HV_pop_rv2hv_helem:
1039                 case MDEREF_HV_vivify_rv2hv_helem:
1040                     is_hash = TRUE;
1041                 do_vivify_rv2xv_elem:
1042                 case MDEREF_AV_pop_rv2av_aelem:
1043                 case MDEREF_AV_vivify_rv2av_aelem:
1044                 do_elem:
1045                     switch (actions & MDEREF_INDEX_MASK) {
1046                     case MDEREF_INDEX_none:
1047                         last = 1;
1048                         break;
1049                     case MDEREF_INDEX_const:
1050                         if (is_hash) {
1051 #ifdef USE_ITHREADS
1052                             /* see RT #15654 */
1053                             pad_swipe((++items)->pad_offset, 1);
1054 #else
1055                             SvREFCNT_dec((++items)->sv);
1056 #endif
1057                         }
1058                         else
1059                             items++;
1060                         break;
1061                     case MDEREF_INDEX_padsv:
1062                         pad_free((++items)->pad_offset);
1063                         break;
1064                     case MDEREF_INDEX_gvsv:
1065 #ifdef USE_ITHREADS
1066                         S_op_clear_gv(aTHX_ o, &((++items)->pad_offset));
1067 #else
1068                         S_op_clear_gv(aTHX_ o, &((++items)->sv));
1069 #endif
1070                         break;
1071                     }
1072
1073                     if (actions & MDEREF_FLAG_last)
1074                         last = 1;
1075                     is_hash = FALSE;
1076
1077                     break;
1078
1079                 default:
1080                     assert(0);
1081                     last = 1;
1082                     break;
1083
1084                 } /* switch */
1085
1086                 actions >>= MDEREF_SHIFT;
1087             } /* while */
1088
1089             /* start of malloc is at op_aux[-1], where the length is
1090              * stored */
1091             PerlMemShared_free(cUNOP_AUXo->op_aux - 1);
1092         }
1093         break;
1094     }
1095
1096     if (o->op_targ > 0) {
1097         pad_free(o->op_targ);
1098         o->op_targ = 0;
1099     }
1100 }
1101
1102 STATIC void
1103 S_cop_free(pTHX_ COP* cop)
1104 {
1105     PERL_ARGS_ASSERT_COP_FREE;
1106
1107     CopFILE_free(cop);
1108     if (! specialWARN(cop->cop_warnings))
1109         PerlMemShared_free(cop->cop_warnings);
1110     cophh_free(CopHINTHASH_get(cop));
1111     if (PL_curcop == cop)
1112        PL_curcop = NULL;
1113 }
1114
1115 STATIC void
1116 S_forget_pmop(pTHX_ PMOP *const o
1117               )
1118 {
1119     HV * const pmstash = PmopSTASH(o);
1120
1121     PERL_ARGS_ASSERT_FORGET_PMOP;
1122
1123     if (pmstash && !SvIS_FREED(pmstash) && SvMAGICAL(pmstash)) {
1124         MAGIC * const mg = mg_find((const SV *)pmstash, PERL_MAGIC_symtab);
1125         if (mg) {
1126             PMOP **const array = (PMOP**) mg->mg_ptr;
1127             U32 count = mg->mg_len / sizeof(PMOP**);
1128             U32 i = count;
1129
1130             while (i--) {
1131                 if (array[i] == o) {
1132                     /* Found it. Move the entry at the end to overwrite it.  */
1133                     array[i] = array[--count];
1134                     mg->mg_len = count * sizeof(PMOP**);
1135                     /* Could realloc smaller at this point always, but probably
1136                        not worth it. Probably worth free()ing if we're the
1137                        last.  */
1138                     if(!count) {
1139                         Safefree(mg->mg_ptr);
1140                         mg->mg_ptr = NULL;
1141                     }
1142                     break;
1143                 }
1144             }
1145         }
1146     }
1147     if (PL_curpm == o) 
1148         PL_curpm = NULL;
1149 }
1150
1151 STATIC void
1152 S_find_and_forget_pmops(pTHX_ OP *o)
1153 {
1154     PERL_ARGS_ASSERT_FIND_AND_FORGET_PMOPS;
1155
1156     if (o->op_flags & OPf_KIDS) {
1157         OP *kid = cUNOPo->op_first;
1158         while (kid) {
1159             switch (kid->op_type) {
1160             case OP_SUBST:
1161             case OP_PUSHRE:
1162             case OP_MATCH:
1163             case OP_QR:
1164                 forget_pmop((PMOP*)kid);
1165             }
1166             find_and_forget_pmops(kid);
1167             kid = OpSIBLING(kid);
1168         }
1169     }
1170 }
1171
1172 /*
1173 =for apidoc Am|void|op_null|OP *o
1174
1175 Neutralizes an op when it is no longer needed, but is still linked to from
1176 other ops.
1177
1178 =cut
1179 */
1180
1181 void
1182 Perl_op_null(pTHX_ OP *o)
1183 {
1184     dVAR;
1185
1186     PERL_ARGS_ASSERT_OP_NULL;
1187
1188     if (o->op_type == OP_NULL)
1189         return;
1190     op_clear(o);
1191     o->op_targ = o->op_type;
1192     OpTYPE_set(o, OP_NULL);
1193 }
1194
1195 void
1196 Perl_op_refcnt_lock(pTHX)
1197   PERL_TSA_ACQUIRE(PL_op_mutex)
1198 {
1199 #ifdef USE_ITHREADS
1200     dVAR;
1201 #endif
1202     PERL_UNUSED_CONTEXT;
1203     OP_REFCNT_LOCK;
1204 }
1205
1206 void
1207 Perl_op_refcnt_unlock(pTHX)
1208   PERL_TSA_RELEASE(PL_op_mutex)
1209 {
1210 #ifdef USE_ITHREADS
1211     dVAR;
1212 #endif
1213     PERL_UNUSED_CONTEXT;
1214     OP_REFCNT_UNLOCK;
1215 }
1216
1217
1218 /*
1219 =for apidoc op_sibling_splice
1220
1221 A general function for editing the structure of an existing chain of
1222 op_sibling nodes.  By analogy with the perl-level C<splice()> function, allows
1223 you to delete zero or more sequential nodes, replacing them with zero or
1224 more different nodes.  Performs the necessary op_first/op_last
1225 housekeeping on the parent node and op_sibling manipulation on the
1226 children.  The last deleted node will be marked as as the last node by
1227 updating the op_sibling/op_sibparent or op_moresib field as appropriate.
1228
1229 Note that op_next is not manipulated, and nodes are not freed; that is the
1230 responsibility of the caller.  It also won't create a new list op for an
1231 empty list etc; use higher-level functions like op_append_elem() for that.
1232
1233 C<parent> is the parent node of the sibling chain. It may passed as C<NULL> if
1234 the splicing doesn't affect the first or last op in the chain.
1235
1236 C<start> is the node preceding the first node to be spliced.  Node(s)
1237 following it will be deleted, and ops will be inserted after it.  If it is
1238 C<NULL>, the first node onwards is deleted, and nodes are inserted at the
1239 beginning.
1240
1241 C<del_count> is the number of nodes to delete.  If zero, no nodes are deleted.
1242 If -1 or greater than or equal to the number of remaining kids, all
1243 remaining kids are deleted.
1244
1245 C<insert> is the first of a chain of nodes to be inserted in place of the nodes.
1246 If C<NULL>, no nodes are inserted.
1247
1248 The head of the chain of deleted ops is returned, or C<NULL> if no ops were
1249 deleted.
1250
1251 For example:
1252
1253     action                    before      after         returns
1254     ------                    -----       -----         -------
1255
1256                               P           P
1257     splice(P, A, 2, X-Y-Z)    |           |             B-C
1258                               A-B-C-D     A-X-Y-Z-D
1259
1260                               P           P
1261     splice(P, NULL, 1, X-Y)   |           |             A
1262                               A-B-C-D     X-Y-B-C-D
1263
1264                               P           P
1265     splice(P, NULL, 3, NULL)  |           |             A-B-C
1266                               A-B-C-D     D
1267
1268                               P           P
1269     splice(P, B, 0, X-Y)      |           |             NULL
1270                               A-B-C-D     A-B-X-Y-C-D
1271
1272
1273 For lower-level direct manipulation of C<op_sibparent> and C<op_moresib>,
1274 see C<L</OpMORESIB_set>>, C<L</OpLASTSIB_set>>, C<L</OpMAYBESIB_set>>.
1275
1276 =cut
1277 */
1278
1279 OP *
1280 Perl_op_sibling_splice(OP *parent, OP *start, int del_count, OP* insert)
1281 {
1282     OP *first;
1283     OP *rest;
1284     OP *last_del = NULL;
1285     OP *last_ins = NULL;
1286
1287     if (start)
1288         first = OpSIBLING(start);
1289     else if (!parent)
1290         goto no_parent;
1291     else
1292         first = cLISTOPx(parent)->op_first;
1293
1294     assert(del_count >= -1);
1295
1296     if (del_count && first) {
1297         last_del = first;
1298         while (--del_count && OpHAS_SIBLING(last_del))
1299             last_del = OpSIBLING(last_del);
1300         rest = OpSIBLING(last_del);
1301         OpLASTSIB_set(last_del, NULL);
1302     }
1303     else
1304         rest = first;
1305
1306     if (insert) {
1307         last_ins = insert;
1308         while (OpHAS_SIBLING(last_ins))
1309             last_ins = OpSIBLING(last_ins);
1310         OpMAYBESIB_set(last_ins, rest, NULL);
1311     }
1312     else
1313         insert = rest;
1314
1315     if (start) {
1316         OpMAYBESIB_set(start, insert, NULL);
1317     }
1318     else {
1319         if (!parent)
1320             goto no_parent;
1321         cLISTOPx(parent)->op_first = insert;
1322         if (insert)
1323             parent->op_flags |= OPf_KIDS;
1324         else
1325             parent->op_flags &= ~OPf_KIDS;
1326     }
1327
1328     if (!rest) {
1329         /* update op_last etc */
1330         U32 type;
1331         OP *lastop;
1332
1333         if (!parent)
1334             goto no_parent;
1335
1336         /* ought to use OP_CLASS(parent) here, but that can't handle
1337          * ex-foo OP_NULL ops. Also note that XopENTRYCUSTOM() can't
1338          * either */
1339         type = parent->op_type;
1340         if (type == OP_CUSTOM) {
1341             dTHX;
1342             type = XopENTRYCUSTOM(parent, xop_class);
1343         }
1344         else {
1345             if (type == OP_NULL)
1346                 type = parent->op_targ;
1347             type = PL_opargs[type] & OA_CLASS_MASK;
1348         }
1349
1350         lastop = last_ins ? last_ins : start ? start : NULL;
1351         if (   type == OA_BINOP
1352             || type == OA_LISTOP
1353             || type == OA_PMOP
1354             || type == OA_LOOP
1355         )
1356             cLISTOPx(parent)->op_last = lastop;
1357
1358         if (lastop)
1359             OpLASTSIB_set(lastop, parent);
1360     }
1361     return last_del ? first : NULL;
1362
1363   no_parent:
1364     Perl_croak_nocontext("panic: op_sibling_splice(): NULL parent");
1365 }
1366
1367
1368 #ifdef PERL_OP_PARENT
1369
1370 /*
1371 =for apidoc op_parent
1372
1373 Returns the parent OP of C<o>, if it has a parent. Returns C<NULL> otherwise.
1374 This function is only available on perls built with C<-DPERL_OP_PARENT>.
1375
1376 =cut
1377 */
1378
1379 OP *
1380 Perl_op_parent(OP *o)
1381 {
1382     PERL_ARGS_ASSERT_OP_PARENT;
1383     while (OpHAS_SIBLING(o))
1384         o = OpSIBLING(o);
1385     return o->op_sibparent;
1386 }
1387
1388 #endif
1389
1390
1391 /* replace the sibling following start with a new UNOP, which becomes
1392  * the parent of the original sibling; e.g.
1393  *
1394  *  op_sibling_newUNOP(P, A, unop-args...)
1395  *
1396  *  P              P
1397  *  |      becomes |
1398  *  A-B-C          A-U-C
1399  *                   |
1400  *                   B
1401  *
1402  * where U is the new UNOP.
1403  *
1404  * parent and start args are the same as for op_sibling_splice();
1405  * type and flags args are as newUNOP().
1406  *
1407  * Returns the new UNOP.
1408  */
1409
1410 OP *
1411 S_op_sibling_newUNOP(pTHX_ OP *parent, OP *start, I32 type, I32 flags)
1412 {
1413     OP *kid, *newop;
1414
1415     kid = op_sibling_splice(parent, start, 1, NULL);
1416     newop = newUNOP(type, flags, kid);
1417     op_sibling_splice(parent, start, 0, newop);
1418     return newop;
1419 }
1420
1421
1422 /* lowest-level newLOGOP-style function - just allocates and populates
1423  * the struct. Higher-level stuff should be done by S_new_logop() /
1424  * newLOGOP(). This function exists mainly to avoid op_first assignment
1425  * being spread throughout this file.
1426  */
1427
1428 LOGOP *
1429 S_alloc_LOGOP(pTHX_ I32 type, OP *first, OP* other)
1430 {
1431     dVAR;
1432     LOGOP *logop;
1433     OP *kid = first;
1434     NewOp(1101, logop, 1, LOGOP);
1435     OpTYPE_set(logop, type);
1436     logop->op_first = first;
1437     logop->op_other = other;
1438     logop->op_flags = OPf_KIDS;
1439     while (kid && OpHAS_SIBLING(kid))
1440         kid = OpSIBLING(kid);
1441     if (kid)
1442         OpLASTSIB_set(kid, (OP*)logop);
1443     return logop;
1444 }
1445
1446
1447 /* Contextualizers */
1448
1449 /*
1450 =for apidoc Am|OP *|op_contextualize|OP *o|I32 context
1451
1452 Applies a syntactic context to an op tree representing an expression.
1453 C<o> is the op tree, and C<context> must be C<G_SCALAR>, C<G_ARRAY>,
1454 or C<G_VOID> to specify the context to apply.  The modified op tree
1455 is returned.
1456
1457 =cut
1458 */
1459
1460 OP *
1461 Perl_op_contextualize(pTHX_ OP *o, I32 context)
1462 {
1463     PERL_ARGS_ASSERT_OP_CONTEXTUALIZE;
1464     switch (context) {
1465         case G_SCALAR: return scalar(o);
1466         case G_ARRAY:  return list(o);
1467         case G_VOID:   return scalarvoid(o);
1468         default:
1469             Perl_croak(aTHX_ "panic: op_contextualize bad context %ld",
1470                        (long) context);
1471     }
1472 }
1473
1474 /*
1475
1476 =for apidoc Am|OP*|op_linklist|OP *o
1477 This function is the implementation of the L</LINKLIST> macro.  It should
1478 not be called directly.
1479
1480 =cut
1481 */
1482
1483 OP *
1484 Perl_op_linklist(pTHX_ OP *o)
1485 {
1486     OP *first;
1487
1488     PERL_ARGS_ASSERT_OP_LINKLIST;
1489
1490     if (o->op_next)
1491         return o->op_next;
1492
1493     /* establish postfix order */
1494     first = cUNOPo->op_first;
1495     if (first) {
1496         OP *kid;
1497         o->op_next = LINKLIST(first);
1498         kid = first;
1499         for (;;) {
1500             OP *sibl = OpSIBLING(kid);
1501             if (sibl) {
1502                 kid->op_next = LINKLIST(sibl);
1503                 kid = sibl;
1504             } else {
1505                 kid->op_next = o;
1506                 break;
1507             }
1508         }
1509     }
1510     else
1511         o->op_next = o;
1512
1513     return o->op_next;
1514 }
1515
1516 static OP *
1517 S_scalarkids(pTHX_ OP *o)
1518 {
1519     if (o && o->op_flags & OPf_KIDS) {
1520         OP *kid;
1521         for (kid = cLISTOPo->op_first; kid; kid = OpSIBLING(kid))
1522             scalar(kid);
1523     }
1524     return o;
1525 }
1526
1527 STATIC OP *
1528 S_scalarboolean(pTHX_ OP *o)
1529 {
1530     PERL_ARGS_ASSERT_SCALARBOOLEAN;
1531
1532     if (o->op_type == OP_SASSIGN && cBINOPo->op_first->op_type == OP_CONST
1533      && !(cBINOPo->op_first->op_flags & OPf_SPECIAL)) {
1534         if (ckWARN(WARN_SYNTAX)) {
1535             const line_t oldline = CopLINE(PL_curcop);
1536
1537             if (PL_parser && PL_parser->copline != NOLINE) {
1538                 /* This ensures that warnings are reported at the first line
1539                    of the conditional, not the last.  */
1540                 CopLINE_set(PL_curcop, PL_parser->copline);
1541             }
1542             Perl_warner(aTHX_ packWARN(WARN_SYNTAX), "Found = in conditional, should be ==");
1543             CopLINE_set(PL_curcop, oldline);
1544         }
1545     }
1546     return scalar(o);
1547 }
1548
1549 static SV *
1550 S_op_varname(pTHX_ const OP *o)
1551 {
1552     assert(o);
1553     assert(o->op_type == OP_PADAV || o->op_type == OP_RV2AV ||
1554            o->op_type == OP_PADHV || o->op_type == OP_RV2HV);
1555     {
1556         const char funny  = o->op_type == OP_PADAV
1557                          || o->op_type == OP_RV2AV ? '@' : '%';
1558         if (o->op_type == OP_RV2AV || o->op_type == OP_RV2HV) {
1559             GV *gv;
1560             if (cUNOPo->op_first->op_type != OP_GV
1561              || !(gv = cGVOPx_gv(cUNOPo->op_first)))
1562                 return NULL;
1563             return varname(gv, funny, 0, NULL, 0, 1);
1564         }
1565         return
1566             varname(MUTABLE_GV(PL_compcv), funny, o->op_targ, NULL, 0, 1);
1567     }
1568 }
1569
1570 static void
1571 S_op_pretty(pTHX_ const OP *o, SV **retsv, const char **retpv)
1572 { /* or not so pretty :-) */
1573     if (o->op_type == OP_CONST) {
1574         *retsv = cSVOPo_sv;
1575         if (SvPOK(*retsv)) {
1576             SV *sv = *retsv;
1577             *retsv = sv_newmortal();
1578             pv_pretty(*retsv, SvPVX_const(sv), SvCUR(sv), 32, NULL, NULL,
1579                       PERL_PV_PRETTY_DUMP |PERL_PV_ESCAPE_UNI_DETECT);
1580         }
1581         else if (!SvOK(*retsv))
1582             *retpv = "undef";
1583     }
1584     else *retpv = "...";
1585 }
1586
1587 static void
1588 S_scalar_slice_warning(pTHX_ const OP *o)
1589 {
1590     OP *kid;
1591     const char lbrack =
1592         o->op_type == OP_HSLICE ? '{' : '[';
1593     const char rbrack =
1594         o->op_type == OP_HSLICE ? '}' : ']';
1595     SV *name;
1596     SV *keysv = NULL; /* just to silence compiler warnings */
1597     const char *key = NULL;
1598
1599     if (!(o->op_private & OPpSLICEWARNING))
1600         return;
1601     if (PL_parser && PL_parser->error_count)
1602         /* This warning can be nonsensical when there is a syntax error. */
1603         return;
1604
1605     kid = cLISTOPo->op_first;
1606     kid = OpSIBLING(kid); /* get past pushmark */
1607     /* weed out false positives: any ops that can return lists */
1608     switch (kid->op_type) {
1609     case OP_BACKTICK:
1610     case OP_GLOB:
1611     case OP_READLINE:
1612     case OP_MATCH:
1613     case OP_RV2AV:
1614     case OP_EACH:
1615     case OP_VALUES:
1616     case OP_KEYS:
1617     case OP_SPLIT:
1618     case OP_LIST:
1619     case OP_SORT:
1620     case OP_REVERSE:
1621     case OP_ENTERSUB:
1622     case OP_CALLER:
1623     case OP_LSTAT:
1624     case OP_STAT:
1625     case OP_READDIR:
1626     case OP_SYSTEM:
1627     case OP_TMS:
1628     case OP_LOCALTIME:
1629     case OP_GMTIME:
1630     case OP_ENTEREVAL:
1631         return;
1632     }
1633
1634     /* Don't warn if we have a nulled list either. */
1635     if (kid->op_type == OP_NULL && kid->op_targ == OP_LIST)
1636         return;
1637
1638     assert(OpSIBLING(kid));
1639     name = S_op_varname(aTHX_ OpSIBLING(kid));
1640     if (!name) /* XS module fiddling with the op tree */
1641         return;
1642     S_op_pretty(aTHX_ kid, &keysv, &key);
1643     assert(SvPOK(name));
1644     sv_chop(name,SvPVX(name)+1);
1645     if (key)
1646        /* diag_listed_as: Scalar value @%s[%s] better written as $%s[%s] */
1647         Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
1648                    "Scalar value @%"SVf"%c%s%c better written as $%"SVf
1649                    "%c%s%c",
1650                     SVfARG(name), lbrack, key, rbrack, SVfARG(name),
1651                     lbrack, key, rbrack);
1652     else
1653        /* diag_listed_as: Scalar value @%s[%s] better written as $%s[%s] */
1654         Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
1655                    "Scalar value @%"SVf"%c%"SVf"%c better written as $%"
1656                     SVf"%c%"SVf"%c",
1657                     SVfARG(name), lbrack, SVfARG(keysv), rbrack,
1658                     SVfARG(name), lbrack, SVfARG(keysv), rbrack);
1659 }
1660
1661 OP *
1662 Perl_scalar(pTHX_ OP *o)
1663 {
1664     OP *kid;
1665
1666     /* assumes no premature commitment */
1667     if (!o || (PL_parser && PL_parser->error_count)
1668          || (o->op_flags & OPf_WANT)
1669          || o->op_type == OP_RETURN)
1670     {
1671         return o;
1672     }
1673
1674     o->op_flags = (o->op_flags & ~OPf_WANT) | OPf_WANT_SCALAR;
1675
1676     switch (o->op_type) {
1677     case OP_REPEAT:
1678         scalar(cBINOPo->op_first);
1679         if (o->op_private & OPpREPEAT_DOLIST) {
1680             kid = cLISTOPx(cUNOPo->op_first)->op_first;
1681             assert(kid->op_type == OP_PUSHMARK);
1682             if (OpHAS_SIBLING(kid) && !OpHAS_SIBLING(OpSIBLING(kid))) {
1683                 op_null(cLISTOPx(cUNOPo->op_first)->op_first);
1684                 o->op_private &=~ OPpREPEAT_DOLIST;
1685             }
1686         }
1687         break;
1688     case OP_OR:
1689     case OP_AND:
1690     case OP_COND_EXPR:
1691         for (kid = OpSIBLING(cUNOPo->op_first); kid; kid = OpSIBLING(kid))
1692             scalar(kid);
1693         break;
1694         /* FALLTHROUGH */
1695     case OP_SPLIT:
1696     case OP_MATCH:
1697     case OP_QR:
1698     case OP_SUBST:
1699     case OP_NULL:
1700     default:
1701         if (o->op_flags & OPf_KIDS) {
1702             for (kid = cUNOPo->op_first; kid; kid = OpSIBLING(kid))
1703                 scalar(kid);
1704         }
1705         break;
1706     case OP_LEAVE:
1707     case OP_LEAVETRY:
1708         kid = cLISTOPo->op_first;
1709         scalar(kid);
1710         kid = OpSIBLING(kid);
1711     do_kids:
1712         while (kid) {
1713             OP *sib = OpSIBLING(kid);
1714             if (sib && kid->op_type != OP_LEAVEWHEN
1715              && (  OpHAS_SIBLING(sib) || sib->op_type != OP_NULL
1716                 || (  sib->op_targ != OP_NEXTSTATE
1717                    && sib->op_targ != OP_DBSTATE  )))
1718                 scalarvoid(kid);
1719             else
1720                 scalar(kid);
1721             kid = sib;
1722         }
1723         PL_curcop = &PL_compiling;
1724         break;
1725     case OP_SCOPE:
1726     case OP_LINESEQ:
1727     case OP_LIST:
1728         kid = cLISTOPo->op_first;
1729         goto do_kids;
1730     case OP_SORT:
1731         Perl_ck_warner(aTHX_ packWARN(WARN_VOID), "Useless use of sort in scalar context");
1732         break;
1733     case OP_KVHSLICE:
1734     case OP_KVASLICE:
1735     {
1736         /* Warn about scalar context */
1737         const char lbrack = o->op_type == OP_KVHSLICE ? '{' : '[';
1738         const char rbrack = o->op_type == OP_KVHSLICE ? '}' : ']';
1739         SV *name;
1740         SV *keysv;
1741         const char *key = NULL;
1742
1743         /* This warning can be nonsensical when there is a syntax error. */
1744         if (PL_parser && PL_parser->error_count)
1745             break;
1746
1747         if (!ckWARN(WARN_SYNTAX)) break;
1748
1749         kid = cLISTOPo->op_first;
1750         kid = OpSIBLING(kid); /* get past pushmark */
1751         assert(OpSIBLING(kid));
1752         name = S_op_varname(aTHX_ OpSIBLING(kid));
1753         if (!name) /* XS module fiddling with the op tree */
1754             break;
1755         S_op_pretty(aTHX_ kid, &keysv, &key);
1756         assert(SvPOK(name));
1757         sv_chop(name,SvPVX(name)+1);
1758         if (key)
1759   /* diag_listed_as: %%s[%s] in scalar context better written as $%s[%s] */
1760             Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
1761                        "%%%"SVf"%c%s%c in scalar context better written "
1762                        "as $%"SVf"%c%s%c",
1763                         SVfARG(name), lbrack, key, rbrack, SVfARG(name),
1764                         lbrack, key, rbrack);
1765         else
1766   /* diag_listed_as: %%s[%s] in scalar context better written as $%s[%s] */
1767             Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
1768                        "%%%"SVf"%c%"SVf"%c in scalar context better "
1769                        "written as $%"SVf"%c%"SVf"%c",
1770                         SVfARG(name), lbrack, SVfARG(keysv), rbrack,
1771                         SVfARG(name), lbrack, SVfARG(keysv), rbrack);
1772     }
1773     }
1774     return o;
1775 }
1776
1777 OP *
1778 Perl_scalarvoid(pTHX_ OP *arg)
1779 {
1780     dVAR;
1781     OP *kid;
1782     SV* sv;
1783     U8 want;
1784     SSize_t defer_stack_alloc = 0;
1785     SSize_t defer_ix = -1;
1786     OP **defer_stack = NULL;
1787     OP *o = arg;
1788
1789     PERL_ARGS_ASSERT_SCALARVOID;
1790
1791     do {
1792         SV *useless_sv = NULL;
1793         const char* useless = NULL;
1794
1795         if (o->op_type == OP_NEXTSTATE
1796             || o->op_type == OP_DBSTATE
1797             || (o->op_type == OP_NULL && (o->op_targ == OP_NEXTSTATE
1798                                           || o->op_targ == OP_DBSTATE)))
1799             PL_curcop = (COP*)o;                /* for warning below */
1800
1801         /* assumes no premature commitment */
1802         want = o->op_flags & OPf_WANT;
1803         if ((want && want != OPf_WANT_SCALAR)
1804             || (PL_parser && PL_parser->error_count)
1805             || o->op_type == OP_RETURN || o->op_type == OP_REQUIRE || o->op_type == OP_LEAVEWHEN)
1806         {
1807             continue;
1808         }
1809
1810         if ((o->op_private & OPpTARGET_MY)
1811             && (PL_opargs[o->op_type] & OA_TARGLEX))/* OPp share the meaning */
1812         {
1813             /* newASSIGNOP has already applied scalar context, which we
1814                leave, as if this op is inside SASSIGN.  */
1815             continue;
1816         }
1817
1818         o->op_flags = (o->op_flags & ~OPf_WANT) | OPf_WANT_VOID;
1819
1820         switch (o->op_type) {
1821         default:
1822             if (!(PL_opargs[o->op_type] & OA_FOLDCONST))
1823                 break;
1824             /* FALLTHROUGH */
1825         case OP_REPEAT:
1826             if (o->op_flags & OPf_STACKED)
1827                 break;
1828             if (o->op_type == OP_REPEAT)
1829                 scalar(cBINOPo->op_first);
1830             goto func_ops;
1831         case OP_SUBSTR:
1832             if (o->op_private == 4)
1833                 break;
1834             /* FALLTHROUGH */
1835         case OP_WANTARRAY:
1836         case OP_GV:
1837         case OP_SMARTMATCH:
1838         case OP_AV2ARYLEN:
1839         case OP_REF:
1840         case OP_REFGEN:
1841         case OP_SREFGEN:
1842         case OP_DEFINED:
1843         case OP_HEX:
1844         case OP_OCT:
1845         case OP_LENGTH:
1846         case OP_VEC:
1847         case OP_INDEX:
1848         case OP_RINDEX:
1849         case OP_SPRINTF:
1850         case OP_KVASLICE:
1851         case OP_KVHSLICE:
1852         case OP_UNPACK:
1853         case OP_PACK:
1854         case OP_JOIN:
1855         case OP_LSLICE:
1856         case OP_ANONLIST:
1857         case OP_ANONHASH:
1858         case OP_SORT:
1859         case OP_REVERSE:
1860         case OP_RANGE:
1861         case OP_FLIP:
1862         case OP_FLOP:
1863         case OP_CALLER:
1864         case OP_FILENO:
1865         case OP_EOF:
1866         case OP_TELL:
1867         case OP_GETSOCKNAME:
1868         case OP_GETPEERNAME:
1869         case OP_READLINK:
1870         case OP_TELLDIR:
1871         case OP_GETPPID:
1872         case OP_GETPGRP:
1873         case OP_GETPRIORITY:
1874         case OP_TIME:
1875         case OP_TMS:
1876         case OP_LOCALTIME:
1877         case OP_GMTIME:
1878         case OP_GHBYNAME:
1879         case OP_GHBYADDR:
1880         case OP_GHOSTENT:
1881         case OP_GNBYNAME:
1882         case OP_GNBYADDR:
1883         case OP_GNETENT:
1884         case OP_GPBYNAME:
1885         case OP_GPBYNUMBER:
1886         case OP_GPROTOENT:
1887         case OP_GSBYNAME:
1888         case OP_GSBYPORT:
1889         case OP_GSERVENT:
1890         case OP_GPWNAM:
1891         case OP_GPWUID:
1892         case OP_GGRNAM:
1893         case OP_GGRGID:
1894         case OP_GETLOGIN:
1895         case OP_PROTOTYPE:
1896         case OP_RUNCV:
1897         func_ops:
1898             useless = OP_DESC(o);
1899             break;
1900
1901         case OP_GVSV:
1902         case OP_PADSV:
1903         case OP_PADAV:
1904         case OP_PADHV:
1905         case OP_PADANY:
1906         case OP_AELEM:
1907         case OP_AELEMFAST:
1908         case OP_AELEMFAST_LEX:
1909         case OP_ASLICE:
1910         case OP_HELEM:
1911         case OP_HSLICE:
1912             if (!(o->op_private & (OPpLVAL_INTRO|OPpOUR_INTRO)))
1913                 /* Otherwise it's "Useless use of grep iterator" */
1914                 useless = OP_DESC(o);
1915             break;
1916
1917         case OP_SPLIT:
1918             kid = cLISTOPo->op_first;
1919             if (kid && kid->op_type == OP_PUSHRE
1920                 && !kid->op_targ
1921                 && !(o->op_flags & OPf_STACKED)
1922 #ifdef USE_ITHREADS
1923                 && !((PMOP*)kid)->op_pmreplrootu.op_pmtargetoff
1924 #else
1925                 && !((PMOP*)kid)->op_pmreplrootu.op_pmtargetgv
1926 #endif
1927                 )
1928                 useless = OP_DESC(o);
1929             break;
1930
1931         case OP_NOT:
1932             kid = cUNOPo->op_first;
1933             if (kid->op_type != OP_MATCH && kid->op_type != OP_SUBST &&
1934                 kid->op_type != OP_TRANS && kid->op_type != OP_TRANSR) {
1935                 goto func_ops;
1936             }
1937             useless = "negative pattern binding (!~)";
1938             break;
1939
1940         case OP_SUBST:
1941             if (cPMOPo->op_pmflags & PMf_NONDESTRUCT)
1942                 useless = "non-destructive substitution (s///r)";
1943             break;
1944
1945         case OP_TRANSR:
1946             useless = "non-destructive transliteration (tr///r)";
1947             break;
1948
1949         case OP_RV2GV:
1950         case OP_RV2SV:
1951         case OP_RV2AV:
1952         case OP_RV2HV:
1953             if (!(o->op_private & (OPpLVAL_INTRO|OPpOUR_INTRO)) &&
1954                 (!OpHAS_SIBLING(o) || OpSIBLING(o)->op_type != OP_READLINE))
1955                 useless = "a variable";
1956             break;
1957
1958         case OP_CONST:
1959             sv = cSVOPo_sv;
1960             if (cSVOPo->op_private & OPpCONST_STRICT)
1961                 no_bareword_allowed(o);
1962             else {
1963                 if (ckWARN(WARN_VOID)) {
1964                     NV nv;
1965                     /* don't warn on optimised away booleans, eg
1966                      * use constant Foo, 5; Foo || print; */
1967                     if (cSVOPo->op_private & OPpCONST_SHORTCIRCUIT)
1968                         useless = NULL;
1969                     /* the constants 0 and 1 are permitted as they are
1970                        conventionally used as dummies in constructs like
1971                        1 while some_condition_with_side_effects;  */
1972                     else if (SvNIOK(sv) && ((nv = SvNV(sv)) == 0.0 || nv == 1.0))
1973                         useless = NULL;
1974                     else if (SvPOK(sv)) {
1975                         SV * const dsv = newSVpvs("");
1976                         useless_sv
1977                             = Perl_newSVpvf(aTHX_
1978                                             "a constant (%s)",
1979                                             pv_pretty(dsv, SvPVX_const(sv),
1980                                                       SvCUR(sv), 32, NULL, NULL,
1981                                                       PERL_PV_PRETTY_DUMP
1982                                                       | PERL_PV_ESCAPE_NOCLEAR
1983                                                       | PERL_PV_ESCAPE_UNI_DETECT));
1984                         SvREFCNT_dec_NN(dsv);
1985                     }
1986                     else if (SvOK(sv)) {
1987                         useless_sv = Perl_newSVpvf(aTHX_ "a constant (%"SVf")", SVfARG(sv));
1988                     }
1989                     else
1990                         useless = "a constant (undef)";
1991                 }
1992             }
1993             op_null(o);         /* don't execute or even remember it */
1994             break;
1995
1996         case OP_POSTINC:
1997             OpTYPE_set(o, OP_PREINC);  /* pre-increment is faster */
1998             break;
1999
2000         case OP_POSTDEC:
2001             OpTYPE_set(o, OP_PREDEC);  /* pre-decrement is faster */
2002             break;
2003
2004         case OP_I_POSTINC:
2005             OpTYPE_set(o, OP_I_PREINC);        /* pre-increment is faster */
2006             break;
2007
2008         case OP_I_POSTDEC:
2009             OpTYPE_set(o, OP_I_PREDEC);        /* pre-decrement is faster */
2010             break;
2011
2012         case OP_SASSIGN: {
2013             OP *rv2gv;
2014             UNOP *refgen, *rv2cv;
2015             LISTOP *exlist;
2016
2017             if ((o->op_private & ~OPpASSIGN_BACKWARDS) != 2)
2018                 break;
2019
2020             rv2gv = ((BINOP *)o)->op_last;
2021             if (!rv2gv || rv2gv->op_type != OP_RV2GV)
2022                 break;
2023
2024             refgen = (UNOP *)((BINOP *)o)->op_first;
2025
2026             if (!refgen || (refgen->op_type != OP_REFGEN
2027                             && refgen->op_type != OP_SREFGEN))
2028                 break;
2029
2030             exlist = (LISTOP *)refgen->op_first;
2031             if (!exlist || exlist->op_type != OP_NULL
2032                 || exlist->op_targ != OP_LIST)
2033                 break;
2034
2035             if (exlist->op_first->op_type != OP_PUSHMARK
2036                 && exlist->op_first != exlist->op_last)
2037                 break;
2038
2039             rv2cv = (UNOP*)exlist->op_last;
2040
2041             if (rv2cv->op_type != OP_RV2CV)
2042                 break;
2043
2044             assert ((rv2gv->op_private & OPpDONT_INIT_GV) == 0);
2045             assert ((o->op_private & OPpASSIGN_CV_TO_GV) == 0);
2046             assert ((rv2cv->op_private & OPpMAY_RETURN_CONSTANT) == 0);
2047
2048             o->op_private |= OPpASSIGN_CV_TO_GV;
2049             rv2gv->op_private |= OPpDONT_INIT_GV;
2050             rv2cv->op_private |= OPpMAY_RETURN_CONSTANT;
2051
2052             break;
2053         }
2054
2055         case OP_AASSIGN: {
2056             inplace_aassign(o);
2057             break;
2058         }
2059
2060         case OP_OR:
2061         case OP_AND:
2062             kid = cLOGOPo->op_first;
2063             if (kid->op_type == OP_NOT
2064                 && (kid->op_flags & OPf_KIDS)) {
2065                 if (o->op_type == OP_AND) {
2066                     OpTYPE_set(o, OP_OR);
2067                 } else {
2068                     OpTYPE_set(o, OP_AND);
2069                 }
2070                 op_null(kid);
2071             }
2072             /* FALLTHROUGH */
2073
2074         case OP_DOR:
2075         case OP_COND_EXPR:
2076         case OP_ENTERGIVEN:
2077         case OP_ENTERWHEN:
2078             for (kid = OpSIBLING(cUNOPo->op_first); kid; kid = OpSIBLING(kid))
2079                 if (!(kid->op_flags & OPf_KIDS))
2080                     scalarvoid(kid);
2081                 else
2082                     DEFER_OP(kid);
2083         break;
2084
2085         case OP_NULL:
2086             if (o->op_flags & OPf_STACKED)
2087                 break;
2088             /* FALLTHROUGH */
2089         case OP_NEXTSTATE:
2090         case OP_DBSTATE:
2091         case OP_ENTERTRY:
2092         case OP_ENTER:
2093             if (!(o->op_flags & OPf_KIDS))
2094                 break;
2095             /* FALLTHROUGH */
2096         case OP_SCOPE:
2097         case OP_LEAVE:
2098         case OP_LEAVETRY:
2099         case OP_LEAVELOOP:
2100         case OP_LINESEQ:
2101         case OP_LEAVEGIVEN:
2102         case OP_LEAVEWHEN:
2103         kids:
2104             for (kid = cLISTOPo->op_first; kid; kid = OpSIBLING(kid))
2105                 if (!(kid->op_flags & OPf_KIDS))
2106                     scalarvoid(kid);
2107                 else
2108                     DEFER_OP(kid);
2109             break;
2110         case OP_LIST:
2111             /* If the first kid after pushmark is something that the padrange
2112                optimisation would reject, then null the list and the pushmark.
2113             */
2114             if ((kid = cLISTOPo->op_first)->op_type == OP_PUSHMARK
2115                 && (  !(kid = OpSIBLING(kid))
2116                       || (  kid->op_type != OP_PADSV
2117                             && kid->op_type != OP_PADAV
2118                             && kid->op_type != OP_PADHV)
2119                       || kid->op_private & ~OPpLVAL_INTRO
2120                       || !(kid = OpSIBLING(kid))
2121                       || (  kid->op_type != OP_PADSV
2122                             && kid->op_type != OP_PADAV
2123                             && kid->op_type != OP_PADHV)
2124                       || kid->op_private & ~OPpLVAL_INTRO)
2125             ) {
2126                 op_null(cUNOPo->op_first); /* NULL the pushmark */
2127                 op_null(o); /* NULL the list */
2128             }
2129             goto kids;
2130         case OP_ENTEREVAL:
2131             scalarkids(o);
2132             break;
2133         case OP_SCALAR:
2134             scalar(o);
2135             break;
2136         }
2137
2138         if (useless_sv) {
2139             /* mortalise it, in case warnings are fatal.  */
2140             Perl_ck_warner(aTHX_ packWARN(WARN_VOID),
2141                            "Useless use of %"SVf" in void context",
2142                            SVfARG(sv_2mortal(useless_sv)));
2143         }
2144         else if (useless) {
2145             Perl_ck_warner(aTHX_ packWARN(WARN_VOID),
2146                            "Useless use of %s in void context",
2147                            useless);
2148         }
2149     } while ( (o = POP_DEFERRED_OP()) );
2150
2151     Safefree(defer_stack);
2152
2153     return arg;
2154 }
2155
2156 static OP *
2157 S_listkids(pTHX_ OP *o)
2158 {
2159     if (o && o->op_flags & OPf_KIDS) {
2160         OP *kid;
2161         for (kid = cLISTOPo->op_first; kid; kid = OpSIBLING(kid))
2162             list(kid);
2163     }
2164     return o;
2165 }
2166
2167 OP *
2168 Perl_list(pTHX_ OP *o)
2169 {
2170     OP *kid;
2171
2172     /* assumes no premature commitment */
2173     if (!o || (o->op_flags & OPf_WANT)
2174          || (PL_parser && PL_parser->error_count)
2175          || o->op_type == OP_RETURN)
2176     {
2177         return o;
2178     }
2179
2180     if ((o->op_private & OPpTARGET_MY)
2181         && (PL_opargs[o->op_type] & OA_TARGLEX))/* OPp share the meaning */
2182     {
2183         return o;                               /* As if inside SASSIGN */
2184     }
2185
2186     o->op_flags = (o->op_flags & ~OPf_WANT) | OPf_WANT_LIST;
2187
2188     switch (o->op_type) {
2189     case OP_FLOP:
2190         list(cBINOPo->op_first);
2191         break;
2192     case OP_REPEAT:
2193         if (o->op_private & OPpREPEAT_DOLIST
2194          && !(o->op_flags & OPf_STACKED))
2195         {
2196             list(cBINOPo->op_first);
2197             kid = cBINOPo->op_last;
2198             if (kid->op_type == OP_CONST && SvIOK(kSVOP_sv)
2199              && SvIVX(kSVOP_sv) == 1)
2200             {
2201                 op_null(o); /* repeat */
2202                 op_null(cUNOPx(cBINOPo->op_first)->op_first);/* pushmark */
2203                 /* const (rhs): */
2204                 op_free(op_sibling_splice(o, cBINOPo->op_first, 1, NULL));
2205             }
2206         }
2207         break;
2208     case OP_OR:
2209     case OP_AND:
2210     case OP_COND_EXPR:
2211         for (kid = OpSIBLING(cUNOPo->op_first); kid; kid = OpSIBLING(kid))
2212             list(kid);
2213         break;
2214     default:
2215     case OP_MATCH:
2216     case OP_QR:
2217     case OP_SUBST:
2218     case OP_NULL:
2219         if (!(o->op_flags & OPf_KIDS))
2220             break;
2221         if (!o->op_next && cUNOPo->op_first->op_type == OP_FLOP) {
2222             list(cBINOPo->op_first);
2223             return gen_constant_list(o);
2224         }
2225         listkids(o);
2226         break;
2227     case OP_LIST:
2228         listkids(o);
2229         if (cLISTOPo->op_first->op_type == OP_PUSHMARK) {
2230             op_null(cUNOPo->op_first); /* NULL the pushmark */
2231             op_null(o); /* NULL the list */
2232         }
2233         break;
2234     case OP_LEAVE:
2235     case OP_LEAVETRY:
2236         kid = cLISTOPo->op_first;
2237         list(kid);
2238         kid = OpSIBLING(kid);
2239     do_kids:
2240         while (kid) {
2241             OP *sib = OpSIBLING(kid);
2242             if (sib && kid->op_type != OP_LEAVEWHEN)
2243                 scalarvoid(kid);
2244             else
2245                 list(kid);
2246             kid = sib;
2247         }
2248         PL_curcop = &PL_compiling;
2249         break;
2250     case OP_SCOPE:
2251     case OP_LINESEQ:
2252         kid = cLISTOPo->op_first;
2253         goto do_kids;
2254     }
2255     return o;
2256 }
2257
2258 static OP *
2259 S_scalarseq(pTHX_ OP *o)
2260 {
2261     if (o) {
2262         const OPCODE type = o->op_type;
2263
2264         if (type == OP_LINESEQ || type == OP_SCOPE ||
2265             type == OP_LEAVE || type == OP_LEAVETRY)
2266         {
2267             OP *kid, *sib;
2268             for (kid = cLISTOPo->op_first; kid; kid = sib) {
2269                 if ((sib = OpSIBLING(kid))
2270                  && (  OpHAS_SIBLING(sib) || sib->op_type != OP_NULL
2271                     || (  sib->op_targ != OP_NEXTSTATE
2272                        && sib->op_targ != OP_DBSTATE  )))
2273                 {
2274                     scalarvoid(kid);
2275                 }
2276             }
2277             PL_curcop = &PL_compiling;
2278         }
2279         o->op_flags &= ~OPf_PARENS;
2280         if (PL_hints & HINT_BLOCK_SCOPE)
2281             o->op_flags |= OPf_PARENS;
2282     }
2283     else
2284         o = newOP(OP_STUB, 0);
2285     return o;
2286 }
2287
2288 STATIC OP *
2289 S_modkids(pTHX_ OP *o, I32 type)
2290 {
2291     if (o && o->op_flags & OPf_KIDS) {
2292         OP *kid;
2293         for (kid = cLISTOPo->op_first; kid; kid = OpSIBLING(kid))
2294             op_lvalue(kid, type);
2295     }
2296     return o;
2297 }
2298
2299
2300 /* for a helem/hslice/kvslice, if its a fixed hash, croak on invalid
2301  * const fields. Also, convert CONST keys to HEK-in-SVs.
2302  * rop is the op that retrieves the hash;
2303  * key_op is the first key
2304  */
2305
2306 void
2307 S_check_hash_fields_and_hekify(pTHX_ UNOP *rop, SVOP *key_op)
2308 {
2309     PADNAME *lexname;
2310     GV **fields;
2311     bool check_fields;
2312
2313     /* find the padsv corresponding to $lex->{} or @{$lex}{} */
2314     if (rop) {
2315         if (rop->op_first->op_type == OP_PADSV)
2316             /* @$hash{qw(keys here)} */
2317             rop = (UNOP*)rop->op_first;
2318         else {
2319             /* @{$hash}{qw(keys here)} */
2320             if (rop->op_first->op_type == OP_SCOPE
2321                 && cLISTOPx(rop->op_first)->op_last->op_type == OP_PADSV)
2322                 {
2323                     rop = (UNOP*)cLISTOPx(rop->op_first)->op_last;
2324                 }
2325             else
2326                 rop = NULL;
2327         }
2328     }
2329
2330     lexname = NULL; /* just to silence compiler warnings */
2331     fields  = NULL; /* just to silence compiler warnings */
2332
2333     check_fields =
2334             rop
2335          && (lexname = padnamelist_fetch(PL_comppad_name, rop->op_targ),
2336              SvPAD_TYPED(lexname))
2337          && (fields = (GV**)hv_fetchs(PadnameTYPE(lexname), "FIELDS", FALSE))
2338          && isGV(*fields) && GvHV(*fields);
2339
2340     for (; key_op; key_op = (SVOP*)OpSIBLING(key_op)) {
2341         SV **svp, *sv;
2342         if (key_op->op_type != OP_CONST)
2343             continue;
2344         svp = cSVOPx_svp(key_op);
2345
2346         /* Make the CONST have a shared SV */
2347         if (   !SvIsCOW_shared_hash(sv = *svp)
2348             && SvTYPE(sv) < SVt_PVMG
2349             && SvOK(sv)
2350             && !SvROK(sv))
2351         {
2352             SSize_t keylen;
2353             const char * const key = SvPV_const(sv, *(STRLEN*)&keylen);
2354             SV *nsv = newSVpvn_share(key, SvUTF8(sv) ? -keylen : keylen, 0);
2355             SvREFCNT_dec_NN(sv);
2356             *svp = nsv;
2357         }
2358
2359         if (   check_fields
2360             && !hv_fetch_ent(GvHV(*fields), *svp, FALSE, 0))
2361         {
2362             Perl_croak(aTHX_ "No such class field \"%"SVf"\" "
2363                         "in variable %"PNf" of type %"HEKf,
2364                         SVfARG(*svp), PNfARG(lexname),
2365                         HEKfARG(HvNAME_HEK(PadnameTYPE(lexname))));
2366         }
2367     }
2368 }
2369
2370
2371 /*
2372 =for apidoc finalize_optree
2373
2374 This function finalizes the optree.  Should be called directly after
2375 the complete optree is built.  It does some additional
2376 checking which can't be done in the normal C<ck_>xxx functions and makes
2377 the tree thread-safe.
2378
2379 =cut
2380 */
2381 void
2382 Perl_finalize_optree(pTHX_ OP* o)
2383 {
2384     PERL_ARGS_ASSERT_FINALIZE_OPTREE;
2385
2386     ENTER;
2387     SAVEVPTR(PL_curcop);
2388
2389     finalize_op(o);
2390
2391     LEAVE;
2392 }
2393
2394 #ifdef USE_ITHREADS
2395 /* Relocate sv to the pad for thread safety.
2396  * Despite being a "constant", the SV is written to,
2397  * for reference counts, sv_upgrade() etc. */
2398 PERL_STATIC_INLINE void
2399 S_op_relocate_sv(pTHX_ SV** svp, PADOFFSET* targp)
2400 {
2401     PADOFFSET ix;
2402     PERL_ARGS_ASSERT_OP_RELOCATE_SV;
2403     if (!*svp) return;
2404     ix = pad_alloc(OP_CONST, SVf_READONLY);
2405     SvREFCNT_dec(PAD_SVl(ix));
2406     PAD_SETSV(ix, *svp);
2407     /* XXX I don't know how this isn't readonly already. */
2408     if (!SvIsCOW(PAD_SVl(ix))) SvREADONLY_on(PAD_SVl(ix));
2409     *svp = NULL;
2410     *targp = ix;
2411 }
2412 #endif
2413
2414
2415 STATIC void
2416 S_finalize_op(pTHX_ OP* o)
2417 {
2418     PERL_ARGS_ASSERT_FINALIZE_OP;
2419
2420
2421     switch (o->op_type) {
2422     case OP_NEXTSTATE:
2423     case OP_DBSTATE:
2424         PL_curcop = ((COP*)o);          /* for warnings */
2425         break;
2426     case OP_EXEC:
2427         if (OpHAS_SIBLING(o)) {
2428             OP *sib = OpSIBLING(o);
2429             if ((  sib->op_type == OP_NEXTSTATE || sib->op_type == OP_DBSTATE)
2430                 && ckWARN(WARN_EXEC)
2431                 && OpHAS_SIBLING(sib))
2432             {
2433                     const OPCODE type = OpSIBLING(sib)->op_type;
2434                     if (type != OP_EXIT && type != OP_WARN && type != OP_DIE) {
2435                         const line_t oldline = CopLINE(PL_curcop);
2436                         CopLINE_set(PL_curcop, CopLINE((COP*)sib));
2437                         Perl_warner(aTHX_ packWARN(WARN_EXEC),
2438                             "Statement unlikely to be reached");
2439                         Perl_warner(aTHX_ packWARN(WARN_EXEC),
2440                             "\t(Maybe you meant system() when you said exec()?)\n");
2441                         CopLINE_set(PL_curcop, oldline);
2442                     }
2443             }
2444         }
2445         break;
2446
2447     case OP_GV:
2448         if ((o->op_private & OPpEARLY_CV) && ckWARN(WARN_PROTOTYPE)) {
2449             GV * const gv = cGVOPo_gv;
2450             if (SvTYPE(gv) == SVt_PVGV && GvCV(gv) && SvPVX_const(GvCV(gv))) {
2451                 /* XXX could check prototype here instead of just carping */
2452                 SV * const sv = sv_newmortal();
2453                 gv_efullname3(sv, gv, NULL);
2454                 Perl_warner(aTHX_ packWARN(WARN_PROTOTYPE),
2455                     "%"SVf"() called too early to check prototype",
2456                     SVfARG(sv));
2457             }
2458         }
2459         break;
2460
2461     case OP_CONST:
2462         if (cSVOPo->op_private & OPpCONST_STRICT)
2463             no_bareword_allowed(o);
2464         /* FALLTHROUGH */
2465 #ifdef USE_ITHREADS
2466     case OP_HINTSEVAL:
2467         op_relocate_sv(&cSVOPo->op_sv, &o->op_targ);
2468 #endif
2469         break;
2470
2471 #ifdef USE_ITHREADS
2472     /* Relocate all the METHOP's SVs to the pad for thread safety. */
2473     case OP_METHOD_NAMED:
2474     case OP_METHOD_SUPER:
2475     case OP_METHOD_REDIR:
2476     case OP_METHOD_REDIR_SUPER:
2477         op_relocate_sv(&cMETHOPx(o)->op_u.op_meth_sv, &o->op_targ);
2478         break;
2479 #endif
2480
2481     case OP_HELEM: {
2482         UNOP *rop;
2483         SVOP *key_op;
2484         OP *kid;
2485
2486         if ((key_op = cSVOPx(((BINOP*)o)->op_last))->op_type != OP_CONST)
2487             break;
2488
2489         rop = (UNOP*)((BINOP*)o)->op_first;
2490
2491         goto check_keys;
2492
2493     case OP_HSLICE:
2494         S_scalar_slice_warning(aTHX_ o);
2495         /* FALLTHROUGH */
2496
2497     case OP_KVHSLICE:
2498         kid = OpSIBLING(cLISTOPo->op_first);
2499         if (/* I bet there's always a pushmark... */
2500             OP_TYPE_ISNT_AND_WASNT_NN(kid, OP_LIST)
2501             && OP_TYPE_ISNT_NN(kid, OP_CONST))
2502         {
2503             break;
2504         }
2505
2506         key_op = (SVOP*)(kid->op_type == OP_CONST
2507                                 ? kid
2508                                 : OpSIBLING(kLISTOP->op_first));
2509
2510         rop = (UNOP*)((LISTOP*)o)->op_last;
2511
2512       check_keys:       
2513         if (o->op_private & OPpLVAL_INTRO || rop->op_type != OP_RV2HV)
2514             rop = NULL;
2515         S_check_hash_fields_and_hekify(aTHX_ rop, key_op);
2516         break;
2517     }
2518     case OP_ASLICE:
2519         S_scalar_slice_warning(aTHX_ o);
2520         break;
2521
2522     case OP_SUBST: {
2523         if (cPMOPo->op_pmreplrootu.op_pmreplroot)
2524             finalize_op(cPMOPo->op_pmreplrootu.op_pmreplroot);
2525         break;
2526     }
2527     default:
2528         break;
2529     }
2530
2531     if (o->op_flags & OPf_KIDS) {
2532         OP *kid;
2533
2534 #ifdef DEBUGGING
2535         /* check that op_last points to the last sibling, and that
2536          * the last op_sibling/op_sibparent field points back to the
2537          * parent, and that the only ops with KIDS are those which are
2538          * entitled to them */
2539         U32 type = o->op_type;
2540         U32 family;
2541         bool has_last;
2542
2543         if (type == OP_NULL) {
2544             type = o->op_targ;
2545             /* ck_glob creates a null UNOP with ex-type GLOB
2546              * (which is a list op. So pretend it wasn't a listop */
2547             if (type == OP_GLOB)
2548                 type = OP_NULL;
2549         }
2550         family = PL_opargs[type] & OA_CLASS_MASK;
2551
2552         has_last = (   family == OA_BINOP
2553                     || family == OA_LISTOP
2554                     || family == OA_PMOP
2555                     || family == OA_LOOP
2556                    );
2557         assert(  has_last /* has op_first and op_last, or ...
2558               ... has (or may have) op_first: */
2559               || family == OA_UNOP
2560               || family == OA_UNOP_AUX
2561               || family == OA_LOGOP
2562               || family == OA_BASEOP_OR_UNOP
2563               || family == OA_FILESTATOP
2564               || family == OA_LOOPEXOP
2565               || family == OA_METHOP
2566               /* I don't know why SASSIGN is tagged as OA_BASEOP - DAPM */
2567               || type == OP_SASSIGN
2568               || type == OP_CUSTOM
2569               || type == OP_NULL /* new_logop does this */
2570               );
2571
2572         for (kid = cUNOPo->op_first; kid; kid = OpSIBLING(kid)) {
2573 #  ifdef PERL_OP_PARENT
2574             if (!OpHAS_SIBLING(kid)) {
2575                 if (has_last)
2576                     assert(kid == cLISTOPo->op_last);
2577                 assert(kid->op_sibparent == o);
2578             }
2579 #  else
2580             if (has_last && !OpHAS_SIBLING(kid))
2581                 assert(kid == cLISTOPo->op_last);
2582 #  endif
2583         }
2584 #endif
2585
2586         for (kid = cUNOPo->op_first; kid; kid = OpSIBLING(kid))
2587             finalize_op(kid);
2588     }
2589 }
2590
2591 /*
2592 =for apidoc Amx|OP *|op_lvalue|OP *o|I32 type
2593
2594 Propagate lvalue ("modifiable") context to an op and its children.
2595 C<type> represents the context type, roughly based on the type of op that
2596 would do the modifying, although C<local()> is represented by C<OP_NULL>,
2597 because it has no op type of its own (it is signalled by a flag on
2598 the lvalue op).
2599
2600 This function detects things that can't be modified, such as C<$x+1>, and
2601 generates errors for them.  For example, C<$x+1 = 2> would cause it to be
2602 called with an op of type C<OP_ADD> and a C<type> argument of C<OP_SASSIGN>.
2603
2604 It also flags things that need to behave specially in an lvalue context,
2605 such as C<$$x = 5> which might have to vivify a reference in C<$x>.
2606
2607 =cut
2608 */
2609
2610 static void
2611 S_mark_padname_lvalue(pTHX_ PADNAME *pn)
2612 {
2613     CV *cv = PL_compcv;
2614     PadnameLVALUE_on(pn);
2615     while (PadnameOUTER(pn) && PARENT_PAD_INDEX(pn)) {
2616         cv = CvOUTSIDE(cv);
2617         assert(cv);
2618         assert(CvPADLIST(cv));
2619         pn =
2620            PadlistNAMESARRAY(CvPADLIST(cv))[PARENT_PAD_INDEX(pn)];
2621         assert(PadnameLEN(pn));
2622         PadnameLVALUE_on(pn);
2623     }
2624 }
2625
2626 static bool
2627 S_vivifies(const OPCODE type)
2628 {
2629     switch(type) {
2630     case OP_RV2AV:     case   OP_ASLICE:
2631     case OP_RV2HV:     case OP_KVASLICE:
2632     case OP_RV2SV:     case   OP_HSLICE:
2633     case OP_AELEMFAST: case OP_KVHSLICE:
2634     case OP_HELEM:
2635     case OP_AELEM:
2636         return 1;
2637     }
2638     return 0;
2639 }
2640
2641 static void
2642 S_lvref(pTHX_ OP *o, I32 type)
2643 {
2644     dVAR;
2645     OP *kid;
2646     switch (o->op_type) {
2647     case OP_COND_EXPR:
2648         for (kid = OpSIBLING(cUNOPo->op_first); kid;
2649              kid = OpSIBLING(kid))
2650             S_lvref(aTHX_ kid, type);
2651         /* FALLTHROUGH */
2652     case OP_PUSHMARK:
2653         return;
2654     case OP_RV2AV:
2655         if (cUNOPo->op_first->op_type != OP_GV) goto badref;
2656         o->op_flags |= OPf_STACKED;
2657         if (o->op_flags & OPf_PARENS) {
2658             if (o->op_private & OPpLVAL_INTRO) {
2659                  yyerror(Perl_form(aTHX_ "Can't modify reference to "
2660                       "localized parenthesized array in list assignment"));
2661                 return;
2662             }
2663           slurpy:
2664             OpTYPE_set(o, OP_LVAVREF);
2665             o->op_private &= OPpLVAL_INTRO|OPpPAD_STATE;
2666             o->op_flags |= OPf_MOD|OPf_REF;
2667             return;
2668         }
2669         o->op_private |= OPpLVREF_AV;
2670         goto checkgv;
2671     case OP_RV2CV:
2672         kid = cUNOPo->op_first;
2673         if (kid->op_type == OP_NULL)
2674             kid = cUNOPx(OpSIBLING(kUNOP->op_first))
2675                 ->op_first;
2676         o->op_private = OPpLVREF_CV;
2677         if (kid->op_type == OP_GV)
2678             o->op_flags |= OPf_STACKED;
2679         else if (kid->op_type == OP_PADCV) {
2680             o->op_targ = kid->op_targ;
2681             kid->op_targ = 0;
2682             op_free(cUNOPo->op_first);
2683             cUNOPo->op_first = NULL;
2684             o->op_flags &=~ OPf_KIDS;
2685         }
2686         else goto badref;
2687         break;
2688     case OP_RV2HV:
2689         if (o->op_flags & OPf_PARENS) {
2690           parenhash:
2691             yyerror(Perl_form(aTHX_ "Can't modify reference to "
2692                                  "parenthesized hash in list assignment"));
2693                 return;
2694         }
2695         o->op_private |= OPpLVREF_HV;
2696         /* FALLTHROUGH */
2697     case OP_RV2SV:
2698       checkgv:
2699         if (cUNOPo->op_first->op_type != OP_GV) goto badref;
2700         o->op_flags |= OPf_STACKED;
2701         break;
2702     case OP_PADHV:
2703         if (o->op_flags & OPf_PARENS) goto parenhash;
2704         o->op_private |= OPpLVREF_HV;
2705         /* FALLTHROUGH */
2706     case OP_PADSV:
2707         PAD_COMPNAME_GEN_set(o->op_targ, PERL_INT_MAX);
2708         break;
2709     case OP_PADAV:
2710         PAD_COMPNAME_GEN_set(o->op_targ, PERL_INT_MAX);
2711         if (o->op_flags & OPf_PARENS) goto slurpy;
2712         o->op_private |= OPpLVREF_AV;
2713         break;
2714     case OP_AELEM:
2715     case OP_HELEM:
2716         o->op_private |= OPpLVREF_ELEM;
2717         o->op_flags   |= OPf_STACKED;
2718         break;
2719     case OP_ASLICE:
2720     case OP_HSLICE:
2721         OpTYPE_set(o, OP_LVREFSLICE);
2722         o->op_private &= OPpLVAL_INTRO|OPpLVREF_ELEM;
2723         return;
2724     case OP_NULL:
2725         if (o->op_flags & OPf_SPECIAL)          /* do BLOCK */
2726             goto badref;
2727         else if (!(o->op_flags & OPf_KIDS))
2728             return;
2729         if (o->op_targ != OP_LIST) {
2730             S_lvref(aTHX_ cBINOPo->op_first, type);
2731             return;
2732         }
2733         /* FALLTHROUGH */
2734     case OP_LIST:
2735         for (kid = cLISTOPo->op_first; kid; kid = OpSIBLING(kid)) {
2736             assert((kid->op_flags & OPf_WANT) != OPf_WANT_VOID);
2737             S_lvref(aTHX_ kid, type);
2738         }
2739         return;
2740     case OP_STUB:
2741         if (o->op_flags & OPf_PARENS)
2742             return;
2743         /* FALLTHROUGH */
2744     default:
2745       badref:
2746         /* diag_listed_as: Can't modify reference to %s in %s assignment */
2747         yyerror(Perl_form(aTHX_ "Can't modify reference to %s in %s",
2748                      o->op_type == OP_NULL && o->op_flags & OPf_SPECIAL
2749                       ? "do block"
2750                       : OP_DESC(o),
2751                      PL_op_desc[type]));
2752     }
2753     OpTYPE_set(o, OP_LVREF);
2754     o->op_private &=
2755         OPpLVAL_INTRO|OPpLVREF_ELEM|OPpLVREF_TYPE|OPpPAD_STATE;
2756     if (type == OP_ENTERLOOP)
2757         o->op_private |= OPpLVREF_ITER;
2758 }
2759
2760 OP *
2761 Perl_op_lvalue_flags(pTHX_ OP *o, I32 type, U32 flags)
2762 {
2763     dVAR;
2764     OP *kid;
2765     /* -1 = error on localize, 0 = ignore localize, 1 = ok to localize */
2766     int localize = -1;
2767
2768     if (!o || (PL_parser && PL_parser->error_count))
2769         return o;
2770
2771     if ((o->op_private & OPpTARGET_MY)
2772         && (PL_opargs[o->op_type] & OA_TARGLEX))/* OPp share the meaning */
2773     {
2774         return o;
2775     }
2776
2777     assert( (o->op_flags & OPf_WANT) != OPf_WANT_VOID );
2778
2779     if (type == OP_PRTF || type == OP_SPRINTF) type = OP_ENTERSUB;
2780
2781     switch (o->op_type) {
2782     case OP_UNDEF:
2783         PL_modcount++;
2784         return o;
2785     case OP_STUB:
2786         if ((o->op_flags & OPf_PARENS))
2787             break;
2788         goto nomod;
2789     case OP_ENTERSUB:
2790         if ((type == OP_UNDEF || type == OP_REFGEN || type == OP_LOCK) &&
2791             !(o->op_flags & OPf_STACKED)) {
2792             OpTYPE_set(o, OP_RV2CV);            /* entersub => rv2cv */
2793             assert(cUNOPo->op_first->op_type == OP_NULL);
2794             op_null(((LISTOP*)cUNOPo->op_first)->op_first);/* disable pushmark */
2795             break;
2796         }
2797         else {                          /* lvalue subroutine call */
2798             o->op_private |= OPpLVAL_INTRO;
2799             PL_modcount = RETURN_UNLIMITED_NUMBER;
2800             if (type == OP_GREPSTART || type == OP_ENTERSUB
2801              || type == OP_REFGEN    || type == OP_LEAVESUBLV) {
2802                 /* Potential lvalue context: */
2803                 o->op_private |= OPpENTERSUB_INARGS;
2804                 break;
2805             }
2806             else {                      /* Compile-time error message: */
2807                 OP *kid = cUNOPo->op_first;
2808                 CV *cv;
2809                 GV *gv;
2810                 SV *namesv;
2811
2812                 if (kid->op_type != OP_PUSHMARK) {
2813                     if (kid->op_type != OP_NULL || kid->op_targ != OP_LIST)
2814                         Perl_croak(aTHX_
2815                                 "panic: unexpected lvalue entersub "
2816                                 "args: type/targ %ld:%"UVuf,
2817                                 (long)kid->op_type, (UV)kid->op_targ);
2818                     kid = kLISTOP->op_first;
2819                 }
2820                 while (OpHAS_SIBLING(kid))
2821                     kid = OpSIBLING(kid);
2822                 if (!(kid->op_type == OP_NULL && kid->op_targ == OP_RV2CV)) {
2823                     break;      /* Postpone until runtime */
2824                 }
2825
2826                 kid = kUNOP->op_first;
2827                 if (kid->op_type == OP_NULL && kid->op_targ == OP_RV2SV)
2828                     kid = kUNOP->op_first;
2829                 if (kid->op_type == OP_NULL)
2830                     Perl_croak(aTHX_
2831                                "Unexpected constant lvalue entersub "
2832                                "entry via type/targ %ld:%"UVuf,
2833                                (long)kid->op_type, (UV)kid->op_targ);
2834                 if (kid->op_type != OP_GV) {
2835                     break;
2836                 }
2837
2838                 gv = kGVOP_gv;
2839                 cv = isGV(gv)
2840                     ? GvCV(gv)
2841                     : SvROK(gv) && SvTYPE(SvRV(gv)) == SVt_PVCV
2842                         ? MUTABLE_CV(SvRV(gv))
2843                         : NULL;
2844                 if (!cv)
2845                     break;
2846                 if (CvLVALUE(cv))
2847                     break;
2848                 if (flags & OP_LVALUE_NO_CROAK)
2849                     return NULL;
2850
2851                 namesv = cv_name(cv, NULL, 0);
2852                 yyerror_pv(Perl_form(aTHX_ "Can't modify non-lvalue "
2853                                      "subroutine call of &%"SVf" in %s",
2854                                      SVfARG(namesv), PL_op_desc[type]),
2855                            SvUTF8(namesv));
2856                 return o;
2857             }
2858         }
2859         /* FALLTHROUGH */
2860     default:
2861       nomod:
2862         if (flags & OP_LVALUE_NO_CROAK) return NULL;
2863         /* grep, foreach, subcalls, refgen */
2864         if (type == OP_GREPSTART || type == OP_ENTERSUB
2865          || type == OP_REFGEN    || type == OP_LEAVESUBLV)
2866             break;
2867         yyerror(Perl_form(aTHX_ "Can't modify %s in %s",
2868                      (o->op_type == OP_NULL && (o->op_flags & OPf_SPECIAL)
2869                       ? "do block"
2870                       : OP_DESC(o)),
2871                      type ? PL_op_desc[type] : "local"));
2872         return o;
2873
2874     case OP_PREINC:
2875     case OP_PREDEC:
2876     case OP_POW:
2877     case OP_MULTIPLY:
2878     case OP_DIVIDE:
2879     case OP_MODULO:
2880     case OP_ADD:
2881     case OP_SUBTRACT:
2882     case OP_CONCAT:
2883     case OP_LEFT_SHIFT:
2884     case OP_RIGHT_SHIFT:
2885     case OP_BIT_AND:
2886     case OP_BIT_XOR:
2887     case OP_BIT_OR:
2888     case OP_I_MULTIPLY:
2889     case OP_I_DIVIDE:
2890     case OP_I_MODULO:
2891     case OP_I_ADD:
2892     case OP_I_SUBTRACT:
2893         if (!(o->op_flags & OPf_STACKED))
2894             goto nomod;
2895         PL_modcount++;
2896         break;
2897
2898     case OP_REPEAT:
2899         if (o->op_flags & OPf_STACKED) {
2900             PL_modcount++;
2901             break;
2902         }
2903         if (!(o->op_private & OPpREPEAT_DOLIST))
2904             goto nomod;
2905         else {
2906             const I32 mods = PL_modcount;
2907             modkids(cBINOPo->op_first, type);
2908             if (type != OP_AASSIGN)
2909                 goto nomod;
2910             kid = cBINOPo->op_last;
2911             if (kid->op_type == OP_CONST && SvIOK(kSVOP_sv)) {
2912                 const IV iv = SvIV(kSVOP_sv);
2913                 if (PL_modcount != RETURN_UNLIMITED_NUMBER)
2914                     PL_modcount =
2915                         mods + (PL_modcount - mods) * (iv < 0 ? 0 : iv);
2916             }
2917             else
2918                 PL_modcount = RETURN_UNLIMITED_NUMBER;
2919         }
2920         break;
2921
2922     case OP_COND_EXPR:
2923         localize = 1;
2924         for (kid = OpSIBLING(cUNOPo->op_first); kid; kid = OpSIBLING(kid))
2925             op_lvalue(kid, type);
2926         break;
2927
2928     case OP_RV2AV:
2929     case OP_RV2HV:
2930         if (type == OP_REFGEN && o->op_flags & OPf_PARENS) {
2931            PL_modcount = RETURN_UNLIMITED_NUMBER;
2932             return o;           /* Treat \(@foo) like ordinary list. */
2933         }
2934         /* FALLTHROUGH */
2935     case OP_RV2GV:
2936         if (scalar_mod_type(o, type))
2937             goto nomod;
2938         ref(cUNOPo->op_first, o->op_type);
2939         /* FALLTHROUGH */
2940     case OP_ASLICE:
2941     case OP_HSLICE:
2942         localize = 1;
2943         /* FALLTHROUGH */
2944     case OP_AASSIGN:
2945         /* Do not apply the lvsub flag for rv2[ah]v in scalar context.  */
2946         if (type == OP_LEAVESUBLV && (
2947                 (o->op_type != OP_RV2AV && o->op_type != OP_RV2HV)
2948              || (o->op_flags & OPf_WANT) != OPf_WANT_SCALAR
2949            ))
2950             o->op_private |= OPpMAYBE_LVSUB;
2951         /* FALLTHROUGH */
2952     case OP_NEXTSTATE:
2953     case OP_DBSTATE:
2954        PL_modcount = RETURN_UNLIMITED_NUMBER;
2955         break;
2956     case OP_KVHSLICE:
2957     case OP_KVASLICE:
2958         if (type == OP_LEAVESUBLV)
2959             o->op_private |= OPpMAYBE_LVSUB;
2960         goto nomod;
2961     case OP_AV2ARYLEN:
2962         PL_hints |= HINT_BLOCK_SCOPE;
2963         if (type == OP_LEAVESUBLV)
2964             o->op_private |= OPpMAYBE_LVSUB;
2965         PL_modcount++;
2966         break;
2967     case OP_RV2SV:
2968         ref(cUNOPo->op_first, o->op_type);
2969         localize = 1;
2970         /* FALLTHROUGH */
2971     case OP_GV:
2972         PL_hints |= HINT_BLOCK_SCOPE;
2973         /* FALLTHROUGH */
2974     case OP_SASSIGN:
2975     case OP_ANDASSIGN:
2976     case OP_ORASSIGN:
2977     case OP_DORASSIGN:
2978         PL_modcount++;
2979         break;
2980
2981     case OP_AELEMFAST:
2982     case OP_AELEMFAST_LEX:
2983         localize = -1;
2984         PL_modcount++;
2985         break;
2986
2987     case OP_PADAV:
2988     case OP_PADHV:
2989        PL_modcount = RETURN_UNLIMITED_NUMBER;
2990         if (type == OP_REFGEN && o->op_flags & OPf_PARENS)
2991             return o;           /* Treat \(@foo) like ordinary list. */
2992         if (scalar_mod_type(o, type))
2993             goto nomod;
2994         if ((o->op_flags & OPf_WANT) != OPf_WANT_SCALAR
2995           && type == OP_LEAVESUBLV)
2996             o->op_private |= OPpMAYBE_LVSUB;
2997         /* FALLTHROUGH */
2998     case OP_PADSV:
2999         PL_modcount++;
3000         if (!type) /* local() */
3001             Perl_croak(aTHX_ "Can't localize lexical variable %"PNf,
3002                               PNfARG(PAD_COMPNAME(o->op_targ)));
3003         if (!(o->op_private & OPpLVAL_INTRO)
3004          || (  type != OP_SASSIGN && type != OP_AASSIGN
3005             && PadnameIsSTATE(PAD_COMPNAME_SV(o->op_targ))  ))
3006             S_mark_padname_lvalue(aTHX_ PAD_COMPNAME_SV(o->op_targ));
3007         break;
3008
3009     case OP_PUSHMARK:
3010         localize = 0;
3011         break;
3012
3013     case OP_KEYS:
3014         if (type != OP_SASSIGN && type != OP_LEAVESUBLV)
3015             goto nomod;
3016         goto lvalue_func;
3017     case OP_SUBSTR:
3018         if (o->op_private == 4) /* don't allow 4 arg substr as lvalue */
3019             goto nomod;
3020         /* FALLTHROUGH */
3021     case OP_POS:
3022     case OP_VEC:
3023       lvalue_func:
3024         if (type == OP_LEAVESUBLV)
3025             o->op_private |= OPpMAYBE_LVSUB;
3026         if (o->op_flags & OPf_KIDS)
3027             op_lvalue(OpSIBLING(cBINOPo->op_first), type);
3028         break;
3029
3030     case OP_AELEM:
3031     case OP_HELEM:
3032         ref(cBINOPo->op_first, o->op_type);
3033         if (type == OP_ENTERSUB &&
3034              !(o->op_private & (OPpLVAL_INTRO | OPpDEREF)))
3035             o->op_private |= OPpLVAL_DEFER;
3036         if (type == OP_LEAVESUBLV)
3037             o->op_private |= OPpMAYBE_LVSUB;
3038         localize = 1;
3039         PL_modcount++;
3040         break;
3041
3042     case OP_LEAVE:
3043     case OP_LEAVELOOP:
3044         o->op_private |= OPpLVALUE;
3045         /* FALLTHROUGH */
3046     case OP_SCOPE:
3047     case OP_ENTER:
3048     case OP_LINESEQ:
3049         localize = 0;
3050         if (o->op_flags & OPf_KIDS)
3051             op_lvalue(cLISTOPo->op_last, type);
3052         break;
3053
3054     case OP_NULL:
3055         localize = 0;
3056         if (o->op_flags & OPf_SPECIAL)          /* do BLOCK */
3057             goto nomod;
3058         else if (!(o->op_flags & OPf_KIDS))
3059             break;
3060         if (o->op_targ != OP_LIST) {
3061             op_lvalue(cBINOPo->op_first, type);
3062             break;
3063         }
3064         /* FALLTHROUGH */
3065     case OP_LIST:
3066         localize = 0;
3067         for (kid = cLISTOPo->op_first; kid; kid = OpSIBLING(kid))
3068             /* elements might be in void context because the list is
3069                in scalar context or because they are attribute sub calls */
3070             if ( (kid->op_flags & OPf_WANT) != OPf_WANT_VOID )
3071                 op_lvalue(kid, type);
3072         break;
3073
3074     case OP_COREARGS:
3075         return o;
3076
3077     case OP_AND:
3078     case OP_OR:
3079         if (type == OP_LEAVESUBLV
3080          || !S_vivifies(cLOGOPo->op_first->op_type))
3081             op_lvalue(cLOGOPo->op_first, type);
3082         if (type == OP_LEAVESUBLV
3083          || !S_vivifies(OpSIBLING(cLOGOPo->op_first)->op_type))
3084             op_lvalue(OpSIBLING(cLOGOPo->op_first), type);
3085         goto nomod;
3086
3087     case OP_SREFGEN:
3088         if (type != OP_AASSIGN && type != OP_SASSIGN
3089          && type != OP_ENTERLOOP)
3090             goto nomod;
3091         /* Don’t bother applying lvalue context to the ex-list.  */
3092         kid = cUNOPx(cUNOPo->op_first)->op_first;
3093         assert (!OpHAS_SIBLING(kid));
3094         goto kid_2lvref;
3095     case OP_REFGEN:
3096         if (type != OP_AASSIGN) goto nomod;
3097         kid = cUNOPo->op_first;
3098       kid_2lvref:
3099         {
3100             const U8 ec = PL_parser ? PL_parser->error_count : 0;
3101             S_lvref(aTHX_ kid, type);
3102             if (!PL_parser || PL_parser->error_count == ec) {
3103                 if (!FEATURE_REFALIASING_IS_ENABLED)
3104                     Perl_croak(aTHX_
3105                        "Experimental aliasing via reference not enabled");
3106                 Perl_ck_warner_d(aTHX_
3107                                  packWARN(WARN_EXPERIMENTAL__REFALIASING),
3108                                 "Aliasing via reference is experimental");
3109             }
3110         }
3111         if (o->op_type == OP_REFGEN)
3112             op_null(cUNOPx(cUNOPo->op_first)->op_first); /* pushmark */
3113         op_null(o);
3114         return o;
3115
3116     case OP_SPLIT:
3117         kid = cLISTOPo->op_first;
3118         if (kid && kid->op_type == OP_PUSHRE &&
3119                 (  kid->op_targ
3120                 || o->op_flags & OPf_STACKED
3121 #ifdef USE_ITHREADS
3122                 || ((PMOP*)kid)->op_pmreplrootu.op_pmtargetoff
3123 #else
3124                 || ((PMOP*)kid)->op_pmreplrootu.op_pmtargetgv
3125 #endif
3126         )) {
3127             /* This is actually @array = split.  */
3128             PL_modcount = RETURN_UNLIMITED_NUMBER;
3129             break;
3130         }
3131         goto nomod;
3132
3133     case OP_SCALAR:
3134         op_lvalue(cUNOPo->op_first, OP_ENTERSUB);
3135         goto nomod;
3136     }
3137
3138     /* [20011101.069] File test operators interpret OPf_REF to mean that
3139        their argument is a filehandle; thus \stat(".") should not set
3140        it. AMS 20011102 */
3141     if (type == OP_REFGEN &&
3142         PL_check[o->op_type] == Perl_ck_ftst)
3143         return o;
3144
3145     if (type != OP_LEAVESUBLV)
3146         o->op_flags |= OPf_MOD;
3147
3148     if (type == OP_AASSIGN || type == OP_SASSIGN)
3149         o->op_flags |= OPf_SPECIAL|OPf_REF;
3150     else if (!type) { /* local() */
3151         switch (localize) {
3152         case 1:
3153             o->op_private |= OPpLVAL_INTRO;
3154             o->op_flags &= ~OPf_SPECIAL;
3155             PL_hints |= HINT_BLOCK_SCOPE;
3156             break;
3157         case 0:
3158             break;
3159         case -1:
3160             Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX),
3161                            "Useless localization of %s", OP_DESC(o));
3162         }
3163     }
3164     else if (type != OP_GREPSTART && type != OP_ENTERSUB
3165              && type != OP_LEAVESUBLV)
3166         o->op_flags |= OPf_REF;
3167     return o;
3168 }
3169
3170 STATIC bool
3171 S_scalar_mod_type(const OP *o, I32 type)
3172 {
3173     switch (type) {
3174     case OP_POS:
3175     case OP_SASSIGN:
3176         if (o && o->op_type == OP_RV2GV)
3177             return FALSE;
3178         /* FALLTHROUGH */
3179     case OP_PREINC:
3180     case OP_PREDEC:
3181     case OP_POSTINC:
3182     case OP_POSTDEC:
3183     case OP_I_PREINC:
3184     case OP_I_PREDEC:
3185     case OP_I_POSTINC:
3186     case OP_I_POSTDEC:
3187     case OP_POW:
3188     case OP_MULTIPLY:
3189     case OP_DIVIDE:
3190     case OP_MODULO:
3191     case OP_REPEAT:
3192     case OP_ADD:
3193     case OP_SUBTRACT:
3194     case OP_I_MULTIPLY:
3195     case OP_I_DIVIDE:
3196     case OP_I_MODULO:
3197     case OP_I_ADD:
3198     case OP_I_SUBTRACT:
3199     case OP_LEFT_SHIFT:
3200     case OP_RIGHT_SHIFT:
3201     case OP_BIT_AND:
3202     case OP_BIT_XOR:
3203     case OP_BIT_OR:
3204     case OP_CONCAT:
3205     case OP_SUBST:
3206     case OP_TRANS:
3207     case OP_TRANSR:
3208     case OP_READ:
3209     case OP_SYSREAD:
3210     case OP_RECV:
3211     case OP_ANDASSIGN:
3212     case OP_ORASSIGN:
3213     case OP_DORASSIGN:
3214         return TRUE;
3215     default:
3216         return FALSE;
3217     }
3218 }
3219
3220 STATIC bool
3221 S_is_handle_constructor(const OP *o, I32 numargs)
3222 {
3223     PERL_ARGS_ASSERT_IS_HANDLE_CONSTRUCTOR;
3224
3225     switch (o->op_type) {
3226     case OP_PIPE_OP:
3227     case OP_SOCKPAIR:
3228         if (numargs == 2)
3229             return TRUE;
3230         /* FALLTHROUGH */
3231     case OP_SYSOPEN:
3232     case OP_OPEN:
3233     case OP_SELECT:             /* XXX c.f. SelectSaver.pm */
3234     case OP_SOCKET:
3235     case OP_OPEN_DIR:
3236     case OP_ACCEPT:
3237         if (numargs == 1)
3238             return TRUE;
3239         /* FALLTHROUGH */
3240     default:
3241         return FALSE;
3242     }
3243 }
3244
3245 static OP *
3246 S_refkids(pTHX_ OP *o, I32 type)
3247 {
3248     if (o && o->op_flags & OPf_KIDS) {
3249         OP *kid;
3250         for (kid = cLISTOPo->op_first; kid; kid = OpSIBLING(kid))
3251             ref(kid, type);
3252     }
3253     return o;
3254 }
3255
3256 OP *
3257 Perl_doref(pTHX_ OP *o, I32 type, bool set_op_ref)
3258 {
3259     dVAR;
3260     OP *kid;
3261
3262     PERL_ARGS_ASSERT_DOREF;
3263
3264     if (PL_parser && PL_parser->error_count)
3265         return o;
3266
3267     switch (o->op_type) {
3268     case OP_ENTERSUB:
3269         if ((type == OP_EXISTS || type == OP_DEFINED) &&
3270             !(o->op_flags & OPf_STACKED)) {
3271             OpTYPE_set(o, OP_RV2CV);             /* entersub => rv2cv */
3272             assert(cUNOPo->op_first->op_type == OP_NULL);
3273             op_null(((LISTOP*)cUNOPo->op_first)->op_first);     /* disable pushmark */
3274             o->op_flags |= OPf_SPECIAL;
3275         }
3276         else if (type == OP_RV2SV || type == OP_RV2AV || type == OP_RV2HV){
3277             o->op_private |= (type == OP_RV2AV ? OPpDEREF_AV
3278                               : type == OP_RV2HV ? OPpDEREF_HV
3279                               : OPpDEREF_SV);
3280             o->op_flags |= OPf_MOD;
3281         }
3282
3283         break;
3284
3285     case OP_COND_EXPR:
3286         for (kid = OpSIBLING(cUNOPo->op_first); kid; kid = OpSIBLING(kid))
3287             doref(kid, type, set_op_ref);
3288         break;
3289     case OP_RV2SV:
3290         if (type == OP_DEFINED)
3291             o->op_flags |= OPf_SPECIAL;         /* don't create GV */
3292         doref(cUNOPo->op_first, o->op_type, set_op_ref);
3293         /* FALLTHROUGH */
3294     case OP_PADSV:
3295         if (type == OP_RV2SV || type == OP_RV2AV || type == OP_RV2HV) {
3296             o->op_private |= (type == OP_RV2AV ? OPpDEREF_AV
3297                               : type == OP_RV2HV ? OPpDEREF_HV
3298                               : OPpDEREF_SV);
3299             o->op_flags |= OPf_MOD;
3300         }
3301         break;
3302
3303     case OP_RV2AV:
3304     case OP_RV2HV:
3305         if (set_op_ref)
3306             o->op_flags |= OPf_REF;
3307         /* FALLTHROUGH */
3308     case OP_RV2GV:
3309         if (type == OP_DEFINED)
3310             o->op_flags |= OPf_SPECIAL;         /* don't create GV */
3311         doref(cUNOPo->op_first, o->op_type, set_op_ref);
3312         break;
3313
3314     case OP_PADAV:
3315     case OP_PADHV:
3316         if (set_op_ref)
3317             o->op_flags |= OPf_REF;
3318         break;
3319
3320     case OP_SCALAR:
3321     case OP_NULL:
3322         if (!(o->op_flags & OPf_KIDS) || type == OP_DEFINED)
3323             break;
3324         doref(cBINOPo->op_first, type, set_op_ref);
3325         break;
3326     case OP_AELEM:
3327     case OP_HELEM:
3328         doref(cBINOPo->op_first, o->op_type, set_op_ref);
3329         if (type == OP_RV2SV || type == OP_RV2AV || type == OP_RV2HV) {
3330             o->op_private |= (type == OP_RV2AV ? OPpDEREF_AV
3331                               : type == OP_RV2HV ? OPpDEREF_HV
3332                               : OPpDEREF_SV);
3333             o->op_flags |= OPf_MOD;
3334         }
3335         break;
3336
3337     case OP_SCOPE:
3338     case OP_LEAVE:
3339         set_op_ref = FALSE;
3340         /* FALLTHROUGH */
3341     case OP_ENTER:
3342     case OP_LIST:
3343         if (!(o->op_flags & OPf_KIDS))
3344             break;
3345         doref(cLISTOPo->op_last, type, set_op_ref);
3346         break;
3347     default:
3348         break;
3349     }
3350     return scalar(o);
3351
3352 }
3353
3354 STATIC OP *
3355 S_dup_attrlist(pTHX_ OP *o)
3356 {
3357     OP *rop;
3358
3359     PERL_ARGS_ASSERT_DUP_ATTRLIST;
3360
3361     /* An attrlist is either a simple OP_CONST or an OP_LIST with kids,
3362      * where the first kid is OP_PUSHMARK and the remaining ones
3363      * are OP_CONST.  We need to push the OP_CONST values.
3364      */
3365     if (o->op_type == OP_CONST)
3366         rop = newSVOP(OP_CONST, o->op_flags, SvREFCNT_inc_NN(cSVOPo->op_sv));
3367     else {
3368         assert((o->op_type == OP_LIST) && (o->op_flags & OPf_KIDS));
3369         rop = NULL;
3370         for (o = cLISTOPo->op_first; o; o = OpSIBLING(o)) {
3371             if (o->op_type == OP_CONST)
3372                 rop = op_append_elem(OP_LIST, rop,
3373                                   newSVOP(OP_CONST, o->op_flags,
3374                                           SvREFCNT_inc_NN(cSVOPo->op_sv)));
3375         }
3376     }
3377     return rop;
3378 }
3379
3380 STATIC void
3381 S_apply_attrs(pTHX_ HV *stash, SV *target, OP *attrs)
3382 {
3383     PERL_ARGS_ASSERT_APPLY_ATTRS;
3384     {
3385         SV * const stashsv = newSVhek(HvNAME_HEK(stash));
3386
3387         /* fake up C<use attributes $pkg,$rv,@attrs> */
3388
3389 #define ATTRSMODULE "attributes"
3390 #define ATTRSMODULE_PM "attributes.pm"
3391
3392         Perl_load_module(
3393           aTHX_ PERL_LOADMOD_IMPORT_OPS,
3394           newSVpvs(ATTRSMODULE),
3395           NULL,
3396           op_prepend_elem(OP_LIST,
3397                           newSVOP(OP_CONST, 0, stashsv),
3398                           op_prepend_elem(OP_LIST,
3399                                           newSVOP(OP_CONST, 0,
3400                                                   newRV(target)),
3401                                           dup_attrlist(attrs))));
3402     }
3403 }
3404
3405 STATIC void
3406 S_apply_attrs_my(pTHX_ HV *stash, OP *target, OP *attrs, OP **imopsp)
3407 {
3408     OP *pack, *imop, *arg;
3409     SV *meth, *stashsv, **svp;
3410
3411     PERL_ARGS_ASSERT_APPLY_ATTRS_MY;
3412
3413     if (!attrs)
3414         return;
3415
3416     assert(target->op_type == OP_PADSV ||
3417            target->op_type == OP_PADHV ||
3418            target->op_type == OP_PADAV);
3419
3420     /* Ensure that attributes.pm is loaded. */
3421     /* Don't force the C<use> if we don't need it. */
3422     svp = hv_fetchs(GvHVn(PL_incgv), ATTRSMODULE_PM, FALSE);
3423     if (svp && *svp != &PL_sv_undef)
3424         NOOP;   /* already in %INC */
3425     else
3426         Perl_load_module(aTHX_ PERL_LOADMOD_NOIMPORT,
3427                                newSVpvs(ATTRSMODULE), NULL);
3428
3429     /* Need package name for method call. */
3430     pack = newSVOP(OP_CONST, 0, newSVpvs(ATTRSMODULE));
3431
3432     /* Build up the real arg-list. */
3433     stashsv = newSVhek(HvNAME_HEK(stash));
3434
3435     arg = newOP(OP_PADSV, 0);
3436     arg->op_targ = target->op_targ;
3437     arg = op_prepend_elem(OP_LIST,
3438                        newSVOP(OP_CONST, 0, stashsv),
3439                        op_prepend_elem(OP_LIST,
3440                                     newUNOP(OP_REFGEN, 0,
3441                                             arg),
3442                                     dup_attrlist(attrs)));
3443
3444     /* Fake up a method call to import */
3445     meth = newSVpvs_share("import");
3446     imop = op_convert_list(OP_ENTERSUB, OPf_STACKED|OPf_SPECIAL|OPf_WANT_VOID,
3447                    op_append_elem(OP_LIST,
3448                                op_prepend_elem(OP_LIST, pack, arg),
3449                                newMETHOP_named(OP_METHOD_NAMED, 0, meth)));
3450
3451     /* Combine the ops. */
3452     *imopsp = op_append_elem(OP_LIST, *imopsp, imop);
3453 }
3454
3455 /*
3456 =notfor apidoc apply_attrs_string
3457
3458 Attempts to apply a list of attributes specified by the C<attrstr> and
3459 C<len> arguments to the subroutine identified by the C<cv> argument which
3460 is expected to be associated with the package identified by the C<stashpv>
3461 argument (see L<attributes>).  It gets this wrong, though, in that it
3462 does not correctly identify the boundaries of the individual attribute
3463 specifications within C<attrstr>.  This is not really intended for the
3464 public API, but has to be listed here for systems such as AIX which
3465 need an explicit export list for symbols.  (It's called from XS code
3466 in support of the C<ATTRS:> keyword from F<xsubpp>.)  Patches to fix it
3467 to respect attribute syntax properly would be welcome.
3468
3469 =cut
3470 */
3471
3472 void
3473 Perl_apply_attrs_string(pTHX_ const char *stashpv, CV *cv,
3474                         const char *attrstr, STRLEN len)
3475 {
3476     OP *attrs = NULL;
3477
3478     PERL_ARGS_ASSERT_APPLY_ATTRS_STRING;
3479
3480     if (!len) {
3481         len = strlen(attrstr);
3482     }
3483
3484     while (len) {
3485         for (; isSPACE(*attrstr) && len; --len, ++attrstr) ;
3486         if (len) {
3487             const char * const sstr = attrstr;
3488             for (; !isSPACE(*attrstr) && len; --len, ++attrstr) ;
3489             attrs = op_append_elem(OP_LIST, attrs,
3490                                 newSVOP(OP_CONST, 0,
3491                                         newSVpvn(sstr, attrstr-sstr)));
3492         }
3493     }
3494
3495     Perl_load_module(aTHX_ PERL_LOADMOD_IMPORT_OPS,
3496                      newSVpvs(ATTRSMODULE),
3497                      NULL, op_prepend_elem(OP_LIST,
3498                                   newSVOP(OP_CONST, 0, newSVpv(stashpv,0)),
3499                                   op_prepend_elem(OP_LIST,
3500                                                newSVOP(OP_CONST, 0,
3501                                                        newRV(MUTABLE_SV(cv))),
3502                                                attrs)));
3503 }
3504
3505 STATIC void
3506 S_move_proto_attr(pTHX_ OP **proto, OP **attrs, const GV * name)
3507 {
3508     OP *new_proto = NULL;
3509     STRLEN pvlen;
3510     char *pv;
3511     OP *o;
3512
3513     PERL_ARGS_ASSERT_MOVE_PROTO_ATTR;
3514
3515     if (!*attrs)
3516         return;
3517
3518     o = *attrs;
3519     if (o->op_type == OP_CONST) {
3520         pv = SvPV(cSVOPo_sv, pvlen);
3521         if (pvlen >= 10 && memEQ(pv, "prototype(", 10)) {
3522             SV * const tmpsv = newSVpvn_flags(pv + 10, pvlen - 11, SvUTF8(cSVOPo_sv));
3523             SV ** const tmpo = cSVOPx_svp(o);
3524             SvREFCNT_dec(cSVOPo_sv);
3525             *tmpo = tmpsv;
3526             new_proto = o;
3527             *attrs = NULL;
3528         }
3529     } else if (o->op_type == OP_LIST) {
3530         OP * lasto;
3531         assert(o->op_flags & OPf_KIDS);
3532         lasto = cLISTOPo->op_first;
3533         assert(lasto->op_type == OP_PUSHMARK);
3534         for (o = OpSIBLING(lasto); o; o = OpSIBLING(o)) {
3535             if (o->op_type == OP_CONST) {
3536                 pv = SvPV(cSVOPo_sv, pvlen);
3537                 if (pvlen >= 10 && memEQ(pv, "prototype(", 10)) {
3538                     SV * const tmpsv = newSVpvn_flags(pv + 10, pvlen - 11, SvUTF8(cSVOPo_sv));
3539                     SV ** const tmpo = cSVOPx_svp(o);
3540                     SvREFCNT_dec(cSVOPo_sv);
3541                     *tmpo = tmpsv;
3542                     if (new_proto && ckWARN(WARN_MISC)) {
3543                         STRLEN new_len;
3544                         const char * newp = SvPV(cSVOPo_sv, new_len);
3545                         Perl_warner(aTHX_ packWARN(WARN_MISC),
3546                             "Attribute prototype(%"UTF8f") discards earlier prototype attribute in same sub",
3547                             UTF8fARG(SvUTF8(cSVOPo_sv), new_len, newp));
3548                         op_free(new_proto);
3549                     }
3550                     else if (new_proto)
3551                         op_free(new_proto);
3552                     new_proto = o;
3553                     /* excise new_proto from the list */
3554                     op_sibling_splice(*attrs, lasto, 1, NULL);
3555                     o = lasto;
3556                     continue;
3557                 }
3558             }
3559             lasto = o;
3560         }
3561         /* If the list is now just the PUSHMARK, scrap the whole thing; otherwise attributes.xs
3562            would get pulled in with no real need */
3563         if (!OpHAS_SIBLING(cLISTOPx(*attrs)->op_first)) {
3564             op_free(*attrs);
3565             *attrs = NULL;
3566         }
3567     }
3568
3569     if (new_proto) {
3570         SV *svname;
3571         if (isGV(name)) {
3572             svname = sv_newmortal();
3573             gv_efullname3(svname, name, NULL);
3574         }
3575         else if (SvPOK(name) && *SvPVX((SV *)name) == '&')
3576             svname = newSVpvn_flags(SvPVX((SV *)name)+1, SvCUR(name)-1, SvUTF8(name)|SVs_TEMP);
3577         else
3578             svname = (SV *)name;
3579         if (ckWARN(WARN_ILLEGALPROTO))
3580             (void)validate_proto(svname, cSVOPx_sv(new_proto), TRUE);
3581         if (*proto && ckWARN(WARN_PROTOTYPE)) {
3582             STRLEN old_len, new_len;
3583             const char * oldp = SvPV(cSVOPx_sv(*proto), old_len);
3584             const char * newp = SvPV(cSVOPx_sv(new_proto), new_len);
3585
3586             Perl_warner(aTHX_ packWARN(WARN_PROTOTYPE),
3587                 "Prototype '%"UTF8f"' overridden by attribute 'prototype(%"UTF8f")'"
3588                 " in %"SVf,
3589                 UTF8fARG(SvUTF8(cSVOPx_sv(*proto)), old_len, oldp),
3590                 UTF8fARG(SvUTF8(cSVOPx_sv(new_proto)), new_len, newp),
3591                 SVfARG(svname));
3592         }
3593         if (*proto)
3594             op_free(*proto);
3595         *proto = new_proto;
3596     }
3597 }
3598
3599 static void
3600 S_cant_declare(pTHX_ OP *o)
3601 {
3602     if (o->op_type == OP_NULL
3603      && (o->op_flags & (OPf_SPECIAL|OPf_KIDS)) == OPf_KIDS)
3604         o = cUNOPo->op_first;
3605     yyerror(Perl_form(aTHX_ "Can't declare %s in \"%s\"",
3606                              o->op_type == OP_NULL
3607                                && o->op_flags & OPf_SPECIAL
3608                                  ? "do block"
3609                                  : OP_DESC(o),
3610                              PL_parser->in_my == KEY_our   ? "our"   :
3611                              PL_parser->in_my == KEY_state ? "state" :
3612                                                              "my"));
3613 }
3614
3615 STATIC OP *
3616 S_my_kid(pTHX_ OP *o, OP *attrs, OP **imopsp)
3617 {
3618     I32 type;
3619     const bool stately = PL_parser && PL_parser->in_my == KEY_state;
3620
3621     PERL_ARGS_ASSERT_MY_KID;
3622
3623     if (!o || (PL_parser && PL_parser->error_count))
3624         return o;
3625
3626     type = o->op_type;
3627
3628     if (type == OP_LIST) {
3629         OP *kid;
3630         for (kid = cLISTOPo->op_first; kid; kid = OpSIBLING(kid))
3631             my_kid(kid, attrs, imopsp);
3632         return o;
3633     } else if (type == OP_UNDEF || type == OP_STUB) {
3634         return o;
3635     } else if (type == OP_RV2SV ||      /* "our" declaration */
3636                type == OP_RV2AV ||
3637                type == OP_RV2HV) { /* XXX does this let anything illegal in? */
3638         if (cUNOPo->op_first->op_type != OP_GV) { /* MJD 20011224 */
3639             S_cant_declare(aTHX_ o);
3640         } else if (attrs) {
3641             GV * const gv = cGVOPx_gv(cUNOPo->op_first);
3642             assert(PL_parser);
3643             PL_parser->in_my = FALSE;
3644             PL_parser->in_my_stash = NULL;
3645             apply_attrs(GvSTASH(gv),
3646                         (type == OP_RV2SV ? GvSV(gv) :
3647                          type == OP_RV2AV ? MUTABLE_SV(GvAV(gv)) :
3648                          type == OP_RV2HV ? MUTABLE_SV(GvHV(gv)) : MUTABLE_SV(gv)),
3649                         attrs);
3650         }
3651         o->op_private |= OPpOUR_INTRO;
3652         return o;
3653     }
3654     else if (type != OP_PADSV &&
3655              type != OP_PADAV &&
3656              type != OP_PADHV &&
3657              type != OP_PUSHMARK)
3658     {
3659         S_cant_declare(aTHX_ o);
3660         return o;
3661     }
3662     else if (attrs && type != OP_PUSHMARK) {
3663         HV *stash;
3664
3665         assert(PL_parser);
3666         PL_parser->in_my = FALSE;
3667         PL_parser->in_my_stash = NULL;
3668
3669         /* check for C<my Dog $spot> when deciding package */
3670         stash = PAD_COMPNAME_TYPE(o->op_targ);
3671         if (!stash)
3672             stash = PL_curstash;
3673         apply_attrs_my(stash, o, attrs, imopsp);
3674     }
3675     o->op_flags |= OPf_MOD;
3676     o->op_private |= OPpLVAL_INTRO;
3677     if (stately)
3678         o->op_private |= OPpPAD_STATE;
3679     return o;
3680 }
3681
3682 OP *
3683 Perl_my_attrs(pTHX_ OP *o, OP *attrs)
3684 {
3685     OP *rops;
3686     int maybe_scalar = 0;
3687
3688     PERL_ARGS_ASSERT_MY_ATTRS;
3689
3690 /* [perl #17376]: this appears to be premature, and results in code such as
3691    C< our(%x); > executing in list mode rather than void mode */
3692 #if 0
3693     if (o->op_flags & OPf_PARENS)
3694         list(o);
3695     else
3696         maybe_scalar = 1;
3697 #else
3698     maybe_scalar = 1;
3699 #endif
3700     if (attrs)
3701         SAVEFREEOP(attrs);
3702     rops = NULL;
3703     o = my_kid(o, attrs, &rops);
3704     if (rops) {
3705         if (maybe_scalar && o->op_type == OP_PADSV) {
3706             o = scalar(op_append_list(OP_LIST, rops, o));
3707             o->op_private |= OPpLVAL_INTRO;
3708         }
3709         else {
3710             /* The listop in rops might have a pushmark at the beginning,
3711                which will mess up list assignment. */
3712             LISTOP * const lrops = (LISTOP *)rops; /* for brevity */
3713             if (rops->op_type == OP_LIST && 
3714                 lrops->op_first && lrops->op_first->op_type == OP_PUSHMARK)
3715             {
3716                 OP * const pushmark = lrops->op_first;
3717                 /* excise pushmark */
3718                 op_sibling_splice(rops, NULL, 1, NULL);
3719                 op_free(pushmark);
3720             }
3721             o = op_append_list(OP_LIST, o, rops);
3722         }
3723     }
3724     PL_parser->in_my = FALSE;
3725     PL_parser->in_my_stash = NULL;
3726     return o;
3727 }
3728
3729 OP *
3730 Perl_sawparens(pTHX_ OP *o)
3731 {
3732     PERL_UNUSED_CONTEXT;
3733     if (o)
3734         o->op_flags |= OPf_PARENS;
3735     return o;
3736 }
3737
3738 OP *
3739 Perl_bind_match(pTHX_ I32 type, OP *left, OP *right)
3740 {
3741     OP *o;
3742     bool ismatchop = 0;
3743     const OPCODE ltype = left->op_type;
3744     const OPCODE rtype = right->op_type;
3745
3746     PERL_ARGS_ASSERT_BIND_MATCH;
3747
3748     if ( (ltype == OP_RV2AV || ltype == OP_RV2HV || ltype == OP_PADAV
3749           || ltype == OP_PADHV) && ckWARN(WARN_MISC))
3750     {
3751       const char * const desc
3752           = PL_op_desc[(
3753                           rtype == OP_SUBST || rtype == OP_TRANS
3754                        || rtype == OP_TRANSR
3755                        )
3756                        ? (int)rtype : OP_MATCH];
3757       const bool isary = ltype == OP_RV2AV || ltype == OP_PADAV;
3758       SV * const name =
3759         S_op_varname(aTHX_ left);
3760       if (name)
3761         Perl_warner(aTHX_ packWARN(WARN_MISC),
3762              "Applying %s to %"SVf" will act on scalar(%"SVf")",
3763              desc, SVfARG(name), SVfARG(name));
3764       else {
3765         const char * const sample = (isary
3766              ? "@array" : "%hash");
3767         Perl_warner(aTHX_ packWARN(WARN_MISC),
3768              "Applying %s to %s will act on scalar(%s)",
3769              desc, sample, sample);
3770       }
3771     }
3772
3773     if (rtype == OP_CONST &&
3774         cSVOPx(right)->op_private & OPpCONST_BARE &&
3775         cSVOPx(right)->op_private & OPpCONST_STRICT)
3776     {
3777         no_bareword_allowed(right);
3778     }
3779
3780     /* !~ doesn't make sense with /r, so error on it for now */
3781     if (rtype == OP_SUBST && (cPMOPx(right)->op_pmflags & PMf_NONDESTRUCT) &&
3782         type == OP_NOT)
3783         /* diag_listed_as: Using !~ with %s doesn't make sense */
3784         yyerror("Using !~ with s///r doesn't make sense");
3785     if (rtype == OP_TRANSR && type == OP_NOT)
3786         /* diag_listed_as: Using !~ with %s doesn't make sense */
3787         yyerror("Using !~ with tr///r doesn't make sense");
3788
3789     ismatchop = (rtype == OP_MATCH ||
3790                  rtype == OP_SUBST ||
3791                  rtype == OP_TRANS || rtype == OP_TRANSR)
3792              && !(right->op_flags & OPf_SPECIAL);
3793     if (ismatchop && right->op_private & OPpTARGET_MY) {
3794         right->op_targ = 0;
3795         right->op_private &= ~OPpTARGET_MY;
3796     }
3797     if (!(right->op_flags & OPf_STACKED) && !right->op_targ && ismatchop) {
3798         if (left->op_type == OP_PADSV
3799          && !(left->op_private & OPpLVAL_INTRO))
3800         {
3801             right->op_targ = left->op_targ;
3802             op_free(left);
3803             o = right;
3804         }
3805         else {
3806             right->op_flags |= OPf_STACKED;
3807             if (rtype != OP_MATCH && rtype != OP_TRANSR &&
3808             ! (rtype == OP_TRANS &&
3809                right->op_private & OPpTRANS_IDENTICAL) &&
3810             ! (rtype == OP_SUBST &&
3811                (cPMOPx(right)->op_pmflags & PMf_NONDESTRUCT)))
3812                 left = op_lvalue(left, rtype);
3813             if (right->op_type == OP_TRANS || right->op_type == OP_TRANSR)
3814                 o = newBINOP(OP_NULL, OPf_STACKED, scalar(left), right);
3815             else
3816                 o = op_prepend_elem(rtype, scalar(left), right);
3817         }
3818         if (type == OP_NOT)
3819             return newUNOP(OP_NOT, 0, scalar(o));
3820         return o;
3821     }
3822     else
3823         return bind_match(type, left,
3824                 pmruntime(newPMOP(OP_MATCH, 0), right, NULL, 0, 0));
3825 }
3826
3827 OP *
3828 Perl_invert(pTHX_ OP *o)
3829 {
3830     if (!o)
3831         return NULL;
3832     return newUNOP(OP_NOT, OPf_SPECIAL, scalar(o));
3833 }
3834
3835 /*
3836 =for apidoc Amx|OP *|op_scope|OP *o
3837
3838 Wraps up an op tree with some additional ops so that at runtime a dynamic
3839 scope will be created.  The original ops run in the new dynamic scope,
3840 and then, provided that they exit normally, the scope will be unwound.
3841 The additional ops used to create and unwind the dynamic scope will
3842 normally be an C<enter>/C<leave> pair, but a C<scope> op may be used
3843 instead if the ops are simple enough to not need the full dynamic scope
3844 structure.
3845
3846 =cut
3847 */
3848
3849 OP *
3850 Perl_op_scope(pTHX_ OP *o)
3851 {
3852     dVAR;
3853     if (o) {
3854         if (o->op_flags & OPf_PARENS || PERLDB_NOOPT || TAINTING_get) {
3855             o = op_prepend_elem(OP_LINESEQ, newOP(OP_ENTER, 0), o);
3856             OpTYPE_set(o, OP_LEAVE);
3857         }
3858         else if (o->op_type == OP_LINESEQ) {
3859             OP *kid;
3860             OpTYPE_set(o, OP_SCOPE);
3861             kid = ((LISTOP*)o)->op_first;
3862             if (kid->op_type == OP_NEXTSTATE || kid->op_type == OP_DBSTATE) {
3863                 op_null(kid);
3864
3865                 /* The following deals with things like 'do {1 for 1}' */
3866                 kid = OpSIBLING(kid);
3867                 if (kid &&
3868                     (kid->op_type == OP_NEXTSTATE || kid->op_type == OP_DBSTATE))
3869                     op_null(kid);
3870             }
3871         }
3872         else
3873             o = newLISTOP(OP_SCOPE, 0, o, NULL);
3874     }
3875     return o;
3876 }
3877
3878 OP *
3879 Perl_op_unscope(pTHX_ OP *o)
3880 {
3881     if (o && o->op_type == OP_LINESEQ) {
3882         OP *kid = cLISTOPo->op_first;
3883         for(; kid; kid = OpSIBLING(kid))
3884             if (kid->op_type == OP_NEXTSTATE || kid->op_type == OP_DBSTATE)
3885                 op_null(kid);
3886     }
3887     return o;
3888 }
3889
3890 /*
3891 =for apidoc Am|int|block_start|int full
3892
3893 Handles compile-time scope entry.
3894 Arranges for hints to be restored on block
3895 exit and also handles pad sequence numbers to make lexical variables scope
3896 right.  Returns a savestack index for use with C<block_end>.
3897
3898 =cut
3899 */
3900
3901 int
3902 Perl_block_start(pTHX_ int full)
3903 {
3904     const int retval = PL_savestack_ix;
3905
3906     PL_compiling.cop_seq = PL_cop_seqmax;
3907     COP_SEQMAX_INC;
3908     pad_block_start(full);
3909     SAVEHINTS();
3910     PL_hints &= ~HINT_BLOCK_SCOPE;
3911     SAVECOMPILEWARNINGS();
3912     PL_compiling.cop_warnings = DUP_WARNINGS(PL_compiling.cop_warnings);
3913     SAVEI32(PL_compiling.cop_seq);
3914     PL_compiling.cop_seq = 0;
3915
3916     CALL_BLOCK_HOOKS(bhk_start, full);
3917
3918     return retval;
3919 }
3920
3921 /*
3922 =for apidoc Am|OP *|block_end|I32 floor|OP *seq
3923
3924 Handles compile-time scope exit.  C<floor>
3925 is the savestack index returned by
3926 C<block_start>, and C<seq> is the body of the block.  Returns the block,
3927 possibly modified.
3928
3929 =cut
3930 */
3931
3932 OP*
3933 Perl_block_end(pTHX_ I32 floor, OP *seq)
3934 {
3935     const int needblockscope = PL_hints & HINT_BLOCK_SCOPE;
3936     OP* retval = scalarseq(seq);
3937     OP *o;
3938
3939     /* XXX Is the null PL_parser check necessary here? */
3940     assert(PL_parser); /* Let’s find out under debugging builds.  */
3941     if (PL_parser && PL_parser->parsed_sub) {
3942         o = newSTATEOP(0, NULL, NULL);
3943         op_null(o);
3944         retval = op_append_elem(OP_LINESEQ, retval, o);
3945     }
3946
3947     CALL_BLOCK_HOOKS(bhk_pre_end, &retval);
3948
3949     LEAVE_SCOPE(floor);
3950     if (needblockscope)
3951         PL_hints |= HINT_BLOCK_SCOPE; /* propagate out */
3952     o = pad_leavemy();
3953
3954     if (o) {
3955         /* pad_leavemy has created a sequence of introcv ops for all my
3956            subs declared in the block.  We have to replicate that list with
3957            clonecv ops, to deal with this situation:
3958
3959                sub {
3960                    my sub s1;
3961                    my sub s2;
3962                    sub s1 { state sub foo { \&s2 } }
3963                }->()
3964
3965            Originally, I was going to have introcv clone the CV and turn
3966            off the stale flag.  Since &s1 is declared before &s2, the
3967            introcv op for &s1 is executed (on sub entry) before the one for
3968            &s2.  But the &foo sub inside &s1 (which is cloned when &s1 is
3969            cloned, since it is a state sub) closes over &s2 and expects
3970            to see it in its outer CV’s pad.  If the introcv op clones &s1,
3971            then &s2 is still marked stale.  Since &s1 is not active, and
3972            &foo closes over &s1’s implicit entry for &s2, we get a â€˜Varia-
3973            ble will not stay shared’ warning.  Because it is the same stub
3974            that will be used when the introcv op for &s2 is executed, clos-
3975            ing over it is safe.  Hence, we have to turn off the stale flag
3976            on all lexical subs in the block before we clone any of them.
3977            Hence, having introcv clone the sub cannot work.  So we create a
3978            list of ops like this:
3979
3980                lineseq
3981                   |
3982                   +-- introcv
3983                   |
3984                   +-- introcv
3985                   |
3986                   +-- introcv
3987                   |
3988                   .
3989                   .
3990                   .
3991                   |
3992                   +-- clonecv
3993                   |
3994                   +-- clonecv
3995                   |
3996                   +-- clonecv
3997                   |
3998                   .
3999                   .
4000                   .
4001          */
4002         OP *kid = o->op_flags & OPf_KIDS ? cLISTOPo->op_first : o;
4003         OP * const last = o->op_flags & OPf_KIDS ? cLISTOPo->op_last : o;
4004         for (;; kid = OpSIBLING(kid)) {
4005             OP *newkid = newOP(OP_CLONECV, 0);
4006             newkid->op_targ = kid->op_targ;
4007             o = op_append_elem(OP_LINESEQ, o, newkid);
4008             if (kid == last) break;
4009         }
4010         retval = op_prepend_elem(OP_LINESEQ, o, retval);
4011     }
4012
4013     CALL_BLOCK_HOOKS(bhk_post_end, &retval);
4014
4015     return retval;
4016 }
4017
4018 /*
4019 =head1 Compile-time scope hooks
4020
4021 =for apidoc Aox||blockhook_register
4022
4023 Register a set of hooks to be called when the Perl lexical scope changes
4024 at compile time.  See L<perlguts/"Compile-time scope hooks">.
4025
4026 =cut
4027 */
4028
4029 void
4030 Perl_blockhook_register(pTHX_ BHK *hk)
4031 {
4032     PERL_ARGS_ASSERT_BLOCKHOOK_REGISTER;
4033
4034     Perl_av_create_and_push(aTHX_ &PL_blockhooks, newSViv(PTR2IV(hk)));
4035 }
4036
4037 void
4038 Perl_newPROG(pTHX_ OP *o)
4039 {
4040     PERL_ARGS_ASSERT_NEWPROG;
4041
4042     if (PL_in_eval) {
4043         PERL_CONTEXT *cx;
4044         I32 i;
4045         if (PL_eval_root)
4046                 return;
4047         PL_eval_root = newUNOP(OP_LEAVEEVAL,
4048                                ((PL_in_eval & EVAL_KEEPERR)
4049                                 ? OPf_SPECIAL : 0), o);
4050
4051         cx = &cxstack[cxstack_ix];
4052         assert(CxTYPE(cx) == CXt_EVAL);
4053
4054         if ((cx->blk_gimme & G_WANT) == G_VOID)
4055             scalarvoid(PL_eval_root);
4056         else if ((cx->blk_gimme & G_WANT) == G_ARRAY)
4057             list(PL_eval_root);
4058         else
4059             scalar(PL_eval_root);
4060
4061         PL_eval_start = op_linklist(PL_eval_root);
4062         PL_eval_root->op_private |= OPpREFCOUNTED;
4063         OpREFCNT_set(PL_eval_root, 1);
4064         PL_eval_root->op_next = 0;
4065         i = PL_savestack_ix;
4066         SAVEFREEOP(o);
4067         ENTER;
4068         CALL_PEEP(PL_eval_start);
4069         finalize_optree(PL_eval_root);
4070         S_prune_chain_head(&PL_eval_start);
4071         LEAVE;
4072         PL_savestack_ix = i;
4073     }
4074     else {
4075         if (o->op_type == OP_STUB) {
4076             /* This block is entered if nothing is compiled for the main
4077                program. This will be the case for an genuinely empty main
4078                program, or one which only has BEGIN blocks etc, so already
4079                run and freed.
4080
4081                Historically (5.000) the guard above was !o. However, commit
4082                f8a08f7b8bd67b28 (Jun 2001), integrated to blead as
4083                c71fccf11fde0068, changed perly.y so that newPROG() is now
4084                called with the output of block_end(), which returns a new
4085                OP_STUB for the case of an empty optree. ByteLoader (and
4086                maybe other things) also take this path, because they set up
4087                PL_main_start and PL_main_root directly, without generating an
4088                optree.
4089
4090                If the parsing the main program aborts (due to parse errors,
4091                or due to BEGIN or similar calling exit), then newPROG()
4092                isn't even called, and hence this code path and its cleanups
4093                are skipped. This shouldn't make a make a difference:
4094                * a non-zero return from perl_parse is a failure, and
4095                  perl_destruct() should be called immediately.
4096                * however, if exit(0) is called during the parse, then
4097                  perl_parse() returns 0, and perl_run() is called. As
4098                  PL_main_start will be NULL, perl_run() will return
4099                  promptly, and the exit code will remain 0.
4100             */
4101
4102             PL_comppad_name = 0;
4103             PL_compcv = 0;
4104             S_op_destroy(aTHX_ o);
4105             return;
4106         }
4107         PL_main_root = op_scope(sawparens(scalarvoid(o)));
4108         PL_curcop = &PL_compiling;
4109         PL_main_start = LINKLIST(PL_main_root);
4110         PL_main_root->op_private |= OPpREFCOUNTED;
4111         OpREFCNT_set(PL_main_root, 1);
4112         PL_main_root->op_next = 0;
4113         CALL_PEEP(PL_main_start);
4114         finalize_optree(PL_main_root);
4115         S_prune_chain_head(&PL_main_start);
4116         cv_forget_slab(PL_compcv);
4117         PL_compcv = 0;
4118
4119         /* Register with debugger */
4120         if (PERLDB_INTER) {
4121             CV * const cv = get_cvs("DB::postponed", 0);
4122             if (cv) {
4123                 dSP;
4124                 PUSHMARK(SP);
4125                 XPUSHs(MUTABLE_SV(CopFILEGV(&PL_compiling)));
4126                 PUTBACK;
4127                 call_sv(MUTABLE_SV(cv), G_DISCARD);
4128             }
4129         }
4130     }
4131 }
4132
4133 OP *
4134 Perl_localize(pTHX_ OP *o, I32 lex)
4135 {
4136     PERL_ARGS_ASSERT_LOCALIZE;
4137
4138     if (o->op_flags & OPf_PARENS)
4139 /* [perl #17376]: this appears to be premature, and results in code such as
4140    C< our(%x); > executing in list mode rather than void mode */
4141 #if 0
4142         list(o);
4143 #else
4144         NOOP;
4145 #endif
4146     else {
4147         if ( PL_parser->bufptr > PL_parser->oldbufptr
4148             && PL_parser->bufptr[-1] == ','
4149             && ckWARN(WARN_PARENTHESIS))
4150         {
4151             char *s = PL_parser->bufptr;
4152             bool sigil = FALSE;
4153
4154             /* some heuristics to detect a potential error */
4155             while (*s && (strchr(", \t\n", *s)))
4156                 s++;
4157
4158             while (1) {
4159                 if (*s && (strchr("@$%", *s) || (!lex && *s == '*'))
4160                        && *++s
4161                        && (isWORDCHAR(*s) || UTF8_IS_CONTINUED(*s))) {
4162                     s++;
4163                     sigil = TRUE;
4164                     while (*s && (isWORDCHAR(*s) || UTF8_IS_CONTINUED(*s)))
4165                         s++;
4166                     while (*s && (strchr(", \t\n", *s)))
4167                         s++;
4168                 }
4169                 else
4170                     break;
4171             }
4172             if (sigil && (*s == ';' || *s == '=')) {
4173                 Perl_warner(aTHX_ packWARN(WARN_PARENTHESIS),
4174                                 "Parentheses missing around \"%s\" list",
4175                                 lex
4176                                     ? (PL_parser->in_my == KEY_our
4177                                         ? "our"
4178                                         : PL_parser->in_my == KEY_state
4179                                             ? "state"
4180                                             : "my")
4181                                     : "local");
4182             }
4183         }
4184     }
4185     if (lex)
4186         o = my(o);
4187     else
4188         o = op_lvalue(o, OP_NULL);              /* a bit kludgey */
4189     PL_parser->in_my = FALSE;
4190     PL_parser->in_my_stash = NULL;
4191     return o;
4192 }
4193
4194 OP *
4195 Perl_jmaybe(pTHX_ OP *o)
4196 {
4197     PERL_ARGS_ASSERT_JMAYBE;
4198
4199     if (o->op_type == OP_LIST) {
4200         OP * const o2
4201             = newSVREF(newGVOP(OP_GV, 0, gv_fetchpvs(";", GV_ADD|GV_NOTQUAL, SVt_PV)));
4202         o = op_convert_list(OP_JOIN, 0, op_prepend_elem(OP_LIST, o2, o));
4203     }
4204     return o;
4205 }
4206
4207 PERL_STATIC_INLINE OP *
4208 S_op_std_init(pTHX_ OP *o)
4209 {
4210     I32 type = o->op_type;
4211
4212     PERL_ARGS_ASSERT_OP_STD_INIT;
4213
4214     if (PL_opargs[type] & OA_RETSCALAR)
4215         scalar(o);
4216     if (PL_opargs[type] & OA_TARGET && !o->op_targ)
4217         o->op_targ = pad_alloc(type, SVs_PADTMP);
4218
4219     return o;
4220 }
4221
4222 PERL_STATIC_INLINE OP *
4223 S_op_integerize(pTHX_ OP *o)
4224 {
4225     I32 type = o->op_type;
4226
4227     PERL_ARGS_ASSERT_OP_INTEGERIZE;
4228
4229     /* integerize op. */
4230     if ((PL_opargs[type] & OA_OTHERINT) && (PL_hints & HINT_INTEGER))
4231     {
4232         dVAR;
4233         o->op_ppaddr = PL_ppaddr[++(o->op_type)];
4234     }
4235
4236     if (type == OP_NEGATE)
4237         /* XXX might want a ck_negate() for this */
4238         cUNOPo->op_first->op_private &= ~OPpCONST_STRICT;
4239
4240     return o;
4241 }
4242
4243 static OP *
4244 S_fold_constants(pTHX_ OP *o)
4245 {
4246     dVAR;
4247     OP * VOL curop;
4248     OP *newop;
4249     VOL I32 type = o->op_type;
4250     bool is_stringify;
4251     SV * VOL sv = NULL;
4252     int ret = 0;
4253     I32 oldscope;
4254     OP *old_next;
4255     SV * const oldwarnhook = PL_warnhook;
4256     SV * const olddiehook  = PL_diehook;
4257     COP not_compiling;
4258     U8 oldwarn = PL_dowarn;
4259     dJMPENV;
4260
4261     PERL_ARGS_ASSERT_FOLD_CONSTANTS;
4262
4263     if (!(PL_opargs[type] & OA_FOLDCONST))
4264         goto nope;
4265
4266     switch (type) {
4267     case OP_UCFIRST:
4268     case OP_LCFIRST:
4269     case OP_UC:
4270     case OP_LC:
4271     case OP_FC:
4272 #ifdef USE_LOCALE_CTYPE
4273         if (IN_LC_COMPILETIME(LC_CTYPE))
4274             goto nope;
4275 #endif
4276         break;
4277     case OP_SLT:
4278     case OP_SGT:
4279     case OP_SLE:
4280     case OP_SGE:
4281     case OP_SCMP:
4282 #ifdef USE_LOCALE_COLLATE
4283         if (IN_LC_COMPILETIME(LC_COLLATE))
4284             goto nope;
4285 #endif
4286         break;
4287     case OP_SPRINTF:
4288         /* XXX what about the numeric ops? */
4289 #ifdef USE_LOCALE_NUMERIC
4290         if (IN_LC_COMPILETIME(LC_NUMERIC))
4291             goto nope;
4292 #endif
4293         break;
4294     case OP_PACK:
4295         if (!OpHAS_SIBLING(cLISTOPo->op_first)
4296           || OpSIBLING(cLISTOPo->op_first)->op_type != OP_CONST)
4297             goto nope;
4298         {
4299             SV * const sv = cSVOPx_sv(OpSIBLING(cLISTOPo->op_first));
4300             if (!SvPOK(sv) || SvGMAGICAL(sv)) goto nope;
4301             {
4302                 const char *s = SvPVX_const(sv);
4303                 while (s < SvEND(sv)) {
4304                     if (isALPHA_FOLD_EQ(*s, 'p')) goto nope;
4305                     s++;
4306                 }
4307             }
4308         }
4309         break;
4310     case OP_REPEAT:
4311         if (o->op_private & OPpREPEAT_DOLIST) goto nope;
4312         break;
4313     case OP_SREFGEN:
4314         if (cUNOPx(cUNOPo->op_first)->op_first->op_type != OP_CONST
4315          || SvPADTMP(cSVOPx_sv(cUNOPx(cUNOPo->op_first)->op_first)))
4316             goto nope;
4317     }
4318
4319     if (PL_parser && PL_parser->error_count)
4320         goto nope;              /* Don't try to run w/ errors */
4321
4322     for (curop = LINKLIST(o); curop != o; curop = LINKLIST(curop)) {
4323         const OPCODE type = curop->op_type;
4324         if ((type != OP_CONST || (curop->op_private & OPpCONST_BARE)) &&
4325             type != OP_LIST &&
4326             type != OP_SCALAR &&
4327             type != OP_NULL &&
4328             type != OP_PUSHMARK)
4329         {
4330             goto nope;
4331         }
4332     }
4333
4334     curop = LINKLIST(o);
4335     old_next = o->op_next;
4336     o->op_next = 0;
4337     PL_op = curop;
4338
4339     oldscope = PL_scopestack_ix;
4340     create_eval_scope(G_FAKINGEVAL);
4341
4342     /* Verify that we don't need to save it:  */
4343     assert(PL_curcop == &PL_compiling);
4344     StructCopy(&PL_compiling, &not_compiling, COP);
4345     PL_curcop = &not_compiling;
4346     /* The above ensures that we run with all the correct hints of the
4347        currently compiling COP, but that IN_PERL_RUNTIME is true. */
4348     assert(IN_PERL_RUNTIME);
4349     PL_warnhook = PERL_WARNHOOK_FATAL;
4350     PL_diehook  = NULL;
4351     JMPENV_PUSH(ret);
4352
4353     /* Effective $^W=1.  */
4354     if ( ! (PL_dowarn & G_WARN_ALL_MASK))
4355         PL_dowarn |= G_WARN_ON;
4356
4357     switch (ret) {
4358     case 0:
4359         CALLRUNOPS(aTHX);
4360         sv = *(PL_stack_sp--);
4361         if (o->op_targ && sv == PAD_SV(o->op_targ)) {   /* grab pad temp? */
4362             pad_swipe(o->op_targ,  FALSE);
4363         }
4364         else if (SvTEMP(sv)) {                  /* grab mortal temp? */
4365             SvREFCNT_inc_simple_void(sv);
4366             SvTEMP_off(sv);
4367         }
4368         else { assert(SvIMMORTAL(sv)); }
4369         break;
4370     case 3:
4371         /* Something tried to die.  Abandon constant folding.  */
4372         /* Pretend the error never happened.  */
4373         CLEAR_ERRSV();
4374         o->op_next = old_next;
4375         break;
4376     default:
4377         JMPENV_POP;
4378         /* Don't expect 1 (setjmp failed) or 2 (something called my_exit)  */
4379         PL_warnhook = oldwarnhook;
4380         PL_diehook  = olddiehook;
4381         /* XXX note that this croak may fail as we've already blown away
4382          * the stack - eg any nested evals */
4383         Perl_croak(aTHX_ "panic: fold_constants JMPENV_PUSH returned %d", ret);
4384     }
4385     JMPENV_POP;
4386     PL_dowarn   = oldwarn;
4387     PL_warnhook = oldwarnhook;
4388     PL_diehook  = olddiehook;
4389     PL_curcop = &PL_compiling;
4390
4391     if (PL_scopestack_ix > oldscope)
4392         delete_eval_scope();
4393
4394     if (ret)
4395         goto nope;
4396
4397     /* OP_STRINGIFY and constant folding are used to implement qq.
4398        Here the constant folding is an implementation detail that we
4399        want to hide.  If the stringify op is itself already marked
4400        folded, however, then it is actually a folded join.  */
4401     is_stringify = type == OP_STRINGIFY && !o->op_folded;
4402     op_free(o);
4403     assert(sv);
4404     if (is_stringify)
4405         SvPADTMP_off(sv);
4406     else if (!SvIMMORTAL(sv)) {
4407         SvPADTMP_on(sv);
4408         SvREADONLY_on(sv);
4409     }
4410     newop = newSVOP(OP_CONST, 0, MUTABLE_SV(sv));
4411     if (!is_stringify) newop->op_folded = 1;
4412     return newop;
4413
4414  nope:
4415     return o;
4416 }
4417
4418 static OP *
4419 S_gen_constant_list(pTHX_ OP *o)
4420 {
4421     dVAR;
4422     OP *curop;
4423     const SSize_t oldtmps_floor = PL_tmps_floor;
4424     SV **svp;
4425     AV *av;
4426
4427     list(o);
4428     if (PL_parser && PL_parser->error_count)
4429         return o;               /* Don't attempt to run with errors */
4430
4431     curop = LINKLIST(o);
4432     o->op_next = 0;
4433     CALL_PEEP(curop);
4434     S_prune_chain_head(&curop);
4435     PL_op = curop;
4436     Perl_pp_pushmark(aTHX);
4437     CALLRUNOPS(aTHX);
4438     PL_op = curop;
4439     assert (!(curop->op_flags & OPf_SPECIAL));
4440     assert(curop->op_type == OP_RANGE);
4441     Perl_pp_anonlist(aTHX);
4442     PL_tmps_floor = oldtmps_floor;
4443
4444     OpTYPE_set(o, OP_RV2AV);
4445     o->op_flags &= ~OPf_REF;    /* treat \(1..2) like an ordinary list */
4446     o->op_flags |= OPf_PARENS;  /* and flatten \(1..2,3) */
4447     o->op_opt = 0;              /* needs to be revisited in rpeep() */
4448     av = (AV *)SvREFCNT_inc_NN(*PL_stack_sp--);
4449
4450     /* replace subtree with an OP_CONST */
4451     curop = ((UNOP*)o)->op_first;
4452     op_sibling_splice(o, NULL, -1, newSVOP(OP_CONST, 0, (SV *)av));
4453     op_free(curop);
4454
4455     if (AvFILLp(av) != -1)
4456         for (svp = AvARRAY(av) + AvFILLp(av); svp >= AvARRAY(av); --svp)
4457         {
4458             SvPADTMP_on(*svp);
4459             SvREADONLY_on(*svp);
4460         }
4461     LINKLIST(o);
4462     return list(o);
4463 }
4464
4465 /*
4466 =head1 Optree Manipulation Functions
4467 */
4468
4469 /* List constructors */
4470
4471 /*
4472 =for apidoc Am|OP *|op_append_elem|I32 optype|OP *first|OP *last
4473
4474 Append an item to the list of ops contained directly within a list-type
4475 op, returning the lengthened list.  C<first> is the list-type op,
4476 and C<last> is the op to append to the list.  C<optype> specifies the
4477 intended opcode for the list.  If C<first> is not already a list of the
4478 right type, it will be upgraded into one.  If either C<first> or C<last>
4479 is null, the other is returned unchanged.
4480
4481 =cut
4482 */
4483
4484 OP *
4485 Perl_op_append_elem(pTHX_ I32 type, OP *first, OP *last)
4486 {
4487     if (!first)
4488         return last;
4489
4490     if (!last)
4491         return first;
4492
4493     if (first->op_type != (unsigned)type
4494         || (type == OP_LIST && (first->op_flags & OPf_PARENS)))
4495     {
4496         return newLISTOP(type, 0, first, last);
4497     }
4498
4499     op_sibling_splice(first, ((LISTOP*)first)->op_last, 0, last);
4500     first->op_flags |= OPf_KIDS;
4501     return first;
4502 }
4503
4504 /*
4505 =for apidoc Am|OP *|op_append_list|I32 optype|OP *first|OP *last
4506
4507 Concatenate the lists of ops contained directly within two list-type ops,
4508 returning the combined list.  C<first> and C<last> are the list-type ops
4509 to concatenate.  C<optype> specifies the intended opcode for the list.
4510 If either C<first> or C<last> is not already a list of the right type,
4511 it will be upgraded into one.  If either C<first> or C<last> is null,
4512 the other is returned unchanged.
4513
4514 =cut
4515 */
4516
4517 OP *
4518 Perl_op_append_list(pTHX_ I32 type, OP *first, OP *last)
4519 {
4520     if (!first)
4521         return last;
4522
4523     if (!last)
4524         return first;
4525
4526     if (first->op_type != (unsigned)type)
4527         return op_prepend_elem(type, first, last);
4528
4529     if (last->op_type != (unsigned)type)
4530         return op_append_elem(type, first, last);
4531
4532     OpMORESIB_set(((LISTOP*)first)->op_last, ((LISTOP*)last)->op_first);
4533     ((LISTOP*)first)->op_last = ((LISTOP*)last)->op_last;
4534     OpLASTSIB_set(((LISTOP*)first)->op_last, first);
4535     first->op_flags |= (last->op_flags & OPf_KIDS);
4536
4537     S_op_destroy(aTHX_ last);
4538
4539     return first;
4540 }
4541
4542 /*
4543 =for apidoc Am|OP *|op_prepend_elem|I32 optype|OP *first|OP *last
4544
4545 Prepend an item to the list of ops contained directly within a list-type
4546 op, returning the lengthened list.  C<first> is the op to prepend to the
4547 list, and C<last> is the list-type op.  C<optype> specifies the intended
4548 opcode for the list.  If C<last> is not already a list of the right type,
4549 it will be upgraded into one.  If either C<first> or C<last> is null,
4550 the other is returned unchanged.
4551
4552 =cut
4553 */
4554
4555 OP *
4556 Perl_op_prepend_elem(pTHX_ I32 type, OP *first, OP *last)
4557 {
4558     if (!first)
4559         return last;
4560
4561     if (!last)
4562         return first;
4563
4564     if (last->op_type == (unsigned)type) {
4565         if (type == OP_LIST) {  /* already a PUSHMARK there */
4566             /* insert 'first' after pushmark */
4567             op_sibling_splice(last, cLISTOPx(last)->op_first, 0, first);
4568             if (!(first->op_flags & OPf_PARENS))
4569                 last->op_flags &= ~OPf_PARENS;
4570         }
4571         else
4572             op_sibling_splice(last, NULL, 0, first);
4573         last->op_flags |= OPf_KIDS;
4574         return last;
4575     }
4576
4577     return newLISTOP(type, 0, first, last);
4578 }
4579
4580 /*
4581 =for apidoc Am|OP *|op_convert_list|I32 type|I32 flags|OP *o
4582
4583 Converts C<o> into a list op if it is not one already, and then converts it
4584 into the specified C<type>, calling its check function, allocating a target if
4585 it needs one, and folding constants.
4586
4587 A list-type op is usually constructed one kid at a time via C<newLISTOP>,
4588 C<op_prepend_elem> and C<op_append_elem>.  Then finally it is passed to
4589 C<op_convert_list> to make it the right type.
4590
4591 =cut
4592 */
4593
4594 OP *
4595 Perl_op_convert_list(pTHX_ I32 type, I32 flags, OP *o)
4596 {
4597     dVAR;
4598     if (type < 0) type = -type, flags |= OPf_SPECIAL;
4599     if (!o || o->op_type != OP_LIST)
4600         o = force_list(o, 0);
4601     else
4602     {
4603         o->op_flags &= ~OPf_WANT;
4604         o->op_private &= ~OPpLVAL_INTRO;
4605     }
4606
4607     if (!(PL_opargs[type] & OA_MARK))
4608         op_null(cLISTOPo->op_first);
4609     else {
4610         OP * const kid2 = OpSIBLING(cLISTOPo->op_first);
4611         if (kid2 && kid2->op_type == OP_COREARGS) {
4612             op_null(cLISTOPo->op_first);
4613             kid2->op_private |= OPpCOREARGS_PUSHMARK;
4614         }
4615     }
4616
4617     OpTYPE_set(o, type);
4618     o->op_flags |= flags;
4619     if (flags & OPf_FOLDED)
4620         o->op_folded = 1;
4621
4622     o = CHECKOP(type, o);
4623     if (o->op_type != (unsigned)type)
4624         return o;
4625
4626     return fold_constants(op_integerize(op_std_init(o)));
4627 }
4628
4629 /* Constructors */
4630
4631
4632 /*
4633 =head1 Optree construction
4634
4635 =for apidoc Am|OP *|newNULLLIST
4636
4637 Constructs, checks, and returns a new C<stub> op, which represents an
4638 empty list expression.
4639
4640 =cut
4641 */
4642
4643 OP *
4644 Perl_newNULLLIST(pTHX)
4645 {
4646     return newOP(OP_STUB, 0);
4647 }
4648
4649 /* promote o and any siblings to be a list if its not already; i.e.
4650  *
4651  *  o - A - B
4652  *
4653  * becomes
4654  *
4655  *  list
4656  *    |
4657  *  pushmark - o - A - B
4658  *
4659  * If nullit it true, the list op is nulled.
4660  */
4661
4662 static OP *
4663 S_force_list(pTHX_ OP *o, bool nullit)
4664 {
4665     if (!o || o->op_type != OP_LIST) {
4666         OP *rest = NULL;
4667         if (o) {
4668             /* manually detach any siblings then add them back later */
4669             rest = OpSIBLING(o);
4670             OpLASTSIB_set(o, NULL);
4671         }
4672         o = newLISTOP(OP_LIST, 0, o, NULL);
4673         if (rest)
4674             op_sibling_splice(o, cLISTOPo->op_last, 0, rest);
4675     }
4676     if (nullit)
4677         op_null(o);
4678     return o;
4679 }
4680
4681 /*
4682 =for apidoc Am|OP *|newLISTOP|I32 type|I32 flags|OP *first|OP *last
4683
4684 Constructs, checks, and returns an op of any list type.  C<type> is
4685 the opcode.  C<flags> gives the eight bits of C<op_flags>, except that
4686 C<OPf_KIDS> will be set automatically if required.  C<first> and C<last>
4687 supply up to two ops to be direct children of the list op; they are
4688 consumed by this function and become part of the constructed op tree.
4689
4690 For most list operators, the check function expects all the kid ops to be
4691 present already, so calling C<newLISTOP(OP_JOIN, ...)> (e.g.) is not
4692 appropriate.  What you want to do in that case is create an op of type
4693 C<OP_LIST>, append more children to it, and then call L</op_convert_list>.
4694 See L</op_convert_list> for more information.
4695
4696
4697 =cut
4698 */
4699
4700 OP *
4701 Perl_newLISTOP(pTHX_ I32 type, I32 flags, OP *first, OP *last)
4702 {
4703     dVAR;
4704     LISTOP *listop;
4705
4706     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_LISTOP
4707         || type == OP_CUSTOM);
4708
4709     NewOp(1101, listop, 1, LISTOP);
4710
4711     OpTYPE_set(listop, type);
4712     if (first || last)
4713         flags |= OPf_KIDS;
4714     listop->op_flags = (U8)flags;
4715
4716     if (!last && first)
4717         last = first;
4718     else if (!first && last)
4719         first = last;
4720     else if (first)
4721         OpMORESIB_set(first, last);
4722     listop->op_first = first;
4723     listop->op_last = last;
4724     if (type == OP_LIST) {
4725         OP* const pushop = newOP(OP_PUSHMARK, 0);
4726         OpMORESIB_set(pushop, first);
4727         listop->op_first = pushop;
4728         listop->op_flags |= OPf_KIDS;
4729         if (!last)
4730             listop->op_last = pushop;
4731     }
4732     if (listop->op_last)
4733         OpLASTSIB_set(listop->op_last, (OP*)listop);
4734
4735     return CHECKOP(type, listop);
4736 }
4737
4738 /*
4739 =for apidoc Am|OP *|newOP|I32 type|I32 flags
4740
4741 Constructs, checks, and returns an op of any base type (any type that
4742 has no extra fields).  C<type> is the opcode.  C<flags> gives the
4743 eight bits of C<op_flags>, and, shifted up eight bits, the eight bits
4744 of C<op_private>.
4745
4746 =cut
4747 */
4748
4749 OP *
4750 Perl_newOP(pTHX_ I32 type, I32 flags)
4751 {
4752     dVAR;
4753     OP *o;
4754
4755     if (type == -OP_ENTEREVAL) {
4756         type = OP_ENTEREVAL;
4757         flags |= OPpEVAL_BYTES<<8;
4758     }
4759
4760     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_BASEOP
4761         || (PL_opargs[type] & OA_CLASS_MASK) == OA_BASEOP_OR_UNOP
4762         || (PL_opargs[type] & OA_CLASS_MASK) == OA_FILESTATOP
4763         || (PL_opargs[type] & OA_CLASS_MASK) == OA_LOOPEXOP);
4764
4765     NewOp(1101, o, 1, OP);
4766     OpTYPE_set(o, type);
4767     o->op_flags = (U8)flags;
4768
4769     o->op_next = o;
4770     o->op_private = (U8)(0 | (flags >> 8));
4771     if (PL_opargs[type] & OA_RETSCALAR)
4772         scalar(o);
4773     if (PL_opargs[type] & OA_TARGET)
4774         o->op_targ = pad_alloc(type, SVs_PADTMP);
4775     return CHECKOP(type, o);
4776 }
4777
4778 /*
4779 =for apidoc Am|OP *|newUNOP|I32 type|I32 flags|OP *first
4780
4781 Constructs, checks, and returns an op of any unary type.  C<type> is
4782 the opcode.  C<flags> gives the eight bits of C<op_flags>, except that
4783 C<OPf_KIDS> will be set automatically if required, and, shifted up eight
4784 bits, the eight bits of C<op_private>, except that the bit with value 1
4785 is automatically set.  C<first> supplies an optional op to be the direct
4786 child of the unary op; it is consumed by this function and become part
4787 of the constructed op tree.
4788
4789 =cut
4790 */
4791
4792 OP *
4793 Perl_newUNOP(pTHX_ I32 type, I32 flags, OP *first)
4794 {
4795     dVAR;
4796     UNOP *unop;
4797
4798     if (type == -OP_ENTEREVAL) {
4799         type = OP_ENTEREVAL;
4800         flags |= OPpEVAL_BYTES<<8;
4801     }
4802
4803     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_UNOP
4804         || (PL_opargs[type] & OA_CLASS_MASK) == OA_BASEOP_OR_UNOP
4805         || (PL_opargs[type] & OA_CLASS_MASK) == OA_FILESTATOP
4806         || (PL_opargs[type] & OA_CLASS_MASK) == OA_LOOPEXOP
4807         || type == OP_SASSIGN
4808         || type == OP_ENTERTRY
4809         || type == OP_CUSTOM
4810         || type == OP_NULL );
4811
4812     if (!first)
4813         first = newOP(OP_STUB, 0);
4814     if (PL_opargs[type] & OA_MARK)
4815         first = force_list(first, 1);
4816
4817     NewOp(1101, unop, 1, UNOP);
4818     OpTYPE_set(unop, type);
4819     unop->op_first = first;
4820     unop->op_flags = (U8)(flags | OPf_KIDS);
4821     unop->op_private = (U8)(1 | (flags >> 8));
4822
4823     if (!OpHAS_SIBLING(first)) /* true unless weird syntax error */
4824         OpLASTSIB_set(first, (OP*)unop);
4825
4826     unop = (UNOP*) CHECKOP(type, unop);
4827     if (unop->op_next)
4828         return (OP*)unop;
4829
4830     return fold_constants(op_integerize(op_std_init((OP *) unop)));
4831 }
4832
4833 /*
4834 =for apidoc newUNOP_AUX
4835
4836 Similar to C<newUNOP>, but creates an C<UNOP_AUX> struct instead, with C<op_aux>
4837 initialised to C<aux>
4838
4839 =cut
4840 */
4841
4842 OP *
4843 Perl_newUNOP_AUX(pTHX_ I32 type, I32 flags, OP *first, UNOP_AUX_item *aux)
4844 {
4845     dVAR;
4846     UNOP_AUX *unop;
4847
4848     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_UNOP_AUX
4849         || type == OP_CUSTOM);
4850
4851     NewOp(1101, unop, 1, UNOP_AUX);
4852     unop->op_type = (OPCODE)type;
4853     unop->op_ppaddr = PL_ppaddr[type];
4854     unop->op_first = first;
4855     unop->op_flags = (U8)(flags | (first ? OPf_KIDS : 0));
4856     unop->op_private = (U8)((first ? 1 : 0) | (flags >> 8));
4857     unop->op_aux = aux;
4858
4859     if (first && !OpHAS_SIBLING(first)) /* true unless weird syntax error */
4860         OpLASTSIB_set(first, (OP*)unop);
4861
4862     unop = (UNOP_AUX*) CHECKOP(type, unop);
4863
4864     return op_std_init((OP *) unop);
4865 }
4866
4867 /*
4868 =for apidoc Am|OP *|newMETHOP|I32 type|I32 flags|OP *first
4869
4870 Constructs, checks, and returns an op of method type with a method name
4871 evaluated at runtime.  C<type> is the opcode.  C<flags> gives the eight
4872 bits of C<op_flags>, except that C<OPf_KIDS> will be set automatically,
4873 and, shifted up eight bits, the eight bits of C<op_private>, except that
4874 the bit with value 1 is automatically set.  C<dynamic_meth> supplies an
4875 op which evaluates method name; it is consumed by this function and
4876 become part of the constructed op tree.
4877 Supported optypes: C<OP_METHOD>.
4878
4879 =cut
4880 */
4881
4882 static OP*
4883 S_newMETHOP_internal(pTHX_ I32 type, I32 flags, OP* dynamic_meth, SV* const_meth) {
4884     dVAR;
4885     METHOP *methop;
4886
4887     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_METHOP
4888         || type == OP_CUSTOM);
4889
4890     NewOp(1101, methop, 1, METHOP);
4891     if (dynamic_meth) {
4892         if (PL_opargs[type] & OA_MARK) dynamic_meth = force_list(dynamic_meth, 1);
4893         methop->op_flags = (U8)(flags | OPf_KIDS);
4894         methop->op_u.op_first = dynamic_meth;
4895         methop->op_private = (U8)(1 | (flags >> 8));
4896
4897         if (!OpHAS_SIBLING(dynamic_meth))
4898             OpLASTSIB_set(dynamic_meth, (OP*)methop);
4899     }
4900     else {
4901         assert(const_meth);
4902         methop->op_flags = (U8)(flags & ~OPf_KIDS);
4903         methop->op_u.op_meth_sv = const_meth;
4904         methop->op_private = (U8)(0 | (flags >> 8));
4905         methop->op_next = (OP*)methop;
4906     }
4907
4908 #ifdef USE_ITHREADS
4909     methop->op_rclass_targ = 0;
4910 #else
4911     methop->op_rclass_sv = NULL;
4912 #endif
4913
4914     OpTYPE_set(methop, type);
4915     return CHECKOP(type, methop);
4916 }
4917
4918 OP *
4919 Perl_newMETHOP (pTHX_ I32 type, I32 flags, OP* dynamic_meth) {
4920     PERL_ARGS_ASSERT_NEWMETHOP;
4921     return newMETHOP_internal(type, flags, dynamic_meth, NULL);
4922 }
4923
4924 /*
4925 =for apidoc Am|OP *|newMETHOP_named|I32 type|I32 flags|SV *const_meth
4926
4927 Constructs, checks, and returns an op of method type with a constant
4928 method name.  C<type> is the opcode.  C<flags> gives the eight bits of
4929 C<op_flags>, and, shifted up eight bits, the eight bits of
4930 C<op_private>.  C<const_meth> supplies a constant method name;
4931 it must be a shared COW string.
4932 Supported optypes: C<OP_METHOD_NAMED>.
4933
4934 =cut
4935 */
4936
4937 OP *
4938 Perl_newMETHOP_named (pTHX_ I32 type, I32 flags, SV* const_meth) {
4939     PERL_ARGS_ASSERT_NEWMETHOP_NAMED;
4940     return newMETHOP_internal(type, flags, NULL, const_meth);
4941 }
4942
4943 /*
4944 =for apidoc Am|OP *|newBINOP|I32 type|I32 flags|OP *first|OP *last
4945
4946 Constructs, checks, and returns an op of any binary type.  C<type>
4947 is the opcode.  C<flags> gives the eight bits of C<op_flags>, except
4948 that C<OPf_KIDS> will be set automatically, and, shifted up eight bits,
4949 the eight bits of C<op_private>, except that the bit with value 1 or
4950 2 is automatically set as required.  C<first> and C<last> supply up to
4951 two ops to be the direct children of the binary op; they are consumed
4952 by this function and become part of the constructed op tree.
4953
4954 =cut
4955 */
4956
4957 OP *
4958 Perl_newBINOP(pTHX_ I32 type, I32 flags, OP *first, OP *last)
4959 {
4960     dVAR;
4961     BINOP *binop;
4962
4963     ASSUME((PL_opargs[type] & OA_CLASS_MASK) == OA_BINOP
4964         || type == OP_SASSIGN || type == OP_NULL || type == OP_CUSTOM);
4965
4966     NewOp(1101, binop, 1, BINOP);
4967
4968     if (!first)
4969         first = newOP(OP_NULL, 0);
4970
4971     OpTYPE_set(binop, type);
4972     binop->op_first = first;
4973     binop->op_flags = (U8)(flags | OPf_KIDS);
4974     if (!last) {
4975         last = first;
4976         binop->op_private = (U8)(1 | (flags >> 8));
4977     }
4978     else {
4979         binop->op_private = (U8)(2 | (flags >> 8));
4980         OpMORESIB_set(first, last);
4981     }
4982
4983     if (!OpHAS_SIBLING(last)) /* true unless weird syntax error */
4984         OpLASTSIB_set(last, (OP*)binop);
4985
4986     binop->op_last = OpSIBLING(binop->op_first);
4987     if (binop->op_last)
4988         OpLASTSIB_set(binop->op_last, (OP*)binop);
4989
4990     binop = (BINOP*)CHECKOP(type, binop);
4991     if (binop->op_next || binop->op_type != (OPCODE)type)
4992         return (OP*)binop;
4993
4994     return fold_constants(op_integerize(op_std_init((OP *)binop)));
4995 }
4996
4997 static int uvcompare(const void *a, const void *b)
4998     __attribute__nonnull__(1)
4999     __attribute__nonnull__(2)
5000     __attribute__pure__;
5001 static int uvcompare(const void *a, const void *b)
5002 {
5003     if (*((const UV *)a) < (*(const UV *)b))
5004         return -1;
5005     if (*((const UV *)a) > (*(const UV *)b))
5006         return 1;
5007     if (*((const UV *)a+1) < (*(const UV *)b+1))
5008         return -1;
5009     if (*((const UV *)a+1) > (*(const UV *)b+1))
5010         return 1;
5011     return 0;
5012 }
5013
5014 static OP *
5015 S_pmtrans(pTHX_ OP *o, OP *expr, OP *repl)
5016 {
5017     SV * const tstr = ((SVOP*)expr)->op_sv;
5018     SV * const rstr =
5019                               ((SVOP*)repl)->op_sv;
5020     STRLEN tlen;
5021     STRLEN rlen;
5022     const U8 *t = (U8*)SvPV_const(tstr, tlen);
5023     const U8 *r = (U8*)SvPV_const(rstr, rlen);
5024     I32 i;
5025     I32 j;
5026     I32 grows = 0;
5027     short *tbl;
5028
5029     const I32 complement = o->op_private & OPpTRANS_COMPLEMENT;
5030     const I32 squash     = o->op_private & OPpTRANS_SQUASH;
5031     I32 del              = o->op_private & OPpTRANS_DELETE;
5032     SV* swash;
5033
5034     PERL_ARGS_ASSERT_PMTRANS;
5035
5036     PL_hints |= HINT_BLOCK_SCOPE;
5037
5038     if (SvUTF8(tstr))
5039         o->op_private |= OPpTRANS_FROM_UTF;
5040
5041     if (SvUTF8(rstr))
5042         o->op_private |= OPpTRANS_TO_UTF;
5043
5044     if (o->op_private & (OPpTRANS_FROM_UTF|OPpTRANS_TO_UTF)) {
5045         SV* const listsv = newSVpvs("# comment\n");
5046         SV* transv = NULL;
5047         const U8* tend = t + tlen;
5048         const U8* rend = r + rlen;
5049         STRLEN ulen;
5050         UV tfirst = 1;
5051         UV tlast = 0;
5052         IV tdiff;
5053         STRLEN tcount = 0;
5054         UV rfirst = 1;
5055         UV rlast = 0;
5056         IV rdiff;
5057         STRLEN rcount = 0;
5058         IV diff;
5059         I32 none = 0;
5060         U32 max = 0;
5061         I32 bits;
5062         I32 havefinal = 0;
5063         U32 final = 0;
5064         const I32 from_utf  = o->op_private & OPpTRANS_FROM_UTF;
5065         const I32 to_utf    = o->op_private & OPpTRANS_TO_UTF;
5066         U8* tsave = NULL;
5067         U8* rsave = NULL;
5068         const U32 flags = UTF8_ALLOW_DEFAULT;
5069
5070         if (!from_utf) {
5071             STRLEN len = tlen;
5072             t = tsave = bytes_to_utf8(t, &len);
5073             tend = t + len;
5074         }
5075         if (!to_utf && rlen) {
5076             STRLEN len = rlen;
5077             r = rsave = bytes_to_utf8(r, &len);
5078             rend = r + len;
5079         }
5080
5081 /* There is a snag with this code on EBCDIC: scan_const() in toke.c has
5082  * encoded chars in native encoding which makes ranges in the EBCDIC 0..255
5083  * odd.  */
5084
5085         if (complement) {
5086             U8 tmpbuf[UTF8_MAXBYTES+1];
5087             UV *cp;
5088             UV nextmin = 0;
5089             Newx(cp, 2*tlen, UV);
5090             i = 0;
5091             transv = newSVpvs("");
5092             while (t < tend) {
5093                 cp[2*i] = utf8n_to_uvchr(t, tend-t, &ulen, flags);
5094                 t += ulen;
5095                 if (t < tend && *t == ILLEGAL_UTF8_BYTE) {
5096                     t++;
5097                     cp[2*i+1] = utf8n_to_uvchr(t, tend-t, &ulen, flags);
5098                     t += ulen;
5099                 }
5100                 else {
5101                  cp[2*i+1] = cp[2*i];
5102                 }
5103                 i++;
5104             }
5105             qsort(cp, i, 2*sizeof(UV), uvcompare);
5106             for (j = 0; j < i; j++) {
5107                 UV  val = cp[2*j];
5108                 diff = val - nextmin;
5109                 if (diff > 0) {
5110                     t = uvchr_to_utf8(tmpbuf,nextmin);
5111                     sv_catpvn(transv, (char*)tmpbuf, t - tmpbuf);
5112                     if (diff > 1) {
5113                         U8  range_mark = ILLEGAL_UTF8_BYTE;
5114                         t = uvchr_to_utf8(tmpbuf, val - 1);
5115                         sv_catpvn(transv, (char *)&range_mark, 1);
5116                         sv_catpvn(transv, (char*)tmpbuf, t - tmpbuf);
5117                     }
5118                 }
5119                 val = cp[2*j+1];
5120                 if (val >= nextmin)
5121                     nextmin = val + 1;
5122             }
5123             t = uvchr_to_utf8(tmpbuf,nextmin);
5124             sv_catpvn(transv, (char*)tmpbuf, t - tmpbuf);
5125             {
5126                 U8 range_mark = ILLEGAL_UTF8_BYTE;
5127                 sv_catpvn(transv, (char *)&range_mark, 1);
5128             }
5129             t = uvchr_to_utf8(tmpbuf, 0x7fffffff);
5130             sv_catpvn(transv, (char*)tmpbuf, t - tmpbuf);
5131             t = (const U8*)SvPVX_const(transv);
5132             tlen = SvCUR(transv);
5133             tend = t + tlen;
5134             Safefree(cp);
5135         }
5136         else if (!rlen && !del) {
5137             r = t; rlen = tlen; rend = tend;
5138         }
5139         if (!squash) {
5140                 if ((!rlen && !del) || t == r ||
5141                     (tlen == rlen && memEQ((char *)t, (char *)r, tlen)))
5142                 {
5143                     o->op_private |= OPpTRANS_IDENTICAL;
5144                 }
5145         }
5146
5147         while (t < tend || tfirst <= tlast) {
5148             /* see if we need more "t" chars */
5149             if (tfirst > tlast) {
5150                 tfirst = (I32)utf8n_to_uvchr(t, tend - t, &ulen, flags);
5151                 t += ulen;
5152                 if (t < tend && *t == ILLEGAL_UTF8_BYTE) {      /* illegal utf8 val indicates range */
5153                     t++;
5154                     tlast = (I32)utf8n_to_uvchr(t, tend - t, &ulen, flags);
5155                     t += ulen;
5156                 }
5157                 else
5158                     tlast = tfirst;
5159             }
5160
5161             /* now see if we need more "r" chars */
5162             if (rfirst > rlast) {
5163                 if (r < rend) {
5164                     rfirst = (I32)utf8n_to_uvchr(r, rend - r, &ulen, flags);
5165                     r += ulen;
5166                     if (r < rend && *r == ILLEGAL_UTF8_BYTE) {  /* illegal utf8 val indicates range */
5167                         r++;
5168                         rlast = (I32)utf8n_to_uvchr(r, rend - r, &ulen, flags);
5169                         r += ulen;
5170                     }
5171                     else
5172                         rlast = rfirst;
5173                 }
5174                 else {
5175                     if (!havefinal++)
5176                         final = rlast;
5177                     rfirst = rlast = 0xffffffff;
5178                 }
5179             }
5180
5181             /* now see which range will peter out first, if either. */
5182             tdiff = tlast - tfirst;
5183             rdiff = rlast - rfirst;
5184             tcount += tdiff + 1;
5185             rcount += rdiff + 1;
5186
5187             if (tdiff <= rdiff)
5188                 diff = tdiff;
5189             else
5190                 diff = rdiff;
5191
5192             if (rfirst == 0xffffffff) {
5193                 diff = tdiff;   /* oops, pretend rdiff is infinite */
5194                 if (diff > 0)
5195                     Perl_sv_catpvf(aTHX_ listsv, "%04lx\t%04lx\tXXXX\n",
5196                                    (long)tfirst, (long)tlast);
5197                 else
5198                     Perl_sv_catpvf(aTHX_ listsv, "%04lx\t\tXXXX\n", (long)tfirst);
5199             }
5200             else {
5201                 if (diff > 0)
5202                     Perl_sv_catpvf(aTHX_ listsv, "%04lx\t%04lx\t%04lx\n",
5203                                    (long)tfirst, (long)(tfirst + diff),
5204                                    (long)rfirst);
5205                 else
5206                     Perl_sv_catpvf(aTHX_ listsv, "%04lx\t\t%04lx\n",
5207                                    (long)tfirst, (long)rfirst);
5208
5209                 if (rfirst + diff > max)
5210                     max = rfirst + diff;
5211                 if (!grows)
5212                     grows = (tfirst < rfirst &&
5213                              UVCHR_SKIP(tfirst) < UVCHR_SKIP(rfirst + diff));
5214                 rfirst += diff + 1;
5215             }
5216             tfirst += diff + 1;
5217         }
5218
5219         none = ++max;
5220         if (del)
5221             del = ++max;
5222
5223         if (max > 0xffff)
5224             bits = 32;
5225         else if (max > 0xff)
5226             bits = 16;
5227         else
5228             bits = 8;
5229
5230         swash = MUTABLE_SV(swash_init("utf8", "", listsv, bits, none));
5231 #ifdef USE_ITHREADS
5232         cPADOPo->op_padix = pad_alloc(OP_TRANS, SVf_READONLY);
5233         SvREFCNT_dec(PAD_SVl(cPADOPo->op_padix));
5234         PAD_SETSV(cPADOPo->op_padix, swash);
5235         SvPADTMP_on(swash);
5236         SvREADONLY_on(swash);
5237 #else
5238         cSVOPo->op_sv = swash;
5239 #endif
5240         SvREFCNT_dec(listsv);
5241         SvREFCNT_dec(transv);
5242
5243         if (!del && havefinal && rlen)
5244             (void)hv_store(MUTABLE_HV(SvRV(swash)), "FINAL", 5,
5245                            newSVuv((UV)final), 0);
5246
5247         Safefree(tsave);
5248         Safefree(rsave);
5249
5250         tlen = tcount;
5251         rlen = rcount;
5252         if (r < rend)
5253             rlen++;
5254         else if (rlast == 0xffffffff)
5255             rlen = 0;
5256
5257         goto warnins;
5258     }
5259
5260     tbl = (short*)PerlMemShared_calloc(
5261         (o->op_private & OPpTRANS_COMPLEMENT) &&
5262             !(o->op_private & OPpTRANS_DELETE) ? 258 : 256,
5263         sizeof(short));
5264     cPVOPo->op_pv = (char*)tbl;
5265     if (complement) {
5266         for (i = 0; i < (I32)tlen; i++)
5267             tbl[t[i]] = -1;
5268         for (i = 0, j = 0; i < 256; i++) {
5269             if (!tbl[i]) {
5270                 if (j >= (I32)rlen) {
5271                     if (del)
5272                         tbl[i] = -2;
5273                     else if (rlen)
5274                         tbl[i] = r[j-1];
5275                     else
5276                         tbl[i] = (short)i;
5277                 }
5278                 else {
5279                     if (i < 128 && r[j] >= 128)
5280                         grows = 1;
5281                     tbl[i] = r[j++];
5282                 }
5283             }
5284         }
5285         if (!del) {
5286             if (!rlen) {
5287                 j = rlen;
5288                 if (!squash)
5289                     o->op_private |= OPpTRANS_IDENTICAL;
5290             }
5291             else if (j >= (I32)rlen)
5292                 j = rlen - 1;
5293             else {
5294                 tbl = 
5295                     (short *)
5296                     PerlMemShared_realloc(tbl,
5297                                           (0x101+rlen-j) * sizeof(short));
5298                 cPVOPo->op_pv = (char*)tbl;
5299             }
5300             tbl[0x100] = (short)(rlen - j);
5301             for (i=0; i < (I32)rlen - j; i++)
5302                 tbl[0x101+i] = r[j+i];
5303         }
5304     }
5305     else {
5306         if (!rlen && !del) {
5307             r = t; rlen = tlen;
5308             if (!squash)
5309                 o->op_private |= OPpTRANS_IDENTICAL;
5310         }
5311         else if (!squash && rlen == tlen && memEQ((char*)t, (char*)r, tlen)) {
5312             o->op_private |= OPpTRANS_IDENTICAL;
5313         }
5314         for (i = 0; i < 256; i++)
5315             tbl[i] = -1;
5316         for (i = 0, j = 0; i < (I32)tlen; i++,j++) {
5317             if (j >= (I32)rlen) {
5318                 if (del) {
5319                     if (tbl[t[i]] == -1)
5320                         tbl[t[i]] = -2;
5321                     continue;
5322                 }
5323                 --j;
5324             }
5325             if (tbl[t[i]] == -1) {
5326                 if (t[i] < 128 && r[j] >= 128)
5327                     grows = 1;
5328                 tbl[t[i]] = r[j];
5329             }
5330         }
5331     }
5332
5333   warnins:
5334     if(del && rlen == tlen) {
5335         Perl_ck_warner(aTHX_ packWARN(WARN_MISC), "Useless use of /d modifier in transliteration operator"); 
5336     } else if(rlen > tlen && !complement) {
5337         Perl_ck_warner(aTHX_ packWARN(WARN_MISC), "Replacement list is longer than search list");
5338     }
5339
5340     if (grows)
5341         o->op_private |= OPpTRANS_GROWS;
5342     op_free(expr);
5343     op_free(repl);
5344
5345     return o;
5346 }
5347
5348 /*
5349 =for apidoc Am|OP *|newPMOP|I32 type|I32 flags
5350
5351 Constructs, checks, and returns an op of any pattern matching type.
5352 C<type> is the opcode.  C<flags> gives the eight bits of C<op_flags>
5353 and, shifted up eight bits, the eight bits of C<op_private>.
5354
5355 =cut
5356 */
5357
5358 OP *
5359 Perl_newPMOP(pTHX_ I32 type, I32 flags)
5360 {
5361     dVAR;
5362     PMOP *pmop;
5363
5364     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_PMOP
5365         || type == OP_CUSTOM);
5366
5367     NewOp(1101, pmop, 1, PMOP);
5368     OpTYPE_set(pmop, type);
5369     pmop->op_flags = (U8)flags;
5370     pmop->op_private = (U8)(0 | (flags >> 8));
5371     if (PL_opargs[type] & OA_RETSCALAR)
5372         scalar((OP *)pmop);
5373
5374     if (PL_hints & HINT_RE_TAINT)
5375         pmop->op_pmflags |= PMf_RETAINT;
5376 #ifdef USE_LOCALE_CTYPE
5377     if (IN_LC_COMPILETIME(LC_CTYPE)) {
5378         set_regex_charset(&(pmop->op_pmflags), REGEX_LOCALE_CHARSET);
5379     }
5380     else
5381 #endif
5382          if (IN_UNI_8_BIT) {
5383         set_regex_charset(&(pmop->op_pmflags), REGEX_UNICODE_CHARSET);
5384     }
5385     if (PL_hints & HINT_RE_FLAGS) {
5386         SV *reflags = Perl_refcounted_he_fetch_pvn(aTHX_
5387          PL_compiling.cop_hints_hash, STR_WITH_LEN("reflags"), 0, 0
5388         );
5389         if (reflags && SvOK(reflags)) pmop->op_pmflags |= SvIV(reflags);
5390         reflags = Perl_refcounted_he_fetch_pvn(aTHX_
5391          PL_compiling.cop_hints_hash, STR_WITH_LEN("reflags_charset"), 0, 0
5392         );
5393         if (reflags && SvOK(reflags)) {
5394             set_regex_charset(&(pmop->op_pmflags), (regex_charset)SvIV(reflags));
5395         }
5396     }
5397
5398
5399 #ifdef USE_ITHREADS
5400     assert(SvPOK(PL_regex_pad[0]));
5401     if (SvCUR(PL_regex_pad[0])) {
5402         /* Pop off the "packed" IV from the end.  */
5403         SV *const repointer_list = PL_regex_pad[0];
5404         const char *p = SvEND(repointer_list) - sizeof(IV);
5405         const IV offset = *((IV*)p);
5406
5407         assert(SvCUR(repointer_list) % sizeof(IV) == 0);
5408
5409         SvEND_set(repointer_list, p);
5410
5411         pmop->op_pmoffset = offset;
5412         /* This slot should be free, so assert this:  */
5413         assert(PL_regex_pad[offset] == &PL_sv_undef);
5414     } else {
5415         SV * const repointer = &PL_sv_undef;
5416         av_push(PL_regex_padav, repointer);
5417         pmop->op_pmoffset = av_tindex(PL_regex_padav);
5418         PL_regex_pad = AvARRAY(PL_regex_padav);
5419     }
5420 #endif
5421
5422     return CHECKOP(type, pmop);
5423 }
5424
5425 static void
5426 S_set_haseval(pTHX)
5427 {
5428     PADOFFSET i = 1;
5429     PL_cv_has_eval = 1;
5430     /* Any pad names in scope are potentially lvalues.  */
5431     for (; i < PadnamelistMAXNAMED(PL_comppad_name); i++) {
5432         PADNAME *pn = PAD_COMPNAME_SV(i);
5433         if (!pn || !PadnameLEN(pn))
5434             continue;
5435         if (PadnameOUTER(pn) || PadnameIN_SCOPE(pn, PL_cop_seqmax))
5436             S_mark_padname_lvalue(aTHX_ pn);
5437     }
5438 }
5439
5440 /* Given some sort of match op o, and an expression expr containing a
5441  * pattern, either compile expr into a regex and attach it to o (if it's
5442  * constant), or convert expr into a runtime regcomp op sequence (if it's
5443  * not)
5444  *
5445  * isreg indicates that the pattern is part of a regex construct, eg
5446  * $x =~ /pattern/ or split /pattern/, as opposed to $x =~ $pattern or
5447  * split "pattern", which aren't. In the former case, expr will be a list
5448  * if the pattern contains more than one term (eg /a$b/).
5449  *
5450  * When the pattern has been compiled within a new anon CV (for
5451  * qr/(?{...})/ ), then floor indicates the savestack level just before
5452  * the new sub was created
5453  */
5454
5455 OP *
5456 Perl_pmruntime(pTHX_ OP *o, OP *expr, OP *repl, bool isreg, I32 floor)
5457 {
5458     PMOP *pm;
5459     LOGOP *rcop;
5460     I32 repl_has_vars = 0;
5461     bool is_trans = (o->op_type == OP_TRANS || o->op_type == OP_TRANSR);
5462     bool is_compiletime;
5463     bool has_code;
5464
5465     PERL_ARGS_ASSERT_PMRUNTIME;
5466
5467     if (is_trans) {
5468         return pmtrans(o, expr, repl);
5469     }
5470
5471     /* find whether we have any runtime or code elements;
5472      * at the same time, temporarily set the op_next of each DO block;
5473      * then when we LINKLIST, this will cause the DO blocks to be excluded
5474      * from the op_next chain (and from having LINKLIST recursively
5475      * applied to them). We fix up the DOs specially later */
5476
5477     is_compiletime = 1;
5478     has_code = 0;
5479     if (expr->op_type == OP_LIST) {
5480         OP *o;
5481         for (o = cLISTOPx(expr)->op_first; o; o = OpSIBLING(o)) {
5482             if (o->op_type == OP_NULL && (o->op_flags & OPf_SPECIAL)) {
5483                 has_code = 1;
5484                 assert(!o->op_next);
5485                 if (UNLIKELY(!OpHAS_SIBLING(o))) {
5486                     assert(PL_parser && PL_parser->error_count);
5487                     /* This can happen with qr/ (?{(^{})/.  Just fake up
5488                        the op we were expecting to see, to avoid crashing
5489                        elsewhere.  */
5490                     op_sibling_splice(expr, o, 0,
5491                                       newSVOP(OP_CONST, 0, &PL_sv_no));
5492                 }
5493                 o->op_next = OpSIBLING(o);
5494             }
5495             else if (o->op_type != OP_CONST && o->op_type != OP_PUSHMARK)
5496                 is_compiletime = 0;
5497         }
5498     }
5499     else if (expr->op_type != OP_CONST)
5500         is_compiletime = 0;
5501
5502     LINKLIST(expr);
5503
5504     /* fix up DO blocks; treat each one as a separate little sub;
5505      * also, mark any arrays as LIST/REF */
5506
5507     if (expr->op_type == OP_LIST) {
5508         OP *o;
5509         for (o = cLISTOPx(expr)->op_first; o; o = OpSIBLING(o)) {
5510
5511             if (o->op_type == OP_PADAV || o->op_type == OP_RV2AV) {
5512                 assert( !(o->op_flags  & OPf_WANT));
5513                 /* push the array rather than its contents. The regex
5514                  * engine will retrieve and join the elements later */
5515                 o->op_flags |= (OPf_WANT_LIST | OPf_REF);
5516                 continue;
5517             }
5518
5519             if (!(o->op_type == OP_NULL && (o->op_flags & OPf_SPECIAL)))
5520                 continue;
5521             o->op_next = NULL; /* undo temporary hack from above */
5522             scalar(o);
5523             LINKLIST(o);
5524             if (cLISTOPo->op_first->op_type == OP_LEAVE) {
5525                 LISTOP *leaveop = cLISTOPx(cLISTOPo->op_first);
5526                 /* skip ENTER */
5527                 assert(leaveop->op_first->op_type == OP_ENTER);
5528                 assert(OpHAS_SIBLING(leaveop->op_first));
5529                 o->op_next = OpSIBLING(leaveop->op_first);
5530                 /* skip leave */
5531                 assert(leaveop->op_flags & OPf_KIDS);
5532                 assert(leaveop->op_last->op_next == (OP*)leaveop);
5533                 leaveop->op_next = NULL; /* stop on last op */
5534                 op_null((OP*)leaveop);
5535             }
5536             else {
5537                 /* skip SCOPE */
5538                 OP *scope = cLISTOPo->op_first;
5539                 assert(scope->op_type == OP_SCOPE);
5540                 assert(scope->op_flags & OPf_KIDS);
5541                 scope->op_next = NULL; /* stop on last op */
5542                 op_null(scope);
5543             }
5544             /* have to peep the DOs individually as we've removed it from
5545              * the op_next chain */
5546             CALL_PEEP(o);
5547             S_prune_chain_head(&(o->op_next));
5548             if (is_compiletime)
5549                 /* runtime finalizes as part of finalizing whole tree */
5550                 finalize_optree(o);
5551         }
5552     }
5553     else if (expr->op_type == OP_PADAV || expr->op_type == OP_RV2AV) {
5554         assert( !(expr->op_flags  & OPf_WANT));
5555         /* push the array rather than its contents. The regex
5556          * engine will retrieve and join the elements later */
5557         expr->op_flags |= (OPf_WANT_LIST | OPf_REF);
5558     }
5559
5560     PL_hints |= HINT_BLOCK_SCOPE;
5561     pm = (PMOP*)o;
5562     assert(floor==0 || (pm->op_pmflags & PMf_HAS_CV));
5563
5564     if (is_compiletime) {
5565         U32 rx_flags = pm->op_pmflags & RXf_PMf_COMPILETIME;
5566         regexp_engine const *eng = current_re_engine();
5567
5568         if (o->op_flags & OPf_SPECIAL)
5569             rx_flags |= RXf_SPLIT;
5570
5571         if (!has_code || !eng->op_comp) {
5572             /* compile-time simple constant pattern */
5573
5574             if ((pm->op_pmflags & PMf_HAS_CV) && !has_code) {
5575                 /* whoops! we guessed that a qr// had a code block, but we
5576                  * were wrong (e.g. /[(?{}]/ ). Throw away the PL_compcv
5577                  * that isn't required now. Note that we have to be pretty
5578                  * confident that nothing used that CV's pad while the
5579                  * regex was parsed, except maybe op targets for \Q etc.
5580                  * If there were any op targets, though, they should have
5581                  * been stolen by constant folding.
5582                  */
5583 #ifdef DEBUGGING
5584                 SSize_t i = 0;
5585                 assert(PadnamelistMAXNAMED(PL_comppad_name) == 0);
5586                 while (++i <= AvFILLp(PL_comppad)) {
5587                     assert(!PL_curpad[i]);
5588                 }
5589 #endif
5590                 /* But we know that one op is using this CV's slab. */
5591                 cv_forget_slab(PL_compcv);
5592                 LEAVE_SCOPE(floor);
5593                 pm->op_pmflags &= ~PMf_HAS_CV;
5594             }
5595
5596             PM_SETRE(pm,
5597                 eng->op_comp
5598                     ? eng->op_comp(aTHX_ NULL, 0, expr, eng, NULL, NULL,
5599                                         rx_flags, pm->op_pmflags)
5600                     : Perl_re_op_compile(aTHX_ NULL, 0, expr, eng, NULL, NULL,
5601                                         rx_flags, pm->op_pmflags)
5602             );
5603             op_free(expr);
5604         }
5605         else {
5606             /* compile-time pattern that includes literal code blocks */
5607             REGEXP* re = eng->op_comp(aTHX_ NULL, 0, expr, eng, NULL, NULL,
5608                         rx_flags,
5609                         (pm->op_pmflags |
5610                             ((PL_hints & HINT_RE_EVAL) ? PMf_USE_RE_EVAL : 0))
5611                     );
5612             PM_SETRE(pm, re);
5613             if (pm->op_pmflags & PMf_HAS_CV) {
5614                 CV *cv;
5615                 /* this QR op (and the anon sub we embed it in) is never
5616                  * actually executed. It's just a placeholder where we can
5617                  * squirrel away expr in op_code_list without the peephole
5618                  * optimiser etc processing it for a second time */
5619                 OP *qr = newPMOP(OP_QR, 0);
5620                 ((PMOP*)qr)->op_code_list = expr;
5621
5622                 /* handle the implicit sub{} wrapped round the qr/(?{..})/ */
5623                 SvREFCNT_inc_simple_void(PL_compcv);
5624                 cv = newATTRSUB(floor, 0, NULL, NULL, qr);
5625                 ReANY(re)->qr_anoncv = cv;
5626
5627                 /* attach the anon CV to the pad so that
5628                  * pad_fixup_inner_anons() can find it */
5629                 (void)pad_add_anon(cv, o->op_type);
5630                 SvREFCNT_inc_simple_void(cv);
5631             }
5632             else {
5633                 pm->op_code_list = expr;
5634             }
5635         }
5636     }
5637     else {
5638         /* runtime pattern: build chain of regcomp etc ops */
5639         bool reglist;
5640         PADOFFSET cv_targ = 0;
5641
5642         reglist = isreg && expr->op_type == OP_LIST;
5643         if (reglist)
5644             op_null(expr);
5645
5646         if (has_code) {
5647             pm->op_code_list = expr;
5648             /* don't free op_code_list; its ops are embedded elsewhere too */
5649             pm->op_pmflags |= PMf_CODELIST_PRIVATE;
5650         }
5651
5652         if (o->op_flags & OPf_SPECIAL)
5653             pm->op_pmflags |= PMf_SPLIT;
5654
5655         /* the OP_REGCMAYBE is a placeholder in the non-threaded case
5656          * to allow its op_next to be pointed past the regcomp and
5657          * preceding stacking ops;
5658          * OP_REGCRESET is there to reset taint before executing the
5659          * stacking ops */
5660         if (pm->op_pmflags & PMf_KEEP || TAINTING_get)
5661             expr = newUNOP((TAINTING_get ? OP_REGCRESET : OP_REGCMAYBE),0,expr);
5662
5663         if (pm->op_pmflags & PMf_HAS_CV) {
5664             /* we have a runtime qr with literal code. This means
5665              * that the qr// has been wrapped in a new CV, which
5666              * means that runtime consts, vars etc will have been compiled
5667              * against a new pad. So... we need to execute those ops
5668              * within the environment of the new CV. So wrap them in a call
5669              * to a new anon sub. i.e. for
5670              *
5671              *     qr/a$b(?{...})/,
5672              *
5673              * we build an anon sub that looks like
5674              *
5675              *     sub { "a", $b, '(?{...})' }
5676              *
5677              * and call it, passing the returned list to regcomp.
5678              * Or to put it another way, the list of ops that get executed
5679              * are:
5680              *
5681              *     normal              PMf_HAS_CV
5682              *     ------              -------------------
5683              *                         pushmark (for regcomp)
5684              *                         pushmark (for entersub)
5685              *                         anoncode
5686              *                         srefgen
5687              *                         entersub
5688              *     regcreset                  regcreset
5689              *     pushmark                   pushmark
5690              *     const("a")                 const("a")
5691              *     gvsv(b)                    gvsv(b)
5692              *     const("(?{...})")          const("(?{...})")
5693              *                                leavesub
5694              *     regcomp             regcomp
5695              */
5696
5697             SvREFCNT_inc_simple_void(PL_compcv);
5698             CvLVALUE_on(PL_compcv);
5699             /* these lines are just an unrolled newANONATTRSUB */
5700             expr = newSVOP(OP_ANONCODE, 0,
5701                     MUTABLE_SV(newATTRSUB(floor, 0, NULL, NULL, expr)));
5702             cv_targ = expr->op_targ;
5703             expr = newUNOP(OP_REFGEN, 0, expr);
5704
5705             expr = list(force_list(newUNOP(OP_ENTERSUB, 0, scalar(expr)), 1));
5706         }
5707
5708         rcop = S_alloc_LOGOP(aTHX_ OP_REGCOMP, scalar(expr), o);
5709         rcop->op_flags |=  ((PL_hints & HINT_RE_EVAL) ? OPf_SPECIAL : 0)
5710                            | (reglist ? OPf_STACKED : 0);
5711         rcop->op_targ = cv_targ;
5712
5713         /* /$x/ may cause an eval, since $x might be qr/(?{..})/  */
5714         if (PL_hints & HINT_RE_EVAL)
5715             S_set_haseval(aTHX);
5716
5717         /* establish postfix order */
5718         if (expr->op_type == OP_REGCRESET || expr->op_type == OP_REGCMAYBE) {
5719             LINKLIST(expr);
5720             rcop->op_next = expr;
5721             ((UNOP*)expr)->op_first->op_next = (OP*)rcop;
5722         }
5723         else {
5724             rcop->op_next = LINKLIST(expr);
5725             expr->op_next = (OP*)rcop;
5726         }
5727
5728         op_prepend_elem(o->op_type, scalar((OP*)rcop), o);
5729     }
5730
5731     if (repl) {
5732         OP *curop = repl;
5733         bool konst;
5734         /* If we are looking at s//.../e with a single statement, get past
5735            the implicit do{}. */
5736         if (curop->op_type == OP_NULL && curop->op_flags & OPf_KIDS
5737              && cUNOPx(curop)->op_first->op_type == OP_SCOPE
5738              && cUNOPx(curop)->op_first->op_flags & OPf_KIDS)
5739          {
5740             OP *sib;
5741             OP *kid = cUNOPx(cUNOPx(curop)->op_first)->op_first;
5742             if (kid->op_type == OP_NULL && (sib = OpSIBLING(kid))
5743              && !OpHAS_SIBLING(sib))
5744                 curop = sib;
5745         }
5746         if (curop->op_type == OP_CONST)
5747             konst = TRUE;
5748         else if (( (curop->op_type == OP_RV2SV ||
5749                     curop->op_type == OP_RV2AV ||
5750                     curop->op_type == OP_RV2HV ||
5751                     curop->op_type == OP_RV2GV)
5752                    && cUNOPx(curop)->op_first
5753                    && cUNOPx(curop)->op_first->op_type == OP_GV )
5754                 || curop->op_type == OP_PADSV
5755                 || curop->op_type == OP_PADAV
5756                 || curop->op_type == OP_PADHV
5757                 || curop->op_type == OP_PADANY) {
5758             repl_has_vars = 1;
5759             konst = TRUE;
5760         }
5761         else konst = FALSE;
5762         if (konst
5763             && !(repl_has_vars
5764                  && (!PM_GETRE(pm)
5765                      || !RX_PRELEN(PM_GETRE(pm))
5766                      || RX_EXTFLAGS(PM_GETRE(pm)) & RXf_EVAL_SEEN)))
5767         {
5768             pm->op_pmflags |= PMf_CONST;        /* const for long enough */
5769             op_prepend_elem(o->op_type, scalar(repl), o);
5770         }
5771         else {
5772             rcop = S_alloc_LOGOP(aTHX_ OP_SUBSTCONT, scalar(repl), o);
5773             rcop->op_private = 1;
5774
5775             /* establish postfix order */
5776             rcop->op_next = LINKLIST(repl);
5777             repl->op_next = (OP*)rcop;
5778
5779             pm->op_pmreplrootu.op_pmreplroot = scalar((OP*)rcop);
5780             assert(!(pm->op_pmflags & PMf_ONCE));
5781             pm->op_pmstashstartu.op_pmreplstart = LINKLIST(rcop);
5782             rcop->op_next = 0;
5783         }
5784     }
5785
5786     return (OP*)pm;
5787 }
5788
5789 /*
5790 =for apidoc Am|OP *|newSVOP|I32 type|I32 flags|SV *sv
5791
5792 Constructs, checks, and returns an op of any type that involves an
5793 embedded SV.  C<type> is the opcode.  C<flags> gives the eight bits
5794 of C<op_flags>.  C<sv> gives the SV to embed in the op; this function
5795 takes ownership of one reference to it.
5796
5797 =cut
5798 */
5799
5800 OP *
5801 Perl_newSVOP(pTHX_ I32 type, I32 flags, SV *sv)
5802 {
5803     dVAR;
5804     SVOP *svop;
5805
5806     PERL_ARGS_ASSERT_NEWSVOP;
5807
5808     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_SVOP
5809         || (PL_opargs[type] & OA_CLASS_MASK) == OA_PVOP_OR_SVOP
5810         || (PL_opargs[type] & OA_CLASS_MASK) == OA_FILESTATOP
5811         || type == OP_CUSTOM);
5812
5813     NewOp(1101, svop, 1, SVOP);
5814     OpTYPE_set(svop, type);
5815     svop->op_sv = sv;
5816     svop->op_next = (OP*)svop;
5817     svop->op_flags = (U8)flags;
5818     svop->op_private = (U8)(0 | (flags >> 8));
5819     if (PL_opargs[type] & OA_RETSCALAR)
5820         scalar((OP*)svop);
5821     if (PL_opargs[type] & OA_TARGET)
5822         svop->op_targ = pad_alloc(type, SVs_PADTMP);
5823     return CHECKOP(type, svop);
5824 }
5825
5826 /*
5827 =for apidoc Am|OP *|newDEFSVOP|
5828
5829 Constructs and returns an op to access C<$_>.
5830
5831 =cut
5832 */
5833
5834 OP *
5835 Perl_newDEFSVOP(pTHX)
5836 {
5837         return newSVREF(newGVOP(OP_GV, 0, PL_defgv));
5838 }
5839
5840 #ifdef USE_ITHREADS
5841
5842 /*
5843 =for apidoc Am|OP *|newPADOP|I32 type|I32 flags|SV *sv
5844
5845 Constructs, checks, and returns an op of any type that involves a
5846 reference to a pad element.  C<type> is the opcode.  C<flags> gives the
5847 eight bits of C<op_flags>.  A pad slot is automatically allocated, and
5848 is populated with C<sv>; this function takes ownership of one reference
5849 to it.
5850
5851 This function only exists if Perl has been compiled to use ithreads.
5852
5853 =cut
5854 */
5855
5856 OP *
5857 Perl_newPADOP(pTHX_ I32 type, I32 flags, SV *sv)
5858 {
5859     dVAR;
5860     PADOP *padop;
5861
5862     PERL_ARGS_ASSERT_NEWPADOP;
5863
5864     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_SVOP
5865         || (PL_opargs[type] & OA_CLASS_MASK) == OA_PVOP_OR_SVOP
5866         || (PL_opargs[type] & OA_CLASS_MASK) == OA_FILESTATOP
5867         || type == OP_CUSTOM);
5868
5869     NewOp(1101, padop, 1, PADOP);
5870     OpTYPE_set(padop, type);
5871     padop->op_padix =
5872         pad_alloc(type, isGV(sv) ? SVf_READONLY : SVs_PADTMP);
5873     SvREFCNT_dec(PAD_SVl(padop->op_padix));
5874     PAD_SETSV(padop->op_padix, sv);
5875     assert(sv);
5876     padop->op_next = (OP*)padop;
5877     padop->op_flags = (U8)flags;
5878     if (PL_opargs[type] & OA_RETSCALAR)
5879         scalar((OP*)padop);
5880     if (PL_opargs[type] & OA_TARGET)
5881         padop->op_targ = pad_alloc(type, SVs_PADTMP);
5882     return CHECKOP(type, padop);
5883 }
5884
5885 #endif /* USE_ITHREADS */
5886
5887 /*
5888 =for apidoc Am|OP *|newGVOP|I32 type|I32 flags|GV *gv
5889
5890 Constructs, checks, and returns an op of any type that involves an
5891 embedded reference to a GV.  C<type> is the opcode.  C<flags> gives the
5892 eight bits of C<op_flags>.  C<gv> identifies the GV that the op should
5893 reference; calling this function does not transfer ownership of any
5894 reference to it.
5895
5896 =cut
5897 */
5898
5899 OP *
5900 Perl_newGVOP(pTHX_ I32 type, I32 flags, GV *gv)
5901 {
5902     PERL_ARGS_ASSERT_NEWGVOP;
5903
5904 #ifdef USE_ITHREADS
5905     return newPADOP(type, flags, SvREFCNT_inc_simple_NN(gv));
5906 #else
5907     return newSVOP(type, flags, SvREFCNT_inc_simple_NN(gv));
5908 #endif
5909 }
5910
5911 /*
5912 =for apidoc Am|OP *|newPVOP|I32 type|I32 flags|char *pv
5913
5914 Constructs, checks, and returns an op of any type that involves an
5915 embedded C-level pointer (PV).  C<type> is the opcode.  C<flags> gives
5916 the eight bits of C<op_flags>.  C<pv> supplies the C-level pointer, which
5917 must have been allocated using C<PerlMemShared_malloc>; the memory will
5918 be freed when the op is destroyed.
5919
5920 =cut
5921 */
5922
5923 OP *
5924 Perl_newPVOP(pTHX_ I32 type, I32 flags, char *pv)
5925 {
5926     dVAR;
5927     const bool utf8 = cBOOL(flags & SVf_UTF8);
5928     PVOP *pvop;
5929
5930     flags &= ~SVf_UTF8;
5931
5932     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_PVOP_OR_SVOP
5933         || type == OP_RUNCV || type == OP_CUSTOM
5934         || (PL_opargs[type] & OA_CLASS_MASK) == OA_LOOPEXOP);
5935
5936     NewOp(1101, pvop, 1, PVOP);
5937     OpTYPE_set(pvop, type);
5938     pvop->op_pv = pv;
5939     pvop->op_next = (OP*)pvop;
5940     pvop->op_flags = (U8)flags;
5941     pvop->op_private = utf8 ? OPpPV_IS_UTF8 : 0;
5942     if (PL_opargs[type] & OA_RETSCALAR)
5943         scalar((OP*)pvop);
5944     if (PL_opargs[type] & OA_TARGET)
5945         pvop->op_targ = pad_alloc(type, SVs_PADTMP);
5946     return CHECKOP(type, pvop);
5947 }
5948
5949 void
5950 Perl_package(pTHX_ OP *o)
5951 {
5952     SV *const sv = cSVOPo->op_sv;
5953
5954     PERL_ARGS_ASSERT_PACKAGE;
5955
5956     SAVEGENERICSV(PL_curstash);
5957     save_item(PL_curstname);
5958
5959     PL_curstash = (HV *)SvREFCNT_inc(gv_stashsv(sv, GV_ADD));
5960
5961     sv_setsv(PL_curstname, sv);
5962
5963     PL_hints |= HINT_BLOCK_SCOPE;
5964     PL_parser->copline = NOLINE;
5965
5966     op_free(o);
5967 }
5968
5969 void
5970 Perl_package_version( pTHX_ OP *v )
5971 {
5972     U32 savehints = PL_hints;
5973     PERL_ARGS_ASSERT_PACKAGE_VERSION;
5974     PL_hints &= ~HINT_STRICT_VARS;
5975     sv_setsv( GvSV(gv_fetchpvs("VERSION", GV_ADDMULTI, SVt_PV)), cSVOPx(v)->op_sv );
5976     PL_hints = savehints;
5977     op_free(v);
5978 }
5979
5980 void
5981 Perl_utilize(pTHX_ int aver, I32 floor, OP *version, OP *idop, OP *arg)
5982 {
5983     OP *pack;
5984     OP *imop;
5985     OP *veop;
5986     SV *use_version = NULL;
5987
5988     PERL_ARGS_ASSERT_UTILIZE;
5989
5990     if (idop->op_type != OP_CONST)
5991         Perl_croak(aTHX_ "Module name must be constant");
5992
5993     veop = NULL;
5994
5995     if (version) {
5996         SV * const vesv = ((SVOP*)version)->op_sv;
5997
5998         if (!arg && !SvNIOKp(vesv)) {
5999             arg = version;
6000         }
6001         else {
6002             OP *pack;
6003             SV *meth;
6004
6005             if (version->op_type != OP_CONST || !SvNIOKp(vesv))
6006                 Perl_croak(aTHX_ "Version number must be a constant number");
6007
6008             /* Make copy of idop so we don't free it twice */
6009             pack = newSVOP(OP_CONST, 0, newSVsv(((SVOP*)idop)->op_sv));
6010
6011             /* Fake up a method call to VERSION */
6012             meth = newSVpvs_share("VERSION");
6013             veop = op_convert_list(OP_ENTERSUB, OPf_STACKED|OPf_SPECIAL,
6014                             op_append_elem(OP_LIST,
6015                                         op_prepend_elem(OP_LIST, pack, version),
6016                                         newMETHOP_named(OP_METHOD_NAMED, 0, meth)));
6017         }
6018     }
6019
6020     /* Fake up an import/unimport */
6021     if (arg && arg->op_type == OP_STUB) {
6022         imop = arg;             /* no import on explicit () */
6023     }
6024     else if (SvNIOKp(((SVOP*)idop)->op_sv)) {
6025         imop = NULL;            /* use 5.0; */
6026         if (aver)
6027             use_version = ((SVOP*)idop)->op_sv;
6028         else
6029             idop->op_private |= OPpCONST_NOVER;
6030     }
6031     else {
6032         SV *meth;
6033
6034         /* Make copy of idop so we don't free it twice */
6035         pack = newSVOP(OP_CONST, 0, newSVsv(((SVOP*)idop)->op_sv));
6036
6037         /* Fake up a method call to import/unimport */
6038         meth = aver
6039             ? newSVpvs_share("import") : newSVpvs_share("unimport");
6040         imop = op_convert_list(OP_ENTERSUB, OPf_STACKED|OPf_SPECIAL,
6041                        op_append_elem(OP_LIST,
6042                                    op_prepend_elem(OP_LIST, pack, arg),
6043                                    newMETHOP_named(OP_METHOD_NAMED, 0, meth)
6044                        ));
6045     }
6046
6047     /* Fake up the BEGIN {}, which does its thing immediately. */
6048     newATTRSUB(floor,
6049         newSVOP(OP_CONST, 0, newSVpvs_share("BEGIN")),
6050         NULL,
6051         NULL,
6052         op_append_elem(OP_LINESEQ,
6053             op_append_elem(OP_LINESEQ,
6054                 newSTATEOP(0, NULL, newUNOP(OP_REQUIRE, 0, idop)),
6055                 newSTATEOP(0, NULL, veop)),
6056             newSTATEOP(0, NULL, imop) ));
6057
6058     if (use_version) {
6059         /* Enable the
6060          * feature bundle that corresponds to the required version. */
6061         use_version = sv_2mortal(new_version(use_version));
6062         S_enable_feature_bundle(aTHX_ use_version);
6063
6064         /* If a version >= 5.11.0 is requested, strictures are on by default! */
6065         if (vcmp(use_version,
6066                  sv_2mortal(upg_version(newSVnv(5.011000), FALSE))) >= 0) {
6067             if (!(PL_hints & HINT_EXPLICIT_STRICT_REFS))
6068                 PL_hints |= HINT_STRICT_REFS;
6069             if (!(PL_hints & HINT_EXPLICIT_STRICT_SUBS))
6070                 PL_hints |= HINT_STRICT_SUBS;
6071             if (!(PL_hints & HINT_EXPLICIT_STRICT_VARS))
6072                 PL_hints |= HINT_STRICT_VARS;
6073         }
6074         /* otherwise they are off */
6075         else {
6076             if (!(PL_hints & HINT_EXPLICIT_STRICT_REFS))
6077                 PL_hints &= ~HINT_STRICT_REFS;
6078             if (!(PL_hints & HINT_EXPLICIT_STRICT_SUBS))
6079                 PL_hints &= ~HINT_STRICT_SUBS;
6080             if (!(PL_hints & HINT_EXPLICIT_STRICT_VARS))
6081                 PL_hints &= ~HINT_STRICT_VARS;
6082         }
6083     }
6084
6085     /* The "did you use incorrect case?" warning used to be here.
6086      * The problem is that on case-insensitive filesystems one
6087      * might get false positives for "use" (and "require"):
6088      * "use Strict" or "require CARP" will work.  This causes
6089      * portability problems for the script: in case-strict
6090      * filesystems the script will stop working.
6091      *
6092      * The "incorrect case" warning checked whether "use Foo"
6093      * imported "Foo" to your namespace, but that is wrong, too:
6094      * there is no requirement nor promise in the language that
6095      * a Foo.pm should or would contain anything in package "Foo".
6096      *
6097      * There is very little Configure-wise that can be done, either:
6098      * the case-sensitivity of the build filesystem of Perl does not
6099      * help in guessing the case-sensitivity of the runtime environment.
6100      */
6101
6102     PL_hints |= HINT_BLOCK_SCOPE;
6103     PL_parser->copline = NOLINE;
6104     COP_SEQMAX_INC; /* Purely for B::*'s benefit */
6105 }
6106
6107 /*
6108 =head1 Embedding Functions
6109
6110 =for apidoc load_module
6111
6112 Loads the module whose name is pointed to by the string part of name.
6113 Note that the actual module name, not its filename, should be given.
6114 Eg, "Foo::Bar" instead of "Foo/Bar.pm".  flags can be any of
6115 C<PERL_LOADMOD_DENY>, C<PERL_LOADMOD_NOIMPORT>, or C<PERL_LOADMOD_IMPORT_OPS>
6116 (or 0 for no flags).  ver, if specified
6117 and not NULL, provides version semantics
6118 similar to C<use Foo::Bar VERSION>.  The optional trailing SV*
6119 arguments can be used to specify arguments to the module's C<import()>
6120 method, similar to C<use Foo::Bar VERSION LIST>.  They must be
6121 terminated with a final C<NULL> pointer.  Note that this list can only
6122 be omitted when the C<PERL_LOADMOD_NOIMPORT> flag has been used.
6123 Otherwise at least a single C<NULL> pointer to designate the default
6124 import list is required.
6125
6126 The reference count for each specified C<SV*> parameter is decremented.
6127
6128 =cut */
6129
6130 void
6131 Perl_load_module(pTHX_ U32 flags, SV *name, SV *ver, ...)
6132 {
6133     va_list args;
6134
6135     PERL_ARGS_ASSERT_LOAD_MODULE;
6136
6137     va_start(args, ver);
6138     vload_module(flags, name, ver, &args);
6139     va_end(args);
6140 }
6141
6142 #ifdef PERL_IMPLICIT_CONTEXT
6143 void
6144 Perl_load_module_nocontext(U32 flags, SV *name, SV *ver, ...)
6145 {
6146     dTHX;
6147     va_list args;
6148     PERL_ARGS_ASSERT_LOAD_MODULE_NOCONTEXT;
6149     va_start(args, ver);
6150     vload_module(flags, name, ver, &args);
6151     va_end(args);
6152 }
6153 #endif
6154
6155 void
6156 Perl_vload_module(pTHX_ U32 flags, SV *name, SV *ver, va_list *args)
6157 {
6158     OP *veop, *imop;
6159     OP * const modname = newSVOP(OP_CONST, 0, name);
6160
6161     PERL_ARGS_ASSERT_VLOAD_MODULE;
6162
6163     modname->op_private |= OPpCONST_BARE;
6164     if (ver) {
6165         veop = newSVOP(OP_CONST, 0, ver);
6166     }
6167     else
6168         veop = NULL;
6169     if (flags & PERL_LOADMOD_NOIMPORT) {
6170         imop = sawparens(newNULLLIST());
6171     }
6172     else if (flags & PERL_LOADMOD_IMPORT_OPS) {
6173         imop = va_arg(*args, OP*);
6174     }
6175     else {
6176         SV *sv;
6177         imop = NULL;
6178         sv = va_arg(*args, SV*);
6179         while (sv) {
6180             imop = op_append_elem(OP_LIST, imop, newSVOP(OP_CONST, 0, sv));
6181             sv = va_arg(*args, SV*);
6182         }
6183     }
6184
6185     /* utilize() fakes up a BEGIN { require ..; import ... }, so make sure
6186      * that it has a PL_parser to play with while doing that, and also
6187      * that it doesn't mess with any existing parser, by creating a tmp
6188      * new parser with lex_start(). This won't actually be used for much,
6189      * since pp_require() will create another parser for the real work.
6190      * The ENTER/LEAVE pair protect callers from any side effects of use.  */
6191
6192     ENTER;
6193     SAVEVPTR(PL_curcop);
6194     lex_start(NULL, NULL, LEX_START_SAME_FILTER);
6195     utilize(!(flags & PERL_LOADMOD_DENY), start_subparse(FALSE, 0),
6196             veop, modname, imop);
6197     LEAVE;
6198 }
6199
6200 PERL_STATIC_INLINE OP *
6201 S_new_entersubop(pTHX_ GV *gv, OP *arg)
6202 {
6203     return newUNOP(OP_ENTERSUB, OPf_STACKED,
6204                    newLISTOP(OP_LIST, 0, arg,
6205                              newUNOP(OP_RV2CV, 0,
6206                                      newGVOP(OP_GV, 0, gv))));
6207 }
6208
6209 OP *
6210 Perl_dofile(pTHX_ OP *term, I32 force_builtin)
6211 {
6212     OP *doop;
6213     GV *gv;
6214
6215     PERL_ARGS_ASSERT_DOFILE;
6216
6217     if (!force_builtin && (gv = gv_override("do", 2))) {
6218         doop = S_new_entersubop(aTHX_ gv, term);
6219     }
6220     else {
6221         doop = newUNOP(OP_DOFILE, 0, scalar(term));
6222     }
6223     return doop;
6224 }
6225
6226 /*
6227 =head1 Optree construction
6228
6229 =for apidoc Am|OP *|newSLICEOP|I32 flags|OP *subscript|OP *listval
6230
6231 Constructs, checks, and returns an C<lslice> (list slice) op.  C<flags>
6232 gives the eight bits of C<op_flags>, except that C<OPf_KIDS> will
6233 be set automatically, and, shifted up eight bits, the eight bits of
6234 C<op_private>, except that the bit with value 1 or 2 is automatically
6235 set as required.  C<listval> and C<subscript> supply the parameters of
6236 the slice; they are consumed by this function and become part of the
6237 constructed op tree.
6238
6239 =cut
6240 */
6241
6242 OP *
6243 Perl_newSLICEOP(pTHX_ I32 flags, OP *subscript, OP *listval)
6244 {
6245     return newBINOP(OP_LSLICE, flags,
6246             list(force_list(subscript, 1)),
6247             list(force_list(listval,   1)) );
6248 }
6249
6250 #define ASSIGN_LIST   1
6251 #define ASSIGN_REF    2
6252
6253 STATIC I32
6254 S_assignment_type(pTHX_ const OP *o)
6255 {
6256     unsigned type;
6257     U8 flags;
6258     U8 ret;
6259
6260     if (!o)
6261         return TRUE;
6262
6263     if ((o->op_type == OP_NULL) && (o->op_flags & OPf_KIDS))
6264         o = cUNOPo->op_first;
6265
6266     flags = o->op_flags;
6267     type = o->op_type;
6268     if (type == OP_COND_EXPR) {
6269         OP * const sib = OpSIBLING(cLOGOPo->op_first);
6270         const I32 t = assignment_type(sib);
6271         const I32 f = assignment_type(OpSIBLING(sib));
6272
6273         if (t == ASSIGN_LIST && f == ASSIGN_LIST)
6274             return ASSIGN_LIST;
6275         if ((t == ASSIGN_LIST) ^ (f == ASSIGN_LIST))
6276             yyerror("Assignment to both a list and a scalar");
6277         return FALSE;
6278     }
6279
6280     if (type == OP_SREFGEN)
6281     {
6282         OP * const kid = cUNOPx(cUNOPo->op_first)->op_first;
6283         type = kid->op_type;
6284         flags |= kid->op_flags;
6285         if (!(flags & OPf_PARENS)
6286           && (kid->op_type == OP_RV2AV || kid->op_type == OP_PADAV ||
6287               kid->op_type == OP_RV2HV || kid->op_type == OP_PADHV ))
6288             return ASSIGN_REF;
6289         ret = ASSIGN_REF;
6290     }
6291     else ret = 0;
6292
6293     if (type == OP_LIST &&
6294         (flags & OPf_WANT) == OPf_WANT_SCALAR &&
6295         o->op_private & OPpLVAL_INTRO)
6296         return ret;
6297
6298     if (type == OP_LIST || flags & OPf_PARENS ||
6299         type == OP_RV2AV || type == OP_RV2HV ||
6300         type == OP_ASLICE || type == OP_HSLICE ||
6301         type == OP_KVASLICE || type == OP_KVHSLICE || type == OP_REFGEN)
6302         return TRUE;
6303
6304     if (type == OP_PADAV || type == OP_PADHV)
6305         return TRUE;
6306
6307     if (type == OP_RV2SV)
6308         return ret;
6309
6310     return ret;
6311 }
6312
6313
6314 /*
6315 =for apidoc Am|OP *|newASSIGNOP|I32 flags|OP *left|I32 optype|OP *right
6316
6317 Constructs, checks, and returns an assignment op.  C<left> and C<right>
6318 supply the parameters of the assignment; they are consumed by this
6319 function and become part of the constructed op tree.
6320
6321 If C<optype> is C<OP_ANDASSIGN>, C<OP_ORASSIGN>, or C<OP_DORASSIGN>, then
6322 a suitable conditional optree is constructed.  If C<optype> is the opcode
6323 of a binary operator, such as C<OP_BIT_OR>, then an op is constructed that
6324 performs the binary operation and assigns the result to the left argument.
6325 Either way, if C<optype> is non-zero then C<flags> has no effect.
6326
6327 If C<optype> is zero, then a plain scalar or list assignment is
6328 constructed.  Which type of assignment it is is automatically determined.
6329 C<flags> gives the eight bits of C<op_flags>, except that C<OPf_KIDS>
6330 will be set automatically, and, shifted up eight bits, the eight bits
6331 of C<op_private>, except that the bit with value 1 or 2 is automatically
6332 set as required.
6333
6334 =cut
6335 */
6336
6337 OP *
6338 Perl_newASSIGNOP(pTHX_ I32 flags, OP *left, I32 optype, OP *right)
6339 {
6340     OP *o;
6341     I32 assign_type;
6342
6343     if (optype) {
6344         if (optype == OP_ANDASSIGN || optype == OP_ORASSIGN || optype == OP_DORASSIGN) {
6345             return newLOGOP(optype, 0,
6346                 op_lvalue(scalar(left), optype),
6347                 newUNOP(OP_SASSIGN, 0, scalar(right)));
6348         }
6349         else {
6350             return newBINOP(optype, OPf_STACKED,
6351                 op_lvalue(scalar(left), optype), scalar(right));
6352         }
6353     }
6354
6355     if ((assign_type = assignment_type(left)) == ASSIGN_LIST) {
6356         static const char no_list_state[] = "Initialization of state variables"
6357             " in list context currently forbidden";
6358         OP *curop;
6359
6360         if (left->op_type == OP_ASLICE || left->op_type == OP_HSLICE)
6361             left->op_private &= ~ OPpSLICEWARNING;
6362
6363         PL_modcount = 0;
6364         left = op_lvalue(left, OP_AASSIGN);
6365         curop = list(force_list(left, 1));
6366         o = newBINOP(OP_AASSIGN, flags, list(force_list(right, 1)), curop);
6367         o->op_private = (U8)(0 | (flags >> 8));
6368
6369         if (OP_TYPE_IS_OR_WAS(left, OP_LIST))
6370         {
6371             OP* lop = ((LISTOP*)left)->op_first;
6372             while (lop) {
6373                 if ((lop->op_type == OP_PADSV ||
6374                      lop->op_type == OP_PADAV ||
6375                      lop->op_type == OP_PADHV ||
6376                      lop->op_type == OP_PADANY)
6377                   && (lop->op_private & OPpPAD_STATE)
6378                 )
6379                     yyerror(no_list_state);
6380                 lop = OpSIBLING(lop);
6381             }
6382         }
6383         else if (  (left->op_private & OPpLVAL_INTRO)
6384                 && (left->op_private & OPpPAD_STATE)
6385                 && (   left->op_type == OP_PADSV
6386                     || left->op_type == OP_PADAV
6387                     || left->op_type == OP_PADHV
6388                     || left->op_type == OP_PADANY)
6389         ) {
6390                 /* All single variable list context state assignments, hence
6391                    state ($a) = ...
6392                    (state $a) = ...
6393                    state @a = ...
6394                    state (@a) = ...
6395                    (state @a) = ...
6396                    state %a = ...
6397                    state (%a) = ...
6398                    (state %a) = ...
6399                 */
6400                 yyerror(no_list_state);
6401         }
6402
6403         if (right && right->op_type == OP_SPLIT
6404          && !(right->op_flags & OPf_STACKED)) {
6405             OP* tmpop = ((LISTOP*)right)->op_first;
6406             PMOP * const pm = (PMOP*)tmpop;
6407             assert (tmpop && (tmpop->op_type == OP_PUSHRE));
6408             if (
6409 #ifdef USE_ITHREADS
6410                     !pm->op_pmreplrootu.op_pmtargetoff
6411 #else
6412                     !pm->op_pmreplrootu.op_pmtargetgv
6413 #endif
6414                  && !pm->op_targ
6415                 ) {
6416                     if (!(left->op_private & OPpLVAL_INTRO) &&
6417                         ( (left->op_type == OP_RV2AV &&
6418                           (tmpop=((UNOP*)left)->op_first)->op_type==OP_GV)
6419                         || left->op_type == OP_PADAV )
6420                         ) {
6421                         if (tmpop != (OP *)pm) {
6422 #ifdef USE_ITHREADS
6423                           pm->op_pmreplrootu.op_pmtargetoff
6424                             = cPADOPx(tmpop)->op_padix;
6425                           cPADOPx(tmpop)->op_padix = 0; /* steal it */
6426 #else
6427                           pm->op_pmreplrootu.op_pmtargetgv
6428                             = MUTABLE_GV(cSVOPx(tmpop)->op_sv);
6429                           cSVOPx(tmpop)->op_sv = NULL;  /* steal it */
6430 #endif
6431                           right->op_private |=
6432                             left->op_private & OPpOUR_INTRO;
6433                         }
6434                         else {
6435                             pm->op_targ = left->op_targ;
6436                             left->op_targ = 0; /* filch it */
6437                         }
6438                       detach_split:
6439                         tmpop = cUNOPo->op_first;       /* to list (nulled) */
6440                         tmpop = ((UNOP*)tmpop)->op_first; /* to pushmark */
6441                         /* detach rest of siblings from o subtree,
6442                          * and free subtree */
6443                         op_sibling_splice(cUNOPo->op_first, tmpop, -1, NULL);
6444                         op_free(o);                     /* blow off assign */
6445                         right->op_flags &= ~OPf_WANT;
6446                                 /* "I don't know and I don't care." */
6447                         return right;
6448                     }
6449                     else if (left->op_type == OP_RV2AV
6450                           || left->op_type == OP_PADAV)
6451                     {
6452                         /* Detach the array.  */
6453 #ifdef DEBUGGING
6454                         OP * const ary =
6455 #endif
6456                         op_sibling_splice(cBINOPo->op_last,
6457                                           cUNOPx(cBINOPo->op_last)
6458                                                 ->op_first, 1, NULL);
6459                         assert(ary == left);
6460                         /* Attach it to the split.  */
6461                         op_sibling_splice(right, cLISTOPx(right)->op_last,
6462                                           0, left);
6463                         right->op_flags |= OPf_STACKED;
6464                         /* Detach split and expunge aassign as above.  */
6465                         goto detach_split;
6466                     }
6467                     else if (PL_modcount < RETURN_UNLIMITED_NUMBER &&
6468                             ((LISTOP*)right)->op_last->op_type == OP_CONST)
6469                     {
6470                         SV ** const svp =
6471                             &((SVOP*)((LISTOP*)right)->op_last)->op_sv;
6472                         SV * const sv = *svp;
6473                         if (SvIOK(sv) && SvIVX(sv) == 0)
6474                         {
6475                           if (right->op_private & OPpSPLIT_IMPLIM) {
6476                             /* our own SV, created in ck_split */
6477                             SvREADONLY_off(sv);
6478                             sv_setiv(sv, PL_modcount+1);
6479                           }
6480                           else {
6481                             /* SV may belong to someone else */
6482                             SvREFCNT_dec(sv);
6483                             *svp = newSViv(PL_modcount+1);
6484                           }
6485                         }
6486                     }
6487             }
6488         }
6489         return o;
6490     }
6491     if (assign_type == ASSIGN_REF)
6492         return newBINOP(OP_REFASSIGN, flags, scalar(right), left);
6493     if (!right)
6494         right = newOP(OP_UNDEF, 0);
6495     if (right->op_type == OP_READLINE) {
6496         right->op_flags |= OPf_STACKED;
6497         return newBINOP(OP_NULL, flags, op_lvalue(scalar(left), OP_SASSIGN),
6498                 scalar(right));
6499     }
6500     else {
6501         o = newBINOP(OP_SASSIGN, flags,
6502             scalar(right), op_lvalue(scalar(left), OP_SASSIGN) );
6503     }
6504     return o;
6505 }
6506
6507 /*
6508 =for apidoc Am|OP *|newSTATEOP|I32 flags|char *label|OP *o
6509
6510 Constructs a state op (COP).  The state op is normally a C<nextstate> op,
6511 but will be a C<dbstate> op if debugging is enabled for currently-compiled
6512 code.  The state op is populated from C<PL_curcop> (or C<PL_compiling>).
6513 If C<label> is non-null, it supplies the name of a label to attach to
6514 the state op; this function takes ownership of the memory pointed at by
6515 C<label>, and will free it.  C<flags> gives the eight bits of C<op_flags>
6516 for the state op.
6517
6518 If C<o> is null, the state op is returned.  Otherwise the state op is
6519 combined with C<o> into a C<lineseq> list op, which is returned.  C<o>
6520 is consumed by this function and becomes part of the returned op tree.
6521
6522 =cut
6523 */
6524
6525 OP *
6526 Perl_newSTATEOP(pTHX_ I32 flags, char *label, OP *o)
6527 {
6528     dVAR;
6529     const U32 seq = intro_my();
6530     const U32 utf8 = flags & SVf_UTF8;
6531     COP *cop;
6532
6533     PL_parser->parsed_sub = 0;
6534
6535     flags &= ~SVf_UTF8;
6536
6537     NewOp(1101, cop, 1, COP);
6538     if (PERLDB_LINE && CopLINE(PL_curcop) && PL_curstash != PL_debstash) {
6539         OpTYPE_set(cop, OP_DBSTATE);
6540     }
6541     else {
6542         OpTYPE_set(cop, OP_NEXTSTATE);
6543     }
6544     cop->op_flags = (U8)flags;
6545     CopHINTS_set(cop, PL_hints);
6546 #ifdef VMS
6547     if (VMSISH_HUSHED) cop->op_private |= OPpHUSH_VMSISH;
6548 #endif
6549     cop->op_next = (OP*)cop;
6550
6551     cop->cop_seq = seq;
6552     cop->cop_warnings = DUP_WARNINGS(PL_curcop->cop_warnings);
6553     CopHINTHASH_set(cop, cophh_copy(CopHINTHASH_get(PL_curcop)));
6554     if (label) {
6555         Perl_cop_store_label(aTHX_ cop, label, strlen(label), utf8);
6556
6557         PL_hints |= HINT_BLOCK_SCOPE;
6558         /* It seems that we need to defer freeing this pointer, as other parts
6559            of the grammar end up wanting to copy it after this op has been
6560            created. */
6561         SAVEFREEPV(label);
6562     }
6563
6564     if (PL_parser->preambling != NOLINE) {
6565         CopLINE_set(cop, PL_parser->preambling);
6566         PL_parser->copline = NOLINE;
6567     }
6568     else if (PL_parser->copline == NOLINE)
6569         CopLINE_set(cop, CopLINE(PL_curcop));
6570     else {
6571         CopLINE_set(cop, PL_parser->copline);
6572         PL_parser->copline = NOLINE;
6573     }
6574 #ifdef USE_ITHREADS
6575     CopFILE_set(cop, CopFILE(PL_curcop));       /* XXX share in a pvtable? */
6576 #else
6577     CopFILEGV_set(cop, CopFILEGV(PL_curcop));
6578 #endif
6579     CopSTASH_set(cop, PL_curstash);
6580
6581     if (cop->op_type == OP_DBSTATE) {
6582         /* this line can have a breakpoint - store the cop in IV */
6583         AV *av = CopFILEAVx(PL_curcop);
6584         if (av) {
6585             SV * const * const svp = av_fetch(av, CopLINE(cop), FALSE);
6586             if (svp && *svp != &PL_sv_undef ) {
6587                 (void)SvIOK_on(*svp);
6588                 SvIV_set(*svp, PTR2IV(cop));
6589             }
6590         }
6591     }
6592
6593     if (flags & OPf_SPECIAL)
6594         op_null((OP*)cop);
6595     return op_prepend_elem(OP_LINESEQ, (OP*)cop, o);
6596 }
6597
6598 /*
6599 =for apidoc Am|OP *|newLOGOP|I32 type|I32 flags|OP *first|OP *other
6600
6601 Constructs, checks, and returns a logical (flow control) op.  C<type>
6602 is the opcode.  C<flags> gives the eight bits of C<op_flags>, except
6603 that C<OPf_KIDS> will be set automatically, and, shifted up eight bits,
6604 the eight bits of C<op_private>, except that the bit with value 1 is
6605 automatically set.  C<first> supplies the expression controlling the
6606 flow, and C<other> supplies the side (alternate) chain of ops; they are
6607 consumed by this function and become part of the constructed op tree.
6608
6609 =cut
6610 */
6611
6612 OP *
6613 Perl_newLOGOP(pTHX_ I32 type, I32 flags, OP *first, OP *other)
6614 {
6615     PERL_ARGS_ASSERT_NEWLOGOP;
6616
6617     return new_logop(type, flags, &first, &other);
6618 }
6619
6620 STATIC OP *
6621 S_search_const(pTHX_ OP *o)
6622 {
6623     PERL_ARGS_ASSERT_SEARCH_CONST;
6624
6625     switch (o->op_type) {
6626         case OP_CONST:
6627             return o;
6628         case OP_NULL:
6629             if (o->op_flags & OPf_KIDS)
6630                 return search_const(cUNOPo->op_first);
6631             break;
6632         case OP_LEAVE:
6633         case OP_SCOPE:
6634         case OP_LINESEQ:
6635         {
6636             OP *kid;
6637             if (!(o->op_flags & OPf_KIDS))
6638                 return NULL;
6639             kid = cLISTOPo->op_first;
6640             do {
6641                 switch (kid->op_type) {
6642                     case OP_ENTER:
6643                     case OP_NULL:
6644                     case OP_NEXTSTATE:
6645                         kid = OpSIBLING(kid);
6646                         break;
6647                     default:
6648                         if (kid != cLISTOPo->op_last)
6649                             return NULL;
6650                         goto last;
6651                 }
6652             } while (kid);
6653             if (!kid)
6654                 kid = cLISTOPo->op_last;
6655           last:
6656             return search_const(kid);
6657         }
6658     }
6659
6660     return NULL;
6661 }
6662
6663 STATIC OP *
6664 S_new_logop(pTHX_ I32 type, I32 flags, OP** firstp, OP** otherp)
6665 {
6666     dVAR;
6667     LOGOP *logop;
6668     OP *o;
6669     OP *first;
6670     OP *other;
6671     OP *cstop = NULL;
6672     int prepend_not = 0;
6673
6674     PERL_ARGS_ASSERT_NEW_LOGOP;
6675
6676     first = *firstp;
6677     other = *otherp;
6678
6679     /* [perl #59802]: Warn about things like "return $a or $b", which
6680        is parsed as "(return $a) or $b" rather than "return ($a or
6681        $b)".  NB: This also applies to xor, which is why we do it
6682        here.
6683      */
6684     switch (first->op_type) {
6685     case OP_NEXT:
6686     case OP_LAST:
6687     case OP_REDO:
6688         /* XXX: Perhaps we should emit a stronger warning for these.
6689            Even with the high-precedence operator they don't seem to do
6690            anything sensible.
6691
6692            But until we do, fall through here.
6693          */
6694     case OP_RETURN:
6695     case OP_EXIT:
6696     case OP_DIE:
6697     case OP_GOTO:
6698         /* XXX: Currently we allow people to "shoot themselves in the
6699            foot" by explicitly writing "(return $a) or $b".
6700
6701            Warn unless we are looking at the result from folding or if
6702            the programmer explicitly grouped the operators like this.
6703            The former can occur with e.g.
6704
6705                 use constant FEATURE => ( $] >= ... );
6706                 sub { not FEATURE and return or do_stuff(); }
6707          */
6708         if (!first->op_folded && !(first->op_flags & OPf_PARENS))
6709             Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX),
6710                            "Possible precedence issue with control flow operator");
6711         /* XXX: Should we optimze this to "return $a;" (i.e. remove
6712            the "or $b" part)?
6713         */
6714         break;
6715     }
6716
6717     if (type == OP_XOR)         /* Not short circuit, but here by precedence. */
6718         return newBINOP(type, flags, scalar(first), scalar(other));
6719
6720     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_LOGOP
6721         || type == OP_CUSTOM);
6722
6723     scalarboolean(first);
6724     /* optimize AND and OR ops that have NOTs as children */
6725     if (first->op_type == OP_NOT
6726         && (first->op_flags & OPf_KIDS)
6727         && ((first->op_flags & OPf_SPECIAL) /* unless ($x) { } */
6728             || (other->op_type == OP_NOT))  /* if (!$x && !$y) { } */
6729         ) {
6730         if (type == OP_AND || type == OP_OR) {
6731             if (type == OP_AND)
6732                 type = OP_OR;
6733             else
6734                 type = OP_AND;
6735             op_null(first);
6736             if (other->op_type == OP_NOT) { /* !a AND|OR !b => !(a OR|AND b) */
6737                 op_null(other);
6738                 prepend_not = 1; /* prepend a NOT op later */
6739             }
6740         }
6741     }
6742     /* search for a constant op that could let us fold the test */
6743     if ((cstop = search_const(first))) {
6744         if (cstop->op_private & OPpCONST_STRICT)
6745             no_bareword_allowed(cstop);
6746         else if ((cstop->op_private & OPpCONST_BARE))
6747                 Perl_ck_warner(aTHX_ packWARN(WARN_BAREWORD), "Bareword found in conditional");
6748         if ((type == OP_AND &&  SvTRUE(((SVOP*)cstop)->op_sv)) ||
6749             (type == OP_OR  && !SvTRUE(((SVOP*)cstop)->op_sv)) ||
6750             (type == OP_DOR && !SvOK(((SVOP*)cstop)->op_sv))) {
6751             *firstp = NULL;
6752             if (other->op_type == OP_CONST)
6753                 other->op_private |= OPpCONST_SHORTCIRCUIT;
6754             op_free(first);
6755             if (other->op_type == OP_LEAVE)
6756                 other = newUNOP(OP_NULL, OPf_SPECIAL, other);
6757             else if (other->op_type == OP_MATCH
6758                   || other->op_type == OP_SUBST
6759                   || other->op_type == OP_TRANSR
6760                   || other->op_type == OP_TRANS)
6761                 /* Mark the op as being unbindable with =~ */
6762                 other->op_flags |= OPf_SPECIAL;
6763
6764             other->op_folded = 1;
6765             return other;
6766         }
6767         else {
6768             /* check for C<my $x if 0>, or C<my($x,$y) if 0> */
6769             const OP *o2 = other;
6770             if ( ! (o2->op_type == OP_LIST
6771                     && (( o2 = cUNOPx(o2)->op_first))
6772                     && o2->op_type == OP_PUSHMARK
6773                     && (( o2 = OpSIBLING(o2))) )
6774             )
6775                 o2 = other;
6776             if ((o2->op_type == OP_PADSV || o2->op_type == OP_PADAV
6777                         || o2->op_type == OP_PADHV)
6778                 && o2->op_private & OPpLVAL_INTRO
6779                 && !(o2->op_private & OPpPAD_STATE))
6780             {
6781                 Perl_ck_warner_d(aTHX_ packWARN(WARN_DEPRECATED),
6782                                  "Deprecated use of my() in false conditional");
6783             }
6784
6785             *otherp = NULL;
6786             if (cstop->op_type == OP_CONST)
6787                 cstop->op_private |= OPpCONST_SHORTCIRCUIT;
6788                 op_free(other);
6789             return first;
6790         }
6791     }
6792     else if ((first->op_flags & OPf_KIDS) && type != OP_DOR
6793         && ckWARN(WARN_MISC)) /* [#24076] Don't warn for <FH> err FOO. */
6794     {
6795         const OP * const k1 = ((UNOP*)first)->op_first;
6796         const OP * const k2 = OpSIBLING(k1);
6797         OPCODE warnop = 0;
6798         switch (first->op_type)
6799         {
6800         case OP_NULL:
6801             if (k2 && k2->op_type == OP_READLINE
6802                   && (k2->op_flags & OPf_STACKED)
6803                   && ((k1->op_flags & OPf_WANT) == OPf_WANT_SCALAR))
6804             {
6805                 warnop = k2->op_type;
6806             }
6807             break;
6808
6809         case OP_SASSIGN:
6810             if (k1->op_type == OP_READDIR
6811                   || k1->op_type == OP_GLOB
6812                   || (k1->op_type == OP_NULL && k1->op_targ == OP_GLOB)
6813                  || k1->op_type == OP_EACH
6814                  || k1->op_type == OP_AEACH)
6815             {
6816                 warnop = ((k1->op_type == OP_NULL)
6817                           ? (OPCODE)k1->op_targ : k1->op_type);
6818             }
6819             break;
6820         }
6821         if (warnop) {
6822             const line_t oldline = CopLINE(PL_curcop);
6823             /* This ensures that warnings are reported at the first line
6824                of the construction, not the last.  */
6825             CopLINE_set(PL_curcop, PL_parser->copline);
6826             Perl_warner(aTHX_ packWARN(WARN_MISC),
6827                  "Value of %s%s can be \"0\"; test with defined()",
6828                  PL_op_desc[warnop],
6829                  ((warnop == OP_READLINE || warnop == OP_GLOB)
6830                   ? " construct" : "() operator"));
6831             CopLINE_set(PL_curcop, oldline);
6832         }
6833     }
6834
6835     if (!other)
6836         return first;
6837
6838     if (type == OP_ANDASSIGN || type == OP_ORASSIGN || type == OP_DORASSIGN)
6839         other->op_private |= OPpASSIGN_BACKWARDS;  /* other is an OP_SASSIGN */
6840
6841     logop = S_alloc_LOGOP(aTHX_ type, first, LINKLIST(other));
6842     logop->op_flags |= (U8)flags;
6843     logop->op_private = (U8)(1 | (flags >> 8));
6844
6845     /* establish postfix order */
6846     logop->op_next = LINKLIST(first);
6847     first->op_next = (OP*)logop;
6848     assert(!OpHAS_SIBLING(first));
6849     op_sibling_splice((OP*)logop, first, 0, other);
6850
6851     CHECKOP(type,logop);
6852
6853     o = newUNOP(prepend_not ? OP_NOT : OP_NULL,
6854                 PL_opargs[type] & OA_RETSCALAR ? OPf_WANT_SCALAR : 0,
6855                 (OP*)logop);
6856     other->op_next = o;
6857
6858     return o;
6859 }
6860
6861 /*
6862 =for apidoc Am|OP *|newCONDOP|I32 flags|OP *first|OP *trueop|OP *falseop
6863
6864 Constructs, checks, and returns a conditional-expression (C<cond_expr>)
6865 op.  C<flags> gives the eight bits of C<op_flags>, except that C<OPf_KIDS>
6866 will be set automatically, and, shifted up eight bits, the eight bits of
6867 C<op_private>, except that the bit with value 1 is automatically set.
6868 C<first> supplies the expression selecting between the two branches,
6869 and C<trueop> and C<falseop> supply the branches; they are consumed by
6870 this function and become part of the constructed op tree.
6871
6872 =cut
6873 */
6874
6875 OP *
6876 Perl_newCONDOP(pTHX_ I32 flags, OP *first, OP *trueop, OP *falseop)
6877 {
6878     dVAR;
6879     LOGOP *logop;
6880     OP *start;
6881     OP *o;
6882     OP *cstop;
6883
6884     PERL_ARGS_ASSERT_NEWCONDOP;
6885
6886     if (!falseop)
6887         return newLOGOP(OP_AND, 0, first, trueop);
6888     if (!trueop)
6889         return newLOGOP(OP_OR, 0, first, falseop);
6890
6891     scalarboolean(first);
6892     if ((cstop = search_const(first))) {
6893         /* Left or right arm of the conditional?  */
6894         const bool left = SvTRUE(((SVOP*)cstop)->op_sv);
6895         OP *live = left ? trueop : falseop;
6896         OP *const dead = left ? falseop : trueop;
6897         if (cstop->op_private & OPpCONST_BARE &&
6898             cstop->op_private & OPpCONST_STRICT) {
6899             no_bareword_allowed(cstop);
6900         }
6901         op_free(first);
6902         op_free(dead);
6903         if (live->op_type == OP_LEAVE)
6904             live = newUNOP(OP_NULL, OPf_SPECIAL, live);
6905         else if (live->op_type == OP_MATCH || live->op_type == OP_SUBST
6906               || live->op_type == OP_TRANS || live->op_type == OP_TRANSR)
6907             /* Mark the op as being unbindable with =~ */
6908             live->op_flags |= OPf_SPECIAL;
6909         live->op_folded = 1;
6910         return live;
6911     }
6912     logop = S_alloc_LOGOP(aTHX_ OP_COND_EXPR, first, LINKLIST(trueop));
6913     logop->op_flags |= (U8)flags;
6914     logop->op_private = (U8)(1 | (flags >> 8));
6915     logop->op_next = LINKLIST(falseop);
6916
6917     CHECKOP(OP_COND_EXPR, /* that's logop->op_type */
6918             logop);
6919
6920     /* establish postfix order */
6921     start = LINKLIST(first);
6922     first->op_next = (OP*)logop;
6923
6924     /* make first, trueop, falseop siblings */
6925     op_sibling_splice((OP*)logop, first,  0, trueop);
6926     op_sibling_splice((OP*)logop, trueop, 0, falseop);
6927
6928     o = newUNOP(OP_NULL, 0, (OP*)logop);
6929
6930     trueop->op_next = falseop->op_next = o;
6931
6932     o->op_next = start;
6933     return o;
6934 }
6935
6936 /*
6937 =for apidoc Am|OP *|newRANGE|I32 flags|OP *left|OP *right
6938
6939 Constructs and returns a C<range> op, with subordinate C<flip> and
6940 C<flop> ops.  C<flags> gives the eight bits of C<op_flags> for the
6941 C<flip> op and, shifted up eight bits, the eight bits of C<op_private>
6942 for both the C<flip> and C<range> ops, except that the bit with value
6943 1 is automatically set.  C<left> and C<right> supply the expressions
6944 controlling the endpoints of the range; they are consumed by this function
6945 and become part of the constructed op tree.
6946
6947 =cut
6948 */
6949
6950 OP *
6951 Perl_newRANGE(pTHX_ I32 flags, OP *left, OP *right)
6952 {
6953     LOGOP *range;
6954     OP *flip;
6955     OP *flop;
6956     OP *leftstart;
6957     OP *o;
6958
6959     PERL_ARGS_ASSERT_NEWRANGE;
6960
6961     range = S_alloc_LOGOP(aTHX_ OP_RANGE, left, LINKLIST(right));
6962     range->op_flags = OPf_KIDS;
6963     leftstart = LINKLIST(left);
6964     range->op_private = (U8)(1 | (flags >> 8));
6965
6966     /* make left and right siblings */
6967     op_sibling_splice((OP*)range, left, 0, right);
6968
6969     range->op_next = (OP*)range;
6970     flip = newUNOP(OP_FLIP, flags, (OP*)range);
6971     flop = newUNOP(OP_FLOP, 0, flip);
6972     o = newUNOP(OP_NULL, 0, flop);
6973     LINKLIST(flop);
6974     range->op_next = leftstart;
6975
6976     left->op_next = flip;
6977     right->op_next = flop;
6978
6979     range->op_targ =
6980         pad_add_name_pvn("$", 1, padadd_NO_DUP_CHECK|padadd_STATE, 0, 0);
6981     sv_upgrade(PAD_SV(range->op_targ), SVt_PVNV);
6982     flip->op_targ =
6983         pad_add_name_pvn("$", 1, padadd_NO_DUP_CHECK|padadd_STATE, 0, 0);;
6984     sv_upgrade(PAD_SV(flip->op_targ), SVt_PVNV);
6985     SvPADTMP_on(PAD_SV(flip->op_targ));
6986
6987     flip->op_private =  left->op_type == OP_CONST ? OPpFLIP_LINENUM : 0;
6988     flop->op_private = right->op_type == OP_CONST ? OPpFLIP_LINENUM : 0;
6989
6990     /* check barewords before they might be optimized aways */
6991     if (flip->op_private && cSVOPx(left)->op_private & OPpCONST_STRICT)
6992         no_bareword_allowed(left);
6993     if (flop->op_private && cSVOPx(right)->op_private & OPpCONST_STRICT)
6994         no_bareword_allowed(right);
6995
6996     flip->op_next = o;
6997     if (!flip->op_private || !flop->op_private)
6998         LINKLIST(o);            /* blow off optimizer unless constant */
6999
7000     return o;
7001 }
7002
7003 /*
7004 =for apidoc Am|OP *|newLOOPOP|I32 flags|I32 debuggable|OP *expr|OP *block
7005
7006 Constructs, checks, and returns an op tree expressing a loop.  This is
7007 only a loop in the control flow through the op tree; it does not have
7008 the heavyweight loop structure that allows exiting the loop by C<last>
7009 and suchlike.  C<flags> gives the eight bits of C<op_flags> for the
7010 top-level op, except that some bits will be set automatically as required.
7011 C<expr> supplies the expression controlling loop iteration, and C<block>
7012 supplies the body of the loop; they are consumed by this function and
7013 become part of the constructed op tree.  C<debuggable> is currently
7014 unused and should always be 1.
7015
7016 =cut
7017 */
7018
7019 OP *
7020 Perl_newLOOPOP(pTHX_ I32 flags, I32 debuggable, OP *expr, OP *block)
7021 {
7022     OP* listop;
7023     OP* o;
7024     const bool once = block && block->op_flags & OPf_SPECIAL &&
7025                       block->op_type == OP_NULL;
7026
7027     PERL_UNUSED_ARG(debuggable);
7028
7029     if (expr) {
7030         if (once && (
7031               (expr->op_type == OP_CONST && !SvTRUE(((SVOP*)expr)->op_sv))
7032            || (  expr->op_type == OP_NOT
7033               && cUNOPx(expr)->op_first->op_type == OP_CONST
7034               && SvTRUE(cSVOPx_sv(cUNOPx(expr)->op_first))
7035               )
7036            ))
7037             /* Return the block now, so that S_new_logop does not try to
7038                fold it away. */
7039             return block;       /* do {} while 0 does once */
7040         if (expr->op_type == OP_READLINE
7041             || expr->op_type == OP_READDIR
7042             || expr->op_type == OP_GLOB
7043             || expr->op_type == OP_EACH || expr->op_type == OP_AEACH
7044             || (expr->op_type == OP_NULL && expr->op_targ == OP_GLOB)) {
7045             expr = newUNOP(OP_DEFINED, 0,
7046                 newASSIGNOP(0, newDEFSVOP(), 0, expr) );
7047         } else if (expr->op_flags & OPf_KIDS) {
7048             const OP * const k1 = ((UNOP*)expr)->op_first;
7049             const OP * const k2 = k1 ? OpSIBLING(k1) : NULL;
7050             switch (expr->op_type) {
7051               case OP_NULL:
7052                 if (k2 && (k2->op_type == OP_READLINE || k2->op_type == OP_READDIR)
7053                       && (k2->op_flags & OPf_STACKED)
7054                       && ((k1->op_flags & OPf_WANT) == OPf_WANT_SCALAR))
7055                     expr = newUNOP(OP_DEFINED, 0, expr);
7056                 break;
7057
7058               case OP_SASSIGN:
7059                 if (k1 && (k1->op_type == OP_READDIR
7060                       || k1->op_type == OP_GLOB
7061                       || (k1->op_type == OP_NULL && k1->op_targ == OP_GLOB)
7062                      || k1->op_type == OP_EACH
7063                      || k1->op_type == OP_AEACH))
7064                     expr = newUNOP(OP_DEFINED, 0, expr);
7065                 break;
7066             }
7067         }
7068     }
7069
7070     /* if block is null, the next op_append_elem() would put UNSTACK, a scalar
7071      * op, in listop. This is wrong. [perl #27024] */
7072     if (!block)
7073         block = newOP(OP_NULL, 0);
7074     listop = op_append_elem(OP_LINESEQ, block, newOP(OP_UNSTACK, 0));
7075     o = new_logop(OP_AND, 0, &expr, &listop);
7076
7077     if (once) {
7078         ASSUME(listop);
7079     }
7080
7081     if (listop)
7082         ((LISTOP*)listop)->op_last->op_next = LINKLIST(o);
7083
7084     if (once && o != listop)
7085     {
7086         assert(cUNOPo->op_first->op_type == OP_AND
7087             || cUNOPo->op_first->op_type == OP_OR);
7088         o->op_next = ((LOGOP*)cUNOPo->op_first)->op_other;
7089     }
7090
7091     if (o == listop)
7092         o = newUNOP(OP_NULL, 0, o);     /* or do {} while 1 loses outer block */
7093
7094     o->op_flags |= flags;
7095     o = op_scope(o);
7096     o->op_flags |= OPf_SPECIAL; /* suppress POPBLOCK curpm restoration*/
7097     return o;
7098 }
7099
7100 /*
7101 =for apidoc Am|OP *|newWHILEOP|I32 flags|I32 debuggable|LOOP *loop|OP *expr|OP *block|OP *cont|I32 has_my
7102
7103 Constructs, checks, and returns an op tree expressing a C<while> loop.
7104 This is a heavyweight loop, with structure that allows exiting the loop
7105 by C<last> and suchlike.
7106
7107 C<loop> is an optional preconstructed C<enterloop> op to use in the
7108 loop; if it is null then a suitable op will be constructed automatically.
7109 C<expr> supplies the loop's controlling expression.  C<block> supplies the
7110 main body of the loop, and C<cont> optionally supplies a C<continue> block
7111 that operates as a second half of the body.  All of these optree inputs
7112 are consumed by this function and become part of the constructed op tree.
7113
7114 C<flags> gives the eight bits of C<op_flags> for the C<leaveloop>
7115 op and, shifted up eight bits, the eight bits of C<op_private> for
7116 the C<leaveloop> op, except that (in both cases) some bits will be set
7117 automatically.  C<debuggable> is currently unused and should always be 1.
7118 C<has_my> can be supplied as true to force the
7119 loop body to be enclosed in its own scope.
7120
7121 =cut
7122 */
7123
7124 OP *
7125 Perl_newWHILEOP(pTHX_ I32 flags, I32 debuggable, LOOP *loop,
7126         OP *expr, OP *block, OP *cont, I32 has_my)
7127 {
7128     dVAR;
7129     OP *redo;
7130     OP *next = NULL;
7131     OP *listop;
7132     OP *o;
7133     U8 loopflags = 0;
7134
7135     PERL_UNUSED_ARG(debuggable);
7136
7137     if (expr) {
7138         if (expr->op_type == OP_READLINE
7139          || expr->op_type == OP_READDIR
7140          || expr->op_type == OP_GLOB
7141          || expr->op_type == OP_EACH || expr->op_type == OP_AEACH
7142                      || (expr->op_type == OP_NULL && expr->op_targ == OP_GLOB)) {
7143             expr = newUNOP(OP_DEFINED, 0,
7144                 newASSIGNOP(0, newDEFSVOP(), 0, expr) );
7145         } else if (expr->op_flags & OPf_KIDS) {
7146             const OP * const k1 = ((UNOP*)expr)->op_first;
7147             const OP * const k2 = (k1) ? OpSIBLING(k1) : NULL;
7148             switch (expr->op_type) {
7149               case OP_NULL:
7150                 if (k2 && (k2->op_type == OP_READLINE || k2->op_type == OP_READDIR)
7151                       && (k2->op_flags & OPf_STACKED)
7152                       && ((k1->op_flags & OPf_WANT) == OPf_WANT_SCALAR))
7153                     expr = newUNOP(OP_DEFINED, 0, expr);
7154                 break;
7155
7156               case OP_SASSIGN:
7157                 if (k1 && (k1->op_type == OP_READDIR
7158                       || k1->op_type == OP_GLOB
7159                       || (k1->op_type == OP_NULL && k1->op_targ == OP_GLOB)
7160                      || k1->op_type == OP_EACH
7161                      || k1->op_type == OP_AEACH))
7162                     expr = newUNOP(OP_DEFINED, 0, expr);
7163                 break;
7164             }
7165         }
7166     }
7167
7168     if (!block)
7169         block = newOP(OP_NULL, 0);
7170     else if (cont || has_my) {
7171         block = op_scope(block);
7172     }
7173
7174     if (cont) {
7175         next = LINKLIST(cont);
7176     }
7177     if (expr) {
7178         OP * const unstack = newOP(OP_UNSTACK, 0);
7179         if (!next)
7180             next = unstack;
7181         cont = op_append_elem(OP_LINESEQ, cont, unstack);
7182     }
7183
7184     assert(block);
7185     listop = op_append_list(OP_LINESEQ, block, cont);
7186     assert(listop);
7187     redo = LINKLIST(listop);
7188
7189     if (expr) {
7190         scalar(listop);
7191         o = new_logop(OP_AND, 0, &expr, &listop);
7192         if (o == expr && o->op_type == OP_CONST && !SvTRUE(cSVOPo->op_sv)) {
7193             op_free((OP*)loop);
7194             return expr;                /* listop already freed by new_logop */
7195         }
7196         if (listop)
7197             ((LISTOP*)listop)->op_last->op_next =
7198                 (o == listop ? redo : LINKLIST(o));
7199     }
7200     else
7201         o = listop;
7202
7203     if (!loop) {
7204         NewOp(1101,loop,1,LOOP);
7205         OpTYPE_set(loop, OP_ENTERLOOP);
7206         loop->op_private = 0;
7207         loop->op_next = (OP*)loop;
7208     }
7209
7210     o = newBINOP(OP_LEAVELOOP, 0, (OP*)loop, o);
7211
7212     loop->op_redoop = redo;
7213     loop->op_lastop = o;
7214     o->op_private |= loopflags;
7215
7216     if (next)
7217         loop->op_nextop = next;
7218     else
7219         loop->op_nextop = o;
7220
7221     o->op_flags |= flags;
7222     o->op_private |= (flags >> 8);
7223     return o;
7224 }
7225
7226 /*
7227 =for apidoc Am|OP *|newFOROP|I32 flags|OP *sv|OP *expr|OP *block|OP *cont
7228
7229 Constructs, checks, and returns an op tree expressing a C<foreach>
7230 loop (iteration through a list of values).  This is a heavyweight loop,
7231 with structure that allows exiting the loop by C<last> and suchlike.
7232
7233 C<sv> optionally supplies the variable that will be aliased to each
7234 item in turn; if null, it defaults to C<$_>.
7235 C<expr> supplies the list of values to iterate over.  C<block> supplies
7236 the main body of the loop, and C<cont> optionally supplies a C<continue>
7237 block that operates as a second half of the body.  All of these optree
7238 inputs are consumed by this function and become part of the constructed
7239 op tree.
7240
7241 C<flags> gives the eight bits of C<op_flags> for the C<leaveloop>
7242 op and, shifted up eight bits, the eight bits of C<op_private> for
7243 the C<leaveloop> op, except that (in both cases) some bits will be set
7244 automatically.
7245
7246 =cut
7247 */
7248
7249 OP *
7250 Perl_newFOROP(pTHX_ I32 flags, OP *sv, OP *expr, OP *block, OP *cont)
7251 {
7252     dVAR;
7253     LOOP *loop;
7254     OP *wop;
7255     PADOFFSET padoff = 0;
7256     I32 iterflags = 0;
7257     I32 iterpflags = 0;
7258
7259     PERL_ARGS_ASSERT_NEWFOROP;
7260
7261     if (sv) {
7262         if (sv->op_type == OP_RV2SV) {  /* symbol table variable */
7263             iterpflags = sv->op_private & OPpOUR_INTRO; /* for our $x () */
7264             OpTYPE_set(sv, OP_RV2GV);
7265
7266             /* The op_type check is needed to prevent a possible segfault
7267              * if the loop variable is undeclared and 'strict vars' is in
7268              * effect. This is illegal but is nonetheless parsed, so we
7269              * may reach this point with an OP_CONST where we're expecting
7270              * an OP_GV.
7271              */
7272             if (cUNOPx(sv)->op_first->op_type == OP_GV
7273              && cGVOPx_gv(cUNOPx(sv)->op_first) == PL_defgv)
7274                 iterpflags |= OPpITER_DEF;
7275         }
7276         else if (sv->op_type == OP_PADSV) { /* private variable */
7277             iterpflags = sv->op_private & OPpLVAL_INTRO; /* for my $x () */
7278             padoff = sv->op_targ;
7279             sv->op_targ = 0;
7280             op_free(sv);
7281             sv = NULL;
7282             PAD_COMPNAME_GEN_set(padoff, PERL_INT_MAX);
7283         }
7284         else if (sv->op_type == OP_NULL && sv->op_targ == OP_SREFGEN)
7285             NOOP;
7286         else
7287             Perl_croak(aTHX_ "Can't use %s for loop variable", PL_op_desc[sv->op_type]);
7288         if (padoff) {
7289             PADNAME * const pn = PAD_COMPNAME(padoff);
7290             const char * const name = PadnamePV(pn);
7291
7292             if (PadnameLEN(pn) == 2 && name[0] == '$' && name[1] == '_')
7293                 iterpflags |= OPpITER_DEF;
7294         }
7295     }
7296     else {
7297         sv = newGVOP(OP_GV, 0, PL_defgv);
7298         iterpflags |= OPpITER_DEF;
7299     }
7300
7301     if (expr->op_type == OP_RV2AV || expr->op_type == OP_PADAV) {
7302         expr = op_lvalue(force_list(scalar(ref(expr, OP_ITER)), 1), OP_GREPSTART);
7303         iterflags |= OPf_STACKED;
7304     }
7305     else if (expr->op_type == OP_NULL &&
7306              (expr->op_flags & OPf_KIDS) &&
7307              ((BINOP*)expr)->op_first->op_type == OP_FLOP)
7308     {
7309         /* Basically turn for($x..$y) into the same as for($x,$y), but we
7310          * set the STACKED flag to indicate that these values are to be
7311          * treated as min/max values by 'pp_enteriter'.
7312          */
7313         const UNOP* const flip = (UNOP*)((UNOP*)((BINOP*)expr)->op_first)->op_first;
7314         LOGOP* const range = (LOGOP*) flip->op_first;
7315         OP* const left  = range->op_first;
7316         OP* const right = OpSIBLING(left);
7317         LISTOP* listop;
7318
7319         range->op_flags &= ~OPf_KIDS;
7320         /* detach range's children */
7321         op_sibling_splice((OP*)range, NULL, -1, NULL);
7322
7323         listop = (LISTOP*)newLISTOP(OP_LIST, 0, left, right);
7324         listop->op_first->op_next = range->op_next;
7325         left->op_next = range->op_other;
7326         right->op_next = (OP*)listop;
7327         listop->op_next = listop->op_first;
7328
7329         op_free(expr);
7330         expr = (OP*)(listop);
7331         op_null(expr);
7332         iterflags |= OPf_STACKED;
7333     }
7334     else {
7335         expr = op_lvalue(force_list(expr, 1), OP_GREPSTART);
7336     }
7337
7338     loop = (LOOP*)op_convert_list(OP_ENTERITER, iterflags,
7339                                   op_append_elem(OP_LIST, list(expr),
7340                                                  scalar(sv)));
7341     assert(!loop->op_next);
7342     /* for my  $x () sets OPpLVAL_INTRO;
7343      * for our $x () sets OPpOUR_INTRO */
7344     loop->op_private = (U8)iterpflags;
7345     if (loop->op_slabbed
7346      && DIFF(loop, OpSLOT(loop)->opslot_next)
7347          < SIZE_TO_PSIZE(sizeof(LOOP)))
7348     {
7349         LOOP *tmp;
7350         NewOp(1234,tmp,1,LOOP);
7351         Copy(loop,tmp,1,LISTOP);
7352 #ifdef PERL_OP_PARENT
7353         assert(loop->op_last->op_sibparent == (OP*)loop);
7354         OpLASTSIB_set(loop->op_last, (OP*)tmp); /*point back to new parent */
7355 #endif
7356         S_op_destroy(aTHX_ (OP*)loop);
7357         loop = tmp;
7358     }
7359     else if (!loop->op_slabbed)
7360     {
7361         loop = (LOOP*)PerlMemShared_realloc(loop, sizeof(LOOP));
7362 #ifdef PERL_OP_PARENT
7363         OpLASTSIB_set(loop->op_last, (OP*)loop);
7364 #endif
7365     }
7366     loop->op_targ = padoff;
7367     wop = newWHILEOP(flags, 1, loop, newOP(OP_ITER, 0), block, cont, 0);
7368     return wop;
7369 }
7370
7371 /*
7372 =for apidoc Am|OP *|newLOOPEX|I32 type|OP *label
7373
7374 Constructs, checks, and returns a loop-exiting op (such as C<goto>
7375 or C<last>).  C<type> is the opcode.  C<label> supplies the parameter
7376 determining the target of the op; it is consumed by this function and
7377 becomes part of the constructed op tree.
7378
7379 =cut
7380 */
7381
7382 OP*
7383 Perl_newLOOPEX(pTHX_ I32 type, OP *label)
7384 {
7385     OP *o = NULL;
7386
7387     PERL_ARGS_ASSERT_NEWLOOPEX;
7388
7389     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_LOOPEXOP
7390         || type == OP_CUSTOM);
7391
7392     if (type != OP_GOTO) {
7393         /* "last()" means "last" */
7394         if (label->op_type == OP_STUB && (label->op_flags & OPf_PARENS)) {
7395             o = newOP(type, OPf_SPECIAL);
7396         }
7397     }
7398     else {
7399         /* Check whether it's going to be a goto &function */
7400         if (label->op_type == OP_ENTERSUB
7401                 && !(label->op_flags & OPf_STACKED))
7402             label = newUNOP(OP_REFGEN, 0, op_lvalue(label, OP_REFGEN));
7403     }
7404
7405     /* Check for a constant argument */
7406     if (label->op_type == OP_CONST) {
7407             SV * const sv = ((SVOP *)label)->op_sv;
7408             STRLEN l;
7409             const char *s = SvPV_const(sv,l);
7410             if (l == strlen(s)) {
7411                 o = newPVOP(type,
7412                             SvUTF8(((SVOP*)label)->op_sv),
7413                             savesharedpv(
7414                                 SvPV_nolen_const(((SVOP*)label)->op_sv)));
7415             }
7416     }
7417     
7418     /* If we have already created an op, we do not need the label. */
7419     if (o)
7420                 op_free(label);
7421     else o = newUNOP(type, OPf_STACKED, label);
7422
7423     PL_hints |= HINT_BLOCK_SCOPE;
7424     return o;
7425 }
7426
7427 /* if the condition is a literal array or hash
7428    (or @{ ... } etc), make a reference to it.
7429  */
7430 STATIC OP *
7431 S_ref_array_or_hash(pTHX_ OP *cond)
7432 {
7433     if (cond
7434     && (cond->op_type == OP_RV2AV
7435     ||  cond->op_type == OP_PADAV
7436     ||  cond->op_type == OP_RV2HV
7437     ||  cond->op_type == OP_PADHV))
7438
7439         return newUNOP(OP_REFGEN, 0, op_lvalue(cond, OP_REFGEN));
7440
7441     else if(cond
7442     && (cond->op_type == OP_ASLICE
7443     ||  cond->op_type == OP_KVASLICE
7444     ||  cond->op_type == OP_HSLICE
7445     ||  cond->op_type == OP_KVHSLICE)) {
7446
7447         /* anonlist now needs a list from this op, was previously used in
7448          * scalar context */
7449         cond->op_flags &= ~(OPf_WANT_SCALAR | OPf_REF);
7450         cond->op_flags |= OPf_WANT_LIST;
7451
7452         return newANONLIST(op_lvalue(cond, OP_ANONLIST));
7453     }
7454
7455     else
7456         return cond;
7457 }
7458
7459 /* These construct the optree fragments representing given()
7460    and when() blocks.
7461
7462    entergiven and enterwhen are LOGOPs; the op_other pointer
7463    points up to the associated leave op. We need this so we
7464    can put it in the context and make break/continue work.
7465    (Also, of course, pp_enterwhen will jump straight to
7466    op_other if the match fails.)
7467  */
7468
7469 STATIC OP *
7470 S_newGIVWHENOP(pTHX_ OP *cond, OP *block,
7471                    I32 enter_opcode, I32 leave_opcode,
7472                    PADOFFSET entertarg)
7473 {
7474     dVAR;
7475     LOGOP *enterop;
7476     OP *o;
7477
7478     PERL_ARGS_ASSERT_NEWGIVWHENOP;
7479     PERL_UNUSED_ARG(entertarg); /* used to indicate targ of lexical $_ */
7480
7481     enterop = S_alloc_LOGOP(aTHX_ enter_opcode, block, NULL);
7482     enterop->op_targ = 0;
7483     enterop->op_private = 0;
7484
7485     o = newUNOP(leave_opcode, 0, (OP *) enterop);
7486
7487     if (cond) {
7488         /* prepend cond if we have one */
7489         op_sibling_splice((OP*)enterop, NULL, 0, scalar(cond));
7490
7491         o->op_next = LINKLIST(cond);
7492         cond->op_next = (OP *) enterop;
7493     }
7494     else {
7495         /* This is a default {} block */
7496         enterop->op_flags |= OPf_SPECIAL;
7497         o      ->op_flags |= OPf_SPECIAL;
7498
7499         o->op_next = (OP *) enterop;
7500     }
7501
7502     CHECKOP(enter_opcode, enterop); /* Currently does nothing, since
7503                                        entergiven and enterwhen both
7504                                        use ck_null() */
7505
7506     enterop->op_next = LINKLIST(block);
7507     block->op_next = enterop->op_other = o;
7508
7509     return o;
7510 }
7511
7512 /* Does this look like a boolean operation? For these purposes
7513    a boolean operation is:
7514      - a subroutine call [*]
7515      - a logical connective
7516      - a comparison operator
7517      - a filetest operator, with the exception of -s -M -A -C
7518      - defined(), exists() or eof()
7519      - /$re/ or $foo =~ /$re/
7520    
7521    [*] possibly surprising
7522  */
7523 STATIC bool
7524 S_looks_like_bool(pTHX_ const OP *o)
7525 {
7526     PERL_ARGS_ASSERT_LOOKS_LIKE_BOOL;
7527
7528     switch(o->op_type) {
7529         case OP_OR:
7530         case OP_DOR:
7531             return looks_like_bool(cLOGOPo->op_first);
7532
7533         case OP_AND:
7534         {
7535             OP* sibl = OpSIBLING(cLOGOPo->op_first);
7536             ASSUME(sibl);
7537             return (
7538                 looks_like_bool(cLOGOPo->op_first)
7539              && looks_like_bool(sibl));
7540         }
7541
7542         case OP_NULL:
7543         case OP_SCALAR:
7544             return (
7545                 o->op_flags & OPf_KIDS
7546             && looks_like_bool(cUNOPo->op_first));
7547
7548         case OP_ENTERSUB:
7549
7550         case OP_NOT:    case OP_XOR:
7551
7552         case OP_EQ:     case OP_NE:     case OP_LT:
7553         case OP_GT:     case OP_LE:     case OP_GE:
7554
7555         case OP_I_EQ:   case OP_I_NE:   case OP_I_LT:
7556         case OP_I_GT:   case OP_I_LE:   case OP_I_GE:
7557
7558         case OP_SEQ:    case OP_SNE:    case OP_SLT:
7559         case OP_SGT:    case OP_SLE:    case OP_SGE:
7560         
7561         case OP_SMARTMATCH:
7562         
7563         case OP_FTRREAD:  case OP_FTRWRITE: case OP_FTREXEC:
7564         case OP_FTEREAD:  case OP_FTEWRITE: case OP_FTEEXEC:
7565         case OP_FTIS:     case OP_FTEOWNED: case OP_FTROWNED:
7566         case OP_FTZERO:   case OP_FTSOCK:   case OP_FTCHR:
7567         case OP_FTBLK:    case OP_FTFILE:   case OP_FTDIR:
7568         case OP_FTPIPE:   case OP_FTLINK:   case OP_FTSUID:
7569         case OP_FTSGID:   case OP_FTSVTX:   case OP_FTTTY:
7570         case OP_FTTEXT:   case OP_FTBINARY:
7571         
7572         case OP_DEFINED: case OP_EXISTS:
7573         case OP_MATCH:   case OP_EOF:
7574
7575         case OP_FLOP:
7576
7577             return TRUE;
7578         
7579         case OP_CONST:
7580             /* Detect comparisons that have been optimized away */
7581             if (cSVOPo->op_sv == &PL_sv_yes
7582             ||  cSVOPo->op_sv == &PL_sv_no)
7583             
7584                 return TRUE;
7585             else
7586                 return FALSE;
7587
7588         /* FALLTHROUGH */
7589         default:
7590             return FALSE;
7591     }
7592 }
7593
7594 /*
7595 =for apidoc Am|OP *|newGIVENOP|OP *cond|OP *block|PADOFFSET defsv_off
7596
7597 Constructs, checks, and returns an op tree expressing a C<given> block.
7598 C<cond> supplies the expression that will be locally assigned to a lexical
7599 variable, and C<block> supplies the body of the C<given> construct; they
7600 are consumed by this function and become part of the constructed op tree.
7601 C<defsv_off> must be zero (it used to identity the pad slot of lexical $_).
7602
7603 =cut
7604 */
7605
7606 OP *
7607 Perl_newGIVENOP(pTHX_ OP *cond, OP *block, PADOFFSET defsv_off)
7608 {
7609     PERL_ARGS_ASSERT_NEWGIVENOP;
7610     PERL_UNUSED_ARG(defsv_off);
7611
7612     assert(!defsv_off);
7613     return newGIVWHENOP(
7614         ref_array_or_hash(cond),
7615         block,
7616         OP_ENTERGIVEN, OP_LEAVEGIVEN,
7617         0);
7618 }
7619
7620 /*
7621 =for apidoc Am|OP *|newWHENOP|OP *cond|OP *block
7622
7623 Constructs, checks, and returns an op tree expressing a C<when> block.
7624 C<cond> supplies the test expression, and C<block> supplies the block
7625 that will be executed if the test evaluates to true; they are consumed
7626 by this function and become part of the constructed op tree.  C<cond>
7627 will be interpreted DWIMically, often as a comparison against C<$_>,
7628 and may be null to generate a C<default> block.
7629
7630 =cut
7631 */
7632
7633 OP *
7634 Perl_newWHENOP(pTHX_ OP *cond, OP *block)
7635 {
7636     const bool cond_llb = (!cond || looks_like_bool(cond));
7637     OP *cond_op;
7638
7639     PERL_ARGS_ASSERT_NEWWHENOP;
7640
7641     if (cond_llb)
7642         cond_op = cond;
7643     else {
7644         cond_op = newBINOP(OP_SMARTMATCH, OPf_SPECIAL,
7645                 newDEFSVOP(),
7646                 scalar(ref_array_or_hash(cond)));
7647     }
7648     
7649     return newGIVWHENOP(cond_op, block, OP_ENTERWHEN, OP_LEAVEWHEN, 0);
7650 }
7651
7652 /* must not conflict with SVf_UTF8 */
7653 #define CV_CKPROTO_CURSTASH     0x1
7654
7655 void
7656 Perl_cv_ckproto_len_flags(pTHX_ const CV *cv, const GV *gv, const char *p,
7657                     const STRLEN len, const U32 flags)
7658 {
7659     SV *name = NULL, *msg;
7660     const char * cvp = SvROK(cv)
7661                         ? SvTYPE(SvRV_const(cv)) == SVt_PVCV
7662                            ? (cv = (const CV *)SvRV_const(cv), CvPROTO(cv))
7663                            : ""
7664                         : CvPROTO(cv);
7665     STRLEN clen = CvPROTOLEN(cv), plen = len;
7666
7667     PERL_ARGS_ASSERT_CV_CKPROTO_LEN_FLAGS;
7668
7669     if (p == NULL && cvp == NULL)
7670         return;
7671
7672     if (!ckWARN_d(WARN_PROTOTYPE))
7673         return;
7674
7675     if (p && cvp) {
7676         p = S_strip_spaces(aTHX_ p, &plen);
7677         cvp = S_strip_spaces(aTHX_ cvp, &clen);
7678         if ((flags & SVf_UTF8) == SvUTF8(cv)) {
7679             if (plen == clen && memEQ(cvp, p, plen))
7680                 return;
7681         } else {
7682             if (flags & SVf_UTF8) {
7683                 if (bytes_cmp_utf8((const U8 *)cvp, clen, (const U8 *)p, plen) == 0)
7684                     return;
7685             }
7686             else {
7687                 if (bytes_cmp_utf8((const U8 *)p, plen, (const U8 *)cvp, clen) == 0)
7688                     return;
7689             }
7690         }
7691     }
7692
7693     msg = sv_newmortal();
7694
7695     if (gv)
7696     {
7697         if (isGV(gv))
7698             gv_efullname3(name = sv_newmortal(), gv, NULL);
7699         else if (SvPOK(gv) && *SvPVX((SV *)gv) == '&')
7700             name = newSVpvn_flags(SvPVX((SV *)gv)+1, SvCUR(gv)-1, SvUTF8(gv)|SVs_TEMP);
7701         else if (flags & CV_CKPROTO_CURSTASH || SvROK(gv)) {
7702             name = sv_2mortal(newSVhek(HvNAME_HEK(PL_curstash)));
7703             sv_catpvs(name, "::");
7704             if (SvROK(gv)) {
7705                 assert (SvTYPE(SvRV_const(gv)) == SVt_PVCV);
7706                 assert (CvNAMED(SvRV_const(gv)));
7707                 sv_cathek(name, CvNAME_HEK(MUTABLE_CV(SvRV_const(gv))));
7708             }
7709             else sv_catsv(name, (SV *)gv);
7710         }
7711         else name = (SV *)gv;
7712     }
7713     sv_setpvs(msg, "Prototype mismatch:");
7714     if (name)
7715         Perl_sv_catpvf(aTHX_ msg, " sub %"SVf, SVfARG(name));
7716     if (cvp)
7717         Perl_sv_catpvf(aTHX_ msg, " (%"UTF8f")", 
7718             UTF8fARG(SvUTF8(cv),clen,cvp)
7719         );
7720     else
7721         sv_catpvs(msg, ": none");
7722     sv_catpvs(msg, " vs ");
7723     if (p)
7724         Perl_sv_catpvf(aTHX_ msg, "(%"UTF8f")", UTF8fARG(flags & SVf_UTF8,len,p));
7725     else
7726         sv_catpvs(msg, "none");
7727     Perl_warner(aTHX_ packWARN(WARN_PROTOTYPE), "%"SVf, SVfARG(msg));
7728 }
7729
7730 static void const_sv_xsub(pTHX_ CV* cv);
7731 static void const_av_xsub(pTHX_ CV* cv);
7732
7733 /*
7734
7735 =head1 Optree Manipulation Functions
7736
7737 =for apidoc cv_const_sv
7738
7739 If C<cv> is a constant sub eligible for inlining, returns the constant
7740 value returned by the sub.  Otherwise, returns C<NULL>.
7741
7742 Constant subs can be created with C<newCONSTSUB> or as described in
7743 L<perlsub/"Constant Functions">.
7744
7745 =cut
7746 */
7747 SV *
7748 Perl_cv_const_sv(const CV *const cv)
7749 {
7750     SV *sv;
7751     if (!cv)
7752         return NULL;
7753     if (!(SvTYPE(cv) == SVt_PVCV || SvTYPE(cv) == SVt_PVFM))
7754         return NULL;
7755     sv = CvCONST(cv) ? MUTABLE_SV(CvXSUBANY(cv).any_ptr) : NULL;
7756     if (sv && SvTYPE(sv) == SVt_PVAV) return NULL;
7757     return sv;
7758 }
7759
7760 SV *
7761 Perl_cv_const_sv_or_av(const CV * const cv)
7762 {
7763     if (!cv)
7764         return NULL;
7765     if (SvROK(cv)) return SvRV((SV *)cv);
7766     assert (SvTYPE(cv) == SVt_PVCV || SvTYPE(cv) == SVt_PVFM);
7767     return CvCONST(cv) ? MUTABLE_SV(CvXSUBANY(cv).any_ptr) : NULL;
7768 }
7769
7770 /* op_const_sv:  examine an optree to determine whether it's in-lineable.
7771  * Can be called in 2 ways:
7772  *
7773  * !allow_lex
7774  *      look for a single OP_CONST with attached value: return the value
7775  *
7776  * allow_lex && !CvCONST(cv);
7777  *
7778  *      examine the clone prototype, and if contains only a single
7779  *      OP_CONST, return the value; or if it contains a single PADSV ref-
7780  *      erencing an outer lexical, turn on CvCONST to indicate the CV is
7781  *      a candidate for "constizing" at clone time, and return NULL.
7782  */
7783
7784 static SV *
7785 S_op_const_sv(pTHX_ const OP *o, CV *cv, bool allow_lex)
7786 {
7787     SV *sv = NULL;
7788     bool padsv = FALSE;
7789
7790     assert(o);
7791     assert(cv);
7792
7793     for (; o; o = o->op_next) {
7794         const OPCODE type = o->op_type;
7795
7796         if (type == OP_NEXTSTATE || type == OP_LINESEQ
7797              || type == OP_NULL
7798              || type == OP_PUSHMARK)
7799                 continue;
7800         if (type == OP_DBSTATE)
7801                 continue;
7802         if (type == OP_LEAVESUB)
7803             break;
7804         if (sv)
7805             return NULL;
7806         if (type == OP_CONST && cSVOPo->op_sv)
7807             sv = cSVOPo->op_sv;
7808         else if (type == OP_UNDEF && !o->op_private) {
7809             sv = newSV(0);
7810             SAVEFREESV(sv);
7811         }
7812         else if (allow_lex && type == OP_PADSV) {
7813                 if (PAD_COMPNAME_FLAGS(o->op_targ) & PADNAMEt_OUTER)
7814                 {
7815                     sv = &PL_sv_undef; /* an arbitrary non-null value */
7816                     padsv = TRUE;
7817                 }
7818                 else
7819                     return NULL;
7820         }
7821         else {
7822             return NULL;
7823         }
7824     }
7825     if (padsv) {
7826         CvCONST_on(cv);
7827         return NULL;
7828     }
7829     return sv;
7830 }
7831
7832 static bool
7833 S_already_defined(pTHX_ CV *const cv, OP * const block, OP * const o,
7834                         PADNAME * const name, SV ** const const_svp)
7835 {
7836     assert (cv);
7837     assert (o || name);
7838     assert (const_svp);
7839     if ((!block
7840          )) {
7841         if (CvFLAGS(PL_compcv)) {
7842             /* might have had built-in attrs applied */
7843             const bool pureperl = !CvISXSUB(cv) && CvROOT(cv);
7844             if (CvLVALUE(PL_compcv) && ! CvLVALUE(cv) && pureperl
7845              && ckWARN(WARN_MISC))
7846             {
7847                 /* protect against fatal warnings leaking compcv */
7848                 SAVEFREESV(PL_compcv);
7849                 Perl_warner(aTHX_ packWARN(WARN_MISC), "lvalue attribute ignored after the subroutine has been defined");
7850                 SvREFCNT_inc_simple_void_NN(PL_compcv);
7851             }
7852             CvFLAGS(cv) |=
7853                 (CvFLAGS(PL_compcv) & CVf_BUILTIN_ATTRS
7854                   & ~(CVf_LVALUE * pureperl));
7855         }
7856         return FALSE;
7857     }
7858
7859     /* redundant check for speed: */
7860     if (CvCONST(cv) || ckWARN(WARN_REDEFINE)) {
7861         const line_t oldline = CopLINE(PL_curcop);
7862         SV *namesv = o
7863             ? cSVOPo->op_sv
7864             : sv_2mortal(newSVpvn_utf8(
7865                 PadnamePV(name)+1,PadnameLEN(name)-1, PadnameUTF8(name)
7866               ));
7867         if (PL_parser && PL_parser->copline != NOLINE)
7868             /* This ensures that warnings are reported at the first
7869                line of a redefinition, not the last.  */
7870             CopLINE_set(PL_curcop, PL_parser->copline);
7871         /* protect against fatal warnings leaking compcv */
7872         SAVEFREESV(PL_compcv);
7873         report_redefined_cv(namesv, cv, const_svp);
7874         SvREFCNT_inc_simple_void_NN(PL_compcv);
7875         CopLINE_set(PL_curcop, oldline);
7876     }
7877     SAVEFREESV(cv);
7878     return TRUE;
7879 }
7880
7881 CV *
7882 Perl_newMYSUB(pTHX_ I32 floor, OP *o, OP *proto, OP *attrs, OP *block)
7883 {
7884     CV **spot;
7885     SV **svspot;
7886     const char *ps;
7887     STRLEN ps_len = 0; /* init it to avoid false uninit warning from icc */
7888     U32 ps_utf8 = 0;
7889     CV *cv = NULL;
7890     CV *compcv = PL_compcv;
7891     SV *const_sv;
7892     PADNAME *name;
7893     PADOFFSET pax = o->op_targ;
7894     CV *outcv = CvOUTSIDE(PL_compcv);
7895     CV *clonee = NULL;
7896     HEK *hek = NULL;
7897     bool reusable = FALSE;
7898     OP *start = NULL;
7899 #ifdef PERL_DEBUG_READONLY_OPS
7900     OPSLAB *slab = NULL;
7901 #endif
7902
7903     PERL_ARGS_ASSERT_NEWMYSUB;
7904
7905     /* Find the pad slot for storing the new sub.
7906        We cannot use PL_comppad, as it is the pad owned by the new sub.  We
7907        need to look in CvOUTSIDE and find the pad belonging to the enclos-
7908        ing sub.  And then we need to dig deeper if this is a lexical from
7909        outside, as in:
7910            my sub foo; sub { sub foo { } }
7911      */
7912    redo:
7913     name = PadlistNAMESARRAY(CvPADLIST(outcv))[pax];
7914     if (PadnameOUTER(name) && PARENT_PAD_INDEX(name)) {
7915         pax = PARENT_PAD_INDEX(name);
7916         outcv = CvOUTSIDE(outcv);
7917         assert(outcv);
7918         goto redo;
7919     }
7920     svspot =
7921         &PadARRAY(PadlistARRAY(CvPADLIST(outcv))
7922                         [CvDEPTH(outcv) ? CvDEPTH(outcv) : 1])[pax];
7923     spot = (CV **)svspot;
7924
7925     if (!(PL_parser && PL_parser->error_count))
7926         move_proto_attr(&proto, &attrs, (GV *)PadnameSV(name));
7927
7928     if (proto) {
7929         assert(proto->op_type == OP_CONST);
7930         ps = SvPV_const(((SVOP*)proto)->op_sv, ps_len);
7931         ps_utf8 = SvUTF8(((SVOP*)proto)->op_sv);
7932     }
7933     else
7934         ps = NULL;
7935
7936     if (proto)
7937         SAVEFREEOP(proto);
7938     if (attrs)
7939         SAVEFREEOP(attrs);
7940
7941     if (PL_parser && PL_parser->error_count) {
7942         op_free(block);
7943         SvREFCNT_dec(PL_compcv);
7944         PL_compcv = 0;
7945         goto done;
7946     }
7947
7948     if (CvDEPTH(outcv) && CvCLONE(compcv)) {
7949         cv = *spot;
7950         svspot = (SV **)(spot = &clonee);
7951     }
7952     else if (PadnameIsSTATE(name) || CvDEPTH(outcv))
7953         cv = *spot;
7954     else {
7955         assert (SvTYPE(*spot) == SVt_PVCV);
7956         if (CvNAMED(*spot))
7957             hek = CvNAME_HEK(*spot);
7958         else {
7959             dVAR;
7960             U32 hash;
7961             PERL_HASH(hash, PadnamePV(name)+1, PadnameLEN(name)-1);
7962             CvNAME_HEK_set(*spot, hek =
7963                 share_hek(
7964                     PadnamePV(name)+1,
7965                     (PadnameLEN(name)-1) * (PadnameUTF8(name) ? -1 : 1),
7966                     hash
7967                 )
7968             );
7969             CvLEXICAL_on(*spot);
7970         }
7971         cv = PadnamePROTOCV(name);
7972         svspot = (SV **)(spot = &PadnamePROTOCV(name));
7973     }
7974
7975     if (block) {
7976         /* This makes sub {}; work as expected.  */
7977         if (block->op_type == OP_STUB) {
7978             const line_t l = PL_parser->copline;
7979             op_free(block);
7980             block = newSTATEOP(0, NULL, 0);
7981             PL_parser->copline = l;
7982         }
7983         block = CvLVALUE(compcv)
7984              || (cv && CvLVALUE(cv) && !CvROOT(cv) && !CvXSUB(cv))
7985                    ? newUNOP(OP_LEAVESUBLV, 0,
7986                              op_lvalue(scalarseq(block), OP_LEAVESUBLV))
7987                    : newUNOP(OP_LEAVESUB, 0, scalarseq(block));
7988         start = LINKLIST(block);
7989         block->op_next = 0;
7990         if (ps && !*ps && !attrs && !CvLVALUE(compcv))
7991             const_sv = S_op_const_sv(aTHX_ start, compcv, FALSE);
7992         else
7993             const_sv = NULL;
7994     }
7995     else
7996         const_sv = NULL;
7997
7998     if (cv) {
7999         const bool exists = CvROOT(cv) || CvXSUB(cv);
8000
8001         /* if the subroutine doesn't exist and wasn't pre-declared
8002          * with a prototype, assume it will be AUTOLOADed,
8003          * skipping the prototype check
8004          */
8005         if (exists || SvPOK(cv))
8006             cv_ckproto_len_flags(cv, (GV *)PadnameSV(name), ps, ps_len,
8007                                  ps_utf8);
8008         /* already defined? */
8009         if (exists) {
8010             if (S_already_defined(aTHX_ cv,block,NULL,name,&const_sv))
8011                 cv = NULL;
8012             else {
8013                 if (attrs) goto attrs;
8014                 /* just a "sub foo;" when &foo is already defined */
8015                 SAVEFREESV(compcv);
8016                 goto done;
8017             }
8018         }
8019         else if (CvDEPTH(outcv) && CvCLONE(compcv)) {
8020             cv = NULL;
8021             reusable = TRUE;
8022         }
8023     }
8024     if (const_sv) {
8025         SvREFCNT_inc_simple_void_NN(const_sv);
8026         SvFLAGS(const_sv) |= SVs_PADTMP;
8027         if (cv) {
8028             assert(!CvROOT(cv) && !CvCONST(cv));
8029             cv_forget_slab(cv);
8030         }
8031         else {
8032             cv = MUTABLE_CV(newSV_type(SVt_PVCV));
8033             CvFILE_set_from_cop(cv, PL_curcop);
8034             CvSTASH_set(cv, PL_curstash);
8035             *spot = cv;
8036         }
8037         sv_setpvs(MUTABLE_SV(cv), "");  /* prototype is "" */
8038         CvXSUBANY(cv).any_ptr = const_sv;
8039         CvXSUB(cv) = const_sv_xsub;
8040         CvCONST_on(cv);
8041         CvISXSUB_on(cv);
8042         PoisonPADLIST(cv);
8043         CvFLAGS(cv) |= CvMETHOD(compcv);
8044         op_free(block);
8045         SvREFCNT_dec(compcv);
8046         PL_compcv = NULL;
8047         goto setname;
8048     }
8049     /* Checking whether outcv is CvOUTSIDE(compcv) is not sufficient to
8050        determine whether this sub definition is in the same scope as its
8051        declaration.  If this sub definition is inside an inner named pack-
8052        age sub (my sub foo; sub bar { sub foo { ... } }), outcv points to
8053        the package sub.  So check PadnameOUTER(name) too.
8054      */
8055     if (outcv == CvOUTSIDE(compcv) && !PadnameOUTER(name)) { 
8056         assert(!CvWEAKOUTSIDE(compcv));
8057         SvREFCNT_dec(CvOUTSIDE(compcv));
8058         CvWEAKOUTSIDE_on(compcv);
8059     }
8060     /* XXX else do we have a circular reference? */
8061     if (cv) {   /* must reuse cv in case stub is referenced elsewhere */
8062         /* transfer PL_compcv to cv */
8063         if (block
8064         ) {
8065             cv_flags_t preserved_flags =
8066                 CvFLAGS(cv) & (CVf_BUILTIN_ATTRS|CVf_NAMED);
8067             PADLIST *const temp_padl = CvPADLIST(cv);
8068             CV *const temp_cv = CvOUTSIDE(cv);
8069             const cv_flags_t other_flags =
8070                 CvFLAGS(cv) & (CVf_SLABBED|CVf_WEAKOUTSIDE);
8071             OP * const cvstart = CvSTART(cv);
8072
8073             SvPOK_off(cv);
8074             CvFLAGS(cv) =
8075                 CvFLAGS(compcv) | preserved_flags;
8076             CvOUTSIDE(cv) = CvOUTSIDE(compcv);
8077             CvOUTSIDE_SEQ(cv) = CvOUTSIDE_SEQ(compcv);
8078             CvPADLIST_set(cv, CvPADLIST(compcv));
8079             CvOUTSIDE(compcv) = temp_cv;
8080             CvPADLIST_set(compcv, temp_padl);
8081             CvSTART(cv) = CvSTART(compcv);
8082             CvSTART(compcv) = cvstart;
8083             CvFLAGS(compcv) &= ~(CVf_SLABBED|CVf_WEAKOUTSIDE);
8084             CvFLAGS(compcv) |= other_flags;
8085
8086             if (CvFILE(cv) && CvDYNFILE(cv)) {
8087                 Safefree(CvFILE(cv));
8088             }
8089
8090             /* inner references to compcv must be fixed up ... */
8091             pad_fixup_inner_anons(CvPADLIST(cv), compcv, cv);
8092             if (PERLDB_INTER)/* Advice debugger on the new sub. */
8093               ++PL_sub_generation;
8094         }
8095         else {
8096             /* Might have had built-in attributes applied -- propagate them. */
8097             CvFLAGS(cv) |= (CvFLAGS(compcv) & CVf_BUILTIN_ATTRS);
8098         }
8099         /* ... before we throw it away */
8100         SvREFCNT_dec(compcv);
8101         PL_compcv = compcv = cv;
8102     }
8103     else {
8104         cv = compcv;
8105         *spot = cv;
8106     }
8107    setname:
8108     CvLEXICAL_on(cv);
8109     if (!CvNAME_HEK(cv)) {
8110         if (hek) (void)share_hek_hek(hek);
8111         else {
8112             dVAR;
8113             U32 hash;
8114             PERL_HASH(hash, PadnamePV(name)+1, PadnameLEN(name)-1);
8115             hek = share_hek(PadnamePV(name)+1,
8116                       (PadnameLEN(name)-1) * (PadnameUTF8(name) ? -1 : 1),
8117                       hash);
8118         }
8119         CvNAME_HEK_set(cv, hek);
8120     }
8121     if (const_sv) goto clone;
8122
8123     CvFILE_set_from_cop(cv, PL_curcop);
8124     CvSTASH_set(cv, PL_curstash);
8125
8126     if (ps) {
8127         sv_setpvn(MUTABLE_SV(cv), ps, ps_len);
8128         if ( ps_utf8 ) SvUTF8_on(MUTABLE_SV(cv));
8129     }
8130
8131     if (!block)
8132         goto attrs;
8133
8134     /* If we assign an optree to a PVCV, then we've defined a subroutine that
8135        the debugger could be able to set a breakpoint in, so signal to
8136        pp_entereval that it should not throw away any saved lines at scope
8137        exit.  */
8138        
8139     PL_breakable_sub_gen++;
8140     CvROOT(cv) = block;
8141     CvROOT(cv)->op_private |= OPpREFCOUNTED;
8142     OpREFCNT_set(CvROOT(cv), 1);
8143     /* The cv no longer needs to hold a refcount on the slab, as CvROOT
8144        itself has a refcount. */
8145     CvSLABBED_off(cv);
8146     OpslabREFCNT_dec_padok((OPSLAB *)CvSTART(cv));
8147 #ifdef PERL_DEBUG_READONLY_OPS
8148     slab = (OPSLAB *)CvSTART(cv);
8149 #endif
8150     CvSTART(cv) = start;
8151     CALL_PEEP(start);
8152     finalize_optree(CvROOT(cv));
8153     S_prune_chain_head(&CvSTART(cv));
8154
8155     /* now that optimizer has done its work, adjust pad values */
8156
8157     pad_tidy(CvCLONE(cv) ? padtidy_SUBCLONE : padtidy_SUB);
8158
8159   attrs:
8160     if (attrs) {
8161         /* Need to do a C<use attributes $stash_of_cv,\&cv,@attrs>. */
8162         apply_attrs(PL_curstash, MUTABLE_SV(cv), attrs);
8163     }
8164
8165     if (block) {
8166         if (PERLDB_SUBLINE && PL_curstash != PL_debstash) {
8167             SV * const tmpstr = sv_newmortal();
8168             GV * const db_postponed = gv_fetchpvs("DB::postponed",
8169                                                   GV_ADDMULTI, SVt_PVHV);
8170             HV *hv;
8171             SV * const sv = Perl_newSVpvf(aTHX_ "%s:%ld-%ld",
8172                                           CopFILE(PL_curcop),
8173                                           (long)PL_subline,
8174                                           (long)CopLINE(PL_curcop));
8175             if (HvNAME_HEK(PL_curstash)) {
8176                 sv_sethek(tmpstr, HvNAME_HEK(PL_curstash));
8177                 sv_catpvs(tmpstr, "::");
8178             }
8179             else sv_setpvs(tmpstr, "__ANON__::");
8180             sv_catpvn_flags(tmpstr, PadnamePV(name)+1, PadnameLEN(name)-1,
8181                             PadnameUTF8(name) ? SV_CATUTF8 : SV_CATBYTES);
8182             (void)hv_store(GvHV(PL_DBsub), SvPVX_const(tmpstr),
8183                     SvUTF8(tmpstr) ? -(I32)SvCUR(tmpstr) : (I32)SvCUR(tmpstr), sv, 0);
8184             hv = GvHVn(db_postponed);
8185             if (HvTOTALKEYS(hv) > 0 && hv_exists(hv, SvPVX_const(tmpstr), SvUTF8(tmpstr) ? -(I32)SvCUR(tmpstr) : (I32)SvCUR(tmpstr))) {
8186                 CV * const pcv = GvCV(db_postponed);
8187                 if (pcv) {
8188                     dSP;
8189                     PUSHMARK(SP);
8190                     XPUSHs(tmpstr);
8191                     PUTBACK;
8192                     call_sv(MUTABLE_SV(pcv), G_DISCARD);
8193                 }
8194             }
8195         }
8196     }
8197
8198   clone:
8199     if (clonee) {
8200         assert(CvDEPTH(outcv));
8201         spot = (CV **)
8202             &PadARRAY(PadlistARRAY(CvPADLIST(outcv))[CvDEPTH(outcv)])[pax];
8203         if (reusable) cv_clone_into(clonee, *spot);
8204         else *spot = cv_clone(clonee);
8205         SvREFCNT_dec_NN(clonee);
8206         cv = *spot;
8207     }
8208     if (CvDEPTH(outcv) && !reusable && PadnameIsSTATE(name)) {
8209         PADOFFSET depth = CvDEPTH(outcv);
8210         while (--depth) {
8211             SV *oldcv;
8212             svspot = &PadARRAY(PadlistARRAY(CvPADLIST(outcv))[depth])[pax];
8213             oldcv = *svspot;
8214             *svspot = SvREFCNT_inc_simple_NN(cv);
8215             SvREFCNT_dec(oldcv);
8216         }
8217     }
8218
8219   done:
8220     if (PL_parser)
8221         PL_parser->copline = NOLINE;
8222     LEAVE_SCOPE(floor);
8223 #ifdef PERL_DEBUG_READONLY_OPS
8224     if (slab)
8225         Slab_to_ro(slab);
8226 #endif
8227     op_free(o);
8228     return cv;
8229 }
8230
8231 /* _x = extended */
8232 CV *
8233 Perl_newATTRSUB_x(pTHX_ I32 floor, OP *o, OP *proto, OP *attrs,
8234                             OP *block, bool o_is_gv)
8235 {
8236     GV *gv;
8237     const char *ps;
8238     STRLEN ps_len = 0; /* init it to avoid false uninit warning from icc */
8239     U32 ps_utf8 = 0;
8240     CV *cv = NULL;
8241     SV *const_sv;
8242     const bool ec = PL_parser && PL_parser->error_count;
8243     /* If the subroutine has no body, no attributes, and no builtin attributes
8244        then it's just a sub declaration, and we may be able to get away with
8245        storing with a placeholder scalar in the symbol table, rather than a
8246        full CV.  If anything is present then it will take a full CV to
8247        store it.  */
8248     const I32 gv_fetch_flags
8249         = ec ? GV_NOADD_NOINIT :
8250         (block || attrs || (CvFLAGS(PL_compcv) & CVf_BUILTIN_ATTRS))
8251         ? GV_ADDMULTI : GV_ADDMULTI | GV_NOINIT;
8252     STRLEN namlen = 0;
8253     const char * const name =
8254          o ? SvPV_const(o_is_gv ? (SV *)o : cSVOPo->op_sv, namlen) : NULL;
8255     bool has_name;
8256     bool name_is_utf8 = o && !o_is_gv && SvUTF8(cSVOPo->op_sv);
8257     bool evanescent = FALSE;
8258     OP *start = NULL;
8259 #ifdef PERL_DEBUG_READONLY_OPS
8260     OPSLAB *slab = NULL;
8261 #endif
8262
8263     if (o_is_gv) {
8264         gv = (GV*)o;
8265         o = NULL;
8266         has_name = TRUE;
8267     } else if (name) {
8268         /* Try to optimise and avoid creating a GV.  Instead, the CV’s name
8269            hek and CvSTASH pointer together can imply the GV.  If the name
8270            contains a package name, then GvSTASH(CvGV(cv)) may differ from
8271            CvSTASH, so forego the optimisation if we find any.
8272            Also, we may be called from load_module at run time, so
8273            PL_curstash (which sets CvSTASH) may not point to the stash the
8274            sub is stored in.  */
8275         const I32 flags =
8276            ec ? GV_NOADD_NOINIT
8277               :   PL_curstash != CopSTASH(PL_curcop)
8278                || memchr(name, ':', namlen) || memchr(name, '\'', namlen)
8279                     ? gv_fetch_flags
8280                     : GV_ADDMULTI | GV_NOINIT | GV_NOTQUAL;
8281         gv = gv_fetchsv(cSVOPo->op_sv, flags, SVt_PVCV);
8282         has_name = TRUE;
8283     } else if (PERLDB_NAMEANON && CopLINE(PL_curcop)) {
8284         SV * const sv = sv_newmortal();
8285         Perl_sv_setpvf(aTHX_ sv, "%s[%s:%"IVdf"]",
8286                        PL_curstash ? "__ANON__" : "__ANON__::__ANON__",
8287                        CopFILE(PL_curcop), (IV)CopLINE(PL_curcop));
8288         gv = gv_fetchsv(sv, gv_fetch_flags, SVt_PVCV);
8289         has_name = TRUE;
8290     } else if (PL_curstash) {
8291         gv = gv_fetchpvs("__ANON__", gv_fetch_flags, SVt_PVCV);
8292         has_name = FALSE;
8293     } else {
8294         gv = gv_fetchpvs("__ANON__::__ANON__", gv_fetch_flags, SVt_PVCV);
8295         has_name = FALSE;
8296     }
8297     if (!ec) {
8298         if (isGV(gv)) {
8299             move_proto_attr(&proto, &attrs, gv);
8300         } else {
8301             assert(cSVOPo);
8302             move_proto_attr(&proto, &attrs, (GV *)cSVOPo->op_sv);
8303         }
8304     }
8305
8306     if (proto) {
8307         assert(proto->op_type == OP_CONST);
8308         ps = SvPV_const(((SVOP*)proto)->op_sv, ps_len);
8309         ps_utf8 = SvUTF8(((SVOP*)proto)->op_sv);
8310     }
8311     else
8312         ps = NULL;
8313
8314     if (o)
8315         SAVEFREEOP(o);
8316     if (proto)
8317         SAVEFREEOP(proto);
8318     if (attrs)
8319         SAVEFREEOP(attrs);
8320
8321     if (ec) {
8322         op_free(block);
8323         if (name) SvREFCNT_dec(PL_compcv);
8324         else cv = PL_compcv;
8325         PL_compcv = 0;
8326         if (name && block) {
8327             const char *s = strrchr(name, ':');
8328             s = s ? s+1 : name;
8329             if (strEQ(s, "BEGIN")) {
8330                 if (PL_in_eval & EVAL_KEEPERR)
8331                     Perl_croak_nocontext("BEGIN not safe after errors--compilation aborted");
8332                 else {
8333                     SV * const errsv = ERRSV;
8334                     /* force display of errors found but not reported */
8335                     sv_catpvs(errsv, "BEGIN not safe after errors--compilation aborted");
8336                     Perl_croak_nocontext("%"SVf, SVfARG(errsv));
8337                 }
8338             }
8339         }
8340         goto done;
8341     }
8342
8343     if (!block && SvTYPE(gv) != SVt_PVGV) {
8344       /* If we are not defining a new sub and the existing one is not a
8345          full GV + CV... */
8346       if (attrs || (CvFLAGS(PL_compcv) & CVf_BUILTIN_ATTRS)) {
8347         /* We are applying attributes to an existing sub, so we need it
8348            upgraded if it is a constant.  */
8349         if (SvROK(gv) && SvTYPE(SvRV(gv)) != SVt_PVCV)
8350             gv_init_pvn(gv, PL_curstash, name, namlen,
8351                         SVf_UTF8 * name_is_utf8);
8352       }
8353       else {                    /* Maybe prototype now, and had at maximum
8354                                    a prototype or const/sub ref before.  */
8355         if (SvTYPE(gv) > SVt_NULL) {
8356             cv_ckproto_len_flags((const CV *)gv,
8357                                  o ? (const GV *)cSVOPo->op_sv : NULL, ps,
8358                                  ps_len, ps_utf8);
8359         }
8360         if (!SvROK(gv)) {
8361           if (ps) {
8362             sv_setpvn(MUTABLE_SV(gv), ps, ps_len);
8363             if ( ps_utf8 ) SvUTF8_on(MUTABLE_SV(gv));
8364           }
8365           else
8366             sv_setiv(MUTABLE_SV(gv), -1);
8367         }
8368
8369         SvREFCNT_dec(PL_compcv);
8370         cv = PL_compcv = NULL;
8371         goto done;
8372       }
8373     }
8374
8375     cv = (!name || (isGV(gv) && GvCVGEN(gv)))
8376         ? NULL
8377         : isGV(gv)
8378             ? GvCV(gv)
8379             : SvROK(gv) && SvTYPE(SvRV(gv)) == SVt_PVCV
8380                 ? (CV *)SvRV(gv)
8381                 : NULL;
8382
8383     if (block) {
8384         /* This makes sub {}; work as expected.  */
8385         if (block->op_type == OP_STUB) {
8386             const line_t l = PL_parser->copline;
8387             op_free(block);
8388             block = newSTATEOP(0, NULL, 0);
8389             PL_parser->copline = l;
8390         }
8391         block = CvLVALUE(PL_compcv)
8392              || (cv && CvLVALUE(cv) && !CvROOT(cv) && !CvXSUB(cv)
8393                     && (!isGV(gv) || !GvASSUMECV(gv)))
8394                    ? newUNOP(OP_LEAVESUBLV, 0,
8395                              op_lvalue(scalarseq(block), OP_LEAVESUBLV))
8396                    : newUNOP(OP_LEAVESUB, 0, scalarseq(block));
8397         start = LINKLIST(block);
8398         block->op_next = 0;
8399         if (ps && !*ps && !attrs && !CvLVALUE(PL_compcv))
8400             const_sv =
8401                 S_op_const_sv(aTHX_ start, PL_compcv,
8402                                         cBOOL(CvCLONE(PL_compcv)));
8403         else
8404             const_sv = NULL;
8405     }
8406     else
8407         const_sv = NULL;
8408
8409     if (SvPOK(gv) || (SvROK(gv) && SvTYPE(SvRV(gv)) != SVt_PVCV)) {
8410         cv_ckproto_len_flags((const CV *)gv,
8411                              o ? (const GV *)cSVOPo->op_sv : NULL, ps,
8412                              ps_len, ps_utf8|CV_CKPROTO_CURSTASH);
8413         if (SvROK(gv)) {
8414             /* All the other code for sub redefinition warnings expects the
8415                clobbered sub to be a CV.  Instead of making all those code
8416                paths more complex, just inline the RV version here.  */
8417             const line_t oldline = CopLINE(PL_curcop);
8418             assert(IN_PERL_COMPILETIME);
8419             if (PL_parser && PL_parser->copline != NOLINE)
8420                 /* This ensures that warnings are reported at the first
8421                    line of a redefinition, not the last.  */
8422                 CopLINE_set(PL_curcop, PL_parser->copline);
8423             /* protect against fatal warnings leaking compcv */
8424             SAVEFREESV(PL_compcv);
8425
8426             if (ckWARN(WARN_REDEFINE)
8427              || (  ckWARN_d(WARN_REDEFINE)
8428                 && (  !const_sv || SvRV(gv) == const_sv
8429                    || sv_cmp(SvRV(gv), const_sv)  )))
8430                 Perl_warner(aTHX_ packWARN(WARN_REDEFINE),
8431                           "Constant subroutine %"SVf" redefined",
8432                           SVfARG(cSVOPo->op_sv));
8433
8434             SvREFCNT_inc_simple_void_NN(PL_compcv);
8435             CopLINE_set(PL_curcop, oldline);
8436             SvREFCNT_dec(SvRV(gv));
8437         }
8438     }
8439
8440     if (cv) {
8441         const bool exists = CvROOT(cv) || CvXSUB(cv);
8442
8443         /* if the subroutine doesn't exist and wasn't pre-declared
8444          * with a prototype, assume it will be AUTOLOADed,
8445          * skipping the prototype check
8446          */
8447         if (exists || SvPOK(cv))
8448             cv_ckproto_len_flags(cv, gv, ps, ps_len, ps_utf8);
8449         /* already defined (or promised)? */
8450         if (exists || (isGV(gv) && GvASSUMECV(gv))) {
8451             if (S_already_defined(aTHX_ cv, block, o, NULL, &const_sv))
8452                 cv = NULL;
8453             else {
8454                 if (attrs) goto attrs;
8455                 /* just a "sub foo;" when &foo is already defined */
8456                 SAVEFREESV(PL_compcv);
8457                 goto done;
8458             }
8459         }
8460     }
8461     if (const_sv) {
8462         SvREFCNT_inc_simple_void_NN(const_sv);
8463         SvFLAGS(const_sv) |= SVs_PADTMP;
8464         if (cv) {
8465             assert(!CvROOT(cv) && !CvCONST(cv));
8466             cv_forget_slab(cv);
8467             sv_setpvs(MUTABLE_SV(cv), "");  /* prototype is "" */
8468             CvXSUBANY(cv).any_ptr = const_sv;
8469             CvXSUB(cv) = const_sv_xsub;
8470             CvCONST_on(cv);
8471             CvISXSUB_on(cv);
8472             PoisonPADLIST(cv);
8473             CvFLAGS(cv) |= CvMETHOD(PL_compcv);
8474         }
8475         else {
8476             if (isGV(gv) || CvMETHOD(PL_compcv)) {
8477                 if (name && isGV(gv))
8478                     GvCV_set(gv, NULL);
8479                 cv = newCONSTSUB_flags(
8480                     NULL, name, namlen, name_is_utf8 ? SVf_UTF8 : 0,
8481                     const_sv
8482                 );
8483                 CvFLAGS(cv) |= CvMETHOD(PL_compcv);
8484             }
8485             else {
8486                 if (!SvROK(gv)) {
8487                     SV_CHECK_THINKFIRST_COW_DROP((SV *)gv);
8488                     prepare_SV_for_RV((SV *)gv);
8489                     SvOK_off((SV *)gv);
8490                     SvROK_on(gv);
8491                 }
8492                 SvRV_set(gv, const_sv);
8493             }
8494         }
8495         op_free(block);
8496         SvREFCNT_dec(PL_compcv);
8497         PL_compcv = NULL;
8498         goto done;
8499     }
8500     if (cv) {                           /* must reuse cv if autoloaded */
8501         /* transfer PL_compcv to cv */
8502         if (block
8503         ) {
8504             cv_flags_t existing_builtin_attrs = CvFLAGS(cv) & CVf_BUILTIN_ATTRS;
8505             PADLIST *const temp_av = CvPADLIST(cv);
8506             CV *const temp_cv = CvOUTSIDE(cv);
8507             const cv_flags_t other_flags =
8508                 CvFLAGS(cv) & (CVf_SLABBED|CVf_WEAKOUTSIDE);
8509             OP * const cvstart = CvSTART(cv);
8510
8511             if (isGV(gv)) {
8512                 CvGV_set(cv,gv);
8513                 assert(!CvCVGV_RC(cv));
8514                 assert(CvGV(cv) == gv);
8515             }
8516             else {
8517                 dVAR;
8518                 U32 hash;
8519                 PERL_HASH(hash, name, namlen);
8520                 CvNAME_HEK_set(cv,
8521                                share_hek(name,
8522                                          name_is_utf8
8523                                             ? -(SSize_t)namlen
8524                                             :  (SSize_t)namlen,
8525                                          hash));
8526             }
8527
8528             SvPOK_off(cv);
8529             CvFLAGS(cv) = CvFLAGS(PL_compcv) | existing_builtin_attrs
8530                                              | CvNAMED(cv);
8531             CvOUTSIDE(cv) = CvOUTSIDE(PL_compcv);
8532             CvOUTSIDE_SEQ(cv) = CvOUTSIDE_SEQ(PL_compcv);
8533             CvPADLIST_set(cv,CvPADLIST(PL_compcv));
8534             CvOUTSIDE(PL_compcv) = temp_cv;
8535             CvPADLIST_set(PL_compcv, temp_av);
8536             CvSTART(cv) = CvSTART(PL_compcv);
8537             CvSTART(PL_compcv) = cvstart;
8538             CvFLAGS(PL_compcv) &= ~(CVf_SLABBED|CVf_WEAKOUTSIDE);
8539             CvFLAGS(PL_compcv) |= other_flags;
8540
8541             if (CvFILE(cv) && CvDYNFILE(cv)) {
8542                 Safefree(CvFILE(cv));
8543     }
8544             CvFILE_set_from_cop(cv, PL_curcop);
8545             CvSTASH_set(cv, PL_curstash);
8546
8547             /* inner references to PL_compcv must be fixed up ... */
8548             pad_fixup_inner_anons(CvPADLIST(cv), PL_compcv, cv);
8549             if (PERLDB_INTER)/* Advice debugger on the new sub. */
8550               ++PL_sub_generation;
8551         }
8552         else {
8553             /* Might have had built-in attributes applied -- propagate them. */
8554             CvFLAGS(cv) |= (CvFLAGS(PL_compcv) & CVf_BUILTIN_ATTRS);
8555         }
8556         /* ... before we throw it away */
8557         SvREFCNT_dec(PL_compcv);
8558         PL_compcv = cv;
8559     }
8560     else {
8561         cv = PL_compcv;
8562         if (name && isGV(gv)) {
8563             GvCV_set(gv, cv);
8564             GvCVGEN(gv) = 0;
8565             if (HvENAME_HEK(GvSTASH(gv)))
8566                 /* sub Foo::bar { (shift)+1 } */
8567                 gv_method_changed(gv);
8568         }
8569         else if (name) {
8570             if (!SvROK(gv)) {
8571                 SV_CHECK_THINKFIRST_COW_DROP((SV *)gv);
8572                 prepare_SV_for_RV((SV *)gv);
8573                 SvOK_off((SV *)gv);
8574                 SvROK_on(gv);
8575             }
8576             SvRV_set(gv, (SV *)cv);
8577         }
8578     }
8579     if (!CvHASGV(cv)) {
8580         if (isGV(gv)) CvGV_set(cv, gv);
8581         else {
8582             dVAR;
8583             U32 hash;
8584             PERL_HASH(hash, name, namlen);
8585             CvNAME_HEK_set(cv, share_hek(name,
8586                                          name_is_utf8
8587                                             ? -(SSize_t)namlen
8588                                             :  (SSize_t)namlen,
8589                                          hash));
8590         }
8591         CvFILE_set_from_cop(cv, PL_curcop);
8592         CvSTASH_set(cv, PL_curstash);
8593     }
8594
8595     if (ps) {
8596         sv_setpvn(MUTABLE_SV(cv), ps, ps_len);
8597         if ( ps_utf8 ) SvUTF8_on(MUTABLE_SV(cv));
8598     }
8599
8600     if (!block)
8601         goto attrs;
8602
8603     /* If we assign an optree to a PVCV, then we've defined a subroutine that
8604        the debugger could be able to set a breakpoint in, so signal to
8605        pp_entereval that it should not throw away any saved lines at scope
8606        exit.  */
8607        
8608     PL_breakable_sub_gen++;
8609     CvROOT(cv) = block;
8610     CvROOT(cv)->op_private |= OPpREFCOUNTED;
8611     OpREFCNT_set(CvROOT(cv), 1);
8612     /* The cv no longer needs to hold a refcount on the slab, as CvROOT
8613        itself has a refcount. */
8614     CvSLABBED_off(cv);
8615     OpslabREFCNT_dec_padok((OPSLAB *)CvSTART(cv));
8616 #ifdef PERL_DEBUG_READONLY_OPS
8617     slab = (OPSLAB *)CvSTART(cv);
8618 #endif
8619     CvSTART(cv) = start;
8620     CALL_PEEP(start);
8621     finalize_optree(CvROOT(cv));
8622     S_prune_chain_head(&CvSTART(cv));
8623
8624     /* now that optimizer has done its work, adjust pad values */
8625
8626     pad_tidy(CvCLONE(cv) ? padtidy_SUBCLONE : padtidy_SUB);
8627
8628   attrs:
8629     if (attrs) {
8630         /* Need to do a C<use attributes $stash_of_cv,\&cv,@attrs>. */
8631         HV *stash = name && !CvNAMED(cv) && GvSTASH(CvGV(cv))
8632                         ? GvSTASH(CvGV(cv))
8633                         : PL_curstash;
8634         if (!name) SAVEFREESV(cv);
8635         apply_attrs(stash, MUTABLE_SV(cv), attrs);
8636         if (!name) SvREFCNT_inc_simple_void_NN(cv);
8637     }
8638
8639     if (block && has_name) {
8640         if (PERLDB_SUBLINE && PL_curstash != PL_debstash) {
8641             SV * const tmpstr = cv_name(cv,NULL,0);
8642             GV * const db_postponed = gv_fetchpvs("DB::postponed",
8643                                                   GV_ADDMULTI, SVt_PVHV);
8644             HV *hv;
8645             SV * const sv = Perl_newSVpvf(aTHX_ "%s:%ld-%ld",
8646                                           CopFILE(PL_curcop),
8647                                           (long)PL_subline,
8648                                           (long)CopLINE(PL_curcop));
8649             (void)hv_store(GvHV(PL_DBsub), SvPVX_const(tmpstr),
8650                     SvUTF8(tmpstr) ? -(I32)SvCUR(tmpstr) : (I32)SvCUR(tmpstr), sv, 0);
8651             hv = GvHVn(db_postponed);
8652             if (HvTOTALKEYS(hv) > 0 && hv_exists(hv, SvPVX_const(tmpstr), SvUTF8(tmpstr) ? -(I32)SvCUR(tmpstr) : (I32)SvCUR(tmpstr))) {
8653                 CV * const pcv = GvCV(db_postponed);
8654                 if (pcv) {
8655                     dSP;
8656                     PUSHMARK(SP);
8657                     XPUSHs(tmpstr);
8658                     PUTBACK;
8659                     call_sv(MUTABLE_SV(pcv), G_DISCARD);
8660                 }
8661             }
8662         }
8663
8664         if (name) {
8665             if (PL_parser && PL_parser->error_count)
8666                 clear_special_blocks(name, gv, cv);
8667             else
8668                 evanescent =
8669                     process_special_blocks(floor, name, gv, cv);
8670         }
8671     }
8672
8673   done:
8674     if (PL_parser)
8675         PL_parser->copline = NOLINE;
8676     LEAVE_SCOPE(floor);
8677     if (!evanescent) {
8678 #ifdef PERL_DEBUG_READONLY_OPS
8679       if (slab)
8680         Slab_to_ro(slab);
8681 #endif
8682       if (cv && name && CvOUTSIDE(cv) && !CvEVAL(CvOUTSIDE(cv)))
8683         pad_add_weakref(cv);
8684     }
8685     return cv;
8686 }
8687
8688 STATIC void
8689 S_clear_special_blocks(pTHX_ const char *const fullname,
8690                        GV *const gv, CV *const cv) {
8691     const char *colon;
8692     const char *name;
8693
8694     PERL_ARGS_ASSERT_CLEAR_SPECIAL_BLOCKS;
8695
8696     colon = strrchr(fullname,':');
8697     name = colon ? colon + 1 : fullname;
8698
8699     if ((*name == 'B' && strEQ(name, "BEGIN"))
8700         || (*name == 'E' && strEQ(name, "END"))
8701         || (*name == 'U' && strEQ(name, "UNITCHECK"))
8702         || (*name == 'C' && strEQ(name, "CHECK"))
8703         || (*name == 'I' && strEQ(name, "INIT"))) {
8704         if (!isGV(gv)) {
8705             (void)CvGV(cv);
8706             assert(isGV(gv));
8707         }
8708         GvCV_set(gv, NULL);
8709         SvREFCNT_dec_NN(MUTABLE_SV(cv));
8710     }
8711 }
8712
8713 /* Returns true if the sub has been freed.  */
8714 STATIC bool
8715 S_process_special_blocks(pTHX_ I32 floor, const char *const fullname,
8716                          GV *const gv,
8717                          CV *const cv)
8718 {
8719     const char *const colon = strrchr(fullname,':');
8720     const char *const name = colon ? colon + 1 : fullname;
8721
8722     PERL_ARGS_ASSERT_PROCESS_SPECIAL_BLOCKS;
8723
8724     if (*name == 'B') {
8725         if (strEQ(name, "BEGIN")) {
8726             const I32 oldscope = PL_scopestack_ix;
8727             dSP;
8728             (void)CvGV(cv);
8729             if (floor) LEAVE_SCOPE(floor);
8730             ENTER;
8731             PUSHSTACKi(PERLSI_REQUIRE);
8732             SAVECOPFILE(&PL_compiling);
8733             SAVECOPLINE(&PL_compiling);
8734             SAVEVPTR(PL_curcop);
8735
8736             DEBUG_x( dump_sub(gv) );
8737             Perl_av_create_and_push(aTHX_ &PL_beginav, MUTABLE_SV(cv));
8738             GvCV_set(gv,0);             /* cv has been hijacked */
8739             call_list(oldscope, PL_beginav);
8740
8741             POPSTACK;
8742             LEAVE;
8743             return !PL_savebegin;
8744         }
8745         else
8746             return FALSE;
8747     } else {
8748         if (*name == 'E') {
8749             if strEQ(name, "END") {
8750                 DEBUG_x( dump_sub(gv) );
8751                 Perl_av_create_and_unshift_one(aTHX_ &PL_endav, MUTABLE_SV(cv));
8752             } else
8753                 return FALSE;
8754         } else if (*name == 'U') {
8755             if (strEQ(name, "UNITCHECK")) {
8756                 /* It's never too late to run a unitcheck block */
8757                 Perl_av_create_and_unshift_one(aTHX_ &PL_unitcheckav, MUTABLE_SV(cv));
8758             }
8759             else
8760                 return FALSE;
8761         } else if (*name == 'C') {
8762             if (strEQ(name, "CHECK")) {
8763                 if (PL_main_start)
8764                     /* diag_listed_as: Too late to run %s block */
8765                     Perl_ck_warner(aTHX_ packWARN(WARN_VOID),
8766                                    "Too late to run CHECK block");
8767                 Perl_av_create_and_unshift_one(aTHX_ &PL_checkav, MUTABLE_SV(cv));
8768             }
8769             else
8770                 return FALSE;
8771         } else if (*name == 'I') {
8772             if (strEQ(name, "INIT")) {
8773                 if (PL_main_start)
8774                     /* diag_listed_as: Too late to run %s block */
8775                     Perl_ck_warner(aTHX_ packWARN(WARN_VOID),
8776                                    "Too late to run INIT block");
8777                 Perl_av_create_and_push(aTHX_ &PL_initav, MUTABLE_SV(cv));
8778             }
8779             else
8780                 return FALSE;
8781         } else
8782             return FALSE;
8783         DEBUG_x( dump_sub(gv) );
8784         (void)CvGV(cv);
8785         GvCV_set(gv,0);         /* cv has been hijacked */
8786         return FALSE;
8787     }
8788 }
8789
8790 /*
8791 =for apidoc newCONSTSUB
8792
8793 See L</newCONSTSUB_flags>.
8794
8795 =cut
8796 */
8797
8798 CV *
8799 Perl_newCONSTSUB(pTHX_ HV *stash, const char *name, SV *sv)
8800 {
8801     return newCONSTSUB_flags(stash, name, name ? strlen(name) : 0, 0, sv);
8802 }
8803
8804 /*
8805 =for apidoc newCONSTSUB_flags
8806
8807 Creates a constant sub equivalent to Perl S<C<sub FOO () { 123 }>> which is
8808 eligible for inlining at compile-time.
8809
8810 Currently, the only useful value for C<flags> is C<SVf_UTF8>.
8811
8812 The newly created subroutine takes ownership of a reference to the passed in
8813 SV.
8814
8815 Passing C<NULL> for SV creates a constant sub equivalent to S<C<sub BAR () {}>>,
8816 which won't be called if used as a destructor, but will suppress the overhead
8817 of a call to C<AUTOLOAD>.  (This form, however, isn't eligible for inlining at
8818 compile time.)
8819
8820 =cut
8821 */
8822
8823 CV *
8824 Perl_newCONSTSUB_flags(pTHX_ HV *stash, const char *name, STRLEN len,
8825                              U32 flags, SV *sv)
8826 {
8827     CV* cv;
8828     const char *const file = CopFILE(PL_curcop);
8829
8830     ENTER;
8831
8832     if (IN_PERL_RUNTIME) {
8833         /* at runtime, it's not safe to manipulate PL_curcop: it may be
8834          * an op shared between threads. Use a non-shared COP for our
8835          * dirty work */
8836          SAVEVPTR(PL_curcop);
8837          SAVECOMPILEWARNINGS();
8838          PL_compiling.cop_warnings = DUP_WARNINGS(PL_curcop->cop_warnings);
8839          PL_curcop = &PL_compiling;
8840     }
8841     SAVECOPLINE(PL_curcop);
8842     CopLINE_set(PL_curcop, PL_parser ? PL_parser->copline : NOLINE);
8843
8844     SAVEHINTS();
8845     PL_hints &= ~HINT_BLOCK_SCOPE;
8846
8847     if (stash) {
8848         SAVEGENERICSV(PL_curstash);
8849         PL_curstash = (HV *)SvREFCNT_inc_simple_NN(stash);
8850     }
8851
8852     /* Protect sv against leakage caused by fatal warnings. */
8853     if (sv) SAVEFREESV(sv);
8854
8855     /* file becomes the CvFILE. For an XS, it's usually static storage,
8856        and so doesn't get free()d.  (It's expected to be from the C pre-
8857        processor __FILE__ directive). But we need a dynamically allocated one,
8858        and we need it to get freed.  */
8859     cv = newXS_len_flags(name, len,
8860                          sv && SvTYPE(sv) == SVt_PVAV
8861                              ? const_av_xsub
8862                              : const_sv_xsub,
8863                          file ? file : "", "",
8864                          &sv, XS_DYNAMIC_FILENAME | flags);
8865     CvXSUBANY(cv).any_ptr = SvREFCNT_inc_simple(sv);
8866     CvCONST_on(cv);
8867
8868     LEAVE;
8869
8870     return cv;
8871 }
8872
8873 /*
8874 =for apidoc U||newXS
8875
8876 Used by C<xsubpp> to hook up XSUBs as Perl subs.  C<filename> needs to be
8877 static storage, as it is used directly as CvFILE(), without a copy being made.
8878
8879 =cut
8880 */
8881
8882 CV *
8883 Perl_newXS(pTHX_ const char *name, XSUBADDR_t subaddr, const char *filename)
8884 {
8885     PERL_ARGS_ASSERT_NEWXS;
8886     return newXS_len_flags(
8887         name, name ? strlen(name) : 0, subaddr, filename, NULL, NULL, 0
8888     );
8889 }
8890
8891 CV *
8892 Perl_newXS_flags(pTHX_ const char *name, XSUBADDR_t subaddr,
8893                  const char *const filename, const char *const proto,
8894                  U32 flags)
8895 {
8896     PERL_ARGS_ASSERT_NEWXS_FLAGS;
8897     return newXS_len_flags(
8898        name, name ? strlen(name) : 0, subaddr, filename, proto, NULL, flags
8899     );
8900 }
8901
8902 CV *
8903 Perl_newXS_deffile(pTHX_ const char *name, XSUBADDR_t subaddr)
8904 {
8905     PERL_ARGS_ASSERT_NEWXS_DEFFILE;
8906     return newXS_len_flags(
8907         name, strlen(name), subaddr, NULL, NULL, NULL, 0
8908     );
8909 }
8910
8911 CV *
8912 Perl_newXS_len_flags(pTHX_ const char *name, STRLEN len,
8913                            XSUBADDR_t subaddr, const char *const filename,
8914                            const char *const proto, SV **const_svp,
8915                            U32 flags)
8916 {
8917     CV *cv;
8918     bool interleave = FALSE;
8919
8920     PERL_ARGS_ASSERT_NEWXS_LEN_FLAGS;
8921
8922     {
8923         GV * const gv = gv_fetchpvn(
8924                             name ? name : PL_curstash ? "__ANON__" : "__ANON__::__ANON__",
8925                             name ? len : PL_curstash ? sizeof("__ANON__") - 1:
8926                                 sizeof("__ANON__::__ANON__") - 1,
8927                             GV_ADDMULTI | flags, SVt_PVCV);
8928
8929         if ((cv = (name ? GvCV(gv) : NULL))) {
8930             if (GvCVGEN(gv)) {
8931                 /* just a cached method */
8932                 SvREFCNT_dec(cv);
8933                 cv = NULL;
8934             }
8935             else if (CvROOT(cv) || CvXSUB(cv) || GvASSUMECV(gv)) {
8936                 /* already defined (or promised) */
8937                 /* Redundant check that allows us to avoid creating an SV
8938                    most of the time: */
8939                 if (CvCONST(cv) || ckWARN(WARN_REDEFINE)) {
8940                     report_redefined_cv(newSVpvn_flags(
8941                                          name,len,(flags&SVf_UTF8)|SVs_TEMP
8942                                         ),
8943                                         cv, const_svp);
8944                 }
8945                 interleave = TRUE;
8946                 ENTER;
8947                 SAVEFREESV(cv);
8948                 cv = NULL;
8949             }
8950         }
8951     
8952         if (cv)                         /* must reuse cv if autoloaded */
8953             cv_undef(cv);
8954         else {
8955             cv = MUTABLE_CV(newSV_type(SVt_PVCV));
8956             if (name) {
8957                 GvCV_set(gv,cv);
8958                 GvCVGEN(gv) = 0;
8959                 if (HvENAME_HEK(GvSTASH(gv)))
8960                     gv_method_changed(gv); /* newXS */
8961             }
8962         }
8963
8964         CvGV_set(cv, gv);
8965         if(filename) {
8966             /* XSUBs can't be perl lang/perl5db.pl debugged
8967             if (PERLDB_LINE_OR_SAVESRC)
8968                 (void)gv_fetchfile(filename); */
8969             assert(!CvDYNFILE(cv)); /* cv_undef should have turned it off */
8970             if (flags & XS_DYNAMIC_FILENAME) {
8971                 CvDYNFILE_on(cv);
8972                 CvFILE(cv) = savepv(filename);
8973             } else {
8974             /* NOTE: not copied, as it is expected to be an external constant string */
8975                 CvFILE(cv) = (char *)filename;
8976             }
8977         } else {
8978             assert((flags & XS_DYNAMIC_FILENAME) == 0 && PL_xsubfilename);
8979             CvFILE(cv) = (char*)PL_xsubfilename;
8980         }
8981         CvISXSUB_on(cv);
8982         CvXSUB(cv) = subaddr;
8983 #ifndef PERL_IMPLICIT_CONTEXT
8984         CvHSCXT(cv) = &PL_stack_sp;
8985 #else
8986         PoisonPADLIST(cv);
8987 #endif
8988
8989         if (name)
8990             process_special_blocks(0, name, gv, cv);
8991         else
8992             CvANON_on(cv);
8993     } /* <- not a conditional branch */
8994
8995
8996     sv_setpv(MUTABLE_SV(cv), proto);
8997     if (interleave) LEAVE;
8998     return cv;
8999 }
9000
9001 CV *
9002 Perl_newSTUB(pTHX_ GV *gv, bool fake)
9003 {
9004     CV *cv = MUTABLE_CV(newSV_type(SVt_PVCV));
9005     GV *cvgv;
9006     PERL_ARGS_ASSERT_NEWSTUB;
9007     assert(!GvCVu(gv));
9008     GvCV_set(gv, cv);
9009     GvCVGEN(gv) = 0;
9010     if (!fake && HvENAME_HEK(GvSTASH(gv)))
9011         gv_method_changed(gv);
9012     if (SvFAKE(gv)) {
9013         cvgv = gv_fetchsv((SV *)gv, GV_ADDMULTI, SVt_PVCV);
9014         SvFAKE_off(cvgv);
9015     }
9016     else cvgv = gv;
9017     CvGV_set(cv, cvgv);
9018     CvFILE_set_from_cop(cv, PL_curcop);
9019     CvSTASH_set(cv, PL_curstash);
9020     GvMULTI_on(gv);
9021     return cv;
9022 }
9023
9024 void
9025 Perl_newFORM(pTHX_ I32 floor, OP *o, OP *block)
9026 {
9027     CV *cv;
9028
9029     GV *gv;
9030
9031     if (PL_parser && PL_parser->error_count) {
9032         op_free(block);
9033         goto finish;
9034     }
9035
9036     gv = o
9037         ? gv_fetchsv(cSVOPo->op_sv, GV_ADD, SVt_PVFM)
9038         : gv_fetchpvs("STDOUT", GV_ADD|GV_NOTQUAL, SVt_PVFM);
9039
9040     GvMULTI_on(gv);
9041     if ((cv = GvFORM(gv))) {
9042         if (ckWARN(WARN_REDEFINE)) {
9043             const line_t oldline = CopLINE(PL_curcop);
9044             if (PL_parser && PL_parser->copline != NOLINE)
9045                 CopLINE_set(PL_curcop, PL_parser->copline);
9046             if (o) {
9047                 Perl_warner(aTHX_ packWARN(WARN_REDEFINE),
9048                             "Format %"SVf" redefined", SVfARG(cSVOPo->op_sv));
9049             } else {
9050                 /* diag_listed_as: Format %s redefined */
9051                 Perl_warner(aTHX_ packWARN(WARN_REDEFINE),
9052                             "Format STDOUT redefined");
9053             }
9054             CopLINE_set(PL_curcop, oldline);
9055         }
9056         SvREFCNT_dec(cv);
9057     }
9058     cv = PL_compcv;
9059     GvFORM(gv) = (CV *)SvREFCNT_inc_simple_NN(cv);
9060     CvGV_set(cv, gv);
9061     CvFILE_set_from_cop(cv, PL_curcop);
9062
9063
9064     pad_tidy(padtidy_FORMAT);
9065     CvROOT(cv) = newUNOP(OP_LEAVEWRITE, 0, scalarseq(block));
9066     CvROOT(cv)->op_private |= OPpREFCOUNTED;
9067     OpREFCNT_set(CvROOT(cv), 1);
9068     CvSTART(cv) = LINKLIST(CvROOT(cv));
9069     CvROOT(cv)->op_next = 0;
9070     CALL_PEEP(CvSTART(cv));
9071     finalize_optree(CvROOT(cv));
9072     S_prune_chain_head(&CvSTART(cv));
9073     cv_forget_slab(cv);
9074
9075   finish:
9076     op_free(o);
9077     if (PL_parser)
9078         PL_parser->copline = NOLINE;
9079     LEAVE_SCOPE(floor);
9080     PL_compiling.cop_seq = 0;
9081 }
9082
9083 OP *
9084 Perl_newANONLIST(pTHX_ OP *o)
9085 {
9086     return op_convert_list(OP_ANONLIST, OPf_SPECIAL, o);
9087 }
9088
9089 OP *
9090 Perl_newANONHASH(pTHX_ OP *o)
9091 {
9092     return op_convert_list(OP_ANONHASH, OPf_SPECIAL, o);
9093 }
9094
9095 OP *
9096 Perl_newANONSUB(pTHX_ I32 floor, OP *proto, OP *block)
9097 {
9098     return newANONATTRSUB(floor, proto, NULL, block);
9099 }
9100
9101 OP *
9102 Perl_newANONATTRSUB(pTHX_ I32 floor, OP *proto, OP *attrs, OP *block)
9103 {
9104     SV * const cv = MUTABLE_SV(newATTRSUB(floor, 0, proto, attrs, block));
9105     OP * anoncode = 
9106         newSVOP(OP_ANONCODE, 0,
9107                 cv);
9108     if (CvANONCONST(cv))
9109         anoncode = newUNOP(OP_ANONCONST, 0,
9110                            op_convert_list(OP_ENTERSUB,
9111                                            OPf_STACKED|OPf_WANT_SCALAR,
9112                                            anoncode));
9113     return newUNOP(OP_REFGEN, 0, anoncode);
9114 }
9115
9116 OP *
9117 Perl_oopsAV(pTHX_ OP *o)
9118 {
9119     dVAR;
9120
9121     PERL_ARGS_ASSERT_OOPSAV;
9122
9123     switch (o->op_type) {
9124     case OP_PADSV:
9125     case OP_PADHV:
9126         OpTYPE_set(o, OP_PADAV);
9127         return ref(o, OP_RV2AV);
9128
9129     case OP_RV2SV:
9130     case OP_RV2HV:
9131         OpTYPE_set(o, OP_RV2AV);
9132         ref(o, OP_RV2AV);
9133         break;
9134
9135     default:
9136         Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL), "oops: oopsAV");
9137         break;
9138     }
9139     return o;
9140 }
9141
9142 OP *
9143 Perl_oopsHV(pTHX_ OP *o)
9144 {
9145     dVAR;
9146
9147     PERL_ARGS_ASSERT_OOPSHV;
9148
9149     switch (o->op_type) {
9150     case OP_PADSV:
9151     case OP_PADAV:
9152         OpTYPE_set(o, OP_PADHV);
9153         return ref(o, OP_RV2HV);
9154
9155     case OP_RV2SV:
9156     case OP_RV2AV:
9157         OpTYPE_set(o, OP_RV2HV);
9158         ref(o, OP_RV2HV);
9159         break;
9160
9161     default:
9162         Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL), "oops: oopsHV");
9163         break;
9164     }
9165     return o;
9166 }
9167
9168 OP *
9169 Perl_newAVREF(pTHX_ OP *o)
9170 {
9171     dVAR;
9172
9173     PERL_ARGS_ASSERT_NEWAVREF;
9174
9175     if (o->op_type == OP_PADANY) {
9176         OpTYPE_set(o, OP_PADAV);
9177         return o;
9178     }
9179     else if ((o->op_type == OP_RV2AV || o->op_type == OP_PADAV)) {
9180         Perl_croak(aTHX_ "Can't use an array as a reference");
9181     }
9182     return newUNOP(OP_RV2AV, 0, scalar(o));
9183 }
9184
9185 OP *
9186 Perl_newGVREF(pTHX_ I32 type, OP *o)
9187 {
9188     if (type == OP_MAPSTART || type == OP_GREPSTART || type == OP_SORT)
9189         return newUNOP(OP_NULL, 0, o);
9190     return ref(newUNOP(OP_RV2GV, OPf_REF, o), type);
9191 }
9192
9193 OP *
9194 Perl_newHVREF(pTHX_ OP *o)
9195 {
9196     dVAR;
9197
9198     PERL_ARGS_ASSERT_NEWHVREF;
9199
9200     if (o->op_type == OP_PADANY) {
9201         OpTYPE_set(o, OP_PADHV);
9202         return o;
9203     }
9204     else if ((o->op_type == OP_RV2HV || o->op_type == OP_PADHV)) {
9205         Perl_croak(aTHX_ "Can't use a hash as a reference");
9206     }
9207     return newUNOP(OP_RV2HV, 0, scalar(o));
9208 }
9209
9210 OP *
9211 Perl_newCVREF(pTHX_ I32 flags, OP *o)
9212 {
9213     if (o->op_type == OP_PADANY) {
9214         dVAR;
9215         OpTYPE_set(o, OP_PADCV);
9216     }
9217     return newUNOP(OP_RV2CV, flags, scalar(o));
9218 }
9219
9220 OP *
9221 Perl_newSVREF(pTHX_ OP *o)
9222 {
9223     dVAR;
9224
9225     PERL_ARGS_ASSERT_NEWSVREF;
9226
9227     if (o->op_type == OP_PADANY) {
9228         OpTYPE_set(o, OP_PADSV);
9229         scalar(o);
9230         return o;
9231     }
9232     return newUNOP(OP_RV2SV, 0, scalar(o));
9233 }
9234
9235 /* Check routines. See the comments at the top of this file for details
9236  * on when these are called */
9237
9238 OP *
9239 Perl_ck_anoncode(pTHX_ OP *o)
9240 {
9241     PERL_ARGS_ASSERT_CK_ANONCODE;
9242
9243     cSVOPo->op_targ = pad_add_anon((CV*)cSVOPo->op_sv, o->op_type);
9244     cSVOPo->op_sv = NULL;
9245     return o;
9246 }
9247
9248 static void
9249 S_io_hints(pTHX_ OP *o)
9250 {
9251 #if O_BINARY != 0 || O_TEXT != 0
9252     HV * const table =
9253         PL_hints & HINT_LOCALIZE_HH ? GvHV(PL_hintgv) : NULL;;
9254     if (table) {
9255         SV **svp = hv_fetchs(table, "open_IN", FALSE);
9256         if (svp && *svp) {
9257             STRLEN len = 0;
9258             const char *d = SvPV_const(*svp, len);
9259             const I32 mode = mode_from_discipline(d, len);
9260             /* bit-and:ing with zero O_BINARY or O_TEXT would be useless. */
9261 #  if O_BINARY != 0
9262             if (mode & O_BINARY)
9263                 o->op_private |= OPpOPEN_IN_RAW;
9264 #  endif
9265 #  if O_TEXT != 0
9266             if (mode & O_TEXT)
9267                 o->op_private |= OPpOPEN_IN_CRLF;
9268 #  endif
9269         }
9270
9271         svp = hv_fetchs(table, "open_OUT", FALSE);
9272         if (svp && *svp) {
9273             STRLEN len = 0;
9274             const char *d = SvPV_const(*svp, len);
9275             const I32 mode = mode_from_discipline(d, len);
9276             /* bit-and:ing with zero O_BINARY or O_TEXT would be useless. */
9277 #  if O_BINARY != 0
9278             if (mode & O_BINARY)
9279                 o->op_private |= OPpOPEN_OUT_RAW;
9280 #  endif
9281 #  if O_TEXT != 0
9282             if (mode & O_TEXT)
9283                 o->op_private |= OPpOPEN_OUT_CRLF;
9284 #  endif
9285         }
9286     }
9287 #else
9288     PERL_UNUSED_CONTEXT;
9289     PERL_UNUSED_ARG(o);
9290 #endif
9291 }
9292
9293 OP *
9294 Perl_ck_backtick(pTHX_ OP *o)
9295 {
9296     GV *gv;
9297     OP *newop = NULL;
9298     OP *sibl;
9299     PERL_ARGS_ASSERT_CK_BACKTICK;
9300     /* qx and `` have a null pushmark; CORE::readpipe has only one kid. */
9301     if (o->op_flags & OPf_KIDS && (sibl = OpSIBLING(cUNOPo->op_first))
9302      && (gv = gv_override("readpipe",8)))
9303     {
9304         /* detach rest of siblings from o and its first child */
9305         op_sibling_splice(o, cUNOPo->op_first, -1, NULL);
9306         newop = S_new_entersubop(aTHX_ gv, sibl);
9307     }
9308     else if (!(o->op_flags & OPf_KIDS))
9309         newop = newUNOP(OP_BACKTICK, 0, newDEFSVOP());
9310     if (newop) {
9311         op_free(o);
9312         return newop;
9313     }
9314     S_io_hints(aTHX_ o);
9315     return o;
9316 }
9317
9318 OP *
9319 Perl_ck_bitop(pTHX_ OP *o)
9320 {
9321     PERL_ARGS_ASSERT_CK_BITOP;
9322
9323     o->op_private = (U8)(PL_hints & HINT_INTEGER);
9324
9325     if (o->op_type == OP_NBIT_OR     || o->op_type == OP_SBIT_OR
9326      || o->op_type == OP_NBIT_XOR    || o->op_type == OP_SBIT_XOR
9327      || o->op_type == OP_NBIT_AND    || o->op_type == OP_SBIT_AND
9328      || o->op_type == OP_NCOMPLEMENT || o->op_type == OP_SCOMPLEMENT)
9329         Perl_ck_warner_d(aTHX_ packWARN(WARN_EXPERIMENTAL__BITWISE),
9330                               "The bitwise feature is experimental");
9331     if (!(o->op_flags & OPf_STACKED) /* Not an assignment */
9332             && OP_IS_INFIX_BIT(o->op_type))
9333     {
9334         const OP * const left = cBINOPo->op_first;
9335         const OP * const right = OpSIBLING(left);
9336         if ((OP_IS_NUMCOMPARE(left->op_type) &&
9337                 (left->op_flags & OPf_PARENS) == 0) ||
9338             (OP_IS_NUMCOMPARE(right->op_type) &&
9339                 (right->op_flags & OPf_PARENS) == 0))
9340             Perl_ck_warner(aTHX_ packWARN(WARN_PRECEDENCE),
9341                           "Possible precedence problem on bitwise %s operator",
9342                            o->op_type ==  OP_BIT_OR
9343                          ||o->op_type == OP_NBIT_OR  ? "|"
9344                         :  o->op_type ==  OP_BIT_AND
9345                          ||o->op_type == OP_NBIT_AND ? "&"
9346                         :  o->op_type ==  OP_BIT_XOR
9347                          ||o->op_type == OP_NBIT_XOR ? "^"
9348                         :  o->op_type == OP_SBIT_OR  ? "|."
9349                         :  o->op_type == OP_SBIT_AND ? "&." : "^."
9350                            );
9351     }
9352     return o;
9353 }
9354
9355 PERL_STATIC_INLINE bool
9356 is_dollar_bracket(pTHX_ const OP * const o)
9357 {
9358     const OP *kid;
9359     PERL_UNUSED_CONTEXT;
9360     return o->op_type == OP_RV2SV && o->op_flags & OPf_KIDS
9361         && (kid = cUNOPx(o)->op_first)
9362         && kid->op_type == OP_GV
9363         && strEQ(GvNAME(cGVOPx_gv(kid)), "[");
9364 }
9365
9366 OP *
9367 Perl_ck_cmp(pTHX_ OP *o)
9368 {
9369     PERL_ARGS_ASSERT_CK_CMP;
9370     if (ckWARN(WARN_SYNTAX)) {
9371         const OP *kid = cUNOPo->op_first;
9372         if (kid &&
9373             (
9374                 (   is_dollar_bracket(aTHX_ kid)
9375                  && OpSIBLING(kid) && OpSIBLING(kid)->op_type == OP_CONST
9376                 )
9377              || (   kid->op_type == OP_CONST
9378                  && (kid = OpSIBLING(kid)) && is_dollar_bracket(aTHX_ kid)
9379                 )
9380            )
9381         )
9382             Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
9383                         "$[ used in %s (did you mean $] ?)", OP_DESC(o));
9384     }
9385     return o;
9386 }
9387
9388 OP *
9389 Perl_ck_concat(pTHX_ OP *o)
9390 {
9391     const OP * const kid = cUNOPo->op_first;
9392
9393     PERL_ARGS_ASSERT_CK_CONCAT;
9394     PERL_UNUSED_CONTEXT;
9395
9396     if (kid->op_type == OP_CONCAT && !(kid->op_private & OPpTARGET_MY) &&
9397             !(kUNOP->op_first->op_flags & OPf_MOD))
9398         o->op_flags |= OPf_STACKED;
9399     return o;
9400 }
9401
9402 OP *
9403 Perl_ck_spair(pTHX_ OP *o)
9404 {
9405     dVAR;
9406
9407     PERL_ARGS_ASSERT_CK_SPAIR;
9408
9409     if (o->op_flags & OPf_KIDS) {
9410         OP* newop;
9411         OP* kid;
9412         OP* kidkid;
9413         const OPCODE type = o->op_type;
9414         o = modkids(ck_fun(o), type);
9415         kid    = cUNOPo->op_first;
9416         kidkid = kUNOP->op_first;
9417         newop = OpSIBLING(kidkid);
9418         if (newop) {
9419             const OPCODE type = newop->op_type;
9420             if (OpHAS_SIBLING(newop))
9421                 return o;
9422             if (o->op_type == OP_REFGEN
9423              && (  type == OP_RV2CV
9424                 || (  !(newop->op_flags & OPf_PARENS)
9425                    && (  type == OP_RV2AV || type == OP_PADAV
9426                       || type == OP_RV2HV || type == OP_PADHV))))
9427                 NOOP; /* OK (allow srefgen for \@a and \%h) */
9428             else if (OP_GIMME(newop,0) != G_SCALAR)
9429                 return o;
9430         }
9431         /* excise first sibling */
9432         op_sibling_splice(kid, NULL, 1, NULL);
9433         op_free(kidkid);
9434     }
9435     /* transforms OP_REFGEN into OP_SREFGEN, OP_CHOP into OP_SCHOP,
9436      * and OP_CHOMP into OP_SCHOMP */
9437     o->op_ppaddr = PL_ppaddr[++o->op_type];
9438     return ck_fun(o);
9439 }
9440
9441 OP *
9442 Perl_ck_delete(pTHX_ OP *o)
9443 {
9444     PERL_ARGS_ASSERT_CK_DELETE;
9445
9446     o = ck_fun(o);
9447     o->op_private = 0;
9448     if (o->op_flags & OPf_KIDS) {
9449         OP * const kid = cUNOPo->op_first;
9450         switch (kid->op_type) {
9451         case OP_ASLICE:
9452             o->op_flags |= OPf_SPECIAL;
9453             /* FALLTHROUGH */
9454         case OP_HSLICE:
9455             o->op_private |= OPpSLICE;
9456             break;
9457         case OP_AELEM:
9458             o->op_flags |= OPf_SPECIAL;
9459             /* FALLTHROUGH */
9460         case OP_HELEM:
9461             break;
9462         case OP_KVASLICE:
9463             Perl_croak(aTHX_ "delete argument is index/value array slice,"
9464                              " use array slice");
9465         case OP_KVHSLICE:
9466             Perl_croak(aTHX_ "delete argument is key/value hash slice, use"
9467                              " hash slice");
9468         default:
9469             Perl_croak(aTHX_ "delete argument is not a HASH or ARRAY "
9470                              "element or slice");
9471         }
9472         if (kid->op_private & OPpLVAL_INTRO)
9473             o->op_private |= OPpLVAL_INTRO;
9474         op_null(kid);
9475     }
9476     return o;
9477 }
9478
9479 OP *
9480 Perl_ck_eof(pTHX_ OP *o)
9481 {
9482     PERL_ARGS_ASSERT_CK_EOF;
9483
9484     if (o->op_flags & OPf_KIDS) {
9485         OP *kid;
9486         if (cLISTOPo->op_first->op_type == OP_STUB) {
9487             OP * const newop
9488                 = newUNOP(o->op_type, OPf_SPECIAL, newGVOP(OP_GV, 0, PL_argvgv));
9489             op_free(o);
9490             o = newop;
9491         }
9492         o = ck_fun(o);
9493         kid = cLISTOPo->op_first;
9494         if (kid->op_type == OP_RV2GV)
9495             kid->op_private |= OPpALLOW_FAKE;
9496     }
9497     return o;
9498 }
9499
9500 OP *
9501 Perl_ck_eval(pTHX_ OP *o)
9502 {
9503     dVAR;
9504
9505     PERL_ARGS_ASSERT_CK_EVAL;
9506
9507     PL_hints |= HINT_BLOCK_SCOPE;
9508     if (o->op_flags & OPf_KIDS) {
9509         SVOP * const kid = (SVOP*)cUNOPo->op_first;
9510         assert(kid);
9511
9512         if (o->op_type == OP_ENTERTRY) {
9513             LOGOP *enter;
9514
9515             /* cut whole sibling chain free from o */
9516             op_sibling_splice(o, NULL, -1, NULL);
9517             op_free(o);
9518
9519             enter = S_alloc_LOGOP(aTHX_ OP_ENTERTRY, NULL, NULL);
9520
9521             /* establish postfix order */
9522             enter->op_next = (OP*)enter;
9523
9524             o = op_prepend_elem(OP_LINESEQ, (OP*)enter, (OP*)kid);
9525             OpTYPE_set(o, OP_LEAVETRY);
9526             enter->op_other = o;
9527             return o;
9528         }
9529         else {
9530             scalar((OP*)kid);
9531             S_set_haseval(aTHX);
9532         }
9533     }
9534     else {
9535         const U8 priv = o->op_private;
9536         op_free(o);
9537         /* the newUNOP will recursively call ck_eval(), which will handle
9538          * all the stuff at the end of this function, like adding
9539          * OP_HINTSEVAL
9540          */
9541         return newUNOP(OP_ENTEREVAL, priv <<8, newDEFSVOP());
9542     }
9543     o->op_targ = (PADOFFSET)PL_hints;
9544     if (o->op_private & OPpEVAL_BYTES) o->op_targ &= ~HINT_UTF8;
9545     if ((PL_hints & HINT_LOCALIZE_HH) != 0
9546      && !(o->op_private & OPpEVAL_COPHH) && GvHV(PL_hintgv)) {
9547         /* Store a copy of %^H that pp_entereval can pick up. */
9548         OP *hhop = newSVOP(OP_HINTSEVAL, 0,
9549                            MUTABLE_SV(hv_copy_hints_hv(GvHV(PL_hintgv))));
9550         /* append hhop to only child  */
9551         op_sibling_splice(o, cUNOPo->op_first, 0, hhop);
9552
9553         o->op_private |= OPpEVAL_HAS_HH;
9554     }
9555     if (!(o->op_private & OPpEVAL_BYTES)
9556          && FEATURE_UNIEVAL_IS_ENABLED)
9557             o->op_private |= OPpEVAL_UNICODE;
9558     return o;
9559 }
9560
9561 OP *
9562 Perl_ck_exec(pTHX_ OP *o)
9563 {
9564     PERL_ARGS_ASSERT_CK_EXEC;
9565
9566     if (o->op_flags & OPf_STACKED) {
9567         OP *kid;
9568         o = ck_fun(o);
9569         kid = OpSIBLING(cUNOPo->op_first);
9570         if (kid->op_type == OP_RV2GV)
9571             op_null(kid);
9572     }
9573     else
9574         o = listkids(o);
9575     return o;
9576 }
9577
9578 OP *
9579 Perl_ck_exists(pTHX_ OP *o)
9580 {
9581     PERL_ARGS_ASSERT_CK_EXISTS;
9582
9583     o = ck_fun(o);
9584     if (o->op_flags & OPf_KIDS) {
9585         OP * const kid = cUNOPo->op_first;
9586         if (kid->op_type == OP_ENTERSUB) {
9587             (void) ref(kid, o->op_type);
9588             if (kid->op_type != OP_RV2CV
9589                         && !(PL_parser && PL_parser->error_count))
9590                 Perl_croak(aTHX_
9591                           "exists argument is not a subroutine name");
9592             o->op_private |= OPpEXISTS_SUB;
9593         }
9594         else if (kid->op_type == OP_AELEM)
9595             o->op_flags |= OPf_SPECIAL;
9596         else if (kid->op_type != OP_HELEM)
9597             Perl_croak(aTHX_ "exists argument is not a HASH or ARRAY "
9598                              "element or a subroutine");
9599         op_null(kid);
9600     }
9601     return o;
9602 }
9603
9604 OP *
9605 Perl_ck_rvconst(pTHX_ OP *o)
9606 {
9607     dVAR;
9608     SVOP * const kid = (SVOP*)cUNOPo->op_first;
9609
9610     PERL_ARGS_ASSERT_CK_RVCONST;
9611
9612     o->op_private |= (PL_hints & HINT_STRICT_REFS);
9613
9614     if (kid->op_type == OP_CONST) {
9615         int iscv;
9616         GV *gv;
9617         SV * const kidsv = kid->op_sv;
9618
9619         /* Is it a constant from cv_const_sv()? */
9620         if ((SvROK(kidsv) || isGV_with_GP(kidsv)) && SvREADONLY(kidsv)) {
9621             return o;
9622         }
9623         if (SvTYPE(kidsv) == SVt_PVAV) return o;
9624         if ((o->op_private & HINT_STRICT_REFS) && (kid->op_private & OPpCONST_BARE)) {
9625             const char *badthing;
9626             switch (o->op_type) {
9627             case OP_RV2SV:
9628                 badthing = "a SCALAR";
9629                 break;
9630             case OP_RV2AV:
9631                 badthing = "an ARRAY";
9632                 break;
9633             case OP_RV2HV:
9634                 badthing = "a HASH";
9635                 break;
9636             default:
9637                 badthing = NULL;
9638                 break;
9639             }
9640             if (badthing)
9641                 Perl_croak(aTHX_
9642                            "Can't use bareword (\"%"SVf"\") as %s ref while \"strict refs\" in use",
9643                            SVfARG(kidsv), badthing);
9644         }
9645         /*
9646          * This is a little tricky.  We only want to add the symbol if we
9647          * didn't add it in the lexer.  Otherwise we get duplicate strict
9648          * warnings.  But if we didn't add it in the lexer, we must at
9649          * least pretend like we wanted to add it even if it existed before,
9650          * or we get possible typo warnings.  OPpCONST_ENTERED says
9651          * whether the lexer already added THIS instance of this symbol.
9652          */
9653         iscv = o->op_type == OP_RV2CV ? GV_NOEXPAND|GV_ADDMULTI : 0;
9654         gv = gv_fetchsv(kidsv,
9655                 o->op_type == OP_RV2CV
9656                         && o->op_private & OPpMAY_RETURN_CONSTANT
9657                     ? GV_NOEXPAND
9658                     : iscv | !(kid->op_private & OPpCONST_ENTERED),
9659                 iscv
9660                     ? SVt_PVCV
9661                     : o->op_type == OP_RV2SV
9662                         ? SVt_PV
9663                         : o->op_type == OP_RV2AV
9664                             ? SVt_PVAV
9665                             : o->op_type == OP_RV2HV
9666                                 ? SVt_PVHV
9667                                 : SVt_PVGV);
9668         if (gv) {
9669             if (!isGV(gv)) {
9670                 assert(iscv);
9671                 assert(SvROK(gv));
9672                 if (!(o->op_private & OPpMAY_RETURN_CONSTANT)
9673                   && SvTYPE(SvRV(gv)) != SVt_PVCV)
9674                     gv_fetchsv(kidsv, GV_ADDMULTI, SVt_PVCV);
9675             }
9676             OpTYPE_set(kid, OP_GV);
9677             SvREFCNT_dec(kid->op_sv);
9678 #ifdef USE_ITHREADS
9679             /* XXX hack: dependence on sizeof(PADOP) <= sizeof(SVOP) */
9680             STATIC_ASSERT_STMT(sizeof(PADOP) <= sizeof(SVOP));
9681             kPADOP->op_padix = pad_alloc(OP_GV, SVf_READONLY);
9682             SvREFCNT_dec(PAD_SVl(kPADOP->op_padix));
9683             PAD_SETSV(kPADOP->op_padix, MUTABLE_SV(SvREFCNT_inc_simple_NN(gv)));
9684 #else
9685             kid->op_sv = SvREFCNT_inc_simple_NN(gv);
9686 #endif
9687             kid->op_private = 0;
9688             /* FAKE globs in the symbol table cause weird bugs (#77810) */
9689             SvFAKE_off(gv);
9690         }
9691     }
9692     return o;
9693 }
9694
9695 OP *
9696 Perl_ck_ftst(pTHX_ OP *o)
9697 {
9698     dVAR;
9699     const I32 type = o->op_type;
9700
9701     PERL_ARGS_ASSERT_CK_FTST;
9702
9703     if (o->op_flags & OPf_REF) {
9704         NOOP;
9705     }
9706     else if (o->op_flags & OPf_KIDS && cUNOPo->op_first->op_type != OP_STUB) {
9707         SVOP * const kid = (SVOP*)cUNOPo->op_first;
9708         const OPCODE kidtype = kid->op_type;
9709
9710         if (kidtype == OP_CONST && (kid->op_private & OPpCONST_BARE)
9711          && !kid->op_folded) {
9712             OP * const newop = newGVOP(type, OPf_REF,
9713                 gv_fetchsv(kid->op_sv, GV_ADD, SVt_PVIO));
9714             op_free(o);
9715             return newop;
9716         }
9717         scalar((OP *) kid);
9718         if ((PL_hints & HINT_FILETEST_ACCESS) && OP_IS_FILETEST_ACCESS(o->op_type))
9719             o->op_private |= OPpFT_ACCESS;
9720         if (type != OP_STAT && type != OP_LSTAT
9721             && PL_check[kidtype] == Perl_ck_ftst
9722             && kidtype != OP_STAT && kidtype != OP_LSTAT
9723         ) {
9724             o->op_private |= OPpFT_STACKED;
9725             kid->op_private |= OPpFT_STACKING;
9726             if (kidtype == OP_FTTTY && (
9727                    !(kid->op_private & OPpFT_STACKED)
9728                 || kid->op_private & OPpFT_AFTER_t
9729                ))
9730                 o->op_private |= OPpFT_AFTER_t;
9731         }
9732     }
9733     else {
9734         op_free(o);
9735         if (type == OP_FTTTY)
9736             o = newGVOP(type, OPf_REF, PL_stdingv);
9737         else
9738             o = newUNOP(type, 0, newDEFSVOP());
9739     }
9740     return o;
9741 }
9742
9743 OP *
9744 Perl_ck_fun(pTHX_ OP *o)
9745 {
9746     const int type = o->op_type;
9747     I32 oa = PL_opargs[type] >> OASHIFT;
9748
9749     PERL_ARGS_ASSERT_CK_FUN;
9750
9751     if (o->op_flags & OPf_STACKED) {
9752         if ((oa & OA_OPTIONAL) && (oa >> 4) && !((oa >> 4) & OA_OPTIONAL))
9753             oa &= ~OA_OPTIONAL;
9754         else
9755             return no_fh_allowed(o);
9756     }
9757
9758     if (o->op_flags & OPf_KIDS) {
9759         OP *prev_kid = NULL;
9760         OP *kid = cLISTOPo->op_first;
9761         I32 numargs = 0;
9762         bool seen_optional = FALSE;
9763
9764         if (kid->op_type == OP_PUSHMARK ||
9765             (kid->op_type == OP_NULL && kid->op_targ == OP_PUSHMARK))
9766         {
9767             prev_kid = kid;
9768             kid = OpSIBLING(kid);
9769         }
9770         if (kid && kid->op_type == OP_COREARGS) {
9771             bool optional = FALSE;
9772             while (oa) {
9773                 numargs++;
9774                 if (oa & OA_OPTIONAL) optional = TRUE;
9775                 oa = oa >> 4;
9776             }
9777             if (optional) o->op_private |= numargs;
9778             return o;
9779         }
9780
9781         while (oa) {
9782             if (oa & OA_OPTIONAL || (oa & 7) == OA_LIST) {
9783                 if (!kid && !seen_optional && PL_opargs[type] & OA_DEFGV) {
9784                     kid = newDEFSVOP();
9785                     /* append kid to chain */
9786                     op_sibling_splice(o, prev_kid, 0, kid);
9787                 }
9788                 seen_optional = TRUE;
9789             }
9790             if (!kid) break;
9791
9792             numargs++;
9793             switch (oa & 7) {
9794             case OA_SCALAR:
9795                 /* list seen where single (scalar) arg expected? */
9796                 if (numargs == 1 && !(oa >> 4)
9797                     && kid->op_type == OP_LIST && type != OP_SCALAR)
9798                 {
9799                     return too_many_arguments_pv(o,PL_op_desc[type], 0);
9800                 }
9801                 if (type != OP_DELETE) scalar(kid);
9802                 break;
9803             case OA_LIST:
9804                 if (oa < 16) {
9805                     kid = 0;
9806                     continue;
9807                 }
9808                 else
9809                     list(kid);
9810                 break;
9811             case OA_AVREF:
9812                 if ((type == OP_PUSH || type == OP_UNSHIFT)
9813                     && !OpHAS_SIBLING(kid))
9814                     Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX),
9815                                    "Useless use of %s with no values",
9816                                    PL_op_desc[type]);
9817
9818                 if (kid->op_type == OP_CONST
9819                       && (  !SvROK(cSVOPx_sv(kid)) 
9820                          || SvTYPE(SvRV(cSVOPx_sv(kid))) != SVt_PVAV  )
9821                         )
9822                     bad_type_pv(numargs, "array", o, kid);
9823                 else if (kid->op_type != OP_RV2AV && kid->op_type != OP_PADAV) {
9824                     yyerror_pv(Perl_form(aTHX_ "Experimental %s on scalar is now forbidden",
9825                                          PL_op_desc[type]), 0);
9826                 }
9827                 else {
9828                     op_lvalue(kid, type);
9829                 }
9830                 break;
9831             case OA_HVREF:
9832                 if (kid->op_type != OP_RV2HV && kid->op_type != OP_PADHV)
9833                     bad_type_pv(numargs, "hash", o, kid);
9834                 op_lvalue(kid, type);
9835                 break;
9836             case OA_CVREF:
9837                 {
9838                     /* replace kid with newop in chain */
9839                     OP * const newop =
9840                         S_op_sibling_newUNOP(aTHX_ o, prev_kid, OP_NULL, 0);
9841                     newop->op_next = newop;
9842                     kid = newop;
9843                 }
9844                 break;
9845             case OA_FILEREF:
9846                 if (kid->op_type != OP_GV && kid->op_type != OP_RV2GV) {
9847                     if (kid->op_type == OP_CONST &&
9848                         (kid->op_private & OPpCONST_BARE))
9849                     {
9850                         OP * const newop = newGVOP(OP_GV, 0,
9851                             gv_fetchsv(((SVOP*)kid)->op_sv, GV_ADD, SVt_PVIO));
9852                         /* replace kid with newop in chain */
9853                         op_sibling_splice(o, prev_kid, 1, newop);
9854                         op_free(kid);
9855                         kid = newop;
9856                     }
9857                     else if (kid->op_type == OP_READLINE) {
9858                         /* neophyte patrol: open(<FH>), close(<FH>) etc. */
9859                         bad_type_pv(numargs, "HANDLE", o, kid);
9860                     }
9861                     else {
9862                         I32 flags = OPf_SPECIAL;
9863                         I32 priv = 0;
9864                         PADOFFSET targ = 0;
9865
9866                         /* is this op a FH constructor? */
9867                         if (is_handle_constructor(o,numargs)) {
9868                             const char *name = NULL;
9869                             STRLEN len = 0;
9870                             U32 name_utf8 = 0;
9871                             bool want_dollar = TRUE;
9872
9873                             flags = 0;
9874                             /* Set a flag to tell rv2gv to vivify
9875                              * need to "prove" flag does not mean something
9876                              * else already - NI-S 1999/05/07
9877                              */
9878                             priv = OPpDEREF;
9879                             if (kid->op_type == OP_PADSV) {
9880                                 PADNAME * const pn
9881                                     = PAD_COMPNAME_SV(kid->op_targ);
9882                                 name = PadnamePV (pn);
9883                                 len  = PadnameLEN(pn);
9884                                 name_utf8 = PadnameUTF8(pn);
9885                             }
9886                             else if (kid->op_type == OP_RV2SV
9887                                      && kUNOP->op_first->op_type == OP_GV)
9888                             {
9889                                 GV * const gv = cGVOPx_gv(kUNOP->op_first);
9890                                 name = GvNAME(gv);
9891                                 len = GvNAMELEN(gv);
9892                                 name_utf8 = GvNAMEUTF8(gv) ? SVf_UTF8 : 0;
9893                             }
9894                             else if (kid->op_type == OP_AELEM
9895                                      || kid->op_type == OP_HELEM)
9896                             {
9897                                  OP *firstop;
9898                                  OP *op = ((BINOP*)kid)->op_first;
9899                                  name = NULL;
9900                                  if (op) {
9901                                       SV *tmpstr = NULL;
9902                                       const char * const a =
9903                                            kid->op_type == OP_AELEM ?
9904                                            "[]" : "{}";
9905                                       if (((op->op_type == OP_RV2AV) ||
9906                                            (op->op_type == OP_RV2HV)) &&
9907                                           (firstop = ((UNOP*)op)->op_first) &&
9908                                           (firstop->op_type == OP_GV)) {
9909                                            /* packagevar $a[] or $h{} */
9910                                            GV * const gv = cGVOPx_gv(firstop);
9911                                            if (gv)
9912                                                 tmpstr =
9913                                                      Perl_newSVpvf(aTHX_
9914                                                                    "%s%c...%c",
9915                                                                    GvNAME(gv),
9916                                                                    a[0], a[1]);
9917                                       }
9918                                       else if (op->op_type == OP_PADAV
9919                                                || op->op_type == OP_PADHV) {
9920                                            /* lexicalvar $a[] or $h{} */
9921                                            const char * const padname =
9922                                                 PAD_COMPNAME_PV(op->op_targ);
9923                                            if (padname)
9924                                                 tmpstr =
9925                                                      Perl_newSVpvf(aTHX_
9926                                                                    "%s%c...%c",
9927                                                                    padname + 1,
9928                                                                    a[0], a[1]);
9929                                       }
9930                                       if (tmpstr) {
9931                                            name = SvPV_const(tmpstr, len);
9932                                            name_utf8 = SvUTF8(tmpstr);
9933                                            sv_2mortal(tmpstr);
9934                                       }
9935                                  }
9936                                  if (!name) {
9937                                       name = "__ANONIO__";
9938                                       len = 10;
9939                                       want_dollar = FALSE;
9940                                  }
9941                                  op_lvalue(kid, type);
9942                             }
9943                             if (name) {
9944                                 SV *namesv;
9945                                 targ = pad_alloc(OP_RV2GV, SVf_READONLY);
9946                                 namesv = PAD_SVl(targ);
9947                                 if (want_dollar && *name != '$')
9948                                     sv_setpvs(namesv, "$");
9949                                 else
9950                                     sv_setpvs(namesv, "");
9951                                 sv_catpvn(namesv, name, len);
9952                                 if ( name_utf8 ) SvUTF8_on(namesv);
9953                             }
9954                         }
9955                         scalar(kid);
9956                         kid = S_op_sibling_newUNOP(aTHX_ o, prev_kid,
9957                                     OP_RV2GV, flags);
9958                         kid->op_targ = targ;
9959                         kid->op_private |= priv;
9960                     }
9961                 }
9962                 scalar(kid);
9963                 break;
9964             case OA_SCALARREF:
9965                 if ((type == OP_UNDEF || type == OP_POS)
9966                     && numargs == 1 && !(oa >> 4)
9967                     && kid->op_type == OP_LIST)
9968                     return too_many_arguments_pv(o,PL_op_desc[type], 0);
9969                 op_lvalue(scalar(kid), type);
9970                 break;
9971             }
9972             oa >>= 4;
9973             prev_kid = kid;
9974             kid = OpSIBLING(kid);
9975         }
9976         /* FIXME - should the numargs or-ing move after the too many
9977          * arguments check? */
9978         o->op_private |= numargs;
9979         if (kid)
9980             return too_many_arguments_pv(o,OP_DESC(o), 0);
9981         listkids(o);
9982     }
9983     else if (PL_opargs[type] & OA_DEFGV) {
9984         /* Ordering of these two is important to keep f_map.t passing.  */
9985         op_free(o);
9986         return newUNOP(type, 0, newDEFSVOP());
9987     }
9988
9989     if (oa) {
9990         while (oa & OA_OPTIONAL)
9991             oa >>= 4;
9992         if (oa && oa != OA_LIST)
9993             return too_few_arguments_pv(o,OP_DESC(o), 0);
9994     }
9995     return o;
9996 }
9997
9998 OP *
9999 Perl_ck_glob(pTHX_ OP *o)
10000 {
10001     GV *gv;
10002
10003     PERL_ARGS_ASSERT_CK_GLOB;
10004
10005     o = ck_fun(o);
10006     if ((o->op_flags & OPf_KIDS) && !OpHAS_SIBLING(cLISTOPo->op_first))
10007         op_append_elem(OP_GLOB, o, newDEFSVOP()); /* glob() => glob($_) */
10008
10009     if (!(o->op_flags & OPf_SPECIAL) && (gv = gv_override("glob", 4)))
10010     {
10011         /* convert
10012          *     glob
10013          *       \ null - const(wildcard)
10014          * into
10015          *     null
10016          *       \ enter
10017          *            \ list
10018          *                 \ mark - glob - rv2cv
10019          *                             |        \ gv(CORE::GLOBAL::glob)
10020          *                             |
10021          *                              \ null - const(wildcard)
10022          */
10023         o->op_flags |= OPf_SPECIAL;
10024         o->op_targ = pad_alloc(OP_GLOB, SVs_PADTMP);
10025         o = S_new_entersubop(aTHX_ gv, o);
10026         o = newUNOP(OP_NULL, 0, o);
10027         o->op_targ = OP_GLOB; /* hint at what it used to be: eg in newWHILEOP */
10028         return o;
10029     }
10030     else o->op_flags &= ~OPf_SPECIAL;
10031 #if !defined(PERL_EXTERNAL_GLOB)
10032     if (!PL_globhook) {
10033         ENTER;
10034         Perl_load_module(aTHX_ PERL_LOADMOD_NOIMPORT,
10035                                newSVpvs("File::Glob"), NULL, NULL, NULL);
10036         LEAVE;
10037     }
10038 #endif /* !PERL_EXTERNAL_GLOB */
10039     gv = (GV *)newSV(0);
10040     gv_init(gv, 0, "", 0, 0);
10041     gv_IOadd(gv);
10042     op_append_elem(OP_GLOB, o, newGVOP(OP_GV, 0, gv));
10043     SvREFCNT_dec_NN(gv); /* newGVOP increased it */
10044     scalarkids(o);
10045     return o;
10046 }
10047
10048 OP *
10049 Perl_ck_grep(pTHX_ OP *o)
10050 {
10051     LOGOP *gwop;
10052     OP *kid;
10053     const OPCODE type = o->op_type == OP_GREPSTART ? OP_GREPWHILE : OP_MAPWHILE;
10054
10055     PERL_ARGS_ASSERT_CK_GREP;
10056
10057     /* don't allocate gwop here, as we may leak it if PL_parser->error_count > 0 */
10058
10059     if (o->op_flags & OPf_STACKED) {
10060         kid = cUNOPx(OpSIBLING(cLISTOPo->op_first))->op_first;
10061         if (kid->op_type != OP_SCOPE && kid->op_type != OP_LEAVE)
10062             return no_fh_allowed(o);
10063         o->op_flags &= ~OPf_STACKED;
10064     }
10065     kid = OpSIBLING(cLISTOPo->op_first);
10066     if (type == OP_MAPWHILE)
10067         list(kid);
10068     else
10069         scalar(kid);
10070     o = ck_fun(o);
10071     if (PL_parser && PL_parser->error_count)
10072         return o;
10073     kid = OpSIBLING(cLISTOPo->op_first);
10074     if (kid->op_type != OP_NULL)
10075         Perl_croak(aTHX_ "panic: ck_grep, type=%u", (unsigned) kid->op_type);
10076     kid = kUNOP->op_first;
10077
10078     gwop = S_alloc_LOGOP(aTHX_ type, o, LINKLIST(kid));
10079     kid->op_next = (OP*)gwop;
10080     o->op_private = gwop->op_private = 0;
10081     gwop->op_targ = pad_alloc(type, SVs_PADTMP);
10082
10083     kid = OpSIBLING(cLISTOPo->op_first);
10084     for (kid = OpSIBLING(kid); kid; kid = OpSIBLING(kid))
10085         op_lvalue(kid, OP_GREPSTART);
10086
10087     return (OP*)gwop;
10088 }
10089
10090 OP *
10091 Perl_ck_index(pTHX_ OP *o)
10092 {
10093     PERL_ARGS_ASSERT_CK_INDEX;
10094
10095     if (o->op_flags & OPf_KIDS) {
10096         OP *kid = OpSIBLING(cLISTOPo->op_first);        /* get past pushmark */
10097         if (kid)
10098             kid = OpSIBLING(kid);                       /* get past "big" */
10099         if (kid && kid->op_type == OP_CONST) {
10100             const bool save_taint = TAINT_get;
10101             SV *sv = kSVOP->op_sv;
10102             if ((!SvPOK(sv) || SvNIOKp(sv)) && SvOK(sv) && !SvROK(sv)) {
10103                 sv = newSV(0);
10104                 sv_copypv(sv, kSVOP->op_sv);
10105                 SvREFCNT_dec_NN(kSVOP->op_sv);
10106                 kSVOP->op_sv = sv;
10107             }
10108             if (SvOK(sv)) fbm_compile(sv, 0);
10109             TAINT_set(save_taint);
10110 #ifdef NO_TAINT_SUPPORT
10111             PERL_UNUSED_VAR(save_taint);
10112 #endif
10113         }
10114     }
10115     return ck_fun(o);
10116 }
10117
10118 OP *
10119 Perl_ck_lfun(pTHX_ OP *o)
10120 {
10121     const OPCODE type = o->op_type;
10122
10123     PERL_ARGS_ASSERT_CK_LFUN;
10124
10125     return modkids(ck_fun(o), type);
10126 }
10127
10128 OP *
10129 Perl_ck_defined(pTHX_ OP *o)            /* 19990527 MJD */
10130 {
10131     PERL_ARGS_ASSERT_CK_DEFINED;
10132
10133     if ((o->op_flags & OPf_KIDS)) {
10134         switch (cUNOPo->op_first->op_type) {
10135         case OP_RV2AV:
10136         case OP_PADAV:
10137             Perl_croak(aTHX_ "Can't use 'defined(@array)'"
10138                              " (Maybe you should just omit the defined()?)");
10139         break;
10140         case OP_RV2HV:
10141         case OP_PADHV:
10142             Perl_croak(aTHX_ "Can't use 'defined(%%hash)'"
10143                              " (Maybe you should just omit the defined()?)");
10144             break;
10145         default:
10146             /* no warning */
10147             break;
10148         }
10149     }
10150     return ck_rfun(o);
10151 }
10152
10153 OP *
10154 Perl_ck_readline(pTHX_ OP *o)
10155 {
10156     PERL_ARGS_ASSERT_CK_READLINE;
10157
10158     if (o->op_flags & OPf_KIDS) {
10159          OP *kid = cLISTOPo->op_first;
10160          if (kid->op_type == OP_RV2GV) kid->op_private |= OPpALLOW_FAKE;
10161     }
10162     else {
10163         OP * const newop
10164             = newUNOP(OP_READLINE, 0, newGVOP(OP_GV, 0, PL_argvgv));
10165         op_free(o);
10166         return newop;
10167     }
10168     return o;
10169 }
10170
10171 OP *
10172 Perl_ck_rfun(pTHX_ OP *o)
10173 {
10174     const OPCODE type = o->op_type;
10175
10176     PERL_ARGS_ASSERT_CK_RFUN;
10177
10178     return refkids(ck_fun(o), type);
10179 }
10180
10181 OP *
10182 Perl_ck_listiob(pTHX_ OP *o)
10183 {
10184     OP *kid;
10185
10186     PERL_ARGS_ASSERT_CK_LISTIOB;
10187
10188     kid = cLISTOPo->op_first;
10189     if (!kid) {
10190         o = force_list(o, 1);
10191         kid = cLISTOPo->op_first;
10192     }
10193     if (kid->op_type == OP_PUSHMARK)
10194         kid = OpSIBLING(kid);
10195     if (kid && o->op_flags & OPf_STACKED)
10196         kid = OpSIBLING(kid);
10197     else if (kid && !OpHAS_SIBLING(kid)) {              /* print HANDLE; */
10198         if (kid->op_type == OP_CONST && kid->op_private & OPpCONST_BARE
10199          && !kid->op_folded) {
10200             o->op_flags |= OPf_STACKED; /* make it a filehandle */
10201             scalar(kid);
10202             /* replace old const op with new OP_RV2GV parent */
10203             kid = S_op_sibling_newUNOP(aTHX_ o, cLISTOPo->op_first,
10204                                         OP_RV2GV, OPf_REF);
10205             kid = OpSIBLING(kid);
10206         }
10207     }
10208
10209     if (!kid)
10210         op_append_elem(o->op_type, o, newDEFSVOP());
10211
10212     if (o->op_type == OP_PRTF) return modkids(listkids(o), OP_PRTF);
10213     return listkids(o);
10214 }
10215
10216 OP *
10217 Perl_ck_smartmatch(pTHX_ OP *o)
10218 {
10219     dVAR;
10220     PERL_ARGS_ASSERT_CK_SMARTMATCH;
10221     if (0 == (o->op_flags & OPf_SPECIAL)) {
10222         OP *first  = cBINOPo->op_first;
10223         OP *second = OpSIBLING(first);
10224         
10225         /* Implicitly take a reference to an array or hash */
10226
10227         /* remove the original two siblings, then add back the
10228          * (possibly different) first and second sibs.
10229          */
10230         op_sibling_splice(o, NULL, 1, NULL);
10231         op_sibling_splice(o, NULL, 1, NULL);
10232         first  = ref_array_or_hash(first);
10233         second = ref_array_or_hash(second);
10234         op_sibling_splice(o, NULL, 0, second);
10235         op_sibling_splice(o, NULL, 0, first);
10236         
10237         /* Implicitly take a reference to a regular expression */
10238         if (first->op_type == OP_MATCH) {
10239             OpTYPE_set(first, OP_QR);
10240         }
10241         if (second->op_type == OP_MATCH) {
10242             OpTYPE_set(second, OP_QR);
10243         }
10244     }
10245     
10246     return o;
10247 }
10248
10249
10250 static OP *
10251 S_maybe_targlex(pTHX_ OP *o)
10252 {
10253     OP * const kid = cLISTOPo->op_first;
10254     /* has a disposable target? */
10255     if ((PL_opargs[kid->op_type] & OA_TARGLEX)
10256         && !(kid->op_flags & OPf_STACKED)
10257         /* Cannot steal the second time! */
10258         && !(kid->op_private & OPpTARGET_MY)
10259         )
10260     {
10261         OP * const kkid = OpSIBLING(kid);
10262
10263         /* Can just relocate the target. */
10264         if (kkid && kkid->op_type == OP_PADSV
10265             && (!(kkid->op_private & OPpLVAL_INTRO)
10266                || kkid->op_private & OPpPAD_STATE))
10267         {
10268             kid->op_targ = kkid->op_targ;
10269             kkid->op_targ = 0;
10270             /* Now we do not need PADSV and SASSIGN.
10271              * Detach kid and free the rest. */
10272             op_sibling_splice(o, NULL, 1, NULL);
10273             op_free(o);
10274             kid->op_private |= OPpTARGET_MY;    /* Used for context settings */
10275             return kid;
10276         }
10277     }
10278     return o;
10279 }
10280
10281 OP *
10282 Perl_ck_sassign(pTHX_ OP *o)
10283 {
10284     dVAR;
10285     OP * const kid = cLISTOPo->op_first;
10286
10287     PERL_ARGS_ASSERT_CK_SASSIGN;
10288
10289     if (OpHAS_SIBLING(kid)) {
10290         OP *kkid = OpSIBLING(kid);
10291         /* For state variable assignment with attributes, kkid is a list op
10292            whose op_last is a padsv. */
10293         if ((kkid->op_type == OP_PADSV ||
10294              (OP_TYPE_IS_OR_WAS(kkid, OP_LIST) &&
10295               (kkid = cLISTOPx(kkid)->op_last)->op_type == OP_PADSV
10296              )
10297             )
10298                 && (kkid->op_private & (OPpLVAL_INTRO|OPpPAD_STATE))
10299                     == (OPpLVAL_INTRO|OPpPAD_STATE)) {
10300             const PADOFFSET target = kkid->op_targ;
10301             OP *const other = newOP(OP_PADSV,
10302                                     kkid->op_flags
10303                                     | ((kkid->op_private & ~OPpLVAL_INTRO) << 8));
10304             OP *const first = newOP(OP_NULL, 0);
10305             OP *const nullop =
10306                 newCONDOP(0, first, o, other);
10307             /* XXX targlex disabled for now; see ticket #124160
10308                 newCONDOP(0, first, S_maybe_targlex(aTHX_ o), other);
10309              */
10310             OP *const condop = first->op_next;
10311
10312             OpTYPE_set(condop, OP_ONCE);
10313             other->op_targ = target;
10314             nullop->op_flags |= OPf_WANT_SCALAR;
10315
10316             /* Store the initializedness of state vars in a separate
10317                pad entry.  */
10318             condop->op_targ =
10319               pad_add_name_pvn("$",1,padadd_NO_DUP_CHECK|padadd_STATE,0,0);
10320             /* hijacking PADSTALE for uninitialized state variables */
10321             SvPADSTALE_on(PAD_SVl(condop->op_targ));
10322
10323             return nullop;
10324         }
10325     }
10326     return S_maybe_targlex(aTHX_ o);
10327 }
10328
10329 OP *
10330 Perl_ck_match(pTHX_ OP *o)
10331 {
10332     PERL_UNUSED_CONTEXT;
10333     PERL_ARGS_ASSERT_CK_MATCH;
10334
10335     if (o->op_type == OP_MATCH || o->op_type == OP_QR)
10336         o->op_private |= OPpRUNTIME;
10337     return o;
10338 }
10339
10340 OP *
10341 Perl_ck_method(pTHX_ OP *o)
10342 {
10343     SV *sv, *methsv, *rclass;
10344     const char* method;
10345     char* compatptr;
10346     int utf8;
10347     STRLEN len, nsplit = 0, i;
10348     OP* new_op;
10349     OP * const kid = cUNOPo->op_first;
10350
10351     PERL_ARGS_ASSERT_CK_METHOD;
10352     if (kid->op_type != OP_CONST) return o;
10353
10354     sv = kSVOP->op_sv;
10355
10356     /* replace ' with :: */
10357     while ((compatptr = strchr(SvPVX(sv), '\''))) {
10358         *compatptr = ':';
10359         sv_insert(sv, compatptr - SvPVX_const(sv), 0, ":", 1);
10360     }
10361
10362     method = SvPVX_const(sv);
10363     len = SvCUR(sv);
10364     utf8 = SvUTF8(sv) ? -1 : 1;
10365
10366     for (i = len - 1; i > 0; --i) if (method[i] == ':') {
10367         nsplit = i+1;
10368         break;
10369     }
10370
10371     methsv = newSVpvn_share(method+nsplit, utf8*(len - nsplit), 0);
10372
10373     if (!nsplit) { /* $proto->method() */
10374         op_free(o);
10375         return newMETHOP_named(OP_METHOD_NAMED, 0, methsv);
10376     }
10377
10378     if (nsplit == 7 && memEQ(method, "SUPER::", nsplit)) { /* $proto->SUPER::method() */
10379         op_free(o);
10380         return newMETHOP_named(OP_METHOD_SUPER, 0, methsv);
10381     }
10382
10383     /* $proto->MyClass::method() and $proto->MyClass::SUPER::method() */
10384     if (nsplit >= 9 && strnEQ(method+nsplit-9, "::SUPER::", 9)) {
10385         rclass = newSVpvn_share(method, utf8*(nsplit-9), 0);
10386         new_op = newMETHOP_named(OP_METHOD_REDIR_SUPER, 0, methsv);
10387     } else {
10388         rclass = newSVpvn_share(method, utf8*(nsplit-2), 0);
10389         new_op = newMETHOP_named(OP_METHOD_REDIR, 0, methsv);
10390     }
10391 #ifdef USE_ITHREADS
10392     op_relocate_sv(&rclass, &cMETHOPx(new_op)->op_rclass_targ);
10393 #else
10394     cMETHOPx(new_op)->op_rclass_sv = rclass;
10395 #endif
10396     op_free(o);
10397     return new_op;
10398 }
10399
10400 OP *
10401 Perl_ck_null(pTHX_ OP *o)
10402 {
10403     PERL_ARGS_ASSERT_CK_NULL;
10404     PERL_UNUSED_CONTEXT;
10405     return o;
10406 }
10407
10408 OP *
10409 Perl_ck_open(pTHX_ OP *o)
10410 {
10411     PERL_ARGS_ASSERT_CK_OPEN;
10412
10413     S_io_hints(aTHX_ o);
10414     {
10415          /* In case of three-arg dup open remove strictness
10416           * from the last arg if it is a bareword. */
10417          OP * const first = cLISTOPx(o)->op_first; /* The pushmark. */
10418          OP * const last  = cLISTOPx(o)->op_last;  /* The bareword. */
10419          OP *oa;
10420          const char *mode;
10421
10422          if ((last->op_type == OP_CONST) &&             /* The bareword. */
10423              (last->op_private & OPpCONST_BARE) &&
10424              (last->op_private & OPpCONST_STRICT) &&
10425              (oa = OpSIBLING(first)) &&         /* The fh. */
10426              (oa = OpSIBLING(oa)) &&                    /* The mode. */
10427              (oa->op_type == OP_CONST) &&
10428              SvPOK(((SVOP*)oa)->op_sv) &&
10429              (mode = SvPVX_const(((SVOP*)oa)->op_sv)) &&
10430              mode[0] == '>' && mode[1] == '&' &&        /* A dup open. */
10431              (last == OpSIBLING(oa)))                   /* The bareword. */
10432               last->op_private &= ~OPpCONST_STRICT;
10433     }
10434     return ck_fun(o);
10435 }
10436
10437 OP *
10438 Perl_ck_prototype(pTHX_ OP *o)
10439 {
10440     PERL_ARGS_ASSERT_CK_PROTOTYPE;
10441     if (!(o->op_flags & OPf_KIDS)) {
10442         op_free(o);
10443         return newUNOP(OP_PROTOTYPE, 0, newDEFSVOP());
10444     }
10445     return o;
10446 }
10447
10448 OP *
10449 Perl_ck_refassign(pTHX_ OP *o)
10450 {
10451     OP * const right = cLISTOPo->op_first;
10452     OP * const left = OpSIBLING(right);
10453     OP *varop = cUNOPx(cUNOPx(left)->op_first)->op_first;
10454     bool stacked = 0;
10455
10456     PERL_ARGS_ASSERT_CK_REFASSIGN;
10457     assert (left);
10458     assert (left->op_type == OP_SREFGEN);
10459
10460     o->op_private = 0;
10461     /* we use OPpPAD_STATE in refassign to mean either of those things,
10462      * and the code assumes the two flags occupy the same bit position
10463      * in the various ops below */
10464     assert(OPpPAD_STATE == OPpOUR_INTRO);
10465
10466     switch (varop->op_type) {
10467     case OP_PADAV:
10468         o->op_private |= OPpLVREF_AV;
10469         goto settarg;
10470     case OP_PADHV:
10471         o->op_private |= OPpLVREF_HV;
10472         /* FALLTHROUGH */
10473     case OP_PADSV:
10474       settarg:
10475         o->op_private |= (varop->op_private & (OPpLVAL_INTRO|OPpPAD_STATE));
10476         o->op_targ = varop->op_targ;
10477         varop->op_targ = 0;
10478         PAD_COMPNAME_GEN_set(o->op_targ, PERL_INT_MAX);
10479         break;
10480
10481     case OP_RV2AV:
10482         o->op_private |= OPpLVREF_AV;
10483         goto checkgv;
10484         NOT_REACHED; /* NOTREACHED */
10485     case OP_RV2HV:
10486         o->op_private |= OPpLVREF_HV;
10487         /* FALLTHROUGH */
10488     case OP_RV2SV:
10489       checkgv:
10490         o->op_private |= (varop->op_private & (OPpLVAL_INTRO|OPpOUR_INTRO));
10491         if (cUNOPx(varop)->op_first->op_type != OP_GV) goto bad;
10492       detach_and_stack:
10493         /* Point varop to its GV kid, detached.  */
10494         varop = op_sibling_splice(varop, NULL, -1, NULL);
10495         stacked = TRUE;
10496         break;
10497     case OP_RV2CV: {
10498         OP * const kidparent =
10499             OpSIBLING(cUNOPx(cUNOPx(varop)->op_first)->op_first);
10500         OP * const kid = cUNOPx(kidparent)->op_first;
10501         o->op_private |= OPpLVREF_CV;
10502         if (kid->op_type == OP_GV) {
10503             varop = kidparent;
10504             goto detach_and_stack;
10505         }
10506         if (kid->op_type != OP_PADCV)   goto bad;
10507         o->op_targ = kid->op_targ;
10508         kid->op_targ = 0;
10509         break;
10510     }
10511     case OP_AELEM:
10512     case OP_HELEM:
10513         o->op_private |= (varop->op_private & OPpLVAL_INTRO);
10514         o->op_private |= OPpLVREF_ELEM;
10515         op_null(varop);
10516         stacked = TRUE;
10517         /* Detach varop.  */
10518         op_sibling_splice(cUNOPx(left)->op_first, NULL, -1, NULL);
10519         break;
10520     default:
10521       bad:
10522         /* diag_listed_as: Can't modify reference to %s in %s assignment */
10523         yyerror(Perl_form(aTHX_ "Can't modify reference to %s in scalar "
10524                                 "assignment",
10525                                  OP_DESC(varop)));
10526         return o;
10527     }
10528     if (!FEATURE_REFALIASING_IS_ENABLED)
10529         Perl_croak(aTHX_
10530                   "Experimental aliasing via reference not enabled");
10531     Perl_ck_warner_d(aTHX_
10532                      packWARN(WARN_EXPERIMENTAL__REFALIASING),
10533                     "Aliasing via reference is experimental");
10534     if (stacked) {
10535         o->op_flags |= OPf_STACKED;
10536         op_sibling_splice(o, right, 1, varop);
10537     }
10538     else {
10539         o->op_flags &=~ OPf_STACKED;
10540         op_sibling_splice(o, right, 1, NULL);
10541     }
10542     op_free(left);
10543     return o;
10544 }
10545
10546 OP *
10547 Perl_ck_repeat(pTHX_ OP *o)
10548 {
10549     PERL_ARGS_ASSERT_CK_REPEAT;
10550
10551     if (cBINOPo->op_first->op_flags & OPf_PARENS) {
10552         OP* kids;
10553         o->op_private |= OPpREPEAT_DOLIST;
10554         kids = op_sibling_splice(o, NULL, 1, NULL); /* detach first kid */
10555         kids = force_list(kids, 1); /* promote it to a list */
10556         op_sibling_splice(o, NULL, 0, kids); /* and add back */
10557     }
10558     else
10559         scalar(o);
10560     return o;
10561 }
10562
10563 OP *
10564 Perl_ck_require(pTHX_ OP *o)
10565 {
10566     GV* gv;
10567
10568     PERL_ARGS_ASSERT_CK_REQUIRE;
10569
10570     if (o->op_flags & OPf_KIDS) {       /* Shall we supply missing .pm? */
10571         SVOP * const kid = (SVOP*)cUNOPo->op_first;
10572         HEK *hek;
10573         U32 hash;
10574         char *s;
10575         STRLEN len;
10576         if (kid->op_type == OP_CONST) {
10577           SV * const sv = kid->op_sv;
10578           U32 const was_readonly = SvREADONLY(sv);
10579           if (kid->op_private & OPpCONST_BARE) {
10580             dVAR;
10581             const char *end;
10582
10583             if (was_readonly) {
10584                     SvREADONLY_off(sv);
10585             }   
10586             if (SvIsCOW(sv)) sv_force_normal_flags(sv, 0);
10587
10588             s = SvPVX(sv);
10589             len = SvCUR(sv);
10590             end = s + len;
10591             for (; s < end; s++) {
10592                 if (*s == ':' && s[1] == ':') {
10593                     *s = '/';
10594                     Move(s+2, s+1, end - s - 1, char);
10595                     --end;
10596                 }
10597             }
10598             SvEND_set(sv, end);
10599             sv_catpvs(sv, ".pm");
10600             PERL_HASH(hash, SvPVX(sv), SvCUR(sv));
10601             hek = share_hek(SvPVX(sv),
10602                             (SSize_t)SvCUR(sv) * (SvUTF8(sv) ? -1 : 1),
10603                             hash);
10604             sv_sethek(sv, hek);
10605             unshare_hek(hek);
10606             SvFLAGS(sv) |= was_readonly;
10607           }
10608           else if (SvPOK(sv) && !SvNIOK(sv) && !SvGMAGICAL(sv)
10609                 && !SvVOK(sv)) {
10610             s = SvPV(sv, len);
10611             if (SvREFCNT(sv) > 1) {
10612                 kid->op_sv = newSVpvn_share(
10613                     s, SvUTF8(sv) ? -(SSize_t)len : (SSize_t)len, 0);
10614                 SvREFCNT_dec_NN(sv);
10615             }
10616             else {
10617                 dVAR;
10618                 if (was_readonly) SvREADONLY_off(sv);
10619                 PERL_HASH(hash, s, len);
10620                 hek = share_hek(s,
10621                                 SvUTF8(sv) ? -(SSize_t)len : (SSize_t)len,
10622                                 hash);
10623                 sv_sethek(sv, hek);
10624                 unshare_hek(hek);
10625                 SvFLAGS(sv) |= was_readonly;
10626             }
10627           }
10628         }
10629     }
10630
10631     if (!(o->op_flags & OPf_SPECIAL) /* Wasn't written as CORE::require */
10632         /* handle override, if any */
10633      && (gv = gv_override("require", 7))) {
10634         OP *kid, *newop;
10635         if (o->op_flags & OPf_KIDS) {
10636             kid = cUNOPo->op_first;
10637             op_sibling_splice(o, NULL, -1, NULL);
10638         }
10639         else {
10640             kid = newDEFSVOP();
10641         }
10642         op_free(o);
10643         newop = S_new_entersubop(aTHX_ gv, kid);
10644         return newop;
10645     }
10646
10647     return ck_fun(o);
10648 }
10649
10650 OP *
10651 Perl_ck_return(pTHX_ OP *o)
10652 {
10653     OP *kid;
10654
10655     PERL_ARGS_ASSERT_CK_RETURN;
10656
10657     kid = OpSIBLING(cLISTOPo->op_first);
10658     if (CvLVALUE(PL_compcv)) {
10659         for (; kid; kid = OpSIBLING(kid))
10660             op_lvalue(kid, OP_LEAVESUBLV);
10661     }
10662
10663     return o;
10664 }
10665
10666 OP *
10667 Perl_ck_select(pTHX_ OP *o)
10668 {
10669     dVAR;
10670     OP* kid;
10671
10672     PERL_ARGS_ASSERT_CK_SELECT;
10673
10674     if (o->op_flags & OPf_KIDS) {
10675         kid = OpSIBLING(cLISTOPo->op_first);     /* get past pushmark */
10676         if (kid && OpHAS_SIBLING(kid)) {
10677             OpTYPE_set(o, OP_SSELECT);
10678             o = ck_fun(o);
10679             return fold_constants(op_integerize(op_std_init(o)));
10680         }
10681     }
10682     o = ck_fun(o);
10683     kid = OpSIBLING(cLISTOPo->op_first);    /* get past pushmark */
10684     if (kid && kid->op_type == OP_RV2GV)
10685         kid->op_private &= ~HINT_STRICT_REFS;
10686     return o;
10687 }
10688
10689 OP *
10690 Perl_ck_shift(pTHX_ OP *o)
10691 {
10692     const I32 type = o->op_type;
10693
10694     PERL_ARGS_ASSERT_CK_SHIFT;
10695
10696     if (!(o->op_flags & OPf_KIDS)) {
10697         OP *argop;
10698
10699         if (!CvUNIQUE(PL_compcv)) {
10700             o->op_flags |= OPf_SPECIAL;
10701             return o;
10702         }
10703
10704         argop = newUNOP(OP_RV2AV, 0, scalar(newGVOP(OP_GV, 0, PL_argvgv)));
10705         op_free(o);
10706         return newUNOP(type, 0, scalar(argop));
10707     }
10708     return scalar(ck_fun(o));
10709 }
10710
10711 OP *
10712 Perl_ck_sort(pTHX_ OP *o)
10713 {
10714     OP *firstkid;
10715     OP *kid;
10716     HV * const hinthv =
10717         PL_hints & HINT_LOCALIZE_HH ? GvHV(PL_hintgv) : NULL;
10718     U8 stacked;
10719
10720     PERL_ARGS_ASSERT_CK_SORT;
10721
10722     if (hinthv) {
10723             SV ** const svp = hv_fetchs(hinthv, "sort", FALSE);
10724             if (svp) {
10725                 const I32 sorthints = (I32)SvIV(*svp);
10726                 if ((sorthints & HINT_SORT_QUICKSORT) != 0)
10727                     o->op_private |= OPpSORT_QSORT;
10728                 if ((sorthints & HINT_SORT_STABLE) != 0)
10729                     o->op_private |= OPpSORT_STABLE;
10730             }
10731     }
10732
10733     if (o->op_flags & OPf_STACKED)
10734         simplify_sort(o);
10735     firstkid = OpSIBLING(cLISTOPo->op_first);           /* get past pushmark */
10736
10737     if ((stacked = o->op_flags & OPf_STACKED)) {        /* may have been cleared */
10738         OP *kid = cUNOPx(firstkid)->op_first;           /* get past null */
10739
10740         /* if the first arg is a code block, process it and mark sort as
10741          * OPf_SPECIAL */
10742         if (kid->op_type == OP_SCOPE || kid->op_type == OP_LEAVE) {
10743             LINKLIST(kid);
10744             if (kid->op_type == OP_LEAVE)
10745                     op_null(kid);                       /* wipe out leave */
10746             /* Prevent execution from escaping out of the sort block. */
10747             kid->op_next = 0;
10748
10749             /* provide scalar context for comparison function/block */
10750             kid = scalar(firstkid);
10751             kid->op_next = kid;
10752             o->op_flags |= OPf_SPECIAL;
10753         }
10754         else if (kid->op_type == OP_CONST
10755               && kid->op_private & OPpCONST_BARE) {
10756             char tmpbuf[256];
10757             STRLEN len;
10758             PADOFFSET off;
10759             const char * const name = SvPV(kSVOP_sv, len);
10760             *tmpbuf = '&';
10761             assert (len < 256);
10762             Copy(name, tmpbuf+1, len, char);
10763             off = pad_findmy_pvn(tmpbuf, len+1, SvUTF8(kSVOP_sv));
10764             if (off != NOT_IN_PAD) {
10765                 if (PAD_COMPNAME_FLAGS_isOUR(off)) {
10766                     SV * const fq =
10767                         newSVhek(HvNAME_HEK(PAD_COMPNAME_OURSTASH(off)));
10768                     sv_catpvs(fq, "::");
10769                     sv_catsv(fq, kSVOP_sv);
10770                     SvREFCNT_dec_NN(kSVOP_sv);
10771                     kSVOP->op_sv = fq;
10772                 }
10773                 else {
10774                     OP * const padop = newOP(OP_PADCV, 0);
10775                     padop->op_targ = off;
10776                     /* replace the const op with the pad op */
10777                     op_sibling_splice(firstkid, NULL, 1, padop);
10778                     op_free(kid);
10779                 }
10780             }
10781         }
10782
10783         firstkid = OpSIBLING(firstkid);
10784     }
10785
10786     for (kid = firstkid; kid; kid = OpSIBLING(kid)) {
10787         /* provide list context for arguments */
10788         list(kid);
10789         if (stacked)
10790             op_lvalue(kid, OP_GREPSTART);
10791     }
10792
10793     return o;
10794 }
10795
10796 /* for sort { X } ..., where X is one of
10797  *   $a <=> $b, $b <= $a, $a cmp $b, $b cmp $a
10798  * elide the second child of the sort (the one containing X),
10799  * and set these flags as appropriate
10800         OPpSORT_NUMERIC;
10801         OPpSORT_INTEGER;
10802         OPpSORT_DESCEND;
10803  * Also, check and warn on lexical $a, $b.
10804  */
10805
10806 STATIC void
10807 S_simplify_sort(pTHX_ OP *o)
10808 {
10809     OP *kid = OpSIBLING(cLISTOPo->op_first);    /* get past pushmark */
10810     OP *k;
10811     int descending;
10812     GV *gv;
10813     const char *gvname;
10814     bool have_scopeop;
10815
10816     PERL_ARGS_ASSERT_SIMPLIFY_SORT;
10817
10818     kid = kUNOP->op_first;                              /* get past null */
10819     if (!(have_scopeop = kid->op_type == OP_SCOPE)
10820      && kid->op_type != OP_LEAVE)
10821         return;
10822     kid = kLISTOP->op_last;                             /* get past scope */
10823     switch(kid->op_type) {
10824         case OP_NCMP:
10825         case OP_I_NCMP:
10826         case OP_SCMP:
10827             if (!have_scopeop) goto padkids;
10828             break;
10829         default:
10830             return;
10831     }
10832     k = kid;                                            /* remember this node*/
10833     if (kBINOP->op_first->op_type != OP_RV2SV
10834      || kBINOP->op_last ->op_type != OP_RV2SV)
10835     {
10836         /*
10837            Warn about my($a) or my($b) in a sort block, *if* $a or $b is
10838            then used in a comparison.  This catches most, but not
10839            all cases.  For instance, it catches
10840                sort { my($a); $a <=> $b }
10841            but not
10842                sort { my($a); $a < $b ? -1 : $a == $b ? 0 : 1; }
10843            (although why you'd do that is anyone's guess).
10844         */
10845
10846        padkids:
10847         if (!ckWARN(WARN_SYNTAX)) return;
10848         kid = kBINOP->op_first;
10849         do {
10850             if (kid->op_type == OP_PADSV) {
10851                 PADNAME * const name = PAD_COMPNAME(kid->op_targ);
10852                 if (PadnameLEN(name) == 2 && *PadnamePV(name) == '$'
10853                  && (  PadnamePV(name)[1] == 'a'
10854                     || PadnamePV(name)[1] == 'b'  ))
10855                     /* diag_listed_as: "my %s" used in sort comparison */
10856                     Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
10857                                      "\"%s %s\" used in sort comparison",
10858                                       PadnameIsSTATE(name)
10859                                         ? "state"
10860                                         : "my",
10861                                       PadnamePV(name));
10862             }
10863         } while ((kid = OpSIBLING(kid)));
10864         return;
10865     }
10866     kid = kBINOP->op_first;                             /* get past cmp */
10867     if (kUNOP->op_first->op_type != OP_GV)
10868         return;
10869     kid = kUNOP->op_first;                              /* get past rv2sv */
10870     gv = kGVOP_gv;
10871     if (GvSTASH(gv) != PL_curstash)
10872         return;
10873     gvname = GvNAME(gv);
10874     if (*gvname == 'a' && gvname[1] == '\0')
10875         descending = 0;
10876     else if (*gvname == 'b' && gvname[1] == '\0')
10877         descending = 1;
10878     else
10879         return;
10880
10881     kid = k;                                            /* back to cmp */
10882     /* already checked above that it is rv2sv */
10883     kid = kBINOP->op_last;                              /* down to 2nd arg */
10884     if (kUNOP->op_first->op_type != OP_GV)
10885         return;
10886     kid = kUNOP->op_first;                              /* get past rv2sv */
10887     gv = kGVOP_gv;
10888     if (GvSTASH(gv) != PL_curstash)
10889         return;
10890     gvname = GvNAME(gv);
10891     if ( descending
10892          ? !(*gvname == 'a' && gvname[1] == '\0')
10893          : !(*gvname == 'b' && gvname[1] == '\0'))
10894         return;
10895     o->op_flags &= ~(OPf_STACKED | OPf_SPECIAL);
10896     if (descending)
10897         o->op_private |= OPpSORT_DESCEND;
10898     if (k->op_type == OP_NCMP)
10899         o->op_private |= OPpSORT_NUMERIC;
10900     if (k->op_type == OP_I_NCMP)
10901         o->op_private |= OPpSORT_NUMERIC | OPpSORT_INTEGER;
10902     kid = OpSIBLING(cLISTOPo->op_first);
10903     /* cut out and delete old block (second sibling) */
10904     op_sibling_splice(o, cLISTOPo->op_first, 1, NULL);
10905     op_free(kid);
10906 }
10907
10908 OP *
10909 Perl_ck_split(pTHX_ OP *o)
10910 {
10911     dVAR;
10912     OP *kid;
10913
10914     PERL_ARGS_ASSERT_CK_SPLIT;
10915
10916     if (o->op_flags & OPf_STACKED)
10917         return no_fh_allowed(o);
10918
10919     kid = cLISTOPo->op_first;
10920     if (kid->op_type != OP_NULL)
10921         Perl_croak(aTHX_ "panic: ck_split, type=%u", (unsigned) kid->op_type);
10922     /* delete leading NULL node, then add a CONST if no other nodes */
10923     op_sibling_splice(o, NULL, 1,
10924         OpHAS_SIBLING(kid) ? NULL : newSVOP(OP_CONST, 0, newSVpvs(" ")));
10925     op_free(kid);
10926     kid = cLISTOPo->op_first;
10927
10928     if (kid->op_type != OP_MATCH || kid->op_flags & OPf_STACKED) {
10929         /* remove kid, and replace with new optree */
10930         op_sibling_splice(o, NULL, 1, NULL);
10931         /* OPf_SPECIAL is used to trigger split " " behavior */
10932         kid = pmruntime( newPMOP(OP_MATCH, OPf_SPECIAL), kid, NULL, 0, 0);
10933         op_sibling_splice(o, NULL, 0, kid);
10934     }
10935     OpTYPE_set(kid, OP_PUSHRE);
10936     /* target implies @ary=..., so wipe it */
10937     kid->op_targ = 0;
10938     scalar(kid);
10939     if (((PMOP *)kid)->op_pmflags & PMf_GLOBAL) {
10940       Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP),
10941                      "Use of /g modifier is meaningless in split");
10942     }
10943
10944     if (!OpHAS_SIBLING(kid))
10945         op_append_elem(OP_SPLIT, o, newDEFSVOP());
10946
10947     kid = OpSIBLING(kid);
10948     assert(kid);
10949     scalar(kid);
10950
10951     if (!OpHAS_SIBLING(kid))
10952     {
10953         op_append_elem(OP_SPLIT, o, newSVOP(OP_CONST, 0, newSViv(0)));
10954         o->op_private |= OPpSPLIT_IMPLIM;
10955     }
10956     assert(OpHAS_SIBLING(kid));
10957
10958     kid = OpSIBLING(kid);
10959     scalar(kid);
10960
10961     if (OpHAS_SIBLING(kid))
10962         return too_many_arguments_pv(o,OP_DESC(o), 0);
10963
10964     return o;
10965 }
10966
10967 OP *
10968 Perl_ck_stringify(pTHX_ OP *o)
10969 {
10970     OP * const kid = OpSIBLING(cUNOPo->op_first);
10971     PERL_ARGS_ASSERT_CK_STRINGIFY;
10972     if ((   kid->op_type == OP_JOIN || kid->op_type == OP_QUOTEMETA
10973          || kid->op_type == OP_LC   || kid->op_type == OP_LCFIRST
10974          || kid->op_type == OP_UC   || kid->op_type == OP_UCFIRST)
10975         && !OpHAS_SIBLING(kid)) /* syntax errs can leave extra children */
10976     {
10977         op_sibling_splice(o, cUNOPo->op_first, -1, NULL);
10978         op_free(o);
10979         return kid;
10980     }
10981     return ck_fun(o);
10982 }
10983         
10984 OP *
10985 Perl_ck_join(pTHX_ OP *o)
10986 {
10987     OP * const kid = OpSIBLING(cLISTOPo->op_first);
10988
10989     PERL_ARGS_ASSERT_CK_JOIN;
10990
10991     if (kid && kid->op_type == OP_MATCH) {
10992         if (ckWARN(WARN_SYNTAX)) {
10993             const REGEXP *re = PM_GETRE(kPMOP);
10994             const SV *msg = re
10995                     ? newSVpvn_flags( RX_PRECOMP_const(re), RX_PRELEN(re),
10996                                             SVs_TEMP | ( RX_UTF8(re) ? SVf_UTF8 : 0 ) )
10997                     : newSVpvs_flags( "STRING", SVs_TEMP );
10998             Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
10999                         "/%"SVf"/ should probably be written as \"%"SVf"\"",
11000                         SVfARG(msg), SVfARG(msg));
11001         }
11002     }
11003     if (kid
11004      && (kid->op_type == OP_CONST /* an innocent, unsuspicious separator */
11005         || (kid->op_type == OP_PADSV && !(kid->op_private & OPpLVAL_INTRO))
11006         || (  kid->op_type==OP_RV2SV && kUNOP->op_first->op_type == OP_GV
11007            && !(kid->op_private & (OPpLVAL_INTRO|OPpOUR_INTRO)))))
11008     {
11009         const OP * const bairn = OpSIBLING(kid); /* the list */
11010         if (bairn && !OpHAS_SIBLING(bairn) /* single-item list */
11011          && OP_GIMME(bairn,0) == G_SCALAR)
11012         {
11013             OP * const ret = op_convert_list(OP_STRINGIFY, OPf_FOLDED,
11014                                      op_sibling_splice(o, kid, 1, NULL));
11015             op_free(o);
11016             return ret;
11017         }
11018     }
11019
11020     return ck_fun(o);
11021 }
11022
11023 /*
11024 =for apidoc Am|CV *|rv2cv_op_cv|OP *cvop|U32 flags
11025
11026 Examines an op, which is expected to identify a subroutine at runtime,
11027 and attempts to determine at compile time which subroutine it identifies.
11028 This is normally used during Perl compilation to determine whether
11029 a prototype can be applied to a function call.  C<cvop> is the op
11030 being considered, normally an C<rv2cv> op.  A pointer to the identified
11031 subroutine is returned, if it could be determined statically, and a null
11032 pointer is returned if it was not possible to determine statically.
11033
11034 Currently, the subroutine can be identified statically if the RV that the
11035 C<rv2cv> is to operate on is provided by a suitable C<gv> or C<const> op.
11036 A C<gv> op is suitable if the GV's CV slot is populated.  A C<const> op is
11037 suitable if the constant value must be an RV pointing to a CV.  Details of
11038 this process may change in future versions of Perl.  If the C<rv2cv> op
11039 has the C<OPpENTERSUB_AMPER> flag set then no attempt is made to identify
11040 the subroutine statically: this flag is used to suppress compile-time
11041 magic on a subroutine call, forcing it to use default runtime behaviour.
11042
11043 If C<flags> has the bit C<RV2CVOPCV_MARK_EARLY> set, then the handling
11044 of a GV reference is modified.  If a GV was examined and its CV slot was
11045 found to be empty, then the C<gv> op has the C<OPpEARLY_CV> flag set.
11046 If the op is not optimised away, and the CV slot is later populated with
11047 a subroutine having a prototype, that flag eventually triggers the warning
11048 "called too early to check prototype".
11049
11050 If C<flags> has the bit C<RV2CVOPCV_RETURN_NAME_GV> set, then instead
11051 of returning a pointer to the subroutine it returns a pointer to the
11052 GV giving the most appropriate name for the subroutine in this context.
11053 Normally this is just the C<CvGV> of the subroutine, but for an anonymous
11054 (C<CvANON>) subroutine that is referenced through a GV it will be the
11055 referencing GV.  The resulting C<GV*> is cast to C<CV*> to be returned.
11056 A null pointer is returned as usual if there is no statically-determinable
11057 subroutine.
11058
11059 =cut
11060 */
11061
11062 /* shared by toke.c:yylex */
11063 CV *
11064 Perl_find_lexical_cv(pTHX_ PADOFFSET off)
11065 {
11066     PADNAME *name = PAD_COMPNAME(off);
11067     CV *compcv = PL_compcv;
11068     while (PadnameOUTER(name)) {
11069         assert(PARENT_PAD_INDEX(name));
11070         compcv = CvOUTSIDE(compcv);
11071         name = PadlistNAMESARRAY(CvPADLIST(compcv))
11072                 [off = PARENT_PAD_INDEX(name)];
11073     }
11074     assert(!PadnameIsOUR(name));
11075     if (!PadnameIsSTATE(name) && PadnamePROTOCV(name)) {
11076         return PadnamePROTOCV(name);
11077     }
11078     return (CV *)AvARRAY(PadlistARRAY(CvPADLIST(compcv))[1])[off];
11079 }
11080
11081 CV *
11082 Perl_rv2cv_op_cv(pTHX_ OP *cvop, U32 flags)
11083 {
11084     OP *rvop;
11085     CV *cv;
11086     GV *gv;
11087     PERL_ARGS_ASSERT_RV2CV_OP_CV;
11088     if (flags & ~RV2CVOPCV_FLAG_MASK)
11089         Perl_croak(aTHX_ "panic: rv2cv_op_cv bad flags %x", (unsigned)flags);
11090     if (cvop->op_type != OP_RV2CV)
11091         return NULL;
11092     if (cvop->op_private & OPpENTERSUB_AMPER)
11093         return NULL;
11094     if (!(cvop->op_flags & OPf_KIDS))
11095         return NULL;
11096     rvop = cUNOPx(cvop)->op_first;
11097     switch (rvop->op_type) {
11098         case OP_GV: {
11099             gv = cGVOPx_gv(rvop);
11100             if (!isGV(gv)) {
11101                 if (SvROK(gv) && SvTYPE(SvRV(gv)) == SVt_PVCV) {
11102                     cv = MUTABLE_CV(SvRV(gv));
11103                     gv = NULL;
11104                     break;
11105                 }
11106                 if (flags & RV2CVOPCV_RETURN_STUB)
11107                     return (CV *)gv;
11108                 else return NULL;
11109             }
11110             cv = GvCVu(gv);
11111             if (!cv) {
11112                 if (flags & RV2CVOPCV_MARK_EARLY)
11113                     rvop->op_private |= OPpEARLY_CV;
11114                 return NULL;
11115             }
11116         } break;
11117         case OP_CONST: {
11118             SV *rv = cSVOPx_sv(rvop);
11119             if (!SvROK(rv))
11120                 return NULL;
11121             cv = (CV*)SvRV(rv);
11122             gv = NULL;
11123         } break;
11124         case OP_PADCV: {
11125             cv = find_lexical_cv(rvop->op_targ);
11126             gv = NULL;
11127         } break;
11128         default: {
11129             return NULL;
11130         } NOT_REACHED; /* NOTREACHED */
11131     }
11132     if (SvTYPE((SV*)cv) != SVt_PVCV)
11133         return NULL;
11134     if (flags & (RV2CVOPCV_RETURN_NAME_GV|RV2CVOPCV_MAYBE_NAME_GV)) {
11135         if ((!CvANON(cv) || !gv) && !CvLEXICAL(cv)
11136          && ((flags & RV2CVOPCV_RETURN_NAME_GV) || !CvNAMED(cv)))
11137             gv = CvGV(cv);
11138         return (CV*)gv;
11139     } else {
11140         return cv;
11141     }
11142 }
11143
11144 /*
11145 =for apidoc Am|OP *|ck_entersub_args_list|OP *entersubop
11146
11147 Performs the default fixup of the arguments part of an C<entersub>
11148 op tree.  This consists of applying list context to each of the
11149 argument ops.  This is the standard treatment used on a call marked
11150 with C<&>, or a method call, or a call through a subroutine reference,
11151 or any other call where the callee can't be identified at compile time,
11152 or a call where the callee has no prototype.
11153
11154 =cut
11155 */
11156
11157 OP *
11158 Perl_ck_entersub_args_list(pTHX_ OP *entersubop)
11159 {
11160     OP *aop;
11161
11162     PERL_ARGS_ASSERT_CK_ENTERSUB_ARGS_LIST;
11163
11164     aop = cUNOPx(entersubop)->op_first;
11165     if (!OpHAS_SIBLING(aop))
11166         aop = cUNOPx(aop)->op_first;
11167     for (aop = OpSIBLING(aop); OpHAS_SIBLING(aop); aop = OpSIBLING(aop)) {
11168         /* skip the extra attributes->import() call implicitly added in
11169          * something like foo(my $x : bar)
11170          */
11171         if (   aop->op_type == OP_ENTERSUB
11172             && (aop->op_flags & OPf_WANT) == OPf_WANT_VOID
11173         )
11174             continue;
11175         list(aop);
11176         op_lvalue(aop, OP_ENTERSUB);
11177     }
11178     return entersubop;
11179 }
11180
11181 /*
11182 =for apidoc Am|OP *|ck_entersub_args_proto|OP *entersubop|GV *namegv|SV *protosv
11183
11184 Performs the fixup of the arguments part of an C<entersub> op tree
11185 based on a subroutine prototype.  This makes various modifications to
11186 the argument ops, from applying context up to inserting C<refgen> ops,
11187 and checking the number and syntactic types of arguments, as directed by
11188 the prototype.  This is the standard treatment used on a subroutine call,
11189 not marked with C<&>, where the callee can be identified at compile time
11190 and has a prototype.
11191
11192 C<protosv> supplies the subroutine prototype to be applied to the call.
11193 It may be a normal defined scalar, of which the string value will be used.
11194 Alternatively, for convenience, it may be a subroutine object (a C<CV*>
11195 that has been cast to C<SV*>) which has a prototype.  The prototype
11196 supplied, in whichever form, does not need to match the actual callee
11197 referenced by the op tree.
11198
11199 If the argument ops disagree with the prototype, for example by having
11200 an unacceptable number of arguments, a valid op tree is returned anyway.
11201 The error is reflected in the parser state, normally resulting in a single
11202 exception at the top level of parsing which covers all the compilation
11203 errors that occurred.  In the error message, the callee is referred to
11204 by the name defined by the C<namegv> parameter.
11205
11206 =cut
11207 */
11208
11209 OP *
11210 Perl_ck_entersub_args_proto(pTHX_ OP *entersubop, GV *namegv, SV *protosv)
11211 {
11212     STRLEN proto_len;
11213     const char *proto, *proto_end;
11214     OP *aop, *prev, *cvop, *parent;
11215     int optional = 0;
11216     I32 arg = 0;
11217     I32 contextclass = 0;
11218     const char *e = NULL;
11219     PERL_ARGS_ASSERT_CK_ENTERSUB_ARGS_PROTO;
11220     if (SvTYPE(protosv) == SVt_PVCV ? !SvPOK(protosv) : !SvOK(protosv))
11221         Perl_croak(aTHX_ "panic: ck_entersub_args_proto CV with no proto, "
11222                    "flags=%lx", (unsigned long) SvFLAGS(protosv));
11223     if (SvTYPE(protosv) == SVt_PVCV)
11224          proto = CvPROTO(protosv), proto_len = CvPROTOLEN(protosv);
11225     else proto = SvPV(protosv, proto_len);
11226     proto = S_strip_spaces(aTHX_ proto, &proto_len);
11227     proto_end = proto + proto_len;
11228     parent = entersubop;
11229     aop = cUNOPx(entersubop)->op_first;
11230     if (!OpHAS_SIBLING(aop)) {
11231         parent = aop;
11232         aop = cUNOPx(aop)->op_first;
11233     }
11234     prev = aop;
11235     aop = OpSIBLING(aop);
11236     for (cvop = aop; OpHAS_SIBLING(cvop); cvop = OpSIBLING(cvop)) ;
11237     while (aop != cvop) {
11238         OP* o3 = aop;
11239
11240         if (proto >= proto_end)
11241         {
11242             SV * const namesv = cv_name((CV *)namegv, NULL, 0);
11243             yyerror_pv(Perl_form(aTHX_ "Too many arguments for %"SVf,
11244                                         SVfARG(namesv)), SvUTF8(namesv));
11245             return entersubop;
11246         }
11247
11248         switch (*proto) {
11249             case ';':
11250                 optional = 1;
11251                 proto++;
11252                 continue;
11253             case '_':
11254                 /* _ must be at the end */
11255                 if (proto[1] && !strchr(";@%", proto[1]))
11256                     goto oops;
11257                 /* FALLTHROUGH */
11258             case '$':
11259                 proto++;
11260                 arg++;
11261                 scalar(aop);
11262                 break;
11263             case '%':
11264             case '@':
11265                 list(aop);
11266                 arg++;
11267                 break;
11268             case '&':
11269                 proto++;
11270                 arg++;
11271                 if (    o3->op_type != OP_UNDEF
11272                     && (o3->op_type != OP_SREFGEN
11273                         || (  cUNOPx(cUNOPx(o3)->op_first)->op_first->op_type
11274                                 != OP_ANONCODE
11275                             && cUNOPx(cUNOPx(o3)->op_first)->op_first->op_type
11276                                 != OP_RV2CV)))
11277                     bad_type_gv(arg, namegv, o3,
11278                             arg == 1 ? "block or sub {}" : "sub {}");
11279                 break;
11280             case '*':
11281                 /* '*' allows any scalar type, including bareword */
11282                 proto++;
11283                 arg++;
11284                 if (o3->op_type == OP_RV2GV)
11285                     goto wrapref;       /* autoconvert GLOB -> GLOBref */
11286                 else if (o3->op_type == OP_CONST)
11287                     o3->op_private &= ~OPpCONST_STRICT;
11288                 scalar(aop);
11289                 break;
11290             case '+':
11291                 proto++;
11292                 arg++;
11293                 if (o3->op_type == OP_RV2AV ||
11294                     o3->op_type == OP_PADAV ||
11295                     o3->op_type == OP_RV2HV ||
11296                     o3->op_type == OP_PADHV
11297                 ) {
11298                     goto wrapref;
11299                 }
11300                 scalar(aop);
11301                 break;
11302             case '[': case ']':
11303                 goto oops;
11304
11305             case '\\':
11306                 proto++;
11307                 arg++;
11308             again:
11309                 switch (*proto++) {
11310                     case '[':
11311                         if (contextclass++ == 0) {
11312                             e = strchr(proto, ']');
11313                             if (!e || e == proto)
11314                                 goto oops;
11315                         }
11316                         else
11317                             goto oops;
11318                         goto again;
11319
11320                     case ']':
11321                         if (contextclass) {
11322                             const char *p = proto;
11323                             const char *const end = proto;
11324                             contextclass = 0;
11325                             while (*--p != '[')
11326                                 /* \[$] accepts any scalar lvalue */
11327                                 if (*p == '$'
11328                                  && Perl_op_lvalue_flags(aTHX_
11329                                      scalar(o3),
11330                                      OP_READ, /* not entersub */
11331                                      OP_LVALUE_NO_CROAK
11332                                     )) goto wrapref;
11333                             bad_type_gv(arg, namegv, o3,
11334                                     Perl_form(aTHX_ "one of %.*s",(int)(end - p), p));
11335                         } else
11336                             goto oops;
11337                         break;
11338                     case '*':
11339                         if (o3->op_type == OP_RV2GV)
11340                             goto wrapref;
11341                         if (!contextclass)
11342                             bad_type_gv(arg, namegv, o3, "symbol");
11343                         break;
11344                     case '&':
11345                         if (o3->op_type == OP_ENTERSUB
11346                          && !(o3->op_flags & OPf_STACKED))
11347                             goto wrapref;
11348                         if (!contextclass)
11349                             bad_type_gv(arg, namegv, o3, "subroutine");
11350                         break;
11351                     case '$':
11352                         if (o3->op_type == OP_RV2SV ||
11353                                 o3->op_type == OP_PADSV ||
11354                                 o3->op_type == OP_HELEM ||
11355                                 o3->op_type == OP_AELEM)
11356                             goto wrapref;
11357                         if (!contextclass) {
11358                             /* \$ accepts any scalar lvalue */
11359                             if (Perl_op_lvalue_flags(aTHX_
11360                                     scalar(o3),
11361                                     OP_READ,  /* not entersub */
11362                                     OP_LVALUE_NO_CROAK
11363                                )) goto wrapref;
11364                             bad_type_gv(arg, namegv, o3, "scalar");
11365                         }
11366                         break;
11367                     case '@':
11368                         if (o3->op_type == OP_RV2AV ||
11369                                 o3->op_type == OP_PADAV)
11370                         {
11371                             o3->op_flags &=~ OPf_PARENS;
11372                             goto wrapref;
11373                         }
11374                         if (!contextclass)
11375                             bad_type_gv(arg, namegv, o3, "array");
11376                         break;
11377                     case '%':
11378                         if (o3->op_type == OP_RV2HV ||
11379                                 o3->op_type == OP_PADHV)
11380                         {
11381                             o3->op_flags &=~ OPf_PARENS;
11382                             goto wrapref;
11383                         }
11384                         if (!contextclass)
11385                             bad_type_gv(arg, namegv, o3, "hash");
11386                         break;
11387                     wrapref:
11388                             aop = S_op_sibling_newUNOP(aTHX_ parent, prev,
11389                                                 OP_REFGEN, 0);
11390                         if (contextclass && e) {
11391                             proto = e + 1;
11392                             contextclass = 0;
11393                         }
11394                         break;
11395                     default: goto oops;
11396                 }
11397                 if (contextclass)
11398                     goto again;
11399                 break;
11400             case ' ':
11401                 proto++;
11402                 continue;
11403             default:
11404             oops: {
11405                 Perl_croak(aTHX_ "Malformed prototype for %"SVf": %"SVf,
11406                                   SVfARG(cv_name((CV *)namegv, NULL, 0)),
11407                                   SVfARG(protosv));
11408             }
11409         }
11410
11411         op_lvalue(aop, OP_ENTERSUB);
11412         prev = aop;
11413         aop = OpSIBLING(aop);
11414     }
11415     if (aop == cvop && *proto == '_') {
11416         /* generate an access to $_ */
11417         op_sibling_splice(parent, prev, 0, newDEFSVOP());
11418     }
11419     if (!optional && proto_end > proto &&
11420         (*proto != '@' && *proto != '%' && *proto != ';' && *proto != '_'))
11421     {
11422         SV * const namesv = cv_name((CV *)namegv, NULL, 0);
11423         yyerror_pv(Perl_form(aTHX_ "Not enough arguments for %"SVf,
11424                                     SVfARG(namesv)), SvUTF8(namesv));
11425     }
11426     return entersubop;
11427 }
11428
11429 /*
11430 =for apidoc Am|OP *|ck_entersub_args_proto_or_list|OP *entersubop|GV *namegv|SV *protosv
11431
11432 Performs the fixup of the arguments part of an C<entersub> op tree either
11433 based on a subroutine prototype or using default list-context processing.
11434 This is the standard treatment used on a subroutine call, not marked
11435 with C<&>, where the callee can be identified at compile time.
11436
11437 C<protosv> supplies the subroutine prototype to be applied to the call,
11438 or indicates that there is no prototype.  It may be a normal scalar,
11439 in which case if it is defined then the string value will be used
11440 as a prototype, and if it is undefined then there is no prototype.
11441 Alternatively, for convenience, it may be a subroutine object (a C<CV*>
11442 that has been cast to C<SV*>), of which the prototype will be used if it
11443 has one.  The prototype (or lack thereof) supplied, in whichever form,
11444 does not need to match the actual callee referenced by the op tree.
11445
11446 If the argument ops disagree with the prototype, for example by having
11447 an unacceptable number of arguments, a valid op tree is returned anyway.
11448 The error is reflected in the parser state, normally resulting in a single
11449 exception at the top level of parsing which covers all the compilation
11450 errors that occurred.  In the error message, the callee is referred to
11451 by the name defined by the C<namegv> parameter.
11452
11453 =cut
11454 */
11455
11456 OP *
11457 Perl_ck_entersub_args_proto_or_list(pTHX_ OP *entersubop,
11458         GV *namegv, SV *protosv)
11459 {
11460     PERL_ARGS_ASSERT_CK_ENTERSUB_ARGS_PROTO_OR_LIST;
11461     if (SvTYPE(protosv) == SVt_PVCV ? SvPOK(protosv) : SvOK(protosv))
11462         return ck_entersub_args_proto(entersubop, namegv, protosv);
11463     else
11464         return ck_entersub_args_list(entersubop);
11465 }
11466
11467 OP *
11468 Perl_ck_entersub_args_core(pTHX_ OP *entersubop, GV *namegv, SV *protosv)
11469 {
11470     int opnum = SvTYPE(protosv) == SVt_PVCV ? 0 : (int)SvUV(protosv);
11471     OP *aop = cUNOPx(entersubop)->op_first;
11472
11473     PERL_ARGS_ASSERT_CK_ENTERSUB_ARGS_CORE;
11474
11475     if (!opnum) {
11476         OP *cvop;
11477         if (!OpHAS_SIBLING(aop))
11478             aop = cUNOPx(aop)->op_first;
11479         aop = OpSIBLING(aop);
11480         for (cvop = aop; OpSIBLING(cvop); cvop = OpSIBLING(cvop)) ;
11481         if (aop != cvop)
11482             (void)too_many_arguments_pv(entersubop, GvNAME(namegv), 0);
11483         
11484         op_free(entersubop);
11485         switch(GvNAME(namegv)[2]) {
11486         case 'F': return newSVOP(OP_CONST, 0,
11487                                         newSVpv(CopFILE(PL_curcop),0));
11488         case 'L': return newSVOP(
11489                            OP_CONST, 0,
11490                            Perl_newSVpvf(aTHX_
11491                              "%"IVdf, (IV)CopLINE(PL_curcop)
11492                            )
11493                          );
11494         case 'P': return newSVOP(OP_CONST, 0,
11495                                    (PL_curstash
11496                                      ? newSVhek(HvNAME_HEK(PL_curstash))
11497                                      : &PL_sv_undef
11498                                    )
11499                                 );
11500         }
11501         NOT_REACHED; /* NOTREACHED */
11502     }
11503     else {
11504         OP *prev, *cvop, *first, *parent;
11505         U32 flags = 0;
11506
11507         parent = entersubop;
11508         if (!OpHAS_SIBLING(aop)) {
11509             parent = aop;
11510             aop = cUNOPx(aop)->op_first;
11511         }
11512         
11513         first = prev = aop;
11514         aop = OpSIBLING(aop);
11515         /* find last sibling */
11516         for (cvop = aop;
11517              OpHAS_SIBLING(cvop);
11518              prev = cvop, cvop = OpSIBLING(cvop))
11519             ;
11520         if (!(cvop->op_private & OPpENTERSUB_NOPAREN)
11521             /* Usually, OPf_SPECIAL on an op with no args means that it had
11522              * parens, but these have their own meaning for that flag: */
11523             && opnum != OP_VALUES && opnum != OP_KEYS && opnum != OP_EACH
11524             && opnum != OP_DELETE && opnum != OP_EXISTS)
11525                 flags |= OPf_SPECIAL;
11526         /* excise cvop from end of sibling chain */
11527         op_sibling_splice(parent, prev, 1, NULL);
11528         op_free(cvop);
11529         if (aop == cvop) aop = NULL;
11530
11531         /* detach remaining siblings from the first sibling, then
11532          * dispose of original optree */
11533
11534         if (aop)
11535             op_sibling_splice(parent, first, -1, NULL);
11536         op_free(entersubop);
11537
11538         if (opnum == OP_ENTEREVAL
11539          && GvNAMELEN(namegv)==9 && strnEQ(GvNAME(namegv), "evalbytes", 9))
11540             flags |= OPpEVAL_BYTES <<8;
11541         
11542         switch (PL_opargs[opnum] & OA_CLASS_MASK) {
11543         case OA_UNOP:
11544         case OA_BASEOP_OR_UNOP:
11545         case OA_FILESTATOP:
11546             return aop ? newUNOP(opnum,flags,aop) : newOP(opnum,flags);
11547         case OA_BASEOP:
11548             if (aop) {
11549                     (void)too_many_arguments_pv(aop, GvNAME(namegv), 0);
11550                 op_free(aop);
11551             }
11552             return opnum == OP_RUNCV
11553                 ? newPVOP(OP_RUNCV,0,NULL)
11554                 : newOP(opnum,0);
11555         default:
11556             return op_convert_list(opnum,0,aop);
11557         }
11558     }
11559     NOT_REACHED; /* NOTREACHED */
11560     return entersubop;
11561 }
11562
11563 /*
11564 =for apidoc Am|void|cv_get_call_checker|CV *cv|Perl_call_checker *ckfun_p|SV **ckobj_p
11565
11566 Retrieves the function that will be used to fix up a call to C<cv>.
11567 Specifically, the function is applied to an C<entersub> op tree for a
11568 subroutine call, not marked with C<&>, where the callee can be identified
11569 at compile time as C<cv>.
11570
11571 The C-level function pointer is returned in C<*ckfun_p>, and an SV
11572 argument for it is returned in C<*ckobj_p>.  The function is intended
11573 to be called in this manner:
11574
11575  entersubop = (*ckfun_p)(aTHX_ entersubop, namegv, (*ckobj_p));
11576
11577 In this call, C<entersubop> is a pointer to the C<entersub> op,
11578 which may be replaced by the check function, and C<namegv> is a GV
11579 supplying the name that should be used by the check function to refer
11580 to the callee of the C<entersub> op if it needs to emit any diagnostics.
11581 It is permitted to apply the check function in non-standard situations,
11582 such as to a call to a different subroutine or to a method call.
11583
11584 By default, the function is
11585 L<Perl_ck_entersub_args_proto_or_list|/ck_entersub_args_proto_or_list>,
11586 and the SV parameter is C<cv> itself.  This implements standard
11587 prototype processing.  It can be changed, for a particular subroutine,
11588 by L</cv_set_call_checker>.
11589
11590 =cut
11591 */
11592
11593 static void
11594 S_cv_get_call_checker(CV *cv, Perl_call_checker *ckfun_p, SV **ckobj_p,
11595                       U8 *flagsp)
11596 {
11597     MAGIC *callmg;
11598     callmg = SvMAGICAL((SV*)cv) ? mg_find((SV*)cv, PERL_MAGIC_checkcall) : NULL;
11599     if (callmg) {
11600         *ckfun_p = DPTR2FPTR(Perl_call_checker, callmg->mg_ptr);
11601         *ckobj_p = callmg->mg_obj;
11602         if (flagsp) *flagsp = callmg->mg_flags;
11603     } else {
11604         *ckfun_p = Perl_ck_entersub_args_proto_or_list;
11605         *ckobj_p = (SV*)cv;
11606         if (flagsp) *flagsp = 0;
11607     }
11608 }
11609
11610 void
11611 Perl_cv_get_call_checker(pTHX_ CV *cv, Perl_call_checker *ckfun_p, SV **ckobj_p)
11612 {
11613     PERL_ARGS_ASSERT_CV_GET_CALL_CHECKER;
11614     PERL_UNUSED_CONTEXT;
11615     S_cv_get_call_checker(cv, ckfun_p, ckobj_p, NULL);
11616 }
11617
11618 /*
11619 =for apidoc Am|void|cv_set_call_checker_flags|CV *cv|Perl_call_checker ckfun|SV *ckobj|U32 flags
11620
11621 Sets the function that will be used to fix up a call to C<cv>.
11622 Specifically, the function is applied to an C<entersub> op tree for a
11623 subroutine call, not marked with C<&>, where the callee can be identified
11624 at compile time as C<cv>.
11625
11626 The C-level function pointer is supplied in C<ckfun>, and an SV argument
11627 for it is supplied in C<ckobj>.  The function should be defined like this:
11628
11629     STATIC OP * ckfun(pTHX_ OP *op, GV *namegv, SV *ckobj)
11630
11631 It is intended to be called in this manner:
11632
11633     entersubop = ckfun(aTHX_ entersubop, namegv, ckobj);
11634
11635 In this call, C<entersubop> is a pointer to the C<entersub> op,
11636 which may be replaced by the check function, and C<namegv> supplies
11637 the name that should be used by the check function to refer
11638 to the callee of the C<entersub> op if it needs to emit any diagnostics.
11639 It is permitted to apply the check function in non-standard situations,
11640 such as to a call to a different subroutine or to a method call.
11641
11642 C<namegv> may not actually be a GV.  For efficiency, perl may pass a
11643 CV or other SV instead.  Whatever is passed can be used as the first
11644 argument to L</cv_name>.  You can force perl to pass a GV by including
11645 C<CALL_CHECKER_REQUIRE_GV> in the C<flags>.
11646
11647 The current setting for a particular CV can be retrieved by
11648 L</cv_get_call_checker>.
11649
11650 =for apidoc Am|void|cv_set_call_checker|CV *cv|Perl_call_checker ckfun|SV *ckobj
11651
11652 The original form of L</cv_set_call_checker_flags>, which passes it the
11653 C<CALL_CHECKER_REQUIRE_GV> flag for backward-compatibility.
11654
11655 =cut
11656 */
11657
11658 void
11659 Perl_cv_set_call_checker(pTHX_ CV *cv, Perl_call_checker ckfun, SV *ckobj)
11660 {
11661     PERL_ARGS_ASSERT_CV_SET_CALL_CHECKER;
11662     cv_set_call_checker_flags(cv, ckfun, ckobj, CALL_CHECKER_REQUIRE_GV);
11663 }
11664
11665 void
11666 Perl_cv_set_call_checker_flags(pTHX_ CV *cv, Perl_call_checker ckfun,
11667                                      SV *ckobj, U32 flags)
11668 {
11669     PERL_ARGS_ASSERT_CV_SET_CALL_CHECKER_FLAGS;
11670     if (ckfun == Perl_ck_entersub_args_proto_or_list && ckobj == (SV*)cv) {
11671         if (SvMAGICAL((SV*)cv))
11672             mg_free_type((SV*)cv, PERL_MAGIC_checkcall);
11673     } else {
11674         MAGIC *callmg;
11675         sv_magic((SV*)cv, &PL_sv_undef, PERL_MAGIC_checkcall, NULL, 0);
11676         callmg = mg_find((SV*)cv, PERL_MAGIC_checkcall);
11677         assert(callmg);
11678         if (callmg->mg_flags & MGf_REFCOUNTED) {
11679             SvREFCNT_dec(callmg->mg_obj);
11680             callmg->mg_flags &= ~MGf_REFCOUNTED;
11681         }
11682         callmg->mg_ptr = FPTR2DPTR(char *, ckfun);
11683         callmg->mg_obj = ckobj;
11684         if (ckobj != (SV*)cv) {
11685             SvREFCNT_inc_simple_void_NN(ckobj);
11686             callmg->mg_flags |= MGf_REFCOUNTED;
11687         }
11688         callmg->mg_flags = (callmg->mg_flags &~ MGf_REQUIRE_GV)
11689                          | (U8)(flags & MGf_REQUIRE_GV) | MGf_COPY;
11690     }
11691 }
11692
11693 static void
11694 S_entersub_alloc_targ(pTHX_ OP * const o)
11695 {
11696     o->op_targ = pad_alloc(OP_ENTERSUB, SVs_PADTMP);
11697     o->op_private |= OPpENTERSUB_HASTARG;
11698 }
11699
11700 OP *
11701 Perl_ck_subr(pTHX_ OP *o)
11702 {
11703     OP *aop, *cvop;
11704     CV *cv;
11705     GV *namegv;
11706     SV **const_class = NULL;
11707
11708     PERL_ARGS_ASSERT_CK_SUBR;
11709
11710     aop = cUNOPx(o)->op_first;
11711     if (!OpHAS_SIBLING(aop))
11712         aop = cUNOPx(aop)->op_first;
11713     aop = OpSIBLING(aop);
11714     for (cvop = aop; OpHAS_SIBLING(cvop); cvop = OpSIBLING(cvop)) ;
11715     cv = rv2cv_op_cv(cvop, RV2CVOPCV_MARK_EARLY);
11716     namegv = cv ? (GV*)rv2cv_op_cv(cvop, RV2CVOPCV_MAYBE_NAME_GV) : NULL;
11717
11718     o->op_private &= ~1;
11719     o->op_private |= (PL_hints & HINT_STRICT_REFS);
11720     if (PERLDB_SUB && PL_curstash != PL_debstash)
11721         o->op_private |= OPpENTERSUB_DB;
11722     switch (cvop->op_type) {
11723         case OP_RV2CV:
11724             o->op_private |= (cvop->op_private & OPpENTERSUB_AMPER);
11725             op_null(cvop);
11726             break;
11727         case OP_METHOD:
11728         case OP_METHOD_NAMED:
11729         case OP_METHOD_SUPER:
11730         case OP_METHOD_REDIR:
11731         case OP_METHOD_REDIR_SUPER:
11732             if (aop->op_type == OP_CONST) {
11733                 aop->op_private &= ~OPpCONST_STRICT;
11734                 const_class = &cSVOPx(aop)->op_sv;
11735             }
11736             else if (aop->op_type == OP_LIST) {
11737                 OP * const sib = OpSIBLING(((UNOP*)aop)->op_first);
11738                 if (sib && sib->op_type == OP_CONST) {
11739                     sib->op_private &= ~OPpCONST_STRICT;
11740                     const_class = &cSVOPx(sib)->op_sv;
11741                 }
11742             }
11743             /* make class name a shared cow string to speedup method calls */
11744             /* constant string might be replaced with object, f.e. bigint */
11745             if (const_class && SvPOK(*const_class)) {
11746                 STRLEN len;
11747                 const char* str = SvPV(*const_class, len);
11748                 if (len) {
11749                     SV* const shared = newSVpvn_share(
11750                         str, SvUTF8(*const_class)
11751                                     ? -(SSize_t)len : (SSize_t)len,
11752                         0
11753                     );
11754                     if (SvREADONLY(*const_class))
11755                         SvREADONLY_on(shared);
11756                     SvREFCNT_dec(*const_class);
11757                     *const_class = shared;
11758                 }
11759             }
11760             break;
11761     }
11762
11763     if (!cv) {
11764         S_entersub_alloc_targ(aTHX_ o);
11765         return ck_entersub_args_list(o);
11766     } else {
11767         Perl_call_checker ckfun;
11768         SV *ckobj;
11769         U8 flags;
11770         S_cv_get_call_checker(cv, &ckfun, &ckobj, &flags);
11771         if (CvISXSUB(cv) || !CvROOT(cv))
11772             S_entersub_alloc_targ(aTHX_ o);
11773         if (!namegv) {
11774             /* The original call checker API guarantees that a GV will be
11775                be provided with the right name.  So, if the old API was
11776                used (or the REQUIRE_GV flag was passed), we have to reify
11777                the CV’s GV, unless this is an anonymous sub.  This is not
11778                ideal for lexical subs, as its stringification will include
11779                the package.  But it is the best we can do.  */
11780             if (flags & MGf_REQUIRE_GV) {
11781                 if (!CvANON(cv) && (!CvNAMED(cv) || CvNAME_HEK(cv)))
11782                     namegv = CvGV(cv);
11783             }
11784             else namegv = MUTABLE_GV(cv);
11785             /* After a syntax error in a lexical sub, the cv that
11786                rv2cv_op_cv returns may be a nameless stub. */
11787             if (!namegv) return ck_entersub_args_list(o);
11788
11789         }
11790         return ckfun(aTHX_ o, namegv, ckobj);
11791     }
11792 }
11793
11794 OP *
11795 Perl_ck_svconst(pTHX_ OP *o)
11796 {
11797     SV * const sv = cSVOPo->op_sv;
11798     PERL_ARGS_ASSERT_CK_SVCONST;
11799     PERL_UNUSED_CONTEXT;
11800 #ifdef PERL_COPY_ON_WRITE
11801     /* Since the read-only flag may be used to protect a string buffer, we
11802        cannot do copy-on-write with existing read-only scalars that are not
11803        already copy-on-write scalars.  To allow $_ = "hello" to do COW with
11804        that constant, mark the constant as COWable here, if it is not
11805        already read-only. */
11806     if (!SvREADONLY(sv) && !SvIsCOW(sv) && SvCANCOW(sv)) {
11807         SvIsCOW_on(sv);
11808         CowREFCNT(sv) = 0;
11809 # ifdef PERL_DEBUG_READONLY_COW
11810         sv_buf_to_ro(sv);
11811 # endif
11812     }
11813 #endif
11814     SvREADONLY_on(sv);
11815     return o;
11816 }
11817
11818 OP *
11819 Perl_ck_trunc(pTHX_ OP *o)
11820 {
11821     PERL_ARGS_ASSERT_CK_TRUNC;
11822
11823     if (o->op_flags & OPf_KIDS) {
11824         SVOP *kid = (SVOP*)cUNOPo->op_first;
11825
11826         if (kid->op_type == OP_NULL)
11827             kid = (SVOP*)OpSIBLING(kid);
11828         if (kid && kid->op_type == OP_CONST &&
11829             (kid->op_private & OPpCONST_BARE) &&
11830             !kid->op_folded)
11831         {
11832             o->op_flags |= OPf_SPECIAL;
11833             kid->op_private &= ~OPpCONST_STRICT;
11834         }
11835     }
11836     return ck_fun(o);
11837 }
11838
11839 OP *
11840 Perl_ck_substr(pTHX_ OP *o)
11841 {
11842     PERL_ARGS_ASSERT_CK_SUBSTR;
11843
11844     o = ck_fun(o);
11845     if ((o->op_flags & OPf_KIDS) && (o->op_private == 4)) {
11846         OP *kid = cLISTOPo->op_first;
11847
11848         if (kid->op_type == OP_NULL)
11849             kid = OpSIBLING(kid);
11850         if (kid)
11851             kid->op_flags |= OPf_MOD;
11852
11853     }
11854     return o;
11855 }
11856
11857 OP *
11858 Perl_ck_tell(pTHX_ OP *o)
11859 {
11860     PERL_ARGS_ASSERT_CK_TELL;
11861     o = ck_fun(o);
11862     if (o->op_flags & OPf_KIDS) {
11863      OP *kid = cLISTOPo->op_first;
11864      if (kid->op_type == OP_NULL && OpHAS_SIBLING(kid)) kid = OpSIBLING(kid);
11865      if (kid->op_type == OP_RV2GV) kid->op_private |= OPpALLOW_FAKE;
11866     }
11867     return o;
11868 }
11869
11870 OP *
11871 Perl_ck_each(pTHX_ OP *o)
11872 {
11873     dVAR;
11874     OP *kid = o->op_flags & OPf_KIDS ? cUNOPo->op_first : NULL;
11875     const unsigned orig_type  = o->op_type;
11876
11877     PERL_ARGS_ASSERT_CK_EACH;
11878
11879     if (kid) {
11880         switch (kid->op_type) {
11881             case OP_PADHV:
11882             case OP_RV2HV:
11883                 break;
11884             case OP_PADAV:
11885             case OP_RV2AV:
11886                 OpTYPE_set(o, orig_type == OP_EACH ? OP_AEACH
11887                             : orig_type == OP_KEYS ? OP_AKEYS
11888                             :                        OP_AVALUES);
11889                 break;
11890             case OP_CONST:
11891                 if (kid->op_private == OPpCONST_BARE
11892                  || !SvROK(cSVOPx_sv(kid))
11893                  || (  SvTYPE(SvRV(cSVOPx_sv(kid))) != SVt_PVAV
11894                     && SvTYPE(SvRV(cSVOPx_sv(kid))) != SVt_PVHV  )
11895                    )
11896                     /* we let ck_fun handle it */
11897                     break;
11898             default:
11899                 Perl_croak_nocontext(
11900                     "Experimental %s on scalar is now forbidden",
11901                     PL_op_desc[orig_type]);
11902                 break;
11903         }
11904     }
11905     return ck_fun(o);
11906 }
11907
11908 OP *
11909 Perl_ck_length(pTHX_ OP *o)
11910 {
11911     PERL_ARGS_ASSERT_CK_LENGTH;
11912
11913     o = ck_fun(o);
11914
11915     if (ckWARN(WARN_SYNTAX)) {
11916         const OP *kid = o->op_flags & OPf_KIDS ? cLISTOPo->op_first : NULL;
11917
11918         if (kid) {
11919             SV *name = NULL;
11920             const bool hash = kid->op_type == OP_PADHV
11921                            || kid->op_type == OP_RV2HV;
11922             switch (kid->op_type) {
11923                 case OP_PADHV:
11924                 case OP_PADAV:
11925                 case OP_RV2HV:
11926                 case OP_RV2AV:
11927                     name = S_op_varname(aTHX_ kid);
11928                     break;
11929                 default:
11930                     return o;
11931             }
11932             if (name)
11933                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
11934                     "length() used on %"SVf" (did you mean \"scalar(%s%"SVf
11935                     ")\"?)",
11936                     SVfARG(name), hash ? "keys " : "", SVfARG(name)
11937                 );
11938             else if (hash)
11939      /* diag_listed_as: length() used on %s (did you mean "scalar(%s)"?) */
11940                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
11941                     "length() used on %%hash (did you mean \"scalar(keys %%hash)\"?)");
11942             else
11943      /* diag_listed_as: length() used on %s (did you mean "scalar(%s)"?) */
11944                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
11945                     "length() used on @array (did you mean \"scalar(@array)\"?)");
11946         }
11947     }
11948
11949     return o;
11950 }
11951
11952
11953
11954 /* 
11955    ---------------------------------------------------------
11956  
11957    Common vars in list assignment
11958
11959    There now follows some enums and static functions for detecting
11960    common variables in list assignments. Here is a little essay I wrote
11961    for myself when trying to get my head around this. DAPM.
11962
11963    ----
11964
11965    First some random observations:
11966    
11967    * If a lexical var is an alias of something else, e.g.
11968        for my $x ($lex, $pkg, $a[0]) {...}
11969      then the act of aliasing will increase the reference count of the SV
11970    
11971    * If a package var is an alias of something else, it may still have a
11972      reference count of 1, depending on how the alias was created, e.g.
11973      in *a = *b, $a may have a refcount of 1 since the GP is shared
11974      with a single GvSV pointer to the SV. So If it's an alias of another
11975      package var, then RC may be 1; if it's an alias of another scalar, e.g.
11976      a lexical var or an array element, then it will have RC > 1.
11977    
11978    * There are many ways to create a package alias; ultimately, XS code
11979      may quite legally do GvSV(gv) = SvREFCNT_inc(sv) for example, so
11980      run-time tracing mechanisms are unlikely to be able to catch all cases.
11981    
11982    * When the LHS is all my declarations, the same vars can't appear directly
11983      on the RHS, but they can indirectly via closures, aliasing and lvalue
11984      subs. But those techniques all involve an increase in the lexical
11985      scalar's ref count.
11986    
11987    * When the LHS is all lexical vars (but not necessarily my declarations),
11988      it is possible for the same lexicals to appear directly on the RHS, and
11989      without an increased ref count, since the stack isn't refcounted.
11990      This case can be detected at compile time by scanning for common lex
11991      vars with PL_generation.
11992    
11993    * lvalue subs defeat common var detection, but they do at least
11994      return vars with a temporary ref count increment. Also, you can't
11995      tell at compile time whether a sub call is lvalue.
11996    
11997     
11998    So...
11999          
12000    A: There are a few circumstances where there definitely can't be any
12001      commonality:
12002    
12003        LHS empty:  () = (...);
12004        RHS empty:  (....) = ();
12005        RHS contains only constants or other 'can't possibly be shared'
12006            elements (e.g. ops that return PADTMPs):  (...) = (1,2, length)
12007            i.e. they only contain ops not marked as dangerous, whose children
12008            are also not dangerous;
12009        LHS ditto;
12010        LHS contains a single scalar element: e.g. ($x) = (....); because
12011            after $x has been modified, it won't be used again on the RHS;
12012        RHS contains a single element with no aggregate on LHS: e.g.
12013            ($a,$b,$c)  = ($x); again, once $a has been modified, its value
12014            won't be used again.
12015    
12016    B: If LHS are all 'my' lexical var declarations (or safe ops, which
12017      we can ignore):
12018    
12019        my ($a, $b, @c) = ...;
12020    
12021        Due to closure and goto tricks, these vars may already have content.
12022        For the same reason, an element on the RHS may be a lexical or package
12023        alias of one of the vars on the left, or share common elements, for
12024        example:
12025    
12026            my ($x,$y) = f(); # $x and $y on both sides
12027            sub f : lvalue { ($x,$y) = (1,2); $y, $x }
12028    
12029        and
12030    
12031            my $ra = f();
12032            my @a = @$ra;  # elements of @a on both sides
12033            sub f { @a = 1..4; \@a }
12034    
12035    
12036        First, just consider scalar vars on LHS:
12037    
12038            RHS is safe only if (A), or in addition,
12039                * contains only lexical *scalar* vars, where neither side's
12040                  lexicals have been flagged as aliases 
12041    
12042            If RHS is not safe, then it's always legal to check LHS vars for
12043            RC==1, since the only RHS aliases will always be associated
12044            with an RC bump.
12045    
12046            Note that in particular, RHS is not safe if:
12047    
12048                * it contains package scalar vars; e.g.:
12049    
12050                    f();
12051                    my ($x, $y) = (2, $x_alias);
12052                    sub f { $x = 1; *x_alias = \$x; }
12053    
12054                * It contains other general elements, such as flattened or
12055                * spliced or single array or hash elements, e.g.
12056    
12057                    f();
12058                    my ($x,$y) = @a; # or $a[0] or @a{@b} etc 
12059    
12060                    sub f {
12061                        ($x, $y) = (1,2);
12062                        use feature 'refaliasing';
12063                        \($a[0], $a[1]) = \($y,$x);
12064                    }
12065    
12066                  It doesn't matter if the array/hash is lexical or package.
12067    
12068                * it contains a function call that happens to be an lvalue
12069                  sub which returns one or more of the above, e.g.
12070    
12071                    f();
12072                    my ($x,$y) = f();
12073    
12074                    sub f : lvalue {
12075                        ($x, $y) = (1,2);
12076                        *x1 = \$x;
12077                        $y, $x1;
12078                    }
12079    
12080                    (so a sub call on the RHS should be treated the same
12081                    as having a package var on the RHS).
12082    
12083                * any other "dangerous" thing, such an op or built-in that
12084                  returns one of the above, e.g. pp_preinc
12085    
12086    
12087            If RHS is not safe, what we can do however is at compile time flag
12088            that the LHS are all my declarations, and at run time check whether
12089            all the LHS have RC == 1, and if so skip the full scan.
12090    
12091        Now consider array and hash vars on LHS: e.g. my (...,@a) = ...;
12092    
12093            Here the issue is whether there can be elements of @a on the RHS
12094            which will get prematurely freed when @a is cleared prior to
12095            assignment. This is only a problem if the aliasing mechanism
12096            is one which doesn't increase the refcount - only if RC == 1
12097            will the RHS element be prematurely freed.
12098    
12099            Because the array/hash is being INTROed, it or its elements
12100            can't directly appear on the RHS:
12101    
12102                my (@a) = ($a[0], @a, etc) # NOT POSSIBLE
12103    
12104            but can indirectly, e.g.:
12105    
12106                my $r = f();
12107                my (@a) = @$r;
12108                sub f { @a = 1..3; \@a }
12109    
12110            So if the RHS isn't safe as defined by (A), we must always
12111            mortalise and bump the ref count of any remaining RHS elements
12112            when assigning to a non-empty LHS aggregate.
12113    
12114            Lexical scalars on the RHS aren't safe if they've been involved in
12115            aliasing, e.g.
12116    
12117                use feature 'refaliasing';
12118    
12119                f();
12120                \(my $lex) = \$pkg;
12121                my @a = ($lex,3); # equivalent to ($a[0],3)
12122    
12123                sub f {
12124                    @a = (1,2);
12125                    \$pkg = \$a[0];
12126                }
12127    
12128            Similarly with lexical arrays and hashes on the RHS:
12129    
12130                f();
12131                my @b;
12132                my @a = (@b);
12133    
12134                sub f {
12135                    @a = (1,2);
12136                    \$b[0] = \$a[1];
12137                    \$b[1] = \$a[0];
12138                }
12139    
12140    
12141    
12142    C: As (B), but in addition the LHS may contain non-intro lexicals, e.g.
12143        my $a; ($a, my $b) = (....);
12144    
12145        The difference between (B) and (C) is that it is now physically
12146        possible for the LHS vars to appear on the RHS too, where they
12147        are not reference counted; but in this case, the compile-time
12148        PL_generation sweep will detect such common vars.
12149    
12150        So the rules for (C) differ from (B) in that if common vars are
12151        detected, the runtime "test RC==1" optimisation can no longer be used,
12152        and a full mark and sweep is required
12153    
12154    D: As (C), but in addition the LHS may contain package vars.
12155    
12156        Since package vars can be aliased without a corresponding refcount
12157        increase, all bets are off. It's only safe if (A). E.g.
12158    
12159            my ($x, $y) = (1,2);
12160    
12161            for $x_alias ($x) {
12162                ($x_alias, $y) = (3, $x); # whoops
12163            }
12164    
12165        Ditto for LHS aggregate package vars.
12166    
12167    E: Any other dangerous ops on LHS, e.g.
12168            (f(), $a[0], @$r) = (...);
12169    
12170        this is similar to (E) in that all bets are off. In addition, it's
12171        impossible to determine at compile time whether the LHS
12172        contains a scalar or an aggregate, e.g.
12173    
12174            sub f : lvalue { @a }
12175            (f()) = 1..3;
12176
12177 * ---------------------------------------------------------
12178 */
12179
12180
12181 /* A set of bit flags returned by S_aassign_scan(). Each flag indicates
12182  * that at least one of the things flagged was seen.
12183  */
12184
12185 enum {
12186     AAS_MY_SCALAR       = 0x001, /* my $scalar */
12187     AAS_MY_AGG          = 0x002, /* aggregate: my @array or my %hash */
12188     AAS_LEX_SCALAR      = 0x004, /* $lexical */
12189     AAS_LEX_AGG         = 0x008, /* @lexical or %lexical aggregate */
12190     AAS_LEX_SCALAR_COMM = 0x010, /* $lexical seen on both sides */
12191     AAS_PKG_SCALAR      = 0x020, /* $scalar (where $scalar is pkg var) */
12192     AAS_PKG_AGG         = 0x040, /* package @array or %hash aggregate */
12193     AAS_DANGEROUS       = 0x080, /* an op (other than the above)
12194                                          that's flagged OA_DANGEROUS */
12195     AAS_SAFE_SCALAR     = 0x100, /* produces at least one scalar SV that's
12196                                         not in any of the categories above */
12197     AAS_DEFAV           = 0x200  /* contains just a single '@_' on RHS */
12198 };
12199
12200
12201
12202 /* helper function for S_aassign_scan().
12203  * check a PAD-related op for commonality and/or set its generation number.
12204  * Returns a boolean indicating whether its shared */
12205
12206 static bool
12207 S_aassign_padcheck(pTHX_ OP* o, bool rhs)
12208 {
12209     if (PAD_COMPNAME_GEN(o->op_targ) == PERL_INT_MAX)
12210         /* lexical used in aliasing */
12211         return TRUE;
12212
12213     if (rhs)
12214         return cBOOL(PAD_COMPNAME_GEN(o->op_targ) == (STRLEN)PL_generation);
12215     else
12216         PAD_COMPNAME_GEN_set(o->op_targ, PL_generation);
12217
12218     return FALSE;
12219 }
12220
12221
12222 /*
12223   Helper function for OPpASSIGN_COMMON* detection in rpeep().
12224   It scans the left or right hand subtree of the aassign op, and returns a
12225   set of flags indicating what sorts of things it found there.
12226   'rhs' indicates whether we're scanning the LHS or RHS. If the former, we
12227   set PL_generation on lexical vars; if the latter, we see if
12228   PL_generation matches.
12229   'top' indicates whether we're recursing or at the top level.
12230   'scalars_p' is a pointer to a counter of the number of scalar SVs seen.
12231   This fn will increment it by the number seen. It's not intended to
12232   be an accurate count (especially as many ops can push a variable
12233   number of SVs onto the stack); rather it's used as to test whether there
12234   can be at most 1 SV pushed; so it's only meanings are "0, 1, many".
12235 */
12236
12237 static int
12238 S_aassign_scan(pTHX_ OP* o, bool rhs, bool top, int *scalars_p)
12239 {
12240     int flags = 0;
12241     bool kid_top = FALSE;
12242
12243     /* first, look for a solitary @_ on the RHS */
12244     if (   rhs
12245         && top
12246         && (o->op_flags & OPf_KIDS)
12247         && OP_TYPE_IS_OR_WAS(o, OP_LIST)
12248     ) {
12249         OP *kid = cUNOPo->op_first;
12250         if (   (   kid->op_type == OP_PUSHMARK
12251                 || kid->op_type == OP_PADRANGE) /* ex-pushmark */
12252             && ((kid = OpSIBLING(kid)))
12253             && !OpHAS_SIBLING(kid)
12254             && kid->op_type == OP_RV2AV
12255             && !(kid->op_flags & OPf_REF)
12256             && !(kid->op_private & (OPpLVAL_INTRO|OPpMAYBE_LVSUB))
12257             && ((kid->op_flags & OPf_WANT) == OPf_WANT_LIST)
12258             && ((kid = cUNOPx(kid)->op_first))
12259             && kid->op_type == OP_GV
12260             && cGVOPx_gv(kid) == PL_defgv
12261         )
12262             flags |= AAS_DEFAV;
12263     }
12264
12265     switch (o->op_type) {
12266     case OP_GVSV:
12267         (*scalars_p)++;
12268         return AAS_PKG_SCALAR;
12269
12270     case OP_PADAV:
12271     case OP_PADHV:
12272         (*scalars_p) += 2;
12273         if (top && (o->op_flags & OPf_REF))
12274             return (o->op_private & OPpLVAL_INTRO)
12275                 ? AAS_MY_AGG : AAS_LEX_AGG;
12276         return AAS_DANGEROUS;
12277
12278     case OP_PADSV:
12279         {
12280             int comm = S_aassign_padcheck(aTHX_ o, rhs)
12281                         ?  AAS_LEX_SCALAR_COMM : 0;
12282             (*scalars_p)++;
12283             return (o->op_private & OPpLVAL_INTRO)
12284                 ? (AAS_MY_SCALAR|comm) : (AAS_LEX_SCALAR|comm);
12285         }
12286
12287     case OP_RV2AV:
12288     case OP_RV2HV:
12289         (*scalars_p) += 2;
12290         if (cUNOPx(o)->op_first->op_type != OP_GV)
12291             return AAS_DANGEROUS; /* @{expr}, %{expr} */
12292         /* @pkg, %pkg */
12293         if (top && (o->op_flags & OPf_REF))
12294             return AAS_PKG_AGG;
12295         return AAS_DANGEROUS;
12296
12297     case OP_RV2SV:
12298         (*scalars_p)++;
12299         if (cUNOPx(o)->op_first->op_type != OP_GV) {
12300             (*scalars_p) += 2;
12301             return AAS_DANGEROUS; /* ${expr} */
12302         }
12303         return AAS_PKG_SCALAR; /* $pkg */
12304
12305     case OP_SPLIT:
12306         if (cLISTOPo->op_first->op_type == OP_PUSHRE) {
12307             /* "@foo = split... " optimises away the aassign and stores its
12308              * destination array in the OP_PUSHRE that precedes it.
12309              * A flattened array is always dangerous.
12310              */
12311             (*scalars_p) += 2;
12312             return AAS_DANGEROUS;
12313         }
12314         break;
12315
12316     case OP_UNDEF:
12317         /* undef counts as a scalar on the RHS:
12318          *   (undef, $x) = ...;         # only 1 scalar on LHS: always safe
12319          *   ($x, $y)    = (undef, $x); # 2 scalars on RHS: unsafe
12320          */
12321         if (rhs)
12322             (*scalars_p)++;
12323         flags = AAS_SAFE_SCALAR;
12324         break;
12325
12326     case OP_PUSHMARK:
12327     case OP_STUB:
12328         /* these are all no-ops; they don't push a potentially common SV
12329          * onto the stack, so they are neither AAS_DANGEROUS nor
12330          * AAS_SAFE_SCALAR */
12331         return 0;
12332
12333     case OP_PADRANGE: /* Ignore padrange; checking its siblings is enough */
12334         break;
12335
12336     case OP_NULL:
12337     case OP_LIST:
12338         /* these do nothing but may have children; but their children
12339          * should also be treated as top-level */
12340         kid_top = top;
12341         break;
12342
12343     default:
12344         if (PL_opargs[o->op_type] & OA_DANGEROUS) {
12345             (*scalars_p) += 2;
12346             flags = AAS_DANGEROUS;
12347             break;
12348         }
12349
12350         if (   (PL_opargs[o->op_type] & OA_TARGLEX)
12351             && (o->op_private & OPpTARGET_MY))
12352         {
12353             (*scalars_p)++;
12354             return S_aassign_padcheck(aTHX_ o, rhs)
12355                 ? AAS_LEX_SCALAR_COMM : AAS_LEX_SCALAR;
12356         }
12357
12358         /* if its an unrecognised, non-dangerous op, assume that it
12359          * it the cause of at least one safe scalar */
12360         (*scalars_p)++;
12361         flags = AAS_SAFE_SCALAR;
12362         break;
12363     }
12364
12365     if (o->op_flags & OPf_KIDS) {
12366         OP *kid;
12367         for (kid = cUNOPo->op_first; kid; kid = OpSIBLING(kid))
12368             flags |= S_aassign_scan(aTHX_ kid, rhs, kid_top, scalars_p);
12369     }
12370     return flags;
12371 }
12372
12373
12374 /* Check for in place reverse and sort assignments like "@a = reverse @a"
12375    and modify the optree to make them work inplace */
12376
12377 STATIC void
12378 S_inplace_aassign(pTHX_ OP *o) {
12379
12380     OP *modop, *modop_pushmark;
12381     OP *oright;
12382     OP *oleft, *oleft_pushmark;
12383
12384     PERL_ARGS_ASSERT_INPLACE_AASSIGN;
12385
12386     assert((o->op_flags & OPf_WANT) == OPf_WANT_VOID);
12387
12388     assert(cUNOPo->op_first->op_type == OP_NULL);
12389     modop_pushmark = cUNOPx(cUNOPo->op_first)->op_first;
12390     assert(modop_pushmark->op_type == OP_PUSHMARK);
12391     modop = OpSIBLING(modop_pushmark);
12392
12393     if (modop->op_type != OP_SORT && modop->op_type != OP_REVERSE)
12394         return;
12395
12396     /* no other operation except sort/reverse */
12397     if (OpHAS_SIBLING(modop))
12398         return;
12399
12400     assert(cUNOPx(modop)->op_first->op_type == OP_PUSHMARK);
12401     if (!(oright = OpSIBLING(cUNOPx(modop)->op_first))) return;
12402
12403     if (modop->op_flags & OPf_STACKED) {
12404         /* skip sort subroutine/block */
12405         assert(oright->op_type == OP_NULL);
12406         oright = OpSIBLING(oright);
12407     }
12408
12409     assert(OpSIBLING(cUNOPo->op_first)->op_type == OP_NULL);
12410     oleft_pushmark = cUNOPx(OpSIBLING(cUNOPo->op_first))->op_first;
12411     assert(oleft_pushmark->op_type == OP_PUSHMARK);
12412     oleft = OpSIBLING(oleft_pushmark);
12413
12414     /* Check the lhs is an array */
12415     if (!oleft ||
12416         (oleft->op_type != OP_RV2AV && oleft->op_type != OP_PADAV)
12417         || OpHAS_SIBLING(oleft)
12418         || (oleft->op_private & OPpLVAL_INTRO)
12419     )
12420         return;
12421
12422     /* Only one thing on the rhs */
12423     if (OpHAS_SIBLING(oright))
12424         return;
12425
12426     /* check the array is the same on both sides */
12427     if (oleft->op_type == OP_RV2AV) {
12428         if (oright->op_type != OP_RV2AV
12429             || !cUNOPx(oright)->op_first
12430             || cUNOPx(oright)->op_first->op_type != OP_GV
12431             || cUNOPx(oleft )->op_first->op_type != OP_GV
12432             || cGVOPx_gv(cUNOPx(oleft)->op_first) !=
12433                cGVOPx_gv(cUNOPx(oright)->op_first)
12434         )
12435             return;
12436     }
12437     else if (oright->op_type != OP_PADAV
12438         || oright->op_targ != oleft->op_targ
12439     )
12440         return;
12441
12442     /* This actually is an inplace assignment */
12443
12444     modop->op_private |= OPpSORT_INPLACE;
12445
12446     /* transfer MODishness etc from LHS arg to RHS arg */
12447     oright->op_flags = oleft->op_flags;
12448
12449     /* remove the aassign op and the lhs */
12450     op_null(o);
12451     op_null(oleft_pushmark);
12452     if (oleft->op_type == OP_RV2AV && cUNOPx(oleft)->op_first)
12453         op_null(cUNOPx(oleft)->op_first);
12454     op_null(oleft);
12455 }
12456
12457
12458
12459 /* S_maybe_multideref(): given an op_next chain of ops beginning at 'start'
12460  * that potentially represent a series of one or more aggregate derefs
12461  * (such as $a->[1]{$key}), examine the chain, and if appropriate, convert
12462  * the whole chain to a single OP_MULTIDEREF op (maybe with a few
12463  * additional ops left in too).
12464  *
12465  * The caller will have already verified that the first few ops in the
12466  * chain following 'start' indicate a multideref candidate, and will have
12467  * set 'orig_o' to the point further on in the chain where the first index
12468  * expression (if any) begins.  'orig_action' specifies what type of
12469  * beginning has already been determined by the ops between start..orig_o
12470  * (e.g.  $lex_ary[], $pkg_ary->{}, expr->[], etc).
12471  *
12472  * 'hints' contains any hints flags that need adding (currently just
12473  * OPpHINT_STRICT_REFS) as found in any rv2av/hv skipped by the caller.
12474  */
12475
12476 void
12477 S_maybe_multideref(pTHX_ OP *start, OP *orig_o, UV orig_action, U8 hints)
12478 {
12479     dVAR;
12480     int pass;
12481     UNOP_AUX_item *arg_buf = NULL;
12482     bool reset_start_targ  = FALSE; /* start->op_targ needs zeroing */
12483     int index_skip         = -1;    /* don't output index arg on this action */
12484
12485     /* similar to regex compiling, do two passes; the first pass
12486      * determines whether the op chain is convertible and calculates the
12487      * buffer size; the second pass populates the buffer and makes any
12488      * changes necessary to ops (such as moving consts to the pad on
12489      * threaded builds).
12490      *
12491      * NB: for things like Coverity, note that both passes take the same
12492      * path through the logic tree (except for 'if (pass)' bits), since
12493      * both passes are following the same op_next chain; and in
12494      * particular, if it would return early on the second pass, it would
12495      * already have returned early on the first pass.
12496      */
12497     for (pass = 0; pass < 2; pass++) {
12498         OP *o                = orig_o;
12499         UV action            = orig_action;
12500         OP *first_elem_op    = NULL;  /* first seen aelem/helem */
12501         OP *top_op           = NULL;  /* highest [ah]elem/exists/del/rv2[ah]v */
12502         int action_count     = 0;     /* number of actions seen so far */
12503         int action_ix        = 0;     /* action_count % (actions per IV) */
12504         bool next_is_hash    = FALSE; /* is the next lookup to be a hash? */
12505         bool is_last         = FALSE; /* no more derefs to follow */
12506         bool maybe_aelemfast = FALSE; /* we can replace with aelemfast? */
12507         UNOP_AUX_item *arg     = arg_buf;
12508         UNOP_AUX_item *action_ptr = arg_buf;
12509
12510         if (pass)
12511             action_ptr->uv = 0;
12512         arg++;
12513
12514         switch (action) {
12515         case MDEREF_HV_gvsv_vivify_rv2hv_helem:
12516         case MDEREF_HV_gvhv_helem:
12517             next_is_hash = TRUE;
12518             /* FALLTHROUGH */
12519         case MDEREF_AV_gvsv_vivify_rv2av_aelem:
12520         case MDEREF_AV_gvav_aelem:
12521             if (pass) {
12522 #ifdef USE_ITHREADS
12523                 arg->pad_offset = cPADOPx(start)->op_padix;
12524                 /* stop it being swiped when nulled */
12525                 cPADOPx(start)->op_padix = 0;
12526 #else
12527                 arg->sv = cSVOPx(start)->op_sv;
12528                 cSVOPx(start)->op_sv = NULL;
12529 #endif
12530             }
12531             arg++;
12532             break;
12533
12534         case MDEREF_HV_padhv_helem:
12535         case MDEREF_HV_padsv_vivify_rv2hv_helem:
12536             next_is_hash = TRUE;
12537             /* FALLTHROUGH */
12538         case MDEREF_AV_padav_aelem:
12539         case MDEREF_AV_padsv_vivify_rv2av_aelem:
12540             if (pass) {
12541                 arg->pad_offset = start->op_targ;
12542                 /* we skip setting op_targ = 0 for now, since the intact
12543                  * OP_PADXV is needed by S_check_hash_fields_and_hekify */
12544                 reset_start_targ = TRUE;
12545             }
12546             arg++;
12547             break;
12548
12549         case MDEREF_HV_pop_rv2hv_helem:
12550             next_is_hash = TRUE;
12551             /* FALLTHROUGH */
12552         case MDEREF_AV_pop_rv2av_aelem:
12553             break;
12554
12555         default:
12556             NOT_REACHED; /* NOTREACHED */
12557             return;
12558         }
12559
12560         while (!is_last) {
12561             /* look for another (rv2av/hv; get index;
12562              * aelem/helem/exists/delele) sequence */
12563
12564             OP *kid;
12565             bool is_deref;
12566             bool ok;
12567             UV index_type = MDEREF_INDEX_none;
12568
12569             if (action_count) {
12570                 /* if this is not the first lookup, consume the rv2av/hv  */
12571
12572                 /* for N levels of aggregate lookup, we normally expect
12573                  * that the first N-1 [ah]elem ops will be flagged as
12574                  * /DEREF (so they autovivifiy if necessary), and the last
12575                  * lookup op not to be.
12576                  * For other things (like @{$h{k1}{k2}}) extra scope or
12577                  * leave ops can appear, so abandon the effort in that
12578                  * case */
12579                 if (o->op_type != OP_RV2AV && o->op_type != OP_RV2HV)
12580                     return;
12581
12582                 /* rv2av or rv2hv sKR/1 */
12583
12584                 ASSUME(!(o->op_flags & ~(OPf_WANT|OPf_KIDS|OPf_PARENS
12585                                             |OPf_REF|OPf_MOD|OPf_SPECIAL)));
12586                 if (o->op_flags != (OPf_WANT_SCALAR|OPf_KIDS|OPf_REF))
12587                     return;
12588
12589                 /* at this point, we wouldn't expect any of these
12590                  * possible private flags:
12591                  * OPpMAYBE_LVSUB, OPpOUR_INTRO, OPpLVAL_INTRO
12592                  * OPpTRUEBOOL, OPpMAYBE_TRUEBOOL (rv2hv only)
12593                  */
12594                 ASSUME(!(o->op_private &
12595                     ~(OPpHINT_STRICT_REFS|OPpARG1_MASK|OPpSLICEWARNING)));
12596
12597                 hints = (o->op_private & OPpHINT_STRICT_REFS);
12598
12599                 /* make sure the type of the previous /DEREF matches the
12600                  * type of the next lookup */
12601                 ASSUME(o->op_type == (next_is_hash ? OP_RV2HV : OP_RV2AV));
12602                 top_op = o;
12603
12604                 action = next_is_hash
12605                             ? MDEREF_HV_vivify_rv2hv_helem
12606                             : MDEREF_AV_vivify_rv2av_aelem;
12607                 o = o->op_next;
12608             }
12609
12610             /* if this is the second pass, and we're at the depth where
12611              * previously we encountered a non-simple index expression,
12612              * stop processing the index at this point */
12613             if (action_count != index_skip) {
12614
12615                 /* look for one or more simple ops that return an array
12616                  * index or hash key */
12617
12618                 switch (o->op_type) {
12619                 case OP_PADSV:
12620                     /* it may be a lexical var index */
12621                     ASSUME(!(o->op_flags & ~(OPf_WANT|OPf_PARENS
12622                                             |OPf_REF|OPf_MOD|OPf_SPECIAL)));
12623                     ASSUME(!(o->op_private &
12624                             ~(OPpPAD_STATE|OPpDEREF|OPpLVAL_INTRO)));
12625
12626                     if (   OP_GIMME(o,0) == G_SCALAR
12627                         && !(o->op_flags & (OPf_REF|OPf_MOD))
12628                         && o->op_private == 0)
12629                     {
12630                         if (pass)
12631                             arg->pad_offset = o->op_targ;
12632                         arg++;
12633                         index_type = MDEREF_INDEX_padsv;
12634                         o = o->op_next;
12635                     }
12636                     break;
12637
12638                 case OP_CONST:
12639                     if (next_is_hash) {
12640                         /* it's a constant hash index */
12641                         if (!(SvFLAGS(cSVOPo_sv) & (SVf_IOK|SVf_NOK|SVf_POK)))
12642                             /* "use constant foo => FOO; $h{+foo}" for
12643                              * some weird FOO, can leave you with constants
12644                              * that aren't simple strings. It's not worth
12645                              * the extra hassle for those edge cases */
12646                             break;
12647
12648                         if (pass) {
12649                             UNOP *rop = NULL;
12650                             OP * helem_op = o->op_next;
12651
12652                             ASSUME(   helem_op->op_type == OP_HELEM
12653                                    || helem_op->op_type == OP_NULL);
12654                             if (helem_op->op_type == OP_HELEM) {
12655                                 rop = (UNOP*)(((BINOP*)helem_op)->op_first);
12656                                 if (   helem_op->op_private & OPpLVAL_INTRO
12657                                     || rop->op_type != OP_RV2HV
12658                                 )
12659                                     rop = NULL;
12660                             }
12661                             S_check_hash_fields_and_hekify(aTHX_ rop, cSVOPo);
12662
12663 #ifdef USE_ITHREADS
12664                             /* Relocate sv to the pad for thread safety */
12665                             op_relocate_sv(&cSVOPo->op_sv, &o->op_targ);
12666                             arg->pad_offset = o->op_targ;
12667                             o->op_targ = 0;
12668 #else
12669                             arg->sv = cSVOPx_sv(o);
12670 #endif
12671                         }
12672                     }
12673                     else {
12674                         /* it's a constant array index */
12675                         IV iv;
12676                         SV *ix_sv = cSVOPo->op_sv;
12677                         if (!SvIOK(ix_sv))
12678                             break;
12679                         iv = SvIV(ix_sv);
12680
12681                         if (   action_count == 0
12682                             && iv >= -128
12683                             && iv <= 127
12684                             && (   action == MDEREF_AV_padav_aelem
12685                                 || action == MDEREF_AV_gvav_aelem)
12686                         )
12687                             maybe_aelemfast = TRUE;
12688
12689                         if (pass) {
12690                             arg->iv = iv;
12691                             SvREFCNT_dec_NN(cSVOPo->op_sv);
12692                         }
12693                     }
12694                     if (pass)
12695                         /* we've taken ownership of the SV */
12696                         cSVOPo->op_sv = NULL;
12697                     arg++;
12698                     index_type = MDEREF_INDEX_const;
12699                     o = o->op_next;
12700                     break;
12701
12702                 case OP_GV:
12703                     /* it may be a package var index */
12704
12705                     ASSUME(!(o->op_flags & ~(OPf_WANT|OPf_SPECIAL)));
12706                     ASSUME(!(o->op_private & ~(OPpEARLY_CV)));
12707                     if (  (o->op_flags &~ OPf_SPECIAL) != OPf_WANT_SCALAR
12708                         || o->op_private != 0
12709                     )
12710                         break;
12711
12712                     kid = o->op_next;
12713                     if (kid->op_type != OP_RV2SV)
12714                         break;
12715
12716                     ASSUME(!(kid->op_flags &
12717                             ~(OPf_WANT|OPf_KIDS|OPf_MOD|OPf_REF
12718                              |OPf_SPECIAL|OPf_PARENS)));
12719                     ASSUME(!(kid->op_private &
12720                                     ~(OPpARG1_MASK
12721                                      |OPpHINT_STRICT_REFS|OPpOUR_INTRO
12722                                      |OPpDEREF|OPpLVAL_INTRO)));
12723                     if(   (kid->op_flags &~ OPf_PARENS)
12724                             != (OPf_WANT_SCALAR|OPf_KIDS)
12725                        || (kid->op_private & ~(OPpARG1_MASK|HINT_STRICT_REFS))
12726                     )
12727                         break;
12728
12729                     if (pass) {
12730 #ifdef USE_ITHREADS
12731                         arg->pad_offset = cPADOPx(o)->op_padix;
12732                         /* stop it being swiped when nulled */
12733                         cPADOPx(o)->op_padix = 0;
12734 #else
12735                         arg->sv = cSVOPx(o)->op_sv;
12736                         cSVOPo->op_sv = NULL;
12737 #endif
12738                     }
12739                     arg++;
12740                     index_type = MDEREF_INDEX_gvsv;
12741                     o = kid->op_next;
12742                     break;
12743
12744                 } /* switch */
12745             } /* action_count != index_skip */
12746
12747             action |= index_type;
12748
12749
12750             /* at this point we have either:
12751              *   * detected what looks like a simple index expression,
12752              *     and expect the next op to be an [ah]elem, or
12753              *     an nulled  [ah]elem followed by a delete or exists;
12754              *  * found a more complex expression, so something other
12755              *    than the above follows.
12756              */
12757
12758             /* possibly an optimised away [ah]elem (where op_next is
12759              * exists or delete) */
12760             if (o->op_type == OP_NULL)
12761                 o = o->op_next;
12762
12763             /* at this point we're looking for an OP_AELEM, OP_HELEM,
12764              * OP_EXISTS or OP_DELETE */
12765
12766             /* if something like arybase (a.k.a $[ ) is in scope,
12767              * abandon optimisation attempt */
12768             if (  (o->op_type == OP_AELEM || o->op_type == OP_HELEM)
12769                && PL_check[o->op_type] != Perl_ck_null)
12770                 return;
12771
12772             if (   o->op_type != OP_AELEM
12773                 || (o->op_private &
12774                       (OPpLVAL_INTRO|OPpLVAL_DEFER|OPpDEREF|OPpMAYBE_LVSUB))
12775                 )
12776                 maybe_aelemfast = FALSE;
12777
12778             /* look for aelem/helem/exists/delete. If it's not the last elem
12779              * lookup, it *must* have OPpDEREF_AV/HV, but not many other
12780              * flags; if it's the last, then it mustn't have
12781              * OPpDEREF_AV/HV, but may have lots of other flags, like
12782              * OPpLVAL_INTRO etc
12783              */
12784
12785             if (   index_type == MDEREF_INDEX_none
12786                 || (   o->op_type != OP_AELEM  && o->op_type != OP_HELEM
12787                     && o->op_type != OP_EXISTS && o->op_type != OP_DELETE)
12788             )
12789                 ok = FALSE;
12790             else {
12791                 /* we have aelem/helem/exists/delete with valid simple index */
12792
12793                 is_deref =    (o->op_type == OP_AELEM || o->op_type == OP_HELEM)
12794                            && (   (o->op_private & OPpDEREF) == OPpDEREF_AV
12795                                || (o->op_private & OPpDEREF) == OPpDEREF_HV);
12796
12797                 if (is_deref) {
12798                     ASSUME(!(o->op_flags &
12799                                  ~(OPf_WANT|OPf_KIDS|OPf_MOD|OPf_PARENS)));
12800                     ASSUME(!(o->op_private & ~(OPpARG2_MASK|OPpDEREF)));
12801
12802                     ok =    (o->op_flags &~ OPf_PARENS)
12803                                == (OPf_WANT_SCALAR|OPf_KIDS|OPf_MOD)
12804                          && !(o->op_private & ~(OPpDEREF|OPpARG2_MASK));
12805                 }
12806                 else if (o->op_type == OP_EXISTS) {
12807                     ASSUME(!(o->op_flags & ~(OPf_WANT|OPf_KIDS|OPf_PARENS
12808                                 |OPf_REF|OPf_MOD|OPf_SPECIAL)));
12809                     ASSUME(!(o->op_private & ~(OPpARG1_MASK|OPpEXISTS_SUB)));
12810                     ok =  !(o->op_private & ~OPpARG1_MASK);
12811                 }
12812                 else if (o->op_type == OP_DELETE) {
12813                     ASSUME(!(o->op_flags & ~(OPf_WANT|OPf_KIDS|OPf_PARENS
12814                                 |OPf_REF|OPf_MOD|OPf_SPECIAL)));
12815                     ASSUME(!(o->op_private &
12816                                     ~(OPpARG1_MASK|OPpSLICE|OPpLVAL_INTRO)));
12817                     /* don't handle slices or 'local delete'; the latter
12818                      * is fairly rare, and has a complex runtime */
12819                     ok =  !(o->op_private & ~OPpARG1_MASK);
12820                     if (OP_TYPE_IS_OR_WAS(cUNOPo->op_first, OP_AELEM))
12821                         /* skip handling run-tome error */
12822                         ok = (ok && cBOOL(o->op_flags & OPf_SPECIAL));
12823                 }
12824                 else {
12825                     ASSUME(o->op_type == OP_AELEM || o->op_type == OP_HELEM);
12826                     ASSUME(!(o->op_flags & ~(OPf_WANT|OPf_KIDS|OPf_MOD
12827                                             |OPf_PARENS|OPf_REF|OPf_SPECIAL)));
12828                     ASSUME(!(o->op_private & ~(OPpARG2_MASK|OPpMAYBE_LVSUB
12829                                     |OPpLVAL_DEFER|OPpDEREF|OPpLVAL_INTRO)));
12830                     ok = (o->op_private & OPpDEREF) != OPpDEREF_SV;
12831                 }
12832             }
12833
12834             if (ok) {
12835                 if (!first_elem_op)
12836                     first_elem_op = o;
12837                 top_op = o;
12838                 if (is_deref) {
12839                     next_is_hash = cBOOL((o->op_private & OPpDEREF) == OPpDEREF_HV);
12840                     o = o->op_next;
12841                 }
12842                 else {
12843                     is_last = TRUE;
12844                     action |= MDEREF_FLAG_last;
12845                 }
12846             }
12847             else {
12848                 /* at this point we have something that started
12849                  * promisingly enough (with rv2av or whatever), but failed
12850                  * to find a simple index followed by an
12851                  * aelem/helem/exists/delete. If this is the first action,
12852                  * give up; but if we've already seen at least one
12853                  * aelem/helem, then keep them and add a new action with
12854                  * MDEREF_INDEX_none, which causes it to do the vivify
12855                  * from the end of the previous lookup, and do the deref,
12856                  * but stop at that point. So $a[0][expr] will do one
12857                  * av_fetch, vivify and deref, then continue executing at
12858                  * expr */
12859                 if (!action_count)
12860                     return;
12861                 is_last = TRUE;
12862                 index_skip = action_count;
12863                 action |= MDEREF_FLAG_last;
12864             }
12865
12866             if (pass)
12867                 action_ptr->uv |= (action << (action_ix * MDEREF_SHIFT));
12868             action_ix++;
12869             action_count++;
12870             /* if there's no space for the next action, create a new slot
12871              * for it *before* we start adding args for that action */
12872             if ((action_ix + 1) * MDEREF_SHIFT > UVSIZE*8) {
12873                 action_ptr = arg;
12874                 if (pass)
12875                     arg->uv = 0;
12876                 arg++;
12877                 action_ix = 0;
12878             }
12879         } /* while !is_last */
12880
12881         /* success! */
12882
12883         if (pass) {
12884             OP *mderef;
12885             OP *p, *q;
12886
12887             mderef = newUNOP_AUX(OP_MULTIDEREF, 0, NULL, arg_buf);
12888             if (index_skip == -1) {
12889                 mderef->op_flags = o->op_flags
12890                         & (OPf_WANT|OPf_MOD|(next_is_hash ? OPf_SPECIAL : 0));
12891                 if (o->op_type == OP_EXISTS)
12892                     mderef->op_private = OPpMULTIDEREF_EXISTS;
12893                 else if (o->op_type == OP_DELETE)
12894                     mderef->op_private = OPpMULTIDEREF_DELETE;
12895                 else
12896                     mderef->op_private = o->op_private
12897                         & (OPpMAYBE_LVSUB|OPpLVAL_DEFER|OPpLVAL_INTRO);
12898             }
12899             /* accumulate strictness from every level (although I don't think
12900              * they can actually vary) */
12901             mderef->op_private |= hints;
12902
12903             /* integrate the new multideref op into the optree and the
12904              * op_next chain.
12905              *
12906              * In general an op like aelem or helem has two child
12907              * sub-trees: the aggregate expression (a_expr) and the
12908              * index expression (i_expr):
12909              *
12910              *     aelem
12911              *       |
12912              *     a_expr - i_expr
12913              *
12914              * The a_expr returns an AV or HV, while the i-expr returns an
12915              * index. In general a multideref replaces most or all of a
12916              * multi-level tree, e.g.
12917              *
12918              *     exists
12919              *       |
12920              *     ex-aelem
12921              *       |
12922              *     rv2av  - i_expr1
12923              *       |
12924              *     helem
12925              *       |
12926              *     rv2hv  - i_expr2
12927              *       |
12928              *     aelem
12929              *       |
12930              *     a_expr - i_expr3
12931              *
12932              * With multideref, all the i_exprs will be simple vars or
12933              * constants, except that i_expr1 may be arbitrary in the case
12934              * of MDEREF_INDEX_none.
12935              *
12936              * The bottom-most a_expr will be either:
12937              *   1) a simple var (so padXv or gv+rv2Xv);
12938              *   2) a simple scalar var dereferenced (e.g. $r->[0]):
12939              *      so a simple var with an extra rv2Xv;
12940              *   3) or an arbitrary expression.
12941              *
12942              * 'start', the first op in the execution chain, will point to
12943              *   1),2): the padXv or gv op;
12944              *   3):    the rv2Xv which forms the last op in the a_expr
12945              *          execution chain, and the top-most op in the a_expr
12946              *          subtree.
12947              *
12948              * For all cases, the 'start' node is no longer required,
12949              * but we can't free it since one or more external nodes
12950              * may point to it. E.g. consider
12951              *     $h{foo} = $a ? $b : $c
12952              * Here, both the op_next and op_other branches of the
12953              * cond_expr point to the gv[*h] of the hash expression, so
12954              * we can't free the 'start' op.
12955              *
12956              * For expr->[...], we need to save the subtree containing the
12957              * expression; for the other cases, we just need to save the
12958              * start node.
12959              * So in all cases, we null the start op and keep it around by
12960              * making it the child of the multideref op; for the expr->
12961              * case, the expr will be a subtree of the start node.
12962              *
12963              * So in the simple 1,2 case the  optree above changes to
12964              *
12965              *     ex-exists
12966              *       |
12967              *     multideref
12968              *       |
12969              *     ex-gv (or ex-padxv)
12970              *
12971              *  with the op_next chain being
12972              *
12973              *  -> ex-gv -> multideref -> op-following-ex-exists ->
12974              *
12975              *  In the 3 case, we have
12976              *
12977              *     ex-exists
12978              *       |
12979              *     multideref
12980              *       |
12981              *     ex-rv2xv
12982              *       |
12983              *    rest-of-a_expr
12984              *      subtree
12985              *
12986              *  and
12987              *
12988              *  -> rest-of-a_expr subtree ->
12989              *    ex-rv2xv -> multideref -> op-following-ex-exists ->
12990              *
12991              *
12992              * Where the last i_expr is non-simple (i.e. MDEREF_INDEX_none,
12993              * e.g. $a[0]{foo}[$x+1], the next rv2xv is nulled and the
12994              * multideref attached as the child, e.g.
12995              *
12996              *     exists
12997              *       |
12998              *     ex-aelem
12999              *       |
13000              *     ex-rv2av  - i_expr1
13001              *       |
13002              *     multideref
13003              *       |
13004              *     ex-whatever
13005              *
13006              */
13007
13008             /* if we free this op, don't free the pad entry */
13009             if (reset_start_targ)
13010                 start->op_targ = 0;
13011
13012
13013             /* Cut the bit we need to save out of the tree and attach to
13014              * the multideref op, then free the rest of the tree */
13015
13016             /* find parent of node to be detached (for use by splice) */
13017             p = first_elem_op;
13018             if (   orig_action == MDEREF_AV_pop_rv2av_aelem
13019                 || orig_action == MDEREF_HV_pop_rv2hv_helem)
13020             {
13021                 /* there is an arbitrary expression preceding us, e.g.
13022                  * expr->[..]? so we need to save the 'expr' subtree */
13023                 if (p->op_type == OP_EXISTS || p->op_type == OP_DELETE)
13024                     p = cUNOPx(p)->op_first;
13025                 ASSUME(   start->op_type == OP_RV2AV
13026                        || start->op_type == OP_RV2HV);
13027             }
13028             else {
13029                 /* either a padXv or rv2Xv+gv, maybe with an ex-Xelem
13030                  * above for exists/delete. */
13031                 while (   (p->op_flags & OPf_KIDS)
13032                        && cUNOPx(p)->op_first != start
13033                 )
13034                     p = cUNOPx(p)->op_first;
13035             }
13036             ASSUME(cUNOPx(p)->op_first == start);
13037
13038             /* detach from main tree, and re-attach under the multideref */
13039             op_sibling_splice(mderef, NULL, 0,
13040                     op_sibling_splice(p, NULL, 1, NULL));
13041             op_null(start);
13042
13043             start->op_next = mderef;
13044
13045             mderef->op_next = index_skip == -1 ? o->op_next : o;
13046
13047             /* excise and free the original tree, and replace with
13048              * the multideref op */
13049             p = op_sibling_splice(top_op, NULL, -1, mderef);
13050             while (p) {
13051                 q = OpSIBLING(p);
13052                 op_free(p);
13053                 p = q;
13054             }
13055             op_null(top_op);
13056         }
13057         else {
13058             Size_t size = arg - arg_buf;
13059
13060             if (maybe_aelemfast && action_count == 1)
13061                 return;
13062
13063             arg_buf = (UNOP_AUX_item*)PerlMemShared_malloc(
13064                                 sizeof(UNOP_AUX_item) * (size + 1));
13065             /* for dumping etc: store the length in a hidden first slot;
13066              * we set the op_aux pointer to the second slot */
13067             arg_buf->uv = size;
13068             arg_buf++;
13069         }
13070     } /* for (pass = ...) */
13071 }
13072
13073
13074
13075 /* mechanism for deferring recursion in rpeep() */
13076
13077 #define MAX_DEFERRED 4
13078
13079 #define DEFER(o) \
13080   STMT_START { \
13081     if (defer_ix == (MAX_DEFERRED-1)) { \
13082         OP **defer = defer_queue[defer_base]; \
13083         CALL_RPEEP(*defer); \
13084         S_prune_chain_head(defer); \
13085         defer_base = (defer_base + 1) % MAX_DEFERRED; \
13086         defer_ix--; \
13087     } \
13088     defer_queue[(defer_base + ++defer_ix) % MAX_DEFERRED] = &(o); \
13089   } STMT_END
13090
13091 #define IS_AND_OP(o)   (o->op_type == OP_AND)
13092 #define IS_OR_OP(o)    (o->op_type == OP_OR)
13093
13094
13095 /* A peephole optimizer.  We visit the ops in the order they're to execute.
13096  * See the comments at the top of this file for more details about when
13097  * peep() is called */
13098
13099 void
13100 Perl_rpeep(pTHX_ OP *o)
13101 {
13102     dVAR;
13103     OP* oldop = NULL;
13104     OP* oldoldop = NULL;
13105     OP** defer_queue[MAX_DEFERRED]; /* small queue of deferred branches */
13106     int defer_base = 0;
13107     int defer_ix = -1;
13108     OP *fop;
13109     OP *sop;
13110
13111     if (!o || o->op_opt)
13112         return;
13113     ENTER;
13114     SAVEOP();
13115     SAVEVPTR(PL_curcop);
13116     for (;; o = o->op_next) {
13117         if (o && o->op_opt)
13118             o = NULL;
13119         if (!o) {
13120             while (defer_ix >= 0) {
13121                 OP **defer =
13122                         defer_queue[(defer_base + defer_ix--) % MAX_DEFERRED];
13123                 CALL_RPEEP(*defer);
13124                 S_prune_chain_head(defer);
13125             }
13126             break;
13127         }
13128
13129       redo:
13130
13131         /* oldoldop -> oldop -> o should be a chain of 3 adjacent ops */
13132         assert(!oldoldop || oldoldop->op_next == oldop);
13133         assert(!oldop    || oldop->op_next    == o);
13134
13135         /* By default, this op has now been optimised. A couple of cases below
13136            clear this again.  */
13137         o->op_opt = 1;
13138         PL_op = o;
13139
13140         /* look for a series of 1 or more aggregate derefs, e.g.
13141          *   $a[1]{foo}[$i]{$k}
13142          * and replace with a single OP_MULTIDEREF op.
13143          * Each index must be either a const, or a simple variable,
13144          *
13145          * First, look for likely combinations of starting ops,
13146          * corresponding to (global and lexical variants of)
13147          *     $a[...]   $h{...}
13148          *     $r->[...] $r->{...}
13149          *     (preceding expression)->[...]
13150          *     (preceding expression)->{...}
13151          * and if so, call maybe_multideref() to do a full inspection
13152          * of the op chain and if appropriate, replace with an
13153          * OP_MULTIDEREF
13154          */
13155         {
13156             UV action;
13157             OP *o2 = o;
13158             U8 hints = 0;
13159
13160             switch (o2->op_type) {
13161             case OP_GV:
13162                 /* $pkg[..]   :   gv[*pkg]
13163                  * $pkg->[...]:   gv[*pkg]; rv2sv sKM/DREFAV */
13164
13165                 /* Fail if there are new op flag combinations that we're
13166                  * not aware of, rather than:
13167                  *  * silently failing to optimise, or
13168                  *  * silently optimising the flag away.
13169                  * If this ASSUME starts failing, examine what new flag
13170                  * has been added to the op, and decide whether the
13171                  * optimisation should still occur with that flag, then
13172                  * update the code accordingly. This applies to all the
13173                  * other ASSUMEs in the block of code too.
13174                  */
13175                 ASSUME(!(o2->op_flags &
13176                             ~(OPf_WANT|OPf_MOD|OPf_PARENS|OPf_SPECIAL)));
13177                 ASSUME(!(o2->op_private & ~OPpEARLY_CV));
13178
13179                 o2 = o2->op_next;
13180
13181                 if (o2->op_type == OP_RV2AV) {
13182                     action = MDEREF_AV_gvav_aelem;
13183                     goto do_deref;
13184                 }
13185
13186                 if (o2->op_type == OP_RV2HV) {
13187                     action = MDEREF_HV_gvhv_helem;
13188                     goto do_deref;
13189                 }
13190
13191                 if (o2->op_type != OP_RV2SV)
13192                     break;
13193
13194                 /* at this point we've seen gv,rv2sv, so the only valid
13195                  * construct left is $pkg->[] or $pkg->{} */
13196
13197                 ASSUME(!(o2->op_flags & OPf_STACKED));
13198                 if ((o2->op_flags & (OPf_WANT|OPf_REF|OPf_MOD|OPf_SPECIAL))
13199                             != (OPf_WANT_SCALAR|OPf_MOD))
13200                     break;
13201
13202                 ASSUME(!(o2->op_private & ~(OPpARG1_MASK|HINT_STRICT_REFS
13203                                     |OPpOUR_INTRO|OPpDEREF|OPpLVAL_INTRO)));
13204                 if (o2->op_private & (OPpOUR_INTRO|OPpLVAL_INTRO))
13205                     break;
13206                 if (   (o2->op_private & OPpDEREF) != OPpDEREF_AV
13207                     && (o2->op_private & OPpDEREF) != OPpDEREF_HV)
13208                     break;
13209
13210                 o2 = o2->op_next;
13211                 if (o2->op_type == OP_RV2AV) {
13212                     action = MDEREF_AV_gvsv_vivify_rv2av_aelem;
13213                     goto do_deref;
13214                 }
13215                 if (o2->op_type == OP_RV2HV) {
13216                     action = MDEREF_HV_gvsv_vivify_rv2hv_helem;
13217                     goto do_deref;
13218                 }
13219                 break;
13220
13221             case OP_PADSV:
13222                 /* $lex->[...]: padsv[$lex] sM/DREFAV */
13223
13224                 ASSUME(!(o2->op_flags &
13225                     ~(OPf_WANT|OPf_PARENS|OPf_REF|OPf_MOD|OPf_SPECIAL)));
13226                 if ((o2->op_flags &
13227                         (OPf_WANT|OPf_REF|OPf_MOD|OPf_SPECIAL))
13228                      != (OPf_WANT_SCALAR|OPf_MOD))
13229                     break;
13230
13231                 ASSUME(!(o2->op_private &
13232                                 ~(OPpPAD_STATE|OPpDEREF|OPpLVAL_INTRO)));
13233                 /* skip if state or intro, or not a deref */
13234                 if (      o2->op_private != OPpDEREF_AV
13235                        && o2->op_private != OPpDEREF_HV)
13236                     break;
13237
13238                 o2 = o2->op_next;
13239                 if (o2->op_type == OP_RV2AV) {
13240                     action = MDEREF_AV_padsv_vivify_rv2av_aelem;
13241                     goto do_deref;
13242                 }
13243                 if (o2->op_type == OP_RV2HV) {
13244                     action = MDEREF_HV_padsv_vivify_rv2hv_helem;
13245                     goto do_deref;
13246                 }
13247                 break;
13248
13249             case OP_PADAV:
13250             case OP_PADHV:
13251                 /*    $lex[..]:  padav[@lex:1,2] sR *
13252                  * or $lex{..}:  padhv[%lex:1,2] sR */
13253                 ASSUME(!(o2->op_flags & ~(OPf_WANT|OPf_MOD|OPf_PARENS|
13254                                             OPf_REF|OPf_SPECIAL)));
13255                 if ((o2->op_flags &
13256                         (OPf_WANT|OPf_REF|OPf_MOD|OPf_SPECIAL))
13257                      != (OPf_WANT_SCALAR|OPf_REF))
13258                     break;
13259                 if (o2->op_flags != (OPf_WANT_SCALAR|OPf_REF))
13260                     break;
13261                 /* OPf_PARENS isn't currently used in this case;
13262                  * if that changes, let us know! */
13263                 ASSUME(!(o2->op_flags & OPf_PARENS));
13264
13265                 /* at this point, we wouldn't expect any of the remaining
13266                  * possible private flags:
13267                  * OPpPAD_STATE, OPpLVAL_INTRO, OPpTRUEBOOL,
13268                  * OPpMAYBE_TRUEBOOL, OPpMAYBE_LVSUB
13269                  *
13270                  * OPpSLICEWARNING shouldn't affect runtime
13271                  */
13272                 ASSUME(!(o2->op_private & ~(OPpSLICEWARNING)));
13273
13274                 action = o2->op_type == OP_PADAV
13275                             ? MDEREF_AV_padav_aelem
13276                             : MDEREF_HV_padhv_helem;
13277                 o2 = o2->op_next;
13278                 S_maybe_multideref(aTHX_ o, o2, action, 0);
13279                 break;
13280
13281
13282             case OP_RV2AV:
13283             case OP_RV2HV:
13284                 action = o2->op_type == OP_RV2AV
13285                             ? MDEREF_AV_pop_rv2av_aelem
13286                             : MDEREF_HV_pop_rv2hv_helem;
13287                 /* FALLTHROUGH */
13288             do_deref:
13289                 /* (expr)->[...]:  rv2av sKR/1;
13290                  * (expr)->{...}:  rv2hv sKR/1; */
13291
13292                 ASSUME(o2->op_type == OP_RV2AV || o2->op_type == OP_RV2HV);
13293
13294                 ASSUME(!(o2->op_flags & ~(OPf_WANT|OPf_KIDS|OPf_PARENS
13295                                 |OPf_REF|OPf_MOD|OPf_STACKED|OPf_SPECIAL)));
13296                 if (o2->op_flags != (OPf_WANT_SCALAR|OPf_KIDS|OPf_REF))
13297                     break;
13298
13299                 /* at this point, we wouldn't expect any of these
13300                  * possible private flags:
13301                  * OPpMAYBE_LVSUB, OPpLVAL_INTRO
13302                  * OPpTRUEBOOL, OPpMAYBE_TRUEBOOL, (rv2hv only)
13303                  */
13304                 ASSUME(!(o2->op_private &
13305                     ~(OPpHINT_STRICT_REFS|OPpARG1_MASK|OPpSLICEWARNING
13306                      |OPpOUR_INTRO)));
13307                 hints |= (o2->op_private & OPpHINT_STRICT_REFS);
13308
13309                 o2 = o2->op_next;
13310
13311                 S_maybe_multideref(aTHX_ o, o2, action, hints);
13312                 break;
13313
13314             default:
13315                 break;
13316             }
13317         }
13318
13319
13320         switch (o->op_type) {
13321         case OP_DBSTATE:
13322             PL_curcop = ((COP*)o);              /* for warnings */
13323             break;
13324         case OP_NEXTSTATE:
13325             PL_curcop = ((COP*)o);              /* for warnings */
13326
13327             /* Optimise a "return ..." at the end of a sub to just be "...".
13328              * This saves 2 ops. Before:
13329              * 1  <;> nextstate(main 1 -e:1) v ->2
13330              * 4  <@> return K ->5
13331              * 2    <0> pushmark s ->3
13332              * -    <1> ex-rv2sv sK/1 ->4
13333              * 3      <#> gvsv[*cat] s ->4
13334              *
13335              * After:
13336              * -  <@> return K ->-
13337              * -    <0> pushmark s ->2
13338              * -    <1> ex-rv2sv sK/1 ->-
13339              * 2      <$> gvsv(*cat) s ->3
13340              */
13341             {
13342                 OP *next = o->op_next;
13343                 OP *sibling = OpSIBLING(o);
13344                 if (   OP_TYPE_IS(next, OP_PUSHMARK)
13345                     && OP_TYPE_IS(sibling, OP_RETURN)
13346                     && OP_TYPE_IS(sibling->op_next, OP_LINESEQ)
13347                     && ( OP_TYPE_IS(sibling->op_next->op_next, OP_LEAVESUB)
13348                        ||OP_TYPE_IS(sibling->op_next->op_next,
13349                                     OP_LEAVESUBLV))
13350                     && cUNOPx(sibling)->op_first == next
13351                     && OpHAS_SIBLING(next) && OpSIBLING(next)->op_next
13352                     && next->op_next
13353                 ) {
13354                     /* Look through the PUSHMARK's siblings for one that
13355                      * points to the RETURN */
13356                     OP *top = OpSIBLING(next);
13357                     while (top && top->op_next) {
13358                         if (top->op_next == sibling) {
13359                             top->op_next = sibling->op_next;
13360                             o->op_next = next->op_next;
13361                             break;
13362                         }
13363                         top = OpSIBLING(top);
13364                     }
13365                 }
13366             }
13367
13368             /* Optimise 'my $x; my $y;' into 'my ($x, $y);'
13369              *
13370              * This latter form is then suitable for conversion into padrange
13371              * later on. Convert:
13372              *
13373              *   nextstate1 -> padop1 -> nextstate2 -> padop2 -> nextstate3
13374              *
13375              * into:
13376              *
13377              *   nextstate1 ->     listop     -> nextstate3
13378              *                 /            \
13379              *         pushmark -> padop1 -> padop2
13380              */
13381             if (o->op_next && (
13382                     o->op_next->op_type == OP_PADSV
13383                  || o->op_next->op_type == OP_PADAV
13384                  || o->op_next->op_type == OP_PADHV
13385                 )
13386                 && !(o->op_next->op_private & ~OPpLVAL_INTRO)
13387                 && o->op_next->op_next && o->op_next->op_next->op_type == OP_NEXTSTATE
13388                 && o->op_next->op_next->op_next && (
13389                     o->op_next->op_next->op_next->op_type == OP_PADSV
13390                  || o->op_next->op_next->op_next->op_type == OP_PADAV
13391                  || o->op_next->op_next->op_next->op_type == OP_PADHV
13392                 )
13393                 && !(o->op_next->op_next->op_next->op_private & ~OPpLVAL_INTRO)
13394                 && o->op_next->op_next->op_next->op_next && o->op_next->op_next->op_next->op_next->op_type == OP_NEXTSTATE
13395                 && (!CopLABEL((COP*)o)) /* Don't mess with labels */
13396                 && (!CopLABEL((COP*)o->op_next->op_next)) /* ... */
13397             ) {
13398                 OP *pad1, *ns2, *pad2, *ns3, *newop, *newpm;
13399
13400                 pad1 =    o->op_next;
13401                 ns2  = pad1->op_next;
13402                 pad2 =  ns2->op_next;
13403                 ns3  = pad2->op_next;
13404
13405                 /* we assume here that the op_next chain is the same as
13406                  * the op_sibling chain */
13407                 assert(OpSIBLING(o)    == pad1);
13408                 assert(OpSIBLING(pad1) == ns2);
13409                 assert(OpSIBLING(ns2)  == pad2);
13410                 assert(OpSIBLING(pad2) == ns3);
13411
13412                 /* excise and delete ns2 */
13413                 op_sibling_splice(NULL, pad1, 1, NULL);
13414                 op_free(ns2);
13415
13416                 /* excise pad1 and pad2 */
13417                 op_sibling_splice(NULL, o, 2, NULL);
13418
13419                 /* create new listop, with children consisting of:
13420                  * a new pushmark, pad1, pad2. */
13421                 newop = newLISTOP(OP_LIST, 0, pad1, pad2);
13422                 newop->op_flags |= OPf_PARENS;
13423                 newop->op_flags = (newop->op_flags & ~OPf_WANT) | OPf_WANT_VOID;
13424
13425                 /* insert newop between o and ns3 */
13426                 op_sibling_splice(NULL, o, 0, newop);
13427
13428                 /*fixup op_next chain */
13429                 newpm = cUNOPx(newop)->op_first; /* pushmark */
13430                 o    ->op_next = newpm;
13431                 newpm->op_next = pad1;
13432                 pad1 ->op_next = pad2;
13433                 pad2 ->op_next = newop; /* listop */
13434                 newop->op_next = ns3;
13435
13436                 /* Ensure pushmark has this flag if padops do */
13437                 if (pad1->op_flags & OPf_MOD && pad2->op_flags & OPf_MOD) {
13438                     newpm->op_flags |= OPf_MOD;
13439                 }
13440
13441                 break;
13442             }
13443
13444             /* Two NEXTSTATEs in a row serve no purpose. Except if they happen
13445                to carry two labels. For now, take the easier option, and skip
13446                this optimisation if the first NEXTSTATE has a label.  */
13447             if (!CopLABEL((COP*)o) && !PERLDB_NOOPT) {
13448                 OP *nextop = o->op_next;
13449                 while (nextop && nextop->op_type == OP_NULL)
13450                     nextop = nextop->op_next;
13451
13452                 if (nextop && (nextop->op_type == OP_NEXTSTATE)) {
13453                     op_null(o);
13454                     if (oldop)
13455                         oldop->op_next = nextop;
13456                     o = nextop;
13457                     /* Skip (old)oldop assignment since the current oldop's
13458                        op_next already points to the next op.  */
13459                     goto redo;
13460                 }
13461             }
13462             break;
13463
13464         case OP_CONCAT:
13465             if (o->op_next && o->op_next->op_type == OP_STRINGIFY) {
13466                 if (o->op_next->op_private & OPpTARGET_MY) {
13467                     if (o->op_flags & OPf_STACKED) /* chained concats */
13468                         break; /* ignore_optimization */
13469                     else {
13470                         /* assert(PL_opargs[o->op_type] & OA_TARGLEX); */
13471                         o->op_targ = o->op_next->op_targ;
13472                         o->op_next->op_targ = 0;
13473                         o->op_private |= OPpTARGET_MY;
13474                     }
13475                 }
13476                 op_null(o->op_next);
13477             }
13478             break;
13479         case OP_STUB:
13480             if ((o->op_flags & OPf_WANT) != OPf_WANT_LIST) {
13481                 break; /* Scalar stub must produce undef.  List stub is noop */
13482             }
13483             goto nothin;
13484         case OP_NULL:
13485             if (o->op_targ == OP_NEXTSTATE
13486                 || o->op_targ == OP_DBSTATE)
13487             {
13488                 PL_curcop = ((COP*)o);
13489             }
13490             /* XXX: We avoid setting op_seq here to prevent later calls
13491                to rpeep() from mistakenly concluding that optimisation
13492                has already occurred. This doesn't fix the real problem,
13493                though (See 20010220.007). AMS 20010719 */
13494             /* op_seq functionality is now replaced by op_opt */
13495             o->op_opt = 0;
13496             /* FALLTHROUGH */
13497         case OP_SCALAR:
13498         case OP_LINESEQ:
13499         case OP_SCOPE:
13500         nothin:
13501             if (oldop) {
13502                 oldop->op_next = o->op_next;
13503                 o->op_opt = 0;
13504                 continue;
13505             }
13506             break;
13507
13508         case OP_PUSHMARK:
13509
13510             /* Given
13511                  5 repeat/DOLIST
13512                  3   ex-list
13513                  1     pushmark
13514                  2     scalar or const
13515                  4   const[0]
13516                convert repeat into a stub with no kids.
13517              */
13518             if (o->op_next->op_type == OP_CONST
13519              || (  o->op_next->op_type == OP_PADSV
13520                 && !(o->op_next->op_private & OPpLVAL_INTRO))
13521              || (  o->op_next->op_type == OP_GV
13522                 && o->op_next->op_next->op_type == OP_RV2SV
13523                 && !(o->op_next->op_next->op_private
13524                         & (OPpLVAL_INTRO|OPpOUR_INTRO))))
13525             {
13526                 const OP *kid = o->op_next->op_next;
13527                 if (o->op_next->op_type == OP_GV)
13528                    kid = kid->op_next;
13529                 /* kid is now the ex-list.  */
13530                 if (kid->op_type == OP_NULL
13531                  && (kid = kid->op_next)->op_type == OP_CONST
13532                     /* kid is now the repeat count.  */
13533                  && kid->op_next->op_type == OP_REPEAT
13534                  && kid->op_next->op_private & OPpREPEAT_DOLIST
13535                  && (kid->op_next->op_flags & OPf_WANT) == OPf_WANT_LIST
13536                  && SvIOK(kSVOP_sv) && SvIVX(kSVOP_sv) == 0)
13537                 {
13538                     o = kid->op_next; /* repeat */
13539                     assert(oldop);
13540                     oldop->op_next = o;
13541                     op_free(cBINOPo->op_first);
13542                     op_free(cBINOPo->op_last );
13543                     o->op_flags &=~ OPf_KIDS;
13544                     /* stub is a baseop; repeat is a binop */
13545                     STATIC_ASSERT_STMT(sizeof(OP) <= sizeof(BINOP));
13546                     OpTYPE_set(o, OP_STUB);
13547                     o->op_private = 0;
13548                     break;
13549                 }
13550             }
13551
13552             /* Convert a series of PAD ops for my vars plus support into a
13553              * single padrange op. Basically
13554              *
13555              *    pushmark -> pad[ahs]v -> pad[ahs]?v -> ... -> (list) -> rest
13556              *
13557              * becomes, depending on circumstances, one of
13558              *
13559              *    padrange  ----------------------------------> (list) -> rest
13560              *    padrange  --------------------------------------------> rest
13561              *
13562              * where all the pad indexes are sequential and of the same type
13563              * (INTRO or not).
13564              * We convert the pushmark into a padrange op, then skip
13565              * any other pad ops, and possibly some trailing ops.
13566              * Note that we don't null() the skipped ops, to make it
13567              * easier for Deparse to undo this optimisation (and none of
13568              * the skipped ops are holding any resourses). It also makes
13569              * it easier for find_uninit_var(), as it can just ignore
13570              * padrange, and examine the original pad ops.
13571              */
13572         {
13573             OP *p;
13574             OP *followop = NULL; /* the op that will follow the padrange op */
13575             U8 count = 0;
13576             U8 intro = 0;
13577             PADOFFSET base = 0; /* init only to stop compiler whining */
13578             bool gvoid = 0;     /* init only to stop compiler whining */
13579             bool defav = 0;  /* seen (...) = @_ */
13580             bool reuse = 0;  /* reuse an existing padrange op */
13581
13582             /* look for a pushmark -> gv[_] -> rv2av */
13583
13584             {
13585                 OP *rv2av, *q;
13586                 p = o->op_next;
13587                 if (   p->op_type == OP_GV
13588                     && cGVOPx_gv(p) == PL_defgv
13589                     && (rv2av = p->op_next)
13590                     && rv2av->op_type == OP_RV2AV
13591                     && !(rv2av->op_flags & OPf_REF)
13592                     && !(rv2av->op_private & (OPpLVAL_INTRO|OPpMAYBE_LVSUB))
13593                     && ((rv2av->op_flags & OPf_WANT) == OPf_WANT_LIST)
13594                 ) {
13595                     q = rv2av->op_next;
13596                     if (q->op_type == OP_NULL)
13597                         q = q->op_next;
13598                     if (q->op_type == OP_PUSHMARK) {
13599                         defav = 1;
13600                         p = q;
13601                     }
13602                 }
13603             }
13604             if (!defav) {
13605                 p = o;
13606             }
13607
13608             /* scan for PAD ops */
13609
13610             for (p = p->op_next; p; p = p->op_next) {
13611                 if (p->op_type == OP_NULL)
13612                     continue;
13613
13614                 if ((     p->op_type != OP_PADSV
13615                        && p->op_type != OP_PADAV
13616                        && p->op_type != OP_PADHV
13617                     )
13618                       /* any private flag other than INTRO? e.g. STATE */
13619                    || (p->op_private & ~OPpLVAL_INTRO)
13620                 )
13621                     break;
13622
13623                 /* let $a[N] potentially be optimised into AELEMFAST_LEX
13624                  * instead */
13625                 if (   p->op_type == OP_PADAV
13626                     && p->op_next
13627                     && p->op_next->op_type == OP_CONST
13628                     && p->op_next->op_next
13629                     && p->op_next->op_next->op_type == OP_AELEM
13630                 )
13631                     break;
13632
13633                 /* for 1st padop, note what type it is and the range
13634                  * start; for the others, check that it's the same type
13635                  * and that the targs are contiguous */
13636                 if (count == 0) {
13637                     intro = (p->op_private & OPpLVAL_INTRO);
13638                     base = p->op_targ;
13639                     gvoid = OP_GIMME(p,0) == G_VOID;
13640                 }
13641                 else {
13642                     if ((p->op_private & OPpLVAL_INTRO) != intro)
13643                         break;
13644                     /* Note that you'd normally  expect targs to be
13645                      * contiguous in my($a,$b,$c), but that's not the case
13646                      * when external modules start doing things, e.g.
13647                      i* Function::Parameters */
13648                     if (p->op_targ != base + count)
13649                         break;
13650                     assert(p->op_targ == base + count);
13651                     /* Either all the padops or none of the padops should
13652                        be in void context.  Since we only do the optimisa-
13653                        tion for av/hv when the aggregate itself is pushed
13654                        on to the stack (one item), there is no need to dis-
13655                        tinguish list from scalar context.  */
13656                     if (gvoid != (OP_GIMME(p,0) == G_VOID))
13657                         break;
13658                 }
13659
13660                 /* for AV, HV, only when we're not flattening */
13661                 if (   p->op_type != OP_PADSV
13662                     && !gvoid
13663                     && !(p->op_flags & OPf_REF)
13664                 )
13665                     break;
13666
13667                 if (count >= OPpPADRANGE_COUNTMASK)
13668                     break;
13669
13670                 /* there's a biggest base we can fit into a
13671                  * SAVEt_CLEARPADRANGE in pp_padrange.
13672                  * (The sizeof() stuff will be constant-folded, and is
13673                  * intended to avoid getting "comparison is always false"
13674                  * compiler warnings)
13675                  */
13676                 if (   intro
13677                     && (8*sizeof(base) >
13678                         8*sizeof(UV)-OPpPADRANGE_COUNTSHIFT-SAVE_TIGHT_SHIFT
13679                         ? base : 0) >
13680                         (UV_MAX >> (OPpPADRANGE_COUNTSHIFT+SAVE_TIGHT_SHIFT))
13681                 )
13682                     break;
13683
13684                 /* Success! We've got another valid pad op to optimise away */
13685                 count++;
13686                 followop = p->op_next;
13687             }
13688
13689             if (count < 1 || (count == 1 && !defav))
13690                 break;
13691
13692             /* pp_padrange in specifically compile-time void context
13693              * skips pushing a mark and lexicals; in all other contexts
13694              * (including unknown till runtime) it pushes a mark and the
13695              * lexicals. We must be very careful then, that the ops we
13696              * optimise away would have exactly the same effect as the
13697              * padrange.
13698              * In particular in void context, we can only optimise to
13699              * a padrange if see see the complete sequence
13700              *     pushmark, pad*v, ...., list
13701              * which has the net effect of of leaving the markstack as it
13702              * was.  Not pushing on to the stack (whereas padsv does touch
13703              * the stack) makes no difference in void context.
13704              */
13705             assert(followop);
13706             if (gvoid) {
13707                 if (followop->op_type == OP_LIST
13708                         && OP_GIMME(followop,0) == G_VOID
13709                    )
13710                 {
13711                     followop = followop->op_next; /* skip OP_LIST */
13712
13713                     /* consolidate two successive my(...);'s */
13714
13715                     if (   oldoldop
13716                         && oldoldop->op_type == OP_PADRANGE
13717                         && (oldoldop->op_flags & OPf_WANT) == OPf_WANT_VOID
13718                         && (oldoldop->op_private & OPpLVAL_INTRO) == intro
13719                         && !(oldoldop->op_flags & OPf_SPECIAL)
13720                     ) {
13721                         U8 old_count;
13722                         assert(oldoldop->op_next == oldop);
13723                         assert(   oldop->op_type == OP_NEXTSTATE
13724                                || oldop->op_type == OP_DBSTATE);
13725                         assert(oldop->op_next == o);
13726
13727                         old_count
13728                             = (oldoldop->op_private & OPpPADRANGE_COUNTMASK);
13729
13730                        /* Do not assume pad offsets for $c and $d are con-
13731                           tiguous in
13732                             my ($a,$b,$c);
13733                             my ($d,$e,$f);
13734                         */
13735                         if (  oldoldop->op_targ + old_count == base
13736                            && old_count < OPpPADRANGE_COUNTMASK - count) {
13737                             base = oldoldop->op_targ;
13738                             count += old_count;
13739                             reuse = 1;
13740                         }
13741                     }
13742
13743                     /* if there's any immediately following singleton
13744                      * my var's; then swallow them and the associated
13745                      * nextstates; i.e.
13746                      *    my ($a,$b); my $c; my $d;
13747                      * is treated as
13748                      *    my ($a,$b,$c,$d);
13749                      */
13750
13751                     while (    ((p = followop->op_next))
13752                             && (  p->op_type == OP_PADSV
13753                                || p->op_type == OP_PADAV
13754                                || p->op_type == OP_PADHV)
13755                             && (p->op_flags & OPf_WANT) == OPf_WANT_VOID
13756                             && (p->op_private & OPpLVAL_INTRO) == intro
13757                             && !(p->op_private & ~OPpLVAL_INTRO)
13758                             && p->op_next
13759                             && (   p->op_next->op_type == OP_NEXTSTATE
13760                                 || p->op_next->op_type == OP_DBSTATE)
13761                             && count < OPpPADRANGE_COUNTMASK
13762                             && base + count == p->op_targ
13763                     ) {
13764                         count++;
13765                         followop = p->op_next;
13766                     }
13767                 }
13768                 else
13769                     break;
13770             }
13771
13772             if (reuse) {
13773                 assert(oldoldop->op_type == OP_PADRANGE);
13774                 oldoldop->op_next = followop;
13775                 oldoldop->op_private = (intro | count);
13776                 o = oldoldop;
13777                 oldop = NULL;
13778                 oldoldop = NULL;
13779             }
13780             else {
13781                 /* Convert the pushmark into a padrange.
13782                  * To make Deparse easier, we guarantee that a padrange was
13783                  * *always* formerly a pushmark */
13784                 assert(o->op_type == OP_PUSHMARK);
13785                 o->op_next = followop;
13786                 OpTYPE_set(o, OP_PADRANGE);
13787                 o->op_targ = base;
13788                 /* bit 7: INTRO; bit 6..0: count */
13789                 o->op_private = (intro | count);
13790                 o->op_flags = ((o->op_flags & ~(OPf_WANT|OPf_SPECIAL))
13791                               | gvoid * OPf_WANT_VOID
13792                               | (defav ? OPf_SPECIAL : 0));
13793             }
13794             break;
13795         }
13796
13797         case OP_PADAV:
13798         case OP_PADSV:
13799         case OP_PADHV:
13800         /* Skip over state($x) in void context.  */
13801         if (oldop && o->op_private == (OPpPAD_STATE|OPpLVAL_INTRO)
13802          && (o->op_flags & OPf_WANT) == OPf_WANT_VOID)
13803         {
13804             oldop->op_next = o->op_next;
13805             goto redo_nextstate;
13806         }
13807         if (o->op_type != OP_PADAV)
13808             break;
13809         /* FALLTHROUGH */
13810         case OP_GV:
13811             if (o->op_type == OP_PADAV || o->op_next->op_type == OP_RV2AV) {
13812                 OP* const pop = (o->op_type == OP_PADAV) ?
13813                             o->op_next : o->op_next->op_next;
13814                 IV i;
13815                 if (pop && pop->op_type == OP_CONST &&
13816                     ((PL_op = pop->op_next)) &&
13817                     pop->op_next->op_type == OP_AELEM &&
13818                     !(pop->op_next->op_private &
13819                       (OPpLVAL_INTRO|OPpLVAL_DEFER|OPpDEREF|OPpMAYBE_LVSUB)) &&
13820                     (i = SvIV(((SVOP*)pop)->op_sv)) >= -128 && i <= 127)
13821                 {
13822                     GV *gv;
13823                     if (cSVOPx(pop)->op_private & OPpCONST_STRICT)
13824                         no_bareword_allowed(pop);
13825                     if (o->op_type == OP_GV)
13826                         op_null(o->op_next);
13827                     op_null(pop->op_next);
13828                     op_null(pop);
13829                     o->op_flags |= pop->op_next->op_flags & OPf_MOD;
13830                     o->op_next = pop->op_next->op_next;
13831                     o->op_ppaddr = PL_ppaddr[OP_AELEMFAST];
13832                     o->op_private = (U8)i;
13833                     if (o->op_type == OP_GV) {
13834                         gv = cGVOPo_gv;
13835                         GvAVn(gv);
13836                         o->op_type = OP_AELEMFAST;
13837                     }
13838                     else
13839                         o->op_type = OP_AELEMFAST_LEX;
13840                 }
13841                 if (o->op_type != OP_GV)
13842                     break;
13843             }
13844
13845             /* Remove $foo from the op_next chain in void context.  */
13846             if (oldop
13847              && (  o->op_next->op_type == OP_RV2SV
13848                 || o->op_next->op_type == OP_RV2AV
13849                 || o->op_next->op_type == OP_RV2HV  )
13850              && (o->op_next->op_flags & OPf_WANT) == OPf_WANT_VOID
13851              && !(o->op_next->op_private & OPpLVAL_INTRO))
13852             {
13853                 oldop->op_next = o->op_next->op_next;
13854                 /* Reprocess the previous op if it is a nextstate, to
13855                    allow double-nextstate optimisation.  */
13856               redo_nextstate:
13857                 if (oldop->op_type == OP_NEXTSTATE) {
13858                     oldop->op_opt = 0;
13859                     o = oldop;
13860                     oldop = oldoldop;
13861                     oldoldop = NULL;
13862                     goto redo;
13863                 }
13864                 o = oldop->op_next;
13865                 goto redo;
13866             }
13867             else if (o->op_next->op_type == OP_RV2SV) {
13868                 if (!(o->op_next->op_private & OPpDEREF)) {
13869                     op_null(o->op_next);
13870                     o->op_private |= o->op_next->op_private & (OPpLVAL_INTRO
13871                                                                | OPpOUR_INTRO);
13872                     o->op_next = o->op_next->op_next;
13873                     OpTYPE_set(o, OP_GVSV);
13874                 }
13875             }
13876             else if (o->op_next->op_type == OP_READLINE
13877                     && o->op_next->op_next->op_type == OP_CONCAT
13878                     && (o->op_next->op_next->op_flags & OPf_STACKED))
13879             {
13880                 /* Turn "$a .= <FH>" into an OP_RCATLINE. AMS 20010917 */
13881                 OpTYPE_set(o, OP_RCATLINE);
13882                 o->op_flags |= OPf_STACKED;
13883                 op_null(o->op_next->op_next);
13884                 op_null(o->op_next);
13885             }
13886
13887             break;
13888         
13889 #define HV_OR_SCALARHV(op)                                   \
13890     (  (op)->op_type == OP_PADHV || (op)->op_type == OP_RV2HV \
13891        ? (op)                                                  \
13892        : (op)->op_type == OP_SCALAR && (op)->op_flags & OPf_KIDS \
13893        && (  cUNOPx(op)->op_first->op_type == OP_PADHV          \
13894           || cUNOPx(op)->op_first->op_type == OP_RV2HV)          \
13895          ? cUNOPx(op)->op_first                                   \
13896          : NULL)
13897
13898         case OP_NOT:
13899             if ((fop = HV_OR_SCALARHV(cUNOP->op_first)))
13900                 fop->op_private |= OPpTRUEBOOL;
13901             break;
13902
13903         case OP_AND:
13904         case OP_OR:
13905         case OP_DOR:
13906             fop = cLOGOP->op_first;
13907             sop = OpSIBLING(fop);
13908             while (cLOGOP->op_other->op_type == OP_NULL)
13909                 cLOGOP->op_other = cLOGOP->op_other->op_next;
13910             while (o->op_next && (   o->op_type == o->op_next->op_type
13911                                   || o->op_next->op_type == OP_NULL))
13912                 o->op_next = o->op_next->op_next;
13913
13914             /* if we're an OR and our next is a AND in void context, we'll
13915                follow it's op_other on short circuit, same for reverse.
13916                We can't do this with OP_DOR since if it's true, its return
13917                value is the underlying value which must be evaluated
13918                by the next op */
13919             if (o->op_next &&
13920                 (
13921                     (IS_AND_OP(o) && IS_OR_OP(o->op_next))
13922                  || (IS_OR_OP(o) && IS_AND_OP(o->op_next))
13923                 )
13924                 && (o->op_next->op_flags & OPf_WANT) == OPf_WANT_VOID
13925             ) {
13926                 o->op_next = ((LOGOP*)o->op_next)->op_other;
13927             }
13928             DEFER(cLOGOP->op_other);
13929           
13930             o->op_opt = 1;
13931             fop = HV_OR_SCALARHV(fop);
13932             if (sop) sop = HV_OR_SCALARHV(sop);
13933             if (fop || sop
13934             ){  
13935                 OP * nop = o;
13936                 OP * lop = o;
13937                 if (!((nop->op_flags & OPf_WANT) == OPf_WANT_VOID)) {
13938                     while (nop && nop->op_next) {
13939                         switch (nop->op_next->op_type) {
13940                             case OP_NOT:
13941                             case OP_AND:
13942                             case OP_OR:
13943                             case OP_DOR:
13944                                 lop = nop = nop->op_next;
13945                                 break;
13946                             case OP_NULL:
13947                                 nop = nop->op_next;
13948                                 break;
13949                             default:
13950                                 nop = NULL;
13951                                 break;
13952                         }
13953                     }            
13954                 }
13955                 if (fop) {
13956                     if (  (lop->op_flags & OPf_WANT) == OPf_WANT_VOID
13957                       || o->op_type == OP_AND  )
13958                         fop->op_private |= OPpTRUEBOOL;
13959                     else if (!(lop->op_flags & OPf_WANT))
13960                         fop->op_private |= OPpMAYBE_TRUEBOOL;
13961                 }
13962                 if (  (lop->op_flags & OPf_WANT) == OPf_WANT_VOID
13963                    && sop)
13964                     sop->op_private |= OPpTRUEBOOL;
13965             }                  
13966             
13967             
13968             break;
13969         
13970         case OP_COND_EXPR:
13971             if ((fop = HV_OR_SCALARHV(cLOGOP->op_first)))
13972                 fop->op_private |= OPpTRUEBOOL;
13973 #undef HV_OR_SCALARHV
13974             /* GERONIMO! */ /* FALLTHROUGH */
13975
13976         case OP_MAPWHILE:
13977         case OP_GREPWHILE:
13978         case OP_ANDASSIGN:
13979         case OP_ORASSIGN:
13980         case OP_DORASSIGN:
13981         case OP_RANGE:
13982         case OP_ONCE:
13983             while (cLOGOP->op_other->op_type == OP_NULL)
13984                 cLOGOP->op_other = cLOGOP->op_other->op_next;
13985             DEFER(cLOGOP->op_other);
13986             break;
13987
13988         case OP_ENTERLOOP:
13989         case OP_ENTERITER:
13990             while (cLOOP->op_redoop->op_type == OP_NULL)
13991                 cLOOP->op_redoop = cLOOP->op_redoop->op_next;
13992             while (cLOOP->op_nextop->op_type == OP_NULL)
13993                 cLOOP->op_nextop = cLOOP->op_nextop->op_next;
13994             while (cLOOP->op_lastop->op_type == OP_NULL)
13995                 cLOOP->op_lastop = cLOOP->op_lastop->op_next;
13996             /* a while(1) loop doesn't have an op_next that escapes the
13997              * loop, so we have to explicitly follow the op_lastop to
13998              * process the rest of the code */
13999             DEFER(cLOOP->op_lastop);
14000             break;
14001
14002         case OP_ENTERTRY:
14003             assert(cLOGOPo->op_other->op_type == OP_LEAVETRY);
14004             DEFER(cLOGOPo->op_other);
14005             break;
14006
14007         case OP_SUBST:
14008             assert(!(cPMOP->op_pmflags & PMf_ONCE));
14009             while (cPMOP->op_pmstashstartu.op_pmreplstart &&
14010                    cPMOP->op_pmstashstartu.op_pmreplstart->op_type == OP_NULL)
14011                 cPMOP->op_pmstashstartu.op_pmreplstart
14012                     = cPMOP->op_pmstashstartu.op_pmreplstart->op_next;
14013             DEFER(cPMOP->op_pmstashstartu.op_pmreplstart);
14014             break;
14015
14016         case OP_SORT: {
14017             OP *oright;
14018
14019             if (o->op_flags & OPf_SPECIAL) {
14020                 /* first arg is a code block */
14021                 OP * const nullop = OpSIBLING(cLISTOP->op_first);
14022                 OP * kid          = cUNOPx(nullop)->op_first;
14023
14024                 assert(nullop->op_type == OP_NULL);
14025                 assert(kid->op_type == OP_SCOPE
14026                  || (kid->op_type == OP_NULL && kid->op_targ == OP_LEAVE));
14027                 /* since OP_SORT doesn't have a handy op_other-style
14028                  * field that can point directly to the start of the code
14029                  * block, store it in the otherwise-unused op_next field
14030                  * of the top-level OP_NULL. This will be quicker at
14031                  * run-time, and it will also allow us to remove leading
14032                  * OP_NULLs by just messing with op_nexts without
14033                  * altering the basic op_first/op_sibling layout. */
14034                 kid = kLISTOP->op_first;
14035                 assert(
14036                       (kid->op_type == OP_NULL
14037                       && (  kid->op_targ == OP_NEXTSTATE
14038                          || kid->op_targ == OP_DBSTATE  ))
14039                     || kid->op_type == OP_STUB
14040                     || kid->op_type == OP_ENTER);
14041                 nullop->op_next = kLISTOP->op_next;
14042                 DEFER(nullop->op_next);
14043             }
14044
14045             /* check that RHS of sort is a single plain array */
14046             oright = cUNOPo->op_first;
14047             if (!oright || oright->op_type != OP_PUSHMARK)
14048                 break;
14049
14050             if (o->op_private & OPpSORT_INPLACE)
14051                 break;
14052
14053             /* reverse sort ... can be optimised.  */
14054             if (!OpHAS_SIBLING(cUNOPo)) {
14055                 /* Nothing follows us on the list. */
14056                 OP * const reverse = o->op_next;
14057
14058                 if (reverse->op_type == OP_REVERSE &&
14059                     (reverse->op_flags & OPf_WANT) == OPf_WANT_LIST) {
14060                     OP * const pushmark = cUNOPx(reverse)->op_first;
14061                     if (pushmark && (pushmark->op_type == OP_PUSHMARK)
14062                         && (OpSIBLING(cUNOPx(pushmark)) == o)) {
14063                         /* reverse -> pushmark -> sort */
14064                         o->op_private |= OPpSORT_REVERSE;
14065                         op_null(reverse);
14066                         pushmark->op_next = oright->op_next;
14067                         op_null(oright);
14068                     }
14069                 }
14070             }
14071
14072             break;
14073         }
14074
14075         case OP_REVERSE: {
14076             OP *ourmark, *theirmark, *ourlast, *iter, *expushmark, *rv2av;
14077             OP *gvop = NULL;
14078             LISTOP *enter, *exlist;
14079
14080             if (o->op_private & OPpSORT_INPLACE)
14081                 break;
14082
14083             enter = (LISTOP *) o->op_next;
14084             if (!enter)
14085                 break;
14086             if (enter->op_type == OP_NULL) {
14087                 enter = (LISTOP *) enter->op_next;
14088                 if (!enter)
14089                     break;
14090             }
14091             /* for $a (...) will have OP_GV then OP_RV2GV here.
14092                for (...) just has an OP_GV.  */
14093             if (enter->op_type == OP_GV) {
14094                 gvop = (OP *) enter;
14095                 enter = (LISTOP *) enter->op_next;
14096                 if (!enter)
14097                     break;
14098                 if (enter->op_type == OP_RV2GV) {
14099                   enter = (LISTOP *) enter->op_next;
14100                   if (!enter)
14101                     break;
14102                 }
14103             }
14104
14105             if (enter->op_type != OP_ENTERITER)
14106                 break;
14107
14108             iter = enter->op_next;
14109             if (!iter || iter->op_type != OP_ITER)
14110                 break;
14111             
14112             expushmark = enter->op_first;
14113             if (!expushmark || expushmark->op_type != OP_NULL
14114                 || expushmark->op_targ != OP_PUSHMARK)
14115                 break;
14116
14117             exlist = (LISTOP *) OpSIBLING(expushmark);
14118             if (!exlist || exlist->op_type != OP_NULL
14119                 || exlist->op_targ != OP_LIST)
14120                 break;
14121
14122             if (exlist->op_last != o) {
14123                 /* Mmm. Was expecting to point back to this op.  */
14124                 break;
14125             }
14126             theirmark = exlist->op_first;
14127             if (!theirmark || theirmark->op_type != OP_PUSHMARK)
14128                 break;
14129
14130             if (OpSIBLING(theirmark) != o) {
14131                 /* There's something between the mark and the reverse, eg
14132                    for (1, reverse (...))
14133                    so no go.  */
14134                 break;
14135             }
14136
14137             ourmark = ((LISTOP *)o)->op_first;
14138             if (!ourmark || ourmark->op_type != OP_PUSHMARK)
14139                 break;
14140
14141             ourlast = ((LISTOP *)o)->op_last;
14142             if (!ourlast || ourlast->op_next != o)
14143                 break;
14144
14145             rv2av = OpSIBLING(ourmark);
14146             if (rv2av && rv2av->op_type == OP_RV2AV && !OpHAS_SIBLING(rv2av)
14147                 && rv2av->op_flags == (OPf_WANT_LIST | OPf_KIDS)) {
14148                 /* We're just reversing a single array.  */
14149                 rv2av->op_flags = OPf_WANT_SCALAR | OPf_KIDS | OPf_REF;
14150                 enter->op_flags |= OPf_STACKED;
14151             }
14152
14153             /* We don't have control over who points to theirmark, so sacrifice
14154                ours.  */
14155             theirmark->op_next = ourmark->op_next;
14156             theirmark->op_flags = ourmark->op_flags;
14157             ourlast->op_next = gvop ? gvop : (OP *) enter;
14158             op_null(ourmark);
14159             op_null(o);
14160             enter->op_private |= OPpITER_REVERSED;
14161             iter->op_private |= OPpITER_REVERSED;
14162
14163             oldoldop = NULL;
14164             oldop    = ourlast;
14165             o        = oldop->op_next;
14166             goto redo;
14167             
14168             break;
14169         }
14170
14171         case OP_QR:
14172         case OP_MATCH:
14173             if (!(cPMOP->op_pmflags & PMf_ONCE)) {
14174                 assert (!cPMOP->op_pmstashstartu.op_pmreplstart);
14175             }
14176             break;
14177
14178         case OP_RUNCV:
14179             if (!(o->op_private & OPpOFFBYONE) && !CvCLONE(PL_compcv)
14180              && (!CvANON(PL_compcv) || (!PL_cv_has_eval && !PL_perldb)))
14181             {
14182                 SV *sv;
14183                 if (CvEVAL(PL_compcv)) sv = &PL_sv_undef;
14184                 else {
14185                     sv = newRV((SV *)PL_compcv);
14186                     sv_rvweaken(sv);
14187                     SvREADONLY_on(sv);
14188                 }
14189                 OpTYPE_set(o, OP_CONST);
14190                 o->op_flags |= OPf_SPECIAL;
14191                 cSVOPo->op_sv = sv;
14192             }
14193             break;
14194
14195         case OP_SASSIGN:
14196             if (OP_GIMME(o,0) == G_VOID
14197              || (  o->op_next->op_type == OP_LINESEQ
14198                 && (  o->op_next->op_next->op_type == OP_LEAVESUB
14199                    || (  o->op_next->op_next->op_type == OP_RETURN
14200                       && !CvLVALUE(PL_compcv)))))
14201             {
14202                 OP *right = cBINOP->op_first;
14203                 if (right) {
14204                     /*   sassign
14205                     *      RIGHT
14206                     *      substr
14207                     *         pushmark
14208                     *         arg1
14209                     *         arg2
14210                     *         ...
14211                     * becomes
14212                     *
14213                     *  ex-sassign
14214                     *     substr
14215                     *        pushmark
14216                     *        RIGHT
14217                     *        arg1
14218                     *        arg2
14219                     *        ...
14220                     */
14221                     OP *left = OpSIBLING(right);
14222                     if (left->op_type == OP_SUBSTR
14223                          && (left->op_private & 7) < 4) {
14224                         op_null(o);
14225                         /* cut out right */
14226                         op_sibling_splice(o, NULL, 1, NULL);
14227                         /* and insert it as second child of OP_SUBSTR */
14228                         op_sibling_splice(left, cBINOPx(left)->op_first, 0,
14229                                     right);
14230                         left->op_private |= OPpSUBSTR_REPL_FIRST;
14231                         left->op_flags =
14232                             (o->op_flags & ~OPf_WANT) | OPf_WANT_VOID;
14233                     }
14234                 }
14235             }
14236             break;
14237
14238         case OP_AASSIGN: {
14239             int l, r, lr, lscalars, rscalars;
14240
14241             /* handle common vars detection, e.g. ($a,$b) = ($b,$a).
14242                Note that we do this now rather than in newASSIGNOP(),
14243                since only by now are aliased lexicals flagged as such
14244
14245                See the essay "Common vars in list assignment" above for
14246                the full details of the rationale behind all the conditions
14247                below.
14248
14249                PL_generation sorcery:
14250                To detect whether there are common vars, the global var
14251                PL_generation is incremented for each assign op we scan.
14252                Then we run through all the lexical variables on the LHS,
14253                of the assignment, setting a spare slot in each of them to
14254                PL_generation.  Then we scan the RHS, and if any lexicals
14255                already have that value, we know we've got commonality.
14256                Also, if the generation number is already set to
14257                PERL_INT_MAX, then the variable is involved in aliasing, so
14258                we also have potential commonality in that case.
14259              */
14260
14261             PL_generation++;
14262             /* scan LHS */
14263             lscalars = 0;
14264             l = S_aassign_scan(aTHX_ cLISTOPo->op_last,  FALSE, 1, &lscalars);
14265             /* scan RHS */
14266             rscalars = 0;
14267             r = S_aassign_scan(aTHX_ cLISTOPo->op_first, TRUE, 1, &rscalars);
14268             lr = (l|r);
14269
14270
14271             /* After looking for things which are *always* safe, this main
14272              * if/else chain selects primarily based on the type of the
14273              * LHS, gradually working its way down from the more dangerous
14274              * to the more restrictive and thus safer cases */
14275
14276             if (   !l                      /* () = ....; */
14277                 || !r                      /* .... = (); */
14278                 || !(l & ~AAS_SAFE_SCALAR) /* (undef, pos()) = ...; */
14279                 || !(r & ~AAS_SAFE_SCALAR) /* ... = (1,2,length,undef); */
14280                 || (lscalars < 2)          /* ($x, undef) = ... */
14281             ) {
14282                 NOOP; /* always safe */
14283             }
14284             else if (l & AAS_DANGEROUS) {
14285                 /* always dangerous */
14286                 o->op_private |= OPpASSIGN_COMMON_SCALAR;
14287                 o->op_private |= OPpASSIGN_COMMON_AGG;
14288             }
14289             else if (l & (AAS_PKG_SCALAR|AAS_PKG_AGG)) {
14290                 /* package vars are always dangerous - too many
14291                  * aliasing possibilities */
14292                 if (l & AAS_PKG_SCALAR)
14293                     o->op_private |= OPpASSIGN_COMMON_SCALAR;
14294                 if (l & AAS_PKG_AGG)
14295                     o->op_private |= OPpASSIGN_COMMON_AGG;
14296             }
14297             else if (l & ( AAS_MY_SCALAR|AAS_MY_AGG
14298                           |AAS_LEX_SCALAR|AAS_LEX_AGG))
14299             {
14300                 /* LHS contains only lexicals and safe ops */
14301
14302                 if (l & (AAS_MY_AGG|AAS_LEX_AGG))
14303                     o->op_private |= OPpASSIGN_COMMON_AGG;
14304
14305                 if (l & (AAS_MY_SCALAR|AAS_LEX_SCALAR)) {
14306                     if (lr & AAS_LEX_SCALAR_COMM)
14307                         o->op_private |= OPpASSIGN_COMMON_SCALAR;
14308                     else if (   !(l & AAS_LEX_SCALAR)
14309                              && (r & AAS_DEFAV))
14310                     {
14311                         /* falsely mark
14312                          *    my (...) = @_
14313                          * as scalar-safe for performance reasons.
14314                          * (it will still have been marked _AGG if necessary */
14315                         NOOP;
14316                     }
14317                     else if (r  & (AAS_PKG_SCALAR|AAS_PKG_AGG|AAS_DANGEROUS))
14318                         o->op_private |= OPpASSIGN_COMMON_RC1;
14319                 }
14320             }
14321
14322             /* ... = ($x)
14323              * may have to handle aggregate on LHS, but we can't
14324              * have common scalars. */
14325             if (rscalars < 2)
14326                 o->op_private &=
14327                         ~(OPpASSIGN_COMMON_SCALAR|OPpASSIGN_COMMON_RC1);
14328
14329             break;
14330         }
14331
14332         case OP_CUSTOM: {
14333             Perl_cpeep_t cpeep = 
14334                 XopENTRYCUSTOM(o, xop_peep);
14335             if (cpeep)
14336                 cpeep(aTHX_ o, oldop);
14337             break;
14338         }
14339             
14340         }
14341         /* did we just null the current op? If so, re-process it to handle
14342          * eliding "empty" ops from the chain */
14343         if (o->op_type == OP_NULL && oldop && oldop->op_next == o) {
14344             o->op_opt = 0;
14345             o = oldop;
14346         }
14347         else {
14348             oldoldop = oldop;
14349             oldop = o;
14350         }
14351     }
14352     LEAVE;
14353 }
14354
14355 void
14356 Perl_peep(pTHX_ OP *o)
14357 {
14358     CALL_RPEEP(o);
14359 }
14360
14361 /*
14362 =head1 Custom Operators
14363
14364 =for apidoc Ao||custom_op_xop
14365 Return the XOP structure for a given custom op.  This macro should be
14366 considered internal to C<OP_NAME> and the other access macros: use them instead.
14367 This macro does call a function.  Prior
14368 to 5.19.6, this was implemented as a
14369 function.
14370
14371 =cut
14372 */
14373
14374 XOPRETANY
14375 Perl_custom_op_get_field(pTHX_ const OP *o, const xop_flags_enum field)
14376 {
14377     SV *keysv;
14378     HE *he = NULL;
14379     XOP *xop;
14380
14381     static const XOP xop_null = { 0, 0, 0, 0, 0 };
14382
14383     PERL_ARGS_ASSERT_CUSTOM_OP_GET_FIELD;
14384     assert(o->op_type == OP_CUSTOM);
14385
14386     /* This is wrong. It assumes a function pointer can be cast to IV,
14387      * which isn't guaranteed, but this is what the old custom OP code
14388      * did. In principle it should be safer to Copy the bytes of the
14389      * pointer into a PV: since the new interface is hidden behind
14390      * functions, this can be changed later if necessary.  */
14391     /* Change custom_op_xop if this ever happens */
14392     keysv = sv_2mortal(newSViv(PTR2IV(o->op_ppaddr)));
14393
14394     if (PL_custom_ops)
14395         he = hv_fetch_ent(PL_custom_ops, keysv, 0, 0);
14396
14397     /* assume noone will have just registered a desc */
14398     if (!he && PL_custom_op_names &&
14399         (he = hv_fetch_ent(PL_custom_op_names, keysv, 0, 0))
14400     ) {
14401         const char *pv;
14402         STRLEN l;
14403
14404         /* XXX does all this need to be shared mem? */
14405         Newxz(xop, 1, XOP);
14406         pv = SvPV(HeVAL(he), l);
14407         XopENTRY_set(xop, xop_name, savepvn(pv, l));
14408         if (PL_custom_op_descs &&
14409             (he = hv_fetch_ent(PL_custom_op_descs, keysv, 0, 0))
14410         ) {
14411             pv = SvPV(HeVAL(he), l);
14412             XopENTRY_set(xop, xop_desc, savepvn(pv, l));
14413         }
14414         Perl_custom_op_register(aTHX_ o->op_ppaddr, xop);
14415     }
14416     else {
14417         if (!he)
14418             xop = (XOP *)&xop_null;
14419         else
14420             xop = INT2PTR(XOP *, SvIV(HeVAL(he)));
14421     }
14422     {
14423         XOPRETANY any;
14424         if(field == XOPe_xop_ptr) {
14425             any.xop_ptr = xop;
14426         } else {
14427             const U32 flags = XopFLAGS(xop);
14428             if(flags & field) {
14429                 switch(field) {
14430                 case XOPe_xop_name:
14431                     any.xop_name = xop->xop_name;
14432                     break;
14433                 case XOPe_xop_desc:
14434                     any.xop_desc = xop->xop_desc;
14435                     break;
14436                 case XOPe_xop_class:
14437                     any.xop_class = xop->xop_class;
14438                     break;
14439                 case XOPe_xop_peep:
14440                     any.xop_peep = xop->xop_peep;
14441                     break;
14442                 default:
14443                     NOT_REACHED; /* NOTREACHED */
14444                     break;
14445                 }
14446             } else {
14447                 switch(field) {
14448                 case XOPe_xop_name:
14449                     any.xop_name = XOPd_xop_name;
14450                     break;
14451                 case XOPe_xop_desc:
14452                     any.xop_desc = XOPd_xop_desc;
14453                     break;
14454                 case XOPe_xop_class:
14455                     any.xop_class = XOPd_xop_class;
14456                     break;
14457                 case XOPe_xop_peep:
14458                     any.xop_peep = XOPd_xop_peep;
14459                     break;
14460                 default:
14461                     NOT_REACHED; /* NOTREACHED */
14462                     break;
14463                 }
14464             }
14465         }
14466         /* Some gcc releases emit a warning for this function:
14467          * op.c: In function 'Perl_custom_op_get_field':
14468          * op.c:...: warning: 'any.xop_name' may be used uninitialized in this function [-Wmaybe-uninitialized]
14469          * Whether this is true, is currently unknown. */
14470         return any;
14471     }
14472 }
14473
14474 /*
14475 =for apidoc Ao||custom_op_register
14476 Register a custom op.  See L<perlguts/"Custom Operators">.
14477
14478 =cut
14479 */
14480
14481 void
14482 Perl_custom_op_register(pTHX_ Perl_ppaddr_t ppaddr, const XOP *xop)
14483 {
14484     SV *keysv;
14485
14486     PERL_ARGS_ASSERT_CUSTOM_OP_REGISTER;
14487
14488     /* see the comment in custom_op_xop */
14489     keysv = sv_2mortal(newSViv(PTR2IV(ppaddr)));
14490
14491     if (!PL_custom_ops)
14492         PL_custom_ops = newHV();
14493
14494     if (!hv_store_ent(PL_custom_ops, keysv, newSViv(PTR2IV(xop)), 0))
14495         Perl_croak(aTHX_ "panic: can't register custom OP %s", xop->xop_name);
14496 }
14497
14498 /*
14499
14500 =for apidoc core_prototype
14501
14502 This function assigns the prototype of the named core function to C<sv>, or
14503 to a new mortal SV if C<sv> is C<NULL>.  It returns the modified C<sv>, or
14504 C<NULL> if the core function has no prototype.  C<code> is a code as returned
14505 by C<keyword()>.  It must not be equal to 0.
14506
14507 =cut
14508 */
14509
14510 SV *
14511 Perl_core_prototype(pTHX_ SV *sv, const char *name, const int code,
14512                           int * const opnum)
14513 {
14514     int i = 0, n = 0, seen_question = 0, defgv = 0;
14515     I32 oa;
14516 #define MAX_ARGS_OP ((sizeof(I32) - 1) * 2)
14517     char str[ MAX_ARGS_OP * 2 + 2 ]; /* One ';', one '\0' */
14518     bool nullret = FALSE;
14519
14520     PERL_ARGS_ASSERT_CORE_PROTOTYPE;
14521
14522     assert (code);
14523
14524     if (!sv) sv = sv_newmortal();
14525
14526 #define retsetpvs(x,y) sv_setpvs(sv, x); if(opnum) *opnum=(y); return sv
14527
14528     switch (code < 0 ? -code : code) {
14529     case KEY_and   : case KEY_chop: case KEY_chomp:
14530     case KEY_cmp   : case KEY_defined: case KEY_delete: case KEY_exec  :
14531     case KEY_exists: case KEY_eq     : case KEY_ge    : case KEY_goto  :
14532     case KEY_grep  : case KEY_gt     : case KEY_last  : case KEY_le    :
14533     case KEY_lt    : case KEY_map    : case KEY_ne    : case KEY_next  :
14534     case KEY_or    : case KEY_print  : case KEY_printf: case KEY_qr    :
14535     case KEY_redo  : case KEY_require: case KEY_return: case KEY_say   :
14536     case KEY_select: case KEY_sort   : case KEY_split : case KEY_system:
14537     case KEY_x     : case KEY_xor    :
14538         if (!opnum) return NULL; nullret = TRUE; goto findopnum;
14539     case KEY_glob:    retsetpvs("_;", OP_GLOB);
14540     case KEY_keys:    retsetpvs("\\[%@]", OP_KEYS);
14541     case KEY_values:  retsetpvs("\\[%@]", OP_VALUES);
14542     case KEY_each:    retsetpvs("\\[%@]", OP_EACH);
14543     case KEY_push:    retsetpvs("\\@@", OP_PUSH);
14544     case KEY_unshift: retsetpvs("\\@@", OP_UNSHIFT);
14545     case KEY_pop:     retsetpvs(";\\@", OP_POP);
14546     case KEY_shift:   retsetpvs(";\\@", OP_SHIFT);
14547     case KEY_pos:     retsetpvs(";\\[$*]", OP_POS);
14548     case KEY_splice:
14549         retsetpvs("\\@;$$@", OP_SPLICE);
14550     case KEY___FILE__: case KEY___LINE__: case KEY___PACKAGE__:
14551         retsetpvs("", 0);
14552     case KEY_evalbytes:
14553         name = "entereval"; break;
14554     case KEY_readpipe:
14555         name = "backtick";
14556     }
14557
14558 #undef retsetpvs
14559
14560   findopnum:
14561     while (i < MAXO) {  /* The slow way. */
14562         if (strEQ(name, PL_op_name[i])
14563             || strEQ(name, PL_op_desc[i]))
14564         {
14565             if (nullret) { assert(opnum); *opnum = i; return NULL; }
14566             goto found;
14567         }
14568         i++;
14569     }
14570     return NULL;
14571   found:
14572     defgv = PL_opargs[i] & OA_DEFGV;
14573     oa = PL_opargs[i] >> OASHIFT;
14574     while (oa) {
14575         if (oa & OA_OPTIONAL && !seen_question && (
14576               !defgv || (oa & (OA_OPTIONAL - 1)) == OA_FILEREF
14577         )) {
14578             seen_question = 1;
14579             str[n++] = ';';
14580         }
14581         if ((oa & (OA_OPTIONAL - 1)) >= OA_AVREF
14582             && (oa & (OA_OPTIONAL - 1)) <= OA_SCALARREF
14583             /* But globs are already references (kinda) */
14584             && (oa & (OA_OPTIONAL - 1)) != OA_FILEREF
14585         ) {
14586             str[n++] = '\\';
14587         }
14588         if ((oa & (OA_OPTIONAL - 1)) == OA_SCALARREF
14589          && !scalar_mod_type(NULL, i)) {
14590             str[n++] = '[';
14591             str[n++] = '$';
14592             str[n++] = '@';
14593             str[n++] = '%';
14594             if (i == OP_LOCK || i == OP_UNDEF) str[n++] = '&';
14595             str[n++] = '*';
14596             str[n++] = ']';
14597         }
14598         else str[n++] = ("?$@@%&*$")[oa & (OA_OPTIONAL - 1)];
14599         if (oa & OA_OPTIONAL && defgv && str[n-1] == '$') {
14600             str[n-1] = '_'; defgv = 0;
14601         }
14602         oa = oa >> 4;
14603     }
14604     if (code == -KEY_not || code == -KEY_getprotobynumber) str[n++] = ';';
14605     str[n++] = '\0';
14606     sv_setpvn(sv, str, n - 1);
14607     if (opnum) *opnum = i;
14608     return sv;
14609 }
14610
14611 OP *
14612 Perl_coresub_op(pTHX_ SV * const coreargssv, const int code,
14613                       const int opnum)
14614 {
14615     OP * const argop = newSVOP(OP_COREARGS,0,coreargssv);
14616     OP *o;
14617
14618     PERL_ARGS_ASSERT_CORESUB_OP;
14619
14620     switch(opnum) {
14621     case 0:
14622         return op_append_elem(OP_LINESEQ,
14623                        argop,
14624                        newSLICEOP(0,
14625                                   newSVOP(OP_CONST, 0, newSViv(-code % 3)),
14626                                   newOP(OP_CALLER,0)
14627                        )
14628                );
14629     case OP_SELECT: /* which represents OP_SSELECT as well */
14630         if (code)
14631             return newCONDOP(
14632                          0,
14633                          newBINOP(OP_GT, 0,
14634                                   newAVREF(newGVOP(OP_GV, 0, PL_defgv)),
14635                                   newSVOP(OP_CONST, 0, newSVuv(1))
14636                                  ),
14637                          coresub_op(newSVuv((UV)OP_SSELECT), 0,
14638                                     OP_SSELECT),
14639                          coresub_op(coreargssv, 0, OP_SELECT)
14640                    );
14641         /* FALLTHROUGH */
14642     default:
14643         switch (PL_opargs[opnum] & OA_CLASS_MASK) {
14644         case OA_BASEOP:
14645             return op_append_elem(
14646                         OP_LINESEQ, argop,
14647                         newOP(opnum,
14648                               opnum == OP_WANTARRAY || opnum == OP_RUNCV
14649                                 ? OPpOFFBYONE << 8 : 0)
14650                    );
14651         case OA_BASEOP_OR_UNOP:
14652             if (opnum == OP_ENTEREVAL) {
14653                 o = newUNOP(OP_ENTEREVAL,OPpEVAL_COPHH<<8,argop);
14654                 if (code == -KEY_evalbytes) o->op_private |= OPpEVAL_BYTES;
14655             }
14656             else o = newUNOP(opnum,0,argop);
14657             if (opnum == OP_CALLER) o->op_private |= OPpOFFBYONE;
14658             else {
14659           onearg:
14660               if (is_handle_constructor(o, 1))
14661                 argop->op_private |= OPpCOREARGS_DEREF1;
14662               if (scalar_mod_type(NULL, opnum))
14663                 argop->op_private |= OPpCOREARGS_SCALARMOD;
14664             }
14665             return o;
14666         default:
14667             o = op_convert_list(opnum,OPf_SPECIAL*(opnum == OP_GLOB),argop);
14668             if (is_handle_constructor(o, 2))
14669                 argop->op_private |= OPpCOREARGS_DEREF2;
14670             if (opnum == OP_SUBSTR) {
14671                 o->op_private |= OPpMAYBE_LVSUB;
14672                 return o;
14673             }
14674             else goto onearg;
14675         }
14676     }
14677 }
14678
14679 void
14680 Perl_report_redefined_cv(pTHX_ const SV *name, const CV *old_cv,
14681                                SV * const *new_const_svp)
14682 {
14683     const char *hvname;
14684     bool is_const = !!CvCONST(old_cv);
14685     SV *old_const_sv = is_const ? cv_const_sv(old_cv) : NULL;
14686
14687     PERL_ARGS_ASSERT_REPORT_REDEFINED_CV;
14688
14689     if (is_const && new_const_svp && old_const_sv == *new_const_svp)
14690         return;
14691         /* They are 2 constant subroutines generated from
14692            the same constant. This probably means that
14693            they are really the "same" proxy subroutine
14694            instantiated in 2 places. Most likely this is
14695            when a constant is exported twice.  Don't warn.
14696         */
14697     if (
14698         (ckWARN(WARN_REDEFINE)
14699          && !(
14700                 CvGV(old_cv) && GvSTASH(CvGV(old_cv))
14701              && HvNAMELEN(GvSTASH(CvGV(old_cv))) == 7
14702              && (hvname = HvNAME(GvSTASH(CvGV(old_cv))),
14703                  strEQ(hvname, "autouse"))
14704              )
14705         )
14706      || (is_const
14707          && ckWARN_d(WARN_REDEFINE)
14708          && (!new_const_svp || sv_cmp(old_const_sv, *new_const_svp))
14709         )
14710     )
14711         Perl_warner(aTHX_ packWARN(WARN_REDEFINE),
14712                           is_const
14713                             ? "Constant subroutine %"SVf" redefined"
14714                             : "Subroutine %"SVf" redefined",
14715                           SVfARG(name));
14716 }
14717
14718 /*
14719 =head1 Hook manipulation
14720
14721 These functions provide convenient and thread-safe means of manipulating
14722 hook variables.
14723
14724 =cut
14725 */
14726
14727 /*
14728 =for apidoc Am|void|wrap_op_checker|Optype opcode|Perl_check_t new_checker|Perl_check_t *old_checker_p
14729
14730 Puts a C function into the chain of check functions for a specified op
14731 type.  This is the preferred way to manipulate the L</PL_check> array.
14732 C<opcode> specifies which type of op is to be affected.  C<new_checker>
14733 is a pointer to the C function that is to be added to that opcode's
14734 check chain, and C<old_checker_p> points to the storage location where a
14735 pointer to the next function in the chain will be stored.  The value of
14736 C<new_pointer> is written into the L</PL_check> array, while the value
14737 previously stored there is written to C<*old_checker_p>.
14738
14739 The function should be defined like this:
14740
14741     static OP *new_checker(pTHX_ OP *op) { ... }
14742
14743 It is intended to be called in this manner:
14744
14745     new_checker(aTHX_ op)
14746
14747 C<old_checker_p> should be defined like this:
14748
14749     static Perl_check_t old_checker_p;
14750
14751 L</PL_check> is global to an entire process, and a module wishing to
14752 hook op checking may find itself invoked more than once per process,
14753 typically in different threads.  To handle that situation, this function
14754 is idempotent.  The location C<*old_checker_p> must initially (once
14755 per process) contain a null pointer.  A C variable of static duration
14756 (declared at file scope, typically also marked C<static> to give
14757 it internal linkage) will be implicitly initialised appropriately,
14758 if it does not have an explicit initialiser.  This function will only
14759 actually modify the check chain if it finds C<*old_checker_p> to be null.
14760 This function is also thread safe on the small scale.  It uses appropriate
14761 locking to avoid race conditions in accessing L</PL_check>.
14762
14763 When this function is called, the function referenced by C<new_checker>
14764 must be ready to be called, except for C<*old_checker_p> being unfilled.
14765 In a threading situation, C<new_checker> may be called immediately,
14766 even before this function has returned.  C<*old_checker_p> will always
14767 be appropriately set before C<new_checker> is called.  If C<new_checker>
14768 decides not to do anything special with an op that it is given (which
14769 is the usual case for most uses of op check hooking), it must chain the
14770 check function referenced by C<*old_checker_p>.
14771
14772 If you want to influence compilation of calls to a specific subroutine,
14773 then use L</cv_set_call_checker> rather than hooking checking of all
14774 C<entersub> ops.
14775
14776 =cut
14777 */
14778
14779 void
14780 Perl_wrap_op_checker(pTHX_ Optype opcode,
14781     Perl_check_t new_checker, Perl_check_t *old_checker_p)
14782 {
14783     dVAR;
14784
14785     PERL_UNUSED_CONTEXT;
14786     PERL_ARGS_ASSERT_WRAP_OP_CHECKER;
14787     if (*old_checker_p) return;
14788     OP_CHECK_MUTEX_LOCK;
14789     if (!*old_checker_p) {
14790         *old_checker_p = PL_check[opcode];
14791         PL_check[opcode] = new_checker;
14792     }
14793     OP_CHECK_MUTEX_UNLOCK;
14794 }
14795
14796 #include "XSUB.h"
14797
14798 /* Efficient sub that returns a constant scalar value. */
14799 static void
14800 const_sv_xsub(pTHX_ CV* cv)
14801 {
14802     dXSARGS;
14803     SV *const sv = MUTABLE_SV(XSANY.any_ptr);
14804     PERL_UNUSED_ARG(items);
14805     if (!sv) {
14806         XSRETURN(0);
14807     }
14808     EXTEND(sp, 1);
14809     ST(0) = sv;
14810     XSRETURN(1);
14811 }
14812
14813 static void
14814 const_av_xsub(pTHX_ CV* cv)
14815 {
14816     dXSARGS;
14817     AV * const av = MUTABLE_AV(XSANY.any_ptr);
14818     SP -= items;
14819     assert(av);
14820 #ifndef DEBUGGING
14821     if (!av) {
14822         XSRETURN(0);
14823     }
14824 #endif
14825     if (SvRMAGICAL(av))
14826         Perl_croak(aTHX_ "Magical list constants are not supported");
14827     if (GIMME_V != G_ARRAY) {
14828         EXTEND(SP, 1);
14829         ST(0) = sv_2mortal(newSViv((IV)AvFILLp(av)+1));
14830         XSRETURN(1);
14831     }
14832     EXTEND(SP, AvFILLp(av)+1);
14833     Copy(AvARRAY(av), &ST(0), AvFILLp(av)+1, SV *);
14834     XSRETURN(AvFILLp(av)+1);
14835 }
14836
14837 /*
14838  * ex: set ts=8 sts=4 sw=4 et:
14839  */